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