1package main
2
3import (
4 "bufio"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net"
9 "os"
10 "time"
11
12 log "github.com/sirupsen/logrus"
13)
14
15func main() {
16 conn, err := net.Dial("tcp", "localhost:5050")
17 if err != nil {
18 fmt.Println("Error connecting:", err)
19 os.Exit(1)
20 }
21 defer conn.Close()
22
23 log.SetLevel(log.InfoLevel)
24 log.SetFormatter(&log.TextFormatter{})
25 log.SetOutput(os.Stdout)
26
27 go receiveActions(conn)
28
29 fmt.Println("Starting Uplink Bridge App")
30 for {
31 time.Sleep(5 * time.Second)
32 log.Debug("This is debug")
33 log.Info("This is info")
34 log.Error("This is error")
35 }
36}
37
38
39func receiveAction(conn net.Conn) (map[string]interface{}, error) {
40 reader := bufio.NewReader(conn)
41 msg, err := reader.ReadString('\n')
42 if err != nil {
43 return nil, err
44 }
45
46 var action map[string]interface{}
47 err = json.Unmarshal([]byte(msg), &action)
48 return action, err
49}
50
51
52func sendAction(conn net.Conn, payload map[string]interface{}) error {
53 msg, err := json.Marshal(payload)
54 if err != nil {
55 return err
56 }
57 _, err = conn.Write(append(msg, '\n'))
58 return err
59}
60
61
62func actionComplete(id interface{}) map[string]interface{} {
63 return map[string]interface{}{
64 "stream": "action_status",
65 "sequence": 0,
66 "timestamp": time.Now().UnixNano() / 1000,
67 "action_id": id,
68 "state": "Completed",
69 "progress": 100,
70 "errors": []string{},
71 }
72}
73
74
75func updateConfig(conn net.Conn, action map[string]interface{}) {
76 payloadStr := action["payload"].(string)
77 var payload map[string]interface{}
78 json.Unmarshal([]byte(payloadStr), &payload)
79
80 app := payload["name"].(string)
81 level := payload["level"].(string)
82 if app == "logging" {
83 setLogLevel(level)
84 }
85
86 resp := actionComplete(action["action_id"])
87 sendAction(conn, resp)
88}
89
90func setLogLevel(level string) {
91 switch level {
92 case "info":
93 log.SetLevel(log.InfoLevel)
94 case "error":
95 log.SetLevel(log.ErrorLevel)
96 case "verbose":
97 log.SetLevel(log.TraceLevel)
98 case "debug":
99 log.SetLevel(log.DebugLevel)
100 default:
101 log.SetLevel(log.InfoLevel)
102 }
103 log.Infof("Log level set to %s", level)
104}
105
106
107func receiveActions(conn net.Conn) {
108 for {
109 action, err := receiveAction(conn)
110 if err != nil {
111 if err == io.EOF {
112 fmt.Println("Connection closed by server")
113 return
114 }
115 fmt.Println("Error reading:", err)
116 continue
117 }
118 fmt.Println("Action received:", action)
119
120 if action["name"] == "update_config" {
121 fmt.Println("update_config action received")
122 updateConfig(conn, action)
123 }
124 }
125}
126