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