The provider module for the Arris designed APIs.
[packetcable.git] / packetcable-policy-server / src / main / java / org / opendaylight / controller / packetcable / provider / PacketcableProvider.java
1 package org.opendaylight.controller.packetcable.provider;
2
3 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
4 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
5 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
6 import org.opendaylight.controller.md.sal.common.api.data.AsyncReadWriteTransaction;
7 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
8 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
9 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
10 import org.opendaylight.yang.gen.v1.urn.packetcable.rev150327.Ccap;
11 import org.opendaylight.yang.gen.v1.urn.packetcable.rev150327.Qos;
12 import org.opendaylight.yang.gen.v1.urn.packetcable.rev150327.ServiceClassName;
13 import org.opendaylight.yang.gen.v1.urn.packetcable.rev150327.ServiceFlowDirection;
14 import org.opendaylight.yang.gen.v1.urn.packetcable.rev150327.ccap.Ccaps;
15 import org.opendaylight.yang.gen.v1.urn.packetcable.rev150327.ccap.CcapsKey;
16 import org.opendaylight.yang.gen.v1.urn.packetcable.rev150327.pcmm.qos.gates.Apps;
17 import org.opendaylight.yang.gen.v1.urn.packetcable.rev150327.pcmm.qos.gates.AppsKey;
18 import org.opendaylight.yang.gen.v1.urn.packetcable.rev150327.pcmm.qos.gates.apps.Subs;
19 import org.opendaylight.yang.gen.v1.urn.packetcable.rev150327.pcmm.qos.gates.apps.SubsKey;
20 import org.opendaylight.yang.gen.v1.urn.packetcable.rev150327.pcmm.qos.gates.apps.subs.Gates;
21 import org.opendaylight.yang.gen.v1.urn.packetcable.rev150327.pcmm.qos.gates.apps.subs.GatesKey;
22 import org.opendaylight.yangtools.yang.binding.DataObject;
23 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
24 import org.pcmm.rcd.IPCMMClient;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 import javax.annotation.concurrent.ThreadSafe;
29 import java.net.InetAddress;
30 import java.net.UnknownHostException;
31 import java.util.*;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.concurrent.ExecutionException;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36
37 /**
38  * Called by ODL framework to start this bundle.
39  *
40  * This class is responsible for processing messages received from ODL's restconf interface.
41  * TODO - Remove some of these state maps and move some of this into the PCMMService
42  */
43 @ThreadSafe
44 public class PacketcableProvider implements DataChangeListener, AutoCloseable {
45
46     private static final Logger logger = LoggerFactory.getLogger(PacketcableProvider.class);
47
48     // keys to the /restconf/config/packetcable:ccap and /restconf/config/packetcable:qos config datastore
49     public static final InstanceIdentifier<Ccap> ccapIID = InstanceIdentifier.builder(Ccap.class).build();
50     public static final InstanceIdentifier<Qos> qosIID = InstanceIdentifier.builder(Qos.class).build();
51
52     /**
53      * The ODL object used to broker messages throughout the framework
54      */
55     private final DataBroker dataBroker;
56
57     /**
58      * The thread pool executor
59      */
60     private final ExecutorService executor;
61
62     // TODO - Revisit these maps and remove the ones no longer necessary
63     private final Map<String, Ccaps> ccapMap = new ConcurrentHashMap<>();
64     private final Map<String, Gates> gateMap = new ConcurrentHashMap<>();
65     private final Map<String, String> gateCcapMap = new ConcurrentHashMap<>();
66     private final Map<Subnet, Ccaps> subscriberSubnetsMap = new ConcurrentHashMap<>();
67     private final Map<ServiceClassName, List<Ccaps>> downstreamScnMap = new ConcurrentHashMap<>();
68     private final Map<ServiceClassName, List<Ccaps>> upstreamScnMap = new ConcurrentHashMap<>();
69
70     /**
71      * Holds a PCMMService object for each CCAP being managed.
72      */
73     private final Map<Ccaps, PCMMService> pcmmServiceMap = new ConcurrentHashMap<>();
74
75     /**
76      * Constructor
77      */
78     public PacketcableProvider(final DataBroker dataBroker) {
79         logger.info("Starting provider");
80         this.dataBroker = dataBroker;
81         executor = Executors.newCachedThreadPool();
82     }
83
84     /**
85      * Implemented from the AutoCloseable interface.
86      */
87     @Override
88     public void close() throws ExecutionException, InterruptedException {
89         executor.shutdown();
90         if (dataBroker != null) {
91             // remove our config datastore instances
92             final AsyncReadWriteTransaction<InstanceIdentifier<?>, ?> tx = dataBroker.newReadWriteTransaction();
93             tx.delete(LogicalDatastoreType.CONFIGURATION, ccapIID);
94             tx.delete(LogicalDatastoreType.CONFIGURATION, qosIID);
95             tx.commit().get();
96         }
97     }
98
99     public InetAddress getInetAddress(final String subId){
100         try {
101             return InetAddress.getByName(subId);
102         } catch (UnknownHostException e) {
103             logger.error("getInetAddress: {} FAILED: {}", subId, e.getMessage());
104             return null;
105         }
106     }
107
108     private String getIpPrefixStr(final IpPrefix ipPrefix) {
109         final Ipv4Prefix ipv4 = ipPrefix.getIpv4Prefix();
110         if (ipv4 != null) {
111             return ipv4.getValue();
112         } else {
113             return ipPrefix.getIpv6Prefix().getValue();
114         }
115     }
116
117     private void updateCcapMaps(final Ccaps ccap) {
118         // add ccap to the subscriberSubnets map
119         for (final IpPrefix ipPrefix : ccap.getSubscriberSubnets()) {
120             try {
121                 subscriberSubnetsMap.put(Subnet.createInstance(getIpPrefixStr(ipPrefix)), ccap);
122             } catch (UnknownHostException e) {
123                 logger.error("updateSubscriberSubnets: {}:{} FAILED: {}", ipPrefix, ccap, e.getMessage());
124             }
125         }
126         // ccap to upstream SCN map
127         for (final ServiceClassName scn : ccap.getUpstreamScns()) {
128             if (upstreamScnMap.containsKey(scn)) {
129                 upstreamScnMap.get(scn).add(ccap);
130             } else {
131                 final List<Ccaps> ccapList = new ArrayList<>();
132                 ccapList.add(ccap);
133                 upstreamScnMap.put(scn, ccapList);
134             }
135         }
136         // ccap to downstream SCN map
137         for (final ServiceClassName scn : ccap.getDownstreamScns()) {
138             if (downstreamScnMap.containsKey(scn)) {
139                 downstreamScnMap.get(scn).add(ccap);
140             } else {
141                 final List<Ccaps> ccapList = new ArrayList<>();
142                 ccapList.add(ccap);
143                 downstreamScnMap.put(scn, ccapList);
144             }
145         }
146     }
147
148     private void removeCcapFromAllMaps(final Ccaps ccap) {
149         // remove the ccap from all maps
150         // subscriberSubnets map
151         for (final Map.Entry<Subnet, Ccaps> entry : subscriberSubnetsMap.entrySet()) {
152             if (entry.getValue() == ccap) {
153                 subscriberSubnetsMap.remove(entry.getKey());
154             }
155         }
156         // ccap to upstream SCN map
157         for (final Map.Entry<ServiceClassName, List<Ccaps>> entry : upstreamScnMap.entrySet()) {
158             final List<Ccaps> ccapList = entry.getValue();
159             ccapList.remove(ccap);
160             if (ccapList.isEmpty()) {
161                 upstreamScnMap.remove(entry.getKey());
162             }
163         }
164         // ccap to downstream SCN map
165         for (final Map.Entry<ServiceClassName, List<Ccaps>> entry : downstreamScnMap.entrySet()) {
166             final List<Ccaps> ccapList = entry.getValue();
167             ccapList.remove(ccap);
168             if (ccapList.isEmpty()) {
169                 downstreamScnMap.remove(entry.getKey());
170             }
171         }
172
173         final PCMMService service = pcmmServiceMap.remove(ccap);
174         if (service != null) service.disconect();
175     }
176
177     private Ccaps findCcapForSubscriberId(final InetAddress inetAddr) {
178         Ccaps matchedCcap = null;
179         int longestPrefixLen = -1;
180         for (final Map.Entry<Subnet, Ccaps> entry : subscriberSubnetsMap.entrySet()) {
181             final Subnet subnet = entry.getKey();
182             if (subnet.isInNet(inetAddr)) {
183                 int prefixLen = subnet.getPrefixLen();
184                 if (prefixLen > longestPrefixLen) {
185                     matchedCcap = entry.getValue();
186                     longestPrefixLen = prefixLen;
187                 }
188             }
189         }
190         return matchedCcap;
191     }
192
193     private ServiceFlowDirection findScnOnCcap(final ServiceClassName scn, final Ccaps ccap) {
194         if (upstreamScnMap.containsKey(scn)) {
195             final List<Ccaps> ccapList = upstreamScnMap.get(scn);
196             if (ccapList.contains(ccap)) {
197                 return ServiceFlowDirection.Us;
198             }
199         } else if (downstreamScnMap.containsKey(scn)) {
200             final List<Ccaps> ccapList = downstreamScnMap.get(scn);
201             if (ccapList.contains(ccap)) {
202                 return ServiceFlowDirection.Ds;
203             }
204         }
205         return null;
206     }
207
208     /**
209      * Implemented from the DataChangeListener interface.
210      */
211
212     private class InstanceData {
213         // CCAP Identity
214         public final Map<InstanceIdentifier<Ccaps>, Ccaps> ccapIidMap = new HashMap<>();
215         // Gate Identity
216         public String subId;
217         public final Map<String, String> gatePathMap = new HashMap<>();
218         public String gatePath;
219         public final Map<InstanceIdentifier<Gates>, Gates> gateIidMap = new HashMap<>();
220         // remove path for either CCAP or Gates
221         public final Set<String> removePathList = new HashSet<>();
222
223         public InstanceData(final Map<InstanceIdentifier<?>, DataObject> thisData) {
224             // only used to parse createdData or updatedData
225             getCcaps(thisData);
226             if (ccapIidMap.isEmpty()) {
227                 getGates(thisData);
228                 if (! gateIidMap.isEmpty()){
229                     gatePath = gatePathMap.get("appId") + "/" + gatePathMap.get("subId");
230                 }
231             }
232         }
233
234         public InstanceData(final Set<InstanceIdentifier<?>> thisData) {
235             // only used to parse the removedData paths
236             for (final InstanceIdentifier<?> removeThis : thisData) {
237                 getGatePathMap(removeThis);
238                 if (gatePathMap.containsKey("ccapId")) {
239                     gatePath = gatePathMap.get("ccapId");
240                     removePathList.add(gatePath);
241                 } else if (gatePathMap.containsKey("gateId")) {
242                     gatePath = gatePathMap.get("appId") + "/" + gatePathMap.get("subId") + "/" + gatePathMap.get("gateId");
243                     removePathList.add(gatePath);
244                 }
245             }
246         }
247         private void getGatePathMap(final InstanceIdentifier<?> thisInstance) {
248             logger.info("onDataChanged().getGatePathMap(): " + thisInstance);
249             try {
250                 final InstanceIdentifier<Ccaps> ccapInstance = thisInstance.firstIdentifierOf(Ccaps.class);
251                 if (ccapInstance != null) {
252                     final CcapsKey ccapKey = InstanceIdentifier.keyOf(ccapInstance);
253                     if (ccapKey != null) {
254                         gatePathMap.put("ccapId", ccapKey.getCcapId());
255                     }
256                 } else {
257                     // get the gate path keys from the InstanceIdentifier Map key set if they are there
258                     final InstanceIdentifier<Apps> appsInstance = thisInstance.firstIdentifierOf(Apps.class);
259                     if (appsInstance != null) {
260                         final AppsKey appKey = InstanceIdentifier.keyOf(appsInstance);
261                         if (appKey != null) {
262                             gatePathMap.put("appId", appKey.getAppId());
263                         }
264                     }
265                     final InstanceIdentifier<Subs> subsInstance = thisInstance.firstIdentifierOf(Subs.class);
266                     if (subsInstance != null) {
267                         final SubsKey subKey = InstanceIdentifier.keyOf(subsInstance);
268                         if (subKey != null) {
269                             subId = subKey.getSubId();
270                             gatePathMap.put("subId", subId);
271                         }
272                     }
273                     final InstanceIdentifier<Gates> gatesInstance = thisInstance.firstIdentifierOf(Gates.class);
274                     if (gatesInstance != null) {
275                         final GatesKey gateKey = InstanceIdentifier.keyOf(gatesInstance);
276                         if (gateKey != null) {
277                             gatePathMap.put("gateId", gateKey.getGateId());
278                         }
279                     }
280                 }
281             } catch (ClassCastException err) {
282                 logger.warn("Unexpected exception", err);
283             }
284         }
285
286         private void getCcaps(final Map<InstanceIdentifier<?>, DataObject> thisData) {
287             logger.info("onDataChanged().getCcaps(): " + thisData);
288             for (final Map.Entry<InstanceIdentifier<?>, DataObject> entry : thisData.entrySet()) {
289                 if (entry.getValue() instanceof Ccaps) {
290                     ccapIidMap.put((InstanceIdentifier<Ccaps>)entry.getKey(), (Ccaps)entry.getValue());
291                 }
292             }
293         }
294
295         private void getGates(final Map<InstanceIdentifier<?>, DataObject> thisData) {
296             logger.info("onDataChanged().getGates(): " + thisData);
297             for (final Map.Entry<InstanceIdentifier<?>, DataObject> entry : thisData.entrySet()) {
298                 if (entry.getValue() instanceof Gates) {
299                     final Gates gate = (Gates)entry.getValue();
300                     final InstanceIdentifier<Gates> gateIID = (InstanceIdentifier<Gates>)entry.getKey();
301                     getGatePathMap(gateIID);
302                     gateIidMap.put(gateIID, gate);
303                 }
304             }
305         }
306     }
307
308     @Override
309     public void onDataChanged(final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
310         logger.info("onDataChanged");
311         // Determine what change action took place by looking at the change object's InstanceIdentifier sets
312         // and validate all instance data
313         if (!change.getCreatedData().isEmpty()) {
314             if (!new ValidateInstanceData(dataBroker, change.getCreatedData()).validateYang()) {
315                 // leave now -- a bad yang object has been detected and a response object has been inserted
316                 return;
317             }
318             onCreate(new InstanceData(change.getCreatedData()));
319         } else if (!change.getRemovedPaths().isEmpty()) {
320             onRemove(new InstanceData(change.getRemovedPaths()));
321         } else if (!change.getUpdatedData().isEmpty()) {
322             if (new ValidateInstanceData(dataBroker, change.getUpdatedData()).isResponseEcho()) {
323                 // leave now -- this is an echo of the inserted response object
324                 return;
325             }
326             onUpdate(new InstanceData(change.getUpdatedData()));
327         } else {
328             // we should not be here -- complain bitterly and return
329             logger.error("onDataChanged(): Unknown change action: " + change);
330         }
331     }
332
333     private void onCreate(final InstanceData thisData) {
334         logger.info("onCreate(): " + thisData);
335
336         // get the CCAP parameters
337         String message;
338         if (! thisData.ccapIidMap.isEmpty()) {
339             for (Map.Entry<InstanceIdentifier<Ccaps>, Ccaps> entry : thisData.ccapIidMap.entrySet()) {
340                 final Ccaps thisCcap = entry.getValue();
341                 // get the CCAP node identity from the Instance Data
342                 final String ccapId = thisCcap.getCcapId();
343
344                 if (pcmmServiceMap.get(thisCcap) == null) {
345                     final PCMMService pcmmService = new PCMMService(IPCMMClient.CLIENT_TYPE, thisCcap);
346                     // TODO - may want to use the AMID but for the client type but probably not???
347 /*
348                             final PCMMService pcmmService = new PCMMService(
349                                     thisCcap.getAmId().getAmType().shortValue(), thisCcap);
350 */
351                     pcmmServiceMap.put(thisCcap, pcmmService);
352                     message = pcmmService.addCcap();
353                     if (message.contains("200 OK")) {
354                         ccapMap.put(ccapId, thisCcap);
355                         updateCcapMaps(thisCcap);
356                         logger.info("onDataChanged(): created CCAP: {}/{} : {}", thisData.gatePath, thisCcap, message);
357                         logger.info("onDataChanged(): created CCAP: {} : {}", thisData.gatePath, message);
358                     } else {
359                         logger.error("onDataChanged(): create CCAP Failed: {} : {}", thisData.gatePath, message);
360                     }
361                     // set the response string in the config ccap object using a new thread
362                     executor.execute(new Response(dataBroker, entry.getKey(), thisCcap, message));
363                 } else {
364                     logger.error("Already monitoring CCAP - " + thisCcap);
365                     break;
366                 }
367             }
368         } else {
369             // get the PCMM gate parameters from the ccapId/appId/subId/gateId path in the Maps entry (if new gate)
370             for (final Map.Entry<InstanceIdentifier<Gates>, Gates> entry : thisData.gateIidMap.entrySet()) {
371                 message = null;
372                 final Gates gate = entry.getValue();
373                 final String gateId = gate.getGateId();
374                 final String gatePathStr = thisData.gatePath + "/" + gateId ;
375                 final InetAddress subId = getInetAddress(thisData.subId);
376                 if (subId != null) {
377                     final Ccaps thisCcap = findCcapForSubscriberId(subId);
378                     if (thisCcap != null) {
379                         final String ccapId = thisCcap.getCcapId();
380                         // verify SCN exists on CCAP and force gateSpec.Direction to align with SCN direction
381                         final ServiceClassName scn = gate.getTrafficProfile().getServiceClassName();
382                         if (scn != null) {
383                             final ServiceFlowDirection scnDir = findScnOnCcap(scn, thisCcap);
384                             if (scnDir != null) {
385                                 if (pcmmServiceMap.get(thisCcap) != null) {
386                                     message = pcmmServiceMap.get(thisCcap).sendGateSet(gatePathStr, subId, gate, scnDir);
387                                     if (message.contains("200 OK")) {
388                                         gateMap.put(gatePathStr, gate);
389                                         gateCcapMap.put(gatePathStr, thisCcap.getCcapId());
390                                         logger.info("onDataChanged(): created QoS gate {} for {}/{}/{} - {}",
391                                                 gateId, ccapId, gatePathStr, gate, message);
392                                         logger.info("onDataChanged(): created QoS gate {} for {}/{} - {}",
393                                                 gateId, ccapId, gatePathStr, message);
394                                     } else {
395                                         logger.info("onDataChanged(): Unable to create QoS gate {} for {}/{}/{} - {}",
396                                                 gateId, ccapId, gatePathStr, gate, message);
397                                         logger.error("onDataChanged(): Unable to create QoS gate {} for {}/{} - {}",
398                                                 gateId, ccapId, gatePathStr, message);
399                                     }
400                                 } else {
401                                     logger.error("Unable to locate PCMM Service for CCAP - " + thisCcap);
402                                     break;
403                                 }
404                             } else {
405                                 logger.error("PCMMService: sendGateSet(): SCN {} not found on CCAP {} for {}/{}",
406                                         scn.getValue(), thisCcap, gatePathStr, gate);
407                                 message = String.format("404 Not Found - SCN %s not found on CCAP %s for %s",
408                                         scn.getValue(), thisCcap.getCcapId(), gatePathStr);
409                             }
410                         }
411                     } else {
412                         final String subIdStr = thisData.subId;
413                         message = String.format("404 Not Found - no CCAP found for subscriber %s in %s",
414                                 subIdStr, gatePathStr);
415                         logger.info("onDataChanged(): create QoS gate {} FAILED: no CCAP found for subscriber {}: @ {}/{}",
416                                 gateId, subIdStr, gatePathStr, gate);
417                         logger.error("onDataChanged(): create QoS gate {} FAILED: no CCAP found for subscriber {}: @ {}",
418                                 gateId, subIdStr, gatePathStr);
419                     }
420                 } else {
421                     final String subIdStr = thisData.subId;
422                     message = String.format("400 Bad Request - subId must be a valid IP address for subscriber %s in %s",
423                             subIdStr, gatePathStr);
424                     logger.info("onDataChanged(): create QoS gate {} FAILED: subId must be a valid IP address for subscriber {}: @ {}/{}",
425                             gateId, subIdStr, gatePathStr, gate);
426                     logger.error("onDataChanged(): create QoS gate {} FAILED: subId must be a valid IP address for subscriber {}: @ {}",
427                             gateId, subIdStr, gatePathStr);
428                 }
429                 // set the response message in the config gate object using a new thread
430                 executor.execute(new Response(dataBroker, entry.getKey(), gate, message));
431             }
432         }
433     }
434
435     private void onRemove(final InstanceData thisData) {
436         logger.info("onRemove(): " + thisData);
437         for (final String gatePathStr: thisData.removePathList) {
438             if (gateMap.containsKey(gatePathStr)) {
439                 final Gates thisGate = gateMap.remove(gatePathStr);
440                 final String gateId = thisGate.getGateId();
441                 final String ccapId = gateCcapMap.remove(gatePathStr);
442                 final Ccaps thisCcap = ccapMap.get(ccapId);
443                 final PCMMService service = pcmmServiceMap.get(thisCcap);
444                 if (service != null) {
445                     service.sendGateDelete(thisCcap, gatePathStr);
446                     logger.info("onDataChanged(): removed QoS gate {} for {}/{}/{}: ", gateId, ccapId, gatePathStr, thisGate);
447                     logger.info("onDataChanged(): removed QoS gate {} for {}/{}: ", gateId, ccapId, gatePathStr);
448                 } else
449                     logger.warn("Unable to send to locate PCMMService to send gate delete message with CCAP - "
450                             + thisCcap);
451             }
452         }
453         for (final String ccapIdStr: thisData.removePathList) {
454             if (ccapMap.containsKey(ccapIdStr)) {
455                 final Ccaps thisCcap = ccapMap.remove(ccapIdStr);
456                 removeCcapFromAllMaps(thisCcap);
457             }
458         }
459     }
460
461     private void onUpdate(final InstanceData oldData) {
462         logger.info("onUpdate(): " + oldData);
463         // update operation not allowed -- restore the original config object and complain
464         if (! oldData.ccapIidMap.isEmpty()) {
465             for (final Map.Entry<InstanceIdentifier<Ccaps>, Ccaps> entry : oldData.ccapIidMap.entrySet()) {
466                 final Ccaps ccap = entry.getValue();
467                 final String ccapId = ccap.getCcapId();
468                 String message = String.format("405 Method Not Allowed - %s: CCAP update not permitted (use delete); ",
469                         ccapId);
470                 // push new error message onto existing response
471                 message += ccap.getResponse();
472                 // set the response message in the config object using a new thread -- also restores the original data
473                 executor.execute(new Response(dataBroker, entry.getKey(), ccap, message));
474                 logger.error("onDataChanged(): CCAP update not permitted {}/{}", ccapId, ccap);
475             }
476         } else {
477             for (final Map.Entry<InstanceIdentifier<Gates>, Gates> entry : oldData.gateIidMap.entrySet()) {
478                 final Gates gate = entry.getValue();
479                 final String gatePathStr = oldData.gatePath + "/" + gate.getGateId() ;
480                 String message = String.format("405 Method Not Allowed - %s: QoS Gate update not permitted (use delete); ", gatePathStr);
481                 // push new error message onto existing response
482                 message += gate.getResponse();
483                 // set the response message in the config object using a new thread -- also restores the original data
484                 executor.execute(new Response(dataBroker, entry.getKey(), gate, message));
485                 logger.error("onDataChanged(): QoS Gate update not permitted: {}/{}", gatePathStr, gate);
486             }
487         }
488     }
489
490 }