Example #1
0
func TestServerGroups(t *testing.T) {
	choices, err := ComputeChoicesFromEnv()
	if err != nil {
		t.Fatal(err)
	}

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

	sg, err := createServerGroup(t, computeClient)
	if err != nil {
		t.Fatalf("Unable to create server group: %v", err)
	}
	defer func() {
		servergroups.Delete(computeClient, sg.ID)
		t.Logf("Server Group deleted.")
	}()

	err = getServerGroup(t, computeClient, sg.ID)
	if err != nil {
		t.Fatalf("Unable to get server group: %v", err)
	}

	firstServer, err := createServerInGroup(t, computeClient, choices, sg)
	if err != nil {
		t.Fatalf("Unable to create server: %v", err)
	}
	defer func() {
		servers.Delete(computeClient, firstServer.ID)
		t.Logf("Server deleted.")
	}()

	if err = waitForStatus(computeClient, firstServer, "ACTIVE"); err != nil {
		t.Fatalf("Unable to wait for server: %v", err)
	}

	firstServer, err = servers.Get(computeClient, firstServer.ID).Extract()

	secondServer, err := createServerInGroup(t, computeClient, choices, sg)
	if err != nil {
		t.Fatalf("Unable to create server: %v", err)
	}
	defer func() {
		servers.Delete(computeClient, secondServer.ID)
		t.Logf("Server deleted.")
	}()

	if err = waitForStatus(computeClient, secondServer, "ACTIVE"); err != nil {
		t.Fatalf("Unable to wait for server: %v", err)
	}

	secondServer, err = servers.Get(computeClient, secondServer.ID).Extract()

	if err = verifySchedulerWorked(t, firstServer, secondServer); err != nil {
		t.Fatalf("Scheduling did not work: %v", err)
	}
}
func (s *StepWaitForRackConnect) Run(state multistep.StateBag) multistep.StepAction {
	if !s.Wait {
		return multistep.ActionContinue
	}

	config := state.Get("config").(Config)
	server := state.Get("server").(*servers.Server)
	ui := state.Get("ui").(packer.Ui)

	// We need the v2 compute client
	computeClient, err := config.computeV2Client()
	if err != nil {
		err = fmt.Errorf("Error initializing compute client: %s", err)
		state.Put("error", err)
		return multistep.ActionHalt
	}

	ui.Say(fmt.Sprintf(
		"Waiting for server (%s) to become RackConnect ready...", server.ID))
	for {
		server, err = servers.Get(computeClient, server.ID).Extract()
		if err != nil {
			return multistep.ActionHalt
		}

		if server.Metadata["rackconnect_automation_status"] == "DEPLOYED" {
			state.Put("server", server)
			break
		}

		time.Sleep(2 * time.Second)
	}

	return multistep.ActionContinue
}
func testAccCheckComputeV2InstanceExists(t *testing.T, n string, instance *servers.Server) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		config := testAccProvider.Meta().(*Config)
		computeClient, err := config.computeV2Client(OS_REGION_NAME)
		if err != nil {
			return fmt.Errorf("(testAccCheckComputeV2InstanceExists) Error creating OpenStack compute client: %s", err)
		}

		found, err := servers.Get(computeClient, rs.Primary.ID).Extract()
		if err != nil {
			return err
		}

		if found.ID != rs.Primary.ID {
			return fmt.Errorf("Instance not found")
		}

		*instance = *found

		return nil
	}
}
Example #4
0
func (c *GenericClient) GetServerDetail(d *Driver) (*servers.Server, error) {
	server, err := servers.Get(c.Compute, d.MachineId).Extract()
	if err != nil {
		return nil, err
	}
	return server, nil
}
Example #5
0
func (driver *Driver) getInstance() (*servers.Server, error) {
	server, err := servers.Get(driver.Client, driver.InstanceID).Extract()
	if err != nil {
		return nil, err
	}

	return server, nil
}
Example #6
0
func TestExtractGet(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()
	servers.HandleServerGetSuccessfully(t)

	config, err := ExtractGet(servers.Get(client.ServiceClient(), "1234asdf"))
	th.AssertNoErr(t, err)
	th.CheckEquals(t, Manual, *config)
}
Example #7
0
func (d *driver) getInstance() (*servers.Server, error) {
	server, err := servers.Get(d.client, d.instanceID).Extract()
	if err != nil {
		return nil,
			errors.WithFieldsE(ef(), "error getting server instance", err)
	}

	return server, nil
}
Example #8
0
func TestCreateServerWithKeyPair(t *testing.T) {
	client, err := newClient()
	th.AssertNoErr(t, err)

	if testing.Short() {
		t.Skip("Skipping test that requires server creation in short mode.")
	}

	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	publicKey := privateKey.PublicKey
	pub, err := ssh.NewPublicKey(&publicKey)
	th.AssertNoErr(t, err)
	pubBytes := ssh.MarshalAuthorizedKey(pub)
	pk := string(pubBytes)

	kp, err := keypairs.Create(client, keypairs.CreateOpts{
		Name:      keyName,
		PublicKey: pk,
	}).Extract()
	th.AssertNoErr(t, err)
	t.Logf("Created key pair: %s\n", kp)

	choices, err := ComputeChoicesFromEnv()
	th.AssertNoErr(t, err)

	name := tools.RandomString("Gophercloud-", 8)
	t.Logf("Creating server [%s] with key pair.", name)

	serverCreateOpts := servers.CreateOpts{
		Name:      name,
		FlavorRef: choices.FlavorID,
		ImageRef:  choices.ImageID,
	}

	server, err := servers.Create(client, keypairs.CreateOptsExt{
		serverCreateOpts,
		keyName,
	}).Extract()
	th.AssertNoErr(t, err)
	defer servers.Delete(client, server.ID)
	if err = waitForStatus(client, server, "ACTIVE"); err != nil {
		t.Fatalf("Unable to wait for server: %v", err)
	}

	server, err = servers.Get(client, server.ID).Extract()
	t.Logf("Created server: %+v\n", server)
	th.AssertNoErr(t, err)
	th.AssertEquals(t, server.KeyName, keyName)

	t.Logf("Deleting key pair [%s]...", kp.Name)
	err = keypairs.Delete(client, keyName).ExtractErr()
	th.AssertNoErr(t, err)

	t.Logf("Deleting server [%s]...", name)
}
// getInstanceNetworks collects instance network information from different sources
// and aggregates it all together.
func getInstanceNetworksAndAddresses(computeClient *gophercloud.ServiceClient, d *schema.ResourceData) ([]map[string]interface{}, error) {
	server, err := servers.Get(computeClient, d.Id()).Extract()

	if err != nil {
		return nil, CheckDeleted(d, err, "server")
	}

	networkDetails, err := getInstanceNetworks(computeClient, d)
	addresses := getInstanceAddresses(server.Addresses)
	if err != nil {
		return nil, err
	}

	// if there are no networkDetails, make networks at least a length of 1
	networkLength := 1
	if len(networkDetails) > 0 {
		networkLength = len(networkDetails)
	}
	networks := make([]map[string]interface{}, networkLength)

	// Loop through all networks and addresses,
	// merge relevant address details.
	if len(networkDetails) == 0 {
		for netName, n := range addresses {
			networks[0] = map[string]interface{}{
				"name":        netName,
				"fixed_ip_v4": n["fixed_ip_v4"],
				"fixed_ip_v6": n["fixed_ip_v6"],
				"floating_ip": n["floating_ip"],
				"mac":         n["mac"],
			}
		}
	} else {
		for i, net := range networkDetails {
			n := addresses[net["name"].(string)]

			networks[i] = map[string]interface{}{
				"uuid":           networkDetails[i]["uuid"],
				"name":           networkDetails[i]["name"],
				"port":           networkDetails[i]["port"],
				"fixed_ip_v4":    n["fixed_ip_v4"],
				"fixed_ip_v6":    n["fixed_ip_v6"],
				"floating_ip":    n["floating_ip"],
				"mac":            n["mac"],
				"access_network": networkDetails[i]["access_network"],
			}
		}
	}

	log.Printf("[DEBUG] networks: %+v", networks)

	return networks, nil
}
Example #10
0
func waitForStatus(client *gophercloud.ServiceClient, server *servers.Server, status string) error {
	return tools.WaitFor(func() (bool, error) {
		latest, err := servers.Get(client, server.ID).Extract()
		if err != nil {
			return false, err
		}

		if latest.Status == status {
			// Success!
			return true, nil
		}

		return false, nil
	})
}
func TestUpdateServer(t *testing.T) {
	client, err := newClient()
	if err != nil {
		t.Fatalf("Unable to create a compute client: %v", err)
	}

	choices, err := ComputeChoicesFromEnv()
	if err != nil {
		t.Fatal(err)
	}

	server, err := createServer(t, client, choices)
	if err != nil {
		t.Fatal(err)
	}
	defer servers.Delete(client, server.ID)

	if err = waitForStatus(client, server, "ACTIVE"); err != nil {
		t.Fatal(err)
	}

	alternateName := tools.RandomString("ACPTTEST", 16)
	for alternateName == server.Name {
		alternateName = tools.RandomString("ACPTTEST", 16)
	}

	t.Logf("Attempting to rename the server to %s.", alternateName)

	updated, err := servers.Update(client, server.ID, servers.UpdateOpts{Name: alternateName}).Extract()
	if err != nil {
		t.Fatalf("Unable to rename server: %v", err)
	}

	if updated.ID != server.ID {
		t.Errorf("Updated server ID [%s] didn't match original server ID [%s]!", updated.ID, server.ID)
	}

	err = tools.WaitFor(func() (bool, error) {
		latest, err := servers.Get(client, updated.ID).Extract()
		if err != nil {
			return false, err
		}

		return latest.Name == alternateName, nil
	})
}
// ServerV2StateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// an OpenStack instance.
func ServerV2StateRefreshFunc(client *gophercloud.ServiceClient, instanceID string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		s, err := servers.Get(client, instanceID).Extract()
		if err != nil {
			errCode, ok := err.(*gophercloud.UnexpectedResponseCodeError)
			if !ok {
				return nil, "", err
			}
			if errCode.Actual == 404 {
				return s, "DELETED", nil
			}
			return nil, "", err
		}

		return s, s.Status, nil
	}
}
Example #13
0
func (c *GenericClient) WaitForInstanceStatus(d *Driver, status string) error {
	return mcnutils.WaitForSpecificOrError(func() (bool, error) {
		current, err := servers.Get(c.Compute, d.MachineId).Extract()
		if err != nil {
			return true, err
		}

		if current.Status == "ERROR" {
			return true, fmt.Errorf("Instance creation failed. Instance is in ERROR state")
		}

		if current.Status == status {
			return true, nil
		}

		return false, nil
	}, (d.ActiveTimeout / 4), 4*time.Second)
}
Example #14
0
// ServerStateRefreshFunc returns a StateRefreshFunc that is used to watch
// an openstack server.
func ServerStateRefreshFunc(
	client *gophercloud.ServiceClient, s *servers.Server) StateRefreshFunc {
	return func() (interface{}, string, int, error) {
		serverNew, err := servers.Get(client, s.ID).Extract()
		if err != nil {
			errCode, ok := err.(*gophercloud.UnexpectedResponseCodeError)
			if ok && errCode.Actual == 404 {
				log.Printf("[INFO] 404 on ServerStateRefresh, returning DELETED")
				return nil, "DELETED", 0, nil
			} else {
				log.Printf("[ERROR] Error on ServerStateRefresh: %s", err)
				return nil, "", 0, err
			}
		}

		return serverNew, serverNew.Status, serverNew.Progress, nil
	}
}
Example #15
0
// CommHost looks up the host for the communicator.
func CommHost(
	client *gophercloud.ServiceClient,
	sshinterface string,
	sshipversion string) func(multistep.StateBag) (string, error) {
	return func(state multistep.StateBag) (string, error) {
		s := state.Get("server").(*servers.Server)

		// If we have a specific interface, try that
		if sshinterface != "" {
			if addr := sshAddrFromPool(s, sshinterface, sshipversion); addr != "" {
				log.Printf("[DEBUG] Using IP address %s from specified interface %s to connect", addr, sshinterface)
				return addr, nil
			}
		}

		// If we have a floating IP, use that
		ip := state.Get("access_ip").(*floatingip.FloatingIP)
		if ip != nil && ip.IP != "" {
			log.Printf("[DEBUG] Using floating IP %s to connect", ip.IP)
			return ip.IP, nil
		}

		if s.AccessIPv4 != "" {
			log.Printf("[DEBUG] Using AccessIPv4 %s to connect", s.AccessIPv4)
			return s.AccessIPv4, nil
		}

		// Try to get it from the requested interface
		if addr := sshAddrFromPool(s, sshinterface, sshipversion); addr != "" {
			log.Printf("[DEBUG] Using IP address %s to connect", addr)
			return addr, nil
		}

		s, err := servers.Get(client, s.ID).Extract()
		if err != nil {
			return "", err
		}

		state.Put("server", s)
		time.Sleep(1 * time.Second)

		return "", errors.New("couldn't determine IP address for server")
	}
}
func testAccCheckComputeV2InstanceDestroy(s *terraform.State) error {
	config := testAccProvider.Meta().(*Config)
	computeClient, err := config.computeV2Client(OS_REGION_NAME)
	if err != nil {
		return fmt.Errorf("(testAccCheckComputeV2InstanceDestroy) Error creating OpenStack compute client: %s", err)
	}

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "openstack_compute_instance_v2" {
			continue
		}

		_, err := servers.Get(computeClient, rs.Primary.ID).Extract()
		if err == nil {
			return fmt.Errorf("Instance still exists")
		}
	}

	return nil
}
func testAccCheckComputeV2InstanceDoesNotExist(t *testing.T, n string, instance *servers.Server) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		config := testAccProvider.Meta().(*Config)
		computeClient, err := config.computeV2Client(OS_REGION_NAME)
		if err != nil {
			return fmt.Errorf("(testAccCheckComputeV2InstanceExists) Error creating OpenStack compute client: %s", err)
		}

		_, err = servers.Get(computeClient, instance.ID).Extract()
		if err != nil {
			errCode, ok := err.(*gophercloud.UnexpectedResponseCodeError)
			if !ok {
				return err
			}
			if errCode.Actual == 404 {
				return nil
			}
			return err
		}

		return fmt.Errorf("Instance still exists")
	}
}
Example #18
0
func associateFloatingIPFixed(t *testing.T, client *gophercloud.ServiceClient, serverId string, fip *floatingip.FloatingIP) {

	network := os.Getenv("OS_NETWORK_NAME")
	server, err := servers.Get(client, serverId).Extract()
	if err != nil {
		t.Fatalf("%s", err)
	}

	var fixedIP string
	for _, networkAddresses := range server.Addresses[network].([]interface{}) {
		address := networkAddresses.(map[string]interface{})
		if address["OS-EXT-IPS:type"] == "fixed" {
			if address["version"].(float64) == 4 {
				fixedIP = address["addr"].(string)
			}
		}
	}

	associateOpts := floatingip.AssociateOpts{
		ServerID:   serverId,
		FloatingIP: fip.IP,
		FixedIP:    fixedIP,
	}

	err = floatingip.AssociateInstance(client, associateOpts).ExtractErr()
	th.AssertNoErr(t, err)
	t.Logf("Associated floating IP %v from instance %v with Fixed IP %v", fip.IP, serverId, fixedIP)
	defer func() {
		err = floatingip.DisassociateInstance(client, associateOpts).ExtractErr()
		th.AssertNoErr(t, err)
		t.Logf("Disassociated floating IP %v from instance %v with Fixed IP %v", fip.IP, serverId, fixedIP)
	}()
	floatingIp, err := floatingip.Get(client, fip.ID).Extract()
	th.AssertNoErr(t, err)
	th.AssertEquals(t, floatingIp.FixedIP, fixedIP)
	t.Logf("Floating IP %v is associated with Fixed IP %v", fip.IP, floatingIp.FixedIP)
}
func resourceComputeInstanceV2Read(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	computeClient, err := config.computeV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack compute client: %s", err)
	}

	server, err := servers.Get(computeClient, d.Id()).Extract()
	if err != nil {
		return CheckDeleted(d, err, "server")
	}

	log.Printf("[DEBUG] Retreived Server %s: %+v", d.Id(), server)

	d.Set("name", server.Name)

	// Get the instance network and address information
	networks, err := getInstanceNetworksAndAddresses(computeClient, d)
	if err != nil {
		return err
	}

	// Determine the best IPv4 and IPv6 addresses to access the instance with
	hostv4, hostv6 := getInstanceAccessAddresses(d, networks)

	d.Set("network", networks)
	d.Set("access_ip_v4", hostv4)
	d.Set("access_ip_v6", hostv6)

	// Determine the best IP address to use for SSH connectivity.
	// Prefer IPv4 over IPv6.
	preferredSSHAddress := ""
	if hostv4 != "" {
		preferredSSHAddress = hostv4
	} else if hostv6 != "" {
		preferredSSHAddress = hostv6
	}

	if preferredSSHAddress != "" {
		// Initialize the connection info
		d.SetConnInfo(map[string]string{
			"type": "ssh",
			"host": preferredSSHAddress,
		})
	}

	d.Set("metadata", server.Metadata)

	secGrpNames := []string{}
	for _, sg := range server.SecurityGroups {
		secGrpNames = append(secGrpNames, sg["name"].(string))
	}
	d.Set("security_groups", secGrpNames)

	flavorId, ok := server.Flavor["id"].(string)
	if !ok {
		return fmt.Errorf("Error setting OpenStack server's flavor: %v", server.Flavor)
	}
	d.Set("flavor_id", flavorId)

	flavor, err := flavors.Get(computeClient, flavorId).Extract()
	if err != nil {
		return err
	}
	d.Set("flavor_name", flavor.Name)

	// Set the instance's image information appropriately
	if err := setImageInformation(computeClient, server, d); err != nil {
		return err
	}

	// volume attachments
	if err := getVolumeAttachments(computeClient, d); err != nil {
		return err
	}

	return nil
}
Example #20
0
// Get requests details on a single server, by ID.
func Get(client *gophercloud.ServiceClient, id string) os.GetResult {
	return os.Get(client, id)
}
func resourceComputeInstanceV2Read(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	computeClient, err := config.computeV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack compute client: %s", err)
	}

	server, err := servers.Get(computeClient, d.Id()).Extract()
	if err != nil {
		return CheckDeleted(d, err, "server")
	}

	log.Printf("[DEBUG] Retreived Server %s: %+v", d.Id(), server)

	d.Set("name", server.Name)

	// begin reading the network configuration
	d.Set("access_ip_v4", server.AccessIPv4)
	d.Set("access_ip_v6", server.AccessIPv6)
	hostv4 := server.AccessIPv4
	hostv6 := server.AccessIPv6

	networkDetails, err := resourceInstanceNetworks(computeClient, d)
	addresses := resourceInstanceAddresses(server.Addresses)
	if err != nil {
		return err
	}

	// if there are no networkDetails, make networks at least a length of 1
	networkLength := 1
	if len(networkDetails) > 0 {
		networkLength = len(networkDetails)
	}
	networks := make([]map[string]interface{}, networkLength)

	// Loop through all networks and addresses,
	// merge relevant address details.
	if len(networkDetails) == 0 {
		for netName, n := range addresses {
			if floatingIP, ok := n["floating_ip"]; ok {
				hostv4 = floatingIP.(string)
			} else {
				if hostv4 == "" && n["fixed_ip_v4"] != nil {
					hostv4 = n["fixed_ip_v4"].(string)
				}
			}

			if hostv6 == "" && n["fixed_ip_v6"] != nil {
				hostv6 = n["fixed_ip_v6"].(string)
			}

			networks[0] = map[string]interface{}{
				"name":        netName,
				"fixed_ip_v4": n["fixed_ip_v4"],
				"fixed_ip_v6": n["fixed_ip_v6"],
				"mac":         n["mac"],
			}
		}
	} else {
		for i, net := range networkDetails {
			n := addresses[net["name"].(string)]

			if floatingIP, ok := n["floating_ip"]; ok {
				hostv4 = floatingIP.(string)
			} else {
				if hostv4 == "" && n["fixed_ip_v4"] != nil {
					hostv4 = n["fixed_ip_v4"].(string)
				}
			}

			if hostv6 == "" && n["fixed_ip_v6"] != nil {
				hostv6 = n["fixed_ip_v6"].(string)
			}

			networks[i] = map[string]interface{}{
				"uuid":        networkDetails[i]["uuid"],
				"name":        networkDetails[i]["name"],
				"port":        networkDetails[i]["port"],
				"fixed_ip_v4": n["fixed_ip_v4"],
				"fixed_ip_v6": n["fixed_ip_v6"],
				"mac":         n["mac"],
			}
		}
	}

	log.Printf("[DEBUG] new networks: %+v", networks)

	d.Set("network", networks)
	d.Set("access_ip_v4", hostv4)
	d.Set("access_ip_v6", hostv6)
	log.Printf("hostv4: %s", hostv4)
	log.Printf("hostv6: %s", hostv6)

	// prefer the v6 address if no v4 address exists.
	preferredv := ""
	if hostv4 != "" {
		preferredv = hostv4
	} else if hostv6 != "" {
		preferredv = hostv6
	}

	if preferredv != "" {
		// Initialize the connection info
		d.SetConnInfo(map[string]string{
			"type": "ssh",
			"host": preferredv,
		})
	}
	// end network configuration

	d.Set("metadata", server.Metadata)

	secGrpNames := []string{}
	for _, sg := range server.SecurityGroups {
		secGrpNames = append(secGrpNames, sg["name"].(string))
	}
	d.Set("security_groups", secGrpNames)

	flavorId, ok := server.Flavor["id"].(string)
	if !ok {
		return fmt.Errorf("Error setting OpenStack server's flavor: %v", server.Flavor)
	}
	d.Set("flavor_id", flavorId)

	flavor, err := flavors.Get(computeClient, flavorId).Extract()
	if err != nil {
		return err
	}
	d.Set("flavor_name", flavor.Name)

	// Set the instance's image information appropriately
	if err := setImageInformation(computeClient, server, d); err != nil {
		return err
	}

	// volume attachments
	if err := getVolumeAttachments(computeClient, d); err != nil {
		return err
	}

	return nil
}