| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package docker
- import (
- "context"
- "errors"
- "fmt"
- "net/netip"
- fw "git.buran.team/main/fairwind"
- mobynetwork "github.com/moby/moby/api/types/network"
- moby "github.com/moby/moby/client"
- )
- var DEFAULT_NETWORK_CIDR = netip.MustParsePrefix("172.16.0.0/24")
- var DEFAULT_NETWORK_GATEWAY = netip.MustParseAddr("172.16.0.1")
- var ErrNetworkAlreadyExists = errors.New("network already exists")
- type Network struct {
- ctx context.Context
- log *fw.Log
- client *Docker
- name string
- cidr netip.Prefix
- gateway netip.Addr
- }
- func NewNetwork(ctx context.Context, log *fw.Log, client *Docker, name string, cidr netip.Prefix, gateway netip.Addr) *Network {
- return &Network{
- ctx: ctx,
- log: log,
- client: client,
- name: name,
- cidr: cidr,
- gateway: gateway,
- }
- }
- func (this *Network) Name() string {
- return this.name
- }
- func (this *Network) Create() error {
- networks, err := this.client.Docker.NetworkList(this.ctx, moby.NetworkListOptions{})
- if err != nil {
- return fmt.Errorf("can't create network: %w", err)
- }
- for _, network := range networks.Items {
- if network.Name == this.name {
- return ErrNetworkAlreadyExists
- }
- }
- _, err = this.client.Docker.NetworkCreate(
- this.ctx,
- this.name,
- moby.NetworkCreateOptions{
- Driver: "bridge",
- IPAM: &mobynetwork.IPAM{
- Config: []mobynetwork.IPAMConfig{
- {
- Subnet: this.cidr,
- Gateway: this.gateway,
- },
- },
- },
- },
- )
- if err != nil {
- return fmt.Errorf("can't create network: %w", err)
- }
- return nil
- }
- func (this *Network) Delete() error {
- _, err := this.client.Docker.NetworkRemove(this.ctx, this.name, moby.NetworkRemoveOptions{})
- if err != nil {
- return fmt.Errorf("can't delete network: %w", err)
- }
- return nil
- }
|