slapgrid.py 95.6 KB
Newer Older
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
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) 2010 Vifib SARL 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
from __future__ import absolute_import
Łukasz Nowak's avatar
Łukasz Nowak committed
29
import logging
Łukasz Nowak's avatar
Łukasz Nowak committed
30
import os
Marco Mariani's avatar
Marco Mariani committed
31
import random
Łukasz Nowak's avatar
Łukasz Nowak committed
32
import shutil
33
import signal
Łukasz Nowak's avatar
Łukasz Nowak committed
34
import socket
35
import sys
36
import stat
37
import tempfile
Marco Mariani's avatar
Marco Mariani committed
38
import textwrap
39
import time
40
import unittest
Łukasz Nowak's avatar
Łukasz Nowak committed
41
import urlparse
42
import json
Marco Mariani's avatar
Marco Mariani committed
43

44
import xml_marshaller
45
from mock import patch
Łukasz Nowak's avatar
Łukasz Nowak committed
46

Marco Mariani's avatar
Marco Mariani committed
47 48 49 50
import slapos.slap.slap
import slapos.grid.utils
from slapos.grid import slapgrid
from slapos.grid.utils import md5digest
51
from slapos.grid.watchdog import Watchdog
52
from slapos.grid import SlapObject
53
from slapos.grid.SlapObject import WATCHDOG_MARK
54
import slapos.grid.SlapObject
Marco Mariani's avatar
Marco Mariani committed
55

56 57
import httmock

58

Marco Mariani's avatar
Marco Mariani committed
59 60
dummylogger = logging.getLogger()

61

62
WATCHDOG_TEMPLATE = """#!{python_path} -S
63
import sys
64 65
sys.path={sys_path}
import slapos.slap
66 67
import slapos.grid.watchdog

68 69 70 71 72 73 74 75 76 77 78
def bang(self_partition, message):
  nl = chr(10)
  with open('{watchdog_banged}', 'w') as fout:
    for key, value in vars(self_partition).items():
      fout.write('%s: %s%s' % (key, value, nl))
      if key == '_connection_helper':
        for k, v in vars(value).items():
          fout.write('   %s: %s%s' % (k, v, nl))
    fout.write(message)

slapos.slap.ComputerPartition.bang = bang
79 80 81
slapos.grid.watchdog.main()
"""

82 83 84 85
WRAPPER_CONTENT = """#!/bin/sh
touch worked &&
mkdir -p etc/run &&
echo "#!/bin/sh" > etc/run/wrapper &&
Marco Mariani's avatar
Marco Mariani committed
86
echo "while true; do echo Working; sleep 0.1; done" >> etc/run/wrapper &&
87 88 89
chmod 755 etc/run/wrapper
"""

90 91 92 93 94
DAEMON_CONTENT = """#!/bin/sh
mkdir -p etc/service &&
echo "#!/bin/sh" > etc/service/daemon &&
echo "touch launched
if [ -f ./crashed ]; then
Marco Mariani's avatar
Marco Mariani committed
95
while true; do echo Working; sleep 0.1; done
96
else
Marco Mariani's avatar
Marco Mariani committed
97
touch ./crashed; echo Failing; sleep 1; exit 111;
98 99 100 101 102
fi" >> etc/service/daemon &&
chmod 755 etc/service/daemon &&
touch worked
"""

103

104 105

class BasicMixin(object):
Łukasz Nowak's avatar
Łukasz Nowak committed
106 107
  def setUp(self):
    self._tempdir = tempfile.mkdtemp()
108 109
    self.software_root = os.path.join(self._tempdir, 'software')
    self.instance_root = os.path.join(self._tempdir, 'instance')
110 111 112
    logging.basicConfig(level=logging.DEBUG)
    self.setSlapgrid()

Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
113
  def setSlapgrid(self, develop=False):
114
    if getattr(self, 'master_url', None) is None:
115
      self.master_url = 'http://127.0.0.1:80/'
Łukasz Nowak's avatar
Łukasz Nowak committed
116 117 118
    self.computer_id = 'computer'
    self.supervisord_socket = os.path.join(self._tempdir, 'supervisord.sock')
    self.supervisord_configuration_path = os.path.join(self._tempdir,
119
                                                       'supervisord')
Łukasz Nowak's avatar
Łukasz Nowak committed
120 121
    self.usage_report_periodicity = 1
    self.buildout = None
122 123 124 125 126 127 128
    self.grid = slapgrid.Slapgrid(self.software_root,
                                  self.instance_root,
                                  self.master_url,
                                  self.computer_id,
                                  self.buildout,
                                  develop=develop,
                                  logger=logging.getLogger())
129
    # monkey patch buildout bootstrap
130

131 132
    def dummy(*args, **kw):
      pass
133

134
    slapos.grid.utils.bootstrapBuildout = dummy
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
135

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    SlapObject.PROGRAM_PARTITION_TEMPLATE = textwrap.dedent("""\
        [program:%(program_id)s]
        directory=%(program_directory)s
        command=%(program_command)s
        process_name=%(program_name)s
        autostart=false
        autorestart=false
        startsecs=0
        startretries=0
        exitcodes=0
        stopsignal=TERM
        stopwaitsecs=60
        stopasgroup=true
        killasgroup=true
        user=%(user_id)s
        group=%(group_id)s
        serverurl=AUTO
        redirect_stderr=true
        stdout_logfile=%(instance_path)s/.%(program_id)s.log
        stderr_logfile=%(instance_path)s/.%(program_id)s.log
        environment=USER="%(USER)s",LOGNAME="%(USER)s",HOME="%(HOME)s"
        """)

Marco Mariani's avatar
Marco Mariani committed
159
  def launchSlapgrid(self, develop=False):
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
160 161
    self.setSlapgrid(develop=develop)
    return self.grid.processComputerPartitionList()
162

Marco Mariani's avatar
Marco Mariani committed
163
  def launchSlapgridSoftware(self, develop=False):
164 165 166
    self.setSlapgrid(develop=develop)
    return self.grid.processSoftwareReleaseList()

Marco Mariani's avatar
Marco Mariani committed
167 168 169 170
  def assertLogContent(self, log_path, expected, tries=50):
    for i in range(tries):
      if expected in open(log_path).read():
        return
171
      time.sleep(0.01)
Marco Mariani's avatar
Marco Mariani committed
172 173 174 175 176 177
    self.fail('%r not found in %s' % (expected, log_path))

  def assertIsCreated(self, path, tries=50):
    for i in range(tries):
      if os.path.exists(path):
        return
178
      time.sleep(0.01)
Marco Mariani's avatar
Marco Mariani committed
179 180 181 182 183 184
    self.fail('%s should be created' % path)

  def assertIsNotCreated(self, path, tries=50):
    for i in range(tries):
      if os.path.exists(path):
        self.fail('%s should not be created' % path)
185
      time.sleep(0.01)
Marco Mariani's avatar
Marco Mariani committed
186

187 188 189 190 191 192
  def assertInstanceDirectoryListEqual(self, instance_list):
    instance_list.append('etc')
    instance_list.append('var')
    instance_list.append('supervisord.socket')
    self.assertItemsEqual(os.listdir(self.instance_root), instance_list)

Łukasz Nowak's avatar
Łukasz Nowak committed
193
  def tearDown(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
194 195 196 197 198 199 200 201 202
    # XXX: Hardcoded pid, as it is not configurable in slapos
    svc = os.path.join(self.instance_root, 'var', 'run', 'supervisord.pid')
    if os.path.exists(svc):
      try:
        pid = int(open(svc).read().strip())
      except ValueError:
        pass
      else:
        os.kill(pid, signal.SIGTERM)
203
    shutil.rmtree(self._tempdir, True)
Łukasz Nowak's avatar
Łukasz Nowak committed
204

205

206
class TestRequiredOnlyPartitions(unittest.TestCase):
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
  def test_no_errors(self):
    required = ['one', 'three']
    existing = ['one', 'two', 'three']
    slapgrid.check_required_only_partitions(existing, required)

  def test_one_missing(self):
    required = ['foobar', 'two', 'one']
    existing = ['one', 'two', 'three']
    self.assertRaisesRegexp(ValueError,
                            'Unknown partition: foobar',
                            slapgrid.check_required_only_partitions,
                            existing, required)

  def test_several_missing(self):
    required = ['foobar', 'barbaz']
    existing = ['one', 'two', 'three']
    self.assertRaisesRegexp(ValueError,
                            'Unknown partitions: barbaz, foobar',
                            slapgrid.check_required_only_partitions,
                            existing, required)


229
class TestBasicSlapgridCP(BasicMixin, unittest.TestCase):
Łukasz Nowak's avatar
Łukasz Nowak committed
230 231 232 233 234 235 236
  def test_no_software_root(self):
    self.assertRaises(OSError, self.grid.processComputerPartitionList)

  def test_no_instance_root(self):
    os.mkdir(self.software_root)
    self.assertRaises(OSError, self.grid.processComputerPartitionList)

237
  @unittest.skip('which request handler here?')
Łukasz Nowak's avatar
Łukasz Nowak committed
238 239 240 241
  def test_no_master(self):
    os.mkdir(self.software_root)
    os.mkdir(self.instance_root)
    self.assertRaises(socket.error, self.grid.processComputerPartitionList)
242

243

244
class MasterMixin(BasicMixin):
245

246 247 248 249 250 251 252 253 254 255 256 257 258
  def _mock_sleep(self):
    self.fake_waiting_time = None
    self.real_sleep = time.sleep

    def mocked_sleep(secs):
      if self.fake_waiting_time is not None:
        secs = self.fake_waiting_time
      self.real_sleep(secs)

    time.sleep = mocked_sleep

  def _unmock_sleep(self):
    time.sleep = self.real_sleep
259

260
  def setUp(self):
261
    self._mock_sleep()
262
    BasicMixin.setUp(self)
263 264

  def tearDown(self):
265
    self._unmock_sleep()
266 267
    BasicMixin.tearDown(self)

268

269
class ComputerForTest(object):
270 271 272 273
  """
  Class to set up environment for tests setting instance, software
  and server response
  """
274 275 276 277 278
  def __init__(self,
               software_root,
               instance_root,
               instance_amount=1,
               software_amount=1):
279 280 281 282
    """
    Will set up instances, software and sequence
    """
    self.sequence = []
283 284 285 286
    self.instance_amount = instance_amount
    self.software_amount = software_amount
    self.software_root = software_root
    self.instance_root = instance_root
287 288 289 290 291
    self.ip_address_list = [
            ('interface1', '10.0.8.3'),
            ('interface2', '10.0.8.4'),
            ('route_interface1', '10.10.8.4')
      ]
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
292 293 294 295
    if not os.path.isdir(self.instance_root):
      os.mkdir(self.instance_root)
    if not os.path.isdir(self.software_root):
      os.mkdir(self.software_root)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
296 297
    self.setSoftwares()
    self.setInstances()
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317


  def request_handler(self, url, req):
    """
    Define _callback.
    Will register global sequence of message, sequence by partition
    and error and error message by partition
    """
    self.sequence.append(url.path)
    if req.method == 'GET':
      qs = urlparse.parse_qs(url.query)
    else:
      qs = urlparse.parse_qs(req.body)
    if (url.path == '/getFullComputerInformation'
            and 'computer_id' in qs):
      slap_computer = self.getComputer(qs['computer_id'][0])
      return {
              'status_code': 200,
              'content': xml_marshaller.xml_marshaller.dumps(slap_computer)
              }
318 319 320 321 322 323
    elif url.path == '/getHostingSubscriptionIpList':
      ip_address_list = self.ip_address_list
      return {
              'status_code': 200,
              'content': xml_marshaller.xml_marshaller.dumps(ip_address_list)
              }
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    if req.method == 'POST' and 'computer_partition_id' in qs:
      instance = self.instance_list[int(qs['computer_partition_id'][0])]
      instance.sequence.append(url.path)
      instance.header_list.append(req.headers)
      if url.path == '/availableComputerPartition':
        return {'status_code': 200}
      if url.path == '/startedComputerPartition':
        instance.state = 'started'
        return {'status_code': 200}
      if url.path == '/stoppedComputerPartition':
        instance.state = 'stopped'
        return {'status_code': 200}
      if url.path == '/destroyedComputerPartition':
        instance.state = 'destroyed'
        return {'status_code': 200}
      if url.path == '/softwareInstanceBang':
        return {'status_code': 200}
      if url.path == '/softwareInstanceError':
        instance.error_log = '\n'.join(
            [
                line
                for line in qs['error_log'][0].splitlines()
                if 'dropPrivileges' not in line
            ]
        )
        instance.error = True
        return {'status_code': 200}

    elif req.method == 'POST' and 'url' in qs:
      # XXX hardcoded to first software release!
      software = self.software_list[0]
      software.sequence.append(url.path)
      if url.path == '/buildingSoftwareRelease':
        return {'status_code': 200}
      if url.path == '/softwareReleaseError':
        software.error_log = '\n'.join(
            [
                line
                for line in qs['error_log'][0].splitlines()
                if 'dropPrivileges' not in line
            ]
        )
        software.error = True
        return {'status_code': 200}

    else:
      return {'status_code': 500}



374

375 376 377 378
  def setSoftwares(self):
    """
    Will set requested amount of software
    """
Marco Mariani's avatar
Marco Mariani committed
379
    self.software_list = [
380 381 382
        SoftwareForTest(self.software_root, name=str(i))
        for i in range(self.software_amount)
    ]
383

384
  def setInstances(self):
385 386 387
    """
    Will set requested amount of instance giving them by default first software
    """
Marco Mariani's avatar
Marco Mariani committed
388 389 390 391 392 393
    if self.software_list:
      software = self.software_list[0]
    else:
      software = None

    self.instance_list = [
394 395 396
        InstanceForTest(self.instance_root, name=str(i), software=software)
        for i in range(self.instance_amount)
    ]
397

Marco Mariani's avatar
Marco Mariani committed
398
  def getComputer(self, computer_id):
399 400 401
    """
    Will return current requested state of computer
    """
402
    slap_computer = slapos.slap.Computer(computer_id)
Marco Mariani's avatar
Marco Mariani committed
403
    slap_computer._software_release_list = [
404 405 406
        software.getSoftware(computer_id)
        for software in self.software_list
    ]
Marco Mariani's avatar
Marco Mariani committed
407
    slap_computer._computer_partition_list = [
408 409 410
        instance.getInstance(computer_id)
        for instance in self.instance_list
    ]
411 412 413 414
    return slap_computer



415
class InstanceForTest(object):
416 417 418
  """
  Class containing all needed paramaters and function to simulate instances
  """
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
419
  def __init__(self, instance_root, name, software):
420
    self.instance_root = instance_root
421
    self.software = software
422
    self.requested_state = 'stopped'
423
    self.state = None
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
424
    self.error = False
425
    self.error_log = None
426
    self.sequence = []
427
    self.header_list = []
428 429
    self.name = name
    self.partition_path = os.path.join(self.instance_root, self.name)
Marco Mariani's avatar
Marco Mariani committed
430
    os.mkdir(self.partition_path, 0o750)
431
    self.timestamp = None
432 433 434
    self.ip_list = [('interface0', '10.0.8.2')]
    self.full_ip_list = [('route_interface0', '10.10.2.3', '10.10.0.1',
                          '255.0.0.0', '10.0.0.0')]
435

436
  def getInstance(self, computer_id, ):
437 438 439
    """
    Will return current requested state of instance
    """
440
    partition = slapos.slap.ComputerPartition(computer_id, self.name)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
441
    partition._software_release_document = self.getSoftwareRelease()
442
    partition._requested_state = self.requested_state
443 444
    if getattr(self, 'filter_dict', None):
      partition._filter_dict = self.filter_dict
445 446 447
    partition._parameter_dict = {'ip_list': self.ip_list,
                                  'full_ip_list': self.full_ip_list
                                  }
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
448
    if self.software is not None:
449
      if self.timestamp is not None:
450 451
        partition._parameter_dict['timestamp'] = self.timestamp
        
452
    self.current_partition = partition
453 454
    return partition

Marco Mariani's avatar
Marco Mariani committed
455
  def getSoftwareRelease(self):
456 457 458
    """
    Return software release for Instance
    """
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
459
    if self.software is not None:
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
460
      sr = slapos.slap.SoftwareRelease()
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
461 462
      sr._software_release = self.software.name
      return sr
463 464
    else:
      return None
465

Marco Mariani's avatar
Marco Mariani committed
466
  def setPromise(self, promise_name, promise_content):
467 468 469 470 471 472
    """
    This function will set promise and return its path
    """
    promise_path = os.path.join(self.partition_path, 'etc', 'promise')
    if not os.path.isdir(promise_path):
      os.makedirs(promise_path)
473
    promise = os.path.join(promise_path, promise_name)
474
    open(promise, 'w').write(promise_content)
Marco Mariani's avatar
Marco Mariani committed
475
    os.chmod(promise, 0o777)
476

477 478 479 480 481
  def setCertificate(self, certificate_repository_path):
    if not os.path.exists(certificate_repository_path):
      os.mkdir(certificate_repository_path)
    self.cert_file = os.path.join(certificate_repository_path,
                                  "%s.crt" % self.name)
Marco Mariani's avatar
Marco Mariani committed
482
    self.certificate = str(random.random())
483 484
    open(self.cert_file, 'w').write(self.certificate)
    self.key_file = os.path.join(certificate_repository_path,
485
                                 '%s.key' % self.name)
Marco Mariani's avatar
Marco Mariani committed
486
    self.key = str(random.random())
487
    open(self.key_file, 'w').write(self.key)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
488

489

490
class SoftwareForTest(object):
491 492 493 494
  """
  Class to prepare and simulate software.
  each instance has a sotfware attributed
  """
495
  def __init__(self, software_root, name=''):
496 497 498
    """
    Will set file and variable for software
    """
499 500 501
    self.software_root = software_root
    self.name = 'http://sr%s/' % name
    self.sequence = []
Marco Mariani's avatar
Marco Mariani committed
502
    self.software_hash = md5digest(self.name)
503
    self.srdir = os.path.join(self.software_root, self.software_hash)
504
    self.requested_state = 'available'
505
    os.mkdir(self.srdir)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
506
    self.setTemplateCfg()
507 508
    self.srbindir = os.path.join(self.srdir, 'bin')
    os.mkdir(self.srbindir)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
509
    self.setBuildout()
510

Marco Mariani's avatar
Marco Mariani committed
511
  def getSoftware(self, computer_id):
512 513 514 515 516 517 518
    """
    Will return current requested state of software
    """
    software = slapos.slap.SoftwareRelease(self.name, computer_id)
    software._requested_state = self.requested_state
    return software

Marco Mariani's avatar
Marco Mariani committed
519
  def setTemplateCfg(self, template="""[buildout]"""):
520 521 522
    """
    Set template.cfg
    """
523 524
    open(os.path.join(self.srdir, 'template.cfg'), 'w').write(template)

Marco Mariani's avatar
Marco Mariani committed
525
  def setBuildout(self, buildout="""#!/bin/sh
526
touch worked"""):
527 528 529
    """
    Set a buildout exec in bin
    """
530
    open(os.path.join(self.srbindir, 'buildout'), 'w').write(buildout)
Marco Mariani's avatar
Marco Mariani committed
531
    os.chmod(os.path.join(self.srbindir, 'buildout'), 0o755)
532

Marco Mariani's avatar
Marco Mariani committed
533
  def setPeriodicity(self, periodicity):
534 535 536
    """
    Set a periodicity file
    """
537 538
    with open(os.path.join(self.srdir, 'periodicity'), 'w') as fout:
      fout.write(str(periodicity))
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
539 540


541
class TestSlapgridCPWithMaster(MasterMixin, unittest.TestCase):
542

543
  def test_nothing_to_do(self):
544 545 546
    computer = ComputerForTest(self.software_root, self.instance_root, 0, 0)
    with httmock.HTTMock(computer.request_handler):
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
547
      self.assertInstanceDirectoryListEqual([])
548 549 550
      self.assertItemsEqual(os.listdir(self.software_root), [])
      st = os.stat(os.path.join(self.instance_root, 'var'))
      self.assertEquals(stat.S_IMODE(st.st_mode), 0o755)
551 552

  def test_one_partition(self):
Marco Mariani's avatar
Marco Mariani committed
553
    computer = ComputerForTest(self.software_root, self.instance_root)
554 555 556
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
557
      self.assertInstanceDirectoryListEqual(['0'])
558 559 560 561 562 563 564
      partition = os.path.join(self.instance_root, '0')
      self.assertItemsEqual(os.listdir(partition), ['.slapgrid', 'buildout.cfg',
                                                    'software_release', 'worked', '.slapos-retention-lock-delay'])
      self.assertItemsEqual(os.listdir(self.software_root), [instance.software.software_hash])
      self.assertEqual(computer.sequence,
                       ['/getFullComputerInformation', '/availableComputerPartition',
                        '/stoppedComputerPartition'])
565 566 567 568 569 570

  def test_one_partition_instance_cfg(self):
    """
    Check that slapgrid processes instance is profile is not named
    "template.cfg" but "instance.cfg".
    """
Marco Mariani's avatar
Marco Mariani committed
571
    computer = ComputerForTest(self.software_root, self.instance_root)
572 573 574
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
575
      self.assertInstanceDirectoryListEqual(['0'])
576 577 578 579 580 581 582
      partition = os.path.join(self.instance_root, '0')
      self.assertItemsEqual(os.listdir(partition), ['.slapgrid', 'buildout.cfg',
                                                    'software_release', 'worked', '.slapos-retention-lock-delay'])
      self.assertItemsEqual(os.listdir(self.software_root), [instance.software.software_hash])
      self.assertEqual(computer.sequence,
                       ['/getFullComputerInformation', '/availableComputerPartition',
                        '/stoppedComputerPartition'])
583

584 585
  def test_one_free_partition(self):
    """
586
    Test if slapgrid cp does not process "free" partition
587
    """
Marco Mariani's avatar
Marco Mariani committed
588 589 590
    computer = ComputerForTest(self.software_root,
                               self.instance_root,
                               software_amount=0)
591 592 593 594
    with httmock.HTTMock(computer.request_handler):
      partition = computer.instance_list[0]
      partition.requested_state = 'destroyed'
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
595
      self.assertInstanceDirectoryListEqual(['0'])
596 597 598
      self.assertItemsEqual(os.listdir(partition.partition_path), [])
      self.assertItemsEqual(os.listdir(self.software_root), [])
      self.assertEqual(partition.sequence, [])
599

600
  def test_one_partition_started(self):
Marco Mariani's avatar
Marco Mariani committed
601
    computer = ComputerForTest(self.software_root, self.instance_root)
602 603 604 605 606
    with httmock.HTTMock(computer.request_handler):
      partition = computer.instance_list[0]
      partition.requested_state = 'started'
      partition.software.setBuildout(WRAPPER_CONTENT)
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
607
      self.assertInstanceDirectoryListEqual(['0'])
608 609 610 611 612 613 614 615 616 617
      self.assertItemsEqual(os.listdir(partition.partition_path),
                            ['.slapgrid', '.0_wrapper.log', 'buildout.cfg',
                             'etc', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      wrapper_log = os.path.join(partition.partition_path, '.0_wrapper.log')
      self.assertLogContent(wrapper_log, 'Working')
      self.assertItemsEqual(os.listdir(self.software_root), [partition.software.software_hash])
      self.assertEqual(computer.sequence,
                       ['/getFullComputerInformation', '/availableComputerPartition',
                        '/startedComputerPartition'])
      self.assertEqual(partition.state, 'started')
618

619
  def test_one_partition_started_stopped(self):
Marco Mariani's avatar
Marco Mariani committed
620
    computer = ComputerForTest(self.software_root, self.instance_root)
621 622
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
623

624 625
      instance.requested_state = 'started'
      instance.software.setBuildout("""#!/bin/sh
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
touch worked &&
mkdir -p etc/run &&
(
cat <<'HEREDOC'
#!%(python)s
import signal
def handler(signum, frame):
  print 'Signal handler called with signal', signum
  raise SystemExit
signal.signal(signal.SIGTERM, handler)

while True:
  print "Working"
HEREDOC
)> etc/run/wrapper &&
chmod 755 etc/run/wrapper
Marco Mariani's avatar
Marco Mariani committed
642
""" % {'python': sys.executable})
643
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
644
      self.assertInstanceDirectoryListEqual(['0'])
645 646 647 648 649 650 651 652 653 654 655 656 657 658
      self.assertItemsEqual(os.listdir(instance.partition_path),
                            ['.slapgrid', '.0_wrapper.log', 'buildout.cfg',
                             'etc', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      wrapper_log = os.path.join(instance.partition_path, '.0_wrapper.log')
      self.assertLogContent(wrapper_log, 'Working')
      self.assertItemsEqual(os.listdir(self.software_root), [instance.software.software_hash])
      self.assertEqual(computer.sequence,
                       ['/getFullComputerInformation', '/availableComputerPartition',
                        '/startedComputerPartition'])
      self.assertEqual(instance.state, 'started')

      computer.sequence = []
      instance.requested_state = 'stopped'
      self.assertEqual(self.launchSlapgrid(), slapgrid.SLAPGRID_SUCCESS)
659
      self.assertInstanceDirectoryListEqual(['0'])
660 661 662 663 664
      self.assertItemsEqual(os.listdir(instance.partition_path),
                            ['.slapgrid', '.0_wrapper.log', 'buildout.cfg',
                             'etc', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      self.assertLogContent(wrapper_log, 'Signal handler called with signal 15')
      self.assertEqual(computer.sequence,
665
                       ['/getHateoasUrl', '/getFullComputerInformation', '/availableComputerPartition',
666 667
                        '/stoppedComputerPartition'])
      self.assertEqual(instance.state, 'stopped')
668

669 670 671 672 673 674
  def test_one_broken_partition_stopped(self):
    """
    Check that, for, an already started instance if stop is requested,
    processes will be stopped even if instance is broken (buildout fails
    to run) but status is still started.
    """
Marco Mariani's avatar
Marco Mariani committed
675
    computer = ComputerForTest(self.software_root, self.instance_root)
676 677
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
678

679 680
      instance.requested_state = 'started'
      instance.software.setBuildout("""#!/bin/sh
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
touch worked &&
mkdir -p etc/run &&
(
cat <<'HEREDOC'
#!%(python)s
import signal
def handler(signum, frame):
  print 'Signal handler called with signal', signum
  raise SystemExit
signal.signal(signal.SIGTERM, handler)

while True:
  print "Working"
HEREDOC
)> etc/run/wrapper &&
chmod 755 etc/run/wrapper
Marco Mariani's avatar
Marco Mariani committed
697
""" % {'python': sys.executable})
698
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
699
      self.assertInstanceDirectoryListEqual(['0'])
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
      self.assertItemsEqual(os.listdir(instance.partition_path),
                            ['.slapgrid', '.0_wrapper.log', 'buildout.cfg',
                             'etc', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      wrapper_log = os.path.join(instance.partition_path, '.0_wrapper.log')
      self.assertLogContent(wrapper_log, 'Working')
      self.assertItemsEqual(os.listdir(self.software_root),
                            [instance.software.software_hash])
      self.assertEqual(computer.sequence,
                       ['/getFullComputerInformation', '/availableComputerPartition',
                        '/startedComputerPartition'])
      self.assertEqual(instance.state, 'started')

      computer.sequence = []
      instance.requested_state = 'stopped'
      instance.software.setBuildout("""#!/bin/sh
715 716
exit 1
""")
717
      self.assertEqual(self.launchSlapgrid(), slapgrid.SLAPGRID_FAIL)
718
      self.assertInstanceDirectoryListEqual(['0'])
719 720 721 722 723
      self.assertItemsEqual(os.listdir(instance.partition_path),
                            ['.slapgrid', '.0_wrapper.log', 'buildout.cfg',
                             'etc', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      self.assertLogContent(wrapper_log, 'Signal handler called with signal 15')
      self.assertEqual(computer.sequence,
724
                       ['/getHateoasUrl', '/getFullComputerInformation',
725 726
                        '/softwareInstanceError'])
      self.assertEqual(instance.state, 'started')
727

728
  def test_one_partition_stopped_started(self):
Marco Mariani's avatar
Marco Mariani committed
729
    computer = ComputerForTest(self.software_root, self.instance_root)
730 731 732 733 734 735
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.requested_state = 'stopped'
      instance.software.setBuildout(WRAPPER_CONTENT)
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)

736
      self.assertInstanceDirectoryListEqual(['0'])
737 738 739 740 741 742 743 744 745 746 747 748 749
      partition = os.path.join(self.instance_root, '0')
      self.assertItemsEqual(os.listdir(partition),
                            ['.slapgrid', 'buildout.cfg', 'etc', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      self.assertItemsEqual(os.listdir(self.software_root),
                            [instance.software.software_hash])
      self.assertEqual(computer.sequence,
                       ['/getFullComputerInformation', '/availableComputerPartition',
                        '/stoppedComputerPartition'])
      self.assertEqual('stopped', instance.state)

      instance.requested_state = 'started'
      computer.sequence = []
      self.assertEqual(self.launchSlapgrid(), slapgrid.SLAPGRID_SUCCESS)
750
      self.assertInstanceDirectoryListEqual(['0'])
751 752 753 754 755 756 757 758 759
      partition = os.path.join(self.instance_root, '0')
      self.assertItemsEqual(os.listdir(partition),
                            ['.slapgrid', '.0_wrapper.log', 'etc',
                             'buildout.cfg', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      self.assertItemsEqual(os.listdir(self.software_root),
                            [instance.software.software_hash])
      wrapper_log = os.path.join(instance.partition_path, '.0_wrapper.log')
      self.assertLogContent(wrapper_log, 'Working')
      self.assertEqual(computer.sequence,
760
                       ['/getHateoasUrl', '/getFullComputerInformation', '/availableComputerPartition',
761 762
                        '/startedComputerPartition'])
      self.assertEqual('started', instance.state)
763

764 765 766 767 768 769
  def test_one_partition_destroyed(self):
    """
    Test that an existing partition with "destroyed" status will only be
    stopped by slapgrid-cp, not processed
    """
    computer = ComputerForTest(self.software_root, self.instance_root)
770 771 772
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.requested_state = 'destroyed'
Marco Mariani's avatar
Marco Mariani committed
773

774 775 776
      dummy_file_name = 'dummy_file'
      with open(os.path.join(instance.partition_path, dummy_file_name), 'w') as dummy_file:
          dummy_file.write('dummy')
777

778
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
779

780
      self.assertInstanceDirectoryListEqual(['0'])
781 782 783 784 785 786 787
      partition = os.path.join(self.instance_root, '0')
      self.assertItemsEqual(os.listdir(partition), ['.slapgrid', dummy_file_name])
      self.assertItemsEqual(os.listdir(self.software_root), [instance.software.software_hash])
      self.assertEqual(computer.sequence,
                       ['/getFullComputerInformation',
                        '/stoppedComputerPartition'])
      self.assertEqual('stopped', instance.state)
788

789

790
class TestSlapgridCPWithMasterWatchdog(MasterMixin, unittest.TestCase):
791

792 793 794 795 796
  def setUp(self):
    MasterMixin.setUp(self)
    # Prepare watchdog
    self.watchdog_banged = os.path.join(self._tempdir, 'watchdog_banged')
    watchdog_path = os.path.join(self._tempdir, 'watchdog')
797 798 799 800 801
    open(watchdog_path, 'w').write(WATCHDOG_TEMPLATE.format(
        python_path=sys.executable,
        sys_path=sys.path,
        watchdog_banged=self.watchdog_banged
    ))
Marco Mariani's avatar
Marco Mariani committed
802
    os.chmod(watchdog_path, 0o755)
803 804 805
    self.grid.watchdog_path = watchdog_path
    slapos.grid.slapgrid.WATCHDOG_PATH = watchdog_path

806 807 808 809 810 811 812 813 814 815 816 817
  def test_one_failing_daemon_in_service_will_bang_with_watchdog(self):
    """
    Check that a failing service watched by watchdog trigger bang
    1.Prepare computer and set a service named daemon in etc/service
       (to be watched by watchdog). This daemon will fail.
    2.Prepare file for supervisord to call watchdog
       -Set sys.path
       -Monkeypatch computer partition bang
    3.Check damemon is launched
    4.Wait for it to fail
    5.Wait for file generated by monkeypacthed bang to appear
    """
Cédric de Saint Martin's avatar
PEP8  
Cédric de Saint Martin committed
818
    computer = ComputerForTest(self.software_root, self.instance_root)
819 820 821 822 823 824
    with httmock.HTTMock(computer.request_handler):
      partition = computer.instance_list[0]
      partition.requested_state = 'started'
      partition.software.setBuildout(DAEMON_CONTENT)

      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
825
      self.assertInstanceDirectoryListEqual(['0'])
826 827 828 829 830 831 832
      self.assertItemsEqual(os.listdir(partition.partition_path),
                            ['.slapgrid', '.0_daemon.log', 'buildout.cfg',
                             'etc', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      daemon_log = os.path.join(partition.partition_path, '.0_daemon.log')
      self.assertLogContent(daemon_log, 'Failing')
      self.assertIsCreated(self.watchdog_banged)
      self.assertIn('daemon', open(self.watchdog_banged).read())
833 834 835

  def test_one_failing_daemon_in_run_will_not_bang_with_watchdog(self):
    """
836
    Check that a failing service watched by watchdog does not trigger bang
837 838 839 840 841 842 843 844 845
    1.Prepare computer and set a service named daemon in etc/run
       (not watched by watchdog). This daemon will fail.
    2.Prepare file for supervisord to call watchdog
       -Set sys.path
       -Monkeypatch computer partition bang
    3.Check damemon is launched
    4.Wait for it to fail
    5.Check that file generated by monkeypacthed bang do not appear
    """
Marco Mariani's avatar
Marco Mariani committed
846
    computer = ComputerForTest(self.software_root, self.instance_root)
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
    with httmock.HTTMock(computer.request_handler):
      partition = computer.instance_list[0]
      partition.requested_state = 'started'

      # Content of run wrapper
      WRAPPER_CONTENT = textwrap.dedent("""#!/bin/sh
          touch ./launched
          touch ./crashed
          echo Failing
          sleep 1
          exit 111
      """)

      BUILDOUT_RUN_CONTENT = textwrap.dedent("""#!/bin/sh
          mkdir -p etc/run &&
          echo "%s" >> etc/run/daemon &&
          chmod 755 etc/run/daemon &&
          touch worked
          """ % WRAPPER_CONTENT)

      partition.software.setBuildout(BUILDOUT_RUN_CONTENT)

      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
870
      self.assertInstanceDirectoryListEqual(['0'])
871 872 873 874 875 876
      self.assertItemsEqual(os.listdir(partition.partition_path),
                            ['.slapgrid', '.0_daemon.log', 'buildout.cfg',
                             'etc', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      daemon_log = os.path.join(partition.partition_path, '.0_daemon.log')
      self.assertLogContent(daemon_log, 'Failing')
      self.assertIsNotCreated(self.watchdog_banged)
877 878 879 880 881

  def test_watched_by_watchdog_bang(self):
    """
    Test that a process going to fatal or exited mode in supervisord
    is banged if watched by watchdog
882
    Certificates used for the bang are also checked
883 884
    (ie: watchdog id in process name)
    """
Marco Mariani's avatar
Marco Mariani committed
885
    computer = ComputerForTest(self.software_root, self.instance_root)
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      certificate_repository_path = os.path.join(self._tempdir, 'partition_pki')
      instance.setCertificate(certificate_repository_path)

      watchdog = Watchdog(
          master_url='https://127.0.0.1/',
          computer_id=self.computer_id,
          certificate_repository_path=certificate_repository_path
      )
      for event in watchdog.process_state_events:
        instance.sequence = []
        instance.header_list = []
        headers = {'eventname': event}
        payload = 'processname:%s groupname:%s from_state:RUNNING' % (
            'daemon' + WATCHDOG_MARK, instance.name)
        watchdog.handle_event(headers, payload)
        self.assertEqual(instance.sequence, ['/softwareInstanceBang'])
904 905 906 907 908 909

  def test_unwanted_events_will_not_bang(self):
    """
    Test that a process going to a mode not watched by watchdog
    in supervisord is not banged if watched by watchdog
    """
Marco Mariani's avatar
Marco Mariani committed
910
    computer = ComputerForTest(self.software_root, self.instance_root)
911 912
    instance = computer.instance_list[0]

913 914 915 916 917
    watchdog = Watchdog(
        master_url=self.master_url,
        computer_id=self.computer_id,
        certificate_repository_path=None
    )
918 919 920
    for event in ['EVENT', 'PROCESS_STATE', 'PROCESS_STATE_RUNNING',
                  'PROCESS_STATE_BACKOFF', 'PROCESS_STATE_STOPPED']:
      computer.sequence = []
Marco Mariani's avatar
Marco Mariani committed
921
      headers = {'eventname': event}
922
      payload = 'processname:%s groupname:%s from_state:RUNNING' % (
923
          'daemon' + WATCHDOG_MARK, instance.name)
Marco Mariani's avatar
Marco Mariani committed
924 925
      watchdog.handle_event(headers, payload)
      self.assertEqual(instance.sequence, [])
926 927 928 929 930 931 932

  def test_not_watched_by_watchdog_do_not_bang(self):
    """
    Test that a process going to fatal or exited mode in supervisord
    is not banged if not watched by watchdog
    (ie: no watchdog id in process name)
    """
Marco Mariani's avatar
Marco Mariani committed
933
    computer = ComputerForTest(self.software_root, self.instance_root)
934 935
    instance = computer.instance_list[0]

936 937 938 939 940
    watchdog = Watchdog(
        master_url=self.master_url,
        computer_id=self.computer_id,
        certificate_repository_path=None
    )
941 942
    for event in watchdog.process_state_events:
      computer.sequence = []
Marco Mariani's avatar
Marco Mariani committed
943
      headers = {'eventname': event}
944
      payload = "processname:%s groupname:%s from_state:RUNNING"\
Marco Mariani's avatar
Marco Mariani committed
945 946 947
          % ('daemon', instance.name)
      watchdog.handle_event(headers, payload)
      self.assertEqual(computer.sequence, [])
948

949 950 951 952 953 954 955
  def test_watchdog_create_bang_file_after_bang(self):
    """
    For a partition that has been successfully deployed (thus .timestamp file
    existing), check that bang file is created and contains the timestamp of
    .timestamp file.
    """
    computer = ComputerForTest(self.software_root, self.instance_root)
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      certificate_repository_path = os.path.join(self._tempdir, 'partition_pki')
      instance.setCertificate(certificate_repository_path)
      partition = os.path.join(self.instance_root, '0')
      timestamp_content = '1234'
      timestamp_file = open(os.path.join(partition, slapos.grid.slapgrid.COMPUTER_PARTITION_TIMESTAMP_FILENAME), 'w')
      timestamp_file.write(timestamp_content)
      timestamp_file.close()

      watchdog = Watchdog(
          master_url='https://127.0.0.1/',
          computer_id=self.computer_id,
          certificate_repository_path=certificate_repository_path,
          instance_root_path=self.instance_root
      )
      event = watchdog.process_state_events[0]
      instance.sequence = []
      instance.header_list = []
      headers = {'eventname': event}
      payload = 'processname:%s groupname:%s from_state:RUNNING' % (
          'daemon' + WATCHDOG_MARK, instance.name)
      watchdog.handle_event(headers, payload)
      self.assertEqual(instance.sequence, ['/softwareInstanceBang'])
980

981
      self.assertEqual(open(os.path.join(partition, slapos.grid.slapgrid.COMPUTER_PARTITION_LATEST_BANG_TIMESTAMP_FILENAME)).read(), timestamp_content)
982 983 984 985 986 987 988 989 990 991


  def test_watchdog_ignore_bang_if_partition_not_deployed(self):
    """
    For a partition that has never been successfully deployed (buildout is
    failing, promise is not passing, etc), test that bang is ignored.

    Practically speaking, .timestamp file in the partition does not exsit.
    """
    computer = ComputerForTest(self.software_root, self.instance_root)
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      certificate_repository_path = os.path.join(self._tempdir, 'partition_pki')
      instance.setCertificate(certificate_repository_path)
      partition = os.path.join(self.instance_root, '0')
      timestamp_content = '1234'

      watchdog = Watchdog(
          master_url='https://127.0.0.1/',
          computer_id=self.computer_id,
          certificate_repository_path=certificate_repository_path,
          instance_root_path=self.instance_root
      )
      event = watchdog.process_state_events[0]
      instance.sequence = []
      instance.header_list = []
      headers = {'eventname': event}
      payload = 'processname:%s groupname:%s from_state:RUNNING' % (
          'daemon' + WATCHDOG_MARK, instance.name)
      watchdog.handle_event(headers, payload)
      self.assertEqual(instance.sequence, ['/softwareInstanceBang'])
1013

1014
      self.assertNotEqual(open(os.path.join(partition, slapos.grid.slapgrid.COMPUTER_PARTITION_LATEST_BANG_TIMESTAMP_FILENAME)).read(), timestamp_content)
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024


  def test_watchdog_bang_only_once_if_partition_never_deployed(self):
    """
    For a partition that has been never successfully deployed (promises are not passing,
    etc), test that:
     * First bang is transmitted
     * subsequent bangs are ignored until a deployment is successful.
    """
    computer = ComputerForTest(self.software_root, self.instance_root)
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      certificate_repository_path = os.path.join(self._tempdir, 'partition_pki')
      instance.setCertificate(certificate_repository_path)
      partition = os.path.join(self.instance_root, '0')

      watchdog = Watchdog(
          master_url='https://127.0.0.1/',
          computer_id=self.computer_id,
          certificate_repository_path=certificate_repository_path,
          instance_root_path=self.instance_root
      )
      # First bang
      event = watchdog.process_state_events[0]
      instance.sequence = []
      instance.header_list = []
      headers = {'eventname': event}
      payload = 'processname:%s groupname:%s from_state:RUNNING' % (
          'daemon' + WATCHDOG_MARK, instance.name)
      watchdog.handle_event(headers, payload)
      self.assertEqual(instance.sequence, ['/softwareInstanceBang'])
1046

1047 1048 1049 1050 1051 1052 1053 1054 1055
      # Second bang
      event = watchdog.process_state_events[0]
      instance.sequence = []
      instance.header_list = []
      headers = {'eventname': event}
      payload = 'processname:%s groupname:%s from_state:RUNNING' % (
          'daemon' + WATCHDOG_MARK, instance.name)
      watchdog.handle_event(headers, payload)
      self.assertEqual(instance.sequence, [])
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074


  def test_watchdog_bang_only_once_if_timestamp_did_not_change(self):
    """
    For a partition that has been successfully deployed (promises are passing,
    etc), test that:
     * First bang is transmitted
     * subsequent bangs are ignored until a new deployment is successful.
    Scenario:
     * slapgrid successfully deploys a partition
     * A process crashes, watchdog calls bang
     * Another deployment (run of slapgrid) is done, but not successful (
       promise is failing)
     * The process crashes again, but watchdog ignores it
     * Yet another deployment is done, and it is successful
     * The process crashes again, watchdog calls bang
     * The process crashes again, watchdog ignroes it
    """
    computer = ComputerForTest(self.software_root, self.instance_root)
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      certificate_repository_path = os.path.join(self._tempdir, 'partition_pki')
      instance.setCertificate(certificate_repository_path)
      partition = os.path.join(self.instance_root, '0')
      timestamp_content = '1234'
      timestamp_file = open(os.path.join(partition, slapos.grid.slapgrid.COMPUTER_PARTITION_TIMESTAMP_FILENAME), 'w')
      timestamp_file.write(timestamp_content)
      timestamp_file.close()

      watchdog = Watchdog(
          master_url='https://127.0.0.1/',
          computer_id=self.computer_id,
          certificate_repository_path=certificate_repository_path,
          instance_root_path=self.instance_root
      )
      # First bang
      event = watchdog.process_state_events[0]
      instance.sequence = []
      instance.header_list = []
      headers = {'eventname': event}
      payload = 'processname:%s groupname:%s from_state:RUNNING' % (
          'daemon' + WATCHDOG_MARK, instance.name)
      watchdog.handle_event(headers, payload)
      self.assertEqual(instance.sequence, ['/softwareInstanceBang'])
1100

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
      self.assertEqual(open(os.path.join(partition, slapos.grid.slapgrid.COMPUTER_PARTITION_LATEST_BANG_TIMESTAMP_FILENAME)).read(), timestamp_content)

      # Second bang
      event = watchdog.process_state_events[0]
      instance.sequence = []
      instance.header_list = []
      headers = {'eventname': event}
      payload = 'processname:%s groupname:%s from_state:RUNNING' % (
          'daemon' + WATCHDOG_MARK, instance.name)
      watchdog.handle_event(headers, payload)
      self.assertEqual(instance.sequence, [])

      # Second successful deployment
      timestamp_content = '12345'
      timestamp_file = open(os.path.join(partition, slapos.grid.slapgrid.COMPUTER_PARTITION_TIMESTAMP_FILENAME), 'w')
      timestamp_file.write(timestamp_content)
      timestamp_file.close()

      # Third bang
      event = watchdog.process_state_events[0]
      instance.sequence = []
      instance.header_list = []
      headers = {'eventname': event}
      payload = 'processname:%s groupname:%s from_state:RUNNING' % (
          'daemon' + WATCHDOG_MARK, instance.name)
      watchdog.handle_event(headers, payload)
      self.assertEqual(instance.sequence, ['/softwareInstanceBang'])

      self.assertEqual(open(os.path.join(partition, slapos.grid.slapgrid.COMPUTER_PARTITION_LATEST_BANG_TIMESTAMP_FILENAME)).read(), timestamp_content)

      # Fourth bang
      event = watchdog.process_state_events[0]
      instance.sequence = []
      instance.header_list = []
      headers = {'eventname': event}
      payload = 'processname:%s groupname:%s from_state:RUNNING' % (
          'daemon' + WATCHDOG_MARK, instance.name)
      watchdog.handle_event(headers, payload)
      self.assertEqual(instance.sequence, [])
1140

1141
class TestSlapgridCPPartitionProcessing(MasterMixin, unittest.TestCase):
1142

1143
  def test_partition_timestamp(self):
Marco Mariani's avatar
Marco Mariani committed
1144
    computer = ComputerForTest(self.software_root, self.instance_root)
1145 1146 1147 1148 1149 1150
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      timestamp = str(int(time.time()))
      instance.timestamp = timestamp

      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
1151
      self.assertInstanceDirectoryListEqual(['0'])
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
      partition = os.path.join(self.instance_root, '0')
      self.assertItemsEqual(os.listdir(partition),
                            ['.slapgrid', '.timestamp', 'buildout.cfg', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      self.assertItemsEqual(os.listdir(self.software_root), [instance.software.software_hash])
      timestamp_path = os.path.join(instance.partition_path, '.timestamp')
      self.setSlapgrid()
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
      self.assertIn(timestamp, open(timestamp_path).read())
      self.assertEqual(instance.sequence,
                       ['/availableComputerPartition', '/stoppedComputerPartition'])
1162

1163
  def test_partition_timestamp_develop(self):
Marco Mariani's avatar
Marco Mariani committed
1164
    computer = ComputerForTest(self.software_root, self.instance_root)
1165 1166 1167 1168
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      timestamp = str(int(time.time()))
      instance.timestamp = timestamp
1169

1170
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
1171
      self.assertInstanceDirectoryListEqual(['0'])
1172 1173 1174 1175 1176
      partition = os.path.join(self.instance_root, '0')
      self.assertItemsEqual(os.listdir(partition),
                            ['.slapgrid', '.timestamp', 'buildout.cfg',
                             'software_release', 'worked', '.slapos-retention-lock-delay'])
      self.assertItemsEqual(os.listdir(self.software_root), [instance.software.software_hash])
1177

1178 1179 1180
      self.assertEqual(self.launchSlapgrid(develop=True),
                       slapgrid.SLAPGRID_SUCCESS)
      self.assertEqual(self.launchSlapgrid(), slapgrid.SLAPGRID_SUCCESS)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
1181

1182 1183 1184
      self.assertEqual(instance.sequence,
                       ['/availableComputerPartition', '/stoppedComputerPartition',
                        '/availableComputerPartition', '/stoppedComputerPartition'])
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
1185 1186

  def test_partition_old_timestamp(self):
Marco Mariani's avatar
Marco Mariani committed
1187
    computer = ComputerForTest(self.software_root, self.instance_root)
1188 1189 1190 1191 1192 1193
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      timestamp = str(int(time.time()))
      instance.timestamp = timestamp

      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
1194
      self.assertInstanceDirectoryListEqual(['0'])
1195 1196 1197 1198 1199 1200 1201 1202
      partition = os.path.join(self.instance_root, '0')
      self.assertItemsEqual(os.listdir(partition),
                            ['.slapgrid', '.timestamp', 'buildout.cfg', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      self.assertItemsEqual(os.listdir(self.software_root), [instance.software.software_hash])
      instance.timestamp = str(int(timestamp) - 1)
      self.assertEqual(self.launchSlapgrid(), slapgrid.SLAPGRID_SUCCESS)
      self.assertEqual(instance.sequence,
                       ['/availableComputerPartition', '/stoppedComputerPartition'])
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
1203 1204

  def test_partition_timestamp_new_timestamp(self):
Marco Mariani's avatar
Marco Mariani committed
1205
    computer = ComputerForTest(self.software_root, self.instance_root)
1206 1207 1208 1209 1210 1211
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      timestamp = str(int(time.time()))
      instance.timestamp = timestamp

      self.assertEqual(self.launchSlapgrid(), slapgrid.SLAPGRID_SUCCESS)
1212
      self.assertInstanceDirectoryListEqual(['0'])
1213 1214 1215 1216 1217 1218 1219 1220
      partition = os.path.join(self.instance_root, '0')
      self.assertItemsEqual(os.listdir(partition),
                            ['.slapgrid', '.timestamp', 'buildout.cfg', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      self.assertItemsEqual(os.listdir(self.software_root), [instance.software.software_hash])
      instance.timestamp = str(int(timestamp) + 1)
      self.assertEqual(self.launchSlapgrid(), slapgrid.SLAPGRID_SUCCESS)
      self.assertEqual(self.launchSlapgrid(), slapgrid.SLAPGRID_SUCCESS)
      self.assertEqual(computer.sequence,
1221 1222 1223 1224
                       ['/getHateoasUrl',
                        '/getFullComputerInformation', '/availableComputerPartition',
                        '/stoppedComputerPartition',
                        '/getHateoasUrl', '/getFullComputerInformation',
1225
                        '/availableComputerPartition', '/stoppedComputerPartition',
1226
                        '/getHateoasUrl',
1227
                        '/getFullComputerInformation'])
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
1228 1229

  def test_partition_timestamp_no_timestamp(self):
Marco Mariani's avatar
Marco Mariani committed
1230
    computer = ComputerForTest(self.software_root, self.instance_root)
1231 1232 1233 1234 1235 1236
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      timestamp = str(int(time.time()))
      instance.timestamp = timestamp

      self.launchSlapgrid()
1237
      self.assertInstanceDirectoryListEqual(['0'])
1238 1239 1240 1241 1242 1243 1244 1245
      partition = os.path.join(self.instance_root, '0')
      self.assertItemsEqual(os.listdir(partition),
                            ['.slapgrid', '.timestamp', 'buildout.cfg', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      self.assertItemsEqual(os.listdir(self.software_root),
                            [instance.software.software_hash])
      instance.timestamp = None
      self.launchSlapgrid()
      self.assertEqual(computer.sequence,
1246 1247 1248 1249
                       ['/getHateoasUrl',
                        '/getFullComputerInformation', '/availableComputerPartition',
                        '/stoppedComputerPartition',
                        '/getHateoasUrl', '/getFullComputerInformation',
1250
                        '/availableComputerPartition', '/stoppedComputerPartition'])
1251

1252 1253 1254 1255 1256
  def test_partition_periodicity_remove_timestamp(self):
    """
    Check that if periodicity forces run of buildout for a partition, it
    removes the .timestamp file.
    """
Marco Mariani's avatar
Marco Mariani committed
1257
    computer = ComputerForTest(self.software_root, self.instance_root)
1258 1259 1260
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      timestamp = str(int(time.time()))
1261

1262 1263 1264
      instance.timestamp = timestamp
      instance.requested_state = 'started'
      instance.software.setPeriodicity(1)
1265

1266 1267 1268 1269 1270
      self.launchSlapgrid()
      partition = os.path.join(self.instance_root, '0')
      self.assertItemsEqual(os.listdir(partition),
                            ['.slapgrid', '.timestamp', 'buildout.cfg',
                             'software_release', 'worked', '.slapos-retention-lock-delay'])
1271

1272 1273 1274 1275
      time.sleep(2)
      # dummify install() so that it doesn't actually do anything so that it
      # doesn't recreate .timestamp.
      instance.install = lambda: None
1276

1277 1278 1279 1280
      self.launchSlapgrid()
      self.assertItemsEqual(os.listdir(partition),
                            ['.slapgrid', '.timestamp', 'buildout.cfg',
                             'software_release', 'worked', '.slapos-retention-lock-delay'])
1281 1282 1283 1284 1285 1286

  def test_one_partition_periodicity_from_file_does_not_disturb_others(self):
    """
    If time between last processing of instance and now is superior
    to periodicity then instance should be proceed
    1. We set a wanted maximum_periodicity in periodicity file in
1287
        in one software release directory and not the other one
1288 1289 1290
    2. We process computer partition and check if wanted_periodicity was
        used as maximum_periodicty
    3. We wait for a time superior to wanted_periodicty
1291 1292
    4. We launch processComputerPartition and check that partition using
        software with periodicity was runned and not the other
1293 1294
    5. We check that modification time of .timestamp was modified
    """
Marco Mariani's avatar
Marco Mariani committed
1295
    computer = ComputerForTest(self.software_root, self.instance_root, 20, 20)
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    with httmock.HTTMock(computer.request_handler):
      instance0 = computer.instance_list[0]
      timestamp = str(int(time.time() - 5))
      instance0.timestamp = timestamp
      instance0.requested_state = 'started'
      for instance in computer.instance_list[1:]:
        instance.software = \
            computer.software_list[computer.instance_list.index(instance)]
        instance.timestamp = timestamp

      wanted_periodicity = 1
      instance0.software.setPeriodicity(wanted_periodicity)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
1308

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
      self.launchSlapgrid()
      self.assertNotEqual(wanted_periodicity, self.grid.maximum_periodicity)
      last_runtime = os.path.getmtime(
          os.path.join(instance0.partition_path, '.timestamp'))
      time.sleep(wanted_periodicity + 1)
      for instance in computer.instance_list[1:]:
        self.assertEqual(instance.sequence,
                         ['/availableComputerPartition', '/stoppedComputerPartition'])
      time.sleep(1)
      self.launchSlapgrid()
      self.assertEqual(instance0.sequence,
                       ['/availableComputerPartition', '/startedComputerPartition',
                        '/availableComputerPartition', '/startedComputerPartition',
                        ])
      for instance in computer.instance_list[1:]:
        self.assertEqual(instance.sequence,
                         ['/availableComputerPartition', '/stoppedComputerPartition'])
      self.assertGreater(
          os.path.getmtime(os.path.join(instance0.partition_path, '.timestamp')),
          last_runtime)
      self.assertNotEqual(wanted_periodicity, self.grid.maximum_periodicity)
1330 1331 1332

  def test_one_partition_stopped_is_not_processed_after_periodicity(self):
    """
1333
    Check that periodicity forces processing a partition even if it is not
1334 1335
    started.
    """
Marco Mariani's avatar
Marco Mariani committed
1336
    computer = ComputerForTest(self.software_root, self.instance_root, 20, 20)
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
    with httmock.HTTMock(computer.request_handler):
      instance0 = computer.instance_list[0]
      timestamp = str(int(time.time() - 5))
      instance0.timestamp = timestamp
      for instance in computer.instance_list[1:]:
        instance.software = \
            computer.software_list[computer.instance_list.index(instance)]
        instance.timestamp = timestamp

      wanted_periodicity = 1
      instance0.software.setPeriodicity(wanted_periodicity)
1348

1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
      self.launchSlapgrid()
      self.assertNotEqual(wanted_periodicity, self.grid.maximum_periodicity)
      last_runtime = os.path.getmtime(
          os.path.join(instance0.partition_path, '.timestamp'))
      time.sleep(wanted_periodicity + 1)
      for instance in computer.instance_list[1:]:
        self.assertEqual(instance.sequence,
                         ['/availableComputerPartition', '/stoppedComputerPartition'])
      time.sleep(1)
      self.launchSlapgrid()
      self.assertEqual(instance0.sequence,
                       ['/availableComputerPartition', '/stoppedComputerPartition',
                        '/availableComputerPartition', '/stoppedComputerPartition'])
      for instance in computer.instance_list[1:]:
        self.assertEqual(instance.sequence,
                         ['/availableComputerPartition', '/stoppedComputerPartition'])
      self.assertNotEqual(os.path.getmtime(os.path.join(instance0.partition_path,
                                                        '.timestamp')),
                          last_runtime)
      self.assertNotEqual(wanted_periodicity, self.grid.maximum_periodicity)
1369

1370 1371
  def test_one_partition_destroyed_is_not_processed_after_periodicity(self):
    """
1372
    Check that periodicity forces processing a partition even if it is not
1373 1374
    started.
    """
Marco Mariani's avatar
Marco Mariani committed
1375
    computer = ComputerForTest(self.software_root, self.instance_root, 20, 20)
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
    with httmock.HTTMock(computer.request_handler):
      instance0 = computer.instance_list[0]
      timestamp = str(int(time.time() - 5))
      instance0.timestamp = timestamp
      instance0.requested_state = 'stopped'
      for instance in computer.instance_list[1:]:
        instance.software = \
            computer.software_list[computer.instance_list.index(instance)]
        instance.timestamp = timestamp

      wanted_periodicity = 1
      instance0.software.setPeriodicity(wanted_periodicity)
1388

1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
      self.launchSlapgrid()
      self.assertNotEqual(wanted_periodicity, self.grid.maximum_periodicity)
      last_runtime = os.path.getmtime(
          os.path.join(instance0.partition_path, '.timestamp'))
      time.sleep(wanted_periodicity + 1)
      for instance in computer.instance_list[1:]:
        self.assertEqual(instance.sequence,
                         ['/availableComputerPartition', '/stoppedComputerPartition'])
      time.sleep(1)
      instance0.requested_state = 'destroyed'
      self.launchSlapgrid()
      self.assertEqual(instance0.sequence,
                       ['/availableComputerPartition', '/stoppedComputerPartition',
                                                       '/stoppedComputerPartition'])
      for instance in computer.instance_list[1:]:
        self.assertEqual(instance.sequence,
                         ['/availableComputerPartition', '/stoppedComputerPartition'])
      self.assertNotEqual(os.path.getmtime(os.path.join(instance0.partition_path,
                                                        '.timestamp')),
                          last_runtime)
      self.assertNotEqual(wanted_periodicity, self.grid.maximum_periodicity)
1410

1411 1412 1413 1414
  def test_one_partition_is_never_processed_when_periodicity_is_negative(self):
    """
    Checks that a partition is not processed when
    its periodicity is negative
1415 1416 1417 1418 1419
    1. We setup one instance and set periodicity at -1
    2. We mock the install method from slapos.grid.slapgrid.Partition
    3. We launch slapgrid once so that .timestamp file is created and check that install method is
    indeed called (through mocked_method.called
    4. We launch slapgrid anew and check that install as not been called again
1420 1421 1422
    """

    computer = ComputerForTest(self.software_root, self.instance_root, 1, 1)
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
    with httmock.HTTMock(computer.request_handler):
      timestamp = str(int(time.time()))
      instance = computer.instance_list[0]
      instance.software.setPeriodicity(-1)
      instance.timestamp = timestamp
      with patch.object(slapos.grid.slapgrid.Partition, 'install', return_value=None) as mock_method:
        self.launchSlapgrid()
        self.assertTrue(mock_method.called)
        self.launchSlapgrid()
        self.assertEqual(mock_method.call_count, 1)
1433 1434 1435 1436 1437

  def test_one_partition_is_always_processed_when_periodicity_is_zero(self):
    """
    Checks that a partition is always processed when
    its periodicity is 0
1438 1439 1440 1441 1442
    1. We setup one instance and set periodicity at 0
    2. We mock the install method from slapos.grid.slapgrid.Partition
    3. We launch slapgrid once so that .timestamp file is created
    4. We launch slapgrid anew and check that install has been called twice (one time because of the
    new setup and one time because of periodicity = 0)
1443 1444 1445
    """

    computer = ComputerForTest(self.software_root, self.instance_root, 1, 1)
1446 1447 1448 1449 1450 1451 1452 1453 1454
    with httmock.HTTMock(computer.request_handler):
      timestamp = str(int(time.time()))
      instance = computer.instance_list[0]
      instance.software.setPeriodicity(0)
      instance.timestamp = timestamp
      with patch.object(slapos.grid.slapgrid.Partition, 'install', return_value=None) as mock_method:
        self.launchSlapgrid()
        self.launchSlapgrid()
        self.assertEqual(mock_method.call_count, 2)
1455

1456 1457 1458 1459 1460
  def test_one_partition_buildout_fail_does_not_disturb_others(self):
    """
    1. We set up two instance one using a corrupted buildout
    2. One will fail but the other one will be processed correctly
    """
Marco Mariani's avatar
Marco Mariani committed
1461
    computer = ComputerForTest(self.software_root, self.instance_root, 2, 2)
1462 1463 1464 1465 1466
    with httmock.HTTMock(computer.request_handler):
      instance0 = computer.instance_list[0]
      instance1 = computer.instance_list[1]
      instance1.software = computer.software_list[1]
      instance0.software.setBuildout("""#!/bin/sh
1467
exit 42""")
1468 1469 1470 1471 1472
      self.launchSlapgrid()
      self.assertEqual(instance0.sequence,
                       ['/softwareInstanceError'])
      self.assertEqual(instance1.sequence,
                       ['/availableComputerPartition', '/stoppedComputerPartition'])
1473 1474 1475 1476 1477 1478

  def test_one_partition_lacking_software_path_does_not_disturb_others(self):
    """
    1. We set up two instance but remove software path of one
    2. One will fail but the other one will be processed correctly
    """
Marco Mariani's avatar
Marco Mariani committed
1479
    computer = ComputerForTest(self.software_root, self.instance_root, 2, 2)
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
    with httmock.HTTMock(computer.request_handler):
      instance0 = computer.instance_list[0]
      instance1 = computer.instance_list[1]
      instance1.software = computer.software_list[1]
      shutil.rmtree(instance0.software.srdir)
      self.launchSlapgrid()
      self.assertEqual(instance0.sequence,
                       ['/softwareInstanceError'])
      self.assertEqual(instance1.sequence,
                       ['/availableComputerPartition', '/stoppedComputerPartition'])
1490 1491 1492 1493 1494 1495

  def test_one_partition_lacking_software_bin_path_does_not_disturb_others(self):
    """
    1. We set up two instance but remove software bin path of one
    2. One will fail but the other one will be processed correctly
    """
Marco Mariani's avatar
Marco Mariani committed
1496
    computer = ComputerForTest(self.software_root, self.instance_root, 2, 2)
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
    with httmock.HTTMock(computer.request_handler):
      instance0 = computer.instance_list[0]
      instance1 = computer.instance_list[1]
      instance1.software = computer.software_list[1]
      shutil.rmtree(instance0.software.srbindir)
      self.launchSlapgrid()
      self.assertEqual(instance0.sequence,
                       ['/softwareInstanceError'])
      self.assertEqual(instance1.sequence,
                       ['/availableComputerPartition', '/stoppedComputerPartition'])
1507 1508 1509

  def test_one_partition_lacking_path_does_not_disturb_others(self):
    """
1510
    1. We set up two instances but remove path of one
1511 1512
    2. One will fail but the other one will be processed correctly
    """
Marco Mariani's avatar
Marco Mariani committed
1513
    computer = ComputerForTest(self.software_root, self.instance_root, 2, 2)
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
    with httmock.HTTMock(computer.request_handler):
      instance0 = computer.instance_list[0]
      instance1 = computer.instance_list[1]
      instance1.software = computer.software_list[1]
      shutil.rmtree(instance0.partition_path)
      self.launchSlapgrid()
      self.assertEqual(instance0.sequence,
                       ['/softwareInstanceError'])
      self.assertEqual(instance1.sequence,
                       ['/availableComputerPartition', '/stoppedComputerPartition'])
1524

1525 1526 1527 1528 1529 1530
  def test_one_partition_buildout_fail_is_correctly_logged(self):
    """
    1. We set up an instance using a corrupted buildout
    2. It will fail, make sure that whole log is sent to master
    """
    computer = ComputerForTest(self.software_root, self.instance_root, 1, 1)
1531 1532
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
1533

1534 1535 1536
      line1 = "Nerdy kitten: Can I haz a process crash?"
      line2 = "Cedric: Sure, here it is."
      instance.software.setBuildout("""#!/bin/sh
1537
echo %s; echo %s; exit 42""" % (line1, line2))
1538 1539 1540 1541 1542 1543
      self.launchSlapgrid()
      self.assertEqual(instance.sequence, ['/softwareInstanceError'])
      # We don't care of actual formatting, we just want to have full log
      self.assertIn(line1, instance.error_log)
      self.assertIn(line2, instance.error_log)
      self.assertIn('Failed to run buildout', instance.error_log)
1544

1545

1546
class TestSlapgridUsageReport(MasterMixin, unittest.TestCase):
1547 1548 1549 1550 1551 1552 1553 1554
  """
  Test suite about slapgrid-ur
  """

  def test_slapgrid_destroys_instance_to_be_destroyed(self):
    """
    Test than an instance in "destroyed" state is correctly destroyed
    """
Marco Mariani's avatar
Marco Mariani committed
1555
    computer = ComputerForTest(self.software_root, self.instance_root)
1556 1557 1558 1559 1560
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.requested_state = 'started'
      instance.software.setBuildout(WRAPPER_CONTENT)
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
1561
      self.assertInstanceDirectoryListEqual(['0'])
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
      self.assertItemsEqual(os.listdir(instance.partition_path),
                            ['.slapgrid', '.0_wrapper.log', 'buildout.cfg',
                             'etc', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      wrapper_log = os.path.join(instance.partition_path, '.0_wrapper.log')
      self.assertLogContent(wrapper_log, 'Working')
      self.assertItemsEqual(os.listdir(self.software_root), [instance.software.software_hash])
      self.assertEqual(computer.sequence,
                       ['/getFullComputerInformation',
                        '/availableComputerPartition',
                        '/startedComputerPartition'])
      self.assertEqual(instance.state, 'started')

      # Then destroy the instance
      computer.sequence = []
      instance.requested_state = 'destroyed'
      self.assertEqual(self.grid.agregateAndSendUsage(), slapgrid.SLAPGRID_SUCCESS)
      # Assert partition directory is empty
1579
      self.assertInstanceDirectoryListEqual(['0'])
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
      self.assertItemsEqual(os.listdir(instance.partition_path), [])
      self.assertItemsEqual(os.listdir(self.software_root),
                            [instance.software.software_hash])
      # Assert supervisor stopped process
      wrapper_log = os.path.join(instance.partition_path, '.0_wrapper.log')
      self.assertIsNotCreated(wrapper_log)

      self.assertEqual(computer.sequence,
                       ['/getFullComputerInformation',
                        '/stoppedComputerPartition',
                        '/destroyedComputerPartition'])
      self.assertEqual(instance.state, 'destroyed')
1592

1593
  def test_partition_list_is_complete_if_empty_destroyed_partition(self):
1594
    """
1595 1596 1597 1598 1599 1600
    Test that an empty partition with destroyed state but with SR informations
    Is correctly destroyed
    Axiom: each valid partition has a state and a software_release.
    Scenario:
    1. Simulate computer containing one "destroyed" partition but with valid SR
    2. See if it destroyed
1601
    """
1602
    computer = ComputerForTest(self.software_root, self.instance_root)
1603 1604
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
1605

1606 1607 1608 1609
      computer.sequence = []
      instance.requested_state = 'destroyed'
      self.assertEqual(self.grid.agregateAndSendUsage(), slapgrid.SLAPGRID_SUCCESS)
      # Assert partition directory is empty
1610
      self.assertInstanceDirectoryListEqual(['0'])
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
      self.assertItemsEqual(os.listdir(instance.partition_path), [])
      self.assertItemsEqual(os.listdir(self.software_root),
                            [instance.software.software_hash])
      # Assert supervisor stopped process
      wrapper_log = os.path.join(instance.partition_path, '.0_wrapper.log')
      self.assertIsNotCreated(wrapper_log)

      self.assertEqual(
          computer.sequence,
          ['/getFullComputerInformation', '/stoppedComputerPartition', '/destroyedComputerPartition'])
1621 1622 1623 1624 1625

  def test_slapgrid_not_destroy_bad_instance(self):
    """
    Checks that slapgrid-ur don't destroy instance not to be destroyed.
    """
Marco Mariani's avatar
Marco Mariani committed
1626
    computer = ComputerForTest(self.software_root, self.instance_root)
1627 1628 1629 1630 1631
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.requested_state = 'started'
      instance.software.setBuildout(WRAPPER_CONTENT)
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
1632
      self.assertInstanceDirectoryListEqual(['0'])
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
      self.assertItemsEqual(os.listdir(instance.partition_path),
                            ['.slapgrid', '.0_wrapper.log', 'buildout.cfg',
                             'etc', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      wrapper_log = os.path.join(instance.partition_path, '.0_wrapper.log')
      self.assertLogContent(wrapper_log, 'Working')
      self.assertItemsEqual(os.listdir(self.software_root), [instance.software.software_hash])
      self.assertEqual(computer.sequence,
                       ['/getFullComputerInformation',
                        '/availableComputerPartition',
                        '/startedComputerPartition'])
      self.assertEqual('started', instance.state)

      # Then run usage report and see if it is still working
      computer.sequence = []
      self.assertEqual(self.grid.agregateAndSendUsage(), slapgrid.SLAPGRID_SUCCESS)
1648
      self.assertInstanceDirectoryListEqual(['0'])
1649 1650 1651 1652 1653
      self.assertItemsEqual(os.listdir(instance.partition_path),
                            ['.slapgrid', '.0_wrapper.log', 'buildout.cfg',
                             'etc', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      wrapper_log = os.path.join(instance.partition_path, '.0_wrapper.log')
      self.assertLogContent(wrapper_log, 'Working')
1654
      self.assertInstanceDirectoryListEqual(['0'])
1655 1656 1657 1658 1659 1660 1661 1662
      self.assertItemsEqual(os.listdir(instance.partition_path),
                            ['.slapgrid', '.0_wrapper.log', 'buildout.cfg',
                             'etc', 'software_release', 'worked', '.slapos-retention-lock-delay'])
      wrapper_log = os.path.join(instance.partition_path, '.0_wrapper.log')
      self.assertLogContent(wrapper_log, 'Working')
      self.assertEqual(computer.sequence,
                       ['/getFullComputerInformation'])
      self.assertEqual('started', instance.state)
1663

1664
  def test_slapgrid_instance_ignore_free_instance(self):
1665
    """
1666 1667
    Test than a free instance (so in "destroyed" state, but empty, without
    software_release URI) is ignored by slapgrid-cp.
1668 1669
    """
    computer = ComputerForTest(self.software_root, self.instance_root)
1670 1671 1672
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.software.name = None
1673

1674 1675 1676 1677
      computer.sequence = []
      instance.requested_state = 'destroyed'
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
      # Assert partition directory is empty
1678
      self.assertInstanceDirectoryListEqual(['0'])
1679 1680 1681
      self.assertItemsEqual(os.listdir(instance.partition_path), [])
      self.assertItemsEqual(os.listdir(self.software_root), [instance.software.software_hash])
      self.assertEqual(computer.sequence, ['/getFullComputerInformation'])
1682

1683 1684 1685 1686 1687 1688
  def test_slapgrid_report_ignore_free_instance(self):
    """
    Test than a free instance (so in "destroyed" state, but empty, without
    software_release URI) is ignored by slapgrid-ur.
    """
    computer = ComputerForTest(self.software_root, self.instance_root)
1689 1690 1691
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.software.name = None
1692

1693 1694 1695 1696
      computer.sequence = []
      instance.requested_state = 'destroyed'
      self.assertEqual(self.grid.agregateAndSendUsage(), slapgrid.SLAPGRID_SUCCESS)
      # Assert partition directory is empty
1697
      self.assertInstanceDirectoryListEqual(['0'])
1698 1699 1700
      self.assertItemsEqual(os.listdir(instance.partition_path), [])
      self.assertItemsEqual(os.listdir(self.software_root), [instance.software.software_hash])
      self.assertEqual(computer.sequence, ['/getFullComputerInformation'])
1701 1702


1703
class TestSlapgridSoftwareRelease(MasterMixin, unittest.TestCase):
1704 1705 1706 1707 1708 1709
  def test_one_software_buildout_fail_is_correctly_logged(self):
    """
    1. We set up a software using a corrupted buildout
    2. It will fail, make sure that whole log is sent to master
    """
    computer = ComputerForTest(self.software_root, self.instance_root, 1, 1)
1710 1711
    with httmock.HTTMock(computer.request_handler):
      software = computer.software_list[0]
1712

1713 1714 1715
      line1 = "Nerdy kitten: Can I haz a process crash?"
      line2 = "Cedric: Sure, here it is."
      software.setBuildout("""#!/bin/sh
1716
echo %s; echo %s; exit 42""" % (line1, line2))
1717 1718 1719 1720 1721 1722 1723
      self.launchSlapgridSoftware()
      self.assertEqual(software.sequence,
                       ['/buildingSoftwareRelease', '/softwareReleaseError'])
      # We don't care of actual formatting, we just want to have full log
      self.assertIn(line1, software.error_log)
      self.assertIn(line2, software.error_log)
      self.assertIn('Failed to run buildout', software.error_log)
1724

1725

1726
class SlapgridInitialization(unittest.TestCase):
1727
  """
1728 1729
  "Abstract" class setting setup and teardown for TestSlapgridArgumentTuple
  and TestSlapgridConfigurationFile.
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
  """

  def setUp(self):
    """
      Create the minimun default argument and configuration.
    """
    self.certificate_repository_path = tempfile.mkdtemp()
    self.fake_file_descriptor = tempfile.NamedTemporaryFile()
    self.slapos_config_descriptor = tempfile.NamedTemporaryFile()
    self.slapos_config_descriptor.write("""
[slapos]
software_root = /opt/slapgrid
instance_root = /srv/slapgrid
master_url = https://slap.vifib.com/
computer_id = your computer id
buildout = /path/to/buildout/binary
Marco Mariani's avatar
Marco Mariani committed
1746
""")
1747 1748 1749 1750 1751 1752
    self.slapos_config_descriptor.seek(0)
    self.default_arg_tuple = (
        '--cert_file', self.fake_file_descriptor.name,
        '--key_file', self.fake_file_descriptor.name,
        '--master_ca_file', self.fake_file_descriptor.name,
        '--certificate_repository_path', self.certificate_repository_path,
1753
        '-c', self.slapos_config_descriptor.name, '--now')
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766

    self.signature_key_file_descriptor = tempfile.NamedTemporaryFile()
    self.signature_key_file_descriptor.seek(0)

  def tearDown(self):
    """
      Removing the temp file.
    """
    self.fake_file_descriptor.close()
    self.slapos_config_descriptor.close()
    self.signature_key_file_descriptor.close()
    shutil.rmtree(self.certificate_repository_path, True)

1767

1768
class TestSlapgridCPWithMasterPromise(MasterMixin, unittest.TestCase):
1769
  def test_one_failing_promise(self):
Marco Mariani's avatar
Marco Mariani committed
1770
    computer = ComputerForTest(self.software_root, self.instance_root)
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.requested_state = 'started'
      worked_file = os.path.join(instance.partition_path, 'fail_worked')
      fail = textwrap.dedent("""\
              #!/usr/bin/env sh
              touch "%s"
              exit 127""" % worked_file)
      instance.setPromise('fail', fail)
      self.assertEqual(self.grid.processComputerPartitionList(),
                       slapos.grid.slapgrid.SLAPGRID_PROMISE_FAIL)
      self.assertTrue(os.path.isfile(worked_file))
      self.assertTrue(instance.error)
      self.assertNotEqual('started', instance.state)
1785 1786

  def test_one_succeeding_promise(self):
1787
    computer = ComputerForTest(self.software_root, self.instance_root)
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.requested_state = 'started'
      self.fake_waiting_time = 0.1
      worked_file = os.path.join(instance.partition_path, 'succeed_worked')
      succeed = textwrap.dedent("""\
              #!/usr/bin/env sh
              touch "%s"
              exit 0""" % worked_file)
      instance.setPromise('succeed', succeed)
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
      self.assertTrue(os.path.isfile(worked_file))

      self.assertFalse(instance.error)
      self.assertEqual(instance.state, 'started')
1803 1804

  def test_stderr_has_been_sent(self):
Marco Mariani's avatar
Marco Mariani committed
1805
    computer = ComputerForTest(self.software_root, self.instance_root)
1806 1807
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
1808

1809 1810
      instance.requested_state = 'started'
      self.fake_waiting_time = 0.5
1811

1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
      promise_path = os.path.join(instance.partition_path, 'etc', 'promise')
      os.makedirs(promise_path)
      succeed = os.path.join(promise_path, 'stderr_writer')
      worked_file = os.path.join(instance.partition_path, 'stderr_worked')
      with open(succeed, 'w') as f:
        f.write(textwrap.dedent("""\
              #!/usr/bin/env sh
              touch "%s"
              echo Error 1>&2
              exit 127""" % worked_file))
      os.chmod(succeed, 0o777)
      self.assertEqual(self.grid.processComputerPartitionList(),
                       slapos.grid.slapgrid.SLAPGRID_PROMISE_FAIL)
      self.assertTrue(os.path.isfile(worked_file))
1826

1827 1828 1829 1830 1831
      self.assertEqual(instance.error_log[-5:], 'Error')
      self.assertTrue(instance.error)
      self.assertIsNone(instance.state)

  def test_timeout_works(self):
Marco Mariani's avatar
Marco Mariani committed
1832
    computer = ComputerForTest(self.software_root, self.instance_root)
1833 1834
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
1835

1836 1837
      instance.requested_state = 'started'
      self.fake_waiting_time = 0.1
1838

1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
      promise_path = os.path.join(instance.partition_path, 'etc', 'promise')
      os.makedirs(promise_path)
      succeed = os.path.join(promise_path, 'timed_out_promise')
      worked_file = os.path.join(instance.partition_path, 'timed_out_worked')
      with open(succeed, 'w') as f:
        f.write(textwrap.dedent("""\
              #!/usr/bin/env sh
              touch "%s"
              sleep 5
              exit 0""" % worked_file))
      os.chmod(succeed, 0o777)
      self.assertEqual(self.grid.processComputerPartitionList(),
                       slapos.grid.slapgrid.SLAPGRID_PROMISE_FAIL)
1852
      self.assertTrue(os.path.isfile(worked_file))
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878

      self.assertTrue(instance.error)
      self.assertIsNone(instance.state)

  def test_two_succeeding_promises(self):
    computer = ComputerForTest(self.software_root, self.instance_root)
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.requested_state = 'started'

      self.fake_waiting_time = 0.1

      for i in range(2):
        worked_file = os.path.join(instance.partition_path, 'succeed_%s_worked' % i)
        succeed = textwrap.dedent("""\
              #!/usr/bin/env sh
              touch "%s"
              exit 0""" % worked_file)
        instance.setPromise('succeed_%s' % i, succeed)

      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
      for i in range(2):
        worked_file = os.path.join(instance.partition_path, 'succeed_%s_worked' % i)
        self.assertTrue(os.path.isfile(worked_file))
      self.assertFalse(instance.error)
      self.assertEqual(instance.state, 'started')
1879

1880
  def test_one_succeeding_one_failing_promises(self):
Marco Mariani's avatar
Marco Mariani committed
1881
    computer = ComputerForTest(self.software_root, self.instance_root)
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.requested_state = 'started'
      self.fake_waiting_time = 0.1

      for i in range(2):
        worked_file = os.path.join(instance.partition_path, 'promise_worked_%d' % i)
        lockfile = os.path.join(instance.partition_path, 'lock')
        promise = textwrap.dedent("""\
                  #!/usr/bin/env sh
                  touch "%(worked_file)s"
                  if [ ! -f %(lockfile)s ]
                  then
                    touch "%(lockfile)s"
                    exit 0
                  else
                    exit 127
                  fi""" % {
            'worked_file': worked_file,
            'lockfile': lockfile
        })
        instance.setPromise('promise_%s' % i, promise)
      self.assertEqual(self.grid.processComputerPartitionList(),
                       slapos.grid.slapgrid.SLAPGRID_PROMISE_FAIL)
      self.assertEquals(instance.error, 1)
      self.assertNotEqual('started', instance.state)
1908 1909

  def test_one_succeeding_one_timing_out_promises(self):
Marco Mariani's avatar
Marco Mariani committed
1910
    computer = ComputerForTest(self.software_root, self.instance_root)
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.requested_state = 'started'
      self.fake_waiting_time = 0.1
      for i in range(2):
        worked_file = os.path.join(instance.partition_path, 'promise_worked_%d' % i)
        lockfile = os.path.join(instance.partition_path, 'lock')
        promise = textwrap.dedent("""\
                  #!/usr/bin/env sh
                  touch "%(worked_file)s"
                  if [ ! -f %(lockfile)s ]
                  then
                    touch "%(lockfile)s"
                  else
                    sleep 5
                  fi
                  exit 0""" % {
            'worked_file': worked_file,
            'lockfile': lockfile}
        )
        instance.setPromise('promise_%d' % i, promise)

      self.assertEqual(self.grid.processComputerPartitionList(),
                       slapos.grid.slapgrid.SLAPGRID_PROMISE_FAIL)

      self.assertEquals(instance.error, 1)
      self.assertNotEqual(instance.state, 'started')
1938 1939 1940 1941 1942 1943 1944 1945

class TestSlapgridDestructionLock(MasterMixin, unittest.TestCase):
  def test_retention_lock(self):
    """
    Higher level test about actual retention (or no-retention) of instance
    if specifying a retention lock delay.
    """
    computer = ComputerForTest(self.software_root, self.instance_root)
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.requested_state = 'started'
      instance.filter_dict = {'retention_delay': 1.0 / (3600 * 24)}
      self.grid.processComputerPartitionList()
      dummy_instance_file_path = os.path.join(instance.partition_path, 'dummy')
      with open(dummy_instance_file_path, 'w') as dummy_instance_file:
        dummy_instance_file.write('dummy')

      self.assertTrue(os.path.exists(os.path.join(
          instance.partition_path,
          slapos.grid.SlapObject.Partition.retention_lock_delay_filename
      )))

      instance.requested_state = 'destroyed'
      self.grid.agregateAndSendUsage()
      self.assertTrue(os.path.exists(dummy_instance_file_path))
      self.assertTrue(os.path.exists(os.path.join(
          instance.partition_path,
          slapos.grid.SlapObject.Partition.retention_lock_date_filename
      )))

      self.grid.agregateAndSendUsage()
      self.assertTrue(os.path.exists(dummy_instance_file_path))

      time.sleep(1)
      self.grid.agregateAndSendUsage()
      self.assertFalse(os.path.exists(dummy_instance_file_path))

1975 1976 1977 1978 1979 1980

class TestSlapgridCPWithFirewall(MasterMixin, unittest.TestCase):
  
  def setFirewallConfig(self, source_ip=""):
    firewall_conf= dict(
      authorized_sources=source_ip,
1981
      firewall_cmd='/bin/echo "no" #',
Alain Takoudjou's avatar
Alain Takoudjou committed
1982 1983
      firewall_executable='/bin/echo "service firewall started"',
      reload_config_cmd='/bin/echo "Config reloaded."',
1984 1985 1986 1987 1988
      log_file='fw-log.log',
      testing=True,
    )
    self.grid.firewall_conf = firewall_conf
  
1989 1990 1991
  def checkRuleFromIpSource(self, ip, accept_ip_list, cmd_list):
    # XXX - rules for one ip contain 2*len(ip_address_list + accept_ip_list) rules ACCEPT and 4 rules REJECT
    num_rules = len(self.ip_address_list) * 2 + len(accept_ip_list) * 2 + 4
1992
    self.assertEqual(len(cmd_list), num_rules)
1993
    base_cmd = '--permanent --direct --add-rule ipv4 filter'
1994

1995 1996
    # Check that there is REJECT rule on INPUT
    rule = '%s INPUT 1000 -d %s -j REJECT' % (base_cmd, ip)
1997 1998
    self.assertIn(rule, cmd_list)

1999 2000
    # Check that there is REJECT rule on FORWARD
    rule = '%s FORWARD 1000 -d %s -j REJECT' % (base_cmd, ip)
2001 2002
    self.assertIn(rule, cmd_list)

2003 2004
    # Check that there is REJECT rule on INPUT, ESTABLISHED,RELATED
    rule = '%s INPUT 900 -d %s -m state --state ESTABLISHED,RELATED -j REJECT' % (base_cmd, ip)
2005 2006
    self.assertIn(rule, cmd_list)

2007 2008
    # Check that there is REJECT rule on FORWARD, ESTABLISHED,RELATED
    rule = '%s FORWARD 900 -d %s -m state --state ESTABLISHED,RELATED -j REJECT' % (base_cmd, ip)
2009 2010 2011 2012 2013 2014
    self.assertIn(rule, cmd_list)
    
    # Check that there is INPUT ACCEPT on ip_list
    for _, other_ip in self.ip_address_list:
      rule = '%s INPUT 0 -s %s -d %s -j ACCEPT' % (base_cmd, other_ip, ip)
      self.assertIn(rule, cmd_list)
2015 2016
      rule = '%s FORWARD 0 -s %s -d %s -j ACCEPT' % (base_cmd, other_ip, ip)
      self.assertIn(rule, cmd_list)
2017 2018

    # Check that there is FORWARD ACCEPT on ip_list
2019 2020 2021
    for other_ip in accept_ip_list:
      rule = '%s INPUT 0 -s %s -d %s -j ACCEPT' % (base_cmd, other_ip, ip)
      self.assertIn(rule, cmd_list)
2022 2023
      rule = '%s FORWARD 0 -s %s -d %s -j ACCEPT' % (base_cmd, other_ip, ip)
      self.assertIn(rule, cmd_list)
2024 2025 2026
  
  def checkRuleFromIpSourceReject(self, ip, reject_ip_list, cmd_list):
    # XXX - rules for one ip contain 2 + 2*len(ip_address_list) rules ACCEPT and 4*len(reject_ip_list) rules REJECT
2027
    num_rules = (len(self.ip_address_list) * 2) + (len(reject_ip_list) * 4)
2028
    self.assertEqual(len(cmd_list), num_rules)
2029
    base_cmd = '--permanent --direct --add-rule ipv4 filter'
2030 2031

    # Check that there is ACCEPT rule on INPUT
2032 2033
    #rule = '%s INPUT 0 -d %s -j ACCEPT' % (base_cmd, ip)
    #self.assertIn(rule, cmd_list)
2034 2035

    # Check that there is ACCEPT rule on FORWARD
2036 2037
    #rule = '%s FORWARD 0 -d %s -j ACCEPT' % (base_cmd, ip)
    #self.assertIn(rule, cmd_list)
2038 2039 2040
    
    # Check that there is INPUT/FORWARD ACCEPT on ip_list
    for _, other_ip in self.ip_address_list:
2041
      rule = '%s INPUT 0 -s %s -d %s -j ACCEPT' % (base_cmd, other_ip, ip)
2042
      self.assertIn(rule, cmd_list)
2043
      rule = '%s FORWARD 0 -s %s -d %s -j ACCEPT' % (base_cmd, other_ip, ip)
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
      self.assertIn(rule, cmd_list)

    # Check that there is INPUT/FORWARD REJECT on ip_list
    for other_ip in reject_ip_list:
      rule = '%s INPUT 900 -s %s -d %s -j REJECT' % (base_cmd, other_ip, ip)
      self.assertIn(rule, cmd_list)
      rule = '%s FORWARD 900 -s %s -d %s -j REJECT' % (base_cmd, other_ip, ip)
      self.assertIn(rule, cmd_list)
      rule = '%s INPUT 800 -s %s -d %s -m state --state ESTABLISHED,RELATED -j REJECT' % (base_cmd, other_ip, ip)
      self.assertIn(rule, cmd_list)
      rule = '%s FORWARD 800 -s %s -d %s -m state --state ESTABLISHED,RELATED -j REJECT' % (base_cmd, other_ip, ip)
      self.assertIn(rule, cmd_list)
2056 2057 2058 2059 2060 2061

  def test_getFirewallRules(self):
    computer = ComputerForTest(self.software_root, self.instance_root)
    self.setFirewallConfig()
    self.ip_address_list = computer.ip_address_list
    ip = computer.instance_list[0].full_ip_list[0][1]
2062 2063 2064 2065 2066 2067 2068
    source_ip_list = ['10.32.0.15', '10.32.0.0/8']
    
    cmd_list = self.grid._getFirewallAcceptRules(ip,
                                [elt[1] for elt in self.ip_address_list],
                                source_ip_list,
                                ip_type='ipv4')
    self.checkRuleFromIpSource(ip, source_ip_list, cmd_list)
2069
    
2070
    cmd_list = self.grid._getFirewallRejectRules(ip,
2071
                                [elt[1] for elt in self.ip_address_list],
2072
                                source_ip_list,
2073
                                ip_type='ipv4')
2074
    self.checkRuleFromIpSourceReject(ip, source_ip_list, cmd_list)
2075 2076 2077 2078 2079


  def test_checkAddFirewallRules(self):
    computer = ComputerForTest(self.software_root, self.instance_root)
    self.setFirewallConfig()
2080
    # For simulate query rule success
2081
    self.grid.firewall_conf['firewall_cmd'] = '/bin/echo "no" #'
2082 2083 2084 2085 2086
    self.ip_address_list = computer.ip_address_list
    instance = computer.instance_list[0]
    ip = instance.full_ip_list[0][1]
    name = computer.instance_list[0].name
    
2087
    cmd_list = self.grid._getFirewallAcceptRules(ip,
2088
                                [elt[1] for elt in self.ip_address_list],
2089
                                [],
2090 2091 2092
                                ip_type='ipv4')
    self.grid._checkAddFirewallRules(name, cmd_list, add=True)

2093 2094 2095 2096
    rules_path = os.path.join(
          instance.partition_path,
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
      )
2097 2098
    with open(rules_path, 'r') as frules:
      rules_list = json.loads(frules.read())
2099
      self.checkRuleFromIpSource(ip, [], rules_list)
2100 2101

    # Remove all rules
2102
    self.grid.firewall_conf['firewall_cmd'] = '/bin/echo "yes" #'
2103 2104 2105 2106 2107 2108
    self.grid._checkAddFirewallRules(name, cmd_list, add=False)
    with open(rules_path, 'r') as frules:
      rules_list = json.loads(frules.read())
      self.assertEqual(rules_list, [])

    # Add one more ip in the authorized list
2109
    self.grid.firewall_conf['firewall_cmd'] = '/bin/echo "no" #'
2110
    self.ip_address_list.append(('interface1', '10.0.8.7'))
2111
    cmd_list = self.grid._getFirewallAcceptRules(ip,
2112
                                [elt[1] for elt in self.ip_address_list],
2113
                                [],
2114 2115 2116 2117 2118
                                ip_type='ipv4')

    self.grid._checkAddFirewallRules(name, cmd_list, add=True)
    with open(rules_path, 'r') as frules:
      rules_list = json.loads(frules.read())
2119
      self.checkRuleFromIpSource(ip, [], rules_list)
2120 2121 2122 2123 2124 2125 2126 2127 2128

  def test_partition_no_firewall(self):
    computer = ComputerForTest(self.software_root, self.instance_root)
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      self.assertEqual(self.grid.processComputerPartitionList(),
                        slapgrid.SLAPGRID_SUCCESS)
      self.assertFalse(os.path.exists(os.path.join(
          instance.partition_path,
2129
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
2130 2131
      )))

2132 2133 2134 2135 2136 2137 2138 2139
  def test_partition_firewall_restrict(self):
    computer = ComputerForTest(self.software_root, self.instance_root)
    self.setFirewallConfig()
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
      self.assertTrue(os.path.exists(os.path.join(
          instance.partition_path,
2140
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
      )))
      rules_path = os.path.join(
          instance.partition_path,
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
      )
      self.ip_address_list = computer.ip_address_list
      with open(rules_path, 'r') as frules:
        rules_list = json.loads(frules.read())
      
      ip = instance.full_ip_list[0][1]
      self.checkRuleFromIpSource(ip, [], rules_list)

2153 2154 2155 2156 2157
  def test_partition_firewall(self):
    computer = ComputerForTest(self.software_root, self.instance_root)
    self.setFirewallConfig()
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
2158
      instance.filter_dict = {'fw_restricted_access': 'off'}
2159 2160 2161
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
      self.assertTrue(os.path.exists(os.path.join(
          instance.partition_path,
2162
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
2163
      )))
2164 2165 2166 2167
      rules_path = os.path.join(
          instance.partition_path,
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
      )
2168 2169 2170 2171 2172
      self.ip_address_list = computer.ip_address_list
      with open(rules_path, 'r') as frules:
        rules_list = json.loads(frules.read())
      
      ip = instance.full_ip_list[0][1]
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
      self.checkRuleFromIpSourceReject(ip, [], rules_list)

  @unittest.skip('Always fail: instance.filter_dict can\'t change')
  def test_partition_firewall_restricted_access_change(self):
    computer = ComputerForTest(self.software_root, self.instance_root)
    self.setFirewallConfig()
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.filter_dict = {'fw_restricted_access': 'off',
                              'fw_rejected_sources': '10.0.8.11'}
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
      self.assertTrue(os.path.exists(os.path.join(
          instance.partition_path,
2186
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
      )))
      rules_path = os.path.join(
          instance.partition_path,
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
      )
      self.ip_address_list = computer.ip_address_list
      with open(rules_path, 'r') as frules:
        rules_list = json.loads(frules.read())

      ip = instance.full_ip_list[0][1]
      self.checkRuleFromIpSourceReject(ip, ['10.0.8.11'], rules_list)

2199 2200
      # For remove rules
      self.grid.firewall_conf['firewall_cmd'] = '/bin/echo "yes" #'
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
      instance.setFilterParameter({'fw_restricted_access': 'on',
                              'fw_authorized_sources': ''})
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)

      with open(rules_path, 'r') as frules:
        rules_list = json.loads(frules.read())

      self.checkRuleFromIpSource(ip, [], rules_list)

  def test_partition_firewall_ipsource_accept(self):
2211 2212
    computer = ComputerForTest(self.software_root, self.instance_root)
    self.setFirewallConfig()
2213 2214
    source_ip = ['10.0.8.10', '10.0.8.11']
    self.grid.firewall_conf['authorized_sources'] = [source_ip[0]]
2215 2216
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
2217 2218
      instance.filter_dict = {'fw_restricted_access': 'on',
                              'fw_authorized_sources': source_ip[1]}
2219 2220 2221
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
      self.assertTrue(os.path.exists(os.path.join(
          instance.partition_path,
2222
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
2223
      )))
2224 2225 2226 2227
      rules_path = os.path.join(
          instance.partition_path,
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
      )
2228
      rules_list= []
2229
      self.ip_address_list = computer.ip_address_list
2230
      ip = instance.full_ip_list[0][1]
2231
      base_cmd = '--permanent --direct --add-rule ipv4 filter'
2232 2233 2234
      with open(rules_path, 'r') as frules:
        rules_list = json.loads(frules.read())

2235 2236 2237 2238 2239 2240
      for thier_ip in source_ip:
        rule_input = '%s INPUT 0 -s %s -d %s -j ACCEPT' % (base_cmd, thier_ip, ip)
        self.assertIn(rule_input, rules_list)
  
        rule_fwd = '%s FORWARD 0 -s %s -d %s -j ACCEPT' % (base_cmd, thier_ip, ip)
        self.assertIn(rule_fwd, rules_list)
2241

2242
      self.checkRuleFromIpSource(ip, source_ip, rules_list)
2243

2244
  def test_partition_firewall_ipsource_reject(self):
2245 2246 2247
    computer = ComputerForTest(self.software_root, self.instance_root)
    self.setFirewallConfig()
    source_ip = '10.0.8.10'
2248 2249
    
    self.grid.firewall_conf['authorized_sources'] = ['10.0.8.15']
2250 2251
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
2252 2253
      instance.filter_dict = {'fw_rejected_sources': source_ip,
                              'fw_restricted_access': 'off'}
2254 2255 2256
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
      self.assertTrue(os.path.exists(os.path.join(
          instance.partition_path,
2257
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
2258
      )))
2259 2260 2261 2262
      rules_path = os.path.join(
          instance.partition_path,
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
      )
2263
      rules_list= []
2264 2265
      self.ip_address_list = computer.ip_address_list
      self.ip_address_list.append(('iface', '10.0.8.15'))
2266
      ip = instance.full_ip_list[0][1]
2267
      base_cmd = '--permanent --direct --add-rule ipv4 filter'
2268 2269 2270
      with open(rules_path, 'r') as frules:
        rules_list = json.loads(frules.read())

2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
      self.checkRuleFromIpSourceReject(ip, source_ip.split(' '), rules_list)

  def test_partition_firewall_ip_change(self):
    computer = ComputerForTest(self.software_root, self.instance_root)
    self.setFirewallConfig()
    source_ip = ['10.0.8.10', '10.0.8.11']
    self.grid.firewall_conf['authorized_sources'] = [source_ip[0]]
    with httmock.HTTMock(computer.request_handler):
      instance = computer.instance_list[0]
      instance.filter_dict = {'fw_restricted_access': 'on',
                              'fw_authorized_sources': source_ip[1]}
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
      self.assertTrue(os.path.exists(os.path.join(
          instance.partition_path,
2285
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
      )))
      rules_path = os.path.join(
          instance.partition_path,
          slapos.grid.SlapObject.Partition.partition_firewall_rules_name
      )
      rules_list= []
      self.ip_address_list = computer.ip_address_list
      ip = instance.full_ip_list[0][1]
      with open(rules_path, 'r') as frules:
        rules_list = json.loads(frules.read())

      self.checkRuleFromIpSource(ip, source_ip, rules_list)
      instance = computer.instance_list[0]
      # XXX -- removed
      #instance.filter_dict = {'fw_restricted_access': 'on',
      #                        'fw_authorized_sources': source_ip[0]}
2302

2303 2304
      # For simulate query rule exist
      self.grid.firewall_conf['firewall_cmd'] = '/bin/echo "yes" #'
2305 2306 2307 2308
      self.grid.firewall_conf['authorized_sources'] = []
      computer.ip_address_list.append(('route_interface1', '10.10.8.4'))
      self.assertEqual(self.grid.processComputerPartitionList(), slapgrid.SLAPGRID_SUCCESS)
      self.ip_address_list = computer.ip_address_list
2309

2310 2311 2312 2313
      with open(rules_path, 'r') as frules:
        rules_list = json.loads(frules.read())
      self.checkRuleFromIpSource(ip, [source_ip[1]], rules_list)