blob: 9da1ce5b30fada426629b11dcaf13769e32ebf35 [file] [log] [blame]
Matteo Scandolof0441032017-08-08 13:05:26 -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
Scott Bakerb63ea792016-08-11 10:24:48 -070017import hashlib
18import os
19import socket
20import sys
21import base64
22import time
Scott Bakerc808c672019-02-04 11:38:20 -080023from xossynchronizer.steps.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
24from xossynchronizer.steps.syncstep import DeferredException
25from xossynchronizer.ansible_helper import run_template_ssh
26from xossynchronizer.modelaccessor import *
27from xosconfig import Config
28from multistructlog import create_logger
29
30log = create_logger(Config().get('logging'))
Scott Bakerb63ea792016-08-11 10:24:48 -070031
32# hpclibrary will be in steps/..
33parentdir = os.path.join(os.path.dirname(__file__),"..")
34sys.path.insert(0,parentdir)
35
Scott Bakerb63ea792016-08-11 10:24:48 -070036class SyncContainer(SyncInstanceUsingAnsible):
37 provides=[Instance]
38 observes=Instance
39 requested_interval=0
40 template_name = "sync_container.yaml"
41
42 def __init__(self, *args, **kwargs):
43 super(SyncContainer, self).__init__(*args, **kwargs)
44
45 def fetch_pending(self, deletion=False):
46 objs = super(SyncContainer, self).fetch_pending(deletion)
47 objs = [x for x in objs if x.isolation in ["container", "container_vm"]]
48 return objs
49
50 def get_instance_port(self, container_port):
51 for p in container_port.network.links.all():
Scott Bakeraf599eb2017-03-21 12:43:26 -070052 if (p.instance) and (p.instance.isolation=="vm") and (p.instance.node.id == container_port.instance.node.id) and (p.mac):
Scott Bakerb63ea792016-08-11 10:24:48 -070053 return p
54 return None
55
56 def get_parent_port_mac(self, instance, port):
57 if not instance.parent:
58 raise Exception("instance has no parent")
59 for parent_port in instance.parent.ports.all():
60 if parent_port.network == port.network:
61 if not parent_port.mac:
62 raise DeferredException("parent port on network %s does not have mac yet" % parent_port.network.name)
63 return parent_port.mac
64 raise Exception("failed to find corresponding parent port for network %s" % port.network.name)
65
66 def get_ports(self, o):
67 i=0
68 ports = []
69 if (o.slice.network in ["host", "bridged"]):
70 pass # no ports in host or bridged mode
71 else:
72 for port in o.ports.all():
73 if (not port.ip):
74 # 'unmanaged' ports may have an ip, but no mac
75 # XXX: are there any ports that have a mac but no ip?
76 raise DeferredException("Port on network %s is not yet ready" % port.network.name)
77
78 pd={}
79 pd["mac"] = port.mac or ""
80 pd["ip"] = port.ip or ""
81 pd["xos_network_id"] = port.network.id
82
83 if port.network.name == "wan_network":
84 if port.ip:
85 (a, b, c, d) = port.ip.split('.')
86 pd["mac"] = "02:42:%02x:%02x:%02x:%02x" % (int(a), int(b), int(c), int(d))
87
88
89 if o.isolation == "container":
90 # container on bare metal
91 instance_port = self.get_instance_port(port)
92 if not instance_port:
93 raise DeferredException("No instance on slice for port on network %s" % port.network.name)
94
95 pd["snoop_instance_mac"] = instance_port.mac
96 pd["snoop_instance_id"] = instance_port.instance.instance_id
97 pd["src_device"] = ""
98 pd["bridge"] = "br-int"
99 else:
100 # container in VM
101 pd["snoop_instance_mac"] = ""
102 pd["snoop_instance_id"] = ""
103 pd["parent_mac"] = self.get_parent_port_mac(o, port)
104 pd["bridge"] = ""
105
106 for (k,v) in port.get_parameters().items():
107 pd[k] = v
108
109 ports.append(pd)
110
111 # for any ports that don't have a device, assign one
112 used_ports = [x["device"] for x in ports if ("device" in x)]
113 avail_ports = ["eth%d"%i for i in range(0,64) if ("eth%d"%i not in used_ports)]
114 for port in ports:
115 if not port.get("device",None):
116 port["device"] = avail_ports.pop(0)
117
118 return ports
119
120 def get_extra_attributes(self, o):
121 fields={}
122 fields["ansible_tag"] = "container-%s" % str(o.id)
123 if o.image.tag:
124 fields["docker_image"] = o.image.path + ":" + o.image.tag
125 else:
126 fields["docker_image"] = o.image.path
127 fields["ports"] = self.get_ports(o)
128 if o.volumes:
129 fields["volumes"] = [x.strip() for x in o.volumes.split(",")]
130 else:
131 fields["volumes"] = ""
132 fields["network_method"] = o.slice.network or "default"
133 return fields
134
135 def sync_record(self, o):
Scott Bakerc808c672019-02-04 11:38:20 -0800136 log.info("sync'ing object %s" % str(o),extra=o.tologdict())
Scott Bakerb63ea792016-08-11 10:24:48 -0700137
138 fields = self.get_ansible_fields(o)
139
140 # If 'o' defines a 'sync_attributes' list, then we'll copy those
141 # attributes into the Ansible recipe's field list automatically.
142 if hasattr(o, "sync_attributes"):
143 for attribute_name in o.sync_attributes:
144 fields[attribute_name] = getattr(o, attribute_name)
145
146 fields.update(self.get_extra_attributes(o))
147
148 self.run_playbook(o, fields)
149
150 o.instance_id = fields["container_name"]
151 o.instance_name = fields["container_name"]
152
153 o.save()
154
155 def delete_record(self, o):
Scott Bakerc808c672019-02-04 11:38:20 -0800156 log.info("delete'ing object %s" % str(o),extra=o.tologdict())
Scott Bakerb63ea792016-08-11 10:24:48 -0700157
158 fields = self.get_ansible_fields(o)
159
160 # If 'o' defines a 'sync_attributes' list, then we'll copy those
161 # attributes into the Ansible recipe's field list automatically.
162 if hasattr(o, "sync_attributes"):
163 for attribute_name in o.sync_attributes:
164 fields[attribute_name] = getattr(o, attribute_name)
165
166 fields.update(self.get_extra_attributes(o))
167
168 self.run_playbook(o, fields, "teardown_container.yaml")
169
170 def run_playbook(self, o, fields, template_name=None):
171 if not template_name:
172 template_name = self.template_name
173 tStart = time.time()
Sapan Bhatiac76afbe2017-02-04 09:26:31 -0800174 run_template_ssh(template_name, fields, path="container", object=o)
Scott Bakerc808c672019-02-04 11:38:20 -0800175 log.info("playbook execution time %d" % int(time.time()-tStart),extra=o.tologdict())
Scott Bakerb63ea792016-08-11 10:24:48 -0700176
177