network.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package docker
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/netip"
  7. fw "git.buran.team/main/fairwind"
  8. mobynetwork "github.com/moby/moby/api/types/network"
  9. moby "github.com/moby/moby/client"
  10. )
  11. var DEFAULT_NETWORK_CIDR = netip.MustParsePrefix("172.16.0.0/24")
  12. var DEFAULT_NETWORK_GATEWAY = netip.MustParseAddr("172.16.0.1")
  13. var ErrNetworkAlreadyExists = errors.New("network already exists")
  14. type Network struct {
  15. ctx context.Context
  16. log *fw.Log
  17. client *Docker
  18. name string
  19. cidr netip.Prefix
  20. gateway netip.Addr
  21. }
  22. func NewNetwork(ctx context.Context, log *fw.Log, client *Docker, name string, cidr netip.Prefix, gateway netip.Addr) *Network {
  23. return &Network{
  24. ctx: ctx,
  25. log: log,
  26. client: client,
  27. name: name,
  28. cidr: cidr,
  29. gateway: gateway,
  30. }
  31. }
  32. func (this *Network) Name() string {
  33. return this.name
  34. }
  35. func (this *Network) Create() error {
  36. networks, err := this.client.Docker.NetworkList(this.ctx, moby.NetworkListOptions{})
  37. if err != nil {
  38. return fmt.Errorf("can't create network: %w", err)
  39. }
  40. for _, network := range networks.Items {
  41. if network.Name == this.name {
  42. return ErrNetworkAlreadyExists
  43. }
  44. }
  45. _, err = this.client.Docker.NetworkCreate(
  46. this.ctx,
  47. this.name,
  48. moby.NetworkCreateOptions{
  49. Driver: "bridge",
  50. IPAM: &mobynetwork.IPAM{
  51. Config: []mobynetwork.IPAMConfig{
  52. {
  53. Subnet: this.cidr,
  54. Gateway: this.gateway,
  55. },
  56. },
  57. },
  58. },
  59. )
  60. if err != nil {
  61. return fmt.Errorf("can't create network: %w", err)
  62. }
  63. return nil
  64. }
  65. func (this *Network) Delete() error {
  66. _, err := this.client.Docker.NetworkRemove(this.ctx, this.name, moby.NetworkRemoveOptions{})
  67. if err != nil {
  68. return fmt.Errorf("can't delete network: %w", err)
  69. }
  70. return nil
  71. }