AlarmLibrary.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */

  20. package org.openspcoop2.monitor.engine.alarm;

  21. import java.util.ArrayList;
  22. import java.util.Collections;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.concurrent.ConcurrentHashMap;

  26. import org.slf4j.Logger;
  27. import org.openspcoop2.core.allarmi.Allarme;
  28. import org.openspcoop2.core.allarmi.IdAllarme;
  29. import org.openspcoop2.core.allarmi.constants.TipoAllarme;
  30. import org.openspcoop2.core.allarmi.constants.TipoPeriodo;
  31. import org.openspcoop2.core.allarmi.dao.IAllarmeServiceSearch;
  32. import org.openspcoop2.core.allarmi.dao.IServiceManager;
  33. import org.openspcoop2.core.allarmi.utils.AllarmiConverterUtils;
  34. import org.openspcoop2.core.allarmi.utils.ProjectInfo;
  35. import org.openspcoop2.core.commons.dao.DAOFactory;
  36. import org.openspcoop2.generic_project.exception.ExpressionException;
  37. import org.openspcoop2.generic_project.exception.ExpressionNotImplementedException;
  38. import org.openspcoop2.generic_project.exception.MultipleResultException;
  39. import org.openspcoop2.generic_project.exception.NotFoundException;
  40. import org.openspcoop2.generic_project.exception.NotImplementedException;
  41. import org.openspcoop2.generic_project.exception.ServiceException;
  42. import org.openspcoop2.generic_project.expression.IExpression;
  43. import org.openspcoop2.generic_project.expression.IPaginatedExpression;
  44. import org.openspcoop2.monitor.sdk.alarm.IAlarm;
  45. import org.openspcoop2.monitor.sdk.constants.AlarmStateValues;
  46. import org.openspcoop2.monitor.sdk.exceptions.AlarmException;
  47. import org.openspcoop2.utils.Utilities;

  48. /**
  49.  * AlarmLibrary
  50.  *
  51.  * @author Poli Andrea (apoli@link.it)
  52.  * @author $Author$
  53.  * @version $Rev$, $Date$
  54.  */
  55. public class AlarmLibrary {

  56.     private IAllarmeServiceSearch allarmeSearchDAO;
  57.     private Logger log;
  58.     private AlarmEngineConfig alarmEngineConfig;
  59.     private DAOFactory daoFactory;
  60.    
  61.     private Map<String, AlarmThread> activeThreads = null;
  62.    
  63.     private String getMessageAlarmNotExists(String name) {
  64.         return "Alarm ["+name+"] not exists";
  65.     }
  66.    
  67.     public AlarmLibrary(DAOFactory daoFactory,Logger log,AlarmEngineConfig alarmEngineConfig) throws AlarmException{
  68.         try{
  69.             this.daoFactory = daoFactory;
  70.             IServiceManager pluginSM = (IServiceManager) this.daoFactory.getServiceManager(ProjectInfo.getInstance());
  71.             this.allarmeSearchDAO = pluginSM.getAllarmeServiceSearch();
  72.             this.log = log;
  73.             this.alarmEngineConfig = alarmEngineConfig;
  74.             AlarmManager.setAlarmEngineConfig(alarmEngineConfig);
  75.         }catch(Exception e){
  76.             throw new AlarmException(e.getMessage(),e);
  77.         }
  78.     }
  79.    
  80.     /*
  81.      * Utiltiies per dormire
  82.      * NOTA: Devo dormire il tempo minimo configurabile per un allarme (un minuto).
  83.      **/
  84.    
  85.     public void sleep(){
  86.         for (int i = 0; i < 60; i++) {
  87.             Utilities.sleep(1000); // Devo dormire il tempo minimo configurabile per un allarme (un minuto).
  88.             if(this.stop){
  89.                 break;
  90.             }
  91.         }
  92.     }
  93.    
  94.     /* Utiltiies per stop threads */
  95.    
  96.     private boolean stop = false;
  97.     public void stop(){
  98.         if(this.activeThreads!=null && this.activeThreads.size()>0){
  99.             for (AlarmThread alarmThread : this.activeThreads.values()) {
  100.                 this.stopAlarm(alarmThread);
  101.             }
  102.         }
  103.         this.stop = true;
  104.         this.activeThreads = null;
  105.     }
  106.     public void stopAlarm(String name,boolean throwExceptionNotFound) throws AlarmException{
  107.         if(this.activeThreads!=null && this.activeThreads.size()>0 && this.activeThreads.containsKey(name)){
  108.             AlarmThread alarmThread = this.activeThreads.get(name);
  109.             this.stopAlarm(alarmThread);
  110.             this.activeThreads.remove(name);
  111.         }
  112.         else{
  113.             if(throwExceptionNotFound){
  114.                 throw new AlarmException(getMessageAlarmNotExists(name));
  115.             }
  116.         }
  117.     }
  118.     private void stopAlarm(AlarmThread alarmThread){
  119.         alarmThread.setStop(true);
  120.         int max = 10 * 60 * 5; // attendo 5 minuti
  121.         int offset = 0;
  122.         int increment = 100;
  123.         while(offset<max && !alarmThread.isTerminated()){
  124.             Utilities.sleep(increment);
  125.             offset = offset + increment;
  126.         }
  127.     }
  128.    
  129.     /* Utiltiies per start threads */
  130.        
  131.     private boolean stopLibrary = false;
  132.     public void setStopLibrary(boolean stopLibrary) {
  133.         this.stopLibrary = stopLibrary;
  134.     }

  135.     public void executeAlarms(boolean exitAfterExecution) throws AlarmException{
  136.         try{
  137.             this.activeThreads = this.getActiveAlarmThreads(this.allarmeSearchDAO, this.log);
  138.             if(this.activeThreads.size()>0){
  139.                 for (AlarmThread alarmThread : this.activeThreads.values()) {
  140.                     Thread t = new Thread(alarmThread);
  141.                     t.start();  
  142.                 }
  143.                
  144.                 if(!exitAfterExecution){
  145.                     while (!this.stopLibrary){
  146.                         // non deve morire mai
  147.                         this.sleep();
  148.                     }
  149.                 }
  150.             }
  151.             else{
  152.                 this.log.warn("Non sono stati trovati allarmi");
  153.             }
  154.         }catch(Exception e){
  155.             throw new AlarmException(e.getMessage(),e);
  156.         }
  157.     }
  158.    
  159.     private Allarme getAlarmConf(String name) throws AlarmException {
  160.         Allarme conf = null;
  161.         try{
  162.             conf = this.getActiveAlarmThread(this.allarmeSearchDAO, name);
  163.         }catch(Exception e){
  164.             throw new AlarmException(e.getMessage(),e);
  165.         }
  166.         if(conf==null){
  167.             throw new AlarmException(getMessageAlarmNotExists(name));
  168.         }
  169.         return conf;
  170.     }
  171.     public void executeAlarm(String name) throws AlarmException{
  172.         try{
  173.             Allarme conf = getAlarmConf(name);
  174.             if(conf.getEnabled()==1 && TipoAllarme.ATTIVO.equals(conf.getTipoAllarme())){
  175.                 AlarmThread alarmThread = this.createAlarmThread(conf);
  176.                 if(alarmThread!=null){
  177.                     if(this.activeThreads==null) {
  178.                         this.activeThreads = new ConcurrentHashMap<>();
  179.                     }
  180.                     this.activeThreads.put(conf.getNome(),alarmThread);
  181.                     Thread t = new Thread(alarmThread);
  182.                     t.start();  
  183.                 }
  184.             }
  185.         }catch(Exception e){
  186.             throw new AlarmException(e.getMessage(),e);
  187.         }
  188.     }
  189.    
  190.     /* Utiltiies per refresh threads */
  191.    
  192.     public void forceNewCheckAlarm(String name) throws AlarmException{
  193.         try{
  194.             getAlarmConf(name); // verificare se eliminabile
  195.             AlarmThread alarmThread = this.activeThreads.get(name);
  196.             alarmThread.forceNewCheck();
  197.         }catch(Exception e){
  198.             throw new AlarmException(e.getMessage(),e);
  199.         }
  200.     }
  201.    
  202.     /* Utiltiies per update stato threads */
  203.    
  204.     public void updateStateAlarm(String name,AlarmStateValues alarmStatus) throws AlarmException{
  205.         try{
  206.             getAlarmConf(name); // verificare se eliminabile
  207.             AlarmThread alarmThread = this.activeThreads.get(name);
  208.             alarmThread.updateState(alarmStatus);
  209.         }catch(Exception e){
  210.             throw new AlarmException(e.getMessage(),e);
  211.         }
  212.     }
  213.    
  214.     public void updateAcknoledgement(String name,boolean acknoledgement) throws AlarmException{
  215.         try{
  216.             getAlarmConf(name); // verificare se eliminabile
  217.             AlarmThread alarmThread = this.activeThreads.get(name);
  218.             alarmThread.updateAcknowledged(acknoledgement);
  219.         }catch(Exception e){
  220.             throw new AlarmException(e.getMessage(),e);
  221.         }
  222.     }
  223.    
  224.    
  225.     /* Utiltiies per get image threads */
  226.    
  227.     public String getAlarmImage(String name) throws AlarmException{
  228.         if(this.activeThreads!=null && this.activeThreads.size()>0 && this.activeThreads.containsKey(name)){
  229.             AlarmThread alarmThread = this.activeThreads.get(name);
  230.             return alarmThread.getStatoAllarme();
  231.         }
  232.         else{
  233.             throw new AlarmException(getMessageAlarmNotExists(name));
  234.         }
  235.     }
  236.    
  237.     public String getAlarmsImages() {
  238.         if(this.activeThreads!=null && this.activeThreads.size()>0){
  239.             List<String> list = new ArrayList<>();
  240.             for (String idAllarme : this.activeThreads.keySet()) {
  241.                 list.add(idAllarme);
  242.             }
  243.             Collections.sort(list);
  244.             StringBuilder sb = new StringBuilder();
  245.             for (String idAllarme : list) {
  246.                 if(sb.length()>0) {
  247.                     sb.append("\n");
  248.                 }
  249.                 sb.append(idAllarme);
  250.             }
  251.             return sb.toString();
  252.         }
  253.         else{
  254.             return "";
  255.         }
  256.     }
  257.    
  258.    
  259.    
  260.     /* Utiltiies per exists threads */
  261.    
  262.     public boolean existsAlarm(String name) {
  263.         return this.activeThreads!=null && this.activeThreads.size()>0 && this.activeThreads.containsKey(name);
  264.     }
  265.    
  266.    
  267.     /* Utiltiies interne */
  268.    
  269.     private Map<String, AlarmThread> getActiveAlarmThreads(IAllarmeServiceSearch allarmeSearchDAO, Logger log) throws ServiceException, NotImplementedException, ExpressionNotImplementedException, ExpressionException {
  270.        
  271.         IExpression expr = allarmeSearchDAO.newExpression();
  272.         expr.and();
  273.         expr.notEquals(Allarme.model().ENABLED,
  274.                 Integer.valueOf(0));
  275.         expr.notEquals(Allarme.model().TIPO_ALLARME,
  276.                 TipoAllarme.PASSIVO);
  277.         /**expr.isNotNull(Allarme.model().CLASS_NAME);*/

  278.         IPaginatedExpression pagExpr = allarmeSearchDAO
  279.                 .toPaginatedExpression(expr);
  280.        
  281.         List<Allarme> list = allarmeSearchDAO.findAll(pagExpr);
  282.         Map<String, AlarmThread> listAlarmThread = new ConcurrentHashMap<>();
  283.        
  284.         for (Allarme confAllarme : list) {
  285.             try {
  286.                 AlarmThread alarmThread = createAlarmThread(confAllarme);
  287.                 if(alarmThread!=null){
  288.                     listAlarmThread.put(confAllarme.getNome(),alarmThread);
  289.                 }
  290.             }catch(Exception t) {
  291.                 log.error("Creazione allarme con id '"+confAllarme.getNome()+"' (alias: "+confAllarme.getAlias()+") non riuscita: "+t.getMessage(),t);
  292.             }
  293.         }
  294.         return listAlarmThread;
  295.     }
  296.    
  297.     private Allarme getActiveAlarmThread(IAllarmeServiceSearch allarmeSearchDAO, String name) throws ServiceException, NotFoundException, MultipleResultException, NotImplementedException {
  298.        
  299.         IdAllarme id = new IdAllarme();
  300.         id.setNome(name);
  301.         return allarmeSearchDAO.get(id);
  302.        
  303.     }
  304.    
  305.     private AlarmThread createAlarmThread(Allarme confAllarme) throws AlarmException{
  306.         IAlarm alarm = AlarmManager.getAlarm(confAllarme,this.log,this.daoFactory);
  307.         String classname = ((AlarmImpl) alarm).getPluginClassName();
  308.         TipoPeriodo tipoPeriodo = AllarmiConverterUtils.toTipoPeriodo(confAllarme.getTipoPeriodo());
  309.         int periodo = confAllarme.getPeriodo().intValue();

  310.         AlarmThread alarmThread = null;
  311.         /**if (alarm != null) {*/
  312.         try {
  313.             alarmThread = new AlarmThread(this.log, confAllarme.getTipo(), classname, alarm, this.alarmEngineConfig);
  314.             if (periodo != 0) {
  315.                 switch (tipoPeriodo) {
  316.                 case G:
  317.                     alarmThread.setPeriodByDays(periodo);
  318.                     break;
  319.                 case H:
  320.                     alarmThread.setPeriodByHours(periodo);
  321.                     break;
  322.                 case M:
  323.                     alarmThread.setPeriodByMinutes(periodo);
  324.                     break;
  325.                 default:
  326.                     alarmThread.setPeriodBySeconds(periodo);
  327.                     break;
  328.                 }
  329.             }
  330.            
  331.         } catch (AlarmException e) {
  332.             this.log.error(e.getMessage(),e);
  333.         }
  334.         return alarmThread;
  335.     }
  336.        
  337. }