Modify iaas adapter provider files license headers
[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
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.adapter.iaas.ProviderAdapter;
37 import org.onap.appc.adapter.iaas.impl.IdentityURL;
38 import org.onap.appc.adapter.iaas.impl.RequestContext;
39 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
40 import org.onap.appc.adapter.iaas.impl.VMURL;
41 import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property;
42 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
43 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
44 import org.onap.appc.configuration.Configuration;
45 import org.onap.appc.configuration.ConfigurationFactory;
46 import org.onap.appc.exceptions.APPCException;
47 import org.onap.appc.i18n.Msg;
48 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
49 import org.slf4j.MDC;
50 import java.io.IOException;
51 import java.text.DateFormat;
52 import java.text.SimpleDateFormat;
53 import java.util.Arrays;
54 import java.util.Collection;
55 import java.util.Date;
56 import java.util.Map;
57 import java.util.TimeZone;
58 import java.util.Iterator;
59 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.MIGRATE_SERVICE;
60 import static org.onap.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, ZoneException 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(Property.SKIP_HYPERVISOR_CHECK);
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
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
136                 break;
137
138             } catch (ZoneException e) {
139                 try {
140                     msg = getConnectionExceptionMessage(rc, ctx, e);
141                 } catch (ZoneException e1) {
142                     String phase = inConfirmPhase ? "VERIFY MIGRATE" : "REQUEST MIGRATE";
143                     msg = EELFResourceManager.format(Msg.MIGRATE_SERVER_FAILED, server.getName(), server.getId(), phase,
144                         e1.getMessage());
145                     generateEvent(rc, false, msg);
146                     logger.error(msg, e1);
147                     metricsLogger.error(msg, e1);
148                     throw new RequestFailedException("Migrate Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
149                 }
150                 logger.error(msg, e);
151                 metricsLogger.error(msg, e);
152                 rc.delay();
153             }
154         }
155     }
156
157     /**
158      * @see org.onap.appc.adapter.iaas.ProviderAdapter#migrateServer(java.util.Map,
159      *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
160      */
161     private Server migrateServer(Map<String, String> params, SvcLogicContext ctx) {
162         Server server = null;
163         RequestContext rc = new RequestContext(ctx);
164         rc.isAlive();
165
166         setTimeForMetricsLogger();
167
168         try {
169             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
170                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
171             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
172
173             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
174             VMURL vm = VMURL.parseURL(vm_url);
175
176             if (validateVM(rc, appName, vm_url, vm))
177                 return null;
178
179             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
180             String identStr = (ident == null) ? null : ident.toString();
181
182             server = conductServerMigration(rc, vm_url, identStr, ctx);
183
184         } catch (RequestFailedException e) {
185             doFailure(rc, e.getStatus(), e.getMessage());
186         }
187
188         return server;
189     }
190
191     @Override
192     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
193             throws APPCException {
194         setMDC(Operation.MIGRATE_SERVICE.toString(), "App-C IaaS Adapter:Migrate", ADAPTER_NAME);
195         logOperation(Msg.MIGRATING_SERVER, params, context);
196
197         setTimeForMetricsLogger();
198
199         metricsLogger.info("Executing Provider Operation: Migrate");
200
201         return migrateServer(params, context);
202     }
203
204     private void setTimeForMetricsLogger() {
205         long startTime = System.currentTimeMillis();
206         TimeZone tz = TimeZone.getTimeZone("UTC");
207         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
208         df.setTimeZone(tz);
209         long endTime = System.currentTimeMillis();
210         long duration = endTime - startTime;
211         String durationStr = String.valueOf(duration);
212         String endTimeStrUTC = df.format(new Date());
213         MDC.put("EndTimestamp", endTimeStrUTC);
214         MDC.put("ElapsedTime", durationStr);
215         MDC.put("TargetEntity", "cdp");
216         MDC.put("TargetServiceName", "migrate server");
217         MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.MigrateServer");
218     }
219
220     private Server conductServerMigration(RequestContext rc, String vm_url, String identStr, SvcLogicContext ctx) throws RequestFailedException {
221         String msg;
222         Context context = getContext(rc, vm_url, identStr);
223         VMURL vm = VMURL.parseURL(vm_url);
224         Server server = null;
225
226         try {
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 (IOException | ZoneException e1) {
236             msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
237                     MIGRATE_SERVICE.toString(), vm_url, context.getTenantName());
238             logger.error(msg, e1);
239             metricsLogger.error(msg);
240             doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
241         }
242         return server;
243     }
244 }