Refactor OLM timers management
[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 OLMTIMER1_OPTION_NAME = "olmtimer1";
51     private static final String OLMTIMER2_OPTION_NAME = "olmtimer2";
52
53     private static final Logger LOG = LoggerFactory.getLogger(Main.class);
54
55     private ShutdownHook shutdownHook;
56
57     public void start() {
58         start(null, false, null, null, false);
59     }
60
61     @SuppressWarnings("checkstyle:Illegalcatch")
62     public void start(String restConfConfigurationFile, boolean activateNbiNotification,
63                       String olmtimer1, String olmtimer2, boolean registerShutdownHook) {
64         long startTime = System.nanoTime();
65         TpceBanner.print();
66         RestConfConfiguration restConfConfig = null;
67         try {
68             // 1. get controller configuration
69             ControllerConfiguration singleNodeConfiguration = ControllerConfigUtils
70                     .getDefaultSingleNodeConfiguration(TPCEUtils.getYangModels());
71             // 2. get RESTCONF NBP configuration
72             if (restConfConfigurationFile != null) {
73                 Path configPath = Paths.get(restConfConfigurationFile);
74                 LOG.info("Using restconf configuration from file {} ...", configPath);
75                 restConfConfig = RestConfConfigUtils.getRestConfConfiguration(Files.newInputStream(configPath));
76
77             } else {
78                 LOG.info("Using default restconf configuration with http port 8181 ...");
79
80                 restConfConfig = RestConfConfigUtils.getDefaultRestConfConfiguration();
81                 restConfConfig.setHttpPort(8181);
82
83             }
84             restConfConfig.setJsonRestconfServiceType(JsonRestConfServiceType.DRAFT_02);
85             // 3. NETCONF SBP configuration
86             NetconfConfiguration netconfSBPConfig = NetconfConfigUtils.createDefaultNetconfConfiguration();
87             startLighty(singleNodeConfiguration, restConfConfig, netconfSBPConfig, registerShutdownHook,
88                     activateNbiNotification, olmtimer1, olmtimer2);
89             float duration = (System.nanoTime() - startTime) / 1_000_000f;
90             LOG.info("lighty.io and RESTCONF-NETCONF started in {}ms", duration);
91         } catch (ConfigurationException | ExecutionException | IOException e) {
92             LOG.error("An error occured while starting application: ", e);
93             throw new TechnicalException("An error occured while starting application", e);
94         } catch (InterruptedException e) {
95             LOG.error("Application start interrupted : ", e);
96             Thread.currentThread().interrupt();
97             throw new TechnicalException("Application start interrupted", e);
98           //CHECKSTYLE:OFF
99         } catch (Exception e) {
100           //CHECKSTYLE:ON
101             LOG.error("Application start unmanaged exception : ", e);
102             throw new TechnicalException("Application start unmanaged exception", e);
103
104         }
105     }
106
107     /**
108      * Build options for command line arguments.
109      * @return
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 olmTimer1Option = Option.builder(OLMTIMER1_OPTION_NAME)
125                 .desc("OLM timer 1 value")
126                 .argName(OLMTIMER1_OPTION_NAME)
127                 .hasArg(true)
128                 .required(false)
129                 .build();
130         Option olmTimer2Option = Option.builder(OLMTIMER2_OPTION_NAME)
131                 .desc("OLM timer 2 value")
132                 .argName(OLMTIMER1_OPTION_NAME)
133                 .hasArg(true)
134                 .required(false)
135                 .build();
136         Options options = new Options();
137         options.addOption(restconfFileOption);
138         options.addOption(useNbiNotificationsOption);
139         options.addOption(olmTimer1Option);
140         options.addOption(olmTimer2Option);
141         return options;
142     }
143
144     private void startLighty(ControllerConfiguration controllerConfiguration,
145             RestConfConfiguration restConfConfiguration, NetconfConfiguration netconfSBPConfiguration,
146             boolean registerShutdownHook, boolean activateNbiNotification, String olmtimer1, String olmtimer2)
147                     throws ConfigurationException, ExecutionException, InterruptedException {
148
149         // 1. initialize and start Lighty controller (MD-SAL, Controller, YangTools,
150         // Akka)
151         LightyControllerBuilder lightyControllerBuilder = new LightyControllerBuilder();
152         LightyController lightyController = lightyControllerBuilder.from(controllerConfiguration).build();
153         lightyController.start().get();
154
155         // 2. start RestConf server
156         LightyServerBuilder jettyServerBuilder = new LightyServerBuilder(
157                 new InetSocketAddress(restConfConfiguration.getInetAddress(), restConfConfiguration.getHttpPort()));
158         CommunityRestConfBuilder communityRestConfBuilder = CommunityRestConfBuilder.from(
159                 RestConfConfigUtils.getRestConfConfiguration(restConfConfiguration, lightyController.getServices()));
160         CommunityRestConf communityRestConf = communityRestConfBuilder.withLightyServer(jettyServerBuilder).build();
161         communityRestConf.start().get();
162         communityRestConf.startServer();
163
164         // 3. start NetConf SBP
165         NetconfSBPlugin netconfSouthboundPlugin;
166         netconfSBPConfiguration = NetconfConfigUtils.injectServicesToTopologyConfig(netconfSBPConfiguration,
167                 lightyController.getServices());
168         NetconfTopologyPluginBuilder netconfSBPBuilder = new NetconfTopologyPluginBuilder(
169                 lightyController.getServices(), netconfSBPConfiguration);
170         netconfSouthboundPlugin = netconfSBPBuilder.from(netconfSBPConfiguration, lightyController.getServices())
171                 .build();
172         netconfSouthboundPlugin.start().get();
173
174         // 4. start TransportPCE beans
175         TransportPCE transportPCE = new TransportPCEImpl(lightyController.getServices(), activateNbiNotification,
176             olmtimer1, olmtimer2);
177         transportPCE.start().get();
178
179         // 5. Register shutdown hook for graceful shutdown.
180         shutdownHook = new ShutdownHook(lightyController, communityRestConf, netconfSouthboundPlugin, transportPCE);
181         if (registerShutdownHook) {
182             Runtime.getRuntime().addShutdownHook(shutdownHook);
183         }
184     }
185
186     public void shutdown() {
187         shutdownHook.run();
188     }
189
190     public static void main(String[] args) {
191         Options options = buildOptions();
192         try {
193             CommandLine commandLine = new DefaultParser().parse(options, args);
194             String restConfConfigurationFile = commandLine.getOptionValue(RESTCONF_OPTION_NAME, null);
195             boolean useNbiNotifications = commandLine.hasOption(NBINOTIFICATION_OPTION_NAME);
196             String olmtimer1 = commandLine.getOptionValue(OLMTIMER1_OPTION_NAME, null);
197             String olmtimer2 = commandLine.getOptionValue(OLMTIMER2_OPTION_NAME, null);
198             Main app = new Main();
199             app.start(restConfConfigurationFile, useNbiNotifications, olmtimer1, olmtimer2, true);
200         } catch (ParseException e) {
201             HelpFormatter formatter = new HelpFormatter();
202             formatter.printHelp(
203                     "java -ms<size> -mx<size> -XX:MaxMetaspaceSize=<size> -jar tpce.jar "
204                     + "[-restconf <restconfConfigurationFile>] [-nbinotification]"
205                     + " e.g. java -ms128m -mx512m -XX:MaxMetaspaceSize=128m -jar tpce.jar"
206                     + "-restconf ../src/test/resources/config.json -nbinotification"
207                     + "-olmtimer1 120000 -olmtimer2 20000",
208                     options);
209             System.exit(1);
210         }
211     }
212
213     private static class ShutdownHook extends Thread {
214
215         private static final Logger LOG = LoggerFactory.getLogger(ShutdownHook.class);
216         private final LightyController lightyController;
217         private final CommunityRestConf communityRestConf;
218         private final LightyModule netconfSouthboundPlugin;
219         private final TransportPCE transportPCE;
220
221         ShutdownHook(LightyController lightyController, CommunityRestConf communityRestConf,
222                 LightyModule netconfSouthboundPlugin, TransportPCE transportPCE) {
223             this.lightyController = lightyController;
224             this.communityRestConf = communityRestConf;
225             this.netconfSouthboundPlugin = netconfSouthboundPlugin;
226             this.transportPCE = transportPCE;
227         }
228
229         @Override
230         @SuppressWarnings({"checkstyle:Illegalcatch", "checkstyle:VariableDeclarationUsageDistance"})
231         public void run() {
232             LOG.info("lighty.io and RESTCONF-NETCONF shutting down ...");
233             long startTime = System.nanoTime();
234             try {
235                 transportPCE.shutdown().get();
236             } catch (Exception e) {
237                 LOG.error("Exception while shutting down TransportPCE: ", e);
238             }
239             try {
240                 communityRestConf.shutdown().get();
241             } catch (Exception e) {
242                 LOG.error("Exception while shutting down RESTCONF: ", e);
243             }
244             try {
245                 netconfSouthboundPlugin.shutdown().get();
246             } catch (Exception e) {
247                 LOG.error("Exception while shutting down NETCONF: ", e);
248             }
249             try {
250                 lightyController.shutdown().get();
251             } catch (Exception e) {
252                 LOG.error("Exception while shutting down lighty.io controller:", e);
253             }
254             float duration = (System.nanoTime() - startTime) / 1_000_000f;
255             LOG.info("lighty.io and RESTCONF-NETCONF stopped in {}ms", duration);
256         }
257
258     }
259
260 }