mirror of
https://github.com/wavetermdev/backup.git
synced 2026-08-05 13:57:07 -07:00
use log.Printf, ensure sc home dir
This commit is contained in:
+23
-19
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
@@ -69,7 +70,7 @@ func removeWSStateAfterTimeout(clientId string, connectTime time.Time, waitDurat
|
||||
func HandleWs(w http.ResponseWriter, r *http.Request) {
|
||||
shell, err := wsshell.StartWS(w, r)
|
||||
if err != nil {
|
||||
fmt.Printf("WebSocket Upgrade Failed %T: %v\n", w, err)
|
||||
log.Printf("WebSocket Upgrade Failed %T: %v\n", w, err)
|
||||
return
|
||||
}
|
||||
defer shell.Conn.Close()
|
||||
@@ -91,7 +92,7 @@ func HandleWs(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
removeWSStateAfterTimeout(clientId, stateConnectTime, WSStateReconnectTime)
|
||||
}()
|
||||
fmt.Printf("WebSocket opened %s %s\n", state.ClientId, shell.RemoteAddr)
|
||||
log.Printf("WebSocket opened %s %s\n", state.ClientId, shell.RemoteAddr)
|
||||
state.RunWSRead()
|
||||
}
|
||||
|
||||
@@ -313,7 +314,7 @@ func HandleRunCommand(w http.ResponseWriter, r *http.Request) {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
fmt.Printf("[error] in run-command: %v\n", r)
|
||||
log.Printf("[error] in run-command: %v\n", r)
|
||||
debug.PrintStack()
|
||||
WriteJsonError(w, fmt.Errorf("panic: %v", r))
|
||||
return
|
||||
@@ -354,10 +355,10 @@ func runWebSocketServer() {
|
||||
Handler: gr,
|
||||
}
|
||||
server.SetKeepAlivesEnabled(false)
|
||||
fmt.Printf("Running websocket server on %s\n", WebSocketServerAddr)
|
||||
log.Printf("Running websocket server on %s\n", WebSocketServerAddr)
|
||||
err := server.ListenAndServe()
|
||||
if err != nil {
|
||||
fmt.Printf("[error] trying to run websocket server: %v\n", err)
|
||||
log.Printf("[error] trying to run websocket server: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -371,7 +372,7 @@ func stdinReadWatch() {
|
||||
for {
|
||||
_, err := os.Stdin.Read(buf)
|
||||
if err != nil {
|
||||
fmt.Printf("stdin closed/error, shutting down: %v\n", err)
|
||||
log.Printf("stdin closed/error, shutting down: %v\n", err)
|
||||
time.Sleep(1 * time.Second)
|
||||
syscall.Kill(syscall.Getpid(), syscall.SIGINT)
|
||||
}
|
||||
@@ -380,57 +381,60 @@ func stdinReadWatch() {
|
||||
|
||||
func main() {
|
||||
if len(os.Args) >= 2 && os.Args[1] == "--test" {
|
||||
fmt.Printf("running test fn\n")
|
||||
log.Printf("running test fn\n")
|
||||
err := test()
|
||||
if err != nil {
|
||||
fmt.Printf("[error] %v\n", err)
|
||||
log.Printf("[error] %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
scHomeDir := scbase.GetScHomeDir()
|
||||
log.Printf("[scripthaus] homedir = %q\n", scHomeDir)
|
||||
|
||||
scLock, err := scbase.AcquireSCLock()
|
||||
if err != nil || scLock == nil {
|
||||
fmt.Printf("[error] cannot acquire sh2 lock: %v\n", err)
|
||||
log.Printf("[error] cannot acquire sh2 lock: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(os.Args) >= 2 && strings.HasPrefix(os.Args[1], "--migrate") {
|
||||
err := sstore.MigrateCommandOpts(os.Args[1:])
|
||||
if err != nil {
|
||||
fmt.Printf("[error] migrate cmd: %v\n", err)
|
||||
log.Printf("[error] migrate cmd: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
err = sstore.TryMigrateUp()
|
||||
if err != nil {
|
||||
fmt.Printf("[error] migrate up: %v\n", err)
|
||||
log.Printf("[error] migrate up: %v\n", err)
|
||||
return
|
||||
}
|
||||
clientData, err := sstore.EnsureClientData(context.Background())
|
||||
if err != nil {
|
||||
fmt.Printf("[error] ensuring client data: %v\n", err)
|
||||
log.Printf("[error] ensuring client data: %v\n", err)
|
||||
return
|
||||
}
|
||||
fmt.Printf("userid = %s\n", clientData.UserId)
|
||||
log.Printf("userid = %s\n", clientData.UserId)
|
||||
err = sstore.EnsureLocalRemote(context.Background())
|
||||
if err != nil {
|
||||
fmt.Printf("[error] ensuring local remote: %v\n", err)
|
||||
log.Printf("[error] ensuring local remote: %v\n", err)
|
||||
return
|
||||
}
|
||||
_, err = sstore.EnsureDefaultSession(context.Background())
|
||||
if err != nil {
|
||||
fmt.Printf("[error] ensuring default session: %v\n", err)
|
||||
log.Printf("[error] ensuring default session: %v\n", err)
|
||||
return
|
||||
}
|
||||
err = remote.LoadRemotes(context.Background())
|
||||
if err != nil {
|
||||
fmt.Printf("[error] loading remotes: %v\n", err)
|
||||
log.Printf("[error] loading remotes: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
err = sstore.HangupAllRunningCmds(context.Background())
|
||||
if err != nil {
|
||||
fmt.Printf("[error] calling HUP on all running commands\n")
|
||||
log.Printf("[error] calling HUP on all running commands\n")
|
||||
}
|
||||
|
||||
go stdinReadWatch()
|
||||
@@ -451,9 +455,9 @@ func main() {
|
||||
Handler: http.TimeoutHandler(gr, HttpTimeoutDuration, "Timeout"),
|
||||
}
|
||||
server.SetKeepAlivesEnabled(false)
|
||||
fmt.Printf("Running main server on %s\n", MainServerAddr)
|
||||
log.Printf("Running main server on %s\n", MainServerAddr)
|
||||
err = server.ListenAndServe()
|
||||
if err != nil {
|
||||
fmt.Printf("ERROR: %v\n", err)
|
||||
log.Printf("ERROR: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
@@ -312,7 +313,7 @@ func EvalCommand(ctx context.Context, pk *scpacket.FeCommandPacketType) (sstore.
|
||||
if !resolveBool(pk.Kwargs["nohist"], false) {
|
||||
err := addToHistory(ctx, pk, historyContext, (newPk.MetaCmd != "run"), (rtnErr != nil))
|
||||
if err != nil {
|
||||
fmt.Printf("[error] adding to history: %v\n", err)
|
||||
log.Printf("[error] adding to history: %v\n", err)
|
||||
// continue...
|
||||
}
|
||||
}
|
||||
@@ -1005,7 +1006,7 @@ func addLineForCmd(ctx context.Context, metaCmd string, shouldFocus bool, ids re
|
||||
sw, err := sstore.GetScreenWindowByIds(ctx, ids.SessionId, ids.ScreenId, ids.WindowId)
|
||||
if err != nil {
|
||||
// ignore error here, because the command has already run (nothing to do)
|
||||
fmt.Printf("%s error getting screen-window: %v\n", metaCmd, err)
|
||||
log.Printf("%s error getting screen-window: %v\n", metaCmd, err)
|
||||
}
|
||||
if sw != nil {
|
||||
updateMap := make(map[string]interface{})
|
||||
@@ -1016,7 +1017,7 @@ func addLineForCmd(ctx context.Context, metaCmd string, shouldFocus bool, ids re
|
||||
sw, err = sstore.UpdateScreenWindow(ctx, ids.SessionId, ids.ScreenId, ids.WindowId, updateMap)
|
||||
if err != nil {
|
||||
// ignore error again (nothing to do)
|
||||
fmt.Printf("%s error updating screen-window selected line: %v\n", metaCmd, err)
|
||||
log.Printf("%s error updating screen-window selected line: %v\n", metaCmd, err)
|
||||
}
|
||||
}
|
||||
update := &sstore.ModelUpdate{
|
||||
@@ -1267,7 +1268,7 @@ func CommentCommand(ctx context.Context, pk *scpacket.FeCommandPacketType) (ssto
|
||||
sw, err := sstore.UpdateScreenWindow(ctx, ids.SessionId, ids.ScreenId, ids.WindowId, updateMap)
|
||||
if err != nil {
|
||||
// ignore error again (nothing to do)
|
||||
fmt.Printf("/comment error updating screen-window selected line: %v\n", err)
|
||||
log.Printf("/comment error updating screen-window selected line: %v\n", err)
|
||||
}
|
||||
update := sstore.ModelUpdate{Line: rtnLine, ScreenWindows: []*sstore.ScreenWindowType{sw}}
|
||||
return update, nil
|
||||
@@ -1547,7 +1548,6 @@ func splitLinesForInfo(str string) []string {
|
||||
}
|
||||
|
||||
func resizeRunningCommand(ctx context.Context, cmd *sstore.CmdType, newCols int) error {
|
||||
fmt.Printf("resize running cmd %s/%s %d => %d\n", cmd.SessionId, cmd.CmdId, cmd.TermOpts.Cols, newCols)
|
||||
siPk := packet.MakeSpecialInputPacket()
|
||||
siPk.CK = base.MakeCommandKey(cmd.SessionId, cmd.CmdId)
|
||||
siPk.WinSize = &packet.WinSize{Rows: int(cmd.TermOpts.Rows), Cols: newCols}
|
||||
@@ -1666,7 +1666,7 @@ func LineShowCommand(ctx context.Context, pk *scpacket.FeCommandPacketType) (sst
|
||||
|
||||
func KillServerCommand(ctx context.Context, pk *scpacket.FeCommandPacketType) (sstore.UpdatePacket, error) {
|
||||
go func() {
|
||||
fmt.Printf("received /killserver, shutting down\n")
|
||||
log.Printf("received /killserver, shutting down\n")
|
||||
time.Sleep(1 * time.Second)
|
||||
syscall.Kill(syscall.Getpid(), syscall.SIGINT)
|
||||
}()
|
||||
|
||||
@@ -372,7 +372,7 @@ func ParseFuncs(funcs string) (map[string]string, error) {
|
||||
for _, stmt := range file.Stmts {
|
||||
funcName, funcVal, err := parseFuncStmt(stmt, funcs)
|
||||
if err != nil {
|
||||
fmt.Printf("stmt-err: %v\n", err)
|
||||
// TODO where to put parse errors
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(funcName, "_scripthaus_") {
|
||||
|
||||
@@ -1410,7 +1410,7 @@ func (msh *MShellProc) handleDataPacket(dataPk *packet.DataPacketType, dataPosMa
|
||||
if ack != nil {
|
||||
msh.ServerProc.Input.SendPacket(ack)
|
||||
}
|
||||
// fmt.Printf("data %s fd=%d len=%d eof=%v err=%v\n", dataPk.CK, dataPk.FdNum, len(realData), dataPk.Eof, dataPk.Error)
|
||||
// log.Printf("data %s fd=%d len=%d eof=%v err=%v\n", dataPk.CK, dataPk.FdNum, len(realData), dataPk.Eof, dataPk.Error)
|
||||
}
|
||||
|
||||
func (msh *MShellProc) makeHandleDataPacketClosure(dataPk *packet.DataPacketType, dataPosMap map[base.CommandKey]int64) func() {
|
||||
|
||||
+8
-15
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
@@ -17,8 +18,8 @@ import (
|
||||
const HomeVarName = "HOME"
|
||||
const ScHomeVarName = "SCRIPTHAUS_HOME"
|
||||
const SessionsDirBaseName = "sessions"
|
||||
const RemotesDirBaseName = "remotes"
|
||||
const SCLockFile = "sh2.lock"
|
||||
const ScriptHausDirName = "scripthaus"
|
||||
|
||||
var SessionDirCache = make(map[string]string)
|
||||
var BaseLock = &sync.Mutex{}
|
||||
@@ -30,13 +31,17 @@ func GetScHomeDir() string {
|
||||
if homeVar == "" {
|
||||
homeVar = "/"
|
||||
}
|
||||
scHome = path.Join(homeVar, "scripthaus")
|
||||
scHome = path.Join(homeVar, ScriptHausDirName)
|
||||
}
|
||||
return scHome
|
||||
}
|
||||
|
||||
func AcquireSCLock() (*os.File, error) {
|
||||
homeDir := GetScHomeDir()
|
||||
err := ensureDir(homeDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot find/create SCRIPTHAUS_HOME directory %q", homeDir)
|
||||
}
|
||||
lockFileName := path.Join(homeDir, SCLockFile)
|
||||
fd, err := os.Create(lockFileName)
|
||||
if err != nil {
|
||||
@@ -79,6 +84,7 @@ func ensureDir(dirName string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("[scripthaus] created directory %q\n", dirName)
|
||||
info, err = os.Stat(dirName)
|
||||
}
|
||||
if err != nil {
|
||||
@@ -118,19 +124,6 @@ func RunOutFile(sessionId string, cmdId string) (string, error) {
|
||||
return fmt.Sprintf("%s/%s.runout", sdir, cmdId), nil
|
||||
}
|
||||
|
||||
func RemotePtyOut(remoteId string) (string, error) {
|
||||
if remoteId == "" {
|
||||
return "", fmt.Errorf("cannot get remote ptyout file for blank remoteid")
|
||||
}
|
||||
scHome := GetScHomeDir()
|
||||
rdir := path.Join(scHome, RemotesDirBaseName)
|
||||
err := ensureDir(rdir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("%s/%s.ptyout.cf", rdir, remoteId), nil
|
||||
}
|
||||
|
||||
type ScFileNameGenerator struct {
|
||||
ScHome string
|
||||
}
|
||||
|
||||
+12
-11
@@ -3,6 +3,7 @@ package scws
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -85,7 +86,7 @@ func (ws *WSState) UnWatchScreen() {
|
||||
sstore.MainBus.UnregisterChannel(ws.ClientId)
|
||||
ws.SessionId = ""
|
||||
ws.ScreenId = ""
|
||||
fmt.Printf("[ws] unwatch screen clientid=%s\n", ws.ClientId)
|
||||
log.Printf("[ws] unwatch screen clientid=%s\n", ws.ClientId)
|
||||
}
|
||||
|
||||
func (ws *WSState) getUpdateCh() chan interface{} {
|
||||
@@ -154,10 +155,10 @@ func (ws *WSState) handleWatchScreen(wsPk *scpacket.WatchScreenPacketType) error
|
||||
ws.UnWatchScreen()
|
||||
} else {
|
||||
ws.WatchScreen(wsPk.SessionId, wsPk.ScreenId)
|
||||
fmt.Printf("[ws %s] watchscreen %s/%s\n", ws.ClientId, wsPk.SessionId, wsPk.ScreenId)
|
||||
log.Printf("[ws %s] watchscreen %s/%s\n", ws.ClientId, wsPk.SessionId, wsPk.ScreenId)
|
||||
}
|
||||
if wsPk.Connect {
|
||||
fmt.Printf("[ws %s] watchscreen connect\n", ws.ClientId)
|
||||
log.Printf("[ws %s] watchscreen connect\n", ws.ClientId)
|
||||
err := ws.handleConnection()
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect: %w", err)
|
||||
@@ -175,24 +176,24 @@ func (ws *WSState) RunWSRead() {
|
||||
for msgBytes := range shell.ReadChan {
|
||||
pk, err := packet.ParseJsonPacket(msgBytes)
|
||||
if err != nil {
|
||||
fmt.Printf("error unmarshalling ws message: %v\n", err)
|
||||
log.Printf("error unmarshalling ws message: %v\n", err)
|
||||
continue
|
||||
}
|
||||
if pk.GetType() == scpacket.FeInputPacketStr {
|
||||
feInputPk := pk.(*scpacket.FeInputPacketType)
|
||||
if feInputPk.Remote.OwnerId != "" {
|
||||
fmt.Printf("[error] cannot send input to remote with ownerid\n")
|
||||
log.Printf("[error] cannot send input to remote with ownerid\n")
|
||||
continue
|
||||
}
|
||||
if feInputPk.Remote.RemoteId == "" {
|
||||
fmt.Printf("[error] invalid input packet, remoteid is not set\n")
|
||||
log.Printf("[error] invalid input packet, remoteid is not set\n")
|
||||
continue
|
||||
}
|
||||
go func() {
|
||||
// TODO enforce a strong ordering (channel with list)
|
||||
err = sendCmdInput(feInputPk)
|
||||
if err != nil {
|
||||
fmt.Printf("[error] sending command input: %v\n", err)
|
||||
log.Printf("[error] sending command input: %v\n", err)
|
||||
}
|
||||
}()
|
||||
continue
|
||||
@@ -202,25 +203,25 @@ func (ws *WSState) RunWSRead() {
|
||||
err := ws.handleWatchScreen(wsPk)
|
||||
if err != nil {
|
||||
// TODO send errors back to client, likely unrecoverable
|
||||
fmt.Printf("[ws %s] error %v\n", err)
|
||||
log.Printf("[ws %s] error %v\n", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if pk.GetType() == scpacket.RemoteInputPacketStr {
|
||||
inputPk := pk.(*scpacket.RemoteInputPacketType)
|
||||
if inputPk.RemoteId == "" {
|
||||
fmt.Printf("[error] invalid remoteinput packet, remoteid is not set\n")
|
||||
log.Printf("[error] invalid remoteinput packet, remoteid is not set\n")
|
||||
continue
|
||||
}
|
||||
go func() {
|
||||
err = remote.SendRemoteInput(inputPk)
|
||||
if err != nil {
|
||||
fmt.Printf("[error] processing remote input: %v\n", err)
|
||||
log.Printf("[error] processing remote input: %v\n", err)
|
||||
}
|
||||
}()
|
||||
continue
|
||||
}
|
||||
fmt.Printf("got ws bad message: %v\n", pk.GetType())
|
||||
log.Printf("got ws bad message: %v\n", pk.GetType())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -733,7 +733,6 @@ func HangupRunningCmdsByRemoteId(ctx context.Context, remoteId string) error {
|
||||
}
|
||||
|
||||
func getNextId(ids []string, delId string) string {
|
||||
fmt.Printf("getnextid %v | %v\n", ids, delId)
|
||||
if len(ids) == 0 {
|
||||
return ""
|
||||
}
|
||||
@@ -779,7 +778,6 @@ func DeleteScreen(ctx context.Context, sessionId string, screenId string) (Updat
|
||||
var newActiveScreenId string
|
||||
txErr := WithTx(ctx, func(tx *TxWrap) error {
|
||||
isActive := tx.Exists(`SELECT sessionid FROM session WHERE sessionid = ? AND activescreenid = ?`, sessionId, screenId)
|
||||
fmt.Printf("delete-screen %s %s | %v\n", sessionId, screenId, isActive)
|
||||
if isActive {
|
||||
screenIds := tx.SelectStrings(`SELECT screenid FROM screen WHERE sessionid = ? ORDER BY screenidx`, sessionId)
|
||||
nextId := getNextId(screenIds, screenId)
|
||||
|
||||
@@ -2,6 +2,7 @@ package sstore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"strconv"
|
||||
|
||||
_ "github.com/golang-migrate/migrate/v4/database/sqlite3"
|
||||
@@ -91,7 +92,7 @@ func MigratePrintVersion() error {
|
||||
if dirty {
|
||||
return fmt.Errorf("error db is dirty, version=%d", version)
|
||||
}
|
||||
fmt.Printf("[db] version=%d\n", version)
|
||||
log.Printf("[db] version=%d\n", version)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -802,7 +802,7 @@ func createClientData(tx *TxWrap) error {
|
||||
query := `INSERT INTO client ( clientid, userid, activesessionid, userpublickeybytes, userprivatekeybytes, winsize)
|
||||
VALUES (:clientid,:userid,:activesessionid,:userpublickeybytes,:userprivatekeybytes,:winsize)`
|
||||
tx.NamedExecWrap(query, c.ToMap())
|
||||
fmt.Printf("create new clientid[%s] userid[%s] with public/private keypair\n", c.ClientId, c.UserId)
|
||||
log.Printf("create new clientid[%s] userid[%s] with public/private keypair\n", c.ClientId, c.UserId)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package sstore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
)
|
||||
|
||||
@@ -180,7 +181,7 @@ func (bus *UpdateBus) SendUpdate(sessionId string, update interface{}) {
|
||||
case uch.Ch <- update:
|
||||
|
||||
default:
|
||||
fmt.Printf("[error] dropped update on updatebus uch clientid=%s\n", uch.ClientId)
|
||||
log.Printf("[error] dropped update on updatebus uch clientid=%s\n", uch.ClientId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user