TimerStatisticheLib.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.pdd.timers;


  21. import java.sql.Connection;

  22. import org.openspcoop2.core.commons.dao.DAOFactory;
  23. import org.openspcoop2.core.commons.dao.DAOFactoryProperties;
  24. import org.openspcoop2.core.config.driver.IDriverConfigurazioneGet;
  25. import org.openspcoop2.core.config.driver.db.DriverConfigurazioneDB;
  26. import org.openspcoop2.core.statistiche.constants.TipoIntervalloStatistico;
  27. import org.openspcoop2.generic_project.utils.ServiceManagerProperties;
  28. import org.openspcoop2.monitor.engine.statistic.StatisticsConfig;
  29. import org.openspcoop2.monitor.engine.statistic.StatisticsLibrary;
  30. import org.openspcoop2.pdd.config.ConfigurazionePdDReader;
  31. import org.openspcoop2.pdd.config.DBStatisticheManager;
  32. import org.openspcoop2.pdd.config.DBTransazioniManager;
  33. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  34. import org.openspcoop2.pdd.config.Resource;
  35. import org.openspcoop2.pdd.core.CostantiPdD;
  36. import org.openspcoop2.pdd.core.GestoreMessaggi;
  37. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  38. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  39. import org.openspcoop2.pdd.services.OpenSPCoop2Startup;
  40. import org.openspcoop2.protocol.engine.ProtocolFactoryManager;
  41. import org.openspcoop2.protocol.engine.constants.Costanti;
  42. import org.openspcoop2.protocol.utils.ModIUtils;
  43. import org.openspcoop2.utils.TipiDatabase;
  44. import org.openspcoop2.utils.Utilities;
  45. import org.openspcoop2.utils.date.DateManager;
  46. import org.openspcoop2.utils.id.serial.InfoStatistics;
  47. import org.openspcoop2.utils.semaphore.Semaphore;
  48. import org.openspcoop2.utils.semaphore.SemaphoreConfiguration;
  49. import org.openspcoop2.utils.semaphore.SemaphoreMapping;
  50. import org.slf4j.Logger;


  51. /**    
  52.  * TimerStatisticheLib
  53.  *
  54.  * @author Poli Andrea (poli@link.it)
  55.  * @author $Author$
  56.  * @version $Rev$, $Date$
  57.  */
  58. public class TimerStatisticheLib {

  59.     private static TimerState STATE_STATISTICHE_ORARIE = TimerState.OFF; // abilitato in OpenSPCoop2Startup al momento dell'avvio
  60.     public static TimerState getSTATE_STATISTICHE_ORARIE() {
  61.         return STATE_STATISTICHE_ORARIE;
  62.     }
  63.     public static void setSTATE_STATISTICHE_ORARIE(TimerState sTATE_STATISTICHE_ORARIE) {
  64.         STATE_STATISTICHE_ORARIE = sTATE_STATISTICHE_ORARIE;
  65.     }

  66.     private static TimerState STATE_STATISTICHE_GIORNALIERE = TimerState.OFF; // abilitato in OpenSPCoop2Startup al momento dell'avvio
  67.     public static TimerState getSTATE_STATISTICHE_GIORNALIERE() {
  68.         return STATE_STATISTICHE_GIORNALIERE;
  69.     }
  70.     public static void setSTATE_STATISTICHE_GIORNALIERE(TimerState sTATE_STATISTICHE_GIORNALIERE) {
  71.         STATE_STATISTICHE_GIORNALIERE = sTATE_STATISTICHE_GIORNALIERE;
  72.     }

  73.     private static TimerState STATE_STATISTICHE_SETTIMANALI = TimerState.OFF; // abilitato in OpenSPCoop2Startup al momento dell'avvio
  74.     public static TimerState getSTATE_STATISTICHE_SETTIMANALI() {
  75.         return STATE_STATISTICHE_SETTIMANALI;
  76.     }
  77.     public static void setSTATE_STATISTICHE_SETTIMANALI(TimerState sTATE_STATISTICHE_SETTIMANALI) {
  78.         STATE_STATISTICHE_SETTIMANALI = sTATE_STATISTICHE_SETTIMANALI;
  79.     }

  80.     private static TimerState STATE_STATISTICHE_MENSILI = TimerState.OFF; // abilitato in OpenSPCoop2Startup al momento dell'avvio
  81.     public static TimerState getSTATE_STATISTICHE_MENSILI() {
  82.         return STATE_STATISTICHE_MENSILI;
  83.     }
  84.     public static void setSTATE_STATISTICHE_MENSILI(TimerState sTATE_STATISTICHE_MENSILI) {
  85.         STATE_STATISTICHE_MENSILI = sTATE_STATISTICHE_MENSILI;
  86.     }
  87.    
  88.     private static TimerState STATE_PDND_TRACCIAMENTO_PUBBLICAZIONE = TimerState.OFF; // abilitato in OpenSPCoop2Startup al momento dell'avvio
  89.     public static TimerState getSTATE_PDND_TRACCIAMENTO_PUBBLICAZIONE() {
  90.         return STATE_PDND_TRACCIAMENTO_PUBBLICAZIONE;
  91.     }
  92.     public static void setSTATE_PDND_TRACCIAMENTO_PUBBLICAZIONE(TimerState sTATE_PDND_TRACCIAMENTO_PUBBLICAZIONE) {
  93.         STATE_PDND_TRACCIAMENTO_PUBBLICAZIONE = sTATE_PDND_TRACCIAMENTO_PUBBLICAZIONE;
  94.     }

  95.     private static TimerState STATE_PDND_TRACCIAMENTO_GENERAZIONE = TimerState.OFF; // abilitato in OpenSPCoop2Startup al momento dell'avvio
  96.     public static TimerState getSTATE_PDND_TRACCIAMENTO_GENERAZIONE() {
  97.         return STATE_PDND_TRACCIAMENTO_GENERAZIONE;
  98.     }
  99.     public static void setSTATE_PDND_TRACCIAMENTO_GENERAZIONE(TimerState sTATE_PDND_TRACCIAMENTO_GENERAZIONE) {
  100.         STATE_PDND_TRACCIAMENTO_GENERAZIONE = sTATE_PDND_TRACCIAMENTO_GENERAZIONE;
  101.     }

  102.     /** Logger utilizzato per debug. */
  103.     private Logger logCore = null;
  104.     private Logger logSql = null;
  105.     private Logger logTimer = null;
  106.     private MsgDiagnostico msgDiag = null;

  107.     /** OpenSPCoop2Properties */
  108.     private OpenSPCoop2Properties op2Properties = null;
  109.    
  110.     /** Indicazione se devono essere generate le statistiche custom */
  111.     private boolean generazioneStatisticheCustom = false;
  112.     private boolean analisiTransazioniCustom = false;
  113.    
  114.     /** Indicazione se deve essere effettuato il log delle query */
  115.     private boolean debug = false;  
  116.    
  117.     /** Indicazione se deve essere usata la union per calcolare i tempi di latenza */
  118.     private boolean useUnionForLatency = false;
  119.    
  120.     /** Intervallo di attesa prima di passare al prossimo intervallo */
  121.     private long waitMsBeforeNextInterval = -1;
  122.    
  123.     /** Attesa che tutte le transazioni siano state consegnate con successo prima di passare al prossimo intervallo */
  124.     private boolean waitStatiInConsegna = false;
  125.    
  126.     /** Tipologie di statistiche */
  127.     private TipoIntervalloStatistico tipoStatistica;
  128.     private boolean statisticheOrarie = false;
  129.     private boolean statisticheGiornaliere = false;
  130.     private boolean statisticheSettimanali = false;
  131.     private boolean statisticheMensili = false;
  132.     private boolean tracciamentoPdndGenerazione = false;
  133.     private boolean tracciamentoPdndPubblicazione = false;
  134.    
  135.     /** Tipologie di statistiche: gestione ultimo intervallo */
  136.     private boolean statisticheOrarie_gestioneUltimoIntervallo = false;
  137.     private boolean statisticheGiornaliere_gestioneUltimoIntervallo = false;
  138.     private boolean statisticheSettimanali_gestioneUltimoIntervallo = false;
  139.     private boolean statisticheMensili_gestioneUltimoIntervallo = false;
  140.    
  141.     /** Database */
  142. //  private DataSource ds = null;
  143. //  private String datasource = null;
  144.     private String tipoDatabase = null; //tipoDatabase
  145.     private DAOFactory daoFactory = null;
  146.     private Logger daoFactoryLogger = null;
  147.     private ServiceManagerProperties daoFactoryServiceManagerPropertiesTransazioni = null;
  148.     private ServiceManagerProperties daoFactoryServiceManagerPropertiesStatistiche = null;
  149.     private ServiceManagerProperties daoFactoryServiceManagerPropertiesPluginsStatistiche = null;
  150.     private ServiceManagerProperties daoFactoryServiceManagerPropertiesPluginsBase = null;
  151.     private ServiceManagerProperties daoFactoryServiceManagerPropertiesUtils = null;
  152.     private ServiceManagerProperties daoFactoryServiceManagerPropertiesPluginsTransazioni = null;

  153.     /** StatisticsConfig */
  154.     private StatisticsConfig statisticsConfig;
  155.    
  156.     /** Timer */
  157.     private TimerLock timerLock = null;

  158.     /** Semaforo */
  159.     private Semaphore semaphore = null;
  160.     private InfoStatistics semaphore_statistics;

  161.    
  162.    
  163.     /** Costruttore */
  164.     public TimerStatisticheLib(TipoIntervalloStatistico tipoStatistica, MsgDiagnostico msgDiag,Logger logTimer,OpenSPCoop2Properties p) throws Exception{
  165.    
  166.         this.msgDiag = msgDiag;
  167.         this.op2Properties = p;
  168.        
  169.         this.debug = this.op2Properties.isStatisticheGenerazioneDebug();
  170.        
  171.         this.logCore = OpenSPCoop2Logger.getLoggerOpenSPCoopStatistiche(tipoStatistica, this.debug);
  172.         this.logSql = OpenSPCoop2Logger.getLoggerOpenSPCoopStatisticheSql(tipoStatistica, this.debug);
  173.         this.logTimer = logTimer;
  174.        
  175.         this.useUnionForLatency = this.op2Properties.isStatisticheGenerazioneUseUnionForLatency();
  176.         this.generazioneStatisticheCustom = this.op2Properties.isStatisticheGenerazioneCustomEnabled();
  177.         this.analisiTransazioniCustom = this.op2Properties.isStatisticheGenerazioneCustomSdkEnabled();
  178.        
  179.         this.tipoStatistica = tipoStatistica;
  180.        
  181.         switch (this.tipoStatistica) {
  182.         case STATISTICHE_ORARIE:
  183.             this.statisticheOrarie = this.op2Properties.isStatisticheGenerazioneBaseOrariaEnabled();
  184.             this.statisticheOrarie_gestioneUltimoIntervallo = this.op2Properties.isStatisticheGenerazioneBaseOrariaEnabledUltimaOra();
  185.             break;
  186.         case STATISTICHE_GIORNALIERE:
  187.             this.statisticheGiornaliere = this.op2Properties.isStatisticheGenerazioneBaseGiornalieraEnabled();
  188.             this.statisticheGiornaliere_gestioneUltimoIntervallo = this.op2Properties.isStatisticheGenerazioneBaseGiornalieraEnabledUltimoGiorno();
  189.             break;
  190.         case STATISTICHE_SETTIMANALI:
  191.             this.statisticheSettimanali = this.op2Properties.isStatisticheGenerazioneBaseSettimanaleEnabled();
  192.             this.statisticheSettimanali_gestioneUltimoIntervallo = this.op2Properties.isStatisticheGenerazioneBaseSettimanaleEnabledUltimaSettimana();
  193.             break;
  194.         case STATISTICHE_MENSILI:
  195.             this.statisticheMensili = this.op2Properties.isStatisticheGenerazioneBaseMensileEnabled();
  196.             this.statisticheMensili_gestioneUltimoIntervallo = this.op2Properties.isStatisticheGenerazioneBaseMensileEnabledUltimoMese();
  197.             break;
  198.         case PDND_GENERAZIONE_TRACCIAMENTO:
  199.             this.tracciamentoPdndGenerazione = this.op2Properties.isStatistichePdndTracciamentoGenerazioneEnabled();
  200.             break;
  201.         case PDND_PUBBLICAZIONE_TRACCIAMENTO:
  202.             this.tracciamentoPdndPubblicazione = this.op2Properties.isStatistichePdndTracciamentoPubblicazioneEnabled();
  203.             break;
  204.         }
  205.        
  206.         this.waitStatiInConsegna = this.op2Properties.isStatisticheGenerazioneAttendiCompletamentoTransazioniInFasiIntermedie();
  207.         this.waitMsBeforeNextInterval = this.op2Properties.getStatisticheGenerazioneTradeOffMs();
  208.                
  209.         try{
  210.            
  211.             // se avviato il thread le statistiche devono essere nella base dati delle transazioni (altrimenti si usa il batch)
  212.             this.tipoDatabase = this.op2Properties.getDatabaseType();
  213.             if(this.tipoDatabase==null){
  214.                 throw new Exception("Tipo Database non definito");
  215.             }
  216.            
  217.             String tipoDatabaseTransazioni = DBTransazioniManager.getInstance().getTipoDatabase();
  218.             if(tipoDatabaseTransazioni==null){
  219.                 throw new Exception("Tipo Database Transazioni non definito");
  220.             }

  221.             // Inizializzazione datasource
  222. //          GestoreJNDI jndi = new GestoreJNDI();
  223. //          this.ds = (DataSource) jndi.lookup(this.datasource);
  224.        
  225.             // DAOFactory
  226.             DAOFactoryProperties daoFactoryProperties = null;
  227.             this.daoFactoryLogger = this.logSql;
  228.             this.daoFactory = DAOFactory.getInstance(this.daoFactoryLogger);
  229.             daoFactoryProperties = DAOFactoryProperties.getInstance(this.daoFactoryLogger);
  230.            
  231.             this.daoFactoryServiceManagerPropertiesTransazioni =
  232.                     daoFactoryProperties.getServiceManagerProperties(org.openspcoop2.core.transazioni.utils.ProjectInfo.getInstance());
  233.             this.daoFactoryServiceManagerPropertiesTransazioni.setShowSql(this.debug);  
  234.             this.daoFactoryServiceManagerPropertiesTransazioni.setDatabaseType(tipoDatabaseTransazioni);
  235.            
  236.             this.daoFactoryServiceManagerPropertiesStatistiche =
  237.                     daoFactoryProperties.getServiceManagerProperties(org.openspcoop2.core.statistiche.utils.ProjectInfo.getInstance());
  238.             this.daoFactoryServiceManagerPropertiesStatistiche.setShowSql(this.debug);  
  239.             this.daoFactoryServiceManagerPropertiesStatistiche.setDatabaseType(tipoDatabaseTransazioni);
  240.            
  241.             if(this.generazioneStatisticheCustom){
  242.            
  243.                 this.daoFactoryServiceManagerPropertiesPluginsStatistiche =
  244.                         daoFactoryProperties.getServiceManagerProperties(org.openspcoop2.monitor.engine.config.statistiche.utils.ProjectInfo.getInstance());
  245.                 this.daoFactoryServiceManagerPropertiesPluginsStatistiche.setShowSql(this.debug);  
  246.                 this.daoFactoryServiceManagerPropertiesPluginsStatistiche.setDatabaseType(this.tipoDatabase);
  247.                
  248.                 this.daoFactoryServiceManagerPropertiesPluginsBase =
  249.                         daoFactoryProperties.getServiceManagerProperties(org.openspcoop2.core.plugins.utils.ProjectInfo.getInstance());
  250.                 this.daoFactoryServiceManagerPropertiesPluginsBase.setShowSql(this.debug);  
  251.                 this.daoFactoryServiceManagerPropertiesPluginsBase.setDatabaseType(this.tipoDatabase);
  252.                
  253.                 this.daoFactoryServiceManagerPropertiesUtils =
  254.                         daoFactoryProperties.getServiceManagerProperties(org.openspcoop2.core.commons.search.utils.ProjectInfo.getInstance());
  255.                 this.daoFactoryServiceManagerPropertiesUtils.setShowSql(this.debug);    
  256.                 this.daoFactoryServiceManagerPropertiesUtils.setDatabaseType(this.tipoDatabase);
  257.                
  258.                 if(this.analisiTransazioniCustom){
  259.                
  260.                     this.daoFactoryServiceManagerPropertiesPluginsTransazioni =
  261.                             daoFactoryProperties.getServiceManagerProperties(org.openspcoop2.monitor.engine.config.transazioni.utils.ProjectInfo.getInstance());
  262.                     this.daoFactoryServiceManagerPropertiesPluginsTransazioni.setShowSql(this.debug);  
  263.                     this.daoFactoryServiceManagerPropertiesPluginsTransazioni.setDatabaseType(this.tipoDatabase);
  264.                    
  265.                 }
  266.                
  267.             }
  268.                
  269.         }catch(Exception e){
  270.             throw new Exception("Errore durante l'inizializzazione del datasource: "+e.getMessage(),e);
  271.         }
  272.        
  273.        
  274.         try{
  275.             this.statisticsConfig = new StatisticsConfig(false);
  276.            
  277.             this.statisticsConfig.setLogCore(this.logCore);
  278.             this.statisticsConfig.setLogSql(this.logSql);
  279.             this.statisticsConfig.setGenerazioneStatisticheCustom(this.generazioneStatisticheCustom);
  280.             this.statisticsConfig.setAnalisiTransazioniCustom(this.analisiTransazioniCustom);
  281.             this.statisticsConfig.setDebug(this.debug);
  282.             this.statisticsConfig.setUseUnionForLatency(this.useUnionForLatency);
  283.             this.statisticsConfig.setStatisticheOrarie(this.statisticheOrarie);
  284.             this.statisticsConfig.setStatisticheGiornaliere(this.statisticheGiornaliere);
  285.             this.statisticsConfig.setStatisticheSettimanali(this.statisticheSettimanali);
  286.             this.statisticsConfig.setStatisticheMensili(this.statisticheMensili);
  287.             this.statisticsConfig.setStatisticheOrarieGestioneUltimoIntervallo(this.statisticheOrarie_gestioneUltimoIntervallo);
  288.             this.statisticsConfig.setStatisticheGiornaliereGestioneUltimoIntervallo(this.statisticheGiornaliere_gestioneUltimoIntervallo);
  289.             this.statisticsConfig.setStatisticheSettimanaliGestioneUltimoIntervallo(this.statisticheSettimanali_gestioneUltimoIntervallo);
  290.             this.statisticsConfig.setStatisticheMensiliGestioneUltimoIntervallo(this.statisticheMensili_gestioneUltimoIntervallo);
  291.             this.statisticsConfig.setWaitMsBeforeNextInterval(this.waitMsBeforeNextInterval);
  292.             this.statisticsConfig.setWaitStatiInConsegna(this.waitStatiInConsegna);
  293.            
  294.             if(ProtocolFactoryManager.getInstance().existsProtocolFactory(Costanti.MODIPA_PROTOCOL_NAME)
  295.                     &&
  296.                     ModIUtils.isTracingPDNDEnabled()) {
  297.                 this.statisticsConfig.setPdndTracciamentoGenerazione(this.tracciamentoPdndGenerazione);
  298.                 this.statisticsConfig.setPdndTracciamentoPubblicazione(this.tracciamentoPdndPubblicazione);
  299.             }
  300.             else {
  301.                 this.statisticsConfig.setPdndTracciamentoGenerazione(false);
  302.                 this.statisticsConfig.setPdndTracciamentoPubblicazione(false);
  303.             }
  304.             this.statisticsConfig.setPdndTracciamentoErogazioniEnabled(this.op2Properties.isStatistichePdndTracciamentoErogazioniEnabled());
  305.             this.statisticsConfig.setPdndTracciamentoFruizioniEnabled(this.op2Properties.isStatistichePdndTracciamentoFruizioniEnabled());
  306.             this.statisticsConfig.setPdndTracciamentoRequestConfig(this.op2Properties.getStatistichePdndTracciamentoHttpRequestConfig());
  307.             this.statisticsConfig.setPdndTracciamentoSoggettiEnabled(this.op2Properties.getStatistichePdndTracciamentoSoggettiEnabled());
  308.             this.statisticsConfig.setPdndTracciamentoSoggettiDisabled(this.op2Properties.isStatistichePdndTracciamentoSoggettiDisabled());
  309.             this.statisticsConfig.setPdndTracciamentoMaxAttempt(this.op2Properties.getStatistichePdndTracciamentoMaxAttempts());
  310.             this.statisticsConfig.setPdndTracciamentoPendingCheck(this.op2Properties.getStatistichePdndTracciamentoPendingCheck());
  311.         }catch(Exception e){
  312.             throw new Exception("Errore durante la generazione delle statistiche (InitConfigurazione): "+e.getMessage(),e);
  313.         }
  314.        
  315.         switch (this.tipoStatistica) {
  316.         case STATISTICHE_ORARIE:
  317.             this.timerLock = new TimerLock(TipoLock.GENERAZIONE_STATISTICHE_ORARIE);
  318.             break;
  319.         case STATISTICHE_GIORNALIERE:
  320.             this.timerLock = new TimerLock(TipoLock.GENERAZIONE_STATISTICHE_GIORNALIERE);
  321.             break;
  322.         case STATISTICHE_SETTIMANALI:
  323.             this.timerLock = new TimerLock(TipoLock.GENERAZIONE_STATISTICHE_SETTIMANALI);
  324.             break;
  325.         case STATISTICHE_MENSILI:
  326.             this.timerLock = new TimerLock(TipoLock.GENERAZIONE_STATISTICHE_MENSILI);
  327.             break;
  328.         case PDND_GENERAZIONE_TRACCIAMENTO:
  329.             this.timerLock = new TimerLock(TipoLock.GENERAZIONE_PDND_TRACCIAMENTO_GENERAZIONE);
  330.             break;
  331.         case PDND_PUBBLICAZIONE_TRACCIAMENTO:
  332.             this.timerLock = new TimerLock(TipoLock.GENERAZIONE_PDND_TRACCIAMENTO_PUBBLICAZIONE);
  333.             break;
  334.         }
  335.        
  336.         if(this.op2Properties.isTimerLockByDatabase()) {
  337.             this.semaphore_statistics = new InfoStatistics();

  338.             SemaphoreConfiguration config = GestoreMessaggi.newSemaphoreConfiguration(this.op2Properties.getStatisticheGenerazioneTimerLockMaxLife(),
  339.                     this.op2Properties.getStatisticheGenerazioneTimerLockIdleTime());

  340.             TipiDatabase databaseType = TipiDatabase.toEnumConstant(this.tipoDatabase);
  341.             try {
  342.                 this.semaphore = new Semaphore(this.semaphore_statistics, SemaphoreMapping.newInstance(this.timerLock.getIdLock()),
  343.                         config, databaseType, this.logTimer);
  344.             }catch(Exception e) {
  345.                 throw new TimerException(e.getMessage(),e);
  346.             }
  347.         }
  348.     }
  349.    
  350.     public void check() throws TimerException {
  351.        
  352.         // Controllo che il sistema non sia andando in shutdown
  353.         if(OpenSPCoop2Startup.contextDestroyed){
  354.             this.logTimer.error("["+TimerStatisticheThread.ID_MODULO+"] Rilevato sistema in shutdown");
  355.             return;
  356.         }

  357.         // Controllo che l'inizializzazione corretta delle risorse sia effettuata
  358.         if(!OpenSPCoop2Startup.initialize){
  359.             this.msgDiag.logFatalError("inizializzazione di OpenSPCoop non effettuata", "Check Inizializzazione");
  360.             String msgErrore = "Riscontrato errore: inizializzazione del Timer o di OpenSPCoop non effettuata";
  361.             this.logTimer.error(msgErrore);
  362.             throw new TimerException(msgErrore);
  363.         }

  364.         // Controllo risorse di sistema disponibili
  365.         if( !TimerMonitoraggioRisorseThread.isRisorseDisponibili()){
  366.             this.logTimer.error("["+TimerStatisticheThread.ID_MODULO+"] Risorse di sistema non disponibili: "+TimerMonitoraggioRisorseThread.getRisorsaNonDisponibile().getMessage(),TimerMonitoraggioRisorseThread.getRisorsaNonDisponibile());
  367.             return;
  368.         }
  369.         if( !MsgDiagnostico.gestoreDiagnosticaDisponibile){
  370.             this.logTimer.error("["+TimerStatisticheThread.ID_MODULO+"] Sistema di diagnostica non disponibile: "+MsgDiagnostico.motivoMalfunzionamentoDiagnostici.getMessage(),MsgDiagnostico.motivoMalfunzionamentoDiagnostici);
  371.             return;
  372.         }
  373.        
  374.         boolean enabled = false;
  375.         switch (this.tipoStatistica) {
  376.         case STATISTICHE_ORARIE:
  377.             enabled = TimerState.ENABLED.equals(STATE_STATISTICHE_ORARIE);
  378.             break;
  379.         case STATISTICHE_GIORNALIERE:
  380.             enabled = TimerState.ENABLED.equals(STATE_STATISTICHE_GIORNALIERE);
  381.             break;
  382.         case STATISTICHE_SETTIMANALI:
  383.             enabled = TimerState.ENABLED.equals(STATE_STATISTICHE_SETTIMANALI);
  384.             break;
  385.         case STATISTICHE_MENSILI:
  386.             enabled = TimerState.ENABLED.equals(STATE_STATISTICHE_MENSILI);
  387.             break;
  388.         case PDND_GENERAZIONE_TRACCIAMENTO:
  389.             enabled = TimerState.ENABLED.equals(STATE_PDND_TRACCIAMENTO_GENERAZIONE);
  390.             break;
  391.         case PDND_PUBBLICAZIONE_TRACCIAMENTO:
  392.             enabled = TimerState.ENABLED.equals(STATE_PDND_TRACCIAMENTO_PUBBLICAZIONE);
  393.             break;
  394.         }
  395.         if(!enabled) {
  396.             this.msgDiag.logPersonalizzato("disabilitato");
  397.             this.logCore.info(this.msgDiag.getMessaggio_replaceKeywords("disabilitato"));
  398.             this.logTimer.info(this.msgDiag.getMessaggio_replaceKeywords("disabilitato"));
  399.             return;
  400.         }
  401.        
  402.        
  403.        
  404.         this.msgDiag.logPersonalizzato("generazioneStatistiche");
  405.         this.logTimer.info(this.msgDiag.getMessaggio_replaceKeywords("generazioneStatistiche"));
  406.         long startControlloTimer = DateManager.getTimeMillis();
  407.            
  408.            
  409.         DBTransazioniManager dbTransazioniManager = null;
  410.         DBStatisticheManager dbStatisticheManager = null;
  411.         Resource rTransazioni = null;
  412.         Resource rStatistiche = null;
  413.         Connection conConfig = null;
  414.         DriverConfigurazioneDB driverConfigurazioneDB = null;
  415.         try{

  416.             dbTransazioniManager = DBTransazioniManager.getInstance();
  417.             rTransazioni = dbTransazioniManager.getResource(this.op2Properties.getIdentitaPortaDefaultWithoutProtocol(), TimerStatisticheThread.ID_MODULO, null);
  418.             if(rTransazioni==null){
  419.                 throw new Exception("Risorsa al database delle transazioni non disponibile");
  420.             }
  421.             Connection conTransazioni = (Connection) rTransazioni.getResource();
  422.             if(conTransazioni == null)
  423.                 throw new Exception("Connessione al database delle transazioni non disponibile");  

  424.             Connection conStatistiche = null;
  425.             if(this.op2Properties.isStatisticheUseTransazioniDatasource()) {
  426.                 conStatistiche = conTransazioni; // non prendo due connessioni per "atterrare" sul solito database
  427.             }
  428.             else if(this.op2Properties.isStatisticheUsePddRuntimeDatasource() && this.op2Properties.isTransazioniUsePddRuntimeDatasource()) {
  429.                 conStatistiche = conTransazioni; // non prendo due connessioni per "atterrare" sul solito database
  430.             }
  431.             else {
  432.                 dbStatisticheManager = DBStatisticheManager.getInstance();
  433.                 rStatistiche = dbStatisticheManager.getResource(this.op2Properties.getIdentitaPortaDefaultWithoutProtocol(), TimerStatisticheThread.ID_MODULO, null);
  434.                 if(rStatistiche==null){
  435.                     throw new Exception("Risorsa al database delle statistiche non disponibile");
  436.                 }
  437.                 conStatistiche = (Connection) rStatistiche.getResource();
  438.                 if(conStatistiche == null)
  439.                     throw new Exception("Connessione al database delle statistiche non disponibile");  
  440.             }
  441.            
  442.             org.openspcoop2.core.statistiche.dao.IServiceManager statisticheSM =
  443.                     (org.openspcoop2.core.statistiche.dao.IServiceManager)
  444.                     this.daoFactory.getServiceManager(org.openspcoop2.core.statistiche.utils.ProjectInfo.getInstance(), conStatistiche,
  445.                         this.daoFactoryServiceManagerPropertiesStatistiche, this.daoFactoryLogger);
  446.                
  447.             org.openspcoop2.core.transazioni.dao.IServiceManager transazioniSM =
  448.                     (org.openspcoop2.core.transazioni.dao.IServiceManager)
  449.                         this.daoFactory.getServiceManager(org.openspcoop2.core.transazioni.utils.ProjectInfo.getInstance(), conTransazioni,
  450.                         this.daoFactoryServiceManagerPropertiesTransazioni, this.daoFactoryLogger);
  451.            
  452.             org.openspcoop2.monitor.engine.config.statistiche.dao.IServiceManager pluginsStatisticheSM = null;
  453.             org.openspcoop2.core.plugins.dao.IServiceManager pluginsBaseSM = null;
  454.             org.openspcoop2.core.commons.search.dao.IServiceManager utilsSM = null;
  455.             org.openspcoop2.monitor.engine.config.transazioni.dao.IServiceManager pluginsTransazioniSM = null;
  456.             if(this.generazioneStatisticheCustom || this.tracciamentoPdndGenerazione || this.tracciamentoPdndPubblicazione){
  457.                
  458.                 IDriverConfigurazioneGet driverConfigurazione = ConfigurazionePdDReader.getDriverConfigurazionePdD();
  459.                 if(driverConfigurazione instanceof DriverConfigurazioneDB) {
  460.                     driverConfigurazioneDB = (DriverConfigurazioneDB) driverConfigurazione;
  461.                 }
  462.                 else {
  463.                     throw new Exception("La generazione delle statistiche custom richiede una configurazione di tipo 'db', trovato: "+driverConfigurazione.getClass().getName());
  464.                 }
  465.                 conConfig = driverConfigurazioneDB.getConnection(TimerStatisticheThread.ID_MODULO+".customStats");
  466.                
  467.                 pluginsStatisticheSM = (org.openspcoop2.monitor.engine.config.statistiche.dao.IServiceManager)
  468.                         this.daoFactory.getServiceManager(
  469.                                 org.openspcoop2.monitor.engine.config.statistiche.utils.ProjectInfo.getInstance(), conConfig,
  470.                                 this.daoFactoryServiceManagerPropertiesPluginsStatistiche, this.daoFactoryLogger);
  471.                 pluginsBaseSM = (org.openspcoop2.core.plugins.dao.IServiceManager)
  472.                         this.daoFactory.getServiceManager(
  473.                                 org.openspcoop2.core.plugins.utils.ProjectInfo.getInstance(), conConfig,
  474.                                 this.daoFactoryServiceManagerPropertiesPluginsBase, this.daoFactoryLogger);
  475.                 utilsSM = (org.openspcoop2.core.commons.search.dao.IServiceManager)
  476.                         this.daoFactory.getServiceManager(
  477.                                 org.openspcoop2.core.commons.search.utils.ProjectInfo.getInstance(), conConfig,
  478.                                 this.daoFactoryServiceManagerPropertiesUtils, this.daoFactoryLogger);
  479.                 if(this.analisiTransazioniCustom){
  480.                     pluginsTransazioniSM = (org.openspcoop2.monitor.engine.config.transazioni.dao.IServiceManager)
  481.                             this.daoFactory.getServiceManager(
  482.                                     org.openspcoop2.monitor.engine.config.transazioni.utils.ProjectInfo.getInstance(), conConfig,
  483.                                     this.daoFactoryServiceManagerPropertiesPluginsTransazioni, this.daoFactoryLogger);
  484.                 }
  485.             }
  486.            
  487.             // aggiorno configurazione per forceIndex
  488.             this.statisticsConfig.setForceIndexConfig(this.op2Properties.getStatisticheGenerazioneExternalForceIndexRepository());
  489.            
  490.             String causa = "Generazione Statistiche";
  491.             try {
  492.                 GestoreMessaggi.acquireLock(
  493.                         this.semaphore, conStatistiche, this.timerLock,
  494.                         this.msgDiag, causa,
  495.                         this.op2Properties.getStatisticheGenerazioneTimerLockAttesaAttiva(),
  496.                         this.op2Properties.getStatisticheGenerazioneTimerLockCheckInterval());
  497.                
  498.                 StatisticsLibrary sLibrary = new StatisticsLibrary(this.statisticsConfig, statisticheSM, transazioniSM,
  499.                         pluginsStatisticheSM, pluginsBaseSM, utilsSM, pluginsTransazioniSM);
  500.                
  501.                
  502.                 switch (this.tipoStatistica) {
  503.                 case STATISTICHE_ORARIE:
  504.                     if(generaStatistica("orario", conStatistiche, sLibrary, TipoIntervalloStatistico.STATISTICHE_ORARIE) == false) {
  505.                         return; // problemi con il lock
  506.                     }
  507.                     break;
  508.                 case STATISTICHE_GIORNALIERE:
  509.                     if(generaStatistica("giornaliero", conStatistiche, sLibrary, TipoIntervalloStatistico.STATISTICHE_GIORNALIERE) == false) {
  510.                         return; // problemi con il lock
  511.                     }
  512.                     break;
  513.                 case STATISTICHE_SETTIMANALI:
  514.                     if(generaStatistica("settimanale", conStatistiche, sLibrary, TipoIntervalloStatistico.STATISTICHE_SETTIMANALI) == false) {
  515.                         return; // problemi con il lock
  516.                     }
  517.                     break;
  518.                 case STATISTICHE_MENSILI:
  519.                     if(generaStatistica("mensile", conStatistiche, sLibrary, TipoIntervalloStatistico.STATISTICHE_MENSILI) == false) {
  520.                         return; // problemi con il lock
  521.                     }
  522.                     break;
  523.                 case PDND_GENERAZIONE_TRACCIAMENTO:
  524.                     if(!generaStatistica("pdnd tracciamento generazione", conStatistiche, sLibrary, TipoIntervalloStatistico.PDND_GENERAZIONE_TRACCIAMENTO)) {
  525.                         return; // problemi con il lock
  526.                     }
  527.                     break;
  528.                 case PDND_PUBBLICAZIONE_TRACCIAMENTO:
  529.                     if(!generaStatistica("pdnd pubblicazione generazione", conStatistiche, sLibrary, TipoIntervalloStatistico.PDND_PUBBLICAZIONE_TRACCIAMENTO)) {
  530.                         return; // problemi con il lock
  531.                     }
  532.                     break;
  533.                 }
  534.                
  535.                
  536.             }finally{
  537.                 try{
  538.                     GestoreMessaggi.releaseLock(
  539.                             this.semaphore, conStatistiche, this.timerLock,
  540.                             this.msgDiag, causa);
  541.                 }catch(Exception e){}
  542.             }
  543.            
  544.            
  545.            
  546.             // end
  547.             long endControlloTimer = DateManager.getTimeMillis();
  548.             long diff = (endControlloTimer-startControlloTimer);
  549.             this.logTimer.info("Generazione '"+this.tipoStatistica.getValue()+"' terminato in "+Utilities.convertSystemTimeIntoStringMillisecondi(diff, true));
  550.            
  551.            
  552.         }
  553.         catch(TimerLockNotAvailableException t) {
  554.             // msg diagnostico emesso durante l'emissione dell'eccezione
  555.             this.logTimer.info(t.getMessage(),t);
  556.         }
  557.         catch (Exception e) {
  558.             this.msgDiag.logErroreGenerico(e,"GenerazioneStatistiche");
  559.             this.logTimer.error("Riscontrato errore durante la generazione delle statistiche ("+this.tipoStatistica.getValue()+"): "+ e.getMessage(),e);
  560.         }finally{
  561.             try{
  562.                 if(rTransazioni!=null)
  563.                     dbTransazioniManager.releaseResource(this.op2Properties.getIdentitaPortaDefaultWithoutProtocol(), TimerStatisticheThread.ID_MODULO, rTransazioni);
  564.             }catch(Throwable eClose){}
  565.             try{
  566.                 if(rStatistiche!=null)
  567.                     dbStatisticheManager.releaseResource(this.op2Properties.getIdentitaPortaDefaultWithoutProtocol(), TimerStatisticheThread.ID_MODULO, rStatistiche);
  568.             }catch(Throwable eClose){}
  569.             try{
  570.                 if(conConfig!=null)
  571.                     driverConfigurazioneDB.releaseConnection(conConfig);
  572.             }catch(Throwable eClose){}
  573.         }
  574.            
  575.     }

  576.    
  577.     private boolean generaStatistica(String intervallo, Connection conStatistiche, StatisticsLibrary sLibrary, TipoIntervalloStatistico tipoIntervalloStatistico) {
  578.        
  579.         long startGenerazione = DateManager.getTimeMillis();
  580.         this.msgDiag.addKeyword(CostantiPdD.KEY_TIPO_STATISTICA, intervallo); // riferito a intervallo
  581.         this.msgDiag.logPersonalizzato("generazioneStatistiche.inCorso");
  582.         this.logTimer.info(this.msgDiag.getMessaggio_replaceKeywords("generazioneStatistiche.inCorso"));
  583.        
  584.         try{
  585.             GestoreMessaggi.updateLock(
  586.                     this.semaphore, conStatistiche, this.timerLock,
  587.                     this.msgDiag, "Generazione statistiche intervallo '"+intervallo+"' ...");
  588.         }catch(Throwable e){
  589.             this.msgDiag.logErroreGenerico(e,"TimerStatistiche-UpdateLock");
  590.             this.logTimer.error("TimerStatistiche-UpdateLock: "+e.getMessage(),e);
  591.             return false;
  592.         }
  593.        
  594.         switch (tipoIntervalloStatistico) {
  595.         case STATISTICHE_ORARIE:
  596.             sLibrary.generateStatisticaOraria();
  597.             break;
  598.         case STATISTICHE_GIORNALIERE:
  599.             sLibrary.generateStatisticaGiornaliera();
  600.             break;
  601.         case STATISTICHE_SETTIMANALI:
  602.             sLibrary.generateStatisticaSettimanale();
  603.             break;
  604.         case STATISTICHE_MENSILI:
  605.             sLibrary.generateStatisticaMensile();
  606.             break;
  607.         case PDND_GENERAZIONE_TRACCIAMENTO:
  608.             sLibrary.generatePdndGenerazioneTracciamento();
  609.             break;
  610.         case PDND_PUBBLICAZIONE_TRACCIAMENTO:
  611.             sLibrary.generatePdndPubblicazioneTracciamento();
  612.             break;
  613.         }  
  614.                
  615.         long endGenerazione = DateManager.getTimeMillis();
  616.         String tempoImpiegato = Utilities.convertSystemTimeIntoStringMillisecondi((endGenerazione-startGenerazione), true);
  617.         this.msgDiag.addKeyword(CostantiPdD.KEY_TEMPO_GENERAZIONE, tempoImpiegato);
  618.         this.msgDiag.logPersonalizzato("generazioneStatistiche.effettuata");
  619.         this.logTimer.info(this.msgDiag.getMessaggio_replaceKeywords("generazioneStatistiche.effettuata"));
  620.        
  621.         return true;
  622.     }
  623. }