remove raise
[plstackapi.git] / planetstack / observer / steps / sync_image_deployments.py
1 import os
2 import base64
3 from collections import defaultdict
4 from django.db.models import F, Q
5 from planetstack.config import Config
6 from observer.openstacksyncstep import OpenStackSyncStep
7 from core.models.deployment import Deployment
8 from core.models.image import Image, ImageDeployments
9
10 class SyncImageDeployments(OpenStackSyncStep):
11     provides=[ImageDeployments]
12     requested_interval=0
13
14     def fetch_pending(self):
15         # ensure images are available across all deployments
16         image_deployments = ImageDeployments.objects.all()
17         image_deploy_lookup = defaultdict(list)
18         for image_deployment in image_deployments:
19             image_deploy_lookup[image_deployment.image].append(image_deployment.deployment)
20         
21         all_deployments = Deployment.objects.all() 
22         for image in Image.objects.all():
23             expected_deployments = all_deployments
24             for expected_deployment in expected_deployments:
25                 if image not in image_deploy_lookup or \
26                   expected_deployment not in image_deploy_lookup[image]:
27                     id = ImageDeployments(image=image, deployment=expected_deployment)
28                     id.save()
29             
30         # now we return all images that need to be enacted
31         return ImageDeployments.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) 
32                       
33     def sync_record(self, image_deployment):
34         driver = self.driver.admin_driver(deployment=image_deployment.deployment.name)
35         images = driver.shell.glance.get_images()
36         glance_image = None
37         for image in images:
38             if image['name'] == image_deployment.image.name:
39                 glance_image = image
40                 break
41         if glance_image:
42             image_deployment.glance_image_id = glance_image['id']
43         elif image_deployment.image.path:
44             glance_image = driver.shell.glanceclient.images.create(name=image_deployment.image.name,
45                                                                    is_public=True,
46                                                                    disk_format='raw',
47                                                                    container_format='bare')
48             glance_image.update(data=open(image_deployment.image.path, 'rb'))
49             image_deployment.glance_image_id = glance_image.id
50         image_deployment.save()