From 08dbc382760145f11803a033e76b2d9ef010bfc0 Mon Sep 17 00:00:00 2001 From: abd Date: Thu, 28 Aug 2008 09:20:09 +0000 Subject: [PATCH] Fix compilation problems on Win32 platform --- bin/Makefile.am | 2 +- bin/NSparam.py | 2 +- bin/addToKillList.py | 2 +- bin/killSalome.py | 9 +- bin/killSalomeWithPort.py | 6 +- bin/runSalome.py | 6 +- bin/salome_session.py | 4 +- bin/salome_utils.py | 346 +++++ src/Batch/Batch_BatchManager_LSF.hxx | 3 +- src/Batch/Batch_BatchManager_Local.cxx | 521 +++---- src/Batch/Batch_BatchManager_Local.hxx | 6 +- src/Batch/Batch_BatchManager_Local_RSH.cxx | 4 +- src/Batch/Batch_BatchManager_Local_RSH.hxx | 3 +- src/Batch/Batch_BatchManager_Local_SH.cxx | 2 + src/Batch/Batch_BatchManager_Local_SH.hxx | 3 +- src/Batch/Batch_BatchManager_Local_SSH.cxx | 5 +- src/Batch/Batch_BatchManager_Local_SSH.hxx | 3 +- src/Batch/Batch_BatchManager_PBS.hxx | 3 +- src/Batch/Batch_BatchManager_eClient.cxx | 84 +- src/Batch/Batch_BatchManager_eClient.hxx | 5 +- src/Batch/Batch_BatchManager_eLSF.cxx | 13 +- src/Batch/Batch_BatchManager_eLSF.hxx | 3 +- src/Batch/Batch_BatchManager_ePBS.cxx | 14 +- src/Batch/Batch_BatchManager_ePBS.hxx | 4 +- src/Batch/Batch_FactBatchManager_eLSF.hxx | 5 +- src/Batch/Batch_FactBatchManager_ePBS.hxx | 5 +- src/Batch/Batch_Job_Local.cxx | 2 + src/Batch/Batch_Parametre.hxx | 2 +- src/Batch/Makefile.am | 3 +- src/Batch/MpiImpl.hxx | 15 +- src/Container/Container_i.cxx | 1267 +++++++++-------- src/Container/SALOME_ContainerManager.cxx | 103 +- src/Container/Salome_file_i.cxx | 35 +- src/DSC/DSC_Basic/ConnectionManager_i.cxx | 11 +- src/Launcher/BatchTest.cxx | 30 +- src/Launcher/BatchTest.hxx | 13 +- src/Launcher/Launcher.cxx | 6 +- src/Launcher/Launcher.hxx | 14 +- src/Launcher/SALOME_Launcher.cxx | 14 +- src/Launcher/SALOME_Launcher.hxx | 22 +- src/Launcher/SALOME_LauncherServer.cxx | 2 + src/ModuleCatalog/SALOME_ModuleCatalog.hxx | 20 +- src/ResourcesManager/Makefile.am | 7 +- src/ResourcesManager/ResourcesManager.cxx | 49 +- src/ResourcesManager/ResourcesManager.hxx | 10 +- .../SALOME_LoadRateManager.hxx | 15 +- .../SALOME_ResourcesCatalog_Handler.hxx | 5 +- .../SALOME_ResourcesCatalog_Parser.hxx | 6 +- .../SALOME_ResourcesManager.cxx | 8 +- .../SALOME_ResourcesManager.hxx | 10 +- src/SALOMELocalTrace/utilities.h | 3 +- src/Utils/OpUtil.cxx | 107 +- src/Utils/OpUtil.hxx | 4 + 53 files changed, 1651 insertions(+), 1195 deletions(-) create mode 100644 bin/salome_utils.py diff --git a/bin/Makefile.am b/bin/Makefile.am index 077743e33..328b52a91 100644 --- a/bin/Makefile.am +++ b/bin/Makefile.am @@ -61,7 +61,7 @@ dist_salomescript_SCRIPTS = \ runSalome.py \ salomeConsole.py \ salome_session.py \ - salome_utilities.py \ + salome_utils.py \ server.py \ setenv.py \ showNS.py \ diff --git a/bin/NSparam.py b/bin/NSparam.py index 2f93c9e54..e209063ff 100755 --- a/bin/NSparam.py +++ b/bin/NSparam.py @@ -31,7 +31,7 @@ def getNSparams(info=""): 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 diff --git a/bin/addToKillList.py b/bin/addToKillList.py index 548a8958d..e13aebc5d 100755 --- a/bin/addToKillList.py +++ b/bin/addToKillList.py @@ -29,7 +29,7 @@ def findFileDict(): 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 diff --git a/bin/killSalome.py b/bin/killSalome.py index 1c76890a9..60529d1e7 100755 --- a/bin/killSalome.py +++ b/bin/killSalome.py @@ -29,9 +29,12 @@ def killAllPorts(): """ 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): @@ -45,9 +48,11 @@ def killAllPorts(): 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): diff --git a/bin/killSalomeWithPort.py b/bin/killSalomeWithPort.py index 2308505a0..748d8e9d9 100755 --- a/bin/killSalomeWithPort.py +++ b/bin/killSalomeWithPort.py @@ -39,7 +39,7 @@ def getPiDict(port,appname='salome',full=True,hidden=True): - 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 @@ -68,7 +68,7 @@ def appliCleanOmniOrbConfig(port): - ${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: @@ -115,7 +115,7 @@ def killMyPort(port): 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", diff --git a/bin/runSalome.py b/bin/runSalome.py index aae7d0dfa..334f5bafb 100755 --- a/bin/runSalome.py +++ b/bin/runSalome.py @@ -204,7 +204,7 @@ class LoggerServer(Server): 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, @@ -749,7 +749,7 @@ def searchFreePort(args, save_config=1): 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") @@ -831,7 +831,7 @@ def no_main(): 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) diff --git a/bin/salome_session.py b/bin/salome_session.py index 64e13c951..cbf5a136f 100644 --- a/bin/salome_session.py +++ b/bin/salome_session.py @@ -39,7 +39,7 @@ def getShortHostName(): 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(): @@ -48,7 +48,7 @@ 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 diff --git a/bin/salome_utils.py b/bin/salome_utils.py new file mode 100644 index 000000000..7b3aadeac --- /dev/null +++ b/bin/salome_utils.py @@ -0,0 +1,346 @@ +# 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 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 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 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 diff --git a/src/Batch/Batch_BatchManager_LSF.hxx b/src/Batch/Batch_BatchManager_LSF.hxx index 170dbd791..e81f2df9d 100644 --- a/src/Batch/Batch_BatchManager_LSF.hxx +++ b/src/Batch/Batch_BatchManager_LSF.hxx @@ -30,6 +30,7 @@ #ifndef _BATCHMANAGER_LSF_H_ #define _BATCHMANAGER_LSF_H_ +#include "Batch_Defines.hxx" #include "Batch_Job.hxx" #include "Batch_Job.hxx" @@ -50,7 +51,7 @@ namespace Batch { class JobInfo; class FactBatchManager; - class BatchManager_LSF : public BatchManager + class BATCH_EXPORT BatchManager_LSF : public BatchManager { public: // Constructeur et destructeur diff --git a/src/Batch/Batch_BatchManager_Local.cxx b/src/Batch/Batch_BatchManager_Local.cxx index 5359c3d1c..46b1f9463 100644 --- a/src/Batch/Batch_BatchManager_Local.cxx +++ b/src/Batch/Batch_BatchManager_Local.cxx @@ -17,23 +17,27 @@ // 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 #include #include #include #include -#include +#ifdef WIN32 +# include +#else +# include +# include +#endif #include -#include #include #include #include @@ -45,7 +49,10 @@ namespace Batch { // 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); @@ -95,7 +102,7 @@ namespace Batch { cancel(thread_id); } - + // Methode pour le controle des jobs : suspend un job en file d'attente void BatchManager_Local::holdJob(const JobId & jobid) { @@ -129,8 +136,8 @@ namespace Batch { 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 @@ -202,7 +209,12 @@ namespace Batch { 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; @@ -213,9 +225,9 @@ namespace Batch { // 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(p_ta)); + &thread_attr, + &ThreadAdapter::run, + static_cast(p_ta)); if (rc) { } @@ -253,12 +265,14 @@ namespace Batch { // @@@ --------> 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 <-------- @@@ @@ -274,6 +288,7 @@ namespace Batch { // @@@ --------> 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); @@ -281,6 +296,7 @@ namespace Batch { } 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 <-------- @@@ @@ -291,7 +307,7 @@ namespace Batch { // 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 } @@ -301,12 +317,12 @@ namespace Batch { // 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); @@ -338,8 +354,13 @@ namespace Batch { 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; @@ -354,21 +375,21 @@ namespace Batch { 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); + } } } @@ -376,7 +397,10 @@ namespace Batch { - +#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()); @@ -390,7 +414,7 @@ namespace Batch { } else { // fils p_ta->fils(); } - +#endif @@ -400,21 +424,21 @@ namespace Batch { 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); + } } } @@ -427,9 +451,9 @@ namespace Batch { if ( (rc == 0) || (child < 0) ) { std::vector::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()); } } @@ -448,7 +472,7 @@ namespace Batch { UNDER_LOCK( cout << "Father is leaving" << endl ); pthread_exit(NULL); - +#endif return NULL; } @@ -457,6 +481,7 @@ namespace Batch { 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 @@ -492,44 +517,44 @@ namespace Batch { 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; } @@ -543,33 +568,33 @@ namespace Batch { 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 <-------- @@@ + } } @@ -578,51 +603,52 @@ namespace Batch { // @@@ --------> 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 } @@ -632,139 +658,140 @@ namespace Batch { 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( (*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( (*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(*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(*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 } @@ -772,6 +799,8 @@ namespace Batch { void BatchManager_Local::kill_child_on_exit(void * p_pid) { +#ifndef WIN32 + //TODO: porting of following functionality pid_t child = * static_cast(p_pid); // On tue le fils @@ -780,7 +809,7 @@ namespace Batch { // 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) diff --git a/src/Batch/Batch_BatchManager_Local.hxx b/src/Batch/Batch_BatchManager_Local.hxx index 53091cab2..e6d969c82 100644 --- a/src/Batch/Batch_BatchManager_Local.hxx +++ b/src/Batch/Batch_BatchManager_Local.hxx @@ -29,6 +29,7 @@ #ifndef _BATCHMANAGER_LOCAL_H_ #define _BATCHMANAGER_LOCAL_H_ +#include "Batch_Defines.hxx" #include #include @@ -50,7 +51,7 @@ namespace Batch { class FactBatchManager; - class BatchManager_Local : public BatchManager + class BATCH_EXPORT BatchManager_Local : public BatchManager { private: friend class ThreadAdapter; @@ -148,7 +149,10 @@ namespace Batch { 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 _thread_id_id_association; +#endif #ifdef SWIG public: diff --git a/src/Batch/Batch_BatchManager_Local_RSH.cxx b/src/Batch/Batch_BatchManager_Local_RSH.cxx index e93ede663..ea2a66e4e 100644 --- a/src/Batch/Batch_BatchManager_Local_RSH.cxx +++ b/src/Batch/Batch_BatchManager_Local_RSH.cxx @@ -35,9 +35,11 @@ #include #include #include +#ifndef WIN32 #include -#include #include +#endif +#include #include #include #include diff --git a/src/Batch/Batch_BatchManager_Local_RSH.hxx b/src/Batch/Batch_BatchManager_Local_RSH.hxx index be7a4a04b..f71459260 100644 --- a/src/Batch/Batch_BatchManager_Local_RSH.hxx +++ b/src/Batch/Batch_BatchManager_Local_RSH.hxx @@ -29,6 +29,7 @@ #ifndef _BATCHMANAGER_LOCAL_RSH_H_ #define _BATCHMANAGER_LOCAL_RSH_H_ +#include "Batch_Defines.hxx" #include #include @@ -50,7 +51,7 @@ namespace Batch { class FactBatchManager; - class BatchManager_Local_RSH : public BatchManager_Local + class BATCH_EXPORT BatchManager_Local_RSH : public BatchManager_Local { public: // Constructeur et destructeur diff --git a/src/Batch/Batch_BatchManager_Local_SH.cxx b/src/Batch/Batch_BatchManager_Local_SH.cxx index be9b990ea..f543c47d5 100644 --- a/src/Batch/Batch_BatchManager_Local_SH.cxx +++ b/src/Batch/Batch_BatchManager_Local_SH.cxx @@ -35,7 +35,9 @@ #include #include #include +#ifndef WIN32 #include +#endif #include #include #include diff --git a/src/Batch/Batch_BatchManager_Local_SH.hxx b/src/Batch/Batch_BatchManager_Local_SH.hxx index c3de1af7a..bd28a28aa 100644 --- a/src/Batch/Batch_BatchManager_Local_SH.hxx +++ b/src/Batch/Batch_BatchManager_Local_SH.hxx @@ -29,6 +29,7 @@ #ifndef _BATCHMANAGER_LOCAL_SH_H_ #define _BATCHMANAGER_LOCAL_SH_H_ +#include "Batch_Defines.hxx" #include #include @@ -50,7 +51,7 @@ namespace Batch { class FactBatchManager; - class BatchManager_Local_SH : public BatchManager_Local + class BATCH_EXPORT BatchManager_Local_SH : public BatchManager_Local { public: // Constructeur et destructeur diff --git a/src/Batch/Batch_BatchManager_Local_SSH.cxx b/src/Batch/Batch_BatchManager_Local_SSH.cxx index 696d7473e..9f77016e2 100644 --- a/src/Batch/Batch_BatchManager_Local_SSH.cxx +++ b/src/Batch/Batch_BatchManager_Local_SSH.cxx @@ -35,9 +35,12 @@ #include #include #include +#ifndef WIN32 #include -#include #include +#endif +#include + #include #include #include diff --git a/src/Batch/Batch_BatchManager_Local_SSH.hxx b/src/Batch/Batch_BatchManager_Local_SSH.hxx index b45314f3c..5d6c89c7b 100644 --- a/src/Batch/Batch_BatchManager_Local_SSH.hxx +++ b/src/Batch/Batch_BatchManager_Local_SSH.hxx @@ -29,6 +29,7 @@ #ifndef _BATCHMANAGER_LOCAL_SSH_H_ #define _BATCHMANAGER_LOCAL_SSH_H_ +#include "Batch_Defines.hxx" #include #include @@ -50,7 +51,7 @@ namespace Batch { class FactBatchManager; - class BatchManager_Local_SSH : public BatchManager_Local + class BATCH_EXPORT BatchManager_Local_SSH : public BatchManager_Local { public: // Constructeur et destructeur diff --git a/src/Batch/Batch_BatchManager_PBS.hxx b/src/Batch/Batch_BatchManager_PBS.hxx index 53e8a2798..9e995b540 100644 --- a/src/Batch/Batch_BatchManager_PBS.hxx +++ b/src/Batch/Batch_BatchManager_PBS.hxx @@ -30,6 +30,7 @@ #ifndef _BATCHMANAGER_PBS_H_ #define _BATCHMANAGER_PBS_H_ +#include "Batch_Defines.hxx" #include "Batch_Job.hxx" #include "Batch_Job.hxx" @@ -50,7 +51,7 @@ namespace Batch { class JobInfo; class FactBatchManager; - class BatchManager_PBS : public BatchManager + class BATCH_EXPORT BatchManager_PBS : public BatchManager { public: // Constructeur et destructeur diff --git a/src/Batch/Batch_BatchManager_eClient.cxx b/src/Batch/Batch_BatchManager_eClient.cxx index 41ce47c2e..9a199e9b7 100644 --- a/src/Batch/Batch_BatchManager_eClient.cxx +++ b/src/Batch/Batch_BatchManager_eClient.cxx @@ -18,20 +18,21 @@ // 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 #include #include #include #include "Batch_BatchManager_eClient.hxx" +#include "OpUtil.hxx" namespace Batch { @@ -65,7 +66,7 @@ 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 += " "; @@ -108,7 +109,7 @@ namespace Batch { 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++) { @@ -118,8 +119,8 @@ namespace Batch { command += inputFile.getLocal(); command += " "; if(_username != ""){ - command += _username; - command += "@"; + command += _username; + command += "@"; } command += _hostname; command += ":"; @@ -127,11 +128,11 @@ namespace Batch { 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()); } } @@ -145,20 +146,20 @@ namespace Batch { 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 += ":"; @@ -169,13 +170,13 @@ namespace Batch { 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; } } @@ -203,26 +204,22 @@ namespace Batch { 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); @@ -231,5 +228,4 @@ namespace Batch { system(temp); free(temp); } - } diff --git a/src/Batch/Batch_BatchManager_eClient.hxx b/src/Batch/Batch_BatchManager_eClient.hxx index 717eae6a3..ca84efdb4 100644 --- a/src/Batch/Batch_BatchManager_eClient.hxx +++ b/src/Batch/Batch_BatchManager_eClient.hxx @@ -30,6 +30,7 @@ #ifndef _BATCHMANAGER_eClient_H_ #define _BATCHMANAGER_eClient_H_ +#include "Batch_Defines.hxx" #include "MpiImpl.hxx" #include "Batch_BatchManager.hxx" @@ -38,7 +39,7 @@ namespace Batch { class Job; - class EmulationException + class BATCH_EXPORT EmulationException { public: const std::string msg; @@ -46,7 +47,7 @@ namespace Batch { EmulationException(const std::string m) : msg(m) {} }; - class BatchManager_eClient : public BatchManager + class BATCH_EXPORT BatchManager_eClient : public BatchManager { public: // Constructeur et destructeur diff --git a/src/Batch/Batch_BatchManager_eLSF.cxx b/src/Batch/Batch_BatchManager_eLSF.cxx index d1c44e60d..46552a015 100644 --- a/src/Batch/Batch_BatchManager_eLSF.cxx +++ b/src/Batch/Batch_BatchManager_eLSF.cxx @@ -32,6 +32,10 @@ #include #include #include "Batch_BatchManager_eLSF.hxx" +#ifdef WIN32 +# include +# include +#endif namespace Batch { @@ -228,6 +232,7 @@ 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]; @@ -263,7 +268,12 @@ namespace Batch { 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; @@ -291,6 +301,7 @@ namespace Batch { throw EmulationException("Error of connection on remote host"); RmTmpFile(TmpFileName); +#endif } diff --git a/src/Batch/Batch_BatchManager_eLSF.hxx b/src/Batch/Batch_BatchManager_eLSF.hxx index 00d79a4fa..9673d1a1e 100644 --- a/src/Batch/Batch_BatchManager_eLSF.hxx +++ b/src/Batch/Batch_BatchManager_eLSF.hxx @@ -30,6 +30,7 @@ #ifndef _BATCHMANAGER_eLSF_H_ #define _BATCHMANAGER_eLSF_H_ +#include "Batch_Defines.hxx" #include "Batch_JobId.hxx" #include "Batch_JobInfo.hxx" @@ -48,7 +49,7 @@ namespace Batch { class JobInfo; class FactBatchManager; - class BatchManager_eLSF : public BatchManager_eClient + class BATCH_EXPORT BatchManager_eLSF : public BatchManager_eClient { public: // Constructeur et destructeur diff --git a/src/Batch/Batch_BatchManager_ePBS.cxx b/src/Batch/Batch_BatchManager_ePBS.cxx index 999025cfb..d806ddae3 100644 --- a/src/Batch/Batch_BatchManager_ePBS.cxx +++ b/src/Batch/Batch_BatchManager_ePBS.cxx @@ -32,6 +32,10 @@ #include #include #include "Batch_BatchManager_ePBS.hxx" +#ifdef WIN32 +# include +# include +#endif namespace Batch { @@ -227,6 +231,7 @@ 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]; @@ -262,7 +267,12 @@ namespace Batch { 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; @@ -290,7 +300,7 @@ namespace Batch { throw EmulationException("Error of connection on remote host"); RmTmpFile(TmpFileName); - +#endif } } diff --git a/src/Batch/Batch_BatchManager_ePBS.hxx b/src/Batch/Batch_BatchManager_ePBS.hxx index 42f4b1b69..2bfa60a1a 100644 --- a/src/Batch/Batch_BatchManager_ePBS.hxx +++ b/src/Batch/Batch_BatchManager_ePBS.hxx @@ -30,6 +30,8 @@ #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" @@ -47,7 +49,7 @@ namespace Batch { class JobInfo; class FactBatchManager; - class BatchManager_ePBS : public BatchManager_eClient + class BATCH_EXPORT BatchManager_ePBS : public BatchManager_eClient { public: // Constructeur et destructeur diff --git a/src/Batch/Batch_FactBatchManager_eLSF.hxx b/src/Batch/Batch_FactBatchManager_eLSF.hxx index e1660aaaa..558ee007e 100644 --- a/src/Batch/Batch_FactBatchManager_eLSF.hxx +++ b/src/Batch/Batch_FactBatchManager_eLSF.hxx @@ -29,7 +29,8 @@ #ifndef _FACTBATCHMANAGER_eLSF_H_ #define _FACTBATCHMANAGER_eLSF_H_ -using namespace std; +#include "Batch_Defines.hxx" + #include #include #include "Batch_BatchManager_eClient.hxx" @@ -39,7 +40,7 @@ namespace Batch { class BatchManager_eLSF; - class FactBatchManager_eLSF : public FactBatchManager_eClient + class BATCH_EXPORT FactBatchManager_eLSF : public FactBatchManager_eClient { public: // Constructeur et destructeur diff --git a/src/Batch/Batch_FactBatchManager_ePBS.hxx b/src/Batch/Batch_FactBatchManager_ePBS.hxx index 69fdf322a..b78e76144 100644 --- a/src/Batch/Batch_FactBatchManager_ePBS.hxx +++ b/src/Batch/Batch_FactBatchManager_ePBS.hxx @@ -29,7 +29,8 @@ #ifndef _FACTBATCHMANAGER_ePBS_H_ #define _FACTBATCHMANAGER_ePBS_H_ -using namespace std; +#include "Batch_Defines.hxx" + #include #include #include "Batch_BatchManager_eClient.hxx" @@ -39,7 +40,7 @@ namespace Batch { class BatchManager_ePBS; - class FactBatchManager_ePBS : public FactBatchManager_eClient + class BATCH_EXPORT FactBatchManager_ePBS : public FactBatchManager_eClient { public: // Constructeur et destructeur diff --git a/src/Batch/Batch_Job_Local.cxx b/src/Batch/Batch_Job_Local.cxx index bc276f819..74401458e 100644 --- a/src/Batch/Batch_Job_Local.cxx +++ b/src/Batch/Batch_Job_Local.cxx @@ -28,7 +28,9 @@ #include #include +#ifndef WIN32 #include +#endif #include "Batch_Job_Local.hxx" namespace Batch { diff --git a/src/Batch/Batch_Parametre.hxx b/src/Batch/Batch_Parametre.hxx index a0cf0da5d..ea2bd8f09 100644 --- a/src/Batch/Batch_Parametre.hxx +++ b/src/Batch/Batch_Parametre.hxx @@ -43,7 +43,7 @@ using namespace std; // 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; diff --git a/src/Batch/Makefile.am b/src/Batch/Makefile.am index f6e53292b..bc9ad8367 100644 --- a/src/Batch/Makefile.am +++ b/src/Batch/Makefile.am @@ -117,7 +117,8 @@ LIB_CPPFLAGS = \ ${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 \ diff --git a/src/Batch/MpiImpl.hxx b/src/Batch/MpiImpl.hxx index 07f306bdf..1056c2581 100644 --- a/src/Batch/MpiImpl.hxx +++ b/src/Batch/MpiImpl.hxx @@ -29,9 +29,10 @@ #ifndef _BL_MPIIMPL_H_ #define _BL_MPIIMPL_H_ +#include "Batch_Defines.hxx" #include -class MpiImplException +class BATCH_EXPORT MpiImplException { public: const std::string msg; @@ -39,7 +40,7 @@ public: MpiImplException(const std::string m) : msg(m) {} }; -class MpiImpl +class BATCH_EXPORT MpiImpl { public: // Constructeur et destructeur @@ -58,7 +59,7 @@ private: }; -class MpiImpl_LAM : public MpiImpl +class BATCH_EXPORT MpiImpl_LAM : public MpiImpl { public: // Constructeur et destructeur @@ -77,7 +78,7 @@ private: }; -class MpiImpl_MPICH1 : public MpiImpl +class BATCH_EXPORT MpiImpl_MPICH1 : public MpiImpl { public: // Constructeur et destructeur @@ -96,7 +97,7 @@ private: }; -class MpiImpl_MPICH2 : public MpiImpl +class BATCH_EXPORT MpiImpl_MPICH2 : public MpiImpl { public: // Constructeur et destructeur @@ -115,7 +116,7 @@ private: }; -class MpiImpl_OPENMPI : public MpiImpl +class BATCH_EXPORT MpiImpl_OPENMPI : public MpiImpl { public: // Constructeur et destructeur @@ -134,7 +135,7 @@ private: }; -class MpiImpl_SLURM : public MpiImpl +class BATCH_EXPORT MpiImpl_SLURM : public MpiImpl { public: // Constructeur et destructeur diff --git a/src/Container/Container_i.cxx b/src/Container/Container_i.cxx index 22e9c8352..71a044a2b 100644 --- a/src/Container/Container_i.cxx +++ b/src/Container/Container_i.cxx @@ -74,10 +74,16 @@ char ** _ArgV ; // 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 @@ -88,19 +94,19 @@ omni_mutex Engines_Container_i::_numInstanceMutex ; //============================================================================= /*! - * 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, @@ -110,7 +116,7 @@ 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(); @@ -123,104 +129,104 @@ Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb, 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() @@ -233,19 +239,19 @@ 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() @@ -257,8 +263,8 @@ char* Engines_Container_i::workingdir() //============================================================================= /*! - * CORBA attribute: Container log file name - */ +* CORBA attribute: Container log file name +*/ //============================================================================= char* Engines_Container_i::logfilename() @@ -273,8 +279,8 @@ void Engines_Container_i::logfilename(const char* name) //============================================================================= /*! - * 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() @@ -286,8 +292,8 @@ 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() @@ -297,8 +303,8 @@ 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() @@ -308,11 +314,11 @@ 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() @@ -320,8 +326,8 @@ 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::iterator itm; for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++) itm->second->destroy(); @@ -331,94 +337,141 @@ void Engines_Container_i::Shutdown() //_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 @@ -435,17 +488,17 @@ Engines_Container_i::load_component_Library(const char* componentName) 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 ) ; @@ -456,9 +509,9 @@ Engines_Container_i::load_component_Library(const char* componentName) if ( handle ) { - _library_map[impl_name] = handle; - _numInstanceMutex.unlock(); - return true; + _library_map[impl_name] = handle; + _numInstanceMutex.unlock(); + return true; } _numInstanceMutex.unlock(); @@ -466,41 +519,41 @@ Engines_Container_i::load_component_Library(const char* componentName) INFOS("try import Python component "<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 @@ -527,56 +580,56 @@ Engines_Container_i::create_component_instance(const char*genericRegisterName, 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 @@ -585,13 +638,13 @@ Engines_Container_i::create_component_instance(const char*genericRegisterName, 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 @@ -612,11 +665,11 @@ Engines_Container_i::create_component_instance(const char*genericRegisterName, //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 @@ -645,97 +698,99 @@ Engines_Container_i::create_component_instance(const char*genericRegisterName, 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::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() ; @@ -743,13 +798,13 @@ Engines_Container_i::load_impl( const char* genericRegisterName, 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) @@ -766,44 +821,44 @@ 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::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("==============================================================="); @@ -814,14 +869,14 @@ bool Engines_Container_i::Kill_impl() //============================================================================= /*! - * 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 @@ -831,22 +886,22 @@ Engines_Container_i::createFileRef(const char* origFileName) 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(); @@ -854,9 +909,9 @@ Engines_Container_i::createFileRef(const char* origFileName) //============================================================================= /*! - * CORBA method: - * \return a reference to the fileTransfer object - */ +* CORBA method: +* \return a reference to the fileTransfer object +*/ //============================================================================= Engines::fileTransfer_ptr @@ -873,26 +928,26 @@ Engines_Container_i::createSalome_file(const char* origFileName) { 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)); @@ -900,25 +955,25 @@ Engines_Container_i::createSalome_file(const char* origFileName) } //============================================================================= /*! - * 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 @@ -928,77 +983,77 @@ Engines_Container_i::find_or_create_instance(string genericRegisterName, 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 + (_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 - (_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 @@ -1014,10 +1069,10 @@ Engines_Container_i::createInstance(string genericRegisterName, 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() ); @@ -1027,11 +1082,11 @@ Engines_Container_i::createInstance(string genericRegisterName, 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 @@ -1039,68 +1094,68 @@ Engines_Container_i::createInstance(string genericRegisterName, 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(_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(_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) @@ -1111,25 +1166,25 @@ 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) @@ -1144,8 +1199,8 @@ bool Engines_Container_i::isPythonContainer(const char* ContainerName) //============================================================================= /*! - * - */ +* +*/ //============================================================================= void ActSigIntHandler() @@ -1156,27 +1211,27 @@ 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 : @@ -1213,36 +1268,36 @@ void SigIntHandler(int what , // << " 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 ) @@ -1253,31 +1308,31 @@ 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 diff --git a/src/Container/SALOME_ContainerManager.cxx b/src/Container/SALOME_ContainerManager.cxx index 8d887aed8..6264e682b 100644 --- a/src/Container/SALOME_ContainerManager.cxx +++ b/src/Container/SALOME_ContainerManager.cxx @@ -216,7 +216,7 @@ StartContainer(const Engines::MachineParameters& params, possibleComputers.length()); vector lm; - for(int i=0;iGetComponent(compoi); @@ -903,14 +903,17 @@ string 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; @@ -921,24 +924,28 @@ SALOME_ContainerManager::BuildCommandToLaunchLocalContainer 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 != "") { @@ -946,33 +953,57 @@ SALOME_ContainerManager::BuildCommandToLaunchLocalContainer 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; } @@ -1038,23 +1069,13 @@ void SALOME_ContainerManager::AddOmninamesParams(ofstream& fileStream) const 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; } @@ -1133,7 +1154,9 @@ SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer tempOutputFile << " &" << endl; tempOutputFile.flush(); tempOutputFile.close(); +#ifndef WIN32 chmod(_TmpFileName.c_str(), 0x1ED); +#endif // --- Build command diff --git a/src/Container/Salome_file_i.cxx b/src/Container/Salome_file_i.cxx index 89aae57db..ed49325f9 100644 --- a/src/Container/Salome_file_i.cxx +++ b/src/Container/Salome_file_i.cxx @@ -26,9 +26,17 @@ #include "Salome_file_i.hxx" #include "utilities.h" #include -#include #include "HDFOI.hxx" -#include +#ifndef WNT +# include +# define _getcwd getcwd +# define _open open +#else +# include +# include +# include +#endif + //============================================================================= /*! @@ -39,7 +47,14 @@ 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; @@ -155,10 +170,8 @@ Salome_file_i::load(const char* hdf5_file) { 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); @@ -491,10 +504,8 @@ Salome_file_i::setLocalFile(const char* comp_file_name) } 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 @@ -556,9 +567,7 @@ Salome_file_i::setDistributedFile(const char* comp_file_name) 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 diff --git a/src/DSC/DSC_Basic/ConnectionManager_i.cxx b/src/DSC/DSC_Basic/ConnectionManager_i.cxx index 2f7f089c9..d023cf6e3 100644 --- a/src/DSC/DSC_Basic/ConnectionManager_i.cxx +++ b/src/DSC/DSC_Basic/ConnectionManager_i.cxx @@ -26,6 +26,10 @@ #include "ConnectionManager_i.hxx" #include "SALOME_NamingService.hxx" +#ifdef WIN32 +# include +#endif + ConnectionManager_i::ConnectionManager_i(CORBA::ORB_ptr orb) { _orb = CORBA::ORB::_duplicate(orb) ; SALOME_NamingService * ns = new SALOME_NamingService(orb); @@ -126,5 +130,10 @@ ConnectionManager_i::ShutdownWithExit() CORBA::Long ConnectionManager_i::getPID() { - return (CORBA::Long)getpid(); + return +#ifndef WIN32 + (CORBA::Long)getpid(); +#else + (CORBA::Long)_getpid(); +#endif } diff --git a/src/Launcher/BatchTest.cxx b/src/Launcher/BatchTest.cxx index bb44166f4..5e9afaf32 100644 --- a/src/Launcher/BatchTest.cxx +++ b/src/Launcher/BatchTest.cxx @@ -1,5 +1,8 @@ #include "BatchTest.hxx" +#ifdef WIN32 +# include +#endif BatchTest::BatchTest(const Engines::MachineParameters& batch_descr) { _batch_descr = batch_descr; @@ -66,11 +69,11 @@ BatchTest::test() << "--- 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; @@ -99,7 +102,7 @@ BatchTest::test_connection() result += "username is empty !"; return result; } - if( protocol != "rsh" and protocol != "ssh") + if( protocol != "rsh" && protocol != "ssh") { result += "protocol unknown ! (" + protocol + ")"; return result; @@ -341,7 +344,11 @@ BatchTest::test_jobsubmit_simple() if(status == 153 || status == 256*153 ) stop = true; +#ifdef WIN32 + Sleep(1); +#else sleep(1); +#endif } // Build command for getting results @@ -446,7 +453,12 @@ BatchTest::test_jobsubmit_mpi() << "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; @@ -529,7 +541,11 @@ BatchTest::test_jobsubmit_mpi() if(status == 153 || status == 256*153 ) stop = true; +#ifdef WIN32 + Sleep(1); +#else sleep(1); +#endif } // Build command for getting results diff --git a/src/Launcher/BatchTest.hxx b/src/Launcher/BatchTest.hxx index 600b71bee..fdbe568e2 100644 --- a/src/Launcher/BatchTest.hxx +++ b/src/Launcher/BatchTest.hxx @@ -32,7 +32,18 @@ #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); diff --git a/src/Launcher/Launcher.cxx b/src/Launcher/Launcher.cxx index 7f2d491c5..13e273437 100644 --- a/src/Launcher/Launcher.cxx +++ b/src/Launcher/Launcher.cxx @@ -305,6 +305,7 @@ Batch::BatchManager_eClient *Launcher_cpp::FactoryBatchManager( const ParserReso 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()); @@ -412,6 +413,9 @@ string Launcher_cpp::buildSalomeCouplingScript(const string fileToExecute, const delete mpiImpl; return TmpFileName; +#else + return ""; +#endif } @@ -527,7 +531,7 @@ bool Launcher_cpp::check(const batchParams& batch_params) 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; } diff --git a/src/Launcher/Launcher.hxx b/src/Launcher/Launcher.hxx index 84dd59dd5..d567d3b56 100644 --- a/src/Launcher/Launcher.hxx +++ b/src/Launcher/Launcher.hxx @@ -20,6 +20,16 @@ #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" @@ -32,7 +42,7 @@ struct batchParams{ unsigned long nb_proc; }; -class LauncherException +class LAUNCHER_EXPORT LauncherException { public: const std::string msg; @@ -40,7 +50,7 @@ public: LauncherException(const std::string m) : msg(m) {} }; -class Launcher_cpp +class LAUNCHER_EXPORT Launcher_cpp { public: diff --git a/src/Launcher/SALOME_Launcher.cxx b/src/Launcher/SALOME_Launcher.cxx index 726091089..b98ca33f5 100644 --- a/src/Launcher/SALOME_Launcher.cxx +++ b/src/Launcher/SALOME_Launcher.cxx @@ -20,8 +20,10 @@ #include "SALOME_Launcher.hxx" #include "OpUtil.hxx" #include -#ifndef WNT -#include +#ifndef WIN32 +# include +#else +# include #endif #include #include "Utils_CorbaException.hxx" @@ -97,7 +99,13 @@ void SALOME_Launcher::Shutdown() //============================================================================= CORBA::Long SALOME_Launcher::getPID() { - return (CORBA::Long)getpid(); + return +#ifndef WIN32 + (CORBA::Long)getpid(); +#else + (CORBA::Long)_getpid(); +#endif + } //============================================================================= diff --git a/src/Launcher/SALOME_Launcher.hxx b/src/Launcher/SALOME_Launcher.hxx index 8ba73cdac..2455320b5 100644 --- a/src/Launcher/SALOME_Launcher.hxx +++ b/src/Launcher/SALOME_Launcher.hxx @@ -30,21 +30,7 @@ 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 { @@ -59,9 +45,9 @@ public: 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); diff --git a/src/Launcher/SALOME_LauncherServer.cxx b/src/Launcher/SALOME_LauncherServer.cxx index a79dc3f91..f0f25f91a 100644 --- a/src/Launcher/SALOME_LauncherServer.cxx +++ b/src/Launcher/SALOME_LauncherServer.cxx @@ -28,6 +28,7 @@ using namespace std; void AttachDebugger() { +#ifndef WIN32 if(getenv ("DEBUGGER")) { std::stringstream exec; @@ -36,6 +37,7 @@ void AttachDebugger() system(exec.str().c_str()); while(1); } +#endif } void terminateHandler(void) diff --git a/src/ModuleCatalog/SALOME_ModuleCatalog.hxx b/src/ModuleCatalog/SALOME_ModuleCatalog.hxx index 75d05ccb8..7f2fcf44c 100755 --- a/src/ModuleCatalog/SALOME_ModuleCatalog.hxx +++ b/src/ModuleCatalog/SALOME_ModuleCatalog.hxx @@ -26,20 +26,12 @@ #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 diff --git a/src/ResourcesManager/Makefile.am b/src/ResourcesManager/Makefile.am index b12707efa..61eb8e186 100755 --- a/src/ResourcesManager/Makefile.am +++ b/src/ResourcesManager/Makefile.am @@ -39,7 +39,8 @@ salomeinclude_HEADERS = \ SALOME_ResourcesManager.hxx \ SALOME_ResourcesCatalog_Handler.hxx \ SALOME_LoadRateManager.hxx \ - ResourcesManager.hxx + ResourcesManager.hxx \ + ResourcesManager_Defs.hxx # # =============================================================== @@ -89,9 +90,7 @@ libResourcesManager_la_SOURCES =\ 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 =\ diff --git a/src/ResourcesManager/ResourcesManager.cxx b/src/ResourcesManager/ResourcesManager.cxx index 06dc126ed..68db580fa 100644 --- a/src/ResourcesManager/ResourcesManager.cxx +++ b/src/ResourcesManager/ResourcesManager.cxx @@ -18,6 +18,7 @@ // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // #include "ResourcesManager.hxx" +#include #include #include #include @@ -27,9 +28,13 @@ #include #include -#include #include +#ifndef WIN32 +# include +#endif + + #include "utilities.h" #define MAX_SIZE_FOR_HOSTNAME 256; @@ -419,7 +424,7 @@ throw(ResourcesException) bool erasedHost = false; if( mapOfModulesOfCurrentHost.size() > 0 ){ - for(int i=0;i::const_iterator itt = find(mapOfModulesOfCurrentHost.begin(), mapOfModulesOfCurrentHost.end(), @@ -446,43 +451,3 @@ ParserResourcesType ResourcesManager_cpp::GetResourcesList(const std::string& ma 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; -} - diff --git a/src/ResourcesManager/ResourcesManager.hxx b/src/ResourcesManager/ResourcesManager.hxx index 951aba5da..bd509b77f 100644 --- a/src/ResourcesManager/ResourcesManager.hxx +++ b/src/ResourcesManager/ResourcesManager.hxx @@ -20,6 +20,8 @@ #ifndef __RESOURCESMANAGER_HXX__ #define __RESOURCESMANAGER_HXX__ +#include "ResourcesManager_Defs.hxx" + #include #include #include @@ -42,7 +44,7 @@ struct machineParams{ unsigned int mem_mb; }; -class ResourcesException +class RESOURCESMANAGER_EXPORT ResourcesException { public: const std::string msg; @@ -50,7 +52,7 @@ public: ResourcesException(const std::string m) : msg(m) {} }; -class ResourcesManager_cpp +class RESOURCESMANAGER_EXPORT ResourcesManager_cpp { public: @@ -108,9 +110,7 @@ class ResourcesManager_cpp SALOME_LoadRateManager _dynamicResourcesSelecter; //! different behaviour if $APPLI exists (SALOME Application) - bool _isAppliSalomeDefined; - - std::string GetHostname(); + bool _isAppliSalomeDefined; }; #endif // __RESOURCESMANAGER_HXX__ diff --git a/src/ResourcesManager/SALOME_LoadRateManager.hxx b/src/ResourcesManager/SALOME_LoadRateManager.hxx index 7c4c3f03d..66a5d827c 100644 --- a/src/ResourcesManager/SALOME_LoadRateManager.hxx +++ b/src/ResourcesManager/SALOME_LoadRateManager.hxx @@ -20,23 +20,10 @@ #ifndef __SALOME_LOADRATEMANAGER_HXX__ #define __SALOME_LOADRATEMANAGER_HXX__ +#include "ResourcesManager_Defs.hxx" #include #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 { diff --git a/src/ResourcesManager/SALOME_ResourcesCatalog_Handler.hxx b/src/ResourcesManager/SALOME_ResourcesCatalog_Handler.hxx index 9422c7bd1..152b5c58e 100755 --- a/src/ResourcesManager/SALOME_ResourcesCatalog_Handler.hxx +++ b/src/ResourcesManager/SALOME_ResourcesCatalog_Handler.hxx @@ -29,6 +29,9 @@ #ifndef SALOME_RESOURCES_CATALOG_HANDLER #define SALOME_RESOURCES_CATALOG_HANDLER + +#include "ResourcesManager_Defs.hxx" + #include "SALOME_ResourcesCatalog_Parser.hxx" #include @@ -36,7 +39,7 @@ #include -class SALOME_ResourcesCatalog_Handler +class RESOURCESMANAGER_EXPORT SALOME_ResourcesCatalog_Handler { public : diff --git a/src/ResourcesManager/SALOME_ResourcesCatalog_Parser.hxx b/src/ResourcesManager/SALOME_ResourcesCatalog_Parser.hxx index 901def13c..b668279e3 100755 --- a/src/ResourcesManager/SALOME_ResourcesCatalog_Parser.hxx +++ b/src/ResourcesManager/SALOME_ResourcesCatalog_Parser.hxx @@ -29,6 +29,8 @@ #ifndef SALOME_RESOURCES_CATALOG_PARSER #define SALOME_RESOURCES_CATALOG_PARSER +#include "ResourcesManager_Defs.hxx" + #include #include #include @@ -42,7 +44,7 @@ enum BatchType {none, pbs, lsf}; enum MpiImplType {indif, lam, mpich1, mpich2, openmpi, slurm}; -class ResourceDataToSort +class RESOURCESMANAGER_EXPORT ResourceDataToSort { public: @@ -70,7 +72,7 @@ class ResourceDataToSort unsigned int GetNumberOfPoints() const; }; -struct ParserResourcesType +struct RESOURCESMANAGER_EXPORT ParserResourcesType { ResourceDataToSort DataForSort; std::string HostName; diff --git a/src/ResourcesManager/SALOME_ResourcesManager.cxx b/src/ResourcesManager/SALOME_ResourcesManager.cxx index 90f273d69..52276bd87 100644 --- a/src/ResourcesManager/SALOME_ResourcesManager.cxx +++ b/src/ResourcesManager/SALOME_ResourcesManager.cxx @@ -153,14 +153,14 @@ SALOME_ResourcesManager::GetFittingResources(const Engines::MachineParameters& p p.mem_mb = params.mem_mb; vector cl; - for(int i=0;i vec = _rm.GetFittingResources(p,cl); ret->length(vec.size()); - for(int i=0;i ml; - for(int i=0;iusername = 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;imodList[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; diff --git a/src/ResourcesManager/SALOME_ResourcesManager.hxx b/src/ResourcesManager/SALOME_ResourcesManager.hxx index dceb9db67..bec75471c 100644 --- a/src/ResourcesManager/SALOME_ResourcesManager.hxx +++ b/src/ResourcesManager/SALOME_ResourcesManager.hxx @@ -34,13 +34,13 @@ #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 --- @@ -49,7 +49,7 @@ // 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 { diff --git a/src/SALOMELocalTrace/utilities.h b/src/SALOMELocalTrace/utilities.h index 8aced915f..add94a466 100644 --- a/src/SALOMELocalTrace/utilities.h +++ b/src/SALOMELocalTrace/utilities.h @@ -65,7 +65,8 @@ #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 < 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 diff --git a/src/Utils/OpUtil.hxx b/src/Utils/OpUtil.hxx index f462726a4..f8a5f1ab5 100644 --- a/src/Utils/OpUtil.hxx +++ b/src/Utils/OpUtil.hxx @@ -49,6 +49,10 @@ public: // /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 ); -- 2.39.2