apkipa 1 неделя назад
Родитель
Сommit
302f2da3e1
4 измененных файлов с 229 добавлено и 1 удалено
  1. 22 0
      go.mod
  2. 30 0
      go.sum
  3. 176 0
      main.go
  4. 1 1
      stck-nsq-msg

+ 22 - 0
go.mod

@@ -0,0 +1,22 @@
+module stck/stck-bastion
+
+go 1.22.2
+
+replace stck/stck-nsq-msg => ./stck-nsq-msg
+
+require (
+	github.com/nsqio/go-nsq v1.1.0
+	github.com/sirupsen/logrus v1.9.3
+	stck/stck-nsq-msg v0.0.0-00010101000000-000000000000
+)
+
+require (
+	github.com/Masterminds/semver/v3 v3.3.1 // indirect
+	github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
+	github.com/denisbrodbeck/machineid v1.0.1 // indirect
+	github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
+	github.com/golang/snappy v0.0.1 // indirect
+	github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
+	github.com/stretchr/testify v1.9.0 // indirect
+	golang.org/x/sys v0.28.0 // indirect
+)

+ 30 - 0
go.sum

@@ -0,0 +1,30 @@
+github.com/Masterminds/semver/v3 v3.3.1 h1:QtNSWtVZ3nBfk8mAOu/B6v7FMJ+NHTIgUPi7rj+4nv4=
+github.com/Masterminds/semver/v3 v3.3.1/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/denisbrodbeck/machineid v1.0.1 h1:geKr9qtkB876mXguW2X6TU4ZynleN6ezuMSRhl4D7AQ=
+github.com/denisbrodbeck/machineid v1.0.1/go.mod h1:dJUwb7PTidGDeYyUBmXZ2GphQBbjJCrnectwCyxcUSI=
+github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
+github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
+github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
+github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
+github.com/nsqio/go-nsq v1.1.0 h1:PQg+xxiUjA7V+TLdXw7nVrJ5Jbl3sN86EhGCQj4+FYE=
+github.com/nsqio/go-nsq v1.1.0/go.mod h1:vKq36oyeVXgsS5Q8YEO7WghqidAVXQlcFxzQbQTuDEY=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
+github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
+github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
+github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
+golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

+ 176 - 0
main.go

@@ -0,0 +1,176 @@
+package main
+
+import (
+	"bufio"
+	"fmt"
+	"os"
+	"stck/stck-nsq-msg"
+	smsg "stck/stck-nsq-msg/msg"
+	"strings"
+	"time"
+
+	// "github.com/natefinch/lumberjack"
+	"github.com/nsqio/go-nsq"
+	"github.com/sirupsen/logrus"
+	// "github.com/spf13/viper"
+)
+
+type AppConfig struct {
+	Nsq struct {
+		TcpAddr         string `mapstructure:"tcp_addr"`
+		LookupdHttpAddr string `mapstructure:"lookupd_http_addr"`
+	} `mapstructure:"nsq"`
+	Mysql struct {
+		User     string `mapstructure:"user"`
+		Password string `mapstructure:"password"`
+		Host     string `mapstructure:"host"`
+		Database string `mapstructure:"database"`
+	} `mapstructure:"mysql"`
+}
+
+var logger *logrus.Logger
+var gAppConfig *AppConfig
+var gNsqProducer *nsq.Producer
+var gNsqConsumer *nsq.Consumer
+
+func PublishMessage(msg stcknsqmsg.StckNsqMsgVariant) error {
+	payload, err := stcknsqmsg.ToStckNsqMsgString(msg)
+	if err != nil {
+		return fmt.Errorf("marshal message error: %w", err)
+	}
+	err = gNsqProducer.Publish(smsg.ClientDoActionTopic, []byte(payload))
+	if err != nil {
+		return fmt.Errorf("publish message error: %w", err)
+	}
+	return nil
+}
+
+func main() {
+	var err error
+
+	// Init logger
+	initLog()
+
+	gAppConfig = &AppConfig{}
+	gAppConfig.Nsq.TcpAddr = "localhost:4150"
+	gAppConfig.Nsq.LookupdHttpAddr = "localhost:4161"
+
+	// Init NSQ
+	nsqConfig := nsq.NewConfig()
+	gNsqProducer, err = nsq.NewProducer(gAppConfig.Nsq.TcpAddr, nsqConfig)
+	if err != nil {
+		logger.Fatalf("NSQ Producer init error: %s", err)
+	}
+	gNsqConsumer, err = nsq.NewConsumer(smsg.ServerDoNotifyTopic, "main-bastion-1", nsqConfig)
+	if err != nil {
+		logger.Fatalf("NSQ Consumer init error: %s", err)
+	}
+	gNsqConsumer.AddConcurrentHandlers(nsq.HandlerFunc(func(message *nsq.Message) error {
+		logger.Debugf("NSQ Consumer received message: %s", message.Body)
+
+		// Parse the message
+		recvTime := message.Timestamp
+		msg, err := stcknsqmsg.FromString(string(message.Body))
+		if err != nil {
+			logger.Errorf("NSQ Consumer unmarshal message error: %s", err)
+			return nil
+		}
+
+		// Process the message
+		switch data := msg.Data.(type) {
+		case *smsg.DeviceHeartbeatMsg:
+			if time.Since(time.Unix(0, recvTime)) > time.Second*60 {
+				logger.Debugf("NSQ Consumer ignored DeviceHeartbeatMsg: %v", data)
+				break
+			}
+			logger.Infof("NSQ Consumer received DeviceHeartbeatMsg: %v", data)
+		case *smsg.DeviceActionDoneMsg:
+			logger.Infof("NSQ Consumer received DeviceActionDoneMsg: %v", data)
+		default:
+			logger.Debugf("NSQ Consumer ignored unknown or uninteresting message: %v", msg)
+		}
+
+		return nil
+	}), 1)
+	err = gNsqConsumer.ConnectToNSQD(gAppConfig.Nsq.TcpAddr)
+	if err != nil {
+		logger.Fatalf("NSQ Consumer connect error: %s", err)
+	}
+
+	// Enter CLI loop
+	fmt.Print("Welcome to stck bastion CLI.\n\n")
+	scanner := bufio.NewScanner(os.Stdin)
+	for scanner.Scan() {
+		fmt.Print("stck> ")
+		var cmd string
+		cmd = scanner.Text()
+		cmd = strings.TrimSpace(cmd)
+		cmds := strings.Split(cmd, " ")
+		switch cmds[0] {
+		case "":
+			continue
+		case "exit":
+			goto Exit
+		case "help":
+			fmt.Println("Commands: exit, help")
+		case "reboot":
+			// Send a message to NSQ
+			msg := smsg.MakeForceDeviceRebootMsg("*")
+			err := PublishMessage(&msg)
+			if err != nil {
+				logger.Errorf("Publish message error: %s", err)
+			}
+		case "runcmd":
+			// Send a message to NSQ
+			cmd := strings.TrimSpace(strings.TrimPrefix(cmd, "runcmd"))
+			if cmd == "" {
+				cmd = "echo Hello\necho World!"
+			}
+			msg := smsg.MakeRequestDeviceExecuteShellScriptMsg("*", cmd)
+			err := PublishMessage(&msg)
+			if err != nil {
+				logger.Errorf("Publish message error: %s", err)
+			}
+		case "update":
+			if len(cmds) < 3 {
+				fmt.Println("Usage: update <service_name> <binary_url>")
+				continue
+			}
+			serviceName := cmds[1]
+			binaryUrl := cmds[2]
+			// http://localhost:19010/api/v1/buckets/app-updater/objects/download?prefix=watch-daemon-universal-installer-v2025-01-07.tar.gz
+			msg := smsg.MakeRequestDeviceUpdateMsg("*", serviceName, "0.1.0", binaryUrl, "")
+			err := PublishMessage(&msg)
+			if err != nil {
+				logger.Errorf("Publish message error: %s", err)
+			}
+		case "upload-log":
+			msg := smsg.MakeRequestDeviceUploadLogsToMinioMsg("*", "app-logs", "logs")
+			err := PublishMessage(&msg)
+			if err != nil {
+				logger.Errorf("Publish message error: %s", err)
+			}
+		default:
+			fmt.Println("Unknown command. Type 'help' to see available commands.")
+		}
+	}
+Exit:
+	fmt.Println("Bye :)")
+
+	// Close NSQ
+	gNsqConsumer.Stop()
+	gNsqProducer.Stop()
+}
+
+func initLog() {
+	logger = logrus.New()
+	envLevel := strings.ToLower(os.Getenv("LOG_LEVEL"))
+	if envLevel == "trace" {
+		logger.SetLevel(logrus.TraceLevel)
+	} else if envLevel == "debug" {
+		logger.SetLevel(logrus.DebugLevel)
+	} else {
+		logger.SetLevel(logrus.InfoLevel)
+	}
+	logger.Out = os.Stdout
+}

+ 1 - 1
stck-nsq-msg

@@ -1 +1 @@
-Subproject commit b96ecce927903672638216f998107aa3364ae69c
+Subproject commit edbe73395f7dd0978f203d3488ac737887b53015