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

Last change on this file since 1342 was 1342, checked in by gah, 16 years ago

preliminary HQ output from molvisviewer; unexpand tabs; all jpeg generation at 100%

File size: 10.9 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            puts stderr "MiddlewareTime: job=[incr jobnum] event=simulation start=$times(start) walltime=$times(walltime) cputime=$times(cputime) status=$status"
197
198            #
199            # Scan through stderr channel and look for statements that
200            # represent grid jobs that were executed.  The statements
201            # look like this:
202            #
203            # MiddlewareTime: job=1 event=simulation start=3.001094 ...
204            #
205            set subjobs 0
206            while {[regexp -indices {(^|\n)MiddlewareTime:( +[a-z]+=[^ \n]+)+(\n|$)} $job(error) match]} {
207                foreach {p0 p1} $match break
208                if {[string index $job(error) $p0] == "\n"} { incr p0 }
209
210                catch {unset data}
211                array set data {
212                    job 1
213                    event simulation
214                    start 0
215                    walltime 0
216                    cputime 0
217                    status 0
218                }
219                foreach arg [lrange [string range $job(error) $p0 $p1] 1 end] {
220                    foreach {key val} [split $arg =] break
221                    set data($key) $val
222                }
223                set data(job) [expr {$jobnum+$data(job)}]
224                set data(event) "subsimulation"
225                set data(start) [expr {$times(start)+$data(start)}]
226
227                set stmt "MiddlewareTime:"
228                foreach key {job event start walltime cputime status} {
229                    # add required keys in a particular order
230                    append stmt " $key=$data($key)"
231                    unset data($key)
232                }
233                foreach key [array names data] {
234                    # add anything else that the client gave -- venue, etc.
235                    append stmt " $key=$data($key)"
236                }
237                puts stderr $stmt
238                incr subjobs
239
240                # done -- remove this statement
241                set job(error) [string replace $job(error) $p0 $p1]
242            }
243            incr jobnum $subjobs
244        }
245
246    } else {
247        set job(error) "$result\n$errorInfo"
248    }
249    if {$status == 0} {
250        file delete -force -- $file
251    }
252
253    # see if the job was aborted
254    if {[regexp {^KILLED} $job(control)]} {
255        return [list 0 "ABORT"]
256    }
257
258    #
259    # If successful, return the output, which should include
260    # a reference to the run.xml file containing results.
261    #
262    if {$status == 0} {
263        set result [string trim $job(output)]
264        if {[regexp {=RAPPTURE-RUN=>([^\n]+)} $result match file]} {
265            set status [catch {Rappture::library $file} result]
266            if {$status != 0} {
267                global errorInfo
268                set result "$result\n$errorInfo"
269            }
270
271            # if there's a results_directory defined in the resources
272            # file, then move the run.xml file there for storage
273            if {[info exists _resources(-resultdir)]
274                  && "" != $_resources(-resultdir)} {
275                catch {
276                    if {![file exists $_resources(-resultdir)]} {
277                        _mkdir $_resources(-resultdir)
278                    }
279                    file rename -force -- $file $_resources(-resultdir)
280                }
281            }
282        } else {
283            set status 1
284            set result "Can't find result file in output.\nDid you call Rappture
285::result in your simulator?"
286        }
287        return [list $status $result]
288    } elseif {"" != $job(output) || "" != $job(error)} {
289        return [list $status [string trim "$job(output)\n$job(error)"]]
290    }
291    return [list $status $result]
292}
293
294# ----------------------------------------------------------------------
295# USAGE: _mkdir <directory>
296#
297# Used internally to create the <directory> in the file system.
298# The parent directory is also created, as needed.
299# ----------------------------------------------------------------------
300itcl::body Rappture::Tool::_mkdir {dir} {
301    set parent [file dirname $dir]
302    if {"." != $parent && "/" != $parent} {
303        if {![file exists $parent]} {
304            _mkdir $parent
305        }
306    }
307    file mkdir $dir
308}
309
310
311# ----------------------------------------------------------------------
312# USAGE: abort
313#
314# Clients use this during a "run" to abort the current job.
315# Kills the job and forces the "run" method to return.
316# ----------------------------------------------------------------------
317itcl::body Rappture::Tool::abort {} {
318    set job(control) "abort"
319}
320
321# ----------------------------------------------------------------------
322# USAGE: _output <data>
323#
324# Used internally to send each bit of output <data> coming from the
325# tool onto the caller, so the user can see progress.
326# ----------------------------------------------------------------------
327itcl::body Rappture::Tool::_output {data} {
328    if {[string length $_outputcb] > 0} {
329        uplevel #0 [list $_outputcb $data]
330    }
331}
Note: See TracBrowser for help on using the repository browser.