-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathmain.go
190 lines (156 loc) · 4.28 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
//
// Copyright (C) 2020 OpenSIPS Solutions
//
// Call API is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Call API is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
package main
import (
"encoding/json"
"flag"
"fmt"
"net/url"
"os"
"os/signal"
"time"
"github.com/OpenSIPS/call-api/internal/jsonrpc"
"github.com/OpenSIPS/call-api/pkg/config"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
)
func usage(prog string) {
logrus.Fatalf("Usage: %s jsonrpc_method [jsonrpc_arguments]", prog)
}
func ParseClientArgs() (string, int, string, string, interface{}, string) {
var wsServer, method, params, id string
var wsPort int
flag.StringVar(&wsServer, "wshost", "", "The websocket host to connect to")
flag.IntVar(&wsPort, "wsport", 0, "The websocket port to connect to")
flag.StringVar(&method, "method", "", "JSON-RPC method")
flag.StringVar(¶ms, "params", "", "JSON-RPC params")
flag.StringVar(&id, "id", "", "JSON-RPC id")
cfgPath, err := config.ParseFlags("call-api")
if err != nil {
logrus.Fatal(err)
}
if method == "" {
logrus.Error("no method specified!")
usage(os.Args[0])
}
var v interface{}
if params != "" {
err = json.Unmarshal([]byte(params), &v)
if err != nil {
logrus.Fatalf("failed to parse JSON args: %s", err)
}
}
return wsServer, wsPort, cfgPath, method, v, id
}
func closeWSConnection(c *websocket.Conn) {
logrus.Info("gracefully closing connection...")
// Cleanly close the connection by sending a close message
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
logrus.Errorf("write close: %s", err)
return
}
}
func main() {
// parse cmdline args
wsServer, wsPort, cfgPath, method, params, id := ParseClientArgs()
// read configuration
cfg, err := config.NewConfig(cfgPath)
if err != nil {
logrus.Fatal(err)
}
if wsServer == "" {
wsServer = cfg.WSServer.Host
}
if wsPort == 0 {
wsPort = cfg.WSServer.Port
}
// prepare logging
logfile, err := config.InitLogging(cfg)
if err != nil {
logrus.Fatal(err)
}
if logfile != nil {
defer logfile.Close()
}
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
api_hostport := fmt.Sprintf("%s:%d", wsServer, wsPort)
u := url.URL{Scheme: "ws", Host: api_hostport, Path: cfg.WSServer.Path}
logrus.Printf("connecting to %s", u.String())
// open a single WebSocket connection
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
logrus.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
// keep listening for messages until EOF
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
logrus.Println("read:", err)
return
}
logrus.Printf("recv: %s", message)
var v interface{}
err = json.Unmarshal(message, &v)
if err != nil {
logrus.Printf("failed to parse JSON reply: %s", err)
return
}
params := v.(map[string]interface{})["params"]
if params != nil {
status := params.(map[string]interface{})["event"]
if status == "Ended" || status == "Error" {
closeWSConnection(c)
return
}
}
}
}()
// create a JSON-RPC request
req := jsonrpc.NewRequest(id, method, params)
if req == nil {
logrus.Fatal("failed to create JSON-RPC request")
}
// ... serialize it
buf, err := req.Buffer()
if err != nil {
logrus.Fatal("write:", err)
}
logrus.Infof("send: %s", buf)
// ... and send it!
err = c.WriteMessage(websocket.TextMessage, buf)
if err != nil {
logrus.Fatal("write:", err)
}
select {
case <-done:
return
case <-interrupt:
logrus.Println("interrupt")
closeWSConnection(c)
// wait (with timeout) for the server to close the connection
select {
case <-done:
case <-time.After(time.Second):
}
}
}