blob: 0959073d4612265deafa47df30088db84d59c85e [file] [log] [blame]
Matteo Scandolo6288d5a2017-08-08 13:05:26 -07001
2# Copyright 2017-present Open Networking Foundation
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080017import hashlib
18import os
19import socket
20import sys
21import base64
22import time
23from urlparse import urlparse
Andrea Campanella08c14ca2017-03-31 16:13:09 +020024from synchronizers.new_base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
25from synchronizers.new_base.modelaccessor import *
26from synchronizers.new_base.ansible_helper import run_template_ssh
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080027from xos.logger import Logger, logging
Scott Baker3b8ceca2017-10-12 11:38:50 -070028import wrappers.vegtenant
29import wrappers.veeserviceinstance
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080030
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080031# hpclibrary will be in steps/..
32parentdir = os.path.join(os.path.dirname(__file__),"..")
33sys.path.insert(0,parentdir)
34
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080035
36logger = Logger(level=logging.INFO)
37
38ENABLE_QUICK_UPDATE=False
39
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080040class SyncVEGTenant(SyncInstanceUsingAnsible):
41 provides=[VEGTenant]
42 observes=VEGTenant
43 requested_interval=0
44 template_name = "sync_vegtenant.yaml"
Andrea Campanella08c14ca2017-03-31 16:13:09 +020045 watches = [ModelLink(ServiceDependency, via='servicedependency'), ModelLink(ServiceMonitoringAgentInfo, via='monitoringagentinfo')]
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080046
47 def __init__(self, *args, **kwargs):
48 super(SyncVEGTenant, self).__init__(*args, **kwargs)
49
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080050 def get_veg_service(self, o):
Andrea Campanella2a2df422017-08-30 16:59:17 +020051 if not o.owner:
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080052 return None
53
Scott Baker3b8ceca2017-10-12 11:38:50 -070054 vegs = VEGService.objects.filter(id=o.owner.id)
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080055 if not vegs:
56 return None
57
58 return vegs[0]
59
60 def get_extra_attributes(self, o):
61 # This is a place to include extra attributes that aren't part of the
62 # object itself. In the case of vEG, we need to know:
63 # 1) the addresses of dnsdemux, to setup dnsmasq in the vEG
64 # 2) CDN prefixes, so we know what URLs to send to dnsdemux
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080065 # 4) vlan_ids, for setting up networking in the vEG VM
66
67 veg_service = self.get_veg_service(o)
68
69 dnsdemux_ip = None
70 cdn_prefixes = []
71 #FIXME this will probably break since no folder is under syncronizers
72 cdn_config_fn = "/opt/xos/synchronizers/veg/cdn_config"
73 if os.path.exists(cdn_config_fn):
74 # manual CDN configuration
75 # the first line is the address of dnsredir
76 # the remaining lines are domain names, one per line
77 lines = file(cdn_config_fn).readlines()
78 if len(lines)>=2:
79 dnsdemux_ip = lines[0].strip()
80 cdn_prefixes = [x.strip() for x in lines[1:] if x.strip()]
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080081
82 dnsdemux_ip = dnsdemux_ip or "none"
83
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080084 s_tags = []
85 c_tags = []
86 if o.volt:
87 s_tags.append(o.volt.s_tag)
88 c_tags.append(o.volt.c_tag)
89
Andrea Campanella2a2df422017-08-30 16:59:17 +020090 full_setup = True
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080091
92 safe_macs=[]
93 if veg_service.url_filter_kind == "safebrowsing":
Scott Baker3b8ceca2017-10-12 11:38:50 -070094 if o.volt and o.volt.subscriber and hasattr(o.volt.subscriber, "devices"):
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080095 for user in o.volt.subscriber.devices:
96 level = user.get("level",None)
97 mac = user.get("mac",None)
98 if level in ["G", "PG"]:
99 if mac:
100 safe_macs.append(mac)
101
102
103 docker_opts = []
104 if veg_service.docker_insecure_registry:
105 reg_name = veg_service.docker_image_name.split("/",1)[0]
106 docker_opts.append("--insecure-registry " + reg_name)
107
108 fields = {"s_tags": s_tags,
109 "c_tags": c_tags,
110 "docker_remote_image_name": veg_service.docker_image_name,
Andrea Campanella08c14ca2017-03-31 16:13:09 +0200111 "docker_local_image_name": veg_service.docker_image_name,
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800112 "docker_opts": " ".join(docker_opts),
113 "dnsdemux_ip": dnsdemux_ip,
114 "cdn_prefixes": cdn_prefixes,
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800115 "full_setup": full_setup,
116 "isolation": o.instance.isolation,
117 "safe_browsing_macs": safe_macs,
118 "container_name": "veg-%s-%s" % (s_tags[0], c_tags[0]),
119 "dns_servers": [x.strip() for x in veg_service.dns_servers.split(",")],
120 "url_filter_kind": veg_service.url_filter_kind }
121
Scott Baker3b8ceca2017-10-12 11:38:50 -0700122 # Some subscriber models may not implement all fields that we look for, so specify some defaults.
123 fields["firewall_rules"] = ""
124 fields["firewall_enable"] = False
125 fields["url_filter_enable"] = False
126 fields["url_filter_level"] = "PG"
127 fields["cdn_enable"] = False
128 fields["uplink_speed"] = 1000000000
129 fields["downlink_speed"] = 1000000000
130 fields["enable_uverse"] = True
131 fields["status"] = "enabled"
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800132
Scott Baker3b8ceca2017-10-12 11:38:50 -0700133 # add in the sync_attributes that come from the SubscriberRoot object
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800134 if o.volt and o.volt.subscriber and hasattr(o.volt.subscriber, "sync_attributes"):
135 for attribute_name in o.volt.subscriber.sync_attributes:
136 fields[attribute_name] = getattr(o.volt.subscriber, attribute_name)
137
138 return fields
139
140 def sync_fields(self, o, fields):
141 # the super causes the playbook to be run
142
143 super(SyncVEGTenant, self).sync_fields(o, fields)
144
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800145 def run_playbook(self, o, fields):
146 ansible_hash = hashlib.md5(repr(sorted(fields.items()))).hexdigest()
147 quick_update = (o.last_ansible_hash == ansible_hash)
148
149 if ENABLE_QUICK_UPDATE and quick_update:
150 logger.info("quick_update triggered; skipping ansible recipe",extra=o.tologdict())
151 else:
152 if o.instance.isolation in ["container", "container_vm"]:
Andrea Campanella08c14ca2017-03-31 16:13:09 +0200153 raise Exception("probably not implemented")
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800154 super(SyncVEGTenant, self).run_playbook(o, fields, "sync_vegtenant_new.yaml")
155 else:
Andrea Campanella08c14ca2017-03-31 16:13:09 +0200156 super(SyncVEGTenant, self).run_playbook(o, fields, template_name="sync_vegtenant_vtn.yaml")
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800157
158 o.last_ansible_hash = ansible_hash
159
Andrea Campanella2a2df422017-08-30 16:59:17 +0200160 def sync_record(self, o):
161 if (not o.policed) or (o.policed<o.updated):
162 defer_sync("waiting on model policy")
163 super(SyncVEGTenant, self).sync_record(o)
164
165 def delete_record(self, o):
166 if (not o.policed) or (o.policed<o.updated):
167 defer_sync("waiting on model policy")
168 # do not call super, as we don't want to re-run the playbook
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800169
170 def handle_service_monitoringagentinfo_watch_notification(self, monitoring_agent_info):
171 if not monitoring_agent_info.service:
172 logger.info("handle watch notifications for service monitoring agent info...ignoring because service attribute in monitoring agent info:%s is null" % (monitoring_agent_info))
173 return
174
175 if not monitoring_agent_info.target_uri:
176 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))
177 return
178
179 objs = VEGTenant.get_tenant_objects().all()
180 for obj in objs:
Andrea Campanella2a2df422017-08-30 16:59:17 +0200181 if obj.owner.id != monitoring_agent_info.service.id:
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800182 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))
183 return
184
185 instance = self.get_instance(obj)
186 if not instance:
187 logger.warn("handle watch notifications for service monitoring agent info...: No valid instance found for object %s" % (str(obj)))
188 return
189
190 logger.info("handling watch notification for monitoring agent info:%s for VEGTenant object:%s" % (monitoring_agent_info, obj))
191
192 #Run ansible playbook to update the routing table entries in the instance
193 fields = self.get_ansible_fields(instance)
194 fields["ansible_tag"] = obj.__class__.__name__ + "_" + str(obj.id) + "_service_monitoring"
195
196 #Parse the monitoring agent target_uri
197 url = urlparse(monitoring_agent_info.target_uri)
198
199 #Assuming target_uri is rabbitmq URI
200 fields["rabbit_user"] = url.username
201 fields["rabbit_password"] = url.password
202 fields["rabbit_host"] = url.hostname
203
204 template_name = "sync_monitoring_agent.yaml"
205 super(SyncVEGTenant, self).run_playbook(obj, fields, template_name)