# This script loads everything up into memory
# from the database

# We're going to use ns_shares to keep our data
# We want to use ns_sets cause they're cool and 
# in a way they don't lock us into too specific 
# a data model

# One monitored page is represented by one ns_set
# attributes are: name, url, expected_result, failure_action, 
# admin_list, pager_list, n_retries, optional: notify_threshold
# (the last argument is the number of remaining failures at which
#  the server actually sends email; it defaults to n_retries (i.e.,
#  always send email if there is a problem).

ns_share -init {set keepalive_monitor_list [list]} keepalive_monitor_list

proc keepalive_init {} {
    ns_share keepalive_monitor_list

    ##
    ## Here goes the list of keepalives
    ##

    # example: ArsDigita (restart after 4 failures, email after the first two)
    # lappend keepalive_monitor_list [new_monitor "arsdigita" "http://www.arsdigita.com/SYSTEM/dbtest.tcl" "success" "restart-aolserver arsdigita" [list email_1@arsdigita.com email_2@arsdigita.com] [list your_pager@arsdigita.com] 4 2]

}

proc keepalive_reset {} {
    ns_share keepalive_monitor_list
    set keepalive_monitor_list [list]
}
    
proc new_monitor {name url expected_result failure_action admin_list {pager_list ""} {n_tries 5} {notify_threshold ""}} {
    set return_set [ns_set create -persist]
    ns_set put $return_set name $name
    ns_set put $return_set url $url
    ns_set put $return_set expected_result $expected_result
    ns_set put $return_set failure_action $failure_action
    ns_set put $return_set admin_list $admin_list
    ns_set put $return_set pager_list $pager_list
    ns_set put $return_set n_tries $n_tries
    ns_set put $return_set counter $n_tries
    if { $notify_threshold != "" } {
	ns_set put $return_set notify_threshold $notify_threshold
    } else {
	# default it to n_tries (always notify)
	ns_set put $return_set notify_threshold $n_tries
    }
    return $return_set
}

# every Tcl init will result in this list being set fresh

keepalive_reset
keepalive_init

# we will separately schedule the keepalive procedure per se
# because this must only be done once (i.e., don't want a Tcl
# reinit to result in an extra keepalive being scheduled).

ns_share -init {set procs_scheduled_p 0} procs_scheduled_p

if { !$procs_scheduled_p } {
    set procs_scheduled_p 1
    # we don't use -thread because we only want one copy at a time
    # running.
    ns_schedule_proc 60 keepalive_check_monitors
    ns_log Notice "proc scheduled"
}

