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