-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
291 lines (243 loc) · 6.67 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
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
package main
import (
"bufio"
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"github.com/brianvoe/gofakeit/v6"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"golang.org/x/sys/unix"
)
const (
deploymentDir = "./deployment-logs"
logIdleTimeout = 60
readHeaderTimeout = 5 * time.Second
)
var (
clients = make(map[string]*gin.Context)
clientsMtx sync.Mutex
)
func main() {
if err := os.MkdirAll(deploymentDir, 0755); err != nil {
log.Fatalf("failed to create deployment directory: %v", err)
}
r := gin.Default()
r.GET("/", handleIndex)
r.POST("/deployment", handleDeployment)
r.GET("/logs/:id", streamLogs)
r.POST("/disconnect", handleDisconnect)
r.POST("/ping", handlePing)
httpServer := &http.Server{
Addr: ":8080",
ReadHeaderTimeout: readHeaderTimeout,
Handler: r,
}
go func() {
log.Printf("listening on %s\n", httpServer.Addr)
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
fmt.Fprintf(os.Stderr, "error listening and serving: %s\n", err)
}
}()
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
<-ctx.Done()
log.Println("Shutting down server...")
notifyClientsOfTermination()
cleanupDirectory()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
defer cancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
log.Fatalf("error during server shutdown : %v", err)
}
log.Println("Server exited properly")
}
func handleIndex(c *gin.Context) {
content, err := os.ReadFile("index.html")
if err != nil {
c.String(http.StatusInternalServerError, "error loading index file")
return
}
c.Data(http.StatusOK, "text/html; charset=utf-8", content)
}
func handleDeployment(c *gin.Context) {
deploymentID := uuid.New().String()
filePath := filepath.Join(deploymentDir, deploymentID+".txt")
file, err := os.Create(filePath)
if err != nil {
log.Fatalf("error creating new deployment: %s", err)
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
log.Fatalf("error deleting deployment: %s, error: %s", deploymentID, err)
}
}(file)
go generateSentences(filePath)
c.JSON(http.StatusOK, gin.H{
"deployment_id": deploymentID,
})
}
func generateSentences(filePath string) {
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Printf("error occurred during deployment: %s", err)
return
}
defer file.Close()
for i := 0; i < 60; i++ {
timeStamp := time.Now().Format(time.RFC3339Nano)
sentence := gofakeit.Sentence(30)
logEntry := fmt.Sprintf("%s: %s\n", timeStamp, sentence)
if _, err := file.WriteString(logEntry); err != nil {
log.Printf("error writing to file %s: %v", filePath, err)
return
}
time.Sleep(300 * time.Millisecond)
}
}
func streamLogs(c *gin.Context) {
deploymentID := c.Param("id")
filePath := filepath.Join(deploymentDir, deploymentID+".txt")
file, err := os.Open(filePath)
if err != nil {
log.Printf("error opening the file for streaming logs, deployment-id: %s, error: %s", deploymentID, err)
return
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
fmt.Printf("error closing file for streaming logs, deployment-id: %s, error: %s", deploymentID, err)
}
}(file)
clientID := uuid.New().String()
setupResponseHeaders(c, clientID)
addClient(clientID, c)
defer removeClient(clientID)
reader := bufio.NewReader(file)
handleLogStreaming(c, reader, clientID)
}
func setupResponseHeaders(c *gin.Context, clientID string) {
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")
c.Header("X-Client-ID", clientID)
c.Writer.WriteHeaderNow() // Disable buffering
}
func handleLogStreaming(c *gin.Context, reader *bufio.Reader, clientID string) {
eofCount := 0
for {
if checkForInactivity(c, clientID, eofCount) {
break
}
line, err := readLogLine(reader)
if err != nil {
if err.Error() == "EOF" {
time.Sleep(400 * time.Millisecond)
eofCount++
continue
}
log.Printf("error reading file for streaming logs: %s", err)
continue
}
if !sendLogLine(c, line, clientID) {
return
}
eofCount = 0
}
}
func checkForInactivity(c *gin.Context, clientID string, eofCount int) bool {
if eofCount == logIdleTimeout {
_, err := fmt.Fprintf(c.Writer, "event: inactivity\ndata: closing connection due to inactivity.\n\n")
if err != nil {
log.Printf("unable to notify client %s: %v", clientID, err)
} else {
c.Writer.Flush()
}
return true
}
return false
}
func readLogLine(reader *bufio.Reader) (string, error) {
line, err := reader.ReadString('\n')
line = strings.TrimRight(line, "\n")
return line, err
}
func sendLogLine(c *gin.Context, line, clientID string) bool {
// Write the log line to the client in SSE format
_, err := fmt.Fprintf(c.Writer, "data: %s\n\n", line)
if err != nil {
if isEPIPE(err) {
log.Printf("client connection closed: %s", err)
} else if errors.Is(err, context.Canceled) {
log.Printf("Request canceled: %s\n", clientID)
} else {
log.Printf("Error sending logs to client %s: %v\n", clientID, err)
}
return false // Indicate failure to send
}
// Flush the data to the client
c.Writer.Flush()
return true
}
func isEPIPE(err error) bool {
var sErr *os.SyscallError
return errors.As(err, &sErr) && errors.Is(sErr.Err, unix.EPIPE)
}
func cleanupDirectory() {
log.Println("Cleaning up directory...")
if err := os.RemoveAll(deploymentDir); err != nil {
log.Printf("error removing directory %s: %v", deploymentDir, err)
} else {
log.Println("Cleanup complete.")
}
}
func notifyClientsOfTermination() {
clientsMtx.Lock()
defer clientsMtx.Unlock()
for id, c := range clients {
_, err := fmt.Fprintf(c.Writer, "event: termination\ndata: Server is shutting down.\n\n")
if err != nil {
log.Printf("unable to notify client %s: %v", id, err)
} else {
c.Writer.Flush()
}
}
}
func handleDisconnect(c *gin.Context) {
clientID := c.GetHeader("X-Client-ID")
if clientID == "" {
c.String(http.StatusBadRequest, "Missing client ID")
return
}
removeClient(clientID)
c.String(http.StatusOK, "Disconnected")
}
func addClient(id string, c *gin.Context) {
clientsMtx.Lock()
defer clientsMtx.Unlock()
clients[id] = c
}
func removeClient(id string) {
clientsMtx.Lock()
defer clientsMtx.Unlock()
delete(clients, id)
}
func handlePing(c *gin.Context) {
clientID := c.GetHeader("X-Client-ID")
if clientID != "" {
// Optionally log or update client activity here
c.String(http.StatusOK, "Pong")
} else {
c.String(http.StatusBadRequest, "Missing client ID")
}
}