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