source: trunk/gui/scripts/tool.tcl @ 1642

Last change on this file since 1642 was 1625, checked in by gah, 15 years ago
File size: 11.1 KB
RevLine 
[11]1# ----------------------------------------------------------------------
2#  COMPONENT: tool - represents an entire tool
3#
4#  This object represents an entire tool defined by Rappture.
5#  Each tool resides in an installation directory with other tool
6#  resources (libraries, examples, etc.).  Each tool is defined by
7#  its inputs and outputs, which are tied to various widgets in the
8#  GUI.  Each tool tracks the inputs, knows when they're changed,
9#  and knows how to run itself to produce new results.
10# ======================================================================
11#  AUTHOR:  Michael McLennan, Purdue University
[115]12#  Copyright (c) 2004-2005  Purdue Research Foundation
13#
14#  See the file "license.terms" for information on usage and
15#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
[11]16# ======================================================================
17package require BLT
18
19itcl::class Rappture::Tool {
[22]20    inherit Rappture::ControlOwner
[11]21
[22]22    constructor {xmlobj installdir args} {
[1342]23        Rappture::ControlOwner::constructor ""
[22]24    } { # defined below }
[11]25
26    public method installdir {} { return $_installdir }
27
28    public method run {args}
29    public method abort {}
30
[1003]31    protected method _mkdir {dir}
[23]32    protected method _output {data}
33
[11]34    private variable _installdir ""  ;# installation directory for this tool
[23]35    private variable _outputcb ""    ;# callback for tool output
[11]36    private common job               ;# array var used for blt::bgexec jobs
[158]37    private common jobnum 0          ;# counter for unique job number
[413]38
[724]39    # get global resources for this tool session
40    public proc resources {{option ""}}
41
42    public common _resources
[903]43    public proc setAppName {name}   { set _resources(-appname) $name }
44    public proc setHubName {name}   { set _resources(-hubname) $name }
45    public proc setHubURL {name}    { set _resources(-huburl) $name }
46    public proc setSession {name}   { set _resources(-session) $name }
47    public proc setJobPrt {name}    { set _resources(-jobprotocol) $name }
48    public proc setResultDir {name} { set _resources(-resultdir) $name }
[11]49}
[413]50
51# must use this name -- plugs into Rappture::resources::load
52proc tool_init_resources {} {
53    Rappture::resources::register \
[1342]54        application_name  Rappture::Tool::setAppName \
55        application_id    Rappture::Tool::setAppId \
56        hub_name          Rappture::Tool::setHubName \
57        hub_url           Rappture::Tool::setHubURL \
58        session_token     Rappture::Tool::setSession \
59        job_protocol      Rappture::Tool::setJobPrt \
60        results_directory Rappture::Tool::setResultDir
[413]61}
[1342]62                                                                               
[11]63# ----------------------------------------------------------------------
64# CONSTRUCTOR
65# ----------------------------------------------------------------------
66itcl::body Rappture::Tool::constructor {xmlobj installdir args} {
67    if {![Rappture::library isvalid $xmlobj]} {
[1342]68        error "bad value \"$xmlobj\": should be Rappture::Library"
[11]69    }
70    set _xmlobj $xmlobj
71
72    if {![file exists $installdir]} {
[1342]73        error "directory \"$installdir\" doesn't exist"
[11]74    }
75    set _installdir $installdir
76
77    eval configure $args
78}
79
80# ----------------------------------------------------------------------
[724]81# USAGE: resources ?-option?
[640]82#
83# Clients use this to query information about the tool.
84# ----------------------------------------------------------------------
[724]85itcl::body Rappture::Tool::resources {{option ""}} {
[640]86    if {$option == ""} {
[1342]87        return [array get _resources]
[640]88    }
[731]89    if {[info exists _resources($option)]} {
[1342]90        return $_resources($option)
[640]91    }
[731]92    return ""
[640]93}
94
95# ----------------------------------------------------------------------
[23]96# USAGE: run ?<path1> <value1> <path2> <value2> ...? ?-output <callbk>?
[11]97#
98# This method causes the tool to run.  All widgets are synchronized
99# to the current XML representation, and a "driver.xml" file is
100# created as the input for the run.  That file is fed to the tool
101# according to the <tool><command> string, and the job is executed.
102#
[23]103# Any "<path> <value>" arguments are used to override the current
104# settings from the GUI.  This is useful, for example, when filling
105# in missing simulation results from the analyzer.
106#
107# If the -output argument is included, then the next arg is a
108# callback command for output messages.  Any output that comes in
109# while the tool is running is sent back to the caller, so the user
110# can see progress running the tool.
111#
[11]112# Returns a list of the form {status result}, where status is an
113# integer status code (0=success) and result is the output from the
114# simulator.  Successful output is something like {0 run1293921.xml},
115# where 0=success and run1293921.xml is the name of the file containing
116# results.
117# ----------------------------------------------------------------------
118itcl::body Rappture::Tool::run {args} {
119    global errorInfo
120
[674]121    #
122    # Make sure that we save the proper application name.
123    # Actually, the best place to get this information is
124    # straight from the "installtool" script, but just in
125    # case we have an older tool, we should insert the
126    # tool name from the resources config file.
127    #
[726]128    if {[info exists _resources(-appname)]
[1342]129          && "" != $_resources(-appname)
130          && "" == [$_xmlobj get tool.name]} {
131        $_xmlobj put tool.name $_resources(-appname)
[413]132    }
133
[11]134    # sync all widgets to the XML tree
135    sync
136
137    # if there are any args, use them to override parameters
[23]138    set _outputcb ""
[11]139    foreach {path val} $args {
[1342]140        if {$path == "-output"} {
141            set _outputcb $val
142        } else {
143            $_xmlobj put $path.current $val
144        }
[11]145    }
146
147    foreach item {control output error} { set job($item) "" }
148
149    # write out the driver.xml file for the tool
150    set file "driver[pid].xml"
151    set status [catch {
[1342]152        set fid [open $file w]
153        puts $fid "<?xml version=\"1.0\"?>"
154        puts $fid [$_xmlobj xml]
155        close $fid
[11]156    } result]
157
[1286]158    # set limits for cpu time
[158]159    set limit [$_xmlobj get tool.limits.cputime]
160    if {"" == $limit || [catch {Rappture::rlimit set cputime $limit}]} {
[1342]161        Rappture::rlimit set cputime 900  ;# 15 mins by default
[158]162    }
163
[11]164    # execute the tool using the path from the tool description
165    if {$status == 0} {
[1342]166        set cmd [$_xmlobj get tool.command]
167        regsub -all @tool $cmd $_installdir cmd
168        regsub -all @driver $cmd $file cmd
169        regsub -all {\\} $cmd {\\\\} cmd
170        set cmd [string trimleft $cmd " "]
[11]171
[1342]172        # if job_protocol is "submit", then use use submit command
173        if {[resources -jobprotocol] == "submit"} {
174            set cmd [linsert $cmd 0 submit --local]
175        }
[731]176
[1342]177        # starting job...
178        Rappture::rusage mark
[158]179
[1342]180        if {0 == [string compare -nocase -length 5 $cmd "ECHO "] } {
181            set status 0;
182            set job(output) [string range $cmd 5 end]
183        } else {
184            set status [catch {eval blt::bgexec \
185                ::Rappture::Tool::job(control) \
186                -keepnewline yes \
187                -killsignal SIGTERM \
188                -onoutput [list [itcl::code $this _output]] \
189                -output ::Rappture::Tool::job(output) \
190                -error ::Rappture::Tool::job(error) $cmd} result]
191        }
192        # ...job is finished
193        array set times [Rappture::rusage measure]
[158]194
[1342]195        if {[resources -jobprotocol] != "submit"} {
[1625]196            set id [$_xmlobj get tool.id]
197            set vers [$_xmlobj get tool.version.application.revision]
198            set simulation simulation
199            if { $id != "" && $vers != "" } {
200                set simulation ${id}_r${vers}
201            }
202            puts stderr "MiddlewareTime: job=[incr jobnum] event=$simulation start=$times(start) walltime=$times(walltime) cputime=$times(cputime) status=$status"
[637]203
[1342]204            #
205            # Scan through stderr channel and look for statements that
206            # represent grid jobs that were executed.  The statements
207            # look like this:
208            #
209            # MiddlewareTime: job=1 event=simulation start=3.001094 ...
210            #
211            set subjobs 0
212            while {[regexp -indices {(^|\n)MiddlewareTime:( +[a-z]+=[^ \n]+)+(\n|$)} $job(error) match]} {
213                foreach {p0 p1} $match break
214                if {[string index $job(error) $p0] == "\n"} { incr p0 }
[637]215
[1342]216                catch {unset data}
217                array set data {
218                    job 1
219                    event simulation
220                    start 0
221                    walltime 0
222                    cputime 0
223                    status 0
224                }
225                foreach arg [lrange [string range $job(error) $p0 $p1] 1 end] {
226                    foreach {key val} [split $arg =] break
227                    set data($key) $val
228                }
229                set data(job) [expr {$jobnum+$data(job)}]
230                set data(event) "subsimulation"
231                set data(start) [expr {$times(start)+$data(start)}]
[734]232
[1342]233                set stmt "MiddlewareTime:"
234                foreach key {job event start walltime cputime status} {
235                    # add required keys in a particular order
236                    append stmt " $key=$data($key)"
237                    unset data($key)
238                }
239                foreach key [array names data] {
240                    # add anything else that the client gave -- venue, etc.
241                    append stmt " $key=$data($key)"
242                }
243                puts stderr $stmt
244                incr subjobs
[734]245
[1342]246                # done -- remove this statement
247                set job(error) [string replace $job(error) $p0 $p1]
248            }
249            incr jobnum $subjobs
250        }
[637]251
[11]252    } else {
[1342]253        set job(error) "$result\n$errorInfo"
[11]254    }
255    if {$status == 0} {
[1342]256        file delete -force -- $file
[11]257    }
258
259    # see if the job was aborted
260    if {[regexp {^KILLED} $job(control)]} {
[1342]261        return [list 0 "ABORT"]
[11]262    }
263
264    #
265    # If successful, return the output, which should include
266    # a reference to the run.xml file containing results.
267    #
268    if {$status == 0} {
[1342]269        set result [string trim $job(output)]
270        if {[regexp {=RAPPTURE-RUN=>([^\n]+)} $result match file]} {
271            set status [catch {Rappture::library $file} result]
272            if {$status != 0} {
273                global errorInfo
274                set result "$result\n$errorInfo"
275            }
[903]276
[1342]277            # if there's a results_directory defined in the resources
278            # file, then move the run.xml file there for storage
279            if {[info exists _resources(-resultdir)]
280                  && "" != $_resources(-resultdir)} {
281                catch {
282                    if {![file exists $_resources(-resultdir)]} {
283                        _mkdir $_resources(-resultdir)
284                    }
285                    file rename -force -- $file $_resources(-resultdir)
286                }
287            }
288        } else {
289            set status 1
290            set result "Can't find result file in output.\nDid you call Rappture
[903]291::result in your simulator?"
[1342]292        }
293        return [list $status $result]
[11]294    } elseif {"" != $job(output) || "" != $job(error)} {
[1342]295        return [list $status [string trim "$job(output)\n$job(error)"]]
[11]296    }
297    return [list $status $result]
298}
299
300# ----------------------------------------------------------------------
[1003]301# USAGE: _mkdir <directory>
302#
303# Used internally to create the <directory> in the file system.
304# The parent directory is also created, as needed.
305# ----------------------------------------------------------------------
306itcl::body Rappture::Tool::_mkdir {dir} {
307    set parent [file dirname $dir]
308    if {"." != $parent && "/" != $parent} {
[1342]309        if {![file exists $parent]} {
310            _mkdir $parent
311        }
[1003]312    }
313    file mkdir $dir
314}
315
316
317# ----------------------------------------------------------------------
[11]318# USAGE: abort
319#
320# Clients use this during a "run" to abort the current job.
321# Kills the job and forces the "run" method to return.
322# ----------------------------------------------------------------------
323itcl::body Rappture::Tool::abort {} {
324    set job(control) "abort"
325}
[23]326
327# ----------------------------------------------------------------------
328# USAGE: _output <data>
329#
330# Used internally to send each bit of output <data> coming from the
331# tool onto the caller, so the user can see progress.
332# ----------------------------------------------------------------------
333itcl::body Rappture::Tool::_output {data} {
334    if {[string length $_outputcb] > 0} {
[1342]335        uplevel #0 [list $_outputcb $data]
[23]336    }
337}
Note: See TracBrowser for help on using the repository browser.