File: CommandBuilder.py

package info (click to toggle)
mobyle 1.5.5%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 8,288 kB
  • sloc: python: 22,709; makefile: 35; sh: 33; ansic: 10; xml: 6
file content (280 lines) | stat: -rw-r--r-- 12,887 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
########################################################################################
#                                                                                      #
#   Author: Bertrand Neron,                                                            #
#   Organization:'Biological Software and Databases' Group, Institut Pasteur, Paris.   #  
#   Distributed under GPLv2 Licence. Please refer to the COPYING.LIB document.        #
#                                                                                      #
########################################################################################

""" 
Build the command from the parameters chosen by the users
"""

import os
from StringIO import StringIO

from Mobyle.MobyleError import MobyleError
from logging import getLogger
c_log = getLogger(__name__)
b_log = getLogger( 'Mobyle.builder' )
from Mobyle.ConfigManager import Config
_cfg = Config()

__extra_epydoc_fields__ = [( 'call', 'Called by','Called by' )]





class CommandBuilder:
    """
    This class create the command from the parameters chosen by the users
    3 main methods exist
      - buildLocalCommand: to build a unix command line for a local job
      - buildCGI : to build the url, to invoke a cgi
      - buildWS : to build the ,to call a WebService
     """

    def __init__( self , job_dir = None ):
        self._commandLine = "" 
        self._paramfileHandles = {} # the key is the filename,
                                    # the value is the StrinIO file object like
        
    def buildLocalCommand( self, service ):
        """
        Build a unix command line from a - L{Service} instance
        @param service: the service  which correspond to the programm asked by the user
        @type service: a - L{Service} instance
        @return: a String representing the command line
        """
        debug = _cfg.debug( service.getName() )
        commandIsInserted = False
        commandParameterName = service.getCommandParameterName()
        if commandParameterName:
            commandPos = service.getArgpos( commandParameterName )
        else:
            commandPos = 0

        if debug > 1:
            b_log.debug( """\n
            \t#####################################################
            \t#                                                   # 
            \t#               command line building               #
            \t#                                                   #
            \t#####################################################
            \n""" )
            
        myEvaluator = service.getEvaluator()
            
        for parameter in service.getAllParameterByArgpos():
            paramName = parameter.getName()
            if debug > 1:
                b_log.debug( "--------------- " + paramName + " ---------------")
                b_log.debug( "commandIsInserted " + str( commandIsInserted ) )
                b_log.debug( "service.getArgpos( paramName ) " + str( parameter.getArgpos()))
            if not commandIsInserted and parameter.getArgpos() >= commandPos:
                if parameter.iscommand():
                    #the command from parameter is priority vs command
                    #the command comes from this parameter
                    if debug > 1 :
                        b_log.debug( "self._commandLine service.iscommand " + self._commandLine )                            
                    commandIsInserted = True
                else:
                    #I insert the command from command tag in commandLine
                    if debug > 1:
                        b_log.debug( "self._commandLine = " + self._commandLine )

                    self._commandLine += " " + service.getCommand()[0]
                    commandIsInserted = True
                    if debug > 1:
                        b_log.debug( "self._commandLine+ command = " + self._commandLine )
                    
            #set "vdef" and "value" in the protected namespace (evaluator) 
            rawVdef = parameter.getVdef()
            
            if rawVdef is None:
                myEvaluator.setVar( 'vdef' , None )
                convertedVdef = None #TODO a suprimmer qund b_log renove
            else:
                convertedVdef , mt = parameter.convert(rawVdef , parameter.getType() )
                myEvaluator.setVar( 'vdef' , convertedVdef )
                                    
            if debug > 1:
                b_log.debug( "rawVdef = " + str( rawVdef ) )
                b_log.debug( "convertedVdef = " + str( convertedVdef ) )
                b_log.debug( "myEvaluator.setVar( 'vdef' , "+ str( convertedVdef ) +" )")

            if ( myEvaluator.isDefined( paramName ) ) :
                # be careful we can't use the test: if servive.getValue(),
                # because, the value could be fill with False.
                # thus we must test if the value exist or not, and not test the value itself!
                myEvaluator.setVar( 'value', parameter.getValue( ) )
                if debug > 1:
                    b_log.debug( "myEvaluator.isDefined( " + paramName + " ) = True" )
                    b_log.debug( "myEvaluator.setVar( 'value' ,"+ str( parameter.getValue() ) + " )" )
            else:
                myEvaluator.setVar( 'value' , convertedVdef )
                
                if debug > 1:
                    b_log.debug( "myEvaluator.isDefined( " + paramName + " ) = False" )
                    b_log.debug( "rawVdef = " + str( rawVdef ) )
                    b_log.debug( "convertedVdef = " + str( convertedVdef ) ) 
                    b_log.debug( "myEvaluator.setVar( 'value' , " + str( convertedVdef ) + " )" ) 

            if parameter.precondHas_proglang( 'python' ):
                if debug > 1:
                    b_log.debug("precondHas_proglang( "+ paramName +" , 'python' ) = True")
                allPrecondTrue = True
                preconds = parameter.getPreconds( proglang='python' )
                
                for precond in preconds:
                    if not  myEvaluator.eval( precond ):
                        if debug > 1:
                            b_log.debug("eval( "+ precond  +" ) = False")
                        
                        allPrecondTrue = False
                        break
                    else:
                        if debug > 1:
                            b_log.debug("eval( "+ precond  +" ) = True")
                if not allPrecondTrue :
                    continue #next parameter
                
            if parameter.formatHas_proglang( 'python' ):
                if debug > 1:
                    b_log.debug("service.formatHas_proglang( "+ paramName +" , 'python' ) = True")
                format =  parameter.getFormat( 'python' )

            else:
                value = myEvaluator.getVar( 'value' )
                if value is not None :
                    if parameter.flistHas_proglang( value , 'python' ) :

                        if debug > 1:
                            b_log.debug("service.flistHas_proglang( "+ paramName +" , "+ str( value ) + " , 'python' ) = True")

                        format = parameter.getFlistCode( value , 'python' )
                    else:
                        format = None
                else:
                    format = None

            if debug > 1:
                b_log.debug( "value = " + str( myEvaluator.getVar( 'value' )) + "  type = "+ str(type( myEvaluator.getVar( 'value' ) ) ) )
                b_log.debug( "vdef = " + str( myEvaluator.getVar( 'vdef' )) + "  type = "+ str(type( myEvaluator.getVar( 'value' ) ) )   )
                b_log.debug(" format = " + str( format ) )
                
            if format :
                if parameter.hasParamfile():
                    #the Parameter.setParamfile method had already trim the spaces
                    paramfileName = parameter.getParamfile()
                    if paramfileName:
                        if self._paramfileHandles.has_key( paramfileName ):
                            paramfileHandle = self._paramfileHandles[ paramfileName ]
                        else:
                            try:
                                paramfileHandle = self.openParamFile( paramfileName )
                                self._paramfileHandles[paramfileName] = paramfileHandle
                            except IOError:
                                raise MobyleError, "cannot open the file: "+str( paramfileName )
                else :
                    paramfileHandle = None
            else:
                if  myEvaluator.getVar( 'value' ) is not None:
                    if parameter.formatHas_proglang( 'perl' ) or  parameter.flistHas_proglang( parameter.getValue() , 'perl' ) :
                        if debug > 1:
                            b_log.debug( "#################### WARNING ##############################################" )
                            b_log.debug( "the parameter " + paramName + " had a format code in Perl but not in Python" )
                            b_log.debug( "###########################################################################" )
                continue
                
            try:
                arg = myEvaluator.eval( format )
            except Exception, err:
                msg = "Error during evaluation of \"%s.%s\" format parameter: %s : \"%s\"" % (
                    service.getName(),
                    paramName ,
                    format,
                    err
                    )
                if debug > 1:
                    b_log.debug( msg )
                raise MobyleError , msg
                
            if paramfileHandle:
                if debug > 1:
                    b_log.debug( ">> " + paramfileName + " , " + arg )
                if arg :
                    paramfileHandle.write( arg )
                    paramfileHandle.flush()
            else:
                self._commandLine = str( self._commandLine ) + str( arg )
                if debug > 1:
                    b_log.debug( "commandLine = " + self._commandLine )
        if debug > 1:
            b_log.debug( "------------ end of parameter loop  -------------" )        
       
#===============================================================================
#            
#        the environment is modified here ( it will be just before to do run in _batch ) to avoid 
#        dramatic side effects on well of mobyle.
#        we usr the environment to find the right python everywhere in mobyle and if we modified the path
#        we could change the python used.
#                 
#===============================================================================
        xmlEnv = {}
        
        if commandParameterName : #the command come from a parameter
            path  = service.getEnv( 'PATH' )            
        else:#the command come from the element command in head
            path = service.getCommand()[2]
            path_env = service.getEnv( 'PATH' )
            if path and path_env:
                path = "%s:%s" % ( path, path_env )
            elif path_env:
                path = path_env
        if path :
            #os.environ['PATH'] = "%s:%s" %( path , os.environ['PATH'])
            xmlEnv[ 'PATH' ] = path
            if debug > 1:
                b_log.debug( "PATH= " + str( path  ) )            
        else:
            if debug > 1 :
                b_log.debug( "PATH= "+ str( os.environ[ 'PATH' ] ) )
        for varEnv in service.envVars():
            envArg = service.getEnv( varEnv ).strip()
            if varEnv == 'PATH':
                continue
            else:
                xmlEnv[ varEnv ] = envArg
        
        for var, value in xmlEnv.items():
            if value.startswith('()'):
                msg = 'Bash vulnerabilty Exploitation: service unsafe check env %s'% var
                c_log.critical("Security Error: %s : %s" % (service.getName(), msg))
                raise MobyleError, msg              
        #trim multi espaces , ...
        self._commandLine = ' '.join( self._commandLine.split() )
        self._commandLine.strip()
        self._commandLine.replace( '"','\\"' )
        self._commandLine.replace( '@','\@' )
        self._commandLine.replace( '_SQ_',"\'" )
        self._commandLine.replace( '_DQ_','\"' )


        if debug > 1:
            b_log.debug( "Environment ="+str( xmlEnv ) )
            b_log.debug( "command line= " + self._commandLine )
        return { 'cmd' : self._commandLine , 
                 'env'  : xmlEnv ,
                 'paramfiles': self._paramfileHandles
                }
        

    def __str__( self ):
        return str( self._commandLine )

    def openParamFile(self , paramfileName ):
        return StringIO()