forked from PelionIoT/maestro
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpSymphonyClient.go
More file actions
379 lines (351 loc) · 10.1 KB
/
Copy pathhttpSymphonyClient.go
File metadata and controls
379 lines (351 loc) · 10.1 KB
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
//
// Overview:
// Setups a go 'channel' - and uses this channel to transfer log data to symphonyd
// This same on-going connection can be used for the server to 'ride back' for commands
//
package maestro
// Copyright (c) 2018, Arm Limited and affiliates.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
"github.com/armPelionEdge/greasego"
"github.com/armPelionEdge/maestro/debugging"
// DEBUG("runtime")
)
type logBuffer struct {
data *greasego.TargetCallbackData
godata []byte
}
// begin generic
// m4_define({{*NODE*}},{{*logBuffer*}}) m4_define({{*FIFO*}},{{*logBufferFifo*}})
// Thread safe queue for LogBuffer
type logBufferFifo struct {
q []*logBuffer
mutex *sync.Mutex
condWait *sync.Cond
condFull *sync.Cond
maxSize uint32
drops int
shutdown bool
wakeupIter int // this is to deal with the fact that go developers
// decided not to implement pthread_cond_timedwait()
// So we use this as a work around to temporarily wakeup
// (but not shutdown) the queue. Bring your own timer.
}
func New_logBufferFifo(maxsize uint32) (ret *logBufferFifo) {
ret = new(logBufferFifo)
ret.mutex = new(sync.Mutex)
ret.condWait = sync.NewCond(ret.mutex)
ret.condFull = sync.NewCond(ret.mutex)
ret.maxSize = maxsize
ret.drops = 0
ret.shutdown = false
ret.wakeupIter = 0
return
}
func (fifo *logBufferFifo) Push(n *logBuffer) (drop bool, dropped *logBuffer) {
drop = false
debugging.DEBUG_OUT2(" >>>>>>>>>>>> In Push\n")
fifo.mutex.Lock()
debugging.DEBUG_OUT2(" ------------ In Push (past Lock)\n")
if int(fifo.maxSize) > 0 && len(fifo.q)+1 > int(fifo.maxSize) {
// drop off the queue
dropped = (fifo.q)[0]
fifo.q = (fifo.q)[1:]
fifo.drops++
debugging.DEBUG_OUT2("!!! Dropping logBuffer in logBufferFifo \n")
drop = true
}
fifo.q = append(fifo.q, n)
debugging.DEBUG_OUT2(" ------------ In Push (@ Unlock)\n")
fifo.mutex.Unlock()
fifo.condWait.Signal()
debugging.DEBUG_OUT2(" <<<<<<<<<<< Return Push\n")
return
}
func (fifo *logBufferFifo) Pop() (n *logBuffer) {
fifo.mutex.Lock()
if len(fifo.q) > 0 {
n = (fifo.q)[0]
fifo.q = (fifo.q)[1:]
fifo.condFull.Signal()
}
fifo.mutex.Unlock()
return
}
func (fifo *logBufferFifo) Len() int {
fifo.mutex.Lock()
ret := len(fifo.q)
fifo.mutex.Unlock()
return ret
}
func (fifo *logBufferFifo) PopOrWait() (n *logBuffer) {
n = nil
debugging.DEBUG_OUT2(" >>>>>>>>>>>> In PopOrWait (Lock)\n")
fifo.mutex.Lock()
_wakeupIter := fifo.wakeupIter
if fifo.shutdown {
fifo.mutex.Unlock()
debugging.DEBUG_OUT2(" <<<<<<<<<<<<< In PopOrWait (Unlock 1)\n")
return
}
if len(fifo.q) > 0 {
n = (fifo.q)[0]
fifo.q = (fifo.q)[1:]
fifo.mutex.Unlock()
fifo.condFull.Signal()
debugging.DEBUG_OUT2(" <<<<<<<<<<<<< In PopOrWait (Unlock 2)\n")
return
}
// nothing there, let's wait
for !fifo.shutdown && fifo.wakeupIter == _wakeupIter {
// fmt.Printf(" --entering wait %+v\n",*fifo);
debugging.DEBUG_OUT2(" ----------- In PopOrWait (Wait / Unlock 1)\n")
fifo.condWait.Wait() // will unlock it's "Locker" - which is fifo.mutex
// Wait returns with Lock
// fmt.Printf(" --out of wait %+v\n",*fifo);
if fifo.shutdown {
fifo.mutex.Unlock()
debugging.DEBUG_OUT2(" <<<<<<<<<<<<< In PopOrWait (Unlock 4)\n")
return
}
if len(fifo.q) > 0 {
n = (fifo.q)[0]
fifo.q = (fifo.q)[1:]
fifo.mutex.Unlock()
fifo.condFull.Signal()
debugging.DEBUG_OUT2(" <<<<<<<<<<<<< In PopOrWait (Unlock 3)\n")
return
}
}
debugging.DEBUG_OUT2(" <<<<<<<<<<<<< In PopOrWait (Unlock 5)\n")
fifo.mutex.Unlock()
return
}
func (fifo *logBufferFifo) PushOrWait(n *logBuffer) (ret bool) {
ret = true
fifo.mutex.Lock()
_wakeupIter := fifo.wakeupIter
for int(fifo.maxSize) > 0 && (len(fifo.q)+1 > int(fifo.maxSize)) && !fifo.shutdown && (fifo.wakeupIter == _wakeupIter) {
// fmt.Printf(" --entering push wait %+v\n",*fifo);
fifo.condFull.Wait()
if fifo.shutdown {
fifo.mutex.Unlock()
ret = false
return
}
// fmt.Printf(" --exiting push wait %+v\n",*fifo);
}
fifo.q = append(fifo.q, n)
fifo.mutex.Unlock()
fifo.condWait.Signal()
return
}
func (fifo *logBufferFifo) Shutdown() {
fifo.mutex.Lock()
fifo.shutdown = true
fifo.mutex.Unlock()
fifo.condWait.Broadcast()
fifo.condFull.Broadcast()
}
func (fifo *logBufferFifo) WakeupAll() {
debugging.DEBUG_OUT2(" >>>>>>>>>>> in WakeupAll @Lock\n")
fifo.mutex.Lock()
debugging.DEBUG_OUT2(" +++++++++++ in WakeupAll\n")
fifo.wakeupIter++
fifo.mutex.Unlock()
debugging.DEBUG_OUT2(" +++++++++++ in WakeupAll @Unlock\n")
fifo.condWait.Broadcast()
fifo.condFull.Broadcast()
debugging.DEBUG_OUT2(" <<<<<<<<<<< in WakeupAll past @Broadcast\n")
}
func (fifo *logBufferFifo) IsShutdown() (ret bool) {
fifo.mutex.Lock()
ret = fifo.shutdown
fifo.mutex.Unlock()
return
}
// end generic
const TIMEOUT = time.Second * 10
type Client struct {
url string
clientId string
httpClient *http.Client
fifo *logBufferFifo // see fifo.go
ticker *time.Ticker
interval time.Duration
}
// maxBuffers: this number represents the amount of stored log buffers we will hold
// before dropping them. This can be from 1 to [max amount of bytes from greasego callback]
// In effect, this should be close to the same number as NumBanks is set in the target options
// for the greasego target
func NewSymphonyClient(url string, clientid string, maxBuffers uint32, heartbeatInterval time.Duration) *Client {
client := new(Client)
client.url = url
client.clientId = clientid
client.httpClient = &http.Client{
Timeout: TIMEOUT,
}
client.fifo = New_logBufferFifo(maxBuffers)
client.interval = heartbeatInterval
fmt.Printf("")
return client
}
func (client *Client) Start() {
go client.clientWorker()
client.startTicker()
debugging.DEBUG_OUT("client started: %s\n", client.url)
}
func (client *Client) SubmitLogs(data *greasego.TargetCallbackData, godata []byte) {
buf := new(logBuffer)
buf.data = data
buf.godata = godata
dropped, _ := client.fifo.Push(buf)
if dropped {
debugging.DEBUG_OUT("Dropped some log entries!!!!!!\n\n")
}
}
func (client *Client) startTicker() {
client.ticker = time.NewTicker(client.interval)
go func() {
// only dump ticker info when in debug build:
if debugging.DebugEnabled {
for t := range client.ticker.C {
debugging.DEBUG_OUT("Tick at %d", t.Unix())
debugging.DumpMemStats()
client.fifo.WakeupAll()
}
}
}()
}
// the client worker goroutine
// does the sending of data to the server
func (client *Client) clientWorker() {
closeHttp := func(r *http.Response) {
r.Body.Close()
}
closeBuf := func(buf *logBuffer) {
greasego.RetireCallbackData(buf.data)
}
var next *logBuffer
for true {
next = client.fifo.PopOrWait()
if next == nil {
if client.fifo.IsShutdown() {
debugging.DEBUG_OUT("clientWorker @shutdown - via FIFO")
break
} else {
// SEND HEARTBEAT or whatever
continue
}
}
// send data to server0
// req, err := http.NewRequest("POST", client.url, bytes.NewReader(next.data.GetBufferAsSlice()))
req, err := http.NewRequest("POST", client.url, bytes.NewReader(next.godata))
if err != nil {
debugging.DEBUG_OUT("XXXXXXXXXXXXXXXXXXXXXXX error on new request %+v\n", err)
closeBuf(next)
} else {
req.Header.Set("Content-Type", "application/json")
req.Header.Add("X-Symphony-ClientId", client.clientId)
resp, err := client.httpClient.Do(req)
if err != nil {
debugging.DEBUG_OUT("XXXXXXXXXXXXXXXXXXXXXXX error on sending request %+v\n", err)
closeBuf(next)
} else {
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
debugging.DEBUG_OUT(" OKOKOKOKOKOKOKOKOK -----> retired callback data\n\n")
closeBuf(next)
}
if resp != nil {
closeHttp(resp)
}
}
}
}
func (client *Client) Shutdown() {
client.ticker.Stop()
client.fifo.Shutdown()
// all go routines should end
}
// Test for our FIFO above
// func TestFifo() {
// buffer := New_logBufferFifo(5)
// exits := 0
// // addsome := func(z int, name string){
// // for n :=0;n < z;n++ {
// // dropped, _ := buffer.Push(new(logBuffer))
// // if(dropped) {
// // fmt.Printf("[%s] Added and Dropped a buffer!: %d\n",name,n)
// // } else {
// // fmt.Printf("[%s] added a buffer: %d\n",name,n)
// // }
// // }
// // }
// addsome := func(z int, name string){
// for n :=0;n < z;n++ {
// ok := buffer.PushOrWait(new(logBuffer))
// if(ok) {
// fmt.Printf("[%s] Added a buffer!: %d\n",name,n)
// } else {
// fmt.Printf("[%s] (add buffer) must be shutdown: %d\n",name,n)
// break
// }
// }
// }
// removesome := func(z int, name string){
// for n :=0;n < z;n++ {
// fmt.Printf("[%s] PopOrWait()...\n",name)
// outbuf := buffer.PopOrWait()
// if(outbuf != nil) {
// fmt.Printf("[%s] Got a buffer\n",name)
// } else {
// fmt.Printf("[%s] Got nil - must be shutdown\n",name)
// break
// }
// }
// fmt.Printf("[%s] removesome Done :)\n",name)
// exits++;
// }
// shutdown_in := func(s int) {
// time.Sleep(time.Duration(s)*time.Second)
// fmt.Printf("Shutting down FIFO\n")
// buffer.Shutdown()
// fmt.Printf("Shutdown FIFO complete\n")
// }
// go addsome(10,"one")
// go removesome(10,"remove_one")
// go addsome(10,"two")
// go removesome(10,"remove_two")
// go addsome(10,"three")
// go removesome(11,"remove_three")
// shutdown_in(5)
// time.Sleep(time.Duration(2)*time.Second)
// if exits != 3 {
// fmt.Printf("exits: %d\n",exits)
// panic("Not all exited")
// }
// }
// var netClient = &http.Client{
// Timeout: time.Second * 10,
// }