#!/bin/sh
# restart -*-Tcl-*- \
exec "/opt/ecloud/i686_Linux/bin/ecagent" "$0" "$@"

# agentconnect
#
# Cloudbursting script to start/stop agent.
#
# This script connects EC agents then waits for a Ctrl-C signal to
# stop the EC agents.  Depending on the wait arguments, it waits for a
# signal here in this script (instead of terminating and then a
# different script being invoked for stopping EC agents) because
# lsfAdministrators and other entities may request termination as
# well. This way, this running script becomes a central point for
# stopping the agents.
#
# This script assumes an agent is 'idle'.  That to say that the agent
# daemon/service is up but is not currently connected to a cm.
#
# Copyright (c) 2002-2026 Electric Cloud, Inc.
# Copyright (C) 2019-2020 CloudBees, Inc.
# All rights reserved.

## Global variables

variable gPlat
variable gConsoleDir


# This is the name mask that is used to find the console port numbers.
# It must match the name in runagent.

set gConsoleFile eaconsole
set wait 1

#---------------------------------------------------------------------------
# Print out to both the stdout as well as to a
# log file.
#---------------------------------------------------------------------------

proc logputs {output} {
    set stamp [clock format [clock seconds] -format {%a %b %d %Y %H:%M:%S}]
    puts "$stamp | $output"

}

#---------------------------------------------------------------------------
# agentCommand
#
#       Run a given script inside an agent process on a remote machine.
#
# Results:
#       The return value is the result or error message that is returned
#       as result by the script.  Currently there is no differentiation
#       between normal and error returns.
#
# Arguments:
#       s               The socket connected to the remote agent
#       script          Tcl script to run in the agent.
#---------------------------------------------------------------------------

proc agentCommand {s script} {
    set length [string length $script]
    puts $s "DoCommand $length"
    puts -nonewline $s $script
    flush $s
    
    # Read the result back.  The other side sends us information in the
    # following form:
    #  - the command-line prompt (output before we sent the command)
    #  - a line consisting of "xyzzy"; this line allows us to skip over
    #    the command-line prompt
    #  - a line containing a decimal number, which is the number of bytes
    #    in the result
    #  - the result (exactly the number of bytes promised)
    
    while {1} {
        set line [gets $s]
        if {$line == "xyzzy"} {
            break
        }
    }
    set length [gets $s]
    set result [read $s $length]

    return $result
}

#---------------------------------------------------------------------------
# getConsolePort
#
#       Given a port file name, read the file and return the port number.
#
# Results:
#       Returns the port number found in the first line of the file.
#
# Arguments:
#       consoleFileName     - file name we expect the port number to be in.
#---------------------------------------------------------------------------

proc getConsolePort {consoleFileName} {

    if [catch {open $consoleFileName r} infile] {
        return -code error "Unable to open port file $consoleFileName: $infile"
    }

    gets $infile port
    gets $infile key
    close $infile
    return [list $port $key]
}


#---------------------------------------------------------------------------
# connectAgent
#
#       Connects an agent to the requested CM.
#
# Results:
#       None or throws an error.
#
# Side effects:
#       The agent is connected to the requested CM and ready to accept work
#       from emake.
#
# Arguments:
#       consoleFileName   The name of a file containing the port number of the
#                         agent to disconnect.
# 
#       host              The host name and port number for the CM to connect
#                         to.  The format is "hostname:port".
#
#       resource          The resource name sent by the CM when starting the 
#                         agent.
#---------------------------------------------------------------------------

proc connectAgent {consolePortFile host resource} {
    global wait
    set result [getConsolePort $consolePortFile]
    set consolePort [lindex $result 0]
    set consoleKey  [lindex $result 1]
    set sock [socket localhost $consolePort]

    puts $sock "setKey $consoleKey"
    flush $sock
    set result [gets $sock]
    if { ![string match "*Key set*" $result] } {
        close $sock
        error $result
    }

    if { [string is true -strict $wait] } {
        agentCommand $sock "setExitHandler cmDisconnect"
    }
    agentCommand $sock "cmConnectNewHost \"$host\" \"$resource\""
    return $sock
}

#---------------------------------------------------------------------------
# getTopDirectory
#
#       Use information about our executable to figure out the top-level
#       directory in the Electric Cloud installation.  This procedure is
#       used to determine where to put various files such as logs and
#       the mount recovery database.
#
# Results:
#       The return value is the name of a directory.  Normally it is the
#       top-level directory in the Electric Cloud installation, such as
#       C:/ECloud on Windows.  However, if the executable doesn't seem to
#       be part of a standard installation, then the current directory
#       is returned.
#
# Side effects:
#       None.
#
# Arguments:
#       exec -                   If this argument is supplied, it specifies
#                                the name of the executable file used to
#                                compute the top-level directory.  If
#                                omitted it defaults to
#                                [info nameofexecutable].
#---------------------------------------------------------------------------

proc getTopDirectory {{exec {}}} {
    
    # If the binary for the executable is in a directory with a name like
    # /x/y/z/arch/bin, where "arch" is one of our architectures, then the
    # top-level directory is /x/y/z.
    
    if {$exec == ""} {
        set exec [info nameofexecutable]
    }
    set dir [file dirname $exec]
    set parent [file dirname $dir]
    set lastDir [file tail $dir]
    set lastParent [file tail $parent]
    
    if {($lastDir == "bin") && (($lastParent == "i686_win32")\
            || ($lastParent == "sun4u_SunOS")\
            || ($lastParent == "i686_Linux"))} {
        return [file dirname $parent]
    }
    
    return .
}

#---------------------------------------------------------------------------
# usage
#
#       Print the command and legal parameters.
#
# Results:
#       Note.
# 
# Side effects:
#       None.
#
# Arguments:
#       None.
#---------------------------------------------------------------------------

proc usage {} {
    puts {agentconnect
Sets the Cluster Manager for the Electric Cloud Agents on the host 
on which it is invoked and waits for a signal to disconnect from the 
Cluster Manager unless wait is 0.

Usage: agentconnect host:port resource [wait]
       host:port             - Cluster Manager host name and port
       resource              - Name of the cloud resource launching
                               the agent.
       wait                  - (Optional) When set to 1, the 
                               agentconnect script waits for a
                               signal to disconnect from the 
                               Cluster Manager. If 0, the script 
                               exits without waiting (default 1).}
}

#---------------------------------------------------------------------------
# initialize
#
#       Creates and opens the log file.
#       Finds the platform specific mask for finding console port files.
#
# Results:
#       None.
# 
# Side effects:
#       Sets gPlat, gConsoleDir
#
# Arguments:
#       None.
#---------------------------------------------------------------------------

proc initialize {} {
    global gPlat gConsoleDir gConsoleFile

    set gPlat $::tcl_platform(platform)
    
    if { $gPlat == "unix" } {
        set gConsoleDir /var/run/$gConsoleFile*.port
    } elseif { $gPlat == "windows"} {
        set gConsoleDir [file join [getTopDirectory] $gConsoleFile*.port]
    } else {
        # Reality check. Adjust to an unknown world.
        puts "Unknown platform: $gPlat. Pretending to be windows platform" 
        set gPlat "windows"
        set gConsoleDir /var/run/$gConsoleFile*.port
    }

}

#---------------------------------------------------------------------------
# printSettings
#
#       Prints the settings that we are using to operate.
#
# Results:
# 
# Side effects:
#       None.
#
# Arguments:
#       host                    cmhost:port
#---------------------------------------------------------------------------

proc printSettings {host} {
    global gPlat 

    # Print the various settings for debugging purposes
    # This needs to be done in its own function to ensure that we are truly
    # retrieving the specified global values rather than some local variable
    # value.

    set myPid [pid]
    logputs "-----------------------------------------------------"
    logputs "Current SETTINGS:"
    logputs "Platform        is: $gPlat"
    logputs "My Process Id   is: $myPid"
    logputs "Cluster Manager is: $host"
    logputs "-----------------------------------------------------"
    logputs ""
}

#---------------------------------------------------------------------------
# main
#
#       Connects the agents to the specified CM, and if wait is true,
#       waits for a signal and then disconnects the agents.
#
# Results:
#       None.
# 
# Side effects:
#       None.
#
# Arguments:
#       argv                    Command line arguments
#---------------------------------------------------------------------------

proc main {argv} {
    global gPlat gConsoleFile gConsoleDir wait

    set numArgs [llength $argv]
    if { $numArgs < 1 || $numArgs > 3 } {
        usage
        exit 1
    }
    
    set host [lindex $argv 0]
    if {![regexp {[^:]+:[0-9]+$} $host]} {
        usage
        exit 1
    }
    if { $numArgs > 1 } {
        set resourceName [lindex $argv 1]
    }

    if { $numArgs == 3 } {
        set wait [lindex $argv 2]
    }

    initialize
    printSettings $host
            
    # Start the agents

    logputs "Starting Electric Cloud agents ..."

    set portFiles [list]
    for {set retries 0} {$retries < 60} {incr retries} {
        set portFiles [lsort -dictionary [glob -nocomplain $gConsoleDir]]
        if { [llength $portFiles] > 0 } {
            break
        }
        after 3000
    }
    if { [llength $portFiles] == 0 } {
        logputs "No connection files found.  Exiting..."
        exit 1
    }

    set sockets [list]
    set counter 0
    foreach file $portFiles {
        incr counter
        for {set retries 0} {$retries < 60} {incr retries} {
            if {[catch {connectAgent $file $host $resourceName} sock]} {
                logputs "Unable to connect to agent-$counter: $sock"
            } else {
                lappend sockets $sock
                logputs "Connected to agent-$counter"
                break
            }
            after 3000
        }
    }

    if { [string is true -strict $wait] } {
        # Wait for a signal we care about.  We do this by opening a connection
        # to the socket server that the parent agentconnect process started.
        # When the parent receives a SIGINT or SIGKILL, the socket will be
        # invalid, and that's when we know we received a signal and start
        # cleanup.
        
        set s [socket -server dummy 0]
        set ::signalled ""
        
        logputs "-----------------------------------------------------"
        logputs "Waiting for signal..."
        
        update
        if { $::signalled == "" } {
            vwait ::signalled
        }
        
        # Ctrl-C has been received. Stop any running agents now.
        logputs "Signal received."
        logputs "-----------------------------------------------------"
        logputs "Disconnecting Electric Cloud agents ..."
        
        
        foreach sock $sockets {
            catch {close $sock}
        }
        
        logputs "Disconnect complete."
        logputs "-----------------------------------------------------"
    }
}


##############################################################################
# Execution begin here
##############################################################################

main $argv
