aboutsummaryrefslogtreecommitdiffstats
path: root/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/provider/operation/impl/StopServer.java
blob: 9e053cc6ae8bd7c3bcbeb21fc2c58c6a5f8d8d21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/*-
 * ============LICENSE_START=======================================================
 * ONAP : APPC
 * ================================================================================
 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Copyright (C) 2017 Amdocs
 * ================================================================================
 * Modifications Copyright (c) 2019 IBM
 * =============================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * ============LICENSE_END=========================================================
 */

package org.onap.appc.adapter.iaas.provider.operation.impl;

import org.onap.appc.Constants;
import org.onap.appc.adapter.iaas.ProviderAdapter;
import org.onap.appc.adapter.iaas.impl.IdentityURL;
import org.onap.appc.adapter.iaas.impl.RequestContext;
import org.onap.appc.adapter.iaas.impl.RequestFailedException;
import org.onap.appc.adapter.iaas.impl.VMURL;
import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome;
import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
import org.onap.appc.exceptions.APPCException;
import org.onap.appc.i18n.Msg;
import org.onap.appc.logging.LoggingConstants;
import org.onap.appc.logging.LoggingUtils;
import com.att.cdp.exceptions.ResourceNotFoundException;
import com.att.cdp.zones.Context;
import com.att.cdp.zones.model.ModelObject;
import com.att.cdp.zones.model.Server;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.att.eelf.i18n.EELFResourceManager;
import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
import org.glassfish.grizzly.http.util.HttpStatus;
import java.util.Date;
import java.util.Map;
import org.slf4j.MDC;
import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.STOP_SERVICE;
import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property;

public class StopServer extends ProviderServerOperation {

    private final EELFLogger logger = EELFManager.getInstance().getLogger(StopServer.class);
    private final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();

    /**
     * @see org.onap.appc.adapter.iaas.ProviderAdapter#stopServer(java.util.Map,
     *      org.openecomp.sdnc.sli.SvcLogicContext)
     */
    @SuppressWarnings("nls")
    private Server stopServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
        Server server = null;
        RequestContext rc = new RequestContext(ctx);
        rc.isAlive();
        setTimeForMetricsLogger();
        String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
        try {
            validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
                    ProviderAdapter.PROPERTY_PROVIDER_NAME);
            String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
            ctx.setAttribute("STOP_STATUS", "SUCCESS");
            VMURL vm = VMURL.parseURL(vmUrl);
            if (validateVM(rc, appName, vmUrl, vm))
                return null;
            IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
            String identStr = (ident == null) ? null : ident.toString();
            Context context = null;
            ctx.setAttribute("STOP_STATUS", "ERROR");
            // Is the skip Hypervisor check attribute populated?
            String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
            if (skipHypervisorCheck == null && ctx != null) {
                skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
            }
            try {
                context = getContext(rc, vmUrl, identStr);
                if (context != null) {
                    rc.reset();
                    server = lookupServer(rc, context, vm.getServerId());
                    logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString());
                    // Always perform Hypervisor check
                    // unless the skip is set to true
                    if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) {
                        // Check of the Hypervisor for the VM Server is UP and reachable
                        checkHypervisor(server);
                    }
                    String msg;
                    /*
                     * We determine what to do based on the current state of the server
                     */
                    /*
                     * Pending is a bit of a special case. If we find the server is in a pending
                     * state, then the provider is in the process of changing state of the server.
                     * So, lets try to wait a little bit and see if the state settles down to one we
                     * can deal with. If not, then we have to fail the request.
                     */
                    if (server.getStatus().equals(Server.Status.PENDING)) {
                        waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
                                Server.Status.SUSPENDED, Server.Status.PAUSED, Server.Status.DELETED);
                    }
                    switch (server.getStatus()) {
                    case DELETED:
                        // Nothing to do, the server is gone
                        msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
                                server.getTenantId(), "stopped");
                        generateEvent(rc, false, msg);
                        logger.error(msg);
                        metricsLogger.error(msg);
                        throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
                    case RUNNING:
                        // Attempt to stop the server
                        rc.reset();
                        stopServer(rc, server);
                        generateEvent(rc, true, Outcome.SUCCESS.toString());
                        break;
                    case ERROR:
                        // Server is in error state
                        msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
                                server.getTenantId(), "stop");
                        generateEvent(rc, false, msg);
                        logger.error(msg);
                        metricsLogger.error(msg);
                        throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
                    case READY:
                        // Nothing to do, the server was already stopped
                        logger.info("Server was already stopped");
                        break;
                    case PAUSED:
                        // if paused, un-pause it and then stop it
                        rc.reset();
                        unpauseServer(rc, server);
                        rc.reset();
                        stopServer(rc, server);
                        generateEvent(rc, true, Outcome.SUCCESS.toString());
                        break;
                    case SUSPENDED:
                        // Attempt to resume the suspended server and after that stop it
                        rc.reset();
                        resumeServer(rc, server);
                        rc.reset();
                        stopServer(rc, server);
                        generateEvent(rc, true, Outcome.SUCCESS.toString());
                        break;
                    default:
                        // Hmmm, unknown status, should never occur
                        msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
                                server.getTenantId(), server.getStatus().name());
                        generateEvent(rc, false, msg);
                        logger.error(msg);
                        metricsLogger.error(msg);
                        throw new RequestFailedException("Stop Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
                    }
                    context.close();
                    doSuccess(rc);
                    ctx.setAttribute("STOP_STATUS", "SUCCESS");
                    msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "StopServer", vmUrl);
                    ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
                } else {
                    ctx.setAttribute("STOP_STATUS", "CONTEXT_NOT_FOUND");
                }
            } catch (ResourceNotFoundException e) {
                String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
                logger.error(msg);
                doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
            } catch (Exception e1) {
                String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1,
                        e1.getClass().getSimpleName(), STOP_SERVICE.toString(), vmUrl,
                        context == null ? "Unknown" : context.getTenantName());
                logger.error(msg, e1);
                doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
            }
        } catch (RequestFailedException e) {
            logger.error(EELFResourceManager.format(Msg.STOP_SERVER_FAILED, appName, "n/a", "n/a", e.getMessage()));
            doFailure(rc, e.getStatus(), e.getMessage());
        }
        return server;
    }

    @Override
    protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
            throws APPCException {
        setMDC(STOP_SERVICE.toString(), "App-C IaaS Adapter:Stop", ADAPTER_NAME);
        logOperation(Msg.STOPPING_SERVER, params, context);
        return stopServer(params, context);
    }

    private void setTimeForMetricsLogger() {
        String timestamp = LoggingUtils.generateTimestampStr((new Date()).toInstant());
        MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
        MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
        MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
        MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
        MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
        MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "stop server");
        MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, "org.onap.appc.adapter.iaas.provider.operation.impl.StopServer");
    }

}