Update unit tests
[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
42     private static final Logger LOG = LoggerFactory.getLogger(DeviceInitializationUtil.class);
43
44     private DeviceInitializationUtil() {
45         // Hiding implicit constructor
46     }
47
48     /**
49      * Merge empty nodes to operational DS to predict any problems with missing parent for node.
50      *
51      * @param dataBroker the data broker
52      */
53     public static void makeEmptyNodes(final DataBroker dataBroker) {
54         final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
55
56         try {
57             tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), new NodesBuilder()
58                     .setNode(Collections.emptyList())
59                     .build());
60             tx.submit().get();
61         } catch (ExecutionException | InterruptedException e) {
62             LOG.error("Creation of node failed.", e);
63             throw new IllegalStateException(e);
64         }
65     }
66
67     /**
68      * Create specified number of empty tables on device.
69      * FIXME: remove after ovs table features fix
70      *
71      * @param txFacade   transaction facade
72      * @param deviceInfo device info
73      * @param nrOfTables number of tables
74      */
75     public static void makeEmptyTables(final TxFacade txFacade, final DeviceInfo deviceInfo, final short nrOfTables) {
76         if (LOG.isDebugEnabled()) {
77             LOG.debug("About to create {} empty tables for node {}.", nrOfTables, deviceInfo.getLOGValue());
78         }
79
80         for (int i = 0; i < nrOfTables; i++) {
81             try {
82                 txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL,
83                         deviceInfo
84                                 .getNodeInstanceIdentifier()
85                                 .augmentation(FlowCapableNode.class)
86                                 .child(Table.class, new TableKey((short) i)),
87                         new TableBuilder()
88                                 .setId((short) i)
89                                 .addAugmentation(
90                                         FlowTableStatisticsData.class,
91                                         new FlowTableStatisticsDataBuilder().build())
92                                 .build());
93             } catch (final Exception e) {
94                 LOG.debug("makeEmptyTables: Failed to write node {} to DS ", deviceInfo.getLOGValue(), e);
95             }
96         }
97     }
98
99     /**
100      * Retrieve ip address from connection.
101      *
102      * @param connectionContext  connection context
103      * @param instanceIdentifier instance identifier
104      * @return ip address
105      */
106     public static IpAddress getIpAddress(final ConnectionContext connectionContext,
107                                          final InstanceIdentifier<Node> instanceIdentifier) {
108         final String node = PathUtil.extractNodeId(instanceIdentifier).getValue();
109
110         return getRemoteAddress(connectionContext, instanceIdentifier)
111                 .map(inetSocketAddress -> {
112                     final IpAddress ipAddress = IetfInetUtil.INSTANCE.ipAddressFor(inetSocketAddress.getAddress());
113                     LOG.info("IP address of the node {} is: {}", node, ipAddress);
114                     return ipAddress;
115                 })
116                 .orElse(null);
117     }
118
119     /**
120      * Retrieve port number from connection.
121      *
122      * @param connectionContext  connection context
123      * @param instanceIdentifier instance identifier
124      * @return port number
125      */
126     public static PortNumber getPortNumber(final ConnectionContext connectionContext,
127                                            final InstanceIdentifier<Node> instanceIdentifier) {
128         final String node = PathUtil.extractNodeId(instanceIdentifier).getValue();
129
130         return getRemoteAddress(connectionContext, instanceIdentifier)
131                 .map(inetSocketAddress -> {
132                     final int port = inetSocketAddress.getPort();
133                     LOG.info("Port number of the node {} is: {}", node, port);
134                     return new PortNumber(port);
135                 })
136                 .orElse(null);
137
138     }
139
140     /**
141      * Retrieve switch features from connection.
142      *
143      * @param connectionContext connection context
144      * @return switch features
145      */
146     public static SwitchFeatures getSwitchFeatures(final ConnectionContext connectionContext) {
147         return SwitchFeaturesUtil
148                 .getInstance()
149                 .buildSwitchFeatures(new GetFeaturesOutputBuilder(connectionContext
150                         .getFeatures())
151                         .build());
152     }
153
154     private static Optional<InetSocketAddress> getRemoteAddress(final ConnectionContext connectionContext,
155                                                                 final InstanceIdentifier<Node> instanceIdentifier) {
156         final Optional<InetSocketAddress> inetSocketAddress = Optional
157                 .ofNullable(connectionContext.getConnectionAdapter())
158                 .flatMap(connectionAdapter -> Optional.ofNullable(connectionAdapter.getRemoteAddress()));
159
160         if (!inetSocketAddress.isPresent()) {
161             LOG.warn("Remote address of the node {} cannot be obtained. No connection with switch.", PathUtil
162                     .extractNodeId(instanceIdentifier));
163         }
164
165         return inetSocketAddress;
166     }
167
168 }