AlarmManager.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.List;

  23. import org.openspcoop2.core.allarmi.Allarme;
  24. import org.openspcoop2.core.allarmi.AllarmeHistory;
  25. import org.openspcoop2.core.allarmi.AllarmeNotifica;
  26. import org.openspcoop2.core.allarmi.AllarmeParametro;
  27. import org.openspcoop2.core.allarmi.IdAllarme;
  28. import org.openspcoop2.core.allarmi.constants.StatoAllarme;
  29. import org.openspcoop2.core.allarmi.dao.IAllarmeHistoryService;
  30. import org.openspcoop2.core.allarmi.dao.IAllarmeNotificaService;
  31. import org.openspcoop2.core.allarmi.dao.IAllarmeService;
  32. import org.openspcoop2.core.allarmi.dao.IAllarmeServiceSearch;
  33. import org.openspcoop2.core.allarmi.dao.IServiceManager;
  34. import org.openspcoop2.core.allarmi.utils.AllarmiConverterUtils;
  35. import org.openspcoop2.core.allarmi.utils.ProjectInfo;
  36. import org.openspcoop2.core.commons.dao.DAOFactory;
  37. import org.openspcoop2.core.plugins.IdPlugin;
  38. import org.openspcoop2.core.plugins.Plugin;
  39. import org.openspcoop2.core.plugins.constants.TipoPlugin;
  40. import org.openspcoop2.generic_project.exception.NotFoundException;
  41. import org.openspcoop2.generic_project.expression.IExpression;
  42. import org.openspcoop2.monitor.engine.constants.CostantiConfigurazione;
  43. import org.openspcoop2.monitor.engine.dynamic.DynamicFactory;
  44. import org.openspcoop2.monitor.engine.dynamic.IDynamicLoader;
  45. import org.openspcoop2.monitor.sdk.alarm.AlarmStatus;
  46. import org.openspcoop2.monitor.sdk.alarm.IAlarm;
  47. import org.openspcoop2.monitor.sdk.alarm.IAlarmLogger;
  48. import org.openspcoop2.monitor.sdk.constants.AlarmStateValues;
  49. import org.openspcoop2.monitor.sdk.exceptions.AlarmException;
  50. import org.openspcoop2.monitor.sdk.exceptions.AlarmNotifyException;
  51. import org.openspcoop2.monitor.sdk.parameters.Parameter;
  52. import org.openspcoop2.monitor.sdk.plugins.IAlarmProcessing;
  53. import org.openspcoop2.utils.UtilsMultiException;
  54. import org.openspcoop2.utils.date.DateManager;
  55. import org.openspcoop2.utils.mail.Mail;
  56. import org.openspcoop2.utils.mail.Sender;
  57. import org.openspcoop2.utils.mail.SenderFactory;
  58. import org.openspcoop2.utils.resources.ScriptInvoker;
  59. import org.slf4j.Logger;


  60. /**
  61.  * AlarmManager
  62.  *
  63.  * @author Poli Andrea (apoli@link.it)
  64.  * @author $Author$
  65.  * @version $Rev$, $Date$
  66.  */
  67. public class AlarmManager {


  68.     private static AlarmEngineConfig alarmEngineConfig;
  69.     public static AlarmEngineConfig getAlarmEngineConfig() {
  70.         return AlarmManager.alarmEngineConfig;
  71.     }
  72.     public static void setAlarmEngineConfig(AlarmEngineConfig alarmEngineConfig) {
  73.         AlarmManager.alarmEngineConfig = alarmEngineConfig;
  74.     }

  75.     /**
  76.      * Ritorna i dati di un allarme con identificativo idAllarme
  77.      *
  78.      * @param idAllarme
  79.      *            Identificativo dell'allarme
  80.      * @return Allarme
  81.      * @throws AlarmException
  82.      */
  83.     public static IAlarm getAlarm(String idAllarme,Logger log, DAOFactory daoFactory) throws AlarmException {

  84.         AlarmImpl alarm = null;
  85.         try {
  86.             IServiceManager pluginSM = (IServiceManager) daoFactory.getServiceManager(ProjectInfo.getInstance());
  87.             IAllarmeServiceSearch allarmeDAO = pluginSM.getAllarmeServiceSearch();

  88.             IExpression expr = allarmeDAO.newExpression();
  89.             expr.equals(Allarme.model().NOME, idAllarme);

  90.             Allarme allarme = null;
  91.             try{
  92.                 allarme = allarmeDAO.find(expr);
  93.             }catch(NotFoundException notFound){
  94.                 // ignore
  95.             }
  96.                
  97.             if (allarme != null) {
  98.                 alarm = (AlarmImpl) getAlarm(allarme,log,daoFactory);
  99.             } else
  100.                 throw new AlarmException("Allarme -" + idAllarme
  101.                         + "- non esistente");

  102.         } catch (Exception e) {
  103.             log.error("AlarmManager.getAlarm(" + idAllarme
  104.                     + ") ha rilevato un errore: " + e.getMessage(), e);
  105.             throw new AlarmException(e.getMessage(),e);
  106.         }
  107.         return alarm;
  108.     }

  109.     /**
  110.      * Ritorna i dati di un allarme a partire da una configurazione Allarme
  111.      *
  112.      * @param allarme
  113.      *            Configurazione dell'allarme
  114.      * @return Allarme
  115.      * @throws AlarmException
  116.      */
  117.     public static IAlarm getAlarm(Allarme allarme,Logger log, DAOFactory daoFactory)
  118.             throws AlarmException {
  119.         return _getAlarm(allarme, log, daoFactory, null);
  120.     }
  121.     public static IAlarm getAlarm(Allarme allarme,Logger log, DAOFactory daoFactory, org.openspcoop2.core.plugins.dao.IServiceManager pluginSM)
  122.             throws AlarmException {
  123.         return _getAlarm(allarme, log, daoFactory, pluginSM);
  124.     }
  125.     private static IAlarm _getAlarm(Allarme allarme,Logger log, DAOFactory daoFactory, org.openspcoop2.core.plugins.dao.IServiceManager pluginSM)
  126.             throws AlarmException {
  127.        
  128.         AlarmImpl alarm = null;
  129.         try {
  130.             if (allarme != null) {
  131.                
  132.                 alarm = new AlarmImpl(allarme,log,daoFactory);
  133.                 AlarmStateValues statusValue = null;
  134.                 StatoAllarme statoAllarme = AllarmiConverterUtils.toStatoAllarme(allarme.getStato());
  135.                 switch (statoAllarme) {
  136.                 case OK:
  137.                     statusValue = AlarmStateValues.OK;
  138.                     break;
  139.                 case WARNING:
  140.                     statusValue = AlarmStateValues.WARNING;
  141.                     break;
  142.                 case ERROR:
  143.                     statusValue = AlarmStateValues.ERROR;
  144.                     break;
  145.                 }
  146.                 AlarmStatus alarmStatus = new AlarmStatus();
  147.                 alarmStatus.setStatus(statusValue);
  148.                 alarmStatus.setDetail(allarme.getDettaglioStato());
  149.                 alarm.setStatus(alarmStatus);
  150.                
  151.                 if(pluginSM==null) {
  152.                     pluginSM =
  153.                             (org.openspcoop2.core.plugins.dao.IServiceManager)
  154.                             daoFactory.getServiceManager(org.openspcoop2.core.plugins.utils.ProjectInfo.getInstance());
  155.                 }
  156.                 TipoPlugin tipoPlugin = TipoPlugin.ALLARME;
  157.                 IdPlugin idPlugin = new IdPlugin();
  158.                 idPlugin.setTipoPlugin(tipoPlugin.getValue());
  159.                 idPlugin.setTipo(allarme.getTipo());
  160.                 Plugin plugin = pluginSM.getPluginServiceSearch().get(idPlugin);
  161.                
  162.                 alarm.setPluginClassName(plugin.getClassName());
  163.                
  164.                 IDynamicLoader cAllarme = DynamicFactory.getInstance().newDynamicLoader(tipoPlugin, allarme.getTipo(), plugin.getClassName(), log);
  165.                 IAlarmProcessing alarmProc = (IAlarmProcessing) cAllarme.newInstance();
  166.                 alarm.setManuallyUpdateState(alarmProc.isManuallyUpdateState());
  167.                 alarm.setManuallyAckCriteria(alarmProc.isManuallyAckCriteria());
  168.                 AlarmContext ctx = new AlarmContext(allarme, log, daoFactory);
  169.                 List<Parameter<?>> listParameters = alarmProc.getParameters(ctx);
  170.                
  171.                 for (AllarmeParametro parametro : allarme.getAllarmeParametroList()) {
  172.                     for (Parameter<?> parameter : listParameters) {
  173.                         if(parameter.getId().equals(parametro.getIdParametro())){
  174.                             parameter.setValueAsString(parametro.getValore());
  175.                             break;
  176.                         }
  177.                     }
  178.                 }
  179.                
  180.                 for (Parameter<?> parameter : listParameters) {
  181.                     alarm.addParameter(parameter);
  182.                 }
  183.                
  184.             } else
  185.                 throw new AlarmException("Allarme non valido");

  186.         } catch (Exception e) {
  187.             log.error(
  188.                     "AlarmManager.getAlarm(" + (allarme!=null ? allarme.getNome() : "Alarm undefined")
  189.                             + ") ha rilevato un errore: " + e.getMessage(), e);
  190.             throw new AlarmException(e.getMessage(),e);
  191.         }
  192.         return alarm;
  193.     }
  194.    
  195.     protected static void changeStatus(AlarmStatus newStatoAllarme,IAlarm allarme,IServiceManager allarmiSM,String username,boolean statusChanged,
  196.             List<AllarmeHistory> repositoryHistory) throws AlarmException {
  197.         try {
  198.            
  199.             Allarme oldConfig = allarme.getConfigAllarme();
  200.            
  201.             IAllarmeServiceSearch allarmeSearchDAO = allarmiSM
  202.                     .getAllarmeServiceSearch();
  203.             IAllarmeService allarmeDAO = allarmiSM
  204.                     .getAllarmeService();
  205.             IAllarmeHistoryService allarmeHistoryDAO = allarmiSM
  206.                     .getAllarmeHistoryService();

  207.             IExpression expr = allarmeSearchDAO.newExpression();
  208.             expr.equals(Allarme.model().NOME, allarme.getId());

  209.             Allarme confAllarme = allarmeSearchDAO.find(expr); // non mi posso fidare dell'allarme passato come parametro. Potrebbe essere cambiato nel frattempo

  210.             if (confAllarme != null) {
  211.                
  212.                 // Se il tipo è AlarmStatusWithAck sto forzando la decisione dell'ack all'utente console
  213.                 boolean autoChangeAck = true;
  214.                 if(newStatoAllarme instanceof AlarmStatusWithAck){
  215.                     AlarmStatusWithAck withAck = (AlarmStatusWithAck) newStatoAllarme;
  216.                     if(withAck.isAck()){
  217.                         confAllarme.setAcknowledged(1);
  218.                         oldConfig.setAcknowledged(1);
  219.                     }
  220.                     else{
  221.                         confAllarme.setAcknowledged(0);
  222.                         oldConfig.setAcknowledged(0);
  223.                     }
  224.                     autoChangeAck = false;
  225.                 }
  226.                
  227.                 if(statusChanged && confAllarme.getStato()!=null){
  228.                     confAllarme.setStatoPrecedente(confAllarme.getStato());
  229.                     oldConfig.setStatoPrecedente(confAllarme.getStato());
  230.                 }
  231.                
  232.                 switch (newStatoAllarme.getStatus()) {
  233.                 case OK:
  234.                     confAllarme.setStato(AllarmiConverterUtils.toIntegerValue(StatoAllarme.OK));
  235.                     break;
  236.                 case WARNING:
  237.                     confAllarme.setStato(AllarmiConverterUtils.toIntegerValue(StatoAllarme.WARNING));
  238.                     break;
  239.                 default:
  240.                     confAllarme.setStato(AllarmiConverterUtils.toIntegerValue(StatoAllarme.ERROR));
  241.                     break;
  242.                 }
  243.                 oldConfig.setStato(confAllarme.getStato());
  244.                
  245.                 confAllarme.setLasttimestampUpdate(DateManager.getDate());
  246.                 oldConfig.setLasttimestampUpdate(confAllarme.getLasttimestampUpdate());
  247.                
  248.                 // Azzero acknoledgement in caso di cambio stato
  249.                 if(statusChanged){
  250.                     if(autoChangeAck){
  251.                         // lo stato è modificato
  252.                         confAllarme.setAcknowledged(0);
  253.                         oldConfig.setAcknowledged(0);
  254.                     }
  255.                     else{
  256.                         // se lo stato è rimasto lo stesso ma è cambiato il dettaglio, modificao l'acknoldegement ??
  257.     //                  if(newStatoAllarme.getDetail()!=null && !newStatoAllarme.getDetail().equals(confAllarme.getDettaglioStato())){
  258.     //                      confAllarme.setAcknowledged(0);
  259.     //                  }
  260.                     }
  261.                 }
  262.                
  263.                 confAllarme.setDettaglioStato(newStatoAllarme.getDetail());
  264.                 oldConfig.setDettaglioStato(confAllarme.getDettaglioStato());
  265.                
  266.                 IdAllarme idConfAllarme = new IdAllarme();

  267.                 idConfAllarme.setId(confAllarme.getId());
  268.                 idConfAllarme.setNome(confAllarme.getNome());
  269. //              idConfAllarme.setIdConfigurazioneServizioAzione(confAllarme
  270. //                      .getIdConfigurazioneServizioAzione());
  271.                
  272.                 // Recupero stato dell'allarme dal db per evitare di far crescere all'infinito l'history dell'allarme per ogni check.
  273.                 Allarme allarmeImmagineDB = allarmeDAO.get(idConfAllarme);
  274.                
  275.                 //System.out.println("UPDATE ALLARME");
  276.                 allarmeDAO.update(idConfAllarme, confAllarme);
  277.                
  278.                 boolean checkHistory = false;
  279.                 if(repositoryHistory!=null) {
  280.                     checkHistory = true;
  281.                 }
  282.                 else {
  283.                     AlarmEngineConfig alarmEngineConfig = AlarmManager.getAlarmEngineConfig();
  284.                     checkHistory = alarmEngineConfig.isHistoryEnabled();
  285.                 }
  286.                 if(checkHistory) {

  287.                     boolean registraHistory = registraHistory(confAllarme, allarmeImmagineDB);
  288.                     //System.out.println("REGISTRO HISTORY ALLARME ? "+registraHistory);
  289.                     if(registraHistory){
  290.                         AllarmeHistory history = new AllarmeHistory();
  291.                         history.setEnabled(confAllarme.getEnabled());
  292.                         history.setAcknowledged(confAllarme.getAcknowledged());
  293.                         history.setDettaglioStato(confAllarme.getDettaglioStato());
  294.                         history.setStato(confAllarme.getStato());
  295.                         IdAllarme idAllarme = new IdAllarme();
  296.                         idAllarme.setNome(confAllarme.getNome());
  297.                         history.setIdAllarme(idAllarme);
  298.                         history.setUtente(username);    
  299.                         history.setTimestampUpdate(confAllarme.getLasttimestampUpdate());
  300.                         if(repositoryHistory!=null) {
  301.                             repositoryHistory.add(history);
  302.                         }
  303.                         else {
  304.                             allarmeHistoryDAO.create(history);
  305.                         }
  306.                         //System.out.println("REGISTRATO HISTORY ALLARME");
  307.                     }
  308.                    
  309.                 }
  310.                
  311.             } else
  312.                 throw new AlarmException("Allarme -" + allarme.getId()
  313.                         + "- non esistente");
  314.            
  315.         } catch (Exception e) {
  316.             allarme.getLogger().error(
  317.                     "AlarmManager.changeStatus() ha rilevato un errore: "
  318.                             + e.getMessage(), e);
  319.             throw new AlarmException(e.getMessage(),e);
  320.         }
  321.     }
  322.    
  323.     private static boolean registraHistory(Allarme confAllarme, Allarme allarmeImmagineDB){
  324.        
  325.         if(confAllarme.getEnabled()!=null){
  326.             if(allarmeImmagineDB.getEnabled()==null){
  327.                 return true;
  328.             }
  329.             else if(allarmeImmagineDB.getEnabled()!=null && confAllarme.getEnabled()!=null &&
  330.                     (allarmeImmagineDB.getEnabled().intValue() != confAllarme.getEnabled().intValue())){
  331.                 return true;
  332.             }
  333.         }
  334.         else{
  335.             if(allarmeImmagineDB.getEnabled()!=null){
  336.                 return true;
  337.             }
  338.         }
  339.        
  340.         if(confAllarme.getAcknowledged()!=null){
  341.             if(allarmeImmagineDB.getAcknowledged()==null){
  342.                 return true;
  343.             }
  344.             else if(allarmeImmagineDB.getAcknowledged()!=null && confAllarme.getAcknowledged()!=null &&
  345.                     (allarmeImmagineDB.getAcknowledged().intValue() != confAllarme.getAcknowledged().intValue())){
  346.                 return true;
  347.             }
  348.         }
  349.         else{
  350.             if(allarmeImmagineDB.getAcknowledged()!=null){
  351.                 return true;
  352.             }
  353.         }
  354.        
  355. //      Bug Fix OPPT-753:
  356. //          Il Dettaglio non deve far parte della discriminante se salvare o meno nell'history dell'allarme poichè l'allarme ha cambiato stato.
  357. //      if(confAllarme.getDettaglioStato()!=null){
  358. //          if(allarmeImmagineDB.getDettaglioStato()==null){
  359. //              return true;
  360. //          }
  361. //          else if(!allarmeImmagineDB.getDettaglioStato().equals(confAllarme.getDettaglioStato())){
  362. //              return true;
  363. //          }
  364. //      }
  365. //      else{
  366. //          if(allarmeImmagineDB.getDettaglioStato()!=null){
  367. //              return true;
  368. //          }
  369. //      }
  370.        
  371.         if(confAllarme.getStato()!=null){
  372.             if(allarmeImmagineDB.getStato()==null){
  373.                 return true;
  374.             }
  375.             else if(!allarmeImmagineDB.getStato().equals(confAllarme.getStato())){
  376.                 return true;
  377.             }
  378.         }
  379.         else{
  380.             if(allarmeImmagineDB.getStato()!=null){
  381.                 return true;
  382.             }
  383.         }
  384.        
  385.        
  386.         return false;
  387.     }
  388.    
  389.     protected static void sendMail(Allarme configAllarme, IAlarmLogger alarmLog, List<String> logEvents) throws Exception{
  390.        
  391.         AlarmEngineConfig alarmEngineConfig = AlarmManager.getAlarmEngineConfig();
  392.         if(alarmEngineConfig==null){
  393.             throw new Exception("Configurazione Mail non fornita, utilizzare il metodo AlarmManager.setAlarmEngineConfig(...)");
  394.         }
  395.        
  396.         List<String> destinatari = new ArrayList<>();
  397.         if(configAllarme.getMail()!=null && configAllarme.getMail().getDestinatari()!=null){
  398.             String [] tmp = configAllarme.getMail().getDestinatari().split(",");
  399.             if(tmp!=null && tmp.length>0){
  400.                 for (int i = 0; i < tmp.length; i++) {
  401.                     destinatari.add(tmp[i].trim());
  402.                 }
  403.             }
  404.         }
  405.        
  406.         if(destinatari.size()>0){
  407.            
  408.             Sender sender = null;
  409.             if(alarmEngineConfig.getMailSenderType()==null){
  410.                 throw new Exception("Configurazione mail errata [Parametro 'SenderType' non definito]");
  411.             }
  412.             else{
  413.                 sender = SenderFactory.newSender(alarmEngineConfig.getMailSenderType(), alarmLog.getInternalLogger());
  414.             }
  415.            
  416.             if(alarmEngineConfig.getMailSenderConnectionTimeout()!=null){
  417.                 sender.setConnectionTimeout(alarmEngineConfig.getMailSenderConnectionTimeout());
  418.             }
  419.             if(alarmEngineConfig.getMailSenderReadTimeout()!=null){
  420.                 sender.setReadTimeout(alarmEngineConfig.getMailSenderReadTimeout());
  421.             }
  422.            
  423.             for (String destinatario : destinatari) {
  424.                
  425.                 Mail mail = new Mail();
  426.            
  427.                 // agent
  428.                 mail.setUserAgent(alarmEngineConfig.getMailAgent());
  429.                
  430.                 // from
  431.                 if(alarmEngineConfig.getMailFrom()==null){
  432.                     throw new Exception("Configurazione mail errata [Parametro 'From' non definito]");
  433.                 }
  434.                 else{
  435.                     mail.setFrom(alarmEngineConfig.getMailFrom());
  436.                 }
  437.                
  438.                 // to
  439.                 mail.setTo(destinatario);
  440.                
  441.                 // dati connessione
  442.                 if(alarmEngineConfig.getMailHost()==null){
  443.                     throw new Exception("Configurazione mail errata [Parametro 'Hostname' non definito]");
  444.                 }
  445.                 else{
  446.                     mail.setServerHost(alarmEngineConfig.getMailHost());
  447.                 }
  448.                 if(alarmEngineConfig.getMailPort()==null){
  449.                     throw new Exception("Configurazione mail errata [Parametro 'Port' non definito]");
  450.                 }
  451.                 else{
  452.                     mail.setServerPort(alarmEngineConfig.getMailPort());
  453.                 }
  454.                 if(alarmEngineConfig.getMailUsername()!=null){
  455.                     mail.setUsername(alarmEngineConfig.getMailUsername());
  456.                 }
  457.                 if(alarmEngineConfig.getMailPassword()!=null){
  458.                     mail.setPassword(alarmEngineConfig.getMailPassword());
  459.                 }
  460.                
  461.                 // ssl
  462.                 mail.setSslConfig(alarmEngineConfig.getMailSSLConfig());
  463.                 mail.setStartTls(alarmEngineConfig.isMailStartTls());
  464.                
  465.                 // subject
  466.                 String templateSubjectMail = null;
  467.                 if(configAllarme.getMail()!=null && configAllarme.getMail().getSubject()!=null) {
  468.                     templateSubjectMail = configAllarme.getMail().getSubject();
  469.                 }
  470.                 if(templateSubjectMail==null || "".equals(templateSubjectMail)){
  471.                     templateSubjectMail = alarmEngineConfig.getMailSubject();
  472.                     if(templateSubjectMail==null){
  473.                         throw new Exception("Configurazione mail errata [Parametro 'Subject' non definito]");
  474.                     }
  475.                 }
  476.                 mail.setSubject(replaceKeywordTemplate(templateSubjectMail, configAllarme, false));
  477.                
  478.                 // body
  479.                 String templateBodyMail = null;
  480.                 if(configAllarme.getMail()!=null && configAllarme.getMail().getBody()!=null) {
  481.                     templateBodyMail = configAllarme.getMail().getBody();
  482.                 }
  483.                 if(templateBodyMail==null || "".equals(templateBodyMail)){
  484.                     templateBodyMail = alarmEngineConfig.getMailBody();
  485.                     if(templateBodyMail==null){
  486.                         throw new Exception("Configurazione mail errata [Parametro 'Body' non definito]");
  487.                     }
  488.                 }
  489.                 mail.getBody().setMessage(replaceKeywordTemplate(templateBodyMail, configAllarme, false));
  490.                
  491.                 // send
  492.                 sender.send(mail, alarmEngineConfig.isMailDebug());
  493.                
  494.                 if(alarmEngineConfig.isMailDebug()){
  495.                     logEvents.add("eMail per notifica stato ["+configAllarme.getStato()+"] inviata correttamente al destinatario ["+destinatario+"]");
  496.                 }
  497.                
  498.             }
  499.            
  500.         }
  501.     }
  502.    
  503.     protected static void invokeScript(Allarme configAllarme, IAlarmLogger alarmLog, List<String> logEvents) throws Exception{
  504.        
  505.         AlarmEngineConfig alarmEngineConfig = AlarmManager.getAlarmEngineConfig();
  506.         if(alarmEngineConfig==null){
  507.             throw new Exception("Configurazione Script non fornita, utilizzare il metodo AlarmManager.setAlarmEngineConfig(...)");
  508.         }
  509.        
  510.         String path = null;
  511.         if(configAllarme.getScript()!=null) {
  512.             path = configAllarme.getScript().getCommand();
  513.         }
  514.         if(path==null || "".equals(path)){
  515.             path = alarmEngineConfig.getDefaultScriptPath();
  516.             if(path==null){
  517.                 throw new Exception("Configurazione script errata [Parametro 'Path' non definito]");
  518.             }
  519.         }
  520.        
  521.         String args = null;
  522.         if(configAllarme.getScript()!=null) {
  523.             args = configAllarme.getScript().getArgs();
  524.         }
  525.         if(args==null || "".equals(args)){
  526.             args = alarmEngineConfig.getDefaultScriptArgs();
  527.             if(args==null){
  528.                 throw new Exception("Configurazione script errata [Parametro 'Args' non definito]");
  529.             }
  530.         }
  531.         args = replaceKeywordTemplate(args, configAllarme, true);
  532.        
  533.         ScriptInvoker invoker = new ScriptInvoker(path);
  534.        
  535.         List<String> arguments = new ArrayList<>();
  536.         StringBuilder bfUtils = null;
  537.         if(args!=null && !"".equals(args)){
  538.             String [] tmp = args.trim().split(" ");
  539.             for (int i = 0; i < tmp.length; i++) {
  540.                 String s = tmp[i].trim();
  541.                 if(bfUtils == null){
  542.                     if(s.startsWith("\"")){
  543.                         if(s.endsWith("\"")){
  544.                             if(s.length()>2){
  545.                                 arguments.add(s.substring(1,s.length()-1));
  546.                             }
  547.                             else{
  548.                                 arguments.add(s); // caso speciale?
  549.                             }
  550.                         }
  551.                         else{
  552.                             bfUtils = new StringBuilder(s.substring(1));
  553.                         }
  554.                     }
  555.                     else{
  556.                         arguments.add(s);
  557.                     }
  558.                 }
  559.                 else{
  560.                     if(s.endsWith("\"")){
  561.                         bfUtils.append(" ").append(s.substring(0, (s.length()-1)));
  562.                         arguments.add(bfUtils.toString());
  563.                         bfUtils = null;
  564.                     }
  565.                     else{
  566.                         bfUtils.append(" ").append(s);
  567.                     }
  568.                 }
  569.             }
  570.         }
  571.        
  572.         if(arguments.size()>0)
  573.             invoker.run(arguments.toArray(new String[1]));
  574.         else{
  575.             invoker.run();
  576.         }
  577.        
  578.         String msg = "Invocazione script ["+path+"] (args: "+args+") ha ritornato un codice di uscita ["+invoker.getExitValue()+
  579.                 "]\nOutputStream: "+invoker.getOutputStream()+"\nErrorStream: "+invoker.getErrorStream();
  580.         if(invoker.getExitValue()!=0){
  581.             throw new Exception(msg);
  582.         }
  583.         else{
  584.             if(alarmEngineConfig.isScriptDebug()){
  585.                 logEvents.add(msg);
  586.             }
  587.         }
  588.        
  589.     }
  590.    
  591.     public static String replaceKeywordTemplate(String original, Allarme configAllarme, boolean script){
  592.        
  593.         String newS = original.replace(CostantiConfigurazione.ALARM_KEYWORD_TEMPLATE_NOME_ALLARME, configAllarme.getAlias());
  594.        
  595.         newS = newS.replace(CostantiConfigurazione.ALARM_KEYWORD_TEMPLATE_ID_ALLARME, configAllarme.getNome());
  596.        
  597.         StatoAllarme statoAllarme = AllarmiConverterUtils.toStatoAllarme(configAllarme.getStato());
  598.         switch ( statoAllarme ) {
  599.         case OK:
  600.             newS = newS.replace(CostantiConfigurazione.ALARM_KEYWORD_TEMPLATE_STATO_ALLARME, "Ok");
  601.             break;
  602.         case WARNING:
  603.             newS = newS.replace(CostantiConfigurazione.ALARM_KEYWORD_TEMPLATE_STATO_ALLARME, "Warning");
  604.             break;
  605.         case ERROR:
  606.             newS = newS.replace(CostantiConfigurazione.ALARM_KEYWORD_TEMPLATE_STATO_ALLARME, "Error");
  607.             break;
  608.         }
  609.        
  610.         String details = configAllarme.getDettaglioStato();
  611.         if(details==null){
  612.             details = "";
  613.         }
  614.         if(script){
  615.             newS = newS.replace(CostantiConfigurazione.ALARM_KEYWORD_TEMPLATE_DETTAGLIO_ALLARME,"\""+details+"\"");
  616.         }else{
  617.             newS = newS.replace(CostantiConfigurazione.ALARM_KEYWORD_TEMPLATE_DETTAGLIO_ALLARME,details);
  618.         }
  619.         return newS;
  620.     }

  621.     public static void notifyChangeStatus(AlarmEngineConfig alarmEngineConfig, Allarme allarme,
  622.             IAlarm alarm, String pluginClassName,String threadName,
  623.             AlarmLogger alarmLogger,
  624.             AlarmStatus oldStatus, AlarmStatus nuovoStatoAllarme,
  625.             boolean checkAcknowledState) throws AlarmException, AlarmNotifyException {
  626.        
  627.         boolean statusChanged = false;
  628.         String prefix = null;
  629.         try{
  630.            
  631.             // Cambio di stato effettivo ?
  632.             if(oldStatus==null || oldStatus.getStatus()==null){
  633.                 statusChanged = true;
  634.             }
  635.             else{
  636.                 statusChanged = !oldStatus.getStatus().equals(nuovoStatoAllarme.getStatus());
  637.             }
  638.            
  639.             // Gestione invocazione script, mail e notifiche a plugin
  640.             boolean statusWarningError = false;
  641.             if(nuovoStatoAllarme!=null) {
  642.                 statusWarningError = AlarmStateValues.WARNING.equals(nuovoStatoAllarme.getStatus()) || AlarmStateValues.ERROR.equals(nuovoStatoAllarme.getStatus());
  643.             }
  644.             if(!statusChanged && (!statusWarningError || !checkAcknowledState)){
  645.                 alarmLogger.debug("Cambio di stato non rilevato (old:"+oldStatus+" new:"+nuovoStatoAllarme+")");
  646.                 return;
  647.             }
  648.            
  649.             if(statusChanged) {
  650.                 prefix = "Cambio di stato rilevato (old:"+oldStatus+" new:"+nuovoStatoAllarme+"); ";
  651.             }
  652.             else {
  653.                 prefix = "Cambio di stato non rilevato; ";
  654.             }
  655.            
  656.         }catch(Exception e){
  657.             throw new AlarmException(e.getMessage(),e);
  658.         }
  659.        
  660.         boolean invokePlugin = statusChanged;
  661.         boolean sendMail = false;
  662.         boolean invokeScript = false;
  663.         try {
  664.             alarmLogger.debug(prefix+"lettura configurazione in corso ...");
  665.            
  666.             boolean mailCheckAcknowledgedStatus = alarmEngineConfig.isMailCheckAcknowledgedStatus();
  667.             boolean mailSendChangeStatusOk = alarmEngineConfig.isMailSendChangeStatusOk();
  668.            
  669.             boolean scriptCheckAcknowledgedStatus = alarmEngineConfig.isScriptCheckAcknowledgedStatus();
  670.             boolean scriptSendChangeStatusOk = alarmEngineConfig.isScriptSendChangeStatusOk();
  671.            
  672.             boolean acknowledged = (allarme.getAcknowledged()==null || allarme.getAcknowledged()==1);
  673.            
  674.            
  675.             alarmLogger.debug(prefix+"valutazione se è necessario una notifica di cambio stato per mail/script (acknowledged:"+acknowledged+") ...");
  676.            
  677.             alarmLogger.debug(prefix+"mail sendChangeStatusOk:"+mailSendChangeStatusOk+" checkAcknowledgedStatus:"+mailCheckAcknowledgedStatus+"");
  678.             alarmLogger.debug(prefix+"script sendChangeStatusOk:"+scriptSendChangeStatusOk+" checkAcknowledgedStatus:"+scriptCheckAcknowledgedStatus+"");
  679.            
  680.             if(nuovoStatoAllarme!=null) {
  681.                
  682.                 if(AlarmStateValues.OK.equals(nuovoStatoAllarme.getStatus())){
  683.                     if(mailSendChangeStatusOk){
  684.                         // sia in ack mode che non in ack mode viene spedito da questo metodo.
  685.                         // tanto deve essere spedita solo la prima volta e non continuamente
  686.                         sendMail = (allarme.getMail()!=null &&
  687.                                 allarme.getMail().getInvia()!=null &&
  688.                                 allarme.getMail().getInvia()==1);
  689.                     }
  690.                     if(scriptSendChangeStatusOk){
  691.                         // sia in ack mode che non in ack mode viene spedito da questo metodo.
  692.                         // tanto deve essere spedita solo la prima volta e non continuamente
  693.                         invokeScript = (allarme.getScript()!=null &&
  694.                                 allarme.getScript().getInvoca()!=null &&
  695.                                 allarme.getScript().getInvoca()==1);
  696.                     }
  697.                    
  698.                 }
  699.                
  700.                
  701.                 else if(AlarmStateValues.WARNING.equals(nuovoStatoAllarme.getStatus())){
  702.                    
  703.                     if( (statusChanged) || (mailCheckAcknowledgedStatus && !acknowledged) ){
  704.                         // NOTA: per come è impostata la pddMonitor il warning esiste solo se è attivo anche l'alert
  705.                         sendMail = (
  706.                                     allarme.getMail()!=null &&
  707.                                     allarme.getMail().getInvia()!=null &&
  708.                                     allarme.getMail().getInvia()==1
  709.                                 )
  710.                                 &&
  711.                                 (
  712.                                     allarme.getMail()!=null &&
  713.                                     allarme.getMail().getInviaWarning()!=null &&
  714.                                     allarme.getMail().getInviaWarning()==1
  715.                                 );
  716.                     }
  717.                     if( (statusChanged) || (scriptCheckAcknowledgedStatus && !acknowledged) ){
  718.                         // NOTA: per come è impostata la pddMonitor il warning esiste solo se è attivo anche l'alert
  719.                         invokeScript = (
  720.                                     allarme.getScript()!=null &&
  721.                                     allarme.getScript().getInvoca()!=null &&
  722.                                     allarme.getScript().getInvoca()==1
  723.                                 )
  724.                                 &&
  725.                                 (
  726.                                     allarme.getScript()!=null &&
  727.                                     allarme.getScript().getInvocaWarning()!=null &&
  728.                                     allarme.getScript().getInvocaWarning()==1
  729.                                 );
  730.                     }
  731.                    
  732.                 }
  733.                 else if(AlarmStateValues.ERROR.equals(nuovoStatoAllarme.getStatus())){
  734.                    
  735.                     if( (statusChanged) || (mailCheckAcknowledgedStatus && !acknowledged) ){
  736.                         sendMail = allarme.getMail()!=null &&
  737.                                 allarme.getMail().getInvia()!=null &&
  738.                                 allarme.getMail().getInvia()==1; // note: Alert rappresenta l'invio della mail nel db e non veramente solo il livello error
  739.                     }
  740.                     if( (statusChanged) || (scriptCheckAcknowledgedStatus && !acknowledged) ){
  741.                         invokeScript = allarme.getScript()!=null &&
  742.                                 allarme.getScript().getInvoca()!=null &&
  743.                                 allarme.getScript().getInvoca()==1; // note: Alert rappresenta l'invio via script nel db e non veramente solo il livello error
  744.                     }
  745.                    
  746.                 }
  747.             }
  748.            
  749.         }catch(Exception e){
  750.             throw new AlarmException(e.getMessage(),e);
  751.         }
  752.        
  753.         List<Exception> listExceptions = new ArrayList<Exception>();
  754.        
  755.         // Notifico cambio di stato all'interfaccia
  756.         String pluginInvocationError = null;
  757.         try {
  758.             if(invokePlugin) {
  759.                 alarmLogger.debug(prefix+"notifica plugin ...");
  760.                 IDynamicLoader cPlugin = DynamicFactory.getInstance().newDynamicLoader(TipoPlugin.ALLARME,allarme.getTipo(),pluginClassName, alarmLogger.getInternalLogger());
  761.                 IAlarmProcessing alarmProc = (IAlarmProcessing) cPlugin.newInstance();
  762.                 alarmProc.changeStatusNotify(alarm, oldStatus, nuovoStatoAllarme);
  763.                 alarmLogger.debug(prefix+"notifica plugin terminata");
  764.             }
  765.         } catch( Exception e) {
  766.             alarmLogger.error(prefix+"notifica plugin fallita: "+e.getMessage(),e);
  767.             pluginInvocationError = e.getMessage();
  768.             listExceptions.add(e);
  769.         }
  770.        
  771.         // Notifico cambio di stato via mail
  772.         String sendMailError = null;
  773.         try {
  774.             if(sendMail){
  775.                 alarmLogger.debug(prefix+"notifica mail ...");
  776.                 List<String> logEvents = new ArrayList<>();
  777.                 AlarmManager.sendMail(allarme, alarmLogger, logEvents);
  778.                 if(logEvents!=null && !logEvents.isEmpty()) {
  779.                     for (String logEvent : logEvents) {
  780.                         String prefixLog = AlarmLogger.buildPrefix(threadName,allarme.getAlias(),allarme.getNome());
  781.                         alarmLogger.debug(prefixLog+logEvent);
  782.                     }
  783.                 }
  784.                 alarmLogger.debug(prefix+"notifica mail completata");
  785.             }
  786.         }  
  787.         catch( Exception e) {
  788.             alarmLogger.error(prefix+"notifica mail fallita: "+e.getMessage(),e);
  789.             sendMailError = e.getMessage();
  790.             listExceptions.add(e);
  791.         }
  792.        
  793.         // Notifico cambio di stato via script
  794.         String scriptInvocationError = null;
  795.         try {
  796.             if(invokeScript){
  797.                 alarmLogger.debug(prefix+"notifica via script ...");
  798.                 List<String> logEvents = new ArrayList<>();
  799.                 AlarmManager.invokeScript(allarme, alarmLogger, logEvents);
  800.                 if(logEvents!=null && !logEvents.isEmpty()) {
  801.                     for (String logEvent : logEvents) {
  802.                         String prefixLog = AlarmLogger.buildPrefix(threadName,allarme.getAlias(),allarme.getNome());
  803.                         alarmLogger.debug(prefixLog+logEvent);
  804.                     }
  805.                 }
  806.                 alarmLogger.debug(prefix+"notifica via script completata");
  807.             }
  808.         }  
  809.         catch( Exception e) {
  810.             alarmLogger.error(prefix+"notifica via script fallita: "+e.getMessage(),e);
  811.             scriptInvocationError = e.getMessage();
  812.             listExceptions.add(e);
  813.         }
  814.        
  815.         if(!listExceptions.isEmpty()) {
  816.             AlarmNotifyException ane = null;
  817.             if(listExceptions.size()==1) {
  818.                 Exception e = listExceptions.get(0);
  819.                 ane = new AlarmNotifyException(e.getMessage(),e);
  820.             }
  821.             else {
  822.                 org.openspcoop2.utils.UtilsMultiException multi = new UtilsMultiException(listExceptions.toArray(new Exception[listExceptions.size()]));
  823.                 ane = new AlarmNotifyException("Notifiche di cambio stato fallite",multi);
  824.             }
  825.             ane.setPluginInvocationError(pluginInvocationError);
  826.             ane.setSendMailError(sendMailError);
  827.             ane.setScriptInvocationError(scriptInvocationError);
  828.             throw ane;
  829.         }
  830.     }
  831.    
  832.     protected static void registraNotifica(AlarmLogger alarmLogger, Allarme allarme, AlarmStatus oldStatoAllarme, AlarmStatus newStatoAllarme, AllarmeHistory repositoryHistory,
  833.             IServiceManager allarmiSM) throws AlarmException {
  834.         try {
  835.             IAllarmeNotificaService allarmeNotificaSearchDAO = allarmiSM
  836.                     .getAllarmeNotificaService();
  837.            
  838.             AllarmeNotifica notifica = new AllarmeNotifica();
  839.            
  840.             notifica.setDataNotifica(DateManager.getDate());
  841.            
  842.             IdAllarme idAllarme = allarmiSM.getAllarmeServiceSearch().convertToId(allarme);
  843.             notifica.setIdAllarme(idAllarme);
  844.            
  845.             notifica.setOldStato(AllarmiConverterUtils.toIntegerValue(StatoAllarme.valueOf(oldStatoAllarme.getStatus().name())));
  846.             notifica.setOldDettaglioStato(oldStatoAllarme.getDetail());
  847.            
  848.             notifica.setNuovoStato(AllarmiConverterUtils.toIntegerValue(StatoAllarme.valueOf(newStatoAllarme.getStatus().name())));
  849.             notifica.setNuovoDettaglioStato(newStatoAllarme.getDetail());
  850.            
  851.             if(repositoryHistory!=null) {
  852.                 org.openspcoop2.core.allarmi.utils.serializer.JaxbSerializer serializer = new org.openspcoop2.core.allarmi.utils.serializer.JaxbSerializer();
  853.                 notifica.setHistoryEntry(serializer.toString(repositoryHistory));
  854.             }
  855.             allarmeNotificaSearchDAO.create(notifica);
  856.            
  857.         } catch (Exception e) {
  858.             alarmLogger.error(
  859.                     "Registrazione notifica di cambio stato fallita: "
  860.                             + e.getMessage(), e);
  861.             throw new AlarmException(e.getMessage(),e);
  862.         }
  863.     }
  864. }