github.com/Prakhar-Agarwal-byte/moby@v0.0.0-20231027092010-a14e3e8ab87e/libnetwork/cmd/readme_test/readme.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/Prakhar-Agarwal-byte/moby/libnetwork"
     8  	"github.com/Prakhar-Agarwal-byte/moby/libnetwork/config"
     9  	"github.com/Prakhar-Agarwal-byte/moby/libnetwork/netlabel"
    10  	"github.com/Prakhar-Agarwal-byte/moby/libnetwork/options"
    11  )
    12  
    13  func main() {
    14  	// Select and configure the network driver
    15  	networkType := "bridge"
    16  
    17  	// Create a new controller instance
    18  	driverOptions := options.Generic{}
    19  	genericOption := make(map[string]interface{})
    20  	genericOption[netlabel.GenericData] = driverOptions
    21  	controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption))
    22  	if err != nil {
    23  		log.Fatalf("libnetwork.New: %s", err)
    24  	}
    25  
    26  	// Create a network for containers to join.
    27  	// NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can use.
    28  	network, err := controller.NewNetwork(networkType, "network1", "")
    29  	if err != nil {
    30  		log.Fatalf("controller.NewNetwork: %s", err)
    31  	}
    32  
    33  	// For each new container: allocate IP and interfaces. The returned network
    34  	// settings will be used for container infos (inspect and such), as well as
    35  	// iptables rules for port publishing. This info is contained or accessible
    36  	// from the returned endpoint.
    37  	ep, err := network.CreateEndpoint("Endpoint1")
    38  	if err != nil {
    39  		log.Fatalf("network.CreateEndpoint: %s", err)
    40  	}
    41  
    42  	// Create the sandbox for the container.
    43  	// NewSandbox accepts Variadic optional arguments which libnetwork can use.
    44  	sbx, err := controller.NewSandbox("container1",
    45  		libnetwork.OptionHostname("test"),
    46  		libnetwork.OptionDomainname("example.com"))
    47  	if err != nil {
    48  		log.Fatalf("controller.NewSandbox: %s", err)
    49  	}
    50  
    51  	// A sandbox can join the endpoint via the join api.
    52  	err = ep.Join(sbx)
    53  	if err != nil {
    54  		log.Fatalf("ep.Join: %s", err)
    55  	}
    56  
    57  	// libnetwork client can check the endpoint's operational data via the Info() API
    58  	epInfo, err := ep.DriverInfo()
    59  	if err != nil {
    60  		log.Fatalf("ep.DriverInfo: %s", err)
    61  	}
    62  
    63  	macAddress, ok := epInfo[netlabel.MacAddress]
    64  	if !ok {
    65  		log.Fatal("failed to get mac address from endpoint info")
    66  	}
    67  
    68  	fmt.Printf("Joined endpoint %s (%s) to sandbox %s (%s)\n", ep.Name(), macAddress, sbx.ContainerID(), sbx.Key())
    69  }