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