Guard lifecycle of contexts
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / util / DeviceInitializationUtil.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.openflowplugin.impl.util;
10
11 import java.net.InetSocketAddress;
12 import java.util.Collections;
13 import java.util.Optional;
14 import java.util.concurrent.ExecutionException;
15 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
16 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
17 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
18 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
19 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
20 import org.opendaylight.openflowplugin.api.openflow.device.TxFacade;
21 import org.opendaylight.openflowplugin.openflow.md.core.sal.SwitchFeaturesUtil;
22 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.flow.node.SwitchFeatures;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsData;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsDataBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public class DeviceInitializationUtil {
41     private static final Logger LOG = LoggerFactory.getLogger(DeviceInitializationUtil.class);
42
43     private DeviceInitializationUtil() {
44         // Hiding implicit constructor
45     }
46
47     /**
48      * Merge empty nodes to operational DS to predict any problems with missing parent for node.
49      *
50      * @param dataBroker the data broker
51      */
52     public static void makeEmptyNodes(final DataBroker dataBroker) {
53         final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
54
55         try {
56             tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), new NodesBuilder()
57                     .setNode(Collections.emptyList())
58                     .build());
59             tx.submit().get();
60         } catch (ExecutionException | InterruptedException e) {
61             LOG.error("Creation of node failed.", e);
62             throw new IllegalStateException(e);
63         }
64     }
65
66     /**
67      * Create specified number of empty tables on device.
68      * FIXME: remove after ovs table features fix
69      *
70      * @param txFacade   transaction facade
71      * @param deviceInfo device info
72      * @param nrOfTables number of tables
73      */
74     public static void makeEmptyTables(final TxFacade txFacade, final DeviceInfo deviceInfo, final short nrOfTables) {
75         if (LOG.isDebugEnabled()) {
76             LOG.debug("About to create {} empty tables for node {}.", nrOfTables, deviceInfo.getLOGValue());
77         }
78
79         for (int i = 0; i < nrOfTables; i++) {
80             try {
81                 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL,
82                         deviceInfo
83                                 .getNodeInstanceIdentifier()
84                                 .augmentation(FlowCapableNode.class)
85                                 .child(Table.class, new TableKey((short) i)),
86                         new TableBuilder()
87                                 .setId((short) i)
88                                 .addAugmentation(
89                                         FlowTableStatisticsData.class,
90                                         new FlowTableStatisticsDataBuilder().build())
91                                 .build());
92             } catch (final Exception e) {
93                 LOG.debug("makeEmptyTables: Failed to write node {} to DS ", deviceInfo.getLOGValue(), e);
94             }
95         }
96     }
97
98     /**
99      * Retrieve ip address from connection.
100      *
101      * @param connectionContext  connection context
102      * @param instanceIdentifier instance identifier
103      * @return ip address
104      */
105     public static IpAddress getIpAddress(final ConnectionContext connectionContext,
106                                          final InstanceIdentifier<Node> instanceIdentifier) {
107         final String node = PathUtil.extractNodeId(instanceIdentifier).getValue();
108
109         return getRemoteAddress(connectionContext, instanceIdentifier)
110                 .map(inetSocketAddress -> {
111                     final IpAddress ipAddress = IetfInetUtil.INSTANCE.ipAddressFor(inetSocketAddress.getAddress());
112                     LOG.info("IP address of the node {} is: {}", node, ipAddress);
113                     return ipAddress;
114                 })
115                 .orElse(null);
116     }
117
118     /**
119      * Retrieve port number from connection.
120      *
121      * @param connectionContext  connection context
122      * @param instanceIdentifier instance identifier
123      * @return port number
124      */
125     public static PortNumber getPortNumber(final ConnectionContext connectionContext,
126                                            final InstanceIdentifier<Node> instanceIdentifier) {
127         final String node = PathUtil.extractNodeId(instanceIdentifier).getValue();
128
129         return getRemoteAddress(connectionContext, instanceIdentifier)
130                 .map(inetSocketAddress -> {
131                     final int port = inetSocketAddress.getPort();
132                     LOG.info("Port number of the node {} is: {}", node, port);
133                     return new PortNumber(port);
134                 })
135                 .orElse(null);
136
137     }
138
139     /**
140      * Retrieve switch features from connection.
141      *
142      * @param connectionContext connection context
143      * @return switch features
144      */
145     public static SwitchFeatures getSwitchFeatures(final ConnectionContext connectionContext) {
146         return SwitchFeaturesUtil
147                 .getInstance()
148                 .buildSwitchFeatures(new GetFeaturesOutputBuilder(connectionContext
149                         .getFeatures())
150                         .build());
151     }
152
153     private static Optional<InetSocketAddress> getRemoteAddress(final ConnectionContext connectionContext,
154                                                                 final InstanceIdentifier<Node> instanceIdentifier) {
155         final Optional<InetSocketAddress> inetSocketAddress = Optional
156                 .ofNullable(connectionContext.getConnectionAdapter())
157                 .flatMap(connectionAdapter -> Optional.ofNullable(connectionAdapter.getRemoteAddress()));
158
159         if (!inetSocketAddress.isPresent()) {
160             LOG.warn("Remote address of the node {} cannot be obtained. No connection with switch.", PathUtil
161                     .extractNodeId(instanceIdentifier));
162         }
163
164         return inetSocketAddress;
165     }
166
167 }