fbd3165139a65a4fa4b770a687bb93e3b5674545
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / RestartServer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.adapter.iaas.provider.operation.impl;
25
26 import com.att.cdp.exceptions.ResourceNotFoundException;
27 import com.att.cdp.exceptions.ZoneException;
28 import com.att.cdp.zones.Context;
29 import com.att.cdp.zones.model.ModelObject;
30 import com.att.cdp.zones.model.Server;
31 import com.att.eelf.configuration.EELFLogger;
32 import com.att.eelf.configuration.EELFManager;
33 import com.att.eelf.i18n.EELFResourceManager;
34 import org.glassfish.grizzly.http.util.HttpStatus;
35 import org.onap.appc.Constants;
36 import org.onap.appc.adapter.iaas.ProviderAdapter;
37 import org.onap.appc.adapter.iaas.impl.IdentityURL;
38 import org.onap.appc.adapter.iaas.impl.RequestContext;
39 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
40 import org.onap.appc.adapter.iaas.impl.VMURL;
41 import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property;
42 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome;
43 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
44 import org.onap.appc.exceptions.UnknownProviderException;
45 import org.onap.appc.i18n.Msg;
46 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
47 import org.slf4j.MDC;
48 import java.text.DateFormat;
49 import java.text.SimpleDateFormat;
50 import java.util.Date;
51 import java.util.Map;
52 import java.util.TimeZone;
53 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.RESTART_SERVICE;
54 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
55
56 public class RestartServer extends ProviderServerOperation {
57
58     private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestartServer.class);
59     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
60
61
62     /**
63      * This method handles the case of restarting a server once we have found the server and have obtained the abstract
64      * representation of the server via the context (i.e., the "Server" object from the CDP-Zones abstraction).
65      *
66      * @param rc The request context that manages the state and recovery of the request for the life of its processing.
67      * @param server The server object representing the server we want to operate on
68      * @throws ZoneException when error occurs.
69      * @throws RequestFailedException when server status is error.
70      */
71     @SuppressWarnings("nls")
72     private void restartServer(RequestContext rc, Server server, SvcLogicContext ctx)
73             throws ZoneException, RequestFailedException {
74         /*
75          * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
76          * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
77          * to one we can deal with. If not, then we have to fail the request.
78          */
79         String msg;
80         if (server.getStatus().equals(Server.Status.PENDING)) {
81             waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
82                     Server.Status.SUSPENDED, Server.Status.PAUSED);
83         }
84
85         setTimeForMetricsLogger("restart server");
86
87         String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
88         if (skipHypervisorCheck == null && ctx != null) {
89             skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
90         }
91
92         // Always perform Virtual Machine/Hypervisor Status/Network checks
93         // unless the skip is set to true
94         if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) {
95             // Check of the Hypervisor for the VM Server is UP and reachable
96             checkHypervisor(server);
97         }
98
99         /*
100          * We determine what to do based on the current state of the server
101          */
102         switch (server.getStatus()) {
103             case DELETED:
104                 // Nothing to do, the server is gone
105                 msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
106                         server.getTenantId(), "restarted");
107                 generateEvent(rc, false, msg);
108                 logger.error(msg);
109                 metricsLogger.error(msg);
110                 break;
111
112             case RUNNING:
113                 // Attempt to stop and start the server
114                 stopServer(rc, server);
115                 startServer(rc, server);
116                 generateEvent(rc, true, Outcome.SUCCESS.toString());
117                 metricsLogger.info("Server status: RUNNING");
118                 break;
119
120             case ERROR:
121                 msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
122                         server.getTenantId(), "restart");
123                 generateEvent(rc, false, msg);
124                 logger.error(msg);
125                 metricsLogger.error(msg);
126                 throw new RequestFailedException("Restart Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
127
128             case READY:
129                 // Attempt to start the server
130                 startServer(rc, server);
131                 generateEvent(rc, true, Outcome.SUCCESS.toString());
132                 metricsLogger.info("Server status: READY");
133                 break;
134
135             case PAUSED:
136                 // if paused, un-pause it
137                 unpauseServer(rc, server);
138                 generateEvent(rc, true, Outcome.SUCCESS.toString());
139                 metricsLogger.info("Server status: PAUSED");
140                 break;
141
142             case SUSPENDED:
143                 // Attempt to resume the suspended server
144                 resumeServer(rc, server);
145                 generateEvent(rc, true, Outcome.SUCCESS.toString());
146                 metricsLogger.info("Server status: SUSPENDED");
147                 break;
148
149             default:
150                 // Hmmm, unknown status, should never occur
151                 msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
152                         server.getTenantId(), server.getStatus().name());
153                 generateEvent(rc, false, msg);
154                 logger.error(msg);
155                 metricsLogger.error(msg);
156                 break;
157         }
158
159
160     }
161
162     /**
163      * This method is used to restart an existing virtual machine given the fully qualified URL of the machine.
164      * <p>
165      * The fully qualified URL contains enough information to locate the appropriate server. The URL is of the form
166      * 
167      * <pre>
168      *  [scheme]://[host[:port]] / [path] / [tenant_id] / servers / [vm_id]
169      * </pre>
170      * 
171      * Where the various parts of the URL can be parsed and extracted and used to locate the appropriate service in the
172      * provider service catalog. This then allows us to open a context using the CDP abstraction, obtain the server by
173      * its UUID, and then perform the restart.
174      * </p>
175      *
176      * @throws UnknownProviderException If the provider cannot be found
177      * @throws IllegalArgumentException if the expected argument(s) are not defined or are invalid
178      * @see org.onap.appc.adapter.iaas.ProviderAdapter#restartServer(java.util.Map,
179      *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
180      */
181     @SuppressWarnings("nls")
182     private Server restartServer(Map<String, String> params, SvcLogicContext ctx)
183             throws UnknownProviderException, IllegalArgumentException {
184         Server server = null;
185         RequestContext rc = new RequestContext(ctx);
186         rc.isAlive();
187
188         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
189
190         /*
191          * Set Time for Metrics Logger
192          */
193         setTimeForMetricsLogger("GET server status");
194
195         ctx.setAttribute("RESTART_STATUS", "ERROR");
196         try {
197             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
198                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
199
200             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
201
202             VMURL vm = VMURL.parseURL(vm_url);
203             if (validateVM(rc, appName, vm_url, vm))
204                 return null;
205
206             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
207             String identStr = (ident == null) ? null : ident.toString();
208
209             Context context = null;
210             String tenantName = "Unknown";//to be used also in case of exception
211             try {
212                 context = getContext(rc, vm_url, identStr);
213                 if (context != null) {
214                     tenantName = context.getTenantName();//this varaible also is used in case of exception
215                     rc.reset();
216                     server = lookupServer(rc, context, vm.getServerId());
217                     logger.debug(Msg.SERVER_FOUND, vm_url, tenantName, server.getStatus().toString());
218                     rc.reset();
219                     restartServer(rc, server, ctx);
220                     context.close();
221                     doSuccess(rc);
222                     ctx.setAttribute("RESTART_STATUS", "SUCCESS");
223                     String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "RestartServer", vm_url);
224                     ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
225                 }
226             } catch (RequestFailedException e) {
227                 doFailure(rc, e.getStatus(), e.getMessage());
228             } catch (ResourceNotFoundException e) {
229                 String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
230                 logger.error(msg);
231                 metricsLogger.error(msg);
232                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
233             } catch (Exception e1) {
234                 String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1,
235                         e1.getClass().getSimpleName(), RESTART_SERVICE.toString(), vm_url,
236                         tenantName);
237                 logger.error(msg, e1);
238                 metricsLogger.error(msg, e1);
239                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
240             }
241         } catch (RequestFailedException e) {
242             doFailure(rc, e.getStatus(), e.getMessage());
243         }
244
245         return server;
246     }
247
248     @Override
249     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
250             throws UnknownProviderException {
251         setMDC(RESTART_SERVICE.toString(), "App-C IaaS Adapter:Restart", ADAPTER_NAME);
252         logOperation(Msg.RESTARTING_SERVER, params, context);
253
254         setTimeForMetricsLogger("execute restart");
255
256         metricsLogger.info("Executing Provider Operation: Restart");
257
258         return restartServer(params, context);
259     }
260
261     private void setTimeForMetricsLogger(String targetServiceName) {
262         long startTime = System.currentTimeMillis();
263         TimeZone tz = TimeZone.getTimeZone("UTC");
264         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
265         df.setTimeZone(tz);
266         long endTime = System.currentTimeMillis();
267         long duration = endTime - startTime;
268         String durationStr = String.valueOf(duration);
269         String endTimeStrUTC = df.format(new Date());
270         MDC.put("EndTimestamp", endTimeStrUTC);
271         MDC.put("ElapsedTime", durationStr);
272         MDC.put("TargetEntity", "cdp");
273         MDC.put("TargetServiceName", targetServiceName);
274         MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.RestartServer");
275     }
276 }