slapgrid.py 62 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
import json
44

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

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

Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
51 52
from slapos.slap.slap import NotFoundError
from slapos.slap.slap import ServerError
53
from slapos.slap.slap import COMPUTER_PARTITION_REQUEST_LIST_TEMPLATE_FILENAME
54
from slapos.util import mkdir_p, chownDirectory, string_to_boolean
Marco Mariani's avatar
Marco Mariani committed
55
from slapos.grid.exception import BuildoutFailedError
56
from slapos.grid.SlapObject import Software, Partition
57 58 59 60
from slapos.grid.svcbackend import (launchSupervisord,
                                    createSupervisordConfiguration,
                                    _getSupervisordConfigurationDirectory,
                                    _getSupervisordSocketPath)
61
from slapos.grid.utils import (md5digest, dropPrivileges, SlapPopen, updateFile)
62
from slapos.human import human2bytes
Marco Mariani's avatar
Marco Mariani committed
63
import slapos.slap
64
from netaddr import valid_ipv4, valid_ipv6
Łukasz Nowak's avatar
Łukasz Nowak committed
65 66


Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
67
# XXX: should be moved to SLAP library
68
COMPUTER_PARTITION_DESTROYED_STATE = 'destroyed'
69 70
COMPUTER_PARTITION_STARTED_STATE = 'started'
COMPUTER_PARTITION_STOPPED_STATE = 'stopped'
Łukasz Nowak's avatar
Łukasz Nowak committed
71

72 73 74 75
# Global variables about return state of slapgrid
SLAPGRID_SUCCESS = 0
SLAPGRID_FAIL = 1
SLAPGRID_PROMISE_FAIL = 2
76
PROMISE_TIMEOUT = 3
77

78
COMPUTER_PARTITION_TIMESTAMP_FILENAME = '.timestamp'
79
COMPUTER_PARTITION_LATEST_BANG_TIMESTAMP_FILENAME = '.slapos_latest_bang_timestamp'
80

81 82 83
# XXX hardcoded watchdog_path
WATCHDOG_PATH = '/opt/slapos/bin/slapos-watchdog'

84 85 86 87 88

class _formatXMLError(Exception):
  pass


89 90 91 92 93 94 95 96 97 98 99 100
class FPopen(subprocess.Popen):
  def __init__(self, *args, **kwargs):
    kwargs['stdin'] = subprocess.PIPE
    kwargs['stderr'] = subprocess.STDOUT
    kwargs.setdefault('stdout', subprocess.PIPE)
    kwargs.setdefault('close_fds', True)
    kwargs.setdefault('shell', True)
    subprocess.Popen.__init__(self, *args, **kwargs)
    self.stdin.flush()
    self.stdin.close()
    self.stdin = None

101 102 103
def check_missing_parameters(options):
  required = set([
      'computer_id',
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
104
      # XXX: instance_root is better named "partition_root"
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
      '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)))

122 123 124 125 126 127 128 129
  # parameter can NOT be empty string or None
  for option in required:
    if not options.get(option):
      missing.add(option)

  if missing:
    raise RuntimeError('Mandatory parameters present but empty: %s' % ', '.join(sorted(missing)))

130

131 132
def check_missing_files(options):
  req_files = [
Marco Mariani's avatar
Marco Mariani committed
133 134 135
      options.get('key_file'),
      options.get('cert_file'),
      options.get('master_ca_file'),
136
      options.get('shacache-ca-file'),
Marco Mariani's avatar
Marco Mariani committed
137 138
      options.get('shacache-cert-file'),
      options.get('shacache-key-file'),
139
      options.get('shadir-ca-file'),
Marco Mariani's avatar
Marco Mariani committed
140 141
      options.get('shadir-cert-file'),
      options.get('shadir-key-file'),
142 143
      options.get('signature-private-key-file',
        options.get('signature_private_key_file')),
Marco Mariani's avatar
Marco Mariani committed
144
  ]
145 146

  req_dirs = [
Marco Mariani's avatar
Marco Mariani committed
147 148
      options.get('certificate_repository_path')
  ]
149 150 151

  for f in req_files:
    if f and not os.path.exists(f):
Marco Mariani's avatar
Marco Mariani committed
152
      raise RuntimeError('File %r does not exist.' % f)
153 154 155 156 157 158

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


159 160
def merged_options(args, configp):
  options = dict(configp.items('slapos'))
161

162 163
  if configp.has_section('networkcache'):
    options.update(dict(configp.items('networkcache')))
164 165 166 167
  for key, value in vars(args).iteritems():
    if value is not None:
      options[key] = value

Marco Mariani's avatar
Marco Mariani committed
168 169 170 171 172
  if options.get('all'):
    options['develop'] = True

  # Parse cache / binary cache options
  # Backward compatibility about "binary-cache-url-blacklist" deprecated option
Marco Mariani's avatar
Marco Mariani committed
173 174
  if (options.get("binary-cache-url-blacklist") and not
        options.get("download-from-binary-cache-url-blacklist")):
Marco Mariani's avatar
Marco Mariani committed
175 176 177 178 179 180 181 182 183
    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]

184 185 186 187 188 189
  options['firewall'] = {}
  if configp.has_section('firewall'):
    options['firewall'] = dict(configp.items('firewall'))
    options['firewall']["authorized_sources"] = [
        source.strip() for source in options['firewall'].get(
            "authorized_sources", "").split('\n') if source]
190 191 192
    options['firewall']['firewall_cmd'] = options['firewall'].get(
            "firewall_cmd", "firewall-cmd")
    options['firewall']['firewall_executable'] = options['firewall'].get(
193
            "firewall_executable", "")
194 195
    options['firewall']['dbus_executable'] = options['firewall'].get(
            "dbus_executable", "")
196 197
    options['firewall']['reload_config_cmd'] = options['firewall'].get(
            "reload_config_cmd",
198
            "slapos node restart firewall")
199

200 201 202
  return options


203
def random_delay(options, logger):
204 205 206 207
  """
  Sleep for a random time to avoid SlapOS Master being DDOSed by an army of
  SlapOS Nodes configured with cron.
  """
208 209
  if options['now']:
    # XXX-Cedric: deprecate '--now'
210 211
    return

212
  maximal_delay = int(options.get('maximal_delay', '0'))
213 214
  if maximal_delay:
    duration = random.randint(1, maximal_delay)
Marco Mariani's avatar
Marco Mariani committed
215 216
    logger.info('Sleeping for %s seconds. To disable this feature, '
                'check --now parameter in slapgrid help.', duration)
217 218 219
    time.sleep(duration)


220
def create_slapgrid_object(options, logger):
221 222 223 224
  signature_certificate_list = None
  if 'signature-certificate-list' in options:
    cert_marker = '-----BEGIN CERTIFICATE-----'
    signature_certificate_list = [
Marco Mariani's avatar
Marco Mariani committed
225 226 227 228
        cert_marker + '\n' + q.strip()
        for q in options['signature-certificate-list'].split(cert_marker)
        if q.strip()
    ]
229 230

  op = options
231 232 233
  software_min_free_space = human2bytes(op.get('software_min_free_space', '200M'))
  instance_min_free_space = human2bytes(op.get('instance_min_free_space', '100M'))

234 235 236 237
  return Slapgrid(software_root=op['software_root'],
                  instance_root=op['instance_root'],
                  master_url=op['master_url'],
                  computer_id=op['computer_id'],
238 239
                  buildout=op.get('buildout'),
                  logger=logger,
240
                  maximum_periodicity = op.get('maximum_periodicity', 86400),
241 242
                  key_file=op.get('key_file'),
                  cert_file=op.get('cert_file'),
243 244
                  signature_private_key_file=op.get(
                    'signature-private-key-file', op.get('signature_private_key_file')),
245 246 247
                  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
248
                  download_from_binary_cache_url_blacklist=
249
                      op.get('download-from-binary-cache-url-blacklist', []),
Marco Mariani's avatar
Marco Mariani committed
250
                  upload_to_binary_cache_url_blacklist=
251 252 253 254 255
                      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'),
256 257
                  master_ca_file=op.get('master_ca_file'),
                  certificate_repository_path=op.get('certificate_repository_path'),
258
                  promise_timeout=op.get('promise_timeout', PROMISE_TIMEOUT),
259
                  shacache_ca_file=op.get('shacache-ca-file'),
260 261
                  shacache_cert_file=op.get('shacache-cert-file'),
                  shacache_key_file=op.get('shacache-key-file'),
262
                  shadir_ca_file=op.get('shadir-ca-file'),
263 264
                  shadir_cert_file=op.get('shadir-cert-file'),
                  shadir_key_file=op.get('shadir-key-file'),
265
                  forbid_supervisord_automatic_launch=string_to_boolean(op.get('forbid_supervisord_automatic_launch', 'false')),
266 267 268 269
                  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
270 271
                  computer_partition_filter_list=op.get('only-cp', op.get('only_cp')),
                  software_min_free_space=software_min_free_space,
272
                  instance_min_free_space=instance_min_free_space,
273
                  instance_storage_home=op.get('instance_storage_home'),
274 275
                  ipv4_global_network=op.get('ipv4_global_network'),
                  firewall_conf=op.get('firewall'))
Łukasz Nowak's avatar
Łukasz Nowak committed
276 277


278
def check_required_only_partitions(existing, required):
279 280 281
  """
  Verify the existence of partitions specified by the --only parameter
  """
282 283
  missing = set(required) - set(existing)
  if missing:
Marco Mariani's avatar
Marco Mariani committed
284 285
    plural = ['s', ''][len(missing) == 1]
    raise ValueError('Unknown partition%s: %s' % (plural, ', '.join(sorted(missing))))
286 287


Łukasz Nowak's avatar
Łukasz Nowak committed
288 289 290 291
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
292 293 294 295

  class PromiseError(Exception):
    pass

Łukasz Nowak's avatar
Łukasz Nowak committed
296 297 298 299 300
  def __init__(self,
               software_root,
               instance_root,
               master_url,
               computer_id,
301
               buildout,
302
               logger,
303
               maximum_periodicity=86400,
Łukasz Nowak's avatar
Łukasz Nowak committed
304 305
               key_file=None,
               cert_file=None,
306
               signature_private_key_file=None,
Yingjie Xu's avatar
Yingjie Xu committed
307 308 309
               signature_certificate_list=None,
               download_binary_cache_url=None,
               upload_binary_cache_url=None,
310 311
               download_from_binary_cache_url_blacklist=None,
               upload_to_binary_cache_url_blacklist=None,
312
               upload_cache_url=None,
Yingjie Xu's avatar
Yingjie Xu committed
313 314
               download_binary_dir_url=None,
               upload_binary_dir_url=None,
315
               upload_dir_url=None,
Łukasz Nowak's avatar
Łukasz Nowak committed
316 317
               master_ca_file=None,
               certificate_repository_path=None,
318
               promise_timeout=3,
319
               shacache_ca_file=None,
320 321
               shacache_cert_file=None,
               shacache_key_file=None,
322
               shadir_ca_file=None,
323
               shadir_cert_file=None,
324
               shadir_key_file=None,
325
               forbid_supervisord_automatic_launch=False,
326
               develop=False,
327
               software_release_filter_list=None,
328
               computer_partition_filter_list=None,
329 330
               software_min_free_space=None,
               instance_min_free_space=None,
331
               instance_storage_home=None,
332
               ipv4_global_network=None,
333
               firewall_conf={},
334
               ):
Łukasz Nowak's avatar
Łukasz Nowak committed
335 336 337 338 339 340
    """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
341
    self.supervisord_socket = _getSupervisordSocketPath(instance_root)
Łukasz Nowak's avatar
Łukasz Nowak committed
342 343 344 345
    self.key_file = key_file
    self.cert_file = cert_file
    self.master_ca_file = master_ca_file
    self.certificate_repository_path = certificate_repository_path
346
    self.signature_private_key_file = signature_private_key_file
Yingjie Xu's avatar
Yingjie Xu committed
347 348 349
    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
350 351 352 353
    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
354
    self.upload_cache_url = upload_cache_url
Yingjie Xu's avatar
Yingjie Xu committed
355 356
    self.download_binary_dir_url = download_binary_dir_url
    self.upload_binary_dir_url = upload_binary_dir_url
357
    self.upload_dir_url = upload_dir_url
358
    self.shacache_ca_file = shacache_ca_file
359 360
    self.shacache_cert_file = shacache_cert_file
    self.shacache_key_file = shacache_key_file
361
    self.shadir_ca_file = shadir_ca_file
362 363
    self.shadir_cert_file = shadir_cert_file
    self.shadir_key_file = shadir_key_file
364
    self.forbid_supervisord_automatic_launch = forbid_supervisord_automatic_launch
365
    self.logger = logger
Łukasz Nowak's avatar
Łukasz Nowak committed
366
    # Creates objects from slap module
Marco Mariani's avatar
Marco Mariani committed
367
    self.slap = slapos.slap.slap()
Łukasz Nowak's avatar
Łukasz Nowak committed
368 369 370 371
    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
372
    self.buildout = buildout
373
    self.promise_timeout = promise_timeout
374
    self.develop = develop
375
    if software_release_filter_list is not None:
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
376 377
      self.software_release_filter_list = \
          software_release_filter_list.split(",")
378
    else:
379
      self.software_release_filter_list = []
380 381
    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
382 383
      self.computer_partition_filter_list = \
          computer_partition_filter_list.split(",")
384
    self.maximum_periodicity = maximum_periodicity
385 386
    self.software_min_free_space = software_min_free_space
    self.instance_min_free_space = instance_min_free_space
387 388 389 390
    if instance_storage_home:
      self.instance_storage_home = os.path.abspath(instance_storage_home)
    else:
      self.instance_storage_home = ""
391 392 393 394
    if ipv4_global_network:
      self.ipv4_global_network = ipv4_global_network
    else:
      self.ipv4_global_network= ""
395 396
    self.firewall_conf = firewall_conf

Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
397

398
  def _getWatchdogLine(self):
399
    invocation_list = [WATCHDOG_PATH]
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
400
    invocation_list.append("--master-url '%s' " % self.master_url)
401
    if self.certificate_repository_path:
Marco Mariani's avatar
Marco Mariani committed
402 403
      invocation_list.append("--certificate-repository-path '%s'" %
                                self.certificate_repository_path)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
404
    invocation_list.append("--computer-id '%s'" % self.computer_id)
405
    invocation_list.append("--instance-root '%s'" % self.instance_root)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
406
    return ' '.join(invocation_list)
Łukasz Nowak's avatar
Łukasz Nowak committed
407

408 409 410 411 412 413 414 415
  def _generateFirewallSupervisorConf(self):
    """If firewall section is defined in slapos configuration, generate
      supervisor configuration entry for firewall process.
    """
    supervisord_conf_folder_path = os.path.join(self.instance_root,
                                               'etc', 'supervisord.conf.d')
    supervisord_firewall_conf = os.path.join(supervisord_conf_folder_path,
                                              'firewall.conf')
416 417
    if not self.firewall_conf or not self.firewall_conf.get('firewall_executable') \
      or self.firewall_conf.get('testing', False):
418 419 420 421 422 423 424 425
      if os.path.exists(supervisord_firewall_conf):
        os.unlink(supervisord_firewall_conf)
      return
    supervisord_firewall_program_conf = """\
[program:firewall]
directory=/opt/slapos
command=%(firewall_executable)s
process_name=firewall
426
priority=5
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
autostart=true
autorestart=true
startsecs=0
startretries=0
exitcodes=0
stopsignal=TERM
stopwaitsecs=60
user=0
group=0
serverurl=AUTO
redirect_stderr=true
stdout_logfile=%(log_file)s
stdout_logfile_maxbytes=100KB
stdout_logfile_backups=1
stderr_logfile=%(log_file)s
stderr_logfile_maxbytes=100KB
stderr_logfile_backups=1
""" %  {'firewall_executable': self.firewall_conf['firewall_executable'],
        'log_file': self.firewall_conf.get('log_file', '/var/log/firewall.log')}

    if not os.path.exists(supervisord_conf_folder_path):
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
      os.makedirs(supervisord_conf_folder_path)
    updateFile(supervisord_firewall_conf, supervisord_firewall_program_conf)


  def _generateDbusSupervisorConf(self):
    """If dbus command is defined in slapos configuration, generate
      supervisor configuration entry for dbus daemon.
    """
    supervisord_conf_folder_path = os.path.join(self.instance_root,
                                               'etc', 'supervisord.conf.d')
    supervisord_dbus_conf = os.path.join(supervisord_conf_folder_path,
                                              'dbus.conf')
    if not self.firewall_conf or not self.firewall_conf.get('dbus_executable') \
      or self.firewall_conf.get('testing', False):
      if os.path.exists(supervisord_dbus_conf):
        os.unlink(supervisord_dbus_conf)
      return
    supervisord_dbus_program_conf = """\
[program:dbus]
directory=/opt/slapos
command=%(dbus_executable)s
process_name=dbus
priority=1
autostart=true
autorestart=true
startsecs=0
startretries=0
exitcodes=0
stopsignal=TERM
stopwaitsecs=60
user=0
group=0
serverurl=AUTO
redirect_stderr=true
stdout_logfile=%(dbus_log_file)s
stdout_logfile_maxbytes=100KB
stdout_logfile_backups=1
stderr_logfile=%(dbus_log_file)s
stderr_logfile_maxbytes=100KB
stderr_logfile_backups=1
""" %  {'dbus_executable': self.firewall_conf['dbus_executable'],
        'dbus_log_file': self.firewall_conf.get('dbus_log_file', '/var/log/dbus.log')}

    if not os.path.exists(supervisord_conf_folder_path):
      os.makedirs(supervisord_conf_folder_path)
    updateFile(supervisord_dbus_conf, supervisord_dbus_program_conf)
494

Łukasz Nowak's avatar
Łukasz Nowak committed
495 496 497 498 499 500
  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):
501
      raise OSError('%s does not exist.' % self.software_root)
502 503

    createSupervisordConfiguration(self.instance_root, self._getWatchdogLine())
504
    self._generateFirewallSupervisorConf()
505
    self._generateDbusSupervisorConf()
506 507

  def _launchSupervisord(self):
508 509
    if not self.forbid_supervisord_automatic_launch:
      launchSupervisord(instance_root=self.instance_root, logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
510 511 512

  def getComputerPartitionList(self):
    try:
513
      return self.computer.getComputerPartitionList()
Marco Mariani's avatar
Marco Mariani committed
514 515
    except socket.error as exc:
      self.logger.fatal(exc)
516
      raise
Łukasz Nowak's avatar
Łukasz Nowak committed
517 518 519 520 521

  def processSoftwareReleaseList(self):
    """Will process each Software Release.
    """
    self.checkEnvironmentAndCreateStructure()
522
    self.logger.info('Processing software releases...')
523
    # Boolean to know if every instance has correctly been deployed
Łukasz Nowak's avatar
Łukasz Nowak committed
524 525
    clean_run = True
    for software_release in self.computer.getSoftwareReleaseList():
Łukasz Nowak's avatar
Łukasz Nowak committed
526
      state = software_release.getState()
Łukasz Nowak's avatar
Łukasz Nowak committed
527 528
      try:
        software_release_uri = software_release.getURI()
Marco Mariani's avatar
Marco Mariani committed
529
        url_hash = md5digest(software_release_uri)
530
        software_path = os.path.join(self.software_root, url_hash)
Łukasz Nowak's avatar
Łukasz Nowak committed
531 532
        software = Software(url=software_release_uri,
            software_root=self.software_root,
533
            buildout=self.buildout,
534
            logger=self.logger,
535
            signature_private_key_file=self.signature_private_key_file,
Yingjie Xu's avatar
Yingjie Xu committed
536 537 538
            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
539
            download_from_binary_cache_url_blacklist=
540
                self.download_from_binary_cache_url_blacklist,
Marco Mariani's avatar
Marco Mariani committed
541
            upload_to_binary_cache_url_blacklist=
542
                self.upload_to_binary_cache_url_blacklist,
543
            upload_cache_url=self.upload_cache_url,
Yingjie Xu's avatar
Yingjie Xu committed
544 545
            download_binary_dir_url=self.download_binary_dir_url,
            upload_binary_dir_url=self.upload_binary_dir_url,
546
            upload_dir_url=self.upload_dir_url,
547
            shacache_ca_file=self.shacache_ca_file,
548 549
            shacache_cert_file=self.shacache_cert_file,
            shacache_key_file=self.shacache_key_file,
550
            shadir_ca_file=self.shadir_ca_file,
551
            shadir_cert_file=self.shadir_cert_file,
552 553
            shadir_key_file=self.shadir_key_file,
            software_min_free_space=self.software_min_free_space)
Łukasz Nowak's avatar
Łukasz Nowak committed
554
        if state == 'available':
555
          completed_tag = os.path.join(software_path, '.completed')
Marco Mariani's avatar
Marco Mariani committed
556 557 558 559
          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)):
560 561 562 563 564
            try:
              software_release.building()
            except NotFoundError:
              pass
            software.install()
Marco Mariani's avatar
Marco Mariani committed
565 566
            with open(completed_tag, 'w') as fout:
              fout.write(time.asctime())
Łukasz Nowak's avatar
Łukasz Nowak committed
567
        elif state == 'destroyed':
568
          if os.path.exists(software_path):
569
            self.logger.info('Destroying %r...' % software_release_uri)
570
            software.destroy()
571
            self.logger.info('Destroyed %r.' % software_release_uri)
572
      # Send log before exiting
Łukasz Nowak's avatar
Łukasz Nowak committed
573
      except (SystemExit, KeyboardInterrupt):
574
        software_release.error(traceback.format_exc(), logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
575
        raise
576 577

      # Buildout failed: send log but don't print it to output (already done)
Marco Mariani's avatar
Marco Mariani committed
578
      except BuildoutFailedError as exc:
579 580
        clean_run = False
        try:
581
          software_release.error(exc, logger=self.logger)
582 583 584
        except (SystemExit, KeyboardInterrupt):
          raise
        except Exception:
585
          self.logger.exception('Problem while reporting error, continuing:')
586 587

      # For everything else: log it, send it, continue.
Łukasz Nowak's avatar
Łukasz Nowak committed
588
      except Exception:
589 590
        self.logger.exception('')
        software_release.error(traceback.format_exc(), logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
591 592
        clean_run = False
      else:
Łukasz Nowak's avatar
Łukasz Nowak committed
593
        if state == 'available':
594 595
          try:
            software_release.available()
596
          except (NotFoundError, ServerError):
597
            pass
Łukasz Nowak's avatar
Łukasz Nowak committed
598
        elif state == 'destroyed':
599 600
          try:
            software_release.destroyed()
601
          except (NotFoundError, ServerError):
602
            self.logger.exception('')
603
    self.logger.info('Finished software releases.')
604 605 606 607 608

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

Antoine Catton's avatar
Antoine Catton committed
610
  def _checkPromises(self, computer_partition):
611
    self.logger.info("Checking promises...")
Marco Mariani's avatar
Marco Mariani committed
612
    instance_path = os.path.join(self.instance_root, computer_partition.getId())
Antoine Catton's avatar
Antoine Catton committed
613 614 615 616 617 618 619 620

    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

621
    promise_present = False
Antoine Catton's avatar
Antoine Catton committed
622 623 624 625
    # 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
626
      for promise in os.listdir(promise_dir):
627
        promise_present = True
Antoine Catton's avatar
Antoine Catton committed
628

Antoine Catton's avatar
Antoine Catton committed
629 630 631
        command = [os.path.join(promise_dir, promise)]

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

634
        process_handler = subprocess.Popen(command,
635
                                           preexec_fn=lambda: dropPrivileges(uid, gid, logger=self.logger),
Marco Mariani's avatar
Marco Mariani committed
636
                                           cwd=instance_path,
Marco Mariani's avatar
Marco Mariani committed
637
                                           env=None if sys.platform == 'cygwin' else {},
Marco Mariani's avatar
Marco Mariani committed
638 639 640
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE,
                                           stdin=subprocess.PIPE)
641 642 643
        process_handler.stdin.flush()
        process_handler.stdin.close()
        process_handler.stdin = None
Antoine Catton's avatar
Antoine Catton committed
644

645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
        # Check if the promise finished every tenth of second,
        # but timeout after promise_timeout.
        sleep_time = 0.1
        increment_limit = int(self.promise_timeout / sleep_time)
        for current_increment in range(0, increment_limit):
          if process_handler.poll() is None:
            time.sleep(sleep_time)
            continue
          if process_handler.poll() == 0:
            # Success!
            break
          else:
            stderr = process_handler.communicate()[1]
            if stderr is None:
              stderr = "No error output from '%s'." % promise
            else:
              stderr = "Promise '%s':" % promise + stderr
            raise Slapgrid.PromiseError(stderr)
        else:
664
          process_handler.terminate()
665
          raise Slapgrid.PromiseError("The promise '%s' timed out" % promise)
Antoine Catton's avatar
Antoine Catton committed
666

Antoine Catton's avatar
Antoine Catton committed
667 668 669
    if not promise_present:
      self.logger.info("No promise.")

670 671 672 673 674 675 676 677 678
  def _endInstallationTransaction(self, computer_partition):
    partition_id = computer_partition.getId()
    transaction_file_name = COMPUTER_PARTITION_REQUEST_LIST_TEMPLATE_FILENAME % partition_id
    transaction_file_path = os.path.join(self.instance_root,
                                      partition_id,
                                      transaction_file_name)

    if os.path.exists(transaction_file_path):
      with open(transaction_file_path, 'r') as tf:
679 680 681 682 683 684 685 686 687
        try:
          computer_partition.setComputerPartitionRelatedInstanceList(
            [reference for reference in tf.read().split('\n') if reference]
          )
        except NotFoundError, e:
          # Master doesn't implement this feature ?
          self.logger.warning("NotFoundError: %s. \nCannot send requested instance "\
                            "list to master. Please check if this feature is"\
                            "implemented on SlapOS Master." % str(e))
688

689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
  def _addFirewallRule(self, rule_command):
    """
    """
    query_cmd = rule_command.replace('--add-rule', '--query-rule')
    process = FPopen(query_cmd)
    result = process.communicate()[0]
    if result.strip() == 'no':
      self.logger.debug(rule_command)
      process = FPopen(rule_command)
      process.communicate()[0]
    if process.returncode == 1 and result.strip() != 'no':
      raise Exception("Failed to add firewalld rule %s." % rule_command)

    return result.strip() == 'no'

  def _removeFirewallRule(self, rule_command):
    """
    """
    query_cmd = rule_command.replace('--add-rule', '--query-rule')
    process = FPopen(query_cmd)
    result = process.communicate()[0]
    if result.strip() == 'yes':
      remove_command = rule_command.replace('--add-rule', '--remove-rule')
      self.logger.debug(remove_command)
      process = FPopen(remove_command)
      process.communicate()[0]
    if process.returncode == 1 and result.strip() != 'no':
      raise Exception("Failed to remove firewalld rule %s." % remove_command)

    return result.strip() == 'yes'

720
  def _checkAddFirewallRules(self, partition_id, command_list, add=True):
721
    """
722
    Process Firewall rules from and save rules to firewall_rules_path
723
    """
724
    
725
    instance_path = os.path.join(self.instance_root, partition_id)
726 727
    firewall_rules_path = os.path.join(instance_path,
                                Partition.partition_firewall_rules_name)
728
    reload_rules = False
729 730
    fw_base_cmd = self.firewall_conf['firewall_cmd']
    json_list = []
731

732 733
    if os.path.exists(firewall_rules_path):
      with open(firewall_rules_path, 'r') as frules:
734 735 736
        rules_list = json.loads(frules.read())

      for command in rules_list:
737
        skip_remove = False
738
        if add:
739
          for new_cmd in command_list:
740
            if command == new_cmd:
741
              skip_remove = True
742
              break
743 744 745 746

        if not skip_remove:
          state = self._removeFirewallRule('%s %s' % (fw_base_cmd, command))
          reload_rules = reload_rules or state
747 748

    if add:
749 750 751 752
      json_list = command_list
      for command in command_list:
        state = self._addFirewallRule('%s %s' % (fw_base_cmd, command))
        reload_rules = reload_rules or state
753

754 755 756 757 758
    if reload_rules:
      # Apply changes: reload configuration
      # XXX - need to check firewalld reload instead of restart
      self.logger.info("Reloading firewall configuration...")
      reload_cmd = self.firewall_conf['reload_config_cmd']
759
      reload_process = FPopen(reload_cmd)
760 761 762
      result = reload_process.communicate()[0]
      if reload_process.returncode == 1:
        raise Exception("Failed to load firewalld rules with command %s" % reload_cmd)
763

764
      with open(firewall_rules_path, 'w') as frules:
765
        frules.write(json.dumps(json_list))
766

767
  def _getFirewallAcceptRules(self, ip, hosting_ip_list, source_ip_list, ip_type='ipv4'):
768
    """
769
    Generate rules for firewall based on list of IP that should have access to `ip`
770
    """
771 772 773
    if ip_type not in ['ipv4', 'ipv6', 'eb']:
      raise NotImplementedError("firewall-cmd has not rules with tables %s." % ip_type)

774
    command = '--permanent --direct --add-rule %s filter' % ip_type
775 776

    cmd_list = []
777
    ip_list = hosting_ip_list + source_ip_list
778 779

    for other_ip in ip_list:
780
      # Configure INPUT rules
781 782
      cmd_list.append('%s INPUT 0 -s %s -d %s -j ACCEPT' % (command,
                                                            other_ip, ip))
783
      # Configure FORWARD rules
784 785 786
      cmd_list.append('%s FORWARD 0 -s %s -d %s -j ACCEPT' % (command,
                                                              other_ip, ip))

787 788 789 790
    # Reject all other requests
    cmd_list.append('%s INPUT 1000 -d %s -j REJECT' % (command, ip))
    cmd_list.append('%s FORWARD 1000 -d %s -j REJECT' % (command, ip))
    cmd_list.append('%s INPUT 900 -d %s -m state --state ESTABLISHED,RELATED -j REJECT' % (
791
                    command, ip))
792
    cmd_list.append('%s FORWARD 900 -d %s -m state --state ESTABLISHED,RELATED -j REJECT' % (
793 794
                    command, ip))

795
    return cmd_list
796 797 798 799 800 801 802 803
  
  def _getFirewallRejectRules(self, ip, hosting_ip_list, source_ip_list, ip_type='ipv4'):
    """
    Generate rules for firewall based on list of IP that should not have access to `ip`
    """
    if ip_type not in ['ipv4', 'ipv6', 'eb']:
      raise NotImplementedError("firewall-cmd has not rules with tables %s." % ip_type)

804
    command = '--permanent --direct --add-rule %s filter' % ip_type
805 806 807 808

    cmd_list = []

    # Accept all other requests
809 810
    #cmd_list.append('%s INPUT 1000 -d %s -j ACCEPT' % (command, ip))
    #cmd_list.append('%s FORWARD 1000 -d %s -j ACCEPT' % (command, ip))
811 812 813 814 815 816 817 818 819 820 821 822 823

    # Reject all other requests from the list
    for other_ip in source_ip_list:
      cmd_list.append('%s INPUT 800 -s %s -d %s -m state --state ESTABLISHED,RELATED -j REJECT' % (
                    command, other_ip, ip))
      cmd_list.append('%s FORWARD 800 -s %s -d %s -m state --state ESTABLISHED,RELATED -j REJECT' % (
                    command, other_ip, ip))
      cmd_list.append('%s INPUT 900 -s %s -d %s -j REJECT' % (command,
                                                            other_ip, ip))
      cmd_list.append('%s FORWARD 900 -s %s -d %s -j REJECT' % (command,
                                                              other_ip, ip))
    # Accept on this hosting subscription
    for other_ip in hosting_ip_list:
824
      cmd_list.append('%s INPUT 0 -s %s -d %s -j ACCEPT' % (command,
825
                                                            other_ip, ip))
826
      cmd_list.append('%s FORWARD 0 -s %s -d %s -j ACCEPT' % (command,
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
                                                              other_ip, ip))

    return cmd_list

  def _getValidIpv4FromList(self, ipv4_list, warn=False):
    """
    Return the list containing only valid ipv4 or network address.
    """
    valid_list = []
    for ip in ipv4_list:
      if not ip:
        continue
      the_ip = ip.split('/')[0]
      if valid_ipv4(the_ip):
        valid_list.append(ip)
      elif warn:
        self.logger.warn("IP/Network address %s is not valid. ignored.." % ip)
    return valid_list
845

846
  def _setupComputerPartitionFirewall(self, computer_partition, ip_list, drop_entries=False):
847 848 849 850 851 852
    """
    Using linux iptables, limit access to IP of this partition to all 
    others partitions of the same Hosting Subscription
    """
    ipv4_list = []
    ipv6_list = []
853 854 855 856 857 858 859 860 861 862 863 864
    source_ipv4_list = []
    source_ipv6_list = []
    hosting_ipv4_list = []
    hosting_ipv6_list = []
    getFirewallRules = getattr(self, '_getFirewallAcceptRules')

    if not drop_entries:
      self.logger.info("Configuring firewall...")
      add_rules = True
    else:
      add_rules = False
      self.logger.info("Removing firewall configuration...")
865 866 867 868 869

    for net_ip in ip_list:
      iface, ip = (net_ip[0], net_ip[1])
      if not iface.startswith('route_'):
        continue
870 871 872 873
      if valid_ipv4(ip):
        ipv4_list.append(ip)
      elif valid_ipv6(ip):
        ipv6_list.append(ip)
874

875 876
    hosting_ip_list = computer_partition.getFullHostingIpAddressList()
    for iface, ip in hosting_ip_list:
877 878
      if valid_ipv4(ip):
        if not ip in ipv4_list:
879
          hosting_ipv4_list.append(ip)
880 881
      elif valid_ipv6(ip):
        if not ip in ipv6_list:
882
          hosting_ipv6_list.append(ip)
883 884

    filter_dict = getattr(computer_partition, '_filter_dict', None)
885
    extra_list = []
886
    accept_ip_list = []
887
    if filter_dict is not None:
888 889 890 891 892 893 894 895
      if filter_dict.get('fw_restricted_access', 'on') == 'off':
        extra_list = filter_dict.get('fw_rejected_sources', '').split(' ')
        getFirewallRules = getattr(self, '_getFirewallRejectRules')
        accept_ip_list.extend(self.firewall_conf.get('authorized_sources', []))
        accept_ip_list.extend(filter_dict.get('fw_authorized_sources', '').split(' '))
      else:
        extra_list = filter_dict.get('fw_authorized_sources', '').split(' ')
        extra_list.extend(self.firewall_conf.get('authorized_sources', []))
896

897 898
    source_ipv4_list = self._getValidIpv4FromList(extra_list, True)
    hosting_ipv4_list.extend(self._getValidIpv4FromList(accept_ip_list, True))
899

900
    # XXX - ipv6_list and source_ipv6_list ignored for the moment
901
    for ip in ipv4_list:
902 903 904 905
      cmd_list = getFirewallRules(ip, hosting_ipv4_list,
                                  source_ipv4_list, ip_type='ipv4')
      self._checkAddFirewallRules(computer_partition.getId(),
                                  cmd_list, add=add_rules)
Antoine Catton's avatar
Antoine Catton committed
906

907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
  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

924
    self.logger.debug('Check if %s requires processing...' % computer_partition_id)
925

926
    instance_path = os.path.join(self.instance_root, computer_partition_id)
927 928 929 930 931 932 933 934
    os.environ['SLAPGRID_INSTANCE_ROOT'] = self.instance_root

    # Check if transaction file of this partition exists, if the file was created,
    # remove it so it will be generate with this new transaction
    transaction_file_name = COMPUTER_PARTITION_REQUEST_LIST_TEMPLATE_FILENAME % computer_partition_id
    transaction_file_path = os.path.join(instance_path, transaction_file_name)
    if os.path.exists(transaction_file_path):
      os.unlink(transaction_file_path)
935 936

    # Try to get partition timestamp (last modification date)
937 938 939 940
    timestamp_path = os.path.join(
        instance_path,
        COMPUTER_PARTITION_TIMESTAMP_FILENAME
    )
941 942 943 944 945 946
    parameter_dict = computer_partition.getInstanceParameterDict()
    if 'timestamp' in parameter_dict:
      timestamp = parameter_dict['timestamp']
    else:
      timestamp = None

947 948 949 950 951 952 953
    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
954
      software_path = os.path.join(self.software_root, md5digest(software_url))
955 956 957 958 959
    except TypeError:
      # Problem with instance: SR URI not set.
      # Try to process it anyway, it may need to be deleted.
      software_path = None

960
    periodicity = self.maximum_periodicity
961
    if software_path:
962 963 964 965 966 967 968
      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('')
969 970 971 972

    # 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
973 974
    if (computer_partition_id not in self.computer_partition_filter_list and
          not self.develop and os.path.exists(timestamp_path)):
975 976 977 978
      old_timestamp = open(timestamp_path).read()
      last_runtime = int(os.path.getmtime(timestamp_path))
      if timestamp:
        try:
979 980 981
          if periodicity == 0:
            os.remove(timestamp_path)
          elif int(timestamp) <= int(old_timestamp):
982 983
            # Check periodicity, i.e if periodicity is one day, partition
            # should be processed at least every day.
984
            if int(time.time()) <= (last_runtime + periodicity) or periodicity < 0:
985
              self.logger.debug('Partition already up-to-date, skipping.')
986
              return
987 988 989 990
            else:
              # Periodicity forced processing this partition. Removing
              # the timestamp file in case it fails.
              os.remove(timestamp_path)
991 992
        except ValueError:
          os.remove(timestamp_path)
993
          self.logger.exception('')
994

995 996 997 998 999 1000 1001
    # 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)
1002
    chownDirectory("%s/.slapgrid" % instance_path,
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
                   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)
1016

1017 1018 1019 1020 1021 1022
      filter_dict = getattr(computer_partition, '_filter_dict', None)
      if filter_dict:
        retention_delay = filter_dict.get('retention_delay', '0')
      else:
        retention_delay = '0'

1023 1024 1025 1026
      local_partition = Partition(
        software_path=software_path,
        instance_path=instance_path,
        supervisord_partition_configuration_path=os.path.join(
1027
          _getSupervisordConfigurationDirectory(self.instance_root), '%s.conf' %
1028 1029 1030 1031 1032 1033 1034 1035 1036
          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,
1037
        logger=self.logger,
1038
        retention_delay=retention_delay,
1039
        instance_min_free_space=self.instance_min_free_space,
1040
        instance_storage_home=self.instance_storage_home,
1041
        ipv4_global_network=self.ipv4_global_network,
1042
      )
1043
      computer_partition_state = computer_partition.getState()
1044

1045 1046 1047
      # XXX this line breaks 37 tests
      # self.logger.info('  Instance type: %s' % computer_partition.getType())
      self.logger.info('  Instance status: %s' % computer_partition_state)
1048

1049 1050 1051
      partition_ip_list = full_hosting_ip_list = []
      if self.firewall_conf:
        partition_ip_list = parameter_dict['ip_list'] + parameter_dict.get(
1052
                                                            'full_ip_list', [])
1053

1054
      if computer_partition_state == COMPUTER_PARTITION_STARTED_STATE:
1055 1056
        local_partition.install()
        computer_partition.available()
1057
        local_partition.start()
1058 1059
        if self.firewall_conf:
          self._setupComputerPartitionFirewall(computer_partition,
1060
                                              partition_ip_list)
1061 1062
        self._checkPromises(computer_partition)
        computer_partition.started()
1063
        self._endInstallationTransaction(computer_partition)
1064 1065 1066 1067 1068 1069
      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()
1070 1071
          if self.firewall_conf:
            self._setupComputerPartitionFirewall(computer_partition,
1072
                                                partition_ip_list)
1073 1074 1075
        finally:
          # Instance has to be stopped even if buildout/reporting is wrong.
          local_partition.stop()
1076
        computer_partition.stopped()
1077
        self._endInstallationTransaction(computer_partition)
1078 1079
      elif computer_partition_state == COMPUTER_PARTITION_DESTROYED_STATE:
        local_partition.stop()
1080 1081 1082 1083
        if self.firewall_conf:
          self._setupComputerPartitionFirewall(computer_partition,
                                              partition_ip_list,
                                              drop_entries=True)
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
        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)
1098 1099 1100 1101 1102

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

1103
  def FilterComputerPartitionList(self, computer_partition_list):
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
1104
    """
1105
    Try to filter valid partitions to be processed from free partitions.
Łukasz Nowak's avatar
Łukasz Nowak committed
1106
    """
1107 1108
    filtered_computer_partition_list = []
    for computer_partition in computer_partition_list:
Łukasz Nowak's avatar
Łukasz Nowak committed
1109
      try:
1110 1111 1112 1113 1114 1115 1116
        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"
1117
        # partition, and check if it has some Software information.
1118 1119 1120
        # 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()
1121 1122 1123 1124
        try:
          software_url = computer_partition.getSoftwareRelease().getURI()
        except (NotFoundError, TypeError, NameError):
          software_url = None
1125
        if computer_partition_state == COMPUTER_PARTITION_DESTROYED_STATE and \
1126
           not software_url:
1127 1128 1129
          if os.listdir(computer_partition_path) != []:
            self.logger.warning("Free partition %s contains file(s) in %s." % (
                computer_partition.getId(), computer_partition_path))
1130
          continue
1131

1132 1133 1134 1135 1136 1137 1138
        # Everything seems fine
        filtered_computer_partition_list.append(computer_partition)

      # XXX-Cedric: factor all this error handling

      # Send log before exiting
      except (SystemExit, KeyboardInterrupt):
1139
        computer_partition.error(traceback.format_exc(), logger=self.logger)
1140 1141
        raise

Marco Mariani's avatar
Marco Mariani committed
1142
      except Exception as exc:
1143 1144 1145 1146
        # 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('')
1147
        try:
1148
          computer_partition.error(exc, logger=self.logger)
1149 1150 1151
        except (SystemExit, KeyboardInterrupt):
          raise
        except Exception:
1152
          self.logger.exception('Problem while reporting error, continuing:')
1153 1154 1155 1156 1157 1158 1159

    return filtered_computer_partition_list

  def processComputerPartitionList(self):
    """
    Will start supervisord and process each Computer Partition.
    """
1160
    self.logger.info('Processing computer partitions...')
1161 1162 1163
    # Prepares environment
    self.checkEnvironmentAndCreateStructure()
    self._launchSupervisord()
1164 1165

    # Boolean to know if every instance has correctly been deployed
1166
    clean_run = True
1167 1168
    # Boolean to know if every promises correctly passed
    clean_run_promise = True
1169

1170 1171 1172
    check_required_only_partitions([cp.getId() for cp in self.getComputerPartitionList()],
                                   self.computer_partition_filter_list)

1173 1174 1175 1176 1177 1178 1179 1180 1181
    # 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:
1182
        # Process the partition itself
1183
        self.processComputerPartition(computer_partition)
1184

1185
      # Send log before exiting
Łukasz Nowak's avatar
Łukasz Nowak committed
1186
      except (SystemExit, KeyboardInterrupt):
1187
        computer_partition.error(traceback.format_exc(), logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
1188
        raise
1189

Marco Mariani's avatar
Marco Mariani committed
1190
      except Slapgrid.PromiseError as exc:
1191 1192
        clean_run_promise = False
        try:
1193
          self.logger.error(exc)
1194
          computer_partition.error(exc, logger=self.logger)
1195 1196 1197
        except (SystemExit, KeyboardInterrupt):
          raise
        except Exception:
1198
          self.logger.exception('Problem while reporting error, continuing:')
1199

Marco Mariani's avatar
Marco Mariani committed
1200
      except Exception as exc:
Łukasz Nowak's avatar
Łukasz Nowak committed
1201
        clean_run = False
1202 1203 1204 1205
        # 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('')
1206
        try:
1207
          computer_partition.error(exc, logger=self.logger)
1208 1209 1210
        except (SystemExit, KeyboardInterrupt):
          raise
        except Exception:
1211
          self.logger.exception('Problem while reporting error, continuing:')
1212

1213
    self.logger.info('Finished computer partitions.')
1214 1215 1216 1217 1218 1219 1220

    # 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
1221

1222 1223 1224 1225 1226
  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
1227 1228
    xmlschema = etree.XMLSchema(xmlschema_doc)

1229
    try:
1230
      document = etree.fromstring(to_be_validated)
Marco Mariani's avatar
Marco Mariani committed
1231
    except (etree.XMLSyntaxError, etree.DocumentInvalid) as exc:
Marco Mariani's avatar
Marco Mariani committed
1232 1233
      self.logger.info('Failed to parse this XML report :  %s\n%s' %
                          (to_be_validated, _formatXMLError(exc)))
1234
      self.logger.error(_formatXMLError(exc))
1235 1236
      return False

Łukasz Nowak's avatar
Łukasz Nowak committed
1237 1238 1239 1240 1241
    if xmlschema.validate(document):
      return True

    return False

1242 1243 1244
  def asXML(self, computer_partition_usage_list):
    """Generates a XML report from computer partition usage list
    """
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
    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>']
1259 1260 1261

    for computer_partition_usage in computer_partition_usage_list:
      try:
1262
        root = etree.fromstring(computer_partition_usage.usage)
Marco Mariani's avatar
Marco Mariani committed
1263
      except UnicodeError as exc:
1264
        self.logger.info("Failed to read %s." % computer_partition_usage.usage)
1265
        self.logger.error(UnicodeError)
Marco Mariani's avatar
Marco Mariani committed
1266 1267
        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
1268
        self.logger.info("Failed to parse %s." % (computer_partition_usage.usage))
Marco Mariani's avatar
Marco Mariani committed
1269 1270 1271 1272
        self.logger.error(exc)
        raise _formatXMLError(exc)
      except Exception as exc:
        raise Exception("Failed to generate XML report: %s" % exc)
1273 1274

      for movement in root.findall('movement'):
1275 1276 1277 1278
        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))
1279
          else:
1280 1281
            xml.append('<%s>%s</%s>' % (child.tag, child.text, child.tag))
        xml.append('</movement>')
1282

1283
    xml.append('</transaction></journal>')
1284

1285
    return ''.join(xml)
1286

Łukasz Nowak's avatar
Łukasz Nowak committed
1287 1288 1289
  def agregateAndSendUsage(self):
    """Will agregate usage from each Computer Partition.
    """
1290 1291 1292 1293
    # Prepares environment
    self.checkEnvironmentAndCreateStructure()
    self._launchSupervisord()

Łukasz Nowak's avatar
Łukasz Nowak committed
1294 1295
    slap_computer_usage = self.slap.registerComputer(self.computer_id)
    computer_partition_usage_list = []
1296
    self.logger.info('Aggregating and sending usage reports...')
Łukasz Nowak's avatar
Łukasz Nowak committed
1297

1298 1299 1300 1301 1302 1303 1304 1305 1306
    #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(
1307
          __name__,
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
          '../../../../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(
1318
          __name__,
1319 1320
          '../../../../slapos/slap/doc/partition_consumption.xsd')

Łukasz Nowak's avatar
Łukasz Nowak committed
1321
    clean_run = True
1322
    # Loop over the different computer partitions
1323 1324
    computer_partition_list = self.FilterComputerPartitionList(
       slap_computer_usage.getComputerPartitionList())
1325

1326
    for computer_partition in computer_partition_list:
1327 1328
      try:
        computer_partition_id = computer_partition.getId()
1329

1330
        # We want to execute all the script in the report folder
1331 1332 1333 1334 1335 1336 1337
        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
1338

1339
        # We now generate the pseudorandom name for the xml file
1340 1341 1342 1343 1344
        # 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
1345

1346 1347 1348 1349 1350
        failed_script_list = []
        for script in script_list_to_run:
          invocation_list = []
          invocation_list.append(os.path.join(instance_path, 'etc', 'report',
            script))
1351
          # We add the xml_file name to the invocation_list
1352 1353 1354
          #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
1355

1356
          invocation_list.append(path_to_slapreport)
1357
          # Dropping privileges
1358 1359 1360 1361 1362 1363
          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,
1364
                                      preexec_fn=lambda: dropPrivileges(uid, gid, logger=self.logger),
Marco Mariani's avatar
Marco Mariani committed
1365 1366
                                      cwd=os.path.join(instance_path, 'etc', 'report'),
                                      env=None,
Marco Mariani's avatar
Marco Mariani committed
1367
                                      stdout=subprocess.PIPE,
1368 1369
                                      stderr=subprocess.STDOUT,
                                      logger=self.logger)
1370 1371 1372 1373
          if process_handler.returncode is None:
            process_handler.kill()
          if process_handler.returncode != 0:
            clean_run = False
1374
            failed_script_list.append("Script %r failed." % script)
1375
            self.logger.warning('Failed to run %r' % invocation_list)
1376
          if len(failed_script_list):
1377
            computer_partition.error('\n'.join(failed_script_list), logger=self.logger)
1378 1379
      # Whatever happens, don't stop processing other instances
      except Exception:
1380 1381
        self.logger.exception('Cannot run usage script(s) for %r:' %
                                  computer_partition.getId())
Łukasz Nowak's avatar
Łukasz Nowak committed
1382

1383
    # Now we loop through the different computer partitions to report
Łukasz Nowak's avatar
Łukasz Nowak committed
1384
    report_usage_issue_cp_list = []
1385
    for computer_partition in computer_partition_list:
1386 1387 1388 1389
      try:
        filename_delete_list = []
        computer_partition_id = computer_partition.getId()
        instance_path = os.path.join(self.instance_root, computer_partition_id)
1390
        dir_report_list = [os.path.join(instance_path, 'var', 'xml_report'),
1391
            os.path.join(self.instance_root, 'var', 'xml_report',
1392
                         computer_partition_id)]
1393

1394 1395 1396 1397 1398
        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)
1399
          else:
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
            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
1424

1425 1426 1427
          # 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))
1428 1429 1430

      # Whatever happens, don't stop processing other instances
      except Exception:
1431 1432
        self.logger.exception('Cannot run usage script(s) for %r:' %
                                computer_partition.getId())
1433 1434

    for computer_partition_usage in computer_partition_usage_list:
Marco Mariani's avatar
Marco Mariani committed
1435 1436
      self.logger.info('computer_partition_usage_list: %s - %s' %
                       (computer_partition_usage.usage, computer_partition_usage.getId()))
1437

1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
    filename_delete_list = []
    computer_report_dir = os.path.join(self.instance_root,
                                 'var', 'xml_report', self.computer_id)

    # 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(computer_report_dir):
      filename_list = os.listdir(computer_report_dir)
    else:
      filename_list = []

    for filename in filename_list:

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

      if self.validateXML(usage, computer_consumption_model):
        self.logger.info('XML file generated by asXML is valid')
        slap_computer_usage.reportUsage(usage)
        filename_delete_list.append(filename)
      else:
        self.logger.info('XML file is invalid %s' % filename)

    # After sending the aggregated file we remove all the valid xml reports
    for filename in filename_delete_list:
      os.remove(os.path.join(computer_report_dir, filename))

1466
    # If there is, at least, one report
1467
    if computer_partition_usage_list != []:
Łukasz Nowak's avatar
Łukasz Nowak committed
1468
      try:
1469
        # We generate the final XML report with asXML method
1470 1471
        computer_consumption = self.asXML(computer_partition_usage_list)

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

1474
        # We test the XML report before sending it
1475
        if self.validateXML(computer_consumption, computer_consumption_model):
1476
          self.logger.info('XML file generated by asXML is valid')
1477 1478
          slap_computer_usage.reportUsage(computer_consumption)
        else:
1479
          self.logger.info('XML file generated by asXML is not valid !')
1480
          raise ValueError('XML file generated by asXML is not valid !')
Łukasz Nowak's avatar
Łukasz Nowak committed
1481
      except Exception:
1482
        issue = "Cannot report usage for %r: %s" % (
Marco Mariani's avatar
Marco Mariani committed
1483 1484
            computer_partition.getId(),
            traceback.format_exc())
1485
        self.logger.info(issue)
1486
        computer_partition.error(issue, logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
1487 1488
        report_usage_issue_cp_list.append(computer_partition_id)

1489
    for computer_partition in computer_partition_list:
1490
      if computer_partition.getState() == COMPUTER_PARTITION_DESTROYED_STATE:
1491
        destroyed = False
Łukasz Nowak's avatar
Łukasz Nowak committed
1492
        try:
1493
          computer_partition_id = computer_partition.getId()
1494
          try:
1495 1496
            software_url = computer_partition.getSoftwareRelease().getURI()
            software_path = os.path.join(self.software_root, md5digest(software_url))
1497 1498 1499
          except (NotFoundError, TypeError):
            software_url = None
            software_path = None
1500

1501 1502 1503 1504 1505
          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(
1506
              _getSupervisordConfigurationDirectory(self.instance_root), '%s.conf' %
1507 1508 1509 1510 1511 1512 1513 1514
              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,
1515
            buildout=self.buildout,
1516
            logger=self.logger,
1517
            instance_storage_home=self.instance_storage_home,
1518
            ipv4_global_network=self.ipv4_global_network,
1519
          )
Łukasz Nowak's avatar
Łukasz Nowak committed
1520 1521 1522 1523
          local_partition.stop()
          try:
            computer_partition.stopped()
          except (SystemExit, KeyboardInterrupt):
1524
            computer_partition.error(traceback.format_exc(), logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
1525 1526 1527
            raise
          except Exception:
            pass
1528
          if computer_partition.getId() in report_usage_issue_cp_list:
1529 1530
            self.logger.info('Ignoring destruction of %r, as no report usage was sent' %
                                computer_partition.getId())
1531
            continue
1532
          destroyed = local_partition.destroy()
Łukasz Nowak's avatar
Łukasz Nowak committed
1533
        except (SystemExit, KeyboardInterrupt):
1534
          computer_partition.error(traceback.format_exc(), logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
1535 1536 1537
          raise
        except Exception:
          clean_run = False
1538
          self.logger.exception('')
Marco Mariani's avatar
Marco Mariani committed
1539
          exc = traceback.format_exc()
1540
          computer_partition.error(exc, logger=self.logger)
Łukasz Nowak's avatar
Łukasz Nowak committed
1541
        try:
1542 1543
          if destroyed:
            computer_partition.destroyed()
Marco Mariani's avatar
Marco Mariani committed
1544
        except NotFoundError:
1545 1546 1547
          self.logger.debug('Ignored slap error while trying to inform about '
                            'destroying not fully configured Computer Partition %r' %
                                computer_partition.getId())
1548
        except ServerError as server_error:
1549 1550 1551
          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
1552

1553
    self.logger.info('Finished usage reports.')
1554 1555 1556 1557 1558

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