blob: e272c9e365366b807dfa0a09d10a01be89639b15 [file] [log] [blame]
Andy Bavier7b321c52017-08-30 15:33:59 -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
17import os
18import requests
19import socket
20import sys
21import base64
22import json
Scott Baker7934f9c2017-09-21 11:44:44 -070023from synchronizers.new_base.syncstep import DeferredException
Andy Bavier7b321c52017-08-30 15:33:59 -070024from synchronizers.new_base.syncstep import SyncStep
25from synchronizers.new_base.modelaccessor import *
26from xos.logger import Logger, logging
27
28logger = Logger(level=logging.INFO)
29
30class SyncONOSNetcfg(SyncStep):
31 provides=[VTNService]
32 observes=VTNService
33 watches=[ModelLink(Node,via='node'), ModelLink(AddressPool,via='addresspool')]
34 requested_interval=0
35
36 def __init__(self, **args):
37 SyncStep.__init__(self, **args)
38
39 def handle_watched_object(self, o):
40 logger.info("handle_watched_object is invoked for object %s" % (str(o)),extra=o.tologdict())
41 if (type(o) is Node): # For Node add/delete/modify
42 self.call()
43 if (type(o) is AddressPool): # For public gateways
44 self.call()
45
46 def get_node_tag(self, node, tagname):
47 tags = Tag.objects.filter(content_type=model_accessor.get_content_type_id(node),
48 object_id=node.id,
49 name=tagname)
50 return tags[0].value
51
52 def get_service_instances_who_want_config(self):
53 service_instances = []
54 # attribute is comma-separated list
55 for ta in ServiceInstanceAttribute.objects.filter(name="autogenerate"):
56 if ta.value:
57 for config in ta.value.split(','):
58 if config == "vtn-network-cfg":
59 service_instances.append(ta.service_instance)
60 return service_instances
61
62 def save_service_instance_attribute(self, service_instance, name, value):
Scott Bakered645f52017-09-06 13:51:18 -070063 # returns True if something changed
64 something_changed=False
Andy Bavier7b321c52017-08-30 15:33:59 -070065 tas = ServiceInstanceAttribute.objects.filter(service_instance_id=service_instance.id, name=name)
66 if tas:
67 ta = tas[0]
68 if ta.value != value:
69 logger.info("updating %s with attribute" % name)
70 ta.value = value
Scott Bakered645f52017-09-06 13:51:18 -070071 ta.save(update_fields=["value", "updated"], always_update_timestamp=True)
72 something_changed = True
Andy Bavier7b321c52017-08-30 15:33:59 -070073 else:
74 logger.info("saving autogenerated config %s" % name)
75 ta = model_accessor.create_obj(ServiceInstanceAttribute, service_instance=service_instance, name=name, value=value)
76 ta.save()
Scott Bakered645f52017-09-06 13:51:18 -070077 something_changed = True
78 return something_changed
Andy Bavier7b321c52017-08-30 15:33:59 -070079
80 # This function currently assumes a single Deployment and Site
81 def get_onos_netcfg(self, vtn):
82 privateGatewayMac = vtn.privateGatewayMac
83 localManagementIp = vtn.localManagementIp
84 ovsdbPort = vtn.ovsdbPort
85 sshPort = vtn.sshPort
86 sshUser = vtn.sshUser
87 sshKeyFile = vtn.sshKeyFile
88 mgmtSubnetBits = vtn.mgmtSubnetBits
89 xosEndpoint = vtn.xosEndpoint
90 xosUser = vtn.xosUser
91 xosPassword = vtn.xosPassword
92
93 controllerPort = vtn.controllerPort
94 if ":" in controllerPort:
95 (c_hostname, c_port) = controllerPort.split(":",1)
96 controllerPort = socket.gethostbyname(c_hostname) + ":" + c_port
97 else:
98 controllerPort = ":" + controllerPort
99
100 data = {
101 "apps" : {
102 "org.opencord.vtn" : {
103 "cordvtn" : {
104 "privateGatewayMac" : privateGatewayMac,
105 "localManagementIp": localManagementIp,
106 "ovsdbPort": ovsdbPort,
107 "ssh": {
108 "sshPort": sshPort,
109 "sshUser": sshUser,
110 "sshKeyFile": sshKeyFile
111 },
112 "xos": {
113 "endpoint": xosEndpoint,
114 "user": xosUser,
115 "password": xosPassword
116 },
117 "publicGateways": [],
118 "nodes" : [],
119 "controllers": [controllerPort]
120 }
121 }
122 }
123 }
124
125 # Generate apps->org.opencord.vtn->cordvtn->openstack
126 controllers = Controller.objects.all()
127 if controllers:
128 controller = controllers[0]
129 keystone_server = controller.auth_url
130 user_name = controller.admin_user
131 tenant_name = controller.admin_tenant
132 password = controller.admin_password
133 openstack = {
134 "endpoint": keystone_server,
135 "tenant": tenant_name,
136 "user": user_name,
137 "password": password
138 }
139 data["apps"]["org.opencord.vtn"]["cordvtn"]["openstack"] = openstack
140
141 # Generate apps->org.opencord.vtn->cordvtn->nodes
142 nodes = Node.objects.all()
143 for node in nodes:
144 try:
145 nodeip = socket.gethostbyname(node.name)
146 except socket.gaierror:
147 logger.warn("unable to resolve hostname %s: node will not be added to config"
148 % node.name)
149 continue
150
151 try:
152 bridgeId = self.get_node_tag(node, "bridgeId")
153 dataPlaneIntf = self.get_node_tag(node, "dataPlaneIntf")
154 dataPlaneIp = self.get_node_tag(node, "dataPlaneIp")
155 except:
156 logger.error("not adding node %s to the VTN configuration" % node.name)
157 continue
158
159 node_dict = {
160 "hostname": node.name,
161 "hostManagementIp": "%s/%s" % (nodeip, mgmtSubnetBits),
162 "bridgeId": bridgeId,
163 "dataPlaneIntf": dataPlaneIntf,
164 "dataPlaneIp": dataPlaneIp
165 }
166
167 # this one is optional
168 try:
169 node_dict["hostManagementIface"] = self.get_node_tag(node, "hostManagementIface")
170 except IndexError:
171 pass
172
173 data["apps"]["org.opencord.vtn"]["cordvtn"]["nodes"].append(node_dict)
174
Scott Baker7934f9c2017-09-21 11:44:44 -0700175 if not (data["apps"]["org.opencord.vtn"]["cordvtn"]["nodes"]):
176 raise DeferredException("Waiting for there to be valid nodes")
177
Andy Bavier7b321c52017-08-30 15:33:59 -0700178 # Generate apps->org.onosproject.cordvtn->cordvtn->publicGateways
179 # Pull the gateway information from Address Pool objects
180 for ap in AddressPool.objects.all():
181 if (not ap.gateway_ip) or (not ap.gateway_mac):
182 logger.info("Gateway_ip or gateway_mac is blank for addresspool %s. Skipping." % ap)
183 continue
184
185 gateway_dict = {
186 "gatewayIp": ap.gateway_ip,
187 "gatewayMac": ap.gateway_mac
188 }
189 data["apps"]["org.opencord.vtn"]["cordvtn"]["publicGateways"].append(gateway_dict)
190
191 if not AddressPool.objects.all().exists():
192 logger.info("No Address Pools present, not adding publicGateways to config")
193
194 return json.dumps(data, indent=4, sort_keys=True)
195
196 # TODO: Does this step execute every 5 seconds regardless of whether objects have changed?
197 # If so, what purpose does using watchers serve?
198
199 def call(self, **args):
200 vtn_service = VTNService.objects.all()
201 if not vtn_service:
202 raise Exception("No VTN Service")
203
204 vtn_service = vtn_service[0]
205
206 # Check for autogenerate attribute
207 netcfg = self.get_onos_netcfg(vtn_service)
208
209 service_instances = self.get_service_instances_who_want_config()
210 for service_instance in service_instances:
Scott Bakered645f52017-09-06 13:51:18 -0700211 something_changed = self.save_service_instance_attribute(service_instance, "rest_onos/v1/network/configuration/", netcfg)
212 if (something_changed):
213 # make sure we cause the ServiceInstance to be updated as well as the attribute
214 # TODO: revisit this after synchronizer multi-object-watching is complete
215 service_instance.save(update_fields=["updated"], always_update_timestamp=True)