test.py 59.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
##############################################################################
#
# Copyright (c) 2018 Nexedi SA and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

28
import six.moves.http_client as httplib
29
import json
30
import os
31
import glob
32 33
import hashlib
import psutil
34
import re
35
import requests
36
import six
37 38
import slapos.util
import sqlite3
39
from six.moves.urllib.parse import parse_qs, urlparse
40
import unittest
41
import subprocess
42
import tempfile
43 44
import six.moves.socketserver as SocketServer
from six.moves import SimpleHTTPServer
45 46 47
import multiprocessing
import time
import shutil
48
import sys
49

50
from slapos.qemuqmpclient import QemuQMPWrapper
51
from slapos.proxy.db_version import DB_VERSION
52
from slapos.recipe.librecipe import generateHashFromFiles
53
from slapos.testing.testcase import makeModuleSetUpAndTestCaseClass
54
from slapos.slap.standalone import SlapOSNodeCommandError
55
from slapos.testing.utils import findFreeTCPPort
56

57
has_kvm = os.access('/dev/kvm', os.R_OK | os.W_OK)
58
skipUnlessKvm = unittest.skipUnless(has_kvm, 'kvm not loaded or not allowed')
59

60
if has_kvm:
61
  setUpModule, InstanceTestCase = makeModuleSetUpAndTestCaseClass(
62
    os.path.abspath(
63
      os.path.join(os.path.dirname(__file__), '..', 'software.cfg')))
64 65
  # XXX Keep using slapos node instance --all, because of missing promises
  InstanceTestCase.slap._force_slapos_node_instance_all = True
66 67 68 69 70
else:
  setUpModule, InstanceTestCase = None, unittest.TestCase

  class SanityCheckTestCase(unittest.TestCase):
    def test_kvm_sanity_check(self):
71 72
      self.fail('This environment is not usable for kvm testing,'
                ' as it lacks kvm_intel kernel module')
73

74 75
bootstrap_common_param_dict = {
    # the bootstrap script is vm-bootstrap
76 77 78 79
    "bootstrap-script-url":
    "http://shacache.org/shacache/05105cd25d1ad798b71fd46a206c9b73da2c285a078"
    "af33d0e739525a595886785725a68811578bc21f75d0a97700a66d5e75bce5b2721ca455"
    "6a0734cb13e65#c98825aa1b6c8087914d2bfcafec3058",
80 81
    "slave-frontend": {
        "slave-frontend-dict": {}
82
    },
83 84 85 86
    "authorized-keys": [
        "ssh-rsa %s key_one" % ("A" * 372),
        "ssh-rsa %s key_two" % ("B" * 372),
        "ssh-rsa %s key_three" % ("C" * 372)
87
    ],
88 89 90
    "fw-restricted-access": "off",
    "fw-authorized-sources": [],
    "fw-reject-sources": ["10.32.0.0/13"]
91
}
92

93 94 95 96 97 98 99 100
bootstrap_machine_param_dict = {
    "computer-guid": "local",
    "disable-ansible-promise": True,
    "state": "started",
    "auto-ballooning": True,
    "ram-size": 4096,
    "cpu-count": 2,
    "disk-size": 50,
101
    "virtual-hard-drive-url":
102 103 104 105 106
    "http://shacache.org/shacache/a869d906fcd0af5091d5104451a2b86736485ae38e5"
    "c4388657bb957c25593b98378ed125f593683e7fda7e0dd485a376a0ce29dcbaa8d60766"
    "e1f67a7ef7b96",
    "virtual-hard-drive-md5sum": "9ffd690a5fcb4fa56702f2b99183e493",
    "virtual-hard-drive-gzipped": True,
107 108 109
    "hard-drive-url-check-certificate": False,
    "use-tap": True,
    "use-nat": True,
110
    "nat-restrict-mode": True,
111 112 113 114 115 116
    "enable-vhost": True,
    "external-disk-number": 1,
    "external-disk-size": 100,
    "external-disk-format": "qcow2",
    "enable-monitor": True,
    "keyboard-layout-language": "fr"
117
}
118

119 120 121 122 123 124 125 126 127

class KvmMixin(object):
  def getProcessInfo(self):
    hash_value = generateHashFromFiles([
      os.path.join(self.computer_partition_root_path, hash_file)
      for hash_file in [
        'software_release/buildout.cfg',
      ]
    ])
128 129 130 131 132 133 134 135 136 137 138 139
    # find bin/kvm_raw
    kvm_raw_list = glob.glob(
      os.path.join(self.slap.instance_directory, '*', 'bin', 'kvm_raw'))
    self.assertEqual(1, len(kvm_raw_list))  # allow to work only with one
    hash_file_list = [
      kvm_raw_list[0],
      'software_release/buildout.cfg',
    ]
    kvm_hash_value = generateHashFromFiles([
      os.path.join(self.computer_partition_root_path, hash_file)
      for hash_file in hash_file_list
    ])
140
    with self.slap.instance_supervisor_rpc as supervisor:
141 142 143 144
      running_process_info = '\n'.join(sorted([
        '%(group)s:%(name)s %(statename)s' % q for q
        in supervisor.getAllProcessInfo()
        if q['name'] != 'watchdog' and q['group'] != 'watchdog']))
145 146
    return running_process_info.replace(
      hash_value, '{hash}').replace(kvm_hash_value, '{kvm-hash-value}')
147

148 149 150 151 152 153 154 155 156 157 158 159 160 161
  def raising_waitForInstance(self, max_retry):
    with self.assertRaises(SlapOSNodeCommandError):
      self.slap.waitForInstance(max_retry=max_retry)

  def rerequestInstance(self, parameter_dict, state='started'):
    software_url = self.getSoftwareURL()
    software_type = self.getInstanceSoftwareType()
    return self.slap.request(
        software_release=software_url,
        software_type=software_type,
        partition_reference=self.default_partition_reference,
        partition_parameter_kw=parameter_dict,
        state=state)

162

163 164 165
@skipUnlessKvm
class TestInstance(InstanceTestCase, KvmMixin):
  __partition_reference__ = 'i'
166

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
  def test(self):
    connection_parameter_dict = self\
      .computer_partition.getConnectionParameterDict()
    present_key_list = []
    assert_key_list = [
     'backend-url', 'url', 'monitor-setup-url', 'ipv6-network-info',
     'tap-ipv4', 'tap-ipv6']
    for k in assert_key_list:
      if k in connection_parameter_dict:
        present_key_list.append(k)
        connection_parameter_dict.pop(k)
    self.assertEqual(
      connection_parameter_dict,
      {
        'ipv6': self._ipv6_address,
        'maximum-extra-disk-amount': '0',
        'monitor-base-url': 'https://[%s]:8026' % (self._ipv6_address,),
        'nat-rule-port-tcp-22': '%s : 10022' % (self._ipv6_address,),
        'nat-rule-port-tcp-443': '%s : 10443' % (self._ipv6_address,),
        'nat-rule-port-tcp-80': '%s : 10080' % (self._ipv6_address,),
      }
    )
    self.assertEqual(set(present_key_list), set(assert_key_list))
    self.assertEqual(
      """i0:6tunnel-10022-{hash}-on-watch RUNNING
i0:6tunnel-10080-{hash}-on-watch RUNNING
i0:6tunnel-10443-{hash}-on-watch RUNNING
i0:bootstrap-monitor EXITED
i0:certificate_authority-{hash}-on-watch RUNNING
i0:crond-{hash}-on-watch RUNNING
197
i0:kvm-{kvm-hash-value}-on-watch RUNNING
198 199 200
i0:kvm_controller EXITED
i0:monitor-httpd-{hash}-on-watch RUNNING
i0:monitor-httpd-graceful EXITED
201 202 203
i0:websockify-{hash}-on-watch RUNNING
i0:whitelist-domains-download-{hash} RUNNING
i0:whitelist-firewall-{hash} RUNNING""",
204 205
      self.getProcessInfo()
    )
206 207


208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
@skipUnlessKvm
class TestMemoryManagement(InstanceTestCase, KvmMixin):
  __partition_reference__ = 'i'

  def getKvmProcessInfo(self, switch_list):
    return_list = []
    with self.slap.instance_supervisor_rpc as instance_supervisor:
      kvm_pid = [q for q in instance_supervisor.getAllProcessInfo()
                 if 'kvm-' in q['name']][0]['pid']
      kvm_process = psutil.Process(kvm_pid)
      get_next = False
      for entry in kvm_process.cmdline():
        if get_next:
          return_list.append(entry)
          get_next = False
        elif entry in switch_list:
          get_next = True
    return kvm_pid, return_list

  def test(self):
    kvm_pid_1, info_list = self.getKvmProcessInfo(['-smp', '-m'])
    self.assertEqual(
230
      ['2,maxcpus=3', '4096M,slots=128,maxmem=4608M'],
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
      info_list
    )
    self.rerequestInstance({
      'ram-size': '1536',
      'cpu-count': '2',
    })
    self.slap.waitForInstance(max_retry=10)
    kvm_pid_2, info_list = self.getKvmProcessInfo(['-smp', '-m'])
    self.assertEqual(
      ['2,maxcpus=3', '1536M,slots=128,maxmem=2048M'],
      info_list
    )

    # assert that process was restarted
    self.assertNotEqual(kvm_pid_1, kvm_pid_2, "Unexpected: KVM not restarted")

  def tearDown(self):
    self.rerequestInstance({})
    self.slap.waitForInstance(max_retry=10)

  def test_enable_device_hotplug(self):
    def getHotpluggedCpuRamValue():
      qemu_wrapper = QemuQMPWrapper(os.path.join(
        self.computer_partition_root_path, 'var', 'qmp_socket'))
      ram_mb = sum(
        [q['size']
         for q in qemu_wrapper.getMemoryInfo()['hotplugged']]) / 1024 / 1024
      cpu_count = len(
        [q['CPU'] for q in qemu_wrapper.getCPUInfo()['hotplugged']])
      return {'cpu_count': cpu_count, 'ram_mb': ram_mb}

    kvm_pid_1, info_list = self.getKvmProcessInfo(['-smp', '-m'])
    self.assertEqual(
264
      ['2,maxcpus=3', '4096M,slots=128,maxmem=4608M'],
265 266 267 268 269 270 271 272 273 274
      info_list
    )
    self.assertEqual(
      getHotpluggedCpuRamValue(),
      {'cpu_count': 0, 'ram_mb': 0}
    )

    parameter_dict = {
      'enable-device-hotplug': 'true',
      # to avoid restarts the max RAM and CPU has to be static
275 276
      'ram-max-size': '8192',
      'cpu-max-count': '6',
277 278 279 280 281 282
    }
    self.rerequestInstance(parameter_dict)
    self.slap.waitForInstance(max_retry=2)
    kvm_pid_2, info_list = self.getKvmProcessInfo(['-smp', '-m'])

    self.assertEqual(
283
      ['2,maxcpus=6', '4096M,slots=128,maxmem=8192M'],
284 285 286 287 288 289 290 291
      info_list
    )
    self.assertEqual(
      getHotpluggedCpuRamValue(),
      {'cpu_count': 0, 'ram_mb': 0}
    )
    self.assertNotEqual(kvm_pid_1, kvm_pid_2, "Unexpected: KVM not restarted")
    parameter_dict.update(**{
292 293
      'ram-size': '5120',
      'cpu-count': '4'
294 295 296 297 298 299
    })
    self.rerequestInstance(parameter_dict)
    self.slap.waitForInstance(max_retry=10)
    kvm_pid_3, info_list = self.getKvmProcessInfo(['-smp', '-m'])

    self.assertEqual(
300
      ['2,maxcpus=6', '4096M,slots=128,maxmem=8192M'],
301 302 303 304 305
      info_list
    )
    self.assertEqual(kvm_pid_2, kvm_pid_3, "Unexpected: KVM restarted")
    self.assertEqual(
      getHotpluggedCpuRamValue(),
306
      {'cpu_count': 2, 'ram_mb': 1024}
307 308 309
    )


310 311 312 313 314 315 316 317 318 319 320 321
class MonitorAccessMixin(object):
  def sqlite3_connect(self):
    sqlitedb_file = os.path.join(
      os.path.abspath(
        os.path.join(
          self.slap.instance_directory, os.pardir
        )
      ), 'var', 'proxy.db'
    )
    return sqlite3.connect(sqlitedb_file)

  def get_all_instantiated_partition_list(self):
322 323 324 325 326 327 328 329
    db = self.sqlite3_connect()
    try:
      db.row_factory = lambda cursor, row: {
        col[0]: row[idx]
        for idx, col in enumerate(cursor.description)
      }
      return db.execute(
        "SELECT reference, xml, connection_xml, partition_reference,"
330
        " software_release, requested_state, software_type"
331 332 333 334
        " FROM partition%s"
        " WHERE slap_state='busy'" % DB_VERSION).fetchall()
    finally:
      db.close()
335 336 337 338 339 340 341

  def test_access_monitor(self):
    connection_parameter_dict = self.computer_partition\
      .getConnectionParameterDict()
    monitor_setup_url = connection_parameter_dict['monitor-setup-url']
    monitor_url_with_auth = 'https' + monitor_setup_url.split('https')[2]

342
    auth = parse_qs(urlparse(monitor_url_with_auth).path)
343 344 345 346 347 348 349 350 351

    # check that monitor-base-url for all partitions in the tree are accessible
    # with published username and password
    partition_with_monitor_base_url_count = 0
    for partition_information in self.get_all_instantiated_partition_list():
      connection_xml = partition_information.get('connection_xml')
      if not connection_xml:
        continue
      connection_dict = slapos.util.xml2dict(
352
        connection_xml if six.PY3 else connection_xml.encode('utf-8'))
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
      monitor_base_url = connection_dict.get('monitor-base-url')
      if not monitor_base_url:
        continue
      result = requests.get(
        monitor_base_url, verify=False, auth=(
          auth['username'][0],
          auth['password'][0])
      )

      self.assertEqual(
        httplib.OK,
        result.status_code
      )
      partition_with_monitor_base_url_count += 1
    self.assertEqual(
      self.expected_partition_with_monitor_base_url_count,
      partition_with_monitor_base_url_count
    )


373
@skipUnlessKvm
374
class TestAccessDefault(MonitorAccessMixin, InstanceTestCase):
375 376 377 378 379 380 381 382 383 384 385
  __partition_reference__ = 'ad'
  expected_partition_with_monitor_base_url_count = 1

  def test(self):
    connection_parameter_dict = self.computer_partition\
      .getConnectionParameterDict()
    result = requests.get(connection_parameter_dict['url'], verify=False)
    self.assertEqual(
      httplib.OK,
      result.status_code
    )
386 387
    self.assertIn('<title>noVNC</title>', result.text)
    self.assertNotIn('url-additional', connection_parameter_dict)
388 389


390
@skipUnlessKvm
391
class TestAccessDefaultAdditional(MonitorAccessMixin, InstanceTestCase):
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
  __partition_reference__ = 'ada'
  expected_partition_with_monitor_base_url_count = 1

  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'frontend-additional-instance-guid': 'SOMETHING'
    }

  def test(self):
    connection_parameter_dict = self.computer_partition\
      .getConnectionParameterDict()

    result = requests.get(connection_parameter_dict['url'], verify=False)
    self.assertEqual(
      httplib.OK,
      result.status_code
    )
410
    self.assertIn('<title>noVNC</title>', result.text)
411 412 413 414 415 416 417

    result = requests.get(
      connection_parameter_dict['url-additional'], verify=False)
    self.assertEqual(
      httplib.OK,
      result.status_code
    )
418
    self.assertIn('<title>noVNC</title>', result.text)
419

420

421 422 423 424 425 426 427
@skipUnlessKvm
class TestAccessDefaultBootstrap(MonitorAccessMixin, InstanceTestCase):
  __partition_reference__ = 'adb'
  expected_partition_with_monitor_base_url_count = 1

  @classmethod
  def getInstanceParameterDict(cls):
428 429
    return {'_': json.dumps(dict(
      bootstrap_common_param_dict, **bootstrap_machine_param_dict))}
430 431

  def test(self):
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    # START: mock .slapos-resource with tap.ipv4_addr
    # needed for netconfig.sh
    test_partition_slapos_resource_file = os.path.join(
      self.computer_partition_root_path, '.slapos-resource')
    path = os.path.realpath(os.curdir)
    while path != '/':
      root_slapos_resource_file = os.path.join(path, '.slapos-resource')
      if os.path.exists(root_slapos_resource_file):
        break
      path = os.path.realpath(os.path.join(path, '..'))
    else:
      raise ValueError('No .slapos-resource found to base the mock on')
    with open(root_slapos_resource_file) as fh:
      root_slapos_resource = json.load(fh)
    if root_slapos_resource['tap']['ipv4_addr'] == '':
      root_slapos_resource['tap'].update({
        "ipv4_addr": "10.0.0.2",
        "ipv4_gateway": "10.0.0.1",
        "ipv4_netmask": "255.255.0.0",
        "ipv4_network": "10.0.0.0"
      })
    with open(test_partition_slapos_resource_file, 'w') as fh:
      json.dump(root_slapos_resource, fh, indent=4)
    self.slap.waitForInstance(max_retry=10)
    # END: mock .slapos-resource with tap.ipv4_addr

Łukasz Nowak's avatar
Łukasz Nowak committed
458 459
    cp = self.computer_partition
    connection_parameter_dict = cp.getConnectionParameterDict()
460 461 462 463 464 465 466

    result = requests.get(connection_parameter_dict['url'], verify=False)
    self.assertEqual(
      httplib.OK,
      result.status_code
    )
    self.assertIn('<title>noVNC</title>', result.text)
467 468 469 470 471 472
    # check that expected files to configure the VM are exposed by the instance
    self.assertEqual(
      ['delDefaultIface', 'netconfig.sh'],
      sorted(os.listdir(os.path.join(
        self.computer_partition_root_path, 'srv', 'public')))
    )
473

474

475
@skipUnlessKvm
476
class TestAccessKvmCluster(MonitorAccessMixin, InstanceTestCase):
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
  __partition_reference__ = 'akc'
  expected_partition_with_monitor_base_url_count = 2

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-cluster'

  @classmethod
  def getInstanceParameterDict(cls):
    return {'_': json.dumps({
      "kvm-partition-dict": {
        "KVM0": {
            "disable-ansible-promise": True
        }
      }
    })}

  def test(self):
    connection_parameter_dict = self.computer_partition\
      .getConnectionParameterDict()
Bryton Lacquement's avatar
Bryton Lacquement committed
497
    result = requests.get(connection_parameter_dict['KVM0-url'], verify=False)
498 499 500 501
    self.assertEqual(
      httplib.OK,
      result.status_code
    )
502
    self.assertIn('<title>noVNC</title>', result.text)
Bryton Lacquement's avatar
Bryton Lacquement committed
503
    self.assertNotIn('KVM0-url-additional', connection_parameter_dict)
504 505


506
@skipUnlessKvm
507
class TestAccessKvmClusterAdditional(MonitorAccessMixin, InstanceTestCase):
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
  __partition_reference__ = 'akca'
  expected_partition_with_monitor_base_url_count = 2

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-cluster'

  @classmethod
  def getInstanceParameterDict(cls):
    return {'_': json.dumps({
      "frontend": {
        'frontend-additional-instance-guid': 'SOMETHING',
      },
      "kvm-partition-dict": {
        "KVM0": {
            "disable-ansible-promise": True,
        }
      }
    })}

  def test(self):
    connection_parameter_dict = self.computer_partition\
      .getConnectionParameterDict()
Bryton Lacquement's avatar
Bryton Lacquement committed
531
    result = requests.get(connection_parameter_dict['KVM0-url'], verify=False)
532 533 534 535
    self.assertEqual(
      httplib.OK,
      result.status_code
    )
536
    self.assertIn('<title>noVNC</title>', result.text)
537 538

    result = requests.get(
Bryton Lacquement's avatar
Bryton Lacquement committed
539
      connection_parameter_dict['KVM0-url-additional'], verify=False)
540 541 542 543
    self.assertEqual(
      httplib.OK,
      result.status_code
    )
544
    self.assertIn('<title>noVNC</title>', result.text)
545

546

547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
@skipUnlessKvm
class TestAccessKvmClusterBootstrap(MonitorAccessMixin, InstanceTestCase):
  __partition_reference__ = 'akcb'
  expected_partition_with_monitor_base_url_count = 3

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-cluster'

  @classmethod
  def getInstanceParameterDict(cls):
    return {'_': json.dumps(dict(bootstrap_common_param_dict, **{
      "kvm-partition-dict": {
          "test-machine1": bootstrap_machine_param_dict,
          "test-machine2": dict(bootstrap_machine_param_dict, **{
562
              "virtual-hard-drive-url":
563 564 565 566
              "http://shacache.org/shacache/5bdc95ea3f8ca40ff4fb8d086776e393"
              "87a68e91f76b1a5f883dfc33fa13cf1ee71c7d218a4e9401f56519a352791"
              "272ada4a5c334b3ca38a32c0bcacb6838e2",
              "virtual-hard-drive-md5sum": "deaf751a31dd6aec320d67c75c88c2e1",
567
              "virtual-hard-drive-gzipped": True,
568 569 570
          })
      }
    }))}
571 572 573 574

  def test(self):
    connection_parameter_dict = self.computer_partition\
      .getConnectionParameterDict()
575 576
    result = requests.get(
      connection_parameter_dict['test-machine1-url'], verify=False)
577 578 579 580 581
    self.assertEqual(
      httplib.OK,
      result.status_code
    )
    self.assertIn('<title>noVNC</title>', result.text)
582 583
    result = requests.get(
      connection_parameter_dict['test-machine2-url'], verify=False)
584 585 586 587 588 589
    self.assertEqual(
      httplib.OK,
      result.status_code
    )
    self.assertIn('<title>noVNC</title>', result.text)

590

591
@skipUnlessKvm
592
class TestInstanceResilient(InstanceTestCase, KvmMixin):
593 594 595 596 597 598 599
  __partition_reference__ = 'ir'
  instance_max_retry = 20

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-resilient'

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
  def test_kvm_exporter(self):
    exporter_partition = os.path.join(
      self.slap.instance_directory,
      self.__partition_reference__ + '2')
    backup_path = os.path.join(
      exporter_partition, 'srv', 'backup', 'kvm', 'virtual.qcow2.gz')
    exporter = os.path.join(exporter_partition, 'bin', 'exporter')
    if os.path.exists(backup_path):
      os.unlink(backup_path)

    def call_exporter():
      try:
        return (0, subprocess.check_output(
          [exporter], stderr=subprocess.STDOUT).decode('utf-8'))
      except subprocess.CalledProcessError as e:
        return (e.returncode, e.output.decode('utf-8'))
    status_code, status_text = call_exporter()
    self.assertEqual(0, status_code, status_text)

619
  def test(self):
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
    connection_parameter_dict = self\
      .computer_partition.getConnectionParameterDict()
    present_key_list = []
    assert_key_list = [
     'monitor-password', 'takeover-kvm-1-password', 'backend-url', 'url',
     'monitor-setup-url', 'ipv6-network-info']
    for k in assert_key_list:
      if k in connection_parameter_dict:
        present_key_list.append(k)
        connection_parameter_dict.pop(k)
    self.assertEqual(
      connection_parameter_dict,
      {
        'feed-url-kvm-1-pull': 'http://[%s]:8088/get/local-ir0-kvm-1-pull' % (
          self._ipv6_address,),
        'feed-url-kvm-1-push': 'http://[%s]:8088/get/local-ir0-kvm-1-push' % (
          self._ipv6_address,),
        'ipv6': self._ipv6_address,
        'monitor-base-url': 'https://[%s]:8160' % (self._ipv6_address,),
        'monitor-user': 'admin',
        'takeover-kvm-1-url': 'http://[%s]:9263/' % (self._ipv6_address,),
      }
    )
    self.assertEqual(set(present_key_list), set(assert_key_list))

    self.assertEqual(
      """ir0:bootstrap-monitor EXITED
ir0:certificate_authority-{hash}-on-watch RUNNING
ir0:crond-{hash}-on-watch RUNNING
ir0:monitor-httpd-{hash}-on-watch RUNNING
ir0:monitor-httpd-graceful EXITED
ir1:bootstrap-monitor EXITED
ir1:certificate_authority-{hash}-on-watch RUNNING
ir1:crond-{hash}-on-watch RUNNING
ir1:equeue-on-watch RUNNING
ir1:monitor-httpd-{hash}-on-watch RUNNING
ir1:monitor-httpd-graceful EXITED
ir1:notifier-on-watch RUNNING
ir1:pbs_sshkeys_authority-on-watch RUNNING
ir2:6tunnel-10022-{hash}-on-watch RUNNING
ir2:6tunnel-10080-{hash}-on-watch RUNNING
ir2:6tunnel-10443-{hash}-on-watch RUNNING
ir2:bootstrap-monitor EXITED
ir2:certificate_authority-{hash}-on-watch RUNNING
ir2:crond-{hash}-on-watch RUNNING
ir2:equeue-on-watch RUNNING
666
ir2:kvm-{kvm-hash-value}-on-watch RUNNING
667 668 669 670 671 672 673 674
ir2:kvm_controller EXITED
ir2:monitor-httpd-{hash}-on-watch RUNNING
ir2:monitor-httpd-graceful EXITED
ir2:notifier-on-watch RUNNING
ir2:resilient_sshkeys_authority-on-watch RUNNING
ir2:sshd-graceful EXITED
ir2:sshd-on-watch RUNNING
ir2:websockify-{hash}-on-watch RUNNING
675 676
ir2:whitelist-domains-download-{hash} RUNNING
ir2:whitelist-firewall-{hash} RUNNING
677 678 679 680 681 682 683 684 685 686 687 688 689
ir3:bootstrap-monitor EXITED
ir3:certificate_authority-{hash}-on-watch RUNNING
ir3:crond-{hash}-on-watch RUNNING
ir3:equeue-on-watch RUNNING
ir3:monitor-httpd-{hash}-on-watch RUNNING
ir3:monitor-httpd-graceful EXITED
ir3:notifier-on-watch RUNNING
ir3:resilient-web-takeover-httpd-on-watch RUNNING
ir3:resilient_sshkeys_authority-on-watch RUNNING
ir3:sshd-graceful EXITED
ir3:sshd-on-watch RUNNING""",
      self.getProcessInfo()
    )
690

691

692 693 694 695 696 697 698 699 700
@skipUnlessKvm
class TestInstanceResilientDiskTypeIde(InstanceTestCase, KvmMixin):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'disk-type': 'ide'
    }


701
@skipUnlessKvm
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
class TestAccessResilientAdditional(InstanceTestCase):
  __partition_reference__ = 'ara'
  expected_partition_with_monitor_base_url_count = 1

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-resilient'

  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'frontend-additional-instance-guid': 'SOMETHING'
    }

  def test(self):
    connection_parameter_dict = self.computer_partition\
      .getConnectionParameterDict()

    result = requests.get(connection_parameter_dict['url'], verify=False)
    self.assertEqual(
      httplib.OK,
      result.status_code
    )
    self.assertIn('<title>noVNC</title>', result.text)

    result = requests.get(
      connection_parameter_dict['url-additional'], verify=False)
    self.assertEqual(
      httplib.OK,
      result.status_code
    )
    self.assertIn('<title>noVNC</title>', result.text)

735

736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
class TestInstanceNbdServer(InstanceTestCase):
  __partition_reference__ = 'ins'
  instance_max_retry = 5

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'nbd'

  @classmethod
  def getInstanceParameterDict(cls):
    # port 8080 is used by testnode, use another one
    return {
      'otu-port': '8090'
    }

  def test(self):
    connection_parameter_dict = self.computer_partition\
      .getConnectionParameterDict()
754 755
    result = requests.get(
      connection_parameter_dict['upload_url'].strip(), verify=False)
756 757 758 759 760 761
    self.assertEqual(
      httplib.OK,
      result.status_code
    )
    self.assertIn('<title>Upload new File</title>', result.text)
    self.assertIn("WARNING", connection_parameter_dict['status_message'])
762 763


764 765 766 767 768 769 770 771
class FakeImageHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
  def log_message(self, *args):
    if os.environ.get('SLAPOS_TEST_DEBUG'):
      return SimpleHTTPServer.SimpleHTTPRequestHandler.log_message(self, *args)
    else:
      return


772
class FakeImageServerMixin(KvmMixin):
773 774 775
  @classmethod
  def startImageHttpServer(cls):
    cls.image_source_directory = tempfile.mkdtemp()
776
    server = SocketServer.TCPServer(
777
      (cls._ipv4_address, findFreeTCPPort(cls._ipv4_address)),
778 779
      FakeImageHandler)

780
    # c89f17758be13adeb06886ef935d5ff1
781
    fake_image_content = b'fake_image_content'
782
    cls.fake_image_md5sum = hashlib.md5(fake_image_content).hexdigest()
783
    with open(os.path.join(
784
      cls.image_source_directory, cls.fake_image_md5sum), 'wb') as fh:
785 786
      fh.write(fake_image_content)

787
    # bc81d2aee81e030c6cee210c802339c2
788
    fake_image2_content = b'fake_image2_content'
789
    cls.fake_image2_md5sum = hashlib.md5(fake_image2_content).hexdigest()
790
    with open(os.path.join(
791
      cls.image_source_directory, cls.fake_image2_md5sum), 'wb') as fh:
792 793
      fh.write(fake_image2_content)

794 795 796 797 798 799 800 801
    cls.fake_image_wrong_md5sum = cls.fake_image2_md5sum

    # c5ef5d70ad5a0dbfd890a734f588e344
    fake_image3_content = b'fake_image3_content'
    cls.fake_image3_md5sum = hashlib.md5(fake_image3_content).hexdigest()
    with open(os.path.join(
      cls.image_source_directory, cls.fake_image3_md5sum), 'wb') as fh:
      fh.write(fake_image3_content)
802 803

    url = 'http://%s:%s' % server.server_address
804 805 806
    cls.fake_image = '/'.join([url, cls.fake_image_md5sum])
    cls.fake_image2 = '/'.join([url, cls.fake_image2_md5sum])
    cls.fake_image3 = '/'.join([url, cls.fake_image3_md5sum])
807 808

    old_dir = os.path.realpath(os.curdir)
809
    os.chdir(cls.image_source_directory)
810
    try:
811
      cls.server_process = multiprocessing.Process(
812
        target=server.serve_forever, name='FakeImageHttpServer')
813
      cls.server_process.start()
814 815 816
    finally:
      os.chdir(old_dir)

817 818 819 820 821
  @classmethod
  def stopImageHttpServer(cls):
    cls.logger.debug('Stopping process %s' % (cls.server_process,))
    cls.server_process.join(10)
    cls.server_process.terminate()
822
    time.sleep(0.1)
823 824 825
    if cls.server_process.is_alive():
      cls.logger.warning(
        'Process %s still alive' % (cls.server_process, ))
826

827
    shutil.rmtree(cls.image_source_directory)
828 829


830
@skipUnlessKvm
831
class TestBootImageUrlList(InstanceTestCase, FakeImageServerMixin):
832
  __partition_reference__ = 'biul'
833
  kvm_instance_partition_reference = 'biul0'
834

835 836 837
  # variations
  key = 'boot-image-url-list'
  test_input = "%s#%s\n%s#%s"
838
  empty_input = ""
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
  image_directory = 'boot-image-url-list-repository'
  config_state_promise = 'boot-image-url-list-config-state-promise.py'
  download_md5sum_promise = 'boot-image-url-list-download-md5sum-promise.py'
  download_state_promise = 'boot-image-url-list-download-state-promise.py'

  bad_value = "jsutbad"
  incorrect_md5sum_value_image = "%s#"
  incorrect_md5sum_value = "url#asdasd"
  single_image_value = "%s#%s"
  unreachable_host_value = "evennotahost#%s"
  too_many_image_value = """
      image1#11111111111111111111111111111111
      image2#22222222222222222222222222222222
      image3#33333333333333333333333333333333
      image4#44444444444444444444444444444444
      image5#55555555555555555555555555555555
      image6#66666666666666666666666666666666
      """

858 859 860 861 862 863
  @classmethod
  def getInstanceSoftwareType(cls):
    return 'default'

  @classmethod
  def getInstanceParameterDict(cls):
864 865 866 867 868
    return {
      cls.key: cls.test_input % (
        cls.fake_image, cls.fake_image_md5sum, cls.fake_image2,
        cls.fake_image2_md5sum)
    }
869

870 871 872
  @classmethod
  def setUpClass(cls):
    cls.startImageHttpServer()
Łukasz Nowak's avatar
Łukasz Nowak committed
873
    super(TestBootImageUrlList, cls).setUpClass()
874 875 876

  @classmethod
  def tearDownClass(cls):
Łukasz Nowak's avatar
Łukasz Nowak committed
877
    super(TestBootImageUrlList, cls).tearDownClass()
878
    cls.stopImageHttpServer()
879

880 881 882
  def tearDown(self):
    # clean up the instance for other tests
    # 1st remove all images...
883
    self.rerequestInstance({self.key: ''})
884 885 886 887
    self.slap.waitForInstance(max_retry=10)
    # 2nd ...move instance to "default" state
    self.rerequestInstance({})
    self.slap.waitForInstance(max_retry=10)
Łukasz Nowak's avatar
Łukasz Nowak committed
888
    super(TestBootImageUrlList, self).tearDown()
889

Łukasz Nowak's avatar
Łukasz Nowak committed
890 891
  def getRunningImageList(
      self, kvm_instance_partition,
892
      _match_cdrom=re.compile('file=(.+),media=cdrom$').match,
893
      _sub_iso=re.compile(r'(/debian)(-[^-/]+)(-[^/]+-netinst\.iso)$').sub,
Łukasz Nowak's avatar
Łukasz Nowak committed
894
    ):
895 896
    with self.slap.instance_supervisor_rpc as instance_supervisor:
      kvm_pid = next(q for q in instance_supervisor.getAllProcessInfo()
Łukasz Nowak's avatar
Łukasz Nowak committed
897
                     if 'kvm-' in q['name'])['pid']
898 899
    sub_shared = re.compile(r'^%s/[^/]+/[0-9a-f]{32}/'
                            % re.escape(self.slap.shared_directory)).sub
900 901 902 903 904
    image_list = []
    for entry in psutil.Process(kvm_pid).cmdline():
      m = _match_cdrom(entry)
      if m:
        path = m.group(1)
905
        image_list.append(
Łukasz Nowak's avatar
Łukasz Nowak committed
906 907 908 909 910 911
          _sub_iso(
            r'\1-${ver}\3',
            sub_shared(
              r'${shared}/',
              path.replace(kvm_instance_partition, '${inst}')
            )))
912 913
    return image_list

914
  def test(self):
915
    # check that image is correctly downloaded
916 917
    kvm_instance_partition = os.path.join(
      self.slap.instance_directory, self.kvm_instance_partition_reference)
918
    image_repository = os.path.join(
919
      kvm_instance_partition, 'srv', self.image_directory)
920 921 922 923 924 925 926 927 928 929 930 931
    image = os.path.join(image_repository, self.fake_image_md5sum)
    self.assertTrue(os.path.exists(image))
    with open(image, 'rb') as fh:
      image_md5sum = hashlib.md5(fh.read()).hexdigest()
    self.assertEqual(image_md5sum, self.fake_image_md5sum)

    image2 = os.path.join(image_repository, self.fake_image2_md5sum)
    self.assertTrue(os.path.exists(image2))
    with open(image2, 'rb') as fh:
      image2_md5sum = hashlib.md5(fh.read()).hexdigest()
    self.assertEqual(image2_md5sum, self.fake_image2_md5sum)

932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
    self.assertEqual(
      [
        '${inst}/srv/%s/%s' % (self.image_directory, self.fake_image_md5sum),
        '${inst}/srv/%s/%s' % (self.image_directory, self.fake_image2_md5sum),
        '${shared}/debian-${ver}-amd64-netinst.iso',
      ],
      self.getRunningImageList(kvm_instance_partition)
    )

    # Switch image
    self.rerequestInstance({
      self.key: self.test_input % (
        self.fake_image3, self.fake_image3_md5sum,
        self.fake_image2, self.fake_image2_md5sum)
    })
    self.slap.waitForInstance(max_retry=10)
    self.assertTrue(os.path.exists(os.path.join(
      image_repository, self.fake_image3_md5sum)))
    self.assertTrue(os.path.exists(os.path.join(
      image_repository, self.fake_image2_md5sum)))
952

953 954
    self.assertEqual(
      [
955 956
        '${inst}/srv/%s/%s' % (self.image_directory, self.fake_image3_md5sum),
        '${inst}/srv/%s/%s' % (self.image_directory, self.fake_image2_md5sum),
957
        '${shared}/debian-${ver}-amd64-netinst.iso',
958
      ],
959
      self.getRunningImageList(kvm_instance_partition)
960
    )
961 962 963

    # cleanup of images works, also asserts that configuration changes are
    # reflected
964 965 966 967 968
    # Note: key is left and empty_input is provided, as otherwise the part
    #       which generate images is simply removed, which can lead to
    #       leftover
    self.rerequestInstance({self.key: self.empty_input})
    self.slap.waitForInstance(max_retry=10)
969 970 971 972 973
    self.assertEqual(
      os.listdir(image_repository),
      []
    )

974 975
    # again only default image is available in the running process
    self.assertEqual(
976
      ['${shared}/debian-${ver}-amd64-netinst.iso'],
977
      self.getRunningImageList(kvm_instance_partition)
978 979
    )

980
  def assertPromiseFails(self, promise):
981 982 983
    partition_directory = os.path.join(
      self.slap.instance_directory,
      self.kvm_instance_partition_reference)
984
    monitor_run_promise = os.path.join(
985
      partition_directory, 'software_release', 'bin',
986 987 988
      'monitor.runpromise'
    )
    monitor_configuration = os.path.join(
989
      partition_directory, 'etc', 'monitor.conf')
990 991 992 993 994 995 996 997 998 999

    self.assertNotEqual(
      0,
      subprocess.call([
        monitor_run_promise, '-c', monitor_configuration, '-a', '-f',
        '--run-only', promise])
    )

  def test_bad_parameter(self):
    self.rerequestInstance({
1000
      self.key: self.bad_value
1001 1002
    })
    self.raising_waitForInstance(3)
1003
    self.assertPromiseFails(self.config_state_promise)
1004 1005 1006

  def test_incorrect_md5sum(self):
    self.rerequestInstance({
1007
      self.key: self.incorrect_md5sum_value_image % (self.fake_image,)
1008 1009
    })
    self.raising_waitForInstance(3)
1010
    self.assertPromiseFails(self.config_state_promise)
1011
    self.rerequestInstance({
1012
      self.key: self.incorrect_md5sum_value
1013 1014
    })
    self.raising_waitForInstance(3)
1015
    self.assertPromiseFails(self.config_state_promise)
1016 1017 1018

  def test_not_matching_md5sum(self):
    self.rerequestInstance({
1019
      self.key: self.single_image_value % (
1020 1021 1022
        self.fake_image, self.fake_image_wrong_md5sum)
    })
    self.raising_waitForInstance(3)
1023 1024
    self.assertPromiseFails(self.download_md5sum_promise)
    self.assertPromiseFails(self.download_state_promise)
1025 1026 1027

  def test_unreachable_host(self):
    self.rerequestInstance({
1028
      self.key: self.unreachable_host_value % (
1029 1030 1031
        self.fake_image_md5sum,)
    })
    self.raising_waitForInstance(3)
1032
    self.assertPromiseFails(self.download_state_promise)
1033 1034 1035

  def test_too_many_images(self):
    self.rerequestInstance({
1036 1037 1038 1039 1040 1041
      self.key: self.too_many_image_value
    })
    self.raising_waitForInstance(3)
    self.assertPromiseFails(self.config_state_promise)


1042 1043 1044
@skipUnlessKvm
class TestBootImageUrlListResilient(TestBootImageUrlList):
  kvm_instance_partition_reference = 'biul2'
Łukasz Nowak's avatar
Łukasz Nowak committed
1045

1046 1047 1048 1049 1050
  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-resilient'


1051 1052 1053
@skipUnlessKvm
class TestBootImageUrlSelect(TestBootImageUrlList):
  __partition_reference__ = 'bius'
1054
  kvm_instance_partition_reference = 'bius0'
1055 1056 1057 1058

  # variations
  key = 'boot-image-url-select'
  test_input = '["%s#%s", "%s#%s"]'
1059
  empty_input = '[]'
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
  image_directory = 'boot-image-url-select-repository'
  config_state_promise = 'boot-image-url-select-config-state-promise.py'
  download_md5sum_promise = 'boot-image-url-select-download-md5sum-promise.py'
  download_state_promise = 'boot-image-url-select-download-state-promise.py'

  bad_value = '["jsutbad"]'
  incorrect_md5sum_value_image = '["%s#"]'
  incorrect_md5sum_value = '["url#asdasd"]'
  single_image_value = '["%s#%s"]'
  unreachable_host_value = '["evennotahost#%s"]'
  too_many_image_value = """[
      "image1#11111111111111111111111111111111",
      "image2#22222222222222222222222222222222",
      "image3#33333333333333333333333333333333",
      "image4#44444444444444444444444444444444",
      "image5#55555555555555555555555555555555",
      "image6#66666666666666666666666666666666"
      ]"""

  def test_not_json(self):
    self.rerequestInstance({
      self.key: 'notjson#notjson'
1082 1083
    })
    self.raising_waitForInstance(3)
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
    self.assertPromiseFails(self.config_state_promise)

  def test_together(self):
    partition_parameter_kw = {
      'boot-image-url-list': "%s#%s" % (
        self.fake_image, self.fake_image_md5sum),
      'boot-image-url-select': '["%s#%s"]' % (
        self.fake_image, self.fake_image_md5sum)
    }
    self.rerequestInstance(partition_parameter_kw)
    self.slap.waitForInstance(max_retry=10)
1095
    # check that image is correctly downloaded
1096 1097 1098
    for image_directory in [
      'boot-image-url-list-repository', 'boot-image-url-select-repository']:
      image_repository = os.path.join(
1099 1100
        self.slap.instance_directory, self.kvm_instance_partition_reference,
        'srv', image_directory)
1101 1102 1103 1104 1105 1106
      image = os.path.join(image_repository, self.fake_image_md5sum)
      self.assertTrue(os.path.exists(image))
      with open(image, 'rb') as fh:
        image_md5sum = hashlib.md5(fh.read()).hexdigest()
      self.assertEqual(image_md5sum, self.fake_image_md5sum)

1107 1108 1109
    kvm_instance_partition = os.path.join(
      self.slap.instance_directory, self.kvm_instance_partition_reference)

1110 1111
    self.assertEqual(
      [
1112 1113 1114 1115
        '${inst}/srv/boot-image-url-select-repository/%s' % (
          self.fake_image_md5sum,),
        '${inst}/srv/boot-image-url-list-repository/%s' % (
          self.fake_image_md5sum,),
1116
        '${shared}/debian-${ver}-amd64-netinst.iso',
1117
      ],
1118
      self.getRunningImageList(kvm_instance_partition)
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
    )

    # cleanup of images works, also asserts that configuration changes are
    # reflected
    self.rerequestInstance(
      {'boot-image-url-list': '', 'boot-image-url-select': ''})
    self.slap.waitForInstance(max_retry=2)
    for image_directory in [
      'boot-image-url-list-repository', 'boot-image-url-select-repository']:
      image_repository = os.path.join(
1129
        kvm_instance_partition, 'srv', image_directory)
1130 1131 1132 1133 1134
      self.assertEqual(
        os.listdir(image_repository),
        []
      )

1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
    # cleanup of images works, also asserts that configuration changes are
    # reflected
    partition_parameter_kw[self.key] = ''
    partition_parameter_kw['boot-image-url-list'] = ''
    self.rerequestInstance(partition_parameter_kw)
    self.slap.waitForInstance(max_retry=2)
    self.assertEqual(
      os.listdir(image_repository),
      []
    )

1146 1147
    # again only default image is available in the running process
    self.assertEqual(
1148
      ['${shared}/debian-${ver}-amd64-netinst.iso'],
1149
      self.getRunningImageList(kvm_instance_partition)
1150
    )
1151 1152


1153 1154 1155
@skipUnlessKvm
class TestBootImageUrlSelectResilient(TestBootImageUrlSelect):
  kvm_instance_partition_reference = 'bius2'
Łukasz Nowak's avatar
Łukasz Nowak committed
1156

1157 1158 1159 1160 1161
  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-resilient'


1162
@skipUnlessKvm
1163
class TestBootImageUrlListKvmCluster(InstanceTestCase, FakeImageServerMixin):
1164
  __partition_reference__ = 'biulkc'
1165 1166 1167 1168 1169

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-cluster'

1170 1171 1172 1173
  input_value = "%s#%s"
  key = 'boot-image-url-list'
  config_file_name = 'boot-image-url-list.conf'

1174
  def setUp(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
1175
    super(TestBootImageUrlListKvmCluster, self).setUp()
1176 1177 1178 1179
    self.startImageHttpServer()

  def tearDown(self):
    self.stopImageHttpServer()
Łukasz Nowak's avatar
Łukasz Nowak committed
1180
    super(TestBootImageUrlListKvmCluster, self).tearDown()
1181

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
  @classmethod
  def getInstanceParameterDict(cls):
    return {'_': json.dumps({
      "kvm-partition-dict": {
        "KVM0": {
            "disable-ansible-promise": True,
        },
        "KVM1": {
            "disable-ansible-promise": True,
        }
      }
    })}

  def test(self):
    # Note: As there is no way to introspect nicely where partition landed
    #       we assume ordering of the cluster requests
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
    self.rerequestInstance({'_': json.dumps({
      "kvm-partition-dict": {
        "KVM0": {
            "disable-ansible-promise": True,
            self.key: self.input_value % (
              self.fake_image, self.fake_image_md5sum)
        },
        "KVM1": {
            "disable-ansible-promise": True,
            self.key: self.input_value % (
              self.fake_image2, self.fake_image2_md5sum)
        }
      }
    })})
    self.slap.waitForInstance(max_retry=10)
1213 1214
    KVM0_config = os.path.join(
      self.slap.instance_directory, self.__partition_reference__ + '1', 'etc',
1215
      self.config_file_name)
1216 1217
    KVM1_config = os.path.join(
      self.slap.instance_directory, self.__partition_reference__ + '2', 'etc',
1218
      self.config_file_name)
1219 1220
    with open(KVM0_config, 'r') as fh:
      self.assertEqual(
1221 1222
        self.input_value % (self.fake_image, self.fake_image_md5sum),
        fh.read().strip()
1223 1224 1225
      )
    with open(KVM1_config, 'r') as fh:
      self.assertEqual(
1226 1227
        self.input_value % (self.fake_image2, self.fake_image2_md5sum),
        fh.read().strip()
1228
      )
1229 1230


1231 1232 1233 1234 1235 1236 1237 1238 1239
@skipUnlessKvm
class TestBootImageUrlSelectKvmCluster(TestBootImageUrlListKvmCluster):
  __partition_reference__ = 'biuskc'

  input_value = "[\"%s#%s\"]"
  key = 'boot-image-url-select'
  config_file_name = 'boot-image-url-select.json'


1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
@skipUnlessKvm
class TestNatRules(InstanceTestCase):
  __partition_reference__ = 'nr'

  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'nat-rules': '100 200',
    }

  def test(self):
    connection_parameter_dict = self.computer_partition\
      .getConnectionParameterDict()

    self.assertIn('nat-rule-port-tcp-100', connection_parameter_dict)
    self.assertIn('nat-rule-port-tcp-200', connection_parameter_dict)

    self.assertEqual(
      '%s : 10100' % (self._ipv6_address,),
      connection_parameter_dict['nat-rule-port-tcp-100']
    )
    self.assertEqual(
      '%s : 10200' % (self._ipv6_address,),
      connection_parameter_dict['nat-rule-port-tcp-200']
    )


@skipUnlessKvm
class TestNatRulesKvmCluster(InstanceTestCase):
  __partition_reference__ = 'nrkc'

  nat_rules = ["100", "200", "300"]
Łukasz Nowak's avatar
Łukasz Nowak committed
1272

1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-cluster'

  @classmethod
  def getInstanceParameterDict(cls):
    return {'_': json.dumps({
      "kvm-partition-dict": {
        "KVM0": {
            "nat-rules": cls.nat_rules,
            "disable-ansible-promise": True,
        }
      }
    })}

  def getRunningHostFwd(self):
    with self.slap.instance_supervisor_rpc as instance_supervisor:
      kvm_pid = [q for q in instance_supervisor.getAllProcessInfo()
                 if 'kvm-' in q['name']][0]['pid']
      kvm_process = psutil.Process(kvm_pid)
      for entry in kvm_process.cmdline():
        if 'hostfwd' in entry:
          return entry

  def test(self):
    host_fwd_entry = self.getRunningHostFwd()
    self.assertIn(
      'hostfwd=tcp:%s:10100-:100' % (self._ipv4_address,),
      host_fwd_entry)
    self.assertIn(
      'hostfwd=tcp:%s:10200-:200' % (self._ipv4_address,),
      host_fwd_entry)
    self.assertIn(
      'hostfwd=tcp:%s:10300-:300' % (self._ipv4_address,),
      host_fwd_entry)
1308 1309 1310 1311 1312 1313


@skipUnlessKvm
class TestNatRulesKvmClusterComplex(TestNatRulesKvmCluster):
  __partition_reference__ = 'nrkcc'
  nat_rules = ["100", "200 300"]
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326


@skipUnlessKvm
class TestWhitelistFirewall(InstanceTestCase):
  __partition_reference__ = 'wf'
  kvm_instance_partition_reference = 'wf0'

  def test(self):
    slapos_whitelist_firewall = os.path.join(
      self.slap.instance_directory, self.kvm_instance_partition_reference,
      '.slapos-whitelist-firewall')
    self.assertTrue(os.path.exists(slapos_whitelist_firewall))
    with open(slapos_whitelist_firewall, 'rb') as fh:
1327
      content = fh.read()
1328 1329 1330
    try:
      self.content_json = json.loads(content)
    except ValueError:
1331
      self.fail('Failed to parse json of %r' % (content,))
1332 1333
    self.assertTrue(isinstance(self.content_json, list))
    # check /etc/resolv.conf
1334
    with open('/etc/resolv.conf', 'r') as f:
1335
      resolv_conf_ip_list = []
1336
      for line in f.readlines():
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
        if line.startswith('nameserver'):
          resolv_conf_ip_list.append(line.split()[1])
    resolv_conf_ip_list = list(set(resolv_conf_ip_list))
    self.assertFalse(len(resolv_conf_ip_list) == 0)
    self.assertTrue(all([q in self.content_json for q in resolv_conf_ip_list]))
    # there is something more
    self.assertGreater(len(self.content_json), len(resolv_conf_ip_list))


@skipUnlessKvm
class TestWhitelistFirewallRequest(TestWhitelistFirewall):
  whitelist_domains = '2.2.2.2 3.3.3.3\n4.4.4.4'
Łukasz Nowak's avatar
Łukasz Nowak committed
1349

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'whitelist-domains': cls.whitelist_domains,
    }

  def test(self):
    super(TestWhitelistFirewallRequest, self).test()
    self.assertIn('2.2.2.2', self.content_json)
    self.assertIn('3.3.3.3', self.content_json)
    self.assertIn('4.4.4.4', self.content_json)


@skipUnlessKvm
class TestWhitelistFirewallResilient(TestWhitelistFirewall):
  kvm_instance_partition_reference = 'wf2'

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-resilient'


@skipUnlessKvm
class TestWhitelistFirewallRequestResilient(TestWhitelistFirewallRequest):
  kvm_instance_partition_reference = 'wf2'

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-resilient'


@skipUnlessKvm
class TestWhitelistFirewallCluster(TestWhitelistFirewall):
  kvm_instance_partition_reference = 'wf1'

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-cluster'

  @classmethod
  def getInstanceParameterDict(cls):
    return {'_': json.dumps({
      "kvm-partition-dict": {
        "KVM0": {
            "disable-ansible-promise": True
        }
      }
    })}


@skipUnlessKvm
class TestWhitelistFirewallRequestCluster(TestWhitelistFirewallRequest):
  kvm_instance_partition_reference = 'wf1'

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-cluster'

  @classmethod
  def getInstanceParameterDict(cls):
    return {'_': json.dumps({
      "kvm-partition-dict": {
        "KVM0": {
            "whitelist-domains": cls.whitelist_domains,
            "disable-ansible-promise": True
        }
      }
    })}
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429


@skipUnlessKvm
class TestDiskDevicePathWipeDiskOndestroy(InstanceTestCase, KvmMixin):
  __partition_reference__ = 'ddpwdo'
  kvm_instance_partition_reference = 'ddpwdo0'

  def test(self):
    self.rerequestInstance({
      'disk-device-path': '/dev/virt0 /dev/virt1',
      'wipe-disk-ondestroy': True
    })
1430
    self.raising_waitForInstance(3)
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
    instance_path = os.path.join(
      self.slap.instance_directory, self.kvm_instance_partition_reference)

    slapos_wipe_device_disk = os.path.join(
      instance_path, 'etc', 'prerm', 'slapos_wipe_device_disk')

    # check prerm script, it's trusted that prerm manager really works
    self.assertTrue(os.path.exists(slapos_wipe_device_disk))
    with open(slapos_wipe_device_disk) as fh:
      self.assertEqual(
        fh.read().strip(),
1442 1443
        r"""#!/bin/sh
dd if=/dev/zero of=/dev/virt0 bs=4096 count=500k
1444 1445 1446
dd if=/dev/zero of=/dev/virt1 bs=4096 count=500k"""
      )
    self.assertTrue(os.access(slapos_wipe_device_disk, os.X_OK))
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471


@skipUnlessKvm
class TestImageDownloadController(InstanceTestCase, FakeImageServerMixin):
  __partition_reference__ = 'idc'
  maxDiff = None

  def setUp(self):
    super(TestImageDownloadController, self).setUp()
    self.working_directory = tempfile.mkdtemp()
    self.destination_directory = os.path.join(
      self.working_directory, 'destination')
    os.mkdir(self.destination_directory)
    self.config_json = os.path.join(
      self.working_directory, 'config.json')
    self.md5sum_fail_file = os.path.join(
      self.working_directory, 'md5sum_fail_file')
    self.error_state_file = os.path.join(
      self.working_directory, 'error_state_file')
    self.processed_md5sum = os.path.join(
      self.working_directory, 'processed_md5sum')
    self.startImageHttpServer()
    self.image_download_controller = os.path.join(
      self.slap.instance_directory, self.__partition_reference__ + '0',
      'software_release', 'parts', 'image-download-controller',
1472
      'image-download-controller.py')
1473 1474 1475 1476

  def tearDown(self):
    self.stopImageHttpServer()
    shutil.rmtree(self.working_directory)
Łukasz Nowak's avatar
Łukasz Nowak committed
1477
    super(TestImageDownloadController, self).tearDown()
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514

  def callImageDownloadController(self, *args):
    call_list = [sys.executable, self.image_download_controller] + list(args)
    try:
      return (0, subprocess.check_output(
        call_list, stderr=subprocess.STDOUT).decode('utf-8'))
    except subprocess.CalledProcessError as e:
      return (e.returncode, e.output.decode('utf-8'))

  def runImageDownloadControlerWithDict(self, json_dict):
    with open(self.config_json, 'w') as fh:
      json.dump(json_dict, fh, indent=2)
    return self.callImageDownloadController(
      self.config_json,
      'curl',  # comes from test environemnt, considered to be recent enough
      self.md5sum_fail_file,
      self.error_state_file,
      self.processed_md5sum
    )

  def assertFileContent(self, path, content):
    self.assertTrue(os.path.exists, path)
    with open(path, 'r') as fh:
      self.assertEqual(
        fh.read(),
        content)

  def test(self):
    json_dict = {
      'error-amount': 0,
      'config-md5sum': 'config-md5sum',
      'destination-directory': self.destination_directory,
      'image-list': [
        {
          'destination-tmp': 'tmp',
          'url': self.fake_image,
          'destination': 'destination',
1515
          'image-number': '001',
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
          'gzipped': False,
          'md5sum': self.fake_image_md5sum,
        }
      ]
    }
    code, result = self.runImageDownloadControlerWithDict(
      json_dict
    )
    self.assertEqual(
      (code, result.strip()),
      (0, """
INF: Storing errors in %(error_state_file)s
INF: %(fake_image)s : Downloading
INF: %(fake_image)s : Stored with checksum %(checksum)s
""".strip() % {
        'fake_image': self.fake_image,
        'checksum': self.fake_image_md5sum,
        'error_state_file': self.error_state_file,
        'destination': os.path.join(self.destination_directory, 'destination'),
      })
    )
    self.assertFileContent(self.md5sum_fail_file, '')
    self.assertFileContent(self.error_state_file, '')
    self.assertFileContent(self.processed_md5sum, 'config-md5sum')
    self.assertFalse(
      os.path.exists(os.path.join(self.destination_directory, 'tmp')))
    self.assertFileContent(
      os.path.join(self.destination_directory, 'destination'),
      'fake_image_content'
    )

    # Nothing happens if all is downloaded
    code, result = self.runImageDownloadControlerWithDict(
      json_dict
    )
    self.assertEqual(
      (code, result.strip()),
      (0, """
INF: Storing errors in %(error_state_file)s
INF: %(fake_image)s : already downloaded
""".strip() % {
        'fake_image': self.fake_image,
        'checksum': self.fake_image_md5sum,
        'error_state_file': self.error_state_file,
        'destination': os.path.join(self.destination_directory, 'destination'),
      })
    )

  def test_fail(self):
    json_dict = {
      'error-amount': 0,
      'config-md5sum': 'config-md5sum',
      'destination-directory': self.destination_directory,
      'image-list': [
        {
          'destination-tmp': 'tmp',
          'url': self.fake_image,
          'destination': 'destination',
1574
          'image-number': '001',
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
          'gzipped': False,
          'md5sum': self.fake_image_wrong_md5sum,
        }
      ]
    }
    for try_num in range(1, 5):
      code, result = self.runImageDownloadControlerWithDict(
        json_dict
      )
      self.assertEqual(
        (code, result.strip()),
        (1, """
INF: Storing errors in %(error_state_file)s
INF: %(fake_image)s : Downloading
""".  strip() % {
          'fake_image': self.fake_image,
          'error_state_file': self.error_state_file,
          'destination': os.path.join(
            self.destination_directory, 'destination'),
        })
      )
      fake_image_url = '#'.join([
        self.fake_image, self.fake_image_wrong_md5sum])
      self.assertFileContent(
        self.md5sum_fail_file, """{
  "%s": %s
}""" % (fake_image_url, try_num))
      self.assertFileContent(
        self.error_state_file, """
        ERR: %(fake_image)s : MD5 mismatch expected is %(wrong_checksum)s """
        """but got instead %(real_checksum)s""".strip() % {
          'fake_image': self.fake_image,
          'wrong_checksum': self.fake_image_wrong_md5sum,
          'real_checksum': self.fake_image_md5sum,
        })
      self.assertFileContent(self.processed_md5sum, 'config-md5sum')
      self.assertFalse(
        os.path.exists(os.path.join(self.destination_directory, 'tmp')))
      self.assertFalse(
        os.path.exists(
          os.path.join(self.destination_directory, 'destination')))

    code, result = self.runImageDownloadControlerWithDict(
      json_dict
    )
    self.assertEqual(
      (code, result.strip()),
      (1, """
INF: Storing errors in %(error_state_file)s
""".  strip() % {
        'fake_image': self.fake_image,
        'error_state_file': self.error_state_file,
        'destination': os.path.join(
          self.destination_directory, 'destination'),
      })
    )
    fake_image_url = '#'.join([
      self.fake_image, self.fake_image_wrong_md5sum])
    self.assertFileContent(
      self.md5sum_fail_file, """{
  "%s": %s
}""" % (fake_image_url, 4))
    self.assertFileContent(
      self.error_state_file, """
      ERR: %(fake_image)s : Checksum is incorrect after 4 tries, will not """
      """retry""".strip() % {
        'fake_image': self.fake_image,
      })
    self.assertFileContent(self.processed_md5sum, 'config-md5sum')
    self.assertFalse(
      os.path.exists(os.path.join(self.destination_directory, 'tmp')))
    self.assertFalse(
      os.path.exists(
        os.path.join(self.destination_directory, 'destination')))
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664


@skipUnlessKvm
class TestParameterDefault(InstanceTestCase, KvmMixin):
  __partition_reference__ = 'pd'

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'default'

  def mangleParameterDict(self, parameter_dict):
    return parameter_dict

  def _test(self, parameter_dict, expected):
    self.rerequestInstance(self.mangleParameterDict(parameter_dict))
    self.slap.waitForInstance(max_retry=10)
Łukasz Nowak's avatar
Łukasz Nowak committed
1665

1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
    kvm_raw = glob.glob(os.path.join(
      self.slap.instance_directory, '*', 'bin', 'kvm_raw'))
    self.assertEqual(len(kvm_raw), 1)
    kvm_raw = kvm_raw[0]
    with open(kvm_raw, 'r') as fh:
      kvm_raw = fh.read()
    self.assertIn(expected, kvm_raw)

  def test_disk_type_default(self):
    self._test({}, "disk_type = 'virtio'")

  def test_disk_type_set(self):
    self._test({'disk-type': 'ide'}, "disk_type = 'ide'")

  def test_network_adapter_default(self):
    self._test({}, "network_adapter = 'virtio-net-pci")

  def test_network_adapter_set(self):
    self._test({'network-adapter': 'e1000'}, "network_adapter = 'e1000'")

Łukasz Nowak's avatar
Łukasz Nowak committed
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
  def test_cpu_count_default(self):
    self._test({}, "init_smp_count = 2")

  def test_cpu_count_default_max(self):
    self._test({}, "smp_max_count = 3")

  def test_cpu_count_set(self):
    self._test({'cpu-count': 4}, "init_smp_count = 4")

  def test_cpu_count_set_max(self):
    self._test({'cpu-count': 4}, "smp_max_count = 5")

  def test_ram_size_default(self):
    self._test({}, "init_ram_size = 4096")

  def test_ram_size_default_max(self):
    self._test({}, "ram_max_size = '4608'")

  def test_ram_size_set(self):
    self._test({'ram-size': 2048}, "init_ram_size = 2048")

  def test_ram_size_set_max(self):
    self._test({'ram-size': 2048}, "ram_max_size = '2560'")

1710 1711 1712 1713

@skipUnlessKvm
class TestParameterResilient(TestParameterDefault):
  __partition_reference__ = 'pr'
Łukasz Nowak's avatar
Łukasz Nowak committed
1714

1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-resilient'


@skipUnlessKvm
class TestParameterCluster(TestParameterDefault):
  __partition_reference__ = 'pc'

  parameter_dict = {
    "disable-ansible-promise": True
  }

  @classmethod
  def getInstanceParameterDict(cls):
    return {'_': json.dumps({
      "kvm-partition-dict": {
        "KVM0": cls.parameter_dict
      }
    })}

  def mangleParameterDict(self, parameter_dict):
    local_parameter_dict = self.parameter_dict.copy()
    local_parameter_dict.update(parameter_dict)
    return {'_': json.dumps({
      "kvm-partition-dict": {
        "KVM0": local_parameter_dict
      }
    })}

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'kvm-cluster'
Łukasz Nowak's avatar
Łukasz Nowak committed
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801


@skipUnlessKvm
class TestExternalDisk(InstanceTestCase, KvmMixin):
  __partition_reference__ = 'ed'
  kvm_instance_partition_reference = 'ed0'

  @classmethod
  def getInstanceSoftwareType(cls):
    return 'default'

  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'external-disk-number': 2,
      'external-disk-size': 1
    }

  @classmethod
  def _prepareExternalStorageList(cls):
    external_storage_path = os.path.join(cls.working_directory, 'STORAGE')
    os.mkdir(external_storage_path)
    # reuse .slapos-resource infomration of the containing partition
    # it's similar to slapos/recipe/slapconfiguration.py
    _resource_home = cls.slap.instance_directory
    parent_slapos_resource = None
    while not os.path.exists(os.path.join(_resource_home, '.slapos-resource')):
      _resource_home = os.path.normpath(os.path.join(_resource_home, '..'))
      if _resource_home == "/":
        break
    else:
      with open(os.path.join(_resource_home, '.slapos-resource')) as fh:
        parent_slapos_resource = json.load(fh)
    assert parent_slapos_resource is not None

    for partition in os.listdir(cls.slap.instance_directory):
      if not partition.startswith(cls.__partition_reference__):
        continue
      partition_store_list = []
      for number in range(10):
        storage = os.path.join(external_storage_path, 'data%s' % (number,))
        if not os.path.exists(storage):
          os.mkdir(storage)
        partition_store = os.path.join(storage, partition)
        os.mkdir(partition_store)
        partition_store_list.append(partition_store)
      slapos_resource = parent_slapos_resource.copy()
      slapos_resource['external_storage_list'] = partition_store_list
      with open(
        os.path.join(
          cls.slap.instance_directory, partition, '.slapos-resource'),
        'w') as fh:
        json.dump(slapos_resource, fh, indent=2)
    # above is not enough: the presence of parameter is required in slapos.cfg
1802
    slapos_config = []
Łukasz Nowak's avatar
Łukasz Nowak committed
1803
    with open(cls.slap._slapos_config) as fh:
1804 1805 1806 1807 1808 1809 1810
      for line in fh.readlines():
        if line.strip() == '[slapos]':
          slapos_config.append('[slapos]\n')
          slapos_config.append(
            'instance_storage_home = %s\n' % (external_storage_path,))
        else:
          slapos_config.append(line)
Łukasz Nowak's avatar
Łukasz Nowak committed
1811
    with open(cls.slap._slapos_config, 'w') as fh:
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
      fh.write(''.join(slapos_config))

  @classmethod
  def _dropExternalStorageList(cls):
    slapos_config = []
    with open(cls.slap._slapos_config) as fh:
      for line in fh.readlines():
        if line.startswith("instance_storage_home ="):
          continue
        slapos_config.append(line)
    with open(cls.slap._slapos_config, 'w') as fh:
      fh.write(''.join(slapos_config))
Łukasz Nowak's avatar
Łukasz Nowak committed
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835

  @classmethod
  def _setUpClass(cls):
    super(TestExternalDisk, cls)._setUpClass()
    cls.working_directory = tempfile.mkdtemp()
    # setup the external_storage_list, to mimic part of slapformat
    cls._prepareExternalStorageList()
    # re-run the instance, as information has been updated
    cls.waitForInstance()

  @classmethod
  def tearDownClass(cls):
1836
    cls._dropExternalStorageList()
Łukasz Nowak's avatar
Łukasz Nowak committed
1837 1838 1839
    super(TestExternalDisk, cls).tearDownClass()
    shutil.rmtree(cls.working_directory)

1840 1841
  def getRunningDriveList(self, kvm_instance_partition):
    _match_drive = re.compile('file=(.+),if=virtio').match
Łukasz Nowak's avatar
Łukasz Nowak committed
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
    with self.slap.instance_supervisor_rpc as instance_supervisor:
      kvm_pid = next(q for q in instance_supervisor.getAllProcessInfo()
                     if 'kvm-' in q['name'])['pid']
    dirve_list = []
    for entry in psutil.Process(kvm_pid).cmdline():
      m = _match_drive(entry)
      if m:
        path = m.group(1)
        dirve_list.append(
          path.replace(kvm_instance_partition, '${partition}')
        )
    return dirve_list

  def test(self):
    kvm_instance_partition = os.path.join(
      self.slap.instance_directory, self.kvm_instance_partition_reference)
    drive_list = self.getRunningDriveList(kvm_instance_partition)

1860 1861
    # Note: Do to unknown set of drives it's impossible to directly check
    #       drive paths, thus the count is important
Łukasz Nowak's avatar
Łukasz Nowak committed
1862 1863
    self.assertEqual(
      1 + 2,  # 1 the default drive, 2 additional ones
1864 1865
      len(drive_list)
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880

    # restart the VM
    self.requestDefaultInstance(state='stopped')
    self.waitForInstance()
    self.requestDefaultInstance(state='started')
    self.waitForInstance()
    restarted_drive_list = self.getRunningDriveList(kvm_instance_partition)
    self.assertEqual(drive_list, restarted_drive_list)
    # prove that even on resetting parameters, drives are still there
    self.rerequestInstance({}, state='stopped')
    self.waitForInstance()
    self.rerequestInstance({})
    self.waitForInstance()
    dropped_drive_list = self.getRunningDriveList(kvm_instance_partition)
    self.assertEqual(drive_list, dropped_drive_list)