blob: 8f070b226dc51ba9f69095124bd8ad28088a3bbb [file] [log] [blame]
Sho SHIMIZUe4efe452015-08-26 15:06:55 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Sho SHIMIZUe4efe452015-08-26 15:06:55 -07003 *
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 */
16package org.onosproject.ovsdb.controller.impl;
17
andreaed976a42015-10-05 14:38:25 -070018import com.fasterxml.jackson.databind.JsonNode;
19import com.google.common.collect.ImmutableList;
Sho SHIMIZUe4efe452015-08-26 15:06:55 -070020import org.apache.felix.scr.annotations.Activate;
21import org.apache.felix.scr.annotations.Component;
22import org.apache.felix.scr.annotations.Deactivate;
Jian Li9b1bc9d2018-05-03 15:54:03 +090023import org.apache.felix.scr.annotations.Modified;
24import org.apache.felix.scr.annotations.Property;
25import org.apache.felix.scr.annotations.Reference;
26import org.apache.felix.scr.annotations.ReferenceCardinality;
Sho SHIMIZUe4efe452015-08-26 15:06:55 -070027import org.apache.felix.scr.annotations.Service;
28import org.onlab.packet.IpAddress;
29import org.onlab.packet.MacAddress;
Hyunsun Moon5fb20a52015-09-25 17:02:33 -070030import org.onlab.packet.TpPort;
Jian Li9b1bc9d2018-05-03 15:54:03 +090031import org.onlab.util.Tools;
32import org.onosproject.cfg.ComponentConfigService;
Sho SHIMIZUe4efe452015-08-26 15:06:55 -070033import org.onosproject.ovsdb.controller.DefaultEventSubject;
34import org.onosproject.ovsdb.controller.EventSubject;
35import org.onosproject.ovsdb.controller.OvsdbClientService;
36import org.onosproject.ovsdb.controller.OvsdbConstant;
37import org.onosproject.ovsdb.controller.OvsdbController;
38import org.onosproject.ovsdb.controller.OvsdbDatapathId;
39import org.onosproject.ovsdb.controller.OvsdbEvent;
40import org.onosproject.ovsdb.controller.OvsdbEvent.Type;
41import org.onosproject.ovsdb.controller.OvsdbEventListener;
42import org.onosproject.ovsdb.controller.OvsdbIfaceId;
43import org.onosproject.ovsdb.controller.OvsdbNodeId;
44import org.onosproject.ovsdb.controller.OvsdbNodeListener;
45import org.onosproject.ovsdb.controller.OvsdbPortName;
46import org.onosproject.ovsdb.controller.OvsdbPortNumber;
47import org.onosproject.ovsdb.controller.OvsdbPortType;
48import org.onosproject.ovsdb.controller.driver.OvsdbAgent;
49import org.onosproject.ovsdb.rfc.jsonrpc.Callback;
50import org.onosproject.ovsdb.rfc.message.TableUpdate;
51import org.onosproject.ovsdb.rfc.message.TableUpdates;
52import org.onosproject.ovsdb.rfc.message.UpdateNotification;
53import org.onosproject.ovsdb.rfc.notation.OvsdbMap;
54import org.onosproject.ovsdb.rfc.notation.OvsdbSet;
55import org.onosproject.ovsdb.rfc.notation.Row;
Jonathan Hart51539b82015-10-29 09:53:04 -070056import org.onosproject.ovsdb.rfc.notation.Uuid;
Sho SHIMIZUe4efe452015-08-26 15:06:55 -070057import org.onosproject.ovsdb.rfc.schema.DatabaseSchema;
58import org.onosproject.ovsdb.rfc.table.Bridge;
59import org.onosproject.ovsdb.rfc.table.Interface;
60import org.onosproject.ovsdb.rfc.table.OvsdbTable;
61import org.onosproject.ovsdb.rfc.table.TableGenerator;
62import org.onosproject.ovsdb.rfc.utils.FromJsonUtil;
63import org.osgi.service.component.ComponentContext;
64import org.slf4j.Logger;
65import org.slf4j.LoggerFactory;
66
andreaed976a42015-10-05 14:38:25 -070067import java.math.BigInteger;
Jian Li9b1bc9d2018-05-03 15:54:03 +090068import java.util.Dictionary;
andreaed976a42015-10-05 14:38:25 -070069import java.util.HashSet;
70import java.util.Iterator;
71import java.util.List;
72import java.util.Map;
73import java.util.Set;
74import java.util.concurrent.ConcurrentHashMap;
75import java.util.concurrent.CopyOnWriteArraySet;
76import java.util.concurrent.ExecutionException;
jiangruibce80652017-10-17 14:35:42 +080077import java.util.concurrent.TimeUnit;
78import java.util.concurrent.TimeoutException;
jaegonkim1af0ae52017-01-01 10:46:55 +090079import java.util.function.Consumer;
andreaed976a42015-10-05 14:38:25 -070080
81import static com.google.common.base.Preconditions.checkNotNull;
Jian Li9b1bc9d2018-05-03 15:54:03 +090082import static org.onosproject.ovsdb.controller.OvsdbConstant.SERVER_MODE;
Sho SHIMIZUe4efe452015-08-26 15:06:55 -070083
84/**
85 * The implementation of OvsdbController.
86 */
87@Component(immediate = true)
88@Service
89public class OvsdbControllerImpl implements OvsdbController {
90
91 public static final Logger log = LoggerFactory
92 .getLogger(OvsdbControllerImpl.class);
jiangruibce80652017-10-17 14:35:42 +080093 private static final long DEFAULT_OVSDB_RPC_TIMEOUT = 3000;
94 private final Controller controller = new Controller();
Sho SHIMIZUe4efe452015-08-26 15:06:55 -070095 protected ConcurrentHashMap<OvsdbNodeId, OvsdbClientService> ovsdbClients =
kdarapu71f623c2018-05-10 19:37:53 +053096 new ConcurrentHashMap<>();
Sho SHIMIZUe4efe452015-08-26 15:06:55 -070097 protected OvsdbAgent agent = new InternalOvsdbNodeAgent();
98 protected InternalMonitorCallBack updateCallback = new InternalMonitorCallBack();
Sho SHIMIZUe4efe452015-08-26 15:06:55 -070099 protected Set<OvsdbNodeListener> ovsdbNodeListener = new CopyOnWriteArraySet<>();
100 protected Set<OvsdbEventListener> ovsdbEventListener = new CopyOnWriteArraySet<>();
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700101 protected ConcurrentHashMap<String, OvsdbClientService> requestNotification =
kdarapu71f623c2018-05-10 19:37:53 +0530102 new ConcurrentHashMap<>();
103 protected ConcurrentHashMap<String, String> requestDbName = new ConcurrentHashMap<>();
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700104
Jian Li9b1bc9d2018-05-03 15:54:03 +0900105 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
106 protected ComponentConfigService configService;
107
108 @Property(name = "serverMode", boolValue = SERVER_MODE,
109 label = "Run as server mode, listen on 6640 port")
110 private boolean serverMode = SERVER_MODE;
111
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700112 @Activate
113 public void activate(ComponentContext context) {
Jian Li9b1bc9d2018-05-03 15:54:03 +0900114 controller.start(agent, updateCallback, serverMode);
115
116 configService.registerProperties(getClass());
117
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700118 log.info("Started");
119 }
120
121 @Deactivate
122 public void deactivate() {
123 controller.stop();
Jian Li9b1bc9d2018-05-03 15:54:03 +0900124
125 configService.unregisterProperties(getClass(), false);
126
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700127 log.info("Stoped");
128 }
129
Jian Li9b1bc9d2018-05-03 15:54:03 +0900130 @Modified
131 protected void modified(ComponentContext context) {
132 Dictionary<?, ?> properties = context.getProperties();
133 Boolean flag;
134
135 flag = Tools.isPropertyEnabled(properties, "serverMode");
136 if (flag == null) {
137 log.info("OVSDB server mode is not configured, " +
138 "using current value of {}", serverMode);
139 } else {
140 serverMode = flag;
141 log.info("Configured. OVSDB server mode was {}",
142 serverMode ? "enabled" : "disabled");
143 }
144
145 restartController();
146 }
147
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700148 @Override
149 public void addNodeListener(OvsdbNodeListener listener) {
150 if (!ovsdbNodeListener.contains(listener)) {
151 this.ovsdbNodeListener.add(listener);
152 }
153 }
154
155 @Override
156 public void removeNodeListener(OvsdbNodeListener listener) {
157 this.ovsdbNodeListener.remove(listener);
158 }
159
160 @Override
161 public void addOvsdbEventListener(OvsdbEventListener listener) {
162 if (!ovsdbEventListener.contains(listener)) {
163 this.ovsdbEventListener.add(listener);
164 }
165 }
166
167 @Override
168 public void removeOvsdbEventListener(OvsdbEventListener listener) {
169 this.ovsdbEventListener.remove(listener);
170 }
171
172 @Override
173 public List<OvsdbNodeId> getNodeIds() {
andreaed976a42015-10-05 14:38:25 -0700174 return ImmutableList.copyOf(ovsdbClients.keySet());
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700175 }
176
177 @Override
178 public OvsdbClientService getOvsdbClient(OvsdbNodeId nodeId) {
179 return ovsdbClients.get(nodeId);
180 }
181
Hyunsun Moon5fb20a52015-09-25 17:02:33 -0700182 @Override
183 public void connect(IpAddress ip, TpPort port) {
184 controller.connect(ip, port);
185 }
186
jaegonkim1af0ae52017-01-01 10:46:55 +0900187 @Override
188 public void connect(IpAddress ip, TpPort port, Consumer<Exception> failhandler) {
189 controller.connect(ip, port, failhandler);
190 }
191
Jian Li9b1bc9d2018-05-03 15:54:03 +0900192 @Override
193 public void setServerMode(boolean serverMode) {
194 this.serverMode = serverMode;
195 restartController();
196 }
197
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700198 /**
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700199 * Processes table updates.
200 *
201 * @param clientService OvsdbClientService instance
andreaed976a42015-10-05 14:38:25 -0700202 * @param updates TableUpdates instance
203 * @param dbName ovsdb database name
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700204 */
205 private void processTableUpdates(OvsdbClientService clientService,
206 TableUpdates updates, String dbName)
207 throws InterruptedException {
208 checkNotNull(clientService, "OvsdbClientService is not null");
209
210 DatabaseSchema dbSchema = clientService.getDatabaseSchema(dbName);
211
212 for (String tableName : updates.result().keySet()) {
213 TableUpdate update = updates.result().get(tableName);
Jonathan Hart51539b82015-10-29 09:53:04 -0700214 for (Uuid uuid : (Set<Uuid>) update.rows().keySet()) {
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700215 log.debug("Begin to process table updates uuid: {}, databaseName: {}, tableName: {}",
216 uuid.value(), dbName, tableName);
217
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700218 Row newRow = update.getNew(uuid);
219 if (newRow != null) {
220 clientService.updateOvsdbStore(dbName, tableName,
221 uuid.value(), newRow);
222
223 if (OvsdbConstant.INTERFACE.equals(tableName)) {
224 dispatchInterfaceEvent(clientService,
CNluciusa66c3972015-09-06 20:31:29 +0800225 newRow,
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700226 OvsdbEvent.Type.PORT_ADDED,
227 dbSchema);
228 }
229 } else if (update.getOld(uuid) != null) {
CNluciusa66c3972015-09-06 20:31:29 +0800230 if (OvsdbConstant.INTERFACE.equals(tableName)) {
231 Row row = clientService.getRow(OvsdbConstant.DATABASENAME, tableName, uuid.value());
232 dispatchInterfaceEvent(clientService,
233 row,
andreaed976a42015-10-05 14:38:25 -0700234 OvsdbEvent.Type.PORT_REMOVED,
235 dbSchema);
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700236 }
CNluciusa66c3972015-09-06 20:31:29 +0800237 clientService.removeRow(dbName, tableName, uuid.value());
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700238 }
239 }
240 }
241 }
242
243 /**
244 * Dispatches event to the north.
245 *
246 * @param clientService OvsdbClientService instance
andreaed976a42015-10-05 14:38:25 -0700247 * @param newRow a new row
248 * @param oldRow an old row
249 * @param eventType type of event
250 * @param dbSchema ovsdb database schema
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700251 */
252 private void dispatchInterfaceEvent(OvsdbClientService clientService,
CNluciusa66c3972015-09-06 20:31:29 +0800253 Row row,
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700254 Type eventType,
255 DatabaseSchema dbSchema) {
256
257 long dpid = getDataPathid(clientService, dbSchema);
258 Interface intf = (Interface) TableGenerator
CNluciusa66c3972015-09-06 20:31:29 +0800259 .getTable(dbSchema, row, OvsdbTable.INTERFACE);
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700260 if (intf == null) {
261 return;
262 }
263
264 String portType = (String) intf.getTypeColumn().data();
265 long localPort = getOfPort(intf);
266 if (localPort < 0) {
267 return;
268 }
269 String[] macAndIfaceId = getMacAndIfaceid(intf);
270 if (macAndIfaceId == null) {
271 return;
272 }
273
274 EventSubject eventSubject = new DefaultEventSubject(MacAddress.valueOf(
andreaed976a42015-10-05 14:38:25 -0700275 macAndIfaceId[0]),
kdarapu71f623c2018-05-10 19:37:53 +0530276 new HashSet<>(),
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700277 new OvsdbPortName(intf
andreaed976a42015-10-05 14:38:25 -0700278 .getName()),
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700279 new OvsdbPortNumber(localPort),
280 new OvsdbDatapathId(Long
andreaed976a42015-10-05 14:38:25 -0700281 .toString(dpid)),
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700282 new OvsdbPortType(portType),
283 new OvsdbIfaceId(macAndIfaceId[1]));
284 for (OvsdbEventListener listener : ovsdbEventListener) {
kdarapu71f623c2018-05-10 19:37:53 +0530285 listener.handle(new OvsdbEvent<>(eventType,
286 eventSubject));
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700287 }
288 }
289
290 /**
291 * Gets mac and iface from the table Interface.
292 *
293 * @param intf Interface instance
294 * @return attachedMac, ifaceid
295 */
296 private String[] getMacAndIfaceid(Interface intf) {
297 OvsdbMap ovsdbMap = (OvsdbMap) intf.getExternalIdsColumn().data();
298 @SuppressWarnings("unchecked")
299 Map<String, String> externalIds = ovsdbMap.map();
300 if (externalIds == null) {
301 log.warn("The external_ids is null");
302 return null;
303 }
304
305 String attachedMac = externalIds.get(OvsdbConstant.EXTERNAL_ID_VM_MAC);
306 if (attachedMac == null) {
andreaed976a42015-10-05 14:38:25 -0700307 log.debug("The attachedMac is null"); //FIXME why always null?
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700308 return null;
309 }
310 String ifaceid = externalIds
311 .get(OvsdbConstant.EXTERNAL_ID_INTERFACE_ID);
312 if (ifaceid == null) {
313 log.warn("The ifaceid is null");
314 return null;
315 }
andreaed976a42015-10-05 14:38:25 -0700316 return new String[]{attachedMac, ifaceid};
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700317 }
318
319 /**
320 * Gets ofPorts number from table Interface.
321 *
322 * @param intf Interface instance
323 * @return ofport the ofport number
324 */
325 private long getOfPort(Interface intf) {
326 OvsdbSet ofPortSet = (OvsdbSet) intf.getOpenFlowPortColumn().data();
327 @SuppressWarnings("unchecked")
328 Set<Integer> ofPorts = ofPortSet.set();
Jon Hallb1f4e0f2017-02-22 13:36:16 -0800329 if (ofPorts == null || ofPorts.isEmpty()) {
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700330 log.debug("The ofport is null in {}", intf.getName());
331 return -1;
332 }
333 Iterator<Integer> it = ofPorts.iterator();
334 return Long.parseLong(it.next().toString());
335 }
336
337 /**
338 * Gets datapathid from table bridge.
339 *
340 * @param clientService OvsdbClientService instance
andreaed976a42015-10-05 14:38:25 -0700341 * @param dbSchema ovsdb database schema
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700342 * @return datapathid the bridge datapathid
343 */
344 private long getDataPathid(OvsdbClientService clientService,
345 DatabaseSchema dbSchema) {
346 String bridgeUuid = clientService
347 .getBridgeUuid(OvsdbConstant.INTEGRATION_BRIDGE);
348 if (bridgeUuid == null) {
349 log.debug("Unable to spot bridge uuid for {} in {}",
350 OvsdbConstant.INTEGRATION_BRIDGE, clientService);
351 return 0;
352 }
353
354 Row bridgeRow = clientService.getRow(OvsdbConstant.DATABASENAME,
355 "Bridge", bridgeUuid);
356 Bridge bridge = (Bridge) TableGenerator.getTable(dbSchema, bridgeRow,
357 OvsdbTable.BRIDGE);
358 OvsdbSet dpidSet = (OvsdbSet) bridge.getDatapathIdColumn().data();
359 @SuppressWarnings("unchecked")
360 Set<String> dpids = dpidSet.set();
Jon Hallcbd1b392017-01-18 20:15:44 -0800361 if (dpids == null || dpids.isEmpty()) {
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700362 return 0;
363 }
364 return stringToLong((String) dpids.toArray()[0]);
365 }
366
367 private long stringToLong(String values) {
368 long value = (new BigInteger(values.replaceAll(":", ""), 16))
369 .longValue();
370 return value;
371 }
372
Jian Li9b1bc9d2018-05-03 15:54:03 +0900373 private void restartController() {
374 controller.stop();
375 controller.start(agent, updateCallback, serverMode);
376 }
377
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700378 /**
jiangruibce80652017-10-17 14:35:42 +0800379 * Implementation of an Ovsdb Agent which is responsible for keeping track
380 * of connected node and the state in which they are.
381 */
382 private class InternalOvsdbNodeAgent implements OvsdbAgent {
383 @Override
384 public void addConnectedNode(OvsdbNodeId nodeId,
385 OvsdbClientService ovsdbClient) {
386
387 if (ovsdbClients.get(nodeId) != null) {
388 ovsdbClient.disconnect();
389 return;
390 } else {
391
392 try {
393 List<String> dbNames = ovsdbClient.listDbs().get(DEFAULT_OVSDB_RPC_TIMEOUT, TimeUnit.MILLISECONDS);
394 for (String dbName : dbNames) {
395 DatabaseSchema dbSchema;
396 dbSchema = ovsdbClient.getOvsdbSchema(dbName)
397 .get(DEFAULT_OVSDB_RPC_TIMEOUT, TimeUnit.MILLISECONDS);
398
399 log.debug("Begin to monitor tables");
400 String id = java.util.UUID.randomUUID().toString();
401 TableUpdates updates = ovsdbClient
402 .monitorTables(dbName, id).get(DEFAULT_OVSDB_RPC_TIMEOUT, TimeUnit.MILLISECONDS);
403
404 requestDbName.put(id, dbName);
405 requestNotification.put(id, ovsdbClient);
406
407 if (updates != null) {
408 processTableUpdates(ovsdbClient, updates,
409 dbSchema.name());
410 }
411 }
412 } catch (InterruptedException e) {
413 log.warn("Interrupted while waiting to get message from ovsdb");
414 Thread.currentThread().interrupt();
415 return;
416 } catch (ExecutionException e) {
417 log.error("Exception thrown while to get message from ovsdb");
418 ovsdbClient.disconnect();
419 return;
420 } catch (TimeoutException e) {
421 log.error("TimeoutException thrown while to get message from ovsdb");
422 ovsdbClient.disconnect();
423 return;
424 }
425 ovsdbClients.put(nodeId, ovsdbClient);
426
427 log.debug("Add node to north");
428 for (OvsdbNodeListener l : ovsdbNodeListener) {
429 l.nodeAdded(nodeId);
430 }
431 return;
432 }
433 }
434
435 @Override
436 public void removeConnectedNode(OvsdbNodeId nodeId) {
437 ovsdbClients.remove(nodeId);
438 log.debug("Node connection is removed");
439 for (OvsdbNodeListener l : ovsdbNodeListener) {
440 l.nodeRemoved(nodeId);
441 }
442 }
443 }
444
445 /**
Sho SHIMIZUe4efe452015-08-26 15:06:55 -0700446 * Implementation of an Callback which is responsible for receiving request
447 * infomation from ovsdb.
448 */
449 private class InternalMonitorCallBack implements Callback {
450 @Override
451 public void update(UpdateNotification updateNotification) {
452 Object key = updateNotification.jsonValue();
453 OvsdbClientService ovsdbClient = requestNotification.get(key);
454
455 String dbName = requestDbName.get(key);
456 JsonNode updatesJson = updateNotification.tbUpdatesJsonNode();
457 DatabaseSchema dbSchema = ovsdbClient.getDatabaseSchema(dbName);
458 TableUpdates updates = FromJsonUtil
459 .jsonNodeToTableUpdates(updatesJson, dbSchema);
460 try {
461 processTableUpdates(ovsdbClient, updates, dbName);
462 } catch (InterruptedException e) {
463 log.warn("Interrupted while processing table updates");
464 Thread.currentThread().interrupt();
465 }
466 }
467
468 @Override
469 public void locked(List<String> ids) {
470 // TODO Auto-generated method stub
471 }
472
473 @Override
474 public void stolen(List<String> ids) {
475 // TODO Auto-generated method stub
476 }
477
478 }
479
480}