Bump versions by 0.1.0 for next dev cycle
[vpnservice.git] / fcapsapplication / fcapsapplication-impl / src / main / java / org / opendaylight / vpnservice / fcapsapp / performancecounter / FlowNodeConnectorInventoryTranslatorImpl.java
1 /*
2  * Copyright (c) 2016 Ericsson India Global Services Pvt Ltd. 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 package org.opendaylight.vpnservice.fcapsapp.performancecounter;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.*;
13 import org.opendaylight.controller.md.sal.binding.api.*;
14 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
15 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
16 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
17 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
18 import org.opendaylight.openflowplugin.common.wait.SimpleTaskRetryLooper;
19 import org.opendaylight.vpnservice.fcapsapp.portinfo.PortNameMapping;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
25 import org.opendaylight.yangtools.concepts.ListenerRegistration;
26 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import java.lang.String;
30 import java.util.HashMap;
31 import java.util.Collection;
32 import java.util.concurrent.Callable;
33
34 public class FlowNodeConnectorInventoryTranslatorImpl extends NodeConnectorEventListener<FlowCapableNodeConnector>  {
35     public static final int STARTUP_LOOP_TICK = 500;
36     public static final int STARTUP_LOOP_MAX_RETRIES = 8;
37     private static final Logger LOG = LoggerFactory.getLogger(FlowNodeConnectorInventoryTranslatorImpl.class);
38     private final EntityOwnershipService entityOwnershipService;
39
40     private ListenerRegistration<FlowNodeConnectorInventoryTranslatorImpl> dataTreeChangeListenerRegistration;
41
42     public static final String SEPARATOR = ":";
43     private static final PMAgent pmAgent = new PMAgent();
44
45     private static final InstanceIdentifier<FlowCapableNodeConnector> II_TO_FLOW_CAPABLE_NODE_CONNECTOR
46             = InstanceIdentifier.builder(Nodes.class)
47             .child(Node.class)
48             .child(NodeConnector.class)
49             .augmentation(FlowCapableNodeConnector.class)
50             .build();
51
52     private static Multimap<Long,String> dpnToPortMultiMap = Multimaps.synchronizedListMultimap(ArrayListMultimap.<Long,String>create());
53
54     private static HashMap<String, String> nodeConnectorCountermap = new HashMap<String, String>();
55
56     public FlowNodeConnectorInventoryTranslatorImpl(final DataBroker dataBroker,final EntityOwnershipService eos) {
57         super( FlowCapableNodeConnector.class);
58         Preconditions.checkNotNull(dataBroker, "DataBroker can not be null!");
59
60         entityOwnershipService = eos;
61         final DataTreeIdentifier<FlowCapableNodeConnector> treeId =
62                 new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, getWildCardPath());
63         try {
64             SimpleTaskRetryLooper looper = new SimpleTaskRetryLooper(STARTUP_LOOP_TICK,
65                     STARTUP_LOOP_MAX_RETRIES);
66             dataTreeChangeListenerRegistration = looper.loopUntilNoException(new Callable<ListenerRegistration<FlowNodeConnectorInventoryTranslatorImpl>>() {
67                 @Override
68                 public ListenerRegistration<FlowNodeConnectorInventoryTranslatorImpl> call() throws Exception {
69                     return dataBroker.registerDataTreeChangeListener(treeId, FlowNodeConnectorInventoryTranslatorImpl.this);
70                 }
71             });
72         } catch (final Exception e) {
73             LOG.warn(" FlowNodeConnectorInventoryTranslatorImpl listener registration fail!");
74             LOG.debug("FlowNodeConnectorInventoryTranslatorImpl DataChange listener registration fail ..", e);
75             throw new IllegalStateException("FlowNodeConnectorInventoryTranslatorImpl startup fail! System needs restart.", e);
76         }
77     }
78
79
80     protected InstanceIdentifier<FlowCapableNodeConnector> getWildCardPath() {
81         return InstanceIdentifier.create(Nodes.class)
82                 .child(Node.class)
83                 .child(NodeConnector.class)
84                 .augmentation(FlowCapableNodeConnector.class);
85     }
86
87     @Override
88     public void close() {
89         if (dataTreeChangeListenerRegistration != null) {
90             try {
91                 dataTreeChangeListenerRegistration.close();
92             } catch (final Exception e) {
93                 LOG.warn("Error by stop FRM FlowNodeConnectorInventoryTranslatorImpl: {}", e.getMessage());
94                 LOG.debug("Error by stop FRM FlowNodeConnectorInventoryTranslatorImpl..", e);
95             }
96             dataTreeChangeListenerRegistration = null;
97         }
98     }
99     @Override
100     public void remove(InstanceIdentifier<FlowCapableNodeConnector> identifier, FlowCapableNodeConnector del, InstanceIdentifier<FlowCapableNodeConnector> nodeConnIdent) {
101         if(compareInstanceIdentifierTail(identifier,II_TO_FLOW_CAPABLE_NODE_CONNECTOR)) {
102             String sNodeConnectorIdentifier = getNodeConnectorId(String.valueOf(nodeConnIdent.firstKeyOf(NodeConnector.class).getId()));
103             long nDpId = getDpIdFromPortName(sNodeConnectorIdentifier);
104             if (dpnToPortMultiMap.containsKey(nDpId)) {
105                 LOG.debug("Node Connector {} removed", sNodeConnectorIdentifier);
106                 dpnToPortMultiMap.remove(nDpId, sNodeConnectorIdentifier);
107                 sendNodeConnectorUpdation(nDpId);
108                 PortNameMapping.updatePortMap("openflow:" + nDpId + ":" + del.getName(), sNodeConnectorIdentifier, "DELETE");
109             }
110         }
111     }
112
113     @Override
114     public void update(InstanceIdentifier<FlowCapableNodeConnector> identifier, FlowCapableNodeConnector original, FlowCapableNodeConnector update, InstanceIdentifier<FlowCapableNodeConnector> nodeConnIdent) {
115         if(compareInstanceIdentifierTail(identifier,II_TO_FLOW_CAPABLE_NODE_CONNECTOR)) {
116
117             //donot need to do anything as we are not considering updates here
118             String sNodeConnectorIdentifier = getNodeConnectorId(String.valueOf(nodeConnIdent.firstKeyOf(NodeConnector.class).getId()));
119             long nDpId = getDpIdFromPortName(sNodeConnectorIdentifier);
120             if (isNodeOwner(getNodeId(nDpId))) {
121                 boolean original_portstatus = original.getConfiguration().isPORTDOWN();
122                 boolean update_portstatus = update.getConfiguration().isPORTDOWN();
123
124                 if (update_portstatus == true) {
125                     //port has gone down
126                     LOG.debug("Node Connector {} updated port is down", sNodeConnectorIdentifier);
127                 } else if (original_portstatus == true) {
128                     //port has come up
129                     LOG.debug("Node Connector {} updated port is up", sNodeConnectorIdentifier);
130                 }
131             }
132         }
133     }
134
135     @Override
136     public void add(InstanceIdentifier<FlowCapableNodeConnector> identifier, FlowCapableNodeConnector add, InstanceIdentifier<FlowCapableNodeConnector> nodeConnIdent) {
137         if (compareInstanceIdentifierTail(identifier,II_TO_FLOW_CAPABLE_NODE_CONNECTOR)){
138
139             String sNodeConnectorIdentifier = getNodeConnectorId(String.valueOf(nodeConnIdent.firstKeyOf(NodeConnector.class).getId()));
140             long nDpId = getDpIdFromPortName(sNodeConnectorIdentifier);
141             if (isNodeOwner(getNodeId(nDpId))) {
142                 if (!dpnToPortMultiMap.containsEntry(nDpId, sNodeConnectorIdentifier)) {
143                     LOG.debug("Node Connector {} added", sNodeConnectorIdentifier);
144                     dpnToPortMultiMap.put(nDpId, sNodeConnectorIdentifier);
145                     sendNodeConnectorUpdation(nDpId);
146                     PortNameMapping.updatePortMap("openflow:" + nDpId + ":" + add.getName(), sNodeConnectorIdentifier, "ADD");
147                 } else {
148                     LOG.error("Duplicate Event.Node Connector already added");
149                 }
150             }
151         }
152     }
153     private String getNodeConnectorId(String node) {
154         //Uri [_value=openflow:1:1]
155         String temp[] = node.split("=");
156         String dpnId = temp[1].substring(0,temp[1].length() - 1);
157         return dpnId;
158     }
159
160     private String getNodeId(Long dpnId){
161         return "openflow:" + dpnId;
162     }
163     /**
164      * Method checks if *this* instance of controller is owner of
165      * the given openflow node.
166      * @param nodeId openflow node Id
167      * @return True if owner, else false
168      */
169     public boolean isNodeOwner(String nodeId) {
170         Entity entity = new Entity("openflow", nodeId);
171         Optional<EntityOwnershipState> eState = this.entityOwnershipService.getOwnershipState(entity);
172         if(eState.isPresent()) {
173             return eState.get().isOwner();
174         }
175         return false;
176     }
177
178     private boolean compareInstanceIdentifierTail(InstanceIdentifier<?> identifier1,
179                                                   InstanceIdentifier<?> identifier2) {
180         return Iterables.getLast(identifier1.getPathArguments()).equals(Iterables.getLast(identifier2.getPathArguments()));
181     }
182
183     private long getDpIdFromPortName(String portName) {
184         String dpId = portName.substring(portName.indexOf(SEPARATOR) + 1, portName.lastIndexOf(SEPARATOR));
185         return Long.parseLong(dpId);
186     }
187
188     private void sendNodeConnectorUpdation(Long dpnId) {
189         Collection<String> portname = dpnToPortMultiMap.get(dpnId);
190         String nodeListPortsCountStr,counterkey;
191         nodeListPortsCountStr = "dpnId_" + dpnId + "_NumberOfOFPorts";
192         counterkey = "NumberOfOFPorts:" + nodeListPortsCountStr;
193
194         if (portname.size()!=0) {
195             nodeConnectorCountermap.put(counterkey, "" + portname.size());
196         } else {
197             nodeConnectorCountermap.remove(counterkey);
198         }
199         LOG.debug("NumberOfOFPorts:" + nodeListPortsCountStr + " portlistsize " + portname.size());
200         pmAgent.connectToPMAgentForNOOfPorts(nodeConnectorCountermap);
201     }
202 }