github.com/projecteru2/core@v0.0.0-20240321043226-06bcc1c23f58/engine/docker/network.go (about) 1 package docker 2 3 import ( 4 "context" 5 "net" 6 7 "github.com/cockroachdb/errors" 8 dockertypes "github.com/docker/docker/api/types" 9 dockerfilters "github.com/docker/docker/api/types/filters" 10 dockernetwork "github.com/docker/docker/api/types/network" 11 12 enginetypes "github.com/projecteru2/core/engine/types" 13 coretypes "github.com/projecteru2/core/types" 14 ) 15 16 // NetworkConnect connect to a network 17 func (e *Engine) NetworkConnect(ctx context.Context, network, target, ipv4, _ string) ([]string, error) { 18 config, err := e.makeIPV4EndpointSetting(ipv4) 19 if err != nil { 20 return nil, err 21 } 22 if err := e.client.NetworkConnect(ctx, network, target, config); err != nil { 23 return nil, err 24 } 25 workload, err := e.client.ContainerInspect(ctx, target) 26 if err != nil { 27 return nil, err 28 } 29 ns := workload.NetworkSettings.Networks[network] 30 if ns == nil { 31 return []string{}, nil 32 } 33 return []string{ns.IPAddress}, nil 34 } 35 36 // NetworkDisconnect disconnect from a network 37 func (e *Engine) NetworkDisconnect(ctx context.Context, network, target string, force bool) error { 38 return e.client.NetworkDisconnect(ctx, network, target, force) 39 } 40 41 // NetworkList show all networks 42 func (e *Engine) NetworkList(ctx context.Context, drivers []string) ([]*enginetypes.Network, error) { 43 networks := []*enginetypes.Network{} 44 filters := dockerfilters.NewArgs() 45 for _, driver := range drivers { 46 filters.Add("driver", driver) 47 } 48 49 ns, err := e.client.NetworkList(ctx, dockertypes.NetworkListOptions{Filters: filters}) 50 if err != nil { 51 return networks, err 52 } 53 54 for _, n := range ns { 55 subnets := []string{} 56 for _, config := range n.IPAM.Config { 57 subnets = append(subnets, config.Subnet) 58 } 59 networks = append(networks, &enginetypes.Network{Name: n.Name, Subnets: subnets}) 60 } 61 return networks, nil 62 } 63 64 func (e *Engine) makeIPV4EndpointSetting(ipv4 string) (*dockernetwork.EndpointSettings, error) { 65 config := &dockernetwork.EndpointSettings{ 66 IPAMConfig: &dockernetwork.EndpointIPAMConfig{}, 67 } 68 // set specified IP 69 // but if IP is empty, just ignore 70 if ipv4 != "" { 71 ip := net.ParseIP(ipv4) 72 if ip == nil { 73 return nil, errors.Wrapf(coretypes.ErrInvaildIPAddress, "ip: %s", ipv4) 74 } 75 config.IPAMConfig.IPv4Address = ip.String() 76 } 77 return config, nil 78 }