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