blob: 26bb49bc10a50e8b94f3931403d4aa5af6962e5e [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
10from django.db.models import F, Q
11from xos.config import Config
12from synchronizers.base.ansible import run_template
13from synchronizers.base.syncstep import SyncStep
14from synchronizers.base.ansible import run_template_ssh
15from synchronizers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
16from core.models import Service, Slice, Controller, ControllerSlice, ControllerUser, Node, TenantAttribute, Tag
17from services.onos.models import ONOSService, ONOSApp
18from xos.logger import Logger, logging
Scott Baker7a327592016-06-20 17:34:06 -070019
20# hpclibrary will be in steps/..
21parentdir = os.path.join(os.path.dirname(__file__),"..")
22sys.path.insert(0,parentdir)
23
24logger = Logger(level=logging.INFO)
25
26class SyncONOSApp(SyncInstanceUsingAnsible):
27 provides=[ONOSApp]
28 observes=ONOSApp
29 requested_interval=0
30 template_name = "sync_onosapp.yaml"
31 #service_key_name = "/opt/xos/synchronizers/onos/onos_key"
32
33 def __init__(self, *args, **kwargs):
34 super(SyncONOSApp, self).__init__(*args, **kwargs)
35
36 def fetch_pending(self, deleted):
37 if (not deleted):
38 objs = ONOSApp.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
39 else:
40 objs = ONOSApp.get_deleted_tenant_objects()
41
42 return objs
43
44 def get_instance(self, o):
45 # We assume the ONOS service owns a slice, so pick one of the instances
46 # inside that slice to sync to.
47
48 serv = self.get_onos_service(o)
49
50 if serv.no_container:
51 raise Exception("get_instance() was called on a service that was marked no_container")
52
53 if serv.slices.exists():
54 slice = serv.slices.all()[0]
55 if slice.instances.exists():
56 return slice.instances.all()[0]
57
58 return None
59
60 def get_onos_service(self, o):
61 if not o.provider_service:
62 return None
63
64 onoses = ONOSService.get_service_objects().filter(id=o.provider_service.id)
65 if not onoses:
66 return None
67
68 return onoses[0]
69
70 def is_no_container(self, o):
71 return self.get_onos_service(o).no_container
72
73 def skip_ansible_fields(self, o):
74 return self.is_no_container(o)
75
76 def get_files_dir(self, o):
77 if not hasattr(Config(), "observer_steps_dir"):
78 # make steps_dir mandatory; there's no valid reason for it to not
79 # be defined.
80 raise Exception("observer_steps_dir is not defined in config file")
81
82 step_dir = Config().observer_steps_dir
83
84 return os.path.join(step_dir, "..", "files", str(self.get_onos_service(o).id), o.name)
85
86 def get_cluster_configuration(self, o):
87 instance = self.get_instance(o)
88 if not instance:
89 raise Exception("No instance for ONOS App")
90 node_ips = [socket.gethostbyname(instance.node.name)]
91
92 ipPrefix = ".".join(node_ips[0].split(".")[:3]) + ".*"
93 result = '{ "nodes": ['
94 result = result + ",".join(['{ "ip": "%s"}' % ip for ip in node_ips])
95 result = result + '], "ipPrefix": "%s"}' % ipPrefix
96 return result
97
98 def get_dynamic_parameter_value(self, o, param):
99 instance = self.get_instance(o)
100 if not instance:
101 raise Exception("No instance for ONOS App")
102 if param == 'rabbit_host':
103 return instance.controller.rabbit_host
104 if param == 'rabbit_user':
105 return instance.controller.rabbit_user
106 if param == 'rabbit_password':
107 return instance.controller.rabbit_password
108 if param == 'keystone_tenant_id':
109 cslice = ControllerSlice.objects.get(slice=instance.slice)
110 if not cslice:
111 raise Exception("Controller slice object for %s does not exist" % instance.slice.name)
112 return cslice.tenant_id
113 if param == 'keystone_user_id':
114 cuser = ControllerUser.objects.get(user=instance.creator)
115 if not cuser:
116 raise Exception("Controller user object for %s does not exist" % instance.creator)
117 return cuser.kuser_id
118
Scott Baker7a327592016-06-20 17:34:06 -0700119 def write_configs(self, o):
120 o.config_fns = []
121 o.rest_configs = []
122 o.component_configs = []
123 o.files_dir = self.get_files_dir(o)
124
125 if not os.path.exists(o.files_dir):
126 os.makedirs(o.files_dir)
127
128 # Combine the service attributes with the tenant attributes. Tenant
129 # attribute can override service attributes.
130 attrs = o.provider_service.serviceattribute_dict
131 attrs.update(o.tenantattribute_dict)
132
133 ordered_attrs = attrs.keys()
134
135 onos = self.get_onos_service(o)
136 if onos.node_key:
137 file(os.path.join(o.files_dir, "node_key"),"w").write(onos.node_key)
138 o.node_key_fn="node_key"
139 else:
140 o.node_key_fn=None
141
142 o.early_rest_configs=[]
143 if ("cordvtn" in o.dependencies) and (not self.is_no_container(o)):
144 # For VTN, since it's running in a docker host container, we need
145 # to make sure it configures the cluster using the right ip addresses.
146 # NOTE: rest_onos/v1/cluster/configuration/ will reboot the cluster and
147 # must go first.
148 name="rest_onos/v1/cluster/configuration/"
149 value= self.get_cluster_configuration(o)
150 fn = name[5:].replace("/","_")
151 endpoint = name[5:]
152 file(os.path.join(o.files_dir, fn),"w").write(" " +value)
153 o.early_rest_configs.append( {"endpoint": endpoint, "fn": fn} )
154
Scott Baker7a327592016-06-20 17:34:06 -0700155 for name in attrs.keys():
156 value = attrs[name]
157 if name.startswith("config_"):
158 fn = name[7:] # .replace("_json",".json")
159 o.config_fns.append(fn)
160 file(os.path.join(o.files_dir, fn),"w").write(value)
161 if name.startswith("rest_"):
162 fn = name[5:].replace("/","_")
163 endpoint = name[5:]
164 # Ansible goes out of it's way to make our life difficult. If
165 # 'lookup' sees a file that it thinks contains json, then it'll
166 # insist on parsing and return a json object. We just want
167 # a string, so prepend a space and then strip the space off
168 # later.
169 file(os.path.join(o.files_dir, fn),"w").write(" " +value)
170 o.rest_configs.append( {"endpoint": endpoint, "fn": fn} )
171 if name.startswith("component_config"):
172 components = json.loads(value,object_pairs_hook=OrderedDict)
173 for component in components.keys():
174 config = components[component]
175 for key in config.keys():
176 config_val = config[key]
177 found = re.findall('<(.+?)>',config_val)
178 for x in found:
179 #Get value corresponding to that string
180 val = self.get_dynamic_parameter_value(o, x)
181 if val:
182 config_val = re.sub('<'+x+'>', val, config_val)
183 #TODO: else raise an exception?
184 o.component_configs.append( {"component": component, "config_params": "'{\""+key+"\":\""+config_val+"\"}'"} )
185
186 def prepare_record(self, o):
187 self.write_configs(o)
188
189 def get_extra_attributes_common(self, o):
190 fields = {}
191
192 # These are attributes that are not dependent on Instance. For example,
193 # REST API stuff.
194
195 onos = self.get_onos_service(o)
196
197 fields["files_dir"] = o.files_dir
198 fields["appname"] = o.name
199 fields["rest_configs"] = o.rest_configs
200 fields["rest_hostname"] = onos.rest_hostname
201 fields["rest_port"] = onos.rest_port
202
203 if o.dependencies:
204 fields["dependencies"] = [x.strip() for x in o.dependencies.split(",")]
205 else:
206 fields["dependencies"] = []
207
Andy Bavier4a503b12016-06-21 11:41:29 -0400208 if o.install_dependencies:
209 fields["install_dependencies"] = [x.strip() for x in o.install_dependencies.split(",")]
210 else:
211 fields["install_dependencies"] = []
212
Scott Baker7a327592016-06-20 17:34:06 -0700213 return fields
214
215 def get_extra_attributes_full(self, o):
216 instance = self.get_instance(o)
217
218 fields = self.get_extra_attributes_common(o)
219
220 fields["config_fns"] = o.config_fns
221 fields["early_rest_configs"] = o.early_rest_configs
222 fields["component_configs"] = o.component_configs
223 fields["node_key_fn"] = o.node_key_fn
224
Scott Baker7a327592016-06-20 17:34:06 -0700225 if (instance.isolation=="container"):
226 fields["ONOS_container"] = "%s-%s" % (instance.slice.name, str(instance.id))
227 else:
228 fields["ONOS_container"] = "ONOS"
229 return fields
230
231 def get_extra_attributes(self, o):
232 if self.is_no_container(o):
233 return self.get_extra_attributes_common(o)
234 else:
235 return self.get_extra_attributes_full(o)
236
237 def sync_fields(self, o, fields):
238 # the super causes the playbook to be run
239 super(SyncONOSApp, self).sync_fields(o, fields)
240
241 def run_playbook(self, o, fields):
242 if self.is_no_container(o):
243 # There is no machine to SSH to, so use the synchronizer's
244 # run_template method directly.
245 run_template("sync_onosapp_nocontainer.yaml", fields)
246 else:
247 super(SyncONOSApp, self).run_playbook(o, fields)
248
249 def delete_record(self, m):
250 pass