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