forked from P-E-D-L/proclone
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcloning_handler.go
More file actions
526 lines (443 loc) · 15 KB
/
cloning_handler.go
File metadata and controls
526 lines (443 loc) · 15 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
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
package handlers
import (
"fmt"
"log"
"net/http"
"path/filepath"
"strings"
"github.com/cpp-cyber/proclone/internal/cloning"
"github.com/cpp-cyber/proclone/internal/ldap"
"github.com/cpp-cyber/proclone/internal/proxmox"
"github.com/cpp-cyber/proclone/internal/tools"
"github.com/cpp-cyber/proclone/internal/tools/sse"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
// NewCloningHandler creates a new cloning handler, loading dependencies internally
func NewCloningHandler() (*CloningHandler, error) {
// Initialize database connection
dbClient, err := tools.NewDBClient()
if err != nil {
return nil, fmt.Errorf("failed to initialize database client: %w", err)
}
// Initialize Proxmox service
proxmoxService, err := proxmox.NewService()
if err != nil {
return nil, fmt.Errorf("failed to create Proxmox service: %w", err)
}
// Initialize LDAP service
ldapService, err := ldap.NewLDAPService()
if err != nil {
return nil, fmt.Errorf("failed to create LDAP service: %w", err)
}
// Initialize Cloning manager
cloningService, err := cloning.NewCloningService(proxmoxService, dbClient.DB(), ldapService)
if err != nil {
return nil, fmt.Errorf("failed to initialize cloning manager: %w", err)
}
log.Println("Cloning manager initialized")
return &CloningHandler{
Service: cloningService,
dbClient: dbClient,
}, nil
}
// CloneTemplateHandler handles requests to clone a template pool for a user or group
func (ch *CloningHandler) CloneTemplateHandler(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("id").(string)
var req CloneRequest
if !validateAndBind(c, &req) {
return
}
log.Printf("User %s requested cloning of template %s", username, req.Template)
publishedTemplates, err := ch.Service.DatabaseService.GetPublishedTemplates()
if err != nil {
log.Printf("Error fetching published templates: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to fetch published templates",
"details": err.Error(),
})
return
}
// Check if the requested template is in the list of published templates
templateFound := false
for _, tmpl := range publishedTemplates {
if tmpl.Name == req.Template {
templateFound = true
break
}
}
if !templateFound {
log.Printf("Template %s not found or not published", req.Template)
c.JSON(http.StatusBadRequest, gin.H{
"error": "Template not found or not published",
"details": fmt.Sprintf("Template %s is not available for cloning", req.Template),
})
return
}
// Check for existing deployments before starting SSE
targetPoolName := fmt.Sprintf("%s_%s", req.Template, username)
isValid, err := ch.Service.ValidateCloneRequest(targetPoolName, username)
if err != nil {
log.Printf("Error validating deployment for user %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to validate existing deployments",
"details": err.Error(),
})
return
}
if !isValid {
log.Printf("Template %s is already deployed for user %s or they have exceeded deployment limits", req.Template, username)
c.JSON(http.StatusConflict, gin.H{
"error": "Deployment not allowed",
"details": fmt.Sprintf("Template %s is already deployed for %s or they have exceeded the maximum of 5 deployed pods", req.Template, username),
})
return
}
// Create new sse object for streaming
sseWriter, err := sse.NewWriter(c.Writer)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to initialize SSE",
"details": err.Error(),
})
return
}
sseWriter.Send(
cloning.ProgressMessage{
Message: "Retrieving template information",
Progress: 0,
},
)
// Create the cloning request using the new format
cloneReq := cloning.CloneRequest{
Template: req.Template,
CheckExistingDeployments: false, // Already checked above
Targets: []cloning.CloneTarget{
{
Name: username,
IsGroup: false,
},
},
SSE: sseWriter,
}
if err := ch.Service.CloneTemplate(cloneReq); err != nil {
log.Printf("Error cloning template: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to clone template",
"details": err.Error(),
})
return
}
log.Printf("Template %s cloned successfully for user %s", req.Template, username)
c.JSON(http.StatusOK, gin.H{"success": true})
}
// ADMIN: BulkCloneTemplateHandler handles POST requests for cloning multiple templates for a list of users
func (ch *CloningHandler) AdminCloneTemplateHandler(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("id").(string)
var req AdminCloneRequest
if !validateAndBind(c, &req) {
return
}
log.Printf("%s requested bulk cloning of template %s", username, req.Template)
// Build targets slice from usernames and groups
var targets []cloning.CloneTarget
// Add users as targets
for _, user := range req.Usernames {
targets = append(targets, cloning.CloneTarget{
Name: user,
IsGroup: false,
})
}
// Add groups as targets
for _, group := range req.Groups {
targets = append(targets, cloning.CloneTarget{
Name: group,
IsGroup: true,
})
}
// Create new sse object for streaming
sseWriter, err := sse.NewWriter(c.Writer)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to initialize SSE",
"details": err.Error(),
})
return
}
// Create clone request
cloneReq := cloning.CloneRequest{
Template: req.Template,
Targets: targets,
CheckExistingDeployments: false,
StartingVMID: req.StartingVMID,
SSE: sseWriter,
}
// Perform clone operation
err = ch.Service.CloneTemplate(cloneReq)
if err != nil {
log.Printf("Admin %s encountered error while bulk cloning template: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to clone templates",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Templates cloned successfully",
})
}
// DeletePodHandler handles requests to delete a pod
func (ch *CloningHandler) DeletePodHandler(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("id").(string)
var req DeletePodRequest
if !validateAndBind(c, &req) {
return
}
log.Printf("User %s requested deletion of pod %s", username, req.Pod)
// Check if the pod belongs to the user (maybe allow users to delete group pods in the future?)
if !strings.Contains(req.Pod, username) {
c.JSON(http.StatusForbidden, gin.H{
"error": "You do not have permission to delete this pod",
"details": fmt.Sprintf("Pod %s does not belong to user %s", req.Pod, username),
})
return
}
err := ch.Service.DeletePod(req.Pod)
if err != nil {
log.Printf("Error deleting %s pod: %v", req.Pod, err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to delete pod",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Pod deleted successfully"})
}
func (ch *CloningHandler) AdminDeletePodHandler(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("id").(string)
var req AdminDeletePodRequest
if !validateAndBind(c, &req) {
return
}
log.Printf("Admin %s requested deletion of pods: %v", username, req.Pods)
var errors []error
for _, pod := range req.Pods {
err := ch.Service.DeletePod(pod)
if err != nil {
errors = append(errors, fmt.Errorf("failed to delete pod %s: %v", pod, err))
}
}
if len(errors) > 0 {
log.Printf("Admin %s encountered errors while deleting pods: %v", username, errors)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to delete pods",
"details": errors,
})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Pods deleted successfully"})
}
func (ch *CloningHandler) GetUnpublishedTemplatesHandler(c *gin.Context) {
templates, err := ch.Service.GetUnpublishedTemplates()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to retrieve unpublished templates",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"templates": templates,
"count": len(templates),
})
}
// PRIVATE: GetPodsHandler handles GET requests for retrieving a user's pods
func (ch *CloningHandler) GetPodsHandler(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("id").(string)
pods, err := ch.Service.GetPods(username)
if err != nil {
log.Printf("Error retrieving pods for user %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve pods", "details": err.Error()})
return
}
// Loop through the user's deployed pods and add template information
for i := range pods {
templateName := strings.Replace(strings.ToLower(pods[i].Name[5:]), fmt.Sprintf("_%s", strings.ToLower(username)), "", 1)
templateInfo, err := ch.Service.DatabaseService.GetTemplateInfo(templateName)
if err != nil {
log.Printf("Error retrieving template info for pod %s: %v", pods[i].Name, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve template info for pod", "details": err.Error()})
return
}
pods[i].Template = templateInfo
}
c.JSON(http.StatusOK, gin.H{"pods": pods})
}
// ADMIN: AdminGetPodsHandler handles GET requests for retrieving all pods
func (ch *CloningHandler) AdminGetPodsHandler(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("id").(string)
pods, err := ch.Service.AdminGetPods()
if err != nil {
log.Printf("Error retrieving all pods for admin %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve pods for user", "details": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"pods": pods})
}
// PRIVATE: GetTemplatesHandler handles GET requests for retrieving templates
func (ch *CloningHandler) GetTemplatesHandler(c *gin.Context) {
templates, err := ch.Service.DatabaseService.GetTemplates()
if err != nil {
log.Printf("Error retrieving templates: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to retrieve templates",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"templates": templates,
"count": len(templates),
})
}
// ADMIN: GetPublishedTemplatesHandler handles GET requests for retrieving all templates
func (ch *CloningHandler) AdminGetTemplatesHandler(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("id").(string)
templates, err := ch.Service.DatabaseService.GetPublishedTemplates()
if err != nil {
log.Printf("Error retrieving all templates for admin %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to retrieve all templates",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"templates": templates,
"count": len(templates),
})
}
// PRIVATE: GetTemplateImageHandler handles GET requests for retrieving a template's image
func (ch *CloningHandler) GetTemplateImageHandler(c *gin.Context) {
filename := c.Param("filename")
config := ch.Service.DatabaseService.GetTemplateConfig()
filePath := filepath.Join(config.UploadDir, filename)
// Serve the file
c.File(filePath)
}
// ADMIN: PublishTemplateHandler handles POST requests for publishing a template
func (ch *CloningHandler) PublishTemplateHandler(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("id").(string)
var req PublishTemplateRequest
if !validateAndBind(c, &req) {
return
}
log.Printf("Admin %s requested publishing of template %s", username, req.Template.Name)
if err := ch.Service.PublishTemplate(req.Template); err != nil {
log.Printf("Error publishing template for admin %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to publish template",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "Template published successfully",
})
}
// ADMIN: EditTemplateHandler handles POST requests for editing a published template
func (ch *CloningHandler) EditTemplateHandler(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("id").(string)
var req PublishTemplateRequest
if !validateAndBind(c, &req) {
return
}
log.Printf("Admin %s requested editing of template %s", username, req.Template.Name)
if err := ch.Service.DatabaseService.EditTemplate(req.Template); err != nil {
log.Printf("Error editing template for admin %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to edit template",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "Template edited successfully",
})
}
// ADMIN: DeleteTemplateHandler handles POST requests for deleting a template
func (ch *CloningHandler) DeleteTemplateHandler(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("id").(string)
var req TemplateRequest
if !validateAndBind(c, &req) {
return
}
log.Printf("Admin %s requested deletion of template %s", username, req.Template)
if err := ch.Service.DatabaseService.DeleteTemplate(req.Template); err != nil {
log.Printf("Error deleting template for admin %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to delete template",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "Template deleted successfully",
})
}
// ADMIN: ToggleTemplateVisibilityHandler handles POST requests for toggling a template's visibility
func (ch *CloningHandler) ToggleTemplateVisibilityHandler(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("id").(string)
var req TemplateRequest
if !validateAndBind(c, &req) {
return
}
log.Printf("Admin %s requested toggling visibility of template %s", username, req.Template)
if err := ch.Service.DatabaseService.ToggleTemplateVisibility(req.Template); err != nil {
log.Printf("Error toggling template visibility for admin %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to toggle template visibility",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "Template visibility toggled successfully",
})
}
// ADMIN: UploadTemplateImageHandler handles POST requests for uploading a template's image
func (ch *CloningHandler) UploadTemplateImageHandler(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("id").(string)
log.Printf("Admin %s requested uploading a template image", username)
result, err := ch.Service.DatabaseService.UploadTemplateImage(c)
if err != nil {
log.Printf("Error uploading template image for admin %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to upload template image",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, result)
}
// HealthCheck checks the database connection health
func (ch *CloningHandler) HealthCheck() error {
return ch.dbClient.HealthCheck()
}
// Reconnect attempts to reconnect to the database
func (ch *CloningHandler) Reconnect() error {
return ch.dbClient.Connect()
}