network.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package executor
  2. import (
  3. "fmt"
  4. "net/netip"
  5. fw "git.buran.team/main/fairwind"
  6. dockerpkg "git.buran.team/main/cep/docker"
  7. )
  8. type Host struct {
  9. Name string
  10. IP string
  11. }
  12. type Network struct {
  13. global *Global
  14. network *dockerpkg.Network
  15. hosts []Host
  16. }
  17. func NewNetwork(global *Global, ticket *Ticket, hosts []Host) (*Network, error) {
  18. cidr, err := networkCIDR(ticket.Index)
  19. if err != nil {
  20. global.Log.Information("can't create network", fw.LogError(err))
  21. return nil, err
  22. }
  23. gateway, err := networkGateway(ticket.Index)
  24. if err != nil {
  25. global.Log.Information("can't create network", fw.LogError(err))
  26. return nil, err
  27. }
  28. network := dockerpkg.NewNetwork(
  29. global.Ctx,
  30. global.Log,
  31. global.Docker,
  32. networkName(
  33. ticket.Index,
  34. ),
  35. cidr,
  36. gateway,
  37. )
  38. return &Network{
  39. global: global,
  40. network: network,
  41. hosts: hosts,
  42. }, nil
  43. }
  44. func (this *Network) Create() error {
  45. return this.network.Create()
  46. }
  47. func (this *Network) Delete() error {
  48. return this.network.Delete()
  49. }
  50. func (this *Network) Network() *dockerpkg.Network {
  51. return this.network
  52. }
  53. func (this *Network) Hosts() []Host {
  54. return this.hosts
  55. }
  56. func networkName(index int) string {
  57. return fmt.Sprintf("network-%d", index)
  58. }
  59. func networkCIDR(index int) (netip.Prefix, error) {
  60. prefix, err := netip.ParsePrefix(fmt.Sprintf("172.16.%d.0/24", index))
  61. if err != nil {
  62. return netip.Prefix{}, fmt.Errorf("can't parse prefix: %w", err)
  63. }
  64. return prefix, nil
  65. }
  66. func networkGateway(index int) (netip.Addr, error) {
  67. address, err := netip.ParseAddr(fmt.Sprintf("172.16.%d.1", index))
  68. if err != nil {
  69. return netip.Addr{}, fmt.Errorf("can't parse address: %w", err)
  70. }
  71. return address, nil
  72. }