views.py 16.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010, 2011, 2012 Vifib SARL and Contributors.
# All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly 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.
#
##############################################################################

Łukasz Nowak's avatar
Łukasz Nowak committed
30 31 32
from flask import g, Flask, request, abort
import xml_marshaller
from lxml import etree
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
33
from slapos.slap.slap import Computer, ComputerPartition, \
34
    SoftwareRelease, SoftwareInstance, NotFoundError
Łukasz Nowak's avatar
Łukasz Nowak committed
35 36 37 38 39
import sqlite3

app = Flask(__name__)
DB_VERSION = app.open_resource('schema.sql').readline().strip().split(':')[1]

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

Łukasz Nowak's avatar
Łukasz Nowak committed
41 42 43
class UnauthorizedError(Exception):
  pass

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

Łukasz Nowak's avatar
Łukasz Nowak committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
def xml2dict(xml):
  result_dict = {}
  if xml is not None and xml != '':
    tree = etree.fromstring(xml.encode('utf-8'))
    for element in tree.iter(tag=etree.Element):
      if element.tag == 'parameter':
        key = element.get('id')
        value = result_dict.get(key, None)
        if value is not None:
          value = value + ' ' + element.text
        else:
          value = element.text
        result_dict[key] = value
  return result_dict

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

Łukasz Nowak's avatar
Łukasz Nowak committed
61 62 63 64 65 66
def dict2xml(dictionnary):
  instance = etree.Element('instance')
  for parameter_id, parameter_value in dictionnary.iteritems():
    # cast everything to string
    parameter_value = str(parameter_value)
    etree.SubElement(instance, "parameter",
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
67
                     attrib={'id': parameter_id}).text = parameter_value
Łukasz Nowak's avatar
Łukasz Nowak committed
68 69 70
  return etree.tostring(instance, pretty_print=True,
                                xml_declaration=True, encoding='utf-8')

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

Łukasz Nowak's avatar
Łukasz Nowak committed
72 73 74
def partitiondict2partition(partition):
  slap_partition = ComputerPartition(app.config['computer_id'],
      partition['reference'])
75 76 77 78
  slap_partition._software_release_document = None
  slap_partition._requested_state = 'destroyed'
  slap_partition._need_modification = 0

Łukasz Nowak's avatar
Łukasz Nowak committed
79 80
  if partition['software_release']:
    slap_partition._need_modification = 1
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    slap_partition._requested_state = 'started'
    slap_partition._parameter_dict = xml2dict(partition['xml'])
    address_list = []
    for address in execute_db('partition_network',
                              'SELECT * FROM %s WHERE partition_reference=?',
                              [partition['reference']]):
      address_list.append((address['reference'], address['address']))
    slap_partition._parameter_dict['ip_list'] = address_list
    slap_partition._parameter_dict['slap_software_type'] = \
        partition['software_type']
    if not partition['slave_instance_list'] == None:
      slap_partition._parameter_dict['slave_instance_list'] = \
          xml_marshaller.xml_marshaller.loads(partition['slave_instance_list'])
    slap_partition._connection_dict = xml2dict(partition['connection_xml'])
    slap_partition._software_release_document = SoftwareRelease(
Łukasz Nowak's avatar
Łukasz Nowak committed
96 97
      software_release=partition['software_release'],
      computer_guid=app.config['computer_id'])
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

Łukasz Nowak's avatar
Łukasz Nowak committed
102 103 104 105 106 107 108 109 110 111
def execute_db(table, query, args=(), one=False):
  try:
    cur = g.db.execute(query % (table + DB_VERSION,), args)
  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
112

Łukasz Nowak's avatar
Łukasz Nowak committed
113 114 115
def connect_db():
  return sqlite3.connect(app.config['DATABASE_URI'])

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

Łukasz Nowak's avatar
Łukasz Nowak committed
117 118 119 120
@app.before_request
def before_request():
  g.db = connect_db()
  schema = app.open_resource('schema.sql')
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
121
  schema = schema.read() % dict(version=DB_VERSION)
Łukasz Nowak's avatar
Łukasz Nowak committed
122 123 124 125 126 127 128 129 130 131 132
  g.db.cursor().executescript(schema)
  g.db.commit()

@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
133 134
  # Kept only for backward compatiblity
  return getFullComputerInformation()
135 136 137

@app.route('/getFullComputerInformation', methods=['GET'])
def getFullComputerInformation():
Łukasz Nowak's avatar
Łukasz Nowak committed
138 139 140 141 142 143 144 145 146 147 148 149 150
  computer_id = request.args['computer_id']
  if app.config['computer_id'] == computer_id:
    slap_computer = Computer(computer_id)
    slap_computer._software_release_list = []
    for sr in execute_db('software', 'select * from %s'):
      slap_computer._software_release_list.append(SoftwareRelease(
        software_release=sr['url'], computer_guid=computer_id))
    slap_computer._computer_partition_list = []
    for partition in execute_db('partition', 'SELECT * FROM %s'):
      slap_computer._computer_partition_list.append(partitiondict2partition(
        partition))
    return xml_marshaller.xml_marshaller.dumps(slap_computer)
  else:
151
    raise NotFoundError, "Only accept request for: %s" % \
Łukasz Nowak's avatar
Łukasz Nowak committed
152 153 154 155
                             app.config['computer_id']

@app.route('/setComputerPartitionConnectionXml', methods=['POST'])
def setComputerPartitionConnectionXml():
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
156
  slave_reference = request.form['slave_reference'].encode()
Łukasz Nowak's avatar
Łukasz Nowak committed
157 158 159
  computer_partition_id = request.form['computer_partition_id']
  connection_xml = request.form['connection_xml']
  connection_dict = xml_marshaller.xml_marshaller.loads(
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
160
                                            connection_xml.encode())
Łukasz Nowak's avatar
Łukasz Nowak committed
161
  connection_xml = dict2xml(connection_dict)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
162 163 164 165 166 167 168 169 170 171 172
  if slave_reference == 'None':
    query = 'UPDATE %s SET connection_xml=? WHERE reference=?'
    argument_list = [connection_xml, computer_partition_id.encode()]
    execute_db('partition', query, argument_list)
    return 'done'
  else:
    query = 'UPDATE %s SET connection_xml=? , hosted_by=? WHERE reference=?'
    argument_list = [connection_xml, computer_partition_id.encode(),
                     slave_reference]
    execute_db('slave', query, argument_list)
    return 'done'
Łukasz Nowak's avatar
Łukasz Nowak committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

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

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

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

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

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

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

@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
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
@app.route('/useComputer', methods=['POST'])
def useComputer():
  return 'Ignored'

@app.route('/loadComputerConfigurationFromXML', methods=['POST'])
def loadComputerConfigurationFromXML():
  xml = request.form['xml']
  computer_dict = xml_marshaller.xml_marshaller.loads(str(xml))
  if app.config['computer_id'] == computer_dict['reference']:
    execute_db('computer', 'INSERT OR REPLACE INTO %s values(:address, :netmask)',
        computer_dict)
    for partition in computer_dict['partition_list']:

      execute_db('partition', 'INSERT OR IGNORE INTO %s (reference) values(:reference)', partition)
      execute_db('partition_network', 'DELETE FROM %s WHERE partition_reference = ?', [partition['reference']])
      for address in partition['address_list']:
        address['reference'] = partition['tap']['name']
        address['partition_reference'] = partition['reference']
        execute_db('partition_network', 'INSERT OR REPLACE INTO %s (reference, partition_reference, address, netmask) values(:reference, :partition_reference, :addr, :netmask)', address)

    return 'done'
  else:
    raise UnauthorizedError, "Only accept request for: %s" % \
                             app.config['computer_id']

@app.route('/registerComputerPartition', methods=['GET'])
def registerComputerPartition():
  computer_reference = request.args['computer_reference']
  computer_partition_reference = request.args['computer_partition_reference']
  if app.config['computer_id'] == computer_reference:
    partition = execute_db('partition', 'SELECT * FROM %s WHERE reference=?',
      [computer_partition_reference.encode()], one=True)
    if partition is None:
      raise UnauthorizedError
    return xml_marshaller.xml_marshaller.dumps(
        partitiondict2partition(partition))
  else:
    raise UnauthorizedError, "Only accept request for: %s" % \
                             app.config['computer_id']

@app.route('/supplySupply', methods=['POST'])
def supplySupply():
  url = request.form['url']
  computer_id = request.form['computer_id']
  if app.config['computer_id'] == computer_id:
    execute_db('software', 'INSERT OR REPLACE INTO %s VALUES(?)', [url])
  else:
    raise UnauthorizedError, "Only accept request for: %s" % \
                             app.config['computer_id']
  return '%r added' % url


Łukasz Nowak's avatar
Łukasz Nowak committed
262 263
@app.route('/requestComputerPartition', methods=['POST'])
def requestComputerPartition():
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
264 265 266 267 268 269 270 271
  shared_xml = request.form.get('shared_xml')
  share = xml_marshaller.xml_marshaller.loads(shared_xml)
  if not share:
    return request_not_shared()
  else:
    return request_slave()

def request_not_shared():
Łukasz Nowak's avatar
Łukasz Nowak committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
  software_release = request.form['software_release'].encode()
  # some supported parameters
  software_type = request.form.get('software_type', 'RootSoftwareInstance'
      ).encode()
  partition_reference = request.form.get('partition_reference', '').encode()
  partition_id = request.form.get('computer_partition_id', '').encode()
  partition_parameter_kw = request.form.get('partition_parameter_xml', None)
  if partition_parameter_kw:
    partition_parameter_kw = xml_marshaller.xml_marshaller.loads(
                                              partition_parameter_kw.encode())
  else:
    partition_parameter_kw = {}
  instance_xml = dict2xml(partition_parameter_kw)
  args = []
  a = args.append
  q = 'SELECT * FROM %s WHERE software_release=?'
  a(software_release)
  if software_type:
    q += ' AND software_type=?'
    a(software_type)
  if partition_reference:
    q += ' AND partition_reference=?'
    a(partition_reference)
  if partition_id:
    q += ' AND requested_by=?'
    a(partition_id)
  partition = execute_db('partition', q, args, one=True)
  if partition is None:
    partition = execute_db('partition',
        'SELECT * FROM %s WHERE slap_state="free"', (), one=True)
    if partition is None:
      app.logger.warning('No more free computer partition')
      abort(408)
  args = []
  a = args.append
  q = 'UPDATE %s SET software_release=?, slap_state="busy"'
  a(software_release)
  if software_type:
    q += ' ,software_type=?'
    a(software_type)
  if partition_reference:
    q += ' ,partition_reference=?'
    a(partition_reference)
  if partition_id:
    q += ' ,requested_by=?'
    a(partition_id)
  if instance_xml:
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
319
    q += ' ,xml=?'
Łukasz Nowak's avatar
Łukasz Nowak committed
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
    a(instance_xml)
  q += ' WHERE reference=?'
  a(partition['reference'].encode())
  execute_db('partition', q, args)
  args = []
  partition = execute_db('partition', 'SELECT * FROM %s WHERE reference=?',
      [partition['reference'].encode()], one=True)
  address_list = []
  for address in execute_db('partition_network', 'SELECT * FROM %s WHERE partition_reference=?', [partition['reference']]):
    address_list.append((address['reference'], address['address']))
  return xml_marshaller.xml_marshaller.dumps(SoftwareInstance(**dict(
    xml=partition['xml'],
    connection_xml=partition['connection_xml'],
    slap_computer_id=app.config['computer_id'],
    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'],
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
338
    slave_instance_list=partition['slave_instance_list'],
Łukasz Nowak's avatar
Łukasz Nowak committed
339 340 341 342 343 344
    ip_list=address_list
    )))
  abort(408)
  raise NotImplementedError


Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
345 346
def request_slave():
  """
347 348 349 350 351 352 353 354
  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.
  2. A dictionnary in slave_instance_list of selected slave master
      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
355 356 357 358 359 360
  """
  software_release = request.form['software_release'].encode()
  # some supported parameters
  software_type = request.form.get('software_type').encode()
  partition_reference = request.form.get('partition_reference', '').encode()
  partition_id = request.form.get('computer_partition_id', '').encode()
361
  # Contain slave parameters to be given to slave master
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
362 363 364 365
  partition_parameter_kw = request.form.get('partition_parameter_xml', None)
  if partition_parameter_kw :
    partition_parameter_kw = xml_marshaller.xml_marshaller.loads(
                                              partition_parameter_kw.encode())
Łukasz Nowak's avatar
Łukasz Nowak committed
366
  else:
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
367 368
    partition_parameter_kw = {}
  instance_xml = dict2xml(partition_parameter_kw)
369
  # We will search for a master corresponding to request
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
370 371 372 373 374 375 376 377 378 379 380
  args = []
  a = args.append
  q = 'SELECT * FROM %s WHERE software_release=?'
  a(software_release)
  if software_type:
    q += ' AND software_type=?'
    a(software_type)
  partition = execute_db('partition', q, args, one=True)
  if partition is None:
    app.logger.warning('No partition corresponding to slave request')
    abort(408)
381 382

  # We set slave dictionnary as described in docstring
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
383 384 385 386 387
  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
388

Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
389
  for key in partition_parameter_kw :
390 391
    if partition_parameter_kw[key] is not None :
      new_slave[key] = partition_parameter_kw[key]
Łukasz Nowak's avatar
Łukasz Nowak committed
392

393
  # Add slave to partition slave_list if not present else replace information
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
394 395 396
  slave_instance_list = partition['slave_instance_list']
  if slave_instance_list == None:
    slave_instance_list = []
Łukasz Nowak's avatar
Łukasz Nowak committed
397
  else:
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
398
    slave_instance_list = xml_marshaller.xml_marshaller.loads(slave_instance_list)
399 400 401 402 403
    for x in slave_instance_list:
      if x['slave_reference'] == slave_reference:
        slave_instance_list.remove(x)

  slave_instance_list.append(new_slave)
Łukasz Nowak's avatar
Łukasz Nowak committed
404

405
  # Update slave_instance_list in database
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
  args = []
  a = args.append
  q = 'UPDATE %s SET slave_instance_list=?'
  a(xml_marshaller.xml_marshaller.dumps(slave_instance_list))
  q += ' WHERE reference=?'
  a(partition['reference'].encode())
  execute_db('partition', q, args)
  args = []
  partition = execute_db('partition', 'SELECT * FROM %s WHERE reference=?',
      [partition['reference'].encode()], one=True)

  # Add slave to slave table if not there
  slave = execute_db('slave', 'SELECT * FROM %s WHERE reference=?',
                     [slave_reference], one=True)
  if slave is None :
    execute_db('slave',
422 423
               'INSERT OR IGNORE INTO %s (reference,asked_by,hosted_by) values(:reference,:asked_by,:hosted_by)',
               [slave_reference,partition_id,partition['reference']])
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
424 425 426 427 428 429 430 431 432 433 434 435
    slave = execute_db('slave','SELECT * FROM %s WHERE reference=?',
                     [slave_reference], one = True)

  address_list = []
  for address in execute_db('partition_network',
                            'SELECT * FROM %s WHERE partition_reference=?',
                            [partition['reference']]):
    address_list.append((address['reference'], address['address']))
  return xml_marshaller.xml_marshaller.dumps(SoftwareInstance(**dict(
        _connection_dict=xml2dict(slave['connection_xml']),
        xml = instance_xml,
        slap_computer_id=app.config['computer_id'],
436
        slap_computer_partition_id=slave['hosted_by'],
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
437 438 439 440 441
        slap_software_release_url=partition['software_release'],
        slap_server_url='slap_server_url',
        slap_software_type=partition['software_type'],
        ip_list=address_list
        )))