runSalome.py \
salomeConsole.py \
salome_session.py \
- salome_utilities.py \
+ salome_utils.py \
server.py \
setenv.py \
showNS.py \
elif info==port print host
else print 2 strings on stdout on one line: host port
"""
- from salome_utilities import getORBcfgInfo
+ from salome_utils import getORBcfgInfo
my_version, my_host, my_port = getORBcfgInfo()
if info=='host':
# keep print, stdout used in shell
Detect current SALOME session's port number.
Returns port number.
"""
- from salome_utilities import getPortNumber
+ from salome_utils import getPortNumber
port = getPortNumber()
if verbose(): print "myport = ", port
return port
"""
user = os.getenv('USER')
# new-style dot-prefixed pidict file
- fpidict = getPiDict('(\d*)',hidden=True)
+ #fpidict = getPiDict('(\d*)',hidden=True)
+ #problem with WIN32 path slashes
+ fpidict = getPiDict('#####',hidden=True)
dirpidict = os.path.dirname(fpidict)
fpidict = os.path.basename(fpidict)
+ fpidict = fpidict.replace('#####', '(\d*)')
fnamere = re.compile("^%s$" % fpidict)
try:
for f in os.listdir(dirpidict):
except:
pass
# provide compatibility with old-style pidict file (not dot-prefixed)
- fpidict = getPiDict('(\d*)',hidden=False)
+ #fpidict = getPiDict('(\d*)',hidden=False)
+ fpidict = getPiDict('#####',hidden=True)
dirpidict = os.path.dirname(fpidict)
fpidict = os.path.basename(fpidict)
+ fpidict = fpidict.replace('#####', '(\d*)')
fnamere = re.compile("^%s$" % fpidict)
try:
for f in os.listdir(dirpidict):
- hidden : if True, file name is prefixed with . (dot) symbol; this internal parameter is used
to support compatibility with older versions of SALOME
"""
- from salome_utilities import generateFileName, getTmpDir
+ from salome_utils import generateFileName, getTmpDir
dir = ""
if full:
# full path to the pidict file is requested
- ${HOME}/${APPLI}/.omniORB_last.cfg
the last is removed only if the link points to the first file.
"""
- from salome_utilities import generateFileName
+ from salome_utils import generateFileName
home = os.getenv("HOME")
appli = os.getenv("APPLI")
if appli is None:
try:
fpid = open(filedict, 'r')
#
- from salome_utilities import generateFileName
+ from salome_utils import generateFileName
fpidomniNames = generateFileName(os.path.join('/tmp/logs', os.getenv('USER')),
prefix="",
suffix="Pid_omniNames",
def __init__(self,args):
self.args=args
self.initArgs()
- from salome_utilities import generateFileName
+ from salome_utils import generateFileName
if sys.platform == "win32": dirpath = os.environ["HOME"]
else: dirpath = "/tmp"
logfile = generateFileName( dirpath,
if not portIsUsed(NSPORT, ports):
print "%s - OK"%(NSPORT)
#
- from salome_utilities import generateFileName, getHostName
+ from salome_utils import generateFileName, getHostName
hostname = getHostName()
#
home = os.getenv("HOME")
def main():
"""Salome launch as a main application"""
import sys
- from salome_utilities import getHostName
+ from salome_utils import getHostName
print "runSalome running on %s" % getHostName()
args, modules_list, modules_root_dir = setenv.get_config()
kill_salome(args)
socket.gethostname() gives short or complete Hostname, depending on
defined aliases.
"""
- from salome_utilities import getShortHostName
+ from salome_utils import getShortHostName
return getShortHostName()
def searchFreePort():
Returns first found free port number.
"""
print "Searching a free port for naming service:",
- from salome_utilities import generateFileName, getHostName
+ from salome_utils import generateFileName, getHostName
hostname = getHostName()
NSPORT = 2810
limit = NSPORT+100
--- /dev/null
+# Copyright (C) 2005 OPEN CASCADE, CEA, EDF R&D, LEG
+# PRINCIPIA R&D, EADS CCR, Lip6, BV, CEDRAT
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+# ---
+#
+# File : salome_utils.py
+# Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
+#
+# ---
+
+"""
+Set of utility functions used by SALOME python scripts.
+"""
+
+#
+# Exported functions
+#
+__all__ = [
+ 'getORBcfgInfo',
+ 'getHostFromORBcfg',
+ 'getPortFromORBcfg',
+ 'getUserName',
+ 'getHostName',
+ 'getShortHostName',
+ 'getAppName',
+ 'getPortNumber',
+ 'getTmpDir',
+ 'generateFileName',
+ ]
+
+# ---
+
+def _try_bool( arg ):
+ """
+ Check if specified parameter represents boolean value and returns its value.
+ String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
+ are supported.
+ If <arg> does not represent a boolean, an exception is raised.
+ """
+ import types
+ if type( arg ) == types.BooleanType :
+ return arg
+ elif type( arg ) == types.StringType :
+ v = str( arg ).lower()
+ if v in [ "yes", "y", "true" ]: return True
+ elif v in [ "no", "n", "false" ]: return False
+ pass
+ raise Exception("Not boolean value")
+
+# ---
+
+def getORBcfgInfo():
+ """
+ Get omniORB current configuration.
+ Returns a list of three values: [ orb_version, host_name, port_number ].
+
+ The information is retrieved from the omniORB configuration file defined
+ by the OMNIORB_CONFIG environment variable.
+ If omniORB configuration file can not be accessed, a list of three empty
+ strings is returned.
+ """
+ import os, re
+ ret = [ "", "", "" ]
+ try:
+ f = open( os.getenv( "OMNIORB_CONFIG" ) )
+ lines = f.readlines()
+ f.close()
+ regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
+ for l in lines:
+ try:
+ m = regvar.match( l )
+ if m:
+ if m.group(1) is None:
+ ret[0] = "4"
+ else:
+ ret[0] = "3"
+ pass
+ ret[1] = m.group(2)
+ ret[2] = m.group(3)
+ break
+ pass
+ except:
+ pass
+ pass
+ pass
+ except:
+ pass
+ return ret
+
+# ---
+
+def getHostFromORBcfg():
+ """
+ Get current omniORB host.
+ """
+ return getORBcfgInfo()[1]
+# ---
+
+def getPortFromORBcfg():
+ """
+ Get current omniORB port.
+ """
+ return getORBcfgInfo()[2]
+
+# ---
+
+def getUserName():
+ """
+ Get user name:
+ 1. try USER environment variable
+ 2. if fails, return 'unknown' as default user name
+ """
+ import os
+ return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
+
+# ---
+
+def getHostName():
+ """
+ Get host name:
+ 1. try socket python module gethostname() function
+ 2. if fails, try HOSTNAME environment variable
+ 3. if fails, try HOST environment variable
+ 4. if fails, return 'unknown' as default host name
+ """
+ import os
+ try:
+ import socket
+ host = socket.gethostname()
+ except:
+ host = None
+ pass
+ if not host: host = os.getenv("HOSTNAME")
+ if not host: host = os.getenv("HOST")
+ if not host: host = "unknown" # 'unknown' is default host name
+ return host
+
+# ---
+
+def getShortHostName():
+ """
+ Get short host name:
+ 1. try socket python module gethostname() function
+ 2. if fails, try HOSTNAME environment variable
+ 3. if fails, try HOST environment variable
+ 4. if fails, return 'unknown' as default host name
+ """
+ try:
+ return getHostName().split('.')[0]
+ except:
+ pass
+ return "unknown" # 'unknown' is default host name
+
+# ---
+
+def getAppName():
+ """
+ Get application name:
+ 1. try APPNAME environment variable
+ 2. if fails, return 'SALOME' as default application name
+ """
+ import os
+ return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
+
+# ---
+
+def getPortNumber():
+ """
+ Get current naming server port number:
+ 1. try NSPORT environment variable
+ 1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
+ 2. if fails, return 2809 as default port number
+ """
+ import os
+ try:
+ return int( os.getenv( "NSPORT" ) )
+ except:
+ pass
+ port = getPortFromORBcfg()
+ if port is not None: return port
+ return 2809 # '2809' is default port number
+
+# ---
+
+def getTmpDir():
+ """
+ Get directory to be used for the temporary files.
+ """
+ import os, sys
+ if sys.platform == "win32":
+ # for Windows: temporarily using home directory for tmp files;
+ # to be replaced with TEMP environment variable later...
+ dir = os.getenv("HOME")
+ else:
+ # for Linux: use /tmp/logs/{user} folder
+ dir = os.path.join( '/tmp', 'logs', getUserName() )
+ pass
+ return dir
+
+# ---
+
+def generateFileName( dir, prefix = None, suffix = None, extension = None,
+ unique = False, separator = "_", hidden = False, **kwargs ):
+ """
+ Generate file name by sepecified parameters. If necessary, file name
+ can be generated to be unique.
+
+ Parameters:
+ - dir : directory path
+ - prefix : file prefix (not added by default)
+ - suffix : file suffix (not added by default)
+ - extension : file extension (not added by default)
+ - unique : if this parameter is True, the unique file name is generated:
+ in this case, if the file with the generated name already exists
+ in the <dir> directory, an integer suffix is added to the end of the
+ file name. This parameter is False by default.
+ - separator : separator of the words ('_' by default)
+ - hidden : if this parameter is True, the file name is prepended by . (dot)
+ symbol. This parameter is False by default.
+
+ Other keyword parameters are:
+ - with_username : 'add user name' flag/option:
+ * boolean value can be passed to determine user name automatically
+ * string value to be used as user name
+ - with_hostname : 'add host name' flag/option:
+ * boolean value can be passed to determine host name automatically
+ * string value to be used as host name
+ - with_port : 'add port number' flag/option:
+ * boolean value can be passed to determine port number automatically
+ * string value to be used as port number
+ - with_app : 'add application name' flag/option:
+ * boolean value can be passed to determine application name automatically
+ * string value to be used as application name
+ All <with_...> parameters are optional.
+ """
+ supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
+ from launchConfigureParser import verbose
+ filename = []
+ # separator
+ if separator is None:
+ separator = ""
+ pass
+ else:
+ separator = str( separator )
+ pass
+ # prefix (if specified)
+ if prefix is not None:
+ filename.append( str( prefix ) )
+ pass
+ # additional keywords
+ ### check unsupported parameters
+ for kw in kwargs:
+ if kw not in supported and verbose():
+ print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
+ pass
+ pass
+ ### process supported keywords
+ for kw in supported:
+ if kw not in kwargs: continue
+ ### user name
+ if kw == 'with_username':
+ try:
+ # auto user name ?
+ if _try_bool( kwargs[kw] ): filename.append( getUserName() )
+ pass
+ except:
+ # user name given as parameter
+ filename.append( kwargs[kw] )
+ pass
+ pass
+ ### host name
+ elif kw == 'with_hostname':
+ try:
+ # auto host name ?
+ if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
+ pass
+ except:
+ # host name given as parameter
+ filename.append( kwargs[kw] )
+ pass
+ pass
+ ### port number
+ elif kw == 'with_port':
+ try:
+ # auto port number ?
+ if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
+ pass
+ except:
+ # port number given as parameter
+ filename.append( str( kwargs[kw] ) )
+ pass
+ pass
+ ### application name
+ elif kw == 'with_app':
+ try:
+ # auto application name ?
+ if _try_bool( kwargs[kw] ): filename.append( getAppName() )
+ pass
+ except:
+ # application name given as parameter
+ filename.append( kwargs[kw] )
+ pass
+ pass
+ pass
+ # suffix (if specified)
+ if suffix is not None:
+ filename.append( str( suffix ) )
+ pass
+ # raise an exception if file name is empty
+ if not filename:
+ raise Exception("Empty file name")
+ #
+ if extension is not None and extension.startswith("."): extension = extension[1:]
+ #
+ import os
+ name = separator.join( filename )
+ if hidden: name = "." + name # add dot for hidden files
+ if extension: name = name + "." + str( extension ) # add extension if defined
+ name = os.path.join( dir, name )
+ if unique:
+ # create unique file name
+ index = 0
+ while os.path.exists( name ):
+ index = index + 1
+ name = separator.join( filename ) + separator + str( index )
+ if hidden: name = "." + name # add dot for hidden files
+ if extension: name = name + "." + str( extension ) # add extension if defined
+ name = os.path.join( dir, name )
+ pass
+ pass
+ return name
#ifndef _BATCHMANAGER_LSF_H_
#define _BATCHMANAGER_LSF_H_
+#include "Batch_Defines.hxx"
#include "Batch_Job.hxx"
#include "Batch_Job.hxx"
class JobInfo;
class FactBatchManager;
- class BatchManager_LSF : public BatchManager
+ class BATCH_EXPORT BatchManager_LSF : public BatchManager
{
public:
// Constructeur et destructeur
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
/*
- * BatchManager_Local.cxx :
- *
- * Auteur : Ivan DUTKA-MALEN - EDF R&D
- * Mail : mailto:ivan.dutka-malen@der.edf.fr
- * Date : Thu Nov 6 10:17:22 2003
- * Projet : Salome 2
- *
- */
+* BatchManager_Local.cxx :
+*
+* Auteur : Ivan DUTKA-MALEN - EDF R&D
+* Mail : mailto:ivan.dutka-malen@der.edf.fr
+* Date : Thu Nov 6 10:17:22 2003
+* Projet : Salome 2
+*
+*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <sys/types.h>
-#include <sys/wait.h>
+#ifdef WIN32
+# include <direct.h>
+#else
+# include <sys/wait.h>
+# include <unistd.h>
+#endif
#include <ctime>
-#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <errno.h>
// Constructeur
- BatchManager_Local::BatchManager_Local(const FactBatchManager * parent, const char * host) throw(InvalidArgumentException,ConnexionFailureException) : BatchManager(parent, host), _connect(0), _threads_mutex(), _threads(), _thread_id_id_association_mutex(), _thread_id_id_association_cond(), _thread_id_id_association()
+ BatchManager_Local::BatchManager_Local(const FactBatchManager * parent, const char * host) throw(InvalidArgumentException,ConnexionFailureException) : BatchManager(parent, host), _connect(0), _threads_mutex(), _threads(), _thread_id_id_association_mutex(), _thread_id_id_association_cond()
+#ifndef WIN32 //TODO: porting of following functionality
+ ,_thread_id_id_association()
+#endif
{
pthread_mutex_init(&_threads_mutex, NULL);
pthread_mutex_init(&_thread_id_id_association_mutex, NULL);
cancel(thread_id);
}
-
+
// Methode pour le controle des jobs : suspend un job en file d'attente
void BatchManager_Local::holdJob(const JobId & jobid)
{
if (_threads.find(id) != _threads.end())
_threads[id].command_queue.push(RELEASE);
pthread_mutex_unlock(&_threads_mutex);
- // @@@ --------> SECTION CRITIQUE <-------- @@@
- }
+ // @@@ --------> SECTION CRITIQUE <-------- @@@
+ }
// Methode pour le controle des jobs : modifie un job en file d'attente
pthread_t BatchManager_Local::submit(const Job_Local & job)
{
// L'id du thread a creer
- pthread_t thread_id = 0;
+ pthread_t thread_id =
+#ifdef WIN32
+ {0,0};
+#else
+ 0;
+#endif
// Les attributs du thread a sa creation
pthread_attr_t thread_attr;
// Creation du thread qui va executer la commande systeme qu'on lui passe
int rc = pthread_create(&thread_id,
- &thread_attr,
- &ThreadAdapter::run,
- static_cast<void *>(p_ta));
+ &thread_attr,
+ &ThreadAdapter::run,
+ static_cast<void *>(p_ta));
if (rc) {
}
// @@@ --------> SECTION CRITIQUE <-------- @@@
pthread_mutex_lock(&_thread_id_id_association_mutex);
+#ifndef WIN32 //TODO: porting of following functionality
while (_thread_id_id_association.find(thread_id) == _thread_id_id_association.end())
pthread_cond_wait(&_thread_id_id_association_cond, &_thread_id_id_association_mutex);
id = _thread_id_id_association[thread_id];
_thread_id_id_association.erase(thread_id);
-
+#endif
+
pthread_mutex_unlock(&_thread_id_id_association_mutex);
// @@@ --------> SECTION CRITIQUE <-------- @@@
// @@@ --------> SECTION CRITIQUE <-------- @@@
pthread_mutex_lock(&_thread_id_id_association_mutex);
+#ifndef WIN32 //TODO: porting of following functionality
if (_thread_id_id_association.find(thread_id) == _thread_id_id_association.end()) {
id = _thread_id_id_association[thread_id] = nextId();
pthread_cond_signal(&_thread_id_id_association_cond);
} else {
UNDER_LOCK( cerr << "ERROR : Pthread Inconstency. Two threads own the same thread_id." << endl );
}
+#endif
pthread_mutex_unlock(&_thread_id_id_association_mutex);
// @@@ --------> SECTION CRITIQUE <-------- @@@
// Constructeur de la classe ThreadAdapter
BatchManager_Local::ThreadAdapter::ThreadAdapter(BatchManager_Local & bm, const Job_Local & job) :
- _bm(bm), _job(job)
+ _bm(bm), _job(job)
{
// Nothing to do
}
// Methode d'execution du thread
void * BatchManager_Local::ThreadAdapter::run(void * arg)
{
+#ifndef WIN32 //TODO: porting of following functionality
// On bloque tous les signaux pour ce thread
sigset_t setmask;
sigfillset(&setmask);
pthread_sigmask(SIG_BLOCK, &setmask, NULL);
-
// On autorise la terminaison differee du thread
// (ces valeurs sont les valeurs par defaut mais on les force par precaution)
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
Parametre::const_iterator it;
// On initialise la variable workdir a la valeur du Current Working Directory
- char * cwd = new char [PATH_MAX];
+ char * cwd =
+#ifdef WIN32
+ _getcwd(NULL, 0);
+#else
+ new char [PATH_MAX];
getcwd(cwd, PATH_MAX);
+#endif
string workdir = cwd;
delete [] cwd;
Versatile::iterator Vit;
for(Vit=V.begin(); Vit!=V.end(); Vit++) {
- CoupleType cpt = *static_cast< CoupleType * >(*Vit);
- Couple cp = cpt;
- string local = cp.getLocal();
- string remote = cp.getRemote();
-
- string copy_cmd = p_ta->getBatchManager().copy_command("", local, executionhost, workdir + "/" + remote);
- UNDER_LOCK( cout << "Copying : " << copy_cmd << endl );
-
- if (system(copy_cmd.c_str()) ) {
- // Echec de la copie
- rc |= 1;
- } else {
- // On enregistre le fichier comme etant a detruire
- files_to_delete.push_back(workdir + "/" + remote);
- }
+ CoupleType cpt = *static_cast< CoupleType * >(*Vit);
+ Couple cp = cpt;
+ string local = cp.getLocal();
+ string remote = cp.getRemote();
+
+ string copy_cmd = p_ta->getBatchManager().copy_command("", local, executionhost, workdir + "/" + remote);
+ UNDER_LOCK( cout << "Copying : " << copy_cmd << endl );
+
+ if (system(copy_cmd.c_str()) ) {
+ // Echec de la copie
+ rc |= 1;
+ } else {
+ // On enregistre le fichier comme etant a detruire
+ files_to_delete.push_back(workdir + "/" + remote);
+ }
}
}
-
+#ifdef WIN32
+ //TODO
+ //Using CreateThread instead fork() POSIX function
+#else
// On forke/exec un nouveau process pour pouvoir controler le fils
// (plus finement qu'avec un appel system)
// int rc = system(commande.c_str());
} else { // fils
p_ta->fils();
}
-
+#endif
Versatile::iterator Vit;
for(Vit=V.begin(); Vit!=V.end(); Vit++) {
- CoupleType cpt = *static_cast< CoupleType * >(*Vit);
- Couple cp = cpt;
- string local = cp.getLocal();
- string remote = cp.getRemote();
-
- string copy_cmd = p_ta->getBatchManager().copy_command(executionhost, workdir + "/" + remote, "", local);
- UNDER_LOCK( cout << "Copying : " << copy_cmd << endl );
-
- if (system(copy_cmd.c_str()) ) {
- // Echec de la copie
- rc |= 1;
- } else {
- // On enregistre le fichier comme etant a detruire
- files_to_delete.push_back(workdir + "/" + remote);
- }
+ CoupleType cpt = *static_cast< CoupleType * >(*Vit);
+ Couple cp = cpt;
+ string local = cp.getLocal();
+ string remote = cp.getRemote();
+
+ string copy_cmd = p_ta->getBatchManager().copy_command(executionhost, workdir + "/" + remote, "", local);
+ UNDER_LOCK( cout << "Copying : " << copy_cmd << endl );
+
+ if (system(copy_cmd.c_str()) ) {
+ // Echec de la copie
+ rc |= 1;
+ } else {
+ // On enregistre le fichier comme etant a detruire
+ files_to_delete.push_back(workdir + "/" + remote);
+ }
}
}
if ( (rc == 0) || (child < 0) ) {
std::vector<string>::const_iterator it;
for(it=files_to_delete.begin(); it!=files_to_delete.end(); it++) {
- string remove_cmd = p_ta->getBatchManager().remove_command(executionhost, *it);
- UNDER_LOCK( cout << "Removing : " << remove_cmd << endl );
- system(remove_cmd.c_str());
+ string remove_cmd = p_ta->getBatchManager().remove_command(executionhost, *it);
+ UNDER_LOCK( cout << "Removing : " << remove_cmd << endl );
+ system(remove_cmd.c_str());
}
}
UNDER_LOCK( cout << "Father is leaving" << endl );
pthread_exit(NULL);
-
+#endif
return NULL;
}
void BatchManager_Local::ThreadAdapter::pere(pid_t child)
{
+#ifndef WIN32 //TODO: porting of following functionality
time_t child_starttime = time(NULL);
// On enregistre le fils dans la table des threads
int child_rc = 0;
pid_t child_wait_rc = waitpid(child, &child_rc, WNOHANG /* | WUNTRACED */);
if (child_wait_rc > 0) {
- if (WIFSTOPPED(child_rc)) {
- // NOTA : pour rentrer dans cette section, il faut que le flag WUNTRACED
- // soit positionne dans l'appel a waitpid ci-dessus. Ce flag est couramment
- // desactive car s'il est possible de detecter l'arret d'un process, il est
- // plus difficile de detecter sa reprise.
-
- // Le fils est simplement stoppe
- // @@@ --------> SECTION CRITIQUE <-------- @@@
- pthread_mutex_lock(&_bm._threads_mutex);
- _bm._threads[id].status = STOPPED;
- _bm._threads[id].param[STATE] = "Stopped";
- pthread_mutex_unlock(&_bm._threads_mutex);
- // @@@ --------> SECTION CRITIQUE <-------- @@@
- UNDER_LOCK( cout << "Father sees his child is STOPPED : " << child_wait_rc << endl );
-
- }
- else {
- // Le fils est termine, on sort de la boucle et du if englobant
- // @@@ --------> SECTION CRITIQUE <-------- @@@
- pthread_mutex_lock(&_bm._threads_mutex);
- _bm._threads[id].status = DONE;
- _bm._threads[id].param[STATE] = "Done";
- pthread_mutex_unlock(&_bm._threads_mutex);
- // @@@ --------> SECTION CRITIQUE <-------- @@@
- UNDER_LOCK( cout << "Father sees his child is DONE : " << child_wait_rc << " (child_rc=" << (WIFEXITED(child_rc) ? WEXITSTATUS(child_rc) : -1) << ")" << endl );
- break;
- }
+ if (WIFSTOPPED(child_rc)) {
+ // NOTA : pour rentrer dans cette section, il faut que le flag WUNTRACED
+ // soit positionne dans l'appel a waitpid ci-dessus. Ce flag est couramment
+ // desactive car s'il est possible de detecter l'arret d'un process, il est
+ // plus difficile de detecter sa reprise.
+
+ // Le fils est simplement stoppe
+ // @@@ --------> SECTION CRITIQUE <-------- @@@
+ pthread_mutex_lock(&_bm._threads_mutex);
+ _bm._threads[id].status = STOPPED;
+ _bm._threads[id].param[STATE] = "Stopped";
+ pthread_mutex_unlock(&_bm._threads_mutex);
+ // @@@ --------> SECTION CRITIQUE <-------- @@@
+ UNDER_LOCK( cout << "Father sees his child is STOPPED : " << child_wait_rc << endl );
+
+ }
+ else {
+ // Le fils est termine, on sort de la boucle et du if englobant
+ // @@@ --------> SECTION CRITIQUE <-------- @@@
+ pthread_mutex_lock(&_bm._threads_mutex);
+ _bm._threads[id].status = DONE;
+ _bm._threads[id].param[STATE] = "Done";
+ pthread_mutex_unlock(&_bm._threads_mutex);
+ // @@@ --------> SECTION CRITIQUE <-------- @@@
+ UNDER_LOCK( cout << "Father sees his child is DONE : " << child_wait_rc << " (child_rc=" << (WIFEXITED(child_rc) ? WEXITSTATUS(child_rc) : -1) << ")" << endl );
+ break;
+ }
}
else if (child_wait_rc == -1) {
- // Le fils a disparu ...
- // @@@ --------> SECTION CRITIQUE <-------- @@@
- pthread_mutex_lock(&_bm._threads_mutex);
- _bm._threads[id].status = DEAD;
- _bm._threads[id].param[STATE] = "Dead";
- pthread_mutex_unlock(&_bm._threads_mutex);
- // @@@ --------> SECTION CRITIQUE <-------- @@@
- UNDER_LOCK( cout << "Father sees his child is DEAD : " << child_wait_rc << " (Reason : " << strerror(errno) << ")" << endl );
- break;
+ // Le fils a disparu ...
+ // @@@ --------> SECTION CRITIQUE <-------- @@@
+ pthread_mutex_lock(&_bm._threads_mutex);
+ _bm._threads[id].status = DEAD;
+ _bm._threads[id].param[STATE] = "Dead";
+ pthread_mutex_unlock(&_bm._threads_mutex);
+ // @@@ --------> SECTION CRITIQUE <-------- @@@
+ UNDER_LOCK( cout << "Father sees his child is DEAD : " << child_wait_rc << " (Reason : " << strerror(errno) << ")" << endl );
+ break;
}
time_t child_currenttime = time(NULL);
time_t child_elapsedtime = child_currenttime - child_starttime;
if (param.find(MAXWALLTIME) != param.end()) {
- int maxwalltime = param[MAXWALLTIME];
- // cout << "child_starttime = " << child_starttime << endl
- // << "child_currenttime = " << child_currenttime << endl
- // << "child_elapsedtime = " << child_elapsedtime << endl
- // << "maxwalltime = " << maxwalltime << endl
- // << "int(maxwalltime * 1.1) = " << int(maxwalltime * 1.1) << endl;
- if (child_elapsedtime > int(maxwalltime * 1.1) ) { // On se donne 10% de marge avant le KILL
- UNDER_LOCK( cout << "Father is sending KILL command to the thread " << id << endl );
- // On introduit une commande dans la queue du thread
- // @@@ --------> SECTION CRITIQUE <-------- @@@
- pthread_mutex_lock(&_bm._threads_mutex);
- if (_bm._threads.find(id) != _bm._threads.end())
- _bm._threads[id].command_queue.push(KILL);
- pthread_mutex_unlock(&_bm._threads_mutex);
- // @@@ --------> SECTION CRITIQUE <-------- @@@
-
-
- } else if (child_elapsedtime > maxwalltime ) {
- UNDER_LOCK( cout << "Father is sending TERM command to the thread " << id << endl );
- // On introduit une commande dans la queue du thread
- // @@@ --------> SECTION CRITIQUE <-------- @@@
- pthread_mutex_lock(&_bm._threads_mutex);
- if (_bm._threads.find(id) != _bm._threads.end())
- _bm._threads[id].command_queue.push(TERM);
- pthread_mutex_unlock(&_bm._threads_mutex);
- // @@@ --------> SECTION CRITIQUE <-------- @@@
- }
+ int maxwalltime = param[MAXWALLTIME];
+ // cout << "child_starttime = " << child_starttime << endl
+ // << "child_currenttime = " << child_currenttime << endl
+ // << "child_elapsedtime = " << child_elapsedtime << endl
+ // << "maxwalltime = " << maxwalltime << endl
+ // << "int(maxwalltime * 1.1) = " << int(maxwalltime * 1.1) << endl;
+ if (child_elapsedtime > int(maxwalltime * 1.1) ) { // On se donne 10% de marge avant le KILL
+ UNDER_LOCK( cout << "Father is sending KILL command to the thread " << id << endl );
+ // On introduit une commande dans la queue du thread
+ // @@@ --------> SECTION CRITIQUE <-------- @@@
+ pthread_mutex_lock(&_bm._threads_mutex);
+ if (_bm._threads.find(id) != _bm._threads.end())
+ _bm._threads[id].command_queue.push(KILL);
+ pthread_mutex_unlock(&_bm._threads_mutex);
+ // @@@ --------> SECTION CRITIQUE <-------- @@@
+
+
+ } else if (child_elapsedtime > maxwalltime ) {
+ UNDER_LOCK( cout << "Father is sending TERM command to the thread " << id << endl );
+ // On introduit une commande dans la queue du thread
+ // @@@ --------> SECTION CRITIQUE <-------- @@@
+ pthread_mutex_lock(&_bm._threads_mutex);
+ if (_bm._threads.find(id) != _bm._threads.end())
+ _bm._threads[id].command_queue.push(TERM);
+ pthread_mutex_unlock(&_bm._threads_mutex);
+ // @@@ --------> SECTION CRITIQUE <-------- @@@
+ }
}
// @@@ --------> SECTION CRITIQUE <-------- @@@
pthread_mutex_lock(&_bm._threads_mutex);
if (_bm._threads.find(id) != _bm._threads.end()) {
- while (_bm._threads[id].command_queue.size() > 0) {
- Commande cmd = _bm._threads[id].command_queue.front();
- _bm._threads[id].command_queue.pop();
-
- switch (cmd) {
- case NOP:
- UNDER_LOCK( cout << "Father does nothing to his child" << endl );
- break;
-
- case HOLD:
- UNDER_LOCK( cout << "Father is sending SIGSTOP signal to his child" << endl );
- kill(child, SIGSTOP);
- break;
-
- case RELEASE:
- UNDER_LOCK( cout << "Father is sending SIGCONT signal to his child" << endl );
- kill(child, SIGCONT);
- break;
-
- case TERM:
- UNDER_LOCK( cout << "Father is sending SIGTERM signal to his child" << endl );
- kill(child, SIGTERM);
- break;
-
- case KILL:
- UNDER_LOCK( cout << "Father is sending SIGKILL signal to his child" << endl );
- kill(child, SIGKILL);
- break;
-
- case ALTER:
- break;
-
- default:
- break;
- }
- }
-
+ while (_bm._threads[id].command_queue.size() > 0) {
+ Commande cmd = _bm._threads[id].command_queue.front();
+ _bm._threads[id].command_queue.pop();
+
+ switch (cmd) {
+ case NOP:
+ UNDER_LOCK( cout << "Father does nothing to his child" << endl );
+ break;
+
+ case HOLD:
+ UNDER_LOCK( cout << "Father is sending SIGSTOP signal to his child" << endl );
+ kill(child, SIGSTOP);
+ break;
+
+ case RELEASE:
+ UNDER_LOCK( cout << "Father is sending SIGCONT signal to his child" << endl );
+ kill(child, SIGCONT);
+ break;
+
+ case TERM:
+ UNDER_LOCK( cout << "Father is sending SIGTERM signal to his child" << endl );
+ kill(child, SIGTERM);
+ break;
+
+ case KILL:
+ UNDER_LOCK( cout << "Father is sending SIGKILL signal to his child" << endl );
+ kill(child, SIGKILL);
+ break;
+
+ case ALTER:
+ break;
+
+ default:
+ break;
+ }
+ }
+
}
pthread_mutex_unlock(&_bm._threads_mutex);
// @@@ --------> SECTION CRITIQUE <-------- @@@
// On fait une petite pause pour ne pas surcharger inutilement le processeur
sleep(1);
-
+
}
+#endif
}
void BatchManager_Local::ThreadAdapter::fils()
{
+#ifndef WIN32 //TODO: porting of following functionality
Parametre param = _job.getParametre();
Parametre::iterator it;
try {
- // On se place dans le repertoire de travail
- if ( (it = param.find(WORKDIR)) != param.end() ) {
- string workdir = static_cast<string>( (*it).second );
- chdir(workdir.c_str());
- }
+ // On se place dans le repertoire de travail
+ if ( (it = param.find(WORKDIR)) != param.end() ) {
+ string workdir = static_cast<string>( (*it).second );
+ chdir(workdir.c_str());
+ }
+
+ // EXECUTABLE is MANDATORY, if missing, we exit with failure notification
+ char * execpath = NULL;
+ if (param.find(EXECUTABLE) != param.end()) {
+ string executable = _bm.exec_command(param);
+ execpath = new char [executable.size() + 1];
+ strncpy(execpath, executable.c_str(), executable.size() + 1);
+ } else exit(1);
- // EXECUTABLE is MANDATORY, if missing, we exit with failure notification
- char * execpath = NULL;
- if (param.find(EXECUTABLE) != param.end()) {
- string executable = _bm.exec_command(param);
- execpath = new char [executable.size() + 1];
- strncpy(execpath, executable.c_str(), executable.size() + 1);
- } else exit(1);
+ string debug_command = execpath;
- string debug_command = execpath;
+ string name = (param.find(NAME) != param.end()) ? param[NAME] : param[EXECUTABLE];
- string name = (param.find(NAME) != param.end()) ? param[NAME] : param[EXECUTABLE];
+ char ** argv = NULL;
+ if (param.find(ARGUMENTS) != param.end()) {
+ Versatile V = param[ARGUMENTS];
- char ** argv = NULL;
- if (param.find(ARGUMENTS) != param.end()) {
- Versatile V = param[ARGUMENTS];
+ argv = new char * [V.size() + 2]; // 1 pour name et 1 pour le NULL terminal
- argv = new char * [V.size() + 2]; // 1 pour name et 1 pour le NULL terminal
+ argv[0] = new char [name.size() + 1];
+ strncpy(argv[0], name.c_str(), name.size() + 1);
- argv[0] = new char [name.size() + 1];
- strncpy(argv[0], name.c_str(), name.size() + 1);
+ debug_command += string(" # ") + argv[0];
- debug_command += string(" # ") + argv[0];
+ int i = 1;
+ for(Versatile::const_iterator it=V.begin(); it!=V.end(); it++, i++) {
+ StringType argt = * static_cast<StringType *>(*it);
+ string arg = argt;
+ argv[i] = new char [arg.size() + 1];
+ strncpy(argv[i], arg.c_str(), arg.size() + 1);
+ debug_command += string(" # ") + argv[i];
+ }
- int i = 1;
- for(Versatile::const_iterator it=V.begin(); it!=V.end(); it++, i++) {
- StringType argt = * static_cast<StringType *>(*it);
- string arg = argt;
- argv[i] = new char [arg.size() + 1];
- strncpy(argv[i], arg.c_str(), arg.size() + 1);
- debug_command += string(" # ") + argv[i];
+ // assert (i == V.size() + 1)
+ argv[i] = NULL;
}
- // assert (i == V.size() + 1)
- argv[i] = NULL;
- }
+ UNDER_LOCK( cout << "*** debug_command = " << debug_command << endl );
- UNDER_LOCK( cout << "*** debug_command = " << debug_command << endl );
+ Environnement env = _job.getEnvironnement();
- Environnement env = _job.getEnvironnement();
+ char ** envp = NULL;
+ if(env.size() > 0) {
+ envp = new char * [env.size() + 1]; // 1 pour le NULL terminal
+ int i = 0;
+ for(Environnement::const_iterator it=env.begin(); it!=env.end(); it++, i++) {
+ const string & key = (*it).first;
+ const string & value = (*it).second;
+ ostringstream oss;
+ oss << key << "=" << value;
+ envp[i] = new char [oss.str().size() + 1];
+ strncpy(envp[i], oss.str().c_str(), oss.str().size() + 1);
+ }
- char ** envp = NULL;
- if(env.size() > 0) {
- envp = new char * [env.size() + 1]; // 1 pour le NULL terminal
- int i = 0;
- for(Environnement::const_iterator it=env.begin(); it!=env.end(); it++, i++) {
- const string & key = (*it).first;
- const string & value = (*it).second;
- ostringstream oss;
- oss << key << "=" << value;
- envp[i] = new char [oss.str().size() + 1];
- strncpy(envp[i], oss.str().c_str(), oss.str().size() + 1);
+ // assert (i == env.size())
+ envp[i] = NULL;
}
- // assert (i == env.size())
- envp[i] = NULL;
- }
+ // On positionne les limites systeme imposees au fils
+ if (param.find(MAXCPUTIME) != param.end()) {
+ int maxcputime = param[MAXCPUTIME];
+ struct rlimit limit;
+ limit.rlim_cur = maxcputime;
+ limit.rlim_max = int(maxcputime * 1.1);
+ setrlimit(RLIMIT_CPU, &limit);
+ }
- // On positionne les limites systeme imposees au fils
- if (param.find(MAXCPUTIME) != param.end()) {
- int maxcputime = param[MAXCPUTIME];
- struct rlimit limit;
- limit.rlim_cur = maxcputime;
- limit.rlim_max = int(maxcputime * 1.1);
- setrlimit(RLIMIT_CPU, &limit);
- }
+ if (param.find(MAXDISKSIZE) != param.end()) {
+ int maxdisksize = param[MAXDISKSIZE];
+ struct rlimit limit;
+ limit.rlim_cur = maxdisksize * 1024;
+ limit.rlim_max = int(maxdisksize * 1.1) * 1024;
+ setrlimit(RLIMIT_FSIZE, &limit);
+ }
- if (param.find(MAXDISKSIZE) != param.end()) {
- int maxdisksize = param[MAXDISKSIZE];
- struct rlimit limit;
- limit.rlim_cur = maxdisksize * 1024;
- limit.rlim_max = int(maxdisksize * 1.1) * 1024;
- setrlimit(RLIMIT_FSIZE, &limit);
- }
+ if (param.find(MAXRAMSIZE) != param.end()) {
+ int maxramsize = param[MAXRAMSIZE];
+ struct rlimit limit;
+ limit.rlim_cur = maxramsize * 1024;
+ limit.rlim_max = int(maxramsize * 1.1) * 1024;
+ setrlimit(RLIMIT_AS, &limit);
+ }
- if (param.find(MAXRAMSIZE) != param.end()) {
- int maxramsize = param[MAXRAMSIZE];
- struct rlimit limit;
- limit.rlim_cur = maxramsize * 1024;
- limit.rlim_max = int(maxramsize * 1.1) * 1024;
- setrlimit(RLIMIT_AS, &limit);
- }
+ // On cree une session pour le fils de facon a ce qu'il ne soit pas
+ // detruit lorsque le shell se termine (le shell ouvre une session et
+ // tue tous les process appartenant a la session en quittant)
+ setsid();
- // On cree une session pour le fils de facon a ce qu'il ne soit pas
- // detruit lorsque le shell se termine (le shell ouvre une session et
- // tue tous les process appartenant a la session en quittant)
- setsid();
+ // On ferme les descripteurs de fichiers standards
+ //close(STDIN_FILENO);
+ //close(STDOUT_FILENO);
+ //close(STDERR_FILENO);
- // On ferme les descripteurs de fichiers standards
- //close(STDIN_FILENO);
- //close(STDOUT_FILENO);
- //close(STDERR_FILENO);
+ // On execute la commande du fils
+ execve(execpath, argv, envp);
- // On execute la commande du fils
- execve(execpath, argv, envp);
+ // No need to deallocate since nothing happens after a successful exec
- // No need to deallocate since nothing happens after a successful exec
+ // Normalement on ne devrait jamais arriver ici
+ ofstream file_err("error.log");
+ UNDER_LOCK( file_err << "Echec de l'appel a execve" << endl );
- // Normalement on ne devrait jamais arriver ici
- ofstream file_err("error.log");
- UNDER_LOCK( file_err << "Echec de l'appel a execve" << endl );
-
} catch (GenericException & e) {
-
+
std::cerr << "Caught exception : " << e.type << " : " << e.message << std::endl;
}
exit(99);
-
+#endif
}
void BatchManager_Local::kill_child_on_exit(void * p_pid)
{
+#ifndef WIN32
+ //TODO: porting of following functionality
pid_t child = * static_cast<pid_t *>(p_pid);
// On tue le fils
// Nota : on pourrait aussi faire a la suite un kill(child, SIGKILL)
// mais cette option n'est pas implementee pour le moment, car il est
// preferable de laisser le process fils se terminer normalement et seul.
-
+#endif
}
void BatchManager_Local::delete_on_exit(void * arg)
#ifndef _BATCHMANAGER_LOCAL_H_
#define _BATCHMANAGER_LOCAL_H_
+#include "Batch_Defines.hxx"
#include <vector>
#include <map>
class FactBatchManager;
- class BatchManager_Local : public BatchManager
+ class BATCH_EXPORT BatchManager_Local : public BatchManager
{
private:
friend class ThreadAdapter;
Id registerThread_id(pthread_t thread_id);
pthread_mutex_t _thread_id_id_association_mutex;
pthread_cond_t _thread_id_id_association_cond;
+#ifndef WIN32 //TODO: porting of following functionality
+ //reason: pthread_t on win32 is a struct of pointer and int members
map<pthread_t, Id> _thread_id_id_association;
+#endif
#ifdef SWIG
public:
#include <sstream>
#include <cstdlib>
#include <sys/types.h>
+#ifndef WIN32
#include <sys/wait.h>
-#include <ctime>
#include <unistd.h>
+#endif
+#include <ctime>
#include <pthread.h>
#include <signal.h>
#include <errno.h>
#ifndef _BATCHMANAGER_LOCAL_RSH_H_
#define _BATCHMANAGER_LOCAL_RSH_H_
+#include "Batch_Defines.hxx"
#include <vector>
#include <map>
class FactBatchManager;
- class BatchManager_Local_RSH : public BatchManager_Local
+ class BATCH_EXPORT BatchManager_Local_RSH : public BatchManager_Local
{
public:
// Constructeur et destructeur
#include <sstream>
#include <cstdlib>
#include <sys/types.h>
+#ifndef WIN32
#include <sys/wait.h>
+#endif
#include <ctime>
#include <unistd.h>
#include <pthread.h>
#ifndef _BATCHMANAGER_LOCAL_SH_H_
#define _BATCHMANAGER_LOCAL_SH_H_
+#include "Batch_Defines.hxx"
#include <vector>
#include <map>
class FactBatchManager;
- class BatchManager_Local_SH : public BatchManager_Local
+ class BATCH_EXPORT BatchManager_Local_SH : public BatchManager_Local
{
public:
// Constructeur et destructeur
#include <sstream>
#include <cstdlib>
#include <sys/types.h>
+#ifndef WIN32
#include <sys/wait.h>
-#include <ctime>
#include <unistd.h>
+#endif
+#include <ctime>
+
#include <pthread.h>
#include <signal.h>
#include <errno.h>
#ifndef _BATCHMANAGER_LOCAL_SSH_H_
#define _BATCHMANAGER_LOCAL_SSH_H_
+#include "Batch_Defines.hxx"
#include <vector>
#include <map>
class FactBatchManager;
- class BatchManager_Local_SSH : public BatchManager_Local
+ class BATCH_EXPORT BatchManager_Local_SSH : public BatchManager_Local
{
public:
// Constructeur et destructeur
#ifndef _BATCHMANAGER_PBS_H_
#define _BATCHMANAGER_PBS_H_
+#include "Batch_Defines.hxx"
#include "Batch_Job.hxx"
#include "Batch_Job.hxx"
class JobInfo;
class FactBatchManager;
- class BatchManager_PBS : public BatchManager
+ class BATCH_EXPORT BatchManager_PBS : public BatchManager
{
public:
// Constructeur et destructeur
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
/*
- * BatchManager_eLSF.cxx : emulation of LSF client
- *
- * Auteur : Bernard SECHER - CEA DEN
- * Mail : mailto:bernard.secher@cea.fr
- * Date : Thu Apr 24 10:17:22 2008
- * Projet : PAL Salome
- *
- */
+* BatchManager_eLSF.cxx : emulation of LSF client
+*
+* Auteur : Bernard SECHER - CEA DEN
+* Mail : mailto:bernard.secher@cea.fr
+* Date : Thu Apr 24 10:17:22 2008
+* Projet : PAL Salome
+*
+*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <sys/stat.h>
#include "Batch_BatchManager_eClient.hxx"
+#include "OpUtil.hxx"
namespace Batch {
copy_command = "scp ";
else
throw EmulationException("Unknown protocol : only rsh and ssh are known !");
-
+
// First step : creating batch tmp files directory
command = _protocol;
command += " ";
ex_mess += oss.str();
throw EmulationException(ex_mess.c_str());
}
-
+
// Third step : copy filesToExportList into
// batch tmp files directory
for(Vit=V.begin(); Vit!=V.end(); Vit++) {
command += inputFile.getLocal();
command += " ";
if(_username != ""){
- command += _username;
- command += "@";
+ command += _username;
+ command += "@";
}
command += _hostname;
command += ":";
cerr << command.c_str() << endl;
status = system(command.c_str());
if(status) {
- std::ostringstream oss;
- oss << status;
- std::string ex_mess("Error of connection on remote host ! status = ");
- ex_mess += oss.str();
- throw EmulationException(ex_mess.c_str());
+ std::ostringstream oss;
+ oss << status;
+ std::string ex_mess("Error of connection on remote host ! status = ");
+ ex_mess += oss.str();
+ throw EmulationException(ex_mess.c_str());
}
}
Parametre params = job.getParametre();
Versatile V = params[OUTFILE];
Versatile::iterator Vit;
-
+
for(Vit=V.begin(); Vit!=V.end(); Vit++) {
CoupleType cpt = *static_cast< CoupleType * >(*Vit);
Couple outputFile = cpt;
if( _protocol == "rsh" )
- command = "rcp ";
+ command = "rcp ";
else if( _protocol == "ssh" )
- command = "scp ";
+ command = "scp ";
else
- throw EmulationException("Unknown protocol");
+ throw EmulationException("Unknown protocol");
if (_username != ""){
- command += _username;
- command += "@";
+ command += _username;
+ command += "@";
}
command += _hostname;
command += ":";
status = system(command.c_str());
if(status)
{
- // Try to get what we can (logs files)
- // throw BatchException("Error of connection on remote host");
- std::string mess("Copy command failed ! status is :");
- ostringstream status_str;
- status_str << status;
- mess += status_str.str();
- cerr << mess << endl;
+ // Try to get what we can (logs files)
+ // throw BatchException("Error of connection on remote host");
+ std::string mess("Copy command failed ! status is :");
+ ostringstream status_str;
+ status_str << status;
+ mess += status_str.str();
+ cerr << mess << endl;
}
}
string BatchManager_eClient::BuildTemporaryFileName() const
{
//build more complex file name to support multiple salome session
- char *temp = new char[19];
- strcpy(temp, "/tmp/command");
- strcat(temp, "XXXXXX");
-#ifndef WNT
- mkstemp(temp);
+ string aFileName = OpUtil_Dir::GetTmpFileName();
+#ifndef WIN32
+ aFileName += ".sh";
#else
- char aPID[80];
- itoa(getpid(), aPID, 10);
- strcat(temp, aPID);
+ aFileName += ".bat";
#endif
-
- string command(temp);
- delete [] temp;
- command += ".sh";
- return command;
+ return aFileName;
}
void BatchManager_eClient::RmTmpFile(std::string & TemporaryFileName)
{
+#ifdef WIN32
+ string command = "del /F ";
+#else
string command = "rm ";
+#endif
command += TemporaryFileName;
char *temp = strdup(command.c_str());
int lgthTemp = strlen(temp);
system(temp);
free(temp);
}
-
}
#ifndef _BATCHMANAGER_eClient_H_
#define _BATCHMANAGER_eClient_H_
+#include "Batch_Defines.hxx"
#include "MpiImpl.hxx"
#include "Batch_BatchManager.hxx"
class Job;
- class EmulationException
+ class BATCH_EXPORT EmulationException
{
public:
const std::string msg;
EmulationException(const std::string m) : msg(m) {}
};
- class BatchManager_eClient : public BatchManager
+ class BATCH_EXPORT BatchManager_eClient : public BatchManager
{
public:
// Constructeur et destructeur
#include <sstream>
#include <sys/stat.h>
#include "Batch_BatchManager_eLSF.hxx"
+#ifdef WIN32
+# include <time.h>
+# include <io.h>
+#endif
namespace Batch {
void BatchManager_eLSF::buildBatchScript(const Job & job) throw(EmulationException)
{
+#ifndef WIN32 //TODO: need for porting on Windows
int status;
Parametre params = job.getParametre();
const int nbproc = params[NBPROC];
tempOutputFile << _mpiImpl->halt();
tempOutputFile.flush();
tempOutputFile.close();
- chmod(TmpFileName.c_str(), 0x1ED);
+#ifdef WIN32
+ _chmod(
+#else
+ chmod(
+#endif
+ TmpFileName.c_str(), 0x1ED);
cerr << TmpFileName.c_str() << endl;
string command;
throw EmulationException("Error of connection on remote host");
RmTmpFile(TmpFileName);
+#endif
}
#ifndef _BATCHMANAGER_eLSF_H_
#define _BATCHMANAGER_eLSF_H_
+#include "Batch_Defines.hxx"
#include "Batch_JobId.hxx"
#include "Batch_JobInfo.hxx"
class JobInfo;
class FactBatchManager;
- class BatchManager_eLSF : public BatchManager_eClient
+ class BATCH_EXPORT BatchManager_eLSF : public BatchManager_eClient
{
public:
// Constructeur et destructeur
#include <sstream>
#include <sys/stat.h>
#include "Batch_BatchManager_ePBS.hxx"
+#ifdef WIN32
+# include <time.h>
+# include <io.h>
+#endif
namespace Batch {
void BatchManager_ePBS::buildBatchScript(const Job & job) throw(EmulationException)
{
+#ifndef WIN32 //TODO: need for porting on Windows
int status;
Parametre params = job.getParametre();
const long nbproc = params[NBPROC];
tempOutputFile << _mpiImpl->halt();
tempOutputFile.flush();
tempOutputFile.close();
- chmod(TmpFileName.c_str(), 0x1ED);
+#ifdef WIN32
+ _chmod(
+#else
+ chmod(
+#endif
+ TmpFileName.c_str(), 0x1ED);
cerr << TmpFileName.c_str() << endl;
string command;
throw EmulationException("Error of connection on remote host");
RmTmpFile(TmpFileName);
-
+#endif
}
}
#ifndef _BATCHMANAGER_eLSF_H_
#define _BATCHMANAGER_eLSF_H_
+#include "Batch_Defines.hxx"
+
#include "Batch_JobId.hxx"
#include "Batch_JobInfo.hxx"
#include "Batch_JobInfo_ePBS.hxx"
class JobInfo;
class FactBatchManager;
- class BatchManager_ePBS : public BatchManager_eClient
+ class BATCH_EXPORT BatchManager_ePBS : public BatchManager_eClient
{
public:
// Constructeur et destructeur
#ifndef _FACTBATCHMANAGER_eLSF_H_
#define _FACTBATCHMANAGER_eLSF_H_
-using namespace std;
+#include "Batch_Defines.hxx"
+
#include <string>
#include <map>
#include "Batch_BatchManager_eClient.hxx"
class BatchManager_eLSF;
- class FactBatchManager_eLSF : public FactBatchManager_eClient
+ class BATCH_EXPORT FactBatchManager_eLSF : public FactBatchManager_eClient
{
public:
// Constructeur et destructeur
#ifndef _FACTBATCHMANAGER_ePBS_H_
#define _FACTBATCHMANAGER_ePBS_H_
-using namespace std;
+#include "Batch_Defines.hxx"
+
#include <string>
#include <map>
#include "Batch_BatchManager_eClient.hxx"
class BatchManager_ePBS;
- class FactBatchManager_ePBS : public FactBatchManager_eClient
+ class BATCH_EXPORT FactBatchManager_ePBS : public FactBatchManager_eClient
{
public:
// Constructeur et destructeur
#include <stdio.h>
#include <stdlib.h>
+#ifndef WIN32
#include <unistd.h>
+#endif
#include "Batch_Job_Local.hxx"
namespace Batch {
// TODO : remplacer ce mecanisme statique par la lecture
// TODO : d'une descrption dans un fichier exterieur (genre XML)
-#define def_extern_MapKey(mk) extern const string & mk;
+#define def_extern_MapKey(mk) extern BATCH_EXPORT const string & mk;
#define def_static_MapKey(mk) const string Batch::Parametre::mk(#mk); \
const string & mk = Batch::Parametre::mk;
${PYTHON_INCLUDES} \
-I$(srcdir)/../Basics \
-I$(srcdir)/../SALOMELocalTrace \
- -I$(top_builddir)/salome_adm/unix
+ -I$(srcdir)/../Utils \
+ -I$(top_builddir)/salome_adm/unix
LIB_LIBADD = \
../SALOMELocalTrace/libSALOMELocalTrace.la \
#ifndef _BL_MPIIMPL_H_
#define _BL_MPIIMPL_H_
+#include "Batch_Defines.hxx"
#include <string>
-class MpiImplException
+class BATCH_EXPORT MpiImplException
{
public:
const std::string msg;
MpiImplException(const std::string m) : msg(m) {}
};
-class MpiImpl
+class BATCH_EXPORT MpiImpl
{
public:
// Constructeur et destructeur
};
-class MpiImpl_LAM : public MpiImpl
+class BATCH_EXPORT MpiImpl_LAM : public MpiImpl
{
public:
// Constructeur et destructeur
};
-class MpiImpl_MPICH1 : public MpiImpl
+class BATCH_EXPORT MpiImpl_MPICH1 : public MpiImpl
{
public:
// Constructeur et destructeur
};
-class MpiImpl_MPICH2 : public MpiImpl
+class BATCH_EXPORT MpiImpl_MPICH2 : public MpiImpl
{
public:
// Constructeur et destructeur
};
-class MpiImpl_OPENMPI : public MpiImpl
+class BATCH_EXPORT MpiImpl_OPENMPI : public MpiImpl
{
public:
// Constructeur et destructeur
};
-class MpiImpl_SLURM : public MpiImpl
+class BATCH_EXPORT MpiImpl_SLURM : public MpiImpl
{
public:
// Constructeur et destructeur
// Other Containers are started via start_impl of FactoryServer
extern "C" {void ActSigIntHandler() ; }
-#ifndef WNT
- extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
+#ifndef WIN32
+extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
#else
- extern "C" {void SigIntHandler( int ) ; }
+extern "C" {void SigIntHandler( int ) ; }
+#endif
+
+#ifdef WIN32
+# define separator '\\'
+#else
+# define separator '/'
#endif
//=============================================================================
/*!
- * Default constructor, not for use
- */
+* Default constructor, not for use
+*/
//=============================================================================
Engines_Container_i::Engines_Container_i () :
- _numInstance(0)
+_numInstance(0)
{
}
//=============================================================================
/*!
- * Construtor to use
- */
+* Construtor to use
+*/
//=============================================================================
Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb,
bool activAndRegist,
bool isServantAloneInProcess
) :
- _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
+_numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
{
_pid = (long)getpid();
string hostname = GetHostname();
#ifndef WNT
MESSAGE(hostname << " " << getpid() <<
- " Engines_Container_i starting argc " <<
- _argc << " Thread " << pthread_self() ) ;
+ " Engines_Container_i starting argc " <<
+ _argc << " Thread " << pthread_self() ) ;
#else
MESSAGE(hostname << " " << _getpid() <<
- " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
+ " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
#endif
int i = 0 ;
while ( _argv[ i ] )
- {
- MESSAGE(" argv" << i << " " << _argv[ i ]) ;
- i++ ;
- }
+ {
+ MESSAGE(" argv" << i << " " << _argv[ i ]) ;
+ i++ ;
+ }
if ( argc < 2 )
- {
- INFOS("SALOME_Container usage : SALOME_Container ServerName");
- ASSERT(0) ;
- }
+ {
+ INFOS("SALOME_Container usage : SALOME_Container ServerName");
+ ASSERT(0) ;
+ }
SCRUTE(argv[1]);
_isSupervContainer = false;
if (strcmp(argv[1],"SuperVisionContainer") == 0) _isSupervContainer = true;
if (_isSupervContainer)
- {
- _ArgC = argc ;
- _ArgV = argv ;
- }
+ {
+ _ArgC = argc ;
+ _ArgV = argv ;
+ }
_orb = CORBA::ORB::_duplicate(orb) ;
_poa = PortableServer::POA::_duplicate(poa) ;
-
+
// Pour les containers paralleles: il ne faut pas enregistrer et activer
// le container generique, mais le container specialise
if(activAndRegist)
+ {
+ _id = _poa->activate_object(this);
+ _NS = new SALOME_NamingService();
+ _NS->init_orb( _orb ) ;
+ CORBA::Object_var obj=_poa->id_to_reference(*_id);
+ Engines::Container_var pCont
+ = Engines::Container::_narrow(obj);
+ _remove_ref();
+
+ _containerName = _NS->BuildContainerNameForNS(containerName,
+ hostname.c_str());
+ SCRUTE(_containerName);
+ _NS->Register(pCont, _containerName.c_str());
+ MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
+ << _containerName);
+
+ // Python:
+ // import SALOME_Container
+ // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
+
+ CORBA::String_var sior = _orb->object_to_string(pCont);
+ string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
+ myCommand += _containerName + "','";
+ myCommand += sior;
+ myCommand += "')\n";
+ SCRUTE(myCommand);
+
+ if (!_isSupervContainer)
{
- _id = _poa->activate_object(this);
- _NS = new SALOME_NamingService();
- _NS->init_orb( _orb ) ;
- CORBA::Object_var obj=_poa->id_to_reference(*_id);
- Engines::Container_var pCont
- = Engines::Container::_narrow(obj);
- _remove_ref();
-
- _containerName = _NS->BuildContainerNameForNS(containerName,
- hostname.c_str());
- SCRUTE(_containerName);
- _NS->Register(pCont, _containerName.c_str());
- MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
- << _containerName);
-
- // Python:
- // import SALOME_Container
- // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
-
- CORBA::String_var sior = _orb->object_to_string(pCont);
- string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
- myCommand += _containerName + "','";
- myCommand += sior;
- myCommand += "')\n";
- SCRUTE(myCommand);
-
- if (!_isSupervContainer)
- {
#ifdef WNT
- PyEval_AcquireLock();
- PyThreadState *myTstate = PyThreadState_New(KERNEL_PYTHON::_interp);
- PyThreadState *myoldTstate = PyThreadState_Swap(myTstate);
+ PyEval_AcquireLock();
+ PyThreadState *myTstate = PyThreadState_New(KERNEL_PYTHON::_interp);
+ PyThreadState *myoldTstate = PyThreadState_Swap(myTstate);
#else
- Py_ACQUIRE_NEW_THREAD;
+ Py_ACQUIRE_NEW_THREAD;
#endif
#ifdef WNT
- // mpv: this is temporary solution: there is a unregular crash if not
- //Sleep(2000);
- //
- // first element is the path to Registry.dll, but it's wrong
- PyRun_SimpleString("import sys\n");
- PyRun_SimpleString("sys.path = sys.path[1:]\n");
+ // mpv: this is temporary solution: there is a unregular crash if not
+ //Sleep(2000);
+ //
+ // first element is the path to Registry.dll, but it's wrong
+ PyRun_SimpleString("import sys\n");
+ PyRun_SimpleString("sys.path = sys.path[1:]\n");
#endif
- PyRun_SimpleString("import SALOME_Container\n");
- PyRun_SimpleString((char*)myCommand.c_str());
- Py_RELEASE_NEW_THREAD;
- }
-
- fileTransfer_i* aFileTransfer = new fileTransfer_i();
- CORBA::Object_var obref=aFileTransfer->_this();
- _fileTransfer = Engines::fileTransfer::_narrow(obref);
- aFileTransfer->_remove_ref();
+ PyRun_SimpleString("import SALOME_Container\n");
+ PyRun_SimpleString((char*)myCommand.c_str());
+ Py_RELEASE_NEW_THREAD;
}
+
+ fileTransfer_i* aFileTransfer = new fileTransfer_i();
+ CORBA::Object_var obref=aFileTransfer->_this();
+ _fileTransfer = Engines::fileTransfer::_narrow(obref);
+ aFileTransfer->_remove_ref();
+ }
}
//=============================================================================
/*!
- * Destructor
- */
+* Destructor
+*/
//=============================================================================
Engines_Container_i::~Engines_Container_i()
//=============================================================================
/*!
- * CORBA attribute: Container name (see constructor)
- */
+* CORBA attribute: Container name (see constructor)
+*/
//=============================================================================
char* Engines_Container_i::name()
{
- return CORBA::string_dup(_containerName.c_str()) ;
+ return CORBA::string_dup(_containerName.c_str()) ;
}
//=============================================================================
/*!
- * CORBA attribute: Container working directory
- */
+* CORBA attribute: Container working directory
+*/
//=============================================================================
char* Engines_Container_i::workingdir()
//=============================================================================
/*!
- * CORBA attribute: Container log file name
- */
+* CORBA attribute: Container log file name
+*/
//=============================================================================
char* Engines_Container_i::logfilename()
//=============================================================================
/*!
- * CORBA method: Get the hostName of the Container (without domain extensions)
- */
+* CORBA method: Get the hostName of the Container (without domain extensions)
+*/
//=============================================================================
char* Engines_Container_i::getHostName()
//=============================================================================
/*!
- * CORBA method: Get the PID (process identification) of the Container
- */
+* CORBA method: Get the PID (process identification) of the Container
+*/
//=============================================================================
CORBA::Long Engines_Container_i::getPID()
//=============================================================================
/*!
- * CORBA method: check if servant is still alive
- */
+* CORBA method: check if servant is still alive
+*/
//=============================================================================
void Engines_Container_i::ping()
//=============================================================================
/*!
- * CORBA method, oneway: Server shutdown.
- * - Container name removed from naming service,
- * - servant deactivation,
- * - orb shutdown if no other servants in the process
- */
+* CORBA method, oneway: Server shutdown.
+* - Container name removed from naming service,
+* - servant deactivation,
+* - orb shutdown if no other servants in the process
+*/
//=============================================================================
void Engines_Container_i::Shutdown()
MESSAGE("Engines_Container_i::Shutdown()");
/* For each component contained in this container
- * tell it to self-destroy
- */
+ * tell it to self-destroy
+ */
std::map<std::string, Engines::Component_var>::iterator itm;
for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
itm->second->destroy();
//_remove_ref();
//_poa->deactivate_object(*_id);
if(_isServantAloneInProcess)
- {
- MESSAGE("Effective Shutdown of container Begins...");
- if(!CORBA::is_nil(_orb))
- _orb->shutdown(0);
- }
+ {
+ MESSAGE("Effective Shutdown of container Begins...");
+ if(!CORBA::is_nil(_orb))
+ _orb->shutdown(0);
+ }
}
/* int checkifexecutable(const char *filename)
- *
- * Return non-zero if the name is an executable file, and
- * zero if it is not executable, or if it does not exist.
- */
+*
+* Return non-zero if the name is an executable file, and
+* zero if it is not executable, or if it does not exist.
+*/
-int checkifexecutable(const char *filename)
+int checkifexecutable(const string& filename)
{
- int result;
- struct stat statinfo;
-
- result = stat(filename, &statinfo);
- if (result < 0) return 0;
- if (!S_ISREG(statinfo.st_mode)) return 0;
-
- if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
- if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
- return statinfo.st_mode & S_IXOTH;
+ int result;
+ struct stat statinfo;
+
+ result = stat(filename.c_str(), &statinfo);
+ if (result < 0) return 0;
+ if (!S_ISREG(statinfo.st_mode)) return 0;
+
+#ifdef WIN32
+ return 1;
+#else
+ if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
+ if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
+ return statinfo.st_mode & S_IXOTH;
+#endif
}
/* int findpathof(char *pth, const char *exe)
- *
- * Find executable by searching the PATH environment variable.
- *
- * const char *exe - executable name to search for.
- * char *pth - the path found is stored here, space
- * needs to be available.
- *
- * If a path is found, returns non-zero, and the path is stored
- * in pth. If exe is not found returns 0, with pth undefined.
- */
-
-int findpathof(char *pth, const char *exe)
+*
+* Find executable by searching the PATH environment variable.
+*
+* const char *exe - executable name to search for.
+* char *pth - the path found is stored here, space
+* needs to be available.
+*
+* If a path is found, returns non-zero, and the path is stored
+* in pth. If exe is not found returns 0, with pth undefined.
+*/
+
+int findpathof(string& pth, const string& exe)
{
- char *searchpath;
- char *beg, *end;
- int stop, found;
- int len;
-
- if (strchr(exe, '/') != NULL) {
- if (realpath(exe, pth) == NULL) return 0;
- return checkifexecutable(pth);
- }
-
- searchpath = getenv("PATH");
- if (searchpath == NULL) return 0;
- if (strlen(searchpath) <= 0) return 0;
-
- beg = searchpath;
- stop = 0; found = 0;
- do {
- end = strchr(beg, ':');
- if (end == NULL) {
- stop = 1;
- strncpy(pth, beg, PATH_MAX);
- len = strlen(pth);
- } else {
- strncpy(pth, beg, end - beg);
- pth[end - beg] = '\0';
- len = end - beg;
- }
- if (pth[len - 1] != '/') strncat(pth, "/", 1);
- strncat(pth, exe, PATH_MAX - len);
- found = checkifexecutable(pth);
- if (!stop) beg = end + 1;
- } while (!stop && !found);
-
- return found;
+ string path( getenv("PATH") );
+ if ( path.size() == 0 )
+ return 0;
+
+ char path_spr =
+#ifdef WIN32
+ ';';
+#else
+ ':';
+#endif
+
+ char dir_spr =
+#ifdef WIN32
+ '\\';
+#else
+ '/';
+#endif
+
+ int offset = 0;
+ int stop = 0;
+ int found = 0;
+ while(!stop && !found)
+ {
+ int pos = path.find( path_spr, offset );
+ if (pos == string::npos)
+ stop = 1;
+
+ pth = path.substr( offset, pos - offset );
+ if ( pth.size() > 0 )
+ {
+ if( pth[pth.size()-1] != dir_spr )
+ pth += dir_spr;
+ pth += exe;
+ found = checkifexecutable(pth.c_str());
+ }
+ offset = pos+1;
+ }
+
+
+/* char *searchpath;
+ char *beg, *end;
+ int stop, found;
+ int len;
+
+ if (strchr(exe, separator) != NULL) {
+#ifndef WIN32
+ if (realpath(exe, pth) == NULL) return 0;
+#endif
+ return checkifexecutable(pth);
+ }
+
+ searchpath = getenv("PATH");
+ if (searchpath == NULL) return 0;
+ if (strlen(searchpath) <= 0) return 0;
+
+ string env_path(searchpath);
+
+ beg = searchpath;
+ stop = 0; found = 0;
+ do {
+ end = strchr(beg, ':');
+ if (end == NULL) {
+ stop = 1;
+ strncpy(pth, beg, PATH_MAX);
+ len = strlen(pth);
+ } else {
+ strncpy(pth, beg, end - beg);
+ pth[end - beg] = '\0';
+ len = end - beg;
+ }
+ if (pth[len - 1] != '/') strncat(pth, "/", 1);
+ strncat(pth, exe, PATH_MAX - len);
+ found = checkifexecutable(pth);
+ if (!stop) beg = end + 1;
+ } while (!stop && !found);
+*/
+ return found;
}
//=============================================================================
/*!
- * CORBA method: load a new component class (Python or C++ implementation)
- * \param componentName like COMPONENT
- * try to make a Python import of COMPONENT,
- * then a lib open of libCOMPONENTEngine.so
- * \return true if dlopen successfull or already done, false otherwise
- */
+* CORBA method: load a new component class (Python or C++ implementation)
+* \param componentName like COMPONENT
+* try to make a Python import of COMPONENT,
+* then a lib open of libCOMPONENTEngine.so
+* \return true if dlopen successfull or already done, false otherwise
+*/
//=============================================================================
bool
string impl_name = aCompName + string("Engine.dll");
#endif
SCRUTE(impl_name);
-
+
_numInstanceMutex.lock(); // lock to be alone
// (see decInstanceCnt, finalize_removal))
if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
if (_library_map.count(impl_name) != 0)
- {
- MESSAGE("Library " << impl_name << " already loaded");
- _numInstanceMutex.unlock();
- return true;
- }
-
+ {
+ MESSAGE("Library " << impl_name << " already loaded");
+ _numInstanceMutex.unlock();
+ return true;
+ }
+
#ifndef WNT
void* handle;
handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
if ( handle )
{
- _library_map[impl_name] = handle;
- _numInstanceMutex.unlock();
- return true;
+ _library_map[impl_name] = handle;
+ _numInstanceMutex.unlock();
+ return true;
}
_numInstanceMutex.unlock();
INFOS("try import Python component "<<componentName);
if (_isSupervContainer)
- {
- INFOS("Supervision Container does not support Python Component Engines");
- return false;
- }
+ {
+ INFOS("Supervision Container does not support Python Component Engines");
+ return false;
+ }
if (_library_map.count(aCompName) != 0)
- {
- return true; // Python Component, already imported
- }
+ {
+ return true; // Python Component, already imported
+ }
else
+ {
+ Py_ACQUIRE_NEW_THREAD;
+ PyObject *mainmod = PyImport_AddModule("__main__");
+ PyObject *globals = PyModule_GetDict(mainmod);
+ PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
+ PyObject *result = PyObject_CallMethod(pyCont,
+ (char*)"import_component",
+ (char*)"s",componentName);
+ int ret= PyInt_AsLong(result);
+ Py_XDECREF(result);
+ SCRUTE(ret);
+ Py_RELEASE_NEW_THREAD;
+
+ if (ret) // import possible: Python component
{
- Py_ACQUIRE_NEW_THREAD;
- PyObject *mainmod = PyImport_AddModule("__main__");
- PyObject *globals = PyModule_GetDict(mainmod);
- PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
- PyObject *result = PyObject_CallMethod(pyCont,
- (char*)"import_component",
- (char*)"s",componentName);
- int ret= PyInt_AsLong(result);
- Py_XDECREF(result);
- SCRUTE(ret);
- Py_RELEASE_NEW_THREAD;
-
- if (ret) // import possible: Python component
- {
- _numInstanceMutex.lock() ; // lock to be alone (stl container write)
- _library_map[aCompName] = (void *)pyCont; // any non O value OK
- _numInstanceMutex.unlock() ;
- MESSAGE("import Python: "<<aCompName<<" OK");
- return true;
- }
+ _numInstanceMutex.lock() ; // lock to be alone (stl container write)
+ _library_map[aCompName] = (void *)pyCont; // any non O value OK
+ _numInstanceMutex.unlock() ;
+ MESSAGE("import Python: "<<aCompName<<" OK");
+ return true;
}
+ }
// Try to find an executable
std::string executable=aCompName+".exe";
- char path[PATH_MAX+1];
- if (findpathof(path, executable.c_str()))
+ string path;
+ if (findpathof(path, executable))
return true;
INFOS( "Impossible to load component: " << componentName );
//=============================================================================
/*!
- * CORBA method: Creates a new servant instance of a component.
- * The servant registers itself to naming service and Registry.
- * \param genericRegisterName Name of the component instance to register
- * in Registry & Name Service (without _inst_n suffix)
- * \param studyId 0 for multiStudy instance,
- * study Id (>0) otherwise
- * \return a loaded component
- */
+* CORBA method: Creates a new servant instance of a component.
+* The servant registers itself to naming service and Registry.
+* \param genericRegisterName Name of the component instance to register
+* in Registry & Name Service (without _inst_n suffix)
+* \param studyId 0 for multiStudy instance,
+* study Id (>0) otherwise
+* \return a loaded component
+*/
//=============================================================================
Engines::Component_ptr
CORBA::Long studyId)
{
if (studyId < 0)
- {
- INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
- return Engines::Component::_nil() ;
- }
+ {
+ INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
+ return Engines::Component::_nil() ;
+ }
Engines::Component_var iobject = Engines::Component::_nil() ;
string aCompName = genericRegisterName;
if (_library_map.count(aCompName) != 0) // Python component
+ {
+ if (_isSupervContainer)
{
- if (_isSupervContainer)
- {
- INFOS("Supervision Container does not support Python Component Engines");
- return Engines::Component::_nil();
- }
- _numInstanceMutex.lock() ; // lock on the instance number
- _numInstance++ ;
- int numInstance = _numInstance ;
- _numInstanceMutex.unlock() ;
-
- char aNumI[12];
- sprintf( aNumI , "%d" , numInstance ) ;
- string instanceName = aCompName + "_inst_" + aNumI ;
- string component_registerName =
- _containerName + "/" + instanceName;
-
- Py_ACQUIRE_NEW_THREAD;
- PyObject *mainmod = PyImport_AddModule("__main__");
- PyObject *globals = PyModule_GetDict(mainmod);
- PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
- PyObject *result = PyObject_CallMethod(pyCont,
- (char*)"create_component_instance",
- (char*)"ssl",
- aCompName.c_str(),
- instanceName.c_str(),
- studyId);
- string iors = PyString_AsString(result);
- Py_DECREF(result);
- SCRUTE(iors);
- Py_RELEASE_NEW_THREAD;
-
- if( iors!="" )
- {
- CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
- iobject = Engines::Component::_narrow( obj ) ;
- _listInstances_map[instanceName] = iobject;
- }
- return iobject._retn();
+ INFOS("Supervision Container does not support Python Component Engines");
+ return Engines::Component::_nil();
}
-
+ _numInstanceMutex.lock() ; // lock on the instance number
+ _numInstance++ ;
+ int numInstance = _numInstance ;
+ _numInstanceMutex.unlock() ;
+
+ char aNumI[12];
+ sprintf( aNumI , "%d" , numInstance ) ;
+ string instanceName = aCompName + "_inst_" + aNumI ;
+ string component_registerName =
+ _containerName + "/" + instanceName;
+
+ Py_ACQUIRE_NEW_THREAD;
+ PyObject *mainmod = PyImport_AddModule("__main__");
+ PyObject *globals = PyModule_GetDict(mainmod);
+ PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
+ PyObject *result = PyObject_CallMethod(pyCont,
+ (char*)"create_component_instance",
+ (char*)"ssl",
+ aCompName.c_str(),
+ instanceName.c_str(),
+ studyId);
+ string iors = PyString_AsString(result);
+ Py_DECREF(result);
+ SCRUTE(iors);
+ Py_RELEASE_NEW_THREAD;
+
+ if( iors!="" )
+ {
+ CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
+ iobject = Engines::Component::_narrow( obj ) ;
+ _listInstances_map[instanceName] = iobject;
+ }
+ return iobject._retn();
+ }
+
//--- try C++
#ifndef WNT
string impl_name = genericRegisterName +string("Engine.dll");
#endif
if (_library_map.count(impl_name) != 0) // C++ component
- {
- void* handle = _library_map[impl_name];
- iobject = createInstance(genericRegisterName,
- handle,
- studyId);
- return iobject._retn();
- }
+ {
+ void* handle = _library_map[impl_name];
+ iobject = createInstance(genericRegisterName,
+ handle,
+ studyId);
+ return iobject._retn();
+ }
// If it's not a Python or a C++ component try to launch a standalone component
// in a sub directory
//check if an entry exist in naming service
CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
if ( !CORBA::is_nil(nsobj) )
- {
- // unregister the registered component
- _NS->Destroy_Name(component_registerName.c_str());
- //kill or shutdown it ???
- }
+ {
+ // unregister the registered component
+ _NS->Destroy_Name(component_registerName.c_str());
+ //kill or shutdown it ???
+ }
// first arg container ior string
// second arg container name
int status=system(command.c_str());
if (status == -1)
- {
- MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status -1)");
- return Engines::Component::_nil();
- }
+ {
+ MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status -1)");
+ return Engines::Component::_nil();
+ }
+#ifndef WIN32
else if (WEXITSTATUS(status) == 217)
- {
- MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status 217)");
- return Engines::Component::_nil();
- }
+ {
+ MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status 217)");
+ return Engines::Component::_nil();
+ }
+#endif
else
+ {
+ int count=20;
+ CORBA::Object_var obj = CORBA::Object::_nil() ;
+ while ( CORBA::is_nil(obj) && count )
{
- int count=20;
- CORBA::Object_var obj = CORBA::Object::_nil() ;
- while ( CORBA::is_nil(obj) && count )
- {
-#ifndef WNT
- sleep( 1 ) ;
+#ifndef WIN32
+ sleep( 1 ) ;
#else
- Sleep(1000);
+ Sleep(1000);
#endif
- count-- ;
- MESSAGE( count << ". Waiting for component " << genericRegisterName);
- obj = _NS->Resolve(component_registerName.c_str());
- }
+ count-- ;
+ MESSAGE( count << ". Waiting for component " << genericRegisterName);
+ obj = _NS->Resolve(component_registerName.c_str());
+ }
- if(CORBA::is_nil(obj))
- {
- MESSAGE("SALOME_Container::create_component_instance failed");
- return Engines::Component::_nil();
- }
- else
- {
- MESSAGE("SALOME_Container::create_component_instance successful");
- iobject=Engines::Component::_narrow(obj);
- _listInstances_map[instanceName] = iobject;
- return iobject._retn();
- }
+ if(CORBA::is_nil(obj))
+ {
+ MESSAGE("SALOME_Container::create_component_instance failed");
+ return Engines::Component::_nil();
}
+ else
+ {
+ MESSAGE("SALOME_Container::create_component_instance successful");
+ iobject=Engines::Component::_narrow(obj);
+ _listInstances_map[instanceName] = iobject;
+ return iobject._retn();
+ }
+ }
}
//=============================================================================
/*!
- * CORBA method: Finds a servant instance of a component
- * \param registeredName Name of the component in Registry or Name Service,
- * without instance suffix number
- * \param studyId 0 if instance is not associated to a study,
- * >0 otherwise (== study id)
- * \return the first instance found with same studyId
- */
+* CORBA method: Finds a servant instance of a component
+* \param registeredName Name of the component in Registry or Name Service,
+* without instance suffix number
+* \param studyId 0 if instance is not associated to a study,
+* >0 otherwise (== study id)
+* \return the first instance found with same studyId
+*/
//=============================================================================
Engines::Component_ptr
Engines_Container_i::find_component_instance( const char* registeredName,
- CORBA::Long studyId)
+ CORBA::Long studyId)
{
Engines::Component_var anEngine = Engines::Component::_nil();
map<string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
while (itm != _listInstances_map.end())
+ {
+ string instance = (*itm).first;
+ SCRUTE(instance);
+ if (instance.find(registeredName) == 0)
{
- string instance = (*itm).first;
- SCRUTE(instance);
- if (instance.find(registeredName) == 0)
- {
- anEngine = (*itm).second;
- if (studyId == anEngine->getStudyId())
- {
- return anEngine._retn();
- }
- }
- itm++;
+ anEngine = (*itm).second;
+ if (studyId == anEngine->getStudyId())
+ {
+ return anEngine._retn();
+ }
}
+ itm++;
+ }
return anEngine._retn();
}
//=============================================================================
/*!
- * CORBA method: find or create an instance of the component (servant),
- * load a new component class (dynamic library) if required,
- * ---- FOR COMPATIBILITY WITH 2.2 ----
- * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
- * The servant registers itself to naming service and Registry.
- * \param genericRegisterName Name of the component to register
- * in Registry & Name Service
- * \param componentName Name of the constructed library of the component
- * \return a loaded component
- */
+* CORBA method: find or create an instance of the component (servant),
+* load a new component class (dynamic library) if required,
+* ---- FOR COMPATIBILITY WITH 2.2 ----
+* ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
+* The servant registers itself to naming service and Registry.
+* \param genericRegisterName Name of the component to register
+* in Registry & Name Service
+* \param componentName Name of the constructed library of the component
+* \return a loaded component
+*/
//=============================================================================
Engines::Component_ptr
Engines_Container_i::load_impl( const char* genericRegisterName,
- const char* componentName )
+ const char* componentName )
{
string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
Engines::Component_var iobject = Engines::Component::_nil() ;
iobject = find_or_create_instance(genericRegisterName, impl_name);
return iobject._retn();
}
-
+
//=============================================================================
/*!
- * CORBA method: Stops the component servant, and deletes all related objects
- * \param component_i Component to be removed
- */
+* CORBA method: Stops the component servant, and deletes all related objects
+* \param component_i Component to be removed
+*/
//=============================================================================
void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
//=============================================================================
/*!
- * CORBA method: Discharges unused libraries from the container.
- */
+* CORBA method: Discharges unused libraries from the container.
+*/
//=============================================================================
void Engines_Container_i::finalize_removal()
{
MESSAGE("finalize unload : dlclose");
_numInstanceMutex.lock(); // lock to be alone
- // (see decInstanceCnt, load_component_Library)
+ // (see decInstanceCnt, load_component_Library)
map<string, void *>::iterator ith;
for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
+ {
+ void *handle = (*ith).second;
+ string impl_name= (*ith).first;
+ if (handle)
{
- void *handle = (*ith).second;
- string impl_name= (*ith).first;
- if (handle)
- {
- SCRUTE(handle);
- SCRUTE(impl_name);
-// dlclose(handle); // SALOME unstable after ...
-// _library_map.erase(impl_name);
- }
+ SCRUTE(handle);
+ SCRUTE(impl_name);
+ // dlclose(handle); // SALOME unstable after ...
+ // _library_map.erase(impl_name);
}
+ }
_toRemove_map.clear();
_numInstanceMutex.unlock();
}
//=============================================================================
/*!
- * CORBA method: Kill the container process with exit(0).
- * To remove : never returns !
- */
+* CORBA method: Kill the container process with exit(0).
+* To remove : never returns !
+*/
//=============================================================================
bool Engines_Container_i::Kill_impl()
{
MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
- << _containerName.c_str() << " machineName "
- << GetHostname().c_str());
+ << _containerName.c_str() << " machineName "
+ << GetHostname().c_str());
INFOS("===============================================================");
INFOS("= REMOVE calls to Kill_impl in C++ container =");
INFOS("===============================================================");
//=============================================================================
/*!
- * CORBA method: get or create a fileRef object associated to a local file
- * (a file on the computer on which runs the container server), which stores
- * a list of (machine, localFileName) corresponding to copies already done.
- *
- * \param origFileName absolute path for a local file to copy on other
- * computers
- * \return a fileRef object associated to the file.
- */
+* CORBA method: get or create a fileRef object associated to a local file
+* (a file on the computer on which runs the container server), which stores
+* a list of (machine, localFileName) corresponding to copies already done.
+*
+* \param origFileName absolute path for a local file to copy on other
+* computers
+* \return a fileRef object associated to the file.
+*/
//=============================================================================
Engines::fileRef_ptr
Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
if (origName[0] != '/')
- {
- INFOS("path of file to copy must be an absolute path begining with '/'");
- return Engines::fileRef::_nil();
- }
+ {
+ INFOS("path of file to copy must be an absolute path begining with '/'");
+ return Engines::fileRef::_nil();
+ }
if (CORBA::is_nil(_fileRef_map[origName]))
- {
- CORBA::Object_var obj=_poa->id_to_reference(*_id);
- Engines::Container_var pCont = Engines::Container::_narrow(obj);
- fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
- theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
- _numInstanceMutex.lock() ; // lock to be alone (stl container write)
- _fileRef_map[origName] = theFileRef;
- _numInstanceMutex.unlock() ;
- }
-
+ {
+ CORBA::Object_var obj=_poa->id_to_reference(*_id);
+ Engines::Container_var pCont = Engines::Container::_narrow(obj);
+ fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
+ theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
+ _numInstanceMutex.lock() ; // lock to be alone (stl container write)
+ _fileRef_map[origName] = theFileRef;
+ _numInstanceMutex.unlock() ;
+ }
+
theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
ASSERT(! CORBA::is_nil(theFileRef));
return theFileRef._retn();
//=============================================================================
/*!
- * CORBA method:
- * \return a reference to the fileTransfer object
- */
+* CORBA method:
+* \return a reference to the fileTransfer object
+*/
//=============================================================================
Engines::fileTransfer_ptr
{
string origName(origFileName);
if (CORBA::is_nil(_Salome_file_map[origName]))
+ {
+ Salome_file_i* aSalome_file = new Salome_file_i();
+ aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
+ try
{
- Salome_file_i* aSalome_file = new Salome_file_i();
- aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
- try
- {
- aSalome_file->setLocalFile(origFileName);
- aSalome_file->recvFiles();
- }
- catch (const SALOME::SALOME_Exception& e)
- {
- return Engines::Salome_file::_nil();
- }
-
- Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
- theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
- _numInstanceMutex.lock() ; // lock to be alone (stl container write)
- _Salome_file_map[origName] = theSalome_file;
- _numInstanceMutex.unlock() ;
+ aSalome_file->setLocalFile(origFileName);
+ aSalome_file->recvFiles();
+ }
+ catch (const SALOME::SALOME_Exception& e)
+ {
+ return Engines::Salome_file::_nil();
}
-
+
+ Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
+ theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
+ _numInstanceMutex.lock() ; // lock to be alone (stl container write)
+ _Salome_file_map[origName] = theSalome_file;
+ _numInstanceMutex.unlock() ;
+ }
+
Engines::Salome_file_ptr theSalome_file =
Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
ASSERT(!CORBA::is_nil(theSalome_file));
}
//=============================================================================
/*!
- * C++ method: Finds an already existing servant instance of a component, or
- * create an instance.
- * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
- * \param genericRegisterName Name of the component instance to register
- * in Registry & Name Service,
- * (without _inst_n suffix, like "COMPONENT")
- * \param componentLibraryName like "libCOMPONENTEngine.so"
- * \return a loaded component
- *
- * example with names:
- * aGenRegisterName = COMPONENT (= first argument)
- * impl_name = libCOMPONENTEngine.so (= second argument)
- * _containerName = /Containers/cli76ce/FactoryServer
- * factoryName = COMPONENTEngine_factory
- * component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
- *
- * instanceName = COMPONENT_inst_1
- * component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
- */
+* C++ method: Finds an already existing servant instance of a component, or
+* create an instance.
+* ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
+* \param genericRegisterName Name of the component instance to register
+* in Registry & Name Service,
+* (without _inst_n suffix, like "COMPONENT")
+* \param componentLibraryName like "libCOMPONENTEngine.so"
+* \return a loaded component
+*
+* example with names:
+* aGenRegisterName = COMPONENT (= first argument)
+* impl_name = libCOMPONENTEngine.so (= second argument)
+* _containerName = /Containers/cli76ce/FactoryServer
+* factoryName = COMPONENTEngine_factory
+* component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
+*
+* instanceName = COMPONENT_inst_1
+* component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
+*/
//=============================================================================
Engines::Component_ptr
string aGenRegisterName = genericRegisterName;
string impl_name = componentLibraryName;
if (_library_map.count(impl_name) == 0)
- {
- INFOS("shared library " << impl_name <<" must be loaded before creating instance");
- return Engines::Component::_nil() ;
- }
+ {
+ INFOS("shared library " << impl_name <<" must be loaded before creating instance");
+ return Engines::Component::_nil() ;
+ }
else
- {
- // --- find a registered instance in naming service, or create
+ {
+ // --- find a registered instance in naming service, or create
- void* handle = _library_map[impl_name];
- string component_registerBase =
- _containerName + "/" + aGenRegisterName;
- Engines::Component_var iobject = Engines::Component::_nil() ;
- try
+ void* handle = _library_map[impl_name];
+ string component_registerBase =
+ _containerName + "/" + aGenRegisterName;
+ Engines::Component_var iobject = Engines::Component::_nil() ;
+ try
+ {
+ CORBA::Object_var obj =
+ _NS->ResolveFirst( component_registerBase.c_str());
+ if ( CORBA::is_nil( obj ) )
+ {
+ iobject = createInstance(genericRegisterName,
+ handle,
+ 0); // force multiStudy instance here !
+ }
+ else
+ {
+ iobject = Engines::Component::_narrow( obj ) ;
+ Engines_Component_i *servant =
+ dynamic_cast<Engines_Component_i*>
+ (_poa->reference_to_servant(iobject));
+ ASSERT(servant)
+ int studyId = servant->getStudyId();
+ ASSERT (studyId >= 0);
+ if (studyId == 0) // multiStudy instance, OK
{
- CORBA::Object_var obj =
- _NS->ResolveFirst( component_registerBase.c_str());
- if ( CORBA::is_nil( obj ) )
- {
- iobject = createInstance(genericRegisterName,
- handle,
- 0); // force multiStudy instance here !
- }
- else
- {
- iobject = Engines::Component::_narrow( obj ) ;
- Engines_Component_i *servant =
- dynamic_cast<Engines_Component_i*>
- (_poa->reference_to_servant(iobject));
- ASSERT(servant)
- int studyId = servant->getStudyId();
- ASSERT (studyId >= 0);
- if (studyId == 0) // multiStudy instance, OK
- {
- // No ReBind !
- MESSAGE(component_registerBase.c_str()<<" already bound");
- }
- else // monoStudy instance: NOK
- {
- iobject = Engines::Component::_nil();
- INFOS("load_impl & find_component_instance methods "
- << "NOT SUITABLE for mono study components");
- }
- }
+ // No ReBind !
+ MESSAGE(component_registerBase.c_str()<<" already bound");
}
- catch (...)
+ else // monoStudy instance: NOK
{
- INFOS( "Container_i::load_impl catched" ) ;
+ iobject = Engines::Component::_nil();
+ INFOS("load_impl & find_component_instance methods "
+ << "NOT SUITABLE for mono study components");
}
- return iobject._retn();
+ }
}
+ catch (...)
+ {
+ INFOS( "Container_i::load_impl catched" ) ;
+ }
+ return iobject._retn();
+ }
}
//=============================================================================
/*!
- * C++ method: create a servant instance of a component.
- * \param genericRegisterName Name of the component instance to register
- * in Registry & Name Service,
- * (without _inst_n suffix, like "COMPONENT")
- * \param handle loaded library handle
- * \param studyId 0 for multiStudy instance,
- * study Id (>0) otherwise
- * \return a loaded component
- *
- * example with names:
- * aGenRegisterName = COMPONENT (= first argument)
- * _containerName = /Containers/cli76ce/FactoryServer
- * factoryName = COMPONENTEngine_factory
- * component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
- * instanceName = COMPONENT_inst_1
- * component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
- */
+* C++ method: create a servant instance of a component.
+* \param genericRegisterName Name of the component instance to register
+* in Registry & Name Service,
+* (without _inst_n suffix, like "COMPONENT")
+* \param handle loaded library handle
+* \param studyId 0 for multiStudy instance,
+* study Id (>0) otherwise
+* \return a loaded component
+*
+* example with names:
+* aGenRegisterName = COMPONENT (= first argument)
+* _containerName = /Containers/cli76ce/FactoryServer
+* factoryName = COMPONENTEngine_factory
+* component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
+* instanceName = COMPONENT_inst_1
+* component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
+*/
//=============================================================================
Engines::Component_ptr
typedef PortableServer::ObjectId * (*FACTORY_FUNCTION)
(CORBA::ORB_ptr,
- PortableServer::POA_ptr,
- PortableServer::ObjectId *,
- const char *,
- const char *) ;
+ PortableServer::POA_ptr,
+ PortableServer::ObjectId *,
+ const char *,
+ const char *) ;
#ifndef WNT
FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
if ( !Component_factory )
{
- INFOS( "Can't resolve symbol: " + factory_name );
+ INFOS( "Can't resolve symbol: " + factory_name );
#ifndef WNT
- SCRUTE( dlerror() );
+ SCRUTE( dlerror() );
#endif
- return Engines::Component::_nil() ;
+ return Engines::Component::_nil() ;
}
// --- create instance
Engines::Component_var iobject = Engines::Component::_nil() ;
try
- {
- _numInstanceMutex.lock() ; // lock on the instance number
- _numInstance++ ;
- int numInstance = _numInstance ;
- _numInstanceMutex.unlock() ;
-
- char aNumI[12];
- sprintf( aNumI , "%d" , numInstance ) ;
- string instanceName = aGenRegisterName + "_inst_" + aNumI ;
- string component_registerName =
- _containerName + "/" + instanceName;
-
- // --- Instanciate required CORBA object
-
- PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
- id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
- aGenRegisterName.c_str() ) ;
- if (id == NULL)
- return iobject._retn();
-
- // --- get reference & servant from id
-
- CORBA::Object_var obj = _poa->id_to_reference(*id);
- iobject = Engines::Component::_narrow( obj ) ;
+ {
+ _numInstanceMutex.lock() ; // lock on the instance number
+ _numInstance++ ;
+ int numInstance = _numInstance ;
+ _numInstanceMutex.unlock() ;
+
+ char aNumI[12];
+ sprintf( aNumI , "%d" , numInstance ) ;
+ string instanceName = aGenRegisterName + "_inst_" + aNumI ;
+ string component_registerName =
+ _containerName + "/" + instanceName;
+
+ // --- Instanciate required CORBA object
+
+ PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
+ id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
+ aGenRegisterName.c_str() ) ;
+ if (id == NULL)
+ return iobject._retn();
- Engines_Component_i *servant =
- dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
- ASSERT(servant);
- //SCRUTE(servant->pd_refCount);
- servant->_remove_ref(); // compensate previous id_to_reference
- //SCRUTE(servant->pd_refCount);
- _numInstanceMutex.lock() ; // lock to be alone (stl container write)
- _listInstances_map[instanceName] = iobject;
- _cntInstances_map[aGenRegisterName] += 1;
- _numInstanceMutex.unlock() ;
- SCRUTE(aGenRegisterName);
- SCRUTE(_cntInstances_map[aGenRegisterName]);
- //SCRUTE(servant->pd_refCount);
+ // --- get reference & servant from id
+
+ CORBA::Object_var obj = _poa->id_to_reference(*id);
+ iobject = Engines::Component::_narrow( obj ) ;
+
+ Engines_Component_i *servant =
+ dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
+ ASSERT(servant);
+ //SCRUTE(servant->pd_refCount);
+ servant->_remove_ref(); // compensate previous id_to_reference
+ //SCRUTE(servant->pd_refCount);
+ _numInstanceMutex.lock() ; // lock to be alone (stl container write)
+ _listInstances_map[instanceName] = iobject;
+ _cntInstances_map[aGenRegisterName] += 1;
+ _numInstanceMutex.unlock() ;
+ SCRUTE(aGenRegisterName);
+ SCRUTE(_cntInstances_map[aGenRegisterName]);
+ //SCRUTE(servant->pd_refCount);
#if defined(_DEBUG_) || defined(_DEBUG)
- bool ret_studyId = servant->setStudyId(studyId);
- ASSERT(ret_studyId);
+ bool ret_studyId = servant->setStudyId(studyId);
+ ASSERT(ret_studyId);
#else
- servant->setStudyId(studyId);
+ servant->setStudyId(studyId);
#endif
- // --- register the engine under the name
- // containerName(.dir)/instanceName(.object)
+ // --- register the engine under the name
+ // containerName(.dir)/instanceName(.object)
- _NS->Register( iobject , component_registerName.c_str() ) ;
- MESSAGE( component_registerName.c_str() << " bound" ) ;
- }
+ _NS->Register( iobject , component_registerName.c_str() ) ;
+ MESSAGE( component_registerName.c_str() << " bound" ) ;
+ }
catch (...)
- {
- INFOS( "Container_i::createInstance exception catched" ) ;
- }
+ {
+ INFOS( "Container_i::createInstance exception catched" ) ;
+ }
return iobject._retn();
}
//=============================================================================
/*!
- *
- */
+*
+*/
//=============================================================================
void Engines_Container_i::decInstanceCnt(string genericRegisterName)
MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
ASSERT(_cntInstances_map[aGenRegisterName] > 0);
_numInstanceMutex.lock(); // lock to be alone
- // (see finalize_removal, load_component_Library)
+ // (see finalize_removal, load_component_Library)
_cntInstances_map[aGenRegisterName] -= 1;
SCRUTE(_cntInstances_map[aGenRegisterName]);
if (_cntInstances_map[aGenRegisterName] == 0)
- {
- string impl_name =
- Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
- SCRUTE(impl_name);
- void* handle = _library_map[impl_name];
- ASSERT(handle);
- _toRemove_map[impl_name] = handle;
- }
+ {
+ string impl_name =
+ Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
+ SCRUTE(impl_name);
+ void* handle = _library_map[impl_name];
+ ASSERT(handle);
+ _toRemove_map[impl_name] = handle;
+ }
_numInstanceMutex.unlock();
}
//=============================================================================
/*!
- * Retrieves only with container naming convention if it is a python container
- */
+* Retrieves only with container naming convention if it is a python container
+*/
//=============================================================================
bool Engines_Container_i::isPythonContainer(const char* ContainerName)
//=============================================================================
/*!
- *
- */
+*
+*/
//=============================================================================
void ActSigIntHandler()
SigIntAct.sa_flags = SA_SIGINFO ;
#endif
-// DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
-// (SIGINT | SIGUSR1) :
-// it must be only one signal ===> one call for SIGINT
-// and an other one for SIGUSR1
+ // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
+ // (SIGINT | SIGUSR1) :
+ // it must be only one signal ===> one call for SIGINT
+ // and an other one for SIGUSR1
#ifndef WNT
if ( sigaction( SIGINT , &SigIntAct, NULL ) )
- {
- perror("SALOME_Container main ") ;
- exit(0) ;
- }
+ {
+ perror("SALOME_Container main ") ;
+ exit(0) ;
+ }
if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
- {
- perror("SALOME_Container main ") ;
- exit(0) ;
- }
+ {
+ perror("SALOME_Container main ") ;
+ exit(0) ;
+ }
if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
- {
- perror("SALOME_Container main ") ;
- exit(0) ;
- }
+ {
+ perror("SALOME_Container main ") ;
+ exit(0) ;
+ }
//PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
// use of streams (and so on) should never be used because :
// << " si_pid " << siginfo->si_pid) ;
if ( _Sleeping )
+ {
+ _Sleeping = false ;
+ // MESSAGE("SigIntHandler END sleeping.") ;
+ return ;
+ }
+ else
+ {
+ ActSigIntHandler() ;
+ if ( siginfo->si_signo == SIGUSR1 )
{
- _Sleeping = false ;
- // MESSAGE("SigIntHandler END sleeping.") ;
- return ;
+ SetCpuUsed() ;
}
- else
+ else if ( siginfo->si_signo == SIGUSR2 )
{
- ActSigIntHandler() ;
- if ( siginfo->si_signo == SIGUSR1 )
- {
- SetCpuUsed() ;
- }
- else if ( siginfo->si_signo == SIGUSR2 )
- {
- CallCancelThread() ;
- }
- else
- {
- _Sleeping = true ;
- // MESSAGE("SigIntHandler BEGIN sleeping.") ;
- int count = 0 ;
- while( _Sleeping )
- {
- sleep( 1 ) ;
- count += 1 ;
- }
- // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
- }
- return ;
+ CallCancelThread() ;
+ }
+ else
+ {
+ _Sleeping = true ;
+ // MESSAGE("SigIntHandler BEGIN sleeping.") ;
+ int count = 0 ;
+ while( _Sleeping )
+ {
+ sleep( 1 ) ;
+ count += 1 ;
+ }
+ // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
}
+ return ;
+ }
}
#else // Case WNT
void SigIntHandler( int what )
MESSAGE( "SigIntHandler what " << what << endl );
#endif
if ( _Sleeping )
+ {
+ _Sleeping = false ;
+ MESSAGE("SigIntHandler END sleeping.") ;
+ return ;
+ }
+ else
+ {
+ ActSigIntHandler() ;
+ if ( what == SIGUSR1 )
{
- _Sleeping = false ;
- MESSAGE("SigIntHandler END sleeping.") ;
- return ;
+ SetCpuUsed() ;
}
- else
+ else
{
- ActSigIntHandler() ;
- if ( what == SIGUSR1 )
- {
- SetCpuUsed() ;
- }
- else
- {
- _Sleeping = true ;
- MESSAGE("SigIntHandler BEGIN sleeping.") ;
- int count = 0 ;
- while( _Sleeping )
- {
- Sleep( 1000 ) ;
- count += 1 ;
- }
- MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
- }
- return ;
+ _Sleeping = true ;
+ MESSAGE("SigIntHandler BEGIN sleeping.") ;
+ int count = 0 ;
+ while( _Sleeping )
+ {
+ Sleep( 1000 ) ;
+ count += 1 ;
+ }
+ MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
}
+ return ;
+ }
}
#endif
possibleComputers.length());
vector<string> lm;
- for(int i=0;i<possibleComputers.length();i++)
+ for(unsigned int i=0;i<possibleComputers.length();i++)
lm.push_back(string(possibleComputers[i]));
string theMachine;
if (CORBA::is_nil (Catalog))
return Engines::Container::_nil();
// Loop through component list
- for(int i=0;i<componentList.length();i++)
+ for(unsigned int i=0;i<componentList.length();i++)
{
const char* compoi = componentList[i];
SALOME_ModuleCatalog::Acomponent_var compoInfo = Catalog->GetComponent(compoi);
SALOME_ContainerManager::BuildCommandToLaunchLocalContainer
(const Engines::MachineParameters& params, const long id,const std::string& container_exe)
{
- _TmpFileName = "";
+ _TmpFileName = BuildTemporaryFileName();
string command;
int nbproc = 0;
- char idc[3*sizeof(long)];
+ //char idc[3*sizeof(long)];
+
+ ofstream command_file( _TmpFileName.c_str() );
if (params.isMPI)
{
- command = "mpirun -np ";
+ //command = "mpirun -np ";
+ command_file << "mpirun -np ";
if ( (params.nb_node <= 0) && (params.nb_proc_per_node <= 0) )
nbproc = 1;
else
nbproc = params.nb_node * params.nb_proc_per_node;
- std::ostringstream o;
+ //std::ostringstream o;
- o << nbproc << " ";
+ //o << nbproc << " ";
+ command_file << nbproc << " ";
- command += o.str();
+ //command += o.str();
#ifdef WITHLAM
- command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
+ //command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
+ command_file << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
#endif
if (isPythonContainer(params.container_name))
- command += "pyMPI SALOME_ContainerPy.py ";
+ //command += "pyMPI SALOME_ContainerPy.py ";
+ command_file << "pyMPI SALOME_ContainerPy.py ";
else
- command += "SALOME_MPIContainer ";
+ //command += "SALOME_MPIContainer ";
+ command_file << "SALOME_MPIContainer ";
}
else
{
- command="";
+ //command="";
std::string wdir=params.workingdir.in();
if(wdir != "")
{
if(wdir == "$TEMPDIR")
{
// a new temporary directory is requested
- char dir[]="/tmp/salomeXXXXXX";
- char* mdir=mkdtemp(dir);
- if(mdir==NULL)
- std::cerr << "Problem in mkdtemp " << dir << " " << mdir << std::endl;
- else
- command="cd "+std::string(dir)+";";
+ string dir = OpUtil_Dir::GetTmpDir();
+#ifdef WIN32
+ //command += "cd /d "+ dir +";";
+ command_file << "cd /d " << dir << endl;
+#else
+ //command = "cd "+ dir +";";
+ command_file << "cd " << dir << ";";
+#endif
+
}
else
{
// a permanent directory is requested use it or create it
- command="mkdir -p " + wdir + " && cd " + wdir + ";";
+#ifdef WIN32
+ //command="mkdir " + wdir;
+ command_file << "mkdir " + wdir << endl;
+ command_file << "cd /D " + wdir << endl;
+#else
+ //command="mkdir -p " + wdir + " && cd " + wdir + ";";
+ command_file << "mkdir -p " << wdir << " && cd " << wdir + ";";
+#endif
}
}
if (isPythonContainer(params.container_name))
- command += "SALOME_ContainerPy.py ";
+ //command += "SALOME_ContainerPy.py ";
+ command_file << "SALOME_ContainerPy.py ";
else
- command += container_exe + " ";
+ //command += container_exe + " ";
+ command_file << container_exe + " ";
+
}
- command += _NS->ContainerName(params);
+
+ /*command += _NS->ContainerName(params);
command += " -id ";
sprintf(idc,"%ld",id);
command += idc;
- command += " -";
- AddOmninamesParams(command);
+ command += " -";
+ AddOmninamesParams(command);*/
+
+ command_file << _NS->ContainerName(params);
+ command_file << " -id " << id << " -";
+ AddOmninamesParams(command_file);
+ command_file.close();
+
+#ifndef WIN32
+ chmod(_TmpFileName.c_str(), 0x1ED);
+#endif
+ command = _TmpFileName;
- MESSAGE("Command is ... " << command);
+ MESSAGE("Command is file ... " << command);
return command;
}
string SALOME_ContainerManager::BuildTemporaryFileName() const
{
//build more complex file name to support multiple salome session
- char *temp = new char[19];
- strcpy(temp, "/tmp/command");
- strcat(temp, "XXXXXX");
-#ifndef WNT
-
- mkstemp(temp);
+ string aFileName = OpUtil_Dir::GetTmpFileName();
+#ifndef WIN32
+ aFileName += ".sh";
#else
-
- char aPID[80];
- itoa(getpid(), aPID, 10);
- strcat(temp, aPID);
+ aFileName += ".bat";
#endif
-
- string command(temp);
- delete [] temp;
- command += ".sh";
- return command;
+ return aFileName;
}
tempOutputFile << " &" << endl;
tempOutputFile.flush();
tempOutputFile.close();
+#ifndef WIN32
chmod(_TmpFileName.c_str(), 0x1ED);
+#endif
// --- Build command
#include "Salome_file_i.hxx"
#include "utilities.h"
#include <stdlib.h>
-#include <unistd.h>
#include "HDFOI.hxx"
-#include <stdlib.h>
+#ifndef WNT
+# include <unistd.h>
+# define _getcwd getcwd
+# define _open open
+#else
+# include <direct.h>
+# include <io.h>
+# include <windows.h>
+#endif
+
//=============================================================================
/*!
Salome_file_i::Salome_file_i()
{
_fileId = 0;
+#ifndef WIN32
_path_max = 1 + pathconf("/", _PC_PATH_MAX);
+#else
+ _path_max = 32768;
+ //from MSDN:
+ //Note The C Runtime supports path lengths up to 32768 characters in length, but it is up to the operating system, specifically the file system, to support these longer paths. The sum of the fields should not exceed _MAX_PATH for full backwards compatibility with Windows 98 FAT32 file systems. Windows NT 4.0, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003, and Windows Server 2003 NTFS file system supports paths up to 32768 characters in length, but only when using the Unicode APIs. When using long path names, prefix the path with the characters \\?\ and use the Unicode versions of the C Runtime functions.
+ //currently #define _MAX_PATH 260
+#endif
_state.name = CORBA::string_dup("");
_state.hdf5_file_name = CORBA::string_dup("");
_state.number_of_files = 0;
if (mode == "all") {
// Changing path, is now current directory
- char CurrentPath[_path_max];
- getcwd(CurrentPath, _path_max);
- path = CurrentPath;
-
+ path = getcwd(NULL, _path_max);
+
std::string group_name("GROUP");
group_name += file_name;
hdf_group = new HDFgroup(group_name.c_str(),hdf_file);
}
else
{
- file_name = comp_file_name;
- char CurrentPath[_path_max];
- getcwd(CurrentPath, _path_max);
- path = CurrentPath;
+ file_name = comp_file_name;
+ path = getcwd(NULL, _path_max);;
}
// Test if this file is already added
else
{
file_name = comp_file_name;
- char CurrentPath[_path_max];
- getcwd(CurrentPath, _path_max);
- path = CurrentPath;
+ path = getcwd(NULL, _path_max);;
}
// Test if this file is already added
#include "ConnectionManager_i.hxx"
#include "SALOME_NamingService.hxx"
+#ifdef WIN32
+# include <process.h>
+#endif
+
ConnectionManager_i::ConnectionManager_i(CORBA::ORB_ptr orb) {
_orb = CORBA::ORB::_duplicate(orb) ;
SALOME_NamingService * ns = new SALOME_NamingService(orb);
CORBA::Long
ConnectionManager_i::getPID()
{
- return (CORBA::Long)getpid();
+ return
+#ifndef WIN32
+ (CORBA::Long)getpid();
+#else
+ (CORBA::Long)_getpid();
+#endif
}
#include "BatchTest.hxx"
+#ifdef WIN32
+# include <io.h>
+#endif
BatchTest::BatchTest(const Engines::MachineParameters& batch_descr)
{
_batch_descr = batch_descr;
<< "--- Application : " << result_appli << std::endl
);
- if (result_connection == "OK" and
- result_filecopy == "OK" and
- result_getresult == "OK" and
- result_jobsubmit_simple == "OK" and
- result_jobsubmit_mpi == "OK" and
+ if (result_connection == "OK" &&
+ result_filecopy == "OK" &&
+ result_getresult == "OK" &&
+ result_jobsubmit_simple == "OK" &&
+ result_jobsubmit_mpi == "OK" &&
result_appli == "OK")
rtn = true;
result += "username is empty !";
return result;
}
- if( protocol != "rsh" and protocol != "ssh")
+ if( protocol != "rsh" && protocol != "ssh")
{
result += "protocol unknown ! (" + protocol + ")";
return result;
if(status == 153 || status == 256*153 )
stop = true;
+#ifdef WIN32
+ Sleep(1);
+#else
sleep(1);
+#endif
}
// Build command for getting results
<< "echo HELLO MPI\n";
file_script.flush();
file_script.close();
- chmod(_test_file_script.c_str(), 0x1ED);
+#ifdef WIN32
+ _chmod
+#else
+ chmod
+#endif
+ (_test_file_script.c_str(), 0x1ED);
std::string _test_file_mpi = _test_filename + "_mpi";
std::ofstream file_mpi;
if(status == 153 || status == 256*153 )
stop = true;
+#ifdef WIN32
+ Sleep(1);
+#else
sleep(1);
+#endif
}
// Build command for getting results
#include "Batch_Date.hxx"
#include "MpiImpl.hxx"
-class BatchTest
+#ifdef WIN32
+# ifdef SALOMELAUNCHER_EXPORTS
+# define SALOMELAUNCHER_EXPORT __declspec(dllexport)
+# else
+# define SALOMELAUNCHER_EXPORT __declspec(dllimport)
+# endif
+#else
+# define SALOMELAUNCHER_EXPORT
+#endif
+
+
+class SALOMELAUNCHER_EXPORT BatchTest
{
public:
BatchTest(const Engines::MachineParameters& batch_descr);
string Launcher_cpp::buildSalomeCouplingScript(const string fileToExecute, const string dirForTmpFiles, const ParserResourcesType& params)
{
+#ifndef WIN32 //TODO: need for porting on Windows
int idx = dirForTmpFiles.find("Batch/");
std::string filelogtemp = dirForTmpFiles.substr(idx+6, dirForTmpFiles.length());
delete mpiImpl;
return TmpFileName;
+#else
+ return "";
+#endif
}
rtn = false;
}
std::string end_mem_value = mem_value.substr(mem_value.length()-2);
- if (end_mem_value != "gb" and end_mem_value != "mb") {
+ if (end_mem_value != "gb" && end_mem_value != "mb") {
mem_info = "Error on definition, type is bad ! " + mem_value;
rtn = false;
}
#ifndef __LAUNCHER_HXX__
#define __LAUNCHER_HXX__
+#ifdef WIN32
+# ifdef LAUNCHER_EXPORTS
+# define LAUNCHER_EXPORT __declspec(dllexport)
+# else
+# define LAUNCHER_EXPORT __declspec(dllimport)
+# endif
+#else
+# define LAUNCHER_EXPORT
+#endif
+
#include "Batch_BatchManager_eClient.hxx"
#include "ResourcesManager.hxx"
unsigned long nb_proc;
};
-class LauncherException
+class LAUNCHER_EXPORT LauncherException
{
public:
const std::string msg;
LauncherException(const std::string m) : msg(m) {}
};
-class Launcher_cpp
+class LAUNCHER_EXPORT Launcher_cpp
{
public:
#include "SALOME_Launcher.hxx"
#include "OpUtil.hxx"
#include <sys/types.h>
-#ifndef WNT
-#include <unistd.h>
+#ifndef WIN32
+# include <unistd.h>
+#else
+# include <process.h>
#endif
#include <vector>
#include "Utils_CorbaException.hxx"
//=============================================================================
CORBA::Long SALOME_Launcher::getPID()
{
- return (CORBA::Long)getpid();
+ return
+#ifndef WIN32
+ (CORBA::Long)getpid();
+#else
+ (CORBA::Long)_getpid();
+#endif
+
}
//=============================================================================
class SALOME_NamingService;
-#if defined LAUNCHER_EXPORTS
-#if defined WIN32
-#define LAUNCHER_EXPORT __declspec( dllexport )
-#else
-#define LAUNCHER_EXPORT
-#endif
-#else
-#if defined WNT
-#define LAUNCHER_EXPORT __declspec( dllimport )
-#else
-#define LAUNCHER_EXPORT
-#endif
-#endif
-
-class LAUNCHER_EXPORT SALOME_Launcher:
+class SALOMELAUNCHER_EXPORT SALOME_Launcher:
public POA_Engines::SalomeLauncher,
public PortableServer::RefCountServantBase
{
const Engines::BatchParameters& batch_params,
const Engines::MachineParameters& params);
- char* querySalomeJob( const CORBA::Long jobId, const Engines::MachineParameters& params);
- void deleteSalomeJob( const CORBA::Long jobId, const Engines::MachineParameters& params);
- void getResultSalomeJob( const char * directory, const CORBA::Long jobId, const Engines::MachineParameters& params );
+ char* querySalomeJob( CORBA::Long jobId, const Engines::MachineParameters& params);
+ void deleteSalomeJob( CORBA::Long jobId, const Engines::MachineParameters& params);
+ void getResultSalomeJob( const char * directory, CORBA::Long jobId, const Engines::MachineParameters& params );
CORBA::Boolean testBatch(const Engines::MachineParameters& params);
void AttachDebugger()
{
+#ifndef WIN32
if(getenv ("DEBUGGER"))
{
std::stringstream exec;
system(exec.str().c_str());
while(1);
}
+#endif
}
void terminateHandler(void)
#ifndef _SALOME_ModuleCatalog_HXX_
#define _SALOME_ModuleCatalog_HXX_
-#ifdef WNT
- #if defined MODULECATALOG_EXPORTS
- #if defined WIN32
- #define MODULECATALOG_EXPORT __declspec( dllexport )
- #else
- #define MODULECATALOG_EXPORT
- #endif
- #else
- #if defined WIN32
- #define MODULECATALOG_EXPORT __declspec( dllimport )
- #else
- #define MODULECATALOG_EXPORT
- #endif
- #endif
+#ifdef WIN32
+# ifdef MODULECATALOG_EXPORTS
+# define MODULECATALOG_EXPORT __declspec( dllexport )
+# else
+# define MODULECATALOG_EXPORT __declspec( dllimport )
+# endif
#else
#define MODULECATALOG_EXPORT
#endif
SALOME_ResourcesManager.hxx \
SALOME_ResourcesCatalog_Handler.hxx \
SALOME_LoadRateManager.hxx \
- ResourcesManager.hxx
+ ResourcesManager.hxx \
+ ResourcesManager_Defs.hxx
#
# ===============================================================
ResourcesManager.cxx
libResourcesManager_la_CPPFLAGS =\
- -I$(srcdir)/../Basics \
- -I$(srcdir)/../SALOMELocalTrace \
- @LIBXML_INCLUDES@
+ $(COMMON_CPPFLAGS)
libResourcesManager_la_LDFLAGS = -no-undefined -version-info=0:0:0
libResourcesManager_la_LIBADD =\
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
#include "ResourcesManager.hxx"
+#include <OpUtil.hxx>
#include <fstream>
#include <iostream>
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
-#include <unistd.h>
#include <libxml/parser.h>
+#ifndef WIN32
+# include <unistd.h>
+#endif
+
+
#include "utilities.h"
#define MAX_SIZE_FOR_HOSTNAME 256;
bool erasedHost = false;
if( mapOfModulesOfCurrentHost.size() > 0 ){
- for(int i=0;i<componentList.size();i++){
+ for(unsigned int i=0;i<componentList.size();i++){
const char* compoi = componentList[i].c_str();
vector<string>::const_iterator itt = find(mapOfModulesOfCurrentHost.begin(),
mapOfModulesOfCurrentHost.end(),
else
return _resourcesBatchList[machine];
}
-
-std::string ResourcesManager_cpp::GetHostname()
-{
- int ls = 100, r = 1;
- char *s;
-
- while (ls < 10000 && r) {
- ls *= 2;
- s = new char[ls];
- r = gethostname(s, ls-1);
- switch (r)
- {
- case 0:
- break;
- default:
-#ifdef EINVAL
- case EINVAL:
-#endif
-#ifdef ENAMETOOLONG
- case ENAMETOOLONG:
-#endif
- delete [] s;
- continue;
- }
- }
-
- if (r != 0) {
- s = new char[50];
- strcpy(s, "localhost");
- }
-
- // remove all after '.'
- char *aDot = (strchr(s,'.'));
- if (aDot) aDot[0] = '\0';
-
- string p = s;
- delete [] s;
- return p;
-}
-
#ifndef __RESOURCESMANAGER_HXX__
#define __RESOURCESMANAGER_HXX__
+#include "ResourcesManager_Defs.hxx"
+
#include <string>
#include <fstream>
#include <vector>
unsigned int mem_mb;
};
-class ResourcesException
+class RESOURCESMANAGER_EXPORT ResourcesException
{
public:
const std::string msg;
ResourcesException(const std::string m) : msg(m) {}
};
-class ResourcesManager_cpp
+class RESOURCESMANAGER_EXPORT ResourcesManager_cpp
{
public:
SALOME_LoadRateManager _dynamicResourcesSelecter;
//! different behaviour if $APPLI exists (SALOME Application)
- bool _isAppliSalomeDefined;
-
- std::string GetHostname();
+ bool _isAppliSalomeDefined;
};
#endif // __RESOURCESMANAGER_HXX__
#ifndef __SALOME_LOADRATEMANAGER_HXX__
#define __SALOME_LOADRATEMANAGER_HXX__
+#include "ResourcesManager_Defs.hxx"
#include <string>
#include "SALOME_ResourcesCatalog_Parser.hxx"
-#if defined RESOURCESMANAGER_EXPORTS
-#if defined WIN32
-#define RESOURCESMANAGER_EXPORT __declspec( dllexport )
-#else
-#define RESOURCESMANAGER_EXPORT
-#endif
-#else
-#if defined WNT
-#define RESOURCESMANAGER_EXPORT __declspec( dllimport )
-#else
-#define RESOURCESMANAGER_EXPORT
-#endif
-#endif
-
class RESOURCESMANAGER_EXPORT SALOME_LoadRateManager
{
#ifndef SALOME_RESOURCES_CATALOG_HANDLER
#define SALOME_RESOURCES_CATALOG_HANDLER
+
+#include "ResourcesManager_Defs.hxx"
+
#include "SALOME_ResourcesCatalog_Parser.hxx"
#include <string>
#include <libxml/parser.h>
-class SALOME_ResourcesCatalog_Handler
+class RESOURCESMANAGER_EXPORT SALOME_ResourcesCatalog_Handler
{
public :
#ifndef SALOME_RESOURCES_CATALOG_PARSER
#define SALOME_RESOURCES_CATALOG_PARSER
+#include "ResourcesManager_Defs.hxx"
+
#include <string>
#include <vector>
#include <map>
enum MpiImplType {indif, lam, mpich1, mpich2, openmpi, slurm};
-class ResourceDataToSort
+class RESOURCESMANAGER_EXPORT ResourceDataToSort
{
public:
unsigned int GetNumberOfPoints() const;
};
-struct ParserResourcesType
+struct RESOURCESMANAGER_EXPORT ParserResourcesType
{
ResourceDataToSort DataForSort;
std::string HostName;
p.mem_mb = params.mem_mb;
vector<string> cl;
- for(int i=0;i<componentList.length();i++)
+ for(unsigned int i=0;i<componentList.length();i++)
cl.push_back(string(componentList[i]));
Engines::MachineList *ret=new Engines::MachineList;
try{
vector <std::string> vec = _rm.GetFittingResources(p,cl);
ret->length(vec.size());
- for(int i=0;i<vec.size();i++)
+ for(unsigned int i=0;i<vec.size();i++)
(*ret)[i] = (vec[i]).c_str();
}
catch(const ResourcesException &ex){
SALOME_ResourcesManager::FindFirst(const Engines::MachineList& listOfMachines)
{
vector<string> ml;
- for(int i=0;i<listOfMachines.length();i++)
+ for(unsigned int i=0;i<listOfMachines.length();i++)
ml.push_back(string(listOfMachines[i]));
return CORBA::string_dup(_rm.FindFirst(ml).c_str());
p_ptr->username = CORBA::string_dup(resource.UserName.c_str());
p_ptr->applipath = CORBA::string_dup(resource.AppliPath.c_str());
p_ptr->modList.length(resource.ModulesList.size());
- for(int i=0;i<resource.ModulesList.size();i++)
+ for(unsigned int i=0;i<resource.ModulesList.size();i++)
p_ptr->modList[i] = CORBA::string_dup(resource.ModulesList[i].c_str());
p_ptr->OS = CORBA::string_dup(resource.OS.c_str());
p_ptr->mem_mb = resource.DataForSort._memInMB;
#ifdef WIN32
-# ifdef RESOURCESMANAGER_EXPORTS
-# define RESOURCESMANAGER_EXPORT __declspec( dllexport )
+# ifdef SALOMERESOURCESMANAGER_EXPORTS
+# define SALOMERESOURCESMANAGER_EXPORT __declspec( dllexport )
# else
-# define RESOURCESMANAGER_EXPORT __declspec( dllimport )
+# define SALOMERESOURCESMANAGER_EXPORT __declspec( dllimport )
# endif
#else
-# define RESOURCESMANAGER_EXPORT
+# define SALOMERESOURCESMANAGER_EXPORT
#endif
// --- WARNING ---
// Only one thread should use the SALOME_ResourcesManager class in a SALOME
// session.
-class RESOURCESMANAGER_EXPORT SALOME_ResourcesManager:
+class SALOMERESOURCESMANAGER_EXPORT SALOME_ResourcesManager:
public POA_Engines::ResourcesManager,
public PortableServer::RefCountServantBase
{
#define INFOS(msg) {MESS_BEGIN("- Trace ") << msg << MESS_END}
#define PYSCRIPT(msg) {MESS_INIT("---PYSCRIPT--- ") << msg << MESS_END}
#define INTERRUPTION(msg) {MESS_BEGIN("- INTERRUPTION: ")<< msg << MESS_ABORT}
-#ifdef WNT
+
+#ifdef WIN32
#define IMMEDIATE_ABORT(code) {std::cout <<std::flush; \
std::cerr << "- ABORT " << __FILE__ << " [" <<__LINE__<< "] : " << flush; \
std::cerr << "ABORT return code= "<< code << std::endl; \
#endif
using namespace std;
+#ifdef WIN32
+# define separator '\\'
+#else
+# define separator '/'
+#endif
+
//int gethostname(char *name, size_t len);
std::string GetHostname()
std::string OpUtil_Dir::GetTmpDirByPath( const std::string& tmp_path )
{
string aTmpDir = tmp_path;
- char sep =
-#ifdef WNT
- '\\';
-#else
- '/';
-#endif
- /*if ( tmp_path.length() > 0 )
- {
- char *Tmp_dir = getenv(tmp_path_env.c_str());
- if( Tmp_dir != NULL )
- {
- aTmpDir = string(Tmp_dir);
- if(aTmpDir[aTmpDir.size()-1] != sep)
- aTmpDir+=sep;
- }
- }*/
if ( aTmpDir == "" )
{
#ifdef WNT
#endif
}
- if(aTmpDir[aTmpDir.size()-1] != sep)
- aTmpDir+=sep;
+ if(aTmpDir[aTmpDir.size()-1] != separator)
+ aTmpDir+=separator;
srand((unsigned int)time(NULL));
int aRND = 999 + (int)(100000.0*rand()/(RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
}
}
- if(aDir[aDir.size()-1] != sep) aDir+=sep;
+ if(aDir[aDir.size()-1] != separator) aDir+=separator;
#ifdef WNT
CreateDirectory(aDir.c_str(), NULL);
std::string OpUtil_Dir::GetTmpDir()
{
return GetTmpDirByPath( "" );
- //Find a temporary directory to store a file
-/*
- string aTmpDir = "";
- char sep =
-#ifdef WNT
- '\\';
-#else
- '/';
-#endif
- if ( tmp_path_env.length() > 0 )
- {
- char *Tmp_dir = getenv(tmp_path_env.c_str());
- if( Tmp_dir != NULL )
- {
- aTmpDir = string(Tmp_dir);
- if(aTmpDir[aTmpDir.size()-1] != sep)
- aTmpDir+=sep;
- }
- }
- if ( aTmpDir == "" )
- {
-#ifdef WNT
- char *Tmp_dir = getenv("TEMP");
- if( Tmp_dir == NULL )
- {
- Tmp_dir = getenv("TMP");
- if (Tmp_dir == NULL)
- aTmpDir = string("C:\\");
- else
- aTmpDir = string(Tmp_dir);
- }
- else
- aTmpDir = string(Tmp_dir);
-#else
- aTmpDir = string("/tmp/");
-#endif
- }
-
- srand((unsigned int)time(NULL));
- int aRND = 999 + (int)(100000.0*rand()/(RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
- char buffer[127];
- sprintf(buffer, "%d", aRND);
- string aSubDir(buffer);
- if(aSubDir.size() <= 1) aSubDir = string("123409876");
-
- aTmpDir += aSubDir; //Get RND sub directory
-
- string aDir = aTmpDir;
+}
- if(Exists(aDir)) {
- for(aRND = 0; Exists(aDir); aRND++) {
+string OpUtil_Dir::GetTmpFileName()
+{
+ string tmpDir = GetTmpDir();
+ string aFilePath = "";
+ if(IsExists(tmpDir)) {
+ srand((unsigned int)time(NULL));
+ int aRND = 999 + (int)(100000.0*rand()/(RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
+ char buffer[127];
+ sprintf(buffer, "%d", aRND);
+ string aSubDir(buffer);
+ if(aSubDir.size() <= 1) aSubDir = string("123409876");
+
+ string aFilePath = tmpDir;
+ for(aRND = 0; IsExists(aFilePath); aRND++) {
sprintf(buffer, "%d", aRND);
- aDir = aTmpDir+buffer; //Build a unique directory name
+ aFilePath = tmpDir+buffer; //Build a unique file name
}
}
-
- if(aDir[aDir.size()-1] != sep) aDir+=sep;
-
-#ifdef WNT
- CreateDirectory(aDir.c_str(), NULL);
-#else
- mkdir(aDir.c_str(), 0x1ff);
-#endif
-
- return aDir;*/
+ return aFilePath;
}
+
bool OpUtil_Dir::IsExists(const string& thePath)
{
#ifdef WNT
// /tmp/something/ for Unix or c:\something\ for WNT
static std::string GetTmpDir();
+ // Returns the unique temporary file name without any extension
+ // /tmp/something/file for Unix or c:\something\file for WNT
+ static std::string GetTmpFileName();
+
// Returns True(False) if the path (not)exists
static bool IsExists( const std::string& path );