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

Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
30 31 32 33
import argparse
import ConfigParser
from hashlib import md5
from lxml import etree
Łukasz Nowak's avatar
Łukasz Nowak committed
34 35 36
import logging
import os
import pkg_resources
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
37 38 39 40 41 42 43 44
from random import random
import socket
import subprocess
import StringIO
import sys
import tempfile
import time
import traceback
Łukasz Nowak's avatar
Łukasz Nowak committed
45 46 47 48 49
import warnings
if sys.version_info < (2, 6):
  warnings.warn('Used python version (%s) is old and have problems with'
      ' IPv6 connections' % sys.version.split('\n')[0])

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
Łukasz Nowak's avatar
Łukasz Nowak committed
52 53
from SlapObject import Software, Partition, WrongPermissionError, \
    PathDoesNotExistError
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
54
from svcbackend import launchSupervisord
Łukasz Nowak's avatar
Łukasz Nowak committed
55
from utils import createPrivateDirectory
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
56 57
from utils import dropPrivileges
from utils import getSoftwareUrlHash
Łukasz Nowak's avatar
Łukasz Nowak committed
58 59 60
from utils import setRunning
from utils import setFinished
from utils import SlapPopen
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
61 62
from utils import updateFile
from slapos import slap
Łukasz Nowak's avatar
Łukasz Nowak committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

MANDATORY_PARAMETER_LIST = [
    'computer_id',
    'instance_root',
    'master_url',
    'software_root',
]


def parseArgumentTupleAndReturnSlapgridObject(*argument_tuple):
  """Parses arguments either from command line, from method parameters or from
     config file. Then returns a new instance of slapgrid.Slapgrid with those
     parameters. Also returns the options dict and unused variable list, and
     configures logger.
  """
  parser = argparse.ArgumentParser()
  parser.add_argument("--instance-root",
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
80
      help="The instance root directory location.")
Łukasz Nowak's avatar
Łukasz Nowak committed
81
  parser.add_argument("--software-root",
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
82
      help="The software_root directory location.")
Łukasz Nowak's avatar
Łukasz Nowak committed
83
  parser.add_argument("--master-url",
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
84
      help="The master server URL. Mandatory.")
Łukasz Nowak's avatar
Łukasz Nowak committed
85
  parser.add_argument("--computer-id",
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
86
      help="The computer id defined in the server.")
Łukasz Nowak's avatar
Łukasz Nowak committed
87
  parser.add_argument("--supervisord-socket",
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
88
      help="The socket supervisor will use.")
Łukasz Nowak's avatar
Łukasz Nowak committed
89
  parser.add_argument("--supervisord-configuration-path",
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
90 91 92
      help="The location where supervisord configuration will be stored.")
  parser.add_argument("--buildout", default=None,
      help="Location of buildout binary.")
Łukasz Nowak's avatar
Łukasz Nowak committed
93
  parser.add_argument("--pidfile",
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
94
      help="The location where pidfile will be created.")
Łukasz Nowak's avatar
Łukasz Nowak committed
95
  parser.add_argument("--logfile",
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
96
      help="The location where slapgrid logfile will be created.")
Łukasz Nowak's avatar
Łukasz Nowak committed
97 98 99
  parser.add_argument("--key_file", help="SSL Authorisation key file.")
  parser.add_argument("--cert_file",
      help="SSL Authorisation certificate file.")
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
100 101 102 103
  parser.add_argument("--signature_private_key_file",
      help="Signature private key file.")
  parser.add_argument("--master_ca_file",
      help="Root certificate of SlapOS master key.")
Łukasz Nowak's avatar
Łukasz Nowak committed
104 105 106 107 108 109
  parser.add_argument("--certificate_repository_path",
      help="Path to directory where downloaded certificates would be stored.")
  parser.add_argument("-c", "--console", action="store_true", default=False,
      help="Enables console output and live output from subcommands.")
  parser.add_argument("-v", "--verbose", action="store_true", default=False,
      help="Be verbose.")
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
110 111
  parser.add_argument("--promise-timeout", type=int, default=3,
      help="Promise timeout in seconds.")
Łukasz Nowak's avatar
Łukasz Nowak committed
112 113
  parser.add_argument("configuration_file", nargs=1, type=argparse.FileType(),
      help="SlapOS configuration file.")
114 115
  parser.add_argument("--maximal_delay", help="The maximal delay value in seconds. " \
                    "A negative value leads start immediately.")
Yingjie Xu's avatar
Yingjie Xu committed
116
  parser.add_argument("--now", action="store_true", default=False,
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
117
      help="Launch slapgrid without delay.")
118
  parser.add_argument("--develop", action="store_true", default=False,
119
      help="Deprecated, same as --all.")
120 121 122
  parser.add_argument("--all", action="store_true", default=False,
      help="Launch slapgrid to process all Softare Releases"
           "and/or Computer Partitions.")
Cédric de Saint Martin's avatar
lkj  
Cédric de Saint Martin committed
123
  parser.add_argument("--only_sr",
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
124 125 126
      help="Force the update of a single software release (use url hash),"
           "event if is already installed. This option will make all others "
           "sofware releases be ignored.")
127
  parser.add_argument("--only_cp",
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
128 129 130
      help="Update a single or a list of computer partitions "
           "(ie.:slappartX, slappartY),"
           "this option will make all others computer partitions be ignored.")
Łukasz Nowak's avatar
Łukasz Nowak committed
131

132

Łukasz Nowak's avatar
Łukasz Nowak committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
  # Parses arguments
  if argument_tuple == ():
    # No arguments given to entry point : we parse sys.argv.
    argument_option_instance = parser.parse_args()
  else:
    argument_option_instance = \
      parser.parse_args(list(argument_tuple))
  # Parses arguments from config file, if needed, then merge previous arguments
  option_dict = {}
  configuration_file = argument_option_instance.configuration_file[0]
  # Loads config (if config specified)
  slapgrid_configuration = ConfigParser.SafeConfigParser()
  slapgrid_configuration.readfp(configuration_file)
  # Merges the two dictionnaries
  option_dict = dict(slapgrid_configuration.items("slapos"))
148 149
  if slapgrid_configuration.has_section("networkcache"):
    option_dict.update(dict(slapgrid_configuration.items("networkcache")))
Łukasz Nowak's avatar
Łukasz Nowak committed
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
  for argument_key, argument_value in vars(argument_option_instance
      ).iteritems():
    if argument_value is not None:
      option_dict.update({argument_key: argument_value})
  # Configures logger.
  logger_format = '%(asctime)s %(name)-18s: %(levelname)-8s %(message)s'
  if option_dict['verbose']:
    level = logging.DEBUG
  else:
    level = logging.INFO
  if option_dict.get('logfile'):
    logging.basicConfig(filename=option_dict['logfile'],
      format=logger_format, level=level)
  if option_dict['console']:
    logging.basicConfig(level=level)
  missing_mandatory_parameter_list = []
  for mandatory_parameter in MANDATORY_PARAMETER_LIST:
    if not mandatory_parameter in option_dict:
      missing_mandatory_parameter_list.append(mandatory_parameter)

170
  if 'all' in option_dict:
171
    option_dict['develop'] = True
172

Łukasz Nowak's avatar
Łukasz Nowak committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  repository_required = False
  if 'key_file' in option_dict:
    repository_required = True
    if not 'cert_file' in option_dict:
      missing_mandatory_parameter_list.append('cert_file')
  if 'cert_file' in option_dict:
    repository_required = True
    if not 'key_file' in option_dict:
      missing_mandatory_parameter_list.append('key_file')
  if repository_required:
    if 'certificate_repository_path' not in option_dict:
      missing_mandatory_parameter_list.append('certificate_repository_path')

  if len(missing_mandatory_parameter_list) > 0:
    parser.error('Missing mandatory parameters:\n%s' % '\n'.join(
      missing_mandatory_parameter_list))

  key_file = option_dict.get('key_file')
  cert_file = option_dict.get('cert_file')
  master_ca_file = option_dict.get('master_ca_file')
193 194 195 196 197 198 199 200
  signature_private_key_file = option_dict.get('signature_private_key_file')

  mandatory_file_list = [key_file, cert_file, master_ca_file]
  # signature_private_key_file is not mandatory, we must be able to run
  # slapgrid scripts without this parameter.
  if signature_private_key_file:
    mandatory_file_list.append(signature_private_key_file)

201 202 203 204
  for k in ['shacache-cert-file', 'shacache-key-file', 'shadir-cert-file',
      'shadir-key-file']:
    mandatory_file_list.append(option_dict.get(k, None))

205
  for f in mandatory_file_list:
206 207
    if f is not None:
      if not os.path.exists(f):
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
208
        parser.error('File %r does not exist.' % f)
Łukasz Nowak's avatar
Łukasz Nowak committed
209 210 211 212

  certificate_repository_path = option_dict.get('certificate_repository_path')
  if certificate_repository_path is not None:
    if not os.path.isdir(certificate_repository_path):
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
213
      parser.error('Directory %r does not exist' %
Łukasz Nowak's avatar
Łukasz Nowak committed
214 215 216 217 218 219 220 221 222 223
          certificate_repository_path)

  # Supervisord configuration location
  if not option_dict.get('supervisord_configuration_path'):
    option_dict['supervisord_configuration_path'] = \
      os.path.join(option_dict['instance_root'], 'etc', 'supervisord.conf')
  # Supervisord socket
  if not option_dict.get('supervisord_socket'):
    option_dict['supervisord_socket'] = \
      os.path.join(option_dict['instance_root'], 'supervisord.socket')
Yingjie Xu's avatar
Yingjie Xu committed
224 225 226 227 228 229 230 231 232 233 234

  signature_certificate_list_string = \
    option_dict.get('signature-certificate-list', None)
  if signature_certificate_list_string is not None:
    cert_marker = "-----BEGIN CERTIFICATE-----"
    signature_certificate_list = [cert_marker + '\n' + q.strip() \
      for q in signature_certificate_list_string.split(cert_marker) \
        if q.strip()]
  else:
    signature_certificate_list = None

235 236 237 238 239
  # Parse cache / binary options
  option_dict["binary-cache-url-blacklist"] = [
      url.strip() for url in option_dict.get("binary-cache-url-blacklist", ""
          ).split('\n') if url]

240 241
  # Sleep for a random time to avoid SlapOS Master being DDOSed by an army of
  # SlapOS Nodes configured with cron.
Yingjie Xu's avatar
Yingjie Xu committed
242 243 244
  if option_dict["now"]:
    maximal_delay = 0
  else:
245
    maximal_delay = int(option_dict.get("maximal_delay", "300"))
246
  if maximal_delay > 0:
Yingjie Xu's avatar
Yingjie Xu committed
247
    duration = int(maximal_delay * random())
248 249 250 251
    logging.info("Sleeping for %s seconds. To disable this feature, " \
                    "check maximal_delay parameter in manual." % duration)
    time.sleep(duration)

252
  # Return new Slapgrid instance and options
Łukasz Nowak's avatar
Łukasz Nowak committed
253 254 255 256 257 258 259 260 261 262 263
  return ([Slapgrid(software_root=option_dict['software_root'],
            instance_root=option_dict['instance_root'],
            master_url=option_dict['master_url'],
            computer_id=option_dict['computer_id'],
            supervisord_socket=option_dict['supervisord_socket'],
            supervisord_configuration_path=option_dict[
              'supervisord_configuration_path'],
            key_file=key_file,
            cert_file=cert_file,
            master_ca_file=master_ca_file,
            certificate_repository_path=certificate_repository_path,
264
            signature_private_key_file=signature_private_key_file,
Yingjie Xu's avatar
Yingjie Xu committed
265 266 267 268 269
            signature_certificate_list=signature_certificate_list,
            download_binary_cache_url=\
              option_dict.get('download-binary-cache-url', None),
            upload_binary_cache_url=\
              option_dict.get('upload-binary-cache-url', None),
270 271
            binary_cache_url_blacklist=\
                option_dict.get('binary-cache-url-blacklist', []),
272
            upload_cache_url=option_dict.get('upload-cache-url', None),
Yingjie Xu's avatar
Yingjie Xu committed
273 274 275 276
            download_binary_dir_url=\
              option_dict.get('download-binary-dir-url', None),
            upload_binary_dir_url=\
              option_dict.get('upload-binary-dir-url', None),
277
            upload_dir_url=option_dict.get('upload-dir-url', None),
278
            console=option_dict['console'],
279
            buildout=option_dict.get('buildout'),
280 281 282 283 284
            promise_timeout=option_dict['promise_timeout'],
            shacache_cert_file=option_dict.get('shacache-cert-file', None),
            shacache_key_file=option_dict.get('shacache-key-file', None),
            shadir_cert_file=option_dict.get('shadir-cert-file', None),
            shadir_key_file=option_dict.get('shadir-key-file', None),
285 286 287
            develop=option_dict.get('develop', False),
            software_release_filter_list=option_dict.get('only_sr', None),
            computer_partition_filter_list=option_dict.get('only_cp', None),
288
            ),
Łukasz Nowak's avatar
Łukasz Nowak committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
          option_dict])


def realRun(argument_tuple, method_list):
  clean_run = True
  slapgrid_object, option_dict = \
      parseArgumentTupleAndReturnSlapgridObject(*argument_tuple)
  pidfile = option_dict.get('pidfile')
  if pidfile:
    setRunning(pidfile)
  try:
    for method in method_list:
      if not getattr(slapgrid_object, method)():
        clean_run = False
  finally:
    if pidfile:
      setFinished(pidfile)
  if clean_run:
    sys.exit(0)
  else:
    sys.exit(1)


def run(*argument_tuple):
  """Hooks for generic entry point to proces Software Releases (sr),
     Computer Partitions (cp) and Usage Reports (ur)
     Will run one by one each task (sr, cp, ur). If specified,
     will run in the user wanted order.
  """
  realRun(argument_tuple, ['processSoftwareReleaseList',
    'processComputerPartitionList', 'agregateAndSendUsage'])


def runSoftwareRelease(*argument_tuple):
  """Hook for entry point to process Software Releases only
  """
  realRun(argument_tuple, ['processSoftwareReleaseList'])


def runComputerPartition(*argument_tuple):
  """Hook for entry point to process Computer Partitions only
  """
  realRun(argument_tuple, ['processComputerPartitionList'])


def runUsageReport(*argument_tuple):
  """Hook for entry point to process Usage Reports only
  """
  realRun(argument_tuple, ['agregateAndSendUsage'])


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
344 345 346 347

  class PromiseError(Exception):
    pass

Łukasz Nowak's avatar
Łukasz Nowak committed
348 349 350 351 352 353 354
  def __init__(self,
               software_root,
               instance_root,
               master_url,
               computer_id,
               supervisord_socket,
               supervisord_configuration_path,
355
               buildout,
Łukasz Nowak's avatar
Łukasz Nowak committed
356 357
               key_file=None,
               cert_file=None,
358
               signature_private_key_file=None,
Yingjie Xu's avatar
Yingjie Xu committed
359 360 361
               signature_certificate_list=None,
               download_binary_cache_url=None,
               upload_binary_cache_url=None,
362
               binary_cache_url_blacklist=None,
363
               upload_cache_url=None,
Yingjie Xu's avatar
Yingjie Xu committed
364 365
               download_binary_dir_url=None,
               upload_binary_dir_url=None,
366
               upload_dir_url=None,
Łukasz Nowak's avatar
Łukasz Nowak committed
367 368
               master_ca_file=None,
               certificate_repository_path=None,
369
               console=False,
370 371 372 373
               promise_timeout=3,
               shacache_cert_file=None,
               shacache_key_file=None,
               shadir_cert_file=None,
374
               shadir_key_file=None,
375
               develop=False,
376 377
               software_release_filter_list=None,
               computer_partition_filter_list=None):
Łukasz Nowak's avatar
Łukasz Nowak committed
378 379 380 381 382 383 384 385 386 387 388 389
    """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
390
    self.signature_private_key_file = signature_private_key_file
Yingjie Xu's avatar
Yingjie Xu committed
391 392 393
    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
394
    self.binary_cache_url_blacklist = binary_cache_url_blacklist
395
    self.upload_cache_url = upload_cache_url
Yingjie Xu's avatar
Yingjie Xu committed
396 397
    self.download_binary_dir_url = download_binary_dir_url
    self.upload_binary_dir_url = upload_binary_dir_url
398
    self.upload_dir_url = upload_dir_url
399 400 401 402
    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
Łukasz Nowak's avatar
Łukasz Nowak committed
403 404 405 406 407 408 409 410 411 412 413 414
    # Configures logger
    self.logger = logging.getLogger('Slapgrid')
    # Creates objects from slap module
    self.slap = slap.slap()
    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.instance_etc_directory = os.path.join(self.instance_root, 'etc')
    self.supervisord_configuration_directory = \
        os.path.join(self.instance_etc_directory, 'supervisord.conf.d')
    self.console = console
415
    self.buildout = buildout
416
    self.promise_timeout = promise_timeout
417
    self.develop = develop
418
    if software_release_filter_list is not None:
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
419 420
      self.software_release_filter_list = \
          software_release_filter_list.split(",")
421
    else:
422
      self.software_release_filter_list = []
423 424
    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
425 426
      self.computer_partition_filter_list = \
          computer_partition_filter_list.split(",")
Łukasz Nowak's avatar
Łukasz Nowak committed
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450

  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):
      error = "%s does not exist." % self.software_root
      raise OSError(error)
    if not os.path.isdir(self.instance_root):
      error = "%s does not exist." % self.instance_root
      raise OSError(error)
    # Creates everything needed
    try:
      # Creates instance_root structure
      createPrivateDirectory(self.instance_etc_directory)
      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'))
      createPrivateDirectory(self.supervisord_configuration_directory)
      # Creates supervisord configuration
      updateFile(self.supervisord_configuration_path,
        pkg_resources.resource_stream(__name__,
          'templates/supervisord.conf.in').read() % dict(
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
451 452
            supervisord_configuration_directory=\
                self.supervisord_configuration_directory,
Łukasz Nowak's avatar
Łukasz Nowak committed
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
            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',
          ))
    except (WrongPermissionError, PathDoesNotExistError) as error:
      raise error

  def getComputerPartitionList(self):
    try:
      computer_partition_list = self.computer.getComputerPartitionList()
    except socket.error as error:
      self.logger.fatal(error)
471
      raise
Łukasz Nowak's avatar
Łukasz Nowak committed
472 473 474 475 476 477 478 479 480 481
    return computer_partition_list

  def processSoftwareReleaseList(self):
    """Will process each Software Release.
    """
    self.checkEnvironmentAndCreateStructure()
    logger = logging.getLogger('SoftwareReleases')
    logger.info("Processing software releases...")
    clean_run = True
    for software_release in self.computer.getSoftwareReleaseList():
Łukasz Nowak's avatar
Łukasz Nowak committed
482
      state = software_release.getState()
Łukasz Nowak's avatar
Łukasz Nowak committed
483 484
      try:
        software_release_uri = software_release.getURI()
485 486
        url_hash = md5(software_release_uri).hexdigest()
        software_path = os.path.join(self.software_root, url_hash)
Łukasz Nowak's avatar
Łukasz Nowak committed
487 488
        software = Software(url=software_release_uri,
            software_root=self.software_root,
489
            console=self.console, buildout=self.buildout,
490
            signature_private_key_file=self.signature_private_key_file,
Yingjie Xu's avatar
Yingjie Xu committed
491 492 493
            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,
494
            binary_cache_url_blacklist=self.binary_cache_url_blacklist,
495
            upload_cache_url=self.upload_cache_url,
Yingjie Xu's avatar
Yingjie Xu committed
496 497
            download_binary_dir_url=self.download_binary_dir_url,
            upload_binary_dir_url=self.upload_binary_dir_url,
498 499 500 501
            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
502 503
            shadir_key_file=self.shadir_key_file)
        if state == 'available':
504
          completed_tag = os.path.join(software_path, '.completed')
505
          if self.develop or (not os.path.exists(completed_tag) and \
506 507
                 len(self.software_release_filter_list) == 0) or \
             url_hash in self.software_release_filter_list:
508 509 510 511 512 513 514 515
            try:
              software_release.building()
            except NotFoundError:
              pass
            software.install()
            file_descriptor = open(completed_tag, 'w')
            file_descriptor.write(time.asctime())
            file_descriptor.close()
Łukasz Nowak's avatar
Łukasz Nowak committed
516
        elif state == 'destroyed':
517 518 519 520
          if os.path.exists(software_path):
            logger.info('Destroying %r...' % software_release_uri)
            software.destroy()
            logger.info('Destroyed %r.' % software_release_uri)
Łukasz Nowak's avatar
Łukasz Nowak committed
521 522 523 524 525 526 527 528 529 530
      except (SystemExit, KeyboardInterrupt):
        exception = traceback.format_exc()
        software_release.error(exception)
        raise
      except Exception:
        exception = traceback.format_exc()
        logger.error(exception)
        software_release.error(exception)
        clean_run = False
      else:
Łukasz Nowak's avatar
Łukasz Nowak committed
531
        if state == 'available':
532 533 534 535
          try:
            software_release.available()
          except NotFoundError:
            pass
Łukasz Nowak's avatar
Łukasz Nowak committed
536
        elif state == 'destroyed':
537 538 539 540
          try:
            software_release.destroyed()
          except NotFoundError:
            pass
Łukasz Nowak's avatar
Łukasz Nowak committed
541 542 543 544 545 546 547
    logger.info("Finished software releases...")
    return clean_run

  def _launchSupervisord(self):
    launchSupervisord(self.supervisord_socket,
        self.supervisord_configuration_path)

Antoine Catton's avatar
Antoine Catton committed
548
  def _checkPromises(self, computer_partition):
549
    self.logger.info("Checking promises...")
Antoine Catton's avatar
Antoine Catton committed
550 551 552 553 554 555 556 557 558 559
    instance_path = os.path.join(self.instance_root,
        computer_partition.getId())

    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

560
    promise_present = False
Antoine Catton's avatar
Antoine Catton committed
561 562 563 564 565 566 567 568
    # 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):
      cwd = instance_path
      promises_list = os.listdir(promise_dir)

      # Check whether every promise is kept
      for promise in promises_list:
569
        promise_present = True
Antoine Catton's avatar
Antoine Catton committed
570

Antoine Catton's avatar
Antoine Catton committed
571 572 573
        command = [os.path.join(promise_dir, promise)]

        promise = os.path.basename(command[0])
574
        self.logger.info("Checking promise %r.", promise)
Antoine Catton's avatar
Antoine Catton committed
575 576 577 578 579 580

        kw = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        process_handler = SlapPopen(command,
          preexec_fn=lambda: dropPrivileges(uid, gid),
          cwd=cwd,
Antoine Catton's avatar
Antoine Catton committed
581
          env={}, **kw)
Antoine Catton's avatar
Antoine Catton committed
582 583 584 585 586

        time.sleep(self.promise_timeout)


        if process_handler.poll() is None:
587
          process_handler.terminate()
Antoine Catton's avatar
Antoine Catton committed
588 589 590 591 592
          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
593 594
          else:
            stderr = 'Promise %r:' % promise + stderr
Antoine Catton's avatar
Antoine Catton committed
595 596
          raise Slapgrid.PromiseError(stderr)

Antoine Catton's avatar
Antoine Catton committed
597 598 599
    if not promise_present:
      self.logger.info("No promise.")

Antoine Catton's avatar
Antoine Catton committed
600

Łukasz Nowak's avatar
Łukasz Nowak committed
601 602 603 604 605 606 607 608 609 610 611 612
  def processComputerPartitionList(self):
    """Will start supervisord and process each Computer Partition.
    """
    logger = logging.getLogger('ComputerPartitionProcessing')
    logger.info("Processing computer partitions...")
    # Prepares environment
    self.checkEnvironmentAndCreateStructure()
    self._launchSupervisord()
    # Process Computer Partitions
    clean_run = True
    for computer_partition in self.getComputerPartitionList():
      computer_partition_id = computer_partition.getId()
613

614 615 616 617 618 619 620
      try:
        software_url = computer_partition.getSoftwareRelease().getURI()
        # XXX should test status as well. But getState() returns default value.
      except NotFoundError:
        # No Software Release information: skip.
        continue

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

627 628 629
      instance_path = os.path.join(self.instance_root, computer_partition_id)

      # Try to get partition timestamp (last modification date)
630
      timestamp_path = os.path.join(instance_path, '.timestamp')
631 632 633 634 635 636 637 638
      parameter_dict = computer_partition.getInstanceParameterDict()
      if 'timestamp' in parameter_dict:
        timestamp = parameter_dict['timestamp']
      else:
        timestamp = None

      # Check if timestamp from server is more recent than local one.
      # If not: it's not worth processing this partition (nothing has changed).
639 640
      if computer_partition_id not in self.computer_partition_filter_list and \
          (not self.develop) and os.path.exists(timestamp_path):
641
        old_timestamp = open(timestamp_path).read()
642
        if timestamp:
643 644 645 646
          try:
            if int(timestamp) <= int(old_timestamp):
              continue
          except ValueError:
647
            os.remove(timestamp_path)
Yingjie Xu's avatar
Yingjie Xu committed
648 649
            exception = traceback.format_exc()
            logger.error(exception)
650

Łukasz Nowak's avatar
Łukasz Nowak committed
651 652 653 654
      software_path = os.path.join(self.software_root,
            getSoftwareUrlHash(software_url))
      local_partition = Partition(
        software_path=software_path,
Yingjie Xu's avatar
Typo  
Yingjie Xu committed
655
        instance_path=instance_path,
Łukasz Nowak's avatar
Łukasz Nowak committed
656 657 658 659 660 661 662 663 664 665
        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,
666
        console=self.console, buildout=self.buildout)
Łukasz Nowak's avatar
Łukasz Nowak committed
667 668 669 670 671 672
      try:
        computer_partition_state = computer_partition.getState()
        if computer_partition_state == "started":
          local_partition.install()
          computer_partition.available()
          local_partition.start()
Antoine Catton's avatar
Antoine Catton committed
673
          self._checkPromises(computer_partition)
Łukasz Nowak's avatar
Łukasz Nowak committed
674 675 676 677 678 679 680
          computer_partition.started()
        elif computer_partition_state == "stopped":
          local_partition.install()
          computer_partition.available()
          local_partition.stop()
          computer_partition.stopped()
        elif computer_partition_state == "destroyed":
681
          local_partition.stop()
Łukasz Nowak's avatar
Łukasz Nowak committed
682
          try:
683
            computer_partition.stopped()
Łukasz Nowak's avatar
Łukasz Nowak committed
684 685 686 687 688
          except (SystemExit, KeyboardInterrupt):
            exception = traceback.format_exc()
            computer_partition.error(exception)
            raise
          except Exception:
689
            pass
Łukasz Nowak's avatar
Łukasz Nowak committed
690 691 692 693 694
        else:
          error_string = "Computer Partition %r has unsupported state: %s" % \
            (computer_partition_id, computer_partition_state)
          computer_partition.error(error_string)
          raise NotImplementedError(error_string)
695 696 697 698
        # If partition has been successfully processed, write timestamp
        if timestamp:
          timestamp_path = os.path.join(instance_path, '.timestamp')
          open(timestamp_path, 'w').write(timestamp)
Łukasz Nowak's avatar
Łukasz Nowak committed
699 700 701 702
      except (SystemExit, KeyboardInterrupt):
        exception = traceback.format_exc()
        computer_partition.error(exception)
        raise
703
      except Exception as exception:
Łukasz Nowak's avatar
Łukasz Nowak committed
704
        clean_run = False
705
        logger.error(traceback.format_exc())
706 707 708 709 710 711 712 713 714
        try:
          computer_partition.error(exception)
        except (SystemExit, KeyboardInterrupt):
          raise
        except Exception:
          exception = traceback.format_exc()
          logger.error('Problem during reporting error, continuing:\n' +
            exception)

715

Łukasz Nowak's avatar
Łukasz Nowak committed
716 717 718
    logger.info("Finished computer partitions...")
    return clean_run

719 720
  def validateXML(self, to_be_validated, xsd_model):
    """Validates a given xml file"""
Łukasz Nowak's avatar
Łukasz Nowak committed
721

722 723 724 725 726
    logger = logging.getLogger('XMLValidating')

    #We retrieve the xsd model
    xsd_model = StringIO.StringIO(xsd_model)
    xmlschema_doc = etree.parse(xsd_model)
Łukasz Nowak's avatar
Łukasz Nowak committed
727 728 729
    xmlschema = etree.XMLSchema(xmlschema_doc)

    string_to_validate = StringIO.StringIO(to_be_validated)
730 731 732 733 734 735 736 737 738

    try:
      document = etree.parse(string_to_validate)
    except (etree.XMLSyntaxError, etree.DocumentInvalid) as e:
      logger.info('Failed to parse this XML report :  %s\n%s' % \
        (to_be_validated, _formatXMLError(e)))
      logger.error(_formatXMLError(e))
      return False

Łukasz Nowak's avatar
Łukasz Nowak committed
739 740 741 742 743
    if xmlschema.validate(document):
      return True

    return False

744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
  def asXML(self, computer_partition_usage_list):
    """Generates a XML report from computer partition usage list
    """
    xml_head = ""
    xml_movements = ""
    xml_foot = ""

    xml_head = "<?xml version='1.0' encoding='utf-8'?>" \
               "<journal>" \
               "<transaction type=\"Sale Packing List\">" \
               "<title>Resource consumptions</title>" \
               "<start_date></start_date>" \
               "<stop_date>%s</stop_date>" \
               "<reference>%s</reference>" \
               "<currency></currency>" \
               "<payment_mode></payment_mode>" \
               "<category></category>" \
               "<arrow type=\"Administration\">" \
               "<source></source>" \
               "<destination></destination>" \
               "</arrow>" \
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
765
               % (time.strftime("%Y-%m-%d at %H:%M:%S"),
766 767 768 769 770 771 772
                  self.computer_id)

    for computer_partition_usage in computer_partition_usage_list:
      try:
        usage_string = StringIO.StringIO(computer_partition_usage.usage)
        root = etree.parse(usage_string)
      except UnicodeError:
773 774 775
        self.logger.info("Failed to read %s." % (
            computer_partition_usage.usage))
        self.logger.error(UnicodeError)
776 777
        raise "Failed to read %s." % (computer_partition_usage.usage)
      except (etree.XMLSyntaxError, etree.DocumentInvalid) as e:
778 779
        self.logger.info("Failed to parse %s." % (usage_string))
        self.logger.error(e)
780 781 782 783 784 785 786 787
        raise _formatXMLError(e)
      except Exception:
        raise "Failed to generate XML report."

      for movement in root.findall('movement'):
        xml_movements += "<movement>"
        for children in movement.getchildren():
          if children.tag == "reference":
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
788 789
            xml_movements += "<%s>%s</%s>" % (children.tag,
                computer_partition_usage.getId(), children.tag)
790
          else:
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
791 792
            xml_movements += "<%s>%s</%s>" % (children.tag, children.text,
                children.tag)
793
        xml_movements += "</movement>"
794 795 796 797 798 799 800

    xml_foot = "</transaction>" \
               "</journal>"

    xml = xml_head + xml_movements + xml_foot
    return xml

Łukasz Nowak's avatar
Łukasz Nowak committed
801 802 803 804 805 806 807 808
  def agregateAndSendUsage(self):
    """Will agregate usage from each Computer Partition.
    """
    slap_computer_usage = self.slap.registerComputer(self.computer_id)
    computer_partition_usage_list = []
    logger = logging.getLogger('UsageReporting')
    logger.info("Aggregating and sending usage reports...")

809 810 811 812 813 814 815 816 817
    #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(
818
          __name__,
819 820 821 822 823 824 825 826 827 828
          '../../../../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(
829
          __name__,
830 831
          '../../../../slapos/slap/doc/partition_consumption.xsd')

Łukasz Nowak's avatar
Łukasz Nowak committed
832 833
    clean_run = True
    #We loop on the different computer partitions
834 835
    computer_partition_list = slap_computer_usage.getComputerPartitionList()
    for computer_partition in computer_partition_list:
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
      try:
        computer_partition_id = computer_partition.getId()
        
        #We want execute all the script in the report folder
        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 = []
        
        #We now generate the pseudorandom name for the xml file
        # 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)
        
        failed_script_list = []
        for script in script_list_to_run:
          invocation_list = []
          invocation_list.append(os.path.join(instance_path, 'etc', 'report',
            script))
          #We add the xml_file name 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', name_xml)
        
          invocation_list.append(path_to_slapreport)
          #Dropping privileges
          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
          kw = dict()
          if not self.console:
            kw.update(stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
          process_handler = SlapPopen(invocation_list,
            preexec_fn=lambda: dropPrivileges(uid, gid),
            cwd=os.path.join(instance_path, 'etc', 'report'),
            env=None, **kw)
          result = process_handler.communicate()[0]
          if self.console:
            result = 'Please consult messages above'
          if process_handler.returncode is None:
            process_handler.kill()
          if process_handler.returncode != 0:
            clean_run = False
            failed_script_list.append("Script %r failed with %s." % (script,
                result))
            logger.warning("Failed to run %r, the result was. \n%s" %
              (invocation_list, result))
          if len(failed_script_list):
            computer_partition.error('\n'.join(failed_script_list))
      # Whatever happens, don't stop processing other instances
      except Exception:
        computer_partition_id = computer_partition.getId()
        exception = traceback.format_exc()
        issue = "Cannot run usage script(s) for %r: %s" % (
            computer_partition_id, exception)
        logger.info(issue)
Łukasz Nowak's avatar
Łukasz Nowak committed
899

Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
900
    #Now we loop through the different computer partitions to report
Łukasz Nowak's avatar
Łukasz Nowak committed
901
    report_usage_issue_cp_list = []
902
    for computer_partition in computer_partition_list:
903 904 905 906 907 908 909 910 911
      try:
        filename_delete_list = []
        computer_partition_id = computer_partition.getId()
        instance_path = os.path.join(self.instance_root, computer_partition_id)
        dir_reports = os.path.join(instance_path, 'var', 'xml_report')
        #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)
Łukasz Nowak's avatar
Łukasz Nowak committed
912
        else:
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
          filename_list = []
        #logger.debug('name List %s' % filename_list)
        usage = ''
        
        for filename in filename_list:
        
          file_path = os.path.join(dir_reports, filename)
          if os.path.exists(file_path):
            usage_file = open(file_path, 'r')
            usage = usage_file.read()
            usage_file.close()
        
            #We check the validity of xml content of each reports
            if not self.validateXML(usage, partition_consumption_model):
              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:
            logger.debug("Usage report %r not found, ignored" % file_path)
Łukasz Nowak's avatar
Łukasz Nowak committed
940

941 942 943 944 945 946 947 948 949 950 951
        #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))

      # Whatever happens, don't stop processing other instances
      except Exception:
        computer_partition_id = computer_partition.getId()
        exception = traceback.format_exc()
        issue = "Cannot run usage script(s) for %r: %s" % (
            computer_partition_id, exception)
        logger.info(issue)
952 953 954 955 956 957 958

    for computer_partition_usage in computer_partition_usage_list:
      logger.info('computer_partition_usage_list : %s - %s' % \
        (computer_partition_usage.usage, computer_partition_usage.getId()))

    #If there is, at least, one report
    if computer_partition_usage_list != []:
Łukasz Nowak's avatar
Łukasz Nowak committed
959
      try:
960 961 962 963 964 965 966 967 968 969 970 971
        #We generate the final XML report with asXML method
        computer_consumption = self.asXML(computer_partition_usage_list)

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

        #We test the XML report before sending it
        if self.validateXML(computer_consumption, computer_consumption_model):
          logger.info('XML file generated by asXML is valid')
          slap_computer_usage.reportUsage(computer_consumption)
        else:
          logger.info('XML file generated by asXML is not valid !')
          raise 'XML file generated by asXML is not valid !'
Łukasz Nowak's avatar
Łukasz Nowak committed
972 973 974 975 976 977 978 979 980
      except Exception:
        computer_partition_id = computer_partition.getId()
        exception = traceback.format_exc()
        issue = "Cannot report usage for %r: %s" % (computer_partition_id,
          exception)
        logger.info(issue)
        computer_partition.error(issue)
        report_usage_issue_cp_list.append(computer_partition_id)

981
    for computer_partition in computer_partition_list:
Łukasz Nowak's avatar
Łukasz Nowak committed
982 983 984 985 986 987 988
      computer_partition_id = computer_partition.getId()
      try:
        software_url = computer_partition.getSoftwareRelease().getURI()
      except NotFoundError:
        software_url = None
      if computer_partition.getState() == "destroyed":
        try:
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
          software_path = os.path.join(self.software_root,
                getSoftwareUrlHash(software_url))
          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,
            console=self.console, buildout=self.buildout
            )
Łukasz Nowak's avatar
Łukasz Nowak committed
1007 1008 1009 1010 1011 1012 1013 1014 1015
          local_partition.stop()
          try:
            computer_partition.stopped()
          except (SystemExit, KeyboardInterrupt):
            exception = traceback.format_exc()
            computer_partition.error(exception)
            raise
          except Exception:
            pass
1016 1017 1018 1019 1020
          if computer_partition.getId() in report_usage_issue_cp_list:
            logger.info('Ignoring destruction of %r, as not report usage was '
              'sent' % computer_partition.getId())
            continue
          local_partition.destroy()
Łukasz Nowak's avatar
Łukasz Nowak committed
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
        except (SystemExit, KeyboardInterrupt):
          exception = traceback.format_exc()
          computer_partition.error(exception)
          raise
        except Exception:
          clean_run = False
          exception = traceback.format_exc()
          computer_partition.error(exception)
          logger.error(exception)
        try:
          computer_partition.destroyed()
        except slap.NotFoundError:
          logger.debug('Ignored slap error while trying to inform about '
              'destroying not fully configured Computer Partition %r' %
                  computer_partition.getId())
1036 1037 1038 1039
        except ServerError as server_error:
          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
1040 1041 1042

    logger.info("Finished usage reports...")
    return clean_run