523a6eebbbdb2cfe632cfa39636a2292c4024194
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.client.monitoring.rest;
22
23 import java.io.PrintStream;
24
25 import org.slf4j.ext.XLogger;
26 import org.slf4j.ext.XLoggerFactory;
27
28 /**
29  * The main class for Apex Restful Monitoring.
30  *
31  * @author Michael Watkins (michael.watkins@ericsson.com)
32  */
33 public class ApexMonitoringRestMain {
34     // Logger for this class
35     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexMonitoringRestMain.class);
36
37     // Recurring string constants
38     private static final String REST_ENDPOINT_PREFIX = "Apex Services REST endpoint (";
39
40     // Services state
41     public enum ServicesState {
42         STOPPED, READY, INITIALIZING, RUNNING
43     }
44
45     private ServicesState state = ServicesState.STOPPED;
46
47     // The parameters for the client
48     private ApexMonitoringRestParameters parameters = null;
49
50     // Output and error streams for messages
51     private final PrintStream outStream;
52
53     // The Apex services client this class is running
54     private ApexMonitoringRest apexMonitoringRest = null;
55
56     /**
57      * Constructor, kicks off the rest service.
58      *
59      * @param args The command line arguments for the RESTful service
60      * @param outStream The stream for output messages
61      */
62     public ApexMonitoringRestMain(final String[] args, final PrintStream outStream) {
63         // Save the streams for output and error
64         this.outStream = outStream;
65
66         // Client parameter parsing
67         final ApexMonitoringRestParameterParser parser = new ApexMonitoringRestParameterParser();
68
69         try {
70             // Get and check the parameters
71             parameters = parser.parse(args);
72         } catch (final ApexMonitoringRestParameterException e) {
73             throw new ApexMonitoringRestParameterException(
74                             REST_ENDPOINT_PREFIX + this.toString() + ") parameter error, " + e.getMessage() + '\n'
75                                             + parser.getHelp(ApexMonitoringRestMain.class.getCanonicalName()), e);
76         }
77
78         if (parameters.isHelpSet()) {
79             throw new ApexMonitoringRestParameterException(
80                             parser.getHelp(ApexMonitoringRestMain.class.getCanonicalName()));
81         }
82
83         // Validate the parameters
84         final String validationMessage = parameters.validate();
85         if (validationMessage.length() > 0) {
86             throw new ApexMonitoringRestParameterException(
87                             REST_ENDPOINT_PREFIX + this.toString() + ") parameters invalid, " + validationMessage + '\n'
88                                             + parser.getHelp(ApexMonitoringRestMain.class.getCanonicalName()));
89         }
90
91         state = ServicesState.READY;
92     }
93
94     /**
95      * Initialize the rest service.
96      */
97     public void init() {
98         outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") starting at " + parameters.getBaseUri().toString()
99                         + " . . .");
100
101         try {
102             state = ServicesState.INITIALIZING;
103
104             // Start the REST service
105             apexMonitoringRest = new ApexMonitoringRest(parameters);
106
107             // Add a shutdown hook to shut down the rest services when the process is exiting
108             Runtime.getRuntime().addShutdownHook(new Thread(new ApexServicesShutdownHook()));
109
110             state = ServicesState.RUNNING;
111
112             if (parameters.getTimeToLive() == ApexMonitoringRestParameters.INFINITY_TIME_TO_LIVE) {
113                 outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started at "
114                                 + parameters.getBaseUri().toString());
115             } else {
116                 outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started");
117             }
118
119             // Find out how long is left to wait
120             long timeRemaining = parameters.getTimeToLive();
121             while (timeRemaining == ApexMonitoringRestParameters.INFINITY_TIME_TO_LIVE || timeRemaining > 0) {
122                 // decrement the time to live in the non-infinity case
123                 if (timeRemaining > 0) {
124                     timeRemaining--;
125                 }
126
127                 // Wait for a second
128                 Thread.sleep(1000);
129             }
130         } catch (final Exception e) {
131             String message = REST_ENDPOINT_PREFIX + this.toString() + ") failed at with error: " + e.getMessage();
132             outStream.println(message);
133             LOGGER.warn(message, e);
134         } finally {
135             if (apexMonitoringRest != null) {
136                 apexMonitoringRest.shutdown();
137                 apexMonitoringRest = null;
138             }
139             state = ServicesState.STOPPED;
140         }
141
142     }
143
144     /**
145      * Get services state.
146      *
147      * @return the service state
148      */
149     public ServicesState getState() {
150         return state;
151     }
152
153     @Override
154     public String toString() {
155         final StringBuilder ret = new StringBuilder();
156         ret.append(this.getClass().getSimpleName()).append(": Config=[").append(this.parameters).append("], State=")
157                         .append(this.getState());
158         return ret.toString();
159     }
160
161     /**
162      * Explicitly shut down the services.
163      */
164     public void shutdown() {
165         if (apexMonitoringRest != null) {
166             outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shutting down");
167             apexMonitoringRest.shutdown();
168         }
169         state = ServicesState.STOPPED;
170         outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shut down");
171     }
172
173     /**
174      * This class is a shutdown hook for the Apex services command.
175      */
176     private class ApexServicesShutdownHook implements Runnable {
177         /*
178          * (non-Javadoc)
179          *
180          * @see java.lang.Runnable#run()
181          */
182         @Override
183         public void run() {
184             if (apexMonitoringRest != null) {
185                 apexMonitoringRest.shutdown();
186             }
187         }
188     }
189
190     /**
191      * Main method, main entry point for command.
192      *
193      * @param args The command line arguments for the client
194      */
195     public static void main(final String[] args) {
196         try {
197             final ApexMonitoringRestMain restMain = new ApexMonitoringRestMain(args, System.out);
198             restMain.init();
199         } catch (final Exception e) {
200             LOGGER.error("start failed", e);
201         }
202     }
203 }