Potential Null pointer exception avoided
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / RebootServer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * ================================================================================
9  * Modifications Copyright (C) 2019 Ericsson
10  * Modifications Copyright (C) 2019 IBM
11  * =============================================================================
12  * Licensed under the Apache License, Version 2.0 (the "License");
13  * you may not use this file except in compliance with the License.
14  * You may obtain a copy of the License at
15  * 
16  *      http://www.apache.org/licenses/LICENSE-2.0
17  * 
18  * Unless required by applicable law or agreed to in writing, software
19  * distributed under the License is distributed on an "AS IS" BASIS,
20  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  * See the License for the specific language governing permissions and
22  * limitations under the License.
23  * 
24  * ============LICENSE_END=========================================================
25  */
26 package org.onap.appc.adapter.iaas.provider.operation.impl;
27
28 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
29 import java.util.Map;
30 import java.util.concurrent.TimeoutException;
31 import org.glassfish.grizzly.http.util.HttpStatus;
32 import org.onap.appc.Constants;
33 import org.onap.appc.adapter.iaas.ProviderAdapter;
34 import org.onap.appc.adapter.iaas.impl.IdentityURL;
35 import org.onap.appc.adapter.iaas.impl.RequestContext;
36 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
37 import org.onap.appc.adapter.iaas.impl.VMURL;
38 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
39 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
40 import org.onap.appc.configuration.Configuration;
41 import org.onap.appc.configuration.ConfigurationFactory;
42 import org.onap.appc.exceptions.APPCException;
43 import org.onap.appc.i18n.Msg;
44 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
45 import com.att.cdp.exceptions.ResourceNotFoundException;
46 import com.att.cdp.exceptions.StateException;
47 import com.att.cdp.zones.ComputeService;
48 import com.att.cdp.zones.Context;
49 import com.att.cdp.zones.model.ModelObject;
50 import com.att.cdp.zones.model.Server;
51 import com.att.eelf.configuration.EELFLogger;
52 import com.att.eelf.configuration.EELFManager;
53 import com.att.eelf.i18n.EELFResourceManager;
54 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.REBOOT_SERVICE;
55 import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property;
56
57 public class RebootServer extends ProviderServerOperation {
58     private final EELFLogger logger = EELFManager.getInstance().getLogger(RebootServer.class);
59     private static final Configuration config = ConfigurationFactory.getConfiguration();
60     private static final Integer NO_OF_ATTEMPTS = 30;
61     private static final Integer RETRY_INTERVAL = 10;
62     private static final int MILLI_SECONDS = 1000;
63
64     @Override
65     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
66             throws APPCException {
67         setMDC(Operation.REBOOT_SERVICE.toString(), "App-C IaaS Adapter:rebootServer", ADAPTER_NAME);
68         return rebootServer(params, context);
69     }
70
71     private Server rebootServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
72         Server server = null;
73         RequestContext requestContext = new RequestContext(ctx);
74         requestContext.isAlive();
75         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
76         String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
77         String rebooType = params.get(ProviderAdapter.REBOOT_TYPE);
78         String tenantName = "Unknown";
79         if (rebooType.isEmpty()) {
80             rebooType = "SOFT";
81         }
82         logger.info("reboot type" + rebooType);
83         if (ctx != null) {
84         try {
85             VMURL vm = VMURL.parseURL(vmUrl);
86             Context context;
87             // to be used also in case of exception
88             if (validateVM(requestContext, appName, vmUrl, vm)) {
89                 return null;
90             }
91             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
92             String identStr = (ident == null) ? null : ident.toString();
93             context = getContext(requestContext, vmUrl, identStr);
94             // Is the skip Hypervisor check attribute populated?
95             String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
96             if (skipHypervisorCheck == null && ctx != null) {
97                 skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
98             }
99             if (context != null) {
100                 tenantName = context.getTenantName();// this variable also is
101                 // used in case of exception
102                 requestContext.reset();
103                 server = lookupServer(requestContext, context, vm.getServerId());
104                 logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString());
105                 // Always perform Hypervisor check
106                 // unless the skip is set to true
107                 if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) {
108                     // Check of the Hypervisor for the VM Server is UP and reachable
109                     checkHypervisor(server);
110                 }
111                 Context contx = server.getContext();
112                 ComputeService service = contx.getComputeService();
113                 logger.info("performing reboot action for " + server.getId() + " rebootype " + rebooType);
114                 service.rebootServer(server.getId(), rebooType);
115                 if (waitForServerStatusChange(requestContext, server, vmUrl, Server.Status.RUNNING)) {
116                     ctx.setAttribute("REBOOT_STATUS", "SUCCESS");
117                     doSuccess(requestContext);
118                 } else {
119                     ctx.setAttribute("REBOOT_STATUS", "FAILURE");
120                 }
121                 context.close();
122             } else {
123                 ctx.setAttribute("REBOOT_STATUS", "FAILURE");
124             }
125
126         } catch (ResourceNotFoundException | StateException ex) {
127             ctx.setAttribute("REBOOT_STATUS", "FAILURE");
128             if (ex instanceof ResourceNotFoundException) {
129                 doFailure(requestContext, HttpStatus.NOT_FOUND_404, ex.getMessage());
130             } else {
131                 doFailure(requestContext, HttpStatus.CONFLICT_409, ex.getMessage());
132             }
133         } catch (Exception ex) {
134             ctx.setAttribute("REBOOT_STATUS", "FAILURE");
135             doFailure(requestContext, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.getMessage());
136         }
137         }
138         return server;
139     }
140
141     private boolean waitForServerStatusChange(RequestContext rc, Server server, String vmUrl,
142             Server.Status... desiredStates) throws Exception {
143         int pollInterval = RETRY_INTERVAL.intValue();
144         int timeout = configuration.getIntegerProperty(Constants.PROPERTY_SERVER_STATE_CHANGE_TIMEOUT);
145         config.setProperty(Constants.PROPERTY_RETRY_DELAY, RETRY_INTERVAL.toString());
146         config.setProperty(Constants.PROPERTY_RETRY_LIMIT, NO_OF_ATTEMPTS.toString());
147         Context context = server.getContext();
148         String msg;
149         boolean status = false;
150         while (rc.attempt()) {
151             if ( Server.Status.ERROR.equals(server.getStatus())) {
152                 msg = "Device status " + Server.Status.ERROR + " cannot proceed further";
153                 throw new RequestFailedException("Waiting for State Change", msg, HttpStatus.CONFLICT_409, server);
154             } else {
155                 server.waitForStateChange(pollInterval, timeout, desiredStates);
156                 if (Server.Status.RUNNING.equals(server.getStatus())
157                         || Server.Status.READY.equals(server.getStatus())) {
158                     status = true;
159                 }
160                 logger.info(server.getStatus() + " status ");
161             }
162             if (status) {
163                 logger.info("Done Trying " + rc.getAttempts() + " attempts");
164                 break;
165             } else {
166                 rc.delay();
167             }
168         }
169         if (rc.isFailed()) {
170             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, vmUrl);
171             logger.info("waitForStateChange Failed");
172             logger.error(msg);
173             throw new RequestFailedException("Waiting for State Change", msg, HttpStatus.BAD_GATEWAY_502, server);
174         }
175         if ((rc.getAttempts() == NO_OF_ATTEMPTS) && (!status)) {
176
177             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, Long.toString(rc.getRetryDelay()),
178                     Integer.toString(rc.getAttempts()), Integer.toString(rc.getRetryLimit()));
179             logger.error(msg);
180             throw new TimeoutException(msg);
181         }
182         rc.reset();
183         logger.info("Reboot server status flag --> " + status);
184         return status;
185     }
186 }