81a939e3f26fac3ea92684c26d4a7b2c94bbda4c
[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-2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Modifications Copyright (C) 2018-2019 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 import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property;
64
65 public class CreateSnapshot extends ProviderServerOperation {
66
67     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CreateSnapshot.class);
68     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
69     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
70
71     private String generateSnapshotName(String server) {
72         setTimeForMetricsLogger();
73         SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
74         metricsLogger.info("Snapshot Name Generated: Snapshot of %s at %s", server, df.format(new Date()));
75         return String.format("Snapshot of %s at %s", server, df.format(new Date()));
76     }
77
78     private Image createSnapshot(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
79         Context context = server.getContext();
80         Provider provider = context.getProvider();
81         ImageService service = context.getImageService(); // Already checked access by this point
82         String snapshotName = generateSnapshotName(server.getName());
83         setTimeForMetricsLogger();
84         logger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(), server.getId(),
85                 snapshotName));
86         metricsLogger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(),
87                 server.getId(), snapshotName));
88         // Request Snapshot
89         String msg;
90         while (rc.attempt()) {
91             try {
92                 server.createSnapshot(snapshotName);
93                 break;
94             } catch (ContextConnectionException e) {
95                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
96                         context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
97                         Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
98                         Integer.toString(rc.getRetryLimit()));
99                 logger.error(msg, e);
100                 metricsLogger.error(msg, e);
101                 rc.delay();
102             }
103         }
104         if (rc.isFailed()) {
105             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
106             logger.error(msg);
107             metricsLogger.error(msg);
108             throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
109         }
110         rc.reset();
111         // Locate snapshot image - image names containing colon must be prefixed by in:
112         // and surrounded with quotes
113         Image snapshot = null;
114         while (rc.attempt()) {
115             try {
116                 snapshot = service.getImageByName("in:\"" + snapshotName + "\"");
117                 if (snapshot != null) {
118                     break;
119                 }
120             } catch (ContextConnectionException e) {
121                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
122                         context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
123                         Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
124                         Integer.toString(rc.getRetryLimit()));
125                 logger.error(msg, e);
126                 metricsLogger.error(msg, e);
127                 rc.delay();
128             }
129         }
130         if (rc.isFailed()) {
131             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
132             logger.error(msg);
133             metricsLogger.error(msg);
134             throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
135         }
136         rc.reset();
137         // Wait for it to be ready
138         waitForStateChange(rc, snapshot, Image.Status.ACTIVE);
139         return snapshot;
140     }
141
142     private Image createSnapshot(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
143         Image snapshot = null;
144         RequestContext rc = new RequestContext(ctx);
145         rc.isAlive();
146         setTimeForMetricsLogger();
147         try {
148             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
149                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
150             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
151             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
152             VMURL vm = VMURL.parseURL(vm_url);
153             if (validateVM(rc, appName, vm_url, vm))
154                 return null;
155             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
156             String identStr = (ident == null) ? null : ident.toString();
157             snapshot = createSnapshotNested(snapshot, rc, vm, vm_url, identStr,ctx);
158         } catch (RequestFailedException e) {
159             doFailure(rc, e.getStatus(), e.getMessage());
160         }
161         return snapshot;
162     }
163
164     private Image createSnapshotNested(Image SnapShot, RequestContext RcContext, VMURL vm, String vmUrl,
165             String identStr, SvcLogicContext ctx){
166         String msg;
167         Context context = null;
168         String tenantName = "Unknown";// this variable is also used in catch
169         try {
170             context = getContext(RcContext, vmUrl, identStr);
171             if (context != null) {
172                 tenantName = context.getTenantName();
173                 Server server = lookupServer(RcContext, context, vm.getServerId());
174                 // Is the skip Hypervisor check attribute populated?
175                 String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
176                 if (skipHypervisorCheck == null && ctx != null) {
177                     skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
178                 }
179                 // Always perform Hypervisor check
180                 // unless the skip is set to true
181                 if (skipHypervisorCheck == null || (!"true".equalsIgnoreCase(skipHypervisorCheck))) {
182                     // Check of the Hypervisor for the VM Server is UP and reachable
183                     checkHypervisor(server);
184                 }
185
186                 logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString());
187                 if (hasImageAccess(RcContext, context)) {
188                     SnapShot = createSnapshot(RcContext, server);
189                     doSuccess(RcContext);
190                 } else {
191                     msg = EELFResourceManager.format(Msg.IMAGE_SERVICE_FAILED, server.getName(), server.getId(),
192                             "Accessing Image Service Failed");
193                     logger.error(msg);
194                     metricsLogger.error(msg);
195                     doFailure(RcContext, HttpStatus.FORBIDDEN_403, msg);
196                 }
197                 context.close();
198             }
199         } catch (ResourceNotFoundException e) {
200             msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
201             logger.error(msg);
202             metricsLogger.error(msg, e);
203             doFailure(RcContext, HttpStatus.NOT_FOUND_404, msg);
204         } catch (Exception e1) {
205             msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
206                     Operation.SNAPSHOT_SERVICE.toString(), vmUrl, tenantName);
207             logger.error(msg, e1);
208             doFailure(RcContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
209         }
210         return SnapShot;
211     }
212
213     @Override
214     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
215             throws APPCException {
216         setMDC(Operation.SNAPSHOT_SERVICE.toString(), "App-C IaaS Adapter:Snapshot", ADAPTER_NAME);
217         logOperation(Msg.SNAPSHOTING_SERVER, params, context);
218         setTimeForMetricsLogger();
219         metricsLogger.info("Executing Provider Operation: Create Snapshot");
220         return createSnapshot(params, context);
221     }
222
223     private void setTimeForMetricsLogger() {
224         MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
225         MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "create snapshot");
226         MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
227                 "org.onap.appc.adapter.iaas.provider.operation.impl.CreateSnapshot");
228     }
229 }