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