-
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathupload_handler.go
More file actions
187 lines (164 loc) · 6.08 KB
/
upload_handler.go
File metadata and controls
187 lines (164 loc) · 6.08 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
/*
* Copyright 2022-present Kuei-chun Chen. All rights reserved.
* upload_handler.go
*/
package hatchet
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/julienschmidt/httprouter"
)
// uploadSemaphore limits concurrent upload processing to prevent database contention
// Even with WAL mode, limiting concurrent writes improves performance
var uploadSemaphore = make(chan struct{}, 2)
const (
maxUploadSize = 200 << 20 // 200 MB max file size
maxUploadSizeMB = 200
)
// UploadHandler handles file uploads for processing
func UploadHandler(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
if r.Method != http.MethodPost {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusMethodNotAllowed)
json.NewEncoder(w).Encode(map[string]interface{}{"status": "error", "error": "Method not allowed"})
return
}
// Parse multipart form - 32MB max in memory, rest goes to temp files
if err := r.ParseMultipartForm(32 << 20); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]interface{}{"status": "error", "error": fmt.Sprintf("Failed to parse form: %v", err)})
return
}
file, header, err := r.FormFile("logfile")
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]interface{}{"status": "error", "error": fmt.Sprintf("Failed to get file: %v", err)})
return
}
defer file.Close()
// Validate file size
if header.Size > maxUploadSize {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "error",
"error": fmt.Sprintf("File too large (%d MB). Maximum size: %d MB", header.Size>>20, maxUploadSizeMB),
})
return
}
// Get optional hatchet name from form, default to filename
hatchetName := r.FormValue("name")
if hatchetName == "" {
hatchetName = header.Filename
// Remove common extensions
hatchetName = strings.TrimSuffix(hatchetName, ".gz")
hatchetName = strings.TrimSuffix(hatchetName, ".log")
}
// Get unique name (adds _2, _3 suffix if name exists, like CLI does)
existingNames, _ := GetExistingHatchetNames()
hatchetName = getUniqueHatchetName(hatchetName, existingNames)
// Create temp file to store the upload
tempDir := os.TempDir()
tempFile, err := os.CreateTemp(tempDir, "hatchet-upload-*")
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]interface{}{"status": "error", "error": fmt.Sprintf("Failed to create temp file: %v", err)})
return
}
tempPath := tempFile.Name()
// Stream upload to temp file (memory efficient)
written, err := io.Copy(tempFile, file)
tempFile.Close()
if err != nil {
os.Remove(tempPath)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]interface{}{"status": "error", "error": fmt.Sprintf("Failed to save file: %v", err)})
return
}
log.Printf("Uploaded %s (%d bytes) -> %s", header.Filename, written, tempPath)
// Validate file is a MongoDB log by checking content
if !isMongoDBLog(tempPath) {
os.Remove(tempPath)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "error",
"error": "Not a valid MongoDB log file. File must contain MongoDB logv2 JSON format.",
})
return
}
// Create a new Logv2 instance for this upload to support concurrent uploads
// Copy config from the singleton but use separate state
baseLogv2 := GetLogv2()
uploadLogv2 := &Logv2{
url: baseLogv2.url,
hatchetName: hatchetName,
version: baseLogv2.version,
cacheSize: baseLogv2.cacheSize,
from: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC), // Include all past logs
to: time.Now().Add(24 * time.Hour), // Include logs up to tomorrow
}
go func(name string, logv2 *Logv2, filename string) {
// Acquire semaphore to limit concurrent database writes
uploadSemaphore <- struct{}{}
defer func() { <-uploadSemaphore }()
defer os.Remove(tempPath) // Clean up temp file when done
if err := logv2.Analyze(tempPath, 0); err != nil { // marker=0 to keep pre-set hatchetName
log.Printf("Error processing upload %s: %v", filename, err)
return
}
logv2.PrintSummary()
log.Printf("Finished processing upload: %s -> %s", filename, name)
}(hatchetName, uploadLogv2, header.Filename)
// Return immediately with status
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "processing",
"name": hatchetName,
"size": written,
"message": fmt.Sprintf("File '%s' uploaded and processing started", header.Filename),
})
}
// UploadStatusHandler checks the status of a processing job
func UploadStatusHandler(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
hatchetName := params.ByName("name")
existingNames, err := GetExistingHatchetNames()
if err != nil {
log.Printf("UploadStatusHandler: error getting hatchet names: %v", err)
}
log.Printf("UploadStatusHandler: checking for '%s' in %v", hatchetName, existingNames)
for _, name := range existingNames {
if name == hatchetName {
log.Printf("UploadStatusHandler: found '%s', returning complete", hatchetName)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "complete",
"name": hatchetName,
})
return
}
}
log.Printf("UploadStatusHandler: '%s' not found, returning processing", hatchetName)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "processing",
"name": hatchetName,
})
}
// getUploadDir ensures upload directory exists and returns path
func getUploadDir() string {
dir := filepath.Join(".", "data", "uploads")
os.MkdirAll(dir, 0755)
return dir
}