Honeynode test tool
[transportpce.git] / tests / honeynode / minimal-distribution-core / src / main / java / io / fd / honeycomb / infra / distro / initializer / DeviceChangeListener.java
1 /*
2  * Copyright (c) 2018 Orange and/or its affiliates.
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 package io.fd.honeycomb.infra.distro.initializer;
17
18 import com.google.common.base.Preconditions;
19
20 import java.util.Collection;
21 import java.util.Iterator;
22 import java.util.concurrent.ExecutionException;
23 import java.util.concurrent.Future;
24
25 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
26 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
27 import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
28 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
29 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
30 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
31 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
32 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.interfaces.grp.Interface;
33 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.interfaces.grp.InterfaceKey;
34 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.OrgOpenroadmDevice;
35 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.RoadmConnections;
36 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.org.openroadm.device.RoadmConnectionsKey;
37 import org.opendaylight.yangtools.yang.binding.DataObject;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * @author Martial COULIBALY ( mcoulibaly.ext@orange.com ) on behalf of Orange
45  */
46 final class DeviceChangeListener implements DataTreeChangeListener<OrgOpenroadmDevice> {
47
48     private static final Logger LOG = LoggerFactory.getLogger(DeviceChangeListener.class);
49     private final DataBroker honeyCombDB;
50     private final DataBroker dataBroker;
51
52     public DeviceChangeListener(DataBroker deviceDataBroker, DataBroker honeycombDB) {
53         this.dataBroker = deviceDataBroker;
54         this.honeyCombDB = honeycombDB;
55         Preconditions.checkArgument(this.dataBroker != null, "Device datastore is null");
56         Preconditions.checkArgument(this.honeyCombDB != null, "HC datastore is null");
57     }
58
59     @Override
60     public void onDataTreeChanged(Collection<DataTreeModification<OrgOpenroadmDevice>> changes) {
61         LOG.info("onDataTreeChanged");
62         for (DataTreeModification<OrgOpenroadmDevice> change : changes) {
63             final DataObjectModification<OrgOpenroadmDevice> rootNode = change.getRootNode();
64             final DataTreeIdentifier<OrgOpenroadmDevice> rootPath = change.getRootPath();
65             if (rootNode != null ) {
66                 final OrgOpenroadmDevice dataBefore = rootNode.getDataBefore();
67                 final OrgOpenroadmDevice dataAfter = rootNode.getDataAfter();
68                 LOG.info("Received Device change({}):\n before={} \n after={}", rootNode.getModificationType(), dataBefore,
69                         dataAfter);
70                 Collection<DataObjectModification<? extends DataObject>> modifiedChildren = rootNode.getModifiedChildren();
71                 switch (rootNode.getModificationType()) {
72                     case SUBTREE_MODIFIED:
73                         if (!modifiedChildren.isEmpty()) {
74                             Iterator<DataObjectModification<? extends DataObject>> iterator = modifiedChildren.iterator();
75                             while (iterator.hasNext()) {
76                                 DataObjectModification<? extends DataObject> modified = iterator.next();
77                                 LOG.info("modified = \ndataType : {}\nid : {}\nmodifiedType : {}\noldData : {}\nnewData : {} \n",
78                                         modified.getDataType(), modified.getIdentifier(),modified.getModificationType(),
79                                         modified.getDataBefore(), modified.getDataAfter());
80                                 switch (modified.getModificationType()) {
81                                   case SUBTREE_MODIFIED:
82                                   case WRITE :
83                                       processChange(rootPath.getRootIdentifier(), dataAfter);
84                                       break;
85                                   case DELETE:
86                                       deleteContainer(rootPath, modified, dataAfter);
87                                       break;
88                                   default:
89                                       break;
90                                }
91                             }
92                         }
93                         processChange(rootPath.getRootIdentifier(), dataAfter);
94                         break;
95                     case WRITE :
96                         processChange(rootPath.getRootIdentifier(), dataAfter);
97                         break;
98                     case DELETE:
99                         deleteChange(rootPath.getRootIdentifier(),dataBefore);
100                         break;
101                     default:
102                         break;
103                 }
104             } else {
105                 LOG.error("rootNode is null !");
106             }
107         }
108     }
109
110     /**
111      * Delete change from device
112      * oper datastore.
113      *
114      * @param id container identifier
115      */
116     private void deleteContainer(DataTreeIdentifier<OrgOpenroadmDevice> rootPath,
117             DataObjectModification<? extends DataObject> modified, final OrgOpenroadmDevice dataAfter) {
118         final String ROADM_CONNECTIONS = "interface org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206"
119                 + ".org.openroadm.device.container.org.openroadm.device.RoadmConnections";
120         final String INTERFACE_GRP = "interface org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206"
121                 + ".interfaces.grp.Interface";
122         Class<? extends DataObject> type = modified.getDataType();
123         PathArgument path = modified.getIdentifier();
124         LOG.info("deleting container type '{}' with id '{}' ...", type.toString(), path);
125         String key = extractKey(path.toString());
126         if ( key != null) {
127             InstanceIdentifier<?> iid = null;
128             switch (type.toString()) {
129                 case ROADM_CONNECTIONS:
130                     LOG.info("roadm-connections ...");
131                     iid = rootPath.getRootIdentifier().child(RoadmConnections.class,
132                         new RoadmConnectionsKey(key));
133                     break;
134                 case INTERFACE_GRP:
135                     LOG.info("interface ....");
136                     iid = rootPath.getRootIdentifier().child(Interface.class,
137                             new InterfaceKey(key));
138                 default:
139                     break;
140             }
141             LOG.info("iid : {}", iid);
142             WriteTransaction writeTx = this.dataBroker.newWriteOnlyTransaction();
143             WriteTransaction writeHCTx = this.honeyCombDB.newWriteOnlyTransaction();
144             if (writeTx != null && writeHCTx != null) {
145                 LOG.info("WriteTransaction is ok, delete container device from device oper datastore");
146                 try {
147                     LOG.info("deleting container element from device oper DS ...");
148                     writeTx.delete(LogicalDatastoreType.OPERATIONAL, iid);
149                     Future<Void> future = writeTx.submit();
150                     future.get();
151                     LOG.info("container element '{}' deleted from device oper datastore", iid);
152                     LOG.info("deleting from HC config DS ...");
153                     writeHCTx.put(LogicalDatastoreType.CONFIGURATION, rootPath.getRootIdentifier(),dataAfter);
154                     future = writeHCTx.submit();
155                     future.get();
156                     LOG.info("device config DS '{}' updated to HC config DS", rootPath.getRootIdentifier());
157                 } catch (InterruptedException | ExecutionException e) {
158                     LOG.error("Failed to process WriteTransactions",e);
159                 }
160             } else {
161                 LOG.error("WriteTransaction object is null");
162             }
163         } else {
164             LOG.error("extract key is null");
165         }
166     }
167
168     private String extractKey(String path) {
169         LOG.info("getting key from pathArgument ...");
170         String result = null;
171         if (path != null && path.length() > 2) {
172             result = path.substring(path.lastIndexOf("=") + 1, path.length()-2);
173             LOG.info("result : {}", result);
174         } else {
175             LOG.error("String pathArgument is not compliant !!");
176         }
177         return result;
178     }
179
180     /**
181      * Delete change from Honeycomb
182      * config datastore.
183      *
184      * @param id OrgOpenroadmDevice identifier
185      * @param dataBefore OrgOpenroadmDevice before delete action
186      */
187     private void deleteChange(final InstanceIdentifier<OrgOpenroadmDevice> id, final OrgOpenroadmDevice dataBefore) {
188         LOG.info("deleting change ...");
189         WriteTransaction writeHCTx = this.honeyCombDB.newWriteOnlyTransaction();
190         if (writeHCTx != null) {
191             LOG.info("WriteTransaction is ok, delete device info from HC config datastore");
192             if(dataBefore != null) {
193                 String deviceId = dataBefore.getInfo().getNodeId();
194                 try {
195                     writeHCTx.delete(LogicalDatastoreType.CONFIGURATION, id);
196                     Future<Void> future = writeHCTx.submit();
197                     future.get();
198                     LOG.info("device '{}' deleted from HC config  datastore", deviceId);
199                 } catch (InterruptedException | ExecutionException e) {
200                     LOG.error("Failed to delete Element '{}' from datastore", deviceId);
201                 }
202             } else {
203                 LOG.error("OrgOpenroadmDevice is null");
204             }
205         } else {
206             LOG.error("WriteTransaction object is null");
207         }
208
209     }
210
211     /**
212      * Merge change to Honeycomb
213      * config datastore and device
214      * config datastore.
215      *
216      * @param id OrgOpenroadmDevice identifier
217      * @param dataAfter OrgOpenroadmDevice to be merged
218      */
219     private void processChange(final InstanceIdentifier<OrgOpenroadmDevice> id, final OrgOpenroadmDevice dataAfter) {
220         LOG.info("processing change ...");
221         WriteTransaction writeTx = this.dataBroker.newWriteOnlyTransaction();
222         WriteTransaction writeHCTx = this.honeyCombDB.newWriteOnlyTransaction();
223         if (writeTx != null && writeHCTx != null) {
224             LOG.info("WriteTransactions are ok, merge device info to datastores");
225             if(dataAfter != null) {
226                 String deviceId = dataAfter.getInfo().getNodeId();
227                 writeTx.merge(LogicalDatastoreType.OPERATIONAL, id, dataAfter);
228                 Future<Void> future = writeTx.submit();
229                 try {
230                     future.get();
231                     LOG.info("device '{}' merged to device oper datastore", deviceId);
232                     writeHCTx.merge(LogicalDatastoreType.CONFIGURATION, id, dataAfter);
233                     future = writeHCTx.submit();
234                     future.get();
235                     LOG.info("device '{}' merged to HC config datastore", deviceId);
236                 } catch (InterruptedException | ExecutionException e) {
237                     LOG.error("Failed to merge Element '{}' to datastores", deviceId);
238                 }
239             } else {
240                 LOG.error("device is null");
241             }
242         } else {
243             LOG.error("WriteTransaction object is null");
244         }
245     }
246
247 }