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

	opts := networks.ListOpts{ID: networkID}
	pager := networks.List(networkClient, opts)
	networkName := ""

	err = pager.EachPage(func(page pagination.Page) (bool, error) {
		networkList, err := networks.ExtractNetworks(page)
		if err != nil {
			return false, err
		}

		for _, n := range networkList {
			if n.ID == networkID {
				networkName = n.Name
				return false, nil
			}
		}

		return true, nil
	})

	return networkName, err
}
Exemplo n.º 2
0
func createServer(t *testing.T, client *gophercloud.ServiceClient, choices *ComputeChoices) (*servers.Server, error) {
	if testing.Short() {
		t.Skip("Skipping test that requires server creation in short mode.")
	}

	var network networks.Network

	networkingClient, err := networkingClient()
	if err != nil {
		t.Fatalf("Unable to create a networking client: %v", err)
	}

	pager := networks.List(networkingClient, networks.ListOpts{
		Name:  choices.NetworkName,
		Limit: 1,
	})
	pager.EachPage(func(page pagination.Page) (bool, error) {
		networks, err := networks.ExtractNetworks(page)
		if err != nil {
			t.Errorf("Failed to extract networks: %v", err)
			return false, err
		}

		if len(networks) == 0 {
			t.Fatalf("No networks to attach to server")
			return false, err
		}

		network = networks[0]

		return false, nil
	})

	name := tools.RandomString("ACPTTEST", 16)
	t.Logf("Attempting to create server: %s\n", name)

	pwd := tools.MakeNewPassword("")

	server, err := servers.Create(client, servers.CreateOpts{
		Name:      name,
		FlavorRef: choices.FlavorID,
		ImageRef:  choices.ImageID,
		Networks: []servers.Network{
			servers.Network{UUID: network.ID},
		},
		AdminPass: pwd,
	}).Extract()
	if err != nil {
		t.Fatalf("Unable to create server: %v", err)
	}

	th.AssertEquals(t, pwd, server.AdminPass)

	return server, err
}
Exemplo n.º 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)
}
Exemplo n.º 4
0
func (c *GenericClient) getNetworkId(d *Driver, networkName string) (string, error) {
	opts := networks.ListOpts{Name: networkName}
	pager := networks.List(c.Network, opts)
	networkId := ""

	err := pager.EachPage(func(page pagination.Page) (bool, error) {
		networkList, err := networks.ExtractNetworks(page)
		if err != nil {
			return false, err
		}

		for _, n := range networkList {
			if n.Name == networkName {
				networkId = n.ID
				return false, nil
			}
		}

		return true, nil
	})

	return networkId, err
}
Exemplo n.º 5
0
// List returns a Pager which allows you to iterate over a collection of
// networks. It accepts a ListOpts struct, which allows you to filter and sort
// the returned collection for greater efficiency.
func List(c *gophercloud.ServiceClient, opts os.ListOptsBuilder) pagination.Pager {
	return os.List(c, opts)
}
Exemplo n.º 6
0
func TestList(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, "GET")
		th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)

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

		fmt.Fprintf(w, `
{
    "networks": [
        {
            "status": "ACTIVE",
            "subnets": [
                "54d6f61d-db07-451c-9ab3-b9609b6b6f0b"
            ],
            "name": "private-network",
            "admin_state_up": true,
            "tenant_id": "4fd44f30292945e481c7b8a0c8908869",
            "shared": true,
            "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
            "provider:segmentation_id": null,
            "provider:physical_network": null,
            "provider:network_type": "local"
        },
        {
            "status": "ACTIVE",
            "subnets": [
                "08eae331-0402-425a-923c-34f7cfe39c1b"
            ],
            "name": "private",
            "admin_state_up": true,
            "tenant_id": "26a7980765d0414dbc1fc1f88cdb7e6e",
            "shared": true,
            "id": "db193ab3-96e3-4cb3-8fc5-05f4296d0324",
            "provider:segmentation_id": 1234567890,
            "provider:physical_network": null,
            "provider:network_type": "local"
        }
    ]
}
			`)
	})

	count := 0

	networks.List(fake.ServiceClient(), networks.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) {
		count++
		actual, err := ExtractList(page)
		if err != nil {
			t.Errorf("Failed to extract networks: %v", err)
			return false, err
		}

		expected := []NetworkExtAttrs{
			NetworkExtAttrs{
				Status:          "ACTIVE",
				Subnets:         []string{"54d6f61d-db07-451c-9ab3-b9609b6b6f0b"},
				Name:            "private-network",
				AdminStateUp:    true,
				TenantID:        "4fd44f30292945e481c7b8a0c8908869",
				Shared:          true,
				ID:              "d32019d3-bc6e-4319-9c1d-6722fc136a22",
				NetworkType:     "local",
				PhysicalNetwork: "",
				SegmentationID:  "",
			},
			NetworkExtAttrs{
				Status:          "ACTIVE",
				Subnets:         []string{"08eae331-0402-425a-923c-34f7cfe39c1b"},
				Name:            "private",
				AdminStateUp:    true,
				TenantID:        "26a7980765d0414dbc1fc1f88cdb7e6e",
				Shared:          true,
				ID:              "db193ab3-96e3-4cb3-8fc5-05f4296d0324",
				NetworkType:     "local",
				PhysicalNetwork: "",
				SegmentationID:  "1234567890",
			},
		}

		th.CheckDeepEquals(t, expected, actual)

		return true, nil
	})

	if count != 1 {
		t.Errorf("Expected 1 page, got %d", count)
	}
}
Exemplo n.º 7
0
func main() {
	// step-1
	var authUsername string = "your_auth_username"
	var authPassword string = "your_auth_password"
	var authUrl string = "http://controller:5000"
	var projectName string = "your_project_id"
	var regionName string = "your_region_name"

	authOpts := gophercloud.AuthOptions{
		IdentityEndpoint: authUrl,
		Username:         authUsername,
		Password:         authPassword,
		TenantID:         projectName,
	}
	provider, _ := openstack.AuthenticatedClient(authOpts)
	client, _ := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{
		Region: regionName,
	})

	// step-2
	pager := images.ListDetail(client, images.ListOpts{})
	page, _ := pager.AllPages()
	imageList, _ := images.ExtractImages(page)
	fmt.Println(imageList)

	// step-3
	pager = flavors.ListDetail(client, flavors.ListOpts{})
	page, _ = pager.AllPages()
	flavorList, _ := flavors.ExtractFlavors(page)
	fmt.Println(flavorList)

	// step-4
	imageID := "74e6d1ec-9a08-444c-8518-4f232446386d"
	image, _ := images.Get(client, imageID).Extract()
	fmt.Println(image)

	// step-5
	flavorID := "1"
	flavor, _ := flavors.Get(client, flavorID).Extract()
	fmt.Println(flavor)

	// step-6
	instanceName := "testing"
	testingInstance, _ := servers.Create(client, servers.CreateOpts{
		Name:      instanceName,
		ImageRef:  imageID,
		FlavorRef: flavorID,
	}).Extract()
	fmt.Println(testingInstance)

	// step-7
	pager = servers.List(client, servers.ListOpts{})
	page, _ = pager.AllPages()
	serverList, _ := servers.ExtractServers(page)
	fmt.Println(serverList)

	// step-8
	servers.Delete(client, testingInstance.ID)

	// step-9
	fmt.Println("Checking for existing SSH key pair...")
	keyPairName := "demokey"
	pubKeyFile := "~/.ssh/id_rsa.pub"
	keyPairExists := false

	pager = keypairs.List(client)
	page, _ = pager.AllPages()
	keypairList, _ := keypairs.ExtractKeyPairs(page)
	for _, k := range keypairList {
		if k.Name == keyPairName {
			keyPairExists = true
			break
		}
	}

	if keyPairExists {
		fmt.Println("Keypair " + keyPairName + " already exists. Skipping import.")
	} else {
		fmt.Println("adding keypair...")
		bs, _ := ioutil.ReadFile(pubKeyFile)
		keypairs.Create(client, keypairs.CreateOpts{
			Name:      keyPairName,
			PublicKey: string(bs),
		}).Extract()
	}

	pager = keypairs.List(client)
	page, _ = pager.AllPages()
	keypairList, _ = keypairs.ExtractKeyPairs(page)
	fmt.Println(keypairList)

	// step-10
	fmt.Println("Checking for existing security group...")
	var allInOneSecurityGroup secgroups.SecurityGroup
	securityGroupName := "all-in-one"
	securityGroupExists := false

	pager = secgroups.List(client)
	page, _ = pager.AllPages()
	secgroupList, _ := secgroups.ExtractSecurityGroups(page)
	for _, secGroup := range secgroupList {
		if secGroup.Name == securityGroupName {
			allInOneSecurityGroup = secGroup
			securityGroupExists = true
			break
		}
	}

	if securityGroupExists {
		fmt.Println("Security Group " + allInOneSecurityGroup.Name + " already exists. Skipping creation.")
	} else {
		allInOneSecurityGroup, _ := secgroups.Create(client, secgroups.CreateOpts{
			Name:        securityGroupName,
			Description: "network access for all-in-one application.",
		}).Extract()
		secgroups.CreateRule(client, secgroups.CreateRuleOpts{
			ParentGroupID: allInOneSecurityGroup.ID,
			FromPort:      80,
			ToPort:        80,
			IPProtocol:    "TCP",
			CIDR:          "0.0.0.0/0",
		}).Extract()
		secgroups.CreateRule(client, secgroups.CreateRuleOpts{
			ParentGroupID: allInOneSecurityGroup.ID,
			FromPort:      22,
			ToPort:        22,
			IPProtocol:    "TCP",
			CIDR:          "0.0.0.0/0",
		}).Extract()
	}

	pager = secgroups.List(client)
	page, _ = pager.AllPages()
	secgroupList, _ = secgroups.ExtractSecurityGroups(page)
	fmt.Println(secgroupList)

	// step-11
	userData := `#!/usr/bin/env bash
curl -L -s https://git.openstack.org/cgit/openstack/faafo/plain/contrib/install.sh | bash -s -- \
    -i faafo -i messaging -r api -r worker -r demo
`

	// step-12
	fmt.Println("Checking for existing instance...")
	instanceName = "all-in-one"
	instanceExists := false

	pager = servers.List(client, servers.ListOpts{})
	page, _ = pager.AllPages()
	serverList, _ = servers.ExtractServers(page)
	for _, s := range serverList {
		if s.Name == instanceName {
			testingInstance = &s
			instanceExists = true
			break
		}
	}

	if instanceExists {
		fmt.Println("Instance " + testingInstance.Name + " already exists. Skipping creation.")
	} else {
		opts := servers.CreateOpts{
			Name:           instanceName,
			ImageRef:       image.ID,
			FlavorRef:      flavor.ID,
			SecurityGroups: []string{securityGroupName},
			UserData:       []byte(userData),
		}
		testingInstance, _ = servers.Create(client, keypairs.CreateOptsExt{
			CreateOptsBuilder: opts,
			KeyName:           keyPairName,
		}).Extract()
	}
	servers.WaitForStatus(client, testingInstance.ID, "ACTIVE", 300)

	pager = servers.List(client, servers.ListOpts{})
	page, _ = pager.AllPages()
	serverList, _ = servers.ExtractServers(page)
	fmt.Println(serverList)

	// step-13
	var privateIP string
	for t, addrs := range testingInstance.Addresses {
		if t != "private" || len(privateIP) != 0 {
			continue
		}
		addrs, ok := addrs.([]interface{})
		if !ok {
			continue
		}
		for _, addr := range addrs {
			a, ok := addr.(map[string]interface{})
			if !ok || a["version"].(float64) != 4 {
				continue
			}
			ip, ok := a["addr"].(string)
			if ok && len(ip) != 0 {
				privateIP = ip
				fmt.Println("Private IP found: " + privateIP)
				break
			}
		}
	}

	// step-14
	var publicIP string
	for t, addrs := range testingInstance.Addresses {
		if t != "public" || len(publicIP) != 0 {
			continue
		}
		addrs, ok := addrs.([]interface{})
		if !ok {
			continue
		}
		for _, addr := range addrs {
			a, ok := addr.(map[string]interface{})
			if !ok || a["version"].(float64) != 4 {
				continue
			}
			ip, ok := a["addr"].(string)
			if ok && len(ip) != 0 {
				publicIP = ip
				fmt.Println("Public IP found: " + publicIP)
				break
			}
		}
	}

	// step-15
	fmt.Println("Checking for unused Floating IP...")
	var unusedFloatingIP string
	pager = floatingip.List(client)
	page, _ = pager.AllPages()
	floatingIPList, _ := floatingip.ExtractFloatingIPs(page)
	for _, ip := range floatingIPList {
		if ip.InstanceID == "" {
			unusedFloatingIP = ip.IP
			break
		}
	}

	networkClient, _ := openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{
		Region: regionName,
	})

	pager = networks.List(networkClient, networks.ListOpts{})
	page, _ = pager.AllPages()
	poolList, _ := external.ExtractList(page)
	for _, pool := range poolList {
		if len(unusedFloatingIP) != 0 || !pool.External {
			continue
		}
		fmt.Println("Allocating new Floating IP from pool: " + pool.Name)
		f, _ := floatingip.Create(client, floatingip.CreateOpts{Pool: pool.Name}).Extract()
		unusedFloatingIP = f.IP
	}

	// step-16
	if len(publicIP) != 0 {
		fmt.Println("Instance " + testingInstance.Name + " already has a public ip. Skipping attachment.")
	} else {
		floatingip.Associate(client, testingInstance.ID, unusedFloatingIP)
	}

	// step-17
	var actualIPAddress string
	if len(publicIP) != 0 {
		actualIPAddress = publicIP
	} else if len(unusedFloatingIP) != 0 {
		actualIPAddress = unusedFloatingIP
	} else {
		actualIPAddress = privateIP
	}

	fmt.Println("The Fractals app will be deployed to http://" + actualIPAddress)
}
Exemplo n.º 8
0
func TestList(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()

	th.Mux.HandleFunc("/networks", func(w http.ResponseWriter, r *http.Request) {
		th.TestMethod(t, r, "GET")
		th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)

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

		fmt.Fprintf(w, `
{
    "networks": [
        {
            "admin_state_up": true,
            "id": "0f38d5ad-10a6-428f-a5fc-825cfe0f1970",
            "name": "net1",
            "router:external": false,
            "shared": false,
            "status": "ACTIVE",
            "subnets": [
                "25778974-48a8-46e7-8998-9dc8c70d2f06"
            ],
            "tenant_id": "b575417a6c444a6eb5cc3a58eb4f714a"
        },
        {
            "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"
        }
    ]
}
			`)
	})

	count := 0

	networks.List(fake.ServiceClient(), networks.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) {
		count++
		actual, err := ExtractList(page)
		if err != nil {
			t.Errorf("Failed to extract networks: %v", err)
			return false, err
		}

		expected := []NetworkExternal{
			NetworkExternal{
				Status:       "ACTIVE",
				Subnets:      []string{"25778974-48a8-46e7-8998-9dc8c70d2f06"},
				Name:         "net1",
				AdminStateUp: true,
				TenantID:     "b575417a6c444a6eb5cc3a58eb4f714a",
				Shared:       false,
				ID:           "0f38d5ad-10a6-428f-a5fc-825cfe0f1970",
				External:     false,
			},
			NetworkExternal{
				Status:       "ACTIVE",
				Subnets:      []string{"2f1fb918-9b0e-4bf9-9a50-6cebbb4db2c5"},
				Name:         "ext_net",
				AdminStateUp: true,
				TenantID:     "5eb8995cf717462c9df8d1edfa498010",
				Shared:       false,
				ID:           "8d05a1b1-297a-46ca-8974-17debf51ca3c",
				External:     true,
			},
		}

		th.CheckDeepEquals(t, expected, actual)

		return true, nil
	})

	if count != 1 {
		t.Errorf("Expected 1 page, got %d", count)
	}
}