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