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