Fix: Use "emu0" as shrot name for the default
[osm/vim-emu.git] / src / emuvim / dcemulator / node.py
1 # Copyright (c) 2015 SONATA-NFV and Paderborn University
2 # ALL RIGHTS RESERVED.
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 # Neither the name of the SONATA-NFV, Paderborn University
17 # nor the names of its contributors may be used to endorse or promote
18 # products derived from this software without specific prior written
19 # permission.
20 #
21 # This work has been performed in the framework of the SONATA project,
22 # funded by the European Commission under Grant number 671517 through
23 # the Horizon 2020 and 5G-PPP programmes. The authors would like to
24 # acknowledge the contributions of their colleagues of the SONATA
25 # partner consortium (www.sonata-nfv.eu).
26 from mininet.node import Docker
27 from mininet.link import Link
28 from emuvim.dcemulator.resourcemodel import NotEnoughResourcesAvailable
29 import logging
30
31
32 LOG = logging.getLogger("dcemulator.node")
33 LOG.setLevel(logging.DEBUG)
34
35
36 DCDPID_BASE = 1000 # start of switch dpid's used for data center switches
37 EXTSAPDPID_BASE = 2000 # start of switch dpid's used for external SAP switches
38
39
40 class EmulatorCompute(Docker):
41 """
42 Emulator specific compute node class.
43 Inherits from Containernet's Docker host class.
44 Represents a single container connected to a (logical)
45 data center.
46 We can add emulator specific helper functions to it.
47 """
48
49 def __init__(
50 self, name, dimage, **kwargs):
51 self.datacenter = kwargs.get("datacenter") # pointer to current DC
52 self.flavor_name = kwargs.get("flavor_name")
53 LOG.debug("Starting compute instance %r in data center %r" %
54 (name, str(self.datacenter)))
55 # call original Docker.__init__
56 Docker.__init__(self, name, dimage, **kwargs)
57
58 def getNetworkStatus(self):
59 """
60 Helper method to receive information about the virtual networks
61 this compute instance is connected to.
62 """
63 # get all links and find dc switch interface
64 networkStatusList = []
65 for i in self.intfList():
66 vnf_name = self.name
67 vnf_interface = str(i)
68 dc_port_name = self.datacenter.net.find_connected_dc_interface(
69 vnf_name, vnf_interface)
70 # format list of tuples (name, Ip, MAC, isUp, status, dc_portname)
71 intf_dict = {'intf_name': str(i), 'ip': "{0}/{1}".format(i.IP(), i.prefixLen), 'netmask': i.prefixLen,
72 'mac': i.MAC(), 'up': i.isUp(), 'status': i.status(), 'dc_portname': dc_port_name}
73 networkStatusList.append(intf_dict)
74
75 return networkStatusList
76
77 def getStatus(self):
78 """
79 Helper method to receive information about this compute instance.
80 """
81 status = {}
82 status["name"] = self.name
83 status["network"] = self.getNetworkStatus()
84 status["docker_network"] = self.dcinfo['NetworkSettings']['IPAddress']
85 status["image"] = self.dimage
86 status["flavor_name"] = self.flavor_name
87 status["cpu_quota"] = self.resources.get('cpu_quota')
88 status["cpu_period"] = self.resources.get('cpu_period')
89 status["cpu_shares"] = self.resources.get('cpu_shares')
90 status["cpuset"] = self.resources.get('cpuset_cpus')
91 status["mem_limit"] = self.resources.get('mem_limit')
92 status["memswap_limit"] = self.resources.get('memswap_limit')
93 status["state"] = self.dcli.inspect_container(self.dc)["State"]
94 status["id"] = self.dcli.inspect_container(self.dc)["Id"]
95 status["short_id"] = self.dcli.inspect_container(self.dc)["Id"][:12]
96 status["hostname"] = self.dcli.inspect_container(self.dc)[
97 "Config"]['Hostname']
98 status["datacenter"] = (None if self.datacenter is None
99 else self.datacenter.label)
100
101 return status
102
103
104 class EmulatorExtSAP(object):
105 """
106 Emulator specific class that defines an external service access point (SAP) for the service.
107 Inherits from Containernet's OVSBridge class.
108 Represents a single OVS switch connected to a (logical)
109 data center.
110 We can add emulator specific helper functions to it.
111 """
112
113 def __init__(self, sap_name, sap_net, datacenter, **kwargs):
114
115 self.datacenter = datacenter # pointer to current DC
116 self.net = self.datacenter.net
117 self.name = sap_name
118
119 LOG.debug("Starting ext SAP instance %r in data center %r" %
120 (sap_name, str(self.datacenter)))
121
122 # create SAP as separate OVS switch with an assigned ip address
123 self.ip = str(sap_net[1]) + '/' + str(sap_net.prefixlen)
124 self.subnet = sap_net
125 # allow connection to the external internet through the host
126 params = dict(NAT=True)
127 self.switch = self.net.addExtSAP(sap_name, self.ip, dpid=hex(
128 self._get_next_extSAP_dpid())[2:], **params)
129 self.switch.start()
130
131 def _get_next_extSAP_dpid(self):
132 global EXTSAPDPID_BASE
133 EXTSAPDPID_BASE += 1
134 return EXTSAPDPID_BASE
135
136 def getNetworkStatus(self):
137 """
138 Helper method to receive information about the virtual networks
139 this compute instance is connected to.
140 """
141 # get all links and find dc switch interface
142 networkStatusList = []
143 for i in self.switch.intfList():
144 vnf_name = self.name
145 vnf_interface = str(i)
146 if vnf_interface == 'lo':
147 continue
148 dc_port_name = self.datacenter.net.find_connected_dc_interface(
149 vnf_name, vnf_interface)
150 # format list of tuples (name, Ip, MAC, isUp, status, dc_portname)
151 intf_dict = {'intf_name': str(i), 'ip': self.ip, 'netmask': i.prefixLen, 'mac': i.MAC(
152 ), 'up': i.isUp(), 'status': i.status(), 'dc_portname': dc_port_name}
153 networkStatusList.append(intf_dict)
154
155 return networkStatusList
156
157 def getStatus(self):
158 return {
159 "name": self.switch.name,
160 "datacenter": self.datacenter.name,
161 "network": self.getNetworkStatus()
162 }
163
164
165 class Datacenter(object):
166 """
167 Represents a logical data center to which compute resources
168 (Docker containers) can be added at runtime.
169
170 Will also implement resource bookkeeping in later versions.
171 """
172
173 DC_COUNTER = 1
174
175 def __init__(self, label, metadata={}, resource_log_path=None):
176 self.net = None # DCNetwork to which we belong
177 # each node (DC) has a short internal name used by Mininet
178 # this is caused by Mininets naming limitations for swtiches etc.
179 self.name = "dc%d" % Datacenter.DC_COUNTER
180 Datacenter.DC_COUNTER += 1
181 # use this for user defined names that can be longer than self.name
182 self.label = label
183 # dict to store arbitrary metadata (e.g. latitude and longitude)
184 self.metadata = metadata
185 # path to which resource information should be logged (e.g. for
186 # experiments). None = no logging
187 self.resource_log_path = resource_log_path
188 # first prototype assumes one "bigswitch" per DC
189 self.switch = None
190 # keep track of running containers
191 self.containers = {}
192 # keep track of attached external access points
193 self.extSAPs = {}
194 # pointer to assigned resource model
195 self._resource_model = None
196
197 def __repr__(self):
198 return self.label
199
200 def _get_next_dc_dpid(self):
201 global DCDPID_BASE
202 DCDPID_BASE += 1
203 return DCDPID_BASE
204
205 def create(self):
206 """
207 Each data center is represented by a single switch to which
208 compute resources can be connected at run time.
209
210 TODO: This will be changed in the future to support multiple networks
211 per data center
212 """
213 self.switch = self.net.addSwitch(
214 "%s.s1" % self.name, dpid=hex(self._get_next_dc_dpid())[2:])
215 LOG.debug("created data center switch: %s" % str(self.switch))
216
217 def start(self):
218 pass
219
220 def startCompute(self, name, image=None, command=None, network=None,
221 flavor_name="tiny", properties=dict(), **params):
222 """
223 Create a new container as compute resource and connect it to this
224 data center.
225 :param name: name (string)
226 :param image: image name (string)
227 :param command: command (string)
228 :param network: networks list({"ip": "10.0.0.254/8"}, {"ip": "11.0.0.254/24"})
229 :param flavor_name: name of the flavor for this compute container
230 :param properties: dictionary of properties (key-value) that will be passed as environment variables
231 :return:
232 """
233 assert name is not None
234 default_net = {"id": "emu0"}
235 # no duplications
236 if name in [c.name for c in self.net.getAllContainers()]:
237 raise Exception("Container with name %s already exists." % name)
238 # set default parameter
239 if image is None:
240 image = "ubuntu:trusty"
241 if network is None:
242 network = {}
243 if isinstance(network, dict):
244 if len(network) < 1:
245 # create at least one default interface
246 network = default_net
247 # if we have only one network, put it in a list
248 network = [network]
249 if isinstance(network, list):
250 if len(network) < 1:
251 # create at least one default interface
252 network.append(default_net)
253
254 # apply hard-set resource limits=0
255 cpu_percentage = params.get('cpu_percent')
256 if cpu_percentage:
257 params['cpu_period'] = self.net.cpu_period
258 params['cpu_quota'] = self.net.cpu_period * float(cpu_percentage)
259
260 env = properties
261 properties['VNF_NAME'] = name
262 # create the container
263 d = self.net.addDocker(
264 str(name),
265 dimage=image,
266 dcmd=command,
267 datacenter=self,
268 flavor_name=flavor_name,
269 environment=env,
270 **params
271 )
272
273 # apply resource limits to container if a resource model is defined
274 if self._resource_model is not None:
275 try:
276 self._resource_model.allocate(d)
277 self._resource_model.write_allocation_log(
278 d, self.resource_log_path)
279 except NotEnoughResourcesAvailable as ex:
280 LOG.warning(
281 "Allocation of container %r was blocked by resource model." % name)
282 LOG.info(ex.message)
283 # ensure that we remove the container
284 self.net.removeDocker(name)
285 return None
286
287 # connect all given networks
288 # if no --net option is given, network = [{}], so 1 empty dict in the list
289 # this results in 1 default interface with a default ip address
290 for nw in network:
291 # clean up network configuration (e.g. RTNETLINK does not allow ':'
292 # in intf names
293 if nw.get("id") is not None:
294 nw["id"] = self._clean_ifname(nw["id"])
295 # TODO we cannot use TCLink here (see:
296 # https://github.com/mpeuster/containernet/issues/3)
297 self.net.addLink(d, self.switch, params1=nw,
298 cls=Link, intfName1=nw.get('id'))
299 # do bookkeeping
300 self.containers[name] = d
301 return d # we might use UUIDs for naming later on
302
303 def stopCompute(self, name):
304 """
305 Stop and remove a container from this data center.
306 """
307 assert name is not None
308 if name not in self.containers:
309 raise Exception("Container with name %s not found." % name)
310 LOG.debug("Stopping compute instance %r in data center %r" %
311 (name, str(self)))
312
313 # stop the monitored metrics
314 if self.net.monitor_agent is not None:
315 self.net.monitor_agent.stop_metric(name)
316
317 # call resource model and free resources
318 if self._resource_model is not None:
319 self._resource_model.free(self.containers[name])
320 self._resource_model.write_free_log(
321 self.containers[name], self.resource_log_path)
322
323 # remove links
324 self.net.removeLink(
325 link=None, node1=self.containers[name], node2=self.switch)
326
327 # remove container
328 self.net.removeDocker("%s" % (name))
329 del self.containers[name]
330
331 return True
332
333 def attachExternalSAP(self, sap_name, sap_net, **params):
334 extSAP = EmulatorExtSAP(sap_name, sap_net, self, **params)
335 # link SAP to the DC switch
336 self.net.addLink(extSAP.switch, self.switch, cls=Link)
337 self.extSAPs[sap_name] = extSAP
338
339 def removeExternalSAP(self, sap_name):
340 sap_switch = self.extSAPs[sap_name].switch
341 # sap_switch = self.net.getNodeByName(sap_name)
342 # remove link of SAP to the DC switch
343 self.net.removeLink(link=None, node1=sap_switch, node2=self.switch)
344 self.net.removeExtSAP(sap_name)
345 del self.extSAPs[sap_name]
346
347 def listCompute(self):
348 """
349 Return a list of all running containers assigned to this
350 data center.
351 """
352 return list(self.containers.itervalues())
353
354 def listExtSAPs(self):
355 """
356 Return a list of all external SAPs assigned to this
357 data center.
358 """
359 return list(self.extSAPs.itervalues())
360
361 def getStatus(self):
362 """
363 Return a dict with status information about this DC.
364 """
365 container_list = [name for name in self.containers]
366 ext_saplist = [sap_name for sap_name in self.extSAPs]
367 return {
368 "label": self.label,
369 "internalname": self.name,
370 "switch": self.switch.name,
371 "n_running_containers": len(self.containers),
372 "metadata": self.metadata,
373 "vnf_list": container_list,
374 "ext SAP list": ext_saplist
375 }
376
377 def assignResourceModel(self, rm):
378 """
379 Assign a resource model to this DC.
380 :param rm: a BaseResourceModel object
381 :return:
382 """
383 if self._resource_model is not None:
384 raise Exception(
385 "There is already an resource model assigned to this DC.")
386 self._resource_model = rm
387 self.net.rm_registrar.register(self, rm)
388 LOG.info("Assigned RM: %r to DC: %r" % (rm, self))
389
390 @staticmethod
391 def _clean_ifname(name):
392 """
393 Cleans up given string to be a
394 RTNETLINK compatible interface name.
395 :param name: string
396 :return: string
397 """
398 if name is None:
399 return "if0"
400 name = name.replace(":", "-")
401 name = name.replace(" ", "-")
402 name = name.replace(".", "-")
403 name = name.replace("_", "-")
404 return name