New iaas unit tests
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / RebuildServer.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.onap.appc.adapter.iaas.provider.operation.impl;
26
27 import com.att.cdp.exceptions.ContextConnectionException;
28 import com.att.cdp.exceptions.ResourceNotFoundException;
29 import com.att.cdp.exceptions.ZoneException;
30 import com.att.cdp.zones.ComputeService;
31 import com.att.cdp.zones.Context;
32 import com.att.cdp.zones.ImageService;
33 import com.att.cdp.zones.Provider;
34 import com.att.cdp.zones.model.Image;
35 import com.att.cdp.zones.model.ModelObject;
36 import com.att.cdp.zones.model.Server;
37 import com.att.cdp.zones.model.ServerBootSource;
38 import com.att.eelf.configuration.EELFLogger;
39 import com.att.eelf.configuration.EELFManager;
40 import com.att.eelf.i18n.EELFResourceManager;
41 import org.glassfish.grizzly.http.util.HttpStatus;
42 import org.onap.appc.Constants;
43 import org.onap.appc.adapter.iaas.ProviderAdapter;
44 import org.onap.appc.adapter.iaas.impl.IdentityURL;
45 import org.onap.appc.adapter.iaas.impl.RequestContext;
46 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
47 import org.onap.appc.adapter.iaas.impl.VMURL;
48 import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property;
49 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
50 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome;
51 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
52 import org.onap.appc.configuration.Configuration;
53 import org.onap.appc.configuration.ConfigurationFactory;
54 import org.onap.appc.exceptions.APPCException;
55 import org.onap.appc.i18n.Msg;
56 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
57 import org.slf4j.MDC;
58 import java.text.DateFormat;
59 import java.text.SimpleDateFormat;
60 import java.util.Date;
61 import java.util.List;
62 import java.util.Map;
63 import java.util.TimeZone;
64 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.STOP_SERVICE;
65 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
66
67 public class RebuildServer extends ProviderServerOperation {
68
69     private static final EELFLogger logger = EELFManager.getInstance().getLogger(RebuildServer.class);
70     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
71     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
72     //the sleep time used by thread.sleep to give "some time for OpenStack to start processing the request"
73     private long rebuildSleepTime = 10L * 1000L;
74
75     /**
76      * Rebuild the indicated server with the indicated image. This method assumes the server has been determined to be
77      * in the correct state to do the rebuild.
78      *
79      * @param rc The request context that manages the state and recovery of the request for the life of its processing.
80      * @param server the server to be rebuilt
81      * @param image The image to be used (or snapshot)
82      * @throws RequestFailedException if the server does not change state in the allotted time
83      */
84     @SuppressWarnings("nls")
85     private void rebuildServer(RequestContext rc, Server server, String image) throws RequestFailedException {
86         logger.debug(Msg.REBUILD_SERVER, server.getId());
87
88         String msg;
89         Context context = server.getContext();
90         Provider provider = context.getProvider();
91         ComputeService service = context.getComputeService();
92
93         /*
94          * Set Time for Metrics Logger
95          */
96         setTimeForMetricsLogger();
97
98         try {
99             while (rc.attempt()) {
100                 try {
101                     server.rebuild(image);
102                     break;
103                 } catch (ContextConnectionException e) {
104                     msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
105                             context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
106                             Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
107                             Integer.toString(rc.getRetryLimit()));
108                     logger.error(msg, e);
109                     metricsLogger.error(msg, e);
110                     rc.delay();
111                 }
112             }
113
114             /*
115              * We need to provide some time for OpenStack to start processing the request.
116              */
117             try {
118                 Thread.sleep(rebuildSleepTime);
119             } catch (InterruptedException e) {
120                 logger.trace("Sleep threw interrupted exception, should never occur");
121                 metricsLogger.trace("Sleep threw interrupted exception, should never occur");
122             }
123         } catch (ZoneException e) {
124             msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
125                     e.getMessage());
126             logger.error(msg);
127             metricsLogger.error(msg);
128             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
129         }
130
131         rc.reset();
132         /*
133          * Once we have started the process, now we wait for the final state of stopped. This should be the final state
134          * (since we started the rebuild with the server stopped).
135          */
136         waitForStateChange(rc, server, Server.Status.READY);
137
138         if (rc.isFailed()) {
139             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
140             logger.error(msg);
141             metricsLogger.error(msg);
142             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
143         }
144         rc.reset();
145     }
146
147     /**
148      * This method is called to rebuild the provided server.
149      * <p>
150      * If the server was booted from a volume, then the request is failed immediately and no action is taken. Rebuilding
151      * a VM from a bootable volume, where the bootable volume itself is not rebuilt, serves no purpose.
152      * </p>
153      *
154      * @param rc The request context that manages the state and recovery of the request for the life of its processing.
155      * @param server The server to be rebuilt
156      * @throws ZoneException When error occurs
157      * @throws RequestFailedException When server status is error
158      */
159     @SuppressWarnings("nls")
160     private void rebuildServer(RequestContext rc, Server server, SvcLogicContext ctx)
161             throws ZoneException, RequestFailedException {
162         ServerBootSource builtFrom = server.getBootSource();
163
164         /*
165          * Set Time for Metrics Logger
166          */
167         setTimeForMetricsLogger();
168
169         String msg;
170         // Throw exception for non image/snap boot source
171         if (ServerBootSource.VOLUME.equals(builtFrom)) {
172             msg = String.format("Rebuilding is currently not supported for servers built from bootable volumes [%s]",
173                     server.getId());
174             generateEvent(rc, false, msg);
175             logger.error(msg);
176             metricsLogger.error(msg);
177             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.FORBIDDEN_403, server);
178         }
179
180         /*
181          * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
182          * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
183          * to one we can deal with. If not, then we have to fail the request.
184          */
185         Context context = server.getContext();
186         Provider provider = context.getProvider();
187         ComputeService service = context.getComputeService();
188         if (server.getStatus().equals(Server.Status.PENDING)) {
189             rc.reset();
190             waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
191                     Server.Status.SUSPENDED, Server.Status.PAUSED);
192         }
193
194         // Is the skip Hypervisor check attribute populated?
195         String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
196         if (skipHypervisorCheck == null && ctx != null) {
197             skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
198         }
199
200         // Always perform Hypervisor Status checks
201         // unless the skip is set to true
202         if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) {
203             // Check of the Hypervisor for the VM Server is UP and reachable
204             checkHypervisor(server);
205         }
206
207         /*
208          * Get the image to use. This is determined by the presence or absence of snapshot images. If any snapshots
209          * exist, then the latest snapshot is used, otherwise the image used to construct the VM is used.
210          */
211         List<Image> snapshots = server.getSnapshots();
212         String imageToUse;
213         if (snapshots != null && !snapshots.isEmpty()) {
214             imageToUse = snapshots.get(0).getId();
215         } else {
216             imageToUse = server.getImage();
217             ImageService imageService = server.getContext().getImageService();
218             rc.reset();
219             try {
220                 while (rc.attempt()) {
221                     try {
222                         /*
223                          * We are just trying to make sure that the image exists. We arent interested in the details at
224                          * this point.
225                          */
226                         imageService.getImage(imageToUse);
227                         break;
228                     } catch (ContextConnectionException e) {
229                         msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(),
230                                 imageService.getURL(), context.getTenant().getName(), context.getTenant().getId(),
231                                 e.getMessage(), Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
232                                 Integer.toString(rc.getRetryLimit()));
233                         logger.error(msg, e);
234                         metricsLogger.error(msg);
235                         rc.delay();
236                     }
237                 }
238             } catch (ZoneException e) {
239                 msg = EELFResourceManager.format(Msg.IMAGE_NOT_FOUND, imageToUse, "rebuild");
240                 generateEvent(rc, false, msg);
241                 logger.error(msg);
242                 metricsLogger.error(msg);
243                 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
244             }
245         }
246         if (rc.isFailed()) {
247             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
248             logger.error(msg);
249             metricsLogger.error(msg);
250             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
251         }
252         rc.reset();
253
254         /*
255          * We determine what to do based on the current state of the server
256          */
257         switch (server.getStatus()) {
258             case DELETED:
259                 // Nothing to do, the server is gone
260                 msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
261                         server.getTenantId(), "rebuilt");
262                 generateEvent(rc, false, msg);
263                 logger.error(msg);
264                 metricsLogger.error(msg);
265                 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
266
267             case RUNNING:
268                 // Attempt to stop the server, then rebuild it
269                 stopServer(rc, server);
270                 rc.reset();
271                 rebuildServer(rc, server, imageToUse);
272                 rc.reset();
273                 startServer(rc, server);
274                 generateEvent(rc, true, Outcome.SUCCESS.toString());
275                 metricsLogger.info("Server status: RUNNING");
276                 break;
277
278             case ERROR:
279                 msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
280                         server.getTenantId(), "rebuild");
281                 generateEvent(rc, false, msg);
282                 logger.error(msg);
283                 metricsLogger.error(msg);
284                 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
285
286             case READY:
287                 // Attempt to rebuild the server
288                 rebuildServer(rc, server, imageToUse);
289                 rc.reset();
290                 startServer(rc, server);
291                 generateEvent(rc, true, Outcome.SUCCESS.toString());
292                 metricsLogger.info("Server status: READY");
293                 break;
294
295             case PAUSED:
296                 // if paused, un-pause it, stop it, and rebuild it
297                 unpauseServer(rc, server);
298                 rc.reset();
299                 stopServer(rc, server);
300                 rc.reset();
301                 rebuildServer(rc, server, imageToUse);
302                 rc.reset();
303                 startServer(rc, server);
304                 generateEvent(rc, true, Outcome.SUCCESS.toString());
305                 metricsLogger.info("Server status: PAUSED");
306                 break;
307
308             case SUSPENDED:
309                 // Attempt to resume the suspended server, stop it, and rebuild it
310                 resumeServer(rc, server);
311                 rc.reset();
312                 stopServer(rc, server);
313                 rc.reset();
314                 rebuildServer(rc, server, imageToUse);
315                 rc.reset();
316                 startServer(rc, server);
317                 generateEvent(rc, true, Outcome.SUCCESS.toString());
318                 metricsLogger.info("Server status: SUSPENDED");
319                 break;
320
321             default:
322                 // Hmmm, unknown status, should never occur
323                 msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
324                         server.getTenantId(), server.getStatus().name());
325                 generateEvent(rc, false, msg);
326                 logger.error(msg);
327                 metricsLogger.error(msg);
328                 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
329         }
330     }
331
332     /**
333      * @see org.onap.appc.adapter.iaas.ProviderAdapter#rebuildServer(java.util.Map,
334      *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
335      */
336     @SuppressWarnings("nls")
337     public Server rebuildServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
338         Server server = null;
339         RequestContext rc = new RequestContext(ctx);
340         rc.isAlive();
341
342         setTimeForMetricsLogger();
343
344         String msg;
345         try {
346             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
347                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
348
349             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
350             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
351             VMURL vm = VMURL.parseURL(vm_url);
352             if (validateVM(rc, appName, vm_url, vm))
353                 return null;
354
355             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
356             String identStr = (ident == null) ? null : ident.toString();
357             ctx.setAttribute("REBUILD_STATUS", "ERROR");
358
359             Context context = null;
360             try {
361                 context = getContext(rc, vm_url, identStr);
362                 if (context != null) {
363                     rc.reset();
364                     server = lookupServer(rc, context, vm.getServerId());
365                     logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
366
367                     // Manually checking image service until new PAL release
368                     if (hasImageAccess(rc, context)) {
369                         rebuildServer(rc, server, ctx);
370                         doSuccess(rc);
371                         ctx.setAttribute("REBUILD_STATUS", "SUCCESS");
372                     } else {
373                         msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
374                                 "Accessing Image Service Failed");
375                         logger.error(msg);
376                         metricsLogger.error(msg);
377                         doFailure(rc, HttpStatus.FORBIDDEN_403, msg);
378                     }
379                     context.close();
380                 } else {
381                     ctx.setAttribute("REBUILD_STATUS", "CONTEXT_NOT_FOUND");
382                 }
383             } catch (RequestFailedException e) {
384                 doFailure(rc, e.getStatus(), e.getMessage());
385                 ctx.setAttribute("REBUILD_STATUS", "ERROR");
386             } catch (ResourceNotFoundException e) {
387                 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
388                 ctx.setAttribute("REBUILD_STATUS", "ERROR");
389                 logger.error(msg);
390                 metricsLogger.error(msg);
391                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
392             } catch (Exception e1) {
393                 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
394                         STOP_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName());
395                 ctx.setAttribute("REBUILD_STATUS", "ERROR");
396                 logger.error(msg, e1);
397                 metricsLogger.error(msg);
398                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
399             }
400         } catch (RequestFailedException e) {
401             doFailure(rc, e.getStatus(), e.getMessage());
402             ctx.setAttribute("REBUILD_STATUS", "ERROR");
403         }
404
405         return server;
406     }
407
408     @Override
409     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
410             throws APPCException {
411         setMDC(Operation.REBUILD_SERVICE.toString(), "App-C IaaS Adapter:Rebuild", ADAPTER_NAME);
412         logOperation(Msg.REBUILDING_SERVER, params, context);
413
414         setTimeForMetricsLogger();
415
416         metricsLogger.info("Executing Provider Operation: Rebuild");
417
418         return rebuildServer(params, context);
419     }
420
421     private void setTimeForMetricsLogger() {
422         long startTime = System.currentTimeMillis();
423         TimeZone tz = TimeZone.getTimeZone("UTC");
424         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
425         df.setTimeZone(tz);
426         long endTime = System.currentTimeMillis();
427         long duration = endTime - startTime;
428         String durationStr = String.valueOf(duration);
429         String endTimeStrUTC = df.format(new Date());
430         MDC.put("EndTimestamp", endTimeStrUTC);
431         MDC.put("ElapsedTime", durationStr);
432         MDC.put("TargetEntity", "cdp");
433         MDC.put("TargetServiceName", "rebuild server");
434         MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.RebuildServer");
435     }
436     
437     /**
438      * Sets the sleep time used by thread.sleep to give
439      * "some time for OpenStack to start processing the request".
440      *
441      * @param millis Time to sleep in milliseconds
442      */
443     public void setRebuildSleepTime(long millis){
444         this.rebuildSleepTime = millis;
445     }
446 }