001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     * 
010     *      http://www.apache.org/licenses/LICENSE-2.0
011     * 
012     * Unless required by applicable law or agreed to in writing, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    package org.apache.oozie.servlet;
019    
020    import java.io.IOException;
021    import java.util.Map;
022    import java.util.TimeZone;
023    
024    import javax.servlet.ServletException;
025    import javax.servlet.http.HttpServletRequest;
026    import javax.servlet.http.HttpServletResponse;
027    
028    import org.apache.oozie.BuildInfo;
029    import org.apache.oozie.client.rest.JsonTags;
030    import org.apache.oozie.client.rest.RestConstants;
031    import org.apache.oozie.service.AuthorizationException;
032    import org.apache.oozie.service.AuthorizationService;
033    import org.apache.oozie.service.InstrumentationService;
034    import org.apache.oozie.service.Services;
035    import org.apache.oozie.util.Instrumentation;
036    import org.json.simple.JSONArray;
037    import org.json.simple.JSONObject;
038    
039    public abstract class BaseAdminServlet extends JsonRestServlet {
040    
041        private static final long serialVersionUID = 1L;
042        protected String modeTag;
043    
044        public BaseAdminServlet(String instrumentationName, ResourceInfo[] RESOURCES_INFO) {
045            super(instrumentationName, RESOURCES_INFO);
046            setAllowSafeModeChanges(true);
047        }
048    
049        /**
050         * Change safemode state.
051         */
052        @Override
053        protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
054            String resourceName = getResourceName(request);
055            request.setAttribute(AUDIT_OPERATION, resourceName);
056            request.setAttribute(AUDIT_PARAM, request.getParameter(modeTag));
057    
058            try {
059                AuthorizationService auth = Services.get().get(AuthorizationService.class);
060                auth.authorizeForAdmin(getUser(request), true);
061            }
062            catch (AuthorizationException ex) {
063                throw new XServletException(HttpServletResponse.SC_UNAUTHORIZED, ex);
064            }
065    
066            setOozieMode(request, response, resourceName);
067            /*if (resourceName.equals(RestConstants.ADMIN_STATUS_RESOURCE)) {
068                boolean safeMode = Boolean.parseBoolean(request.getParameter(RestConstants.ADMIN_SAFE_MODE_PARAM));
069                Services.get().setSafeMode(safeMode);
070                response.setStatus(HttpServletResponse.SC_OK);
071            }
072            else {
073                throw new XServletException(HttpServletResponse.SC_BAD_REQUEST, ErrorCode.E0301, resourceName);
074            }*/
075        }
076    
077        /**
078         * Return safemode state, instrumentation, configuration, osEnv or
079         * javaSysProps
080         */
081        @Override
082        @SuppressWarnings("unchecked")
083        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
084            String resource = getResourceName(request);
085            Instrumentation instr = Services.get().get(InstrumentationService.class).get();
086    
087            if (resource.equals(RestConstants.ADMIN_STATUS_RESOURCE)) {
088                JSONObject json = new JSONObject();
089                populateOozieMode(json);
090                // json.put(JsonTags.SYSTEM_SAFE_MODE, getOozeMode());
091                sendJsonResponse(response, HttpServletResponse.SC_OK, json);
092            }
093            else if (resource.equals(RestConstants.ADMIN_OS_ENV_RESOURCE)) {
094                JSONObject json = new JSONObject();
095                json.putAll(instr.getOSEnv());
096                sendJsonResponse(response, HttpServletResponse.SC_OK, json);
097            }
098            else if (resource.equals(RestConstants.ADMIN_JAVA_SYS_PROPS_RESOURCE)) {
099                JSONObject json = new JSONObject();
100                json.putAll(instr.getJavaSystemProperties());
101                sendJsonResponse(response, HttpServletResponse.SC_OK, json);
102            }
103            else if (resource.equals(RestConstants.ADMIN_CONFIG_RESOURCE)) {
104                JSONObject json = new JSONObject();
105                json.putAll(instr.getConfiguration());
106                sendJsonResponse(response, HttpServletResponse.SC_OK, json);
107            }
108            else if (resource.equals(RestConstants.ADMIN_INSTRUMENTATION_RESOURCE)) {
109                sendJsonResponse(response, HttpServletResponse.SC_OK, instrToJson(instr));
110            }
111            else if (resource.equals(RestConstants.ADMIN_BUILD_VERSION_RESOURCE)) {
112                JSONObject json = new JSONObject();
113                json.put(JsonTags.BUILD_VERSION, BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_VERSION));
114                sendJsonResponse(response, HttpServletResponse.SC_OK, json);
115            }
116            else if (resource.equals(RestConstants.ADMIN_QUEUE_DUMP_RESOURCE)) {
117                JSONObject json = new JSONObject();
118                getQueueDump(json);
119                sendJsonResponse(response, HttpServletResponse.SC_OK, json);
120            }
121            else if (resource.equals(RestConstants.ADMIN_TIME_ZONES_RESOURCE)) {
122                JSONObject json = new JSONObject();
123                json.put(JsonTags.AVAILABLE_TIME_ZONES, availableTimeZonesToJsonArray());
124                sendJsonResponse(response, HttpServletResponse.SC_OK, json);
125            }
126        }
127    
128        @Override
129        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
130                IOException {
131        }
132    
133        @SuppressWarnings("unchecked")
134        private <T> JSONArray instrElementsToJson(Map<String, Map<String, Instrumentation.Element<T>>> instrElements) {
135            JSONArray array = new JSONArray();
136            for (Map.Entry<String, Map<String, Instrumentation.Element<T>>> group : instrElements.entrySet()) {
137                JSONObject json = new JSONObject();
138                String groupName = group.getKey();
139                json.put(JsonTags.INSTR_GROUP, groupName);
140                JSONArray dataArray = new JSONArray();
141                for (Map.Entry<String, Instrumentation.Element<T>> elementEntry : group.getValue().entrySet()) {
142                    String samplerName = elementEntry.getKey();
143                    JSONObject dataJson = new JSONObject();
144                    dataJson.put(JsonTags.INSTR_NAME, samplerName);
145                    Object value = elementEntry.getValue().getValue();
146                    if (value instanceof Instrumentation.Timer) {
147                        Instrumentation.Timer timer = (Instrumentation.Timer) value;
148                        dataJson.put(JsonTags.INSTR_TIMER_TICKS, timer.getTicks());
149                        dataJson.put(JsonTags.INSTR_TIMER_OWN_TIME_AVG, timer.getOwnAvg());
150                        dataJson.put(JsonTags.INSTR_TIMER_TOTAL_TIME_AVG, timer.getTotalAvg());
151                        dataJson.put(JsonTags.INSTR_TIMER_OWN_STD_DEV, timer.getOwnStdDev());
152                        dataJson.put(JsonTags.INSTR_TIMER_TOTAL_STD_DEV, timer.getTotalStdDev());
153                        dataJson.put(JsonTags.INSTR_TIMER_OWN_MIN_TIME, timer.getOwnMin());
154                        dataJson.put(JsonTags.INSTR_TIMER_OWN_MAX_TIME, timer.getOwnMax());
155                        dataJson.put(JsonTags.INSTR_TIMER_TOTAL_MIN_TIME, timer.getTotalMin());
156                        dataJson.put(JsonTags.INSTR_TIMER_TOTAL_MAX_TIME, timer.getTotalMax());
157                    }
158                    else {
159                        dataJson.put(JsonTags.INSTR_VARIABLE_VALUE, value);
160                    }
161                    dataArray.add(dataJson);
162                }
163                json.put(JsonTags.INSTR_DATA, dataArray);
164                array.add(json);
165            }
166            return array;
167        }
168    
169        @SuppressWarnings("unchecked")
170        private JSONObject instrToJson(Instrumentation instr) {
171            JSONObject json = new JSONObject();
172            json.put(JsonTags.INSTR_VARIABLES, instrElementsToJson(instr.getVariables()));
173            json.put(JsonTags.INSTR_SAMPLERS, instrElementsToJson(instr.getSamplers()));
174            json.put(JsonTags.INSTR_COUNTERS, instrElementsToJson(instr.getCounters()));
175            json.put(JsonTags.INSTR_TIMERS, instrElementsToJson(instr.getTimers()));
176            return json;
177        }
178    
179        protected abstract void populateOozieMode(JSONObject json);
180    
181        protected abstract void setOozieMode(HttpServletRequest request, HttpServletResponse response, String resourceName)
182                throws XServletException;
183    
184        protected abstract void getQueueDump(JSONObject json) throws XServletException;
185        
186        private static final JSONArray GMTOffsetTimeZones = new JSONArray();
187        static {
188            prepareGMTOffsetTimeZones();
189        }
190    
191        @SuppressWarnings({"unchecked", "rawtypes"})
192        private static void prepareGMTOffsetTimeZones() {
193            for (String tzId : new String[]{"GMT-12:00", "GMT-11:00", "GMT-10:00", "GMT-09:00", "GMT-08:00", "GMT-07:00", "GMT-06:00",
194                                            "GMT-05:00", "GMT-04:00", "GMT-03:00", "GMT-02:00", "GMT-01:00", "GMT+01:00", "GMT+02:00",
195                                            "GMT+03:00", "GMT+04:00", "GMT+05:00", "GMT+06:00", "GMT+07:00", "GMT+08:00", "GMT+09:00",
196                                            "GMT+10:00", "GMT+11:00", "GMT+12:00"}) {
197                TimeZone tz = TimeZone.getTimeZone(tzId);
198                JSONObject json = new JSONObject();
199                json.put(JsonTags.TIME_ZOME_DISPLAY_NAME, tz.getDisplayName(false, TimeZone.SHORT) + " (" + tzId + ")");
200                json.put(JsonTags.TIME_ZONE_ID, tzId);
201                GMTOffsetTimeZones.add(json);
202            }
203        }
204    
205        @SuppressWarnings({"unchecked", "rawtypes"})
206        private JSONArray availableTimeZonesToJsonArray() {
207            JSONArray array = new JSONArray();
208            for (String tzId : TimeZone.getAvailableIDs()) {
209                // skip id's that are like "Etc/GMT+01:00" because their display names are like "GMT-01:00", which is confusing
210                if (!tzId.startsWith("Etc/GMT")) {
211                    JSONObject json = new JSONObject();
212                    TimeZone tZone = TimeZone.getTimeZone(tzId);
213                    json.put(JsonTags.TIME_ZOME_DISPLAY_NAME, tZone.getDisplayName(false, TimeZone.SHORT) + " (" + tzId + ")");
214                    json.put(JsonTags.TIME_ZONE_ID, tzId);
215                    array.add(json);
216                }
217            }
218    
219            // The combo box this populates cannot be edited, so the user can't type in GMT offsets (like in the CLI), so we'll add
220            // in some hourly offsets here (though the user will not be able to use other offsets without editing the cookie manually
221            // and they are not in order)
222            array.addAll(GMTOffsetTimeZones);
223    
224            return array;
225        }
226    
227    }