source: branches/blt4/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
Line 
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
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.
16# ======================================================================
17package require BLT
18
19itcl::class Rappture::Tool {
20    inherit Rappture::ControlOwner
21
22    constructor {xmlobj installdir args} {
23        Rappture::ControlOwner::constructor ""
24    } { # defined below }
25
26    public method installdir {} { return $_installdir }
27
28    public method run {args}
29    public method abort {}
30
31    protected method _mkdir {dir}
32    protected method _output {data}
33
34    private variable _installdir ""  ;# installation directory for this tool
35    private variable _outputcb ""    ;# callback for tool output
36    private common job               ;# array var used for blt::bgexec jobs
37    private common jobnum 0          ;# counter for unique job number
38
39    # get global resources for this tool session
40    public proc resources {{option ""}}
41
42    public common _resources
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 }
49}
50
51# must use this name -- plugs into Rappture::resources::load
52proc tool_init_resources {} {
53    Rappture::resources::register \
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
61}
62                                                                               
63# ----------------------------------------------------------------------
64# CONSTRUCTOR
65# ----------------------------------------------------------------------
66itcl::body Rappture::Tool::constructor {xmlobj installdir args} {
67    if {![Rappture::library isvalid $xmlobj]} {
68        error "bad value \"$xmlobj\": should be Rappture::Library"
69    }
70    set _xmlobj $xmlobj
71
72    if {![file exists $installdir]} {
73        error "directory \"$installdir\" doesn't exist"
74    }
75    set _installdir $installdir
76
77    eval configure $args
78}
79
80# ----------------------------------------------------------------------
81# USAGE: resources ?-option?
82#
83# Clients use this to query information about the tool.
84# ----------------------------------------------------------------------
85itcl::body Rappture::Tool::resources {{option ""}} {
86    if {$option == ""} {
87        return [array get _resources]
88    }
89    if {[info exists _resources($option)]} {
90        return $_resources($option)
91    }
92    return ""
93}
94
95# ----------------------------------------------------------------------
96# USAGE: run ?<path1> <value1> <path2> <value2> ...? ?-output <callbk>?
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#
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#
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
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    #
128    if {[info exists _resources(-appname)]
129          && "" != $_resources(-appname)
130          && "" == [$_xmlobj get tool.name]} {
131        $_xmlobj put tool.name $_resources(-appname)
132    }
133
134    # sync all widgets to the XML tree
135    sync
136
137    # if there are any args, use them to override parameters
138    set _outputcb ""
139    foreach {path val} $args {
140        if {$path == "-output"} {
141            set _outputcb $val
142        } else {
143            $_xmlobj put $path.current $val
144        }
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 {
152        set fid [open $file w]
153        puts $fid "<?xml version=\"1.0\"?>"
154        puts $fid [$_xmlobj xml]
155        close $fid
156    } result]
157
158    # set limits for cpu time
159    set limit [$_xmlobj get tool.limits.cputime]
160    if {"" == $limit || [catch {Rappture::rlimit set cputime $limit}]} {
161        Rappture::rlimit set cputime 900  ;# 15 mins by default
162    }
163
164    # execute the tool using the path from the tool description
165    if {$status == 0} {
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 " "]
171
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        }
176
177        # starting job...
178        Rappture::rusage mark
179
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]
194
195        if {[resources -jobprotocol] != "submit"} {
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"
203
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 }
215
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)}]
232
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
245
246                # done -- remove this statement
247                set job(error) [string replace $job(error) $p0 $p1]
248            }
249            incr jobnum $subjobs
250        }
251
252    } else {
253        set job(error) "$result\n$errorInfo"
254    }
255    if {$status == 0} {
256        file delete -force -- $file
257    }
258
259    # see if the job was aborted
260    if {[regexp {^KILLED} $job(control)]} {
261        return [list 0 "ABORT"]
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} {
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            }
276
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
291::result in your simulator?"
292        }
293        return [list $status $result]
294    } elseif {"" != $job(output) || "" != $job(error)} {
295        return [list $status [string trim "$job(output)\n$job(error)"]]
296    }
297    return [list $status $result]
298}
299
300# ----------------------------------------------------------------------
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} {
309        if {![file exists $parent]} {
310            _mkdir $parent
311        }
312    }
313    file mkdir $dir
314}
315
316
317# ----------------------------------------------------------------------
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}
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} {
335        uplevel #0 [list $_outputcb $data]
336    }
337}
Note: See TracBrowser for help on using the repository browser.