Class AbstractPythonProcessService
java.lang.Object
de.iip_ecosphere.platform.services.environment.AbstractService
de.iip_ecosphere.platform.services.environment.AbstractRunnablesService
de.iip_ecosphere.platform.services.environment.AbstractPythonProcessService
- All Implemented Interfaces:
GenericMultiTypeService,ParameterConfigurerProvider,Service,ServiceBase
- Direct Known Subclasses:
PythonAsyncProcessService,PythonSyncProcessService
public abstract class AbstractPythonProcessService
extends AbstractRunnablesService
implements GenericMultiTypeService
Generic command-line-based Python integration for multiple data types. Considers
environment mappings if the arguments
indicate that the Python service shall be executed in a conda environment.- Author:
- Holger Eichelberger, SSE
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static classSelf-registering abstract byte array reception callback.protected static interfaceDefines a function that handles "parsed" input, split into type and serialized data.protected static classIngestor implementation for synchronous processing. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate Stringprivate booleanprivate Fileprivate GenericMultiTypeServiceImplprivate Stringprivate Map<String, ParameterConfigurer<?>> private Stringstatic final charFields inherited from interface de.iip_ecosphere.platform.services.environment.switching.ServiceBase
APPLICATION_SEPARATOR, DEFAULT_APPLICATION_INSTANCE_ID -
Constructor Summary
ConstructorsConstructorDescriptionCreates a service from YAML information.AbstractPythonProcessService(String serviceId, InputStream ymlFile) Creates a service from a service id and a YAML artifact. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddParameterConfigurer(Consumer<Map<String, ParameterConfigurer<?>>> paramConsumer) Adds parameter configurers via a consumer.<O> voidattachIngestor(Class<O> outCls, String outTypeName, DataIngestor<O> ingestor) Attaches an asynchronous result data ingestor.protected static StringComposes a symbolic type name with the string-serialized data.protected ProcesscreateAndCustomizeProcess(String data, Map<String, String> reconfValues) Creates and customizes the process.protected ThreadCreates a thread callingscanInputStream(Process, InputHandler).protected voidcustomizePythonArgs(List<String> pythonArgs) Allows to customize the Python command line arguments taken from the yaml spec.voidenableFileDeletion(boolean enableFileDeletion) Enables or deletes file deletion.private voidestablishClientListener(String typeName, String serverChannel) Establishes a client listener for internal server-client communication via Transport.private voidestablishServerListener(String typeName, String serverChannel) Establishes a server listener for internal server-client communication via Transport.longReturns the average response time for the execution in Python (without transport).protected FilegetHome()Returns the home directory.getInTypeInfo(String inTypeName) Returns the input type information object for the given symbolic type name.protected StringReturns the location key for access intoInstalledDependenciesSetup.protected static de.iip_ecosphere.platform.support.logging.LoggerReturns the logger.getOutTypeInfo(String outTypeName) Returns the output type information object for the given symbolic type name.getOutTypeName(String inTypeName) Returns a registered output type name for a given input type name.getParameterConfigurer(String paramName) Returns the parameter configurer for a given parameter.The set of parameter names.protected FileReturns the Python executable, either viaInstalledDependenciesSetupandgetLocationKey()or as fallback viaPythonUtils.getPythonExecutable().private static StringgetPythonModule(String module, YamlService yaml, File homePath) Returns the name of the Python module.protected StringReturns the type mappings as JSON.protected voidHandles the error stream upon process creation.protected <O> voidhandleResult(Class<O> cls, String data, String typeName) Handles a received processing result and ingests it back asynchronously.protected voidinitializeFrom(YamlService yaml) Does further initialization of this instance from the given YAML information.booleanReturns whether file deletion is enabled.voidregisterInOutRelation(String inTypeName, String outTypeName) Explicitly registers the relation between two type names.<I> voidregisterInputTypeTranslator(Class<I> inCls, String inTypeName, de.iip_ecosphere.platform.transport.serialization.TypeTranslator<I, String> inTrans) Adds an input type translator.<O> voidregisterOutputTypeTranslator(Class<O> outCls, String outTypeName, de.iip_ecosphere.platform.transport.serialization.TypeTranslator<String, O> outTrans) Adds an output type translator.protected StringscanInputStream(Process proc, AbstractPythonProcessService.InputHandler handler) Scans the input stream of the given process for return data.protected ServiceStatestart()Starts the service and the background process.protected booleanReturns whether the Python executable shall be started by name or by full path.protected ServiceStatestop()Stops the service and the background process.protected StringTurns a map of string values into JSON.private static StringtoPythonDataCls(Class<?> cls) Turns a Java data class name to a Python data class name.protected booleanunbuffer()Returns whether the python process shall be unbuffered on the console streams (-u).Methods inherited from class de.iip_ecosphere.platform.services.environment.AbstractRunnablesService
registerMethods inherited from class de.iip_ecosphere.platform.services.environment.AbstractService
activate, addConfigurer, addConfigurer, addConfigurer, addTypeSubstitution, createGenericInstance, createGenericInstance, createGenericInstanceByPlugin, createGenericMultiInstance, createGenericMultiInstance, createGenericMultiInstanceByPlugin, createInstance, createInstance, createInstance, createInstanceByPlugin, getArg, getDescription, getId, getKind, getName, getNetMgtKeyAddress, getResourceAsStream, getState, getStringArg, getSubstitutedType, getTypeCreator, getTypeSubstitutions, getVersion, isDeployable, isTopLevel, notifyReconfigured, passivate, reconf, reconfigure, reconfigure, rollbackReconfigurationOnFailure, setLibJars, setState, transferDataMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface de.iip_ecosphere.platform.services.environment.GenericMultiTypeService
process, processQuiet, processSync, processSyncQuietMethods inherited from interface de.iip_ecosphere.platform.services.environment.Service
activate, addTypeSubstitution, createType, createType, getDescription, getKind, getName, getNetMgtKeyAddress, getSubstitutedType, getTypeCreator, getTypeSubstitutions, getVersion, isDeployable, isTopLevel, migrate, passivate, reconfigure, switchTo, updateMethods inherited from interface de.iip_ecosphere.platform.services.environment.switching.ServiceBase
getId, getState, setState
-
Field Details
-
TYPE_SEPARATOR_CHAR
public static final char TYPE_SEPARATOR_CHAR- See Also:
-
home
-
pythonArgs
-
locationKey
-
transportChannel
-
impl
-
paramConfigurers
-
callbacks
-
averageResponseTime
-
enableFileDeletion
private boolean enableFileDeletion
-
-
Constructor Details
-
AbstractPythonProcessService
Creates a service from a service id and a YAML artifact.- Parameters:
serviceId- the service idymlFile- the YML file containing the YAML artifact with the service descriptor
-
AbstractPythonProcessService
Creates a service from YAML information.- Parameters:
yaml- the service information as read from YAML. By default, the Python executable is "ServiceEnvironment.py", which can be overridden byYamlProcess.getExecutable().YamlProcess.getHomePath()is set to the home path where the executable was extracted to. Further,YamlProcess.getCmdArg()are taken over if given.
-
-
Method Details
-
initializeFrom
Description copied from class:AbstractServiceDoes further initialization of this instance from the given YAML information.- Overrides:
initializeFromin classAbstractService- Parameters:
yaml- the service information as read from YAML
-
unbuffer
protected boolean unbuffer()Returns whether the python process shall be unbuffered on the console streams (-u).- Returns:
truefor unbuffer (default),falsefor buffered console streams
-
customizePythonArgs
Allows to customize the Python command line arguments taken from the yaml spec.- Parameters:
pythonArgs- the arguments to customize
-
enableFileDeletion
public void enableFileDeletion(boolean enableFileDeletion) Enables or deletes file deletion. By default, Python files are delete upon end of the process.- Parameters:
enableFileDeletion- enables deletion
-
isFileDeletionEnabled
public boolean isFileDeletionEnabled()Returns whether file deletion is enabled. By default, Python files are delete upon end of the process.- Returns:
trueif enabled,falseelse
-
getHome
Returns the home directory.- Returns:
- the home directory
-
getPythonModule
Returns the name of the Python module. The default (if not explicitly given) is "ServiceEnvironment.py".- Parameters:
module- the module name, may be empty or nullyaml- the YAML service deployment informationhomePath- optional home path to check for the module first if not given- Returns:
- the Python module name
-
startExecutableByName
protected boolean startExecutableByName()Returns whether the Python executable shall be started by name or by full path.- Returns:
falsefor starting by full path returned bygetPythonExecutable()
-
scanInputStream
Scans the input stream of the given process for return data.- Parameters:
proc- the Python processhandler- the input handler- Returns:
- the first line if
returnFirst, else null - See Also:
-
createScanInputThread
protected Thread createScanInputThread(Process proc, AbstractPythonProcessService.InputHandler handler) Creates a thread callingscanInputStream(Process, InputHandler).- Parameters:
proc- the Python processhandler- the input handler- Returns:
- the thread
-
handleResult
Handles a received processing result and ingests it back asynchronously.- Type Parameters:
O- the data type- Parameters:
cls- the data type classdata- the serialized datatypeName- the data type name as specified in the configuration model
-
toJson
Turns a map of string values into JSON.- Parameters:
reconfValues- the values to turn into JSON- Returns:
- the JSON representation
-
toPythonDataCls
Turns a Java data class name to a Python data class name.- Parameters:
cls- the class- Returns:
- the simple Python data class name
-
getTypeSubstitutionsJson
Returns the type mappings as JSON.- Returns:
- the type mappings
-
createAndCustomizeProcess
protected Process createAndCustomizeProcess(String data, Map<String, String> reconfValues) throws ExecutionExceptionCreates and customizes the process.- Parameters:
data- the data to be directly handed to the process via command linereconfValues- values to (re)configure the service environment, may be null for none- Returns:
- the process
- Throws:
ExecutionException- if the process cannot be created
-
getLocationKey
Returns the location key for access intoInstalledDependenciesSetup.- Returns:
- the key, may be null for fallback
-
getPythonExecutable
Returns the Python executable, either viaInstalledDependenciesSetupandgetLocationKey()or as fallback viaPythonUtils.getPythonExecutable().- Returns:
- the Python executable
-
handleErrorStream
Handles the error stream upon process creation.- Parameters:
err- the process error stream
-
getLogger
protected static de.iip_ecosphere.platform.support.logging.Logger getLogger()Returns the logger.- Returns:
- the logger
-
registerInputTypeTranslator
public <I> void registerInputTypeTranslator(Class<I> inCls, String inTypeName, de.iip_ecosphere.platform.transport.serialization.TypeTranslator<I, String> inTrans) Description copied from interface:GenericMultiTypeServiceAdds an input type translator.- Specified by:
registerInputTypeTranslatorin interfaceGenericMultiTypeService- Type Parameters:
I- the input data type- Parameters:
inCls- the class representing the input typeinTypeName- symbolic name ofinCls, e.g. from configuration modelinTrans- the input data type translator- See Also:
-
getInTypeInfo
Returns the input type information object for the given symbolic type name.- Parameters:
inTypeName- the symbolic type name- Returns:
- the information object or null if none was registered
-
registerInOutRelation
Description copied from interface:GenericMultiTypeServiceExplicitly registers the relation between two type names.- Specified by:
registerInOutRelationin interfaceGenericMultiTypeService- Parameters:
inTypeName- symbolic name of an input type, e.g. from configuration modeloutTypeName- symbolic name of an output type, e.g. from configuration model- See Also:
-
getOutTypeName
Description copied from interface:GenericMultiTypeServiceReturns a registered output type name for a given input type name.- Specified by:
getOutTypeNamein interfaceGenericMultiTypeService- Parameters:
inTypeName- the symbolic input type name- Returns:
- the related symbolic output type name, may be null if there is none
- See Also:
-
getOutTypeInfo
Returns the output type information object for the given symbolic type name.- Parameters:
outTypeName- the symbolic type name- Returns:
- the information object or null if none was registered
-
registerOutputTypeTranslator
public <O> void registerOutputTypeTranslator(Class<O> outCls, String outTypeName, de.iip_ecosphere.platform.transport.serialization.TypeTranslator<String, O> outTrans) Description copied from interface:GenericMultiTypeServiceAdds an output type translator.- Specified by:
registerOutputTypeTranslatorin interfaceGenericMultiTypeService- Type Parameters:
O- the output data type- Parameters:
outCls- the class representing the input typeoutTypeName- symbolic name ofoutCls, e.g. from configuration modeloutTrans- the output data type translator- See Also:
-
attachIngestor
Description copied from interface:GenericMultiTypeServiceAttaches an asynchronous result data ingestor.- Specified by:
attachIngestorin interfaceGenericMultiTypeService- Type Parameters:
O- the output data type- Parameters:
outCls- the class representing the typeoutTypeName- symbolic name ofoutCls, e.g. from configuration modelingestor- the ingestor instance
-
compose
Composes a symbolic type name with the string-serialized data.- Parameters:
typeName- the type namedata- the data- Returns:
- the composed String
-
getParameterConfigurer
Description copied from interface:ParameterConfigurerProviderReturns the parameter configurer for a given parameter. We need this generic approach to ease code generation and initial setting of parameter values.- Specified by:
getParameterConfigurerin interfaceParameterConfigurerProvider- Specified by:
getParameterConfigurerin interfaceService- Parameters:
paramName- the name of the parameter- Returns:
- the associated parameter configurer or null if there is none
-
getParameterNames
Description copied from interface:ParameterConfigurerProviderThe set of parameter names.- Specified by:
getParameterNamesin interfaceParameterConfigurerProvider- Specified by:
getParameterNamesin interfaceService- Returns:
- the parameter names, may be null for none
-
addParameterConfigurer
Adds parameter configurers via a consumer.- Parameters:
paramConsumer- the consumer, userAbstractService.addConfigurer(Map, String, Class, TypeTranslator, ValueConfigurer)and related methods in there
-
start
Description copied from class:AbstractServiceStarts the service and the background process.- Overrides:
startin classAbstractService- Returns:
- the state to transition to, may be null for none
- Throws:
ExecutionException- if starting the process fails
-
stop
Description copied from class:AbstractServiceStops the service and the background process.- Overrides:
stopin classAbstractRunnablesService- Returns:
- the state to transition to, may be null for none
-
establishServerListener
Establishes a server listener for internal server-client communication via Transport.- Parameters:
typeName- the name of the type for Java-Python communicationserverChannel- the name of the server channel to send initial request to- Throws:
IOException- if sending/receiving messages fails
-
establishClientListener
Establishes a client listener for internal server-client communication via Transport.- Parameters:
typeName- the name of the type for Java-Python communicationserverChannel- the name of the server channel to send initial request to- Throws:
IOException- if sending/receiving messages fails
-
getAvgResponseTime
public long getAvgResponseTime()Returns the average response time for the execution in Python (without transport).- Returns:
- the average response time (in nanoseconds)
-