Package com.ericsson.ssa.container.overload

Source Code of com.ericsson.ssa.container.overload.OverloadSampler

/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
* Copyright (c) Ericsson AB, 2004-2008. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License").  You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code.  If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license."  If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above.  However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.ericsson.ssa.container.overload;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.glassfish.comms.api.overload.OverloadDetectionRegistrar;
import org.glassfish.comms.api.overload.OverloadDetector;
import org.glassfish.comms.api.overload.OverloadEvent;
import org.glassfish.comms.api.overload.OverloadListener;
import org.glassfish.comms.api.overload.OverloadNotifier;
import org.glassfish.comms.api.overload.OverloadService;
import org.glassfish.comms.api.overload.OverloadEvent.TrafficType;
import org.jvnet.glassfish.comms.util.LogUtil;

import com.ericsson.ssa.config.annotations.Configuration;
import com.ericsson.ssa.sip.timer.GeneralTimer;
import com.ericsson.ssa.sip.timer.GeneralTimerListener;
import com.ericsson.ssa.sip.timer.TimerServiceImpl;

public class OverloadSampler implements GeneralTimerListener, OverloadNotifier,
    OverloadDetectionRegistrar, OverloadListener, OverloadService {
  private static final Logger LOGGER = LogUtil.SIP_LOGGER.getLogger();
  private static final double RETRY_AFTER_FACTOR = 0.1;
  private List<OverloadListener> activeListeners = new ArrayList<OverloadListener>();
  volatile private List<OverloadDetector> activeDetectors = new ArrayList<OverloadDetector>();
  protected final OverloadConfiguration config;
  private GeneralTimer _timer = null;
  private OverloadDetectorFactory detectorFactory;

  //
  // Configured variables
  //
  /**
   * Default sample rate in seconds.
   */
  private static final int DEFAULT_SAMPLE_RATE = 2; // 2 seconds

  /**
   * Default number of samples the threshold is exceeded before concluding
   * overload.
   */
  private static final int DEFAULT_NR_OF_SAMPLES = 5; // 5 samples
  private static final int DEFAULT_RETRY_AFTER_INTERVAL = 10; // 10 seconds

  private int _sampleRate = DEFAULT_SAMPLE_RATE;
  private int _numberOfSamples = DEFAULT_NR_OF_SAMPLES;
  private int _retryAfterInterval = DEFAULT_RETRY_AFTER_INTERVAL;
        private static final int DEFAULT_MM_HTTP_THRESHOLD_WAIT_TIME = 1;
        private int _mmHttpThresholdWaitTime = DEFAULT_MM_HTTP_THRESHOLD_WAIT_TIME;

  public OverloadSampler(OverloadConfiguration config) {
    this.config = config;
    detectorFactory = new OverloadDetectorFactory(config, this);
  }
 
  public synchronized void start() {
    config.activate(this);
   
    // start the factory
    getOverloadDetectorFactory().start();

    // start timer
    startTimer();
  }

  protected OverloadDetectorFactory getOverloadDetectorFactory() {
    return detectorFactory;
  }
 
  public synchronized void stop() {
    config.deactivate(this);
   
    // stop the factory
    getOverloadDetectorFactory().stop();

    // stop timer ...
    stopTimer();

    // ... and remove all detectors and listeners
    removeAllDetectorsAndListeners();
  }

  private void removeAllDetectorsAndListeners() {
    Iterator<OverloadDetector> iter = activeDetectors.iterator();
    while (iter.hasNext()) {
      deactivateDetector(iter.next());
    }
    activeListeners.clear();
  }

  public void addListener(OverloadListener ol) {
    activeListeners.add(ol);
  }

  public void removeListener(OverloadListener ol) {
    activeListeners.remove(ol);
  }

  // FIXME should be invoked in new Thread to not be blocked by listener
  public void raiseOverload(OverloadEvent e) {
    for (OverloadListener ol : activeListeners) {
      ol.raiseOverload(e);
    }
  }

  // FIXME should be invoked in new Thread to not be blocked by listener
  public void ceaseOverload(OverloadEvent e) {
    for (OverloadListener ol : activeListeners) {
      ol.ceaseOverload(e);
    }
  }

  public void addDetector(OverloadDetector od) {
    if (od != null) {
      OverloadDetector activatedOd = get(od.type());
      if (activatedOd == null) {
        activeDetectors.add(od);
        od.addListener(this);
      }
    }
  }

  public void removeDetector(OverloadDetector od) {
    if (od != null) {
      OverloadDetector activatedOd = get(od.type());
      deactivateDetector(activatedOd);
    }
  }

  private void deactivateDetector(OverloadDetector od) {
    if (od != null) {
      // inform all listeners that the detector
      // is removed by ceasing all its event
      od.removeListener(this);
      activeDetectors.remove(od);
    }
  }

  private OverloadDetector get(String type) {
    for (OverloadDetector od : activeDetectors) {
      if (od.type().equalsIgnoreCase(type)) {
        return od;
      }
    }
    return null;
  }

  /**
   * ensure that the timer is started
   */
  private synchronized void startTimer() {
    try {
      if (LOGGER.isLoggable(Level.FINEST)) {
        LOGGER.log(Level.FINEST,
            "Starting timer for OverloadProtection functionality, SampleRate: "
                + _sampleRate + " * 1000");
      }

      _timer = TimerServiceImpl.getInstance().createTimer(this,
          _sampleRate * 1000, _sampleRate * 1000, true, null);
    } catch (Exception e) {
      LOGGER.log(Level.SEVERE, OverloadSampler.class.getCanonicalName()
          + ".could_not_start_timer");
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
  }

  /**
   * ensure that the timer is stopped
   */
  private synchronized void stopTimer() {
    if (_timer != null) {
      if (LOGGER.isLoggable(Level.FINEST)) {
        LOGGER.log(Level.FINEST,
            "Stopping timer for OverloadProtection functionality");
      }

      _timer.cancel();
      _timer = null;
    }
  }

  public void timeout(GeneralTimer timer) {
    int sampleRate = getSampleRate();
    int numberOfSamples = getNumberOfSamples();
    for (OverloadDetector od : activeDetectors) {
      od.timeout(sampleRate, numberOfSamples);
    }
  }

  public int retryAfter(TrafficType trafficType) {
    // special interpretation of negative retryAfter; these do not depend
    // on the number of intervals that the threshold was exceeded
    // just return the value
    if (getRetryAfterInterval() <= 0) {
      return -getRetryAfterInterval();
    }

    int max = 0;
    for (OverloadDetector od : activeDetectors) {
      if (od.retryAfter(trafficType) > max) {
        max = od.retryAfter(trafficType);
      }
    }

    return retryAfter(max);
  }

  /**
   * Returns 0 if max is less than getNumberOfSamples(). Returns
   * getRetryAfterInterval() if max is equal to getNumberOfSamples() otherwise
   * if max is bigger than getRetryAfterInterval() an additional % fraction
   * (RETRY_AFTER_FACTOR) is added to getRetryAfterInterval() and returned.
   *
   * @param max
   * @return
   */
  private int retryAfter(int max) {
    return max >= getNumberOfSamples() ? (int) Math
        .ceil((double) ((1 - RETRY_AFTER_FACTOR) + RETRY_AFTER_FACTOR
            * max / getNumberOfSamples())
            * getRetryAfterInterval()) : 0;
  }

  //
  // General Sampler Configuration
  //

  /**
   * FIXME is this method needed for e.g Mbeans
   *
   * Returns the sample frequency in seconds of monitoring the overload
   * protection levels.
   *
   * @return the sample frequency in seconds of monitoring the overload
   *         protection levels.
   */
  public Integer getSampleRate() {
    if (LOGGER.isLoggable(Level.FINER)) {
      LOGGER.log(Level.FINER, "SampleRate: " + _sampleRate);
    }

    return _sampleRate;
  }

  /**
   * Sets the sample frequency in seconds of monitoring the overload
   * protection thresholds. Must be a positive value.
   *
   * @param rate
   *            sample frequency in seconds
   */
  @Configuration(key = "SampleRate", node = "/SipContainer")
  public void setSampleRate(final Integer rate) {
    if (LOGGER.isLoggable(Level.INFO)) {
      LOGGER.log(Level.INFO, "SampleRate value will be set to "
          + rate.intValue());
    }

    if (rate > 0) {
      _sampleRate = rate;
    }
  }
       
        @Configuration(key = "SampleRate", node = "/OverloadProtectionService")
  public void setOlpServiceSampleRate(final Integer rate) {
            setSampleRate(rate);
        }
 
  /**
   * FIXME is this method needed for e.g Mbeans
   *
   * Returns the number of samples that are required before overload is raised
   * or ceased.
   *
   * @return the number of samples that are required before overload is raised
   *         or ceased.
   */
  public Integer getNumberOfSamples() {
    if (LOGGER.isLoggable(Level.FINER)) {
      LOGGER.log(Level.FINER, "NumberOfSamples: " + _numberOfSamples);
    }

    return _numberOfSamples;
  }

  /**
   * Sets the number of samples that are required before overload is raised or
   * ceased.
   *
   * @param samples
   *            the number of samples
   */
  @Configuration(key = "NumberOfSamples", node = "/SipContainer")
  public void setNumberOfSamples(final Integer samples) {
    if (LOGGER.isLoggable(Level.INFO)) {
      LOGGER.log(Level.INFO, "NumberOfSamples value will be set to "
          + samples.intValue());
    }

    _numberOfSamples = (samples < 2) ? 2 : samples;
  }
       
        @Configuration(key = "NumberOfSamples", node = "/OverloadProtectionService")
  public void setOlpServiceNumberOfSamples(final Integer samples) {
            setNumberOfSamples(samples);
        }
  /**
   * The retry-after value returned in a 503 response is this value with an
   * extra offset depending on the number of consecutive periods the threshold
   * was exceeded after the alarm was first raised. Default
   * DEFAULT_RETRY_AFTER_INTERVAL <br>
   * When a negative value is returned, this absolute value is used in all 503
   * responses, regardless of the number periods the threshold was exceeded.
   *
   * @return the retry-after interval used as base
   */
  public Integer getRetryAfterInterval() {
    if (LOGGER.isLoggable(Level.FINER)) {
      LOGGER.log(Level.FINER, "Retry-After interval: "
          + _retryAfterInterval);
    }
    return _retryAfterInterval;
  }

  /**
   * The retry-after value returned in a 503 response is this value with an
   * extra offset depending on the number of consecutive periods the threshold
   * was exceeded after the alarm was first raised. Default
   * DEFAULT_RETRY_AFTER_INTERVAL <br>
   * When a negative value is returned, this absolute value is used in all 503
   * responses, regardless of the number periods the threshold was exceeded.
   *
   * @param retryAfterInterval
   *            the retry-after interval used as base
   */
  @Configuration(key = "RetryAfterInterval", node = "/SipContainer")
  public void setRetryAfterInterval(final Integer retryAfterInterval) {
    if (LOGGER.isLoggable(Level.INFO)) {
      LOGGER.log(Level.INFO, "Retry-After interval value will be set to "
          + retryAfterInterval.intValue());
    }
    _retryAfterInterval = retryAfterInterval;
  }
       
        @Configuration(key = "RetryAfterInterval", node = "/OverloadProtectionService")
  public void setOlpServiceRetryAfterInterval(final Integer retryAfterInterval) {
            setRetryAfterInterval(retryAfterInterval);
        }
        /**
         * The wait time is the time the thread has to be held before
         * being release back to the pool under maximum overload conditions
         * for Http.
         * @param waittime time in seconds.
         */
        @Configuration(key = "MmThresholdHttpWaitTime", node = "/SipContainer")
        public void setMmThresholdHttpWaitTime(final Integer waittime) {
            _mmHttpThresholdWaitTime = waittime;
        }
       
        @Configuration(key = "MmThresholdHttpWaitTime", node = "/OverloadProtectionService")
        public void setOlpServiceMmThresholdHttpWaitTime(final Integer waittime) {
            setMmThresholdHttpWaitTime(waittime);
        }
        /**
         * The wait time is the time the thread has to be held before
         * being release back to the pool under maximum overload conditions
         * for Http.
         */
        public int getMmThresholdHttpWaitTime(){
            return _mmHttpThresholdWaitTime;
        }
}
TOP

Related Classes of com.ericsson.ssa.container.overload.OverloadSampler

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.