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