blob: cba829049dcefeff131105917e80a27f3b3f0428 [file] [log] [blame]
Scott Baker7a327592016-06-20 17:34:06 -07001import hashlib
2import os
3import socket
4import sys
5import base64
6import time
7import re
8import json
9from collections import OrderedDict
Scott Baker7a327592016-06-20 17:34:06 -070010from xos.config import Config
Scott Baker91ee5e42017-03-14 10:33:52 -070011from synchronizers.new_base.ansible_helper import run_template
12from synchronizers.new_base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
13from synchronizers.new_base.modelaccessor import *
Scott Baker7a327592016-06-20 17:34:06 -070014from xos.logger import Logger, logging
Scott Baker7a327592016-06-20 17:34:06 -070015
Scott Baker7a327592016-06-20 17:34:06 -070016logger = Logger(level=logging.INFO)
17
Matteo Scandolo0d41a862016-09-01 13:21:41 -070018
Scott Baker7a327592016-06-20 17:34:06 -070019class SyncONOSApp(SyncInstanceUsingAnsible):
20 provides=[ONOSApp]
21 observes=ONOSApp
22 requested_interval=0
23 template_name = "sync_onosapp.yaml"
Scott Baker7a327592016-06-20 17:34:06 -070024
25 def __init__(self, *args, **kwargs):
26 super(SyncONOSApp, self).__init__(*args, **kwargs)
27
Scott Baker7a327592016-06-20 17:34:06 -070028 def get_instance(self, o):
29 # We assume the ONOS service owns a slice, so pick one of the instances
30 # inside that slice to sync to.
31
32 serv = self.get_onos_service(o)
33
34 if serv.no_container:
35 raise Exception("get_instance() was called on a service that was marked no_container")
36
37 if serv.slices.exists():
38 slice = serv.slices.all()[0]
39 if slice.instances.exists():
40 return slice.instances.all()[0]
41
42 return None
43
44 def get_onos_service(self, o):
45 if not o.provider_service:
46 return None
47
Scott Baker91ee5e42017-03-14 10:33:52 -070048 onoses = ONOSService.objects.filter(id=o.provider_service.id)
Scott Baker7a327592016-06-20 17:34:06 -070049 if not onoses:
50 return None
51
52 return onoses[0]
53
54 def is_no_container(self, o):
55 return self.get_onos_service(o).no_container
56
57 def skip_ansible_fields(self, o):
58 return self.is_no_container(o)
59
60 def get_files_dir(self, o):
61 if not hasattr(Config(), "observer_steps_dir"):
62 # make steps_dir mandatory; there's no valid reason for it to not
63 # be defined.
64 raise Exception("observer_steps_dir is not defined in config file")
65
66 step_dir = Config().observer_steps_dir
67
68 return os.path.join(step_dir, "..", "files", str(self.get_onos_service(o).id), o.name)
69
70 def get_cluster_configuration(self, o):
71 instance = self.get_instance(o)
72 if not instance:
73 raise Exception("No instance for ONOS App")
74 node_ips = [socket.gethostbyname(instance.node.name)]
75
76 ipPrefix = ".".join(node_ips[0].split(".")[:3]) + ".*"
77 result = '{ "nodes": ['
78 result = result + ",".join(['{ "ip": "%s"}' % ip for ip in node_ips])
79 result = result + '], "ipPrefix": "%s"}' % ipPrefix
80 return result
81
82 def get_dynamic_parameter_value(self, o, param):
83 instance = self.get_instance(o)
84 if not instance:
85 raise Exception("No instance for ONOS App")
86 if param == 'rabbit_host':
87 return instance.controller.rabbit_host
88 if param == 'rabbit_user':
89 return instance.controller.rabbit_user
90 if param == 'rabbit_password':
91 return instance.controller.rabbit_password
92 if param == 'keystone_tenant_id':
93 cslice = ControllerSlice.objects.get(slice=instance.slice)
94 if not cslice:
95 raise Exception("Controller slice object for %s does not exist" % instance.slice.name)
96 return cslice.tenant_id
97 if param == 'keystone_user_id':
98 cuser = ControllerUser.objects.get(user=instance.creator)
99 if not cuser:
100 raise Exception("Controller user object for %s does not exist" % instance.creator)
101 return cuser.kuser_id
102
Scott Baker7a327592016-06-20 17:34:06 -0700103 def write_configs(self, o):
Scott Bakerf458f682017-03-14 17:10:36 -0700104 if hasattr(o, "create_attr"):
105 # new API doesn't let us setattr for things that don't already exist
106 o.create_attr("config_fns")
107 o.create_attr("rest_configs")
108 o.create_attr("component_configs")
109 o.create_attr("files_dir")
110 o.create_attr("node_key_fn")
111 o.create_attr("early_rest_configs")
112
Scott Baker7a327592016-06-20 17:34:06 -0700113 o.config_fns = []
114 o.rest_configs = []
115 o.component_configs = []
116 o.files_dir = self.get_files_dir(o)
117
118 if not os.path.exists(o.files_dir):
119 os.makedirs(o.files_dir)
120
121 # Combine the service attributes with the tenant attributes. Tenant
122 # attribute can override service attributes.
123 attrs = o.provider_service.serviceattribute_dict
124 attrs.update(o.tenantattribute_dict)
125
126 ordered_attrs = attrs.keys()
127
128 onos = self.get_onos_service(o)
129 if onos.node_key:
130 file(os.path.join(o.files_dir, "node_key"),"w").write(onos.node_key)
131 o.node_key_fn="node_key"
132 else:
133 o.node_key_fn=None
134
135 o.early_rest_configs=[]
136 if ("cordvtn" in o.dependencies) and (not self.is_no_container(o)):
137 # For VTN, since it's running in a docker host container, we need
138 # to make sure it configures the cluster using the right ip addresses.
139 # NOTE: rest_onos/v1/cluster/configuration/ will reboot the cluster and
140 # must go first.
141 name="rest_onos/v1/cluster/configuration/"
142 value= self.get_cluster_configuration(o)
143 fn = name[5:].replace("/","_")
144 endpoint = name[5:]
145 file(os.path.join(o.files_dir, fn),"w").write(" " +value)
146 o.early_rest_configs.append( {"endpoint": endpoint, "fn": fn} )
147
Scott Baker7a327592016-06-20 17:34:06 -0700148 for name in attrs.keys():
149 value = attrs[name]
150 if name.startswith("config_"):
151 fn = name[7:] # .replace("_json",".json")
152 o.config_fns.append(fn)
153 file(os.path.join(o.files_dir, fn),"w").write(value)
154 if name.startswith("rest_"):
155 fn = name[5:].replace("/","_")
156 endpoint = name[5:]
157 # Ansible goes out of it's way to make our life difficult. If
158 # 'lookup' sees a file that it thinks contains json, then it'll
159 # insist on parsing and return a json object. We just want
160 # a string, so prepend a space and then strip the space off
161 # later.
162 file(os.path.join(o.files_dir, fn),"w").write(" " +value)
163 o.rest_configs.append( {"endpoint": endpoint, "fn": fn} )
164 if name.startswith("component_config"):
165 components = json.loads(value,object_pairs_hook=OrderedDict)
166 for component in components.keys():
167 config = components[component]
168 for key in config.keys():
169 config_val = config[key]
170 found = re.findall('<(.+?)>',config_val)
171 for x in found:
172 #Get value corresponding to that string
173 val = self.get_dynamic_parameter_value(o, x)
174 if val:
175 config_val = re.sub('<'+x+'>', val, config_val)
176 #TODO: else raise an exception?
177 o.component_configs.append( {"component": component, "config_params": "'{\""+key+"\":\""+config_val+"\"}'"} )
178
179 def prepare_record(self, o):
180 self.write_configs(o)
181
182 def get_extra_attributes_common(self, o):
183 fields = {}
184
185 # These are attributes that are not dependent on Instance. For example,
186 # REST API stuff.
187
188 onos = self.get_onos_service(o)
189
190 fields["files_dir"] = o.files_dir
191 fields["appname"] = o.name
192 fields["rest_configs"] = o.rest_configs
193 fields["rest_hostname"] = onos.rest_hostname
194 fields["rest_port"] = onos.rest_port
195
196 if o.dependencies:
197 fields["dependencies"] = [x.strip() for x in o.dependencies.split(",")]
198 else:
199 fields["dependencies"] = []
200
Andy Bavier4a503b12016-06-21 11:41:29 -0400201 if o.install_dependencies:
202 fields["install_dependencies"] = [x.strip() for x in o.install_dependencies.split(",")]
203 else:
204 fields["install_dependencies"] = []
205
Scott Baker7a327592016-06-20 17:34:06 -0700206 return fields
207
208 def get_extra_attributes_full(self, o):
209 instance = self.get_instance(o)
210
211 fields = self.get_extra_attributes_common(o)
212
213 fields["config_fns"] = o.config_fns
214 fields["early_rest_configs"] = o.early_rest_configs
215 fields["component_configs"] = o.component_configs
216 fields["node_key_fn"] = o.node_key_fn
217
Scott Baker7a327592016-06-20 17:34:06 -0700218 if (instance.isolation=="container"):
219 fields["ONOS_container"] = "%s-%s" % (instance.slice.name, str(instance.id))
220 else:
221 fields["ONOS_container"] = "ONOS"
222 return fields
223
224 def get_extra_attributes(self, o):
225 if self.is_no_container(o):
226 return self.get_extra_attributes_common(o)
227 else:
228 return self.get_extra_attributes_full(o)
229
230 def sync_fields(self, o, fields):
231 # the super causes the playbook to be run
232 super(SyncONOSApp, self).sync_fields(o, fields)
233
234 def run_playbook(self, o, fields):
235 if self.is_no_container(o):
236 # There is no machine to SSH to, so use the synchronizer's
237 # run_template method directly.
Sapan Bhatia81405522017-02-04 09:26:31 -0800238 run_template("sync_onosapp_nocontainer.yaml", fields, object=o)
Scott Baker7a327592016-06-20 17:34:06 -0700239 else:
240 super(SyncONOSApp, self).run_playbook(o, fields)
241
242 def delete_record(self, m):
243 pass