~registry/uec-testing-scripts/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#!/usr/bin/python

import datetime
import logging
import os, os.path
import random
import re
import string
import sys
import yaml
import urllib2
import uec_instances

from twisted.internet import reactor, task
from twisted.python import usage
from zipfile import ZipFile, is_zipfile
from shutil import rmtree
from collections import defaultdict, namedtuple

import uec_utils

class Options(usage.Options):
    optFlags = [
        ["write_log", 'w', "Write log to file" ],
        ["max_instances", 'm', "Run the maximum number of instances" ],
    ]
    optParameters = [
        ["log", "l", "info", 
         "log level wanted (debug, info, warning, error, critical"],
        ["start_stop", "s", None, 
         "start and stop instances over a certain period of time (x minutes)"],
    ]

euca_create_volume    = 'euca-create-volume'
euca_delete_volume    = 'euca-delete-volume'
euca_attach_volume    = 'euca-attach-volume'
euca_detach_volume    = 'euca-detach-volume'
euca_create_snapshot  = 'euca-create-snapshot'
euca_delete_snapshot  = 'euca-delete-snapshot'
euca_describe_volsnap = 'euca-describe-volumes && euca-describe-snapshots'

volumes    = []
snapshots  = []
admin_user = None

class Volume(object):   
    def __init__(self, cluster, user):
        self.cluster       = cluster
        self.size          = None
        self.snapshot      = None
        self.user          = user
        self.id            = None
        self._state        = None
        self.instance      = None
        self.device        = None

    def __repr__(self):
        return "<Volume: %s - %s - %s - %s>" % (self.id, self.user,
                                                self.cluster, self.state)
        
    @property
    def logger(self):
        if self.id:
            return logging.getLogger("VOLUME %s" % (self.id))
        else:
            return logging.getLogger()        
        
    @property
    def state(self):
        return self._state
    @state.setter
    def state(self, value):
        self.logger.debug("State: %s" % (value))
        # The state has changed
        if self._state != value:
            self.logger.debug("New state: %s => %s" % (self._state, value))
            self._state = value        
  
    def getProcessOutput(self, executable, args=(), timeout=60):
        self.logger.debug("Executing: %s - %s" % (executable, args))
        return self.user.getProcessOutput(executable, args, timeout)            
            
    def create(self, **kw):
        if kw.has_key('snapshot'):
            self.snapshot = kw['snapshot']
            self.logger.info("Creating volume from %s" %self.snapshot)
            output = self.getProcessOutput(euca_create_volume,
                                           args= ['--snapshot', self.snapshot,
                                                  '-z', self.cluster])
            output.addCallbacks(self.created, self.errCreated)
        elif kw.has_key('size'):
            self.size = kw['size']
            self.logger.info("Creating volume with size = %s GB" %self.size)
            output = self.getProcessOutput(euca_create_volume,
                                           args= ['-s', self.size,
                                                  '-z', self.cluster])
            output.addCallbacks(self.created, self.errCreated)

    def created(self, output):
        self.logger.debug("Volume creation output: %s" % (output))
        created = False
        for l in output.split("\n"):
            if l.startswith('VOLUME'):
                self.id = l.split()[1]
                if self.id == "Null":
                    # volume creation failed
                    continue
                self.logger.info("Created in %s" %self.cluster)
                created = True
        if not created:
            self.errCreated(output)
     
    def errCreated(self, output):
        self.logger.error("Volume creation failed: %s" % (output))            
            
    def delete(self):
        self.logger.info("Deleting volume")
        output = self.getProcessOutput(euca_delete_volume, args = [self.id])
        output.addCallback(self.deleted)
    
    def deleted(self, output):
        self.logger.info("Deleted")
        self.state = "deleted"
        self.logger.debug("delete output: %s" % (output))

    def attach(self, instance, device='/dev/sdb'):
        self.logger.info("Attaching volume to instance %s as %s" %( instance.id,
                                                                    device))
        self.instance = instance
        self.device   = device
        output = self.getProcessOutput(euca_attach_volume,
                                       args= ['-i', instance.id,
                                              '-d', device, self.id])
        output.addCallbacks(self.attached, self.errAttached)        

    def errAttached(self, output):
        self.logger.warning("Failed to attach volume to %s : %s" %
                            (self.instance.id, output))
        
    def attached(self, output):
        self.logger.debug("Volume attach output: %s" % (output))
        attached = False
        for l in output.split("\n"):
            if l.startswith('VOLUME'):
                self.id = l.split()[1]
                self.logger.info("Attached (%s/%s)" % (self.instance.id,
                                                       self.device))
                attached = True
        if not attached:
            self.errAttached(output) 
    
    def detach(self):
        self.logger.info("Detaching volume")
        self.instance = None
        self.device   = None        
        output = self.getProcessOutput(euca_detach_volume, args = [self.id])
        output.addCallback(self.detached)
    
    def detached(self, output):
        self.logger.info("Detached")
        self.state = "detached"
        self.logger.debug("detach output: %s" % (output))      

class Snapshot(object):    
    def __init__(self, volume, user):
        self.volume        = volume
        self.user          = user
        self.id            = None
        self._state        = None

    def __repr__(self):
        return "<Snapshot: %s - %s - %s>" % (self.id, self.user, self.state)
        
    @property
    def logger(self):
        if self.id:
            return logging.getLogger("SNAPSHOT %s" % (self.id))
        else:
            return logging.getLogger()        
        
    @property
    def state(self):
        return self._state
    @state.setter
    def state(self, value):
        self.logger.debug("State: %s" % (value))
        # The state has changed
        if self._state != value:
            self.logger.debug("New state: %s => %s" % (self._state, value))
            self._state = value        
  
    def getProcessOutput(self, executable, args=(), timeout=60):
        self.logger.debug("Executing: %s - %s" % (executable, args))
        return self.user.getProcessOutput(executable, args, timeout)            
            
    def create(self):
        self.logger.info("Creating snapshot")
        output = self.getProcessOutput(euca_create_snapshot,
                                       args = [self.volume.id])
        output.addCallbacks(self.created, self.errCreated)

    def created(self, output):
        self.logger.debug("Snapshot creation output: %s" % (output))
        created = False
        for l in output.split("\n"):
            if l.startswith('SNAPSHOT'):
                self.id = l.split()[1]
                if self.id == "Null":
                    # snapshot creation failed
                    continue
                self.logger.info("Created")
                created = True
        if not created:
            self.errCreated(output)
     
    def errCreated(self, output):
        self.logger.error("Snapshot creation failed: %s" % (output))            
            
    def delete(self):
        self.logger.info("Deleting snapshot")
        output = self.getProcessOutput(euca_delete_snapshot, args = [self.id])
        output.addCallback(self.deleted)
    
    def deleted(self, output):
        self.logger.info("Deleted")
        self.state = "deleted"
        self.logger.debug("delete output: %s" % (output))
  
def checkVolumeSnapState(volumes, snapshots, admin_user):
    if not admin_user.ready:
        reactor.callLater(16, checkVolumeSnapState, volumes, snapshots,
                          admin_user)
        return
    logging.debug("Checking volumes/snapshots state")
    output = admin_user.getProcessOutput(euca_describe_volsnap)
    output.addCallback(VolumeSnapState, volumes, snapshots, admin_user)
    
def VolumeSnapState(output, volumes, snapshots, admin_user):
    logging.debug("describe volumes and snapshots: %s", output)
    for l in output.split("\n"):
        if l.startswith('VOLUME'):
            try:
                v_id = l.split()[1]
                v = filter(lambda v: v.id == v_id, volumes)[0]
            except IndexError:
                #logging.debug("Unknown volume %s - skipping" % (v_id))
                continue
            state =  l.split("\t")[5]
            v.state = state
        if l.startswith('SNAPSHOT'):
            try:
                s_id = l.split()[1]
                s = filter(lambda s: s.id == s_id, snapshots)[0]
            except IndexError:
                #logging.debug("Unknown snapshot %s - skipping" % (s_id))
                continue
            state =  l.split("\t")[3]
            s.state = state
    reactor.callLater(random.randint(10, 20) + random.random(),
                          checkVolumeSnapState, volumes, snapshots, admin_user)      

def FindBiggestInstance(instances):   
    logging.debug("Look for a High-CPU instance to attach a volume")    
    global volumes
    global admin_user 
    if len(instances) == len(filter(lambda i: i.test_state in \
                                    ( "success", "failed", "lost" ), 
                                    instances)):  
        big = filter(lambda j: j.test_state in 'success' and
        uec_instances.Instance.ZONE_CPU_DICT[j.vmtype].cpu == max( [
        uec_instances.Instance.ZONE_CPU_DICT[i.vmtype].cpu for i in instances
        ] ) and
        uec_instances.Instance.ZONE_CPU_DICT[j.vmtype].ram == max( [
        uec_instances.Instance.ZONE_CPU_DICT[i.vmtype].ram for i in instances
        ] ) and
        uec_instances.Instance.ZONE_CPU_DICT[j.vmtype].disk == max( [
        uec_instances.Instance.ZONE_CPU_DICT[i.vmtype].disk for i in instances
        ] ), instances)[0]
        logging.info("Found a High-CPU instance : %s" %big)
        v = Volume(cluster = big.cluster, user = admin_user)
        v.create(size = "1")
        volumes.append(v)
        reactor.callLater(30, AttachVolumetoBiggestInstance, big, v)
    else:
        reactor.callLater(random.randint(10, 15) + random.random(),
                  FindBiggestInstance, instances)    
   
def AttachVolumetoBiggestInstance(big_i, vol):
    if vol.state not in 'available':
        reactor.callLater(random.randint(5, 10) + random.random(),
                          AttachVolumetoBiggestInstance, big_i, vol)
        return
    big_i.test_state = 'being-tested'
    logging.info("Attaching %s to %s" %( vol, big_i.id ))    
    vol.attach(big_i)
    reactor.callLater(random.randint(10, 15) + random.random(),
                      MountVolumetoBiggestInstance, vol)

def MountVolumetoBiggestInstance(vol):
    if vol.state not in 'in-use':
        reactor.callLater(random.randint(5, 10) + random.random(),
                          MountVolumetoBiggestInstance, vol)
        return
    logging.info("Mounting %s as /ebs in %s" %( vol, vol.instance.id )) 
    cmd  = """sudo perl -e '@a=`lshw -C disk -short 2>&1`;"""
    cmd += """@a=pop(@a)=~/(\/dev\/.*?)\s+/; """
    cmd += """system("parted -s @a mktable msdos"""
    cmd += """&& parted -s -- @a mkpart primary ext3 0 -1 """
    cmd += """&& mke2fs @{a}1 && mkdir -p /ebs && mount @{a}1 /ebs")'""" 
    args = ['-o', 'UserKnownHostsFile=/dev/null',
            '-o', 'StrictHostKeyChecking=no',
            '-o', 'ConnectTimeout=5',
            '-o', 'Batchmode=yes',
            '-i', vol.instance.private_key,
            "ubuntu@%s" % (vol.instance.pub_ip)]
    logging.debug("Ssh args: %s" % (args+[cmd]))
    output = uec_utils.getProcessOutput('ssh', args+[cmd], errortoo=True)    
    output.addCallback(MountedBiggestInstance, vol, args)    
    
def MountedBiggestInstance(output, vol, args):
    logging.debug("Volume mount output: %s" % (output))  
    logging.info("Installing debootstrap in %s" %vol.instance.id) 
    cmd  = "sudo apt-get install --force-yes --yes debootstrap"
    logging.debug("Ssh args: %s" % (args+[cmd]))
    output = uec_utils.getProcessOutput('ssh', args+[cmd], errortoo=True)    
    output.addCallback(InstalldebootstrapBiggestInstance, vol, args)   
    
def InstalldebootstrapBiggestInstance(output, vol, args):
    logging.debug("debootstrap installation output: %s" % (output))  
    logging.info("Debootstrap lucid in /ebs for %s" %vol.instance.id) 
    cmd  = "sudo debootstrap lucid /ebs"
    logging.debug("Ssh args: %s" % (args+[cmd]))
    output = uec_utils.getProcessOutput('ssh', args+[cmd], errortoo=True)    
    output.addCallback(ChrootEBSBiggestInstance, vol, args)     

def ChrootEBSBiggestInstance(output, vol, args):    
    if not re.findall(r"Base system installed successfully", output, re.S):
        logging.error("debootstrap installation failed")
        reactor.stop()
    logging.info("Prepare chroot environnement in %s" %vol.instance.id) 
    cmd  = "sudo mount proc /ebs/proc -t proc && "
    cmd += "sudo mount sysfs /ebs/sys -t sysfs && "
    cmd += "sudo mount -o bind /dev /ebs/dev && "
    cmd += "sudo chroot /ebs apt-get install --force-yes --yes language-pack-en"
    logging.debug("Ssh args: %s" % (args+[cmd]))
    output = uec_utils.getProcessOutput('ssh', args+[cmd], errortoo=True)    
    output.addCallback(InstallServiceBiggestInstance, vol, args)   
  
def InstallServiceBiggestInstance(output, vol, args):  
    logging.debug("chroot env. installation output: %s" % (output)) 
    logging.info("Install service in chrooted env. in %s" %vol.instance.id) 
    cmd = "sudo chroot /ebs apt-get install --force-yes --yes apache2"
    logging.debug("Ssh args: %s" % (args+[cmd]))
    output = uec_utils.getProcessOutput('ssh', args+[cmd], errortoo=True)    
    output.addCallback(ServiceRunningBiggestInstance, vol, args)      
    
def ServiceRunningBiggestInstance(output, vol, args):
    logging.debug("service installation output: %s" % (output))  
    try:
        page = urllib2.urlopen('http://%s' %vol.instance.pub_ip).read()
    except IOError, e:
        if hasattr(e, 'reason'):
            logging.error(e.reason)
        elif hasattr(e, 'code'):
            logging.error(e.code)
        reactor.stop()
    else:
        if not (re.search(r"It works!", page)):
            logging.error('http://%s : "It works!" not found'
                          %vol.instance.pub_ip)
            reactor.stop()
        else:
            logging.info("Service running in %s" %vol.instance.id)   
            logging.info("Stop service chroot environnement in %s" %vol.instance.id)           
            cmd  = "sudo umount /ebs/sys && "
            cmd += "sudo umount /ebs/proc && "
            cmd += "sudo umount /ebs/dev && "
            cmd += "sudo chroot /ebs /etc/init.d/apache2 stop && "
            cmd += "sudo umount -lf /ebs" 
            logging.debug("Ssh args: %s" % (args+[cmd]))
            output = uec_utils.getProcessOutput('ssh', args+[cmd],
                                                errortoo=True)
            output.addCallback(CreateSnapshotfromInuseVolume, vol) 

def CreateSnapshotfromInuseVolume(output, vol):            
    global snapshots    
    logging.debug("service stop output: %s" % (output))   
    s = Snapshot(volume = vol, user = admin_user)
    s.create()
    snapshots.append(s)
    reactor.callLater(30, CreateNewVolumefromSnapshot, s, vol)
    
def CreateNewVolumefromSnapshot(snap, vol):
    if snap.state not in 'completed':
        reactor.callLater(random.randint(5, 10) + random.random(),
                          CreateNewVolumefromSnapshot, snap, vol)
        return
    vol.instance.test_state = "success"
    vol.detach()
    new_vol = Volume(cluster = vol.cluster, user = admin_user)
    new_vol.create(snapshot = snap.id)
    volumes.append(new_vol)
    reactor.callLater(5, WaitforNewVolume, vol, new_vol)

def WaitforNewVolume(vol, new_vol):
    if vol.state not in 'available' or new_vol.state not in 'available':
        reactor.callLater(random.randint(5, 10) + random.random(),
                          WaitforNewVolume, vol, new_vol)
        return
    logging.info("Test run completed")
    reactor.stop()

def main():
    LEVELS = {'debug': logging.DEBUG,
               'info': logging.INFO,
               'warning': logging.WARNING,
               'error': logging.ERROR,
               'critical': logging.CRITICAL}
    
    global volumes
    global snapshots
    global admin_user
    opts = Options()
    uec_instances.opts = opts
   
    try:
        opts.parseOptions() # When given no argument, parses sys.argv[1:]
    except usage.UsageError, errortext:
        print '%s: %s' % (sys.argv[0], errortext)
        print '%s: Try --help for usage details.' % (sys.argv[0])
        return 1 

    # Verify that script is run as root
    if os.getuid():
        sys.stderr.write(
            "This script needs superuser permissions to run correctly\n")
        return 1        
        
    level = LEVELS.get(opts['log'], logging.NOTSET)
   
    if opts['write_log']:
        suffix = "service"
        LOG_FILENAME = "/var/log/uec_ebs.%s.log" %suffix
        handler = logging.handlers.RotatingFileHandler(LOG_FILENAME,
                                                       backupCount=2)
        logging.getLogger().addHandler(handler)
        handler.setFormatter(
            logging.Formatter("[%(asctime)s] %(levelname)s %(message)s"))
        logging.getLogger().setLevel(level)
        handler.doRollover() 
    else:
        logging.basicConfig(level=level)
    logging.info("log level set to " + opts['log']) 
    instances  = [] 
    volumes    = []
    snapshots  = []
    admin_user = uec_instances.User() # Create admin user
    
    #Overload some imported stuff
    uec_instances.TerminaTestedInstances = FindBiggestInstance
    uec_instances.admin_user             = admin_user
    
    reactor.callWhenRunning(admin_user.setup) # setup admin user  
    reactor.callWhenRunning(uec_instances.checkRessources, instances,
                            admin_user, first_call = True)
    reactor.callWhenRunning(uec_instances.checkInstancesState, instances,
                            admin_user)
    reactor.callWhenRunning(checkVolumeSnapState, volumes, snapshots,
                            admin_user)
    uec_instances.printStats(instances)    
    reactor.run()
    uec_instances.cleanUp(instances)
    [ v.delete() for v in volumes ]
    [ s.delete() for s in snapshots ]
    uec_instances.printStats(instances, once=True)
    if len(filter(lambda i: i.test_state == 'success', instances)) != \
       len(instances):
        return 1
    else:
        return 0
    
if __name__ == "__main__":
    sys.exit(main())