-
Notifications
You must be signed in to change notification settings - Fork 1
/
log_service.go
196 lines (159 loc) · 4.22 KB
/
log_service.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
package tracer
import (
"io"
"log"
"time"
"strconv"
"net/http"
"encoding/json"
"encoding/base64"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/mattn/go-sqlite3"
)
type DbLogger struct {
connection *gorm.DB
IdsCache *TerminalIdsCache
}
func (logger DbLogger) storeEntry(termianlId uint64, msg string) {
encodedMsg := base64.StdEncoding.EncodeToString([]byte(msg))
entry := LogEntry{TerminalId : termianlId,
Timestamp : time.Now().UTC().Format(time.RFC3339Nano),
Message : encodedMsg}
go logger.connection.Create(&entry)
go logger.IdsCache.AppendId(termianlId)
}
func (logger DbLogger) buildLogs(res http.ResponseWriter,
termId <- chan uint64,
startTime <- chan time.Time,
quitSignal chan bool) {
type entryType struct {
Timestamp string `json:"timestamp"`
Message string `json:"message"`
}
type responseType struct {
Entries []entryType `json:"entries"`
}
entries := responseType{}
var id uint64
var timePoint time.Time
var status int = 0
const allGot = 2
Loop:
for {
select {
case id = <-termId:
status += 1
if status == allGot {
break Loop
}
continue
case <- quitSignal:
return
case timePoint = <-startTime:
status += 1
if status == allGot {
break Loop
}
continue
}
}
sync := make(chan bool)
go func() {
logEntries := make([]LogEntry, 0)
logger.connection.
Where("terminal_id = ? and timestamp >= ?", id, timePoint.Format(time.RFC3339Nano)).
Find(&logEntries)
entries.Entries = make([]entryType, len(logEntries))
for i, v := range logEntries {
entries.Entries[i] = entryType{ v.Timestamp, v.Message }
}
sync <- true
}()
encoder := json.NewEncoder(res)
<- sync
encoder.Encode(entries)
quitSignal <- true
}
func NewDbLogger(dbName string) (DbLogger, error) {
conn, err := gorm.Open("sqlite3", dbName)
return DbLogger{&conn, nil}, err
}
func (handler DbLogger) PrepareDB() {
if !handler.connection.HasTable(&LogEntry{}) {
handler.connection = handler.connection.CreateTable(&LogEntry{})
}
}
func (handler DbLogger) ServeHTTP(res http.ResponseWriter, req *http.Request) {
if req.Method == "GET" {
handler.GetLogs(res, req)
return
} else if req.Method == "POST" {
handler.AddNewEntry(res, req)
return
} else {
res.WriteHeader(http.StatusBadRequest)
return
}
}
func (handler DbLogger) AddNewEntry(res http.ResponseWriter,
req *http.Request) {
decoder := json.NewDecoder(req.Body)
type message struct {
Msg string `json:"message"`
}
var msg message
{
err := decoder.Decode(&msg)
if err != nil && err != io.EOF {
log.Println("Unable to decode terminal message. ", err)
res.WriteHeader(http.StatusBadRequest)
return
}
}
vars := mux.Vars(req)
id_str := vars["id"]
if len(msg.Msg) == 0 {
log.Println("Empty message! For terminal ", id_str)
res.WriteHeader(http.StatusBadRequest)
return
}
id, err := strconv.ParseUint(id_str, 10, 64)
if err != nil {
log.Println(err)
res.WriteHeader(http.StatusInternalServerError)
return
}
go handler.storeEntry(id, msg.Msg)
}
func (handler DbLogger) GetLogs(res http.ResponseWriter, req *http.Request) {
idSender := make(chan uint64)
timeSender := make(chan time.Time)
quitSignal := make(chan bool)
go handler.buildLogs(res, idSender, timeSender, quitSignal)
vars := mux.Vars(req)
id_str := vars["id"]
id, err := strconv.ParseUint(id_str, 10, 64)
if err != nil {
log.Println(err)
res.WriteHeader(http.StatusInternalServerError)
quitSignal <- true
return
}
requestValues := req.URL.Query()
_, ok := requestValues["since"]
idSender <- id
if ok {
timePt, err := time.Parse(time.RFC3339Nano, requestValues["since"][0])
if err != nil {
log.Println(err)
res.WriteHeader(http.StatusBadRequest)
quitSignal <- true
return
}
timeSender <- timePt
} else {
timeSender <- time.Unix(0, 0)
}
<- quitSignal
}