blob: e54b7e1eaa024a38d05ad9c9a5cc1f7b38e14d8a [file] [log] [blame]
Scott Baker761e1062016-06-20 17:18:17 -07001import hashlib
2import os
3import socket
4import sys
5import base64
6import time
Srikanth Vavilapallicd9d9bd2016-12-03 22:53:42 +00007from urlparse import urlparse
Scott Baker761e1062016-06-20 17:18:17 -07008from django.db.models import F, Q
9from xos.config import Config
10from synchronizers.base.syncstep import SyncStep
Sapan Bhatia506d1792017-01-24 19:32:59 +010011from synchronizers.base.ansible_helper import run_template_ssh
Scott Baker761e1062016-06-20 17:18:17 -070012from synchronizers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
Srikanth Vavilapallicd9d9bd2016-12-03 22:53:42 +000013from core.models import Service, Slice, Tag, ModelLink, CoarseTenant, Tenant, ServiceMonitoringAgentInfo
Scott Baker761e1062016-06-20 17:18:17 -070014from services.vsg.models import VSGService, VSGTenant
Scott Baker761e1062016-06-20 17:18:17 -070015from xos.logger import Logger, logging
16
Scott Bakerb5deceb2016-08-09 15:50:52 -070017# Deal with configurations where the hpc service is not onboarded
18try:
19 from services.hpc.models import HpcService, CDNPrefix
20 hpc_service_onboarded=True
21except:
22 hpc_service_onboarded=False
23
Scott Baker761e1062016-06-20 17:18:17 -070024# hpclibrary will be in steps/..
25parentdir = os.path.join(os.path.dirname(__file__),"..")
26sys.path.insert(0,parentdir)
27
Scott Baker761e1062016-06-20 17:18:17 -070028logger = Logger(level=logging.INFO)
29
30ENABLE_QUICK_UPDATE=False
31
Scott Baker761e1062016-06-20 17:18:17 -070032class SyncVSGTenant(SyncInstanceUsingAnsible):
33 provides=[VSGTenant]
34 observes=VSGTenant
35 requested_interval=0
36 template_name = "sync_vcpetenant.yaml"
Srikanth Vavilapallicd9d9bd2016-12-03 22:53:42 +000037 watches = [ModelLink(CoarseTenant,via='coarsetenant'), ModelLink(ServiceMonitoringAgentInfo,via='monitoringagentinfo')]
Scott Baker761e1062016-06-20 17:18:17 -070038
39 def __init__(self, *args, **kwargs):
40 super(SyncVSGTenant, self).__init__(*args, **kwargs)
41
42 def fetch_pending(self, deleted):
43 if (not deleted):
44 objs = VSGTenant.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
45 else:
46 objs = VSGTenant.get_deleted_tenant_objects()
47
48 return objs
49
50 def get_vcpe_service(self, o):
51 if not o.provider_service:
52 return None
53
54 vcpes = VSGService.get_service_objects().filter(id=o.provider_service.id)
55 if not vcpes:
56 return None
57
58 return vcpes[0]
59
60 def get_extra_attributes(self, o):
61 # This is a place to include extra attributes that aren't part of the
62 # object itself. In the case of vCPE, we need to know:
63 # 1) the addresses of dnsdemux, to setup dnsmasq in the vCPE
64 # 2) CDN prefixes, so we know what URLs to send to dnsdemux
Scott Baker761e1062016-06-20 17:18:17 -070065 # 4) vlan_ids, for setting up networking in the vCPE VM
66
67 vcpe_service = self.get_vcpe_service(o)
68
69 dnsdemux_ip = None
70 cdn_prefixes = []
71
72 cdn_config_fn = "/opt/xos/synchronizers/vsg/cdn_config"
73 if os.path.exists(cdn_config_fn):
74 # manual CDN configuration
75 # the first line is the address of dnsredir
76 # the remaining lines are domain names, one per line
77 lines = file(cdn_config_fn).readlines()
78 if len(lines)>=2:
79 dnsdemux_ip = lines[0].strip()
80 cdn_prefixes = [x.strip() for x in lines[1:] if x.strip()]
Scott Bakerb5deceb2016-08-09 15:50:52 -070081 elif hpc_service_onboarded:
Scott Baker761e1062016-06-20 17:18:17 -070082 # automatic CDN configuiration
83 # it learns everything from CDN objects in XOS
84 # not tested on pod.
85 if vcpe_service.backend_network_label:
86 # Connect to dnsdemux using the network specified by
87 # vcpe_service.backend_network_label
88 for service in HpcService.objects.all():
89 for slice in service.slices.all():
90 if "dnsdemux" in slice.name:
91 for instance in slice.instances.all():
92 for ns in instance.ports.all():
93 if ns.ip and ns.network.labels and (vcpe_service.backend_network_label in ns.network.labels):
94 dnsdemux_ip = ns.ip
95 if not dnsdemux_ip:
96 logger.info("failed to find a dnsdemux on network %s" % vcpe_service.backend_network_label,extra=o.tologdict())
97 else:
98 # Connect to dnsdemux using the instance's public address
99 for service in HpcService.objects.all():
100 for slice in service.slices.all():
101 if "dnsdemux" in slice.name:
102 for instance in slice.instances.all():
103 if dnsdemux_ip=="none":
104 try:
105 dnsdemux_ip = socket.gethostbyname(instance.node.name)
106 except:
107 pass
108 if not dnsdemux_ip:
109 logger.info("failed to find a dnsdemux with a public address",extra=o.tologdict())
110
111 for prefix in CDNPrefix.objects.all():
112 cdn_prefixes.append(prefix.prefix)
113
114 dnsdemux_ip = dnsdemux_ip or "none"
115
Scott Baker761e1062016-06-20 17:18:17 -0700116 s_tags = []
117 c_tags = []
118 if o.volt:
119 s_tags.append(o.volt.s_tag)
120 c_tags.append(o.volt.c_tag)
121
122 try:
123 full_setup = Config().observer_full_setup
124 except:
125 full_setup = True
126
127 safe_macs=[]
128 if vcpe_service.url_filter_kind == "safebrowsing":
129 if o.volt and o.volt.subscriber:
130 for user in o.volt.subscriber.devices:
131 level = user.get("level",None)
132 mac = user.get("mac",None)
133 if level in ["G", "PG"]:
134 if mac:
135 safe_macs.append(mac)
136
Scott Baker8e66d662016-10-13 13:22:49 -0700137
138 docker_opts = []
139 if vcpe_service.docker_insecure_registry:
140 reg_name = vcpe_service.docker_image_name.split("/",1)[0]
141 docker_opts.append("--insecure-registry " + reg_name)
142
Scott Baker761e1062016-06-20 17:18:17 -0700143 fields = {"s_tags": s_tags,
144 "c_tags": c_tags,
Scott Baker8e66d662016-10-13 13:22:49 -0700145 "docker_remote_image_name": vcpe_service.docker_image_name,
146 "docker_local_image_name": vcpe_service.docker_image_name, # vcpe_service.docker_image_name.split("/",1)[1].split(":",1)[0],
147 "docker_opts": " ".join(docker_opts),
Scott Baker761e1062016-06-20 17:18:17 -0700148 "dnsdemux_ip": dnsdemux_ip,
149 "cdn_prefixes": cdn_prefixes,
Scott Baker761e1062016-06-20 17:18:17 -0700150 "full_setup": full_setup,
151 "isolation": o.instance.isolation,
152 "safe_browsing_macs": safe_macs,
153 "container_name": "vcpe-%s-%s" % (s_tags[0], c_tags[0]),
154 "dns_servers": [x.strip() for x in vcpe_service.dns_servers.split(",")],
155 "url_filter_kind": vcpe_service.url_filter_kind }
156
157 # add in the sync_attributes that come from the SubscriberRoot object
158
159 if o.volt and o.volt.subscriber and hasattr(o.volt.subscriber, "sync_attributes"):
160 for attribute_name in o.volt.subscriber.sync_attributes:
161 fields[attribute_name] = getattr(o.volt.subscriber, attribute_name)
162
163 return fields
164
165 def sync_fields(self, o, fields):
166 # the super causes the playbook to be run
Scott Baker761e1062016-06-20 17:18:17 -0700167 super(SyncVSGTenant, self).sync_fields(o, fields)
168
Scott Baker761e1062016-06-20 17:18:17 -0700169 def run_playbook(self, o, fields):
170 ansible_hash = hashlib.md5(repr(sorted(fields.items()))).hexdigest()
171 quick_update = (o.last_ansible_hash == ansible_hash)
172
173 if ENABLE_QUICK_UPDATE and quick_update:
174 logger.info("quick_update triggered; skipping ansible recipe",extra=o.tologdict())
175 else:
176 if o.instance.isolation in ["container", "container_vm"]:
Scott Bakerecee9b12017-03-08 09:56:20 -0800177 raise Exception("probably not implemented")
Scott Baker761e1062016-06-20 17:18:17 -0700178 super(SyncVSGTenant, self).run_playbook(o, fields, "sync_vcpetenant_new.yaml")
179 else:
Scott Bakerecee9b12017-03-08 09:56:20 -0800180 super(SyncVSGTenant, self).run_playbook(o, fields, template_name="sync_vcpetenant_vtn.yaml")
Scott Baker761e1062016-06-20 17:18:17 -0700181
182 o.last_ansible_hash = ansible_hash
183
184 def delete_record(self, m):
185 pass
Srikanth Vavilapallicd9d9bd2016-12-03 22:53:42 +0000186
187 def handle_service_monitoringagentinfo_watch_notification(self, monitoring_agent_info):
188 if not monitoring_agent_info.service:
189 logger.info("handle watch notifications for service monitoring agent info...ignoring because service attribute in monitoring agent info:%s is null" % (monitoring_agent_info))
190 return
191
192 if not monitoring_agent_info.target_uri:
193 logger.info("handle watch notifications for service monitoring agent info...ignoring because target_uri attribute in monitoring agent info:%s is null" % (monitoring_agent_info))
194 return
195
196 objs = VSGTenant.get_tenant_objects().all()
197 for obj in objs:
198 if obj.provider_service.id != monitoring_agent_info.service.id:
199 logger.info("handle watch notifications for service monitoring agent info...ignoring because service attribute in monitoring agent info:%s is not matching" % (monitoring_agent_info))
200 return
201
202 instance = self.get_instance(obj)
203 if not instance:
204 logger.warn("handle watch notifications for service monitoring agent info...: No valid instance found for object %s" % (str(obj)))
205 return
206
207 logger.info("handling watch notification for monitoring agent info:%s for VSGTenant object:%s" % (monitoring_agent_info, obj))
208
209 #Run ansible playbook to update the routing table entries in the instance
210 fields = self.get_ansible_fields(instance)
211 fields["ansible_tag"] = obj.__class__.__name__ + "_" + str(obj.id) + "_service_monitoring"
212
213 #Parse the monitoring agent target_uri
214 url = urlparse(monitoring_agent_info.target_uri)
215
216 #Assuming target_uri is rabbitmq URI
217 fields["rabbit_user"] = url.username
218 fields["rabbit_password"] = url.password
219 fields["rabbit_host"] = url.hostname
220
221 template_name = "sync_monitoring_agent.yaml"
222 super(SyncVSGTenant, self).run_playbook(obj, fields, template_name)
223 pass