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