blob: 98400f3b4ce9d344a8a7e3f5c862883bdf4b20b8 [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
28
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080029# hpclibrary will be in steps/..
30parentdir = os.path.join(os.path.dirname(__file__),"..")
31sys.path.insert(0,parentdir)
32
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080033
34logger = Logger(level=logging.INFO)
35
36ENABLE_QUICK_UPDATE=False
37
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080038class SyncVEGTenant(SyncInstanceUsingAnsible):
39 provides=[VEGTenant]
40 observes=VEGTenant
41 requested_interval=0
42 template_name = "sync_vegtenant.yaml"
Andrea Campanella08c14ca2017-03-31 16:13:09 +020043 watches = [ModelLink(ServiceDependency, via='servicedependency'), ModelLink(ServiceMonitoringAgentInfo, via='monitoringagentinfo')]
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080044
45 def __init__(self, *args, **kwargs):
46 super(SyncVEGTenant, self).__init__(*args, **kwargs)
47
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080048 def get_veg_service(self, o):
Andrea Campanella2a2df422017-08-30 16:59:17 +020049 if not o.owner:
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080050 return None
51
Scott Baker3b8ceca2017-10-12 11:38:50 -070052 vegs = VEGService.objects.filter(id=o.owner.id)
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080053 if not vegs:
54 return None
55
56 return vegs[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 vEG, we need to know:
61 # 1) the addresses of dnsdemux, to setup dnsmasq in the vEG
62 # 2) CDN prefixes, so we know what URLs to send to dnsdemux
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080063 # 4) vlan_ids, for setting up networking in the vEG VM
64
65 veg_service = self.get_veg_service(o)
66
67 dnsdemux_ip = None
68 cdn_prefixes = []
69 #FIXME this will probably break since no folder is under syncronizers
70 cdn_config_fn = "/opt/xos/synchronizers/veg/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()]
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080079
80 dnsdemux_ip = dnsdemux_ip or "none"
81
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080082 s_tags = []
83 c_tags = []
84 if o.volt:
85 s_tags.append(o.volt.s_tag)
86 c_tags.append(o.volt.c_tag)
87
Andrea Campanella2a2df422017-08-30 16:59:17 +020088 full_setup = True
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080089
90 safe_macs=[]
91 if veg_service.url_filter_kind == "safebrowsing":
Scott Baker3b8ceca2017-10-12 11:38:50 -070092 if o.volt and o.volt.subscriber and hasattr(o.volt.subscriber, "devices"):
Andrea Campanellaedfdbca2017-02-01 17:33:47 -080093 for user in o.volt.subscriber.devices:
94 level = user.get("level",None)
95 mac = user.get("mac",None)
96 if level in ["G", "PG"]:
97 if mac:
98 safe_macs.append(mac)
99
100
101 docker_opts = []
102 if veg_service.docker_insecure_registry:
103 reg_name = veg_service.docker_image_name.split("/",1)[0]
104 docker_opts.append("--insecure-registry " + reg_name)
105
106 fields = {"s_tags": s_tags,
107 "c_tags": c_tags,
108 "docker_remote_image_name": veg_service.docker_image_name,
Andrea Campanella08c14ca2017-03-31 16:13:09 +0200109 "docker_local_image_name": veg_service.docker_image_name,
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800110 "docker_opts": " ".join(docker_opts),
111 "dnsdemux_ip": dnsdemux_ip,
112 "cdn_prefixes": cdn_prefixes,
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800113 "full_setup": full_setup,
114 "isolation": o.instance.isolation,
115 "safe_browsing_macs": safe_macs,
116 "container_name": "veg-%s-%s" % (s_tags[0], c_tags[0]),
117 "dns_servers": [x.strip() for x in veg_service.dns_servers.split(",")],
118 "url_filter_kind": veg_service.url_filter_kind }
119
Scott Baker3b8ceca2017-10-12 11:38:50 -0700120 # Some subscriber models may not implement all fields that we look for, so specify some defaults.
121 fields["firewall_rules"] = ""
122 fields["firewall_enable"] = False
123 fields["url_filter_enable"] = False
124 fields["url_filter_level"] = "PG"
125 fields["cdn_enable"] = False
126 fields["uplink_speed"] = 1000000000
127 fields["downlink_speed"] = 1000000000
128 fields["enable_uverse"] = True
129 fields["status"] = "enabled"
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800130
Scott Baker3b8ceca2017-10-12 11:38:50 -0700131 # add in the sync_attributes that come from the SubscriberRoot object
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800132 if o.volt and o.volt.subscriber and hasattr(o.volt.subscriber, "sync_attributes"):
133 for attribute_name in o.volt.subscriber.sync_attributes:
134 fields[attribute_name] = getattr(o.volt.subscriber, attribute_name)
135
136 return fields
137
138 def sync_fields(self, o, fields):
139 # the super causes the playbook to be run
140
141 super(SyncVEGTenant, self).sync_fields(o, fields)
142
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800143 def run_playbook(self, o, fields):
144 ansible_hash = hashlib.md5(repr(sorted(fields.items()))).hexdigest()
145 quick_update = (o.last_ansible_hash == ansible_hash)
146
147 if ENABLE_QUICK_UPDATE and quick_update:
148 logger.info("quick_update triggered; skipping ansible recipe",extra=o.tologdict())
149 else:
150 if o.instance.isolation in ["container", "container_vm"]:
Andrea Campanella08c14ca2017-03-31 16:13:09 +0200151 raise Exception("probably not implemented")
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800152 super(SyncVEGTenant, self).run_playbook(o, fields, "sync_vegtenant_new.yaml")
153 else:
Andrea Campanella08c14ca2017-03-31 16:13:09 +0200154 super(SyncVEGTenant, self).run_playbook(o, fields, template_name="sync_vegtenant_vtn.yaml")
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800155
156 o.last_ansible_hash = ansible_hash
157
Andrea Campanella2a2df422017-08-30 16:59:17 +0200158 def sync_record(self, o):
159 if (not o.policed) or (o.policed<o.updated):
Scott Baker5bbdcac2017-11-29 11:39:24 -0800160 self.defer_sync(o, "waiting on model policy")
Andrea Campanella2a2df422017-08-30 16:59:17 +0200161 super(SyncVEGTenant, self).sync_record(o)
162
163 def delete_record(self, o):
164 if (not o.policed) or (o.policed<o.updated):
Scott Baker5bbdcac2017-11-29 11:39:24 -0800165 self.defer_sync(o, "waiting on model policy")
Andrea Campanella2a2df422017-08-30 16:59:17 +0200166 # do not call super, as we don't want to re-run the playbook
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800167
168 def handle_service_monitoringagentinfo_watch_notification(self, monitoring_agent_info):
169 if not monitoring_agent_info.service:
170 logger.info("handle watch notifications for service monitoring agent info...ignoring because service attribute in monitoring agent info:%s is null" % (monitoring_agent_info))
171 return
172
173 if not monitoring_agent_info.target_uri:
174 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))
175 return
176
177 objs = VEGTenant.get_tenant_objects().all()
178 for obj in objs:
Andrea Campanella2a2df422017-08-30 16:59:17 +0200179 if obj.owner.id != monitoring_agent_info.service.id:
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800180 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))
181 return
182
183 instance = self.get_instance(obj)
184 if not instance:
185 logger.warn("handle watch notifications for service monitoring agent info...: No valid instance found for object %s" % (str(obj)))
186 return
187
188 logger.info("handling watch notification for monitoring agent info:%s for VEGTenant object:%s" % (monitoring_agent_info, obj))
189
190 #Run ansible playbook to update the routing table entries in the instance
191 fields = self.get_ansible_fields(instance)
192 fields["ansible_tag"] = obj.__class__.__name__ + "_" + str(obj.id) + "_service_monitoring"
193
194 #Parse the monitoring agent target_uri
195 url = urlparse(monitoring_agent_info.target_uri)
196
197 #Assuming target_uri is rabbitmq URI
198 fields["rabbit_user"] = url.username
199 fields["rabbit_password"] = url.password
200 fields["rabbit_host"] = url.hostname
201
202 template_name = "sync_monitoring_agent.yaml"
203 super(SyncVEGTenant, self).run_playbook(obj, fields, template_name)