handler.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package provisioning
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "strconv"
  7. "git.linuxforward.com/byom/byom-onboard/internal/common/models"
  8. "git.linuxforward.com/byom/byom-onboard/internal/platform/database"
  9. "github.com/gin-gonic/gin"
  10. )
  11. type Handler struct {
  12. client ProviderClient
  13. db *database.Database
  14. }
  15. func NewHandler(client ProviderClient, db *database.Database) *Handler {
  16. return &Handler{
  17. client: client,
  18. }
  19. }
  20. func (h *Handler) AddVPS(c *gin.Context) {
  21. var req models.AddVPSRequest
  22. if err := c.ShouldBindJSON(&req); err != nil {
  23. c.JSON(400, gin.H{"error": err.Error()})
  24. return
  25. }
  26. vps := models.VPSInstance{
  27. DisplayName: req.DisplayName,
  28. IpAddress: req.IpAddress,
  29. Plan: req.Plan,
  30. }
  31. if err := h.db.AddVPS(&vps); err != nil {
  32. c.JSON(500, gin.H{"error": err.Error()})
  33. return
  34. }
  35. c.JSON(200, gin.H{"message": "VPS added successfully"})
  36. }
  37. func (h *Handler) ListVPS(c *gin.Context) {
  38. instances, err := h.db.ListVPS()
  39. if err != nil {
  40. c.JSON(500, gin.H{"error": err.Error()})
  41. return
  42. }
  43. c.JSON(200, instances)
  44. }
  45. var mapPlanToVPS = map[string]string{
  46. "basic": "1-2-40",
  47. "pro": "2-4-80",
  48. "enterprise": "16-16-160",
  49. }
  50. func (h *Handler) FindVPSForPlan(plan string, userID uint) (string, string, error) {
  51. vps, ok := mapPlanToVPS[plan]
  52. if !ok {
  53. return "", "", fmt.Errorf("plan not found")
  54. }
  55. availableVPS, err := h.db.GetAvailableVPS(context.Background(), vps)
  56. if err != nil {
  57. return "", "", err
  58. }
  59. //assign the vps to the user
  60. id, err := strconv.ParseUint(availableVPS[0].ID, 10, 32)
  61. if err != nil {
  62. return "", "", err
  63. }
  64. if err := h.db.AssignVPSToUser(uint(id), userID); err != nil {
  65. return "", "", err
  66. }
  67. log.Println("Found", len(availableVPS), "available VPS for plan", plan)
  68. return availableVPS[0].DisplayName, availableVPS[0].IpAddress, nil
  69. }
  70. func (h *Handler) GetVPSStatus(c *gin.Context) {
  71. var req models.GetVPSStatusRequest
  72. if err := c.ShouldBindJSON(&req); err != nil {
  73. c.JSON(400, gin.H{"error": err.Error()})
  74. return
  75. }
  76. status, err := h.client.GetVPSStatus(req.ID)
  77. if err != nil {
  78. c.JSON(500, gin.H{"error": err.Error()})
  79. return
  80. }
  81. c.JSON(200, gin.H{"status": status})
  82. }