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 # Initialize sqlite3 database.
116 dbPath = '/etc/sfa/db'
117 dbName = 'euca_aggregate.db'
119 if not os.path.isdir(dbPath):
120 print >>sys.stderr, '%s not found. Creating directory ...' % dbPath
123 conn = connectionForURI('sqlite://%s/%s' % (dbPath, dbName))
124 sqlhub.processConnection = conn
125 Slice.createTable(ifNotExists=True)
126 EucaInstance.createTable(ifNotExists=True)
128 # Make sure the schema exists.
129 if not os.path.exists(EUCALYPTUS_RSPEC_SCHEMA):
130 err = 'Cannot location schema at %s' % EUCALYPTUS_RSPEC_SCHEMA
131 print >>sys.stderr, err
135 # Creates a connection to Eucalytpus. This function is inspired by
136 # the make_connection() in Euca2ools.
138 # @return A connection object or None
140 def getEucaConnection():
142 accessKey = cloud['access_key']
143 secretKey = cloud['secret_key']
144 eucaURL = cloud['cloud_url']
149 if not accessKey or not secretKey or not eucaURL:
150 print >>sys.stderr, 'Please set ALL of the required environment ' \
151 'variables by sourcing the eucarc file.'
154 # Split the url into parts
155 if eucaURL.find('https://') >= 0:
157 eucaURL = eucaURL.replace('https://', '')
158 elif eucaURL.find('http://') >= 0:
160 eucaURL = eucaURL.replace('http://', '')
161 (eucaHost, parts) = eucaURL.split(':')
163 parts = parts.split('/')
164 eucaPort = int(parts[0])
166 srvPath = '/'.join(parts)
168 return boto.connect_ec2(aws_access_key_id=accessKey,
169 aws_secret_access_key=secretKey,
171 region=RegionInfo(None, 'eucalyptus', eucaHost),
176 # Returns a string of keys that belong to the users of the given slice.
177 # @param sliceHRN The hunman readable name of the slice.
180 def getKeysForSlice(sliceHRN):
182 # convert hrn to slice name
183 plSliceName = hrn_to_pl_slicename(sliceHRN)
184 except IndexError, e:
185 print >>sys.stderr, 'Invalid slice name (%s)' % sliceHRN
188 # Get the slice's information
189 sliceData = api.plshell.GetSlices(api.plauth, {'name':plSliceName})
191 print >>sys.stderr, 'Cannot get any data for slice %s' % plSliceName
194 # It should only return a list with len = 1
195 sliceData = sliceData[0]
198 person_ids = sliceData['person_ids']
200 print >>sys.stderr, 'No users in slice %s' % sliceHRN
203 persons = api.plshell.GetPersons(api.plauth, person_ids)
204 for person in persons:
205 pkeys = api.plshell.GetKeys(api.plauth, person['key_ids'])
207 keys.append(key['key'])
212 # A class that builds the RSpec for Eucalyptus.
214 class EucaRSpecBuilder(object):
216 # Initizes a RSpec builder
218 # @param cloud A dictionary containing data about a
219 # cloud (ex. clusters, ip)
220 def __init__(self, cloud):
221 self.eucaRSpec = XMLBuilder(format = True, tab_step = " ")
222 self.cloudInfo = cloud
225 # Creates a request stanza.
227 # @param num The number of instances to create.
228 # @param image The disk image id.
229 # @param kernel The kernel image id.
230 # @param keypair Key pair to embed.
231 # @param ramdisk Ramdisk id (optional).
233 def __requestXML(self, num, image, kernel, keypair, ramdisk = ''):
238 with xml.kernel_image(id=kernel):
244 with xml.ramdisk(id=ramdisk):
246 with xml.disk_image(id=image):
252 # Creates the cluster stanza.
254 # @param clusters Clusters information.
256 def __clustersXML(self, clusters):
257 cloud = self.cloudInfo
260 for cluster in clusters:
261 instances = cluster['instances']
262 with xml.cluster(id=cluster['name']):
266 for inst in instances:
267 with xml.vm_type(name=inst[0]):
270 with xml.max_instances:
274 with xml.memory(unit='MB'):
276 with xml.disk_space(unit='GB'):
278 if inst[0] == 'm1.small':
279 self.__requestXML(1, 'emi-88760F45', 'eki-F26610C6', 'cortex')
280 if 'instances' in cloud and inst[0] in cloud['instances']:
281 existingEucaInstances = cloud['instances'][inst[0]]
282 with xml.euca_instances:
283 for eucaInst in existingEucaInstances:
284 with xml.euca_instance(id=eucaInst['id']):
286 xml << eucaInst['state']
288 xml << eucaInst['public_dns']
290 xml << eucaInst['key']
293 # Creates the Images stanza.
295 # @param images A list of images in Eucalyptus.
297 def __imagesXML(self, images):
301 with xml.image(id=image.id):
305 xml << image.architecture
309 xml << image.location
312 # Creates the KeyPairs stanza.
314 # @param keypairs A list of key pairs in Eucalyptus.
316 def __keyPairsXML(self, keypairs):
324 # Generates the RSpec.
327 if not self.cloudInfo:
328 print >>sys.stderr, 'No cloud information'
332 cloud = self.cloudInfo
333 with xml.RSpec(type='eucalyptus'):
334 with xml.cloud(id=cloud['name']):
337 self.__keyPairsXML(cloud['keypairs'])
338 self.__imagesXML(cloud['images'])
339 self.__clustersXML(cloud['clusters'])
343 # A parser to parse the output of availability-zones.
345 # Note: Only one cluster is supported. If more than one, this will
348 class ZoneResultParser(object):
349 def __init__(self, zones):
353 if len(self.zones) < 3:
359 cluster['name'] = self.zones[0].name
360 cluster['ip'] = self.zones[0].state
362 for i in range(2, len(self.zones)):
363 currZone = self.zones[i]
364 instType = currZone.name.split()[1]
366 stateString = currZone.state.split('/')
367 rscString = stateString[1].split()
369 instFree = int(stateString[0])
370 instMax = int(rscString[0])
371 instNumCpu = int(rscString[1])
372 instRam = int(rscString[2])
373 instDiskSpace = int(rscString[3])
375 instTuple = (instType, instFree, instMax, instNumCpu, instRam, instDiskSpace)
376 instList.append(instTuple)
377 cluster['instances'] = instList
378 clusterList.append(cluster)
382 def get_rspec(api, creds, options):
384 # get slice's hrn from options
385 xrn = options.get('geni_slice_urn', '')
386 hrn, type = urn_to_hrn(xrn)
388 # get hrn of the original caller
389 origin_hrn = options.get('origin_hrn', None)
391 origin_hrn = Credential(string=creds[0]).get_gid_caller().get_hrn()
393 conn = getEucaConnection()
396 print >>sys.stderr, 'Error: Cannot create a connection to Eucalyptus'
397 return 'Cannot create a connection to Eucalyptus'
401 zones = conn.get_all_zones(['verbose'])
402 p = ZoneResultParser(zones)
404 cloud['clusters'] = clusters
407 images = conn.get_all_images()
408 cloud['images'] = images
411 keyPairs = conn.get_all_key_pairs()
412 cloud['keypairs'] = keyPairs
418 # Get the instances that belong to the given slice from sqlite3
419 # XXX use getOne() in production because the slice's hrn is supposed
420 # to be unique. For testing, uniqueness is turned off in the db.
421 # If the slice isn't found in the database, create a record for the
423 matchedSlices = list(Slice.select(Slice.q.slice_hrn == hrn))
425 theSlice = matchedSlices[-1]
427 theSlice = Slice(slice_hrn = hrn)
428 for instance in theSlice.instances:
429 instanceId.append(instance.instance_id)
431 # Get the information about those instances using their ids.
432 if len(instanceId) > 0:
433 reservations = conn.get_all_instances(instanceId)
436 for reservation in reservations:
437 for instance in reservation.instances:
438 instances.append(instance)
440 # Construct a dictory for the EucaRSpecBuilder
442 for instance in instances:
443 instList = instancesDict.setdefault(instance.instance_type, [])
446 instInfoDict['id'] = instance.id
447 instInfoDict['public_dns'] = instance.public_dns_name
448 instInfoDict['state'] = instance.state
449 instInfoDict['key'] = instance.key_name
451 instList.append(instInfoDict)
452 cloud['instances'] = instancesDict
454 except EC2ResponseError, ec2RespErr:
455 errTree = ET.fromstring(ec2RespErr.body)
456 errMsgE = errTree.find('.//Message')
457 print >>sys.stderr, errMsgE.text
459 rspec = EucaRSpecBuilder(cloud).toXML()
461 # Remove the instances records so next time they won't
463 if 'instances' in cloud:
464 del cloud['instances']
469 Hook called via 'sfi.py create'
471 def create_slice(api, xrn, creds, xml, users):
473 hrn = urn_to_hrn(xrn)[0]
475 conn = getEucaConnection()
477 print >>sys.stderr, 'Error: Cannot create a connection to Eucalyptus'
481 schemaXML = ET.parse(EUCALYPTUS_RSPEC_SCHEMA)
482 rspecValidator = ET.RelaxNG(schemaXML)
483 rspecXML = ET.XML(xml)
484 if not rspecValidator(rspecXML):
485 error = rspecValidator.error_log.last_error
486 message = '%s (line %s)' % (error.message, error.line)
487 # XXX: InvalidRSpec is new. Currently, I am not working with Trunk code.
488 #raise InvalidRSpec(message)
489 raise Exception(message)
491 # Get the slice from db or create one.
492 s = Slice.select(Slice.q.slice_hrn == hrn).getOne(None)
494 s = Slice(slice_hrn = hrn)
496 # Process any changes in existing instance allocation
498 for sliceInst in s.instances:
499 pendingRmInst.append(sliceInst.instance_id)
500 existingInstGroup = rspecXML.findall('.//euca_instances')
501 for instGroup in existingInstGroup:
502 for existingInst in instGroup:
503 if existingInst.get('id') in pendingRmInst:
504 pendingRmInst.remove(existingInst.get('id'))
505 for inst in pendingRmInst:
506 print >>sys.stderr, 'Instance %s will be terminated' % inst
507 dbInst = EucaInstance.select(EucaInstance.q.instance_id == inst).getOne(None)
509 conn.terminate_instances(pendingRmInst)
511 # Process new instance requests
512 requests = rspecXML.findall('.//request')
514 # Get all the public keys associate with slice.
515 pubKeys = getKeysForSlice(s.slice_hrn)
516 print sys.stderr, "Passing the following keys to the instance:\n%s" % pubKeys
518 vmTypeElement = req.getparent()
519 instType = vmTypeElement.get('name')
520 numInst = int(req.find('instances').text)
521 instKernel = req.find('kernel_image').get('id')
522 instDiskImg = req.find('disk_image').get('id')
523 instKey = req.find('keypair').text
525 ramDiskElement = req.find('ramdisk')
526 ramDiskAttr = ramDiskElement.attrib
527 if 'id' in ramDiskAttr:
528 instRamDisk = ramDiskAttr['id']
532 # Create the instances
533 for i in range(0, numInst):
534 eucaInst = EucaInstance(slice = s,
535 kernel_id = instKernel,
536 image_id = instDiskImg,
537 ramdisk_id = instRamDisk,
539 inst_type = instType)
540 eucaInst.reserveInstance(conn, pubKeys)
548 #with open(sys.argv[1]) as xml:
549 # theRSpec = xml.read()
550 #create_slice(None, 'planetcloud.pc.test', theRSpec)
552 #rspec = get_rspec('euca', 'planetcloud.pc.test', 'planetcloud.pc.marcoy')
554 print getKeysForSlice('gc.gc.test1')
556 if __name__ == "__main__":