lowered code smells
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / TerminateServer.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.ContextConnectionException;
27 import com.att.cdp.exceptions.ResourceNotFoundException;
28 import com.att.cdp.exceptions.ZoneException;
29 import com.att.cdp.zones.ComputeService;
30 import com.att.cdp.zones.Context;
31 import com.att.cdp.zones.Provider;
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.enums.Outcome;
45 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
46 import org.onap.appc.exceptions.UnknownProviderException;
47 import org.onap.appc.i18n.Msg;
48 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
49 import java.util.Map;
50 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.RESTART_SERVICE;
51 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.TERMINATE_SERVICE;
52 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
53
54 public class TerminateServer extends ProviderServerOperation {
55
56     private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class);
57
58     /**
59      * Start the server and wait for it to enter a running state
60      *
61      * @param rc The request context that manages the state and recovery of the request for the life of its processing.
62      * @param server The server to be started
63      * @throws ZoneException when error occurs
64      * @throws RequestFailedException when request failed
65      */
66     @SuppressWarnings("nls")
67     private void deleteServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
68         String msg;
69         Context context = server.getContext();
70         Provider provider = context.getProvider();
71         ComputeService service = context.getComputeService();
72         while (rc.attempt()) {
73             try {
74                 logger.info("deleting SERVER");
75                 server.delete();
76                 break;
77             } catch (ContextConnectionException e) {
78                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
79                         context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
80                         Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
81                         Integer.toString(rc.getRetryLimit()));
82                 logger.error(msg, e);
83                 rc.delay();
84             }
85         }
86         if (rc.isFailed()) {
87             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
88             logger.error(msg);
89             throw new RequestFailedException("Delete Server", msg, HttpStatus.BAD_GATEWAY_502, server);
90         }
91         rc.reset();
92     }
93
94     /**
95      * This method handles the case of restarting a server once we have found the server and have obtained the abstract
96      * representation of the server via the context (i.e., the "Server" object from the CDP-Zones abstraction).
97      *
98      * @param rc The request context that manages the state and recovery of the request for the life of its processing.
99      * @param server The server object representing the server we want to operate on
100      * @throws ZoneException when error occurs
101      */
102     @SuppressWarnings("nls")
103     private void terminateServer(RequestContext rc, Server server) throws ZoneException, RequestFailedException {
104         /*
105          * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
106          * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
107          * to one we can deal with. If not, then we have to fail the request.
108          */
109         String msg;
110         if (server.getStatus().equals(Server.Status.PENDING)) {
111             waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
112                     Server.Status.SUSPENDED, Server.Status.PAUSED);
113         }
114
115         /*
116          * We determine what to do based on the current state of the server
117          */
118         switch (server.getStatus()) {
119             case DELETED:
120                 // Nothing to do, the server is gone
121                 msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
122                         server.getTenantId(), "restarted");
123                 generateEvent(rc, false, msg);
124                 logger.error(msg);
125                 break;
126
127             case RUNNING:
128                 // Attempt to stop and start the server
129                 logger.info("stopping SERVER");
130                 stopServer(rc, server);
131                 deleteServer(rc, server);
132                 logger.info("after delete SERVER");
133                 generateEvent(rc, true, Outcome.SUCCESS.toString());
134                 break;
135
136             case ERROR:
137
138             case READY:
139
140             case PAUSED:
141
142             case SUSPENDED:
143                 // Attempt to delete the suspended server
144                 deleteServer(rc, server);
145                 generateEvent(rc, true, Outcome.SUCCESS.toString());
146                 break;
147
148             default:
149                 // Hmmm, unknown status, should never occur
150                 msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
151                         server.getTenantId(), server.getStatus().name());
152                 generateEvent(rc, false, msg);
153                 logger.error(msg);
154                 break;
155         }
156
157     }
158
159     /**
160      * This method is used to delete an existing virtual machine given the fully qualified URL of the machine.
161      * <p>
162      * The fully qualified URL contains enough information to locate the appropriate server. The URL is of the form
163      * 
164      * <pre>
165      *  [scheme]://[host[:port]] / [path] / [tenant_id] / servers / [vm_id]
166      * </pre>
167      * 
168      * Where the various parts of the URL can be parsed and extracted and used to locate the appropriate service in the
169      * provider service catalog. This then allows us to open a context using the CDP abstraction, obtain the server by
170      * its UUID, and then perform the restart.
171      * </p>
172      *
173      * @throws UnknownProviderException If the provider cannot be found
174      * @throws IllegalArgumentException if the expected argument(s) are not defined or are invalid
175      * @see org.onap.appc.adapter.iaas.ProviderAdapter#terminateServer(java.util.Map,
176      *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
177      */
178     @SuppressWarnings("nls")
179     public Server terminateServer(Map<String, String> params, SvcLogicContext ctx)
180             throws UnknownProviderException, IllegalArgumentException {
181         Server server = null;
182         RequestContext rc = new RequestContext(ctx);
183         rc.isAlive();
184
185         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
186
187         try {
188             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
189                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
190
191             String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
192             ctx.setAttribute("TERMINATE_STATUS", "SUCCESS");
193
194             VMURL vm = VMURL.parseURL(vmUrl);
195             if (validateVM(rc, appName, vmUrl, vm))
196                 return null;
197
198             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
199             String identStr = (ident == null) ? null : ident.toString();
200
201             Context context = null;
202             String tenantName = "Unknown";//to be used also in case of exception
203             try {
204                 context = getContext(rc, vmUrl, identStr);
205                 if (context != null) {
206                     tenantName = context.getTenantName();//this varaible also is used in case of exception
207                     server = lookupServer(rc, context, vm.getServerId());
208                     logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString());
209                     logger.info(EELFResourceManager.format(Msg.TERMINATING_SERVER, server.getName()));
210                     terminateServer(rc, server);
211                     logger.info(EELFResourceManager.format(Msg.TERMINATE_SERVER, server.getName()));
212                     context.close();
213                     doSuccess(rc);
214                 } else {
215                     ctx.setAttribute("TERMINATE_STATUS", "SERVER_NOT_FOUND");
216                 }
217             } catch (ResourceNotFoundException e) {
218                 String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
219                 logger.error(msg);
220                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
221                 ctx.setAttribute("TERMINATE_STATUS", "SERVER_NOT_FOUND");
222             } catch (Exception e1) {
223                 String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1,
224                         e1.getClass().getSimpleName(), RESTART_SERVICE.toString(), vmUrl,
225                         tenantName);
226                 logger.error(msg, e1);
227                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
228             }
229         } catch (RequestFailedException e) {
230             logger.error(
231                     EELFResourceManager.format(Msg.TERMINATE_SERVER_FAILED, appName, "n/a", "n/a", e.getMessage()));
232             doFailure(rc, e.getStatus(), e.getMessage());
233             ctx.setAttribute("TERMINATE_STATUS", "ERROR");
234         }
235
236         return server;
237     }
238
239     @Override
240     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
241             throws UnknownProviderException {
242         setMDC(TERMINATE_SERVICE.toString(), "App-C IaaS Adapter:Terminate", ADAPTER_NAME);
243         logOperation(Msg.TERMINATING_SERVER, params, context);
244         return terminateServer(params, context);
245     }
246 }