slapobject.py 17.4 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 29
import logging
import os
30
import time
31
import unittest
32

33 34 35
from slapos.slap import ComputerPartition as SlapComputerPartition

from slapos.grid.SlapObject import Partition, Software
36
from slapos.grid import utils
37
from slapos.grid import networkcache
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
38
# XXX: BasicMixin should be in a separated module, not in slapgrid test module.
39 40
from slapos.tests.slapgrid import BasicMixin

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
# Mockup
# XXX: Ambiguous name
# XXX: Factor with common SlapOS tests
class FakeCallAndStore(object):
  """
  Used to check if the mocked method has been called.
  """
  def __init__(self):
    self.called = False

  def __call__(self, *args, **kwargs):
    self.called = True

class FakeCallAndNoop(object):
  """
  Used to no-op a method.
  """
  def __call__(self, *args, **kwargs):
    pass
60

61 62 63 64 65 66
# XXX: change name and behavior to be more generic and factor with other tests
class FakeNetworkCacheCallAndRead(object):
  """
  Short-circuit normal calls to slapos buildout helpers, get and store
  'additional_buildout_parameter_list' for future analysis.
  """
67
  def __init__(self):
68
    self.external_command_list = []
69 70

  def __call__(self, *args, **kwargs):
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
71 72 73
    additional_buildout_parameter_list = \
        kwargs.get('additional_buildout_parameter_list')
    self.external_command_list.extend(additional_buildout_parameter_list)
74

75
# Backup modules
76
original_install_from_buildout = Software._install_from_buildout
77
original_upload_network_cached = networkcache.upload_network_cached
78 79
originalBootstrapBuildout = utils.bootstrapBuildout
originalLaunchBuildout = utils.launchBuildout
80 81
originalUploadSoftwareRelease = Software.uploadSoftwareRelease
originalPartitionGenerateSupervisorConfigurationFile = Partition.generateSupervisorConfigurationFile
82

83
class MasterMixin(BasicMixin, unittest.TestCase):
84
  """
85
  Master Mixin of slapobject test classes.
86 87 88 89
  """
  def setUp(self):
    BasicMixin.setUp(self)
    os.mkdir(self.software_root)
90
    os.mkdir(self.instance_root)
91

92 93 94
  def tearDown(self):
    BasicMixin.tearDown(self)

95
    # Un-monkey patch possible modules
96 97
    global originalBootstrapBuildout
    global originalLaunchBuildout
98 99
    utils.bootstrapBuildout = originalBootstrapBuildout
    utils.launchBuildout = originalLaunchBuildout
100

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
  # Helper functions
  def createSoftware(self, url=None, empty=False):
    """
    Create an empty software, and return a Software object from
    dummy parameters.
    """
    if url is None:
      url = 'mysoftware'

    software_path = os.path.join(self.software_root, utils.md5digest(url))
    os.mkdir(software_path)

    if not empty:
      # Populate the Software Release directory so that it is "complete" and
      # "working" from a slapos point of view.
      open(os.path.join(software_path, 'instance.cfg'), 'w').close()

    return Software(
      url=url,
      software_root=self.software_root,
      buildout=self.buildout,
      logger=logging.getLogger(),
    )

  def createPartition(
      self,
      software_release_url,
      partition_id=None,
129 130
      slap_computer_partition=None,
      retention_delay=None,
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  ):
    """
    Create a partition, and return a Partition object created
    from dummy parameters.
    """
    # XXX dirty, should disappear when Partition is cleaned up
    software_path = os.path.join(
        self.software_root,
        utils.md5digest(software_release_url)
    )

    if partition_id is None:
      partition_id = 'mypartition'

    if slap_computer_partition is None:
      slap_computer_partition = SlapComputerPartition(
        computer_id='bidon',
        partition_id=partition_id)

    instance_path = os.path.join(self.instance_root, partition_id)
    os.mkdir(instance_path)
    os.chmod(instance_path, 0o750)

    supervisor_configuration_path = os.path.join(
          self.instance_root, 'supervisor')
    os.mkdir(supervisor_configuration_path)

158
    partition = Partition(
159 160
      software_path=software_path,
      instance_path=instance_path,
161 162
      supervisord_partition_configuration_path=os.path.join(
          supervisor_configuration_path, partition_id),
163 164 165 166 167 168 169 170 171 172 173
      supervisord_socket=os.path.join(
          supervisor_configuration_path, 'supervisor.sock'),
      computer_partition=slap_computer_partition,
      computer_id='bidon',
      partition_id=partition_id,
      server_url='bidon',
      software_release_url=software_release_url,
      buildout=self.buildout,
      logger=logging.getLogger(),
    )

174 175 176 177 178
    partition.updateSupervisor = FakeCallAndNoop
    if retention_delay:
      partition.retention_delay = retention_delay

    return partition
179 180 181 182 183 184 185

class TestSoftwareNetworkCacheSlapObject(MasterMixin, unittest.TestCase):
  """
  Test for Network Cache related features in Software class.
  """
  def setUp(self):
    MasterMixin.setUp(self)
186 187 188 189
    self.fakeCallAndRead = FakeNetworkCacheCallAndRead()
    utils.bootstrapBuildout = self.fakeCallAndRead
    utils.launchBuildout = self.fakeCallAndRead

190 191 192
    self.signature_private_key_file = '/signature/private/key_file'
    self.upload_cache_url = 'http://example.com/uploadcache'
    self.upload_dir_url = 'http://example.com/uploaddir'
193
    self.shacache_ca_file = '/path/to/shacache/ca/file'
194 195
    self.shacache_cert_file = '/path/to/shacache/cert/file'
    self.shacache_key_file = '/path/to/shacache/key/file'
196
    self.shadir_ca_file = '/path/to/shadir/ca/file'
197 198 199 200 201 202
    self.shadir_cert_file = '/path/to/shadir/cert/file'
    self.shadir_key_file = '/path/to/shadir/key/file'

  def tearDown(self):
    MasterMixin.tearDown(self)

203
    Software._install_from_buildout = original_install_from_buildout
204
    networkcache.upload_network_cached = original_upload_network_cached
205
    Software.uploadSoftwareRelease = originalUploadSoftwareRelease
206

207 208 209 210 211
  # Test methods
  def test_software_install_with_networkcache(self):
    """
      Check if the networkcache parameters are propagated.
    """
212
    software = Software(
213 214 215 216 217 218 219
        url='http://example.com/software.cfg',
        software_root=self.software_root,
        buildout=self.buildout,
        logger=logging.getLogger(),
        signature_private_key_file='/signature/private/key_file',
        upload_cache_url='http://example.com/uploadcache',
        upload_dir_url='http://example.com/uploaddir',
220
        shacache_ca_file=self.shacache_ca_file,
221 222
        shacache_cert_file=self.shacache_cert_file,
        shacache_key_file=self.shacache_key_file,
223
        shadir_ca_file=self.shadir_ca_file,
224 225
        shadir_cert_file=self.shadir_cert_file,
        shadir_key_file=self.shadir_key_file)
226 227 228

    software.install()

229
    command_list = self.fakeCallAndRead.external_command_list
Marco Mariani's avatar
Marco Mariani committed
230 231 232 233
    self.assertIn('buildout:networkcache-section=networkcache', command_list)
    self.assertIn('networkcache:signature-private-key-file=%s' % self.signature_private_key_file, command_list)
    self.assertIn('networkcache:upload-cache-url=%s' % self.upload_cache_url, command_list)
    self.assertIn('networkcache:upload-dir-url=%s' % self.upload_dir_url, command_list)
234
    self.assertIn('networkcache:shacache-ca-file=%s' % self.shacache_ca_file, command_list)
Marco Mariani's avatar
Marco Mariani committed
235 236
    self.assertIn('networkcache:shacache-cert-file=%s' % self.shacache_cert_file, command_list)
    self.assertIn('networkcache:shacache-key-file=%s' % self.shacache_key_file, command_list)
237
    self.assertIn('networkcache:shadir-ca-file=%s' % self.shadir_ca_file, command_list)
Marco Mariani's avatar
Marco Mariani committed
238 239
    self.assertIn('networkcache:shadir-cert-file=%s' % self.shadir_cert_file, command_list)
    self.assertIn('networkcache:shadir-key-file=%s' % self.shadir_key_file, command_list)
240 241 242 243 244 245

  def test_software_install_without_networkcache(self):
    """
      Check if the networkcache parameters are not propagated if they are not
      available.
    """
246
    software = Software(url='http://example.com/software.cfg',
247 248 249
                                   software_root=self.software_root,
                                   buildout=self.buildout,
                                   logger=logging.getLogger())
250 251
    software.install()

252
    command_list = self.fakeCallAndRead.external_command_list
253 254 255 256 257 258 259 260
    self.assertNotIn('buildout:networkcache-section=networkcache', command_list)
    self.assertNotIn('networkcache:signature-private-key-file=%s' %
                     self.signature_private_key_file,
                     command_list)
    self.assertNotIn('networkcache:upload-cache-url=%s' % self.upload_cache_url,
                     command_list)
    self.assertNotIn('networkcache:upload-dir-url=%s' % self.upload_dir_url,
                     command_list)
261 262 263 264 265 266 267 268

  # XXX-Cedric: do the same with upload
  def test_software_install_networkcache_upload_blacklist(self):
    """
      Check if the networkcache upload blacklist parameters are propagated.
    """
    def fakeBuildout(*args, **kw):
      pass
269

270
    Software._install_from_buildout = fakeBuildout
271

272 273
    def fake_upload_network_cached(*args, **kw):
      self.assertFalse(True)
274

275 276 277 278
    networkcache.upload_network_cached = fake_upload_network_cached

    upload_to_binary_cache_url_blacklist = ["http://example.com"]

279
    software = Software(
280 281 282 283 284 285 286
        url='http://example.com/software.cfg',
        software_root=self.software_root,
        buildout=self.buildout,
        logger=logging.getLogger(),
        signature_private_key_file='/signature/private/key_file',
        upload_cache_url='http://example.com/uploadcache',
        upload_dir_url='http://example.com/uploaddir',
287
        shacache_ca_file=self.shacache_ca_file,
288 289
        shacache_cert_file=self.shacache_cert_file,
        shacache_key_file=self.shacache_key_file,
290
        shadir_ca_file=self.shadir_ca_file,
291 292 293 294
        shadir_cert_file=self.shadir_cert_file,
        shadir_key_file=self.shadir_key_file,
        upload_to_binary_cache_url_blacklist=
            upload_to_binary_cache_url_blacklist,
295 296 297
    )
    software.install()

Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
298
  def test_software_install_networkcache_upload_blacklist_side_effect(self):
299 300 301 302 303 304
    """
      Check if the networkcache upload blacklist parameters only prevent
      blacklisted Software Release to be uploaded.
    """
    def fakeBuildout(*args, **kw):
      pass
305
    Software._install_from_buildout = fakeBuildout
306

307 308 309
    def fakeUploadSoftwareRelease(*args, **kw):
      self.uploaded = True

310
    Software.uploadSoftwareRelease = fakeUploadSoftwareRelease
311 312 313

    upload_to_binary_cache_url_blacklist = ["http://anotherexample.com"]

314
    software = Software(
315 316 317 318 319 320 321 322 323
        url='http://example.com/software.cfg',
        software_root=self.software_root,
        buildout=self.buildout,
        logger=logging.getLogger(),
        signature_private_key_file='/signature/private/key_file',
        upload_cache_url='http://example.com/uploadcache',
        upload_dir_url='http://example.com/uploaddir',
        upload_binary_cache_url='http://example.com/uploadcache',
        upload_binary_dir_url='http://example.com/uploaddir',
324
        shacache_ca_file=self.shacache_ca_file,
325 326
        shacache_cert_file=self.shacache_cert_file,
        shacache_key_file=self.shacache_key_file,
327
        shadir_ca_file=self.shadir_ca_file,
328 329 330 331
        shadir_cert_file=self.shadir_cert_file,
        shadir_key_file=self.shadir_key_file,
        upload_to_binary_cache_url_blacklist=
            upload_to_binary_cache_url_blacklist,
332 333 334
    )
    software.install()
    self.assertTrue(getattr(self, 'uploaded', False))
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 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

class TestPartitionSlapObject(MasterMixin, unittest.TestCase):
  def setUp(self):
    MasterMixin.setUp(self)

    Partition.generateSupervisorConfigurationFile = FakeCallAndNoop()
    utils.bootstrapBuildout = FakeCallAndNoop()

    utils.launchBuildout = FakeCallAndStore()

  def tearDown(self):
    MasterMixin.tearDown(self)
    Partition.generateSupervisorConfigurationFile = originalPartitionGenerateSupervisorConfigurationFile

  def test_instance_is_deploying_if_software_release_exists(self):
    """
    Test that slapgrid deploys an instance if its Software Release exists and
    instance.cfg in the Software Release exists.
    """
    software = self.createSoftware()

    partition = self.createPartition(software.url)
    partition.install()

    self.assertTrue(utils.launchBuildout.called)

  def test_backward_compatibility_instance_is_deploying_if_template_cfg_is_used(self):
    """
    Backward compatibility test, for old software releases.
    Test that slapgrid deploys an instance if its Software Release exists and
    template.cfg in the Software Release exists.
    """

    software = self.createSoftware(empty=True)
    open(os.path.join(software.software_path, 'template.cfg'), 'w').close()

    partition = self.createPartition(software.url)
    partition.install()

    self.assertTrue(utils.launchBuildout.called)

  def test_instance_slapgrid_raise_if_software_release_instance_profile_does_not_exist(self):
    """
    Test that slapgrid raises XXX when deploying an instance if the Software Release
    related to the instance is not correctly installed (i.e there is no
    instance.cfg in it).
    """
    software = self.createSoftware(empty=True)

    partition = self.createPartition(software.url)

    # XXX: What should it raise?
    self.assertRaises(IOError, partition.install)

  def test_instance_slapgrid_raise_if_software_release_does_not_exist(self):
    """
    Test that slapgrid raises XXX when deploying an instance if the Software Release
    related to the instance is not present at all (i.e its directory does not
    exist at all).
    """
    software = self.createSoftware(empty=True)
    os.rmdir(software.software_path)

    partition = self.createPartition(software.url)

    # XXX: What should it raise?
    self.assertRaises(IOError, partition.install)

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
class TestPartitionDestructionLock(MasterMixin, unittest.TestCase):
  def setUp(self):
    MasterMixin.setUp(self)
    Partition.generateSupervisorConfigurationFile = FakeCallAndNoop()
    utils.bootstrapBuildout = FakeCallAndNoop()
    utils.launchBuildout = FakeCallAndStore()

  def test_retention_lock_delay_creation(self):
    delay = 42
    software = self.createSoftware()
    partition = self.createPartition(software.url, retention_delay=delay)
    partition.install()
    deployed_delay = int(open(partition.retention_lock_delay_file_path).read())
    self.assertEqual(delay, deployed_delay)

  def test_no_retention_lock_delay(self):
    software = self.createSoftware()
    partition = self.createPartition(software.url)
    partition.install()
    delay = open(partition.retention_lock_delay_file_path).read()
    self.assertTrue(delay, '0')

    self.assertTrue(partition.destroy())

  def test_retention_lock_delay_does_not_change(self):
    delay = 42
    software = self.createSoftware()
    partition = self.createPartition(software.url, retention_delay=delay)
    partition.install()

    partition.retention_delay = 23
    # install/destroy many times
    partition.install()
    partition.destroy()
    partition.destroy()
    partition.install()
    partition.destroy()

    deployed_delay = int(open(partition.retention_lock_delay_file_path).read())
    self.assertEqual(delay, deployed_delay)

  def test_retention_lock_delay_is_respected(self):
    delay = 2.0 / (3600 * 24)
    software = self.createSoftware()
    partition = self.createPartition(software.url, retention_delay=delay)
    partition.install()

    deployed_delay = float(open(partition.retention_lock_delay_file_path).read())
    self.assertEqual(int(delay), int(deployed_delay))

    self.assertFalse(partition.destroy())
    time.sleep(1)
    self.assertFalse(partition.destroy())
    time.sleep(1)
    self.assertTrue(partition.destroy())

  def test_retention_lock_date_creation(self):
    delay = 42
    software = self.createSoftware()
    partition = self.createPartition(software.url, retention_delay=delay)
    partition.install()
    self.assertFalse(os.path.exists(partition.retention_lock_date_file_path))
    partition.destroy()
    deployed_date = float(open(partition.retention_lock_date_file_path).read())
    self.assertEqual(delay * 3600 * 24 + int(time.time()), int(deployed_date))

  def test_retention_lock_date_does_not_change(self):
    delay = 42
    software = self.createSoftware()
    partition = self.createPartition(software.url, retention_delay=delay)
    now = time.time()
    partition.install()
    partition.destroy()

    partition.retention_delay = 23
    # install/destroy many times
    partition.install()
    partition.destroy()
    partition.destroy()
    partition.install()
    partition.destroy()

    deployed_date = float(open(partition.retention_lock_date_file_path).read())
    self.assertEqual(delay * 3600 * 24 + int(now), int(deployed_date))