blob: 7c24f68c012d75ab0349ce3a047d3affdd21759c [file] [log] [blame]
Sapan Bhatia26d40bc2014-05-12 15:28:02 -04001import os
2import base64
3from django.db.models import F, Q
4from planetstack.config import Config
Sapan Bhatia511ea5f2014-07-21 22:53:58 -04005from ec2_observer.syncstep import SyncStep
Sapan Bhatia26d40bc2014-05-12 15:28:02 -04006from core.models.site import *
Sapan Bhatia511ea5f2014-07-21 22:53:58 -04007from ec2_observer.awslib import *
8import pdb
Sapan Bhatia26d40bc2014-05-12 15:28:02 -04009
Sapan Bhatiab55f4a32014-11-19 15:07:36 -050010class SyncSiteDeployments(SyncStep):
Sapan Bhatia7b130102014-07-23 16:39:41 -040011 requested_interval=86400
Sapan Bhatiab55f4a32014-11-19 15:07:36 -050012 provides=[SiteDeployments]
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040013
Sapan Bhatia7b130102014-07-23 16:39:41 -040014 def fetch_pending(self, deletion):
Sapan Bhatiae7e4ca12014-07-22 01:27:02 -040015 if (deletion):
16 return []
17
Sapan Bhatia7b130102014-07-23 16:39:41 -040018 zone_ret = aws_run('ec2 describe-availability-zones')
19 zones = zone_ret['AvailabilityZones']
20 available_sites = [zone['ZoneName'] for zone in zones]
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040021
Sapan Bhatia7b130102014-07-23 16:39:41 -040022 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])
Sapan Bhatia511ea5f2014-07-21 22:53:58 -040027
Sapan Bhatia7b130102014-07-23 16:39:41 -040028 # 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]
Sapan Bhatiab55f4a32014-11-19 15:07:36 -050032 current_site_deployments = SiteDeployments.objects.filter(Q(deployment=deployment))
Sapan Bhatia7b130102014-07-23 16:39:41 -040033 site_dict = {}
Sapan Bhatia511ea5f2014-07-21 22:53:58 -040034
Sapan Bhatia7b130102014-07-23 16:39:41 -040035 for sd in current_site_deployments:
36 site_dict[sd.site]=sd
Sapan Bhatia511ea5f2014-07-21 22:53:58 -040037
Sapan Bhatia7b130102014-07-23 16:39:41 -040038 updated_site_deployments = []
39 for site in current_sites:
40 try:
41 site_record = site_dict[site]
42 except KeyError:
Sapan Bhatiab55f4a32014-11-19 15:07:36 -050043 sd = SiteDeployments(site=site,deployment=deployment,tenant_id=base64.urlsafe_b64encode(os.urandom(12)))
Sapan Bhatia7b130102014-07-23 16:39:41 -040044 updated_site_deployments.append(sd)
Sapan Bhatia511ea5f2014-07-21 22:53:58 -040045
Sapan Bhatia7b130102014-07-23 16:39:41 -040046 return updated_site_deployments
Sapan Bhatia511ea5f2014-07-21 22:53:58 -040047
48
Sapan Bhatia7b130102014-07-23 16:39:41 -040049 def sync_record(self, site_deployment):
50 site_deployment.save()