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'
41 sys.stderr = file('/var/log/euca_agg.log', 'a+')
45 # Meta data of an instance.
47 class Meta(SQLObject):
48 instance = SingleJoin('EucaInstance')
49 state = StringCol(default = 'new')
50 pub_addr = StringCol(default = None)
51 pri_addr = StringCol(default = None)
52 start_time = DateTimeCol(default = None)
55 # A representation of an Eucalyptus instance. This is a support class
56 # for instance <-> slice mapping.
58 class EucaInstance(SQLObject):
59 instance_id = StringCol(unique=True, default=None)
60 kernel_id = StringCol()
61 image_id = StringCol()
62 ramdisk_id = StringCol()
63 inst_type = StringCol()
64 key_pair = StringCol()
65 slice = ForeignKey('Slice')
66 meta = ForeignKey('Meta')
69 # Contacts Eucalyptus and tries to reserve this instance.
71 # @param botoConn A connection to Eucalyptus.
72 # @param pubKeys A list of public keys for the instance.
74 def reserveInstance(self, botoConn, pubKeys):
75 print >>sys.stderr, 'Reserving an instance: image: %s, kernel: ' \
76 '%s, ramdisk: %s, type: %s, key: %s' % \
77 (self.image_id, self.kernel_id, self.ramdisk_id,
78 self.inst_type, self.key_pair)
80 # XXX The return statement is for testing. REMOVE in production
84 reservation = botoConn.run_instances(self.image_id,
85 kernel_id = self.kernel_id,
86 ramdisk_id = self.ramdisk_id,
87 instance_type = self.inst_type,
88 key_name = self.key_pair,
90 for instance in reservation.instances:
91 self.instance_id = instance.id
93 # If there is an error, destroy itself.
94 except EC2ResponseError, ec2RespErr:
95 errTree = ET.fromstring(ec2RespErr.body)
96 msg = errTree.find('.//Message')
97 print >>sys.stderr, msg.text
101 # A representation of a PlanetLab slice. This is a support class
102 # for instance <-> slice mapping.
104 class Slice(SQLObject):
105 slice_hrn = StringCol()
106 #slice_index = DatabaseIndex('slice_hrn')
107 instances = MultipleJoin('EucaInstance')
110 # Initialize the aggregate manager by reading a configuration file.
113 logger = logging.getLogger('EucaAggregate')
114 fileHandler = logging.FileHandler('/var/log/euca.log')
115 fileHandler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
116 logger.addHandler(fileHandler)
117 logger.setLevel(logging.DEBUG)
119 configParser = ConfigParser()
120 configParser.read(['/etc/sfa/eucalyptus_aggregate.conf', 'eucalyptus_aggregate.conf'])
121 if len(configParser.sections()) < 1:
122 print >>sys.stderr, 'No cloud defined in the config file'
123 raise Exception('Cannot find cloud definition in configuration file.')
125 # Only read the first section.
126 cloudSec = configParser.sections()[0]
127 cloud['name'] = cloudSec
128 cloud['access_key'] = configParser.get(cloudSec, 'access_key')
129 cloud['secret_key'] = configParser.get(cloudSec, 'secret_key')
130 cloud['cloud_url'] = configParser.get(cloudSec, 'cloud_url')
131 cloudURL = cloud['cloud_url']
132 if cloudURL.find('https://') >= 0:
133 cloudURL = cloudURL.replace('https://', '')
134 elif cloudURL.find('http://') >= 0:
135 cloudURL = cloudURL.replace('http://', '')
136 (cloud['ip'], parts) = cloudURL.split(':')
138 # Create image bundles
139 images = getEucaConnection().get_all_images()
140 cloud['images'] = images
141 cloud['imageBundles'] = {}
143 if i.type != 'machine' or i.kernel_id is None: continue
144 name = os.path.dirname(i.location)
145 detail = {'imageID' : i.id, 'kernelID' : i.kernel_id, 'ramdiskID' : i.ramdisk_id}
146 cloud['imageBundles'][name] = detail
148 # Initialize sqlite3 database and tables.
149 dbPath = '/etc/sfa/db'
150 dbName = 'euca_aggregate.db'
152 if not os.path.isdir(dbPath):
153 print >>sys.stderr, '%s not found. Creating directory ...' % dbPath
156 conn = connectionForURI('sqlite://%s/%s' % (dbPath, dbName))
157 sqlhub.processConnection = conn
158 Slice.createTable(ifNotExists=True)
159 EucaInstance.createTable(ifNotExists=True)
160 IP.createTable(ifNotExists=True)
162 # Make sure the schema exists.
163 if not os.path.exists(EUCALYPTUS_RSPEC_SCHEMA):
164 err = 'Cannot location schema at %s' % EUCALYPTUS_RSPEC_SCHEMA
165 print >>sys.stderr, err
169 # Creates a connection to Eucalytpus. This function is inspired by
170 # the make_connection() in Euca2ools.
172 # @return A connection object or None
174 def getEucaConnection():
176 accessKey = cloud['access_key']
177 secretKey = cloud['secret_key']
178 eucaURL = cloud['cloud_url']
183 if not accessKey or not secretKey or not eucaURL:
184 print >>sys.stderr, '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):
216 # convert hrn to slice name
217 plSliceName = hrn_to_pl_slicename(sliceHRN)
218 except IndexError, e:
219 print >>sys.stderr, 'Invalid slice name (%s)' % sliceHRN
222 # Get the slice's information
223 sliceData = api.plshell.GetSlices(api.plauth, {'name':plSliceName})
225 print >>sys.stderr, 'Cannot get any data for slice %s' % plSliceName
228 # It should only return a list with len = 1
229 sliceData = sliceData[0]
232 person_ids = sliceData['person_ids']
234 print >>sys.stderr, 'No users in slice %s' % sliceHRN
237 persons = api.plshell.GetPersons(api.plauth, person_ids)
238 for person in persons:
239 pkeys = api.plshell.GetKeys(api.plauth, person['key_ids'])
241 keys.append(key['key'])
246 # A class that builds the RSpec for Eucalyptus.
248 class EucaRSpecBuilder(object):
250 # Initizes a RSpec builder
252 # @param cloud A dictionary containing data about a
253 # cloud (ex. clusters, ip)
254 def __init__(self, cloud):
255 self.eucaRSpec = XMLBuilder(format = True, tab_step = " ")
256 self.cloudInfo = cloud
259 # Creates a request stanza.
261 # @param num The number of instances to create.
262 # @param image The disk image id.
263 # @param kernel The kernel image id.
264 # @param keypair Key pair to embed.
265 # @param ramdisk Ramdisk id (optional).
267 def __requestXML(self, num, image, kernel, keypair, ramdisk = ''):
272 with xml.kernel_image(id=kernel):
278 with xml.ramdisk(id=ramdisk):
280 with xml.disk_image(id=image):
286 # Creates the cluster stanza.
288 # @param clusters Clusters information.
290 def __clustersXML(self, clusters):
291 cloud = self.cloudInfo
294 for cluster in clusters:
295 instances = cluster['instances']
296 with xml.cluster(id=cluster['name']):
300 for inst in instances:
301 with xml.vm_type(name=inst[0]):
304 with xml.max_instances:
308 with xml.memory(unit='MB'):
310 with xml.disk_space(unit='GB'):
312 if 'instances' in cloud and inst[0] in cloud['instances']:
313 existingEucaInstances = cloud['instances'][inst[0]]
314 with xml.euca_instances:
315 for eucaInst in existingEucaInstances:
316 with xml.euca_instance(id=eucaInst['id']):
318 xml << eucaInst['state']
320 xml << eucaInst['public_dns']
322 def __imageBundleXML(self, bundles):
325 for bundle in bundles.keys():
326 with xml.bundle(id=bundle):
330 # Creates the Images stanza.
332 # @param images A list of images in Eucalyptus.
334 def __imagesXML(self, images):
338 with xml.image(id=image.id):
342 xml << image.architecture
346 xml << image.location
349 # Creates the KeyPairs stanza.
351 # @param keypairs A list of key pairs in Eucalyptus.
353 def __keyPairsXML(self, keypairs):
361 # Generates the RSpec.
364 if not self.cloudInfo:
365 print >>sys.stderr, 'No cloud information'
369 cloud = self.cloudInfo
370 with xml.RSpec(type='eucalyptus'):
371 with xml.cloud(id=cloud['name']):
374 #self.__keyPairsXML(cloud['keypairs'])
375 #self.__imagesXML(cloud['images'])
376 self.__imageBundleXML(cloud['imageBundles'])
377 self.__clustersXML(cloud['clusters'])
381 # A parser to parse the output of availability-zones.
383 # Note: Only one cluster is supported. If more than one, this will
386 class ZoneResultParser(object):
387 def __init__(self, zones):
391 if len(self.zones) < 3:
397 cluster['name'] = self.zones[0].name
398 cluster['ip'] = self.zones[0].state
400 for i in range(2, len(self.zones)):
401 currZone = self.zones[i]
402 instType = currZone.name.split()[1]
404 stateString = currZone.state.split('/')
405 rscString = stateString[1].split()
407 instFree = int(stateString[0])
408 instMax = int(rscString[0])
409 instNumCpu = int(rscString[1])
410 instRam = int(rscString[2])
411 instDiskSpace = int(rscString[3])
413 instTuple = (instType, instFree, instMax, instNumCpu, instRam, instDiskSpace)
414 instList.append(instTuple)
415 cluster['instances'] = instList
416 clusterList.append(cluster)
420 def ListResources(api, creds, options, call_id):
421 if Callids().already_handled(call_id): return ""
423 # get slice's hrn from options
424 xrn = options.get('geni_slice_urn', '')
425 hrn, type = urn_to_hrn(xrn)
427 # get hrn of the original caller
428 origin_hrn = options.get('origin_hrn', None)
430 origin_hrn = Credential(string=creds[0]).get_gid_caller().get_hrn()
432 conn = getEucaConnection()
435 print >>sys.stderr, 'Error: Cannot create a connection to Eucalyptus'
436 return 'Cannot create a connection to Eucalyptus'
440 zones = conn.get_all_zones(['verbose'])
441 p = ZoneResultParser(zones)
443 cloud['clusters'] = clusters
446 images = conn.get_all_images()
447 cloud['images'] = images
448 cloud['imageBundles'] = {}
450 if i.type != 'machine' or i.kernel_id is None: continue
451 name = os.path.dirname(i.location)
452 detail = {'imageID' : i.id, 'kernelID' : i.kernel_id, 'ramdiskID' : i.ramdisk_id}
453 cloud['imageBundles'][name] = detail
456 keyPairs = conn.get_all_key_pairs()
457 cloud['keypairs'] = keyPairs
463 # Get the instances that belong to the given slice from sqlite3
464 # XXX use getOne() in production because the slice's hrn is supposed
465 # to be unique. For testing, uniqueness is turned off in the db.
466 # If the slice isn't found in the database, create a record for the
468 matchedSlices = list(Slice.select(Slice.q.slice_hrn == hrn))
470 theSlice = matchedSlices[-1]
472 theSlice = Slice(slice_hrn = hrn)
473 for instance in theSlice.instances:
474 instanceId.append(instance.instance_id)
476 # Get the information about those instances using their ids.
477 if len(instanceId) > 0:
478 reservations = conn.get_all_instances(instanceId)
481 for reservation in reservations:
482 for instance in reservation.instances:
483 instances.append(instance)
485 # Construct a dictionary for the EucaRSpecBuilder
487 for instance in instances:
488 instList = instancesDict.setdefault(instance.instance_type, [])
491 instInfoDict['id'] = instance.id
492 instInfoDict['public_dns'] = instance.public_dns_name
493 instInfoDict['state'] = instance.state
494 instInfoDict['key'] = instance.key_name
496 instList.append(instInfoDict)
497 cloud['instances'] = instancesDict
499 except EC2ResponseError, ec2RespErr:
500 errTree = ET.fromstring(ec2RespErr.body)
501 errMsgE = errTree.find('.//Message')
502 print >>sys.stderr, errMsgE.text
504 rspec = EucaRSpecBuilder(cloud).toXML()
506 # Remove the instances records so next time they won't
508 if 'instances' in cloud:
509 del cloud['instances']
514 Hook called via 'sfi.py create'
516 def CreateSliver(api, xrn, creds, xml, users, call_id):
517 if Callids().already_handled(call_id): return ""
520 hrn = urn_to_hrn(xrn)[0]
522 conn = getEucaConnection()
524 print >>sys.stderr, 'Error: Cannot create a connection to Eucalyptus'
528 schemaXML = ET.parse(EUCALYPTUS_RSPEC_SCHEMA)
529 rspecValidator = ET.RelaxNG(schemaXML)
530 rspecXML = ET.XML(xml)
531 if not rspecValidator(rspecXML):
532 error = rspecValidator.error_log.last_error
533 message = '%s (line %s)' % (error.message, error.line)
534 # XXX: InvalidRSpec is new. Currently, I am not working with Trunk code.
535 #raise InvalidRSpec(message)
536 raise Exception(message)
538 # Get the slice from db or create one.
539 s = Slice.select(Slice.q.slice_hrn == hrn).getOne(None)
541 s = Slice(slice_hrn = hrn)
543 # Process any changes in existing instance allocation
545 for sliceInst in s.instances:
546 pendingRmInst.append(sliceInst.instance_id)
547 existingInstGroup = rspecXML.findall('.//euca_instances')
548 for instGroup in existingInstGroup:
549 for existingInst in instGroup:
550 if existingInst.get('id') in pendingRmInst:
551 pendingRmInst.remove(existingInst.get('id'))
552 for inst in pendingRmInst:
553 print >>sys.stderr, 'Instance %s will be terminated' % inst
554 dbInst = EucaInstance.select(EucaInstance.q.instance_id == inst).getOne(None)
555 # Only change the state but do not remove the entry from the DB.
556 dbInst.meta.state = 'deleted'
557 #dbInst.destroySelf()
558 conn.terminate_instances(pendingRmInst)
560 # Process new instance requests
561 requests = rspecXML.findall('.//request')
563 # Get all the public keys associate with slice.
564 pubKeys = getKeysForSlice(s.slice_hrn)
565 print >>sys.stderr, "Passing the following keys to the instance:\n%s" % pubKeys
568 vmTypeElement = req.getparent()
569 instType = vmTypeElement.get('name')
570 numInst = int(req.find('instances').text)
572 bundleName = req.find('bundle').text
573 if not cloud['imageBundles'][bundleName]:
574 print >>sys.stderr, 'Cannot find bundle %s' % bundleName
575 bundleInfo = cloud['imageBundles'][bundleName]
576 instKernel = bundleInfo['kernelID']
577 instDiskImg = bundleInfo['imageID']
578 instRamDisk = bundleInfo['ramdiskID']
581 # Create the instances
582 for i in range(0, numInst):
583 eucaInst = EucaInstance(slice = s,
584 kernel_id = instKernel,
585 image_id = instDiskImg,
586 ramdisk_id = instRamDisk,
588 inst_type = instType,
589 meta = Meta(start_time=datetime.datetime.now()))
590 eucaInst.reserveInstance(conn, pubKeys)
592 # xxx - should return altered rspec
593 # with enough data for the client to understand what's happened
597 # A thread that will update the meta data.
600 logger = logging.getLogger('EucaAggregate')
604 # Get IDs of the instances that don't have IPs yet.
605 dbResults = Meta.select(
606 AND(Meta.q.pri_addr == None,
607 Meta.q.state != 'deleted')
609 dbResults = list(dbResults)
610 logger.debug('[update thread] dbResults: %s' % dbResults)
613 instids.append(r.instance.instance_id)
614 logger.debug('[update thread] Instance Id: %s' % ', '.join(instids))
616 # Get instance information from Eucalyptus
617 conn = getEucaConnection()
619 reservations = conn.get_all_instances(instids)
620 for reservation in reservations:
621 vmInstances += reservation.instances
624 instIPs = [ {'id':i.id, 'pri_addr':i.private_dns_name, 'pub_addr':i.public_dns_name}
625 for i in vmInstances if i.private_dns_name != '0.0.0.0' ]
626 logger.debug('[update thread] IP dict: %s' % str(instIPs))
628 # Update the local DB
629 for ipData in instIPs:
630 dbInst = EucaInstance.select(EucaInstance.q.instance_id == ipData['id']).getOne(None)
632 logger.info('[update thread] Could not find %s in DB' % ipData['id'])
634 dbInst.meta.pri_addr = ipData['pri_addr']
635 dbInst.meta.pub_addr = ipData['pub_addr']
636 dbInst.meta.state = 'running'
642 #with open(sys.argv[1]) as xml:
643 # theRSpec = xml.read()
644 #CreateSliver(None, 'planetcloud.pc.test', theRSpec, 'call-id-cloudtest')
646 #rspec = ListResources('euca', 'planetcloud.pc.test', 'planetcloud.pc.marcoy', 'test_euca')
648 print getKeysForSlice('gc.gc.test1')
650 if __name__ == "__main__":