PostgreSQLThreshold.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.core.threshold;

  21. import java.sql.Connection;
  22. import java.sql.ResultSet;
  23. import java.sql.SQLException;
  24. import java.sql.Statement;
  25. import java.util.Properties;

  26. import javax.sql.DataSource;
  27. import javax.naming.Context;
  28. import javax.naming.InitialContext;
  29. import javax.naming.NamingException;

  30. import org.openspcoop2.core.commons.CoreException;
  31. import org.openspcoop2.pdd.config.DBManager;
  32. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  33. import org.openspcoop2.pdd.config.Resource;
  34. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  35. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  36. import org.openspcoop2.protocol.basic.BasicComponentFactory;
  37. import org.openspcoop2.utils.jdbc.JDBCUtilities;

  38. /**
  39.  * Implementazione che definisce un meccanismo di Soglia sullo spazio libero rimasto
  40.  * nelle risorse utilizzate dalla PdD, per un database MySQL.
  41.  *  
  42.  * @author Andrea Manca (manca@link.it)
  43.  * @author $Author$
  44.  * @version $Rev$, $Date$
  45.  */


  46. public class PostgreSQLThreshold implements IThreshold {

  47.     private static OpenSPCoop2Properties properties = OpenSPCoop2Properties.getInstance();
  48.     public static final String ID_MODULO = "PostgreSQLThreshold";
  49.    
  50.    
  51.     /**
  52.      * @param parametri puo essere del tipo
  53.      *  "valore=<valore di soglia> [datasource=<nome datasource>]"
  54.      *  se nome datasource non e' indicato verra' utilizzata la connessione
  55.      *  verso il database openspcoop
  56.      *  
  57.      *  Il valore di soglia e' interpretato in byte a meno che non sia esplici
  58.      *  tamente indicata l'unita di misura.
  59.      *  NOTA: la query per il controllo dello spazio necessita dei diritti
  60.      *  di superutente per essere eseguita
  61.      */
  62.     @Override
  63.     public boolean check(Properties parametri) throws ThresholdException {
  64.         DBManager dbManager = DBManager.getInstance();
  65.         Resource resource = null;
  66.         long threshold=-1;
  67.         long size=0L;
  68.         long factor=1L;
  69.         boolean result=false;
  70.         Statement s=null;
  71.         ResultSet rs=null;
  72.        
  73.         String debugS = parametri.getProperty("debug");
  74.         boolean debug = false;
  75.         if(debugS!=null){
  76.             debug = Boolean.valueOf(debugS);
  77.         }
  78.        
  79.         String query = parametri.getProperty("query");
  80.         if(query==null){
  81.             throw new ThresholdException("Parametro 'query' non presente");
  82.         }
  83.        
  84.         String valoreSoglia = parametri.getProperty("valore");
  85.         if(valoreSoglia==null){
  86.             throw new ThresholdException("Parametro 'valore' non presente");
  87.         }
  88.         else{
  89.             valoreSoglia = valoreSoglia.trim();
  90.         }
  91.        
  92.         String datasource = parametri.getProperty("datasource");
  93.         if(datasource!=null){
  94.             datasource = datasource.trim();
  95.         }
  96.        
  97.         String soglia=valoreSoglia.toLowerCase();
  98.         StringBuilder valore=new StringBuilder();
  99.         char ch=soglia.charAt(0);
  100.         int i=1;
  101.         while (Character.isDigit(ch))
  102.         {
  103.             valore.append(ch);
  104.             if(i<soglia.length())
  105.                 ch=soglia.charAt(i++);
  106.             else
  107.                 ch='f';
  108.         }
  109.         if ( soglia.endsWith("kb") || soglia.endsWith("k") )
  110.             factor=1024L;
  111.         else if ( soglia.endsWith("mb") || soglia.endsWith("m") )
  112.             factor=1024L * 1024L;
  113.         else if ( soglia.endsWith("gb") || soglia.endsWith("g") )
  114.             factor=1024L * 1024L * 1024L;
  115.         //else
  116.             //Utilizzo del fattore di default 1
  117.        
  118.         MsgDiagnostico msgDiag = MsgDiagnostico.newInstance(PostgreSQLThreshold.ID_MODULO);
  119.         Connection connection =null;
  120.         try{
  121.             if(datasource==null) {
  122.                 resource = getConnection(dbManager);
  123.                 connection = (Connection) resource.getResource();
  124.             }
  125.             else
  126.             {
  127.                 connection = getConnection(datasource);
  128.             }

  129.             // controllo validita parametro
  130.             threshold=Long.parseLong(valore.toString())*factor;
  131.             if(threshold<0L)
  132.                 throw new CoreException("Valore di soglia negativo");
  133.            
  134.             //Interrogazione del database
  135.             s=connection.createStatement();
  136.             if(!s.execute(query))
  137.                 throw new CoreException("Impossibile verficare lo spazio occupato");
  138.            
  139.             rs=s.getResultSet();
  140.            
  141.             if(rs==null)
  142.                 throw new CoreException("Nessun risultato disponibile per la verifica di soglia");
  143.             if(!rs.next())
  144.                 throw new CoreException("Nessun risultato disponibile per la verifica di soglia");
  145.            
  146.             size=rs.getLong(1);
  147.             if(size==0)
  148.                 throw new CoreException("La quantita' di spazio occupata dai DB e' NULL");

  149.                        
  150.             result=(size<threshold);
  151.            
  152.         }catch(Exception e){
  153.             throw new ThresholdException("PostgreSQLThreshold error: "+e.getMessage(),e);
  154.         }finally{
  155.             JDBCUtilities.closeResources(rs, s);
  156.             rs=null;s=null;
  157.             try {
  158.                 if(datasource==null)
  159.                     dbManager.releaseResource(PostgreSQLThreshold.properties.getIdentitaPortaDefaultWithoutProtocol(), PostgreSQLThreshold.ID_MODULO, resource);
  160.                 else {
  161.                     if ((connection != null) && (!connection.isClosed()))
  162.                         JDBCUtilities.closeConnection(BasicComponentFactory.getCheckLogger(), connection, BasicComponentFactory.isCheckAutocommit(), BasicComponentFactory.isCheckIsClosed());
  163.                 }
  164.             }catch(SQLException ex){
  165.                 // ignore
  166.             }      
  167.         }
  168.        
  169.         String prefix = "";
  170.         if(datasource!=null) {
  171.             prefix = "["+datasource+"] ";
  172.         }
  173.         String msg = prefix+"Spazio occupato: "+size+"; soglia: "+result+"; risultato:"+(result?"ok":"ko");
  174.         if(debug) {
  175.             OpenSPCoop2Logger.getLoggerOpenSPCoopResources().info(msg);
  176.         }
  177.         msgDiag.highDebug(msg);
  178.        
  179.         return result;
  180.        
  181.     }
  182.    
  183.     private Resource getConnection(DBManager dbManager) throws CoreException {
  184.         Resource resource = null;
  185.         try{
  186.             resource = dbManager.getResource(PostgreSQLThreshold.properties.getIdentitaPortaDefaultWithoutProtocol(), PostgreSQLThreshold.ID_MODULO,null);
  187.         }catch(Exception e){
  188.             throw new CoreException("Impossibile ottenere una Risorsa dal DBManager",e);
  189.         }
  190.         if(resource==null)
  191.             throw new CoreException("Risorsa is null");
  192.         if(resource.getResource() == null)
  193.             throw new CoreException("Connessione is null");
  194.         return resource;
  195.     }
  196.     private Connection getConnection(String datasource) throws NamingException, SQLException {
  197.         Context c = new InitialContext();
  198.         DataSource ds= (DataSource)c.lookup(datasource);
  199.         c.close();  
  200.         return ds.getConnection();
  201.     }

  202. }