blob: 9e3dfac7ec120d6222f0e962cbec4eb7b9b65f04 [file] [log] [blame]
Sapan Bhatia4d6cd132016-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 Bhatia6ffd9d52016-01-15 11:38:46 -050011from synchronizers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
Scott Baker6fd78342016-02-18 15:18:47 -080012from core.models import Service, Slice, Tag
Scott Bakerf91e6152016-02-11 12:07:10 -080013from services.cord.models import VSGService, VSGTenant, VOLTTenant
Sapan Bhatia4d6cd132016-01-15 10:43:19 -050014from services.hpc.models import HpcService, CDNPrefix
Scott Bakerb1c0e722016-01-15 07:57:33 -080015from xos.logger import Logger, logging
Sapan Bhatia4d6cd132016-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
Sapan Bhatia4d6cd132016-01-15 10:43:19 -050025ENABLE_QUICK_UPDATE=False
26
Scott Bakercf6eb992016-02-18 06:43:02 -080027CORD_USE_VTN = getattr(Config(), "networking_use_vtn", False)
28
Scott Baker4c052b22016-02-11 11:08:42 -080029class SyncVSGTenant(SyncInstanceUsingAnsible):
30 provides=[VSGTenant]
31 observes=VSGTenant
Sapan Bhatia4d6cd132016-01-15 10:43:19 -050032 requested_interval=0
33 template_name = "sync_vcpetenant.yaml"
Srikanth Vavilapalli562ba492016-01-25 20:06:43 -050034 service_key_name = "/opt/xos/synchronizers/vcpe/vcpe_private_key"
Sapan Bhatia4d6cd132016-01-15 10:43:19 -050035
36 def __init__(self, *args, **kwargs):
Scott Baker4c052b22016-02-11 11:08:42 -080037 super(SyncVSGTenant, self).__init__(*args, **kwargs)
Sapan Bhatia4d6cd132016-01-15 10:43:19 -050038
39 def fetch_pending(self, deleted):
40 if (not deleted):
Scott Baker4c052b22016-02-11 11:08:42 -080041 objs = VSGTenant.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
Sapan Bhatia4d6cd132016-01-15 10:43:19 -050042 else:
Scott Baker4c052b22016-02-11 11:08:42 -080043 objs = VSGTenant.get_deleted_tenant_objects()
Sapan Bhatia4d6cd132016-01-15 10:43:19 -050044
45 return objs
46
47 def get_vcpe_service(self, o):
48 if not o.provider_service:
49 return None
50
Scott Bakerf91e6152016-02-11 12:07:10 -080051 vcpes = VSGService.get_service_objects().filter(id=o.provider_service.id)
Sapan Bhatia4d6cd132016-01-15 10:43:19 -050052 if not vcpes:
53 return None
54
55 return vcpes[0]
56
57 def get_extra_attributes(self, o):
58 # This is a place to include extra attributes that aren't part of the
59 # object itself. In the case of vCPE, we need to know:
60 # 1) the addresses of dnsdemux, to setup dnsmasq in the vCPE
61 # 2) CDN prefixes, so we know what URLs to send to dnsdemux
62 # 3) BroadBandShield server addresses, for parental filtering
63 # 4) vlan_ids, for setting up networking in the vCPE VM
64
65 vcpe_service = self.get_vcpe_service(o)
66
67 dnsdemux_ip = None
Scott Bakerd0447e52016-03-09 12:44:07 -080068 cdn_prefixes = []
69
70 cdn_config_fn = "/opt/xos/synchronizers/vcpe/cdn_config"
71 if os.path.exists(cdn_config_fn):
72 # manual CDN configuration
73 # the first line is the address of dnsredir
74 # the remaining lines are domain names, one per line
75 lines = file(cdn_config_fn).readlines()
76 if len(lines)>=2:
77 dnsdemux_ip = lines[0].strip()
78 cdn_prefixes = [x.strip() for x in lines[1:] if x.strip()]
Sapan Bhatia4d6cd132016-01-15 10:43:19 -050079 else:
Scott Bakerd0447e52016-03-09 12:44:07 -080080 # automatic CDN configuiration
81 # it learns everything from CDN objects in XOS
82 # not tested on pod.
83 if vcpe_service.backend_network_label:
84 # Connect to dnsdemux using the network specified by
85 # vcpe_service.backend_network_label
86 for service in HpcService.objects.all():
87 for slice in service.slices.all():
88 if "dnsdemux" in slice.name:
89 for instance in slice.instances.all():
90 for ns in instance.ports.all():
91 if ns.ip and ns.network.labels and (vcpe_service.backend_network_label in ns.network.labels):
92 dnsdemux_ip = ns.ip
93 if not dnsdemux_ip:
Sapan Bhatia91c497e2016-04-06 19:04:05 +020094 logger.info("failed to find a dnsdemux on network %s" % vcpe_service.backend_network_label,extra=o.tologdict())
Scott Bakerd0447e52016-03-09 12:44:07 -080095 else:
96 # Connect to dnsdemux using the instance's public address
97 for service in HpcService.objects.all():
98 for slice in service.slices.all():
99 if "dnsdemux" in slice.name:
100 for instance in slice.instances.all():
101 if dnsdemux_ip=="none":
102 try:
103 dnsdemux_ip = socket.gethostbyname(instance.node.name)
104 except:
105 pass
106 if not dnsdemux_ip:
Sapan Bhatia91c497e2016-04-06 19:04:05 +0200107 logger.info("failed to find a dnsdemux with a public address",extra=o.tologdict())
Scott Bakerd0447e52016-03-09 12:44:07 -0800108
109 for prefix in CDNPrefix.objects.all():
110 cdn_prefixes.append(prefix.prefix)
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500111
112 dnsdemux_ip = dnsdemux_ip or "none"
113
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500114 # Broadbandshield can either be set up internally, using vcpe_service.bbs_slice,
115 # or it can be setup externally using vcpe_service.bbs_server.
116
117 bbs_addrs = []
118 if vcpe_service.bbs_slice:
119 if vcpe_service.backend_network_label:
120 for bbs_instance in vcpe_service.bbs_slice.instances.all():
121 for ns in bbs_instance.ports.all():
122 if ns.ip and ns.network.labels and (vcpe_service.backend_network_label in ns.network.labels):
123 bbs_addrs.append(ns.ip)
124 else:
Sapan Bhatia91c497e2016-04-06 19:04:05 +0200125 logger.info("unsupported configuration -- bbs_slice is set, but backend_network_label is not",extra=o.tologdict())
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500126 if not bbs_addrs:
Sapan Bhatia91c497e2016-04-06 19:04:05 +0200127 logger.info("failed to find any usable addresses on bbs_slice",extra=o.tologdict())
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500128 elif vcpe_service.bbs_server:
129 bbs_addrs.append(vcpe_service.bbs_server)
130 else:
Sapan Bhatia91c497e2016-04-06 19:04:05 +0200131 logger.info("neither bbs_slice nor bbs_server is configured in the vCPE",extra=o.tologdict())
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500132
133 vlan_ids = []
134 s_tags = []
135 c_tags = []
136 if o.volt:
137 vlan_ids.append(o.volt.vlan_id) # XXX remove this
138 s_tags.append(o.volt.s_tag)
139 c_tags.append(o.volt.c_tag)
140
141 try:
142 full_setup = Config().observer_full_setup
143 except:
144 full_setup = True
145
146 safe_macs=[]
Scott Baker90d09a52016-03-10 19:33:57 -0800147 if vcpe_service.url_filter_kind == "safebrowsing":
148 if o.volt and o.volt.subscriber:
149 for user in o.volt.subscriber.users:
150 level = user.get("level",None)
151 mac = user.get("mac",None)
152 if level in ["G", "PG"]:
153 if mac:
154 safe_macs.append(mac)
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500155
156 fields = {"vlan_ids": vlan_ids, # XXX remove this
157 "s_tags": s_tags,
158 "c_tags": c_tags,
159 "dnsdemux_ip": dnsdemux_ip,
160 "cdn_prefixes": cdn_prefixes,
161 "bbs_addrs": bbs_addrs,
162 "full_setup": full_setup,
163 "isolation": o.instance.isolation,
Scott Bakerd9fba162016-02-23 16:01:09 -0800164 "safe_browsing_macs": safe_macs,
Andy Bavier11309452016-03-03 14:23:51 -0500165 "container_name": "vcpe-%s-%s" % (s_tags[0], c_tags[0]),
Scott Bakerbe2bc9a2016-03-10 20:12:15 -0800166 "dns_servers": [x.strip() for x in vcpe_service.dns_servers.split(",")],
167 "url_filter_kind": vcpe_service.url_filter_kind }
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500168
169 # add in the sync_attributes that come from the SubscriberRoot object
170
171 if o.volt and o.volt.subscriber and hasattr(o.volt.subscriber, "sync_attributes"):
172 for attribute_name in o.volt.subscriber.sync_attributes:
173 fields[attribute_name] = getattr(o.volt.subscriber, attribute_name)
174
175 return fields
176
177 def sync_fields(self, o, fields):
178 # the super causes the playbook to be run
179
Scott Baker4c052b22016-02-11 11:08:42 -0800180 super(SyncVSGTenant, self).sync_fields(o, fields)
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500181
182 # now do all of our broadbandshield stuff...
183
184 service = self.get_vcpe_service(o)
185 if not service:
186 # Ansible uses the service's keypair in order to SSH into the
187 # instance. It would be bad if the slice had no service.
188
189 raise Exception("Slice %s is not associated with a service" % instance.slice.name)
190
191 # Make sure the slice is configured properly
192 if (service != o.instance.slice.service):
193 raise Exception("Slice %s is associated with some service that is not %s" % (str(instance.slice), str(service)))
194
195 # only enable filtering if we have a subscriber object (see below)
196 url_filter_enable = False
197
198 # for attributes that come from CordSubscriberRoot
199 if o.volt and o.volt.subscriber:
200 url_filter_enable = o.volt.subscriber.url_filter_enable
201 url_filter_level = o.volt.subscriber.url_filter_level
202 url_filter_users = o.volt.subscriber.users
203
Scott Baker90d09a52016-03-10 19:33:57 -0800204 if service.url_filter_kind == "broadbandshield":
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500205 # disable url_filter if there are no bbs_addrs
206 if url_filter_enable and (not fields.get("bbs_addrs",[])):
Sapan Bhatia91c497e2016-04-06 19:04:05 +0200207 logger.info("disabling url_filter because there are no bbs_addrs",extra=o.tologdict())
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500208 url_filter_enable = False
209
210 if url_filter_enable:
211 bbs_hostname = None
212 if service.bbs_api_hostname and service.bbs_api_port:
213 bbs_hostname = service.bbs_api_hostname
214 else:
215 # TODO: extract from slice
216 bbs_hostname = "cordcompute01.onlab.us"
217
218 if service.bbs_api_port:
219 bbs_port = service.bbs_api_port
220 else:
221 bbs_port = 8018
222
223 if not bbs_hostname:
Sapan Bhatia91c497e2016-04-06 19:04:05 +0200224 logger.info("broadbandshield is not configured",extra=o.tologdict())
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500225 else:
226 tStart = time.time()
227 bbs = BBS(o.bbs_account, "123", bbs_hostname, bbs_port)
228 bbs.sync(url_filter_level, url_filter_users)
229
230 if o.hpc_client_ip:
Sapan Bhatia91c497e2016-04-06 19:04:05 +0200231 logger.info("associate account %s with ip %s" % (o.bbs_account, o.hpc_client_ip),extra=o.tologdict())
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500232 bbs.associate(o.hpc_client_ip)
233 else:
Sapan Bhatia91c497e2016-04-06 19:04:05 +0200234 logger.info("no hpc_client_ip to associate",extra=o.tologdict())
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500235
Sapan Bhatia91c497e2016-04-06 19:04:05 +0200236 logger.info("bbs update time %d" % int(time.time()-tStart),extra=o.tologdict())
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500237
238
239 def run_playbook(self, o, fields):
240 ansible_hash = hashlib.md5(repr(sorted(fields.items()))).hexdigest()
241 quick_update = (o.last_ansible_hash == ansible_hash)
242
243 if ENABLE_QUICK_UPDATE and quick_update:
Sapan Bhatia91c497e2016-04-06 19:04:05 +0200244 logger.info("quick_update triggered; skipping ansible recipe",extra=o.tologdict())
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500245 else:
246 if o.instance.isolation in ["container", "container_vm"]:
Scott Baker4c052b22016-02-11 11:08:42 -0800247 super(SyncVSGTenant, self).run_playbook(o, fields, "sync_vcpetenant_new.yaml")
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500248 else:
Scott Bakercf6eb992016-02-18 06:43:02 -0800249 if CORD_USE_VTN:
250 super(SyncVSGTenant, self).run_playbook(o, fields, template_name="sync_vcpetenant_vtn.yaml")
251 else:
252 super(SyncVSGTenant, self).run_playbook(o, fields)
Sapan Bhatia4d6cd132016-01-15 10:43:19 -0500253
254 o.last_ansible_hash = ansible_hash
255
256 def delete_record(self, m):
257 pass