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