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.utils.LoggerWrapperFactory;
  41. import org.openspcoop2.utils.UtilsRuntimeException;
  42. import org.openspcoop2.utils.certificate.byok.BYOKManager;
  43. import org.openspcoop2.utils.certificate.hsm.HSMManager;
  44. import org.openspcoop2.utils.certificate.hsm.HSMUtils;
  45. import org.openspcoop2.utils.certificate.ocsp.OCSPManager;
  46. import org.openspcoop2.utils.json.YamlSnakeLimits;
  47. import org.openspcoop2.utils.properties.MapProperties;
  48. import org.openspcoop2.utils.resources.Loader;
  49. import org.openspcoop2.utils.security.ProviderUtils;
  50. import org.openspcoop2.web.ctrlstat.core.Connettori;
  51. import org.openspcoop2.web.ctrlstat.core.ControlStationCore;
  52. import org.openspcoop2.web.ctrlstat.core.DBManager;
  53. import org.openspcoop2.web.ctrlstat.driver.DriverControlStationDB;
  54. import org.openspcoop2.web.ctrlstat.servlet.ConsoleHelper;
  55. import org.openspcoop2.web.lib.users.dao.InterfaceType;
  56. import org.slf4j.Logger;
  57. /**
  58.  * Questa classe si occupa di inizializzare tutte le risorse necessarie al webService.
  59.  *
  60.  *
  61.  * @author Andrea Poli (apoli@link.it)
  62.  * @author $Author$
  63.  * @version $Rev$, $Date$
  64.  *
  65.  */

  66. public class Startup implements ServletContextListener {

  67.     private static Logger log = null;
  68.     public static Logger getLog() {
  69.         return log;
  70.     }

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

  77.          if(initRuntimeConfigReader!=null) {
  78.                 initRuntimeConfigReader.setStop(true);
  79.          }
  80.        
  81.         if(Startup.log!=null)
  82.             Startup.log.info("Undeploy webService effettuato.");

  83.     }

  84.     @Override
  85.     public void contextInitialized(ServletContextEvent sce) {
  86.        
  87.         Startup.initLog();
  88.        
  89.         Startup.initResources();

  90.     }
  91.    

  92.     // LOG
  93.    
  94.     private static boolean initializedLog = false;
  95.    
  96.     public static boolean isInitializedLog() {
  97.         return initializedLog;
  98.     }

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

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

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

  398.     private static void doError(String msg,Exception e) {
  399.         String msgErrore = msg+": " + e.getMessage();
  400.         Startup.log.error(msgErrore,e);
  401.         throw new UtilsRuntimeException(msgErrore,e);
  402.     }
  403. }