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