slapgrid.py 44.5 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
# vim: set et sts=2:
Łukasz Nowak's avatar
Łukasz Nowak committed
3 4
##############################################################################
#
5 6
# Copyright (c) 2010, 2011, 2012 Vifib SARL and Contributors.
# All Rights Reserved.
Łukasz Nowak's avatar
Łukasz Nowak committed
7 8 9 10 11
#
# 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
12
# guarantees and support are strongly advised to contract a Free Software
Łukasz Nowak's avatar
Łukasz Nowak committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# 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.
#
##############################################################################
30

Łukasz Nowak's avatar
Łukasz Nowak committed
31 32
import os
import pkg_resources
33
import random
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
34 35
import socket
import StringIO
36
import subprocess
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
37 38 39 40
import sys
import tempfile
import time
import traceback
Łukasz Nowak's avatar
Łukasz Nowak committed
41
import warnings
42
import logging
43

Łukasz Nowak's avatar
Łukasz Nowak committed
44
if sys.version_info < (2, 6):
Marco Mariani's avatar
Marco Mariani committed
45
  warnings.warn('Used python version (%s) is old and has problems with'
Łukasz Nowak's avatar
Łukasz Nowak committed
46 47
      ' IPv6 connections' % sys.version.split('\n')[0])

Marco Mariani's avatar
Marco Mariani committed
48 49
from lxml import etree

Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
50 51
from slapos.slap.slap import NotFoundError
from slapos.slap.slap import ServerError
52
from slapos.util import mkdir_p, chownDirectory
Marco Mariani's avatar
Marco Mariani committed
53
from slapos.grid.exception import BuildoutFailedError
54
from slapos.grid.SlapObject import Software, Partition
Marco Mariani's avatar
Marco Mariani committed
55
from slapos.grid.svcbackend import launchSupervisord
56
from slapos.grid.utils import (md5digest, createPrivateDirectory, dropPrivileges,
57
                               SlapPopen, updateFile)
Marco Mariani's avatar
Marco Mariani committed
58
import slapos.slap
Łukasz Nowak's avatar
Łukasz Nowak committed
59 60


Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
61
# XXX: should be moved to SLAP library
62
COMPUTER_PARTITION_DESTROYED_STATE = 'destroyed'
63 64
COMPUTER_PARTITION_STARTED_STATE = 'started'
COMPUTER_PARTITION_STOPPED_STATE = 'stopped'
Łukasz Nowak's avatar
Łukasz Nowak committed
65

66 67 68 69
# Global variables about return state of slapgrid
SLAPGRID_SUCCESS = 0
SLAPGRID_FAIL = 1
SLAPGRID_PROMISE_FAIL = 2
70
PROMISE_TIMEOUT = 3
71

72
# XXX hardcoded watchdog_path
73
WATCHDOG_PATH = '/opt/slapos/bin/slapos-watchdog'
74

75
COMPUTER_PARTITION_TIMESTAMP_FILENAME = '.timestamp'
76
COMPUTER_PARTITION_LATEST_BANG_TIMESTAMP_FILENAME = '.slapos_latest_bang_timestamp'
77

78 79 80 81 82

class _formatXMLError(Exception):
  pass


83 84 85
def check_missing_parameters(options):
  required = set([
      'computer_id',
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
86
      # XXX: instance_root is better named "partition_root"
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
      'instance_root',
      'master_url',
      'software_root',
  ])

  if 'key_file' in options:
    required.add('certificate_repository_path')
    required.add('cert_file')
  if 'cert_file' in options:
    required.add('certificate_repository_path')
    required.add('key_file')

  missing = required.difference(options)

  if missing:
    raise RuntimeError('Missing mandatory parameters: %s' % ', '.join(sorted(missing)))


105 106
def check_missing_files(options):
  req_files = [
Marco Mariani's avatar
Marco Mariani committed
107 108 109 110 111 112 113 114 115
      options.get('key_file'),
      options.get('cert_file'),
      options.get('master_ca_file'),
      options.get('shacache-cert-file'),
      options.get('shacache-key-file'),
      options.get('shadir-cert-file'),
      options.get('shadir-key-file'),
      options.get('signature_private_key_file')
  ]
116 117

  req_dirs = [
Marco Mariani's avatar
Marco Mariani committed
118 119
      options.get('certificate_repository_path')
  ]
120 121 122

  for f in req_files:
    if f and not os.path.exists(f):
Marco Mariani's avatar
Marco Mariani committed
123
      raise RuntimeError('File %r does not exist.' % f)
124 125 126 127 128 129

  for d in req_dirs:
    if d and not os.path.isdir(d):
      raise RuntimeError('Directory %r does not exist' % d)


130 131
def merged_options(args, configp):
  options = dict(configp.items('slapos'))
132

133 134
  if configp.has_section('networkcache'):
    options.update(dict(configp.items('networkcache')))
135 136 137 138
  for key, value in vars(args).iteritems():
    if value is not None:
      options[key] = value

Marco Mariani's avatar
Marco Mariani committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152
  if options.get('all'):
    options['develop'] = True

  # Supervisord configuration location
  if not options.get('supervisord_configuration_path'):
    options['supervisord_configuration_path'] = \
      os.path.join(options['instance_root'], 'etc', 'supervisord.conf')
  # Supervisord socket
  if not options.get('supervisord_socket'):
    options['supervisord_socket'] = \
      os.path.join(options['instance_root'], 'supervisord.socket')

  # Parse cache / binary cache options
  # Backward compatibility about "binary-cache-url-blacklist" deprecated option
Marco Mariani's avatar
Marco Mariani committed
153 154
  if (options.get("binary-cache-url-blacklist") and not
        options.get("download-from-binary-cache-url-blacklist")):
Marco Mariani's avatar
Marco Mariani committed
155 156 157 158 159 160 161 162 163
    options["download-from-binary-cache-url-blacklist"] = \
        options["binary-cache-url-blacklist"]
  options["download-from-binary-cache-url-blacklist"] = [
      url.strip() for url in options.get(
          "download-from-binary-cache-url-blacklist", "").split('\n') if url]
  options["upload-to-binary-cache-url-blacklist"] = [
      url.strip() for url in options.get(
          "upload-to-binary-cache-url-blacklist", "").split('\n') if url]

164 165 166
  return options


167
def random_delay(options, logger):
168 169 170 171
  """
  Sleep for a random time to avoid SlapOS Master being DDOSed by an army of
  SlapOS Nodes configured with cron.
  """
172 173
  if options['now']:
    # XXX-Cedric: deprecate '--now'
174 175
    return

176
  maximal_delay = int(options.get('maximal_delay', '0'))
177 178
  if maximal_delay:
    duration = random.randint(1, maximal_delay)
Marco Mariani's avatar
Marco Mariani committed
179 180
    logger.info('Sleeping for %s seconds. To disable this feature, '
                'check --now parameter in slapgrid help.', duration)
181 182 183
    time.sleep(duration)


184
def create_slapgrid_object(options, logger):
185 186 187 188
  signature_certificate_list = None
  if 'signature-certificate-list' in options:
    cert_marker = '-----BEGIN CERTIFICATE-----'
    signature_certificate_list = [
Marco Mariani's avatar
Marco Mariani committed
189 190 191 192
        cert_marker + '\n' + q.strip()
        for q in options['signature-certificate-list'].split(cert_marker)
        if q.strip()
    ]
193 194 195 196 197 198 199 200

  op = options
  return Slapgrid(software_root=op['software_root'],
                  instance_root=op['instance_root'],
                  master_url=op['master_url'],
                  computer_id=op['computer_id'],
                  supervisord_socket=op['supervisord_socket'],
                  supervisord_configuration_path=op['supervisord_configuration_path'],
201 202
                  buildout=op.get('buildout'),
                  logger=logger,
203
                  maximum_periodicity = op.get('maximum_periodicity', 86400),
204 205 206 207 208 209
                  key_file=op.get('key_file'),
                  cert_file=op.get('cert_file'),
                  signature_private_key_file=op.get('signature_private_key_file'),
                  signature_certificate_list=signature_certificate_list,
                  download_binary_cache_url=op.get('download-binary-cache-url'),
                  upload_binary_cache_url=op.get('upload-binary-cache-url'),
Marco Mariani's avatar
Marco Mariani committed
210
                  download_from_binary_cache_url_blacklist=
211
                      op.get('download-from-binary-cache-url-blacklist', []),
Marco Mariani's avatar
Marco Mariani committed
212
                  upload_to_binary_cache_url_blacklist=
213 214 215 216 217
                      op.get('upload-to-binary-cache-url-blacklist', []),
                  upload_cache_url=op.get('upload-cache-url'),
                  download_binary_dir_url=op.get('download-binary-dir-url'),
                  upload_binary_dir_url=op.get('upload-binary-dir-url'),
                  upload_dir_url=op.get('upload-dir-url'),
218 219
                  master_ca_file=op.get('master_ca_file'),
                  certificate_repository_path=op.get('certificate_repository_path'),
220
                  promise_timeout=op.get('promise_timeout', PROMISE_TIMEOUT),
221 222 223 224 225 226 227 228
                  shacache_cert_file=op.get('shacache-cert-file'),
                  shacache_key_file=op.get('shacache-key-file'),
                  shadir_cert_file=op.get('shadir-cert-file'),
                  shadir_key_file=op.get('shadir-key-file'),
                  develop=op.get('develop', False),
                  # Try to fetch from deprecated argument
                  software_release_filter_list=op.get('only-sr', op.get('only_sr')),
                  # Try to fetch from deprecated argument
229
                  computer_partition_filter_list=op.get('only-cp', op.get('only_cp')))
Łukasz Nowak's avatar
Łukasz Nowak committed
230 231


232
def check_required_only_partitions(existing, required):
233 234 235
  """
  Verify the existence of partitions specified by the --only parameter
  """
236 237
  missing = set(required) - set(existing)
  if missing:
Marco Mariani's avatar
Marco Mariani committed
238 239
    plural = ['s', ''][len(missing) == 1]
    raise ValueError('Unknown partition%s: %s' % (plural, ', '.join(sorted(missing))))
240 241


Łukasz Nowak's avatar
Łukasz Nowak committed
242 243 244 245
class Slapgrid(object):
  """ Main class for SlapGrid. Fetches and processes informations from master
  server and pushes usage information to master server.
  """
Antoine Catton's avatar
Antoine Catton committed
246 247 248 249

  class PromiseError(Exception):
    pass

Łukasz Nowak's avatar
Łukasz Nowak committed
250 251 252 253 254 255 256
  def __init__(self,
               software_root,
               instance_root,
               master_url,
               computer_id,
               supervisord_socket,
               supervisord_configuration_path,
257
               buildout,
258
               logger,
259
               maximum_periodicity=86400,
Łukasz Nowak's avatar
Łukasz Nowak committed
260 261
               key_file=None,
               cert_file=None,
262
               signature_private_key_file=None,
Yingjie Xu's avatar
Yingjie Xu committed
263 264 265
               signature_certificate_list=None,
               download_binary_cache_url=None,
               upload_binary_cache_url=None,
266 267
               download_from_binary_cache_url_blacklist=None,
               upload_to_binary_cache_url_blacklist=None,
268
               upload_cache_url=None,
Yingjie Xu's avatar
Yingjie Xu committed
269 270
               download_binary_dir_url=None,
               upload_binary_dir_url=None,
271
               upload_dir_url=None,
Łukasz Nowak's avatar
Łukasz Nowak committed
272 273
               master_ca_file=None,
               certificate_repository_path=None,
274 275 276 277
               promise_timeout=3,
               shacache_cert_file=None,
               shacache_key_file=None,
               shadir_cert_file=None,
278
               shadir_key_file=None,
279
               develop=False,
280
               software_release_filter_list=None,
281 282
               computer_partition_filter_list=None,
               ):
Łukasz Nowak's avatar
Łukasz Nowak committed
283 284 285 286 287 288 289 290 291 292 293 294
    """Makes easy initialisation of class parameters"""
    # Parses arguments
    self.software_root = os.path.abspath(software_root)
    self.instance_root = os.path.abspath(instance_root)
    self.master_url = master_url
    self.computer_id = computer_id
    self.supervisord_socket = supervisord_socket
    self.supervisord_configuration_path = supervisord_configuration_path
    self.key_file = key_file
    self.cert_file = cert_file
    self.master_ca_file = master_ca_file
    self.certificate_repository_path = certificate_repository_path
295
    self.signature_private_key_file = signature_private_key_file
Yingjie Xu's avatar
Yingjie Xu committed
296 297 298
    self.signature_certificate_list = signature_certificate_list
    self.download_binary_cache_url = download_binary_cache_url
    self.upload_binary_cache_url = upload_binary_cache_url
299 300 301 302
    self.download_from_binary_cache_url_blacklist = \
        download_from_binary_cache_url_blacklist
    self.upload_to_binary_cache_url_blacklist = \
        upload_to_binary_cache_url_blacklist
303
    self.upload_cache_url = upload_cache_url
Yingjie Xu's avatar
Yingjie Xu committed
304 305
    self.download_binary_dir_url = download_binary_dir_url
    self.upload_binary_dir_url = upload_binary_dir_url
306
    self.upload_dir_url = upload_dir_url
307 308 309 310
    self.shacache_cert_file = shacache_cert_file
    self.shacache_key_file = shacache_key_file
    self.shadir_cert_file = shadir_cert_file
    self.shadir_key_file = shadir_key_file
311
    self.logger = logger
Łukasz Nowak's avatar
Łukasz Nowak committed
312
    # Creates objects from slap module
Marco Mariani's avatar
Marco Mariani committed
313
    self.slap = slapos.slap.slap()
Łukasz Nowak's avatar
Łukasz Nowak committed
314 315 316 317 318
    self.slap.initializeConnection(self.master_url, key_file=self.key_file,
        cert_file=self.cert_file, master_ca_file=self.master_ca_file)
    self.computer = self.slap.registerComputer(self.computer_id)
    # Defines all needed paths
    self.supervisord_configuration_directory = \
Marco Mariani's avatar
Marco Mariani committed
319
        os.path.join(self.instance_root, 'etc', 'supervisord.conf.d')
320
    self.buildout = buildout
321
    self.promise_timeout = promise_timeout
322
    self.develop = develop
323
    if software_release_filter_list is not None:
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
324 325
      self.software_release_filter_list = \
          software_release_filter_list.split(",")
326
    else:
327
      self.software_release_filter_list = []
328 329
    self.computer_partition_filter_list = []
    if computer_partition_filter_list is not None:
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
330 331
      self.computer_partition_filter_list = \
          computer_partition_filter_list.split(",")
332
    self.maximum_periodicity = maximum_periodicity
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
333 334

  def getWatchdogLine(self):
335
    invocation_list = [WATCHDOG_PATH]
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
336
    invocation_list.append("--master-url '%s' " % self.master_url)
337
    if self.certificate_repository_path:
Marco Mariani's avatar
Marco Mariani committed
338 339
      invocation_list.append("--certificate-repository-path '%s'" %
                                self.certificate_repository_path)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
340
    invocation_list.append("--computer-id '%s'" % self.computer_id)
341
    invocation_list.append("--instance-root '%s'" % self.instance_root)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
342
    return ' '.join(invocation_list)
Łukasz Nowak's avatar
Łukasz Nowak committed
343 344 345 346 347 348 349

  def checkEnvironmentAndCreateStructure(self):
    """Checks for software_root and instance_root existence, then creates
       needed files and directories.
    """
    # Checks for software_root and instance_root existence
    if not os.path.isdir(self.software_root):
350
      raise OSError('%s does not exist.' % self.software_root)
Łukasz Nowak's avatar
Łukasz Nowak committed
351
    if not os.path.isdir(self.instance_root):
352
      raise OSError('%s does not exist.' % self.instance_root)
Łukasz Nowak's avatar
Łukasz Nowak committed
353
    # Creates everything needed
Marco Mariani's avatar
Marco Mariani committed
354

355 356 357 358
    # Creates instance_root structure
    createPrivateDirectory(os.path.join(self.instance_root, 'var'))
    createPrivateDirectory(os.path.join(self.instance_root, 'var', 'log'))
    createPrivateDirectory(os.path.join(self.instance_root, 'var', 'run'))
Marco Mariani's avatar
Marco Mariani committed
359 360

    createPrivateDirectory(os.path.join(self.instance_root, 'etc'))
361
    createPrivateDirectory(self.supervisord_configuration_directory)
362

363 364 365 366 367 368 369 370 371 372 373 374 375
    # Creates supervisord configuration
    updateFile(self.supervisord_configuration_path,
      pkg_resources.resource_stream(__name__,
        'templates/supervisord.conf.in').read() % {
            'supervisord_configuration_directory': self.supervisord_configuration_directory,
            'supervisord_socket': os.path.abspath(self.supervisord_socket),
            'supervisord_loglevel': 'info',
            'supervisord_logfile': os.path.abspath(os.path.join(self.instance_root, 'var', 'log', 'supervisord.log')),
            'supervisord_logfile_maxbytes': '50MB',
            'supervisord_nodaemon': 'false',
            'supervisord_pidfile': os.path.abspath(os.path.join(self.instance_root, 'var', 'run', 'supervisord.pid')),
            'supervisord_logfile_backups': '10',
            'watchdog_command': self.getWatchdogLine(),
Marco Mariani's avatar
Marco Mariani committed
376 377
        }
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
378 379 380

  def getComputerPartitionList(self):
    try:
381
      return self.computer.getComputerPartitionList()
Marco Mariani's avatar
Marco Mariani committed
382 383
    except socket.error as exc:
      self.logger.fatal(exc)
384
      raise
Łukasz Nowak's avatar
Łukasz Nowak committed
385 386 387 388 389

  def processSoftwareReleaseList(self):
    """Will process each Software Release.
    """
    self.checkEnvironmentAndCreateStructure()
390
    self.logger.info('Processing software releases...')
391
    # Boolean to know if every instance has correctly been deployed
Łukasz Nowak's avatar
Łukasz Nowak committed
392 393
    clean_run = True
    for software_release in self.computer.getSoftwareReleaseList():
Łukasz Nowak's avatar
Łukasz Nowak committed
394
      state = software_release.getState()
Łukasz Nowak's avatar
Łukasz Nowak committed
395 396
      try:
        software_release_uri = software_release.getURI()
Marco Mariani's avatar
Marco Mariani committed
397
        url_hash = md5digest(software_release_uri)
398
        software_path = os.path.join(self.software_root, url_hash)
Łukasz Nowak's avatar
Łukasz Nowak committed
399 400
        software = Software(url=software_release_uri,
            software_root=self.software_root,
401
            buildout=self.buildout,
402
            logger=self.logger,
403
            signature_private_key_file=self.signature_private_key_file,
Yingjie Xu's avatar
Yingjie Xu committed
404 405 406
            signature_certificate_list=self.signature_certificate_list,
            download_binary_cache_url=self.download_binary_cache_url,
            upload_binary_cache_url=self.upload_binary_cache_url,
Marco Mariani's avatar
Marco Mariani committed
407
            download_from_binary_cache_url_blacklist=
408
                self.download_from_binary_cache_url_blacklist,
Marco Mariani's avatar
Marco Mariani committed
409
            upload_to_binary_cache_url_blacklist=
410
                self.upload_to_binary_cache_url_blacklist,
411
            upload_cache_url=self.upload_cache_url,
Yingjie Xu's avatar
Yingjie Xu committed
412 413
            download_binary_dir_url=self.download_binary_dir_url,
            upload_binary_dir_url=self.upload_binary_dir_url,
414 415 416 417
            upload_dir_url=self.upload_dir_url,
            shacache_cert_file=self.shacache_cert_file,
            shacache_key_file=self.shacache_key_file,
            shadir_cert_file=self.shadir_cert_file,
Łukasz Nowak's avatar
Łukasz Nowak committed
418 419
            shadir_key_file=self.shadir_key_file)
        if state == 'available':
420
          completed_tag = os.path.join(software_path, '.completed')
Marco Mariani's avatar
Marco Mariani committed
421 422 423 424
          if (self.develop or (not os.path.exists(completed_tag) and
                 len(self.software_release_filter_list) == 0) or
                 url_hash in self.software_release_filter_list or
                 url_hash in (md5digest(uri) for uri in self.software_release_filter_list)):
425 426 427 428 429
            try:
              software_release.building()
            except NotFoundError:
              pass
            software.install()
Marco Mariani's avatar
Marco Mariani committed
430 431
            with open(completed_tag, 'w') as fout:
              fout.write(time.asctime())
Łukasz Nowak's avatar
Łukasz Nowak committed
432
        elif state == 'destroyed':
433
          if os.path.exists(software_path):
434
            self.logger.info('Destroying %r...' % software_release_uri)
435
            software.destroy()
436
            self.logger.info('Destroyed %r.' % software_release_uri)
437
      # Send log before exiting
Łukasz Nowak's avatar
Łukasz Nowak committed
438
      except (SystemExit, KeyboardInterrupt):
439
        software_release.error(traceback.format_exc(), logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
440
        raise
441 442

      # Buildout failed: send log but don't print it to output (already done)
Marco Mariani's avatar
Marco Mariani committed
443
      except BuildoutFailedError as exc:
444 445
        clean_run = False
        try:
446
          software_release.error(exc, logger=self.logger)
447 448 449
        except (SystemExit, KeyboardInterrupt):
          raise
        except Exception:
450
          self.logger.exception('Problem while reporting error, continuing:')
451 452

      # For everything else: log it, send it, continue.
Łukasz Nowak's avatar
Łukasz Nowak committed
453
      except Exception:
454 455
        self.logger.exception('')
        software_release.error(traceback.format_exc(), logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
456 457
        clean_run = False
      else:
Łukasz Nowak's avatar
Łukasz Nowak committed
458
        if state == 'available':
459 460 461 462
          try:
            software_release.available()
          except NotFoundError:
            pass
Łukasz Nowak's avatar
Łukasz Nowak committed
463
        elif state == 'destroyed':
464 465
          try:
            software_release.destroyed()
466
          except (NotFoundError, ServerError):
467
            self.logger.exception('')
468
    self.logger.info('Finished software releases.')
469 470 471 472 473

    # Return success value
    if not clean_run:
      return SLAPGRID_FAIL
    return SLAPGRID_SUCCESS
Łukasz Nowak's avatar
Łukasz Nowak committed
474 475 476

  def _launchSupervisord(self):
    launchSupervisord(self.supervisord_socket,
Marco Mariani's avatar
Marco Mariani committed
477 478
                      self.supervisord_configuration_path,
                      logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
479

Antoine Catton's avatar
Antoine Catton committed
480
  def _checkPromises(self, computer_partition):
481
    self.logger.info("Checking promises...")
Marco Mariani's avatar
Marco Mariani committed
482
    instance_path = os.path.join(self.instance_root, computer_partition.getId())
Antoine Catton's avatar
Antoine Catton committed
483 484 485 486 487 488 489 490

    uid, gid = None, None
    stat_info = os.stat(instance_path)

    #stat sys call to get statistics informations
    uid = stat_info.st_uid
    gid = stat_info.st_gid

491
    promise_present = False
Antoine Catton's avatar
Antoine Catton committed
492 493 494 495
    # Get the list of promises
    promise_dir = os.path.join(instance_path, 'etc', 'promise')
    if os.path.exists(promise_dir) and os.path.isdir(promise_dir):
      # Check whether every promise is kept
Marco Mariani's avatar
Marco Mariani committed
496
      for promise in os.listdir(promise_dir):
497
        promise_present = True
Antoine Catton's avatar
Antoine Catton committed
498

Antoine Catton's avatar
Antoine Catton committed
499 500 501
        command = [os.path.join(promise_dir, promise)]

        promise = os.path.basename(command[0])
502
        self.logger.info("Checking promise %r.", promise)
Antoine Catton's avatar
Antoine Catton committed
503

504
        process_handler = subprocess.Popen(command,
505
                                           preexec_fn=lambda: dropPrivileges(uid, gid, logger=self.logger),
Marco Mariani's avatar
Marco Mariani committed
506
                                           cwd=instance_path,
Marco Mariani's avatar
Marco Mariani committed
507
                                           env=None if sys.platform == 'cygwin' else {},
Marco Mariani's avatar
Marco Mariani committed
508 509 510
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE,
                                           stdin=subprocess.PIPE)
511 512 513
        process_handler.stdin.flush()
        process_handler.stdin.close()
        process_handler.stdin = None
Antoine Catton's avatar
Antoine Catton committed
514 515 516 517

        time.sleep(self.promise_timeout)

        if process_handler.poll() is None:
518
          process_handler.terminate()
Antoine Catton's avatar
Antoine Catton committed
519 520 521 522 523
          raise Slapgrid.PromiseError("The promise %r timed out" % promise)
        elif process_handler.poll() != 0:
          stderr = process_handler.communicate()[1]
          if stderr is None:
            stderr = 'No error output from %r.' % promise
Antoine Catton's avatar
Antoine Catton committed
524 525
          else:
            stderr = 'Promise %r:' % promise + stderr
Antoine Catton's avatar
Antoine Catton committed
526 527
          raise Slapgrid.PromiseError(stderr)

Antoine Catton's avatar
Antoine Catton committed
528 529 530
    if not promise_present:
      self.logger.info("No promise.")

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
  def processComputerPartition(self, computer_partition):
    """
    Process a Computer Partition, depending on its state
    """
    computer_partition_id = computer_partition.getId()

    # Sanity checks before processing
    # Those values should not be None or empty string or any falsy value
    if not computer_partition_id:
      raise ValueError('Computer Partition id is empty.')

    # Check if we defined explicit list of partitions to process.
    # If so, if current partition not in this list, skip.
    if len(self.computer_partition_filter_list) > 0 and \
         (computer_partition_id not in self.computer_partition_filter_list):
      return

548
    self.logger.debug('Check if %s requires processing...' % computer_partition_id)
549

550 551 552
    instance_path = os.path.join(self.instance_root, computer_partition_id)

    # Try to get partition timestamp (last modification date)
553 554 555 556
    timestamp_path = os.path.join(
        instance_path,
        COMPUTER_PARTITION_TIMESTAMP_FILENAME
    )
557 558 559 560 561 562
    parameter_dict = computer_partition.getInstanceParameterDict()
    if 'timestamp' in parameter_dict:
      timestamp = parameter_dict['timestamp']
    else:
      timestamp = None

563 564 565 566 567 568 569
    try:
      software_url = computer_partition.getSoftwareRelease().getURI()
    except NotFoundError:
      # Problem with instance: SR URI not set.
      # Try to process it anyway, it may need to be deleted.
      software_url = None
    try:
Marco Mariani's avatar
Marco Mariani committed
570
      software_path = os.path.join(self.software_root, md5digest(software_url))
571 572 573 574 575
    except TypeError:
      # Problem with instance: SR URI not set.
      # Try to process it anyway, it may need to be deleted.
      software_path = None

576
    periodicity = self.maximum_periodicity
577
    if software_path:
578 579 580 581 582 583 584
      periodicity_path = os.path.join(software_path, 'periodicity')
      if os.path.exists(periodicity_path):
        try:
          periodicity = int(open(periodicity_path).read())
        except ValueError:
          os.remove(periodicity_path)
          self.logger.exception('')
585 586 587 588

    # Check if timestamp from server is more recent than local one.
    # If not: it's not worth processing this partition (nothing has
    # changed).
Marco Mariani's avatar
Marco Mariani committed
589 590
    if (computer_partition_id not in self.computer_partition_filter_list and
          not self.develop and os.path.exists(timestamp_path)):
591 592 593 594
      old_timestamp = open(timestamp_path).read()
      last_runtime = int(os.path.getmtime(timestamp_path))
      if timestamp:
        try:
595 596 597
          if periodicity == 0:
            os.remove(timestamp_path)
          elif int(timestamp) <= int(old_timestamp):
598 599
            # Check periodicity, i.e if periodicity is one day, partition
            # should be processed at least every day.
600
            if int(time.time()) <= (last_runtime + periodicity) or periodicity < 0:
601
              self.logger.debug('Partition already up-to-date, skipping.')
602
              return
603 604 605 606
            else:
              # Periodicity forced processing this partition. Removing
              # the timestamp file in case it fails.
              os.remove(timestamp_path)
607 608
        except ValueError:
          os.remove(timestamp_path)
609
          self.logger.exception('')
610

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
    # Include Partition Logging
    log_folder_path = "%s/.slapgrid/log" % instance_path
    mkdir_p(log_folder_path)
    partition_file_handler = logging.FileHandler(
                filename="%s/instance.log" % (log_folder_path)
            )
    stat_info = os.stat(instance_path)
    chownDirectory("%s/.slapgrid" % instance_path, 
                   uid=stat_info.st_uid,
                   gid=stat_info.st_gid)

    formatter = logging.Formatter(
       '[%(asctime)s] %(levelname)-8s %(name)s %(message)s')
    partition_file_handler.setFormatter(formatter)
    self.logger.addHandler(partition_file_handler)

    try:
      self.logger.info('Processing Computer Partition %s.' % computer_partition_id)
      self.logger.info('  Software URL: %s' % software_url)
      self.logger.info('  Software path: %s' % software_path)
      self.logger.info('  Instance path: %s' % instance_path)
  
      local_partition = Partition(
        software_path=software_path,
        instance_path=instance_path,
        supervisord_partition_configuration_path=os.path.join(
          self.supervisord_configuration_directory, '%s.conf' %
          computer_partition_id),
        supervisord_socket=self.supervisord_socket,
        computer_partition=computer_partition,
        computer_id=self.computer_id,
        partition_id=computer_partition_id,
        server_url=self.master_url,
        software_release_url=software_url,
        certificate_repository_path=self.certificate_repository_path,
        buildout=self.buildout,
        logger=self.logger)
      computer_partition_state = computer_partition.getState()
  
      # XXX this line breaks 37 tests
      # self.logger.info('  Instance type: %s' % computer_partition.getType())
      self.logger.info('  Instance status: %s' % computer_partition_state)
  
      if computer_partition_state == COMPUTER_PARTITION_STARTED_STATE:
655 656
        local_partition.install()
        computer_partition.available()
657 658 659 660 661 662 663 664 665 666 667 668
        local_partition.start()
        self._checkPromises(computer_partition)
        computer_partition.started()
      elif computer_partition_state == COMPUTER_PARTITION_STOPPED_STATE:
        try:
          # We want to process the partition, even if stopped, because it should
          # propagate the state to children if any.
          local_partition.install()
          computer_partition.available()
        finally:
          # Instance has to be stopped even if buildout/reporting is wrong.
          local_partition.stop()
669
        computer_partition.stopped()
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
      elif computer_partition_state == COMPUTER_PARTITION_DESTROYED_STATE:
        local_partition.stop()
        try:
          computer_partition.stopped()
        except (SystemExit, KeyboardInterrupt):
          computer_partition.error(traceback.format_exc(), logger=self.logger)
          raise
        except Exception:
          pass
      else:
        error_string = "Computer Partition %r has unsupported state: %s" % \
          (computer_partition_id, computer_partition_state)
        computer_partition.error(error_string, logger=self.logger)
        raise NotImplementedError(error_string)
    finally:
       self.logger.removeHandler(partition_file_handler)
686 687 688 689 690

    # If partition has been successfully processed, write timestamp
    if timestamp:
      open(timestamp_path, 'w').write(timestamp)

691
  def FilterComputerPartitionList(self, computer_partition_list):
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
692
    """
693
    Try to filter valid partitions to be processed from free partitions.
Łukasz Nowak's avatar
Łukasz Nowak committed
694
    """
695 696
    filtered_computer_partition_list = []
    for computer_partition in computer_partition_list:
Łukasz Nowak's avatar
Łukasz Nowak committed
697
      try:
698 699 700 701 702 703 704
        computer_partition_path = os.path.join(self.instance_root,
            computer_partition.getId())
        if not os.path.exists(computer_partition_path):
          raise NotFoundError('Partition directory %s does not exist.' %
              computer_partition_path)
        # Check state of partition. If it is in "destroyed" state, check if it
        # partition is actually installed in the Computer or if it is "free"
705
        # partition, and check if it has some Software information.
706 707 708
        # XXX-Cedric: Temporary AND ugly solution to check if an instance
        # is in the partition. Dangerous because not 100% sure it is empty
        computer_partition_state = computer_partition.getState()
709 710 711 712
        try:
          software_url = computer_partition.getSoftwareRelease().getURI()
        except (NotFoundError, TypeError, NameError):
          software_url = None
713
        if computer_partition_state == COMPUTER_PARTITION_DESTROYED_STATE and \
714 715
           os.listdir(computer_partition_path) == [] and \
           not software_url:
716
          continue
717

718 719 720 721 722 723 724
        # Everything seems fine
        filtered_computer_partition_list.append(computer_partition)

      # XXX-Cedric: factor all this error handling

      # Send log before exiting
      except (SystemExit, KeyboardInterrupt):
725
        computer_partition.error(traceback.format_exc(), logger=self.logger)
726 727
        raise

Marco Mariani's avatar
Marco Mariani committed
728
      except Exception as exc:
729 730 731 732
        # if Buildout failed: send log but don't print it to output (already done)
        if not isinstance(exc, BuildoutFailedError):
          # For everything else: log it, send it, continue.
          self.logger.exception('')
733
        try:
734
          computer_partition.error(exc, logger=self.logger)
735 736 737
        except (SystemExit, KeyboardInterrupt):
          raise
        except Exception:
738
          self.logger.exception('Problem while reporting error, continuing:')
739 740 741 742 743 744 745

    return filtered_computer_partition_list

  def processComputerPartitionList(self):
    """
    Will start supervisord and process each Computer Partition.
    """
746
    self.logger.info('Processing computer partitions...')
747 748 749
    # Prepares environment
    self.checkEnvironmentAndCreateStructure()
    self._launchSupervisord()
750 751

    # Boolean to know if every instance has correctly been deployed
752
    clean_run = True
753 754
    # Boolean to know if every promises correctly passed
    clean_run_promise = True
755

756 757 758
    check_required_only_partitions([cp.getId() for cp in self.getComputerPartitionList()],
                                   self.computer_partition_filter_list)

759 760 761 762 763 764 765 766 767
    # Filter all dummy / empty partitions
    computer_partition_list = self.FilterComputerPartitionList(
        self.getComputerPartitionList())

    for computer_partition in computer_partition_list:
      # Nothing should raise outside of the current loop iteration, so that
      # even if something is terribly wrong while processing an instance, it
      # won't prevent processing other ones.
      try:
768
        # Process the partition itself
769
        self.processComputerPartition(computer_partition)
770

771
      # Send log before exiting
Łukasz Nowak's avatar
Łukasz Nowak committed
772
      except (SystemExit, KeyboardInterrupt):
773
        computer_partition.error(traceback.format_exc(), logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
774
        raise
775

Marco Mariani's avatar
Marco Mariani committed
776
      except Slapgrid.PromiseError as exc:
777 778
        clean_run_promise = False
        try:
779
          self.logger.error(exc)
780
          computer_partition.error(exc, logger=self.logger)
781 782 783
        except (SystemExit, KeyboardInterrupt):
          raise
        except Exception:
784
          self.logger.exception('Problem while reporting error, continuing:')
785

Marco Mariani's avatar
Marco Mariani committed
786
      except Exception as exc:
Łukasz Nowak's avatar
Łukasz Nowak committed
787
        clean_run = False
788 789 790 791
        # if Buildout failed: send log but don't print it to output (already done)
        if not isinstance(exc, BuildoutFailedError):
          # For everything else: log it, send it, continue.
          self.logger.exception('')
792
        try:
793
          computer_partition.error(exc, logger=self.logger)
794 795 796
        except (SystemExit, KeyboardInterrupt):
          raise
        except Exception:
797
          self.logger.exception('Problem while reporting error, continuing:')
798

799
    self.logger.info('Finished computer partitions.')
800 801 802 803 804 805 806

    # Return success value
    if not clean_run:
      return SLAPGRID_FAIL
    if not clean_run_promise:
      return SLAPGRID_PROMISE_FAIL
    return SLAPGRID_SUCCESS
Łukasz Nowak's avatar
Łukasz Nowak committed
807

808 809 810 811 812
  def validateXML(self, to_be_validated, xsd_model):
    """Validates a given xml file"""
    #We retrieve the xsd model
    xsd_model = StringIO.StringIO(xsd_model)
    xmlschema_doc = etree.parse(xsd_model)
Łukasz Nowak's avatar
Łukasz Nowak committed
813 814
    xmlschema = etree.XMLSchema(xmlschema_doc)

815
    try:
816
      document = etree.fromstring(to_be_validated)
Marco Mariani's avatar
Marco Mariani committed
817
    except (etree.XMLSyntaxError, etree.DocumentInvalid) as exc:
Marco Mariani's avatar
Marco Mariani committed
818 819
      self.logger.info('Failed to parse this XML report :  %s\n%s' %
                          (to_be_validated, _formatXMLError(exc)))
820
      self.logger.error(_formatXMLError(exc))
821 822
      return False

Łukasz Nowak's avatar
Łukasz Nowak committed
823 824 825 826 827
    if xmlschema.validate(document):
      return True

    return False

828 829 830
  def asXML(self, computer_partition_usage_list):
    """Generates a XML report from computer partition usage list
    """
831 832 833 834 835 836 837 838 839 840 841 842 843 844
    xml = ['<?xml version="1.0"?>',
           '<journal>',
           '<transaction type="Sale Packing List">',
           '<title>Resource consumptions</title>',
           '<start_date></start_date>',
           '<stop_date>%s</stop_date>' % time.strftime("%Y-%m-%d at %H:%M:%S"),
           '<reference>%s</reference>' % self.computer_id,
           '<currency></currency>',
           '<payment_mode></payment_mode>',
           '<category></category>',
           '<arrow type="Administration">',
           '<source></source>',
           '<destination></destination>',
           '</arrow>']
845 846 847

    for computer_partition_usage in computer_partition_usage_list:
      try:
848
        root = etree.fromstring(computer_partition_usage.usage)
Marco Mariani's avatar
Marco Mariani committed
849
      except UnicodeError as exc:
850
        self.logger.info("Failed to read %s." % computer_partition_usage.usage)
851
        self.logger.error(UnicodeError)
Marco Mariani's avatar
Marco Mariani committed
852 853
        raise UnicodeError("Failed to read %s: %s" % (computer_partition_usage.usage, exc))
      except (etree.XMLSyntaxError, etree.DocumentInvalid) as exc:
Cédric de Saint Martin's avatar
YATTA  
Cédric de Saint Martin committed
854
        self.logger.info("Failed to parse %s." % (computer_partition_usage.usage))
Marco Mariani's avatar
Marco Mariani committed
855 856 857 858
        self.logger.error(exc)
        raise _formatXMLError(exc)
      except Exception as exc:
        raise Exception("Failed to generate XML report: %s" % exc)
859 860

      for movement in root.findall('movement'):
861 862 863 864
        xml.append('<movement>')
        for child in movement.getchildren():
          if child.tag == "reference":
            xml.append('<%s>%s</%s>' % (child.tag, computer_partition_usage.getId(), child.tag))
865
          else:
866 867
            xml.append('<%s>%s</%s>' % (child.tag, child.text, child.tag))
        xml.append('</movement>')
868

869
    xml.append('</transaction></journal>')
870

871
    return ''.join(xml)
872

Łukasz Nowak's avatar
Łukasz Nowak committed
873 874 875
  def agregateAndSendUsage(self):
    """Will agregate usage from each Computer Partition.
    """
876 877 878 879
    # Prepares environment
    self.checkEnvironmentAndCreateStructure()
    self._launchSupervisord()

Łukasz Nowak's avatar
Łukasz Nowak committed
880 881
    slap_computer_usage = self.slap.registerComputer(self.computer_id)
    computer_partition_usage_list = []
882
    self.logger.info('Aggregating and sending usage reports...')
Łukasz Nowak's avatar
Łukasz Nowak committed
883

884 885 886 887 888 889 890 891 892
    #We retrieve XSD models
    try:
      computer_consumption_model = \
        pkg_resources.resource_string(
          'slapos.slap',
          'doc/computer_consumption.xsd')
    except IOError:
      computer_consumption_model = \
        pkg_resources.resource_string(
893
          __name__,
894 895 896 897 898 899 900 901 902 903
          '../../../../slapos/slap/doc/computer_consumption.xsd')

    try:
      partition_consumption_model = \
        pkg_resources.resource_string(
          'slapos.slap',
          'doc/partition_consumption.xsd')
    except IOError:
      partition_consumption_model = \
        pkg_resources.resource_string(
904
          __name__,
905 906
          '../../../../slapos/slap/doc/partition_consumption.xsd')

Łukasz Nowak's avatar
Łukasz Nowak committed
907
    clean_run = True
908
    # Loop over the different computer partitions
909 910
    computer_partition_list = self.FilterComputerPartitionList(
       slap_computer_usage.getComputerPartitionList())
911

912
    for computer_partition in computer_partition_list:
913 914
      try:
        computer_partition_id = computer_partition.getId()
915

916
        # We want to execute all the script in the report folder
917 918 919 920 921 922 923
        instance_path = os.path.join(self.instance_root,
            computer_partition.getId())
        report_path = os.path.join(instance_path, 'etc', 'report')
        if os.path.isdir(report_path):
          script_list_to_run = os.listdir(report_path)
        else:
          script_list_to_run = []
Marco Mariani's avatar
Marco Mariani committed
924

925
        # We now generate the pseudorandom name for the xml file
926 927 928 929 930
        # and we add it in the invocation_list
        f = tempfile.NamedTemporaryFile()
        name_xml = '%s.%s' % ('slapreport', os.path.basename(f.name))
        path_to_slapreport = os.path.join(instance_path, 'var', 'xml_report',
            name_xml)
Marco Mariani's avatar
Marco Mariani committed
931

932 933 934 935 936
        failed_script_list = []
        for script in script_list_to_run:
          invocation_list = []
          invocation_list.append(os.path.join(instance_path, 'etc', 'report',
            script))
937
          # We add the xml_file name to the invocation_list
938 939 940
          #f = tempfile.NamedTemporaryFile()
          #name_xml = '%s.%s' % ('slapreport', os.path.basename(f.name))
          #path_to_slapreport = os.path.join(instance_path, 'var', name_xml)
Marco Mariani's avatar
Marco Mariani committed
941

942
          invocation_list.append(path_to_slapreport)
943
          # Dropping privileges
944 945 946 947 948 949
          uid, gid = None, None
          stat_info = os.stat(instance_path)
          #stat sys call to get statistics informations
          uid = stat_info.st_uid
          gid = stat_info.st_gid
          process_handler = SlapPopen(invocation_list,
950
                                      preexec_fn=lambda: dropPrivileges(uid, gid, logger=self.logger),
Marco Mariani's avatar
Marco Mariani committed
951 952
                                      cwd=os.path.join(instance_path, 'etc', 'report'),
                                      env=None,
Marco Mariani's avatar
Marco Mariani committed
953
                                      stdout=subprocess.PIPE,
954 955
                                      stderr=subprocess.STDOUT,
                                      logger=self.logger)
956 957 958 959
          if process_handler.returncode is None:
            process_handler.kill()
          if process_handler.returncode != 0:
            clean_run = False
960
            failed_script_list.append("Script %r failed." % script)
961
            self.logger.warning('Failed to run %r' % invocation_list)
962
          if len(failed_script_list):
963
            computer_partition.error('\n'.join(failed_script_list), logger=self.logger)
964 965
      # Whatever happens, don't stop processing other instances
      except Exception:
966 967
        self.logger.exception('Cannot run usage script(s) for %r:' %
                                  computer_partition.getId())
Łukasz Nowak's avatar
Łukasz Nowak committed
968

969
    # Now we loop through the different computer partitions to report
Łukasz Nowak's avatar
Łukasz Nowak committed
970
    report_usage_issue_cp_list = []
971
    for computer_partition in computer_partition_list:
972 973 974 975
      try:
        filename_delete_list = []
        computer_partition_id = computer_partition.getId()
        instance_path = os.path.join(self.instance_root, computer_partition_id)
976 977 978 979 980 981 982 983 984
        dir_report_list = [os.path.join(instance_path, 'var', 'xml_report'),
            os.path.join(self.instance_root, 'var', 'xml_report', 
                         computer_partition_id)]
        
        for dir_reports in dir_report_list:
          # The directory xml_report contain a number of files equal
          # to the number of software instance running inside the same partition
          if os.path.isdir(dir_reports):
            filename_list = os.listdir(dir_reports)
985
          else:
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
            filename_list = []
          # self.logger.debug('name List %s' % filename_list)

          for filename in filename_list:

            file_path = os.path.join(dir_reports, filename)
            if os.path.exists(file_path):
              usage = open(file_path, 'r').read()

              # We check the validity of xml content of each reports
              if not self.validateXML(usage, partition_consumption_model):
                self.logger.info('WARNING: The XML file %s generated by slapreport is '
                                 'not valid - This report is left as is at %s where you can '
                                 'inspect what went wrong ' % (filename, dir_reports))
                # Warn the SlapOS Master that a partition generates corrupted xml
                # report
              else:
                computer_partition_usage = self.slap.registerComputerPartition(
                    self.computer_id, computer_partition_id)
                computer_partition_usage.setUsage(usage)
                computer_partition_usage_list.append(computer_partition_usage)
                filename_delete_list.append(filename)
            else:
              self.logger.debug('Usage report %r not found, ignored' % file_path)
Łukasz Nowak's avatar
Łukasz Nowak committed
1010

1011 1012 1013
          # After sending the aggregated file we remove all the valid xml reports
          for filename in filename_delete_list:
            os.remove(os.path.join(dir_reports, filename))
1014 1015 1016

      # Whatever happens, don't stop processing other instances
      except Exception:
1017 1018
        self.logger.exception('Cannot run usage script(s) for %r:' %
                                computer_partition.getId())
1019 1020

    for computer_partition_usage in computer_partition_usage_list:
Marco Mariani's avatar
Marco Mariani committed
1021 1022
      self.logger.info('computer_partition_usage_list: %s - %s' %
                       (computer_partition_usage.usage, computer_partition_usage.getId()))
1023

1024
    # If there is, at least, one report
1025
    if computer_partition_usage_list != []:
Łukasz Nowak's avatar
Łukasz Nowak committed
1026
      try:
1027
        # We generate the final XML report with asXML method
1028 1029
        computer_consumption = self.asXML(computer_partition_usage_list)

1030
        self.logger.info('Final xml report: %s' % computer_consumption)
1031

1032
        # We test the XML report before sending it
1033
        if self.validateXML(computer_consumption, computer_consumption_model):
1034
          self.logger.info('XML file generated by asXML is valid')
1035 1036
          slap_computer_usage.reportUsage(computer_consumption)
        else:
1037
          self.logger.info('XML file generated by asXML is not valid !')
1038
          raise ValueError('XML file generated by asXML is not valid !')
Łukasz Nowak's avatar
Łukasz Nowak committed
1039
      except Exception:
1040
        issue = "Cannot report usage for %r: %s" % (
Marco Mariani's avatar
Marco Mariani committed
1041 1042
            computer_partition.getId(),
            traceback.format_exc())
1043
        self.logger.info(issue)
1044
        computer_partition.error(issue, logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
1045 1046
        report_usage_issue_cp_list.append(computer_partition_id)

1047
    for computer_partition in computer_partition_list:
1048
      if computer_partition.getState() == COMPUTER_PARTITION_DESTROYED_STATE:
Łukasz Nowak's avatar
Łukasz Nowak committed
1049
        try:
1050
          computer_partition_id = computer_partition.getId()
1051
          try:
1052 1053
            software_url = computer_partition.getSoftwareRelease().getURI()
            software_path = os.path.join(self.software_root, md5digest(software_url))
1054 1055 1056
          except (NotFoundError, TypeError):
            software_url = None
            software_path = None
1057

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
          local_partition = Partition(
            software_path=software_path,
            instance_path=os.path.join(self.instance_root,
                computer_partition.getId()),
            supervisord_partition_configuration_path=os.path.join(
              self.supervisord_configuration_directory, '%s.conf' %
              computer_partition_id),
            supervisord_socket=self.supervisord_socket,
            computer_partition=computer_partition,
            computer_id=self.computer_id,
            partition_id=computer_partition_id,
            server_url=self.master_url,
            software_release_url=software_url,
            certificate_repository_path=self.certificate_repository_path,
1072
            buildout=self.buildout,
1073
            logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
1074 1075 1076 1077
          local_partition.stop()
          try:
            computer_partition.stopped()
          except (SystemExit, KeyboardInterrupt):
1078
            computer_partition.error(traceback.format_exc(), logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
1079 1080 1081
            raise
          except Exception:
            pass
1082
          if computer_partition.getId() in report_usage_issue_cp_list:
1083 1084
            self.logger.info('Ignoring destruction of %r, as no report usage was sent' %
                                computer_partition.getId())
1085 1086
            continue
          local_partition.destroy()
Łukasz Nowak's avatar
Łukasz Nowak committed
1087
        except (SystemExit, KeyboardInterrupt):
1088
          computer_partition.error(traceback.format_exc(), logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
1089 1090 1091
          raise
        except Exception:
          clean_run = False
1092
          self.logger.exception('')
Marco Mariani's avatar
Marco Mariani committed
1093
          exc = traceback.format_exc()
1094
          computer_partition.error(exc, logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
1095 1096
        try:
          computer_partition.destroyed()
Marco Mariani's avatar
Marco Mariani committed
1097
        except NotFoundError:
1098 1099 1100
          self.logger.debug('Ignored slap error while trying to inform about '
                            'destroying not fully configured Computer Partition %r' %
                                computer_partition.getId())
1101
        except ServerError as server_error:
1102 1103 1104
          self.logger.debug('Ignored server error while trying to inform about '
                            'destroying Computer Partition %r. Error is:\n%r' %
                                (computer_partition.getId(), server_error.args[0]))
Łukasz Nowak's avatar
Łukasz Nowak committed
1105

1106
    self.logger.info('Finished usage reports.')
1107 1108 1109 1110 1111

    # Return success value
    if not clean_run:
      return SLAPGRID_FAIL
    return SLAPGRID_SUCCESS