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