github.com/thediveo/morbyd@v0.11.1/network_create.go (about) 1 // Copyright 2024 Harald Albrecht. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package morbyd 16 17 import ( 18 "context" 19 "fmt" 20 21 "github.com/docker/docker/api/types" 22 "github.com/thediveo/morbyd/net" 23 "golang.org/x/exp/maps" 24 ) 25 26 // CreateNetwork creates a new “custom” Docker network using the specified 27 // configuration options. 28 // 29 // Notable configuration options: 30 // - [net.WithInternal] marks the new network as “[internal]”. 31 // - [net.WithDriver] allows setting a different Docker network driver, such 32 // as “macvlan” or “ipvlan”. 33 // - see [github.com/thediveo/morbyd/net/bridge], 34 // [github.com/thediveo/morbyd/net/macvlan], and 35 // [github.com/thediveo/morbyd/net/ipvlan] for further, drive-specific 36 // configuration options. 37 // 38 // See also: [docker network create] 39 // 40 // [docker network create]: https://docs.docker.com/engine/reference/commandline/network_create/ 41 func (s *Session) CreateNetwork(ctx context.Context, name string, opts ...net.Opt) (*Network, error) { 42 nopts := net.Options{ 43 CheckDuplicate: true, // client now enforces this even before API v1.44 44 Labels: map[string]string{}, 45 } 46 maps.Copy(nopts.Labels, s.opts.Labels) 47 for _, opt := range opts { 48 if err := opt((*net.Options)(&nopts)); err != nil { 49 return nil, err 50 } 51 } 52 53 createResp, err := s.moby.NetworkCreate(ctx, name, types.NetworkCreate(nopts)) 54 if err != nil { 55 return nil, fmt.Errorf("cannot create new network %q, reason: %w", 56 name, err) 57 } 58 59 detailsResp, err := s.moby.NetworkInspect(ctx, createResp.ID, types.NetworkInspectOptions{ 60 Verbose: true, 61 }) 62 if err != nil { 63 _ = s.moby.NetworkRemove(ctx, createResp.ID) 64 return nil, fmt.Errorf("cannot inspect newly created network %q, reason: %w", 65 name, err) 66 } 67 68 n := Network{ 69 Name: name, 70 ID: createResp.ID, 71 Session: s, 72 Details: detailsResp, 73 } 74 return &n, nil 75 }