removing plural from model names. some cleanup
[plstackapi.git] / planetstack / ec2_observer / steps / sync_site_deployments.py
1 import os
2 import base64
3 from django.db.models import F, Q
4 from planetstack.config import Config
5 from ec2_observer.syncstep import SyncStep
6 from core.models.site import *
7 from ec2_observer.awslib import *
8 import pdb
9
10 class SyncSiteDeployment(SyncStep):
11     requested_interval=86400
12     provides=[SiteDeployment]
13
14     def fetch_pending(self, deletion):
15         if (deletion):
16             return []
17
18         zone_ret = aws_run('ec2 describe-availability-zones')
19         zones = zone_ret['AvailabilityZones']
20         available_sites = [zone['ZoneName'] for zone in zones]
21
22         current_sites = []
23         for s in available_sites:
24             site = Site.objects.filter(Q(name=s))
25             if (site):
26                 current_sites.append(site[0])
27
28         # OK not to catch exception
29         # The syncstep should catch it
30         # At any rate, we should not run if there are no deployments
31         deployment = Deployment.objects.filter(Q(name="Amazon EC2"))[0]
32         current_site_deployments = SiteDeployment.objects.filter(Q(deployment=deployment))
33         site_dict = {}
34
35         for sd in current_site_deployments:
36             site_dict[sd.site]=sd
37
38         updated_site_deployments = []
39         for site in current_sites:
40             try:
41                 site_record = site_dict[site]
42             except KeyError:
43                 sd = SiteDeployment(site=site,deployment=deployment,tenant_id=base64.urlsafe_b64encode(os.urandom(12)))
44                 updated_site_deployments.append(sd)
45
46         return updated_site_deployments
47
48
49     def sync_record(self, site_deployment):
50         site_deployment.save()