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

# This string (CLEANUP: CHECK) ensures that the "cleanup" script will check
# this file, even though it doesn't have one of the expected extensions.

set OPTIONS {
    {-cm            ""      "Cluster manager network address (host:port)"}
    {-consoleport   ""      "Port used for the agent console; 0=disable"}
    {-local         0       "This is a private agent that should only be allocated to emake instances on the same host."}
    {-matchuser     1       "On Windows, allow all requests from the agent's user ID to match the EFS."}
    {-debug         1       "Debug level: 0, 1, or 2"}
    {-diskcacheportfile ""  "The location where the diskcache manager ports can be found"}
    {-efsid         0       "EFS this agent will work with (default 0)"}
    {-fixedports    0       "Use preset portnums for agent server ports"}
    {-help          ""      "Print this message"}
    {-consolelogfile ""     "Where to log stdout/stderr messages" }
    {-logfile       ""      "File to use for agent session messages"}
    {-myname        ""      "Name of this agent"}
    {-myhost        ""      "Name of this host"}
    {-myip          ""      "IP of this host"}
    {-myip1         ""      ""}
    {-numagents     1       "Total number of agents running on this host"}
    {-porttimeout   10      "Seconds to wait before retrying ports"}
    {-redirect      1       "Redirect standard I/O channels to logs"}
    {-version       ""      "Print the agent version and exit"}
    {-sandbox       "on"    "Use the agent sandbox for process isolation"}
    {-secureconsole "n"     "Require an agent key to use the console port(y|n)"}
    {-tempdir       ""      "Location which the agent should use to store temp files"}
    {-trace         {}      "Space-separated trace flags in addition to those implied by -debug"}
    {-emakesecurity ""      ""}
    {-sslcacert     ""      "Path to CA certification PEM file"}
    {-sslkeystore   ""      "Path to server certification and private key combined PEM file"}
    {-sslallow      ""      "Specification of common names and organizational units that are allowed to connect"}
    {-resource      ""      "Resource name for cloudbursting agent"}
    {-cmsecurity    "relaxed" "The type of security used to connect to the CM"}
    {-cmkeystore    ""       "Path to CM server certification and private key combined PEM file"}
    {-cmallow       ""       "Specification of common names and organizational units that are allowed to connect to the CM"}
    {-check         0        "Check the validity of the command-line options"}
}

# The following global variable specifies the prompt to use in all
# interactive windows:

set prompt %

# If we're processing a command in ConsoleRead, the following variable
# holds into the console from which the command came.  Otherwise this
# variable holds an empty string.

set gCurrentConsole ""

# gLastCM keeps track of the previous CM we have connected to
# it is used to find a transition from one CM to another so
# we can generate a new key

set gLastCM ""

# gConnectedTo - sets to the CM we are connected to
# set to "" when not connected to a CM

set gConnectedTo ""

# If the following variable is true, it means we failed to connect to
# a cluster manager, but will keep retrying.

set cmRetrying 0

# This the command handle for the next connect command.
# It is used for retrying connections.

set cmRetryCommand 0

# This is the file prefix for storing the console port number
# See the agentRun.tcl script for other uses of this name

set gConsoleFilePrefix eaconsole

# This is the console port file name.
# The file has 3 lines in this order:
#    1.  port number
#    2.  agent key
#    3.  most recently connected to CM

set gConsoleFileName ""

# Saves a copy of the originally requested CM
# This is used when we disconnect from the CM.  If you don't save it
# you can't tell if the agent was supposed to boot up and connect to
# a CM or start in an idle state.

set gOriginalCm ""

# This key is re-generated when ever the agent connects to a CM
# It is used to uniquely identify each CM connection (to make
# sure old connections are reused and as a 'password' for
# secure agents.

set gAgentKey 0

# Don't start LOFS, this variable will be set by the installer to
# turn lofs off if the customer requested that.
set gSkipLofs 0

# File names of the local agent files to be deleted on exit.
set gAgentFileName ""
set gAgentTempFileName ""

# Sentinel variable used to initiate clean shutdown of the agent process.

set signalled ""

# The following variable determines how long (in ms) a command must sit idle
# before the agent considers it to be stalled.  (Windows only)
# Cygwin has a difficult-to-reproduce bug that can cause bash.exe to go
# into an infinite loop that gobbles CPU, so don't check cpu for it.

set commandTimeout\
    {\
         { {.*bin[/\\](ba)?sh.exe.*} 60000 {disk} }\
         { {.*} 60000 {cpu disk} }\
     }

#---------------------------------------------------------------------------
# perr
#
#       Abstraction for "puts stderr" that we can override in testing and
#       other contexts.
#---------------------------------------------------------------------------

proc perr {msg} {
    puts stderr $msg
}

#---------------------------------------------------------------------------
# initClockSkew
#
#       Set the maximum clock skew
#
# Results:
#       None.
#
# Side effects: 
#       The maximum clock skew value will be used to by the agent will
#       warn if the agent's clock varies from the emake machine's.
#---------------------------------------------------------------------------

proc initClockSkew {} {
    # The normal behavior of the agent is to send warnings back to the emake
    # machine if the agent's clock varies from the emake machine's by more
    # than [session maxclockskew] milliseconds.  If you set the maximum skew
    # to a negative number, the agent will actually change the local system
    # clock to match the clock on the emake machine; this can lead to trouble
    # if you have multiple agents on the same node working on different builds,
    # so don't invoke "session maxclockskew -1" without telling the cluster
    # manager about it.
    if { $::tcl_platform(platform) == "windows" } {
        if { [file exists [testwin systemdir]\\vmx_fb.dll] } {
            # This is a VM; be a little more relaxed about time syncing.
            # Could also check for MAC address 00:05:69:..., 00:0c:29:...,
            # 00:50:56:... using ipconfig /all.
            session maxclockskew [expr 90000]
        } else {
            session maxclockskew 10000
        }
    } else {
        if { [file exists /etc/vmware-tools] } {
            session maxclockskew [expr 120000]
        } else {
            session maxclockskew 10000
        }
    }
}

#---------------------------------------------------------------------------
# initSandbox
#
#       Sets up the sandbox mount points.
#
# Results:
#       None.
#
# Side effects: 
#       The sandbox bindmounts will be set up and havelofs will be set.
#
#---------------------------------------------------------------------------
proc initSandbox {{mounts ""}} {
    variable opts
    if { [info exists opts(-sandbox)] && !$opts(-sandbox) } {
        # User has instructed not to use the sandbox, so make sure the session
        # is made aware.  This probably means the agent is running inside a
        # container, which provides process isolation in a more robust and
        # efficient way.

        session sandbox off

        # Likewise disable the sandbox integration in the EFS, as it's not
        # needed in this mode.  This does a more efficient disabling than
        # the EFS useSandbox symbol.

        efs unixsandbox off
    }

    if { $::tcl_platform(platform) == "unix" } {
        set gSandboxRoot "/efsroots"
        if { ![string equal -length 8 $gSandboxRoot "REPLACE_"] } {
            if { ![file exists $gSandboxRoot] } {
                catch {file mkdir $gSandboxRoot}
            }
            sandbox root $gSandboxRoot
        }
    }

    if { $::tcl_platform(os) == "Linux" } {
        set kernel ""
        catch {set kernel [exec /bin/uname -r]}
        if { [regexp {^2\.4} $kernel] } {
            # LOFS is only supported on 2.6 kernels.

            sandbox havelofs 0
        }

        catch {
            catch {unset rootFS}
            array set rootFS [libc statfs /]
            set overlayFS 0x794c7630
            if { $rootFS(f_type) == $overlayFS } {
                # LOFS does not work on top of overlayFS, which is used
                # in containers on some versions of Linux, because overlayFS
                # uses the "new" model of stacking filesystems that only
                # involves dentries and not inodes.  For now therefore we
                # disable lofs if the root filesystem is overlayFS.

                sandbox havelofs 0
            }
        }

        # Certain types of filesystems can't be mirrored with lofs.  Scan for
        # those and add any mountpoints using those filesystem types to the
        # list of mounts to mirror using bind.

        set bindmounts [sandbox bindmounts]
        array set unsupportedTypes {
            devpts  1
            proc    1
            tmpfs   1
        }
        catch {
            if { [string length $mounts] == 0 } {
                set mountsFD [open "/proc/mounts" r]
                set mounts   [read $mountsFD]
                close $mountsFD
            }

            set rlen [string length [sandbox root]]
            foreach line [split $mounts \n] {
                foreach {dev mount fstype} $line { break }
                if { [string index $mount 0] != "/" } {
                    # This is not a real filesystem mountpoint -- it's probably
                    # something like "net:[12356]", a pseudo filesystem that
                    # exists to support some aspect of containerization on this
                    # host.  We don't need to mirror it, so skip it.

                    continue
                }
                if { [info exists unsupportedTypes($fstype)] } {
                    if {![string equal -length $rlen $mount [sandbox root]]} {
                        lappend bindmounts $mount
                    }
                }
            }

            set bindmounts [lsort -unique $bindmounts]
        }
        sandbox bindmounts $bindmounts
    }

    if {$::gSkipLofs == 1 || $::gSkipLofs == "y"} {
        sandbox havelofs 0
    }
} 

# On Windows we're typically invoked as a service with a private invisible
# window station.  If the following variable is true, switch to the main
# interactive window station so that if any of the jobs run by this agent
# accidentally pop up windows to interact with the user, the windows will be
# visible (otherwise this kind of problem is very hard to debug).

set debugPopups 1

# The following proc specifies the default port to use for the agent console
# port.  It takes the efsid and returns a port number.

proc consolePort {efsid} {
    return [expr {2409 + 10 * $efsid}]
}

# The following procs specify the ports to use for the various services that
# the agent supports.  These ports are used only if the -fixedports option is
# specified with a non-zero value on the runagent command line.  Otherwise,
# the agent uses dynamically assigned ports.  Each proc takes the efsid.

proc emakePort {efsid} {
    return [expr {2408 + 10 * $efsid}]
}

proc a2aPort {efsid} {
    return [expr {2410 + 10 * $efsid}]
}

proc cmControlPort {efsid} {
    if { $efsid == 0 } {
        return 8001
    }
    return [expr {2411 + 10 * $efsid}]
}

#---------------------------------------------------------------------------
# ConsoleRead
#
#       Read input from an agent console, executing it as a tcl command
#       whenever a complete command is input.
#
# Results:
#       None.
#
# Side effects:
#       Just about anything, depending on the command that is typed in.
#
# Arguments:
#       name -                Name of global variable containing information
#                             about this console.
#---------------------------------------------------------------------------

proc ConsoleRead {name} {
    variable gAgentKey
    upvar #0 $name console

    append console(line) [gets $console(input)]
    if { [eof $console(input)] } {
        ConsoleCleanup $name
        return
    }
    if {[info complete $console(line)]} {
        set ::gCurrentConsole $name
        set safeCommandPattern {^\s*(?:setKey\s+\d+|quit)\s*$}

        # Look for the setKey command.  If it's there strip out the number and
        # set it using the port as an index.  To help prevent hacking, we
        # prevent command and variable substitution until the key is set.

        if {! [regexp -- $safeCommandPattern $console(line)]
            && $console(secure) != "n"
            && $console(key) != $gAgentKey} {
            puts $console(output) "Missing Agent key. Use \"setKey ###\""
            puts -nonewline $console(output) $::prompt
            flush $console(output)
            if {![info exists ::ECLOUD_TEST_MODE] } {
                perr "Missing Agent key. Use \"setKey ###\""
            }
            set console(line) {}
            set ::gCurrentConsole ""
            return
        }

        catch {uplevel #0 $console(line)} result

        if { [info exists console] } {
            # If the command included [quit], then the console array will have
            # been deleted, and we don't want to recreate it now.  Therefore
            # only do this stuff if the console array still exists.

            catch {
                puts $console(output) $result
                puts -nonewline $console(output) $::prompt
                flush $console(output)
            }

            set console(line) {}
        }
        set ::gCurrentConsole ""
    } else {
        append console(line) "\n"
    }
}

#---------------------------------------------------------------------------
# RemoteConsoleStart
#
#       Start up an interactive console in response to a socket connection.
#
# Results:
#       None.
#
# Side effects:
#       The application will display a prompt and respond to input from the
#       socket.  Resets the saved key for the incoming port
#
# Arguments:
#       socket  -               The open socket handle.
#       address -               The IP address of the connecting machine.
#       port    -               The actual connection port.
#---------------------------------------------------------------------------

proc RemoteConsoleStart {socket address port} {
    variable opts
    upvar #0 console_$socket console

    catch {unset console}

    # Set up the state variable for the new console.

    set console(input) $socket
    set console(output) $socket
    set console(line) {}
    set console(key) "NoKey"
    set console(secure) $opts(-secureconsole)

    puts -nonewline $console(output) $::prompt
    flush $console(output)
    fconfigure $console(output) -translation binary
    fileevent $console(input) readable "ConsoleRead console_$socket"

    return
}

#---------------------------------------------------------------------------
# SaveConsolePortFile
#
#       Saves the console port for this agent an a file.  The AgentRun.tcl
#       script uses this file to find the console port.
#
#       Does nothing if $::opts(-consoleport) is 0,
#       which means that the agent console port is disabled.
#
# Results:
#       Creates a port file.
#       The first line of the port file has the port number for this agent.
#       The second line is the magic key for this agent.
#
# Side effects:
#
# Arguments:
#       Uses the opts(-efsid) and opts(-consoleport)
#---------------------------------------------------------------------------

proc SaveConsolePortFile {} {
    variable opts
    variable gConsoleFileName
    variable gAgentKey
    variable gLastCM

    if { $opts(-consoleport) == 0 } {
        return
    }

    # As seen in EC-5303, sometimes we have trouble saving the console port
    # file at startup.  Restarting the agent clears the problem, so
    # presumably sleeping a bit and trying again will do the trick as well.

    set retries 5
    while { $retries > 0 } {
        # The catch around the I/O is split in two parts, so we can always be
        # sure that we close the file handle, even if we get an error during
        # the writes.

        set result [catch {
            set out [open $gConsoleFileName w]
            puts $out $opts(-consoleport)
            puts $out $gAgentKey
            puts $out $gLastCM
        } err]
        catch {close $out}
        if { $result == 0 } {
            break
        }
        after 250
        incr retries -1
    }

    if { $retries == 0 } {
        # We exhausted our retries, so we really need to abort.

        perr \
            "ERROR: Unable to save port number in $gConsoleFileName: $err"
        perr "ERROR: Exiting."
        exit 1
    }

    return
}

#---------------------------------------------------------------------------
# ReadConsolePortFile
#
#       Reads the console port file to get the last CM we connected to
#       and the key that we used.
#
#       Does nothing if $::opts(-consoleport) is 0,
#       which means that the agent console port is disabled.
#
# Results:
#
# Side effects:
#       Sets gAgentKey and gLastCM
#
# Arguments:
#       Uses gConsoleFileName
#---------------------------------------------------------------------------

proc ReadConsolePortFile {} {
    variable opts
    variable gConsoleFileName
    variable gAgentKey
    variable gLastCM

    if { $opts(-consoleport) == 0 } {
        return
    }

    if { [catch {set out [open $gConsoleFileName r]} message] } {
        set gAgentKey [expr {int(rand() * 1000000000)}]
        set gLastCM ""
        SaveConsolePortFile
        return
    }

    gets $out
    set gAgentKey [gets $out]
    set gLastCM   [gets $out]
    close $out
}

#---------------------------------------------------------------------------
# exitCleanup
#
#       This procedure is invoked (either directly by the C code of the agent
#       or by Tcl code in this file) before the agent exits.  The main reason
#       for this procedure is that there is a bug in Tcl 8.3.4 that causes a
#       crash if Tcl exits with TCP sockets open.
#
# Results:
#       None.
#
# Side effects:
#       Various cleanup operations are performed, such as closing all open
#       sockets.
#
# Arguments:
#       None.
#---------------------------------------------------------------------------

proc exitCleanup {} {
    foreach f [file channels] {
        if {[string match sock* $f]} {
            close $f
        }
    }
}

#---------------------------------------------------------------------------
# setKey
#
#       Set the agent console port key to the given value.
#---------------------------------------------------------------------------

proc setKey {key args} {
    variable gAgentKey
    upvar #0 $::gCurrentConsole console
    if { $key == $gAgentKey} {
        set console(key) $key
        return "Key set."
    } else {
        return "Invalid Agent Key. Use \"setKey ###\""
    }
}

#---------------------------------------------------------------------------
# setExitHandler
#
#       Specify a script to be executed when the current console disconnects.
#---------------------------------------------------------------------------

proc setExitHandler {script} {
    upvar #0 $::gCurrentConsole console
    set console(exitHandler) $script
}

#---------------------------------------------------------------------------
# panic
#
#       Convenience wrapper to provoke a kernel dump.
#---------------------------------------------------------------------------

proc panic {} {
    set efs [efs connect]
    $efs uselock false
    $efs panic
}

#---------------------------------------------------------------------------
# exit
#
#       We define our own exit procedure, so that we can do appropriate
#       cleanup when the agent is shutdown.  We have to first rename the
#       "exit" builtin, so that we will still be able to access it after
#       defining our new proc.
#
# Results:
#       None.
#
# Side effects:
#       The session is closed and the application exits.
#
# Arguments:
#       code -                  Exit code.
#---------------------------------------------------------------------------

if { [namespace current] == "::" } {
    if { ![info exists ::ECLOUD_TEST_MODE] || !$::ECLOUD_TEST_MODE } {
        rename exit _exit
        proc exit {{code 0}} {
            if {$::gCurrentConsole != ""} {
                upvar #0 $::gCurrentConsole console
                if {$console(input) != "stdin"} {
                    puts -nonewline $console(output)\
                        "Are you sure you want the agent to exit? (y/n) "
                    flush $console(output)
                    if {[string index [gets $console(input)] 0] != "y"} {
                        return
                    }
                }
            }
            set ::signalled "Shutdown from console"
        }
    }
}

#----------------------------------------------------------------------------
# ConsoleCleanup
#
#       Release resources associated with the named console, including
#       closing the input/output channels and deleting the state array.
#----------------------------------------------------------------------------

proc ConsoleCleanup {name} {
    upvar #0 $name console
    catch {close $console(input)}
    catch {close $console(output)}
    if {$console(input) == "stdin"} {
        exit
    }

    if {[info exists console(exitHandler)]} {
        catch {uplevel #0 $console(exitHandler)}
    }
    unset console
}

#---------------------------------------------------------------------------
# quit
#
#       This command closes the remote console from which it was invoked.
#
# Results:
#       None.
#
# Side effects:
#       The console connection to the agent is terminated.
#
# Arguments:
#       None.
#---------------------------------------------------------------------------

proc quit {} {
    if {$::gCurrentConsole != ""} {
        ConsoleCleanup $::gCurrentConsole
    }
}

#---------------------------------------------------------------------------
# DoCommand
#
#       This procedure enables remote command invocation on the agent.
#       It reads a command from the current console according to a
#       particular protocol, executes the command, and returns the
#       result of the command on the console.
#
# Results:
#       None.
#
# Side effects:
#       Can be arbitrary, depending on the command.  Information is
#       read from and written to the current console
#
# Arguments:
#       length  -               Number of bytes in the incoming command.
#---------------------------------------------------------------------------

proc DoCommand {length} {
    upvar #0 $::gCurrentConsole console

    set command [read $console(input) $length]
    if {[catch {uplevel \#0 $command} message]} {
        set message $::errorInfo
    }
    puts $console(output) "\nxyzzy\n[string length $message]"
    puts -nonewline $console(output) $message
    flush $console(output)
}

#---------------------------------------------------------------------------
# getState
#
#       Return the interesting global variables for debugging
#       agent state.
#
# Results:
#       None.
#
# Side effects:
#       None.
#
# Arguments:
#       None.
#---------------------------------------------------------------------------

proc getState {} {
    upvar #0 $::gCurrentConsole console

    puts $console(output) "Last CM     =$::gLastCM"
    puts $console(output) "Connected To=$::gConnectedTo"
    puts $console(output) "Retry       =$::cmRetrying"
    puts $console(output) "Console File=$::gConsoleFileName"
    puts $console(output) "Console Port=$::opts(-consoleport)"
    puts $console(output) "efsid       =$::opts(-efsid)"
    puts $console(output) "Agent       =$::opts(-myname)"
    puts $console(output) "Num Agents  =$::opts(-numagents)"
}


#---------------------------------------------------------------------------
# findEfs
#
#       This procedure connects to an EFS and evaluates a EFS-specific
#       command for that EFS.  If no EFS is currently connected, this
#       procedure connects to the default EFS; if an EFS already exists,
#       we reconnect to that EFS.  Then the object command for that EFS
#       is invoked with "args" as arguments.  The EFS is then disconnected,
#       but only if its object command didn't exist before this procedure
#       was invoked.
#
# Results:
#       Whatever is returned by the EFS object command.
#
# Side effects:
#       Depends on the arguments.
#
# Arguments:
#       args  -              Arguments to pass to the EFS; they can have
#                            any form acceptable to an EFS object command.
#---------------------------------------------------------------------------

proc findEfs {args} {
    set commands [info commands *]

    set efs [efs connect]
    set code [catch {uplevel $efs $args} result]

    # Don't delete the EFS object command if it existed prior to this
    # procedure being invoked.

    if {[lsearch -exact $commands $efs] < 0} {
        $efs disconnect
    }
    return -code $code $result
}

#---------------------------------------------------------------------------
# safeReadFile
#
#       Safely read a file.  Guaranteed not to raise errors or leak handles.
#---------------------------------------------------------------------------

proc safeReadFile {path} {
    set result {}
    catch {
        set handle [open $path r]
        set result [read $handle]
    }
    catch {close $handle}
    return [string trim $result]
}

#---------------------------------------------------------------------------
# getCPUMHz
#
#       Get the host CPU frequency in MHz.
#---------------------------------------------------------------------------

proc getCPUMHz {} {
    if { $::tcl_platform(platform) == "windows" } {
        # Windows records the CPU maximum frequency in the registry, in MHz.

        package require registry
        set hive HKEY_LOCAL_MACHINE
        set key $hive\\Hardware\\Description\\System\\CentralProcessor\\0
        if { [catch {registry get $key ~MHz} freqMHz] } {
            perr ""
            set freqMHz 0
        }
    } elseif { $::tcl_platform(os) == "Linux" } {
        set freqPath "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"
        set freqKHz [safeReadFile $freqPath]
        if { $freqKHz != "" } {
            # If the CPU supports speed-stepping, then the maximum speed will
            # be reported, in KHz, in cpuinfo_max_freq, and thus freqKHz will
            # be non-empty.

            set freqMHz [expr {$freqKHz / 1000}]
        } else {
            # If the CPU does not support speed-stepping, or if we have some
            # kind of problem getting the maximum frequency value, we just
            # grab the data out of /proc/cpuinfo.

            set cpuinfo [safeReadFile /proc/cpuinfo]
            if { ![regexp {cpu MHz\s+: (\d+)} $cpuinfo -> freqMHz] } {
                set freqMHz 0
            }
        }
    } else {
        # Solaris -- just punt, nobody cares.

        set freqMHz 0
    }
    return $freqMHz
}

#---------------------------------------------------------------------------
# cmConnectNewHost
#
#       This procedure transitions an agent from an idle, disconnected state
#       to connected to a host.
#       This procedure is used from agentRun.tcl.
#
# Results:
#       Connection to a new host is established.
#
# Side effects:
#       Once we get connected to cluster manager, we may start getting
#       requests from emakes to do builds.
#
#       Sets the opts(-cm) variable to the new host.
#
# Arguments:
#       newHost - the Host to connect to in the form of "host:port".
#       resource - the name of the cloud resource that started the host.
#
#---------------------------------------------------------------------------

proc cmConnectNewHost {newHost resource} {
    variable opts

    perr "INFO: Request to connect to $newHost with resource $resource"
    set opts(-cm) $newHost
    if { $resource != "" } {
        set opts(-resource) $resource
    }

    cmConnect
}

#---------------------------------------------------------------------------
# cmConnect
#
#       This procedure notifies the cluster manager of our existence.
#       If it can't connect to the cluster manager, it returns immediately
#       but arranges to retry periodically until eventually it can connect.
#
# Results:
#       None.
#
# Side effects:
#       Once we get connected to cluster manager, we may start getting
#       requests from emakes to do builds.
#
# Arguments:
#       None.  However, the contents of the global "opts" array determine
#       how we connect to a cluster manager.
#---------------------------------------------------------------------------

proc cmConnect {} {
    variable opts
    variable cmRetrying
    variable cmRetryCommand
    variable ports
    variable gAgentKey
    variable gLastCM
    variable gConnectedTo

    set cmRetryCommand 0

    if {$opts(-cm) == "" || [string match ":*" $opts(-cm)] } {
        # Empty cluster manager host name means don't try to connect all.

        set cmRetrying 0
        return "Info: No Host Defined $opts(-cm)"
    }


    # If we are connecting to a new CM, generate a new key.

    if { $opts(-cm) != $gLastCM } {
        set gAgentKey [expr {int(rand() * 1000000000)}]
        set gLastCM $opts(-cm)
    }

    # Rewrite the console port file with the latest key and cm info.  This
    # ensures the file is available even if it was deleted from some other
    # process.

    SaveConsolePortFile

    if {![catch {cm connect -cm $opts(-cm) \
                     -agentname $opts(-myname) \
                     -agenthost $opts(-myhost) \
                     -agentaddress $opts(-myip) \
                     -agentaddress1 $opts(-myip1) \
                     -emakeport [session port] \
                     -httpport $ports(cmControl) \
                     -agentkey $gAgentKey \
                     -version [getVersion] \
                     -mhz [getCPUMHz] \
                     -consoleport $opts(-consoleport) \
                     -localhostonly $opts(-local) \
                     -resource $opts(-resource) \
                     -cmsecurity $opts(-cmsecurity) \
                     -cmkeystore $opts(-cmkeystore) \
                     -cmallow $opts(-cmallow) \
                     -cacert $opts(-sslcacert) \
                     -keystore $opts(-sslkeystore) \
                     -allow $opts(-sslallow) \
                     -a2aport [session a2a port]} msg] } {

        perr "INFO: Connected to CM $opts(-cm)"
        set cmRetrying 0
        set cmRetryCommand 0

        # Enable the thread that sends heartbeat messages to the cluster
        # manager.

        cm heartbeat on
        set gLastCM      $opts(-cm)
        set gConnectedTo $opts(-cm)
        return "Connected agent $opts(-efsid) to $opts(-cm)"
    }

    if {$msg == "Already connected"} {
        set cmRetrying 0
        set cmRetryCommand 0
    }

    # Couldn't connect.  We will retry the connection after a short delay,
    # and we will log the failure the first several attempts.  Eventually
    # we will stop logging to avoid filling up the disk holding the log with
    # the same error message ad infinitum.

    if { $cmRetrying < 5 } {
        puts -nonewline stderr "WARNING: Unable to connect to CM: $msg"
        set detail [cm error]
        if { $detail != "" } {
            puts -nonewline stderr " ($detail)"
        }

        perr ""
        perr "WARNING: Retrying in $opts(-porttimeout) seconds..."
    }
    incr cmRetrying
    set cmRetryCommand [after [expr {int($opts(-porttimeout) * 1000)}] cmConnect]
}

#---------------------------------------------------------------------------
# switchCm
#
#       Disconnect from the current cluster manager, if any, and reconnect
#       to a new cluster manager.  If we can't immediately connect to the
#       new cluster manager this procedure will return an error, but it
#       will arrange to retry in the background.  This procedure is
#       typically invoked remotely using the "cluster" program.
#
# Results:
#       None.
#
# Side effects:
#       From now on, "newCm" will be our cluster manager.
#
# Arguments:
#       newCm -            Address of new cluster manager (host or
#                          host:port).
#---------------------------------------------------------------------------

proc switchCm {newCm} {
    variable opts
    variable cmRetrying

    set opts(-cm) $newCm
    if {$cmRetrying} {
        # We have already scheduled a reconnection attempt in the
        # future, so there's nothing else to do here.

        return
    }

    # Shut down the existing connection and open a new one.

    cm shutdown
    cmConnect
}

#---------------------------------------------------------------------------
# cmDisconnect
#
#       This procedure disconnects from the current CM.
#
# Results:
#       The agent will be in a running state, but not connected to a CM,
#       nor available for any work.
#
# Side effects:
#       If there is a pending connection retry attempt, it is cancelled.
#       This prevents a connection from occuring accidentally after this call.
#
# Arguments:
#       None
#
#---------------------------------------------------------------------------

proc cmDisconnect {} {
    variable opts
    variable cmRetrying
    variable cmRetryCommand
    variable gOriginalCm
    variable gConnectedTo

    # If we are in the process of retrying to connect to something,
    # then stop the process and return.

    if {$cmRetrying} {
        catch {after cancel $cmRetryCommand} msg
        perr "Halted retry attempt $cmRetrying for agent $opts(-efsid) to $opts(-cm)"
    }


    set $opts(-cm) gOriginalCm
    set cmRetrying 0
    set cmRetryCommand 0
    set gConnectedTo ""

    cm shutdown

    set msg "Disconnected agent $opts(-efsid) from $opts(-cm)"
    perr "INFO: $msg"
    return $msg
}

#---------------------------------------------------------------------------
# getLocalAgentXML
#
#       Returns the XML describing this agent for local emake connections.
#---------------------------------------------------------------------------

proc getLocalAgentXML {agentName agentId genId port a2aPort consolePort} {
    set xml ""
    append xml "<AgentList>\n"
    append xml "    <Agent>\n"
    append xml "        <AgentID>$agentId</AgentID>\n"
    append xml "        <GenerationID>$genId</GenerationID>\n"
    append xml "        <Name>$agentName</Name>\n"
    append xml "        <IPAddress>127.0.0.1</IPAddress>\n"
    append xml "        <Port>$port</Port>\n"
    append xml "        <A2APort>$a2aPort</A2APort>\n"
    append xml "        <ConsolePort>$consolePort</ConsolePort>\n"
    append xml "    </Agent>\n"
    append xml "</AgentList>\n"
    return $xml
}

#---------------------------------------------------------------------------
# localConnect
#
#       This procedure sets up the file with the agent information
#       needed by emake to connect to a local agent. The agent
#       information files live in an agent directory.  The Windows
#       directories are under C:\ECloud\ecagent and the Linux
#       directories are under /var/run/ecagent. The agent info files
#       are created with a .tmp name and them moved to .xml when they
#       are finished.
#
# Results:
#       None.
#
# Arguments:
#       None
#---------------------------------------------------------------------------

proc localConnect {} {
    variable opts

    set agentName $opts(-myname)

    # Build the path for the agent files used by emake to find the agents.

    if { $::tcl_platform(platform) == "windows" } {
        set agentDir [file join [getTopDirectory] "ecagent"]
    } else {
        set agentDir /var/run/ecagent
        file delete -force /var/run/ecagent/used
        file delete -force /var/run/ecagent/free
    }
    file mkdir $agentDir

    if { $::tcl_platform(platform) == "windows" } {

        # Need to make sure Windows file is writable by all.

    } else {
        file attributes $agentDir -permissions 0777
    }

    set agentInfoName "ecagent"
    append agentInfoName $::gAgentNumber
    set agentTempInfoName $agentInfoName
    append agentInfoName ".xml"
    append agentTempInfoName ".tmp"

    set ::gAgentTempFileName [file join $agentDir $agentTempInfoName]
    set ::gAgentFileName [file join $agentDir $agentInfoName]

    # Remove any leftovers.

    file delete $::gAgentFileName $::gAgentTempFileName
    
    cm agentname $agentName

    set xml [getLocalAgentXML \
                 $agentName \
                 -$::gAgentNumber \
                 [session genid] \
                 [session port] \
                 [session a2a port] \
                 $opts(-consoleport)]

    set retries 5
    while { $retries > 0 } {
        # The catch around the I/O is split in two parts, so we can always be
        # sure that we close the file handle, even if we get an error during
        # the writes.

        set result [catch {
            set f [open $::gAgentTempFileName "w"]
            puts $f $xml
        } err]
        catch {close $f}
        if { $result == 0 } {
            break
        }
        after 250
        incr retries -1
    }
    
    if { $retries == 0 } {
        # We exhausted our retries, so we really need to abort.

        perr \
            "ERROR: Unable to save agent file in $::gAgentTempFileName: $err"
        perr "ERROR: Exiting."
        exit 1
    }

    file rename -force $::gAgentTempFileName $::gAgentFileName
    cm agentfile $::gAgentFileName

    return
}

#---------------------------------------------------------------------------
# localLog
#
#       This procedure provides commands to manipulate the agent's
#       local on-disk log file.  It is typically invoked remotely
#       using the "cluster" program.
#
# Results:
#       Depends on the particular subcommand.
#
# Side effects:
#       Depends on the particular subcommand.
#
# Arguments:
#       option -                Specifies a particular subcommand to execute.
#       args -                  Zero or more additional arguments, depending
#                               the subcommand.
#---------------------------------------------------------------------------

proc localLog {option args} {
    switch -- $option {


        clear {
            # option clear
            #
            # Delete all of information to log, and start a fresh log.

            # All we have to do to truncate the log is to open it in
            # mode "w", which truncates the file.

            if {$args != ""} {
                error {wrong # args: should be "localLog clear"}
            }
            session logger clear
            return
        }

        tail {
            # option tail numLines
            #
            # Return the last "numLines" lines from the log.

            upvar #0 $::gCurrentConsole console
            if {[llength $args] != 1} {
                error {wrong # args: should be "localLog tail numLines"}
            }
            if {[session tracefile] == ""} {
                return
            }
            set numLines [lindex $args 0]

            # Read chunks of the file, starting at the end and moving
            # backwards until we have all the lines we need.  Then
            # return the tail of the last-read chunk plus all of the
            # earlier chunks (which are later in the file).

            set increment [expr {$numLines*10}]
            set data ""
            set position [file size [session tracefile]]
            set f [open [session tracefile]]
            while 1 {
                if {$position < $increment} {
                    set position 0
                } else {
                    set position [expr {$position - $increment}]
                }
                seek $f $position start
                set data [read $f]

                set splitData [split $data \n]
                set linesAvailable [expr [llength $splitData] - 1]
                if {$linesAvailable > $numLines} {
                    set data [join [lrange $splitData \
                            [expr {$linesAvailable-$numLines}] end] \n]
                    break
                }
                if {$position == 0} {
                    break
                }
            }
            close $f
            return $data
        }

        default {
            error "bad option \"$option\": must be clear or tail"
        }
    }
}

#---------------------------------------------------------------------------
# getVersion
#
#       Get the agent and EFS version in a string suitable for sending to the
#       cluster manager.
#
# Results:
#       The return value is the version information in a string.
#---------------------------------------------------------------------------

proc getVersion {} {
    return [format "Agent %s %d-bit (%s) EFS %s %d-bit (%s)" \
                [agent version] \
                [agent bitness] \
                [agent build] \
                [findEfs get version] \
                [findEfs get bitness] \
                [findEfs get build]]
}

#---------------------------------------------------------------------------
# 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.
#
# 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 or /x/y/z/arch/64/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 lastParent [file tail $parent]

    if { [file tail $dir] != "bin" } {
        # Last directory name is not "bin", so give up.

        return .
    }

    set parent     [file dirname $dir]
    set parentLast [file tail $parent]
    if { $parentLast == "64" } {
        # Parent directory name is "64", so go up one more level to get the
        # arch directory.

        set parent     [file dirname $parent]
        set parentLast [file tail $parent]
    }

    if {($parentLast == "i686_win32")
        || ($parentLast == "sun4u_SunOS")
        || ($parentLast == "i686_SunOS.5.10")
        || ($parentLast == "i686_Linux")} {
        # Arch directory is a recognized string, so we seem to be in a
        # canonical install location.  Top directory is the next dir up.

        return [file dirname $parent]
    }

    # Couldn't match the arch directory, so give up.

    return .
}

#-----------------------------------------------------------------------------
# InitializeCygwin
#
#       Start a cygwin shell in the background, to hopefully stave off
#       problems due to race conditions in the cygwin startup code.
#-----------------------------------------------------------------------------

proc InitializeCygwin {} {
    # Different versions of Cygwin use different registry locations to
    # save configuration data, which makes it tricky to reliably find
    # "sh.exe".  This code tries a few different spots, as well as some
    # common defaults.

    set candidates [list]
    catch {
        package require registry

        set wow6432node ""
        if { [agent bitness] == 64 } {
            set wow6432node "\\Wow6432Node"
        }

        # Old, pre-2.x location.

        set path HKEY_LOCAL_MACHINE
        append path \\SOFTWARE
        append path ${wow6432node}
        append path \\Cygnus\ Solutions
        append path \\Cygwin
        append path \\mounts\ v2
        append path \\/usr/bin
        if { ![catch {registry get $path native} bindir] } {
            lappend candidates $bindir/sh.exe
        }

        # Possible location for 32-bit Cygwin on a 64-bit machine.

        set path HKEY_LOCAL_MACHINE
        append path \\SOFTWARE
        append path ${wow6432node}
        append path \\Cygwin
        append path \\setup
        if { ![catch {registry get $path rootdir} rootdir] } {
            lappend candidates $rootdir/bin/sh.exe
        }

        # Possible location for 64-bit Cygwin on a 64-bit machine,
        # or 32-bit Cygwin on a 32-bit machine.

        set path HKEY_LOCAL_MACHINE
        append path \\SOFTWARE
        append path \\Cygwin
        append path \\setup
        if { ![catch {registry get $path rootdir} rootdir] } {
            lappend candidates $rootdir/bin/sh.exe
        }
    }

    # Default where almost everybody has Cygwin installed anyway.

    lappend candidates C:/Cygwin/bin/sh.exe

    # See if any of the candidates we've computed can actually be
    # started, returning the first one that succeeds.

    foreach sh $candidates {
        set sh [string map [list \\ /] $sh]
        if { ![catch {open "|$sh" r+} token] } {
            return $token
        }
    }
    error "Unable to find Cygwin sh.exe"
}

#-----------------------------------------------------------------------------
# CleanupCygwin
#
#       Cleanup the connection to cygwin previously created by a call to
#       InitializeCygwin.
#-----------------------------------------------------------------------------

proc CleanupCygwin {token} {
    catch {close $token}
}

#-----------------------------------------------------------------------------
# processArguments
#
#       Helper for command-line option processing, factored out to facilitate
#       reuse in ecconfig and the installer, which both want to be able to
#       validate runagent arguments without themselves knowing what arguments
#       runagent allows.
#-----------------------------------------------------------------------------

proc processArguments {argv} {
    variable opts
    variable OPTIONS
    variable usage

    set usage "[file tail $::argv0] \[OPTION...\]\n\n"
    catch {unset opts}

    foreach optionSpec [lsort -dictionary -index 0 $OPTIONS] {
        # Set the default values for each option.

        lassign $optionSpec option defaultValue description
        set opts($option) [subst $defaultValue]

        if { 0 != [string length $description] } {
            # Add this option to the usage message.

            append usage [format "  %-20s %s\n" $option $description]
        }
    }

    # Process command line arguments.  Most of the command-line args are
    # just assigned directly into the opts() array.  A handful, like -help,
    # are processed specially.

    foreach {flag value} $argv {
        switch -- $flag {
            -daemon {
                # -daemon was passed on the commandline.  It should have been
                # handled by the main() procedure in the agent's main.cpp.  We
                # don't do anything with it here.
            }
            -help {
                error ""
            }
            -version {
                error "Version [agent version] [agent build]"
            }
            default {
                # We differentiate good command-line args from bogus args by
                # checking for the existence of the flag in the opts() array:
                # good args are in the array already (see above); bad args
                # are not.

                if { [info exists opts($flag)] } {
                    set opts($flag) $value
                } else {
                    error "ERROR: Bad option: $flag"
                }
            }
        }
    }
}

#---------------------------------------------------------------------------
# main
#
#       This is the main entry point for the application.  It parses
#       command line arguments and launches other commands as necessary.
#
# Results:
#       None.
#
# Side effects:
#       None.
#
# Arguments:
#       argarray -              Name of the arguments array.
#---------------------------------------------------------------------------

proc main {argv} {
    variable opts
    variable ports
    variable gOriginalCm
    variable gAgentKey
    variable gConsoleFileName
    variable gConsoleFilePrefix
    variable usage

    if { [catch {processArguments $argv} err] } {
        if { [string length $err] } {
            perr $err
        }
        perr $usage
        _exit 1
    }
        
    if { $opts(-check) } {
        _exit 0
    }

    initClockSkew
    initSandbox

    # Change working directory to the top of the Electric Cloud installation,
    # if there is one; the locations of various files we'll create are based
    # on that.

    cd [getTopDirectory]

    # When running in containers it's difficult to know apriori what EFS id to
    # use for each agent.  Instead we use the EFS kernel driver, which is
    # shared by all the containers on a physical host, to automatically select
    # an EFS id for each agent.  We do so by opening the /dev/efsids file,
    # which atomically picks an available ID for this agent and reserves it as
    # long as that file handle remains open.

    if { $opts(-efsid) == "auto" } {
        if { $::tcl_platform(os) != "Linux" } {
            perr "ERROR: autonegotiation of EFS id not supported."
            _exit 1
        }

        if { [catch {libc open /dev/efsids O_RDONLY} idfd] } {
            perr "ERROR: unable to autonegotiate EFS id: $idfd"
            _exit 1
        }
        set opts(-efsid) [libc ioctl $idfd 0x65636c77]
    }

    set gOriginalCm opts(-cm)

    if { $::tcl_platform(platform) == "windows" } {
        set ::gAgentNumber $opts(-efsid)

        # EC-11969: set MSBUILDDISABLENODEREUSE=1 to prevent msbuild 4
        # hanging around after a job completes.

        set ::env(MSBUILDDISABLENODEREUSE) "1"
    } else {
        set ::gAgentNumber [expr {$opts(-efsid) + 1}]
    }

    efs use $opts(-efsid)

    set ::prompt "[info hostname]@[lindex [split $opts(-cm) :] 0]: "

    # Extra platform-specific initialization (must happen before I/O
    # channels get reopened, since it closes all existing channels).

    if {$::tcl_platform(platform) == "windows"} {
        #temprarily disable Superfetch and FileInfo as this service
        #is conflict with EFS driver.
        catch {service stop sysmain}
        catch {service stop fileinfo}
        # On Windows, must make sure the EFS device driver is loaded.
        # Ignore errors, which can happen if the service is already loaded.

        catch {service start ElectricFS} message

        # Disable pop-up windows that could leave a node hung.

        popup off

        # Tweak opts(-matchuser) to give more detailed information when we
        # print the arguments in ecagentN.log.
        if { $opts(-matchuser) != 0 } {
            set currentUser [testwin currentuser]
            findEfs identifyingsid [lindex $currentUser 1]
            set opts(-matchuser) "$opts(-matchuser) \[[lindex $currentUser 0] = [lindex $currentUser 1]\]"
        } else {
            findEfs identifyingsid {}
            set opts(-matchuser) "0 \[No CSRSS/svchost/OLE support\]"
        }

        findEfs set fastIoPossible 0
    } else {
        # Unix-specific initialization

        # Specify the location of the execserver program so the agent can
        # find it.

        catch {
            set dirname [file dirname [info nameofexecutable]]
            agentexec path [file join $dirname execserver]
        }
    }

    # Reopen the standard channels so that there is no standard input,
    # and standard output and standard error both go the log file.
    # Before closing the existing channels make sure we can actually
    # open the log file.

    if {$opts(-consolelogfile) == ""} {
        if { $::tcl_platform(platform) == "windows" } {
            set opts(-consolelogfile) console$::gAgentNumber.log
        } else {
            set opts(-consolelogfile) /var/log/console$::gAgentNumber.log
        }
    } else {
        set opts(-consolelogfile) \
            [string map [list %i $::gAgentNumber] $opts(-consolelogfile)]
    }
    if {[catch {close [open $opts(-consolelogfile) {WRONLY APPEND CREAT}]}]} {
        perr "Can't open log file \"$opts(-consolelogfile)\""
        exit 1
    }

    if { $opts(-redirect) } {
        if {$::tcl_platform(platform) != "windows"} {
            # (Windows has no /dev/null, so stdin redirection only
            # happens on Unix).

            catch {close stdin}
            open /dev/null r+                                  ;# new stdin
        }
        catch {close stdout}
        open $opts(-consolelogfile) {WRONLY APPEND CREAT}      ;# new stdout
        fconfigure stdout -buffering line
        catch {close stderr}
        open $opts(-consolelogfile) {WRONLY APPEND CREAT}      ;# new stderr
        fconfigure stderr -buffering line
    }

    # Set up debugging output now based upon command line arguments;
    # runagent.local can then modify this this setting as desired.

    if { $opts(-debug) > 1 } {
        lappend opts(-trace) all
    } elseif { $opts(-debug) > 0 } {
        lappend opts(-trace) log
    }
    eval session trace $opts(-trace)

    # Check for a runagent.local script.  If present, source it.  This provides
    # an upgrade-safe mechanism for customers to tweak runagent behavior and
    # setup.

    set runagentLocal [file join [file dirname [info script]] runagent.local]
    set runagentLocalState "not found"
    if { [file exists $runagentLocal] } {
        set checksum [string repeat 0 32]
        if { ![catch {open $runagentLocal r} runagentLocalFD] } {
            set checksum [system md5 [read $runagentLocalFD]]
            close $runagentLocalFD
        }
        if { [catch {uplevel \#0 source $runagentLocal} runagentLocalError] } {
            perr "WARNING: error in runagent.local: $runagentLocalError"
            set runagentLocalState "loaded with errors (md5: $checksum)"
        } else {
            set runagentLocalState "loaded successfully (md5: $checksum)"
        }
    }

    # If the console port was not specified explicitly,
    # supply a default value based on efsid.

    if { $opts(-consoleport) == "" } {
        set opts(-consoleport) [consolePort $opts(-efsid)]
    }

    # But disable the agent console port completely if we want authentication.

    if { [string length $opts(-emakesecurity)] != 0
         && ! [string equal "none" $opts(-emakesecurity)] } {
        set opts(-consoleport) 0

        if { [string equal $opts(-emakesecurity) "ssl"] } {
            if { [catch {ecsec ssl                           \
                             -cacert $opts(-sslcacert)       \
                             -keystore $opts(-sslkeystore)   \
                             -allow $opts(-sslallow)} err] } {
                perr "ERROR: SSL configuration failure: $err"
                _exit 1
            }
        }
    }

    # set the console port file name

    if { $::tcl_platform(platform) == "windows" } {
        set gConsoleFileName [file join [getTopDirectory] $gConsoleFilePrefix$opts(-efsid).port]
    } else {
        set gConsoleFileName /var/run/$gConsoleFilePrefix$opts(-efsid).port
    }

    # If the -fixedports option was specified, use the "classic" agent port
    # values.  These are specified by the procs defined at the top of this
    # file, but those procedures may be replaced by runagent.local, which is
    # why we use those procedures here, after the sourcing of that script.

    array set ports {emake 0 a2a 0 cmControl 0}
    if { $opts(-fixedports) != 0 } {
        foreach name {emake a2a cmControl} {
            if { [catch {set ports($name) [${name}Port $opts(-efsid)]} err] } {
                set message "ERROR: Failed to compute default value for"
                append message " $name port for -efsid $opts(-efsid): $err"
                perr $message
                _exit 1
            }
        }
    }

    # If the host name was not explicitly specified,
    # then use the unqualified host name:

    if { 0 == [string length $opts(-myhost)] } {
        set opts(-myhost) [hostname]
    }

    # If the agent name was not explicitly specified,
    # then combine the host name and agent number.

    if { 0 == [string length $opts(-myname)] } {
        set opts(-myname) $opts(-myhost)-$::gAgentNumber
    }

    # Output a startup banner.

    set date [clock format [clock seconds] -format {%a %b %d %Y %H:%M:%S}]
    perr "\n***-------------------------------------------------------"
    perr "*** Agent started at    [format %s $date]"
    unset opts(-help)
    unset opts(-version)
    foreach el [lsort [array names opts]] {
        perr "*** [format %-20s $el][format %s $opts($el)]"
    }
    foreach name [lsort [array names ports]] {
        set pn $ports($name)
        if { $pn == 0 } { append pn "    # meaning dynamic" }
        perr "*** [format %-20s ${name}Port][format %s $pn]"
    }
    perr "***-------------------------------------------------------\n"

    perr "INFO: Agent [agent version] [agent build]"
    perr "INFO: EFS   [findEfs get version] [findEfs get build]"
    perr "INFO: runagent.local was $runagentLocalState"
    if { $::tcl_platform(os) == "Linux" } {
        perr "INFO: bindmounts are {[sandbox bindmounts]}"
    }

    # Set up the temporary directory variables if an alternate location
    # was specified above.

    if {$opts(-tempdir) != ""} {
        if {![file exists $opts(-tempdir)]} {
            error "Path specified for agent tempdir does not exist"
        }
        set tempDir $opts(-tempdir)
    } else {
        set tempDir [system tempdir]
    }

    set ::env(TMP) $tempDir
    set ::env(TEMP) $tempDir
    set ::env(TMPDIR) $tempDir

    # Do platform specific startup.

    if { $::tcl_platform(platform) == "windows" } {
        # Optionally switch to the user visible window station.  See the
        # description of debugPopups above for details.

        if {$::debugPopups \
                && [catch {windowstation set WinSta0
                    windowstation setdesktop Default} message]} {
            perr "Setting window station to WinSta0/Default:  $message"
        }

        # Set the idle command timeout value.
        agentexec timeout $::commandTimeout

        if { $opts(-efsid) == 1 } {
            # Start up a Cygwin shell in the background.  This should help
            # mitigate startup races in the Cygwin library.

            if { ![catch {InitializeCygwin} err] } {
                set cygtoken $err
            }
        }
    }

    # Create our console server socket now, before we do other setup.  If we
    # are unable to create the console server for any reason, we're going to
    # bail out entirely, and it's easier to do that if we don't have to tear
    # down other state.
    #
    # But do NOT create the console port if that feature was disabled.

    set msg ""
    set port $opts(-consoleport)
    if { $port != 0
         && [catch {socket -server RemoteConsoleStart $port} msg] } {
        perr "WARNING: Unable to open console port $port: $msg"
        perr "WARNING: Retrying in $opts(-porttimeout) seconds..."
        after [expr {int($opts(-porttimeout) * 1000)}]

        # Try again, but give up if it doesn't work this time.

        if { [catch {socket -server RemoteConsoleStart $port} msg] } {
            perr "ERROR: Unable to open console port after retry: $msg"
            perr "ERROR: Exiting."
            _exit 1
        }

        set port [lindex [fconfigure $msg -sockname] end]
        perr "INFO: Opened console port $port after retry"

        # Now that we have created the console server, snag the port number
        # (which may have been dynamically assigned) and save it for reporting
        # to the CM.

        set opts(-consoleport) [lindex [fconfigure $msg -sockname] end]
    }

    # Create a key for talking to agents that have not yet connected to a host.

    expr {srand([clock seconds])}

    # Read the current console port file to get the past CM connection.

    if { [catch {ReadConsolePortFile} message] } {
        perr "ERROR: Unable to read $gConsoleFileName: $msg"
        perr "ERROR: Exiting."
        _exit 1
    }

    # Write the console file back out to make sure we have saved
    # our actual port number -- in case it changed.

    if { [catch {SaveConsolePortFile} msg] } {
        perr "ERROR: Unable to save port number in $gConsoleFileName: $msg"
        perr "ERROR: Exiting."
        _exit 1
    }

    # Establish our connection to the ecagent.state repository.  This indicates
    # to other agents that this agent is up and will be responsible for
    # cleaning up resources used by it, so other agents need not do so.
    #
    # EC-10604: if the repository happens to be on an NFS volume it can cause
    # problems for the agents.  Therefore on Linux/Solaris we put the 
    # repository in /var/lib/ecagent.

    set repositoryDir "."
    if { $::tcl_platform(platform) != "windows" } {
        set repositoryDir /var/lib/ecagent
        if { [catch {file mkdir $repositoryDir} err] } {
            perr "ERROR: Unable to create repository directory"
            perr "ERROR: Tried to make $repositoryDir: $err"
            perr "ERROR: Exiting."
            _exit 1
        }
    }

    set ::repository [repository create $repositoryDir $::gAgentNumber]
    repository setinstance $::repository

    # We have to force cleanup of mountpoints created by a previous instance
    # of this agent -- other agents won't be able to do it because we have
    # already connected to the repository, so our agent file is locked,
    # preventing other agents from cleaning up mounts that seem to be used
    # use.  One way to force cleanup is to connect to EFS and invoke
    # [efs setroots], which ultimately calls Mount::cleanup().

    set retries 3
    while { $retries && [catch {findEfs setroots [efs mountpoint] 0 1} msg] } {
        # On Windows during system startup, sometimes things are a little
        # sluggish -- too many agents are trying to do this cleanup all at
        # once.  If setroots fails, wait a little bit and try again.  Note that
        # there is ALREADY a retry inside setroots, so if we get here, we may
        # as well wait for a longer interval before trying again.

        incr retries -1
        after 1000
    }

    # Force a connection to the EFS now, before starting up the session.  This
    # ensures that the /efs mountpoint exists before we try to create the
    # Sandbox on Unix.  Otherwise, there's a race between the session thread
    # creating the Sandbox and the main thread creating the /efs mountpoint,
    # which can lead to /efs not appearing inside the Sandbox.
    #
    # Since we're connecting to the EFS now anyway, we take this opportunity
    # to verify that the agent and EFS are speaking the same protocol version
    # (see EC-556).

    findEfs get test
    if { [catch {findEfs get protocolVersion} efsProtocolVersion] } {
        perr "WARNING: unable to verify agent/EFS protocol version"
    } elseif { $efsProtocolVersion != [efs protocolversion] } {
        perr "ERROR: agent/EFS protocol mismatch"
        perr "ERROR: agent protocol version [efs protocolversion]"
        perr "ERROR: EFS protocol version $efsProtocolVersion"
        perr "ERROR: Exiting."
        $::repository delete
        _exit 1
    }

    # Set up the session.  If there's a failure to start up the session, we'll
    # retry once, after a short wait.  This protects us against the situation
    # where the user has shut down the agent and is trying to restart it, but
    # the OS has not completely reaped the ports that were in use by the agent.

    set startCmd {session start \
                      -port $ports(emake) \
                      -a2aport $ports(a2a) \
                      -local $opts(-local)}
    if { [catch $startCmd message] } {
        perr "WARNING: Unable to start session: $message"
        perr "WARNING: Retrying in $opts(-porttimeout) seconds..."
        after [expr {int($opts(-porttimeout) * 1000)}]

        # Try again, but give up if it doesn't work this time.

        if { [catch $startCmd message] } {
            perr "ERROR: Unable to start session after retry: $message"
            perr "ERROR: Exiting."
            _exit 1
        }

        perr "INFO: Started session after retry."
    }

    set sessionPort [session port]
    set a2aPort [session a2a port]
    perr "INFO: Listening for emake on $sessionPort, A2A on $a2aPort"

    # Open the diskcache manager port file and save the port information in
    # the agent session so it will know where to connect for diskcache
    # related access.  We need a timed loop around it because on windows, the
    # ecagent service starts the diskcache and agent processes at the same
    # time, leading to a race.  Sometimes the agents finish startup before
    # the diskcache and can't find the diskcache portfile.

    for {set total 0} {1} {after 50 ; incr total 50} {
        set portfileText [safeReadFile $opts(-diskcacheportfile)]
        set port ""
        set tclport ""
        foreach {port tclport} [split $portfileText \n] {break}
        if { [string is integer -strict $port]
             && [string is integer -strict $tclport] } {
            diskcache port $port
            diskcache tclport $tclport
            break
        } elseif { $total >= 300000 } {
            perr "ERROR: Couldn't open diskcache manager ports file at "
            perr "ERROR: $opts(-diskcacheportfile) "
            perr "ERROR: after 5 minutes, exiting."
            _exit 1
        }
    }

    # Find the base directory containing the ecloud executables, then let the
    # session know what the directory is.

    set bindir [file dirname [info nameofexecutable]]
    if { [string equal [file tail [file dirname $bindir]] "64"] } {
        # We're running a 64-bit version of the agent on Linux or Windows.
        # Strip off the "64" directory so that the agent gets the real base
        # bin directory.

        set bindir [file join [file dirname [file dirname $bindir]] bin]
    }
    session ecloudbindir $bindir

    # Send session tracing output to the same file, so it will be nicely
    # (hopefully) interleaved with any error output.

    if { $opts(-logfile) != "" } {
        session logger filename [file join [pwd] $opts(-logfile)]
    }

    # Apply any truncation parameter settings.  First, get the current
    # settings, then override those with user-specified values, if any.

    set updateTruncationParams false
    foreach {threshold length} [session exec truncationparams] { break }
    if { [info exists ::TruncationThreshold] } {
        set threshold $::TruncationThreshold
        set updateTruncationParams true
    }
    if { [info exists ::TruncationLength] } {
        set length $::TruncationLength
        set updateTruncationParams true
    }
    if { $updateTruncationParams } {
        if { [catch {session exec truncationparams $threshold $length} err] } {
            perr "WARNING: failed to change truncation parameters: $err"
        }
    }

    # Connect to the cluster manager - if one was provided

    cmConnect

    # Create the local agent file for Buddy Build.

    localConnect

    # Note that startup has completed.

    perr "INFO: Finished startup; agent pid [pid]"

    # Wait for a signal telling us to shutdown.

    update
    if { $::signalled == "" } {
        vwait ::signalled
    }

    set date [clock format [clock seconds] -format {%a %b %d %Y %H:%M:%S}]

    perr "INFO: Received signal '$::signalled', shutting down at $date"

    # Cleanup.  First the cluster manager connection so there's no chance of
    # us getting assigned to another build.

    perr "INFO: Closing cluster manager connection."
    cm shutdown

    # Remove the agent file
    file delete $::gAgentFileName

    # Next the agent console and any active connections.

    catch {exitCleanup}

    # Next the session so any currently running build gets shutdown.

    perr "INFO: Closing emake connection."
    session abort wait

    # Next the repository.

    perr "INFO: Releasing resources."
    $::repository delete

    catch {CleanupCygwin $cygtoken}

    # Print one last message before exiting.

    set date [clock format [clock seconds] -format {%a %b %d %Y %H:%M:%S}]

    perr "INFO: Exiting at $date."
}

#---------------------------------------------------------------------------
# bgerror
#
#       This procedure is invoked automatically by Tcl when errors occur
#       in the background where there is no obvious place to print a message.
#
# Results:
#       None.
#
# Side effects:
#       A stack trace for the error gets printed on standard output.
#
# Arguments:
#       Ignored.
#---------------------------------------------------------------------------

proc bgerror args {
    puts $::errorInfo
}

if { [namespace current] == "::" } {
    set starttime [clock seconds]
    if { ![info exists ::ECLOUD_TEST_MODE] || !$::ECLOUD_TEST_MODE } {
        main $argv
    }
}
