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 / MigrateServer.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.IdentityURL;
27 import org.openecomp.appc.adapter.iaas.impl.RequestContext;
28 import org.openecomp.appc.adapter.iaas.impl.RequestFailedException;
29 import org.openecomp.appc.adapter.iaas.impl.VMURL;
30 import org.openecomp.appc.adapter.iaas.provider.operation.common.enums.Operation;
31 import org.openecomp.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
32 import org.openecomp.appc.configuration.Configuration;
33 import org.openecomp.appc.configuration.ConfigurationFactory;
34 import org.openecomp.appc.exceptions.APPCException;
35 import org.openecomp.appc.i18n.Msg;
36 import com.att.cdp.exceptions.ContextConnectionException;
37 import com.att.cdp.exceptions.ResourceNotFoundException;
38 import com.att.cdp.exceptions.ZoneException;
39 import com.att.cdp.zones.ComputeService;
40 import com.att.cdp.zones.Context;
41 import com.att.cdp.zones.model.ModelObject;
42 import com.att.cdp.zones.model.Server;
43 import com.att.eelf.configuration.EELFLogger;
44 import com.att.eelf.configuration.EELFManager;
45 import com.att.eelf.i18n.EELFResourceManager;
46 import org.openecomp.sdnc.sli.SvcLogicContext;
47 import org.glassfish.grizzly.http.util.HttpStatus;
48
49 import java.util.Arrays;
50 import java.util.Collection;
51 import java.util.Map;
52
53 import static org.openecomp.appc.adapter.iaas.provider.operation.common.constants.Constants.MDC_SERVICE;
54 import static org.openecomp.appc.adapter.iaas.provider.operation.common.enums.Operation.MIGRATE_SERVICE;
55 import static org.openecomp.appc.adapter.utils.Constants.ADAPTER_NAME;
56
57 import org.slf4j.MDC;
58 import java.text.DateFormat;
59 import java.text.SimpleDateFormat;
60 import java.util.Date;
61 import java.util.TimeZone;
62
63
64 /**
65  * @since September 26, 2016
66  */
67 public class MigrateServer extends ProviderServerOperation {
68
69     private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class);
70     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
71     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
72
73     /**
74      * A list of valid initial VM statuses for a migrate operations
75      */
76     private final Collection<Server.Status> migratableStatuses = Arrays.asList(Server.Status.READY, Server.Status.RUNNING, Server.Status.SUSPENDED);
77
78
79     private String getConnectionExceptionMessage(RequestContext rc, Context ctx, ContextConnectionException e)
80             throws ZoneException {
81         return EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, ctx.getProvider().getName(),
82                 ctx.getComputeService().getURL(), ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
83                 Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
84                 Integer.toString(rc.getRetryLimit()));
85     }
86
87         private void migrateServer(RequestContext rc, Server server, SvcLogicContext svcCtx)
88                         throws ZoneException, RequestFailedException {
89                 String msg;
90                 Context ctx = server.getContext();
91                 ComputeService service = ctx.getComputeService();
92
93                 // Init status will equal final status
94                 Server.Status initialStatus = server.getStatus();
95
96                 if (initialStatus == null) {
97                         throw new ZoneException("Failed to determine server's starting status");
98                 }
99
100                 // We can only migrate certain statuses
101                 if (!migratableStatuses.contains(initialStatus)) {
102                         throw new ZoneException(String.format("Cannot migrate server that is in %s state. Must be in one of [%s]",
103                                         initialStatus, migratableStatuses));
104                 }
105
106                 /*
107                  * Set Time for Metrics Logger
108                  */
109                 long startTime = System.currentTimeMillis();
110                 TimeZone tz = TimeZone.getTimeZone("UTC");
111                 DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
112                 df.setTimeZone(tz);
113                 String startTimeStr = df.format(new Date());
114                 long endTime = System.currentTimeMillis();
115                 long duration = endTime - startTime;
116                 String endTimeStr = String.valueOf(endTime);
117                 String durationStr = String.valueOf(duration);
118                 String endTimeStrUTC = df.format(new Date());
119                 MDC.put("EndTimestamp", endTimeStrUTC);
120                 MDC.put("ElapsedTime", durationStr);
121                 MDC.put("TargetEntity", "cdp");
122                 MDC.put("TargetServiceName", "migrate server");
123                 MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.MigrateServer");
124                 // Is the skip Hypervisor check attribute populated?
125                 String skipHypervisorCheck = null;
126                 if (svcCtx != null) {
127                         skipHypervisorCheck = svcCtx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
128
129                 }
130
131                 // // Always perform Hypervisor check
132                 // unless the skip is set to true
133                 
134                 if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) {
135
136                         // Check of the Hypervisor for the VM Server is UP and reachable
137                         
138                         checkHypervisor(server);
139                         
140                 }
141                 
142                         boolean inConfirmPhase = false;
143                         try {
144                                 while (rc.attempt()) {
145                                         try {
146                                                 if (!inConfirmPhase) {
147                                                         // Initial migrate request
148                                                         service.migrateServer(server.getId());
149                                                         // Wait for change to verify resize
150                                                         waitForStateChange(rc, server, Server.Status.READY);
151                                                         inConfirmPhase = true;
152                                                 }
153
154                                                 // Verify resize
155                                                 service.processResize(server);
156                                                 // Wait for complete. will go back to init status
157                                                 waitForStateChange(rc, server, initialStatus);
158                                                 logger.info("Completed migrate request successfully");
159                                                 metricsLogger.info("Completed migrate request successfully");
160                                                 return;
161                                         } catch (ContextConnectionException e) {
162                                                 msg = getConnectionExceptionMessage(rc, ctx, e);
163                                                 logger.error(msg, e);
164                                                 metricsLogger.error(msg, e);
165                                                 rc.delay();
166                                         }
167                                 }
168                         } catch (ZoneException e) {
169                                 String phase = inConfirmPhase ? "VERIFY MIGRATE" : "REQUEST MIGRATE";
170                                 msg = EELFResourceManager.format(Msg.MIGRATE_SERVER_FAILED, server.getName(), server.getId(), phase,
171                                                 e.getMessage());
172                                 generateEvent(rc, false, msg);
173                                 logger.error(msg, e);
174                                 metricsLogger.error(msg, e);
175                                 throw new RequestFailedException("Migrate Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
176                         }
177                 
178         }
179
180     /**
181      * @see org.openecomp.appc.adapter.iaas.ProviderAdapter#migrateServer(java.util.Map, org.openecomp.sdnc.sli.SvcLogicContext)
182      */
183     private Server migrateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
184         Server server = null;
185         RequestContext rc = new RequestContext(ctx);
186         rc.isAlive();
187
188         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
189         String msg;
190         
191         /*
192          * Set Time for Metrics Logger
193          */
194         long startTime = System.currentTimeMillis();
195         TimeZone tz = TimeZone.getTimeZone("UTC");
196         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
197         df.setTimeZone(tz);
198         String startTimeStr = df.format(new Date());
199         long endTime = System.currentTimeMillis();
200         long duration = endTime - startTime;
201         String endTimeStr = String.valueOf(endTime);
202         String durationStr = String.valueOf(duration);
203         String endTimeStrUTC = df.format(new Date());
204         MDC.put("EndTimestamp", endTimeStrUTC);
205         MDC.put("ElapsedTime", durationStr);
206         MDC.put("TargetEntity", "cdp");
207         MDC.put("TargetServiceName", "migrate server");
208         MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.MigrateServer"); 
209
210         try {
211             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
212                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
213             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
214
215             VMURL vm = VMURL.parseURL(vm_url);
216             if (validateVM(rc, appName, vm_url, vm)) return null;
217
218             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
219             String identStr = (ident == null) ? null : ident.toString();
220
221             Context context = null;
222             try {
223                 context = getContext(rc, vm_url, identStr);
224                 if (context != null) {
225                     server = lookupServer(rc, context, vm.getServerId());
226                     logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
227                     migrateServer(rc, server, ctx);
228                     server.refreshStatus();
229                     context.close();
230                     doSuccess(rc);
231                 }
232             } catch (RequestFailedException e) {
233                 doFailure(rc, e.getStatus(), e.getMessage());
234             }
235             catch (ResourceNotFoundException e) {
236                 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
237                 logger.error(msg);
238                 metricsLogger.error(msg);
239                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
240             } catch (Throwable t) {
241                 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
242                         MIGRATE_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName());
243                 logger.error(msg, t);
244                 metricsLogger.error(msg);
245                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
246             }
247         } catch (RequestFailedException e) {
248             doFailure(rc, e.getStatus(), e.getMessage());
249         }
250
251         return server;
252     }
253
254     @Override
255     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) throws APPCException {
256
257         setMDC(Operation.MIGRATE_SERVICE.toString(), "App-C IaaS Adapter:Migrate", ADAPTER_NAME);
258         logOperation(Msg.MIGRATING_SERVER, params, context);
259         
260         /*
261          * Set Time for Metrics Logger
262          */
263         long startTime = System.currentTimeMillis();
264         TimeZone tz = TimeZone.getTimeZone("UTC");
265         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
266         df.setTimeZone(tz);
267         String startTimeStr = df.format(new Date());
268         long endTime = System.currentTimeMillis();
269         long duration = endTime - startTime;
270         String endTimeStr = String.valueOf(endTime);
271         String durationStr = String.valueOf(duration);
272         String endTimeStrUTC = df.format(new Date());
273         MDC.put("EndTimestamp", endTimeStrUTC);
274         MDC.put("ElapsedTime", durationStr);
275         MDC.put("TargetEntity", "cdp");
276         MDC.put("TargetServiceName", "migrate server");
277         MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.MigrateServer"); 
278         
279         
280         metricsLogger.info("Executing Provider Operation: Migrate");
281         
282         return migrateServer(params,context);
283     }
284 }