Exemple #1
0
func (mapper *NeutronMapper) retrievePort(mac string) (port ports.Port, err error) {
	opts := ports.ListOpts{MACAddress: mac}
	pager := ports.List(mapper.client, opts)
	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.MACAddress == mac {
				port = p
				return true, nil
			}
		}

		return true, nil
	})

	if len(port.NetworkID) == 0 {
		return port, errors.New("Unable to find port for MAC address: " + mac)
	}

	return port, err
}
func getPortByIP(client *gophercloud.ServiceClient, ipAddress string) (neutronports.Port, error) {
	var targetPort neutronports.Port
	var portFound = false

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

		for _, port := range portList {
			for _, ip := range port.FixedIPs {
				if ip.IPAddress == ipAddress {
					targetPort = port
					portFound = true
					return false, nil
				}
			}
		}

		return true, nil
	})
	if err == nil && !portFound {
		err = ErrNotFound
	}
	return targetPort, err
}
Exemple #3
0
func (command *commandList) Execute(resource *handler.Resource) {
	opts := resource.Params.(*paramsList).opts
	allPages := resource.Params.(*paramsList).allPages
	pager := ports.List(command.Ctx.ServiceClient, opts)
	if allPages {
		pages, err := pager.AllPages()
		if err != nil {
			resource.Err = err
			return
		}
		info, err := osPorts.ExtractPorts(pages)
		if err != nil {
			resource.Err = err
			return
		}
		result := make([]map[string]interface{}, len(info))
		for j, subnet := range info {
			result[j] = portSingle(&subnet)
		}
		resource.Result = result
	} else {
		limit := opts.Limit
		err := pager.EachPage(func(page pagination.Page) (bool, error) {
			info, err := osPorts.ExtractPorts(page)
			if err != nil {
				return false, err
			}
			result := make([]map[string]interface{}, len(info))
			for j, subnet := range info {
				result[j] = portSingle(&subnet)
			}
			resource.Result = result
			if len(info) >= limit {
				return false, nil
			}
			limit -= len(info)
			command.Ctx.WaitGroup.Add(1)
			command.Ctx.Results <- resource
			return true, nil
		})
		if err != nil {
			resource.Err = err
			return
		}
	}
}
Exemple #4
0
func (mapper *NeutronMapper) retrievePort(metadata graph.Metadata) (port ports.Port, err error) {
	var opts ports.ListOpts
	var mac string

	/* If we have a MAC address for a device attached to the interface, that is the one that
	 * will be associated with the Neutron port. */
	if attached_mac, ok := metadata["ExtID.attached-mac"]; ok {
		mac = attached_mac.(string)
	} else {
		mac = metadata["MAC"].(string)
	}

	logging.GetLogger().Debugf("Retrieving attributes from Neutron for MAC: %s", mac)

	/* Determine the best way to search for the Neutron port.
	 * We prefer the Neutron port UUID if we have it, but will fall back
	 * to using the MAC address otherwise. */
	if portid, ok := metadata["ExtID.iface-id"]; ok {
		opts.ID = portid.(string)
	} else {
		opts.MACAddress = mac
	}
	pager := ports.List(mapper.client, opts)
	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.MACAddress == mac {
				port = p
				return true, nil
			}
		}

		return true, nil
	})

	if len(port.NetworkID) == 0 {
		return port, errors.New("Unable to find port for MAC address: " + mac)
	}

	return port, err
}
func getPortIDByIP(client *gophercloud.ServiceClient, ipAddress string) (string, error) {
	var portID string

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

		for _, port := range portList {
			for _, ip := range port.FixedIPs {
				if ip.IPAddress == ipAddress {
					portID = port.ID
					return false, nil
				}
			}
		}

		return true, nil
	})

	return portID, err
}
Exemple #6
0
func (c *GenericClient) GetInstancePortId(d *Driver) (string, error) {
	pager := ports.List(c.Network, ports.ListOpts{
		DeviceID:  d.MachineId,
		NetworkID: d.NetworkId,
	})

	var portId string
	err := pager.EachPage(func(page pagination.Page) (bool, error) {
		portList, err := ports.ExtractPorts(page)
		if err != nil {
			return false, err
		}
		for _, port := range portList {
			portId = port.ID
			return false, nil
		}
		return true, nil
	})

	if err != nil {
		return "", err
	}
	return portId, nil
}
func listPorts(t *testing.T) {
	count := 0
	pager := ports.List(Client, ports.ListOpts{})
	err := pager.EachPage(func(page pagination.Page) (bool, error) {
		count++
		t.Logf("--- Page ---")

		portList, err := ports.ExtractPorts(page)
		th.AssertNoErr(t, err)

		for _, p := range portList {
			t.Logf("Port: ID [%s] Name [%s] Status [%d] MAC addr [%s] Fixed IPs [%#v] Security groups [%#v]",
				p.ID, p.Name, p.Status, p.MACAddress, p.FixedIPs, p.SecurityGroups)
		}

		return true, nil
	})

	th.CheckNoErr(t, err)

	if count == 0 {
		t.Logf("No pages were iterated over when listing ports")
	}
}
Exemple #8
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)})
}
Exemple #9
0
func TestList(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()

	th.Mux.HandleFunc("/ports", 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, `
{
    "ports": [
        {
            "status": "ACTIVE",
            "binding:host_id": "devstack",
            "name": "",
            "admin_state_up": true,
            "network_id": "70c1db1f-b701-45bd-96e0-a313ee3430b3",
            "tenant_id": "",
            "device_owner": "network:router_gateway",
            "mac_address": "fa:16:3e:58:42:ed",
            "fixed_ips": [
                {
                    "subnet_id": "008ba151-0b8c-4a67-98b5-0d2b87666062",
                    "ip_address": "172.24.4.2"
                }
            ],
            "id": "d80b1a3b-4fc1-49f3-952e-1e2ab7081d8b",
            "security_groups": [],
            "device_id": "9ae135f4-b6e0-4dad-9e91-3c223e385824"
        }
    ]
}
      `)
	})

	count := 0

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

		expected := []os.Port{
			os.Port{
				Status:       "ACTIVE",
				Name:         "",
				AdminStateUp: true,
				NetworkID:    "70c1db1f-b701-45bd-96e0-a313ee3430b3",
				TenantID:     "",
				DeviceOwner:  "network:router_gateway",
				MACAddress:   "fa:16:3e:58:42:ed",
				FixedIPs: []os.IP{
					os.IP{
						SubnetID:  "008ba151-0b8c-4a67-98b5-0d2b87666062",
						IPAddress: "172.24.4.2",
					},
				},
				ID:             "d80b1a3b-4fc1-49f3-952e-1e2ab7081d8b",
				SecurityGroups: []string{},
				DeviceID:       "9ae135f4-b6e0-4dad-9e91-3c223e385824",
			},
		}

		th.CheckDeepEquals(t, expected, actual)

		return true, nil
	})

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