6778bae2acf76c0afcacb4ceb0a52d9dcce3eacc
[honeycomb.git] / nsh / impl / src / main / java / io / fd / honeycomb / vppnsh / impl / util / JVppNshProvider.java
1 /*
2  * Copyright (c) 2016 Intel and 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.vppnsh.impl.util;
18
19 import com.google.inject.Inject;
20 import io.fd.honeycomb.infra.distro.ProviderTrait;
21 import io.fd.vpp.jvpp.JVppRegistry;
22 import io.fd.vpp.jvpp.nsh.JVppNshImpl;
23 import io.fd.vpp.jvpp.nsh.future.FutureJVppNshFacade;
24 import java.io.IOException;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 /**
29  * Provides future API for jvpp-nsh plugin. Must be a singleton due to shutdown hook usage.
30  * Registers shutdown hook to free plugin's resources on shutdown.
31  */
32 public final class JVppNshProvider extends ProviderTrait<FutureJVppNshFacade> {
33
34     private static final Logger LOG = LoggerFactory.getLogger(JVppNshProvider.class);
35
36     @Inject
37     private JVppRegistry registry;
38
39     @Override
40     protected FutureJVppNshFacade create() {
41         try {
42             final JVppNshImpl jVppNsh = new JVppNshImpl();
43             // Free jvpp-nsh plugin's resources on shutdown
44             Runtime.getRuntime().addShutdownHook(new Thread() {
45                 @Override
46                 public void run() {
47                     LOG.info("Unloading jvpp-nsh plugin");
48                     jVppNsh.close();
49                     LOG.info("Successfully unloaded jvpp-nsh plugin");
50                 }
51             });
52
53             LOG.info("Successfully loaded jvpp-nsh plugin");
54             return new FutureJVppNshFacade(registry, jVppNsh);
55         } catch (IOException e) {
56             throw new IllegalStateException("Unable to open VPP management connection", e);
57         }
58     }
59 }
60