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