Startup.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.core.config.rs.server.config;

  21. import java.io.File;
  22. import java.io.InputStream;
  23. import java.util.HashMap;
  24. import java.util.Map;
  25. import java.util.Properties;

  26. import javax.servlet.ServletContextEvent;
  27. import javax.servlet.ServletContextListener;

  28. import org.apache.commons.lang.StringUtils;
  29. import org.openspcoop2.core.commons.DBUtils;
  30. import org.openspcoop2.core.config.driver.ExtendedInfoManager;
  31. import org.openspcoop2.core.constants.CostantiDB;
  32. import org.openspcoop2.monitor.engine.alarm.AlarmConfigProperties;
  33. import org.openspcoop2.monitor.engine.alarm.AlarmEngineConfig;
  34. import org.openspcoop2.monitor.engine.alarm.AlarmManager;
  35. import org.openspcoop2.pdd.config.ConfigurazioneNodiRuntime;
  36. import org.openspcoop2.pdd.core.byok.BYOKMapProperties;
  37. import org.openspcoop2.pdd.core.dynamic.DynamicInfo;
  38. import org.openspcoop2.pdd.core.dynamic.DynamicUtils;
  39. import org.openspcoop2.pdd.services.ServicesUtils;
  40. import org.openspcoop2.protocol.engine.ProtocolFactoryManager;
  41. import org.openspcoop2.protocol.sdk.ConfigurazionePdD;
  42. import org.openspcoop2.protocol.utils.ModIUtils;
  43. import org.openspcoop2.utils.LoggerWrapperFactory;
  44. import org.openspcoop2.utils.UtilsRuntimeException;
  45. import org.openspcoop2.utils.certificate.byok.BYOKManager;
  46. import org.openspcoop2.utils.certificate.hsm.HSMManager;
  47. import org.openspcoop2.utils.certificate.hsm.HSMUtils;
  48. import org.openspcoop2.utils.certificate.ocsp.OCSPManager;
  49. import org.openspcoop2.utils.json.YamlSnakeLimits;
  50. import org.openspcoop2.utils.properties.MapProperties;
  51. import org.openspcoop2.utils.resources.Loader;
  52. import org.openspcoop2.utils.security.ProviderUtils;
  53. import org.openspcoop2.web.ctrlstat.core.Connettori;
  54. import org.openspcoop2.web.ctrlstat.core.ControlStationCore;
  55. import org.openspcoop2.web.ctrlstat.core.DBManager;
  56. import org.openspcoop2.web.ctrlstat.driver.DriverControlStationDB;
  57. import org.openspcoop2.web.ctrlstat.servlet.ConsoleHelper;
  58. import org.openspcoop2.web.lib.users.dao.InterfaceType;
  59. import org.slf4j.Logger;
  60. /**
  61.  * Questa classe si occupa di inizializzare tutte le risorse necessarie al webService.
  62.  *
  63.  *
  64.  * @author Andrea Poli (apoli@link.it)
  65.  * @author $Author$
  66.  * @version $Rev$, $Date$
  67.  *
  68.  */

  69. public class Startup implements ServletContextListener {

  70.     private static Logger log = null;
  71.     public static Logger getLog() {
  72.         return log;
  73.     }

  74.     private static InitRuntimeConfigReader initRuntimeConfigReader;
  75.    
  76.     @Override
  77.     public void contextDestroyed(ServletContextEvent sce) {
  78.         if(Startup.log!=null)
  79.             Startup.log.info("Undeploy webService in corso...");

  80.          if(initRuntimeConfigReader!=null) {
  81.                 initRuntimeConfigReader.setStop(true);
  82.          }
  83.        
  84.         if(Startup.log!=null)
  85.             Startup.log.info("Undeploy webService effettuato.");

  86.     }

  87.     @Override
  88.     public void contextInitialized(ServletContextEvent sce) {
  89.        
  90.         Startup.initLog();
  91.        
  92.         Startup.initResources();

  93.     }
  94.    

  95.     // LOG
  96.    
  97.     private static boolean initializedLog = false;
  98.    
  99.     public static boolean isInitializedLog() {
  100.         return initializedLog;
  101.     }

  102.     public static synchronized String initLog(){
  103.        
  104.         String confDir = null;
  105.         try{
  106.             InputStream is = Startup.class.getResourceAsStream("/rs-api-config.properties");
  107.             try{
  108.                 if(is!=null){
  109.                     Properties p = new Properties();
  110.                     p.load(is);
  111.                     confDir = p.getProperty("confDirectory");
  112.                     if(confDir!=null){
  113.                         confDir = confDir.trim();
  114.                     }
  115.                 }
  116.             }finally{
  117.                 try{
  118.                     if(is!=null){
  119.                         is.close();
  120.                     }
  121.                 }catch(Exception eClose){
  122.                     // close
  123.                 }
  124.             }

  125.         }catch(Exception e){
  126.             // ignore
  127.         }
  128.        
  129.         if(!Startup.initializedLog){
  130.            
  131.             try{
  132.                 Startup.log = LoggerWrapperFactory.getLogger(Startup.class);
  133.                 LoggerProperties.initialize(Startup.log, confDir, null);
  134.                 Startup.initializedLog = true;
  135.                 Startup.log = LoggerProperties.getLoggerCore();
  136.                
  137.             }catch(Exception e){
  138.                 throw new UtilsRuntimeException(e.getMessage(),e);
  139.             }
  140.         }
  141.        
  142.         return confDir;
  143.     }
  144.    
  145.    
  146.     // RESOURCES
  147.    
  148.     private static boolean initializedResources = false;
  149.    
  150.     public static synchronized void initResources(){
  151.         if(!Startup.initializedResources){
  152.            
  153.             String confDir = Startup.initLog();
  154.            
  155.             Startup.log.info("Inizializzazione rs api config in corso...");
  156.            
  157.             if(!ServerProperties.initialize(confDir,Startup.log)){
  158.                 return;
  159.             }
  160.             ServerProperties serverProperties = null;
  161.             try {
  162.                 serverProperties = ServerProperties.getInstance();
  163.             } catch (Exception e) {
  164.                 doError("Errore durante l'inizializzazione del serverProperties",e);
  165.             }
  166.            
  167.             // Inizializzo Controlli connessioni
  168.             try {
  169.                 Logger logR = Startup.log;
  170.                 ServicesUtils.initCheckConnectionDB(logR, serverProperties.isJdbcCloseConnectionCheckIsClosed(), serverProperties.isJdbcCloseConnectionCheckAutocommit());
  171.                
  172.                 DriverControlStationDB.setCheckLogger(logR);
  173.                 DriverControlStationDB.setCheckIsClosed(serverProperties.isJdbcCloseConnectionCheckIsClosed());
  174.                 DriverControlStationDB.setCheckAutocommit(serverProperties.isJdbcCloseConnectionCheckAutocommit());
  175.                 DBManager.setCheckLogger(logR);
  176.                 DBManager.setCheckIsClosed(serverProperties.isJdbcCloseConnectionCheckIsClosed());
  177.                 DBManager.setCheckAutocommit(serverProperties.isJdbcCloseConnectionCheckAutocommit());
  178.             } catch (Exception e) {
  179.                 doError("Inizializzazione controlli connessione non riuscita",e);
  180.             }
  181.            
  182.             // Map (environment)
  183.             try {
  184.                 String mapConfig = serverProperties.getEnvMapConfig();
  185.                 if(StringUtils.isNotEmpty(mapConfig)) {
  186.                     Startup.log.info("Inizializzazione environment in corso...");
  187.                     MapProperties.initialize(Startup.log, mapConfig, serverProperties.isEnvMapConfigRequired());
  188.                     MapProperties mapProperties = MapProperties.getInstance();
  189.                     mapProperties.initEnvironment();
  190.                     String msgInit = "Environment inizializzato con le variabili definite nel file '"+mapConfig+"'"+
  191.                             "\n\tJavaProperties: "+mapProperties.getJavaMap().keys()+
  192.                             "\n\tEnvProperties: "+mapProperties.getEnvMap().keys()+
  193.                             "\n\tObfuscateMode: "+mapProperties.getObfuscateModeDescription()+
  194.                             "\n\tObfuscatedJavaKeys: "+mapProperties.getObfuscatedJavaKeys()+
  195.                             "\n\tObfuscatedEnvKeys: "+mapProperties.getObfuscatedEnvKeys();
  196.                     Startup.log.info(msgInit);
  197.                 }
  198.             } catch (Exception e) {
  199.                 doError("Errore durante l'inizializzazione dell'ambiente",e);
  200.             }
  201.            
  202.             // Load Security Provider
  203.             Startup.log.info("Inizializzazione security provider...");
  204.             try {
  205.                 if(serverProperties.isSecurityLoadBouncyCastleProvider()) {
  206.                     ProviderUtils.addBouncyCastleAfterSun(true);
  207.                     Startup.log.info("Aggiunto Security Provider org.bouncycastle.jce.provider.BouncyCastleProvider");
  208.                 }
  209.             } catch (Exception e) {
  210.                 doError("Errore durante l'inizializzazione dei security provider",e);
  211.             }
  212.             Startup.log.info("Inizializzazione security provider effettuata con successo");
  213.            
  214.             // inizializzo HSM Manager
  215.             try {
  216.                 String hsmConfig = serverProperties.getHSMConfigurazione();
  217.                 if(StringUtils.isNotEmpty(hsmConfig)) {
  218.                     Startup.log.info("Inizializzazione HSM in corso...");
  219.                     File f = new File(hsmConfig);
  220.                     HSMManager.init(f, serverProperties.isHSMRequired(), log, false);
  221.                     HSMUtils.setHsmConfigurableKeyPassword(serverProperties.isHSMKeyPasswordConfigurable());
  222.                     Startup.log.info("Inizializzazione HSM effettuata con successo");
  223.                 }
  224.             } catch (Exception e) {
  225.                 doError("Errore durante l'inizializzazione del manager HSM",e);
  226.             }
  227.            
  228.             // inizializzo BYOK Manager
  229.             BYOKManager byokManager = null;
  230.             try {
  231.                 String byokConfig = serverProperties.getBYOKConfigurazione();
  232.                 if(StringUtils.isNotEmpty(byokConfig)) {
  233.                     Startup.log.info("Inizializzazione BYOK in corso...");
  234.                     File f = new File(byokConfig);
  235.                     BYOKManager.init(f, serverProperties.isBYOKRequired(), log);
  236.                     byokManager = BYOKManager.getInstance();
  237.                     String msgInit = "Gestore BYOK inizializzato;"+
  238.                             "\n\tHSM registrati: "+byokManager.getKeystoreTypes()+
  239.                             "\n\tSecurityEngine registrati: "+byokManager.getSecurityEngineTypes()+
  240.                             "\n\tGovWaySecurityEngine: "+byokManager.getSecurityEngineGovWayDescription();
  241.                     Startup.log.info(msgInit);
  242.                 }
  243.             } catch (Exception e) {
  244.                 doError("Errore durante l'inizializzazione del manager BYOK",e);
  245.             }
  246.            
  247.             // inizializzo OCSP Manager
  248.             Startup.log.info("Inizializzazione OCSP in corso...");
  249.             try {
  250.                 String ocspConfig = serverProperties.getOCSPConfigurazione();
  251.                 if(StringUtils.isNotEmpty(ocspConfig)) {
  252.                     File f = new File(ocspConfig);
  253.                     OCSPManager.init(f, serverProperties.isOCSPRequired(), serverProperties.isOCSPLoadDefault(), log);
  254.                 }
  255.             } catch (Exception e) {
  256.                 doError("Errore durante l'inizializzazione del manager OCSP",e);
  257.             }
  258.             Startup.log.info("Inizializzazione OCSP effettuata con successo");
  259.            
  260.             // Secrets (environment)
  261.             boolean reInitSecretMaps = false;
  262.             try {
  263.                 String secretsConfig = serverProperties.getBYOKEnvSecretsConfig();
  264.                 if(byokManager!=null && StringUtils.isNotEmpty(secretsConfig)) {
  265.                     Startup.log.info("Inizializzazione secrets in corso...");

  266.                     boolean useSecurityEngine = true;
  267.                     Map<String, Object> dynamicMap = new HashMap<>();
  268.                     DynamicInfo dynamicInfo = new  DynamicInfo();
  269.                     DynamicUtils.fillDynamicMap(log, dynamicMap, dynamicInfo);
  270.                     if(byokManager.isBYOKRemoteGovWayNodeUnwrapConfig()) {
  271.                         // i secrets cifrati verranno riletti quando i nodi sono attivi (verificato in InitRuntimeConfigReader)
  272.                         reInitSecretMaps = true;
  273.                         useSecurityEngine = false;
  274.                     }
  275.                    
  276.                     BYOKMapProperties.initialize(Startup.log, secretsConfig, serverProperties.isBYOKEnvSecretsConfigRequired(),
  277.                             useSecurityEngine,
  278.                             dynamicMap, true);
  279.                     BYOKMapProperties secretsProperties = BYOKMapProperties.getInstance();
  280.                     secretsProperties.initEnvironment();
  281.                     String msgInit = "Environment inizializzato con i secrets definiti nel file '"+secretsConfig+"'"+
  282.                             "\n\tJavaProperties: "+secretsProperties.getJavaMap().keys()+
  283.                             "\n\tEnvProperties: "+secretsProperties.getEnvMap().keys()+
  284.                             "\n\tObfuscateMode: "+secretsProperties.getObfuscateModeDescription();
  285.                     Startup.log.info(msgInit);
  286.                 }
  287.             } catch (Exception e) {
  288.                 doError("Errore durante l'inizializzazione dell'ambiente (secrets)",e);
  289.             }      
  290.            
  291.             // Database
  292.             if(!DatasourceProperties.initialize(confDir,Startup.log)){
  293.                 return;
  294.             }
  295.             try {
  296.                 if(!org.openspcoop2.web.ctrlstat.config.DatasourceProperties.initialize(DatasourceProperties.getInstance().getPropertiesConsole(),Startup.log)){
  297.                     return;
  298.                 }
  299.             }catch(Exception e) {
  300.                 Startup.log.error("Inizializzazione database console fallita: "+e.getMessage(),e);
  301.             }
  302.            
  303.             // Extended Manager
  304.             Startup.log.info("Inizializzazione ExtendedInfoManager in corso...");
  305.             try{
  306.                 ExtendedInfoManager.initialize(new Loader(), null, null, null);
  307.             }catch(Exception e){
  308.                 throw new UtilsRuntimeException(e.getMessage(),e);
  309.             }
  310.             Startup.log.info("Inizializzazione ExtendedInfoManager effettuata con successo");
  311.            
  312.             // inizializza nodi runtime
  313.             Startup.log.info("Inizializzazione NodiRuntime in corso...");
  314.             try {
  315.                 boolean configFileRequired = false;
  316.                 ConfigurazioneNodiRuntime.initialize(serverProperties.getConfigurazioneNodiRuntime(), configFileRequired);
  317.             } catch (Exception e) {
  318.                 doError("Errore durante l'inizializzazione del gestore dei nodi run",e);
  319.             }
  320.             Startup.log.info("Inizializzazione NodiRuntime effettuata con successo");
  321.            
  322.            
  323.             // Protocol Factory Manager
  324.             Startup.log.info("Inizializzazione ProtocolFactoryManager in corso...");
  325.             ServerProperties properties = null;
  326.             try {
  327.                 properties = ServerProperties.getInstance();
  328.                 ConfigurazionePdD configPdD = new ConfigurazionePdD();
  329.                 configPdD.setAttesaAttivaJDBC(-1);
  330.                 configPdD.setCheckIntervalJDBC(-1);
  331.                 configPdD.setLoader(new Loader(Startup.class.getClassLoader()));
  332.                 configPdD.setLog(Startup.log);
  333.                 ProtocolFactoryManager.initialize(Startup.log, configPdD,
  334.                         properties.getProtocolloDefault());
  335.             } catch (Exception e) {
  336.                 throw new UtilsRuntimeException(e.getMessage(),e);
  337.             }
  338.             Startup.log.info("ProtocolFactoryManager DBManager effettuata con successo");
  339.            
  340.             // Risorse Statiche
  341.             Startup.log.info("Inizializzazione Risorse Statiche Console in corso...");
  342.             try {
  343.                 ConsoleHelper.setTipoInterfacciaAPI(InterfaceType.STANDARD);
  344.                
  345.                 ControlStationCore.setUtenzePasswordEncryptEngineApiMode(serverProperties.getUtenzeCryptConfig());
  346.                
  347.                 ControlStationCore.setApplicativiPasswordEncryptEngineApiMode(serverProperties.getApplicativiCryptConfig());
  348.                 ControlStationCore.setApplicativiApiKeyPasswordGeneratedLengthApiMode(serverProperties.getApplicativiApiKeyPasswordGeneratedLength());
  349.                 if(serverProperties.isApplicativiBasicPasswordEnableConstraints()) {
  350.                     ControlStationCore.setApplicativiPasswordVerifierEngineApiMode(serverProperties.getApplicativiPasswordVerifier());
  351.                 }
  352.                
  353.                 ControlStationCore.setSoggettiPasswordEncryptEngineApiMode(serverProperties.getSoggettiCryptConfig());
  354.                 ControlStationCore.setSoggettiApiKeyPasswordGeneratedLengthApiMode(serverProperties.getSoggettiApiKeyPasswordGeneratedLength());
  355.                 if(serverProperties.isSoggettiBasicPasswordEnableConstraints()) {
  356.                     ControlStationCore.setSoggettiPasswordVerifierEngineApiMode(serverProperties.getSoggettiPasswordVerifier());
  357.                 }
  358.                
  359.                 Properties yamlSnakeLimits = serverProperties.getApiYamlSnakeLimits();
  360.                 if(yamlSnakeLimits!=null && !yamlSnakeLimits.isEmpty()) {
  361.                     YamlSnakeLimits.initialize(Startup.log, yamlSnakeLimits);
  362.                 }
  363.                
  364.                 ControlStationCore.setIsSoggettiApplicativiCredenzialiBasicPermitSameCredentialsApiMode(serverProperties.isSoggettiApplicativiCredenzialiBasicPermitSameCredentials());
  365.                 ControlStationCore.setIsSoggettiApplicativiCredenzialiSslPermitSameCredentialsApiMode(serverProperties.isSoggettiApplicativiCredenzialiSslPermitSameCredentials());
  366.                 ControlStationCore.setIsSoggettiApplicativiCredenzialiPrincipalPermitSameCredentialsApiMode(serverProperties.isSoggettiApplicativiCredenzialiPrincipalPermitSameCredentials());
  367.                
  368.                 DBUtils.setKeystoreJksPasswordRequired(serverProperties.isKeystoreJksPasswordRequired());
  369.                 DBUtils.setKeystoreJksKeyPasswordRequired(serverProperties.isKeystoreJksKeyPasswordRequired());
  370.                 DBUtils.setKeystorePkcs12PasswordRequired(serverProperties.isKeystorePkcs12PasswordRequired());
  371.                 DBUtils.setKeystorePkcs12KeyPasswordRequired(serverProperties.isKeystorePkcs12KeyPasswordRequired());
  372.                 DBUtils.setTruststoreJksPasswordRequired(serverProperties.isTruststoreJksPasswordRequired());
  373.                 DBUtils.setTruststorePkcs12PasswordRequired(serverProperties.isTruststorePkcs12PasswordRequired());
  374.                
  375.                 // Inizializzazione SignalHub
  376.                 if(ProtocolFactoryManager.getInstance().existsProtocolFactory(org.openspcoop2.protocol.engine.constants.Costanti.MODIPA_PROTOCOL_NAME)) {
  377.                     CostantiDB.setServiziDigestEnabled(ModIUtils.isSignalHubEnabled());
  378.                 }
  379.                
  380.             } catch (Exception e) {
  381.                 throw new UtilsRuntimeException(e.getMessage(),e);
  382.             }
  383.             Startup.log.info("Inizializzazione Risorse Statiche Console effettuata con successo");
  384.            
  385.             Startup.log.info("Inizializzazione Connettori in corso...");
  386.             try{
  387.                 Connettori.initialize(log, true, confDir, ServerProperties.getInstance().getProtocolloDefault());
  388.             }catch(Exception e){
  389.                 throw new UtilsRuntimeException(e.getMessage(),e);
  390.             }
  391.             Startup.log.info("Inizializzazione Connettori effettuata con successo");
  392.            
  393.             // Allarmi
  394.             try {
  395.                 if(ServerProperties.getInstance().isConfigurazioneAllarmiEnabled()!=null && ServerProperties.getInstance().isConfigurazioneAllarmiEnabled().booleanValue()) {
  396.                     Startup.log.info("Inizializzazione Allarmi in corso...");
  397.                     AlarmEngineConfig alarmEngineConfig = AlarmConfigProperties.getAlarmConfiguration(log, ServerProperties.getInstance().getAllarmiConfigurazione(), ServerProperties.getInstance().getConfDirectory());
  398.                     AlarmManager.setAlarmEngineConfig(alarmEngineConfig);
  399.                     CostantiDB.setAllarmiEnabled(true);
  400.                     Startup.log.info("Inizializzazione Allarmi effettuata con successo");
  401.                 }
  402.             } catch (Exception e) {
  403.                 doError("Errore durante l'inizializzazione degli allarmi",e);
  404.             }
  405.                
  406.             // InitRuntimeConfigReader
  407.             if(reInitSecretMaps) {
  408.                 try{
  409.                     initRuntimeConfigReader = new InitRuntimeConfigReader(serverProperties, ConfigurazioneNodiRuntime.getConfigurazioneNodiRuntime(), reInitSecretMaps);
  410.                     initRuntimeConfigReader.start();
  411.                     Startup.log.info("RuntimeConfigReader avviato con successo.");
  412.                 } catch (Exception e) {
  413.                     /**doError("Errore durante l'inizializzazione del RuntimeConfigReader",e);*/
  414.                     // non sollevo l'eccezione, e' solo una informazione informativa, non voglio mettere un vincolo che serve per forza un nodo acceso
  415.                     Startup.log.error("Errore durante l'inizializzazione del RuntimeConfigReader: "+e.getMessage(),e);
  416.                 }
  417.             }
  418.            
  419.             Startup.initializedResources = true;
  420.            
  421.             Startup.log.info("Inizializzazione rs api config effettuata con successo.");
  422.         }
  423.     }

  424.     private static void doError(String msg,Exception e) {
  425.         String msgErrore = msg+": " + e.getMessage();
  426.         Startup.log.error(msgErrore,e);
  427.         throw new UtilsRuntimeException(msgErrore,e);
  428.     }
  429. }