blob: 67415184e348f62f6896bfe232296ee545929104 [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
Andrea Campanella08c14ca2017-03-31 16:13:09 +020052 vegs = VEGService.objects.filter(id=o.provider_service.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":
92 if o.volt and o.volt.subscriber:
93 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
120 # add in the sync_attributes that come from the SubscriberRoot object
121
122 if o.volt and o.volt.subscriber and hasattr(o.volt.subscriber, "sync_attributes"):
123 for attribute_name in o.volt.subscriber.sync_attributes:
124 fields[attribute_name] = getattr(o.volt.subscriber, attribute_name)
125
126 return fields
127
128 def sync_fields(self, o, fields):
129 # the super causes the playbook to be run
130
131 super(SyncVEGTenant, self).sync_fields(o, fields)
132
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800133 def run_playbook(self, o, fields):
134 ansible_hash = hashlib.md5(repr(sorted(fields.items()))).hexdigest()
135 quick_update = (o.last_ansible_hash == ansible_hash)
136
137 if ENABLE_QUICK_UPDATE and quick_update:
138 logger.info("quick_update triggered; skipping ansible recipe",extra=o.tologdict())
139 else:
140 if o.instance.isolation in ["container", "container_vm"]:
Andrea Campanella08c14ca2017-03-31 16:13:09 +0200141 raise Exception("probably not implemented")
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800142 super(SyncVEGTenant, self).run_playbook(o, fields, "sync_vegtenant_new.yaml")
143 else:
Andrea Campanella08c14ca2017-03-31 16:13:09 +0200144 super(SyncVEGTenant, self).run_playbook(o, fields, template_name="sync_vegtenant_vtn.yaml")
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800145
146 o.last_ansible_hash = ansible_hash
147
Andrea Campanella2a2df422017-08-30 16:59:17 +0200148 def sync_record(self, o):
149 if (not o.policed) or (o.policed<o.updated):
150 defer_sync("waiting on model policy")
151 super(SyncVEGTenant, self).sync_record(o)
152
153 def delete_record(self, o):
154 if (not o.policed) or (o.policed<o.updated):
155 defer_sync("waiting on model policy")
156 # do not call super, as we don't want to re-run the playbook
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800157
158 def handle_service_monitoringagentinfo_watch_notification(self, monitoring_agent_info):
159 if not monitoring_agent_info.service:
160 logger.info("handle watch notifications for service monitoring agent info...ignoring because service attribute in monitoring agent info:%s is null" % (monitoring_agent_info))
161 return
162
163 if not monitoring_agent_info.target_uri:
164 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))
165 return
166
167 objs = VEGTenant.get_tenant_objects().all()
168 for obj in objs:
Andrea Campanella2a2df422017-08-30 16:59:17 +0200169 if obj.owner.id != monitoring_agent_info.service.id:
Andrea Campanellaedfdbca2017-02-01 17:33:47 -0800170 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))
171 return
172
173 instance = self.get_instance(obj)
174 if not instance:
175 logger.warn("handle watch notifications for service monitoring agent info...: No valid instance found for object %s" % (str(obj)))
176 return
177
178 logger.info("handling watch notification for monitoring agent info:%s for VEGTenant object:%s" % (monitoring_agent_info, obj))
179
180 #Run ansible playbook to update the routing table entries in the instance
181 fields = self.get_ansible_fields(instance)
182 fields["ansible_tag"] = obj.__class__.__name__ + "_" + str(obj.id) + "_service_monitoring"
183
184 #Parse the monitoring agent target_uri
185 url = urlparse(monitoring_agent_info.target_uri)
186
187 #Assuming target_uri is rabbitmq URI
188 fields["rabbit_user"] = url.username
189 fields["rabbit_password"] = url.password
190 fields["rabbit_host"] = url.hostname
191
192 template_name = "sync_monitoring_agent.yaml"
193 super(SyncVEGTenant, self).run_playbook(obj, fields, template_name)