1 from __future__ import with_statement
7 from boto.ec2.regioninfo import RegionInfo
8 from boto.exception import EC2ResponseError
9 from ConfigParser import ConfigParser
10 from xmlbuilder import XMLBuilder
11 from lxml import etree as ET
12 from sqlobject import *
14 from sfa.util.faults import *
15 from sfa.util.xrn import urn_to_hrn
16 from sfa.util.rspec import RSpec
17 from sfa.server.registry import Registries
18 from sfa.trust.credential import Credential
19 from sfa.plc.api import SfaAPI
20 from sfa.util.plxrn import hrn_to_pl_slicename, slicename_to_hrn
23 # The data structure used to represent a cloud.
24 # It contains the cloud name, its ip address, image information,
25 # key pairs, and clusters information.
30 # The location of the RelaxNG schema.
32 EUCALYPTUS_RSPEC_SCHEMA='/etc/sfa/eucalyptus.rng'
35 sys.stderr = file('/var/log/euca_agg.log', 'a+')
39 # A representation of an Eucalyptus instance. This is a support class
40 # for instance <-> slice mapping.
42 class EucaInstance(SQLObject):
43 instance_id = StringCol(unique=True, default=None)
44 kernel_id = StringCol()
45 image_id = StringCol()
46 ramdisk_id = StringCol()
47 inst_type = StringCol()
48 key_pair = StringCol()
49 slice = ForeignKey('Slice')
52 # Contacts Eucalyptus and tries to reserve this instance.
54 # @param botoConn A connection to Eucalyptus.
55 # @param pubKeys A list of public keys for the instance.
57 def reserveInstance(self, botoConn, pubKeys):
58 print >>sys.stderr, 'Reserving an instance: image: %s, kernel: ' \
59 '%s, ramdisk: %s, type: %s, key: %s' % \
60 (self.image_id, self.kernel_id, self.ramdisk_id,
61 self.inst_type, self.key_pair)
63 # XXX The return statement is for testing. REMOVE in production
67 reservation = botoConn.run_instances(self.image_id,
68 kernel_id = self.kernel_id,
69 ramdisk_id = self.ramdisk_id,
70 instance_type = self.inst_type,
71 key_name = self.key_pair,
73 for instance in reservation.instances:
74 self.instance_id = instance.id
76 # If there is an error, destroy itself.
77 except EC2ResponseError, ec2RespErr:
78 errTree = ET.fromstring(ec2RespErr.body)
79 msg = errTree.find('.//Message')
80 print >>sys.stderr, msg.text
84 # A representation of a PlanetLab slice. This is a support class
85 # for instance <-> slice mapping.
87 class Slice(SQLObject):
88 slice_hrn = StringCol()
89 #slice_index = DatabaseIndex('slice_hrn')
90 instances = MultipleJoin('EucaInstance')
93 # Initialize the aggregate manager by reading a configuration file.
96 configParser = ConfigParser()
97 configParser.read(['/etc/sfa/eucalyptus_aggregate.conf', 'eucalyptus_aggregate.conf'])
98 if len(configParser.sections()) < 1:
99 print >>sys.stderr, 'No cloud defined in the config file'
100 raise Exception('Cannot find cloud definition in configuration file.')
102 # Only read the first section.
103 cloudSec = configParser.sections()[0]
104 cloud['name'] = cloudSec
105 cloud['access_key'] = configParser.get(cloudSec, 'access_key')
106 cloud['secret_key'] = configParser.get(cloudSec, 'secret_key')
107 cloud['cloud_url'] = configParser.get(cloudSec, 'cloud_url')
108 cloudURL = cloud['cloud_url']
109 if cloudURL.find('https://') >= 0:
110 cloudURL = cloudURL.replace('https://', '')
111 elif cloudURL.find('http://') >= 0:
112 cloudURL = cloudURL.replace('http://', '')
113 (cloud['ip'], parts) = cloudURL.split(':')
115 # Create image bundles
116 images = getEucaConnection().get_all_images()
117 cloud['images'] = images
118 cloud['imageBundles'] = {}
120 if i.type != 'machine' or i.kernel_id is None: continue
121 name = os.path.dirname(i.location)
122 detail = {'imageID' : i.id, 'kernelID' : i.kernel_id, 'ramdiskID' : i.ramdisk_id}
123 cloud['imageBundles'][name] = detail
125 # Initialize sqlite3 database.
126 dbPath = '/etc/sfa/db'
127 dbName = 'euca_aggregate.db'
129 if not os.path.isdir(dbPath):
130 print >>sys.stderr, '%s not found. Creating directory ...' % dbPath
133 conn = connectionForURI('sqlite://%s/%s' % (dbPath, dbName))
134 sqlhub.processConnection = conn
135 Slice.createTable(ifNotExists=True)
136 EucaInstance.createTable(ifNotExists=True)
138 # Make sure the schema exists.
139 if not os.path.exists(EUCALYPTUS_RSPEC_SCHEMA):
140 err = 'Cannot location schema at %s' % EUCALYPTUS_RSPEC_SCHEMA
141 print >>sys.stderr, err
145 # Creates a connection to Eucalytpus. This function is inspired by
146 # the make_connection() in Euca2ools.
148 # @return A connection object or None
150 def getEucaConnection():
152 accessKey = cloud['access_key']
153 secretKey = cloud['secret_key']
154 eucaURL = cloud['cloud_url']
159 if not accessKey or not secretKey or not eucaURL:
160 print >>sys.stderr, 'Please set ALL of the required environment ' \
161 'variables by sourcing the eucarc file.'
164 # Split the url into parts
165 if eucaURL.find('https://') >= 0:
167 eucaURL = eucaURL.replace('https://', '')
168 elif eucaURL.find('http://') >= 0:
170 eucaURL = eucaURL.replace('http://', '')
171 (eucaHost, parts) = eucaURL.split(':')
173 parts = parts.split('/')
174 eucaPort = int(parts[0])
176 srvPath = '/'.join(parts)
178 return boto.connect_ec2(aws_access_key_id=accessKey,
179 aws_secret_access_key=secretKey,
181 region=RegionInfo(None, 'eucalyptus', eucaHost),
186 # Returns a string of keys that belong to the users of the given slice.
187 # @param sliceHRN The hunman readable name of the slice.
190 def getKeysForSlice(sliceHRN):
192 # convert hrn to slice name
193 plSliceName = hrn_to_pl_slicename(sliceHRN)
194 except IndexError, e:
195 print >>sys.stderr, 'Invalid slice name (%s)' % sliceHRN
198 # Get the slice's information
199 sliceData = api.plshell.GetSlices(api.plauth, {'name':plSliceName})
201 print >>sys.stderr, 'Cannot get any data for slice %s' % plSliceName
204 # It should only return a list with len = 1
205 sliceData = sliceData[0]
208 person_ids = sliceData['person_ids']
210 print >>sys.stderr, 'No users in slice %s' % sliceHRN
213 persons = api.plshell.GetPersons(api.plauth, person_ids)
214 for person in persons:
215 pkeys = api.plshell.GetKeys(api.plauth, person['key_ids'])
217 keys.append(key['key'])
222 # A class that builds the RSpec for Eucalyptus.
224 class EucaRSpecBuilder(object):
226 # Initizes a RSpec builder
228 # @param cloud A dictionary containing data about a
229 # cloud (ex. clusters, ip)
230 def __init__(self, cloud):
231 self.eucaRSpec = XMLBuilder(format = True, tab_step = " ")
232 self.cloudInfo = cloud
235 # Creates a request stanza.
237 # @param num The number of instances to create.
238 # @param image The disk image id.
239 # @param kernel The kernel image id.
240 # @param keypair Key pair to embed.
241 # @param ramdisk Ramdisk id (optional).
243 def __requestXML(self, num, image, kernel, keypair, ramdisk = ''):
248 with xml.kernel_image(id=kernel):
254 with xml.ramdisk(id=ramdisk):
256 with xml.disk_image(id=image):
262 # Creates the cluster stanza.
264 # @param clusters Clusters information.
266 def __clustersXML(self, clusters):
267 cloud = self.cloudInfo
270 for cluster in clusters:
271 instances = cluster['instances']
272 with xml.cluster(id=cluster['name']):
276 for inst in instances:
277 with xml.vm_type(name=inst[0]):
280 with xml.max_instances:
284 with xml.memory(unit='MB'):
286 with xml.disk_space(unit='GB'):
288 if 'instances' in cloud and inst[0] in cloud['instances']:
289 existingEucaInstances = cloud['instances'][inst[0]]
290 with xml.euca_instances:
291 for eucaInst in existingEucaInstances:
292 with xml.euca_instance(id=eucaInst['id']):
294 xml << eucaInst['state']
296 xml << eucaInst['public_dns']
298 def __imageBundleXML(self, bundles):
301 for bundle in bundles.keys():
302 print >>sys.stderr, 'bundle: %r' % bundle
304 with xml.bundle(id=bundle):
308 # Creates the Images stanza.
310 # @param images A list of images in Eucalyptus.
312 def __imagesXML(self, images):
316 with xml.image(id=image.id):
320 xml << image.architecture
324 xml << image.location
327 # Creates the KeyPairs stanza.
329 # @param keypairs A list of key pairs in Eucalyptus.
331 def __keyPairsXML(self, keypairs):
339 # Generates the RSpec.
342 if not self.cloudInfo:
343 print >>sys.stderr, 'No cloud information'
347 cloud = self.cloudInfo
348 with xml.RSpec(type='eucalyptus'):
349 with xml.cloud(id=cloud['name']):
352 #self.__keyPairsXML(cloud['keypairs'])
353 #self.__imagesXML(cloud['images'])
354 self.__imageBundleXML(cloud['imageBundles'])
355 self.__clustersXML(cloud['clusters'])
359 # A parser to parse the output of availability-zones.
361 # Note: Only one cluster is supported. If more than one, this will
364 class ZoneResultParser(object):
365 def __init__(self, zones):
369 if len(self.zones) < 3:
375 cluster['name'] = self.zones[0].name
376 cluster['ip'] = self.zones[0].state
378 for i in range(2, len(self.zones)):
379 currZone = self.zones[i]
380 instType = currZone.name.split()[1]
382 stateString = currZone.state.split('/')
383 rscString = stateString[1].split()
385 instFree = int(stateString[0])
386 instMax = int(rscString[0])
387 instNumCpu = int(rscString[1])
388 instRam = int(rscString[2])
389 instDiskSpace = int(rscString[3])
391 instTuple = (instType, instFree, instMax, instNumCpu, instRam, instDiskSpace)
392 instList.append(instTuple)
393 cluster['instances'] = instList
394 clusterList.append(cluster)
398 def get_rspec(api, creds, options):
400 # get slice's hrn from options
401 xrn = options.get('geni_slice_urn', '')
402 hrn, type = urn_to_hrn(xrn)
404 # get hrn of the original caller
405 origin_hrn = options.get('origin_hrn', None)
407 origin_hrn = Credential(string=creds[0]).get_gid_caller().get_hrn()
409 conn = getEucaConnection()
412 print >>sys.stderr, 'Error: Cannot create a connection to Eucalyptus'
413 return 'Cannot create a connection to Eucalyptus'
417 zones = conn.get_all_zones(['verbose'])
418 p = ZoneResultParser(zones)
420 cloud['clusters'] = clusters
423 images = conn.get_all_images()
424 cloud['images'] = images
425 cloud['imageBundles'] = {}
427 if i.type != 'machine' or i.kernel_id is None: continue
428 name = os.path.dirname(i.location)
429 detail = {'imageID' : i.id, 'kernelID' : i.kernel_id, 'ramdiskID' : i.ramdisk_id}
430 cloud['imageBundles'][name] = detail
433 keyPairs = conn.get_all_key_pairs()
434 cloud['keypairs'] = keyPairs
440 # Get the instances that belong to the given slice from sqlite3
441 # XXX use getOne() in production because the slice's hrn is supposed
442 # to be unique. For testing, uniqueness is turned off in the db.
443 # If the slice isn't found in the database, create a record for the
445 matchedSlices = list(Slice.select(Slice.q.slice_hrn == hrn))
447 theSlice = matchedSlices[-1]
449 theSlice = Slice(slice_hrn = hrn)
450 for instance in theSlice.instances:
451 instanceId.append(instance.instance_id)
453 # Get the information about those instances using their ids.
454 if len(instanceId) > 0:
455 reservations = conn.get_all_instances(instanceId)
458 for reservation in reservations:
459 for instance in reservation.instances:
460 instances.append(instance)
462 # Construct a dictionary for the EucaRSpecBuilder
464 for instance in instances:
465 instList = instancesDict.setdefault(instance.instance_type, [])
468 instInfoDict['id'] = instance.id
469 instInfoDict['public_dns'] = instance.public_dns_name
470 instInfoDict['state'] = instance.state
471 instInfoDict['key'] = instance.key_name
473 instList.append(instInfoDict)
474 cloud['instances'] = instancesDict
476 except EC2ResponseError, ec2RespErr:
477 errTree = ET.fromstring(ec2RespErr.body)
478 errMsgE = errTree.find('.//Message')
479 print >>sys.stderr, errMsgE.text
481 rspec = EucaRSpecBuilder(cloud).toXML()
483 # Remove the instances records so next time they won't
485 if 'instances' in cloud:
486 del cloud['instances']
491 Hook called via 'sfi.py create'
493 def create_slice(api, xrn, creds, xml, users):
495 hrn = urn_to_hrn(xrn)[0]
497 conn = getEucaConnection()
499 print >>sys.stderr, 'Error: Cannot create a connection to Eucalyptus'
503 schemaXML = ET.parse(EUCALYPTUS_RSPEC_SCHEMA)
504 rspecValidator = ET.RelaxNG(schemaXML)
505 rspecXML = ET.XML(xml)
506 if not rspecValidator(rspecXML):
507 error = rspecValidator.error_log.last_error
508 message = '%s (line %s)' % (error.message, error.line)
509 # XXX: InvalidRSpec is new. Currently, I am not working with Trunk code.
510 #raise InvalidRSpec(message)
511 raise Exception(message)
513 # Get the slice from db or create one.
514 s = Slice.select(Slice.q.slice_hrn == hrn).getOne(None)
516 s = Slice(slice_hrn = hrn)
518 # Process any changes in existing instance allocation
520 for sliceInst in s.instances:
521 pendingRmInst.append(sliceInst.instance_id)
522 existingInstGroup = rspecXML.findall('.//euca_instances')
523 for instGroup in existingInstGroup:
524 for existingInst in instGroup:
525 if existingInst.get('id') in pendingRmInst:
526 pendingRmInst.remove(existingInst.get('id'))
527 for inst in pendingRmInst:
528 print >>sys.stderr, 'Instance %s will be terminated' % inst
529 dbInst = EucaInstance.select(EucaInstance.q.instance_id == inst).getOne(None)
531 conn.terminate_instances(pendingRmInst)
533 # Process new instance requests
534 requests = rspecXML.findall('.//request')
536 # Get all the public keys associate with slice.
537 pubKeys = getKeysForSlice(s.slice_hrn)
538 print >>sys.stderr, "Passing the following keys to the instance:\n%s" % pubKeys
540 vmTypeElement = req.getparent()
541 instType = vmTypeElement.get('name')
542 numInst = int(req.find('instances').text)
544 bundleName = req.find('bundle').text
545 if not cloud['imageBundles'][bundleName]:
546 print >>sys.stderr, 'Cannot find bundle %s' % bundleName
547 bundleInfo = cloud['imageBundles'][bundleName]
548 instKernel = bundleInfo['kernelID']
549 instDiskImg = bundleInfo['imageID']
550 instRamDisk = bundleInfo['ramdiskID']
553 # Create the instances
554 for i in range(0, numInst):
555 eucaInst = EucaInstance(slice = s,
556 kernel_id = instKernel,
557 image_id = instDiskImg,
558 ramdisk_id = instRamDisk,
560 inst_type = instType)
561 eucaInst.reserveInstance(conn, pubKeys)
569 #with open(sys.argv[1]) as xml:
570 # theRSpec = xml.read()
571 #create_slice(None, 'planetcloud.pc.test', theRSpec)
573 #rspec = get_rspec('euca', 'planetcloud.pc.test', 'planetcloud.pc.marcoy')
575 print getKeysForSlice('gc.gc.test1')
577 if __name__ == "__main__":