# copyright (C) 1997-2006 Jean-Luc Fontaine (mailto:jfontain@free.fr)
# this program is free software: please read the COPYRIGHT file enclosed in this package or use the Help Copyright menu

# $Id: mystatus.tcl,v 2.55 2006/03/28 15:10:34 jfontain Exp $


package provide mystatus [lindex {$Revision: 2.55 $} 1]
package require miscellaneous 1
if {![catch {package require Thread 2.5}]} {           ;# use threads so that core is not blocked on connection problems with server
    package require stooop 4.1
    namespace import stooop::*
    package require threads 1
    namespace eval mystatus {
        variable thread
        set thread(busy) 0
        set thread(worker) [new worker]
    }
}


namespace eval mystatus {}
source mystatus.dat

namespace eval mystatus {

    array set data {
        updates 0
        0,label display 0,type ascii 0,message {per second values are calculated for the last poll period using the absolute values from the server, and only for variables that make sense (otherwise a ? is displayed in the column)}
        0,0 absolute 1,0 {per second}
        pollTimes {10 5 20 30 60 120 300}
        persistent 0
        switches {--dsn 1 --host 1 --password 1 --port 1 --user 1}
    }
    set file [open mystatus.htm]
    set data(helpText) [read $file]                                                           ;# initialize HTML help data from file
    close $file
    if {[info exists thread]} {                     ;# show on last line of this module help window that we are running with threads
        regsub -nocase </body> $data(helpText) "<p><i>(currently running in threaded mode)</i>\n\\0" data(helpText)
    }

    proc initialize {optionsName} {
        upvar 1 $optionsName options
        variable thread
        variable odbc
        variable connection
        variable data
        variable help
        variable type
        variable nameColumn

        set user $::tcl_platform(user)                                                                                 ;# by default
        catch {set user $options(--user)}
        if {[info exists options(--dsn)]} {                                               ;# ODBC mode id data source name specified
            set odbc 1
            if {[info exists options(--host)] || [info exists options(--port)]} {
                error {--host and --port options incompatible with ODBC mode}
            }
            set arguments [list $options(--dsn)]
            catch {lappend arguments $user}
            catch {lappend arguments $options(--password)}
            if {[info exists thread]} {
                worker::evaluate $thread(worker) {package require tclodbc 2}
                set connection [worker::wait $thread(worker) "database odbc $arguments"]             ;# use a unique connection name
                set list [worker::evaluate $thread(worker) "$connection {show variables like 'version'}"]
            } else {
                package require tclodbc 2                           ;# so that it works with both UNIX 2.2.1 et Windows 2.3 versions
                set connection [eval database odbc $arguments]                                       ;# use a unique connection name
                set list [$connection {show variables like 'version'}]
            }
            set data(identifier) mystatus($options(--dsn))
            scan [lindex [lindex $list 0] 1] %u.%u.%u major minor subMinor
        } else {
            set odbc 0
            if {[info exists options(--port)] && (![info exists options(--host)] || [string equal $options(--host) localhost])} {
                error {--port option useless with local socket connection (localhost as host)}
            }
            set arguments {}
            catch {lappend arguments -host $options(--host)}
            catch {lappend arguments -user $user}
            catch {lappend arguments -password $options(--password)}
            catch {lappend arguments -port $options(--port)}
            if {[info exists thread]} {
                worker::evaluate $thread(worker) {package require mysqltcl}
                set connection [worker::wait $thread(worker) "mysqlconnect $arguments"]                           ;# do not hang GUI
                set host [worker::evaluate $thread(worker) "lindex \[mysqlinfo $connection host\] 0"]
                # do not retrieve version in background as it is unlikely to fail if connection was established:
                set list [worker::evaluate $thread(worker) "mysqlsel $connection {show variables like 'version'} -flatlist"]
            } else {
                package require mysqltcl
                set connection [eval mysqlconnect $arguments]
                set host [lindex [mysqlinfo $connection host] 0]           ;# work around mysqltcl 3 return value: "host via TCP/IP"
                set list [mysqlsel $connection {show variables like 'version'} -flatlist]
            }
            set data(identifier) mystatus($host)
            scan [lindex $list 1] %u.%u.%u major minor subMinor
        }
        switch $major {
            3 {
                if {$minor != 23} {error "cannot monitor a server version 3.$minor"}
                if {$subMinor < 51} {error {cannot monitor a server below version 3.23.51 in the 3.23 series}}
            }
            4 - 5 {
                if {$minor > 1} {error "cannot monitor a server version $major.$minor"}
            }
            default {
                error "cannot monitor a server version $major"
            }
        }
        if {$odbc} {
            if {[info exists thread]} {
                worker::evaluate $thread(worker) "$connection statement $connection.query {show status}; $connection.query execute"
            } else {
                $connection statement $connection.query {show status}; $connection.query execute
            }
        } else {
            if {[info exists thread]} {
                worker::evaluate $thread(worker) "mysqlsel $connection {show status}"
            } else {
                mysqlsel $connection {show status}
            }
        }
        set columns(main) 0
        set columns(queries) 0
        set column 1
        while {1} {                                                                     ;# gather existing variables from the server
            if {$odbc} {
                if {[info exists thread]} {
                    set list [worker::evaluate $thread(worker) "$connection.query fetch"]
                } else {
                    set list [$connection.query fetch]
                }
            } else {
                if {[info exists thread]} {
                    set list [worker::evaluate $thread(worker) "mysqlnext $connection"]
                } else {
                    set list [mysqlnext $connection]
                }
            }
            if {[llength $list] == 0} break
            set variable [lindex $list 0]
            set nameColumn($variable) $column                                                            ;# remember variable column
            set data($column,label) $variable
            set value real                                                                                             ;# by default
            catch {set value $type($variable)}
            if {![string equal $value real]} {
                set data(1,$column) ?                                                                    ;# no per second value ever
            }
            set data($column,type) $value
            if {![info exists help($variable)]} {
                puts stderr "\"$variable\" variable is not recognized by mystatus: please contact author."
                set data($column,message) {not recognized: please contact author}
            } elseif {[string length $help($variable)] == 0} {
                set data($column,message) {undocumented in the MySQL documentation}
            } else {
                set data($column,message) $help($variable)
                if {[string match *Bytes* $variable]} {                             ;# anything in bytes is transformed to kilobytes
                    append data($column,message) { (in kilobytes)}
                }
            }
            set data($column,anchor) left
            if {[string match Com_* $variable]} {
                lappend columns(queries) $column                                         ;# put queries counters in a separate table
            } else {
                lappend columns(main) $column
            }
            incr column
        }
        if {$odbc} {
            if {[info exists thread]} {
                worker::evaluate $thread(worker) "$connection.query drop"
            } else {
                $connection.query drop
            }
        }
        unset help type                                                                                          ;# save some memory
        set data(views) [list [list indices $columns(main) swap 1] [list indices $columns(queries) swap 1]]
    }

    proc update {} {
        variable thread

        if {[info exists thread]} {
            if {$thread(busy)} return
            set thread(busy) 1
        }
        getStatus
    }

    proc getStatus {{result {}} {errorInformation {}}} {
        variable thread
        variable odbc
        variable connection
        variable last
        variable data
        variable nameColumn

        set error 0
        if {[info exists thread]} {
            if {[string length $result] == 0} {                                                        ;# launch query in background
                if {$odbc} {
                    worker::evaluate $thread(worker)\
                        "$connection statement $connection.query {show status}; $connection.query execute; list 1"\
                        mystatus::getStatus
                } else {
                    worker::evaluate $thread(worker) "mysqlsel $connection {show status}; list 1" mystatus::getStatus
                }
                return                                       ;# this procedure is invoked back with a non-empty result (1) when done
            } elseif {[string length $errorInformation] > 0} {                                                   ;# an error occured
                set error 1
                set message $result
            }                                                                           ;# else the query was executed with no error
        } else {
            if {$odbc} {
                set error [catch {$connection statement $connection.query {show status}; $connection.query execute} message]
            } else {
                set error [catch {mysqlsel $connection {show status}} message]
            }
        }
        if {$error} {                                                                                     ;# problem reaching server
            flashMessage "error: $message"
            catch {unset last}
            foreach {name column} [array get nameColumn] {
                if {$column == 0} continue                                                                         ;# headers column
                set data(0,$column) ?
                if {[string equal $data($column,type) real]} {                                     ;# required for per second values
                    set data(1,$column) ?
                }
            }
        } else {
            set clock [expr {[clock clicks -milliseconds] / 1000.0}]                                       ;# store clock in seconds
            catch {set period [expr {$clock - $last(clock)}]}
            set last(clock) $clock
            while {1} {
                if {[info exists thread]} {
                    # no need for background work since the whole data is already in this client (mysql_store_result() used):
                    if {$odbc} {
                        set list [worker::evaluate $thread(worker) "$connection.query fetch"]
                    } else {
                        set list [worker::evaluate $thread(worker) "mysqlnext $connection"]
                    }
                } else {
                    if {$odbc} {
                        set list [$connection.query fetch]
                    } else {
                        set list [mysqlnext $connection]
                    }
                }
                if {[llength $list] == 0} break
                foreach {variable value} $list {}
                set column $nameColumn($variable)
                if {[string equal $variable Uptime]} {
                    set data(0,$column) [formattedTime $value]
                    set data(1,$column) {}
                } else {
                    if {[string equal $data($column,type) real]} {                                 ;# required for per second values
                        set bytes [string match *Bytes* $variable]
                        if {$bytes} {                                               ;# anything in bytes is transformed to kilobytes
                            append value .0                                                                      ;# convert to float
                            set value [expr {$value / 1000.0}]
                            set data(0,$column) [format %.2f $value]
                        } else {
                            set data(0,$column) $value                               ;# display as is as it really may be an integer
                        }
                        if {[info exists period]} {
                            if {$bytes} {
                                set data(1,$column) [format %.2f [expr {($value - $last($column)) / $period}]]
                            } else {
                                # can wrap around, so force 32 bit integers subtractions (valid on 32 and 64 bit Tcl platforms)
                                set data(1,$column) [format %.2f [expr {(($value - $last($column)) & 0xFFFFFFFF) / $period}]]
                            }
                        } else {
                            set data(1,$column) ?
                        }
                        set last($column) $value
                    } else {
                        set data(0,$column) $value
                    }
                }
            }
        }
        if {$odbc} {
            # ignore connection errors at this point (they will be reported at next poll):
            if {[info exists thread]} {
                catch {worker::evaluate $thread(worker) "$connection.query drop"}
            } else {
                catch {$connection.query drop}
            }
        }
        if {[info exists thread]} {
            set thread(busy) 0
        }
        incr data(updates)
    }

    proc terminate {} {
        variable thread
        variable odbc
        variable connection

        if {![info exists connection]} return                                        ;# connection may have failed in initialization
        if {$odbc} {
            if {[info exists thread]} {
                worker::evaluate $thread(worker) "$connection disconnect" list            ;# try to disconnect while ignoring errors
                delete $thread(worker)
            } else {
                catch {$connection disconnect}
            }
        } else {
            if {[info exists thread]} {
                worker::evaluate $thread(worker) "mysqlclose $connection" list      ;# try to close connection while ignoring errors
                delete $thread(worker)
            } else {
                catch {mysqlclose $connection}
            }
        }
    }

}
