blob: cc5d25e2c36abc2562ad784afbff1e52bb650bc8 [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):
104 o.config_fns = []
105 o.rest_configs = []
106 o.component_configs = []
107 o.files_dir = self.get_files_dir(o)
108
109 if not os.path.exists(o.files_dir):
110 os.makedirs(o.files_dir)
111
112 # Combine the service attributes with the tenant attributes. Tenant
113 # attribute can override service attributes.
114 attrs = o.provider_service.serviceattribute_dict
115 attrs.update(o.tenantattribute_dict)
116
117 ordered_attrs = attrs.keys()
118
119 onos = self.get_onos_service(o)
120 if onos.node_key:
121 file(os.path.join(o.files_dir, "node_key"),"w").write(onos.node_key)
122 o.node_key_fn="node_key"
123 else:
124 o.node_key_fn=None
125
126 o.early_rest_configs=[]
127 if ("cordvtn" in o.dependencies) and (not self.is_no_container(o)):
128 # For VTN, since it's running in a docker host container, we need
129 # to make sure it configures the cluster using the right ip addresses.
130 # NOTE: rest_onos/v1/cluster/configuration/ will reboot the cluster and
131 # must go first.
132 name="rest_onos/v1/cluster/configuration/"
133 value= self.get_cluster_configuration(o)
134 fn = name[5:].replace("/","_")
135 endpoint = name[5:]
136 file(os.path.join(o.files_dir, fn),"w").write(" " +value)
137 o.early_rest_configs.append( {"endpoint": endpoint, "fn": fn} )
138
Scott Baker7a327592016-06-20 17:34:06 -0700139 for name in attrs.keys():
140 value = attrs[name]
141 if name.startswith("config_"):
142 fn = name[7:] # .replace("_json",".json")
143 o.config_fns.append(fn)
144 file(os.path.join(o.files_dir, fn),"w").write(value)
145 if name.startswith("rest_"):
146 fn = name[5:].replace("/","_")
147 endpoint = name[5:]
148 # Ansible goes out of it's way to make our life difficult. If
149 # 'lookup' sees a file that it thinks contains json, then it'll
150 # insist on parsing and return a json object. We just want
151 # a string, so prepend a space and then strip the space off
152 # later.
153 file(os.path.join(o.files_dir, fn),"w").write(" " +value)
154 o.rest_configs.append( {"endpoint": endpoint, "fn": fn} )
155 if name.startswith("component_config"):
156 components = json.loads(value,object_pairs_hook=OrderedDict)
157 for component in components.keys():
158 config = components[component]
159 for key in config.keys():
160 config_val = config[key]
161 found = re.findall('<(.+?)>',config_val)
162 for x in found:
163 #Get value corresponding to that string
164 val = self.get_dynamic_parameter_value(o, x)
165 if val:
166 config_val = re.sub('<'+x+'>', val, config_val)
167 #TODO: else raise an exception?
168 o.component_configs.append( {"component": component, "config_params": "'{\""+key+"\":\""+config_val+"\"}'"} )
169
170 def prepare_record(self, o):
171 self.write_configs(o)
172
173 def get_extra_attributes_common(self, o):
174 fields = {}
175
176 # These are attributes that are not dependent on Instance. For example,
177 # REST API stuff.
178
179 onos = self.get_onos_service(o)
180
181 fields["files_dir"] = o.files_dir
182 fields["appname"] = o.name
183 fields["rest_configs"] = o.rest_configs
184 fields["rest_hostname"] = onos.rest_hostname
185 fields["rest_port"] = onos.rest_port
186
187 if o.dependencies:
188 fields["dependencies"] = [x.strip() for x in o.dependencies.split(",")]
189 else:
190 fields["dependencies"] = []
191
Andy Bavier4a503b12016-06-21 11:41:29 -0400192 if o.install_dependencies:
193 fields["install_dependencies"] = [x.strip() for x in o.install_dependencies.split(",")]
194 else:
195 fields["install_dependencies"] = []
196
Scott Baker7a327592016-06-20 17:34:06 -0700197 return fields
198
199 def get_extra_attributes_full(self, o):
200 instance = self.get_instance(o)
201
202 fields = self.get_extra_attributes_common(o)
203
204 fields["config_fns"] = o.config_fns
205 fields["early_rest_configs"] = o.early_rest_configs
206 fields["component_configs"] = o.component_configs
207 fields["node_key_fn"] = o.node_key_fn
208
Scott Baker7a327592016-06-20 17:34:06 -0700209 if (instance.isolation=="container"):
210 fields["ONOS_container"] = "%s-%s" % (instance.slice.name, str(instance.id))
211 else:
212 fields["ONOS_container"] = "ONOS"
213 return fields
214
215 def get_extra_attributes(self, o):
216 if self.is_no_container(o):
217 return self.get_extra_attributes_common(o)
218 else:
219 return self.get_extra_attributes_full(o)
220
221 def sync_fields(self, o, fields):
222 # the super causes the playbook to be run
223 super(SyncONOSApp, self).sync_fields(o, fields)
224
225 def run_playbook(self, o, fields):
226 if self.is_no_container(o):
227 # There is no machine to SSH to, so use the synchronizer's
228 # run_template method directly.
Sapan Bhatia81405522017-02-04 09:26:31 -0800229 run_template("sync_onosapp_nocontainer.yaml", fields, object=o)
Scott Baker7a327592016-06-20 17:34:06 -0700230 else:
231 super(SyncONOSApp, self).run_playbook(o, fields)
232
233 def delete_record(self, m):
234 pass