func resourceNetworkingNetworkV2Create(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	createOpts := NetworkCreateOpts{
		Name:       d.Get("name").(string),
		TenantID:   d.Get("tenant_id").(string),
		ValueSpecs: networkValueSpecs(d),
	}

	asuRaw := d.Get("admin_state_up").(string)
	if asuRaw != "" {
		asu, err := strconv.ParseBool(asuRaw)
		if err != nil {
			return fmt.Errorf("admin_state_up, if provided, must be either 'true' or 'false'")
		}
		createOpts.AdminStateUp = &asu
	}

	sharedRaw := d.Get("shared").(string)
	if sharedRaw != "" {
		shared, err := strconv.ParseBool(sharedRaw)
		if err != nil {
			return fmt.Errorf("shared, if provided, must be either 'true' or 'false': %v", err)
		}
		createOpts.Shared = &shared
	}

	log.Printf("[DEBUG] Create Options: %#v", createOpts)
	n, err := networks.Create(networkingClient, createOpts).Extract()
	if err != nil {
		return fmt.Errorf("Error creating OpenStack Neutron network: %s", err)
	}
	log.Printf("[INFO] Network ID: %s", n.ID)

	log.Printf("[DEBUG] Waiting for Network (%s) to become available", n.ID)

	stateConf := &resource.StateChangeConf{
		Pending:    []string{"BUILD"},
		Target:     []string{"ACTIVE"},
		Refresh:    waitForNetworkActive(networkingClient, n.ID),
		Timeout:    2 * time.Minute,
		Delay:      5 * time.Second,
		MinTimeout: 3 * time.Second,
	}

	_, err = stateConf.WaitForState()

	d.SetId(n.ID)

	return resourceNetworkingNetworkV2Read(d, meta)
}
Beispiel #2
0
func TestCreate(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()

	th.Mux.HandleFunc("/v2.0/networks", func(w http.ResponseWriter, r *http.Request) {
		th.TestMethod(t, r, "POST")
		th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
		th.TestHeader(t, r, "Content-Type", "application/json")
		th.TestHeader(t, r, "Accept", "application/json")
		th.TestJSONRequest(t, r, `
{
    "network": {
        "name": "sample_network",
        "admin_state_up": true
    }
}
			`)

		w.Header().Add("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)

		fmt.Fprintf(w, `
{
    "network": {
        "status": "ACTIVE",
        "subnets": [
            "54d6f61d-db07-451c-9ab3-b9609b6b6f0b"
        ],
        "name": "private-network",
        "provider:physical_network": null,
        "admin_state_up": true,
        "tenant_id": "4fd44f30292945e481c7b8a0c8908869",
        "provider:network_type": "local",
        "shared": true,
        "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
        "provider:segmentation_id": null
    }
}
		`)
	})

	options := networks.CreateOpts{Name: "sample_network", AdminStateUp: Up}
	res := networks.Create(fake.ServiceClient(), options)
	n, err := ExtractCreate(res)

	th.AssertNoErr(t, err)

	th.AssertEquals(t, "", n.PhysicalNetwork)
	th.AssertEquals(t, "local", n.NetworkType)
	th.AssertEquals(t, "", n.SegmentationID)
}
Beispiel #3
0
func TestNetworkCRUDOperations(t *testing.T) {
	Setup(t)
	defer Teardown()

	// Create a network
	n, err := networks.Create(Client, networks.CreateOpts{Name: "sample_network", AdminStateUp: networks.Up}).Extract()
	th.AssertNoErr(t, err)
	defer networks.Delete(Client, n.ID)
	th.AssertEquals(t, n.Name, "sample_network")
	th.AssertEquals(t, n.AdminStateUp, true)
	networkID := n.ID

	// List networks
	pager := networks.List(Client, networks.ListOpts{Limit: 2})
	err = pager.EachPage(func(page pagination.Page) (bool, error) {
		t.Logf("--- Page ---")

		networkList, err := networks.ExtractNetworks(page)
		th.AssertNoErr(t, err)

		for _, n := range networkList {
			t.Logf("Network: ID [%s] Name [%s] Status [%s] Is shared? [%s]",
				n.ID, n.Name, n.Status, strconv.FormatBool(n.Shared))
		}

		return true, nil
	})
	th.CheckNoErr(t, err)

	// Get a network
	if networkID == "" {
		t.Fatalf("In order to retrieve a network, the NetworkID must be set")
	}
	n, err = networks.Get(Client, networkID).Extract()
	th.AssertNoErr(t, err)
	th.AssertEquals(t, n.Status, "ACTIVE")
	th.AssertDeepEquals(t, n.Subnets, []string{})
	th.AssertEquals(t, n.Name, "sample_network")
	th.AssertEquals(t, n.AdminStateUp, true)
	th.AssertEquals(t, n.Shared, false)
	th.AssertEquals(t, n.ID, networkID)

	// Update network
	n, err = networks.Update(Client, networkID, networks.UpdateOpts{Name: "new_network_name"}).Extract()
	th.AssertNoErr(t, err)
	th.AssertEquals(t, n.Name, "new_network_name")

	// Delete network
	res := networks.Delete(Client, networkID)
	th.AssertNoErr(t, res.Err)
}
Beispiel #4
0
func TestCreate(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()

	th.Mux.HandleFunc("/networks", func(w http.ResponseWriter, r *http.Request) {
		th.TestMethod(t, r, "POST")
		th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
		th.TestHeader(t, r, "Content-Type", "application/json")
		th.TestHeader(t, r, "Accept", "application/json")
		th.TestJSONRequest(t, r, `
{
    "network": {
        "admin_state_up": true,
        "name": "ext_net",
        "router:external": true
    }
}
			`)

		w.Header().Add("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)

		fmt.Fprintf(w, `
{
	"network": {
			"admin_state_up": true,
			"id": "8d05a1b1-297a-46ca-8974-17debf51ca3c",
			"name": "ext_net",
			"router:external": true,
			"shared": false,
			"status": "ACTIVE",
			"subnets": [
					"2f1fb918-9b0e-4bf9-9a50-6cebbb4db2c5"
			],
			"tenant_id": "5eb8995cf717462c9df8d1edfa498010"
	}
}
		`)
	})

	options := CreateOpts{networks.CreateOpts{Name: "ext_net", AdminStateUp: Up}, true}
	res := networks.Create(fake.ServiceClient(), options)

	n, err := ExtractCreate(res)

	th.AssertNoErr(t, err)
	th.AssertEquals(t, true, n.External)
}
Beispiel #5
0
func TestCRUD(t *testing.T) {
	Setup(t)
	defer Teardown()

	// Setup network
	t.Log("Setting up network")
	n, err := networks.Create(Client, networks.CreateOpts{Name: "tmp_network", AdminStateUp: networks.Up}).Extract()
	th.AssertNoErr(t, err)
	networkID := n.ID
	defer networks.Delete(Client, networkID)

	// Create subnet
	t.Log("Create subnet")
	enable := false
	opts := subnets.CreateOpts{
		NetworkID:  networkID,
		CIDR:       "192.168.199.0/24",
		IPVersion:  subnets.IPv4,
		Name:       "my_subnet",
		EnableDHCP: &enable,
	}
	s, err := subnets.Create(Client, opts).Extract()
	th.AssertNoErr(t, err)

	th.AssertEquals(t, s.NetworkID, networkID)
	th.AssertEquals(t, s.CIDR, "192.168.199.0/24")
	th.AssertEquals(t, s.IPVersion, 4)
	th.AssertEquals(t, s.Name, "my_subnet")
	th.AssertEquals(t, s.EnableDHCP, false)
	subnetID := s.ID

	// Get subnet
	t.Log("Getting subnet")
	s, err = subnets.Get(Client, subnetID).Extract()
	th.AssertNoErr(t, err)
	th.AssertEquals(t, s.ID, subnetID)

	// Update subnet
	t.Log("Update subnet")
	s, err = subnets.Update(Client, subnetID, subnets.UpdateOpts{Name: "new_subnet_name"}).Extract()
	th.AssertNoErr(t, err)
	th.AssertEquals(t, s.Name, "new_subnet_name")

	// Delete subnet
	t.Log("Delete subnet")
	res := subnets.Delete(Client, subnetID)
	th.AssertNoErr(t, res.Err)
}
Beispiel #6
0
func createInternalTopology(t *testing.T) (string, string, string) {
	t.Logf("Creating an internal network (for port)")
	opts := networks.CreateOpts{Name: "internal_network"}
	n, err := networks.Create(base.Client, opts).Extract()
	th.AssertNoErr(t, err)

	// A subnet is also needed
	subnetID := createSubnet(t, n.ID, cidr2)

	t.Logf("Creating an internal port on network %s", n.ID)
	p, err := ports.Create(base.Client, ports.CreateOpts{
		NetworkID: n.ID,
		Name:      "fixed_internal_port",
	}).Extract()
	th.AssertNoErr(t, err)

	return n.ID, subnetID, p.ID
}
func setupTopology(t *testing.T) (string, string) {
	// create network
	n, err := networks.Create(base.Client, networks.CreateOpts{Name: "tmp_network"}).Extract()
	th.AssertNoErr(t, err)

	t.Logf("Created network, ID %s", n.ID)

	// create subnet
	s, err := subnets.Create(base.Client, subnets.CreateOpts{
		NetworkID: n.ID,
		CIDR:      "192.168.199.0/24",
		IPVersion: subnets.IPv4,
		Name:      "tmp_subnet",
	}).Extract()
	th.AssertNoErr(t, err)

	t.Logf("Created subnet, ID %s", s.ID)

	return n.ID, s.ID
}
func resourceNetworkingNetworkV2Create(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	createOpts := networks.CreateOpts{
		Name:     d.Get("name").(string),
		TenantID: d.Get("tenant_id").(string),
	}

	asuRaw := d.Get("admin_state_up").(string)
	if asuRaw != "" {
		asu, err := strconv.ParseBool(asuRaw)
		if err != nil {
			return fmt.Errorf("admin_state_up, if provided, must be either 'true' or 'false'")
		}
		createOpts.AdminStateUp = &asu
	}

	sharedRaw := d.Get("shared").(string)
	if sharedRaw != "" {
		shared, err := strconv.ParseBool(sharedRaw)
		if err != nil {
			return fmt.Errorf("shared, if provided, must be either 'true' or 'false': %v", err)
		}
		createOpts.Shared = &shared
	}

	log.Printf("[DEBUG] Create Options: %#v", createOpts)
	n, err := networks.Create(networkingClient, createOpts).Extract()
	if err != nil {
		return fmt.Errorf("Error creating OpenStack Neutron network: %s", err)
	}
	log.Printf("[INFO] Network ID: %s", n.ID)

	d.SetId(n.ID)

	return resourceNetworkingNetworkV2Read(d, meta)
}
Beispiel #9
0
func createNetwork(t *testing.T) string {
	t.Logf("Creating a network")

	asu := true
	opts := external.CreateOpts{
		Parent:   networks.CreateOpts{Name: "sample_network", AdminStateUp: &asu},
		External: true,
	}
	n, err := networks.Create(base.Client, opts).Extract()

	th.AssertNoErr(t, err)

	if n.ID == "" {
		t.Fatalf("No ID returned when creating a network")
	}

	createSubnet(t, n.ID, cidr1)

	t.Logf("Network created: ID [%s]", n.ID)

	return n.ID
}
Beispiel #10
0
// Create accepts a CreateOpts struct and creates a new network using the values
// provided. This operation does not actually require a request body, i.e. the
// CreateOpts struct argument can be empty.
//
// The tenant ID that is contained in the URI is the tenant that creates the
// network. An admin user, however, has the option of specifying another tenant
// ID in the CreateOpts struct.
func Create(c *gophercloud.ServiceClient, opts os.CreateOptsBuilder) os.CreateResult {
	return os.Create(c, opts)
}
Beispiel #11
0
func TestSubnetCRUD(t *testing.T) {
	Setup(t)
	defer Teardown()

	// Setup network
	t.Log("Setting up network")
	n, err := networks.Create(Client, networks.CreateOpts{Name: "tmp_network", AdminStateUp: networks.Up}).Extract()
	th.AssertNoErr(t, err)
	networkID := n.ID
	defer networks.Delete(Client, networkID)

	// Create subnet
	t.Log("Create subnet")
	enable := false
	opts := subnets.CreateOpts{
		NetworkID:  networkID,
		CIDR:       "192.168.199.0/24",
		IPVersion:  subnets.IPv4,
		Name:       "my_subnet",
		EnableDHCP: &enable,
	}
	s, err := subnets.Create(Client, opts).Extract()
	th.AssertNoErr(t, err)

	th.AssertEquals(t, s.NetworkID, networkID)
	th.AssertEquals(t, s.CIDR, "192.168.199.0/24")
	th.AssertEquals(t, s.IPVersion, 4)
	th.AssertEquals(t, s.Name, "my_subnet")
	th.AssertEquals(t, s.EnableDHCP, false)
	th.AssertEquals(t, s.GatewayIP, "192.168.199.1")
	subnetID := s.ID

	// Get subnet
	t.Log("Getting subnet")
	s, err = subnets.Get(Client, subnetID).Extract()
	th.AssertNoErr(t, err)
	th.AssertEquals(t, s.ID, subnetID)

	// Update subnet
	t.Log("Update subnet")
	s, err = subnets.Update(Client, subnetID, subnets.UpdateOpts{Name: "new_subnet_name"}).Extract()
	th.AssertNoErr(t, err)
	th.AssertEquals(t, s.Name, "new_subnet_name")

	// Delete subnet
	t.Log("Delete subnet")
	res := subnets.Delete(Client, subnetID)
	th.AssertNoErr(t, res.Err)

	// Create subnet with no gateway
	t.Log("Create subnet with no gateway")
	opts = subnets.CreateOpts{
		NetworkID:  networkID,
		CIDR:       "192.168.199.0/24",
		IPVersion:  subnets.IPv4,
		Name:       "my_subnet",
		EnableDHCP: &enable,
		NoGateway:  true,
	}
	s, err = subnets.Create(Client, opts).Extract()
	th.AssertNoErr(t, err)

	th.AssertEquals(t, s.NetworkID, networkID)
	th.AssertEquals(t, s.CIDR, "192.168.199.0/24")
	th.AssertEquals(t, s.IPVersion, 4)
	th.AssertEquals(t, s.Name, "my_subnet")
	th.AssertEquals(t, s.EnableDHCP, false)
	th.AssertEquals(t, s.GatewayIP, "")
	subnetID = s.ID

	// Get subnet
	t.Log("Getting subnet with no gateway")
	s, err = subnets.Get(Client, subnetID).Extract()
	th.AssertNoErr(t, err)
	th.AssertEquals(t, s.ID, subnetID)

	// Update subnet
	t.Log("Update subnet with no gateway")
	s, err = subnets.Update(Client, subnetID, subnets.UpdateOpts{Name: "new_subnet_name"}).Extract()
	th.AssertNoErr(t, err)
	th.AssertEquals(t, s.Name, "new_subnet_name")

	// Delete subnet
	t.Log("Delete subnet with no gateway")
	res = subnets.Delete(Client, subnetID)
	th.AssertNoErr(t, res.Err)

	// Create subnet with invalid gateway configuration
	t.Log("Create subnet with invalid gateway configuration")
	opts = subnets.CreateOpts{
		NetworkID:  networkID,
		CIDR:       "192.168.199.0/24",
		IPVersion:  subnets.IPv4,
		Name:       "my_subnet",
		EnableDHCP: &enable,
		NoGateway:  true,
		GatewayIP:  "192.168.199.1",
	}
	_, err = subnets.Create(Client, opts).Extract()
	if err == nil {
		t.Fatalf("Expected an error, got none")
	}
}
Beispiel #12
0
func TestNeutron(t *testing.T) {
	g := newGraph(t)

	authUrl := os.Getenv("OS_AUTH_URL")
	username := os.Getenv("OS_USERNAME")
	password := os.Getenv("OS_PASSWORD")
	tenantName := os.Getenv("OS_TENANT_NAME")
	regionName := os.Getenv("OS_REGION_NAME")
	ovsdbPort := os.Getenv("SKYDIVE_OVSDB_REMOTE_PORT")

	params := map[string]interface{}{
		"OsAuthUrl":    authUrl,
		"OsUsername":   username,
		"OsPassword":   password,
		"OsTenantName": tenantName,
		"OsRegionName": regionName,
		"OvsdbPort":    ovsdbPort,
	}
	agent := helper.StartAgentWithConfig(t, confNeutron, params)
	defer agent.Stop()

	opts := gophercloud.AuthOptions{
		IdentityEndpoint: authUrl,
		Username:         username,
		Password:         password,
		TenantName:       tenantName,
	}

	provider, err := openstack.AuthenticatedClient(opts)
	if err != nil {
		t.Fatal(err.Error())
	}

	client, err := openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{
		Name:         "neutron",
		Region:       regionName,
		Availability: gophercloud.AvailabilityPublic,
	})
	if err != nil {
		t.Fatalf("Failed to create neutron client: %s", err.Error())
	}

	result := networks.Create(client, networks.CreateOpts{Name: "skydive-test-network"})
	if result.Err != nil {
		t.Fatalf("Failed to create neutron network: %s", result.Err.Error())
	}

	network, err := result.Extract()
	if err != nil {
		t.Fatalf("Failed to create neutron network: %s", err.Error())
	}

	defer networks.Delete(client, network.ID)

	setupCmds := []helper.Cmd{
		{fmt.Sprintf("neutron subnet-create --name skydive-test-subnet-%s %s 10.0.0.0/24", network.ID, network.ID), false},
		{fmt.Sprintf("neutron-debug probe-create %s", network.ID), false},
	}

	tearDownCmds := []helper.Cmd{
		{fmt.Sprintf("neutron subnet-delete skydive-test-subnet-%s", network.ID), false},
	}

	var port *ports.Port
	testPassed := false
	onChange := func(ws *websocket.Conn) {
		g.Lock()
		defer g.Unlock()

		if port == nil {
			portListOpts := ports.ListOpts{}
			pager := ports.List(client, portListOpts)
			err = pager.EachPage(func(page pagination.Page) (bool, error) {
				portList, err := ports.ExtractPorts(page)
				if err != nil {
					return false, err
				}

				for _, p := range portList {
					if p.DeviceOwner == "network:probe" && p.NetworkID == network.ID {
						port = &p
						return false, nil
					}
				}

				return true, nil
			})

			if port != nil {
				tearDownCmds = append(tearDownCmds, helper.Cmd{})
				copy(tearDownCmds[1:], tearDownCmds[0:])
				tearDownCmds[0] = helper.Cmd{fmt.Sprintf("neutron-debug probe-delete %s", port.ID), false}
			}
		}

		if !testPassed && len(g.GetNodes()) >= 1 && len(g.GetEdges()) >= 1 && port != nil {
			if g.LookupFirstNode(graph.Metadata{"Name": fmt.Sprintf("qdhcp-%s", network.ID), "Type": "netns"}) != nil {
				if g.LookupFirstNode(graph.Metadata{"Name": fmt.Sprintf("qprobe-%s", port.ID), "Type": "netns"}) != nil {
					if g.LookupFirstNode(graph.Metadata{"Type": "internal", "Driver": "openvswitch", "Manager": "neutron", "Neutron.NetworkID": network.ID}) != nil {
						testPassed = true
						ws.Close()
					}
				}
			}
		}
	}

	testTopology(t, g, setupCmds, onChange)
	if !testPassed {
		t.Error("test not executed or failed")
	}

	testCleanup(t, g, tearDownCmds, []string{fmt.Sprintf("qdhcp-%s", network.ID), fmt.Sprintf("qprobe-%s", port.ID)})
}
func createNetwork() (string, error) {
	res, err := networks.Create(Client, networks.CreateOpts{Name: "tmp_network", AdminStateUp: networks.Up}).Extract()
	return res.ID, err
}