コード例 #1
0
ファイル: api_test.go プロジェクト: fwalker/dashboard
func TestHttpHandlerBadBody(t *testing.T) {
	defer netutils.SetupTestNetNS(t)()

	rsp := newWriter()

	c, err := libnetwork.New()
	if err != nil {
		t.Fatal(err)
	}
	handleRequest := NewHTTPHandler(c)

	req, err := http.NewRequest("POST", "/v1.19/networks", &localReader{beBad: true})
	if err != nil {
		t.Fatal(err)
	}
	handleRequest(rsp, req)
	if rsp.statusCode != http.StatusBadRequest {
		t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusBadRequest, rsp.statusCode, string(rsp.body))
	}

	body := []byte{}
	lr := newLocalReader(body)
	req, err = http.NewRequest("POST", "/v1.19/networks", lr)
	if err != nil {
		t.Fatal(err)
	}
	handleRequest(rsp, req)
	if rsp.statusCode != http.StatusBadRequest {
		t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusBadRequest, rsp.statusCode, string(rsp.body))
	}
}
コード例 #2
0
ファイル: dnet.go プロジェクト: nmatsui/libnetwork
func (d *dnetConnection) dnetDaemon(cfgFile string) error {
	if err := startTestDriver(); err != nil {
		return fmt.Errorf("failed to start test driver: %v\n", err)
	}

	cfg, err := parseConfig(cfgFile)
	var cOptions []config.Option
	if err == nil {
		cOptions = processConfig(cfg)
	}
	controller, err := libnetwork.New(cOptions...)
	if err != nil {
		fmt.Println("Error starting dnetDaemon :", err)
		return err
	}
	createDefaultNetwork(controller)
	httpHandler := api.NewHTTPHandler(controller)
	r := mux.NewRouter().StrictSlash(false)
	post := r.PathPrefix("/{.*}/networks").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
	post = r.PathPrefix("/networks").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
	post = r.PathPrefix("/{.*}/services").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
	post = r.PathPrefix("/services").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
	post = r.PathPrefix("/{.*}/sandboxes").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
	post = r.PathPrefix("/sandboxes").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)

	handleSignals(controller)

	return http.ListenAndServe(d.addr, r)
}
コード例 #3
0
ファイル: daemon_unix.go プロジェクト: DCdrone/docker
func (daemon *Daemon) initNetworkController(config *Config) (libnetwork.NetworkController, error) {
	netOptions, err := daemon.networkOptions(config)
	if err != nil {
		return nil, err
	}

	//创建controller,具体代码在libnetwork/controller.go中。
	//主要注册controller的网络驱动,ip地址管理的驱动。
	controller, err := libnetwork.New(netOptions...)
	if err != nil {
		return nil, fmt.Errorf("error obtaining controller instance: %v", err)
	}

	// Initialize default network on "null"
	if _, err := controller.NewNetwork("null", "none", libnetwork.NetworkOptionPersist(false)); err != nil {
		return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
	}

	// Initialize default network on "host"
	if _, err := controller.NewNetwork("host", "host", libnetwork.NetworkOptionPersist(false)); err != nil {
		return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
	}

	//查看bridge模式有没有被禁用。
	if !config.DisableBridge {
		// Initialize default driver "bridge"
		//初始化bridge driver。
		if err := initBridgeDriver(controller, config); err != nil {
			return nil, err
		}
	}

	return controller, nil
}
コード例 #4
0
ファイル: daemon_solaris.go プロジェクト: msabansal/docker
func (daemon *Daemon) initNetworkController(config *Config, activeSandboxes map[string]interface{}) (libnetwork.NetworkController, error) {
	netOptions, err := daemon.networkOptions(config, daemon.PluginStore, activeSandboxes)
	if err != nil {
		return nil, err
	}

	controller, err := libnetwork.New(netOptions...)
	if err != nil {
		return nil, fmt.Errorf("error obtaining controller instance: %v", err)
	}

	// Initialize default network on "null"
	if _, err := controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(false)); err != nil {
		return nil, fmt.Errorf("Error creating default 'null' network: %v", err)
	}

	if !config.DisableBridge {
		// Initialize default driver "bridge"
		if err := initBridgeDriver(controller, config); err != nil {
			return nil, err
		}
	}

	return controller, nil
}
コード例 #5
0
ファイル: daemon_unix.go プロジェクト: getsymbl/docker
func (daemon *Daemon) initNetworkController(config *Config) (libnetwork.NetworkController, error) {
	netOptions, err := daemon.networkOptions(config)
	if err != nil {
		return nil, err
	}

	controller, err := libnetwork.New(netOptions...)
	if err != nil {
		return nil, fmt.Errorf("error obtaining controller instance: %v", err)
	}

	// Initialize default network on "null"
	if _, err := controller.NewNetwork("null", "none", libnetwork.NetworkOptionPersist(false)); err != nil {
		return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
	}

	// Initialize default network on "host"
	if _, err := controller.NewNetwork("host", "host", libnetwork.NetworkOptionPersist(false)); err != nil {
		return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
	}

	if !config.DisableBridge {
		// Initialize default driver "bridge"
		if err := initBridgeDriver(controller, config); err != nil {
			return nil, err
		}
	}

	return controller, nil
}
コード例 #6
0
ファイル: libnetwork_test.go プロジェクト: choldrim/docker
func TestDuplicateNetwork(t *testing.T) {
	if !netutils.IsRunningInContainer() {
		defer netutils.SetupTestNetNS(t)()
	}

	controller, err := libnetwork.New()
	if err != nil {
		t.Fatal(err)
	}

	genericOption := make(map[string]interface{})
	genericOption[netlabel.GenericData] = options.Generic{}

	err = controller.ConfigureNetworkDriver(bridgeNetType, genericOption)
	if err != nil {
		t.Fatal(err)
	}

	_, err = controller.NewNetwork(bridgeNetType, "testnetwork",
		libnetwork.NetworkOptionGeneric(genericOption))
	if err != nil {
		t.Fatal(err)
	}

	_, err = controller.NewNetwork(bridgeNetType, "testnetwork")
	if err == nil {
		t.Fatal("Expected to fail. But instead succeeded")
	}

	if _, ok := err.(libnetwork.NetworkNameError); !ok {
		t.Fatalf("Did not fail with expected error. Actual error: %v", err)
	}
}
コード例 #7
0
func createTestController() (libnetwork.NetworkController, error) {
	controller, err := libnetwork.New("")
	if err != nil {
		return nil, err
	}
	libnetwork.SetTestDataStore(controller, datastore.NewCustomDataStore(datastore.NewMockStore()))
	return controller, nil
}
コード例 #8
0
ファイル: readme.go プロジェクト: nkwilson/libnetwork
func main() {
	// Create a new controller instance
	controller, err := libnetwork.New()
	if err != nil {
		return
	}

	// Select and configure the network driver
	networkType := "bridge"

	driverOptions := options.Generic{}
	genericOption := make(map[string]interface{})
	genericOption[netlabel.GenericData] = driverOptions
	err = controller.ConfigureNetworkDriver(networkType, genericOption)
	if err != nil {
		return
	}

	// Create a network for containers to join.
	// NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can use.
	network, err := controller.NewNetwork(networkType, "network1")
	if err != nil {
		return
	}

	// For each new container: allocate IP and interfaces. The returned network
	// settings will be used for container infos (inspect and such), as well as
	// iptables rules for port publishing. This info is contained or accessible
	// from the returned endpoint.
	ep, err := network.CreateEndpoint("Endpoint1")
	if err != nil {
		return
	}

	// Create the sandbox for the containr.
	sbx, err := controller.NewSandbox("container1",
		libnetwork.OptionHostname("test"),
		libnetwork.OptionDomainname("docker.io"))

	// A sandbox can join the endpoint via the join api.
	// Join accepts Variadic arguments which libnetwork and Drivers can use.
	err = ep.Join(sbx)
	if err != nil {
		return
	}

	// libnetwork client can check the endpoint's operational data via the Info() API
	epInfo, err := ep.DriverInfo()
	mapData, ok := epInfo[netlabel.PortMap]
	if ok {
		portMapping, ok := mapData.([]types.PortBinding)
		if ok {
			fmt.Printf("Current port mapping for endpoint %s: %v", ep.Name(), portMapping)
		}
	}
}
コード例 #9
0
func createController() error {
	var err error

	controller, err = libnetwork.New()
	if err != nil {
		return err
	}

	return nil
}
コード例 #10
0
ファイル: dnet.go プロジェクト: vdemeester/libnetwork
func (d *dnetConnection) dnetDaemon(cfgFile string) error {
	if err := startTestDriver(); err != nil {
		return fmt.Errorf("failed to start test driver: %v\n", err)
	}

	cfg, err := d.parseConfig(cfgFile)
	var cOptions []config.Option
	if err == nil {
		cOptions = processConfig(cfg)
	} else {
		logrus.Errorf("Error parsing config %v", err)
	}

	bridgeConfig := options.Generic{
		"EnableIPForwarding": true,
		"EnableIPTables":     true,
	}

	bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}

	cOptions = append(cOptions, config.OptionDriverConfig("bridge", bridgeOption))

	controller, err := libnetwork.New(cOptions...)
	if err != nil {
		fmt.Println("Error starting dnetDaemon :", err)
		return err
	}
	controller.SetClusterProvider(d)

	if d.Orchestration.Agent || d.Orchestration.Manager {
		d.configEvent <- struct{}{}
	}

	createDefaultNetwork(controller)
	httpHandler := api.NewHTTPHandler(controller)
	r := mux.NewRouter().StrictSlash(false)
	post := r.PathPrefix("/{.*}/networks").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
	post = r.PathPrefix("/networks").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
	post = r.PathPrefix("/{.*}/services").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
	post = r.PathPrefix("/services").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
	post = r.PathPrefix("/{.*}/sandboxes").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
	post = r.PathPrefix("/sandboxes").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)

	handleSignals(controller)
	setupDumpStackTrap()

	return http.ListenAndServe(d.addr, r)
}
コード例 #11
0
ファイル: api_test.go プロジェクト: colebrumley/docker
func TestHttpHandlerUninit(t *testing.T) {
	defer netutils.SetupTestNetNS(t)()

	c, err := libnetwork.New()
	if err != nil {
		t.Fatal(err)
	}

	h := &httpHandler{c: c}
	h.initRouter()
	if h.r == nil {
		t.Fatalf("initRouter() did not initialize the router")
	}

	rsp := newWriter()
	req, err := http.NewRequest("GET", "/networks", nil)
	if err != nil {
		t.Fatal(err)
	}

	handleRequest := NewHTTPHandler(nil)
	handleRequest(rsp, req)
	if rsp.statusCode != http.StatusServiceUnavailable {
		t.Fatalf("Expected (%d). Got (%d): %s", http.StatusServiceUnavailable, rsp.statusCode, rsp.body)
	}

	handleRequest = NewHTTPHandler(c)

	handleRequest(rsp, req)
	if rsp.statusCode != http.StatusOK {
		t.Fatalf("Unexpectded failure: (%d): %s", rsp.statusCode, rsp.body)
	}

	n, err := c.NewNetwork(bridgeNetType, "onenet", nil)
	if err != nil {
		t.Fatal(err)
	}
	nwr := buildNetworkResource(n)
	expected, err := json.Marshal([]networkResource{*nwr})
	if err != nil {
		t.Fatal(err)
	}

	handleRequest(rsp, req)
	if rsp.statusCode != http.StatusOK {
		t.Fatalf("Unexpectded failure: (%d): %s", rsp.statusCode, rsp.body)
	}
	if len(rsp.body) == 0 {
		t.Fatalf("Empty list of networks")
	}
	if bytes.Equal(rsp.body, expected) {
		t.Fatalf("Incorrect list of networks in response's body")
	}
}
コード例 #12
0
ファイル: api_test.go プロジェクト: colebrumley/docker
func TestHttpHandlerGood(t *testing.T) {
	defer netutils.SetupTestNetNS(t)()

	rsp := newWriter()

	c, err := libnetwork.New()
	if err != nil {
		t.Fatal(err)
	}
	handleRequest := NewHTTPHandler(c)

	nc := networkCreate{Name: "zero-network", NetworkType: bridgeNetType}
	body, err := json.Marshal(nc)
	if err != nil {
		t.Fatal(err)
	}

	lr := newLocalReader(body)
	req, err := http.NewRequest("POST", "/networks/name/zero-network", lr)
	if err != nil {
		t.Fatal(err)
	}
	handleRequest(rsp, req)
	if rsp.statusCode != http.StatusCreated {
		t.Fatalf("Unexpectded status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body))
	}
	if len(rsp.body) == 0 {
		t.Fatalf("Empty response body")
	}

	var id string
	err = json.Unmarshal(rsp.body, &id)
	if err != nil {
		t.Fatal(err)
	}

	req, err = http.NewRequest("GET", "/networks/id/"+id, nil)
	if err != nil {
		t.Fatal(err)
	}
	handleRequest(rsp, req)
	if rsp.statusCode != http.StatusOK {
		t.Fatalf("Unexpectded failure: (%d): %s", rsp.statusCode, rsp.body)
	}

	var nwr networkResource
	err = json.Unmarshal(rsp.body, &nwr)
	if err != nil {
		t.Fatal(err)
	}
	if nwr.Name != "zero-network" || id != nwr.ID {
		t.Fatalf("Incongruent resource found")
	}
}
コード例 #13
0
ファイル: dnet.go プロジェクト: fwalker/dashboard
func (d *dnetConnection) dnetDaemon() error {
	controller, err := libnetwork.New()
	if err != nil {
		fmt.Println("Error starting dnetDaemon :", err)
		return err
	}
	httpHandler := api.NewHTTPHandler(controller)
	r := mux.NewRouter().StrictSlash(false)
	post := r.PathPrefix("/{.*}/networks").Subrouter()
	post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
	return http.ListenAndServe(d.addr, r)
}
コード例 #14
0
ファイル: api_test.go プロジェクト: fwalker/dashboard
func TestDetectGetNetworksInvalidQueryComposition(t *testing.T) {
	c, err := libnetwork.New()
	if err != nil {
		t.Fatal(err)
	}

	vars := map[string]string{urlNwName: "x", urlNwPID: "y"}
	_, errRsp := procGetNetworks(c, vars, nil)
	if errRsp.StatusCode != http.StatusBadRequest {
		t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
	}
}
コード例 #15
0
ファイル: libnetwork_test.go プロジェクト: pirater/os
func TestInvalidRemoteDriver(t *testing.T) {
	if !testutils.IsRunningInContainer() {
		t.Skip("Skipping test when not running inside a Container")
	}

	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	if server == nil {
		t.Fatal("Failed to start a HTTP Server")
	}
	defer server.Close()

	type pluginRequest struct {
		name string
	}

	mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintln(w, `{"Implements": ["InvalidDriver"]}`)
	})

	if err := os.MkdirAll("/etc/docker/plugins", 0755); err != nil {
		t.Fatal(err)
	}
	defer func() {
		if err := os.RemoveAll("/etc/docker/plugins"); err != nil {
			t.Fatal(err)
		}
	}()

	if err := ioutil.WriteFile("/etc/docker/plugins/invalid-network-driver.spec", []byte(server.URL), 0644); err != nil {
		t.Fatal(err)
	}

	ctrlr, err := libnetwork.New()
	if err != nil {
		t.Fatal(err)
	}
	defer ctrlr.Stop()

	_, err = ctrlr.NewNetwork("invalid-network-driver", "dummy",
		libnetwork.NetworkOptionGeneric(getEmptyGenericOption()))
	if err == nil {
		t.Fatal("Expected to fail. But instead succeeded")
	}

	if err != plugins.ErrNotImplements {
		t.Fatalf("Did not fail with expected error. Actual error: %v", err)
	}
}
コード例 #16
0
ファイル: libnetwork_test.go プロジェクト: fwalker/dashboard
func TestValidRemoteDriver(t *testing.T) {
	if !netutils.IsRunningInContainer() {
		t.Skip("Skipping test when not running inside a Container")
	}

	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	if server == nil {
		t.Fatal("Failed to start a HTTP Server")
	}
	defer server.Close()

	type pluginRequest struct {
		name string
	}

	mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, `{"Implements": ["%s"]}`, driverapi.NetworkPluginEndpointType)
	})
	mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
		fmt.Fprintf(w, "null")
	})

	if err := os.MkdirAll("/usr/share/docker/plugins", 0755); err != nil {
		t.Fatal(err)
	}
	defer func() {
		if err := os.RemoveAll("/usr/share/docker/plugins"); err != nil {
			t.Fatal(err)
		}
	}()

	if err := ioutil.WriteFile("/usr/share/docker/plugins/valid-network-driver.spec", []byte(server.URL), 0644); err != nil {
		t.Fatal(err)
	}

	controller, err := libnetwork.New()
	if err != nil {
		t.Fatal(err)
	}

	_, err = controller.NewNetwork("valid-network-driver", "dummy",
		libnetwork.NetworkOptionGeneric(getEmptyGenericOption()))
	if err != nil {
		t.Fatal(err)
	}
}
コード例 #17
0
ファイル: daemon_unix.go プロジェクト: docker/docker
func (daemon *Daemon) initNetworkController(config *Config, activeSandboxes map[string]interface{}) (libnetwork.NetworkController, error) {
	netOptions, err := daemon.networkOptions(config, daemon.PluginStore, activeSandboxes)
	if err != nil {
		return nil, err
	}

	controller, err := libnetwork.New(netOptions...)
	if err != nil {
		return nil, fmt.Errorf("error obtaining controller instance: %v", err)
	}

	if len(activeSandboxes) > 0 {
		logrus.Info("There are old running containers, the network config will not take affect")
		return controller, nil
	}

	// Initialize default network on "null"
	if n, _ := controller.NetworkByName("none"); n == nil {
		if _, err := controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(true)); err != nil {
			return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
		}
	}

	// Initialize default network on "host"
	if n, _ := controller.NetworkByName("host"); n == nil {
		if _, err := controller.NewNetwork("host", "host", "", libnetwork.NetworkOptionPersist(true)); err != nil {
			return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
		}
	}

	// Clear stale bridge network
	if n, err := controller.NetworkByName("bridge"); err == nil {
		if err = n.Delete(); err != nil {
			return nil, fmt.Errorf("could not delete the default bridge network: %v", err)
		}
	}

	if !config.DisableBridge {
		// Initialize default driver "bridge"
		if err := initBridgeDriver(controller, config); err != nil {
			return nil, err
		}
	} else {
		removeDefaultBridgeInterface()
	}

	return controller, nil
}
コード例 #18
0
ファイル: libnetwork_test.go プロジェクト: choldrim/docker
func TestNilRemoteDriver(t *testing.T) {
	controller, err := libnetwork.New()
	if err != nil {
		t.Fatal(err)
	}

	_, err = controller.NewNetwork("framerelay", "dummy",
		libnetwork.NetworkOptionGeneric(getEmptyGenericOption()))
	if err == nil {
		t.Fatal("Expected to fail. But instead succeeded")
	}

	if err != plugins.ErrNotFound {
		t.Fatalf("Did not fail with expected error. Actual error: %v", err)
	}
}
コード例 #19
0
ファイル: main.go プロジェクト: choldrim/docker
func main() {
	ip, net, _ := net.ParseCIDR("192.168.100.1/24")
	net.IP = ip

	options := options.Generic{"AddressIPv4": net}
	controller, err := libnetwork.New()
	if err != nil {
		log.Fatal(err)
	}
	netType := "bridge"
	err = controller.ConfigureNetworkDriver(netType, options)
	netw, err := controller.NewNetwork(netType, "dummy")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Network=%#v\n", netw)
}
コード例 #20
0
ファイル: api_test.go プロジェクト: AlphaStaxLLC/libnetwork
func createTestNetwork(t *testing.T, network string) (libnetwork.NetworkController, libnetwork.Network) {
	c, err := libnetwork.New("")
	if err != nil {
		t.Fatal(err)
	}

	err = c.ConfigureNetworkDriver(bridgeNetType, nil)
	if err != nil {
		t.Fatal(err)
	}

	nw, err := c.NewNetwork(bridgeNetType, network, nil)
	if err != nil {
		t.Fatal(err)
	}

	return c, nw
}
コード例 #21
0
ファイル: daemon_unix.go プロジェクト: ranid/docker
func initNetworkController(config *Config) (libnetwork.NetworkController, error) {
	netOptions, err := networkOptions(config)
	if err != nil {
		return nil, err
	}

	controller, err := libnetwork.New(netOptions...)
	if err != nil {
		return nil, fmt.Errorf("error obtaining controller instance: %v", err)
	}

	// Initialize default driver "null"

	if err := controller.ConfigureNetworkDriver("null", options.Generic{}); err != nil {
		return nil, fmt.Errorf("Error initializing null driver: %v", err)
	}

	// Initialize default network on "null"
	if _, err := controller.NewNetwork("null", "none"); err != nil {
		return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
	}

	// Initialize default driver "host"
	if err := controller.ConfigureNetworkDriver("host", options.Generic{}); err != nil {
		return nil, fmt.Errorf("Error initializing host driver: %v", err)
	}

	// Initialize default network on "host"
	if _, err := controller.NewNetwork("host", "host"); err != nil {
		return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
	}

	if !config.DisableBridge {
		// Initialize default driver "bridge"
		if err := initBridgeDriver(controller, config); err != nil {
			return nil, err
		}
	}

	return controller, nil
}
コード例 #22
0
ファイル: libnetwork_test.go プロジェクト: c0b/libnetwork
func createController() error {
	var err error

	option := options.Generic{
		"EnableIPForwarding": true,
	}

	genericOption := make(map[string]interface{})
	genericOption[netlabel.GenericData] = option

	cfgOptions, err := libnetwork.OptionBoltdbWithRandomDBFile()
	if err != nil {
		return err
	}
	controller, err = libnetwork.New(append(cfgOptions, config.OptionDriverConfig(bridgeNetType, genericOption))...)
	if err != nil {
		return err
	}

	return nil
}
コード例 #23
0
ファイル: libnetwork_test.go プロジェクト: choldrim/docker
func createTestNetwork(networkType, networkName string, option options.Generic, netOption options.Generic) (libnetwork.Network, error) {
	controller, err := libnetwork.New()
	if err != nil {
		return nil, err
	}
	genericOption := make(map[string]interface{})
	genericOption[netlabel.GenericData] = option

	err = controller.ConfigureNetworkDriver(networkType, genericOption)
	if err != nil {
		return nil, err
	}

	network, err := controller.NewNetwork(networkType, networkName,
		libnetwork.NetworkOptionGeneric(netOption))
	if err != nil {
		return nil, err
	}

	return network, nil
}
コード例 #24
0
ファイル: libnetwork_test.go プロジェクト: choldrim/docker
func createGlobalInstance(t *testing.T) {
	var err error
	defer close(start)

	origns, err = netns.Get()
	if err != nil {
		t.Fatal(err)
	}

	if netutils.IsRunningInContainer() {
		testns = origns
	} else {
		testns, err = netns.New()
		if err != nil {
			t.Fatal(err)
		}
	}

	ctrlr, err = libnetwork.New()
	if err != nil {
		t.Fatal(err)
	}

	err = ctrlr.ConfigureNetworkDriver(bridgeNetType, getEmptyGenericOption())
	if err != nil {
		t.Fatal("configure driver")
	}

	net, err := ctrlr.NewNetwork(bridgeNetType, "network1")
	if err != nil {
		t.Fatal("new network")
	}

	_, err = net.CreateEndpoint("ep1")
	if err != nil {
		t.Fatal("createendpoint")
	}
}
コード例 #25
0
ファイル: api_test.go プロジェクト: fwalker/dashboard
func TestDetectGetEndpointsInvalidQueryComposition(t *testing.T) {
	defer netutils.SetupTestNetNS(t)()

	c, err := libnetwork.New()
	if err != nil {
		t.Fatal(err)
	}
	err = c.ConfigureNetworkDriver(bridgeNetType, nil)
	if err != nil {
		t.Fatal(err)
	}

	_, err = c.NewNetwork(bridgeNetType, "network", nil)
	if err != nil {
		t.Fatal(err)
	}

	vars := map[string]string{urlNwName: "network", urlEpName: "x", urlEpPID: "y"}
	_, errRsp := procGetEndpoints(c, vars, nil)
	if errRsp.StatusCode != http.StatusBadRequest {
		t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
	}
}
コード例 #26
0
ファイル: libnetwork_test.go プロジェクト: pirater/os
func createController() error {
	var err error

	// Cleanup local datastore file
	os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)

	option := options.Generic{
		"EnableIPForwarding": true,
	}

	genericOption := make(map[string]interface{})
	genericOption[netlabel.GenericData] = option

	cfgOptions, err := libnetwork.OptionBoltdbWithRandomDBFile()
	if err != nil {
		return err
	}
	controller, err = libnetwork.New(append(cfgOptions, config.OptionDriverConfig(bridgeNetType, genericOption))...)
	if err != nil {
		return err
	}

	return nil
}
コード例 #27
0
ファイル: api_test.go プロジェクト: fwalker/dashboard
func TestJoinLeave(t *testing.T) {
	defer netutils.SetupTestNetNS(t)()

	c, err := libnetwork.New()
	if err != nil {
		t.Fatal(err)
	}
	err = c.ConfigureNetworkDriver(bridgeNetType, nil)
	if err != nil {
		t.Fatal(err)
	}

	nb, err := json.Marshal(networkCreate{Name: "network", NetworkType: bridgeNetType})
	if err != nil {
		t.Fatal(err)
	}
	vars := make(map[string]string)
	_, errRsp := procCreateNetwork(c, vars, nb)
	if errRsp != &createdResponse {
		t.Fatalf("Unexepected failure: %v", errRsp)
	}

	eb, err := json.Marshal(endpointCreate{Name: "endpoint"})
	if err != nil {
		t.Fatal(err)
	}
	vars[urlNwName] = "network"
	_, errRsp = procCreateEndpoint(c, vars, eb)
	if errRsp != &createdResponse {
		t.Fatalf("Unexepected failure: %v", errRsp)
	}

	vbad, err := json.Marshal("bad data")
	if err != nil {
		t.Fatal(err)
	}
	_, errRsp = procJoinEndpoint(c, vars, vbad)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}

	vars[urlEpName] = "endpoint"
	bad, err := json.Marshal(endpointJoin{})
	if err != nil {
		t.Fatal(err)
	}
	_, errRsp = procJoinEndpoint(c, vars, bad)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}

	cid := "abcdefghi"
	jl := endpointJoin{ContainerID: cid}
	jlb, err := json.Marshal(jl)
	if err != nil {
		t.Fatal(err)
	}

	vars = make(map[string]string)
	vars[urlNwName] = ""
	vars[urlEpName] = ""
	_, errRsp = procJoinEndpoint(c, vars, jlb)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}

	vars[urlNwName] = "network"
	vars[urlEpName] = ""
	_, errRsp = procJoinEndpoint(c, vars, jlb)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}

	vars[urlEpName] = "epoint"
	_, errRsp = procJoinEndpoint(c, vars, jlb)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}

	vars[urlEpName] = "endpoint"
	cdi, errRsp := procJoinEndpoint(c, vars, jlb)
	if errRsp != &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}

	cd := i2c(cdi)
	if cd.SandboxKey == "" {
		t.Fatalf("Empty sandbox key")
	}
	_, errRsp = procDeleteEndpoint(c, vars, nil)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}

	vars[urlNwName] = "network2"
	_, errRsp = procLeaveEndpoint(c, vars, vbad)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}
	_, errRsp = procLeaveEndpoint(c, vars, bad)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}
	_, errRsp = procLeaveEndpoint(c, vars, jlb)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}
	vars = make(map[string]string)
	vars[urlNwName] = ""
	vars[urlEpName] = ""
	_, errRsp = procLeaveEndpoint(c, vars, jlb)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}
	vars[urlNwName] = "network"
	vars[urlEpName] = ""
	_, errRsp = procLeaveEndpoint(c, vars, jlb)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}
	vars[urlEpName] = "2epoint"
	_, errRsp = procLeaveEndpoint(c, vars, jlb)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}
	vars[urlEpName] = "epoint"
	vars[urlCnID] = "who"
	_, errRsp = procLeaveEndpoint(c, vars, jlb)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}

	delete(vars, urlCnID)
	vars[urlEpName] = "endpoint"
	_, errRsp = procLeaveEndpoint(c, vars, jlb)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}

	vars[urlCnID] = cid
	_, errRsp = procLeaveEndpoint(c, vars, jlb)
	if errRsp != &successResponse {
		t.Fatalf("Unexepected failure: %v", errRsp)
	}

	_, errRsp = procLeaveEndpoint(c, vars, jlb)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, got: %v", errRsp)
	}

	_, errRsp = procDeleteEndpoint(c, vars, nil)
	if errRsp != &successResponse {
		t.Fatalf("Unexepected failure: %v", errRsp)
	}
}
コード例 #28
0
ファイル: daemon.go プロジェクト: julz/guardian-release
func initNetworkController(config *Config) (libnetwork.NetworkController, error) {
	controller, err := libnetwork.New()
	if err != nil {
		return nil, fmt.Errorf("error obtaining controller instance: %v", err)
	}

	// Initialize default driver "null"

	if err := controller.ConfigureNetworkDriver("null", options.Generic{}); err != nil {
		return nil, fmt.Errorf("Error initializing null driver: %v", err)
	}

	// Initialize default network on "null"
	if _, err := controller.NewNetwork("null", "none"); err != nil {
		return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
	}

	// Initialize default driver "host"
	if err := controller.ConfigureNetworkDriver("host", options.Generic{}); err != nil {
		return nil, fmt.Errorf("Error initializing host driver: %v", err)
	}

	// Initialize default network on "host"
	if _, err := controller.NewNetwork("host", "host"); err != nil {
		return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
	}

	// Initialize default driver "bridge"
	option := options.Generic{
		"EnableIPForwarding": config.Bridge.EnableIPForward}

	if err := controller.ConfigureNetworkDriver("bridge", options.Generic{netlabel.GenericData: option}); err != nil {
		return nil, fmt.Errorf("Error initializing bridge driver: %v", err)
	}

	netOption := options.Generic{
		"BridgeName":          config.Bridge.Iface,
		"Mtu":                 config.Mtu,
		"EnableIPTables":      config.Bridge.EnableIPTables,
		"EnableIPMasquerade":  config.Bridge.EnableIPMasq,
		"EnableICC":           config.Bridge.InterContainerCommunication,
		"EnableUserlandProxy": config.Bridge.EnableUserlandProxy,
	}

	if config.Bridge.IP != "" {
		ip, bipNet, err := net.ParseCIDR(config.Bridge.IP)
		if err != nil {
			return nil, err
		}

		bipNet.IP = ip
		netOption["AddressIPv4"] = bipNet
	}

	if config.Bridge.FixedCIDR != "" {
		_, fCIDR, err := net.ParseCIDR(config.Bridge.FixedCIDR)
		if err != nil {
			return nil, err
		}

		netOption["FixedCIDR"] = fCIDR
	}

	if config.Bridge.FixedCIDRv6 != "" {
		_, fCIDRv6, err := net.ParseCIDR(config.Bridge.FixedCIDRv6)
		if err != nil {
			return nil, err
		}

		netOption["FixedCIDRv6"] = fCIDRv6
	}

	if config.Bridge.DefaultGatewayIPv4 != nil {
		netOption["DefaultGatewayIPv4"] = config.Bridge.DefaultGatewayIPv4
	}

	if config.Bridge.DefaultGatewayIPv6 != nil {
		netOption["DefaultGatewayIPv6"] = config.Bridge.DefaultGatewayIPv6
	}

	// --ip processing
	if config.Bridge.DefaultIP != nil {
		netOption["DefaultBindingIP"] = config.Bridge.DefaultIP
	}

	// Initialize default network on "bridge" with the same name
	_, err = controller.NewNetwork("bridge", "bridge",
		libnetwork.NetworkOptionGeneric(options.Generic{
			netlabel.GenericData: netOption,
			netlabel.EnableIPv6:  config.Bridge.EnableIPv6,
		}))
	if err != nil {
		return nil, fmt.Errorf("Error creating default \"bridge\" network: %v", err)
	}

	return controller, nil
}
コード例 #29
0
ファイル: api_test.go プロジェクト: fwalker/dashboard
func TestFindEndpointUtil(t *testing.T) {
	defer netutils.SetupTestNetNS(t)()

	c, err := libnetwork.New()
	if err != nil {
		t.Fatal(err)
	}
	err = c.ConfigureNetworkDriver(bridgeNetType, nil)
	if err != nil {
		t.Fatal(err)
	}

	nw, err := c.NewNetwork(bridgeNetType, "second", nil)
	if err != nil {
		t.Fatal(err)
	}
	nid := nw.ID()

	ep, err := nw.CreateEndpoint("secondEp", nil)
	if err != nil {
		t.Fatal(err)
	}
	eid := ep.ID()

	defer checkPanic(t)
	findEndpoint(c, nid, "", byID, -1)

	_, errRsp := findEndpoint(c, nid, "", byID, byName)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, but got: %v", errRsp)
	}
	if errRsp.StatusCode != http.StatusBadRequest {
		t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode)
	}

	ep0, errRsp := findEndpoint(c, nid, "secondEp", byID, byName)
	if errRsp != &successResponse {
		t.Fatalf("Unexepected failure: %v", errRsp)
	}

	ep1, errRsp := findEndpoint(c, "second", "secondEp", byName, byName)
	if errRsp != &successResponse {
		t.Fatalf("Unexepected failure: %v", errRsp)
	}

	ep2, errRsp := findEndpoint(c, nid, eid, byID, byID)
	if errRsp != &successResponse {
		t.Fatalf("Unexepected failure: %v", errRsp)
	}

	ep3, errRsp := findEndpoint(c, "second", eid, byName, byID)
	if errRsp != &successResponse {
		t.Fatalf("Unexepected failure: %v", errRsp)
	}

	if ep0 != ep1 || ep0 != ep2 || ep0 != ep3 {
		t.Fatalf("Diffenrent queries returned different endpoints")
	}

	ep.Delete()

	_, errRsp = findEndpoint(c, nid, "secondEp", byID, byName)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, but got: %v", errRsp)
	}
	if errRsp.StatusCode != http.StatusNotFound {
		t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
	}

	_, errRsp = findEndpoint(c, "second", "secondEp", byName, byName)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, but got: %v", errRsp)
	}
	if errRsp.StatusCode != http.StatusNotFound {
		t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
	}

	_, errRsp = findEndpoint(c, nid, eid, byID, byID)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, but got: %v", errRsp)
	}
	if errRsp.StatusCode != http.StatusNotFound {
		t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
	}

	_, errRsp = findEndpoint(c, "second", eid, byName, byID)
	if errRsp == &successResponse {
		t.Fatalf("Expected failure, but got: %v", errRsp)
	}
	if errRsp.StatusCode != http.StatusNotFound {
		t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
	}
}
コード例 #30
0
ファイル: daemon_windows.go プロジェクト: fntlnz/docker
func (daemon *Daemon) initNetworkController(config *Config) (libnetwork.NetworkController, error) {
	netOptions, err := daemon.networkOptions(config)
	if err != nil {
		return nil, err
	}
	controller, err := libnetwork.New(netOptions...)
	if err != nil {
		return nil, fmt.Errorf("error obtaining controller instance: %v", err)
	}

	hnsresponse, err := hcsshim.HNSListNetworkRequest("GET", "", "")
	if err != nil {
		return nil, err
	}

	// Remove networks not present in HNS
	for _, v := range controller.Networks() {
		options := v.Info().DriverOptions()
		hnsid := options[winlibnetwork.HNSID]
		found := false

		for _, v := range hnsresponse {
			if v.Id == hnsid {
				found = true
				break
			}
		}

		if !found {
			err = v.Delete()
			if err != nil {
				return nil, err
			}
		}
	}

	_, err = controller.NewNetwork("null", "none", libnetwork.NetworkOptionPersist(false))
	if err != nil {
		return nil, err
	}

	// discover and add HNS networks to windows
	// network that exist are removed and added again
	for _, v := range hnsresponse {
		var n libnetwork.Network
		s := func(current libnetwork.Network) bool {
			options := current.Info().DriverOptions()
			if options[winlibnetwork.HNSID] == v.Id {
				n = current
				return true
			}
			return false
		}

		controller.WalkNetworks(s)
		if n != nil {
			v.Name = n.Name()
			n.Delete()
		}

		netOption := map[string]string{
			winlibnetwork.NetworkName: v.Name,
			winlibnetwork.HNSID:       v.Id,
		}

		v4Conf := []*libnetwork.IpamConf{}
		for _, subnet := range v.Subnets {
			ipamV4Conf := libnetwork.IpamConf{}
			ipamV4Conf.PreferredPool = subnet.AddressPrefix
			ipamV4Conf.Gateway = subnet.GatewayAddress
			v4Conf = append(v4Conf, &ipamV4Conf)
		}

		name := v.Name
		// There is only one nat network supported in windows.
		// If it exists with a different name add it as the default name
		if runconfig.DefaultDaemonNetworkMode() == containertypes.NetworkMode(strings.ToLower(v.Type)) {
			name = runconfig.DefaultDaemonNetworkMode().NetworkName()
		}

		v6Conf := []*libnetwork.IpamConf{}
		_, err := controller.NewNetwork(strings.ToLower(v.Type), name,
			libnetwork.NetworkOptionGeneric(options.Generic{
				netlabel.GenericData: netOption,
			}),
			libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
		)

		if err != nil {
			logrus.Errorf("Error occurred when creating network %v", err)
		}
	}

	if !config.DisableBridge {
		// Initialize default driver "bridge"
		if err := initBridgeDriver(controller, config); err != nil {
			return nil, err
		}
	}

	return controller, nil
}