func()

in fast-build-update-tool/internal/tools/ssh_command_runner.go [46:87]


func (s *SSHCommandRunner) Run(ctx context.Context, remotePublicKey ssh.PublicKey) error {
	// Set up the SSH connection to the remote instance
	client, err := ssh.Dial("tcp", net.JoinHostPort(s.instanceIpAddress, fmt.Sprintf("%d", s.sshPort)), &ssh.ClientConfig{
		User:              s.remoteUserName,
		HostKeyCallback:   ssh.FixedHostKey(remotePublicKey),
		HostKeyAlgorithms: []string{remotePublicKey.Type()},
		Auth: []ssh.AuthMethod{
			ssh.PublicKeys(s.sshKey),
		},
	})
	if err != nil {
		return fmt.Errorf("error dialing ssh connection: %w", err)
	}
	defer client.Close()

	session, err := client.NewSession()
	if err != nil {
		return fmt.Errorf("error starting ssh session: %w", err)
	}
	defer session.Close()

	logFilePath := config.GetLogPathForFile(fmt.Sprintf("%s-ssh-command.log", s.instanceId))
	// Set up a log file so we log out any remote output we get from the instance
	logFile, err := os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE, 0666)
	if err != nil {
		return fmt.Errorf("error creating log file for ssh command runner: %w", err)
	}
	defer logFile.Close()

	session.Stdout = logFile
	session.Stderr = config.NewErrorLogger("SSHCommandRunner")

	slog.Debug("running command on instance", "command", s.updateScriptCommand)

	// Run the actual update command on the instance
	err = session.Run(s.updateScriptCommand)
	if err != nil {
		return fmt.Errorf("error running server update script: %w; Check logs in %s for more information", err, logFilePath)
	}

	return nil
}