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