134914f1127fdf3c1d9d20d4905e7d629713f92a
[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()), e);
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 + '\n'
102                                             + 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 " + parameters.getBaseUri().toString()
113                         + " . . .");
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             String message = REST_ENDPOINT_PREFIX + this.toString() + ") failed at with error: " + e.getMessage();
146             outStream.println(message);
147             LOGGER.warn(message, e);
148         } finally {
149             if (apexDeploymentRest != null) {
150                 apexDeploymentRest.shutdown();
151                 apexDeploymentRest = null;
152             }
153             state = ServicesState.STOPPED;
154         }
155
156     }
157
158     /**
159      * Get services state.
160      *
161      * @return the service state
162      */
163     public ServicesState getState() {
164         return state;
165     }
166
167     @Override
168     public String toString() {
169         final StringBuilder ret = new StringBuilder();
170         ret.append(this.getClass().getSimpleName()).append(": Config=[").append(this.parameters).append("], State=")
171                         .append(this.getState());
172         return ret.toString();
173     }
174
175     /**
176      * Explicitly shut down the services.
177      */
178     public void shutdown() {
179         if (apexDeploymentRest != null) {
180             outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shutting down");
181             apexDeploymentRest.shutdown();
182         }
183         state = ServicesState.STOPPED;
184         outStream.println(REST_ENDPOINT_PREFIX + this.toString() + ") shut down");
185     }
186
187     /**
188      * This class is a shutdown hook for the Apex services command.
189      */
190     private class ApexServicesShutdownHook implements Runnable {
191         /*
192          * (non-Javadoc)
193          *
194          * @see java.lang.Runnable#run()
195          */
196         @Override
197         public void run() {
198             if (apexDeploymentRest != null) {
199                 apexDeploymentRest.shutdown();
200             }
201         }
202     }
203
204 }