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