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