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