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, Xrn
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
21 from sfa.util.callids import Callids
22 from sfa.util.sfalogging import sfa_logger
23 from sfa.rspecs.sfa_rspec import sfa_rspec_version
24 from sfa.util.version import version_core
27 # The data structure used to represent a cloud.
28 # It contains the cloud name, its ip address, image information,
29 # key pairs, and clusters information.
34 # The location of the RelaxNG schema.
36 EUCALYPTUS_RSPEC_SCHEMA='/etc/sfa/eucalyptus.rng'
39 sys.stderr = file('/var/log/euca_agg.log', 'a+')
43 # A representation of an Eucalyptus instance. This is a support class
44 # for instance <-> slice mapping.
46 class EucaInstance(SQLObject):
47 instance_id = StringCol(unique=True, default=None)
48 kernel_id = StringCol()
49 image_id = StringCol()
50 ramdisk_id = StringCol()
51 inst_type = StringCol()
52 key_pair = StringCol()
53 slice = ForeignKey('Slice')
56 # Contacts Eucalyptus and tries to reserve this instance.
58 # @param botoConn A connection to Eucalyptus.
59 # @param pubKeys A list of public keys for the instance.
61 def reserveInstance(self, botoConn, pubKeys):
62 print >>sys.stderr, 'Reserving an instance: image: %s, kernel: ' \
63 '%s, ramdisk: %s, type: %s, key: %s' % \
64 (self.image_id, self.kernel_id, self.ramdisk_id,
65 self.inst_type, self.key_pair)
67 # XXX The return statement is for testing. REMOVE in production
71 reservation = botoConn.run_instances(self.image_id,
72 kernel_id = self.kernel_id,
73 ramdisk_id = self.ramdisk_id,
74 instance_type = self.inst_type,
75 key_name = self.key_pair,
77 for instance in reservation.instances:
78 self.instance_id = instance.id
80 # If there is an error, destroy itself.
81 except EC2ResponseError, ec2RespErr:
82 errTree = ET.fromstring(ec2RespErr.body)
83 msg = errTree.find('.//Message')
84 print >>sys.stderr, msg.text
88 # A representation of a PlanetLab slice. This is a support class
89 # for instance <-> slice mapping.
91 class Slice(SQLObject):
92 slice_hrn = StringCol()
93 #slice_index = DatabaseIndex('slice_hrn')
94 instances = MultipleJoin('EucaInstance')
97 # Initialize the aggregate manager by reading a configuration file.
100 configParser = ConfigParser()
101 configParser.read(['/etc/sfa/eucalyptus_aggregate.conf', 'eucalyptus_aggregate.conf'])
102 if len(configParser.sections()) < 1:
103 print >>sys.stderr, 'No cloud defined in the config file'
104 raise Exception('Cannot find cloud definition in configuration file.')
106 # Only read the first section.
107 cloudSec = configParser.sections()[0]
108 cloud['name'] = cloudSec
109 cloud['access_key'] = configParser.get(cloudSec, 'access_key')
110 cloud['secret_key'] = configParser.get(cloudSec, 'secret_key')
111 cloud['cloud_url'] = configParser.get(cloudSec, 'cloud_url')
112 cloudURL = cloud['cloud_url']
113 if cloudURL.find('https://') >= 0:
114 cloudURL = cloudURL.replace('https://', '')
115 elif cloudURL.find('http://') >= 0:
116 cloudURL = cloudURL.replace('http://', '')
117 (cloud['ip'], parts) = cloudURL.split(':')
119 # Create image bundles
120 images = getEucaConnection().get_all_images()
121 cloud['images'] = images
122 cloud['imageBundles'] = {}
124 if i.type != 'machine' or i.kernel_id is None: continue
125 name = os.path.dirname(i.location)
126 detail = {'imageID' : i.id, 'kernelID' : i.kernel_id, 'ramdiskID' : i.ramdisk_id}
127 cloud['imageBundles'][name] = detail
129 # Initialize sqlite3 database.
130 dbPath = '/etc/sfa/db'
131 dbName = 'euca_aggregate.db'
133 if not os.path.isdir(dbPath):
134 print >>sys.stderr, '%s not found. Creating directory ...' % dbPath
137 conn = connectionForURI('sqlite://%s/%s' % (dbPath, dbName))
138 sqlhub.processConnection = conn
139 Slice.createTable(ifNotExists=True)
140 EucaInstance.createTable(ifNotExists=True)
142 # Make sure the schema exists.
143 if not os.path.exists(EUCALYPTUS_RSPEC_SCHEMA):
144 err = 'Cannot location schema at %s' % EUCALYPTUS_RSPEC_SCHEMA
145 print >>sys.stderr, err
149 # Creates a connection to Eucalytpus. This function is inspired by
150 # the make_connection() in Euca2ools.
152 # @return A connection object or None
154 def getEucaConnection():
156 accessKey = cloud['access_key']
157 secretKey = cloud['secret_key']
158 eucaURL = cloud['cloud_url']
163 if not accessKey or not secretKey or not eucaURL:
164 print >>sys.stderr, 'Please set ALL of the required environment ' \
165 'variables by sourcing the eucarc file.'
168 # Split the url into parts
169 if eucaURL.find('https://') >= 0:
171 eucaURL = eucaURL.replace('https://', '')
172 elif eucaURL.find('http://') >= 0:
174 eucaURL = eucaURL.replace('http://', '')
175 (eucaHost, parts) = eucaURL.split(':')
177 parts = parts.split('/')
178 eucaPort = int(parts[0])
180 srvPath = '/'.join(parts)
182 return boto.connect_ec2(aws_access_key_id=accessKey,
183 aws_secret_access_key=secretKey,
185 region=RegionInfo(None, 'eucalyptus', eucaHost),
190 # Returns a string of keys that belong to the users of the given slice.
191 # @param sliceHRN The hunman readable name of the slice.
194 def getKeysForSlice(sliceHRN):
196 # convert hrn to slice name
197 plSliceName = hrn_to_pl_slicename(sliceHRN)
198 except IndexError, e:
199 print >>sys.stderr, 'Invalid slice name (%s)' % sliceHRN
202 # Get the slice's information
203 sliceData = api.plshell.GetSlices(api.plauth, {'name':plSliceName})
205 print >>sys.stderr, 'Cannot get any data for slice %s' % plSliceName
208 # It should only return a list with len = 1
209 sliceData = sliceData[0]
212 person_ids = sliceData['person_ids']
214 print >>sys.stderr, 'No users in slice %s' % sliceHRN
217 persons = api.plshell.GetPersons(api.plauth, person_ids)
218 for person in persons:
219 pkeys = api.plshell.GetKeys(api.plauth, person['key_ids'])
221 keys.append(key['key'])
226 # A class that builds the RSpec for Eucalyptus.
228 class EucaRSpecBuilder(object):
230 # Initizes a RSpec builder
232 # @param cloud A dictionary containing data about a
233 # cloud (ex. clusters, ip)
234 def __init__(self, cloud):
235 self.eucaRSpec = XMLBuilder(format = True, tab_step = " ")
236 self.cloudInfo = cloud
239 # Creates a request stanza.
241 # @param num The number of instances to create.
242 # @param image The disk image id.
243 # @param kernel The kernel image id.
244 # @param keypair Key pair to embed.
245 # @param ramdisk Ramdisk id (optional).
247 def __requestXML(self, num, image, kernel, keypair, ramdisk = ''):
252 with xml.kernel_image(id=kernel):
258 with xml.ramdisk(id=ramdisk):
260 with xml.disk_image(id=image):
266 # Creates the cluster stanza.
268 # @param clusters Clusters information.
270 def __clustersXML(self, clusters):
271 cloud = self.cloudInfo
274 for cluster in clusters:
275 instances = cluster['instances']
276 with xml.cluster(id=cluster['name']):
280 for inst in instances:
281 with xml.vm_type(name=inst[0]):
284 with xml.max_instances:
288 with xml.memory(unit='MB'):
290 with xml.disk_space(unit='GB'):
292 if 'instances' in cloud and inst[0] in cloud['instances']:
293 existingEucaInstances = cloud['instances'][inst[0]]
294 with xml.euca_instances:
295 for eucaInst in existingEucaInstances:
296 with xml.euca_instance(id=eucaInst['id']):
298 xml << eucaInst['state']
300 xml << eucaInst['public_dns']
302 def __imageBundleXML(self, bundles):
305 for bundle in bundles.keys():
306 with xml.bundle(id=bundle):
310 # Creates the Images stanza.
312 # @param images A list of images in Eucalyptus.
314 def __imagesXML(self, images):
318 with xml.image(id=image.id):
322 xml << image.architecture
326 xml << image.location
329 # Creates the KeyPairs stanza.
331 # @param keypairs A list of key pairs in Eucalyptus.
333 def __keyPairsXML(self, keypairs):
341 # Generates the RSpec.
344 if not self.cloudInfo:
345 print >>sys.stderr, 'No cloud information'
349 cloud = self.cloudInfo
350 with xml.RSpec(type='eucalyptus'):
351 with xml.network(id=cloud['name']):
354 #self.__keyPairsXML(cloud['keypairs'])
355 #self.__imagesXML(cloud['images'])
356 self.__imageBundleXML(cloud['imageBundles'])
357 self.__clustersXML(cloud['clusters'])
361 # A parser to parse the output of availability-zones.
363 # Note: Only one cluster is supported. If more than one, this will
366 class ZoneResultParser(object):
367 def __init__(self, zones):
371 if len(self.zones) < 3:
377 cluster['name'] = self.zones[0].name
378 cluster['ip'] = self.zones[0].state
380 for i in range(2, len(self.zones)):
381 currZone = self.zones[i]
382 instType = currZone.name.split()[1]
384 stateString = currZone.state.split('/')
385 rscString = stateString[1].split()
387 instFree = int(stateString[0])
388 instMax = int(rscString[0])
389 instNumCpu = int(rscString[1])
390 instRam = int(rscString[2])
391 instDiskSpace = int(rscString[3])
393 instTuple = (instType, instFree, instMax, instNumCpu, instRam, instDiskSpace)
394 instList.append(instTuple)
395 cluster['instances'] = instList
396 clusterList.append(cluster)
400 def ListResources(api, creds, options, call_id):
401 if Callids().already_handled(call_id): return ""
403 # get slice's hrn from options
404 xrn = options.get('geni_slice_urn', '')
405 hrn, type = urn_to_hrn(xrn)
407 # get hrn of the original caller
408 origin_hrn = options.get('origin_hrn', None)
410 origin_hrn = Credential(string=creds).get_gid_caller().get_hrn()
411 # origin_hrn = Credential(string=creds[0]).get_gid_caller().get_hrn()
413 conn = getEucaConnection()
416 print >>sys.stderr, 'Error: Cannot create a connection to Eucalyptus'
417 return 'Cannot create a connection to Eucalyptus'
421 zones = conn.get_all_zones(['verbose'])
422 p = ZoneResultParser(zones)
424 cloud['clusters'] = clusters
427 images = conn.get_all_images()
428 cloud['images'] = images
429 cloud['imageBundles'] = {}
431 if i.type != 'machine' or i.kernel_id is None: continue
432 name = os.path.dirname(i.location)
433 detail = {'imageID' : i.id, 'kernelID' : i.kernel_id, 'ramdiskID' : i.ramdisk_id}
434 cloud['imageBundles'][name] = detail
437 keyPairs = conn.get_all_key_pairs()
438 cloud['keypairs'] = keyPairs
444 # Get the instances that belong to the given slice from sqlite3
445 # XXX use getOne() in production because the slice's hrn is supposed
446 # to be unique. For testing, uniqueness is turned off in the db.
447 # If the slice isn't found in the database, create a record for the
449 matchedSlices = list(Slice.select(Slice.q.slice_hrn == hrn))
451 theSlice = matchedSlices[-1]
453 theSlice = Slice(slice_hrn = hrn)
454 for instance in theSlice.instances:
455 instanceId.append(instance.instance_id)
457 # Get the information about those instances using their ids.
458 if len(instanceId) > 0:
459 reservations = conn.get_all_instances(instanceId)
462 for reservation in reservations:
463 for instance in reservation.instances:
464 instances.append(instance)
466 # Construct a dictionary for the EucaRSpecBuilder
468 for instance in instances:
469 instList = instancesDict.setdefault(instance.instance_type, [])
472 instInfoDict['id'] = instance.id
473 instInfoDict['public_dns'] = instance.public_dns_name
474 instInfoDict['state'] = instance.state
475 instInfoDict['key'] = instance.key_name
477 instList.append(instInfoDict)
478 cloud['instances'] = instancesDict
480 except EC2ResponseError, ec2RespErr:
481 errTree = ET.fromstring(ec2RespErr.body)
482 errMsgE = errTree.find('.//Message')
483 print >>sys.stderr, errMsgE.text
485 rspec = EucaRSpecBuilder(cloud).toXML()
487 # Remove the instances records so next time they won't
489 if 'instances' in cloud:
490 del cloud['instances']
495 Hook called via 'sfi.py create'
497 def CreateSliver(api, xrn, creds, xml, users, call_id):
498 if Callids().already_handled(call_id): return ""
501 hrn = urn_to_hrn(xrn)[0]
503 conn = getEucaConnection()
505 print >>sys.stderr, 'Error: Cannot create a connection to Eucalyptus'
509 schemaXML = ET.parse(EUCALYPTUS_RSPEC_SCHEMA)
510 rspecValidator = ET.RelaxNG(schemaXML)
511 rspecXML = ET.XML(xml)
512 if False and not rspecValidator(rspecXML):
513 error = rspecValidator.error_log.last_error
514 message = '%s (line %s)' % (error.message, error.line)
515 # XXX: InvalidRSpec is new. Currently, I am not working with Trunk code.
516 #raise InvalidRSpec(message)
517 raise Exception(message)
519 # Get the slice from db or create one.
520 s = Slice.select(Slice.q.slice_hrn == hrn).getOne(None)
522 s = Slice(slice_hrn = hrn)
524 # Process any changes in existing instance allocation
526 for sliceInst in s.instances:
527 pendingRmInst.append(sliceInst.instance_id)
528 existingInstGroup = rspecXML.findall("./network[@id='%s']//euca_instances"%cloud['name'])
529 for instGroup in existingInstGroup:
530 for existingInst in instGroup:
531 if existingInst.get('id') in pendingRmInst:
532 pendingRmInst.remove(existingInst.get('id'))
533 for inst in pendingRmInst:
534 print >>sys.stderr, 'Instance %s will be terminated' % inst
535 dbInst = EucaInstance.select(EucaInstance.q.instance_id == inst).getOne(None)
537 conn.terminate_instances(pendingRmInst)
539 # Process new instance requests
540 requests = rspecXML.findall("./network[@id='%s']//request"%cloud['name'])
542 # Get all the public keys associate with slice.
543 pubKeys = getKeysForSlice(s.slice_hrn)
544 print >>sys.stderr, "Passing the following keys to the instance:\n%s" % pubKeys
547 vmTypeElement = req.getparent()
548 instType = vmTypeElement.get('name')
549 numInst = int(req.find('instances').text)
551 bundleName = req.find('bundle').text
552 if not cloud['imageBundles'][bundleName]:
553 print >>sys.stderr, 'Cannot find bundle %s' % bundleName
554 bundleInfo = cloud['imageBundles'][bundleName]
555 instKernel = bundleInfo['kernelID']
556 instDiskImg = bundleInfo['imageID']
557 instRamDisk = bundleInfo['ramdiskID']
560 # Create the instances
561 for i in range(0, numInst):
562 eucaInst = EucaInstance(slice = s,
563 kernel_id = instKernel,
564 image_id = instDiskImg,
565 ramdisk_id = instRamDisk,
567 inst_type = instType)
568 eucaInst.reserveInstance(conn, pubKeys)
570 # xxx - should return altered rspec
571 # with enough data for the client to understand what's happened
576 request_rspec_versions = [dict(sfa_rspec_version)]
577 ad_rspec_versions = [dict(sfa_rspec_version)]
578 version_more = {'interface':'aggregate',
581 'request_rspec_versions': request_rspec_versions,
582 'ad_rspec_versions': ad_rspec_versions,
583 'default_ad_rspec': dict(sfa_rspec_version)
585 return version_core(version_more)
591 #with open(sys.argv[1]) as xml:
592 # theRSpec = xml.read()
593 #CreateSliver(None, 'planetcloud.pc.test', theRSpec, 'call-id-cloudtest')
595 #rspec = ListResources('euca', 'planetcloud.pc.test', 'planetcloud.pc.marcoy', 'test_euca')
597 print getKeysForSlice('gc.gc.test1')
599 if __name__ == "__main__":