73374053f5ffd7e6f10d45dc9afd83188323f974
[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.deployment.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 ApexDeploymentRest.
30  *
31  * @author Michael Watkins (michael.watkins@ericsson.com)
32  */
33 public class ApexDeploymentRestMain {
34     // Logger for this class
35     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexDeploymentRestMain.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 ApexDeploymentRestParameters 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 ApexDeploymentRest apexDeploymentRest = null;
55
56     /**
57      * Main method, main entry point for command.
58      *
59      * @param args The command line arguments for the client
60      */
61     public static void main(final String[] args) {
62         try {
63             final ApexDeploymentRestMain restMain = new ApexDeploymentRestMain(args, System.out);
64             restMain.init();
65         } catch (final Exception e) {
66             LOGGER.error("start failed", e);
67         }
68     }
69
70     /**
71      * Constructor, kicks off the rest service.
72      *
73      * @param args The command line arguments for the RESTful service
74      * @param outStream The stream for output messages
75      */
76     public ApexDeploymentRestMain(final String[] args, final PrintStream outStream) {
77         // Save the streams for output and error
78         this.outStream = outStream;
79
80         // Client parameter parsing
81         final ApexDeploymentRestParameterParser parser = new ApexDeploymentRestParameterParser();
82
83         try {
84             // Get and check the parameters
85             parameters = parser.parse(args);
86         } catch (final ApexDeploymentRestParameterException e) {
87             throw new ApexDeploymentRestParameterException(
88                     REST_ENDPOINT_PREFIX + this.toString() + ") parameter error, " + e.getMessage() + '\n'
89                             + parser.getHelp(ApexDeploymentRestMain.class.getCanonicalName()));
90         }
91
92         if (parameters.isHelpSet()) {
93             throw new ApexDeploymentRestParameterException(
94                     parser.getHelp(ApexDeploymentRestMain.class.getCanonicalName()));
95         }
96
97         // Validate the parameters
98         final String validationMessage = parameters.validate();
99         if (validationMessage.length() > 0) {
100             throw new ApexDeploymentRestParameterException(
101                     REST_ENDPOINT_PREFIX + this.toString() + ") parameters invalid, " + validationMessage
102                             + '\n' + parser.getHelp(ApexDeploymentRestMain.class.getCanonicalName()));
103         }
104
105         state = ServicesState.READY;
106     }
107
108     /**
109      * Initialize the rest service.
110      */
111     public void init() {
112         outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") starting at "
113                 + parameters.getBaseUri().toString() + " . . .");
114
115         try {
116             state = ServicesState.INITIALIZING;
117
118             // Start the REST service
119             apexDeploymentRest = new ApexDeploymentRest(parameters);
120
121             // Add a shutdown hook to shut down the rest services when the process is exiting
122             Runtime.getRuntime().addShutdownHook(new Thread(new ApexServicesShutdownHook()));
123
124             state = ServicesState.RUNNING;
125
126             if (parameters.getTimeToLive() == ApexDeploymentRestParameters.INFINITY_TIME_TO_LIVE) {
127                 outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started at "
128                         + parameters.getBaseUri().toString());
129             } else {
130                 outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") started");
131             }
132
133             // Find out how long is left to wait
134             long timeRemaining = parameters.getTimeToLive();
135             while (timeRemaining == ApexDeploymentRestParameters.INFINITY_TIME_TO_LIVE || timeRemaining > 0) {
136                 // decrement the time to live in the non-infinity case
137                 if (timeRemaining > 0) {
138                     timeRemaining--;
139                 }
140
141                 // Wait for a second
142                 Thread.sleep(1000);
143             }
144         } catch (final Exception e) {
145             outStream.println(
146                     REST_ENDPOINT_PREFIX + this.toString() + ") failed at with error: " + e.getMessage());
147         } finally {
148             if (apexDeploymentRest != null) {
149                 apexDeploymentRest.shutdown();
150                 apexDeploymentRest = null;
151             }
152             state = ServicesState.STOPPED;
153         }
154
155     }
156
157     /**
158      * Get services state.
159      *
160      * @return the service state
161      */
162     public ServicesState getState() {
163         return state;
164     }
165
166     @Override
167     public String toString() {
168         final StringBuilder ret = new StringBuilder();
169         ret.append(this.getClass().getSimpleName()).append(": Config=[").append(this.parameters).append("], State=")
170                 .append(this.getState());
171         return ret.toString();
172     }
173
174     /**
175      * Explicitly shut down the services.
176      */
177     public void shutdown() {
178         if (apexDeploymentRest != null) {
179             outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shutting down");
180             apexDeploymentRest.shutdown();
181         }
182         state = ServicesState.STOPPED;
183         outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shut down");
184     }
185
186     /**
187      * This class is a shutdown hook for the Apex services command.
188      */
189     private class ApexServicesShutdownHook implements Runnable {
190         /*
191          * (non-Javadoc)
192          *
193          * @see java.lang.Runnable#run()
194          */
195         @Override
196         public void run() {
197             if (apexDeploymentRest != null) {
198                 apexDeploymentRest.shutdown();
199             }
200         }
201     }
202
203 }