Fix VM Snapshot error during image validation
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / CreateSnapshot.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Modifications Copyright (C) 2018 IBM.
10  * ================================================================================
11  * Modifications (C) 2019 Ericsson
12  * =============================================================================
13  * Licensed under the Apache License, Version 2.0 (the "License");
14  * you may not use this file except in compliance with the License.
15  * You may obtain a copy of the License at
16  * 
17  *      http://www.apache.org/licenses/LICENSE-2.0
18  * 
19  * Unless required by applicable law or agreed to in writing, software
20  * distributed under the License is distributed on an "AS IS" BASIS,
21  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22  * See the License for the specific language governing permissions and
23  * limitations under the License.
24  * 
25  * ============LICENSE_END=========================================================
26  */
27
28 package org.onap.appc.adapter.iaas.provider.operation.impl;
29
30 import com.att.cdp.exceptions.ContextConnectionException;
31 import com.att.cdp.exceptions.ResourceNotFoundException;
32 import com.att.cdp.exceptions.ZoneException;
33 import com.att.cdp.zones.Context;
34 import com.att.cdp.zones.ImageService;
35 import com.att.cdp.zones.Provider;
36 import com.att.cdp.zones.model.Image;
37 import com.att.cdp.zones.model.ModelObject;
38 import com.att.cdp.zones.model.Server;
39 import com.att.eelf.configuration.EELFLogger;
40 import com.att.eelf.configuration.EELFManager;
41 import com.att.eelf.i18n.EELFResourceManager;
42 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
43 import org.glassfish.grizzly.http.util.HttpStatus;
44 import org.onap.appc.Constants;
45 import org.onap.appc.adapter.iaas.ProviderAdapter;
46 import org.onap.appc.adapter.iaas.impl.IdentityURL;
47 import org.onap.appc.adapter.iaas.impl.RequestContext;
48 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
49 import org.onap.appc.adapter.iaas.impl.VMURL;
50 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
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.appc.logging.LoggingConstants;
57 import org.slf4j.MDC;
58 import java.text.SimpleDateFormat;
59 import java.util.Date;
60 import java.util.Map;
61 import static org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants.DATE_FORMAT;
62 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
63
64 public class CreateSnapshot extends ProviderServerOperation {
65
66     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CreateSnapshot.class);
67     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
68     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
69
70     private String generateSnapshotName(String server) {
71         setTimeForMetricsLogger();
72         SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
73         metricsLogger.info("Snapshot Name Generated: Snapshot of %s at %s", server, df.format(new Date()));
74         return String.format("Snapshot of %s at %s", server, df.format(new Date()));
75     }
76
77     private Image createSnapshot(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
78         Context context = server.getContext();
79         Provider provider = context.getProvider();
80         ImageService service = context.getImageService(); // Already checked access by this point
81         String snapshotName = generateSnapshotName(server.getName());
82         setTimeForMetricsLogger();
83         logger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(), server.getId(),
84                 snapshotName));
85         metricsLogger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(),
86                 server.getId(), snapshotName));
87         // Request Snapshot
88         String msg;
89         while (rc.attempt()) {
90             try {
91                 server.createSnapshot(snapshotName);
92                 break;
93             } catch (ContextConnectionException e) {
94                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
95                         context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
96                         Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
97                         Integer.toString(rc.getRetryLimit()));
98                 logger.error(msg, e);
99                 metricsLogger.error(msg, e);
100                 rc.delay();
101             }
102         }
103         if (rc.isFailed()) {
104             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
105             logger.error(msg);
106             metricsLogger.error(msg);
107             throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
108         }
109         rc.reset();
110         // Locate snapshot image - image names containing colon must be prefixed by in: and surrounded with quotes
111         Image snapshot = null;
112         while (rc.attempt()) {
113             try {
114                 snapshot = service.getImageByName("in:\"" + snapshotName + "\"");
115                 if (snapshot != null) {
116                     break;
117                 }
118             } catch (ContextConnectionException e) {
119                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
120                         context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
121                         Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
122                         Integer.toString(rc.getRetryLimit()));
123                 logger.error(msg, e);
124                 metricsLogger.error(msg, e);
125                 rc.delay();
126             }
127         }
128         if (rc.isFailed()) {
129             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
130             logger.error(msg);
131             metricsLogger.error(msg);
132             throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
133         }
134         rc.reset();
135         // Wait for it to be ready
136         waitForStateChange(rc, snapshot, Image.Status.ACTIVE);
137         return snapshot;
138     }
139
140     private Image createSnapshot(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
141         Image snapshot = null;
142         RequestContext rc = new RequestContext(ctx);
143         rc.isAlive();
144         setTimeForMetricsLogger();
145         try {
146             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
147                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
148             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
149             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
150             VMURL vm = VMURL.parseURL(vm_url);
151             if (validateVM(rc, appName, vm_url, vm))
152                 return null;
153             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
154             String identStr = (ident == null) ? null : ident.toString();
155             snapshot = createSnapshotNested(snapshot, rc, vm, vm_url, identStr);
156         } catch (RequestFailedException e) {
157             doFailure(rc, e.getStatus(), e.getMessage());
158         }
159         return snapshot;
160     }
161
162     private Image createSnapshotNested(Image SnapShot, RequestContext RcContext, VMURL vm, String vmUrl,
163             String identStr) throws APPCException {
164         String msg;
165         Context context = null;
166         String tenantName = "Unknown";// this variable is also used in catch
167         try {
168             context = getContext(RcContext, vmUrl, identStr);
169             if (context != null) {
170                 tenantName = context.getTenantName();
171                 Server server = lookupServer(RcContext, context, vm.getServerId());
172                 logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString());
173                 if (hasImageAccess(RcContext, context)) {
174                     SnapShot = createSnapshot(RcContext, server);
175                     doSuccess(RcContext);
176                 } else {
177                     msg = EELFResourceManager.format(Msg.IMAGE_SERVICE_FAILED, server.getName(), server.getId(),
178                             "Accessing Image Service Failed");
179                     logger.error(msg);
180                     metricsLogger.error(msg);
181                     doFailure(RcContext, HttpStatus.FORBIDDEN_403, msg);
182                 }
183                 context.close();
184             }
185         } catch (ResourceNotFoundException e) {
186             msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
187             logger.error(msg);
188             metricsLogger.error(msg, e);
189             doFailure(RcContext, HttpStatus.NOT_FOUND_404, msg);
190         } catch (Exception e1) {
191             msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
192                     Operation.SNAPSHOT_SERVICE.toString(), vmUrl, tenantName);
193             logger.error(msg, e1);
194             doFailure(RcContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
195         }
196         return SnapShot;
197     }
198
199     @Override
200     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
201             throws APPCException {
202         setMDC(Operation.SNAPSHOT_SERVICE.toString(), "App-C IaaS Adapter:Snapshot", ADAPTER_NAME);
203         logOperation(Msg.SNAPSHOTING_SERVER, params, context);
204         setTimeForMetricsLogger();
205         metricsLogger.info("Executing Provider Operation: Create Snapshot");
206         return createSnapshot(params, context);
207     }
208
209     private void setTimeForMetricsLogger() {
210         MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
211         MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "create snapshot");
212         MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
213                 "org.onap.appc.adapter.iaas.provider.operation.impl.CreateSnapshot");
214     }
215 }