blob: 2a211d7f7a532b102496a790b9cd1cfd798c984e [file] [log] [blame]
peusterm72f09882018-05-15 17:10:27 +02001# 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).
26from mininet.node import Docker
peustermea8db832016-03-08 10:25:58 +010027from mininet.link import Link
peusterma41f7862016-04-27 11:01:24 +020028from emuvim.dcemulator.resourcemodel import NotEnoughResourcesAvailable
peustermcbcd4c22015-12-28 11:33:42 +010029import logging
stevenvanrossem86e64a02017-04-13 02:21:45 +020030
peustermcbcd4c22015-12-28 11:33:42 +010031
peustermf9a817d2016-07-18 09:06:04 +020032LOG = logging.getLogger("dcemulator.node")
peusterm3444ae42016-03-16 20:46:41 +010033LOG.setLevel(logging.DEBUG)
34
peustermcbcd4c22015-12-28 11:33:42 +010035
36DCDPID_BASE = 1000 # start of switch dpid's used for data center switches
stevenvanrossem86e64a02017-04-13 02:21:45 +020037EXTSAPDPID_BASE = 2000 # start of switch dpid's used for external SAP switches
peustermcbcd4c22015-12-28 11:33:42 +010038
peusterm72f09882018-05-15 17:10:27 +020039
peusterm7aae6852016-01-12 14:53:18 +010040class EmulatorCompute(Docker):
41 """
42 Emulator specific compute node class.
peusterm5877ea22016-05-11 13:44:59 +020043 Inherits from Containernet's Docker host class.
peusterm7aae6852016-01-12 14:53:18 +010044 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):
peusterm42f08be2016-03-10 21:56:34 +010051 self.datacenter = kwargs.get("datacenter") # pointer to current DC
52 self.flavor_name = kwargs.get("flavor_name")
peusterm72f09882018-05-15 17:10:27 +020053 LOG.debug("Starting compute instance %r in data center %r" %
54 (name, str(self.datacenter)))
peusterm7aae6852016-01-12 14:53:18 +010055 # 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 """
stevenvanrossem566779d2016-11-07 06:33:44 +010063 # 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)
peusterm72f09882018-05-15 17:10:27 +020068 dc_port_name = self.datacenter.net.find_connected_dc_interface(
69 vnf_name, vnf_interface)
stevenvanrossem566779d2016-11-07 06:33:44 +010070 # format list of tuples (name, Ip, MAC, isUp, status, dc_portname)
peusterm72f09882018-05-15 17:10:27 +020071 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}
stevenvanrossem566779d2016-11-07 06:33:44 +010073 networkStatusList.append(intf_dict)
74
75 return networkStatusList
peusterm7aae6852016-01-12 14:53:18 +010076
77 def getStatus(self):
78 """
79 Helper method to receive information about this compute instance.
80 """
peusterm056fd452016-01-12 15:32:25 +010081 status = {}
82 status["name"] = self.name
83 status["network"] = self.getNetworkStatus()
stevenvanrosseme66ef122016-05-03 11:22:54 +020084 status["docker_network"] = self.dcinfo['NetworkSettings']['IPAddress']
peusterm056fd452016-01-12 15:32:25 +010085 status["image"] = self.dimage
peusterm36c070c2016-04-16 17:39:01 +020086 status["flavor_name"] = self.flavor_name
stevenvanrossem08272492017-02-10 17:18:44 +010087 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')
peusterm056fd452016-01-12 15:32:25 +010093 status["state"] = self.dcli.inspect_container(self.dc)["State"]
94 status["id"] = self.dcli.inspect_container(self.dc)["Id"]
stevenvanrossem8a9df3f2017-01-27 22:35:04 +010095 status["short_id"] = self.dcli.inspect_container(self.dc)["Id"][:12]
peusterm72f09882018-05-15 17:10:27 +020096 status["hostname"] = self.dcli.inspect_container(self.dc)[
97 "Config"]['Hostname']
peusterm2ec74e12016-01-13 11:17:53 +010098 status["datacenter"] = (None if self.datacenter is None
peusterma47db032016-02-04 14:55:29 +010099 else self.datacenter.label)
stevenvanrossem18165082017-04-07 17:20:50 +0200100
peusterm056fd452016-01-12 15:32:25 +0100101 return status
peusterm7aae6852016-01-12 14:53:18 +0100102
103
stevenvanrossem17b6e882017-05-04 16:51:34 +0200104class 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
peusterm72f09882018-05-15 17:10:27 +0200119 LOG.debug("Starting ext SAP instance %r in data center %r" %
120 (sap_name, str(self.datacenter)))
stevenvanrossem17b6e882017-05-04 16:51:34 +0200121
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)
peusterm72f09882018-05-15 17:10:27 +0200127 self.switch = self.net.addExtSAP(sap_name, self.ip, dpid=hex(
128 self._get_next_extSAP_dpid())[2:], **params)
stevenvanrossem17b6e882017-05-04 16:51:34 +0200129 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
peusterm72f09882018-05-15 17:10:27 +0200148 dc_port_name = self.datacenter.net.find_connected_dc_interface(
149 vnf_name, vnf_interface)
stevenvanrossem17b6e882017-05-04 16:51:34 +0200150 # format list of tuples (name, Ip, MAC, isUp, status, dc_portname)
peusterm72f09882018-05-15 17:10:27 +0200151 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}
stevenvanrossem17b6e882017-05-04 16:51:34 +0200153 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
peusterm72f09882018-05-15 17:10:27 +0200164
peustermcbcd4c22015-12-28 11:33:42 +0100165class Datacenter(object):
166 """
167 Represents a logical data center to which compute resources
168 (Docker containers) can be added at runtime.
peusterme4e89d32016-01-07 09:14:54 +0100169
170 Will also implement resource bookkeeping in later versions.
peustermcbcd4c22015-12-28 11:33:42 +0100171 """
172
peusterma47db032016-02-04 14:55:29 +0100173 DC_COUNTER = 1
174
peusterm60bf8b82016-04-06 14:12:35 +0200175 def __init__(self, label, metadata={}, resource_log_path=None):
peustermcbcd4c22015-12-28 11:33:42 +0100176 self.net = None # DCNetwork to which we belong
peusterma47db032016-02-04 14:55:29 +0100177 # 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
peusterm53504942016-02-04 16:09:28 +0100181 # use this for user defined names that can be longer than self.name
edmaas7e084ea2016-11-28 13:50:23 +0100182 self.label = label
peusterm53504942016-02-04 16:09:28 +0100183 # dict to store arbitrary metadata (e.g. latitude and longitude)
184 self.metadata = metadata
peusterm72f09882018-05-15 17:10:27 +0200185 # path to which resource information should be logged (e.g. for
186 # experiments). None = no logging
peusterm60bf8b82016-04-06 14:12:35 +0200187 self.resource_log_path = resource_log_path
peusterm42f08be2016-03-10 21:56:34 +0100188 # first prototype assumes one "bigswitch" per DC
189 self.switch = None
190 # keep track of running containers
191 self.containers = {}
stevenvanrossem17b6e882017-05-04 16:51:34 +0200192 # keep track of attached external access points
193 self.extSAPs = {}
peusterm42f08be2016-03-10 21:56:34 +0100194 # pointer to assigned resource model
195 self._resource_model = None
peustermcbcd4c22015-12-28 11:33:42 +0100196
peusterme26487b2016-03-08 14:00:21 +0100197 def __repr__(self):
198 return self.label
199
peustermcbcd4c22015-12-28 11:33:42 +0100200 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
peusterm9c252b62016-01-06 16:59:53 +0100210 TODO: This will be changed in the future to support multiple networks
peustermcbcd4c22015-12-28 11:33:42 +0100211 per data center
212 """
peusterm293cbc32016-01-13 17:05:28 +0100213 self.switch = self.net.addSwitch(
peustermcbcd4c22015-12-28 11:33:42 +0100214 "%s.s1" % self.name, dpid=hex(self._get_next_dc_dpid())[2:])
peusterm3444ae42016-03-16 20:46:41 +0100215 LOG.debug("created data center switch: %s" % str(self.switch))
peustermcbcd4c22015-12-28 11:33:42 +0100216
217 def start(self):
218 pass
219
peusterm72f09882018-05-15 17:10:27 +0200220 def startCompute(self, name, image=None, command=None, network=None,
221 flavor_name="tiny", properties=dict(), **params):
peusterme4e89d32016-01-07 09:14:54 +0100222 """
223 Create a new container as compute resource and connect it to this
224 data center.
peusterm7f8e8402016-02-28 18:38:10 +0100225 :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"})
peusterm42f08be2016-03-10 21:56:34 +0100229 :param flavor_name: name of the flavor for this compute container
splietker7b38ee12017-06-28 17:24:01 +0200230 :param properties: dictionary of properties (key-value) that will be passed as environment variables
peusterm7f8e8402016-02-28 18:38:10 +0100231 :return:
peusterme4e89d32016-01-07 09:14:54 +0100232 """
peusterm4e98b632016-01-12 14:08:07 +0100233 assert name is not None
peusterm2bbd4592019-06-12 10:25:38 +0200234 default_net = {"id": "emu0"}
peusterm9165ef92016-01-13 13:50:39 +0100235 # no duplications
peustermbd44f4a2016-01-13 14:53:30 +0100236 if name in [c.name for c in self.net.getAllContainers()]:
peusterm9165ef92016-01-13 13:50:39 +0100237 raise Exception("Container with name %s already exists." % name)
peusterm4e98b632016-01-12 14:08:07 +0100238 # set default parameter
239 if image is None:
peusterm0dc3ae02016-04-27 09:33:28 +0200240 image = "ubuntu:trusty"
peusterm4e98b632016-01-12 14:08:07 +0100241 if network is None:
peusterm2bbd4592019-06-12 10:25:38 +0200242 network = {}
peusterm7f8e8402016-02-28 18:38:10 +0100243 if isinstance(network, dict):
peusterm2bbd4592019-06-12 10:25:38 +0200244 if len(network) < 1:
245 # create at least one default interface
246 network = default_net
peusterm72f09882018-05-15 17:10:27 +0200247 # if we have only one network, put it in a list
248 network = [network]
peusterm7f8e8402016-02-28 18:38:10 +0100249 if isinstance(network, list):
250 if len(network) < 1:
peusterm2bbd4592019-06-12 10:25:38 +0200251 # create at least one default interface
252 network.append(default_net)
peusterm7f8e8402016-02-28 18:38:10 +0100253
stevenvanrossemb3f34172016-11-16 23:30:57 +0100254 # apply hard-set resource limits=0
stevenvanrosseme8d86282017-01-28 00:52:22 +0100255 cpu_percentage = params.get('cpu_percent')
stevenvanrossemb3f34172016-11-16 23:30:57 +0100256 if cpu_percentage:
stevenvanrosseme8d86282017-01-28 00:52:22 +0100257 params['cpu_period'] = self.net.cpu_period
258 params['cpu_quota'] = self.net.cpu_period * float(cpu_percentage)
stevenvanrossemb3f34172016-11-16 23:30:57 +0100259
splietker7b38ee12017-06-28 17:24:01 +0200260 env = properties
261 properties['VNF_NAME'] = name
peusterm7f8e8402016-02-28 18:38:10 +0100262 # create the container
peusterm42f08be2016-03-10 21:56:34 +0100263 d = self.net.addDocker(
peusterm9467ee52018-12-18 16:22:46 +0100264 str(name),
peusterm42f08be2016-03-10 21:56:34 +0100265 dimage=image,
266 dcmd=command,
267 datacenter=self,
stevenvanrossemb3f34172016-11-16 23:30:57 +0100268 flavor_name=flavor_name,
peusterm72f09882018-05-15 17:10:27 +0200269 environment=env,
edmaas7e084ea2016-11-28 13:50:23 +0100270 **params
peusterm71b3a2f2016-03-19 12:56:11 +0100271 )
peustermd18559d2016-04-16 04:59:23 +0200272
273 # apply resource limits to container if a resource model is defined
274 if self._resource_model is not None:
peusterma41f7862016-04-27 11:01:24 +0200275 try:
276 self._resource_model.allocate(d)
peusterm72f09882018-05-15 17:10:27 +0200277 self._resource_model.write_allocation_log(
278 d, self.resource_log_path)
peusterma41f7862016-04-27 11:01:24 +0200279 except NotEnoughResourcesAvailable as ex:
peusterm72f09882018-05-15 17:10:27 +0200280 LOG.warning(
281 "Allocation of container %r was blocked by resource model." % name)
peusterma41f7862016-04-27 11:01:24 +0200282 LOG.info(ex.message)
283 # ensure that we remove the container
284 self.net.removeDocker(name)
285 return None
peustermd18559d2016-04-16 04:59:23 +0200286
peusterm7f8e8402016-02-28 18:38:10 +0100287 # connect all given networks
stevenvanrossem14c89052016-04-10 23:49:59 +0200288 # 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
peusterm7f8e8402016-02-28 18:38:10 +0100290 for nw in network:
peusterm72f09882018-05-15 17:10:27 +0200291 # clean up network configuration (e.g. RTNETLINK does not allow ':'
292 # in intf names
peusterm761c14d2016-07-19 09:31:19 +0200293 if nw.get("id") is not None:
294 nw["id"] = self._clean_ifname(nw["id"])
peusterm72f09882018-05-15 17:10:27 +0200295 # 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'))
peusterm2ec74e12016-01-13 11:17:53 +0100299 # do bookkeeping
peusterma2ad9ff2016-01-11 17:10:07 +0100300 self.containers[name] = d
peustermfa4bcc72016-01-15 11:08:09 +0100301 return d # we might use UUIDs for naming later on
peustermcbcd4c22015-12-28 11:33:42 +0100302
peusterm7aae6852016-01-12 14:53:18 +0100303 def stopCompute(self, name):
peusterma2ad9ff2016-01-11 17:10:07 +0100304 """
305 Stop and remove a container from this data center.
306 """
peusterm9165ef92016-01-13 13:50:39 +0100307 assert name is not None
308 if name not in self.containers:
309 raise Exception("Container with name %s not found." % name)
peusterm72f09882018-05-15 17:10:27 +0200310 LOG.debug("Stopping compute instance %r in data center %r" %
311 (name, str(self)))
peustermd18559d2016-04-16 04:59:23 +0200312
stevenvanrossem461941c2016-05-10 11:41:29 +0200313 # stop the monitored metrics
314 if self.net.monitor_agent is not None:
315 self.net.monitor_agent.stop_metric(name)
316
peusterm42f08be2016-03-10 21:56:34 +0100317 # call resource model and free resources
318 if self._resource_model is not None:
peustermd18559d2016-04-16 04:59:23 +0200319 self._resource_model.free(self.containers[name])
peusterm72f09882018-05-15 17:10:27 +0200320 self._resource_model.write_free_log(
321 self.containers[name], self.resource_log_path)
peusterm60bf8b82016-04-06 14:12:35 +0200322
peustermd18559d2016-04-16 04:59:23 +0200323 # 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
peusterm4e98b632016-01-12 14:08:07 +0100331 return True
332
stevenvanrossem86e64a02017-04-13 02:21:45 +0200333 def attachExternalSAP(self, sap_name, sap_net, **params):
stevenvanrossem17b6e882017-05-04 16:51:34 +0200334 extSAP = EmulatorExtSAP(sap_name, sap_net, self, **params)
stevenvanrossem86e64a02017-04-13 02:21:45 +0200335 # link SAP to the DC switch
stevenvanrossem17b6e882017-05-04 16:51:34 +0200336 self.net.addLink(extSAP.switch, self.switch, cls=Link)
337 self.extSAPs[sap_name] = extSAP
stevenvanrossemce032e12017-04-05 17:31:20 +0200338
stevenvanrossem68a0ba92017-05-03 21:48:26 +0200339 def removeExternalSAP(self, sap_name):
stevenvanrossem17b6e882017-05-04 16:51:34 +0200340 sap_switch = self.extSAPs[sap_name].switch
peusterm72f09882018-05-15 17:10:27 +0200341 # sap_switch = self.net.getNodeByName(sap_name)
stevenvanrossem17b6e882017-05-04 16:51:34 +0200342 # remove link of SAP to the DC switch
stevenvanrossem00e65b92017-04-18 16:57:40 +0200343 self.net.removeLink(link=None, node1=sap_switch, node2=self.switch)
stevenvanrossem68a0ba92017-05-03 21:48:26 +0200344 self.net.removeExtSAP(sap_name)
stevenvanrossem17b6e882017-05-04 16:51:34 +0200345 del self.extSAPs[sap_name]
stevenvanrossemce032e12017-04-05 17:31:20 +0200346
peusterm4e98b632016-01-12 14:08:07 +0100347 def listCompute(self):
348 """
349 Return a list of all running containers assigned to this
350 data center.
351 """
peusterm5aa8cf22016-01-15 11:12:17 +0100352 return list(self.containers.itervalues())
peustermd313dc12016-02-04 15:36:02 +0100353
stevenvanrossem17b6e882017-05-04 16:51:34 +0200354 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
peustermd313dc12016-02-04 15:36:02 +0100361 def getStatus(self):
362 """
363 Return a dict with status information about this DC.
364 """
stevenvanrossemba51a812017-04-23 01:22:59 +0200365 container_list = [name for name in self.containers]
stevenvanrossem17b6e882017-05-04 16:51:34 +0200366 ext_saplist = [sap_name for sap_name in self.extSAPs]
peusterm53504942016-02-04 16:09:28 +0100367 return {
368 "label": self.label,
369 "internalname": self.name,
370 "switch": self.switch.name,
371 "n_running_containers": len(self.containers),
stevenvanrossemba51a812017-04-23 01:22:59 +0200372 "metadata": self.metadata,
peusterm72f09882018-05-15 17:10:27 +0200373 "vnf_list": container_list,
374 "ext SAP list": ext_saplist
peusterm53504942016-02-04 16:09:28 +0100375 }
peusterm42f08be2016-03-10 21:56:34 +0100376
377 def assignResourceModel(self, rm):
peusterm279565d2016-03-19 10:36:52 +0100378 """
379 Assign a resource model to this DC.
380 :param rm: a BaseResourceModel object
381 :return:
382 """
peusterm42f08be2016-03-10 21:56:34 +0100383 if self._resource_model is not None:
peusterm72f09882018-05-15 17:10:27 +0200384 raise Exception(
385 "There is already an resource model assigned to this DC.")
peusterm42f08be2016-03-10 21:56:34 +0100386 self._resource_model = rm
387 self.net.rm_registrar.register(self, rm)
peusterm3444ae42016-03-16 20:46:41 +0100388 LOG.info("Assigned RM: %r to DC: %r" % (rm, self))
peusterm42f08be2016-03-10 21:56:34 +0100389
peusterm761c14d2016-07-19 09:31:19 +0200390 @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