1 from __future__ import with_statement
9 from boto.ec2.regioninfo import RegionInfo
10 from boto.exception import EC2ResponseError
11 from ConfigParser import ConfigParser
12 from xmlbuilder import XMLBuilder
13 from lxml import etree as ET
14 from sqlobject import *
16 from sfa.util.faults import *
17 from sfa.util.xrn import urn_to_hrn
18 from sfa.util.rspec import RSpec
19 from sfa.server.registry import Registries
20 from sfa.trust.credential import Credential
21 from sfa.plc.api import SfaAPI
22 from sfa.util.plxrn import hrn_to_pl_slicename, slicename_to_hrn
23 from sfa.util.callids import Callids
25 from threading import Thread
26 from time import sleep
29 # The data structure used to represent a cloud.
30 # It contains the cloud name, its ip address, image information,
31 # key pairs, and clusters information.
36 # The location of the RelaxNG schema.
38 EUCALYPTUS_RSPEC_SCHEMA='/etc/sfa/eucalyptus.rng'
43 # Meta data of an instance.
45 class Meta(SQLObject):
46 instance = SingleJoin('EucaInstance')
47 state = StringCol(default = 'new')
48 pub_addr = StringCol(default = None)
49 pri_addr = StringCol(default = None)
50 start_time = DateTimeCol(default = None)
53 # A representation of an Eucalyptus instance. This is a support class
54 # for instance <-> slice mapping.
56 class EucaInstance(SQLObject):
57 instance_id = StringCol(unique=True, default=None)
58 kernel_id = StringCol()
59 image_id = StringCol()
60 ramdisk_id = StringCol()
61 inst_type = StringCol()
62 key_pair = StringCol()
63 slice = ForeignKey('Slice')
64 meta = ForeignKey('Meta')
67 # Contacts Eucalyptus and tries to reserve this instance.
69 # @param botoConn A connection to Eucalyptus.
70 # @param pubKeys A list of public keys for the instance.
72 def reserveInstance(self, botoConn, pubKeys):
73 logger = logging.getLogger('EucaAggregate')
74 logger.info('Reserving an instance: image: %s, kernel: ' \
75 '%s, ramdisk: %s, type: %s, key: %s' % \
76 (self.image_id, self.kernel_id, self.ramdisk_id,
77 self.inst_type, self.key_pair))
79 # XXX The return statement is for testing. REMOVE in production
83 reservation = botoConn.run_instances(self.image_id,
84 kernel_id = self.kernel_id,
85 ramdisk_id = self.ramdisk_id,
86 instance_type = self.inst_type,
87 key_name = self.key_pair,
89 for instance in reservation.instances:
90 self.instance_id = instance.id
92 # If there is an error, destroy itself.
93 except EC2ResponseError, ec2RespErr:
94 errTree = ET.fromstring(ec2RespErr.body)
95 msg = errTree.find('.//Message')
96 logger.error(msg.text)
100 # A representation of a PlanetLab slice. This is a support class
101 # for instance <-> slice mapping.
103 class Slice(SQLObject):
104 slice_hrn = StringCol()
105 #slice_index = DatabaseIndex('slice_hrn')
106 instances = MultipleJoin('EucaInstance')
109 # Initialize the aggregate manager by reading a configuration file.
112 logger = logging.getLogger('EucaAggregate')
113 fileHandler = logging.FileHandler('/var/log/euca.log')
114 fileHandler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
115 logger.addHandler(fileHandler)
116 logger.setLevel(logging.DEBUG)
118 configParser = ConfigParser()
119 configParser.read(['/etc/sfa/eucalyptus_aggregate.conf', 'eucalyptus_aggregate.conf'])
120 if len(configParser.sections()) < 1:
121 logger.error('No cloud defined in the config file')
122 raise Exception('Cannot find cloud definition in configuration file.')
124 # Only read the first section.
125 cloudSec = configParser.sections()[0]
126 cloud['name'] = cloudSec
127 cloud['access_key'] = configParser.get(cloudSec, 'access_key')
128 cloud['secret_key'] = configParser.get(cloudSec, 'secret_key')
129 cloud['cloud_url'] = configParser.get(cloudSec, 'cloud_url')
130 cloudURL = cloud['cloud_url']
131 if cloudURL.find('https://') >= 0:
132 cloudURL = cloudURL.replace('https://', '')
133 elif cloudURL.find('http://') >= 0:
134 cloudURL = cloudURL.replace('http://', '')
135 (cloud['ip'], parts) = cloudURL.split(':')
137 # Create image bundles
138 images = getEucaConnection().get_all_images()
139 cloud['images'] = images
140 cloud['imageBundles'] = {}
142 if i.type != 'machine' or i.kernel_id is None: continue
143 name = os.path.dirname(i.location)
144 detail = {'imageID' : i.id, 'kernelID' : i.kernel_id, 'ramdiskID' : i.ramdisk_id}
145 cloud['imageBundles'][name] = detail
147 # Initialize sqlite3 database and tables.
148 dbPath = '/etc/sfa/db'
149 dbName = 'euca_aggregate.db'
151 if not os.path.isdir(dbPath):
152 logger.info('%s not found. Creating directory ...' % dbPath)
155 conn = connectionForURI('sqlite://%s/%s' % (dbPath, dbName))
156 sqlhub.processConnection = conn
157 Slice.createTable(ifNotExists=True)
158 EucaInstance.createTable(ifNotExists=True)
159 IP.createTable(ifNotExists=True)
161 # Make sure the schema exists.
162 if not os.path.exists(EUCALYPTUS_RSPEC_SCHEMA):
163 err = 'Cannot location schema at %s' % EUCALYPTUS_RSPEC_SCHEMA
168 # Creates a connection to Eucalytpus. This function is inspired by
169 # the make_connection() in Euca2ools.
171 # @return A connection object or None
173 def getEucaConnection():
175 accessKey = cloud['access_key']
176 secretKey = cloud['secret_key']
177 eucaURL = cloud['cloud_url']
181 logger = logging.getLogger('EucaAggregate')
183 if not accessKey or not secretKey or not eucaURL:
184 logger.error('Please set ALL of the required environment ' \
185 'variables by sourcing the eucarc file.')
188 # Split the url into parts
189 if eucaURL.find('https://') >= 0:
191 eucaURL = eucaURL.replace('https://', '')
192 elif eucaURL.find('http://') >= 0:
194 eucaURL = eucaURL.replace('http://', '')
195 (eucaHost, parts) = eucaURL.split(':')
197 parts = parts.split('/')
198 eucaPort = int(parts[0])
200 srvPath = '/'.join(parts)
202 return boto.connect_ec2(aws_access_key_id=accessKey,
203 aws_secret_access_key=secretKey,
205 region=RegionInfo(None, 'eucalyptus', eucaHost),
210 # Returns a string of keys that belong to the users of the given slice.
211 # @param sliceHRN The hunman readable name of the slice.
214 def getKeysForSlice(sliceHRN):
215 logger = logging.getLogger('EucaAggregate')
217 # convert hrn to slice name
218 plSliceName = hrn_to_pl_slicename(sliceHRN)
219 except IndexError, e:
220 logger.error('Invalid slice name (%s)' % sliceHRN)
223 # Get the slice's information
224 sliceData = api.plshell.GetSlices(api.plauth, {'name':plSliceName})
226 logger.warn('Cannot get any data for slice %s' % plSliceName)
229 # It should only return a list with len = 1
230 sliceData = sliceData[0]
233 person_ids = sliceData['person_ids']
235 logger.warn('No users in slice %s' % sliceHRN)
238 persons = api.plshell.GetPersons(api.plauth, person_ids)
239 for person in persons:
240 pkeys = api.plshell.GetKeys(api.plauth, person['key_ids'])
242 keys.append(key['key'])
247 # A class that builds the RSpec for Eucalyptus.
249 class EucaRSpecBuilder(object):
251 # Initizes a RSpec builder
253 # @param cloud A dictionary containing data about a
254 # cloud (ex. clusters, ip)
255 def __init__(self, cloud):
256 self.eucaRSpec = XMLBuilder(format = True, tab_step = " ")
257 self.cloudInfo = cloud
260 # Creates a request stanza.
262 # @param num The number of instances to create.
263 # @param image The disk image id.
264 # @param kernel The kernel image id.
265 # @param keypair Key pair to embed.
266 # @param ramdisk Ramdisk id (optional).
268 def __requestXML(self, num, image, kernel, keypair, ramdisk = ''):
273 with xml.kernel_image(id=kernel):
279 with xml.ramdisk(id=ramdisk):
281 with xml.disk_image(id=image):
287 # Creates the cluster stanza.
289 # @param clusters Clusters information.
291 def __clustersXML(self, clusters):
292 cloud = self.cloudInfo
295 for cluster in clusters:
296 instances = cluster['instances']
297 with xml.cluster(id=cluster['name']):
301 for inst in instances:
302 with xml.vm_type(name=inst[0]):
305 with xml.max_instances:
309 with xml.memory(unit='MB'):
311 with xml.disk_space(unit='GB'):
313 if 'instances' in cloud and inst[0] in cloud['instances']:
314 existingEucaInstances = cloud['instances'][inst[0]]
315 with xml.euca_instances:
316 for eucaInst in existingEucaInstances:
317 with xml.euca_instance(id=eucaInst['id']):
319 xml << eucaInst['state']
321 xml << eucaInst['public_dns']
323 def __imageBundleXML(self, bundles):
326 for bundle in bundles.keys():
327 with xml.bundle(id=bundle):
331 # Creates the Images stanza.
333 # @param images A list of images in Eucalyptus.
335 def __imagesXML(self, images):
339 with xml.image(id=image.id):
343 xml << image.architecture
347 xml << image.location
350 # Creates the KeyPairs stanza.
352 # @param keypairs A list of key pairs in Eucalyptus.
354 def __keyPairsXML(self, keypairs):
362 # Generates the RSpec.
365 logger = logging.getLogger('EucaAggregate')
366 if not self.cloudInfo:
367 logger.error('No cloud information')
371 cloud = self.cloudInfo
372 with xml.RSpec(type='eucalyptus'):
373 with xml.cloud(id=cloud['name']):
376 #self.__keyPairsXML(cloud['keypairs'])
377 #self.__imagesXML(cloud['images'])
378 self.__imageBundleXML(cloud['imageBundles'])
379 self.__clustersXML(cloud['clusters'])
383 # A parser to parse the output of availability-zones.
385 # Note: Only one cluster is supported. If more than one, this will
388 class ZoneResultParser(object):
389 def __init__(self, zones):
393 if len(self.zones) < 3:
399 cluster['name'] = self.zones[0].name
400 cluster['ip'] = self.zones[0].state
402 for i in range(2, len(self.zones)):
403 currZone = self.zones[i]
404 instType = currZone.name.split()[1]
406 stateString = currZone.state.split('/')
407 rscString = stateString[1].split()
409 instFree = int(stateString[0])
410 instMax = int(rscString[0])
411 instNumCpu = int(rscString[1])
412 instRam = int(rscString[2])
413 instDiskSpace = int(rscString[3])
415 instTuple = (instType, instFree, instMax, instNumCpu, instRam, instDiskSpace)
416 instList.append(instTuple)
417 cluster['instances'] = instList
418 clusterList.append(cluster)
422 def ListResources(api, creds, options, call_id):
423 if Callids().already_handled(call_id): return ""
425 # get slice's hrn from options
426 xrn = options.get('geni_slice_urn', '')
427 hrn, type = urn_to_hrn(xrn)
428 logger = logging.getLogger('EucaAggregate')
430 # get hrn of the original caller
431 origin_hrn = options.get('origin_hrn', None)
433 origin_hrn = Credential(string=creds[0]).get_gid_caller().get_hrn()
435 conn = getEucaConnection()
438 logger.error('Cannot create a connection to Eucalyptus')
439 return 'Cannot create a connection to Eucalyptus'
443 zones = conn.get_all_zones(['verbose'])
444 p = ZoneResultParser(zones)
446 cloud['clusters'] = clusters
449 images = conn.get_all_images()
450 cloud['images'] = images
451 cloud['imageBundles'] = {}
453 if i.type != 'machine' or i.kernel_id is None: continue
454 name = os.path.dirname(i.location)
455 detail = {'imageID' : i.id, 'kernelID' : i.kernel_id, 'ramdiskID' : i.ramdisk_id}
456 cloud['imageBundles'][name] = detail
459 keyPairs = conn.get_all_key_pairs()
460 cloud['keypairs'] = keyPairs
466 # Get the instances that belong to the given slice from sqlite3
467 # XXX use getOne() in production because the slice's hrn is supposed
468 # to be unique. For testing, uniqueness is turned off in the db.
469 # If the slice isn't found in the database, create a record for the
471 matchedSlices = list(Slice.select(Slice.q.slice_hrn == hrn))
473 theSlice = matchedSlices[-1]
475 theSlice = Slice(slice_hrn = hrn)
476 for instance in theSlice.instances:
477 instanceId.append(instance.instance_id)
479 # Get the information about those instances using their ids.
480 if len(instanceId) > 0:
481 reservations = conn.get_all_instances(instanceId)
484 for reservation in reservations:
485 for instance in reservation.instances:
486 instances.append(instance)
488 # Construct a dictionary for the EucaRSpecBuilder
490 for instance in instances:
491 instList = instancesDict.setdefault(instance.instance_type, [])
494 instInfoDict['id'] = instance.id
495 instInfoDict['public_dns'] = instance.public_dns_name
496 instInfoDict['state'] = instance.state
497 instInfoDict['key'] = instance.key_name
499 instList.append(instInfoDict)
500 cloud['instances'] = instancesDict
502 except EC2ResponseError, ec2RespErr:
503 errTree = ET.fromstring(ec2RespErr.body)
504 errMsgE = errTree.find('.//Message')
505 logger.error(errMsgE.text)
507 rspec = EucaRSpecBuilder(cloud).toXML()
509 # Remove the instances records so next time they won't
511 if 'instances' in cloud:
512 del cloud['instances']
517 Hook called via 'sfi.py create'
519 def CreateSliver(api, xrn, creds, xml, users, call_id):
520 if Callids().already_handled(call_id): return ""
523 hrn = urn_to_hrn(xrn)[0]
524 logger = logging.getLogger('EucaAggregate')
526 conn = getEucaConnection()
528 logger.error('Cannot create a connection to Eucalyptus')
532 schemaXML = ET.parse(EUCALYPTUS_RSPEC_SCHEMA)
533 rspecValidator = ET.RelaxNG(schemaXML)
534 rspecXML = ET.XML(xml)
535 if not rspecValidator(rspecXML):
536 error = rspecValidator.error_log.last_error
537 message = '%s (line %s)' % (error.message, error.line)
538 # XXX: InvalidRSpec is new. Currently, I am not working with Trunk code.
539 #raise InvalidRSpec(message)
540 raise Exception(message)
542 # Get the slice from db or create one.
543 s = Slice.select(Slice.q.slice_hrn == hrn).getOne(None)
545 s = Slice(slice_hrn = hrn)
547 # Process any changes in existing instance allocation
549 for sliceInst in s.instances:
550 pendingRmInst.append(sliceInst.instance_id)
551 existingInstGroup = rspecXML.findall('.//euca_instances')
552 for instGroup in existingInstGroup:
553 for existingInst in instGroup:
554 if existingInst.get('id') in pendingRmInst:
555 pendingRmInst.remove(existingInst.get('id'))
556 for inst in pendingRmInst:
557 logger.debug('Instance %s will be terminated' % inst)
558 dbInst = EucaInstance.select(EucaInstance.q.instance_id == inst).getOne(None)
559 # Only change the state but do not remove the entry from the DB.
560 dbInst.meta.state = 'deleted'
561 #dbInst.destroySelf()
562 conn.terminate_instances(pendingRmInst)
564 # Process new instance requests
565 requests = rspecXML.findall('.//request')
567 # Get all the public keys associate with slice.
568 pubKeys = getKeysForSlice(s.slice_hrn)
569 logger.debug('Passing the following keys to the instance:\n%s' % pubKeys)
571 vmTypeElement = req.getparent()
572 instType = vmTypeElement.get('name')
573 numInst = int(req.find('instances').text)
575 bundleName = req.find('bundle').text
576 if not cloud['imageBundles'][bundleName]:
577 logger.error('Cannot find bundle %s' % bundleName)
578 bundleInfo = cloud['imageBundles'][bundleName]
579 instKernel = bundleInfo['kernelID']
580 instDiskImg = bundleInfo['imageID']
581 instRamDisk = bundleInfo['ramdiskID']
584 # Create the instances
585 for i in range(0, numInst):
586 eucaInst = EucaInstance(slice = s,
587 kernel_id = instKernel,
588 image_id = instDiskImg,
589 ramdisk_id = instRamDisk,
591 inst_type = instType,
592 meta = Meta(start_time=datetime.datetime.now()))
593 eucaInst.reserveInstance(conn, pubKeys)
595 # xxx - should return altered rspec
596 # with enough data for the client to understand what's happened
600 # A thread that will update the meta data.
603 logger = logging.getLogger('EucaAggregate')
607 # Get IDs of the instances that don't have IPs yet.
608 dbResults = Meta.select(
609 AND(Meta.q.pri_addr == None,
610 Meta.q.state != 'deleted')
612 dbResults = list(dbResults)
613 logger.debug('[update thread] dbResults: %s' % dbResults)
616 instids.append(r.instance.instance_id)
617 logger.debug('[update thread] Instance Id: %s' % ', '.join(instids))
619 # Get instance information from Eucalyptus
620 conn = getEucaConnection()
622 reservations = conn.get_all_instances(instids)
623 for reservation in reservations:
624 vmInstances += reservation.instances
627 instIPs = [ {'id':i.id, 'pri_addr':i.private_dns_name, 'pub_addr':i.public_dns_name}
628 for i in vmInstances if i.private_dns_name != '0.0.0.0' ]
629 logger.debug('[update thread] IP dict: %s' % str(instIPs))
631 # Update the local DB
632 for ipData in instIPs:
633 dbInst = EucaInstance.select(EucaInstance.q.instance_id == ipData['id']).getOne(None)
635 logger.info('[update thread] Could not find %s in DB' % ipData['id'])
637 dbInst.meta.pri_addr = ipData['pri_addr']
638 dbInst.meta.pub_addr = ipData['pub_addr']
639 dbInst.meta.state = 'running'
645 #with open(sys.argv[1]) as xml:
646 # theRSpec = xml.read()
647 #CreateSliver(None, 'planetcloud.pc.test', theRSpec, 'call-id-cloudtest')
649 #rspec = ListResources('euca', 'planetcloud.pc.test', 'planetcloud.pc.marcoy', 'test_euca')
651 print getKeysForSlice('gc.gc.test1')
653 if __name__ == "__main__":