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