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