forked from ivahaev/amigo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ami.go
422 lines (359 loc) · 8.3 KB
/
ami.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package amigo
import (
"bufio"
"bytes"
"errors"
"fmt"
"net"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/ivahaev/amigo/uuid"
)
const (
pingActionID = "AmigoPing"
amigoConnIDKey = "AmigoConnID"
commandResponseKey = "CommandResponse"
)
var (
actionTimeout = 3 * time.Second
dialTimeout = 10 * time.Second
pingInterval = 5 * time.Second
sequence uint64
)
type amiAdapter struct {
id string
eventsChan chan map[string]string
dialString string
username string
password string
connected bool
actionTimeout time.Duration
dialTimeout time.Duration
actionsChan chan map[string]string
responseChans map[string]chan map[string]string
pingerChan chan struct{}
mutex *sync.RWMutex
emitEvent func(string, string)
}
func newAMIAdapter(s *Settings, eventEmitter func(string, string)) (*amiAdapter, error) {
var a = new(amiAdapter)
a.dialString = fmt.Sprintf("%s:%s", s.Host, s.Port)
a.username = s.Username
a.password = s.Password
a.actionTimeout = s.ActionTimeout
a.dialTimeout = s.DialTimeout
a.mutex = &sync.RWMutex{}
a.emitEvent = eventEmitter
a.actionsChan = make(chan map[string]string)
a.responseChans = make(map[string]chan map[string]string)
a.eventsChan = make(chan map[string]string, 4096)
a.pingerChan = make(chan struct{})
fmt.Println("Trying to connect...")
go func() {
for {
func() {
a.id = nextID()
fmt.Println(a.id)
var err error
var conn net.Conn
readErrChan := make(chan error)
writeErrChan := make(chan error)
pingErrChan := make(chan error)
chanStop := make(chan struct{})
for {
conn, err = a.openConnection()
if err == nil {
fmt.Println("connection opened!")
defer conn.Close()
greetings := make([]byte, 100)
n, err := conn.Read(greetings)
if err != nil {
go a.emitEvent("error", fmt.Sprintf("Asterisk connection error: %s", err.Error()))
time.Sleep(s.ReconnectInterval)
return
}
err = a.login(conn)
if err != nil {
go a.emitEvent("error", fmt.Sprintf("Asterisk login error: %s", err.Error()))
time.Sleep(s.ReconnectInterval)
return
}
if n > 2 {
greetings = greetings[:n-2]
}
go a.emitEvent("connect", string(greetings))
break
}
fmt.Println("an error ocorr: ", err)
a.emitEvent("error", "AMI connecting failed")
time.Sleep(s.ReconnectInterval)
return
}
a.mutex.Lock()
a.connected = true
a.mutex.Unlock()
go a.reader(conn, chanStop, readErrChan)
go a.writer(conn, chanStop, writeErrChan)
if s.Keepalive {
go a.pinger(chanStop, pingErrChan)
}
select {
case err = <-readErrChan:
case err = <-writeErrChan:
case err = <-pingErrChan:
}
close(chanStop)
a.mutex.Lock()
a.connected = false
a.mutex.Unlock()
go a.emitEvent("error", fmt.Sprintf("AMI TCP ERROR: %s", err.Error()))
time.Sleep(s.ReconnectInterval)
}()
}
}()
return a, nil
}
func nextID() string {
i := atomic.AddUint64(&sequence, 1)
return strconv.Itoa(int(i))
}
func (a *amiAdapter) pinger(stop <-chan struct{}, errChan chan error) {
ticker := time.NewTicker(pingInterval)
defer ticker.Stop()
ping := map[string]string{"Action": "Ping", "ActionID": pingActionID, amigoConnIDKey: a.id}
for {
select {
case <-stop:
return
default:
}
select {
case <-stop:
return
case <-ticker.C:
}
if !a.online() {
// when stop chan didn't received before ticker
return
}
a.actionsChan <- ping
timer := time.NewTimer(3 * time.Second)
select {
case <-a.pingerChan:
timer.Stop()
continue
case <-timer.C:
errChan <- errors.New("ping timeout")
return
}
}
}
func (a *amiAdapter) writer(conn net.Conn, stop <-chan struct{}, writeErrChan chan error) {
for {
select {
case <-stop:
return
default:
}
select {
case <-stop:
return
case action := <-a.actionsChan:
if action[amigoConnIDKey] != a.id {
// action sent before reconnect, need to be ignored
continue
}
data := serialize(action)
_, err := conn.Write(data)
if err != nil {
writeErrChan <- err
return
}
}
}
}
func (a *amiAdapter) distribute(event map[string]string) {
actionID := event["ActionID"]
if actionID == pingActionID {
a.pingerChan <- struct{}{}
return
}
if len(a.eventsChan) == cap(a.eventsChan) {
a.emitEvent("error", "events chan is full")
}
// TODO: Need to decide to send or not to send action responses to eventsChan
a.eventsChan <- event
if len(actionID) > 0 {
a.mutex.RLock()
resChan := a.responseChans[actionID]
a.mutex.RUnlock()
if resChan != nil {
a.mutex.Lock()
resChan = a.responseChans[actionID]
if resChan == nil {
a.mutex.Unlock()
return
}
delete(a.responseChans, actionID)
a.mutex.Unlock()
resChan <- event
}
}
}
func (a *amiAdapter) exec(action map[string]string) map[string]string {
action[amigoConnIDKey] = a.id
actionID := action["ActionID"]
if actionID == "" {
actionID = uuid.NewV4()
action["ActionID"] = actionID
}
// TODO: parse multi-message response
resChan := make(chan map[string]string)
a.mutex.Lock()
a.responseChans[actionID] = resChan
a.mutex.Unlock()
a.actionsChan <- action
time.AfterFunc(a.actionTimeout, func() {
a.mutex.RLock()
_, ok := a.responseChans[actionID]
a.mutex.RUnlock()
if ok {
a.mutex.Lock()
if ch, ok := a.responseChans[actionID]; ok {
delete(a.responseChans, actionID)
a.mutex.Unlock()
ch <- map[string]string{"Error": "Timeout"}
return
}
a.mutex.Unlock()
}
})
response := <-resChan
return response
}
func (a *amiAdapter) login(conn net.Conn) error {
var action = map[string]string{
"Action": "login",
"Username": a.username,
"Secret": a.password,
}
serialized := serialize(action)
_, err := conn.Write(serialized)
if err != nil {
return err
}
reader := bufio.NewReader(conn)
result, err := readMessage(reader)
if err != nil {
return err
}
if result["Response"] != "Success" && result["Message"] != "Authentication accepted" {
return errors.New(result["Message"])
}
return nil
}
func (a *amiAdapter) online() bool {
a.mutex.RLock()
defer a.mutex.RUnlock()
return a.connected
}
func (a *amiAdapter) openConnection() (net.Conn, error) {
return net.DialTimeout("tcp", a.dialString, a.dialTimeout)
}
func readMessage(r *bufio.Reader) (m map[string]string, err error) {
m = make(map[string]string)
var responseFollows bool
for {
kv, _, err := r.ReadLine()
if len(kv) == 0 {
return m, err
}
var key string
i := bytes.IndexByte(kv, ':')
if i >= 0 {
endKey := i
for endKey > 0 && kv[endKey-1] == ' ' {
endKey--
}
key = string(kv[:endKey])
}
if key == "" && !responseFollows {
if err != nil {
return m, err
}
continue
}
if responseFollows && key != "Privilege" && key != "ActionID" {
if string(kv) != "--END COMMAND--" {
if len(m[commandResponseKey]) == 0 {
m[commandResponseKey] = string(kv)
} else {
m[commandResponseKey] = fmt.Sprintf("%s\n%s", m[commandResponseKey], string(kv))
}
}
if err != nil {
return m, err
}
continue
}
i++
for i < len(kv) && (kv[i] == ' ' || kv[i] == '\t') {
i++
}
value := string(kv[i:])
if key == "Response" && value == "Follows" {
responseFollows = true
}
m[key] = value
if err != nil {
return m, err
}
}
}
func serialize(data map[string]string) []byte {
var outBuf bytes.Buffer
for key := range data {
outBuf.WriteString(key)
outBuf.WriteString(": ")
outBuf.WriteString(data[key])
outBuf.WriteString("\r\n")
}
outBuf.WriteString("\r\n")
return outBuf.Bytes()
}
func (a *amiAdapter) reader(conn net.Conn, stop <-chan struct{}, readErrChan chan error) {
chanErr := make(chan error)
chanEvents := make(chan map[string]string)
go func() {
bufReader := bufio.NewReader(conn)
for i := 0; ; i++ {
var event map[string]string
var err error
event, err = readMessage(bufReader)
if err != nil {
chanErr <- err
return
}
event["#"] = strconv.Itoa(i)
event["TimeReceived"] = time.Now().Format(time.RFC3339Nano)
chanEvents <- event
}
}()
for {
select {
case <-stop:
return
default:
}
select {
case <-stop:
return
case err := <-chanErr:
readErrChan <- err
case event := <-chanEvents:
a.distribute(event)
}
}
}