HONEYCOMB-21 Vpp-integration minimal distribution
[honeycomb.git] / v3po / v3po2vpp / src / main / java / io / fd / honeycomb / translate / v3po / notification / InterfaceChangeNotificationProducer.java
1 /*
2  * Copyright (c) 2016 Cisco 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.translate.v3po.notification;
17
18 import com.google.common.base.Optional;
19 import com.google.common.collect.Lists;
20 import com.google.inject.Inject;
21 import com.google.inject.name.Named;
22 import io.fd.honeycomb.notification.ManagedNotificationProducer;
23 import io.fd.honeycomb.notification.NotificationCollector;
24 import io.fd.honeycomb.translate.MappingContext;
25 import io.fd.honeycomb.translate.v3po.util.NamingContext;
26 import io.fd.honeycomb.translate.v3po.util.TranslateUtils;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.concurrent.CompletionStage;
30 import java.util.concurrent.TimeoutException;
31 import javax.annotation.Nonnull;
32 import javax.annotation.Nullable;
33 import javax.annotation.concurrent.NotThreadSafe;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.InterfaceDeleted;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.InterfaceDeletedBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.InterfaceNameOrIndex;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.InterfaceStateChange;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.InterfaceStateChangeBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.InterfaceStatus;
40 import org.opendaylight.yangtools.yang.binding.Notification;
41 import org.openvpp.jvpp.VppBaseCallException;
42 import org.openvpp.jvpp.dto.SwInterfaceSetFlagsNotification;
43 import org.openvpp.jvpp.dto.WantInterfaceEvents;
44 import org.openvpp.jvpp.dto.WantInterfaceEventsReply;
45 import org.openvpp.jvpp.future.FutureJVpp;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * Notification producer for interface events. It starts interface notification stream and for every
51  * received notification, it transforms it into its BA equivalent and pushes into HC's notification collector.
52  */
53 @NotThreadSafe
54 public final class InterfaceChangeNotificationProducer implements ManagedNotificationProducer {
55
56     private static final Logger LOG = LoggerFactory.getLogger(InterfaceChangeNotificationProducer.class);
57
58     private final FutureJVpp jvpp;
59     private final NamingContext interfaceContext;
60     private final MappingContext mappingContext;
61     @Nullable
62     private AutoCloseable notificationListenerReg;
63
64     @Inject
65     public InterfaceChangeNotificationProducer(@Nonnull final FutureJVpp jvpp,
66                                                @Named("interface-context") @Nonnull final NamingContext interfaceContext,
67                                                @Named("honeycomb-context") @Nonnull final MappingContext mappingContext) {
68         this.jvpp = jvpp;
69         this.interfaceContext = interfaceContext;
70         this.mappingContext = mappingContext;
71     }
72
73     @Override
74     public void start(final NotificationCollector collector) {
75         LOG.trace("Starting interface notifications");
76         enableDisableIfcNotifications(1);
77         LOG.debug("Interface notifications started successfully");
78         notificationListenerReg = jvpp.getNotificationRegistry().registerSwInterfaceSetFlagsNotificationCallback(
79             swInterfaceSetFlagsNotification -> {
80                 LOG.trace("Interface notification received: {}", swInterfaceSetFlagsNotification);
81                 // TODO this should be lazy
82                 collector.onNotification(transformNotification(swInterfaceSetFlagsNotification));
83             }
84         );
85     }
86
87     private Notification transformNotification(final SwInterfaceSetFlagsNotification swInterfaceSetFlagsNotification) {
88         if (swInterfaceSetFlagsNotification.deleted == 1) {
89             return new InterfaceDeletedBuilder().setName(getIfcName(swInterfaceSetFlagsNotification)).build();
90         } else {
91             return new InterfaceStateChangeBuilder()
92                 .setName(getIfcName(swInterfaceSetFlagsNotification))
93                 .setAdminStatus(swInterfaceSetFlagsNotification.adminUpDown == 1 ? InterfaceStatus.Up : InterfaceStatus.Down)
94                 .setOperStatus(swInterfaceSetFlagsNotification.linkUpDown == 1 ? InterfaceStatus.Up : InterfaceStatus.Down)
95                 .build();
96         }
97     }
98
99     /**
100      * Get mapped name for the interface. Best effort only! The mapping might not yet be stored in context
101      * data tree (write transaction is still in progress and context changes have not been committed yet, or
102      * VPP sends the notification before it returns create request(that would store mapping)).
103      * <p/>
104      * In case mapping is not available, index is used as name. TODO inconsistent behavior, maybe just use indices ?
105      */
106     private InterfaceNameOrIndex getIfcName(final SwInterfaceSetFlagsNotification swInterfaceSetFlagsNotification) {
107         final Optional<String> optionalName =
108                 interfaceContext.getNameIfPresent(swInterfaceSetFlagsNotification.swIfIndex, mappingContext);
109         return optionalName.isPresent()
110             ? new InterfaceNameOrIndex(optionalName.get())
111             : new InterfaceNameOrIndex((long) swInterfaceSetFlagsNotification.swIfIndex);
112     }
113
114     @Override
115     public void stop() {
116         LOG.trace("Stopping interface notifications");
117         enableDisableIfcNotifications(0);
118         LOG.debug("Interface notifications stopped successfully");
119         try {
120             if (notificationListenerReg != null) {
121                 notificationListenerReg.close();
122             }
123         } catch (Exception e) {
124             LOG.warn("Unable to properly close notification registration: {}", notificationListenerReg, e);
125         }
126     }
127
128     private void enableDisableIfcNotifications(int enableDisable) {
129         final WantInterfaceEvents wantInterfaceEvents = new WantInterfaceEvents();
130         wantInterfaceEvents.pid = 1;
131         wantInterfaceEvents.enableDisable = enableDisable;
132         final CompletionStage<WantInterfaceEventsReply> wantInterfaceEventsReplyCompletionStage;
133         try {
134             wantInterfaceEventsReplyCompletionStage = jvpp.wantInterfaceEvents(wantInterfaceEvents);
135             TranslateUtils.getReply(wantInterfaceEventsReplyCompletionStage.toCompletableFuture());
136         } catch (VppBaseCallException | TimeoutException e) {
137             LOG.warn("Unable to {} interface notifications", enableDisable == 1 ? "enable" : "disable",  e);
138             throw new IllegalStateException("Unable to control interface notifications", e);
139         }
140     }
141
142     @Nonnull
143     @Override
144     public Collection<Class<? extends Notification>> getNotificationTypes() {
145         final ArrayList<Class<? extends Notification>> classes = Lists.newArrayList();
146         classes.add(InterfaceStateChange.class);
147         classes.add(InterfaceDeleted.class);
148         return classes;
149     }
150
151     @Override
152     public void close() throws Exception {
153         LOG.trace("Closing interface notifications producer");
154         stop();
155     }
156 }