TimerGestoreCacheChiaviPDNDLib.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.pdnd;


  21. import java.sql.Connection;
  22. import java.util.List;

  23. import org.openspcoop2.core.commons.CoreException;
  24. import org.openspcoop2.core.config.driver.db.DriverConfigurazioneDB;
  25. import org.openspcoop2.pdd.config.ConfigurazionePdDReader;
  26. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  27. import org.openspcoop2.pdd.core.CostantiPdD;
  28. import org.openspcoop2.pdd.core.keystore.RemoteStoreProviderDriverUtils;
  29. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  30. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  31. import org.openspcoop2.pdd.services.OpenSPCoop2Startup;
  32. import org.openspcoop2.pdd.timers.TimerException;
  33. import org.openspcoop2.pdd.timers.TimerMonitoraggioRisorseThread;
  34. import org.openspcoop2.pdd.timers.TimerState;
  35. import org.openspcoop2.security.SecurityException;
  36. import org.openspcoop2.security.keystore.cache.GestoreKeystoreCache;
  37. import org.openspcoop2.security.keystore.cache.RemoteStoreCache;
  38. import org.openspcoop2.utils.Utilities;
  39. import org.openspcoop2.utils.certificate.remote.RemoteKeyType;
  40. import org.openspcoop2.utils.certificate.remote.RemoteStoreConfig;
  41. import org.openspcoop2.utils.date.DateManager;
  42. import org.slf4j.Logger;


  43. /**    
  44.  * TimerGestoreCacheChiaviPDNDLib
  45.  *
  46.  * @author Poli Andrea (poli@link.it)
  47.  * @author $Author$
  48.  * @version $Rev$, $Date$
  49.  */
  50. public class TimerGestoreCacheChiaviPDNDLib {

  51.     private static TimerState state = TimerState.OFF; // abilitato in OpenSPCoop2Startup al momento dell'avvio
  52.     public static TimerState getState() {
  53.         return state;
  54.     }
  55.     public static void setState(TimerState stateParam) {
  56.         state = stateParam;
  57.     }
  58.    
  59.     private OpenSPCoop2Properties op2Properties;
  60.     private String tipoDatabase = null;
  61.    
  62.     private Logger logCore = null;
  63.     private Logger logTimer = null;
  64.     private MsgDiagnostico msgDiag = null;
  65.    
  66.     private void logCoreInfo(String msg) {
  67.         if(this.logCore!=null) {
  68.             this.logCore.info(msg);
  69.         }
  70.     }
  71.    
  72.     private void logTimerError(String msgErrore, Throwable e) {
  73.         if(this.logTimer!=null) {
  74.             this.logTimer.error(msgErrore,e);
  75.         }
  76.     }
  77.     private void logTimerError(String msgErrore) {
  78.         if(this.logTimer!=null) {
  79.             this.logTimer.error(msgErrore);
  80.         }
  81.     }
  82.     private void logTimerInfo(String msg) {
  83.         if(this.logTimer!=null) {
  84.             this.logTimer.info(msg);
  85.         }
  86.     }
  87.     private void logTimerDebug(String msg) {
  88.         if(this.logTimer!=null) {
  89.             this.logTimer.debug(msg);
  90.         }
  91.     }
  92.    
  93.     private RemoteStoreConfig remoteStore;
  94.     private RemoteKeyType remoteKeyType;
  95.    
  96.    
  97.     /** Costruttore */
  98.     public TimerGestoreCacheChiaviPDNDLib(Logger logTimer, MsgDiagnostico msgDiag, RemoteStoreConfig remoteStore, RemoteKeyType remoteKeyType) throws TimerException{
  99.        
  100.         this.op2Properties = OpenSPCoop2Properties.getInstance();
  101.         this.tipoDatabase = this.op2Properties.getDatabaseType();
  102.         if(this.tipoDatabase==null){
  103.             throw new TimerException("Tipo Database non definito");
  104.         }
  105.        
  106.         boolean debug = this.op2Properties.isGestoreChiaviPDNDDebug();
  107.        
  108.         this.logCore = OpenSPCoop2Logger.getLoggerOpenSPCoopGestoreChiaviPDND(debug);
  109.         this.logTimer = logTimer;
  110.         this.msgDiag = msgDiag;
  111.        
  112.         this.remoteStore = remoteStore;
  113.         this.remoteKeyType = remoteKeyType;    
  114.     }
  115.    
  116.     public void check() throws TimerException {
  117.        
  118.         // Controllo che il sistema non sia andando in shutdown
  119.         if(OpenSPCoop2Startup.contextDestroyed){
  120.             this.logTimerError("["+TimerGestoreCacheChiaviPDND.ID_MODULO+"] Rilevato sistema in shutdown");
  121.             return;
  122.         }

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

  130.         // Controllo risorse di sistema disponibili
  131.         if( !TimerMonitoraggioRisorseThread.isRisorseDisponibili()){
  132.             this.logTimerError("["+TimerGestoreCacheChiaviPDND.ID_MODULO+"] Risorse di sistema non disponibili: "+TimerMonitoraggioRisorseThread.getRisorsaNonDisponibile().getMessage(),TimerMonitoraggioRisorseThread.getRisorsaNonDisponibile());
  133.             return;
  134.         }
  135.         if( !MsgDiagnostico.gestoreDiagnosticaDisponibile){
  136.             this.logTimerError("["+TimerGestoreCacheChiaviPDND.ID_MODULO+"] Sistema di diagnostica non disponibile: "+MsgDiagnostico.motivoMalfunzionamentoDiagnostici.getMessage(),MsgDiagnostico.motivoMalfunzionamentoDiagnostici);
  137.             return;
  138.         }
  139.        
  140.         boolean enabled = TimerState.ENABLED.equals(TimerGestoreCacheChiaviPDNDLib.state);
  141.         if(!enabled) {
  142.             this.msgDiag.addKeyword(CostantiPdD.KEY_REMOTE_STORE, "-");
  143.             emitDiagnosticLog("disabilitato");
  144.             return;
  145.         }
  146.        
  147.         emitDiagnosticLog("letturaCacheKeys");

  148.         long startControlloTimer = DateManager.getTimeMillis();
  149.            
  150.         long idStore = -1;
  151.        
  152.         DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection = null;
  153.         try{
  154.             Object oConfig = ConfigurazionePdDReader.getDriverConfigurazionePdD();
  155.             if(oConfig instanceof DriverConfigurazioneDB) {
  156.                 driverConfigurazioneDbGestoreConnection = (DriverConfigurazioneDB) oConfig;
  157.             }
  158.             else {
  159.                 throw new TimerException("Gestore utilizzabile solamente con una configurazione su database");
  160.             }
  161.         }
  162.         catch (Exception e) {
  163.             this.msgDiag.logErroreGenerico(e,TimerGestoreCacheChiaviPDND.ID_MODULO);
  164.             this.logTimerError("Riscontrato errore durante la gestione della cache delle chavi della PDND: "+ e.getMessage(),e);
  165.             return;
  166.         }
  167.        
  168.         idStore = getIdStore(driverConfigurazioneDbGestoreConnection);
  169.         if(idStore<=0) {
  170.             emitDiagnosticLog("letturaCacheKeys.nonNecessaria");
  171.             return;
  172.         }
  173.                
  174.         try{
  175.             process(startControlloTimer, idStore, driverConfigurazioneDbGestoreConnection);
  176.         }catch (Exception e) {
  177.             this.msgDiag.logErroreGenerico(e,TimerGestoreCacheChiaviPDND.ID_MODULO);
  178.             this.logTimerError("Riscontrato errore durante la gestione della cache delle chavi della PDND: "+ e.getMessage(),e);
  179.         }
  180.     }
  181.    
  182.     private long getIdStore(DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection) {
  183.         Connection conConfigurazione = null;
  184.         String method = TimerGestoreCacheChiaviPDND.ID_MODULO+".getIdStore";
  185.         try{

  186.             conConfigurazione = driverConfigurazioneDbGestoreConnection.getConnection(method);
  187.             if(conConfigurazione == null) {
  188.                 throw new TimerException(TimerGestoreChiaviPDND.CONNESSIONE_NON_DISPONIBILE);  
  189.             }
  190.            
  191.             return RemoteStoreProviderDriverUtils.getIdRemoteStore(conConfigurazione, this.tipoDatabase, this.remoteStore);        
  192.         }
  193.         catch (Exception e) {
  194.             this.msgDiag.logErroreGenerico(e,TimerGestoreCacheChiaviPDND.ID_MODULO);
  195.             this.logTimerError("Riscontrato errore durante la gestione della cache delle chavi della PDND (read idStore): "+ e.getMessage(),e);
  196.             return -1;
  197.         }finally{
  198.             try{
  199.                 if(conConfigurazione!=null)
  200.                     driverConfigurazioneDbGestoreConnection.releaseConnection(method, conConfigurazione);
  201.             }catch(Exception eClose){
  202.                 // ignore
  203.             }
  204.         }
  205.     }
  206.    
  207.     private void process(long startControlloTimer, long idStore, DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection) throws SecurityException, CoreException, TimerException {
  208.         // NOTA: non viene eliminato dalla cache di primo livello "GestoreRichieste" poichè:
  209.         // - per default i remote store non sono salvati nella cache di primo livello, vedi proprietà 'org.openspcoop2.pdd.cache.impl.requestManager.remoteStore.saveInCache' di govway.properties
  210.         // - se vengono salvati, il tempo di vita di questi elementi deve essere più basso rispetto alle normali cache (per default è 30 secondi)
  211.        
  212.         List<String> keys = GestoreKeystoreCache.keysRemoteStore();
  213.         int sizeCacheKeys = keys!=null ? keys.size() : 0;
  214.         int size = 0;
  215.         if(sizeCacheKeys>0) {
  216.             for (String key : keys) {
  217.                
  218.                 String keyCachePrefix = RemoteStoreCache.RESTORE_STORE_PREFIX+ RemoteStoreCache.getPrefixKeyCache(this.remoteStore, this.remoteKeyType);
  219.                 if(key!=null && key.startsWith(keyCachePrefix) && key.length()>keyCachePrefix.length()) {
  220.                     size++;
  221.                     String kid = key.substring(keyCachePrefix.length());
  222.                     if(!existsRemoteStoreKey(driverConfigurazioneDbGestoreConnection, idStore, kid)) {
  223.                         removeFromCache(key, kid);
  224.                     }
  225.                    
  226.                 }
  227.                
  228.             }
  229.         }

  230.         long endGenerazione = DateManager.getTimeMillis();
  231.         String tempoImpiegato = Utilities.convertSystemTimeIntoStringMillisecondi((endGenerazione-startControlloTimer), true);
  232.         this.msgDiag.addKeyword(CostantiPdD.KEY_TEMPO_GESTIONE, tempoImpiegato);
  233.        
  234.         this.msgDiag.addKeyword(CostantiPdD.KEY_NUMERO_EVENTI, size+"");
  235.        
  236.         emitDiagnosticLog("letturaCacheKeys.effettuata");
  237.     }
  238.    
  239.     private boolean existsRemoteStoreKey(DriverConfigurazioneDB driverConfigurazioneDbGestoreConnection, long idStore, String kid) throws TimerException {
  240.         Connection conConfigurazione = null;
  241.         String method = TimerGestoreCacheChiaviPDND.ID_MODULO+".existsRemoteStoreKey_"+idStore+"_"+kid;
  242.         try{

  243.             conConfigurazione = driverConfigurazioneDbGestoreConnection.getConnection(method);
  244.             if(conConfigurazione == null) {
  245.                 throw new TimerException(TimerGestoreChiaviPDND.CONNESSIONE_NON_DISPONIBILE);  
  246.             }
  247.            
  248.             return RemoteStoreProviderDriverUtils.existsRemoteStoreKey(conConfigurazione, this.tipoDatabase, idStore, kid, true);
  249.         }
  250.         catch (Exception e) {
  251.             throw new TimerException("existsRemoteStoreKey failed: "+e.getMessage());
  252.         }finally{
  253.             try{
  254.                 if(conConfigurazione!=null)
  255.                     driverConfigurazioneDbGestoreConnection.releaseConnection(method, conConfigurazione);
  256.             }catch(Exception eClose){
  257.                 // ignore
  258.             }
  259.         }
  260.     }

  261.     private void removeFromCache(String key, String kid) throws SecurityException, CoreException {
  262.         this.logTimerDebug("Elimino chiave '"+key+"' dalla cache");
  263.        
  264.         GestoreKeystoreCache.removeRemoteStore(null, kid, this.remoteKeyType, this.remoteStore);
  265.        
  266.         if(this.op2Properties.isGestoreChiaviPDNDclientInfoEnabled()) {
  267.             GestoreKeystoreCache.removeRemoteStoreClientInfo(null, kid, this.remoteStore);
  268.         }
  269.     }
  270.    
  271.     private void emitDiagnosticLog(String code) {
  272.         this.msgDiag.logPersonalizzato(code);
  273.         String msg = this.msgDiag.getMessaggio_replaceKeywords(code);
  274.         this.logCoreInfo(msg);
  275.         this.logTimerInfo(msg);
  276.     }
  277. }