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
019package org.apache.oozie.sla.service;
020
021import java.util.Date;
022import java.util.List;
023import java.util.Map;
024
025import org.apache.hadoop.conf.Configuration;
026import org.apache.oozie.ErrorCode;
027import org.apache.oozie.client.event.JobEvent.EventStatus;
028import org.apache.oozie.executor.jpa.JPAExecutorException;
029import org.apache.oozie.service.ConfigurationService;
030import org.apache.oozie.service.EventHandlerService;
031import org.apache.oozie.service.SchedulerService;
032import org.apache.oozie.service.Service;
033import org.apache.oozie.service.ServiceException;
034import org.apache.oozie.service.Services;
035import org.apache.oozie.sla.SLACalculator;
036import org.apache.oozie.sla.SLACalculatorMemory;
037import org.apache.oozie.sla.SLARegistrationBean;
038import org.apache.oozie.util.Pair;
039import org.apache.oozie.util.XLog;
040
041import com.google.common.annotations.VisibleForTesting;
042
043public class SLAService implements Service {
044
045    public static final String CONF_PREFIX = "oozie.sla.service.SLAService.";
046    public static final String CONF_CALCULATOR_IMPL = CONF_PREFIX + "calculator.impl";
047    public static final String CONF_CAPACITY = CONF_PREFIX + "capacity";
048    public static final String CONF_ALERT_EVENTS = CONF_PREFIX + "alert.events";
049    public static final String CONF_EVENTS_MODIFIED_AFTER = CONF_PREFIX + "events.modified.after";
050    public static final String CONF_JOB_EVENT_LATENCY = CONF_PREFIX + "job.event.latency";
051    //Time interval, in seconds, at which SLA Worker will be scheduled to run
052    public static final String CONF_SLA_CHECK_INTERVAL = CONF_PREFIX + "check.interval";
053    public static final String CONF_SLA_CHECK_INITIAL_DELAY = CONF_PREFIX + "check.initial.delay";
054    public static final String CONF_SLA_CALC_LOCK_TIMEOUT = CONF_PREFIX + "oozie.sla.calc.default.lock.timeout";
055    public static final String CONF_SLA_HISTORY_PURGE_INTERVAL = CONF_PREFIX + "history.purge.interval";
056    public static final String CONF_MAXIMUM_RETRY_COUNT = CONF_PREFIX + "maximum.retry.count";
057
058    private static SLACalculator calcImpl;
059    private static boolean slaEnabled = false;
060    private EventHandlerService eventHandler;
061    public static XLog LOG;
062    @Override
063    public void init(Services services) throws ServiceException {
064        try {
065            Configuration conf = services.getConf();
066            Class<? extends SLACalculator> calcClazz = (Class<? extends SLACalculator>) ConfigurationService.getClass(
067                    conf, CONF_CALCULATOR_IMPL);
068            calcImpl = calcClazz == null ? new SLACalculatorMemory() : (SLACalculator) calcClazz.newInstance();
069            calcImpl.init(conf);
070            eventHandler = Services.get().get(EventHandlerService.class);
071            if (eventHandler == null) {
072                throw new ServiceException(ErrorCode.E0103, "EventHandlerService", "Add it under config "
073                        + Services.CONF_SERVICE_EXT_CLASSES + " or declare it BEFORE SLAService");
074            }
075            LOG = XLog.getLog(getClass());
076            java.util.Set<String> appTypes = eventHandler.getAppTypes();
077            appTypes.add("workflow_action");
078            eventHandler.setAppTypes(appTypes);
079
080            Runnable slaThread = new SLAWorker(calcImpl);
081            // schedule runnable by default every 30 sec
082            int slaCheckInterval = ConfigurationService.getInt(conf, CONF_SLA_CHECK_INTERVAL);
083            int slaCheckInitialDelay = ConfigurationService.getInt(conf, CONF_SLA_CHECK_INITIAL_DELAY);
084            services.get(SchedulerService.class).schedule(slaThread, slaCheckInitialDelay, slaCheckInterval,
085                    SchedulerService.Unit.SEC);
086            slaEnabled = true;
087            LOG.info("SLAService initialized with impl [{0}] capacity [{1}]", calcImpl.getClass().getName(),
088                    conf.get(SLAService.CONF_CAPACITY));
089        }
090        catch (Exception ex) {
091            throw new ServiceException(ErrorCode.E0102, ex.getMessage(), ex);
092        }
093    }
094
095    @Override
096    public void destroy() {
097        slaEnabled = false;
098    }
099
100    @Override
101    public Class<? extends Service> getInterface() {
102        return SLAService.class;
103    }
104
105    public static boolean isEnabled() {
106        return slaEnabled;
107    }
108
109    @VisibleForTesting
110    public SLACalculator getSLACalculator() {
111        return calcImpl;
112    }
113
114    public void runSLAWorker() {
115        new SLAWorker(calcImpl).run();
116    }
117
118    @VisibleForTesting
119    public void startSLAWorker() {
120        new Thread(new SLAWorker(calcImpl)).start();
121    }
122
123    private class SLAWorker implements Runnable {
124
125        SLACalculator calc;
126
127        public SLAWorker(SLACalculator calc) {
128            this.calc = calc;
129        }
130
131        @Override
132        public void run() {
133            if (Thread.currentThread().isInterrupted()) {
134                return;
135            }
136            try {
137                calc.updateAllSlaStatus();
138            }
139            catch (Throwable error) {
140                XLog.getLog(SLAService.class).debug("Throwable in SLAWorker thread run : ", error);
141            }
142        }
143    }
144
145    public boolean addRegistrationEvent(SLARegistrationBean reg) throws ServiceException {
146        try {
147            if (calcImpl.addRegistration(reg.getId(), reg)) {
148                return true;
149            }
150            else {
151                LOG.warn("SLA queue full. Unable to add new SLA entry for job [{0}]", reg.getId());
152            }
153        }
154        catch (JPAExecutorException ex) {
155            LOG.warn("Could not add new SLA entry for job [{0}]", reg.getId(), ex);
156        }
157        return false;
158    }
159
160    public boolean updateRegistrationEvent(SLARegistrationBean reg) throws ServiceException {
161        try {
162            if (calcImpl.updateRegistration(reg.getId(), reg)) {
163                return true;
164            }
165            else {
166                LOG.warn("SLA queue full. Unable to update the SLA entry for job [{0}]", reg.getId());
167            }
168        }
169        catch (JPAExecutorException ex) {
170            LOG.warn("Could not update SLA entry for job [{0}]", reg.getId(), ex);
171        }
172        return false;
173    }
174
175    public boolean addStatusEvent(String jobId, String status, EventStatus eventStatus, Date startTime, Date endTime)
176            throws ServiceException {
177        try {
178            if (calcImpl.addJobStatus(jobId, status, eventStatus, startTime, endTime)) {
179                return true;
180            }
181        }
182        catch (JPAExecutorException jpe) {
183            LOG.error("Exception while adding SLA Status event for Job [{0}]", jobId);
184        }
185        return false;
186    }
187
188    public void removeRegistration(String jobId) {
189        calcImpl.removeRegistration(jobId);
190    }
191
192    /**
193     * Enable jobs sla alert.
194     *
195     * @param jobIds the job ids
196     * @return true, if successful
197     * @throws ServiceException the service exception
198     */
199    public boolean enableAlert(List<String> jobIds) throws ServiceException {
200        try {
201            return calcImpl.enableAlert(jobIds);
202        }
203        catch (JPAExecutorException jpe) {
204            LOG.error("Exception while updating SLA alerting for Job [{0}]", jobIds.get(0));
205            throw new ServiceException(jpe);
206        }
207    }
208
209    /**
210     * Enable child jobs sla alert.
211     *
212     * @param parentJobIds the parent job ids
213     * @return true, if successful
214     * @throws ServiceException the service exception
215     */
216    public boolean enableChildJobAlert(List<String> parentJobIds) throws ServiceException {
217        try {
218            return calcImpl.enableChildJobAlert(parentJobIds);
219        }
220        catch (JPAExecutorException jpe) {
221            LOG.error("Exception while updating SLA alerting for Job [{0}]", parentJobIds.get(0));
222            throw new ServiceException(jpe);
223        }
224    }
225
226    /**
227     * Disable jobs Sla alert.
228     *
229     * @param jobIds the job ids
230     * @return true, if successful
231     * @throws ServiceException the service exception
232     */
233    public boolean disableAlert(List<String> jobIds) throws ServiceException {
234        try {
235            return calcImpl.disableAlert(jobIds);
236        }
237        catch (JPAExecutorException jpe) {
238            LOG.error("Exception while updating SLA alerting for Job [{0}]", jobIds.get(0));
239            throw new ServiceException(jpe);
240        }
241    }
242
243    /**
244     * Disable child jobs Sla alert.
245     *
246     * @param parentJobIds the parent job ids
247     * @return true, if successful
248     * @throws ServiceException the service exception
249     */
250    public boolean disableChildJobAlert(List<String> parentJobIds) throws ServiceException {
251        try {
252            return calcImpl.disableChildJobAlert(parentJobIds);
253        }
254        catch (JPAExecutorException jpe) {
255            LOG.error("Exception while updating SLA alerting for Job [{0}]", parentJobIds.get(0));
256            throw new ServiceException(jpe);
257        }
258    }
259
260    /**
261     * Change jobs Sla definitions
262     * It takes list of pairs of jobid and key/value pairs of el evaluated sla definition.
263     * Support definition are sla-should-start, sla-should-end, sla-nominal-time and sla-max-duration.
264     *
265     * @param idSlaDefinitionList the job ids sla pair
266     * @return true, if successful
267     * @throws ServiceException the service exception
268     */
269    public boolean changeDefinition(List<Pair<String, Map<String, String>>> idSlaDefinitionList)
270            throws ServiceException {
271        try {
272            return calcImpl.changeDefinition(idSlaDefinitionList);
273        }
274        catch (JPAExecutorException jpe) {
275            throw new ServiceException(jpe);
276        }
277    }
278}