Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

81 строка
1.6 KiB

  1. package main
  2. import (
  3. "github.com/Depado/ginprom"
  4. "github.com/gin-gonic/gin"
  5. "github.com/mroth/weightedrand/v2"
  6. "github.com/sirupsen/logrus"
  7. ginlogrus "github.com/toorop/gin-logrus"
  8. "net/http"
  9. "strconv"
  10. )
  11. var log = logrus.New()
  12. func assignTarget(c *gin.Context) {
  13. targets := state.GetTargets()
  14. string_size_hint := c.Query("SIZE_HINT")
  15. size_hint, err := strconv.ParseInt(string_size_hint, 10, 64)
  16. if err != nil {
  17. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
  18. "reason": "Invalid size hint",
  19. })
  20. return
  21. }
  22. var choices []weightedrand.Choice[ServerSpec, int]
  23. for _, target := range targets {
  24. expectedFreeSpace := target.FreeSpace - size_hint
  25. if expectedFreeSpace > int64(target.Target.MinimumFreeSpace) && target.Weight > 0 {
  26. choices = append(choices, weightedrand.NewChoice(target.Target, target.Weight))
  27. }
  28. }
  29. if len(choices) == 0 {
  30. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
  31. "reason": "No more targets available",
  32. })
  33. }
  34. chooser, _ := weightedrand.NewChooser(choices...)
  35. result := chooser.Pick()
  36. c.JSON(http.StatusOK, gin.H{
  37. "url": result.Url,
  38. })
  39. }
  40. func setupRouter() *gin.Engine {
  41. r := gin.New()
  42. r.Use(ginlogrus.Logger(log), gin.Recovery())
  43. p := ginprom.New(
  44. ginprom.Engine(r),
  45. ginprom.Subsystem("gin"),
  46. ginprom.Path("/metrics"),
  47. )
  48. r.Use(p.Instrument())
  49. r.GET("/ping", func(c *gin.Context) {
  50. c.JSON(http.StatusOK, gin.H{
  51. "message": "pong",
  52. })
  53. })
  54. r.GET("/offload_target", assignTarget)
  55. return r
  56. }
  57. func main() {
  58. initState()
  59. go state.UpdateThread()
  60. router := setupRouter()
  61. err := router.Run(state.GetListenAddr())
  62. log.WithError(err).Fatal("Failed to run router")
  63. }