func (d *Driver) Create() error {
	client, err := d.getClient()
	if err != nil {
		return err
	}
	log.Infof("Creating SSH key...")
	err = d.createSSHkey()
	if err != nil {
		return err
	}
	userdata, err := d.getCloudInit()
	if err != nil {
		return err
	}
	encoded := base64.StdEncoding.EncodeToString(userdata)
	d.UserData = &encoded
	log.Infof("Creating Brightbox Server...")
	log.Debugf("with the following Userdata")
	log.Debugf("%s", string(userdata))
	log.Debugf("Brightbox API Call: Create Server using image %s", d.Image)
	server, err := client.CreateServer(&d.ServerOptions)
	if err != nil {
		return err
	}
	d.MachineID = server.Id
	return nil
}
func (d *Driver) Remove() error {
	s, err := d.GetState()
	if err != nil {
		if err == ErrMachineNotExist {
			log.Infof("machine does not exist, assuming it has been removed already")
			return nil
		}
		return err
	}
	if s == state.Running {
		if err := d.Stop(); err != nil {
			return err
		}
	}

	if err := d.removeDiskImage(); err != nil {
		return err
	}

	if d.NFSShare {
		log.Infof("Remove NFS share folder must be root. Please insert root password.")
		if _, err := nfsexports.Remove("", d.nfsExportIdentifier()); err != nil {
			log.Errorf("failed removing nfs share: %s", err.Error())
		}

		if err := nfsexports.ReloadDaemon(); err != nil {
			log.Errorf("failed reload nfs daemon: %s", err.Error())
		}
	}
	return nil
}
示例#3
0
// Submit desired power state
func (pt *PowerTask) SubmitPowerState(s PowerState) {
	if err := pt.GetCurrentPowerState(); err != nil {
		pt.TaskIsDone = true
		log.Errorf("Error getting current power state: %s", err)
		return
	}
	if s != pt.State {
		log.Infof("Powering %s server %s for %s.", s, pt.Blade.Name, pt.Blade.SerialNumber)
		var (
			body = PowerRequest{PowerState: s.String(), PowerControl: P_PRESSANDHOLD.String()}
			uri  = strings.Join([]string{pt.Blade.URI.String(),
				"/powerState"}, "")
		)
		log.Debugf("REST : %s \n %+v\n", uri, body)
		log.Debugf("pt -> %+v", pt)
		data, err := pt.Blade.Client.RestAPICall(rest.PUT, uri, body)
		if err != nil {
			pt.TaskIsDone = true
			log.Errorf("Error with power state request: %s", err)
			return
		}

		log.Debugf("SubmitPowerState %s", data)
		if err := json.Unmarshal([]byte(data), &pt); err != nil {
			pt.TaskIsDone = true
			log.Errorf("Error with power state un-marshal: %s", err)
			return
		}
	} else {
		log.Infof("Desired Power State already set -> %s", pt.State)
		pt.TaskIsDone = true
	}

	return
}
示例#4
0
// Submit desired power state and wait
// Most of our concurrency will happen in PowerExecutor
func (pt *PowerTask) PowerExecutor(s PowerState) error {
	currenttime := 0
	pt.State = P_UKNOWN
	pt.ResetTask()
	go pt.SubmitPowerState(s)
	for !pt.TaskIsDone && (currenttime < pt.Timeout) {
		if err := pt.GetCurrentTaskStatus(); err != nil {
			return err
		}
		if pt.URI != "" && T_COMPLETED.Equal(pt.TaskState) {
			pt.TaskIsDone = true
		}
		if pt.URI != "" {
			log.Debugf("Waiting to set power state %s for blade %s, %s", s, pt.Blade.Name)
			log.Infof("Working on power state,%d%%, %s.", pt.ComputedPercentComplete, pt.TaskStatus)
		} else {
			log.Info("Working on power state.")
		}

		// wait time before next check
		time.Sleep(time.Millisecond * (1000 * pt.WaitTime)) // wait 10sec before checking the status again
		currenttime++
	}
	if !(currenttime < pt.Timeout) {
		log.Warnf("Power %s state timed out for %s.", s, pt.Blade.Name)
	}
	log.Infof("Power Task Execution Completed")
	return nil
}
func (d *Driver) mountShareFolder(shareName string, mountPoint string) error {
	// Check the host path is available
	if _, err := os.Stat(mountPoint); err != nil {
		if os.IsNotExist(err) {
			log.Infof("Host path '%s' does not exist. Skipping mount to VM...", mountPoint)
			return nil
		}
		return err
	}

	// Ensure that share is available on the guest side
	checkCmd := "sudo modprobe prl_fs && grep -w " + shareName + " /proc/fs/prl_fs/sf_list"
	if _, err := drivers.RunSSHCommandFromDriver(d, checkCmd); err != nil {
		log.Infof("Shared folder '%s' is unavailable. Skipping mount to VM...", shareName)
		return nil
	}

	// Mount shared folder
	mountCmd := "sudo mkdir -p " + mountPoint + " && sudo mount -t prl_fs " + shareName + " " + mountPoint
	if _, err := drivers.RunSSHCommandFromDriver(d, mountCmd); err != nil {
		return fmt.Errorf("Error mounting shared folder: %s", err)
	}

	return nil
}
示例#6
0
// PreCreateCheck is called to enforce pre-creation steps
func (d *Driver) PreCreateCheck() error {
	c, err := newComputeUtil(d)
	if err != nil {
		return err
	}

	// Check that the project exists. It will also check the credentials
	// at the same time.
	log.Infof("Check that the project exists")

	if _, err = c.service.Projects.Get(d.Project).Do(); err != nil {
		return fmt.Errorf("Project with ID %q not found. %v", d.Project, err)
	}

	// Check if the instance already exists. There will be an error if the instance
	// doesn't exist, so just check instance for nil.
	log.Infof("Check if the instance already exists")

	instance, _ := c.instance()
	if d.UseExisting {
		if instance == nil {
			return fmt.Errorf("Unable to find instance %q in zone %q.", d.MachineName, d.Zone)
		}
	} else {
		if instance != nil {
			return fmt.Errorf("Instance %q already exists in zone %q.", d.MachineName, d.Zone)
		}
	}

	return nil
}
示例#7
0
func (d *Driver) Remove() error {
	client := d.getClient()
	log.Debugf("removing %s", d.MachineName)
	if err := client.DeleteServer(d.MachineID); err != nil {
		if strings.Contains(err.Error(), "Invalid server") {
			log.Infof("VPS doesn't exist, assuming it is already deleted")
		} else {
			return err
		}
	}
	if err := client.DeleteSSHKey(d.SSHKeyID); err != nil {
		if strings.Contains(err.Error(), "Invalid SSH Key") {
			log.Infof("SSH key doesn't exist, assuming it is already deleted")
		} else {
			return err
		}
	}
	if d.ScriptID != 0 && !d.HasCustomScript {
		if err := client.DeleteStartupScript(strconv.Itoa(d.ScriptID)); err != nil {
			if strings.Contains(err.Error(), "Check SCRIPTID") {
				log.Infof("PXE boot script doesn't exist, assuming it is already deleted")
			} else {
				return err
			}
		}
	}
	return nil
}
示例#8
0
文件: driver.go 项目: rogaha/machine
func (d *Driver) Create() error {
	spec := d.buildHostSpec()

	log.Infof("Creating SSH key...")
	key, err := d.createSSHKey()
	if err != nil {
		return err
	}

	log.Infof("SSH key %s (%d) created in SoftLayer", key.Label, key.Id)
	d.SSHKeyID = key.Id

	spec.SshKeys = []*SSHKey{key}

	id, err := d.getClient().VirtualGuest().Create(spec)
	if err != nil {
		return fmt.Errorf("Error creating host: %q", err)
	}
	d.Id = id
	d.getIP()
	d.waitForStart()
	d.waitForSetupTransactions()

	return nil
}
示例#9
0
func (d *Driver) Stop() error {
	currentState, err := d.GetState()
	if err != nil {
		return err
	}

	if currentState == state.Paused {
		if err := d.vbm("controlvm", d.MachineName, "resume"); err != nil { // , "--type", "headless"
			return err
		}
		log.Infof("Resuming VM ...")
	}

	if err := d.vbm("controlvm", d.MachineName, "acpipowerbutton"); err != nil {
		return err
	}
	for {
		s, err := d.GetState()
		if err != nil {
			return err
		}
		if s == state.Running {
			time.Sleep(1 * time.Second)
		} else {
			break
		}
	}
	log.Infof("Stopping VM...")

	d.IPAddress = ""

	return nil
}
示例#10
0
文件: b2d.go 项目: rhendric/machine
func (b *B2dUtils) CopyIsoToMachineDir(isoURL, machineName string) error {
	// TODO: This is a bit off-color.
	machineDir := filepath.Join(b.storePath, "machines", machineName)
	machineIsoPath := filepath.Join(machineDir, b.isoFilename)

	// just in case the cache dir has been manually deleted,
	// check for it and recreate it if it's gone
	if _, err := os.Stat(b.imgCachePath); os.IsNotExist(err) {
		log.Infof("Image cache does not exist, creating it at %s...", b.imgCachePath)
		if err := os.Mkdir(b.imgCachePath, 0700); err != nil {
			return err
		}
	}

	// By default just copy the existing "cached" iso to
	// the machine's directory...
	if isoURL == "" {
		if err := b.copyDefaultIsoToMachine(machineIsoPath); err != nil {
			return err
		}
	} else {
		//if ISO is specified, check if it matches a github releases url or fallback
		//to a direct download
		if downloadUrl, err := b.GetLatestBoot2DockerReleaseURL(isoURL); err == nil {
			log.Infof("Downloading %s from %s...", b.isoFilename, downloadUrl)
			if err := b.DownloadISO(machineDir, b.isoFilename, downloadUrl); err != nil {
				return err
			}
		} else {
			return err
		}
	}

	return nil
}
示例#11
0
文件: host.go 项目: sheltowt/machine
func (h *Host) Start() error {
	log.Infof("Starting %q...", h.Name)
	if err := h.runActionForState(h.Driver.Start, state.Running); err != nil {
		return err
	}

	log.Infof("Machine %q was started.", h.Name)
	return nil
}
示例#12
0
文件: host.go 项目: sheltowt/machine
func (h *Host) Stop() error {
	log.Infof("Stopping %q...", h.Name)
	if err := h.runActionForState(h.Driver.Stop, state.Stopped); err != nil {
		return err
	}

	log.Infof("Machine %q was stopped.", h.Name)
	return nil
}
示例#13
0
文件: host.go 项目: sheltowt/machine
func (h *Host) Kill() error {
	log.Infof("Killing %q...", h.Name)
	if err := h.runActionForState(h.Driver.Kill, state.Stopped); err != nil {
		return err
	}

	log.Infof("Machine %q was killed.", h.Name)
	return nil
}
示例#14
0
func (d *Driver) Create() error {
	log.Infof("Creating SSH key...")

	key, err := d.createSSHKey()
	if err != nil {
		return err
	}

	d.SSHKeyID = key.ID

	log.Infof("Creating Digital Ocean droplet...")

	client := d.getClient()

	createRequest := &godo.DropletCreateRequest{
		Image:             d.Image,
		Name:              d.MachineName,
		Region:            d.Region,
		Size:              d.Size,
		IPv6:              d.IPv6,
		PrivateNetworking: d.PrivateNetworking,
		Backups:           d.Backups,
		SSHKeys:           []interface{}{d.SSHKeyID},
	}

	newDroplet, _, err := client.Droplets.Create(createRequest)
	if err != nil {
		return err
	}

	d.DropletID = newDroplet.Droplet.ID

	log.Info("Waiting for IP address to be assigned to the Droplet...")
	for {
		newDroplet, _, err = client.Droplets.Get(d.DropletID)
		if err != nil {
			return err
		}
		for _, network := range newDroplet.Droplet.Networks.V4 {
			if network.Type == "public" {
				d.IPAddress = network.IPAddress
			}
		}

		if d.IPAddress != "" {
			break
		}

		time.Sleep(1 * time.Second)
	}

	log.Debugf("Created droplet ID %d, IP address %s",
		newDroplet.Droplet.ID,
		d.IPAddress)

	return nil
}
示例#15
0
// deleteDisk deletes the persistent disk.
func (c *ComputeUtil) deleteDisk() error {
	log.Infof("Deleting disk.")
	op, err := c.service.Disks.Delete(c.project, c.zone, c.diskName()).Do()
	if err != nil {
		return err
	}
	log.Infof("Waiting for disk to delete.")
	return c.waitForRegionalOp(op.Name)
}
// PreCreateCheck allows for pre-create operations to make sure a driver is ready for creation
func (d *Driver) PreCreateCheck() error {
	// Check platform type
	if runtime.GOOS != "darwin" {
		return fmt.Errorf("Driver \"parallels\" works only on OS X!")
	}

	// Check Parallels Desktop version
	ver, err := getParallelsVersion()
	if err != nil {
		return err
	}

	if ver < 10 {
		return fmt.Errorf("Driver \"parallels\" supports only Parallels Desktop 10 and higher. You use: Parallels Desktop %d.", ver)
	}

	if ver < 11 {
		log.Debugf("Found Parallels Desktop version: %d", ver)
		log.Infof("Driver \"parallels\" integration with Parallels Desktop 10 is maintained by open source community.")
		log.Infof("For Parallels supported configuration you should use it with Parallels Desktop 11 or later (Pro or Business edition).")
		return nil
	}

	// Check Parallels Desktop edition
	edit, err := getParallelsEdition()
	if err != nil {
		return err
	}

	log.Debugf("Found Parallels Desktop version: %d, edition: %s", ver, edit)

	switch edit {
	case "pro", "business":
		break
	default:
		return fmt.Errorf("Docker Machine can be used only with Parallels Desktop Pro or Business edition. You use: %s edition", edit)
	}

	// Check whether the host is connected to Shared network
	ok, err := isSharedConnected()
	if err != nil {
		return err
	}
	if !ok {
		return errSharedNotConnected
	}

	// Downloading boot2docker to cache should be done here to make sure
	// that a download failure will not leave a machine half created.
	b2dutils := mcnutils.NewB2dUtils(d.StorePath)
	if err := b2dutils.UpdateISOCache(d.Boot2DockerURL); err != nil {
		return err
	}

	return nil
}
示例#17
0
func (d *Driver) Start() error {
	s, err := d.GetState()
	if err != nil {
		return err
	}

	if s == state.Stopped {
		// check network to re-create if needed
		if err := d.setupHostOnlyNetwork(d.MachineName); err != nil {
			return fmt.Errorf("Error setting up host only network on machine start: %s", err)
		}
	}

	switch s {
	case state.Stopped, state.Saved:
		d.SSHPort, err = setPortForwarding(d, 1, "ssh", "tcp", 22, d.SSHPort)
		if err != nil {
			return err
		}
		if err := d.vbm("startvm", d.MachineName, "--type", "headless"); err != nil {
			return err
		}
		log.Infof("Starting VM...")
	case state.Paused:
		if err := d.vbm("controlvm", d.MachineName, "resume", "--type", "headless"); err != nil {
			return err
		}
		log.Infof("Resuming VM ...")
	default:
		log.Infof("VM not in restartable state")
	}

	// Verify that VT-X is not disabled in the started VM
	disabled, err := d.IsVTXDisabledInTheVM()
	if err != nil {
		return fmt.Errorf("Checking if hardware virtualization is enabled failed: %s", err)
	}

	if disabled {
		return ErrMustEnableVTX
	}

	// Wait for SSH over NAT to be available before returning to user
	if err := drivers.WaitForSSH(d); err != nil {
		return err
	}

	// Bail if we don't get an IP from DHCP after a given number of seconds.
	if err := mcnutils.WaitForSpecific(d.hostOnlyIPAvailable, 5, 4*time.Second); err != nil {
		return err
	}

	d.IPAddress, err = d.GetIP()

	return err
}
示例#18
0
// deleteInstance deletes the instance, leaving the persistent disk.
func (c *ComputeUtil) deleteInstance() error {
	log.Infof("Deleting instance.")
	op, err := c.service.Instances.Delete(c.project, c.zone, c.instanceName).Do()
	if err != nil {
		return err
	}

	log.Infof("Waiting for instance to delete.")
	return c.waitForRegionalOp(op.Name)
}
示例#19
0
func (d *Driver) Restart() error {

	p, err := govcloudair.NewClient()
	if err != nil {
		return err
	}

	log.Infof("Connecting to vCloud Air...")
	// Authenticate to vCloud Air
	v, err := p.Authenticate(d.UserName, d.UserPassword, d.ComputeID, d.VDCID)
	if err != nil {
		return err
	}

	vapp, err := v.FindVAppByID(d.VAppID)
	if err != nil {
		return err
	}

	status, err := vapp.GetStatus()
	if err != nil {
		return err
	}

	if status == "POWERED_ON" {
		// If it's powered on, restart the machine
		log.Infof("Restarting %s...", d.MachineName)
		task, err := vapp.Reset()
		if err != nil {
			return err
		}
		if err = task.WaitTaskCompletion(); err != nil {
			return err
		}

	} else {
		// If it's not powered on, start it.
		log.Infof("Docker host %s is powered off, powering it back on...", d.MachineName)
		task, err := vapp.PowerOn()
		if err != nil {
			return err
		}
		if err = task.WaitTaskCompletion(); err != nil {
			return err
		}

	}

	if err = p.Disconnect(); err != nil {
		return err
	}

	d.IPAddress, err = d.GetIP()
	return err
}
示例#20
0
func (d *Driver) Create() error {
	b2dutils := mcnutils.NewB2dUtils(d.StorePath)
	if err := b2dutils.CopyIsoToMachineDir(d.Boot2DockerURL, d.MachineName); err != nil {
		return err
	}

	log.Infof("Creating SSH key...")
	if err := ssh.GenerateSSHKey(d.GetSSHKeyPath()); err != nil {
		return err
	}

	log.Infof("Creating VM...")
	virtualSwitch, err := d.chooseVirtualSwitch()
	if err != nil {
		return err
	}

	log.Infof("Using switch %q", virtualSwitch)

	diskImage, err := d.generateDiskImage()
	if err != nil {
		return err
	}

	if err := cmd("New-VM",
		d.MachineName,
		"-Path", fmt.Sprintf("'%s'", d.ResolveStorePath(".")),
		"-SwitchName", quote(virtualSwitch),
		"-MemoryStartupBytes", toMb(d.MemSize)); err != nil {
		return err
	}

	if d.CPU > 1 {
		if err := cmd("Set-VMProcessor",
			d.MachineName,
			"-Count", fmt.Sprintf("%d", d.CPU)); err != nil {
			return err
		}
	}

	if err := cmd("Set-VMDvdDrive",
		"-VMName", d.MachineName,
		"-Path", quote(d.ResolveStorePath("boot2docker.iso"))); err != nil {
		return err
	}

	if err := cmd("Add-VMHardDiskDrive",
		"-VMName", d.MachineName,
		"-Path", quote(diskImage)); err != nil {
		return err
	}

	log.Infof("Starting VM...")
	return d.Start()
}
func (d *Driver) Remove() error {
	client := d.getClient()

	if _, err := client.Cloud.RemoveKey(d.SSHKeyID); err != nil {
		log.Infof("Remove Key: " + err.Error())
	}
	if _, err := client.Cloud.Destroy(d.ServiceID); err != nil {
		log.Infof("Destroy Cloud: " + err.Error())
	}
	return nil
}
示例#22
0
func (provisioner *Boot2DockerProvisioner) upgradeIso() error {
	// TODO: Ideally, we should not read from mcndirs directory at all.
	// The driver should be able to communicate how and where to place the
	// relevant files.
	b2dutils := mcnutils.NewB2dUtils(mcndirs.GetBaseDir())

	// Check if the driver has specified a custom b2d url
	jsonDriver, err := json.Marshal(provisioner.GetDriver())
	if err != nil {
		return err
	}
	var d struct {
		Boot2DockerURL string
	}
	json.Unmarshal(jsonDriver, &d)

	log.Info("Downloading latest boot2docker iso...")

	// Usually we call this implicitly, but call it here explicitly to get
	// the latest default boot2docker ISO.
	if d.Boot2DockerURL == "" {
		if err := b2dutils.DownloadLatestBoot2Docker(d.Boot2DockerURL); err != nil {
			return err
		}
	}

	log.Info("Stopping machine to do the upgrade...")

	if err := provisioner.Driver.Stop(); err != nil {
		return err
	}

	if err := mcnutils.WaitFor(drivers.MachineInState(provisioner.Driver, state.Stopped)); err != nil {
		return err
	}

	machineName := provisioner.GetDriver().GetMachineName()

	log.Infof("Upgrading machine %q...", machineName)

	// Either download the latest version of the b2d url that was explicitly
	// specified when creating the VM or copy the (updated) default ISO
	if err := b2dutils.CopyIsoToMachineDir(d.Boot2DockerURL, machineName); err != nil {
		return err
	}

	log.Infof("Starting machine back up...")

	if err := provisioner.Driver.Start(); err != nil {
		return err
	}

	return mcnutils.WaitFor(drivers.MachineInState(provisioner.Driver, state.Running))
}
示例#23
0
func saveToken(storePath string, token *oauth.Token) {
	tokenPath := path.Join(storePath, "gce_token")
	log.Infof("Saving token in %v", tokenPath)
	f, err := os.Create(tokenPath)
	if err != nil {
		log.Infof("Warning: failed to cache oauth token: %v", err)
		return
	}
	defer f.Close()
	gob.NewEncoder(f).Encode(token)
}
示例#24
0
// Install Kernel 3.19
func (d *Driver) upgradeKernel(sshClient ssh.Client, tcpAddr string) {
	log.Debugf("%s | Upgrade kernel version ...", d.MachineName)
	output, err := sshClient.Output("for i in 1 2 3 4 5; do apt-get update -y && break || sleep 5; done")
	log.Infof("%s | apt-get update update err, output: %v: %s", d.MachineName, err, output)
	output, err = sshClient.Output("for i in 1 2 3 4 5; do apt-get install -y linux-generic-lts-vivid && break || sleep 5; done")
	log.Infof("%s | Upgrade kernel err, output: %v: %s", d.MachineName, err, output)
	time.Sleep(5 * time.Second)
	log.Infof("%s | Restart VM instance for kernel update ...", d.MachineName)
	d.Restart()
	time.Sleep(30 * time.Second)
	sshClient.Output("echo 'I am back'")
}
// TestGetInterfaces  verify that interfaces works
func TestGetInterfaces(t *testing.T) {

	var (
		d            *ICSPTest
		c            *icsp.ICSPClient
		s            icsp.Server
		serialNumber string
		err          error
	)
	if os.Getenv("ICSP_TEST_ACCEPTANCE") == "true" {
		log.Debug("implements acceptance test for TestGetInterfaces")
		d, c = getTestDriverA()
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		if os.Getenv("ONEVIEW_TEST_PROVISION") == "true" {
			serialNumber = d.Tc.GetTestData(d.Env, "FreeBladeSerialNumber").(string)
			s, err = c.GetServerBySerialNumber(serialNumber)
		} else {
			serialNumber = d.Tc.GetTestData(d.Env, "SerialNumber").(string)
			s, err = c.GetServerBySerialNumber(serialNumber)
		}
		data := s.GetInterfaces()
		assert.NoError(t, err, "GetInterfaces threw error -> %s, %+v\n", err, data)
		assert.True(t, len(data) > 0, "Failed to get a valid list of interfaces -> %+v", data)
		for _, inet := range data {
			log.Infof("inet -> %+v", inet)
			log.Infof("inet ip -> %+v", inet.IPV4Addr)
			log.Infof("inet ip -> %+v", inet.Slot)
			log.Infof("inet ip -> %+v", inet.MACAddr)
		}
	} else {
		log.Debug("implements unit test for TestGetInterfaces")
		d, c = getTestDriverU()
		jsonServerData := d.Tc.GetTestData(d.Env, "ServerJSONString").(string)
		log.Debugf("jsonServerData => %s", jsonServerData)
		err := json.Unmarshal([]byte(jsonServerData), &s)
		assert.NoError(t, err, "Unmarshal Server threw error -> %s, %+v\n", err, jsonServerData)

		log.Debugf("server -> %v", s)

		data := s.GetInterfaces()
		log.Debugf("Interfaces -> %+v", data)
		assert.True(t, len(data) > 0, "Failed to get a valid list of interfaces -> %+v", data)
		for _, inet := range data {
			log.Debugf("inet -> %+v", inet)
			log.Debugf("inet ip -> %+v", inet.IPV4Addr)
			log.Debugf("inet ip -> %+v", inet.Slot)
			log.Debugf("inet ip -> %+v", inet.MACAddr)
		}
	}
}
func (d *Driver) Create() error {
	log.Infof("Creating SSH key...")

	key, err := d.createSSHKey()
	if err != nil {
		return err
	}

	d.SSHKeyID = key
	log.Debugf("Created SSH Key ID: %d", key)

	log.Infof("Creating Ubiquity instance, please wait...")

	createRequest := &goubi.CreateVMParams{
		Hostname:      d.MachineName,
		ImageID:       d.ImageID,
		FlavorID:      d.FlavorID,
		ZoneID:        d.ZoneID,
		KeyID:         d.SSHKeyID,
		DockerMachine: true,
	}

	client := d.getClient()

	instance, err := client.Cloud.Create(createRequest)
	if err != nil {
		return err
	}
	log.Debugf("Instance service ID: %d", instance.ServiceID)
	d.ServiceID = instance.ServiceID

	for {
		details, err := client.Cloud.Get(d.ServiceID)
		if err != nil {
			log.Debugf("Waiting for VM creation... (Error: %v)", err)
			time.Sleep(3 * time.Second)
			continue
		}
		log.Debug("Instance created")
		d.IPAddress = details.MainIPaddress

		if d.IPAddress != "" {
			break
		}
	}
	log.Infof("Initializing instance on IP address: %s", d.IPAddress)
	log.Debugf("Created instance ID %d, IP address %s",
		d.ServiceID,
		d.IPAddress)

	return nil
}
示例#27
0
func (d *Driver) Remove() error {
	log.Infof("%s | Remove instance %s ...", d.MachineName, d.InstanceId)

	if d.InstanceId == "" {
		return fmt.Errorf("%s | Unknown instance id", d.MachineName)
	}

	s, err := d.GetState()
	if err == nil && s == state.Running {
		if err := d.Stop(); err != nil {
			log.Errorf("%s | Unable to removed the instance %s: %s", d.MachineName, d.InstanceId, err)
		}
	}

	instance, err := d.getInstance()
	if err != nil {
		log.Errorf("%s | Unable to describe the instance %s: %s", d.MachineName, d.InstanceId, err)
	} else {
		// Check and release EIP if exists
		if len(instance.EipAddress.AllocationId) != 0 {

			allocationId := instance.EipAddress.AllocationId

			err = d.getClient().UnassociateEipAddress(allocationId, instance.InstanceId)
			if err != nil {
				log.Errorf("%s | Failed to unassociate EIP address from instance %s: %v", d.MachineName, d.InstanceId, err)
			}
			err = d.getClient().WaitForEip(instance.RegionId, allocationId, ecs.EipStatusAvailable, 0)
			if err != nil {
				log.Errorf("%s | Failed to wait EIP %s available: %v", d.MachineName, allocationId, err)
			}
			err = d.getClient().ReleaseEipAddress(allocationId)
			if err != nil {
				log.Errorf("%s | Failed to release EIP address: %v", d.MachineName, err)
			}
		}
		log.Debugf("%s | instance.VpcAttributes: %++v\n", d.MachineName, instance.VpcAttributes)

		vpcId := instance.VpcAttributes.VpcId
		if vpcId != "" {
			// Remove route entry firstly
			d.removeRouteEntry(vpcId, instance.RegionId, instance.InstanceId)
		}
	}

	log.Infof("%s | Deleting instance: %s", d.MachineName, d.InstanceId)
	if err := d.getClient().DeleteInstance(d.InstanceId); err != nil {
		return fmt.Errorf("%s | Unable to delete instance %s: %s", d.MachineName, d.InstanceId, err)
	}
	return nil
}
func (d *Driver) Create() error {
	log.Infof("Creating SSH key...")
	key, err := d.createSSHKey()
	if err != nil {
		return err
	}
	d.SSHKeyID = key.ID

	log.Infof("Creating Vscale scalet...")

	client := d.getClient()
	createRequest := &api.ScaletCreateRequest{
		MakeFrom: d.MadeFrom,
		Rplan:    d.Rplan,
		DoStart:  true,
		Name:     d.MachineName,
		Keys:     []int{d.SSHKeyID},
		Location: d.Location,
	}

	newScalet, _, err := client.Scalet.Create(createRequest)
	if err != nil {
		return err
	}

	d.ScaletID = newScalet.CTID

	log.Info("Waiting for IP address to be assigned to the Scalet...")

	for {
		newScalet, _, err = client.Scalet.GetByID(d.ScaletID)
		if err != nil {
			return err
		}

		if newScalet.PublicAddress != nil {
			d.IPAddress = newScalet.PublicAddress.Address
		}

		if d.IPAddress != "" {
			break
		}

		time.Sleep(1 * time.Second)
	}

	log.Debugf("Created scalet with ID: %v, IPAddress: %v", d.ScaletID, d.IPAddress)
	return nil
}
示例#29
0
// Wait - wait on job task to complete
func (jt *JobTask) Wait() error {
	var (
		currenttime int
	)
	log.Debugf("task : %+v", jt)
	if err := jt.GetCurrentStatus(); err != nil {
		jt.IsDone = true
		return err
	}

	for JOB_RUNNING_YES.Equal(jt.Running) && (currenttime < jt.Timeout) {
		log.Debugf("jt => %+v", jt)
		if jt.JobURI.URI.String() != "" {
			log.Debugf("Waiting for job to complete, %s ", jt.Description)
			lastjobstep := len(jt.JobProgress)
			if lastjobstep > 0 {
				statusmessage := jt.GetLastStatusUpdate()
				if statusmessage == "" {
					log.Infof("Waiting on, %s, %0.0f%%", jt.Description, jt.GetPercentProgress())
				} else {
					log.Infof("Waiting on, %s, %0.0f%%, %s", jt.Description, jt.GetPercentProgress(), statusmessage)
				}
			}
		} else {
			log.Info("Waiting on job creation.")
		}

		// wait time before next check
		time.Sleep(time.Millisecond * (1000 * jt.WaitTime)) // wait 10sec before checking the status again
		currenttime++

		// get the current status
		if err := jt.GetCurrentStatus(); err != nil {
			jt.IsDone = true
			return err
		}
	}
	if !(currenttime < jt.Timeout) {
		log.Warn("Task timed out.")
	}

	if JOB_RUNNING_NO.Equal(jt.Running) {
		log.Infof("Job, %s, completed", jt.GetComplettedStatus())
	} else {
		log.Warn("Job still running un-expected.")
	}
	jt.IsDone = true
	return nil
}
示例#30
0
func (d *Driver) Create() error {
	b2dutils := mcnutils.NewB2dUtils(d.StorePath)
	if err := b2dutils.CopyIsoToMachineDir(d.Boot2DockerURL, d.MachineName); err != nil {
		return err
	}

	log.Infof("Creating VM...")
	if err := os.MkdirAll(d.ResolveStorePath("."), 0755); err != nil {
		return err
	}

	log.Infof("Extracting vmlinuz64 and initrd.img from %s...", isoFilename)
	if err := d.extractKernelImages(); err != nil {
		return err
	}

	log.Infof("Generating %dMB disk image...", d.DiskSize)
	if err := d.generateDiskImage(d.DiskSize); err != nil {
		return err
	}

	// Fix file permission root to current user for vmnet.framework
	log.Infof("Fix file permission...")
	os.Chown(d.ResolveStorePath("."), syscall.Getuid(), syscall.Getegid())
	files, _ := ioutil.ReadDir(d.ResolveStorePath("."))
	for _, f := range files {
		log.Debugf(d.ResolveStorePath(f.Name()))
		os.Chown(d.ResolveStorePath(f.Name()), syscall.Getuid(), syscall.Getegid())
	}

	log.Infof("Generate UUID...")
	d.UUID = uuidgen()
	log.Debugf("Generated UUID: %s", d.UUID)

	log.Infof("Convert UUID to MAC address...")
	rawUUID, err := d.getMACAdress()
	if err != nil {
		return err
	}
	d.MacAddr = trimMacAddress(rawUUID)
	log.Debugf("Converted MAC address: %s", d.MacAddr)

	log.Infof("Starting %s...", d.MachineName)
	if err := d.Start(); err != nil {
		return err
	}

	// Setup NFS sharing
	if d.NFSShare {
		log.Infof("NFS share folder must be root. Please insert root password.")
		err = d.setupNFSShare()
		if err != nil {
			log.Errorf("NFS setup failed: %s", err.Error())
		}
	}

	return nil
}