TimerGestoreOperazioniRemoteLib.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.proxy;


  21. import java.util.Date;
  22. import java.util.List;

  23. import org.openspcoop2.core.commons.CoreException;
  24. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  25. import org.openspcoop2.pdd.core.CostantiPdD;
  26. import org.openspcoop2.pdd.core.jmx.JMXUtils;
  27. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  28. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  29. import org.openspcoop2.pdd.services.OpenSPCoop2Startup;
  30. import org.openspcoop2.pdd.services.connector.Proxy;
  31. import org.openspcoop2.pdd.services.connector.proxy.IProxyOperationService;
  32. import org.openspcoop2.pdd.services.connector.proxy.ProxyOperation;
  33. import org.openspcoop2.pdd.timers.TimerException;
  34. import org.openspcoop2.pdd.timers.TimerMonitoraggioRisorseThread;
  35. import org.openspcoop2.pdd.timers.TimerState;
  36. import org.openspcoop2.utils.Utilities;
  37. import org.openspcoop2.utils.date.DateManager;
  38. import org.openspcoop2.utils.transport.http.HttpResponse;
  39. import org.slf4j.Logger;


  40. /**    
  41.  * TimerGestoreOperazioniRemoteLib
  42.  *
  43.  * @author Poli Andrea (poli@link.it)
  44.  * @author $Author$
  45.  * @version $Rev$, $Date$
  46.  */
  47. public class TimerGestoreOperazioniRemoteLib {

  48.     private static TimerState state = TimerState.OFF; // abilitato in OpenSPCoop2Startup al momento dell'avvio
  49.     public static TimerState getState() {
  50.         return state;
  51.     }
  52.     public static void setState(TimerState stateParam) {
  53.         state = stateParam;
  54.     }
  55.    
  56.     private OpenSPCoop2Properties op2Properties;
  57.     private String tipoDatabase = null;
  58.    
  59.     private Logger logCore = null;
  60.     private Logger logTimer = null;
  61.     private MsgDiagnostico msgDiag = null;
  62.    
  63.     private void logCoreInfo(String msg) {
  64.         if(this.logCore!=null) {
  65.             this.logCore.info(msg);
  66.         }
  67.     }
  68.    
  69.     private void logTimerError(String msgErrore, Throwable e) {
  70.         if(this.logTimer!=null) {
  71.             this.logTimer.error(msgErrore,e);
  72.         }
  73.     }
  74.     private void logTimerError(String msgErrore) {
  75.         if(this.logTimer!=null) {
  76.             this.logTimer.error(msgErrore);
  77.         }
  78.     }
  79.     private void logTimerInfo(String msg) {
  80.         if(this.logTimer!=null) {
  81.             this.logTimer.info(msg);
  82.         }
  83.     }

  84.     private Date dataUltimoAggiornamento;
  85.     private Date now;
  86.    
  87.     private int limit;
  88.    
  89.     private IProxyOperationService proxyOperationService;

  90.     private String urlPrefix;
  91.    
  92.     /** Costruttore */
  93.     public TimerGestoreOperazioniRemoteLib(Logger logTimer, MsgDiagnostico msgDiag,
  94.             IProxyOperationService proxyOperationService,
  95.             Date now, Date dataUltimoAggiornamento, String urlPrefix) throws TimerException{
  96.        
  97.         this.op2Properties = OpenSPCoop2Properties.getInstance();
  98.         this.tipoDatabase = this.op2Properties.getDatabaseType();
  99.         if(this.tipoDatabase==null){
  100.             throw new TimerException("Tipo Database non definito");
  101.         }
  102.        
  103.         boolean debug = this.op2Properties.isProxyReadJMXResourcesAsyncProcessByTimerDebug();
  104.        
  105.         this.logCore = OpenSPCoop2Logger.getLoggerOpenSPCoopGestoreOperazioniRemote(debug);
  106.         this.logTimer = logTimer;
  107.         this.msgDiag = msgDiag;
  108.        
  109.         this.dataUltimoAggiornamento = dataUltimoAggiornamento;
  110.         this.now = now;
  111.        
  112.         this.urlPrefix = urlPrefix;
  113.            
  114.         this.limit = this.op2Properties.getProxyReadJMXResourcesAsyncProcessByTimerLimit();
  115.        
  116.         this.proxyOperationService = proxyOperationService;
  117.        
  118.     }
  119.    
  120.     public void check() throws TimerException {
  121.        
  122.         // Controllo che il sistema non sia andando in shutdown
  123.         if(OpenSPCoop2Startup.contextDestroyed){
  124.             this.logTimerError("["+TimerGestoreOperazioniRemote.ID_MODULO+"] Rilevato sistema in shutdown");
  125.             return;
  126.         }

  127.         // Controllo che l'inizializzazione corretta delle risorse sia effettuata
  128.         if(!OpenSPCoop2Startup.initialize){
  129.             this.msgDiag.logFatalError("inizializzazione di OpenSPCoop non effettuata", "Check Inizializzazione");
  130.             String msgErrore = "Riscontrato errore: inizializzazione del Timer o di OpenSPCoop non effettuata";
  131.             this.logTimerError(msgErrore);
  132.             throw new TimerException(msgErrore);
  133.         }

  134.         // Controllo risorse di sistema disponibili
  135.         if( !TimerMonitoraggioRisorseThread.isRisorseDisponibili()){
  136.             this.logTimerError("["+TimerGestoreOperazioniRemote.ID_MODULO+"] Risorse di sistema non disponibili: "+TimerMonitoraggioRisorseThread.getRisorsaNonDisponibile().getMessage(),TimerMonitoraggioRisorseThread.getRisorsaNonDisponibile());
  137.             return;
  138.         }
  139.         if( !MsgDiagnostico.gestoreDiagnosticaDisponibile){
  140.             this.logTimerError("["+TimerGestoreOperazioniRemote.ID_MODULO+"] Sistema di diagnostica non disponibile: "+MsgDiagnostico.motivoMalfunzionamentoDiagnostici.getMessage(),MsgDiagnostico.motivoMalfunzionamentoDiagnostici);
  141.             return;
  142.         }
  143.        
  144.         boolean enabled = TimerState.ENABLED.equals(TimerGestoreOperazioniRemoteLib.state);
  145.         if(!enabled) {
  146.             emitDiagnosticLog("disabilitato");
  147.             return;
  148.         }
  149.        
  150.         emitDiagnosticLog("letturaOperazioni");

  151.         long startControlloTimer = DateManager.getTimeMillis();
  152.            
  153.         try{

  154.             int offset = 0;
  155.             int op = process(offset);
  156.             while (op>0) {
  157.                 offset = offset + op;
  158.                 op = process(offset);
  159.             }
  160.            
  161.             // end
  162.             long endControlloTimer = DateManager.getTimeMillis();
  163.             long diff = (endControlloTimer-startControlloTimer);
  164.             this.logTimerInfo("Gestione operazioni remote terminata in "+Utilities.convertSystemTimeIntoStringMillisecondi(diff, true));
  165.            
  166.            
  167.         }
  168.         catch (Exception e) {
  169.             this.msgDiag.logErroreGenerico(e,"TimerGestoreOperazioniRemoteLib");
  170.             this.logTimerError("Riscontrato errore durante la gestione delle operazioni remote: "+ e.getMessage(),e);
  171.         }
  172.            
  173.     }

  174.     private int process(int offset) throws CoreException {
  175.        
  176.         this.msgDiag.addKeyword(CostantiPdD.KEY_OFFSET, offset+"");
  177.         this.msgDiag.addKeyword(CostantiPdD.KEY_LIMIT, this.limit+"");
  178.        
  179.         try {
  180.             long startGenerazione = DateManager.getTimeMillis();
  181.            
  182.             emitDiagnosticLog("gestioneOperazioni.inCorso");
  183.            
  184.             List<ProxyOperation> list = this.proxyOperationService.next(this.dataUltimoAggiornamento, this.now, offset, this.limit);
  185.            
  186.             int op = 0;
  187.             if(list==null || list.isEmpty()) {
  188.                 op = 0;
  189.             }
  190.             else {
  191.                 op = list.size();
  192.             }
  193.             this.msgDiag.addKeyword(CostantiPdD.KEY_NUMERO_OPERAZIONI, op+"");
  194.             emitDiagnosticLog("gestioneOperazioni.analisi");
  195.            
  196.             if(op>0) {
  197.                 for (ProxyOperation proxyOperation : list) {
  198.                     gestioneOperazione(proxyOperation);
  199.                 }
  200.             }
  201.            
  202.             long endGenerazione = DateManager.getTimeMillis();
  203.             String tempoImpiegato = Utilities.convertSystemTimeIntoStringMillisecondi((endGenerazione-startGenerazione), true);
  204.             this.msgDiag.addKeyword(CostantiPdD.KEY_TEMPO_GESTIONE, tempoImpiegato);
  205.             emitDiagnosticLog("gestioneOperazioni.effettuata");
  206.            
  207.             return op;
  208.            
  209.         }catch(Exception e) {
  210.             this.msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, e.getMessage());
  211.             emitDiagnosticLog("gestioneOperazioni.fallita");
  212.             return -1;
  213.         }
  214.     }
  215.    
  216.     private void gestioneOperazione(ProxyOperation proxyOperation) {
  217.        
  218.         String dettaglioOperazione = proxyOperation.getDescription()+" (command: "+proxyOperation.getCommand()+")";
  219.         this.msgDiag.addKeyword(CostantiPdD.KEY_DATI_OPERAZIONE, dettaglioOperazione+"");
  220.        
  221.         try {
  222.             String stato = null;
  223.            
  224.             String url = this.urlPrefix + proxyOperation.getCommand();
  225.            
  226.             // Https
  227.             boolean https = this.op2Properties.isProxyReadJMXResourcesHttpsEnabled();
  228.             boolean verificaHostname = false;
  229.             boolean autenticazioneServer = false;
  230.             String autenticazioneServerPath = null;
  231.             String autenticazioneServerType = null;
  232.             String autenticazioneServerPassword = null;
  233.             if(https) {
  234.                 verificaHostname = this.op2Properties.isProxyReadJMXResourcesHttpsEnabledVerificaHostName();
  235.                 autenticazioneServer = this.op2Properties.isProxyReadJMXResourcesHttpsEnabledAutenticazioneServer();
  236.                 if(autenticazioneServer) {
  237.                     autenticazioneServerPath = this.op2Properties.getProxyReadJMXResourcesHttpsEnabledAutenticazioneServerTruststorePath();
  238.                     autenticazioneServerType = this.op2Properties.getProxyReadJMXResourcesHttpsEnabledAutenticazioneServerTruststoreType();
  239.                     autenticazioneServerPassword = this.op2Properties.getProxyReadJMXResourcesHttpsEnabledAutenticazioneServerTruststorePassword();
  240.                 }
  241.             }
  242.            
  243.             // Timeout
  244.             int readTimeout = this.op2Properties.getProxyReadJMXResourcesReadTimeout();
  245.             int connectTimeout = this.op2Properties.getProxyReadJMXResourcesConnectionTimeout();
  246.            
  247.             // Vengono utilizzate le credenziali del servizio check che dovranno essere uguali su tutti i nodi
  248.             String usernameCheck = this.op2Properties.getCheckReadJMXResourcesUsername();
  249.             String passwordCheck = this.op2Properties.getCheckReadJMXResourcesPassword();
  250.            
  251.             HttpResponse httpResponse = Proxy.invokeHttp(url,
  252.                     readTimeout, connectTimeout,
  253.                     usernameCheck, passwordCheck,
  254.                     https, verificaHostname, autenticazioneServer,
  255.                     autenticazioneServerPath, autenticazioneServerType,  autenticazioneServerPassword);
  256.            
  257.             String sResponse = null;
  258.             if(httpResponse.getContent()!=null) {
  259.                 sResponse = new String(httpResponse.getContent());
  260.             }
  261.             boolean error = sResponse!=null && sResponse.startsWith(JMXUtils.MSG_OPERAZIONE_NON_EFFETTUATA);
  262.            
  263.             if(httpResponse.getResultHTTPOperation()==200 && !error) {
  264.                 stato = "Success";
  265.             }
  266.             else {
  267.                 stato = "Failed";
  268.             }
  269.             stato = stato+(sResponse!=null ? "; "+sResponse : "");
  270.            
  271.             this.msgDiag.addKeyword(CostantiPdD.KEY_DETTAGLI_OPERAZIONE, stato);
  272.             emitDiagnosticLog("gestioneOperazioni.operazione");
  273.            
  274.         }catch(Exception e) {
  275.             this.msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, e.getMessage());
  276.             emitDiagnosticLog("gestioneOperazioni.operazione.fallita");
  277.         }
  278.        
  279.     }

  280.     private void emitDiagnosticLog(String code) {
  281.         this.msgDiag.logPersonalizzato(code);
  282.         String msg = this.msgDiag.getMessaggio_replaceKeywords(code);
  283.         emitLog(msg);
  284.     }
  285.     private void emitLog(String msg) {
  286.         this.logCoreInfo(msg);
  287.         this.logTimerInfo(msg);
  288.     }
  289.    
  290.    
  291. }