Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 1 | import os |
| 2 | import base64 |
| 3 | from django.db.models import F, Q |
| 4 | from planetstack.config import Config |
Sapan Bhatia | 511ea5f | 2014-07-21 22:53:58 -0400 | [diff] [blame] | 5 | from ec2_observer.syncstep import SyncStep |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 6 | from core.models.image import Image |
Sapan Bhatia | 511ea5f | 2014-07-21 22:53:58 -0400 | [diff] [blame] | 7 | from ec2_observer.awslib import * |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 8 | |
Sapan Bhatia | 511ea5f | 2014-07-21 22:53:58 -0400 | [diff] [blame] | 9 | |
| 10 | class SyncImages(SyncStep): |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 11 | provides=[Image] |
| 12 | requested_interval=3600 |
| 13 | |
Sapan Bhatia | 511ea5f | 2014-07-21 22:53:58 -0400 | [diff] [blame] | 14 | def fetch_pending(self,deletion): |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 15 | images = Image.objects.all() |
| 16 | image_names = [image.name for image in images] |
| 17 | |
| 18 | new_images = [] |
| 19 | |
Sapan Bhatia | 511ea5f | 2014-07-21 22:53:58 -0400 | [diff] [blame] | 20 | try: |
| 21 | aws_images = json.loads(open('/opt/planetstack/aws-images').read()) |
| 22 | except: |
| 23 | aws_images = aws_run('ec2 describe-images --owner 099720109477') |
| 24 | open('/opt/planetstack/aws-images','w').write(json.dumps(aws_images)) |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 25 | |
Sapan Bhatia | 511ea5f | 2014-07-21 22:53:58 -0400 | [diff] [blame] | 26 | |
| 27 | |
| 28 | aws_images=aws_images['Images'] |
| 29 | aws_images=filter(lambda x:x['ImageType']=='machine',aws_images)[:50] |
| 30 | |
| 31 | names = set([]) |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 32 | for aws_image in aws_images: |
Sapan Bhatia | 511ea5f | 2014-07-21 22:53:58 -0400 | [diff] [blame] | 33 | desc_ok = True |
| 34 | |
| 35 | try: |
| 36 | desc = aws_image['Description'] |
| 37 | except: |
| 38 | try: |
| 39 | desc = aws_image['ImageLocation'] |
| 40 | except: |
| 41 | desc_ok = False |
| 42 | |
| 43 | if (desc_ok): |
| 44 | try: |
| 45 | desc_ok = desc and desc not in names and desc not in image_names and '14.04' in desc |
| 46 | except KeyError: |
| 47 | desc_ok = False |
| 48 | |
| 49 | if desc_ok and aws_image['ImageType']=='machine': |
| 50 | image = Image(disk_format=aws_image['ImageLocation'], |
| 51 | name=desc, |
| 52 | container_format=aws_image['Hypervisor'], |
| 53 | path=aws_image['ImageId']) |
| 54 | new_images.append(image) |
| 55 | names.add(image.name) |
| 56 | |
| 57 | #print new_images |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 58 | return new_images |
| 59 | |
| 60 | def sync_record(self, image): |
| 61 | image.save() |