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