Salome HOME
Improve SALOME logger: customize log file name (add port, user and host ids) to avoid...
[modules/kernel.git] / bin / salome_utilities.py
1 # Copyright (C) 2005  OPEN CASCADE, CEA, EDF R&D, LEG
2 #           PRINCIPIA R&D, EADS CCR, Lip6, BV, CEDRAT
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either 
6 # version 2.1 of the License.
7
8 # This library is distributed in the hope that it will be useful 
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of 
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
11 # Lesser General Public License for more details.
12
13 # You should have received a copy of the GNU Lesser General Public  
14 # License along with this library; if not, write to the Free Software 
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18
19 # ---
20 #
21 # File   : salome_utilities.py
22 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
23 #
24 # ---
25
26 """
27 Set of utility functions used by SALOME python scripts.
28 """
29
30 #
31 # Exported functions
32 #
33 __all__ = [
34     'getUserName',
35     'getHostName',
36     'getAppName',
37     'getPortNumber',
38     'generateFileName'
39     ]
40
41 # ---
42
43 def _try_bool( arg ):
44     """
45     Check if specified parameter represents boolean value and returns its value.
46     String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
47     are supported.
48     If <arg> does not represent a boolean, an exception is raised.
49     """
50     import types
51     if type( arg ) == types.BooleanType  :
52         return arg
53     elif type( arg ) == types.StringType  :
54         v = str( arg ).lower()
55         if   v in [ "yes", "y", "true"  ]: return True
56         elif v in [ "no",  "n", "false" ]: return False
57         pass
58     raise "Not boolean value"
59
60 # ---
61
62 def getUserName():
63     """
64     Get user name:
65     1. try USER environment variable
66     2. if fails, return 'unknown' as default user name
67     """
68     import os
69     return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
70
71 # ---
72
73 def getHostName():
74     """
75     Get host name:
76     1. try socket python module gethostname() function
77     2. if fails, try HOSTNAME environment variable
78     3. if fails, try HOST environment variable
79     4. if fails, return 'unknown' as default host name
80     """
81     import os
82     try:
83         import socket
84         host = socket.gethostname().split('.')[0]
85     except:
86         host = None
87     if not host: host = os.getenv("HOSTNAME")
88     if not host: host = os.getenv("HOST")
89     if not host: host = "unknown"           # 'unknown' is default host name
90     return host
91
92 # ---
93
94 def getAppName():
95     """
96     Get application name:
97     1. try APPNAME environment variable
98     2. if fails, return 'SALOME' as default application name
99     """
100     import os
101     return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
102
103 # ---
104
105 def getPortNumber():
106     """
107     Get current naming server port number:
108     1. try NSPORT environment variable
109     1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
110     2. if fails, return 2809 as default port number
111     """
112     import os, re
113     try:
114         return int( os.getenv( "NSPORT" ) )
115     except:
116         pass
117     try:
118         f = open( os.getenv( "OMNIORB_CONFIG" ) )
119         lines = f.readlines()
120         f.close()
121         regvar = re.compile( "(ORB)?InitRef.*:(\d+)\s*$" )
122         for l in lines:
123             try:
124                 return regvar.match( l ).group( 2 )
125             except:
126                 pass
127             pass
128         pass
129     except:
130         pass
131     return 2809      # '2809' is default port number
132
133 # ---
134
135 def generateFileName( dir, prefix, suffix = None, extension = None,
136                       unique = False, separator = "_", **kwargs ):
137     """
138     Generate unique file name.
139
140     The following parameters are supported:
141     <dir> - directory for the tmp file
142     <prefix> - file prefix
143     <suffix> - file suffix (not added by default)
144     <extension> - file extension (not added by default)
145     <separator> - separator of the words ('_' by default)
146     <with_username> 'add user name' flag/option:
147     - boolean value can be passed to determine user name automatically
148     - string value to be used as user name
149     <with_hostname> 'add host name' flag/option:
150     - boolean value can be passed to determine host name automatically
151     - string value to be used as host name
152     <with_port> 'add port number' flag/option:
153     - boolean value can be passed to determine port number automatically
154     - string value to be used as port number
155     <with_app> 'add application name' flag/option:
156     - boolean value can be passed to determine application name automatically
157     - string value to be used as application name
158     All <with_...> parameters are optional.
159     <unique> If this parameter is True the unique file name is generated:
160     in this case, if the file with the generated name already exists
161     in the <dir> directory, an integer suffix is added to the end of
162     file name. This parameter is False by default.
163     """
164     supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
165     from launchConfigureParser import verbose
166     filename = []
167     # separator
168     if separator is None:
169         separator = ""
170         pass
171     else:
172         separator = str( separator )
173         pass
174     # prefix (if specified)
175     if prefix:
176         filename.append( str( prefix ) )
177         pass
178     # additional keywords
179     ### check unsupported parameters
180     for kw in kwargs:
181         if kw not in supported and verbose():
182             print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
183             pass
184         pass
185     ### process supported keywords
186     for kw in supported:
187         if kw not in kwargs: continue
188         ### user name
189         if kw == 'with_username':
190             try:
191                 # auto user name ?
192                 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
193                 pass
194             except:
195                 # user name given as parameter
196                 filename.append( kwargs[kw] )
197                 pass
198             pass
199         ### host name
200         elif kw == 'with_hostname':
201             try:
202                 # auto host name ?
203                 if _try_bool( kwargs[kw] ): filename.append( getHostName() )
204                 pass
205             except:
206                 # host name given as parameter
207                 filename.append( kwargs[kw] )
208                 pass
209             pass
210         ### port number
211         elif kw == 'with_port':
212             try:
213                 # auto port number ?
214                 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
215                 pass
216             except:
217                 # port number given as parameter
218                 filename.append( str( kwargs[kw] ) )
219                 pass
220             pass
221         ### application name
222         elif kw == 'with_app':
223             try:
224                 # auto application name ?
225                 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
226                 pass
227             except:
228                 # application name given as parameter
229                 filename.append( kwargs[kw] )
230                 pass
231             pass
232         pass
233     # suffix (if specified)
234     if suffix:
235         filename.append( str( suffix ) )
236         pass
237     # raise an exception if file name is empty
238     if not filename:
239         raise "Empty file name"
240     # create unique file name
241     import os
242     name = os.path.join( dir, separator.join( filename ) )
243     if extension: name += str( extension )
244     if unique:
245         index = 0
246         while os.path.exists( name ):
247             index = index + 1
248             name = os.path.join( dir, separator.join( filename ) + separator + str( index ) )
249             if extension: name += str( extension )
250             pass
251         pass
252     return name