Merge of new rebased code
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / openecomp / appc / adapter / iaas / provider / operation / impl / SnapshotStack.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.appc.adapter.iaas.provider.operation.impl;
23
24 import org.openecomp.appc.Constants;
25 import org.openecomp.appc.adapter.iaas.ProviderAdapter;
26 import org.openecomp.appc.adapter.iaas.impl.RequestContext;
27 import org.openecomp.appc.adapter.iaas.impl.RequestFailedException;
28 import org.openecomp.appc.adapter.iaas.provider.operation.common.enums.Operation;
29 import org.openecomp.appc.adapter.iaas.provider.operation.impl.base.ProviderOperation;
30 import org.openecomp.appc.adapter.iaas.provider.operation.impl.base.ProviderStackOperation;
31 import org.openecomp.appc.adapter.openstack.heat.SnapshotResource;
32 import org.openecomp.appc.adapter.openstack.heat.StackResource;
33 import org.openecomp.appc.adapter.openstack.heat.model.CreateSnapshotParams;
34 import org.openecomp.appc.adapter.openstack.heat.model.Snapshot;
35 import org.openecomp.appc.configuration.Configuration;
36 import org.openecomp.appc.configuration.ConfigurationFactory;
37 import org.openecomp.appc.exceptions.APPCException;
38 import org.openecomp.appc.i18n.Msg;
39 import com.att.cdp.exceptions.ResourceNotFoundException;
40 import com.att.cdp.exceptions.ZoneException;
41 import com.att.cdp.openstack.OpenStackContext;
42 import com.att.cdp.openstack.connectors.HeatConnector;
43 import com.att.cdp.openstack.util.ExceptionMapper;
44 import com.att.cdp.zones.Context;
45 import com.att.cdp.zones.model.ModelObject;
46 import com.att.cdp.zones.model.Stack;
47 import com.att.cdp.zones.spi.RequestState;
48 import com.att.eelf.configuration.EELFLogger;
49 import com.att.eelf.configuration.EELFManager;
50 import com.att.eelf.i18n.EELFResourceManager;
51 import org.openecomp.sdnc.sli.SvcLogicContext;
52 import com.woorea.openstack.base.client.OpenStackBaseException;
53 import com.woorea.openstack.heat.Heat;
54 import org.glassfish.grizzly.http.util.HttpStatus;
55
56 import java.util.Map;
57
58 import static org.openecomp.appc.adapter.utils.Constants.ADAPTER_NAME;
59
60 import org.slf4j.MDC;
61 import java.text.DateFormat;
62 import java.text.SimpleDateFormat;
63 import java.util.Date;
64 import java.util.TimeZone;
65
66
67 /**
68  * @since September 26, 2016
69  */
70 public class SnapshotStack extends ProviderStackOperation {
71
72     private static final EELFLogger logger = EELFManager.getInstance().getLogger(SnapshotStack.class);
73     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
74
75
76     private Snapshot snapshotStack(@SuppressWarnings("unused") RequestContext rc, Stack stack) throws ZoneException, RequestFailedException {
77         Snapshot snapshot = new Snapshot();
78         Context context = stack.getContext();
79
80         OpenStackContext osContext = (OpenStackContext)context;
81
82         final HeatConnector heatConnector = osContext.getHeatConnector();
83         ((OpenStackContext)context).refreshIfStale(heatConnector);
84
85         trackRequest(context);
86         RequestState.put("SERVICE", "Orchestration");
87         RequestState.put("SERVICE_URL", heatConnector.getEndpoint());
88
89         Heat heat = heatConnector.getClient();
90
91         SnapshotResource snapshotResource = new SnapshotResource(heat);
92         
93         /*
94          * Set Time for Metrics Logger
95          */
96         long startTime = System.currentTimeMillis();
97         TimeZone tz = TimeZone.getTimeZone("UTC");
98         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
99         df.setTimeZone(tz);
100         String startTimeStr = df.format(new Date());
101         long endTime = System.currentTimeMillis();
102         long duration = endTime - startTime;
103         String endTimeStr = String.valueOf(endTime);
104         String durationStr = String.valueOf(duration);
105         String endTimeStrUTC = df.format(new Date());
106         MDC.put("EndTimestamp", endTimeStrUTC);
107         MDC.put("ElapsedTime", durationStr);
108         MDC.put("TargetEntity", "cdp");
109         MDC.put("TargetServiceName", "snapshot stack");
110         MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.SnapshotStack");
111
112         try {
113
114             snapshot = snapshotResource.create(stack.getName(), stack.getId(), new CreateSnapshotParams()).execute();
115
116             // wait for the stack deletion
117             StackResource stackResource = new StackResource(heat);
118             if (!waitForStack(stack, stackResource, "SNAPSHOT_COMPLETE")) {
119                 throw new RequestFailedException("Stack Snapshot failed.");
120             }
121
122         } catch (OpenStackBaseException e) {
123             ExceptionMapper.mapException(e);
124         }
125
126         return snapshot;
127     }
128
129
130     public Stack snapshotStack(Map<String, String> params, SvcLogicContext ctx) throws IllegalArgumentException, APPCException {
131         Stack stack = null;
132         RequestContext rc = new RequestContext(ctx);
133         rc.isAlive();
134
135         ctx.setAttribute("SNAPSHOT_STATUS", "STACK_NOT_FOUND");
136         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
137
138         String vm_url = null;
139         Context context = null;
140
141         /*
142          * Set Time for Metrics Logger
143          */
144         long startTime = System.currentTimeMillis();
145         TimeZone tz = TimeZone.getTimeZone("UTC");
146         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
147         df.setTimeZone(tz);
148         String startTimeStr = df.format(new Date());
149         long endTime = System.currentTimeMillis();
150         long duration = endTime - startTime;
151         String endTimeStr = String.valueOf(endTime);
152         String durationStr = String.valueOf(duration);
153         String endTimeStrUTC = df.format(new Date());
154         MDC.put("EndTimestamp", endTimeStrUTC);
155         MDC.put("ElapsedTime", durationStr);
156         MDC.put("TargetEntity", "cdp");
157         MDC.put("TargetServiceName", "snapshot stack");
158         MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.SnapshotStack");
159         
160         
161         try {
162
163             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
164                     ProviderAdapter.PROPERTY_PROVIDER_NAME, ProviderAdapter.PROPERTY_STACK_ID);
165
166             String stackId = params.get(ProviderAdapter.PROPERTY_STACK_ID);
167             vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
168
169             context = resolveContext(rc, params, appName, vm_url);
170
171             if (context != null) {
172                 stack = lookupStack(rc, context, stackId);
173                 logger.debug(Msg.STACK_FOUND, vm_url, context.getTenantName(), stack.getStatus().toString());
174                 logger.info(EELFResourceManager.format(Msg.SNAPSHOTING_STACK, stack.getName()));
175                 metricsLogger.info(EELFResourceManager.format(Msg.SNAPSHOTING_STACK, stack.getName()));
176
177                 Snapshot snapshot = snapshotStack(rc, stack);
178
179                 ctx.setAttribute(ProviderAdapter.DG_OUTPUT_PARAM_NAMESPACE +
180                         ProviderAdapter.PROPERTY_SNAPSHOT_ID, snapshot.getId());
181
182                 logger.info(EELFResourceManager.format(Msg.STACK_SNAPSHOTED, stack.getName(), snapshot.getId()));
183                 metricsLogger.info(EELFResourceManager.format(Msg.STACK_SNAPSHOTED, stack.getName(), snapshot.getId()));
184                 context.close();
185                 doSuccess(rc);
186             } else {
187                 ctx.setAttribute(Constants.DG_ATTRIBUTE_STATUS, "failure");
188             }
189
190         } catch (ResourceNotFoundException e) {
191             String msg = EELFResourceManager.format(Msg.STACK_NOT_FOUND, e, vm_url);
192             logger.error(msg);
193             metricsLogger.error(msg);
194             doFailure(rc, HttpStatus.NOT_FOUND_404, msg, e);
195         } catch (RequestFailedException e) {
196             logger.error(EELFResourceManager.format(Msg.MISSING_PARAMETER_IN_REQUEST, e.getReason(), "snapshotStack"));
197             metricsLogger.error(EELFResourceManager.format(Msg.MISSING_PARAMETER_IN_REQUEST, e.getReason(), "snapshotStack"));
198             doFailure(rc, e.getStatus(), e.getMessage(), e);
199         } catch (Throwable t) {
200             String msg = EELFResourceManager.format(Msg.STACK_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
201                     "snapshotStack", vm_url, null == context ? "n/a" : context.getTenantName());
202             logger.error(msg, t);
203             metricsLogger.error(msg);
204             doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg, t);
205         }
206         return stack;
207     }
208
209     @Override
210     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) throws APPCException {
211         setMDC(Operation.SNAPSHOT_STACK.toString(), "App-C IaaS Adapter:Snapshot-Stack", ADAPTER_NAME);
212         logOperation(Msg.SNAPSHOTING_STACK, params, context);
213         
214         /*
215          * Set Time for Metrics Logger
216          */
217         long startTime = System.currentTimeMillis();
218         TimeZone tz = TimeZone.getTimeZone("UTC");
219         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
220         df.setTimeZone(tz);
221         String startTimeStr = df.format(new Date());
222         long endTime = System.currentTimeMillis();
223         long duration = endTime - startTime;
224         String endTimeStr = String.valueOf(endTime);
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", "snapshot stack");
231         MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.SnapshotStack");
232         
233         metricsLogger.info("Executing Provider Operation: Snapshot Stack");
234         
235         return snapshotStack(params, context);
236     }
237 }