300e03806977f871310b5539b3b4d361f61fee84
[hc2vpp.git] /
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.hc2vpp.common.integration;
18
19 import com.google.common.base.Charsets;
20 import com.google.common.io.CharStreams;
21 import com.google.common.primitives.UnsignedInts;
22 import com.google.inject.Inject;
23 import io.fd.honeycomb.binding.init.ProviderTrait;
24 import io.fd.honeycomb.data.init.ShutdownHandler;
25 import io.fd.vpp.jvpp.JVppRegistry;
26 import io.fd.vpp.jvpp.JVppRegistryImpl;
27 import io.fd.vpp.jvpp.VppJNIConnection;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 import java.io.BufferedInputStream;
32 import java.io.IOException;
33 import java.io.InputStreamReader;
34
35 import static com.google.common.base.Preconditions.checkState;
36 import static java.lang.String.format;
37
38 /**
39  * Provides JVppRegistry. Must be a singleton due to shutdown hook usage. Registers shutdown hook to disconnect from
40  * VPP.
41  */
42 public final class JVppRegistryProvider extends ProviderTrait<JVppRegistry> {
43
44     private static final Logger LOG = LoggerFactory.getLogger(JVppRegistryProvider.class);
45
46     @Inject
47     private VppConfigAttributes config;
48     @Inject
49     private ShutdownHandler shutdownHandler;
50
51     private long connectedVppPid;
52
53     @Override
54     protected JVppRegistry create() {
55         final JVppRegistry registry;
56         try {
57             registry = new JVppRegistryImpl(config.jvppConnectionName);
58             connectedVppPid = initConnectedVppPid(registry);
59             shutdownHandler.register("jvpp-registry", () -> {
60                 // Closing JVpp connection with shutdown hook to erase the connection from VPP so HC will be able
61                 // to connect next time. If JVM is force closed, this will not be executed and VPP connection
62                 // with name from config will stay open and prevent next startup of HC to success
63
64                 LOG.info("Disconnecting from VPP");
65
66                 // Handles restart honeycomb service or restart vpp service
67                 // this tells whether vpp that was honeycomb connected to is running(true) or some other instance of vpp is
68                 // running(false). This happens when honeycomb is restarted together with vpp using && ,therefore vpp restarts
69                 // before honeycomb shutdown starts, and keepalive does not have enough time to trigger therefore vpp
70                 // status listener says that vpp is running. This condition prevents honeycomb to invoke disconnect on different vpp
71                 // instance than it was connected to, which would ultimately lead to vpp being in state that is unresponsive
72                 // to connection attempts.
73                 if (isConnectedVppRunning(connectedVppPid)) {
74                     registry.close();
75                     LOG.info("Successfully disconnected from VPP as {}", config.jvppConnectionName);
76                 } else {
77                     // Handles restart vpp && honeycomb service
78                     LOG.info("VPP instance used for jvpp connection is not alive anymore, no need to disconnect");
79                 }
80             });
81         } catch (IOException e) {
82             throw new IllegalStateException("Unable to open VPP management connection", e);
83         }
84         LOG.info("JVpp connection opened successfully as: {}", config.jvppConnectionName);
85         return registry;
86     }
87
88     /**
89      * Tells whether vpp instance that was used for connection is still running
90      */
91     private static boolean isConnectedVppRunning(final long connectedVppPid) {
92         try {
93             final Process process = Runtime.getRuntime().exec(format("ps -eo pid|grep %s", connectedVppPid));
94
95             final BufferedInputStream input = new BufferedInputStream(process.getInputStream());
96             final String processOut = CharStreams.toString(new InputStreamReader(input, Charsets.UTF_8));
97             return processOut.trim().contains(String.valueOf(connectedVppPid));
98         } catch (IOException e) {
99             throw new IllegalStateException(e);
100         }
101     }
102
103     /**
104      * Read process id of currently connected vpp
105      */
106     private static long initConnectedVppPid(final JVppRegistry jVppRegistry) {
107         checkState(jVppRegistry.getConnection() instanceof VppJNIConnection, "Connection is not %s", VppJNIConnection.class);
108         final VppJNIConnection jniConnection = VppJNIConnection.class.cast(jVppRegistry.getConnection());
109         final VppJNIConnection.ConnectionInfo jniConnectionInfo = VppJNIConnection.ConnectionInfo.class.cast(
110                 jniConnection.getConnectionInfo());
111
112         return UnsignedInts.toLong(jniConnectionInfo.pid);
113     }
114 }