views.py 33.7 KB
Newer Older
1
# -*- coding: utf-8 -*-
Marco Mariani's avatar
Marco Mariani committed
2
# vim: set et sts=2:
3 4
##############################################################################
#
5
# Copyright (c) 2010, 2011, 2012, 2013, 2014 Vifib SARL and Contributors.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
# All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

31 32
import random
import string
33
import time
34
from datetime import datetime
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
35
from slapos.slap.slap import Computer, ComputerPartition, \
36
    SoftwareRelease, SoftwareInstance, NotFoundError
Marco Mariani's avatar
Marco Mariani committed
37
from slapos.proxy.db_version import DB_VERSION
38
import slapos.slap
39 40
from slapos.util import bytes2str, unicode2str, sqlite_connect, \
    xml2dict, dict2xml
Łukasz Nowak's avatar
Łukasz Nowak committed
41

Marco Mariani's avatar
Marco Mariani committed
42
from flask import g, Flask, request, abort
Bryton Lacquement's avatar
Bryton Lacquement committed
43 44 45 46
from slapos.util import loads, dumps

import six
from six.moves import range
47
from six.moves.urllib.parse import urlparse
48

Łukasz Nowak's avatar
Łukasz Nowak committed
49 50
app = Flask(__name__)

51
EMPTY_DICT_XML = dumps({})
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
52

Łukasz Nowak's avatar
Łukasz Nowak committed
53 54 55
class UnauthorizedError(Exception):
  pass

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

Łukasz Nowak's avatar
Łukasz Nowak committed
57
def partitiondict2partition(partition):
58
  slap_partition = ComputerPartition(partition['computer_reference'],
Łukasz Nowak's avatar
Łukasz Nowak committed
59
      partition['reference'])
60 61 62
  slap_partition._software_release_document = None
  slap_partition._requested_state = 'destroyed'
  slap_partition._need_modification = 0
63 64
  slap_partition._instance_guid = '%(computer_reference)s-%(reference)s' \
    % partition
65

66 67
  root_partition = getRootPartition(partition['reference'])

Łukasz Nowak's avatar
Łukasz Nowak committed
68 69
  if partition['software_release']:
    slap_partition._need_modification = 1
70
    slap_partition._requested_state = partition['requested_state']
71 72
    slap_partition._parameter_dict = xml2dict(partition['xml'])
    address_list = []
73
    full_address_list = []
74
    for address in execute_db('partition_network',
75 76
                              'SELECT * FROM %s WHERE partition_reference=? AND computer_reference=?',
                              [partition['reference'], partition['computer_reference']]):
77 78
      address_list.append((address['reference'], address['address']))
    slap_partition._parameter_dict['ip_list'] = address_list
79
    slap_partition._parameter_dict['full_address_list'] = full_address_list
80 81
    slap_partition._parameter_dict['slap_software_type'] = \
        partition['software_type']
82 83 84 85
    slap_partition._parameter_dict['instance_title'] = \
        partition['partition_reference']
    slap_partition._parameter_dict['root_instance_title'] = \
        root_partition['partition_reference']
86
    if partition['slave_instance_list'] is not None:
87
      slap_partition._parameter_dict['slave_instance_list'] = \
Bryton Lacquement's avatar
Bryton Lacquement committed
88
          loads(partition['slave_instance_list'].encode('utf-8'))
89 90
    else:
      slap_partition._parameter_dict['slave_instance_list'] = []
91 92 93
    timestamp = partition['timestamp']
    if timestamp:
      slap_partition._parameter_dict['timestamp'] = str(timestamp)
94 95
    slap_partition._connection_dict = xml2dict(partition['connection_xml'])
    slap_partition._software_release_document = SoftwareRelease(
Łukasz Nowak's avatar
Łukasz Nowak committed
96
      software_release=partition['software_release'],
97
      computer_guid=partition['computer_reference'])
98

Łukasz Nowak's avatar
Łukasz Nowak committed
99 100
  return slap_partition

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

102
def execute_db(table, query, args=(), one=False, db_version=None, db=None):
103 104
  if not db:
    db = g.db
105 106 107
  if not db_version:
    db_version = DB_VERSION
  query = query % (table + db_version,)
108
  app.logger.debug(query)
Łukasz Nowak's avatar
Łukasz Nowak committed
109
  try:
110
    cur = db.execute(query, args)
Łukasz Nowak's avatar
Łukasz Nowak committed
111 112 113 114 115 116 117
  except:
    app.logger.error('There was some issue during processing query %r on table %r with args %r' % (query, table, args))
    raise
  rv = [dict((cur.description[idx][0], value)
    for idx, value in enumerate(row)) for row in cur.fetchall()]
  return (rv[0] if rv else None) if one else rv

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

Łukasz Nowak's avatar
Łukasz Nowak committed
119
def connect_db():
120
  return sqlite_connect(app.config['DATABASE_URI'])
Łukasz Nowak's avatar
Łukasz Nowak committed
121

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
def _getTableList():
  return g.db.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY Name").fetchall()

def _getCurrentDatabaseSchemaVersion():
  """
  Return version of database schema.
  As there is no actual definition of version, analyse
  name of all tables (containing version) and take the
  highest version (as several versions can live in the db).
  """
  # XXX: define an actual version and proper migration/repair procedure.
  version = -1
  for table_name in _getTableList():
    try:
      table_version = int(table_name[0][-2:])
    except ValueError:
      table_version = int(table_name[0][-1:])
    if table_version > version:
      version = table_version
  return str(version)

def _upgradeDatabaseIfNeeded():
  """
  Analyses current database compared to defined schema,
  and adapt tables/data it if needed.
  """
  current_schema_version = _getCurrentDatabaseSchemaVersion()
  # If version of current database is not old, do nothing
  if current_schema_version == DB_VERSION:
    return
152

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  previous_table_list = _getTableList()
  # first, make a backup of current database
  if current_schema_version != '-1':
    backup_file_name = "{}-backup-{}to{}-{}.sql".format(
        app.config['DATABASE_URI'],
        current_schema_version,
        DB_VERSION,
        datetime.now().isoformat())
    app.logger.info(
        'Old schema detected: Creating a backup of current tables at %s',
        backup_file_name
    )
    with open(backup_file_name, 'w') as f:
      for line in g.db.iterdump():
          f.write('%s\n' % line)

Bryton Lacquement's avatar
Bryton Lacquement committed
169 170
  with app.open_resource('schema.sql', 'r') as f:
    schema = f.read() % dict(version=DB_VERSION, computer=app.config['computer_id'])
171 172 173 174 175 176 177 178 179 180 181 182 183
  g.db.cursor().executescript(schema)
  g.db.commit()

  if current_schema_version == '-1':
    return

  # Migrate all data to new tables
  app.logger.info('Old schema detected: Migrating old tables...')
  for table in ('software', 'computer', 'partition', 'slave', 'partition_network'):
    for row in execute_db(table, 'SELECT * from %s', db_version=current_schema_version):
      columns = ', '.join(row.keys())
      placeholders = ':'+', :'.join(row.keys())
      query = 'INSERT INTO %s (%s) VALUES (%s)' % ('%s', columns, placeholders)
184
      execute_db(table, query, row)
185 186 187
  # then drop old tables
  for previous_table in previous_table_list:
    g.db.execute("DROP table %s" % previous_table)
188 189 190
  g.db.commit()

is_schema_already_executed = False
Łukasz Nowak's avatar
Łukasz Nowak committed
191 192 193
@app.before_request
def before_request():
  g.db = connect_db()
194 195 196 197
  global is_schema_already_executed
  if not is_schema_already_executed:
    _upgradeDatabaseIfNeeded()
    is_schema_already_executed = True
Łukasz Nowak's avatar
Łukasz Nowak committed
198

199

Łukasz Nowak's avatar
Łukasz Nowak committed
200 201 202 203 204 205 206 207
@app.after_request
def after_request(response):
  g.db.commit()
  g.db.close()
  return response

@app.route('/getComputerInformation', methods=['GET'])
def getComputerInformation():
Cédric de Saint Martin's avatar
Cédric de Saint Martin committed
208 209
  # Kept only for backward compatiblity
  return getFullComputerInformation()
210 211 212

@app.route('/getFullComputerInformation', methods=['GET'])
def getFullComputerInformation():
Łukasz Nowak's avatar
Łukasz Nowak committed
213
  computer_id = request.args['computer_id']
214 215 216 217 218 219 220 221
  computer_list = execute_db('computer', 'SELECT * FROM %s WHERE reference=?', [computer_id])
  if len(computer_list) != 1:
    # Backward compatibility
    if computer_id != app.config['computer_id']:
      raise NotFoundError('%s is not registered.' % computer_id)
  slap_computer = Computer(computer_id)
  slap_computer._software_release_list = []
  for sr in execute_db('software', 'select * from %s WHERE computer_reference=?', [computer_id]):
222 223 224 225 226
    software_release = SoftwareRelease(
        software_release=sr['url'],
        computer_guid=computer_id)
    software_release._requested_state = sr['requested_state']
    slap_computer._software_release_list.append(software_release)
227 228 229 230
  slap_computer._computer_partition_list = []
  for partition in execute_db('partition', 'SELECT * FROM %s WHERE computer_reference=?', [computer_id]):
    slap_computer._computer_partition_list.append(partitiondict2partition(
      partition))
Bryton Lacquement's avatar
Bryton Lacquement committed
231
  return dumps(slap_computer)
Łukasz Nowak's avatar
Łukasz Nowak committed
232 233 234

@app.route('/setComputerPartitionConnectionXml', methods=['POST'])
def setComputerPartitionConnectionXml():
235
  slave_reference = request.form.get('slave_reference', None)
Bryton Lacquement's avatar
Bryton Lacquement committed
236 237 238
  computer_partition_id = unicode2str(request.form['computer_partition_id'])
  computer_id = unicode2str(request.form['computer_id'])
  connection_xml = dict2xml(loads(request.form['connection_xml'].encode('utf-8')))
239
  if not slave_reference or slave_reference == 'None':
240 241
    query = 'UPDATE %s SET connection_xml=? WHERE reference=? AND computer_reference=?'
    argument_list = [connection_xml, computer_partition_id, computer_id]
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
242
    execute_db('partition', query, argument_list)
243 244 245 246 247 248 249
    # Update timestamp of parent partition.
    requested_by = execute_db('partition',
      'SELECT requested_by FROM %s WHERE reference=? AND computer_reference=?',
      (computer_partition_id, computer_id), one=True)['requested_by']
    execute_db('partition',
      "UPDATE %s SET timestamp=? WHERE reference=? AND computer_reference=?",
      (time.time(), requested_by, computer_id))
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
250 251
  else:
    query = 'UPDATE %s SET connection_xml=? , hosted_by=? WHERE reference=?'
252
    argument_list = [connection_xml, computer_partition_id, slave_reference]
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
253
    execute_db('slave', query, argument_list)
254
  return 'done'
Łukasz Nowak's avatar
Łukasz Nowak committed
255 256 257 258 259

@app.route('/buildingSoftwareRelease', methods=['POST'])
def buildingSoftwareRelease():
  return 'Ignored'

260 261 262 263 264 265 266 267
@app.route('/destroyedSoftwareRelease', methods=['POST'])
def destroyedSoftwareRelease():
  execute_db(
    'software',
    'DELETE FROM %s WHERE url = ? and computer_reference=? ',
    [request.form['url'], request.form['computer_id']])
  return 'OK'

Łukasz Nowak's avatar
Łukasz Nowak committed
268 269 270 271 272 273 274 275 276 277 278 279
@app.route('/availableSoftwareRelease', methods=['POST'])
def availableSoftwareRelease():
  return 'Ignored'

@app.route('/softwareReleaseError', methods=['POST'])
def softwareReleaseError():
  return 'Ignored'

@app.route('/softwareInstanceError', methods=['POST'])
def softwareInstanceError():
  return 'Ignored'

280 281
@app.route('/softwareInstanceBang', methods=['POST'])
def softwareInstanceBang():
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
  partition_list = [getRootPartition(
    unicode2str(request.form['computer_partition_id']))['reference']]
  # Now that we have the root partition, browse recursively
  # to update the timestamp of all partitions in the instance.
  now = time.time()
  while True:
    try:
      partition_id = partition_list.pop()
    except IndexError:
      return 'OK'
    execute_db('partition',
      "UPDATE %s SET timestamp=? WHERE reference=?", (now, partition_id))
    partition_list += (partition['reference'] for partition in execute_db(
      'partition', "SELECT reference FROM %s WHERE requested_by=?",
      (partition_id,)))
297

Łukasz Nowak's avatar
Łukasz Nowak committed
298 299 300 301 302 303 304 305 306 307 308 309
@app.route('/startedComputerPartition', methods=['POST'])
def startedComputerPartition():
  return 'Ignored'

@app.route('/stoppedComputerPartition', methods=['POST'])
def stoppedComputerPartition():
  return 'Ignored'

@app.route('/destroyedComputerPartition', methods=['POST'])
def destroyedComputerPartition():
  return 'Ignored'

Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
310 311 312 313 314 315 316
@app.route('/useComputer', methods=['POST'])
def useComputer():
  return 'Ignored'

@app.route('/loadComputerConfigurationFromXML', methods=['POST'])
def loadComputerConfigurationFromXML():
  xml = request.form['xml']
Bryton Lacquement's avatar
Bryton Lacquement committed
317
  computer_dict = loads(xml.encode('utf-8'))
318 319
  execute_db('computer', 'INSERT OR REPLACE INTO %s values(:reference, :address, :netmask)',
             computer_dict)
320 321 322 323 324

  # remove references to old partitions.
  execute_db('partition', 'DELETE FROM %s WHERE computer_reference = :reference', computer_dict)
  execute_db('partition_network', 'DELETE FROM %s WHERE computer_reference = :reference', computer_dict)

325 326 327 328 329 330
  for partition in computer_dict['partition_list']:
    partition['computer_reference'] = computer_dict['reference']
    execute_db('partition', 'INSERT OR IGNORE INTO %s (reference, computer_reference) values(:reference, :computer_reference)', partition)
    for address in partition['address_list']:
      address['reference'] = partition['tap']['name']
      address['partition_reference'] = partition['reference']
331
      address['computer_reference'] = partition['computer_reference']
332
      execute_db('partition_network', 'INSERT OR REPLACE INTO %s (reference, partition_reference, computer_reference, address, netmask) values(:reference, :partition_reference, :computer_reference, :addr, :netmask)', address)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
333

334
  return 'done'
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
335 336 337

@app.route('/registerComputerPartition', methods=['GET'])
def registerComputerPartition():
Bryton Lacquement's avatar
Bryton Lacquement committed
338 339
  computer_reference = unicode2str(request.args['computer_reference'])
  computer_partition_reference = unicode2str(request.args['computer_partition_reference'])
340 341 342 343
  partition = execute_db('partition', 'SELECT * FROM %s WHERE reference=? and computer_reference=?',
      [computer_partition_reference, computer_reference], one=True)
  if partition is None:
    raise UnauthorizedError
Bryton Lacquement's avatar
Bryton Lacquement committed
344
  return dumps(partitiondict2partition(partition))
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
345 346 347 348 349

@app.route('/supplySupply', methods=['POST'])
def supplySupply():
  url = request.form['url']
  computer_id = request.form['computer_id']
350 351 352 353 354 355 356 357 358 359
  state = request.form['state']
  if state not in ('available', 'destroyed'):
    raise ValueError("Wrong state %s" % state)

  execute_db(
    'software',
    'INSERT OR REPLACE INTO %s VALUES(?, ?, ?)',
    [url, computer_id, state])

  return 'Supplied %r to be %s' % (url, state)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
360 361


Łukasz Nowak's avatar
Łukasz Nowak committed
362 363
@app.route('/requestComputerPartition', methods=['POST'])
def requestComputerPartition():
364
  parsed_request_dict = parseRequestComputerPartitionForm(request.form)
365
  # Is it a slave instance?
Bryton Lacquement's avatar
Bryton Lacquement committed
366
  slave = loads(request.form.get('shared_xml', EMPTY_DICT_XML).encode('utf-8'))
367 368 369

  # Check first if instance is already allocated
  if slave:
370 371 372 373 374 375 376 377 378
    # slapproxy cannot request frontends, but we can workaround common cases,
    # so that during tests promises are succesful.
    if not isRequestToBeForwardedToExternalMaster(parsed_request_dict):
      # if client request a "simple" frontend for an URL, we can tell this
      # client to use the URL directly.
      apache_frontend_sr_url_list = (
          'http://git.erp5.org/gitweb/slapos.git/blob_plain/HEAD:/software/apache-frontend/software.cfg',
      )
      if parsed_request_dict['software_release'] in apache_frontend_sr_url_list \
379
        and parsed_request_dict.get('software_type', '') in ('', 'RootSoftwareInstance', 'default'):
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
        url = parsed_request_dict['partition_parameter_kw'].get('url')
        if url:
          app.logger.warning("Bypassing frontend for %s => %s", parsed_request_dict, url)
          partition = ComputerPartition('', 'Fake frontend for {}'.format(url))
          partition.slap_computer_id = ''
          partition.slap_computer_partition_id = ''
          partition._parameter_dict = {}
          partition._connection_dict = {
            'secure_access': url,
            'domain': urlparse(url).netloc,
          }
          return dumps(partition)
      # another similar case is for KVM frontends. This is used in
      # request-slave-frontend from software/kvm/instance-kvm.cfg.jinja2
      # requested values by 'return' recipe are: url resource port domainname
      kvm_frontend_sr_url_list = (
          'http://git.erp5.org/gitweb/slapos.git/blob_plain/refs/tags/slapos-0.92:/software/kvm/software.cfg',
      )
      if parsed_request_dict['software_release'] in kvm_frontend_sr_url_list \
          and parsed_request_dict.get('software_type') in ('frontend', ):
        host = parsed_request_dict['partition_parameter_kw'].get('host')
        port = parsed_request_dict['partition_parameter_kw'].get('port')
        if host and port:
          # host is supposed to be ipv6 without brackets.
          if ':' in host and host[0] != '[':
            host = '[%s]' % host
          url = 'https://%s:%s/' % (host, port)
          app.logger.warning("Bypassing KVM VNC frontend for %s => %s", parsed_request_dict, url)
          partition = ComputerPartition('', 'Fake KVM VNC frontend for {}'.format(url))
          partition.slap_computer_id = ''
          partition.slap_computer_partition_id = ''
          partition._parameter_dict = {}
          partition._connection_dict = {
            'url': url,
            'domainname': host,
            'port': port,
            'path': '/'
          }
          return dumps(partition)
419

420 421
    # XXX: change schema to include a simple "partition_reference" which
    # is name of the instance. Then, no need to do complex search here.
422 423
    slave_reference = parsed_request_dict['partition_id'] + '_' + parsed_request_dict['partition_reference']
    requested_computer_id = parsed_request_dict['filter_kw'].get('computer_guid', app.config['computer_id'])
424
    matching_partition = getAllocatedSlaveInstance(slave_reference, requested_computer_id)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
425
  else:
426
    matching_partition = getAllocatedInstance(parsed_request_dict['partition_reference'])
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
427

428 429 430
  if matching_partition:
    # Then the instance is already allocated, just update it
    # XXX: split request and request slave into different update/allocate functions and simplify.
431 432
    # By default, ALWAYS request instance on default computer
    parsed_request_dict['filter_kw'].setdefault('computer_guid', app.config['computer_id'])
433
    if slave:
434
      software_instance = requestSlave(**parsed_request_dict)
435
    else:
436
      software_instance = requestNotSlave(**parsed_request_dict)
437 438
  else:
    # Instance is not yet allocated: try to do it.
439 440 441
    external_master_url = isRequestToBeForwardedToExternalMaster(parsed_request_dict)
    if external_master_url:
      return forwardRequestToExternalMaster(external_master_url, request.form)
442
    # XXX add support for automatic deployment on specific node depending on available SR and partitions on each Node.
443
    # Note: It only deploys on default node if SLA not specified
444
    # XXX: split request and request slave into different update/allocate functions and simplify.
445 446 447

    # By default, ALWAYS request instance on default computer
    parsed_request_dict['filter_kw'].setdefault('computer_guid', app.config['computer_id'])
448
    if slave:
449
      software_instance = requestSlave(**parsed_request_dict)
450
    else:
451
      software_instance = requestNotSlave(**parsed_request_dict)
Marco Mariani's avatar
Marco Mariani committed
452

453
  return dumps(software_instance)
Marco Mariani's avatar
Marco Mariani committed
454

455 456 457 458
def parseRequestComputerPartitionForm(form):
  """
  Parse without intelligence a form from a request(), return it.
  """
Bryton Lacquement's avatar
Bryton Lacquement committed
459 460 461 462 463 464 465 466 467 468 469
  parsed_dict = {
    'software_release': unicode2str(form['software_release']),
    'software_type': unicode2str(form.get('software_type')),
    'partition_reference': unicode2str(form.get('partition_reference', '')),
    'partition_id': unicode2str(form.get('computer_partition_id', '')),
    'partition_parameter_kw': loads(form.get('partition_parameter_xml', EMPTY_DICT_XML).encode('utf-8')),
    'filter_kw': loads(form.get('filter_xml', EMPTY_DICT_XML).encode('utf-8')),
    # Note: currently ignored for slave instance (slave instances
    # are always started).
    'requested_state': loads(form.get('state').encode('utf-8')),
  }
470 471 472

  return parsed_dict

Bryton Lacquement's avatar
Bryton Lacquement committed
473
run_id = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)])
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
def checkIfMasterIsCurrentMaster(master_url):
  """
  Because there are several ways to contact this server, we can't easily check
  in a request() if master_url is ourself or not. So we contact master_url,
  and if it returns an ID we know: it is ourself
  """
  # Dumb way: compare with listening host/port
  host = request.host
  port = request.environ['SERVER_PORT']
  if master_url == 'http://%s:%s/' % (host, port):
    return True

  # Hack way: call ourself
  slap = slapos.slap.slap()
  slap.initializeConnection(master_url)
  try:
Bryton Lacquement's avatar
Bryton Lacquement committed
490
    return run_id == bytes2str(slap._connection_helper.GET('/getRunId'))
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
  except:
    return False

@app.route('/getRunId', methods=['GET'])
def getRunId():
  return run_id

def checkMasterUrl(master_url):
  """
  Check if master_url doesn't represent ourself, and check if it is whitelisted
  in multimaster configuration.
  """
  if not master_url:
    return False

  if checkIfMasterIsCurrentMaster(master_url):
    # master_url is current server: don't forward
    return False

  master_entry = app.config.get('multimaster').get(master_url, None)
  # Check if this master is known
  if not master_entry:
    # Check if it is ourself
    if not master_url.startswith('https') and checkIfMasterIsCurrentMaster(master_url):
      return False
    app.logger.warning('External SlapOS Master URL %s is not listed in multimaster list.' % master_url)
    abort(404)

  return True

def isRequestToBeForwardedToExternalMaster(parsed_request_dict):
    """
    Check if we HAVE TO forward the request.
    Several cases:
     * The request specifies a master_url in filter_kw
     * The software_release of the request is in a automatic forward list
    """
    master_url = parsed_request_dict['filter_kw'].get('master_url')

    if checkMasterUrl(master_url):
      # Don't allocate the instance locally, but forward to specified master
      return master_url

    software_release = parsed_request_dict['software_release']
Bryton Lacquement's avatar
Bryton Lacquement committed
535
    for mutimaster_url, mutimaster_entry in six.iteritems(app.config.get('multimaster')):
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
      if software_release in mutimaster_entry['software_release_list']:
        # Don't allocate the instance locally, but forward to specified master
        return mutimaster_url
    return None

def forwardRequestToExternalMaster(master_url, request_form):
  """
  Forward instance request to external SlapOS Master.
  """
  master_entry = app.config.get('multimaster').get(master_url, {})
  key_file = master_entry.get('key')
  cert_file = master_entry.get('cert')
  if master_url.startswith('https') and (not key_file or not cert_file):
    app.logger.warning('External master %s configuration did not specify key or certificate.' % master_url)
    abort(404)
  if master_url.startswith('https') and not master_url.startswith('https') and (key_file or cert_file):
    app.logger.warning('External master %s configurqtion specifies key or certificate but is using plain http.' % master_url)
    abort(404)

  slap = slapos.slap.slap()
  if key_file:
    slap.initializeConnection(master_url, key_file=key_file, cert_file=cert_file)
  else:
    slap.initializeConnection(master_url)

Bryton Lacquement's avatar
Bryton Lacquement committed
561
  partition_reference = unicode2str(request_form['partition_reference'])
562 563 564 565 566
  # Store in database
  execute_db('forwarded_partition_request', 'INSERT OR REPLACE INTO %s values(:partition_reference, :master_url)',
             {'partition_reference':partition_reference, 'master_url': master_url})

  new_request_form = request_form.copy()
Bryton Lacquement's avatar
Bryton Lacquement committed
567
  filter_kw = loads(new_request_form['filter_xml'].encode('utf-8'))
568 569 570
  filter_kw['source_instance_id'] = partition_reference
  new_request_form['filter_xml'] = dumps(filter_kw)

571 572
  xml = slap._connection_helper.POST('/requestComputerPartition', data=new_request_form)
  partition = loads(xml)
573 574 575 576 577 578

  # XXX move to other end
  partition._master_url = master_url

  return dumps(partition)

579 580
def getAllocatedInstance(partition_reference):
  """
581
  Look for existence of instance, if so return the
582 583 584 585 586 587 588 589
  corresponding partition dict, else return None
  """
  args = []
  a = args.append
  table = 'partition'
  q = 'SELECT * FROM %s WHERE partition_reference=?'
  a(partition_reference)
  return execute_db(table, q, args, one=True)
Marco Mariani's avatar
Marco Mariani committed
590

591 592
def getAllocatedSlaveInstance(slave_reference, requested_computer_id):
  """
593
  Look for existence of instance, if so return the
594 595 596 597 598 599 600 601 602 603 604 605 606
  corresponding partition dict, else return None
  """
  args = []
  a = args.append
  # XXX: Scope currently depends on instance which requests slave.
  # Meaning that two different instances requesting the same slave will
  # result in two different allocated slaves.
  table = 'slave'
  q = 'SELECT * FROM %s WHERE reference=? and computer_reference=?'
  a(slave_reference)
  a(requested_computer_id)
  # XXX: check there is only one result
  return execute_db(table, q, args, one=True)
607

608
def getRootPartition(reference):
609
  """Climb the partitions tree up by 'requested_by' link to get the root partition."""
610
  p = 'SELECT * FROM %s WHERE reference=?'
611
  partition = execute_db('partition', p, [reference], one=True)
612
  if partition is None:
613
    app.logger.warning("Nonexisting partition \"{}\". Known are\n{!s}".format(
614 615
      reference, execute_db("partition", "select reference, requested_by from %s")))
    return None
616

617 618 619 620 621 622 623
  while True:
    requested_by = partition['requested_by']
    if requested_by is None or requested_by == reference:
      return partition
    parent_partition = execute_db('partition', p, (requested_by,), one=True)
    if parent_partition is None:
      return partition
624
    partition = parent_partition
625
    reference = requested_by
626

627 628 629
def requestNotSlave(software_release, software_type, partition_reference, partition_id, partition_parameter_kw, filter_kw, requested_state):
  instance_xml = dict2xml(partition_parameter_kw)
  requested_computer_id = filter_kw['computer_guid']
630

631 632 633
  partition = execute_db('partition',
    'SELECT * FROM %s WHERE partition_reference=?',
    (partition_reference,), one=True)
634 635 636 637 638

  args = []
  a = args.append
  q = 'UPDATE %s SET slap_state="busy"'

Łukasz Nowak's avatar
Łukasz Nowak committed
639 640
  if partition is None:
    partition = execute_db('partition',
641 642
        'SELECT * FROM %s WHERE slap_state="free" and computer_reference=?',
        [requested_computer_id], one=True)
Łukasz Nowak's avatar
Łukasz Nowak committed
643 644
    if partition is None:
      app.logger.warning('No more free computer partition')
645
      abort(404)
646 647 648 649 650 651
    if partition_reference:
      q += ' ,partition_reference=?'
      a(partition_reference)
    if partition_id:
      q += ' ,requested_by=?'
      a(partition_id)
652 653
    if not software_type:
      software_type = 'RootSoftwareInstance'
654
  else:
655 656 657 658 659 660 661
    if partition['requested_by']:
      root_partition = getRootPartition(partition['requested_by'])
      if root_partition and root_partition['requested_state'] != "started":
        # propagate parent state to child
        # child can be stopped or destroyed while parent is started
        requested_state = root_partition['requested_state']

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
  timestamp = partition['timestamp']
  changed = timestamp is None
  for k, v in (('requested_state', requested_state or
                                   partition['requested_state']),
               ('software_release', software_release),
               ('software_type', software_type),
               ('xml', instance_xml)):
    if partition[k] != v:
      q += ', %s=?' % k
      a(v)
      changed = True

  if changed:
    timestamp = time.time()
    q += ', timestamp=?'
    a(timestamp)
678

679
  q += ' WHERE reference=? AND computer_reference=?'
Bryton Lacquement's avatar
Bryton Lacquement committed
680 681
  a(partition['reference'])
  a(partition['computer_reference'])
682

Łukasz Nowak's avatar
Łukasz Nowak committed
683
  execute_db('partition', q, args)
684
  partition = execute_db('partition', 'SELECT * FROM %s WHERE reference=? and computer_reference=?',
Bryton Lacquement's avatar
Bryton Lacquement committed
685
      [partition['reference'], partition['computer_reference']], one=True)
Łukasz Nowak's avatar
Łukasz Nowak committed
686 687 688
  address_list = []
  for address in execute_db('partition_network', 'SELECT * FROM %s WHERE partition_reference=?', [partition['reference']]):
    address_list.append((address['reference'], address['address']))
689 690

  # XXX it should be ComputerPartition, not a SoftwareInstance
691 692 693 694 695 696 697 698 699 700 701 702 703 704
  parameter_dict = xml2dict(partition['xml'])
  parameter_dict['timestamp'] = str(partition['timestamp'])
  return SoftwareInstance(
    _connection_dict=xml2dict(partition['connection_xml']),
    _parameter_dict=parameter_dict,
    connection_xml=partition['connection_xml'],
    slap_computer_id=partition['computer_reference'],
    slap_computer_partition_id=partition['reference'],
    slap_software_release_url=partition['software_release'],
    slap_server_url='slap_server_url',
    slap_software_type=partition['software_type'],
    _instance_guid='%(computer_reference)s-%(reference)s' % partition,
    _requested_state=requested_state or 'started',
    ip_list=address_list)
Łukasz Nowak's avatar
Łukasz Nowak committed
705

706
def requestSlave(software_release, software_type, partition_reference, partition_id, partition_parameter_kw, filter_kw, requested_state):
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
707
  """
708 709 710 711 712
  Function to organise link between slave and master.
  Slave information are stored in places:
  1. slave table having information such as slave reference,
      connection information to slave (given by slave master),
      hosted_by and asked_by reference.
713
  2. A dictionary in slave_instance_list of selected slave master
714 715
      in which are stored slave_reference, software_type, slave_title and
      partition_parameter_kw stored as individual keys.
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
716
  """
717
  requested_computer_id = filter_kw['computer_guid']
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
718
  instance_xml = dict2xml(partition_parameter_kw)
719

720
  # We will search for a master corresponding to request
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
721 722
  args = []
  a = args.append
723
  q = 'SELECT * FROM %s WHERE software_release=? and computer_reference=?'
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
724
  a(software_release)
725
  a(requested_computer_id)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
726 727 728
  if software_type:
    q += ' AND software_type=?'
    a(software_type)
729 730
  if 'instance_guid' in filter_kw:
    q += ' AND reference=?'
731 732
    # instance_guid should be like: %s-%s % (requested_computer_id, partition_id)
    # But code is convoluted here, so we check
733
    instance_guid = filter_kw['instance_guid']
734 735 736 737
    if instance_guid.startswith(requested_computer_id):
      a(instance_guid[len(requested_computer_id) + 1:])
    else:
      a(instance_guid)
738

Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
739 740
  partition = execute_db('partition', q, args, one=True)
  if partition is None:
741
    app.logger.warning('No partition corresponding to slave request: %s' % args)
742
    abort(404)
743

Marco Mariani's avatar
Marco Mariani committed
744
  # We set slave dictionary as described in docstring
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
745 746 747 748 749
  new_slave = {}
  slave_reference = partition_id + '_' + partition_reference
  new_slave['slave_title'] = slave_reference
  new_slave['slap_software_type'] = software_type
  new_slave['slave_reference'] = slave_reference
750

751
  for key in partition_parameter_kw:
752
    new_slave[key] = partition_parameter_kw[key]
Łukasz Nowak's avatar
Łukasz Nowak committed
753

754
  # Add slave to partition slave_list if not present else replace information
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
755
  slave_instance_list = partition['slave_instance_list']
Bryton Lacquement's avatar
Bryton Lacquement committed
756 757 758
  if slave_instance_list:
    slave_instance_list = loads(slave_instance_list.encode('utf-8'))
    for i, x in enumerate(slave_instance_list):
759
      if x['slave_reference'] == slave_reference:
Bryton Lacquement's avatar
Bryton Lacquement committed
760 761 762 763 764 765
        slave_instance_list[i] = new_slave
        break
    else:
      slave_instance_list.append(new_slave)
  else:
    slave_instance_list = [new_slave]
Łukasz Nowak's avatar
Łukasz Nowak committed
766

767
  # Update slave_instance_list in database
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
768 769 770
  args = []
  a = args.append
  q = 'UPDATE %s SET slave_instance_list=?'
Bryton Lacquement's avatar
Bryton Lacquement committed
771
  a(bytes2str(dumps(slave_instance_list)))
772
  q += ' WHERE reference=? and computer_reference=?'
Bryton Lacquement's avatar
Bryton Lacquement committed
773
  a(partition['reference'])
774
  a(requested_computer_id)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
775
  execute_db('partition', q, args)
776
  partition = execute_db('partition', 'SELECT * FROM %s WHERE reference=? and computer_reference=?',
Bryton Lacquement's avatar
Bryton Lacquement committed
777
      [partition['reference'], requested_computer_id], one=True)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
778 779

  # Add slave to slave table if not there
780 781
  slave = execute_db('slave', 'SELECT * FROM %s WHERE reference=? and computer_reference=?',
                     [slave_reference, requested_computer_id], one=True)
782
  if slave is None:
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
783
    execute_db('slave',
784 785 786 787
               'INSERT OR IGNORE INTO %s (reference,computer_reference,asked_by,hosted_by) values(:reference,:computer_reference,:asked_by,:hosted_by)',
               [slave_reference, requested_computer_id, partition_id, partition['reference']])
    slave = execute_db('slave', 'SELECT * FROM %s WHERE reference=? and computer_reference=?',
                       [slave_reference, requested_computer_id], one=True)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
788 789 790

  address_list = []
  for address in execute_db('partition_network',
791 792
                            'SELECT * FROM %s WHERE partition_reference=? and computer_reference=?',
                            [partition['reference'], partition['computer_reference']]):
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
793
    address_list.append((address['reference'], address['address']))
794 795

  # XXX it should be ComputerPartition, not a SoftwareInstance
796 797 798 799 800 801 802 803 804
  return SoftwareInstance(
    _connection_dict=xml2dict(slave['connection_xml']),
    _parameter_dict=xml2dict(instance_xml),
    slap_computer_id=partition['computer_reference'],
    slap_computer_partition_id=slave['hosted_by'],
    slap_software_release_url=partition['software_release'],
    slap_server_url='slap_server_url',
    slap_software_type=partition['software_type'],
    ip_list=address_list)
805 806 807

@app.route('/softwareInstanceRename', methods=['POST'])
def softwareInstanceRename():
Bryton Lacquement's avatar
Bryton Lacquement committed
808 809 810
  new_name = unicode2str(request.form['new_name'])
  computer_partition_id = unicode2str(request.form['computer_partition_id'])
  computer_id = unicode2str(request.form['computer_id'])
811 812 813 814

  q = 'UPDATE %s SET partition_reference = ? WHERE reference = ? AND computer_reference = ?'
  execute_db('partition', q, [new_name, computer_partition_id, computer_id])
  return 'done'
815

816 817
@app.route('/getComputerPartitionStatus', methods=['GET'])
def getComputerPartitionStatus():
Bryton Lacquement's avatar
Bryton Lacquement committed
818
  return dumps('Not implemented.')
819

820 821
@app.route('/computerBang', methods=['POST'])
def computerBang():
Bryton Lacquement's avatar
Bryton Lacquement committed
822
  return dumps('')
823

824 825 826
@app.route('/getComputerPartitionCertificate', methods=['GET'])
def getComputerPartitionCertificate():
  # proxy does not use partition certificate, but client calls this.
Bryton Lacquement's avatar
Bryton Lacquement committed
827
  return dumps({'certificate': '', 'key': ''})
828

829 830 831 832 833 834 835 836 837 838
@app.route('/getSoftwareReleaseListFromSoftwareProduct', methods=['GET'])
def getSoftwareReleaseListFromSoftwareProduct():
  software_product_reference = request.args.get('software_product_reference')
  software_release_url = request.args.get('software_release_url')

  if software_release_url:
    assert(software_product_reference is None)
    raise NotImplementedError('software_release_url parameter is not supported yet.')
  else:
    assert(software_product_reference is not None)
Bryton Lacquement's avatar
Bryton Lacquement committed
839
    if software_product_reference in app.config['software_product_list']:
840 841 842
      software_release_url_list =\
          [app.config['software_product_list'][software_product_reference]]
    else:
843
      software_release_url_list = []
Bryton Lacquement's avatar
Bryton Lacquement committed
844
    return dumps(software_release_url_list)
845