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