Second part of onap rename
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / RestartServer.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.onap.appc.adapter.iaas.provider.operation.impl;
26
27 import com.att.cdp.exceptions.ResourceNotFoundException;
28 import com.att.cdp.exceptions.ZoneException;
29 import com.att.cdp.zones.Context;
30 import com.att.cdp.zones.model.ModelObject;
31 import com.att.cdp.zones.model.Server;
32 import com.att.eelf.configuration.EELFLogger;
33 import com.att.eelf.configuration.EELFManager;
34 import com.att.eelf.i18n.EELFResourceManager;
35 import org.glassfish.grizzly.http.util.HttpStatus;
36 import org.onap.appc.Constants;
37 import org.onap.appc.adapter.iaas.ProviderAdapter;
38 import org.onap.appc.adapter.iaas.impl.IdentityURL;
39 import org.onap.appc.adapter.iaas.impl.RequestContext;
40 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
41 import org.onap.appc.adapter.iaas.impl.VMURL;
42 import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property;
43 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome;
44 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
45 import org.onap.appc.exceptions.UnknownProviderException;
46 import org.onap.appc.i18n.Msg;
47 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
48 import org.slf4j.MDC;
49 import java.text.DateFormat;
50 import java.text.SimpleDateFormat;
51 import java.util.Date;
52 import java.util.Map;
53 import java.util.TimeZone;
54 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.RESTART_SERVICE;
55 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
56
57 public class RestartServer extends ProviderServerOperation {
58
59     private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestartServer.class);
60     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
61
62
63     /**
64      * This method handles the case of restarting a server once we have found the server and have obtained the abstract
65      * representation of the server via the context (i.e., the "Server" object from the CDP-Zones abstraction).
66      *
67      * @param rc The request context that manages the state and recovery of the request for the life of its processing.
68      * @param server The server object representing the server we want to operate on
69      * @throws ZoneException when error occurs.
70      * @throws RequestFailedException when server status is error.
71      */
72     @SuppressWarnings("nls")
73     private void restartServer(RequestContext rc, Server server, SvcLogicContext ctx)
74             throws ZoneException, RequestFailedException {
75         /*
76          * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
77          * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
78          * to one we can deal with. If not, then we have to fail the request.
79          */
80         String msg;
81         if (server.getStatus().equals(Server.Status.PENDING)) {
82             waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
83                     Server.Status.SUSPENDED, Server.Status.PAUSED);
84         }
85
86         setTimeForMetricsLogger("restart server");
87
88         String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
89         if (skipHypervisorCheck == null && ctx != null) {
90             skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
91         }
92
93         // Always perform Virtual Machine/Hypervisor Status/Network checks
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
100         /*
101          * We determine what to do based on the current state of the server
102          */
103         switch (server.getStatus()) {
104             case DELETED:
105                 // Nothing to do, the server is gone
106                 msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
107                         server.getTenantId(), "restarted");
108                 generateEvent(rc, false, msg);
109                 logger.error(msg);
110                 metricsLogger.error(msg);
111                 break;
112
113             case RUNNING:
114                 // Attempt to stop and start the server
115                 stopServer(rc, server);
116                 startServer(rc, server);
117                 generateEvent(rc, true, Outcome.SUCCESS.toString());
118                 metricsLogger.info("Server status: RUNNING");
119                 break;
120
121             case ERROR:
122                 msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
123                         server.getTenantId(), "rebuild");
124                 generateEvent(rc, false, msg);
125                 logger.error(msg);
126                 metricsLogger.error(msg);
127                 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
128
129             case READY:
130                 // Attempt to start the server
131                 startServer(rc, server);
132                 generateEvent(rc, true, Outcome.SUCCESS.toString());
133                 metricsLogger.info("Server status: READY");
134                 break;
135
136             case PAUSED:
137                 // if paused, un-pause it
138                 unpauseServer(rc, server);
139                 generateEvent(rc, true, Outcome.SUCCESS.toString());
140                 metricsLogger.info("Server status: PAUSED");
141                 break;
142
143             case SUSPENDED:
144                 // Attempt to resume the suspended server
145                 resumeServer(rc, server);
146                 generateEvent(rc, true, Outcome.SUCCESS.toString());
147                 metricsLogger.info("Server status: SUSPENDED");
148                 break;
149
150             default:
151                 // Hmmm, unknown status, should never occur
152                 msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
153                         server.getTenantId(), server.getStatus().name());
154                 generateEvent(rc, false, msg);
155                 logger.error(msg);
156                 metricsLogger.error(msg);
157                 break;
158         }
159
160
161     }
162
163     /**
164      * This method is used to restart an existing virtual machine given the fully qualified URL of the machine.
165      * <p>
166      * The fully qualified URL contains enough information to locate the appropriate server. The URL is of the form
167      * 
168      * <pre>
169      *  [scheme]://[host[:port]] / [path] / [tenant_id] / servers / [vm_id]
170      * </pre>
171      * 
172      * Where the various parts of the URL can be parsed and extracted and used to locate the appropriate service in the
173      * provider service catalog. This then allows us to open a context using the CDP abstraction, obtain the server by
174      * its UUID, and then perform the restart.
175      * </p>
176      *
177      * @throws UnknownProviderException If the provider cannot be found
178      * @throws IllegalArgumentException if the expected argument(s) are not defined or are invalid
179      * @see org.onap.appc.adapter.iaas.ProviderAdapter#restartServer(java.util.Map,
180      *      org.openecomp.sdnc.sli.SvcLogicContext)
181      */
182     @SuppressWarnings("nls")
183     private Server restartServer(Map<String, String> params, SvcLogicContext ctx)
184             throws UnknownProviderException, IllegalArgumentException {
185         Server server = null;
186         RequestContext rc = new RequestContext(ctx);
187         rc.isAlive();
188
189         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
190
191         /*
192          * Set Time for Metrics Logger
193          */
194         setTimeForMetricsLogger("GET server status");
195
196         ctx.setAttribute("RESTART_STATUS", "ERROR");
197         try {
198             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
199                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
200
201             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
202
203             VMURL vm = VMURL.parseURL(vm_url);
204             if (validateVM(rc, appName, vm_url, vm))
205                 return null;
206
207             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
208             String identStr = (ident == null) ? null : ident.toString();
209
210             Context context = null;
211             try {
212                 context = getContext(rc, vm_url, identStr);
213                 if (context != null) {
214                     rc.reset();
215                     server = lookupServer(rc, context, vm.getServerId());
216                     logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
217                     rc.reset();
218                     restartServer(rc, server, ctx);
219                     context.close();
220                     doSuccess(rc);
221                     ctx.setAttribute("RESTART_STATUS", "SUCCESS");
222                     String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "RestartServer", vm_url);
223                     ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
224                 }
225             } catch (RequestFailedException e) {
226                 doFailure(rc, e.getStatus(), e.getMessage());
227             } catch (ResourceNotFoundException e) {
228                 String msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
229                 logger.error(msg);
230                 metricsLogger.error(msg);
231                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
232             } catch (Exception e1) {
233                 String msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1,
234                         e1.getClass().getSimpleName(), RESTART_SERVICE.toString(), vm_url,
235                         context == null ? "Unknown" : context.getTenantName());
236                 logger.error(msg, e1);
237                 metricsLogger.error(msg, e1);
238                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
239             }
240         } catch (RequestFailedException e) {
241             doFailure(rc, e.getStatus(), e.getMessage());
242         }
243
244         return server;
245     }
246
247     @Override
248     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
249             throws UnknownProviderException {
250         setMDC(RESTART_SERVICE.toString(), "App-C IaaS Adapter:Restart", ADAPTER_NAME);
251         logOperation(Msg.RESTARTING_SERVER, params, context);
252
253         setTimeForMetricsLogger("execute restart");
254
255         metricsLogger.info("Executing Provider Operation: Restart");
256
257         return restartServer(params, context);
258     }
259
260     private void setTimeForMetricsLogger(String targetServiceName) {
261         long startTime = System.currentTimeMillis();
262         TimeZone tz = TimeZone.getTimeZone("UTC");
263         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
264         df.setTimeZone(tz);
265         long endTime = System.currentTimeMillis();
266         long duration = endTime - startTime;
267         String durationStr = String.valueOf(duration);
268         String endTimeStrUTC = df.format(new Date());
269         MDC.put("EndTimestamp", endTimeStrUTC);
270         MDC.put("ElapsedTime", durationStr);
271         MDC.put("TargetEntity", "cdp");
272         MDC.put("TargetServiceName", targetServiceName);
273         MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.RestartServer");
274     }
275 }