enchance rebuildaction to make snapshotid Optional
[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.onap.appc.logging.LoggingConstants;
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         SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
71         metricsLogger.info("Snapshot Name Generated: Snapshot of %s at %s", server, df.format(new Date()));
72         return String.format("Snapshot of %s at %s", server, df.format(new Date()));
73     }
74
75     private Image createSnapshot(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
76         Context context = server.getContext();
77         Provider provider = context.getProvider();
78         ImageService service = context.getImageService(); // Already checked access by this point
79         String snapshotName = generateSnapshotName(server.getName());
80         setTimeForMetricsLogger();
81         logger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(), server.getId(),
82                 snapshotName));
83         metricsLogger.info(String.format("Creating snapshot of server %s (%s) with name %s", server.getName(),
84                 server.getId(), snapshotName));
85         // Request Snapshot
86         String msg;
87         while (rc.attempt()) {
88             try {
89                 server.createSnapshot(snapshotName);
90                 break;
91             } catch (ContextConnectionException e) {
92                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
93                         context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
94                         Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
95                         Integer.toString(rc.getRetryLimit()));
96                 logger.error(msg, e);
97                 metricsLogger.error(msg, e);
98                 rc.delay();
99             }
100         }
101         if (rc.isFailed()) {
102             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
103             logger.error(msg);
104             metricsLogger.error(msg);
105             throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
106         }
107         rc.reset();
108         // Locate snapshot image
109         Image snapshot = null;
110         while (rc.attempt()) {
111             try {
112                 snapshot = service.getImageByName(snapshotName);
113                 if (snapshot != null) {
114                     break;
115                 }
116             } catch (ContextConnectionException e) {
117                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
118                         context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
119                         Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
120                         Integer.toString(rc.getRetryLimit()));
121                 logger.error(msg, e);
122                 metricsLogger.error(msg, e);
123                 rc.delay();
124             }
125         }
126         if (rc.isFailed()) {
127             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
128             logger.error(msg);
129             metricsLogger.error(msg);
130             throw new RequestFailedException("Stop Server", msg, HttpStatus.BAD_GATEWAY_502, server);
131         }
132         rc.reset();
133         // Wait for it to be ready
134         waitForStateChange(rc, snapshot, Image.Status.ACTIVE);
135         return snapshot;
136     }
137
138     private Image createSnapshot(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
139         Image snapshot = null;
140         RequestContext rc = new RequestContext(ctx);
141         rc.isAlive();
142         setTimeForMetricsLogger();
143         try {
144             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
145                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
146             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
147             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
148             VMURL vm = VMURL.parseURL(vm_url);
149             if (validateVM(rc, appName, vm_url, vm))
150                 return null;
151             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
152             String identStr = (ident == null) ? null : ident.toString();
153             snapshot = createSnapshotNested(snapshot, rc, vm, vm_url, identStr);
154         } catch (RequestFailedException e) {
155             doFailure(rc, e.getStatus(), e.getMessage());
156         }
157         return snapshot;
158     }
159
160     private Image createSnapshotNested(Image SnapShot, RequestContext RcContext, VMURL vm, String vmUrl,
161             String identStr) throws APPCException {
162         String msg;
163         Context context = null;
164         String tenantName = "Unknown";// this variable is also used in catch
165         try {
166             context = getContext(RcContext, vmUrl, identStr);
167             if (context != null) {
168                 tenantName = context.getTenantName();
169                 Server server = lookupServer(RcContext, context, vm.getServerId());
170                 logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString());
171                 if (hasImageAccess(RcContext, context)) {
172                     SnapShot = createSnapshot(RcContext, server);
173                     doSuccess(RcContext);
174                 } else {
175                     msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
176                             "Accessing Image Service Failed");
177                     logger.error(msg);
178                     metricsLogger.error(msg);
179                     doFailure(RcContext, HttpStatus.FORBIDDEN_403, msg);
180                 }
181                 context.close();
182             }
183         } catch (ResourceNotFoundException e) {
184             msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
185             logger.error(msg);
186             metricsLogger.error(msg, e);
187             doFailure(RcContext, HttpStatus.NOT_FOUND_404, msg);
188         } catch (Exception e1) {
189             msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
190                     Operation.SNAPSHOT_SERVICE.toString(), vmUrl, tenantName);
191             logger.error(msg, e1);
192             doFailure(RcContext, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
193         }
194         return SnapShot;
195     }
196
197     @Override
198     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
199             throws APPCException {
200         setMDC(Operation.SNAPSHOT_SERVICE.toString(), "App-C IaaS Adapter:Snapshot", ADAPTER_NAME);
201         logOperation(Msg.SNAPSHOTING_SERVER, params, context);
202         setTimeForMetricsLogger();
203         metricsLogger.info("Executing Provider Operation: Create Snapshot");
204         return createSnapshot(params, context);
205     }
206
207     private void setTimeForMetricsLogger() {
208         MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
209         MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "create snapshot");
210         MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
211                 "org.onap.appc.adapter.iaas.provider.operation.impl.CreateSnapshot");
212     }
213 }