AppserverDefinition.java

/*
** Module   : AppServerDefinition.java
** Abstract : The settings of an appserver.
**
** Copyright (c) 2013-2025, Golden Code Development Corporation.
**
** -#- -I- --Date-- ---------------------------------Description----------------------------------
** 001 CA  20130704 Created initial version.
** 002 CA  20140206 Removed settings which need to be at the associated P2J process, as the
**                  appserver will start using the scheduler and spawner infrastructure.
**                  Moved logging support to use the logging provided by LogHelper.
** 003 OM  20150108 Progress properties read from directory are can be obtained with getProperties
**                  method to be passed to spawned client process environment.
** 004 OM  20150127 Fixed potential NPE when /properties collection is missing from appserver node.
** 005 CA  20150909 Fixed a race condition on DirectoryService usage - as this may be done in a 
**                  separate thread using the server's context, all threads need to sync on this
**                  object, as the DirectoryService is not thread-safe.
** 006 OM  20160425 Project awareness (support for multiple project running in same JVM.
** 007 CA  20180509 Removed synchronized (it isn't needed, if we will add configuration via the 
**                  FWD Admin Console, we will see then).
** 008 CA  20191211 Allow appservers to be marked as multi-session agent appserver.
** 009 CA  20211214 For State-free appservers, the agents can be bound to remote persistent procedures; this
**                  binding must be made using the agent's ID, as a client can invoke multiple remote 
**                  persistent procedures, and using the procedure's ID for this binding can lead to 
**                  collisions, as the pair (connection ID, procedure ID) is not guaranteed to be unique for
**                  a connection.
** 010 GBB 20230512 Logging methods replaced by CentralLogger/ConversionStatus.
** 011 GBB 20241010 Adding new fields, getters and value resolving for processName, systemUser, 
**                  schedulerMode, enableSsl, logFilename, loggingLevel, logFileThresholdSize, 
**                  logFilesMaxNumber, alias.
** 012 GBB 20250403 Using the class as parent for both the classic and MSA appservers.
**                  Initialize all appserver definitions with initAppServerDefinitions.
*/
/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Affero General Public License for more details.
**
** You may find a copy of the GNU Affero GPL version 3 at the following
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
** 
** Additional terms under GNU Affero GPL version 3 section 7:
** 
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
**   terms apply to the works covered under the License.  These additional terms
**   are non-permissive additional terms allowed under Section 7 of the GNU
**   Affero GPL version 3 and may not be removed by you.
** 
**   0. Attribution Requirement.
** 
**     You must preserve all legal notices or author attributions in the covered
**     work or Appropriate Legal Notices displayed by works containing the covered
**     work.  You may not remove from the covered work any author or developer
**     credit already included within the covered work.
** 
**   1. No License To Use Trademarks.
** 
**     This license does not grant any license or rights to use the trademarks
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
**     of Golden Code Development Corporation. You are not authorized to use the
**     name Golden Code, FWD, or the names of any author or contributor, for
**     publicity purposes without written authorization.
** 
**   2. No Misrepresentation of Affiliation.
** 
**     You may not represent yourself as Golden Code Development Corporation or FWD.
** 
**     You may not represent yourself for publicity purposes as associated with
**     Golden Code Development Corporation, FWD, or any author or contributor to
**     the covered work, without written authorization.
** 
**   3. No Misrepresentation of Source or Origin.
** 
**     You may not represent the covered work as solely your work.  All modified
**     versions of the covered work must be marked in a reasonable way to make it
**     clear that the modified work is not originating from Golden Code Development
**     Corporation or FWD.  All modified versions must contain the notices of
**     attribution required in this license.
*/

package com.goldencode.p2j.util.appserver;

import com.goldencode.p2j.directory.*;
import com.goldencode.p2j.scheduler.*;
import com.goldencode.p2j.security.SecurityManager;
import com.goldencode.p2j.util.*;
import com.goldencode.p2j.util.logging.*;

import java.util.*;
import java.util.logging.*;

/** Base abstract class for appserver definition. */
public abstract class AppserverDefinition
{
   /** Logger. */
   private static final CentralLogger LOG = CentralLogger.get(AppserverDefinition.class);

   /** The appserver name. */
   private final String appserverName;

   /** The project token. Will be set on the context serving the appserver. */
   private final String projectToken;

   /** Appserver's explicit propath. */
   private final String propath;

   /**
    * Environment settings incoming from progress.ini, global per appserver.
    * The spawner will set these into the OS environment directly, before launching the child
    * process.
    */
   private final Map<String, String> properties = new HashMap<>();

   /** Flag for enabling SSL validation. */
   private final boolean enableSsl;

   /** FWD account ids. */
   private String[] accountIds;

   /** The appserver process name. */
   private String processName;

   /** The scheduler mode. */
   private String schedulerMode;

   /** Private key alias. */
   private String alias;
   
   /**
    * Resolve this appserver instance from the directory. Must be called from threads which have
    * their context authorized to access the <code>appservers</code> node for the P2J server.
    *
    * @param    appserverName
    *           The application's server name.
    * @param    ds
    *           Directory service.
    * @param    appSrvPath
    *           The appserver node path in directory.
    */
   AppserverDefinition(String appserverName, DirectoryService ds, String appSrvPath)
   {
      this.appserverName = appserverName;
      this.propath = ds.getNodeString(appSrvPath, "propath");
      this.projectToken = ds.getNodeString(appSrvPath, "project_token");
      this.enableSsl = true;

      String propertiesPath = appSrvPath + "/properties";
      String[] nodes = ds.enumerateNodes(propertiesPath);
      if (nodes != null)
      {
         for (String node : nodes)
         {
            String val = ds.getNodeString(propertiesPath + "/" + node, "value");
            if (val != null)
            {
               properties.put(node, val);
            }
         }
      }
      
      SecurityManager sm = SecurityManager.getInstance();
      String[] processNames = sm.getAccountsForAppserver(appserverName);

      if (processNames != null && processNames.length > 0)
      {
         String firstProcessName = processNames[0];
         this.processName = firstProcessName;
         this.accountIds = sm.getAccountIds(processName);
         
         if (processNames.length > 1)
         {
            this.processName = String.join(", ", processNames);
            LOG.severe("Multiple FWD processes defined for appserver " + appserverName);
         }

         this.schedulerMode = Scheduler.getSchedulerModeFor(firstProcessName);
         this.alias = sm.getAccountAlias(firstProcessName);
      }
   }

   /**
    * Initializes the appserver definitions. Should be called on a thread with proper security context. 
    * The constructor of {@link ClassicAppserverDefinition} or {@link MultiSessionAppserverDefinition} will
    * save the instance in a collection with the resolved definitions.
    */
   public static void initAppServerDefinitions()
   {
      DirectoryService ds = DirectoryService.getInstance();
      if (!ds.bind())
      {
         throw new RuntimeException("directory bind failed");
      }
      
      for (String appServer : Utils.enumerateNodes(ds, "appservers", Utils.DirScope.SERVER, null))
      {
         boolean isMultiSession = false;
         String appSrvPath = Utils.findDirectoryNodePath(ds,
                                                         "appservers/" + appServer,
                                                         "appserver",
                                                         false);
         
         if (appSrvPath == null)
         {
            appSrvPath = Utils.findDirectoryNodePath(ds,
                                                     "appservers/" + appServer,
                                                     "multisession",
                                                     false);
            if (appSrvPath == null)
            {
               throw new IllegalArgumentException(
                  "No appserver named '" + appServer + "' is configured in the directory!"); 
            }
            isMultiSession = true;
         }
         
         AppserverDefinition def = isMultiSession ?
            new MultiSessionAppserverDefinition(appServer, ds, appSrvPath) :
            new ClassicAppserverDefinition(appServer, ds, appSrvPath);
         
         LOG.log(Level.INFO, "Definition for appserver '%s' resolved from directory.", appServer);
      }

      ds.unbind();
   }

   /**
    * Returns <code>true</code> if this definition is for a multi-session agent appserver.
    *
    * @return    See above.
    */
   public abstract boolean isMultiSession();
   
   /**
    * Getter for systemUser.
    *
    * @return  See above.
    */
   public abstract String getSystemUser();
   
   /**
    * Getter for {@link #accountIds}.
    *
    * @return  See above.
    */
   public String[] getAccountIds()
   {
      return accountIds;
   }

   /**
    * Getter for the {@link #appserverName} field.
    *
    * @return   See above.
    */
   public String getAppserverName()
   {
      return appserverName;
   }

   /**
    * Getter for the {@link #propath} field.
    *
    * @return   See above.
    */
   public String getPropath()
   {
      return propath;
   }

   /**
    * Get the project token that this agent serves. If not set then the default is used.
    * 
    * @return  the {@code prokectToken} the agent serves.
    */
   public String getProjectToken()
   {
      return projectToken;
   }
   
   /**
    * Getter for {@link #properties} properties.
    * 
    * @return  a temporary copy of the private map of environment properties. Returns
    *          <code>null</code> is the map is <code>null</code> or empty.
    */
   public Map<String, String> getProperties()
   {
      if (properties.isEmpty())
      {
         return null; // quick out
      }

      return new HashMap<String, String>(properties);
   }

   /**
    * Getter for {@link #schedulerMode}.
    *
    * @return  See above.
    */
   public String getSchedulerMode()
   {
      return schedulerMode;
   }

   /**
    * Getter for {@link #processName}.
    *
    * @return  See above.
    */
   public String getProcessName()
   {
      return processName;
   }

   /**
    * Getter for {@link #alias}.
    *
    * @return  See above.
    */
   public String getAlias()
   {
      return alias;
   }

   /**
    * Getter for {@link #enableSsl}.
    *
    * @return  See above.
    */
   public boolean isEnableSsl()
   {
      return enableSsl;
   }
}