Minor tweaks
[sfa.git] / sfa / managers / aggregate_manager_eucalyptus.py
1 from __future__ import with_statement 
2 from sfa.util.faults import *
3 from sfa.util.namespace import *
4 from sfa.util.rspec import RSpec
5 from sfa.server.registry import Registries
6 from sfa.plc.nodes import *
7
8 import boto
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 *
15
16 import sys
17 import os
18
19 ##
20 # The data structure used to represent a cloud.
21 # It contains the cloud name, its ip address, image information,
22 # key pairs, and clusters information.
23 #
24 cloud = {}
25
26 ##
27 # The location of the RelaxNG schema.
28 #
29 EUCALYPTUS_RSPEC_SCHEMA='/etc/sfa/eucalyptus.rng'
30
31 ##
32 # A representation of an Eucalyptus instance. This is a support class
33 # for instance <-> slice mapping.
34 #
35 class EucaInstance(SQLObject):
36     instance_id = StringCol(unique=True, default=None)
37     kernel_id   = StringCol()
38     image_id    = StringCol()
39     ramdisk_id  = StringCol()
40     inst_type   = StringCol()
41     key_pair    = StringCol()
42     slice = ForeignKey('Slice')
43
44     ##
45     # Contacts Eucalyptus and tries to reserve this instance.
46     # 
47     # @param botoConn A connection to Eucalyptus.
48     #
49     def reserveInstance(self, botoConn):
50         print >>sys.stderr, 'Reserving an instance: image: %s, kernel: ' \
51                             '%s, ramdisk: %s, type: %s, key: %s' % \
52                             (self.image_id, self.kernel_id, self.ramdisk_id, 
53                              self.inst_type, self.key_pair)
54
55         # XXX The return statement is for testing. REMOVE in production
56         #return
57
58         try:
59             reservation = botoConn.run_instances(self.image_id,
60                                                  kernel_id = self.kernel_id,
61                                                  ramdisk_id = self.ramdisk_id,
62                                                  instance_type = self.inst_type,
63                                                  key_name  = self.key_pair)
64             for instance in reservation.instances:
65                 self.instance_id = instance.id
66
67         # If there is an error, destroy itself.
68         except EC2ResponseError, ec2RespErr:
69             errTree = ET.fromstring(ec2RespErr.body)
70             msg = errTree.find('.//Message')
71             print >>sys.stderr, msg.text
72             self.destroySelf()
73
74 ##
75 # A representation of a PlanetLab slice. This is a support class
76 # for instance <-> slice mapping.
77 #
78 class Slice(SQLObject):
79     slice_hrn = StringCol()
80     #slice_index = DatabaseIndex('slice_hrn')
81     instances = MultipleJoin('EucaInstance')
82
83 ##
84 # Initialize the aggregate manager by reading a configuration file.
85 #
86 def init_server():
87     configParser = ConfigParser()
88     configParser.read(['/etc/sfa/eucalyptus_aggregate.conf', 'eucalyptus_aggregate.conf'])
89     if len(configParser.sections()) < 1:
90         print >>sys.stderr, 'No cloud defined in the config file'
91         raise Exception('Cannot find cloud definition in configuration file.')
92
93     # Only read the first section.
94     cloudSec = configParser.sections()[0]
95     cloud['name'] = cloudSec
96     cloud['access_key'] = configParser.get(cloudSec, 'access_key')
97     cloud['secret_key'] = configParser.get(cloudSec, 'secret_key')
98     cloud['cloud_url']  = configParser.get(cloudSec, 'cloud_url')
99     cloudURL = cloud['cloud_url']
100     if cloudURL.find('https://') >= 0:
101         cloudURL = cloudURL.replace('https://', '')
102     elif cloudURL.find('http://') >= 0:
103         cloudURL = cloudURL.replace('http://', '')
104     (cloud['ip'], parts) = cloudURL.split(':')
105
106     # Initialize sqlite3 database.
107     dbPath = '/etc/sfa/db'
108     dbName = 'euca_aggregate.db'
109
110     if not os.path.isdir(dbPath):
111         print >>sys.stderr, '%s not found. Creating directory ...' % dbPath
112         os.mkdir(dbPath)
113
114     conn = connectionForURI('sqlite://%s/%s' % (dbPath, dbName))
115     sqlhub.processConnection = conn
116     Slice.createTable(ifNotExists=True)
117     EucaInstance.createTable(ifNotExists=True)
118
119     # Make sure the schema exists.
120     if not os.path.exists(EUCALYPTUS_RSPEC_SCHEMA):
121         err = 'Cannot location schema at %s' % EUCALYPTUS_RSPEC_SCHEMA
122         print >>sys.stderr, err
123         raise Exception(err)
124
125 ##
126 # Creates a connection to Eucalytpus. This function is inspired by 
127 # the make_connection() in Euca2ools.
128 #
129 # @return A connection object or None
130 #
131 def getEucaConnection():
132     global cloud
133     accessKey = cloud['access_key']
134     secretKey = cloud['secret_key']
135     eucaURL   = cloud['cloud_url']
136     useSSL    = False
137     srvPath   = '/'
138     eucaPort  = 8773
139
140     if not accessKey or not secretKey or not eucaURL:
141         print >>sys.stderr, 'Please set ALL of the required environment ' \
142                             'variables by sourcing the eucarc file.'
143         return None
144     
145     # Split the url into parts
146     if eucaURL.find('https://') >= 0:
147         useSSL  = True
148         eucaURL = eucaURL.replace('https://', '')
149     elif eucaURL.find('http://') >= 0:
150         useSSL  = False
151         eucaURL = eucaURL.replace('http://', '')
152     (eucaHost, parts) = eucaURL.split(':')
153     if len(parts) > 1:
154         parts = parts.split('/')
155         eucaPort = int(parts[0])
156         parts = parts[1:]
157         srvPath = '/'.join(parts)
158
159     return boto.connect_ec2(aws_access_key_id=accessKey,
160                             aws_secret_access_key=secretKey,
161                             is_secure=useSSL,
162                             region=RegionInfo(None, 'eucalyptus', eucaHost), 
163                             port=eucaPort,
164                             path=srvPath)
165
166 ##
167 # A class that builds the RSpec for Eucalyptus.
168 #
169 class EucaRSpecBuilder(object):
170     ##
171     # Initizes a RSpec builder
172     #
173     # @param cloud A dictionary containing data about a 
174     #              cloud (ex. clusters, ip)
175     def __init__(self, cloud):
176         self.eucaRSpec = XMLBuilder(format = True, tab_step = "  ")
177         self.cloudInfo = cloud
178
179     ##
180     # Creates a request stanza.
181     # 
182     # @param num The number of instances to create.
183     # @param image The disk image id.
184     # @param kernel The kernel image id.
185     # @param keypair Key pair to embed.
186     # @param ramdisk Ramdisk id (optional).
187     #
188     def __requestXML(self, num, image, kernel, keypair, ramdisk = ''):
189         xml = self.eucaRSpec
190         with xml.request:
191             with xml.instances:
192                 xml << str(num)
193             with xml.kernel_image(id=kernel):
194                 xml << ''
195             if ramdisk == '':
196                 with xml.ramdisk:
197                     xml << ''
198             else:
199                 with xml.ramdisk(id=ramdisk):
200                     xml << ''
201             with xml.disk_image(id=image):
202                 xml << ''
203             with xml.keypair:
204                 xml << keypair
205
206     ##
207     # Creates the cluster stanza.
208     #
209     # @param clusters Clusters information.
210     #
211     def __clustersXML(self, clusters):
212         xml = self.eucaRSpec
213         for cluster in clusters:
214             instances = cluster['instances']
215             with xml.cluster(id=cluster['name']):
216                 with xml.ipv4:
217                     xml << cluster['ip']
218                 with xml.vm_types:
219                     for inst in instances:
220                         with xml.vm_type(name=inst[0]):
221                             with xml.free_slots:
222                                 xml << str(inst[1])
223                             with xml.max_instances:
224                                 xml << str(inst[2])
225                             with xml.cores:
226                                 xml << str(inst[3])
227                             with xml.memory(unit='MB'):
228                                 xml << str(inst[4])
229                             with xml.disk_space(unit='GB'):
230                                 xml << str(inst[5])
231                             if inst[0] == 'm1.small':
232                                 self.__requestXML(1, 'emi-88760F45', 'eki-F26610C6', 'cortex')
233
234
235     ##
236     # Creates the Images stanza.
237     #
238     # @param images A list of images in Eucalyptus.
239     #
240     def __imagesXML(self, images):
241         xml = self.eucaRSpec
242         with xml.images:
243             for image in images:
244                 with xml.image(id=image.id):
245                     with xml.type:
246                         xml << image.type
247                     with xml.arch:
248                         xml << image.architecture
249                     with xml.state:
250                         xml << image.state
251                     with xml.location:
252                         xml << image.location
253
254     ##
255     # Creates the KeyPairs stanza.
256     #
257     # @param keypairs A list of key pairs in Eucalyptus.
258     #
259     def __keyPairsXML(self, keypairs):
260         xml = self.eucaRSpec
261         with xml.keypairs:
262             for key in keypairs:
263                 with xml.keypair:
264                     xml << key.name
265
266     ##
267     # Generates the RSpec.
268     #
269     def toXML(self):
270         if not self.cloudInfo:
271             print >>sys.stderr, 'No cloud information'
272             return ''
273
274         xml = self.eucaRSpec
275         cloud = self.cloudInfo
276         with xml.RSpec(type='eucalyptus'):
277             with xml.cloud(id=cloud['name']):
278                 with xml.ipv4:
279                     xml << cloud['ip']
280                 self.__keyPairsXML(cloud['keypairs'])
281                 self.__imagesXML(cloud['images'])
282                 self.__clustersXML(cloud['clusters'])
283         return str(xml)
284
285 ##
286 # A parser to parse the output of availability-zones.
287 #
288 # Note: Only one cluster is supported. If more than one, this will
289 #       not work.
290 #
291 class ZoneResultParser(object):
292     def __init__(self, zones):
293         self.zones = zones
294
295     def parse(self):
296         if len(self.zones) < 3:
297             return
298         clusterList = []
299         cluster = {} 
300         instList = []
301
302         cluster['name'] = self.zones[0].name
303         cluster['ip']   = self.zones[0].state
304
305         for i in range(2, len(self.zones)):
306             currZone = self.zones[i]
307             instType = currZone.name.split()[1]
308
309             stateString = currZone.state.split('/')
310             rscString   = stateString[1].split()
311
312             instFree      = int(stateString[0])
313             instMax       = int(rscString[0])
314             instNumCpu    = int(rscString[1])
315             instRam       = int(rscString[2])
316             instDiskSpace = int(rscString[3])
317
318             instTuple = (instType, instFree, instMax, instNumCpu, instRam, instDiskSpace)
319             instList.append(instTuple)
320         cluster['instances'] = instList
321         clusterList.append(cluster)
322
323         return clusterList
324
325 def get_rspec(api, xrn, origin_hrn):
326     global cloud
327     hrn = urn_to_hrn(xrn)[0]
328     conn = getEucaConnection()
329
330     if not conn:
331         print >>sys.stderr, 'Error: Cannot create a connection to Eucalyptus'
332         return 'Cannot create a connection to Eucalyptus'
333
334     try:
335         # Zones
336         zones = conn.get_all_zones(['verbose'])
337         p = ZoneResultParser(zones)
338         clusters = p.parse()
339         cloud['clusters'] = clusters
340         
341         # Images
342         images = conn.get_all_images()
343         cloud['images'] = images
344
345         # Key Pairs
346         keyPairs = conn.get_all_key_pairs()
347         cloud['keypairs'] = keyPairs
348     except EC2ResponseError, ec2RespErr:
349         errTree = ET.fromstring(ec2RespErr.body)
350         errMsgE = errTree.find('.//Message')
351         print >>sys.stderr, errMsgE.text
352
353     rspec = EucaRSpecBuilder(cloud).toXML()
354
355     return rspec
356
357 """
358 Hook called via 'sfi.py create'
359 """
360 def create_slice(api, xrn, xml):
361     global cloud
362     hrn = urn_to_hrn(xrn)[0]
363
364     conn = getEucaConnection()
365     if not conn:
366         print >>sys.stderr, 'Error: Cannot create a connection to Eucalyptus'
367         return False
368
369     # Get the slice from db or create one.
370     # XXX: For testing purposes, I'll just create the slice.
371     #s = Slice.select(Slice.q.slice_hrn == hrn).getOne(None)
372     #if s is None:
373     s = Slice(slice_hrn = hrn)
374
375     # Validate RSpec
376     schemaXML = ET.parse(EUCALYPTUS_RSPEC_SCHEMA)
377     rspecValidator = ET.RelaxNG(schemaXML)
378     rspecXML = ET.XML(xml)
379     if not rspecValidator(rspecXML):
380         error = rspecValidator.error_log.last_error
381         message = '%s (line %s)' % (error.message, error.line) 
382         raise InvalidRSpec(message)
383
384     # Process the RSpec
385     requests = rspecXML.findall('.//request')
386     for req in requests:
387         vmTypeElement = req.getparent()
388         instType = vmTypeElement.get('name')
389         numInst  = int(req.find('instances').text)
390         instKernel  = req.find('kernel_image').get('id')
391         instDiskImg = req.find('disk_image').get('id')
392         instKey     = req.find('keypair').text
393         
394         ramDiskElement = req.find('ramdisk')
395         ramDiskAttr    = ramDiskElement.attrib
396         if 'id' in ramDiskAttr:
397             instRamDisk = ramDiskAttr['id']
398         else:
399             instRamDisk = None
400
401         # Create the instances
402         for i in range(0, numInst):
403             eucaInst = EucaInstance(slice = s, 
404                                     kernel_id = instKernel,
405                                     image_id = instDiskImg,
406                                     ramdisk_id = instRamDisk,
407                                     key_pair = instKey,
408                                     inst_type = instType)
409             eucaInst.reserveInstance(conn)
410
411     return True
412
413 def main():
414     init_server()
415
416     theRSpec = None
417     with open(sys.argv[1]) as xml:
418         theRSpec = xml.read()
419     create_slice(None, 'planetcloud.pc.test', theRSpec)
420
421     #rspec = get_rspec('euca', 'hrn:euca', 'oring_hrn')
422     #print rspec
423
424 if __name__ == "__main__":
425     main()
426