Adapt lighty to run with optional karaf features
[transportpce.git] / lighty / src / main / java / io / lighty / controllers / tpce / Main.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies s.r.o. All Rights Reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at https://www.eclipse.org/legal/epl-v10.html
7  */
8 package io.lighty.controllers.tpce;
9
10 import io.lighty.controllers.tpce.exception.TechnicalException;
11 import io.lighty.controllers.tpce.module.TransportPCE;
12 import io.lighty.controllers.tpce.module.TransportPCEImpl;
13 import io.lighty.controllers.tpce.utils.TPCEUtils;
14 import io.lighty.controllers.tpce.utils.TpceBanner;
15 import io.lighty.core.controller.api.LightyController;
16 import io.lighty.core.controller.api.LightyModule;
17 import io.lighty.core.controller.impl.LightyControllerBuilder;
18 import io.lighty.core.controller.impl.config.ConfigurationException;
19 import io.lighty.core.controller.impl.config.ControllerConfiguration;
20 import io.lighty.core.controller.impl.util.ControllerConfigUtils;
21 import io.lighty.modules.northbound.restconf.community.impl.CommunityRestConf;
22 import io.lighty.modules.northbound.restconf.community.impl.CommunityRestConfBuilder;
23 import io.lighty.modules.northbound.restconf.community.impl.config.JsonRestConfServiceType;
24 import io.lighty.modules.northbound.restconf.community.impl.config.RestConfConfiguration;
25 import io.lighty.modules.northbound.restconf.community.impl.util.RestConfConfigUtils;
26 import io.lighty.modules.southbound.netconf.impl.NetconfSBPlugin;
27 import io.lighty.modules.southbound.netconf.impl.NetconfTopologyPluginBuilder;
28 import io.lighty.modules.southbound.netconf.impl.config.NetconfConfiguration;
29 import io.lighty.modules.southbound.netconf.impl.util.NetconfConfigUtils;
30 import io.lighty.server.LightyServerBuilder;
31 import java.io.IOException;
32 import java.net.InetSocketAddress;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.nio.file.Paths;
36 import java.util.concurrent.ExecutionException;
37 import org.apache.commons.cli.CommandLine;
38 import org.apache.commons.cli.DefaultParser;
39 import org.apache.commons.cli.HelpFormatter;
40 import org.apache.commons.cli.Option;
41 import org.apache.commons.cli.Options;
42 import org.apache.commons.cli.ParseException;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 public class Main {
47
48     private static final String RESTCONF_OPTION_NAME = "restconf";
49     private static final String NBINOTIFICATION_OPTION_NAME = "nbinotification";
50     private static final String TAPI_OPTION_NAME = "tapi";
51     private static final String OLMTIMER1_OPTION_NAME = "olmtimer1";
52     private static final String OLMTIMER2_OPTION_NAME = "olmtimer2";
53
54     private static final Logger LOG = LoggerFactory.getLogger(Main.class);
55
56     private ShutdownHook shutdownHook;
57
58     public void start() {
59         start(null, false, false, null, null, false);
60     }
61
62     @SuppressWarnings("checkstyle:Illegalcatch")
63     public void start(String restConfConfigurationFile, boolean activateNbiNotification, boolean activateTapi,
64                       String olmtimer1, String olmtimer2, boolean registerShutdownHook) {
65         long startTime = System.nanoTime();
66         TpceBanner.print();
67         RestConfConfiguration restConfConfig = null;
68         try {
69             // 1. get controller configuration
70             ControllerConfiguration singleNodeConfiguration = ControllerConfigUtils
71                     .getDefaultSingleNodeConfiguration(TPCEUtils.getYangModels());
72             // 2. get RESTCONF NBP configuration
73             if (restConfConfigurationFile != null) {
74                 Path configPath = Paths.get(restConfConfigurationFile);
75                 LOG.info("Using restconf configuration from file {} ...", configPath);
76                 restConfConfig = RestConfConfigUtils.getRestConfConfiguration(Files.newInputStream(configPath));
77
78             } else {
79                 LOG.info("Using default restconf configuration with http port 8181 ...");
80
81                 restConfConfig = RestConfConfigUtils.getDefaultRestConfConfiguration();
82                 restConfConfig.setHttpPort(8181);
83
84             }
85             restConfConfig.setJsonRestconfServiceType(JsonRestConfServiceType.DRAFT_02);
86             // 3. NETCONF SBP configuration
87             NetconfConfiguration netconfSBPConfig = NetconfConfigUtils.createDefaultNetconfConfiguration();
88             startLighty(singleNodeConfiguration, restConfConfig, netconfSBPConfig, registerShutdownHook,
89                     activateNbiNotification, activateTapi, olmtimer1, olmtimer2);
90             float duration = (System.nanoTime() - startTime) / 1_000_000f;
91             LOG.info("lighty.io and RESTCONF-NETCONF started in {}ms", duration);
92         } catch (ConfigurationException | ExecutionException | IOException e) {
93             LOG.error("An error occured while starting application: ", e);
94             throw new TechnicalException("An error occured while starting application", e);
95         } catch (InterruptedException e) {
96             LOG.error("Application start interrupted : ", e);
97             Thread.currentThread().interrupt();
98             throw new TechnicalException("Application start interrupted", e);
99           //CHECKSTYLE:OFF
100         } catch (Exception e) {
101           //CHECKSTYLE:ON
102             LOG.error("Application start unmanaged exception : ", e);
103             throw new TechnicalException("Application start unmanaged exception", e);
104
105         }
106     }
107
108     /*
109      * Build options for command line arguments.
110      */
111     private static Options buildOptions() {
112         Option restconfFileOption = Option.builder(RESTCONF_OPTION_NAME)
113                 .desc("Restconf configuration file")
114                 .argName(RESTCONF_OPTION_NAME)
115                 .hasArg(true)
116                 .required(false)
117                 .build();
118         Option useNbiNotificationsOption = Option.builder(NBINOTIFICATION_OPTION_NAME)
119             .desc("Activate NBI notifications feature")
120             .argName(NBINOTIFICATION_OPTION_NAME)
121             .hasArg(false)
122             .required(false)
123             .build();
124         Option useTapiOption = Option.builder(TAPI_OPTION_NAME)
125             .desc("Activate TAPI feature")
126             .argName(TAPI_OPTION_NAME)
127             .hasArg(false)
128             .required(false)
129             .build();
130         Option olmTimer1Option = Option.builder(OLMTIMER1_OPTION_NAME)
131                 .desc("OLM timer 1 value")
132                 .argName(OLMTIMER1_OPTION_NAME)
133                 .hasArg(true)
134                 .required(false)
135                 .build();
136         Option olmTimer2Option = Option.builder(OLMTIMER2_OPTION_NAME)
137                 .desc("OLM timer 2 value")
138                 .argName(OLMTIMER1_OPTION_NAME)
139                 .hasArg(true)
140                 .required(false)
141                 .build();
142         Options options = new Options();
143         options.addOption(restconfFileOption);
144         options.addOption(useNbiNotificationsOption);
145         options.addOption(useTapiOption);
146         options.addOption(olmTimer1Option);
147         options.addOption(olmTimer2Option);
148         return options;
149     }
150
151     private void startLighty(ControllerConfiguration controllerConfiguration,
152             RestConfConfiguration restConfConfiguration, NetconfConfiguration netconfSBPConfiguration,
153             boolean registerShutdownHook, boolean activateNbiNotification, boolean activateTapi, String olmtimer1,
154             String olmtimer2) throws ConfigurationException, ExecutionException, InterruptedException {
155
156         // 1. initialize and start Lighty controller (MD-SAL, Controller, YangTools,
157         // Akka)
158         LightyControllerBuilder lightyControllerBuilder = new LightyControllerBuilder();
159         LightyController lightyController = lightyControllerBuilder.from(controllerConfiguration).build();
160         lightyController.start().get();
161
162         // 2. start RestConf server
163         LightyServerBuilder jettyServerBuilder = new LightyServerBuilder(
164                 new InetSocketAddress(restConfConfiguration.getInetAddress(), restConfConfiguration.getHttpPort()));
165         CommunityRestConfBuilder communityRestConfBuilder = CommunityRestConfBuilder.from(
166                 RestConfConfigUtils.getRestConfConfiguration(restConfConfiguration, lightyController.getServices()));
167         CommunityRestConf communityRestConf = communityRestConfBuilder.withLightyServer(jettyServerBuilder).build();
168         communityRestConf.start().get();
169         communityRestConf.startServer();
170
171         // 3. start NetConf SBP
172         NetconfSBPlugin netconfSouthboundPlugin;
173         netconfSBPConfiguration = NetconfConfigUtils.injectServicesToTopologyConfig(netconfSBPConfiguration,
174                 lightyController.getServices());
175         NetconfTopologyPluginBuilder netconfSBPBuilder = new NetconfTopologyPluginBuilder(
176                 lightyController.getServices(), netconfSBPConfiguration);
177         netconfSouthboundPlugin = netconfSBPBuilder.from(netconfSBPConfiguration, lightyController.getServices())
178                 .build();
179         netconfSouthboundPlugin.start().get();
180
181         // 4. start TransportPCE beans
182         TransportPCE transportPCE = new TransportPCEImpl(lightyController.getServices(), activateNbiNotification,
183             activateTapi, olmtimer1, olmtimer2);
184         transportPCE.start().get();
185
186         // 5. Register shutdown hook for graceful shutdown.
187         shutdownHook = new ShutdownHook(lightyController, communityRestConf, netconfSouthboundPlugin, transportPCE);
188         if (registerShutdownHook) {
189             Runtime.getRuntime().addShutdownHook(shutdownHook);
190         }
191     }
192
193     public void shutdown() {
194         shutdownHook.run();
195     }
196
197     public static void main(String[] args) {
198         Options options = buildOptions();
199         try {
200             CommandLine commandLine = new DefaultParser().parse(options, args);
201             String restConfConfigurationFile = commandLine.getOptionValue(RESTCONF_OPTION_NAME, null);
202             boolean useNbiNotifications = commandLine.hasOption(NBINOTIFICATION_OPTION_NAME);
203             boolean useTapi = commandLine.hasOption(TAPI_OPTION_NAME);
204             String olmtimer1 = commandLine.getOptionValue(OLMTIMER1_OPTION_NAME, null);
205             String olmtimer2 = commandLine.getOptionValue(OLMTIMER2_OPTION_NAME, null);
206             Main app = new Main();
207             app.start(restConfConfigurationFile, useNbiNotifications, useTapi, olmtimer1, olmtimer2, true);
208         } catch (ParseException e) {
209             HelpFormatter formatter = new HelpFormatter();
210             formatter.printHelp(
211                     "java -ms<size> -mx<size> -XX:MaxMetaspaceSize=<size> -jar tpce.jar "
212                     + "[-restconf <restconfConfigurationFile>] [-nbinotification]"
213                     + " e.g. java -ms128m -mx512m -XX:MaxMetaspaceSize=128m -jar tpce.jar"
214                     + "-restconf ../src/test/resources/config.json -nbinotification"
215                     + "-olmtimer1 120000 -olmtimer2 20000",
216                     options);
217             System.exit(1);
218         }
219     }
220
221     private static class ShutdownHook extends Thread {
222
223         private static final Logger LOG = LoggerFactory.getLogger(ShutdownHook.class);
224         private final LightyController lightyController;
225         private final CommunityRestConf communityRestConf;
226         private final LightyModule netconfSouthboundPlugin;
227         private final TransportPCE transportPCE;
228
229         ShutdownHook(LightyController lightyController, CommunityRestConf communityRestConf,
230                 LightyModule netconfSouthboundPlugin, TransportPCE transportPCE) {
231             this.lightyController = lightyController;
232             this.communityRestConf = communityRestConf;
233             this.netconfSouthboundPlugin = netconfSouthboundPlugin;
234             this.transportPCE = transportPCE;
235         }
236
237         @Override
238         @SuppressWarnings({"checkstyle:Illegalcatch", "checkstyle:VariableDeclarationUsageDistance"})
239         public void run() {
240             LOG.info("lighty.io and RESTCONF-NETCONF shutting down ...");
241             long startTime = System.nanoTime();
242             try {
243                 transportPCE.shutdown().get();
244             } catch (Exception e) {
245                 LOG.error("Exception while shutting down TransportPCE: ", e);
246             }
247             try {
248                 communityRestConf.shutdown().get();
249             } catch (Exception e) {
250                 LOG.error("Exception while shutting down RESTCONF: ", e);
251             }
252             try {
253                 netconfSouthboundPlugin.shutdown().get();
254             } catch (Exception e) {
255                 LOG.error("Exception while shutting down NETCONF: ", e);
256             }
257             try {
258                 lightyController.shutdown().get();
259             } catch (Exception e) {
260                 LOG.error("Exception while shutting down lighty.io controller:", e);
261             }
262             float duration = (System.nanoTime() - startTime) / 1_000_000f;
263             LOG.info("lighty.io and RESTCONF-NETCONF stopped in {}ms", duration);
264         }
265
266     }
267
268 }