72b2ba26b84b90a5161eb395b74a647e7739dc82
[appc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2019 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  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.adapter.iaas.provider.operation.impl;
25
26 import org.onap.appc.Constants;
27 import org.onap.appc.adapter.iaas.ProviderAdapter;
28 import org.onap.appc.adapter.iaas.impl.IdentityURL;
29 import org.onap.appc.adapter.iaas.impl.RequestContext;
30 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
31 import org.onap.appc.adapter.iaas.impl.VMURL;
32 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome;
33 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
34 import org.onap.appc.exceptions.APPCException;
35 import org.onap.appc.i18n.Msg;
36 import org.onap.appc.logging.LoggingConstants;
37 import org.onap.appc.logging.LoggingUtils;
38 import com.att.cdp.exceptions.ResourceNotFoundException;
39 import com.att.cdp.zones.Context;
40 import com.att.cdp.zones.model.ModelObject;
41 import com.att.cdp.zones.model.Server;
42 import com.att.eelf.configuration.EELFLogger;
43 import com.att.eelf.configuration.EELFManager;
44 import com.att.eelf.i18n.EELFResourceManager;
45 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
46 import org.glassfish.grizzly.http.util.HttpStatus;
47 import java.util.Date;
48 import java.util.Map;
49 import org.slf4j.MDC;
50 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.STOP_SERVICE;
51 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
52 import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property;
53
54 public class StopServer extends ProviderServerOperation {
55
56     private final EELFLogger logger = EELFManager.getInstance().getLogger(StopServer.class);
57     private final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
58
59     /**
60      * @see org.onap.appc.adapter.iaas.ProviderAdapter#stopServer(java.util.Map,
61      *      org.openecomp.sdnc.sli.SvcLogicContext)
62      */
63     @SuppressWarnings("nls")
64     private Server stopServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
65         Server server = null;
66         RequestContext rc = new RequestContext(ctx);
67         rc.isAlive();
68         setTimeForMetricsLogger();
69         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
70         try {
71             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
72                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
73             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
74             ctx.setAttribute("STOP_STATUS", "SUCCESS");
75             VMURL vm = VMURL.parseURL(vm_url);
76             if (validateVM(rc, appName, vm_url, vm))
77                 return null;
78             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
79             String identStr = (ident == null) ? null : ident.toString();
80             Context context = null;
81             ctx.setAttribute("STOP_STATUS", "ERROR");
82             // Is the skip Hypervisor check attribute populated?
83             String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
84             if (skipHypervisorCheck == null && ctx != null) {
85                 skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
86             }
87             try {
88                 context = getContext(rc, vm_url, identStr);
89                 if (context != null) {
90                     rc.reset();
91                     server = lookupServer(rc, context, vm.getServerId());
92                     logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
93                     // Always perform Hypervisor check
94                     // unless the skip is set to true
95                     if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) {
96                         // Check of the Hypervisor for the VM Server is UP and reachable
97                         checkHypervisor(server);
98                     }
99                     String msg;
100                     /*
101                      * We determine what to do based on the current state of the server
102                      */
103                     /*
104                      * Pending is a bit of a special case. If we find the server is in a pending
105                      * state, then the provider is in the process of changing state of the server.
106                      * So, lets try to wait a little bit and see if the state settles down to one we
107                      * can deal with. If not, then we have to fail the request.
108                      */
109                     if (server.getStatus().equals(Server.Status.PENDING)) {
110                         waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
111                                 Server.Status.SUSPENDED, Server.Status.PAUSED, Server.Status.DELETED);
112                     }
113                     switch (server.getStatus()) {
114                     case DELETED:
115                         // Nothing to do, the server is gone
116                         msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
117                                 server.getTenantId(), "stopped");
118                         generateEvent(rc, false, msg);
119                         logger.error(msg);
120                         metricsLogger.error(msg);
121                         throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
122                     case RUNNING:
123                         // Attempt to stop the server
124                         rc.reset();
125                         stopServer(rc, server);
126                         generateEvent(rc, true, Outcome.SUCCESS.toString());
127                         break;
128                     case ERROR:
129                         // Server is in error state
130                         msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
131                                 server.getTenantId(), "stop");
132                         generateEvent(rc, false, msg);
133                         logger.error(msg);
134                         metricsLogger.error(msg);
135                         throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
136                     case READY:
137                         // Nothing to do, the server was already stopped
138                         logger.info("Server was already stopped");
139                         break;
140                     case PAUSED:
141                         // if paused, un-pause it and then stop it
142                         rc.reset();
143                         unpauseServer(rc, server);
144                         rc.reset();
145                         stopServer(rc, server);
146                         generateEvent(rc, true, Outcome.SUCCESS.toString());
147                         break;
148                     case SUSPENDED:
149                         // Attempt to resume the suspended server and after that stop it
150                         rc.reset();
151                         resumeServer(rc, server);
152                         rc.reset();
153                         stopServer(rc, server);
154                         generateEvent(rc, true, Outcome.SUCCESS.toString());
155                         break;
156                     default:
157                         // Hmmm, unknown status, should never occur
158                         msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
159                                 server.getTenantId(), server.getStatus().name());
160                         generateEvent(rc, false, msg);
161                         logger.error(msg);
162                         metricsLogger.error(msg);
163                         throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
164                     }
165                     context.close();
166                     doSuccess(rc);
167                     ctx.setAttribute("STOP_STATUS", "SUCCESS");
168                     msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "StopServer", vm_url);
169                     ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
170                 } else {
171                     ctx.setAttribute("STOP_STATUS", "CONTEXT_NOT_FOUND");
172                 }
173             } catch (ResourceNotFoundException e) {
174                 String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
175                 logger.error(msg);
176                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
177             } catch (Exception e1) {
178                 String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1,
179                         e1.getClass().getSimpleName(), STOP_SERVICE.toString(), vm_url,
180                         context == null ? "Unknown" : context.getTenantName());
181                 logger.error(msg, e1);
182                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
183             }
184         } catch (RequestFailedException e) {
185             logger.error(EELFResourceManager.format(Msg.STOP_SERVER_FAILED, appName, "n/a", "n/a", e.getMessage()));
186             doFailure(rc, e.getStatus(), e.getMessage());
187         }
188         return server;
189     }
190
191     @Override
192     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
193             throws APPCException {
194         setMDC(STOP_SERVICE.toString(), "App-C IaaS Adapter:Stop", ADAPTER_NAME);
195         logOperation(Msg.STOPPING_SERVER, params, context);
196         return stopServer(params, context);
197     }
198
199     private void setTimeForMetricsLogger() {
200         String timestamp = LoggingUtils.generateTimestampStr(((Date) new Date()).toInstant());
201         MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
202         MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
203         MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
204         MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
205         MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
206         MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "stop server");
207         MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, "org.onap.appc.adapter.iaas.provider.operation.impl.StopServer");
208     }
209
210 }