test_resiliency.py 21.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 28 29 30 31 32
##############################################################################
#
# Copyright (c) 2019 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.
#
##############################################################################
from __future__ import unicode_literals

import errno
import os
import re
import shutil
33
import sqlite3
34 35 36 37 38
import subprocess
import time

import requests

39 40
from slapos.proxy.db_version import DB_VERSION

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
from slapos.testing.testcase import SlapOSNodeCommandError, installSoftwareUrlList

from test import TheiaTestCase, ResilientTheiaMixin, theia_software_release_url


dummy_software_url = os.path.abspath(
  os.path.join('resilience_dummy', 'software.cfg'))


class WorkaroundSnapshotConflict(TheiaTestCase):
  @classmethod
  def _copySnapshot(cls, source_file_name, name):
    # Workaround setUpModule snapshots name conflicts
    if not name.startswith(cls.__module__):
      name = '%s.%s' % (cls.__module__, name)
    super(WorkaroundSnapshotConflict, cls)._copySnapshot(source_file_name, name)


def setUpModule():
  installSoftwareUrlList(
    WorkaroundSnapshotConflict,
    [theia_software_release_url],
    debug=bool(int(os.environ.get('SLAPOS_TEST_DEBUG', 0))),
  )


class ResilientTheiaTestCase(ResilientTheiaMixin, TheiaTestCase):
  @classmethod
69
  def _processEmbeddedInstance(cls, retries=0, instance_type='export'):
70 71
    for _ in range(retries):
      try:
72
        output = cls.captureSlapos('node', 'instance', instance_type=instance_type, stderr=subprocess.STDOUT)
73 74 75 76 77 78 79 80 81
      except subprocess.CalledProcessError:
        continue
      print(output)
      break
    else:
      if retries:
        # Sleep a bit as an attempt to workaround monitoring boostrap not being ready
        print("Wait before running slapos node instance one last time")
        time.sleep(120)
82
      cls.checkSlapos('node', 'instance', instance_type=instance_type)
83 84

  @classmethod
85 86
  def _deployEmbeddedSoftware(cls, software_url, instance_name, retries=0, instance_type='export'):
    cls.callSlapos('supply', software_url, 'slaprunner', instance_type=instance_type)
87
    try:
88
      cls.captureSlapos('node', 'software', instance_type=instance_type, stderr=subprocess.STDOUT)
89 90 91
    except subprocess.CalledProcessError as e:
      print(e.output)
      raise
92 93
    cls.callSlapos('request', instance_name, software_url, instance_type=instance_type)
    cls._processEmbeddedInstance(retries, instance_type)
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

  @classmethod
  def getInstanceParameterDict(cls):
    return {'autorun': 'stopped'}


class ResilienceMixin(object):
  def _prepareExport(self):
    pass

  def _doSync(self):
    raise NotImplementedError

  def _checkSync(self):
    pass

  def _doTakeover(self):
    raise NotImplementedError

  def _checkTakeover(self):
    pass

  def test(self):
    # Do stuff on the main instance
    # e.g. deploy an embedded software instance
    self._prepareExport()

    # Backup the main instance to a clone
    # i.e. call export and import scripts
    self._doSync()

    # Check that the export-backup-import process went well
    # e.g. look at logs and compare data
    self._checkSync()

    # Let the clone become a main instance
    # i.e. start embedded services
    self._doTakeover()

    # Check that the takeover went well
    # e.g. check services
    self._checkTakeover()


class ExportAndImportMixin(object):
  def getExportExitfile(self):
140
    return self.getPartitionPath('export', 'srv', 'export-exitcode-file')
141 142

  def getExportErrorfile(self):
143
    return self.getPartitionPath('export', 'srv', 'export-errormessage-file')
144 145

  def getImportExitfile(self):
146
    return self.getPartitionPath('import', 'srv', 'import-exitcode-file')
147 148

  def getImportErrorfile(self):
149
    return self.getPartitionPath('import', 'srv', 'import-errormessage-file')
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

  def makedirs(self, path):
    try:
      os.makedirs(path if os.path.isdir(path) else os.path.dirname(path))
    except OSError as e:
      if e.errno != errno.EEXIST:
        raise

  def writeFile(self, path, content, mode='w'):
    self.makedirs(path)
    executable = mode == 'exec'
    mode = 'w' if executable else mode
    with open(path, mode) as f:
      if executable:
        f.write('#!/bin/sh\n')
      f.write(content)
    if executable:
      os.chmod(path, 0o700)

  def assertPromiseSucess(self):
    # Force promises to recompute regardless of periodicity
    self.slap._force_slapos_node_instance_all = True
    try:
      self.slap.waitForInstance(error_lines=0)
    except SlapOSNodeCommandError as e:
      s = str(e)
      self.assertNotIn("Promise 'resiliency-export-promise.py' failed", s)
      self.assertNotIn('ERROR export script', s)
      self.assertNotIn("Promise 'resiliency-import-promise.py' failed", s)
      self.assertNotIn('ERROR import script', s)
    else:
      pass

  def _doExport(self):
    # Compute last modification of the export exitcode file
    exitfile = self.getExportExitfile()
    initial_exitdate = os.path.getmtime(exitfile)

    # Call export script manually
189
    theia_export_script = self.getPartitionPath('export', 'bin', 'theia-export-script')
190 191 192 193 194 195 196 197 198 199 200 201
    subprocess.check_call((theia_export_script,), stderr=subprocess.STDOUT)

    # Check that the export exitcode file was modified
    self.assertGreater(os.path.getmtime(exitfile), initial_exitdate)
    with open(exitfile) as f:
      self.assertEqual('0', f.read())

    # Check promises
    self.assertPromiseSucess()

  def _doTransfer(self):
    # Copy <export>/srv/backup/theia to <import>/srv/backup/theia manually
202 203
    export_backup_path = self.getPartitionPath('export', 'srv', 'backup', 'theia')
    import_backup_path = self.getPartitionPath('import', 'srv', 'backup', 'theia')
204 205 206 207 208 209 210 211 212
    shutil.rmtree(import_backup_path)
    shutil.copytree(export_backup_path, import_backup_path)

  def _doImport(self):
    # Compute last modification of the import exitcode file
    exitfile = self.getImportExitfile()
    initial_exitdate = os.path.getmtime(exitfile)

    # Call the import script manually
213
    theia_import_script = self.getPartitionPath('import', 'bin', 'theia-import-script')
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    subprocess.check_call((theia_import_script,), stderr=subprocess.STDOUT)

    # Check that the import exitcode file was updated
    self.assertGreater(os.path.getmtime(exitfile), initial_exitdate)
    with open(exitfile) as f:
      self.assertEqual('0', f.read())

    # Check promises
    self.assertPromiseSucess()


class TestTheiaExportAndImportFailures(ExportAndImportMixin, ResilientTheiaTestCase):
  script_relpath = os.path.join(
    'srv', 'runner', 'instance', 'slappart0',
    'srv', '.backup_identity_script')
229 230
  signature_relpath = os.path.join(
    'srv', 'backup', 'theia', 'backup.signature')
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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280

  def assertPromiseFailure(self, *msg):
    # Force promises to recompute regardless of periodicity
    self.slap._force_slapos_node_instance_all = True
    try:
      self.slap.waitForInstance(error_lines=0)
    except SlapOSNodeCommandError as e:
      s = str(e).replace('\\n', '\n')
      for m in msg:
        self.assertIn(m, s)
    else:
      self.fail('No promise failed')

  def assertScriptFailure(self, func, errorfile, exitfile, *msg):
    self.assertRaises(
      subprocess.CalledProcessError,
      func,
    )
    if msg:
      with open(errorfile) as f:
        error = f.read()
      for m in msg:
        self.assertIn(m, error)
    with open(exitfile) as f:
      self.assertNotEqual('0', f.read())

  def assertExportFailure(self, *msg):
    self.assertScriptFailure(
      self._doExport,
      self.getExportErrorfile(),
      self.getExportExitfile(),
      *msg)
    self.assertPromiseFailure('ERROR export script failed', *msg)

  def assertImportFailure(self, *msg):
    self.assertScriptFailure(
      self._doImport,
      self.getImportErrorfile(),
      self.getImportExitfile(),
      *msg)
    self.assertPromiseFailure('ERROR import script failed', *msg)

  def customScript(self, path, content=None):
    if content:
      self.writeFile(path, content, mode='exec')
    else:
      if os.path.exists(path):
        os.remove(path)

  def customSignatureScript(self, content=None):
281
    custom_script = self.getPartitionPath('export', self.script_relpath)
282 283 284
    self.customScript(custom_script, content)

  def customRestoreScript(self, content=None):
285
    restore_script = self.getPartitionPath('import', 'srv', 'runner-import-restore')
286 287 288 289 290 291 292 293 294 295 296
    self.customScript(restore_script, content)
    return restore_script

  def cleanupExitfiles(self):
    self.writeFile(self.getExportExitfile(), '0')
    self.writeFile(self.getImportExitfile(), '0')

  def setUp(self):
    self.customSignatureScript(content=None)
    self.customRestoreScript(content=None)
    self.cleanupExitfiles()
297
    try:
298
      os.remove(self.getPartitionPath('import', self.signature_relpath))
299 300
    except OSError:
      pass
301 302 303 304 305 306 307 308 309 310 311 312

  def test_export_promise(self):
    self.writeFile(self.getExportExitfile(), '1')
    self.assertPromiseFailure('ERROR export script failed')

  def test_import_promise(self):
    self.writeFile(self.getImportExitfile(), '1')
    self.assertPromiseFailure('ERROR import script failed')

  def test_custom_hash_script(self):
    errmsg = 'Bye bye'
    self.customSignatureScript(content='>&2 echo "%s"\nexit 1' % errmsg)
313
    custom_script = self.getPartitionPath('export', self.script_relpath)
314 315
    self.assertExportFailure('Compute partitions backup signatures\n ... ERROR !',
      'Custom signature script %s failed' % os.path.abspath(custom_script),
316 317 318
      'and stderr:\n%s' % errmsg)

  def test_signature_mismatch(self):
319
    signature_file = self.getPartitionPath('import', self.signature_relpath)
320
    self.writeFile(signature_file, 'Bogus Hash\n', mode='a')
321 322 323 324 325 326 327 328 329 330
    self.assertImportFailure('ERROR the backup signatures do not match')

  def test_restore_script_error(self):
    self._doExport()
    self._doTransfer()
    restore_script = self.customRestoreScript('exit 1')
    self.assertImportFailure('Run custom restore script %s\n ... ERROR !' % restore_script)


class TestTheiaExportAndImport(ResilienceMixin, ExportAndImportMixin, ResilientTheiaTestCase):
331 332 333 334 335
  def test_twice(self):
    # Run two synchronisations on the same instances
    # to make sure everything still works the second time
    self._doSync()

336 337 338 339 340 341 342 343 344 345 346 347
  def checkLog(self, log_path, initial=[], newline="Hello"):
    with open(log_path) as f:
      log = f.readlines()
    self.assertEqual(len(log), len(initial) + int(bool(newline)))
    for line, initial_line in zip(log, initial):
      self.assertEqual(line, initial_line)
    if newline:
      self.assertTrue(log[-1].startswith(newline), log[-1])
    return log

  def _prepareExport(self):
    # Copy ./resilience_dummy SR in export theia ~/srv/project/dummy
348
    dummy_target_path = self.getPartitionPath('export', 'srv', 'project', 'dummy')
349 350 351 352 353 354 355
    shutil.copytree(os.path.dirname(dummy_software_url), dummy_target_path)
    self._test_software_url = os.path.join(dummy_target_path, 'software.cfg')

    # Deploy dummy instance in export partition
    self._deployEmbeddedSoftware(self._test_software_url, 'dummy_instance')

    relpath_dummy = os.path.join('srv', 'runner', 'instance', 'slappart0')
356 357
    self.export_dummy_root = dummy_root = self.getPartitionPath('export', relpath_dummy)
    self.import_dummy_root = self.getPartitionPath('import', relpath_dummy)
358 359 360 361 362 363 364 365 366 367 368 369

    # Check that dummy instance was properly deployed
    self.initial_log = self.checkLog(os.path.join(dummy_root, 'log.log'))

    # Create ~/include and ~/include/included
    self.writeFile(os.path.join(dummy_root, 'include', 'included'),
      'This file should be included in resilient backup')

    # Create ~/exclude and ~/exclude/excluded
    self.writeFile(os.path.join(dummy_root, 'exclude', 'excluded'),
      'This file should be excluded from resilient backup')

370
    # Check that ~/srv/exporter.exclude and ~/srv/runner-import-restore exist
371 372 373 374 375
    # As well as ~/srv/.backup_identity_script
    self.assertTrue(os.path.exists(os.path.join(dummy_root, 'srv', 'exporter.exclude')))
    self.assertTrue(os.path.exists(os.path.join(dummy_root, 'srv', 'runner-import-restore')))
    self.assertTrue(os.path.exists(os.path.join(dummy_root, 'srv', '.backup_identity_script')))

376
    # Remember content of ~/etc in the import theia
377
    self.etc_listdir = os.listdir(self.getPartitionPath('import', 'etc'))
378

379 380 381 382 383 384 385 386 387
  def _doSync(self):
    self._doExport()
    self._doTransfer()
    self._doImport()

  def _checkSync(self):
    dummy_root = self.import_dummy_root

    # Check that the software url is correct
388 389
    adapted_test_url = self.getPartitionPath('import', 'srv', 'project', 'dummy', 'software.cfg')
    proxy_content = self.captureSlapos('proxy', 'show', instance_type='import', text=True)
390 391 392
    self.assertIn(adapted_test_url, proxy_content)
    self.assertNotIn(self._test_software_url, proxy_content)

393
    # Check that ~/etc still contains everything it did before
394
    etc_listdir = os.listdir(self.getPartitionPath('import', 'etc'))
395 396
    self.assertTrue(set(self.etc_listdir).issubset(etc_listdir))

397 398 399 400 401 402
    # Check that ~/srv/project was exported
    self.assertTrue(os.path.exists(adapted_test_url))

    # Check that the dummy instance is not yet started
    self.checkLog(os.path.join(dummy_root, 'log.log'), self.initial_log, newline=None)

403
    # Check that ~/srv/.backup_identity_script was detected and called
404
    signature =  self.getPartitionPath(
405 406
      'import', 'srv', 'backup', 'theia', 'slappart0.backup.signature.custom')
    self.assertTrue(os.path.exists(signature))
407 408 409 410 411 412 413 414 415 416 417 418 419 420
    with open(signature) as f:
      self.assertIn('Custom script', f.read())

    # Check that ~/include and ~/include/included were included
    self.assertTrue(os.path.exists(os.path.join(dummy_root, 'include', 'included')))

    # Check that ~/exclude was excluded
    self.assertFalse(os.path.exists(os.path.join(dummy_root, 'exclude')))

    # Check that ~/srv/runner-import-restore was called
    self.checkLog(os.path.join(dummy_root, 'runner-import-restore.log'))

  def _doTakeover(self):
    # Start the dummy instance as a sort of fake takeover
421
    self.callSlapos('node', 'instance', instance_type='import')
422 423 424 425 426 427 428 429 430 431 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 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484

  def _checkTakeover(self):
    # Check that dummy instance was properly re-deployed
    log_path = os.path.join(self.import_dummy_root, 'log.log')
    self.checkLog(log_path, self.initial_log)


class TakeoverMixin(ExportAndImportMixin):
  def _getTakeoverUrlAndPassword(self, scope="theia-1"):
    parameter_dict = self.computer_partition.getConnectionParameterDict()
    takeover_url = parameter_dict["takeover-%s-url" % scope]
    takeover_password = parameter_dict["takeover-%s-password" % scope]
    return takeover_url, takeover_password

  def _getTakeoverPage(self, takeover_url):
    resp = requests.get(takeover_url, verify=True)
    self.assertEqual(requests.codes.ok, resp.status_code)
    return resp.text

  def _waitScriptDone(self, name, start, exitfile, errorfile, maxtries, interval):
    print('Wait until %s script has run' % name.lower())
    for t in range(maxtries):
      if os.path.getmtime(exitfile) < start:
        time.sleep(interval)
        continue
      with open(exitfile) as f:
        if f.read() == '0':
          print(name + ' script ran successfully')
          return maxtries - t
      print(name + ' script failed:\n')
      with open(errorfile) as f:
        print(f.read())
      self.fail(name + ' script failed')
    self.fail(name + ' script did not finish before timeout')

  def _waitTakeoverReady(self, takeover_url, start, maxtries, interval):
    export_exitfile = self.getExportExitfile()
    export_errorfile =  self.getExportErrorfile()
    tries = self._waitScriptDone(
      'Export', start, export_exitfile, export_errorfile, maxtries, interval)
    import_exitfile = self.getImportExitfile()
    import_errorfile =  self.getImportErrorfile()
    tries = self._waitScriptDone(
      'Import', start, import_exitfile, import_errorfile, tries, interval)
    for _ in range(tries):
      info = self._getTakeoverPage(takeover_url)
      if "No backup downloaded yet, takeover should not happen now." in info:
        print('Takeover page still reports export script in progress')
      elif "<b>Importer script(s) of backup in progress:</b> True" in info:
        print('Takeover page still reports import script in progress')
      else:
        return
      time.sleep(interval)
    self.fail('Takeover page failed to report readiness')

  def _requestTakeover(self, takeover_url, takeover_password):
    resp = requests.get("%s?password=%s" % (takeover_url, takeover_password), verify=True)
    self.assertEqual(requests.codes.ok, resp.status_code)
    self.assertNotIn("Error", resp.text, "An Error occured: %s" % resp.text)
    self.assertIn("Success", resp.text, "An Error occured: %s" % resp.text)
    return resp.text


485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
class TheiaSyncMixin(ResilienceMixin, TakeoverMixin):
  def _doSync(self, max_tries=None, wait_interval=None):
    max_tries = max_tries or self.backup_max_tries
    wait_interval = wait_interval or self.backup_wait_interval

    start = time.time()

    # Call exporter script instead of waiting for cron job
    # XXX Accelerate cron frequency instead ?
    exporter_script = self.getPartitionPath('export', 'bin', 'exporter')
    transaction_id = str(int(time.time()))
    subprocess.check_call((exporter_script, '--transaction-id', transaction_id))

    takeover_url, _ = self._getTakeoverUrlAndPassword()

    # Wait for takoever to be ready
    self._waitTakeoverReady(takeover_url, start, max_tries, wait_interval)


class TestTheiaResilience(TheiaSyncMixin, ResilientTheiaTestCase):
505 506 507 508 509 510
  test_instance_max_retries = 0
  backup_max_tries = 70
  backup_wait_interval = 10

  _test_software_url = dummy_software_url

511 512 513 514
  def test_twice(self):
    # Run two synchronisations on the same instances
    # to make sure everything still works the second time
    # Check ~/etc in import theia again
515
    self.etc_listdir = os.listdir(self.getPartitionPath('import', 'etc'))
516 517 518
    self._doSync()
    self._checkSync()

519 520 521 522 523
  def _prepareExport(self):
    # Deploy test instance
    self._deployEmbeddedSoftware(self._test_software_url, 'test_instance', self.test_instance_max_retries)

    # Check that there is an export and import instance and get their partition IDs
524 525
    self.export_id = self.getPartitionId('export')
    self.import_id = self.getPartitionId('import')
526

527
    # Remember content of ~/etc in the import theia
528
    self.etc_listdir = os.listdir(self.getPartitionPath('import', 'etc'))
529 530 531

  def _checkSync(self):
    # Check that ~/etc still contains everything it did before
532
    etc_listdir = os.listdir(self.getPartitionPath('import', 'etc'))
533 534
    self.assertTrue(set(self.etc_listdir).issubset(etc_listdir))

535 536 537 538 539 540 541 542 543 544 545 546 547 548
  def _doTakeover(self):
    # Takeover
    takeover_url, takeover_password = self._getTakeoverUrlAndPassword()
    self._requestTakeover(takeover_url, takeover_password)

    # Wait for import instance to become export instance and new import to be allocated
    # This also checks that all promises of theia instances succeed
    self.slap.waitForInstance(self.instance_max_retry)
    self.computer_partition = self.requestDefaultInstance()

  def _checkTakeover(self):
    # Check that there is an export, import and frozen instance and get their new partition IDs
    import_id = self.import_id
    export_id = self.export_id
549 550 551
    new_export_id = self.getPartitionId('export')
    new_import_id = self.getPartitionId('import')
    new_frozen_id = self.getPartitionId('frozen')
552 553 554 555 556 557 558 559 560 561 562 563 564

    # Check that old export instance is now frozen
    self.assertEqual(export_id, new_frozen_id)

    # Check that old import instance is now the new export instance
    self.assertEqual(import_id, new_export_id)

    # Check that there is a new import instance
    self.assertNotIn(new_import_id, (export_id, new_export_id))

    # Check that the test instance is properly redeployed
    # This checks the promises of the test instance
    self._processEmbeddedInstance(self.test_instance_max_retries)
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596


class TestTheiaFrontendForwarding(TheiaSyncMixin, ResilientTheiaTestCase):
  backup_max_tries = 100
  backup_wait_interval = 20

  html5as_url = os.path.abspath(
    os.path.join(
      os.path.dirname(__file__), '..', '..', 'html5as', 'software.cfg'))

  def _prepareExport(self):
    # Deploy an embedded html5as
    self._deployEmbeddedSoftware(self.html5as_url, 'html5as', 1)

  def _checkSync(self):
    proxy_relpath = os.path.join('srv', 'runner', 'var', 'proxy.db')
    query = "SELECT rowid, partition_reference FROM forwarded_partition_request%s" % DB_VERSION

    # Check that theia0 forwards frontend requests
    with sqlite3.connect(self.getPartitionPath('export', proxy_relpath)) as db:
      rows = db.execute(query).fetchall()
      self.assertIn("slappart0_HTML5AS frontend", (row[1] for row in rows))

    # Check that theia1 does not forward frontend requests
    # i.e that there were no new insertions in the database since it was cloned
    # by ensuring the rowids are still the same
    with sqlite3.connect(self.getPartitionPath('import', proxy_relpath)) as db:
      self.assertEqual(db.execute(query).fetchall(), rows)

  def _doTakeover(self):
    # do nothing
    pass