implment ping server

This commit is contained in:
Adem Baccara
2025-08-26 18:08:13 +01:00
parent fea1fb5764
commit 9a6b8f4702
9 changed files with 165 additions and 47 deletions
+76 -4
View File
@@ -63,6 +63,12 @@ func (t *tui) handleGlobalKeys(event *tcell.EventKey) *tcell.EventKey {
case 'c':
t.handleCopyCommand()
return nil
case 'g':
t.handlePingSelected()
return nil
case 'r':
t.handleRefreshBackground()
return nil
case 't':
t.handleTagsEdit()
return nil
@@ -198,10 +204,66 @@ func (t *tui) handleHelpShow() {
t.showHelpModal()
}
func (t *tui) handlePingSelected() {
if server, ok := t.serverList.GetSelectedServer(); ok {
alias := server.Alias
t.showStatusTemp(fmt.Sprintf("Pinging %s…", alias))
go func() {
up, dur, err := t.serverService.Ping(server)
t.app.QueueUpdateDraw(func() {
if err != nil {
t.showStatusTempColor(fmt.Sprintf("Ping %s: DOWN (%v)", alias, err), "#FF6B6B")
return
}
if up {
t.showStatusTempColor(fmt.Sprintf("Ping %s: UP (%s)", alias, dur), "#A0FFA0")
} else {
t.showStatusTempColor(fmt.Sprintf("Ping %s: DOWN", alias), "#FF6B6B")
}
})
}()
}
}
func (t *tui) handleModalClose() {
t.returnToMain()
}
// handleRefreshBackground refreshes the server list in the background without leaving the current screen.
// It preserves the current search query and selection, shows transient status, and avoids concurrent runs.
func (t *tui) handleRefreshBackground() {
currentIdx := t.serverList.GetCurrentItem()
query := ""
if t.searchVisible {
query = t.searchBar.InputField.GetText()
}
t.showStatusTemp("Refreshing…")
go func(prevIdx int, q string) {
servers, err := t.serverService.ListServers(q)
if err != nil {
t.app.QueueUpdateDraw(func() {
t.showStatusTempColor(fmt.Sprintf("Refresh failed: %v", err), "#FF6B6B")
})
return
}
sortServersForUI(servers, t.sortMode)
t.app.QueueUpdateDraw(func() {
t.serverList.UpdateServers(servers)
// Try to restore selection if still valid
if prevIdx >= 0 && prevIdx < t.serverList.List.GetItemCount() {
t.serverList.SetCurrentItem(prevIdx)
if srv, ok := t.serverList.GetSelectedServer(); ok {
t.details.UpdateServer(srv)
}
}
t.showStatusTemp(fmt.Sprintf("Refreshed %d servers", len(servers)))
})
}(currentIdx, query)
}
// =============================================================================
// UI Display Functions (show UI elements/modals)
// =============================================================================
@@ -293,13 +355,15 @@ func (t *tui) showHelpModal() {
" ↑/↓ Navigate\n" +
" Enter SSH connect \n" +
" c Copy SSH command \n" +
" g Ping server (TCP to SSH port)\n" +
" r Refresh list (background)\n" +
" a Add server \n" +
" e Edit server \n" +
" t Edit tags (quick)\n" +
" d Delete entry \n" +
" p Pin/Unpin server \n" +
" s Sort field (Alias / Last SSH)\n" +
" Shift+S Reverse order (↑/↓)\n" +
" s Switch sort field (Alias Last SSH), keep direction\n" +
" Shift+S Toggle sort direction (↑/↓) for current field\n" +
" / Focus search\n" +
" q Quit\n" +
" ? Help\n"
@@ -344,12 +408,20 @@ func (t *tui) returnToMain() {
t.app.SetRoot(t.root, true)
}
// showStatusTemp displays a temporary message in the status bar and then restores the default text.
// showStatusTemp displays a temporary message in the status bar (default green) and then restores the default text.
func (t *tui) showStatusTemp(msg string) {
if t.statusBar == nil {
return
}
t.statusBar.SetText("[#A0FFA0]" + msg + "[-]")
t.showStatusTempColor(msg, "#A0FFA0")
}
// showStatusTempColor displays a temporary colored message in the status bar and restores default text after 2s.
func (t *tui) showStatusTempColor(msg string, color string) {
if t.statusBar == nil {
return
}
t.statusBar.SetText("[" + color + "]" + msg + "[-]")
time.AfterFunc(2*time.Second, func() {
if t.app != nil {
t.app.QueueUpdateDraw(func() {
+1 -1
View File
@@ -22,6 +22,6 @@ import (
func NewHintBar() *tview.TextView {
hint := tview.NewTextView().SetDynamicColors(true)
hint.SetBackgroundColor(tcell.Color233)
hint.SetText("[#BBBBBB]Press [::b]/[-:-:b] to search… • ↑↓ Navigate • Enter SSH • c Copy SSH • a Add • e Edit • t Tags • d Delete • p Pin/Unpin • s Sort • ? Help[-]")
hint.SetText("[#BBBBBB]Press [::b]/[-:-:b] to search… • ↑↓ Navigate • Enter SSH • c Copy SSH • g Ping • r Refresh • a Add • e Edit • t Tags • d Delete • p Pin/Unpin • s Sort • ? Help[-]")
return hint
}
+1 -1
View File
@@ -71,7 +71,7 @@ func (sd *ServerDetails) UpdateServer(server domain.Server) {
}
tagsText := renderTagChips(server.Tags)
text := fmt.Sprintf(
"[::b]%s[-]\n\nHost: [white]%s[-]\nUser: [white]%s[-]\nPort: [white]%d[-]\nKey: [white]%s[-]\nTags: %s\nPinned: [white]%s[-]\nLast SSH: %s\nSSH Count: [white]%d[-]\n\n[::b]Commands:[-]\n Enter: SSH connect\n c: Copy SSH command\n a: Add new server\n e: Edit entry\n t: Edit tags\n d: Delete entry\n p: Pin/Unpin",
"[::b]%s[-]\n\nHost: [white]%s[-]\nUser: [white]%s[-]\nPort: [white]%d[-]\nKey: [white]%s[-]\nTags: %s\nPinned: [white]%s[-]\nLast SSH: %s\nSSH Count: [white]%d[-]\n\n[::b]Commands:[-]\n Enter: SSH connect\n c: Copy SSH command\n g: Ping server\n r: Refresh list\n a: Add new server\n e: Edit entry\n t: Edit tags\n d: Delete entry\n p: Pin/Unpin",
server.Alias, server.Host, server.User, server.Port,
serverKey, tagsText, pinnedStr,
lastSeen, server.SSHCount)
-1
View File
@@ -175,7 +175,6 @@ func (sf *ServerForm) dataToServer(data ServerFormData) domain.Server {
// validateServerForm returns an error message string if validation fails; empty string means valid.
func validateServerForm(data ServerFormData) string {
alias := data.Alias
if alias == "" {
return "Alias is required"
+1 -1
View File
@@ -20,7 +20,7 @@ import (
)
func DefaultStatusText() string {
return "[white]↑↓[-] Navigate • [white]Enter[-] SSH • [white]c[-] Copy SSH • [white]a[-] Add • [white]e[-] Edit • [white]d[-] Delete • [white]p[-] Pin/Unpin • [white]/[-] Search • [white]q[-] Quit • [white]?[-] Help"
return "[white]↑↓[-] Navigate • [white]Enter[-] SSH • [white]c[-] Copy SSH • [white]a[-] Add • [white]e[-] Edit • [white]g[-] Ping • [white]d[-] Delete • [white]p[-] Pin/Unpin • [white]/[-] Search • [white]q[-] Quit • [white]?[-] Help"
}
func NewStatusBar() *tview.TextView {
+6 -1
View File
@@ -14,7 +14,11 @@
package ports
import "github.com/Adembc/lazyssh/internal/core/domain"
import (
"time"
"github.com/Adembc/lazyssh/internal/core/domain"
)
type ServerService interface {
ListServers(query string) ([]domain.Server, error)
@@ -23,4 +27,5 @@ type ServerService interface {
DeleteServer(server domain.Server) error
SetPinned(alias string, pinned bool) error
SSH(alias string) error
Ping(server domain.Server) (bool, time.Duration, error)
}
+72
View File
@@ -15,13 +15,16 @@
package services
import (
"bufio"
"fmt"
"net"
"os"
"os/exec"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/Adembc/lazyssh/internal/core/domain"
"github.com/Adembc/lazyssh/internal/core/ports"
@@ -164,3 +167,72 @@ func (s *serverService) SSH(alias string) error {
s.logger.Infow("ssh end", "alias", alias)
return nil
}
// Ping checks if the server is reachable on its SSH port.
func (s *serverService) Ping(server domain.Server) (bool, time.Duration, error) {
start := time.Now()
host, port, ok := resolveSSHDestination(server.Alias)
if !ok {
host = strings.TrimSpace(server.Host)
if host == "" {
host = server.Alias
}
if server.Port > 0 {
port = server.Port
} else {
port = 22
}
}
addr := net.JoinHostPort(host, fmt.Sprintf("%d", port))
dialer := net.Dialer{Timeout: 3 * time.Second}
conn, err := dialer.Dial("tcp", addr)
if err != nil {
return false, time.Since(start), err
}
_ = conn.Close()
return true, time.Since(start), nil
}
// resolveSSHDestination uses `ssh -G <alias>` to extract HostName and Port from the user's SSH config.
// Returns host, port, ok where ok=false if resolution failed.
func resolveSSHDestination(alias string) (string, int, bool) {
alias = strings.TrimSpace(alias)
if alias == "" {
return "", 0, false
}
cmd := exec.Command("ssh", "-G", alias)
out, err := cmd.Output()
if err != nil {
return "", 0, false
}
host := ""
port := 0
scanner := bufio.NewScanner(strings.NewReader(string(out)))
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "hostname ") {
parts := strings.Fields(line)
if len(parts) >= 2 {
host = parts[1]
}
}
if strings.HasPrefix(line, "port ") {
parts := strings.Fields(line)
if len(parts) >= 2 {
if p, err := strconv.Atoi(parts[1]); err == nil {
port = p
}
}
}
}
if host == "" {
host = alias
}
if port == 0 {
port = 22
}
return host, port, true
}