708de287a73700e35d8eeb10a0ee206e9afba4fc
[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  * 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  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.adapter.iaas.provider.operation.impl;
25
26 import com.att.cdp.exceptions.ContextConnectionException;
27 import com.att.cdp.exceptions.ResourceNotFoundException;
28 import com.att.cdp.exceptions.ZoneException;
29 import com.att.cdp.zones.Context;
30 import com.att.cdp.zones.ImageService;
31 import com.att.cdp.zones.Provider;
32 import com.att.cdp.zones.model.Image;
33 import com.att.cdp.zones.model.ModelObject;
34 import com.att.cdp.zones.model.Server;
35 import com.att.eelf.configuration.EELFLogger;
36 import com.att.eelf.configuration.EELFManager;
37 import com.att.eelf.i18n.EELFResourceManager;
38 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
39 import org.glassfish.grizzly.http.util.HttpStatus;
40 import org.onap.appc.Constants;
41 import org.onap.appc.adapter.iaas.ProviderAdapter;
42 import org.onap.appc.adapter.iaas.impl.IdentityURL;
43 import org.onap.appc.adapter.iaas.impl.RequestContext;
44 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
45 import org.onap.appc.adapter.iaas.impl.VMURL;
46 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
47 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
48 import org.onap.appc.configuration.Configuration;
49 import org.onap.appc.configuration.ConfigurationFactory;
50 import org.onap.appc.exceptions.APPCException;
51 import org.onap.appc.i18n.Msg;
52 import org.slf4j.MDC;
53 import java.text.DateFormat;
54 import java.text.SimpleDateFormat;
55 import java.util.Date;
56 import java.util.Map;
57 import java.util.TimeZone;
58 import static org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants.DATE_FORMAT;
59 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
60
61 public class CreateSnapshot extends ProviderServerOperation {
62
63     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CreateSnapshot.class);
64     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
65     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
66
67     private String generateSnapshotName(String server) {
68         setTimeForMetricsLogger();
69
70         SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
71         metricsLogger.info("Snapshot Name Generated: Snapshot of %s at %s", server, df.format(new Date()));
72
73         return String.format("Snapshot of %s at %s", server, df.format(new Date()));
74     }
75
76     private Image createSnapshot(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
77         Context context = server.getContext();
78         Provider provider = context.getProvider();
79         ImageService service = context.getImageService(); // Already checked access by this point
80
81         String snapshotName = generateSnapshotName(server.getName());
82
83         setTimeForMetricsLogger();
84
85         logger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(), server.getId(),
86                 snapshotName));
87         metricsLogger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(),
88                 server.getId(), snapshotName));
89
90         // Request Snapshot
91         String msg;
92         while (rc.attempt()) {
93             try {
94                 server.createSnapshot(snapshotName);
95                 break;
96             } catch (ContextConnectionException e) {
97                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
98                         context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
99                         Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
100                         Integer.toString(rc.getRetryLimit()));
101                 logger.error(msg, e);
102                 metricsLogger.error(msg, e);
103                 rc.delay();
104             }
105         }
106         if (rc.isFailed()) {
107             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
108             logger.error(msg);
109             metricsLogger.error(msg);
110             throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
111         }
112         rc.reset();
113
114         // Locate snapshot image
115         Image snapshot = null;
116         while (rc.attempt()) {
117             try {
118                 snapshot = service.getImageByName(snapshotName);
119                 if (snapshot != null) {
120                     break;
121                 }
122             } catch (ContextConnectionException e) {
123                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
124                         context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
125                         Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
126                         Integer.toString(rc.getRetryLimit()));
127                 logger.error(msg, e);
128                 metricsLogger.error(msg, e);
129                 rc.delay();
130             }
131         }
132         if (rc.isFailed()) {
133             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
134             logger.error(msg);
135             metricsLogger.error(msg);
136             throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
137         }
138         rc.reset();
139
140         // Wait for it to be ready
141         waitForStateChange(rc, snapshot, Image.Status.ACTIVE);
142
143         return snapshot;
144     }
145
146     private Image createSnapshot(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
147         Image snapshot = null;
148         RequestContext rc = new RequestContext(ctx);
149         rc.isAlive();
150
151         setTimeForMetricsLogger();
152         try {
153             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
154                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
155             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
156             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
157             VMURL vm = VMURL.parseURL(vm_url);
158             if (validateVM(rc, appName, vm_url, vm))
159                 return null;
160
161             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
162             String identStr = (ident == null) ? null : ident.toString();
163             snapshot = createSnapshotNested(snapshot, rc, vm, vm_url, identStr);
164         } catch (RequestFailedException e) {
165             doFailure(rc, e.getStatus(), e.getMessage());
166         }
167         return snapshot;
168     }
169
170     private Image createSnapshotNested(Image SnapShot, RequestContext RcContext, VMURL vm, String vmUrl, String identStr) 
171             throws APPCException {
172
173         String msg;
174
175         Context context = null;
176         String tenantName = "Unknown";//this variable is also used in catch
177         try {
178             context = getContext(RcContext, vmUrl, identStr);
179             if (context != null) {
180                 tenantName = context.getTenantName();
181                 Server server = lookupServer(RcContext, context, vm.getServerId());
182
183                 logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString());
184
185                 if (hasImageAccess(RcContext, context)) {
186                     SnapShot = createSnapshot(RcContext, server);
187                     doSuccess(RcContext);
188                 } else {
189                     msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
190                             "Accessing Image Service Failed");
191                     logger.error(msg);
192                     metricsLogger.error(msg);
193                     doFailure(RcContext, HttpStatus.FORBIDDEN_403, msg);
194                 }
195                 context.close();
196             }
197         } catch (ResourceNotFoundException e) {
198             msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
199             logger.error(msg);
200             metricsLogger.error(msg, e);
201             doFailure(RcContext, HttpStatus.NOT_FOUND_404, msg);
202         } catch (Exception e1) {
203             msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
204                     Operation.SNAPSHOT_SERVICE.toString(), vmUrl,
205                     tenantName);
206             logger.error(msg, e1);
207             doFailure(RcContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
208         }
209         return SnapShot;
210     }
211
212     @Override
213     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
214             throws APPCException {
215
216         setMDC(Operation.SNAPSHOT_SERVICE.toString(), "App-C IaaS Adapter:Snapshot", ADAPTER_NAME);
217         logOperation(Msg.SNAPSHOTING_SERVER, params, context);
218         setTimeForMetricsLogger();
219
220         metricsLogger.info("Executing Provider Operation: Create Snapshot");
221
222         return createSnapshot(params, context);
223     }
224
225     private void setTimeForMetricsLogger() {
226         long startTime = System.currentTimeMillis();
227         TimeZone tz = TimeZone.getTimeZone("UTC");
228         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
229         df.setTimeZone(tz);
230         long endTime = System.currentTimeMillis();
231         long duration = endTime - startTime;
232         String durationStr = String.valueOf(duration);
233         String endTimeStrUTC = df.format(new Date());
234         MDC.put("EndTimestamp", endTimeStrUTC);
235         MDC.put("ElapsedTime", durationStr);
236         MDC.put("TargetEntity", "cdp");
237         MDC.put("TargetServiceName", "create snapshot");
238         MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.CreateSnapshot");
239     }
240 }