blob: e56892a2d5910307abe004e3ba9c16c446e84db4 [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 *
Matteo Scandolo10f460e2018-06-11 13:31:31 -070026from xosconfig import Config
27from multistructlog import create_logger
Andy Bavier7b321c52017-08-30 15:33:59 -070028
Matteo Scandolo10f460e2018-06-11 13:31:31 -070029log = create_logger(Config().get('logging'))
Andy Bavier7b321c52017-08-30 15:33:59 -070030
31class SyncONOSNetcfg(SyncStep):
32 provides=[VTNService]
33 observes=VTNService
34 watches=[ModelLink(Node,via='node'), ModelLink(AddressPool,via='addresspool')]
35 requested_interval=0
36
37 def __init__(self, **args):
38 SyncStep.__init__(self, **args)
39
40 def handle_watched_object(self, o):
Matteo Scandolo10f460e2018-06-11 13:31:31 -070041 log.info("handle_watched_object is invoked for object %s" % (str(o)),extra=o.tologdict())
Andy Bavier7b321c52017-08-30 15:33:59 -070042 if (type(o) is Node): # For Node add/delete/modify
43 self.call()
44 if (type(o) is AddressPool): # For public gateways
45 self.call()
46
Andy Bavier7b321c52017-08-30 15:33:59 -070047 def get_service_instances_who_want_config(self):
48 service_instances = []
49 # attribute is comma-separated list
50 for ta in ServiceInstanceAttribute.objects.filter(name="autogenerate"):
51 if ta.value:
52 for config in ta.value.split(','):
53 if config == "vtn-network-cfg":
54 service_instances.append(ta.service_instance)
55 return service_instances
56
57 def save_service_instance_attribute(self, service_instance, name, value):
Matteo Scandolo10f460e2018-06-11 13:31:31 -070058
59 vtn_onos_app = [si for si in service_instance.eastbound_service_instances if "ONOSApp" in si.leaf_model.class_names][0]
60
Scott Bakered645f52017-09-06 13:51:18 -070061 # returns True if something changed
62 something_changed=False
Matteo Scandolo10f460e2018-06-11 13:31:31 -070063 tas = ServiceInstanceAttribute.objects.filter(service_instance_id=vtn_onos_app.id, name=name)
Andy Bavier7b321c52017-08-30 15:33:59 -070064 if tas:
65 ta = tas[0]
66 if ta.value != value:
Matteo Scandolo10f460e2018-06-11 13:31:31 -070067 log.info("updating %s with attribute" % name)
Andy Bavier7b321c52017-08-30 15:33:59 -070068 ta.value = value
Scott Bakered645f52017-09-06 13:51:18 -070069 ta.save(update_fields=["value", "updated"], always_update_timestamp=True)
70 something_changed = True
Andy Bavier7b321c52017-08-30 15:33:59 -070071 else:
Matteo Scandolo10f460e2018-06-11 13:31:31 -070072 log.info("saving autogenerated config %s" % name)
73 ta = model_accessor.create_obj(ServiceInstanceAttribute, service_instance=vtn_onos_app, name=name, value=value)
Andy Bavier7b321c52017-08-30 15:33:59 -070074 ta.save()
Scott Bakered645f52017-09-06 13:51:18 -070075 something_changed = True
76 return something_changed
Andy Bavier7b321c52017-08-30 15:33:59 -070077
78 # This function currently assumes a single Deployment and Site
79 def get_onos_netcfg(self, vtn):
80 privateGatewayMac = vtn.privateGatewayMac
81 localManagementIp = vtn.localManagementIp
82 ovsdbPort = vtn.ovsdbPort
83 sshPort = vtn.sshPort
84 sshUser = vtn.sshUser
85 sshKeyFile = vtn.sshKeyFile
86 mgmtSubnetBits = vtn.mgmtSubnetBits
87 xosEndpoint = vtn.xosEndpoint
88 xosUser = vtn.xosUser
89 xosPassword = vtn.xosPassword
90
91 controllerPort = vtn.controllerPort
92 if ":" in controllerPort:
93 (c_hostname, c_port) = controllerPort.split(":",1)
94 controllerPort = socket.gethostbyname(c_hostname) + ":" + c_port
95 else:
96 controllerPort = ":" + controllerPort
97
98 data = {
99 "apps" : {
100 "org.opencord.vtn" : {
101 "cordvtn" : {
102 "privateGatewayMac" : privateGatewayMac,
103 "localManagementIp": localManagementIp,
104 "ovsdbPort": ovsdbPort,
105 "ssh": {
106 "sshPort": sshPort,
107 "sshUser": sshUser,
108 "sshKeyFile": sshKeyFile
109 },
110 "xos": {
111 "endpoint": xosEndpoint,
112 "user": xosUser,
113 "password": xosPassword
114 },
115 "publicGateways": [],
116 "nodes" : [],
117 "controllers": [controllerPort]
118 }
119 }
120 }
121 }
122
123 # Generate apps->org.opencord.vtn->cordvtn->openstack
124 controllers = Controller.objects.all()
125 if controllers:
126 controller = controllers[0]
127 keystone_server = controller.auth_url
128 user_name = controller.admin_user
129 tenant_name = controller.admin_tenant
130 password = controller.admin_password
131 openstack = {
132 "endpoint": keystone_server,
133 "tenant": tenant_name,
134 "user": user_name,
135 "password": password
136 }
137 data["apps"]["org.opencord.vtn"]["cordvtn"]["openstack"] = openstack
138
139 # Generate apps->org.opencord.vtn->cordvtn->nodes
140 nodes = Node.objects.all()
Matteo Scandolocf9102a2017-12-07 08:31:54 -0800141
Andy Bavier7b321c52017-08-30 15:33:59 -0700142 for node in nodes:
143 try:
144 nodeip = socket.gethostbyname(node.name)
145 except socket.gaierror:
Matteo Scandolo10f460e2018-06-11 13:31:31 -0700146 log.warn("unable to resolve hostname %s: node will not be added to config"
Andy Bavier7b321c52017-08-30 15:33:59 -0700147 % node.name)
148 continue
149
150 try:
Matteo Scandolocf9102a2017-12-07 08:31:54 -0800151 bridgeId = node.bridgeId
152 dataPlaneIntf = node.dataPlaneIntf
153 dataPlaneIp = node.dataPlaneIp
Andy Bavier7b321c52017-08-30 15:33:59 -0700154 except:
Matteo Scandolo10f460e2018-06-11 13:31:31 -0700155 log.error("not adding node %s to the VTN configuration" % node.name)
Andy Bavier7b321c52017-08-30 15:33:59 -0700156 continue
157
158 node_dict = {
159 "hostname": node.name,
160 "hostManagementIp": "%s/%s" % (nodeip, mgmtSubnetBits),
161 "bridgeId": bridgeId,
162 "dataPlaneIntf": dataPlaneIntf,
163 "dataPlaneIp": dataPlaneIp
164 }
165
166 # this one is optional
167 try:
Matteo Scandolocf9102a2017-12-07 08:31:54 -0800168 node_dict["hostManagementIface"] = node.hostManagementIface
169 except AttributeError:
Andy Bavier7b321c52017-08-30 15:33:59 -0700170 pass
171
172 data["apps"]["org.opencord.vtn"]["cordvtn"]["nodes"].append(node_dict)
173
Scott Baker7934f9c2017-09-21 11:44:44 -0700174 if not (data["apps"]["org.opencord.vtn"]["cordvtn"]["nodes"]):
175 raise DeferredException("Waiting for there to be valid nodes")
176
Andy Bavier7b321c52017-08-30 15:33:59 -0700177 # Generate apps->org.onosproject.cordvtn->cordvtn->publicGateways
178 # Pull the gateway information from Address Pool objects
179 for ap in AddressPool.objects.all():
180 if (not ap.gateway_ip) or (not ap.gateway_mac):
Matteo Scandolo10f460e2018-06-11 13:31:31 -0700181 log.info("Gateway_ip or gateway_mac is blank for addresspool %s. Skipping." % ap)
Andy Bavier7b321c52017-08-30 15:33:59 -0700182 continue
183
184 gateway_dict = {
185 "gatewayIp": ap.gateway_ip,
186 "gatewayMac": ap.gateway_mac
187 }
188 data["apps"]["org.opencord.vtn"]["cordvtn"]["publicGateways"].append(gateway_dict)
189
190 if not AddressPool.objects.all().exists():
Matteo Scandolo10f460e2018-06-11 13:31:31 -0700191 log.info("No Address Pools present, not adding publicGateways to config")
Andy Bavier7b321c52017-08-30 15:33:59 -0700192
193 return json.dumps(data, indent=4, sort_keys=True)
194
195 # TODO: Does this step execute every 5 seconds regardless of whether objects have changed?
196 # If so, what purpose does using watchers serve?
197
198 def call(self, **args):
199 vtn_service = VTNService.objects.all()
200 if not vtn_service:
201 raise Exception("No VTN Service")
202
203 vtn_service = vtn_service[0]
204
205 # Check for autogenerate attribute
206 netcfg = self.get_onos_netcfg(vtn_service)
207
208 service_instances = self.get_service_instances_who_want_config()
209 for service_instance in service_instances:
Matteo Scandolo10f460e2018-06-11 13:31:31 -0700210 something_changed = self.save_service_instance_attribute(service_instance, "onos/v1/network/configuration/", netcfg)
Scott Bakered645f52017-09-06 13:51:18 -0700211 if (something_changed):
212 # make sure we cause the ServiceInstance to be updated as well as the attribute
213 # TODO: revisit this after synchronizer multi-object-watching is complete
214 service_instance.save(update_fields=["updated"], always_update_timestamp=True)