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