001/*
002 * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Julien Carsique
018 *
019 */
020
021package org.nuxeo.ecm.core.management.statuses;
022
023import java.io.IOException;
024import java.io.OutputStream;
025
026import javax.servlet.ServletException;
027import javax.servlet.http.HttpServlet;
028import javax.servlet.http.HttpServletRequest;
029import javax.servlet.http.HttpServletResponse;
030
031import org.apache.commons.lang3.StringUtils;
032import org.apache.commons.logging.Log;
033import org.apache.commons.logging.LogFactory;
034import org.nuxeo.common.Environment;
035import org.nuxeo.ecm.core.management.api.ProbeManager;
036import org.nuxeo.runtime.AbstractRuntimeService;
037import org.nuxeo.runtime.RuntimeService;
038import org.nuxeo.runtime.api.Framework;
039
040/**
041 * Servlet for retrieving Nuxeo services running status.
042 * 
043 * @since 9.3 this servlet returns a status based of all the probes registered for the healthCheck.
044 */
045public class StatusServlet extends HttpServlet {
046
047    private static final long serialVersionUID = 1L;
048
049    private static final Log log = LogFactory.getLog(StatusServlet.class);
050
051    public static final String PARAM = "info";
052
053    public static final String PARAM_STARTED = "started";
054
055    public static final String PARAM_SUMMARY = "summary";
056
057    public static final String PARAM_SUMMARY_KEY = "key";
058
059    public static final String PARAM_RELOAD = "reload";
060
061    public static final String PROBE_PARAM = "probe";
062
063    private AbstractRuntimeService runtimeService;
064
065    protected ProbeManager pm;
066
067    @Override
068    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
069        String param = req.getParameter(PARAM);
070        if (param != null) {
071            doPost(req, resp);
072        } else {
073            HealthCheckResult result = getOrRunHealthCheck(null);
074            sendHealthCheckResponse(resp, result);
075        }
076    }
077
078    protected void sendHealthCheckResponse(HttpServletResponse resp, HealthCheckResult result) throws IOException {
079        if (result.healthy) {
080            resp.setStatus(HttpServletResponse.SC_OK);
081        } else {
082            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
083        }
084        sendResponse(resp, result.toJson());
085    }
086
087    @Override
088    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
089        StringBuilder response = new StringBuilder();
090        String requestedInfo = req.getParameter(PARAM);
091        if (requestedInfo.equals(PARAM_STARTED)) {
092            getStartedInfo(response);
093        } else if (requestedInfo.equals(PARAM_SUMMARY)) {
094            String givenKey = req.getParameter(PARAM_SUMMARY_KEY);
095            if (getRuntimeService().getProperty(Environment.SERVER_STATUS_KEY).equals(givenKey)) {
096                getSummaryInfo(response);
097            } else {
098                resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
099            }
100        } else if (requestedInfo.equals(PARAM_RELOAD)) {
101            if (isStarted()) {
102                response.append("reload();");
103            } else {
104                resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
105            }
106        } else if (requestedInfo.equals(PROBE_PARAM)) {
107            String probetoEval = req.getParameter(PARAM_SUMMARY_KEY);
108            try {
109                HealthCheckResult result = getOrRunHealthCheck(probetoEval);
110                sendHealthCheckResponse(resp, result);
111            } catch (IllegalArgumentException e) {
112                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
113            }
114        }
115        sendResponse(resp, response.toString());
116    }
117
118    protected void sendResponse(HttpServletResponse resp, String response) throws IOException {
119        resp.setContentType("application/json");
120        resp.setContentLength(response.getBytes().length);
121        OutputStream out = resp.getOutputStream();
122        out.write(response.getBytes());
123        out.close();
124    }
125
126    private RuntimeService getRuntimeService() {
127        if (runtimeService == null) {
128            runtimeService = (AbstractRuntimeService) Framework.getRuntime();
129        }
130        return runtimeService;
131    }
132
133    protected void getSummaryInfo(StringBuilder response) {
134        if (isStarted()) {
135            StringBuilder msg = new StringBuilder();
136            boolean isFine = runtimeService.getStatusMessage(msg);
137            response.append(isFine).append("\n");
138            response.append(msg);
139        } else {
140            response.append(false).append("\n");
141            response.append("Runtime failed to start");
142        }
143    }
144
145    protected void getStartedInfo(StringBuilder response) {
146        response.append(isStarted()).toString();
147    }
148
149    private boolean isStarted() {
150        return getRuntimeService() != null && runtimeService.isStarted();
151    }
152
153    @Override
154    public void init() throws ServletException {
155        log.debug("Ready.");
156    }
157
158    protected HealthCheckResult getOrRunHealthCheck(String probe) {
159        ProbeManager pm = Framework.getService(ProbeManager.class);
160        if (StringUtils.isEmpty(probe)) { // run all healthCheck probes
161            return pm.getOrRunHealthChecks();
162        } else {
163            return pm.getOrRunHealthCheck(probe);
164        }
165    }
166}