blob: 825add44595e70853101ffb1d8631372e705ba85 [file] [log] [blame]
Scott Baker761e1062016-06-20 17:18:17 -07001import hashlib
2import os
3import socket
4import sys
5import base64
6import time
7from django.db.models import F, Q
8from xos.config import Config
9from synchronizers.base.syncstep import SyncStep
10from synchronizers.base.ansible import run_template_ssh
11from synchronizers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
Srikanth Vavilapallia23196c2016-11-17 03:17:15 +000012from core.models import Service, Slice, Tag, ModelLink, CoarseTenant, Tenant
Scott Baker761e1062016-06-20 17:18:17 -070013from services.vsg.models import VSGService, VSGTenant
Scott Baker761e1062016-06-20 17:18:17 -070014from xos.logger import Logger, logging
15
Scott Bakerb5deceb2016-08-09 15:50:52 -070016# Deal with configurations where the hpc service is not onboarded
17try:
18 from services.hpc.models import HpcService, CDNPrefix
19 hpc_service_onboarded=True
20except:
21 hpc_service_onboarded=False
22
Scott Baker761e1062016-06-20 17:18:17 -070023# hpclibrary will be in steps/..
24parentdir = os.path.join(os.path.dirname(__file__),"..")
25sys.path.insert(0,parentdir)
26
27from broadbandshield import BBS
28
29logger = Logger(level=logging.INFO)
30
31ENABLE_QUICK_UPDATE=False
32
33CORD_USE_VTN = getattr(Config(), "networking_use_vtn", False)
34
35class SyncVSGTenant(SyncInstanceUsingAnsible):
36 provides=[VSGTenant]
37 observes=VSGTenant
38 requested_interval=0
39 template_name = "sync_vcpetenant.yaml"
Srikanth Vavilapallia23196c2016-11-17 03:17:15 +000040 watches = [ModelLink(CoarseTenant,via='coarsetenant')]
Scott Baker761e1062016-06-20 17:18:17 -070041
42 def __init__(self, *args, **kwargs):
43 super(SyncVSGTenant, self).__init__(*args, **kwargs)
44
45 def fetch_pending(self, deleted):
46 if (not deleted):
47 objs = VSGTenant.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
48 else:
49 objs = VSGTenant.get_deleted_tenant_objects()
50
51 return objs
52
53 def get_vcpe_service(self, o):
54 if not o.provider_service:
55 return None
56
57 vcpes = VSGService.get_service_objects().filter(id=o.provider_service.id)
58 if not vcpes:
59 return None
60
61 return vcpes[0]
62
63 def get_extra_attributes(self, o):
64 # This is a place to include extra attributes that aren't part of the
65 # object itself. In the case of vCPE, we need to know:
66 # 1) the addresses of dnsdemux, to setup dnsmasq in the vCPE
67 # 2) CDN prefixes, so we know what URLs to send to dnsdemux
68 # 3) BroadBandShield server addresses, for parental filtering
69 # 4) vlan_ids, for setting up networking in the vCPE VM
70
71 vcpe_service = self.get_vcpe_service(o)
72
73 dnsdemux_ip = None
74 cdn_prefixes = []
75
76 cdn_config_fn = "/opt/xos/synchronizers/vsg/cdn_config"
77 if os.path.exists(cdn_config_fn):
78 # manual CDN configuration
79 # the first line is the address of dnsredir
80 # the remaining lines are domain names, one per line
81 lines = file(cdn_config_fn).readlines()
82 if len(lines)>=2:
83 dnsdemux_ip = lines[0].strip()
84 cdn_prefixes = [x.strip() for x in lines[1:] if x.strip()]
Scott Bakerb5deceb2016-08-09 15:50:52 -070085 elif hpc_service_onboarded:
Scott Baker761e1062016-06-20 17:18:17 -070086 # automatic CDN configuiration
87 # it learns everything from CDN objects in XOS
88 # not tested on pod.
89 if vcpe_service.backend_network_label:
90 # Connect to dnsdemux using the network specified by
91 # vcpe_service.backend_network_label
92 for service in HpcService.objects.all():
93 for slice in service.slices.all():
94 if "dnsdemux" in slice.name:
95 for instance in slice.instances.all():
96 for ns in instance.ports.all():
97 if ns.ip and ns.network.labels and (vcpe_service.backend_network_label in ns.network.labels):
98 dnsdemux_ip = ns.ip
99 if not dnsdemux_ip:
100 logger.info("failed to find a dnsdemux on network %s" % vcpe_service.backend_network_label,extra=o.tologdict())
101 else:
102 # Connect to dnsdemux using the instance's public address
103 for service in HpcService.objects.all():
104 for slice in service.slices.all():
105 if "dnsdemux" in slice.name:
106 for instance in slice.instances.all():
107 if dnsdemux_ip=="none":
108 try:
109 dnsdemux_ip = socket.gethostbyname(instance.node.name)
110 except:
111 pass
112 if not dnsdemux_ip:
113 logger.info("failed to find a dnsdemux with a public address",extra=o.tologdict())
114
115 for prefix in CDNPrefix.objects.all():
116 cdn_prefixes.append(prefix.prefix)
117
118 dnsdemux_ip = dnsdemux_ip or "none"
119
120 # Broadbandshield can either be set up internally, using vcpe_service.bbs_slice,
121 # or it can be setup externally using vcpe_service.bbs_server.
122
123 bbs_addrs = []
124 if vcpe_service.bbs_slice:
125 if vcpe_service.backend_network_label:
126 for bbs_instance in vcpe_service.bbs_slice.instances.all():
127 for ns in bbs_instance.ports.all():
128 if ns.ip and ns.network.labels and (vcpe_service.backend_network_label in ns.network.labels):
129 bbs_addrs.append(ns.ip)
130 else:
131 logger.info("unsupported configuration -- bbs_slice is set, but backend_network_label is not",extra=o.tologdict())
132 if not bbs_addrs:
133 logger.info("failed to find any usable addresses on bbs_slice",extra=o.tologdict())
134 elif vcpe_service.bbs_server:
135 bbs_addrs.append(vcpe_service.bbs_server)
136 else:
137 logger.info("neither bbs_slice nor bbs_server is configured in the vCPE",extra=o.tologdict())
138
139 s_tags = []
140 c_tags = []
141 if o.volt:
142 s_tags.append(o.volt.s_tag)
143 c_tags.append(o.volt.c_tag)
144
145 try:
146 full_setup = Config().observer_full_setup
147 except:
148 full_setup = True
149
150 safe_macs=[]
151 if vcpe_service.url_filter_kind == "safebrowsing":
152 if o.volt and o.volt.subscriber:
153 for user in o.volt.subscriber.devices:
154 level = user.get("level",None)
155 mac = user.get("mac",None)
156 if level in ["G", "PG"]:
157 if mac:
158 safe_macs.append(mac)
159
Scott Baker8e66d662016-10-13 13:22:49 -0700160
161 docker_opts = []
162 if vcpe_service.docker_insecure_registry:
163 reg_name = vcpe_service.docker_image_name.split("/",1)[0]
164 docker_opts.append("--insecure-registry " + reg_name)
165
Scott Baker761e1062016-06-20 17:18:17 -0700166 fields = {"s_tags": s_tags,
167 "c_tags": c_tags,
Scott Baker8e66d662016-10-13 13:22:49 -0700168 "docker_remote_image_name": vcpe_service.docker_image_name,
169 "docker_local_image_name": vcpe_service.docker_image_name, # vcpe_service.docker_image_name.split("/",1)[1].split(":",1)[0],
170 "docker_opts": " ".join(docker_opts),
Scott Baker761e1062016-06-20 17:18:17 -0700171 "dnsdemux_ip": dnsdemux_ip,
172 "cdn_prefixes": cdn_prefixes,
173 "bbs_addrs": bbs_addrs,
174 "full_setup": full_setup,
175 "isolation": o.instance.isolation,
176 "safe_browsing_macs": safe_macs,
177 "container_name": "vcpe-%s-%s" % (s_tags[0], c_tags[0]),
178 "dns_servers": [x.strip() for x in vcpe_service.dns_servers.split(",")],
179 "url_filter_kind": vcpe_service.url_filter_kind }
180
181 # add in the sync_attributes that come from the SubscriberRoot object
182
183 if o.volt and o.volt.subscriber and hasattr(o.volt.subscriber, "sync_attributes"):
184 for attribute_name in o.volt.subscriber.sync_attributes:
185 fields[attribute_name] = getattr(o.volt.subscriber, attribute_name)
186
187 return fields
188
189 def sync_fields(self, o, fields):
190 # the super causes the playbook to be run
191
192 super(SyncVSGTenant, self).sync_fields(o, fields)
193
194 # now do all of our broadbandshield stuff...
195
196 service = self.get_vcpe_service(o)
197 if not service:
198 # Ansible uses the service's keypair in order to SSH into the
199 # instance. It would be bad if the slice had no service.
200
201 raise Exception("Slice %s is not associated with a service" % instance.slice.name)
202
203 # Make sure the slice is configured properly
204 if (service != o.instance.slice.service):
205 raise Exception("Slice %s is associated with some service that is not %s" % (str(instance.slice), str(service)))
206
207 # only enable filtering if we have a subscriber object (see below)
208 url_filter_enable = False
209
210 # for attributes that come from CordSubscriberRoot
211 if o.volt and o.volt.subscriber:
212 url_filter_enable = o.volt.subscriber.url_filter_enable
213 url_filter_level = o.volt.subscriber.url_filter_level
214 url_filter_users = o.volt.subscriber.devices
215
216 if service.url_filter_kind == "broadbandshield":
217 # disable url_filter if there are no bbs_addrs
218 if url_filter_enable and (not fields.get("bbs_addrs",[])):
219 logger.info("disabling url_filter because there are no bbs_addrs",extra=o.tologdict())
220 url_filter_enable = False
221
222 if url_filter_enable:
223 bbs_hostname = None
224 if service.bbs_api_hostname and service.bbs_api_port:
225 bbs_hostname = service.bbs_api_hostname
226 else:
227 # TODO: extract from slice
228 bbs_hostname = "cordcompute01.onlab.us"
229
230 if service.bbs_api_port:
231 bbs_port = service.bbs_api_port
232 else:
233 bbs_port = 8018
234
235 if not bbs_hostname:
236 logger.info("broadbandshield is not configured",extra=o.tologdict())
237 else:
238 tStart = time.time()
239 bbs = BBS(o.bbs_account, "123", bbs_hostname, bbs_port)
240 bbs.sync(url_filter_level, url_filter_users)
241
242 if o.hpc_client_ip:
243 logger.info("associate account %s with ip %s" % (o.bbs_account, o.hpc_client_ip),extra=o.tologdict())
244 bbs.associate(o.hpc_client_ip)
245 else:
246 logger.info("no hpc_client_ip to associate",extra=o.tologdict())
247
248 logger.info("bbs update time %d" % int(time.time()-tStart),extra=o.tologdict())
249
250
251 def run_playbook(self, o, fields):
252 ansible_hash = hashlib.md5(repr(sorted(fields.items()))).hexdigest()
253 quick_update = (o.last_ansible_hash == ansible_hash)
254
255 if ENABLE_QUICK_UPDATE and quick_update:
256 logger.info("quick_update triggered; skipping ansible recipe",extra=o.tologdict())
257 else:
258 if o.instance.isolation in ["container", "container_vm"]:
259 super(SyncVSGTenant, self).run_playbook(o, fields, "sync_vcpetenant_new.yaml")
260 else:
261 if CORD_USE_VTN:
262 super(SyncVSGTenant, self).run_playbook(o, fields, template_name="sync_vcpetenant_vtn.yaml")
263 else:
264 super(SyncVSGTenant, self).run_playbook(o, fields)
265
266 o.last_ansible_hash = ansible_hash
267
268 def delete_record(self, m):
269 pass