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