blob: 5e4883788b846792872c9f66d5f73beb8a82bbe4 [file] [log] [blame]
Sapan Bhatia2ac88642016-01-15 10:43:19 -05001import 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
Sapan Bhatia62ee8d12016-01-15 11:38:46 -050011from synchronizers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
Scott Baker7aa5e992016-02-18 15:18:47 -080012from core.models import Service, Slice, Tag
Scott Baker4698b922016-02-11 12:07:10 -080013from services.cord.models import VSGService, VSGTenant, VOLTTenant
Sapan Bhatia2ac88642016-01-15 10:43:19 -050014from services.hpc.models import HpcService, CDNPrefix
Scott Baker3a01eb22016-01-15 07:57:33 -080015from xos.logger import Logger, logging
Sapan Bhatia2ac88642016-01-15 10:43:19 -050016
17# hpclibrary will be in steps/..
18parentdir = os.path.join(os.path.dirname(__file__),"..")
19sys.path.insert(0,parentdir)
20
21from broadbandshield import BBS
22
23logger = Logger(level=logging.INFO)
24
25PARENTAL_MECHANISM="dnsmasq"
26ENABLE_QUICK_UPDATE=False
27
Scott Baker4d3cc752016-02-18 06:43:02 -080028CORD_USE_VTN = getattr(Config(), "networking_use_vtn", False)
29
Scott Baker664bbe52016-02-11 11:08:42 -080030class SyncVSGTenant(SyncInstanceUsingAnsible):
31 provides=[VSGTenant]
32 observes=VSGTenant
Sapan Bhatia2ac88642016-01-15 10:43:19 -050033 requested_interval=0
34 template_name = "sync_vcpetenant.yaml"
Srikanth Vavilapalliae1acd62016-01-25 20:06:43 -050035 service_key_name = "/opt/xos/synchronizers/vcpe/vcpe_private_key"
Sapan Bhatia2ac88642016-01-15 10:43:19 -050036
37 def __init__(self, *args, **kwargs):
Scott Baker664bbe52016-02-11 11:08:42 -080038 super(SyncVSGTenant, self).__init__(*args, **kwargs)
Sapan Bhatia2ac88642016-01-15 10:43:19 -050039
40 def fetch_pending(self, deleted):
41 if (not deleted):
Scott Baker664bbe52016-02-11 11:08:42 -080042 objs = VSGTenant.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
Sapan Bhatia2ac88642016-01-15 10:43:19 -050043 else:
Scott Baker664bbe52016-02-11 11:08:42 -080044 objs = VSGTenant.get_deleted_tenant_objects()
Sapan Bhatia2ac88642016-01-15 10:43:19 -050045
46 return objs
47
48 def get_vcpe_service(self, o):
49 if not o.provider_service:
50 return None
51
Scott Baker4698b922016-02-11 12:07:10 -080052 vcpes = VSGService.get_service_objects().filter(id=o.provider_service.id)
Sapan Bhatia2ac88642016-01-15 10:43:19 -050053 if not vcpes:
54 return None
55
56 return vcpes[0]
57
58 def get_extra_attributes(self, o):
59 # This is a place to include extra attributes that aren't part of the
60 # object itself. In the case of vCPE, we need to know:
61 # 1) the addresses of dnsdemux, to setup dnsmasq in the vCPE
62 # 2) CDN prefixes, so we know what URLs to send to dnsdemux
63 # 3) BroadBandShield server addresses, for parental filtering
64 # 4) vlan_ids, for setting up networking in the vCPE VM
65
66 vcpe_service = self.get_vcpe_service(o)
67
68 dnsdemux_ip = None
69 if vcpe_service.backend_network_label:
70 # Connect to dnsdemux using the network specified by
71 # vcpe_service.backend_network_label
72 for service in HpcService.objects.all():
73 for slice in service.slices.all():
74 if "dnsdemux" in slice.name:
75 for instance in slice.instances.all():
76 for ns in instance.ports.all():
77 if ns.ip and ns.network.labels and (vcpe_service.backend_network_label in ns.network.labels):
78 dnsdemux_ip = ns.ip
79 if not dnsdemux_ip:
80 logger.info("failed to find a dnsdemux on network %s" % vcpe_service.backend_network_label)
81 else:
82 # Connect to dnsdemux using the instance's public address
83 for service in HpcService.objects.all():
84 for slice in service.slices.all():
85 if "dnsdemux" in slice.name:
86 for instance in slice.instances.all():
87 if dnsdemux_ip=="none":
88 try:
89 dnsdemux_ip = socket.gethostbyname(instance.node.name)
90 except:
91 pass
92 if not dnsdemux_ip:
93 logger.info("failed to find a dnsdemux with a public address")
94
95 dnsdemux_ip = dnsdemux_ip or "none"
96
97 cdn_prefixes = []
98 for prefix in CDNPrefix.objects.all():
99 cdn_prefixes.append(prefix.prefix)
100
101 # Broadbandshield can either be set up internally, using vcpe_service.bbs_slice,
102 # or it can be setup externally using vcpe_service.bbs_server.
103
104 bbs_addrs = []
105 if vcpe_service.bbs_slice:
106 if vcpe_service.backend_network_label:
107 for bbs_instance in vcpe_service.bbs_slice.instances.all():
108 for ns in bbs_instance.ports.all():
109 if ns.ip and ns.network.labels and (vcpe_service.backend_network_label in ns.network.labels):
110 bbs_addrs.append(ns.ip)
111 else:
112 logger.info("unsupported configuration -- bbs_slice is set, but backend_network_label is not")
113 if not bbs_addrs:
114 logger.info("failed to find any usable addresses on bbs_slice")
115 elif vcpe_service.bbs_server:
116 bbs_addrs.append(vcpe_service.bbs_server)
117 else:
118 logger.info("neither bbs_slice nor bbs_server is configured in the vCPE")
119
120 vlan_ids = []
121 s_tags = []
122 c_tags = []
123 if o.volt:
124 vlan_ids.append(o.volt.vlan_id) # XXX remove this
125 s_tags.append(o.volt.s_tag)
126 c_tags.append(o.volt.c_tag)
127
128 try:
129 full_setup = Config().observer_full_setup
130 except:
131 full_setup = True
132
133 safe_macs=[]
134 if o.volt and o.volt.subscriber:
135 for user in o.volt.subscriber.users:
136 level = user.get("level",None)
137 mac = user.get("mac",None)
138 if level in ["G", "PG"]:
139 if mac:
140 safe_macs.append(mac)
141
Scott Baker7aa5e992016-02-18 15:18:47 -0800142 wan_vm_ip=""
143 wan_vm_mac=""
144 tags = Tag.select_by_content_object(o.instance).filter(name="vm_wan_addr")
145 if tags:
146 parts=tags[0].value.split(",")
147 if len(parts)!=3:
148 raise Exception("vm_wan_addr tag is malformed: %s" % value)
149 wan_vm_ip = parts[1]
150 wan_vm_mac = parts[2]
151 else:
152 if CORD_USE_VTN:
Scott Bakerb3192322016-02-19 09:31:07 -0800153 raise Exception("no vm_wan_addr tag for instance %s" % o.instance)
Scott Baker7aa5e992016-02-18 15:18:47 -0800154
Sapan Bhatia2ac88642016-01-15 10:43:19 -0500155 fields = {"vlan_ids": vlan_ids, # XXX remove this
156 "s_tags": s_tags,
157 "c_tags": c_tags,
158 "dnsdemux_ip": dnsdemux_ip,
159 "cdn_prefixes": cdn_prefixes,
160 "bbs_addrs": bbs_addrs,
161 "full_setup": full_setup,
162 "isolation": o.instance.isolation,
Scott Baker4d3cc752016-02-18 06:43:02 -0800163 "wan_container_gateway_mac": vcpe_service.wan_container_gateway_mac,
164 "wan_container_gateway_ip": vcpe_service.wan_container_gateway_ip,
165 "wan_container_netbits": vcpe_service.wan_container_netbits,
Scott Baker7aa5e992016-02-18 15:18:47 -0800166 "wan_vm_mac": wan_vm_mac,
167 "wan_vm_ip": wan_vm_ip,
Scott Baker8129fce2016-02-23 16:01:09 -0800168 "safe_browsing_macs": safe_macs,
169 "dns_servers": [x.strip() for x in vcpe_service.dns_servers.split(",")] }
Sapan Bhatia2ac88642016-01-15 10:43:19 -0500170
171 # add in the sync_attributes that come from the SubscriberRoot object
172
173 if o.volt and o.volt.subscriber and hasattr(o.volt.subscriber, "sync_attributes"):
174 for attribute_name in o.volt.subscriber.sync_attributes:
175 fields[attribute_name] = getattr(o.volt.subscriber, attribute_name)
176
177 return fields
178
179 def sync_fields(self, o, fields):
180 # the super causes the playbook to be run
181
Scott Baker664bbe52016-02-11 11:08:42 -0800182 super(SyncVSGTenant, self).sync_fields(o, fields)
Sapan Bhatia2ac88642016-01-15 10:43:19 -0500183
184 # now do all of our broadbandshield stuff...
185
186 service = self.get_vcpe_service(o)
187 if not service:
188 # Ansible uses the service's keypair in order to SSH into the
189 # instance. It would be bad if the slice had no service.
190
191 raise Exception("Slice %s is not associated with a service" % instance.slice.name)
192
193 # Make sure the slice is configured properly
194 if (service != o.instance.slice.service):
195 raise Exception("Slice %s is associated with some service that is not %s" % (str(instance.slice), str(service)))
196
197 # only enable filtering if we have a subscriber object (see below)
198 url_filter_enable = False
199
200 # for attributes that come from CordSubscriberRoot
201 if o.volt and o.volt.subscriber:
202 url_filter_enable = o.volt.subscriber.url_filter_enable
203 url_filter_level = o.volt.subscriber.url_filter_level
204 url_filter_users = o.volt.subscriber.users
205
206 if PARENTAL_MECHANISM=="broadbandshield":
207 # disable url_filter if there are no bbs_addrs
208 if url_filter_enable and (not fields.get("bbs_addrs",[])):
209 logger.info("disabling url_filter because there are no bbs_addrs")
210 url_filter_enable = False
211
212 if url_filter_enable:
213 bbs_hostname = None
214 if service.bbs_api_hostname and service.bbs_api_port:
215 bbs_hostname = service.bbs_api_hostname
216 else:
217 # TODO: extract from slice
218 bbs_hostname = "cordcompute01.onlab.us"
219
220 if service.bbs_api_port:
221 bbs_port = service.bbs_api_port
222 else:
223 bbs_port = 8018
224
225 if not bbs_hostname:
226 logger.info("broadbandshield is not configured")
227 else:
228 tStart = time.time()
229 bbs = BBS(o.bbs_account, "123", bbs_hostname, bbs_port)
230 bbs.sync(url_filter_level, url_filter_users)
231
232 if o.hpc_client_ip:
233 logger.info("associate account %s with ip %s" % (o.bbs_account, o.hpc_client_ip))
234 bbs.associate(o.hpc_client_ip)
235 else:
236 logger.info("no hpc_client_ip to associate")
237
238 logger.info("bbs update time %d" % int(time.time()-tStart))
239
240
241 def run_playbook(self, o, fields):
242 ansible_hash = hashlib.md5(repr(sorted(fields.items()))).hexdigest()
243 quick_update = (o.last_ansible_hash == ansible_hash)
244
245 if ENABLE_QUICK_UPDATE and quick_update:
246 logger.info("quick_update triggered; skipping ansible recipe")
247 else:
248 if o.instance.isolation in ["container", "container_vm"]:
Scott Baker664bbe52016-02-11 11:08:42 -0800249 super(SyncVSGTenant, self).run_playbook(o, fields, "sync_vcpetenant_new.yaml")
Sapan Bhatia2ac88642016-01-15 10:43:19 -0500250 else:
Scott Baker4d3cc752016-02-18 06:43:02 -0800251 if CORD_USE_VTN:
252 super(SyncVSGTenant, self).run_playbook(o, fields, template_name="sync_vcpetenant_vtn.yaml")
253 else:
254 super(SyncVSGTenant, self).run_playbook(o, fields)
Sapan Bhatia2ac88642016-01-15 10:43:19 -0500255
256 o.last_ansible_hash = ansible_hash
257
258 def delete_record(self, m):
259 pass