示例#1
0
文件: client.go 项目: cdosso/machine
func (c *GenericClient) CreateInstance(d *Driver) (string, error) {
	serverOpts := servers.CreateOpts{
		Name:             d.MachineName,
		FlavorRef:        d.FlavorId,
		ImageRef:         d.ImageId,
		SecurityGroups:   d.SecurityGroups,
		AvailabilityZone: d.AvailabilityZone,
	}
	if d.NetworkId != "" {
		serverOpts.Networks = []servers.Network{
			{
				UUID: d.NetworkId,
			},
		}
	}

	log.Info("Creating machine...")

	server, err := servers.Create(c.Compute, keypairs.CreateOptsExt{
		serverOpts,
		d.KeyPairName,
	}).Extract()
	if err != nil {
		return "", err
	}
	return server.ID, nil
}
示例#2
0
文件: azure.go 项目: robebeye/machine
func (d *Driver) Create() error {
	if err := d.setUserSubscription(); err != nil {
		return err
	}

	log.Info("Creating Azure machine...")
	vmConfig, err := vmClient.CreateAzureVMConfiguration(d.MachineName, d.Size, d.Image, d.Location)
	if err != nil {
		return err
	}

	log.Debug("Generating certificate for Azure...")
	if err := d.generateCertForAzure(); err != nil {
		return err
	}

	log.Debug("Adding Linux provisioning...")
	vmConfig, err = vmClient.AddAzureLinuxProvisioningConfig(vmConfig, d.GetSSHUsername(), d.UserPassword, d.azureCertPath(), d.SSHPort)
	if err != nil {
		return err
	}

	log.Debug("Authorizing ports...")
	if err := d.addDockerEndpoints(vmConfig); err != nil {
		return err
	}

	log.Debug("Creating VM...")
	if err := vmClient.CreateAzureVM(vmConfig, d.MachineName, d.Location); err != nil {
		return err
	}

	return nil
}
示例#3
0
func (d *Driver) Restart() error {
	log.Info("Restarting...")

	_, err := d.getClient().Instance.RebootInstance(map[string]string{
		"InstanceId": d.InstanceId,
	})
	return err
}
示例#4
0
func (d *Driver) Stop() error {
	log.Info("Stopping...")

	_, err := d.getClient().Instance.StopInstance(map[string]string{
		"InstanceId": d.InstanceId,
	})
	return err
}
示例#5
0
文件: status.go 项目: phusl/machine
func cmdStatus(c *cli.Context) {
	host := getHost(c)
	currentState, err := host.Driver.GetState()
	if err != nil {
		log.Errorf("error getting state for host %s: %s", host.Name, err)
	}
	log.Info(currentState)
}
示例#6
0
func (d *Driver) Kill() error {
	log.Info("Killing...")

	_, err := d.getClient().Instance.StopInstance(map[string]string{
		"InstanceId": d.InstanceId,
		"ForceStop":  "true",
	})
	return err
}
示例#7
0
func (provisioner *Boot2DockerProvisioner) upgradeIso() error {
	log.Info("Stopping machine to do the upgrade...")

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

	}

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

	}

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

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

	isoFilename := ""
	switch provisioner.GetDriver().DriverName() {
	case "virtualbox":
		isoFilename = "boot2docker-virtualbox.iso"
	case "vmwarefusion", "vmwarevsphere", "vmwareworkstation":
		isoFilename = "boot2docker-vmware.iso"
	case "hyper-v":
		isoFilename = "boot2docker-hyperv.iso"
	default:
		return ErrUnknownDriver
	}

	b2dutils := utils.NewB2dUtils("", "", isoFilename)

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

	}

	// Copy the latest version of boot2docker ISO to the machine's directory
	if err := b2dutils.CopyIsoToMachineDir("", machineName); err != nil {
		return err

	}

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

	}

	return utils.WaitFor(drivers.MachineInState(provisioner.Driver, state.Running))

}
示例#8
0
文件: b2d.go 项目: cdosso/machine
func (b *B2dUtils) copyDefaultIsoToMachine(machineIsoPath string) error {
	if _, err := os.Stat(b.commonIsoPath); os.IsNotExist(err) {
		log.Info("No default boot2docker iso found locally, downloading the latest release...")
		if err := b.DownloadLatestBoot2Docker(); err != nil {
			return err
		}
	}

	if err := CopyFile(b.commonIsoPath, machineIsoPath); err != nil {
		return err
	}

	return nil
}
示例#9
0
func (d *Driver) createSSHKey() error {
	log.Info("Creating SSH Key Pair...")
	if err := ssh.GenerateSSHKey(d.GetSSHKeyPath()); err != nil {
		return err
	}
	publicKey, err := ioutil.ReadFile(d.publicSSHKeyPath())
	if err != nil {
		return err
	}
	d.PublicKey = publicKey[0 : len(publicKey)-1]
	log.Debugf("------------%s\n")
	log.Debug(string(publicKey))

	return nil
}
示例#10
0
func tokenFromWeb(config *oauth.Config) *oauth.Token {
	randState := fmt.Sprintf("st%d", time.Now().UnixNano())

	config.RedirectURL = RedirectURI
	authURL := config.AuthCodeURL(randState)

	log.Info("Opening auth URL in browser.")
	log.Info(authURL)
	log.Info("If the URL doesn't open please open it manually and copy the code here.")
	openURL(authURL)
	code := getCodeFromStdin()

	log.Infof("Got code: %s", code)

	t := &oauth.Transport{
		Config:    config,
		Transport: http.DefaultTransport,
	}
	_, err := t.Exchange(code)
	if err != nil {
		log.Fatalf("Token exchange error: %v", err)
	}
	return t.Token
}
示例#11
0
func (d *Driver) Remove() error {
	log.WithField("MachineId", d.MachineId).Debug("deleting instance...")
	log.Info("Deleting OpenStack instance...")
	if err := d.initCompute(); err != nil {
		return err
	}
	if err := d.client.DeleteInstance(d); err != nil {
		return err
	}
	log.WithField("Name", d.KeyPairName).Debug("deleting key pair...")
	if err := d.client.DeleteKeyPair(d, d.KeyPairName); err != nil {
		return err
	}
	return nil
}
示例#12
0
func (provisioner *RancherProvisioner) upgradeIso() error {
	// Largely copied from Boot2Docker provisioner, we should find a way to share this code
	log.Info("Stopping machine to do the upgrade...")

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

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

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

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

	b2dutils := utils.NewB2dUtils("", "", isoFilename)

	url, err := provisioner.getLatestISOURL()
	if err != nil {
		return err
	}

	if err := b2dutils.DownloadISOFromURL(url); err != nil {
		return err
	}

	// Copy the latest version of boot2docker ISO to the machine's directory
	if err := b2dutils.CopyIsoToMachineDir("", machineName); err != nil {
		return err
	}

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

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

	return utils.WaitFor(drivers.MachineInState(provisioner.Driver, state.Running))
}
示例#13
0
func (provisioner *Boot2DockerProvisioner) upgradeIso() error {
	log.Info("Stopping machine to do the upgrade...")

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

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

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

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

	b2dutils := utils.NewB2dUtils("", "")

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

	// Copy the latest version of boot2docker ISO to the machine's directory
	if err := b2dutils.CopyIsoToMachineDir("", machineName); err != nil {
		return err
	}

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

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

	return utils.WaitFor(drivers.MachineInState(provisioner.Driver, state.Running))
}
示例#14
0
func (d *Driver) Remove() error {
	log.Info("Deleting...")

	if d.InstanceId == "" {
		// Instance id is empty due to some errors while creating,
		log.Warn("InstanceId is empty, assuming it has already bean removed from aliyun.")
		return nil
	}

	// If instance is running, kill it
	if st, _ := d.GetState(); st == state.Running {
		err := d.Kill()
		if err != nil {
			return err
		}
	}
	// Wait for instance to stop
	utils.WaitForSpecific(d.waitToStopInstance, 10, 6*time.Second)

	_, err := d.getClient().Instance.DeleteInstance(map[string]string{
		"InstanceId": d.InstanceId,
	})
	return err
}
示例#15
0
func (d *Driver) Create() error {
	if err := d.checkPrereqs(); err != nil {
		return err
	}

	log.Infof("Launching instance...")

	if err := d.createKeyPair(); err != nil {
		return fmt.Errorf("unable to create key pair: %s", err)
	}

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

	bdm := &amz.BlockDeviceMapping{
		DeviceName:          "/dev/sda1",
		VolumeSize:          d.RootSize,
		DeleteOnTermination: true,
		VolumeType:          "gp2",
	}

	log.Debugf("launching instance in subnet %s", d.SubnetId)
	var instance amz.EC2Instance
	if d.RequestSpotInstance {
		spotInstanceRequestId, err := d.getClient().RequestSpotInstances(d.AMI, d.InstanceType, d.Zone, 1, d.SecurityGroupId, d.KeyName, d.SubnetId, bdm, d.IamInstanceProfile, d.SpotPrice, d.Monitoring)
		if err != nil {
			return fmt.Errorf("Error request spot instance: %s", err)
		}
		var instanceId string
		var spotInstanceRequestStatus string
		log.Info("Waiting for spot instance...")
		// check until fulfilled
		for instanceId == "" {
			time.Sleep(time.Second * 5)
			spotInstanceRequestStatus, instanceId, err = d.getClient().DescribeSpotInstanceRequests(spotInstanceRequestId)
			if err != nil {
				return fmt.Errorf("Error describe spot instance request: %s", err)
			}
			log.Debugf("spot instance request status: %s", spotInstanceRequestStatus)
		}
		instance, err = d.getClient().GetInstance(instanceId)
		if err != nil {
			return fmt.Errorf("Error get instance: %s", err)
		}
	} else {
		inst, err := d.getClient().RunInstance(d.AMI, d.InstanceType, d.Zone, 1, 1, d.SecurityGroupId, d.KeyName, d.SubnetId, bdm, d.IamInstanceProfile, d.PrivateIPOnly, d.Monitoring)
		if err != nil {
			return fmt.Errorf("Error launching instance: %s", err)
		}
		instance = inst
	}

	d.InstanceId = instance.InstanceId

	log.Debug("waiting for ip address to become available")
	if err := utils.WaitFor(d.instanceIpAvailable); err != nil {
		return err
	}

	if len(instance.NetworkInterfaceSet) > 0 {
		d.PrivateIPAddress = instance.NetworkInterfaceSet[0].PrivateIpAddress
	}

	d.waitForInstance()

	log.Debugf("created instance ID %s, IP address %s, Private IP address %s",
		d.InstanceId,
		d.IPAddress,
		d.PrivateIPAddress,
	)

	log.Debug("Settings tags for instance")
	tags := map[string]string{
		"Name": d.MachineName,
	}

	if err := d.getClient().CreateTags(d.InstanceId, tags); err != nil {
		return err
	}

	return nil
}
示例#16
0
文件: restart.go 项目: phusl/machine
func cmdRestart(c *cli.Context) {
	if err := runActionWithContext("restart", c); err != nil {
		log.Fatal(err)
	}
	log.Info("Restarted machines may have new IP addresses. You may need to re-run the `docker-machine env` command.")
}
示例#17
0
func (d *Driver) Create() error {
	// Create SSH key
	log.Debugf("Creating ssh key --- \n")
	if err := d.createSSHKey(); err != nil {
		return err
	}

	return nil

	// Create instance
	log.Info("Creating ECS instance...")
	createResp, err := d.getClient().Instance.CreateInstance(map[string]string{
		"RegionId":                d.RegionId,
		"SecurityGroupId":         d.SecurityGroupId,
		"ImageId":                 d.ImageId,
		"InstanceType":            d.InstanceTypeId,
		"InstanceName":            d.MachineName,
		"InternetMaxBandwidthOut": d.BandwidthOut,
		"Password":                d.SSHPass,
	})
	if err != nil {
		return err
	}
	d.InstanceId = createResp.InstanceId

	// Allocate public ip address
	log.Info("Allocating public IP address...")
	ipResp, err := d.getClient().Network.AllocatePublicIpAddress(map[string]string{
		"InstanceId": d.InstanceId,
	})
	if err != nil {
		return nil
	}
	d.IPAddress = ipResp.IpAddress

	// Start instance
	log.Info("Starting instance, this may take several minutes...")
	_, err = d.getClient().Instance.StartInstance(map[string]string{
		"InstanceId": d.InstanceId,
	})
	if err != nil {
		return err
	}

	// Get private IP address
	statusResp, err := d.getClient().Instance.DescribeInstanceAttribute(map[string]string{
		"InstanceId": d.InstanceId,
	})
	if err != nil {
		return err
	}
	if ips := statusResp.InnerIpAddress.AllIpAddress; len(ips) > 0 {
		d.PrivateIPAddress = ips[0]
	}

	// Wait for instance to start
	if err := utils.WaitFor(d.waitToStartInstance); err != nil {
		return err
	}

	//TODO 暂时处理:等待20秒,主机真正启动
	time.Sleep(20 * time.Second)

	// Wait for ssh available
	port, e := d.GetSSHPort()
	if e != nil {
		return e
	}
	ip, e := d.GetIP()
	if e != nil {
		return e
	}
	if err := ssh.WaitForTCP(fmt.Sprintf("%s:%d", ip, port)); err != nil {
		return err
	}

	// Upload SSH key to host
	log.Info("Upload SSH key to machine...")
	if err := d.uploadKeyPair(); err != nil {
		return err
	}

	log.Infof("Created Instance ID %s, Public IP address %s, Private IP address %s",
		d.InstanceId,
		d.IPAddress,
		d.PrivateIPAddress,
	)

	return nil
}
示例#18
0
func (d *Driver) Create() error {
	if err := d.checkPrereqs(); err != nil {
		return err
	}
	log.Infof("Creating key pair for instances...")

	if err := d.createKeyPair(); err != nil {
		return fmt.Errorf("unable to create key pair: %s", err)
	}

	log.Infof("Configuring security groups...")
	if err := d.configureSecurityGroup(d.SecurityGroupName); err != nil {
		return err
	}

	// TODO Support data disk

	if d.SSHPassword == "" {
		d.SSHPassword = randomPassword()
		log.Info("Launching instance with generated password, please update password in console or log in with ssh key.")
	}

	imageID := d.GetImageID(d.ImageID)
	log.Infof("Launching instance with image %s ...", imageID)

	args := ecs.CreateInstanceArgs{
		RegionId:        d.Region,
		ImageId:         imageID,
		InstanceType:    d.InstanceType,
		SecurityGroupId: d.SecurityGroupId,
		Password:        d.SSHPassword,
		VSwitchId:       d.VSwitchId,
		ClientToken:     d.getClient().GenerateClientToken(),
	}

	// Set InternetMaxBandwidthOut only for classic network
	if d.VSwitchId == "" {
		args.InternetMaxBandwidthOut = d.InternetMaxBandwidthOut
	}

	//log.Debugf("CreateInstanceArgs: %++v", args)

	// Create instance
	instanceId, err := d.getClient().CreateInstance(&args)

	if err != nil {
		err = fmt.Errorf("Error create instance: %s", err)
		log.Error(err)
		return err
	}

	d.InstanceId = instanceId

	// Wait for creation successfully
	err = d.getClient().WaitForInstance(instanceId, ecs.Stopped, 300)

	if err != nil {
		err = fmt.Errorf("Error wait instance to Stopped: %s", err)
		log.Error(err)
	}

	// Assign public IP if not private IP only
	if err == nil && !d.PrivateIPOnly {
		if d.VSwitchId == "" {
			// Allocate public IP address for classic network
			_, err = d.getClient().AllocatePublicIpAddress(instanceId)
			if err != nil {
				err = fmt.Errorf("Error allocate public IP address for instance %s: %v", instanceId, err)
			}
		} else {
			err = d.configNetwork(instanceId)
		}
	}

	if err == nil {
		// Start instance
		err = d.getClient().StartInstance(instanceId)
		if err == nil {
			// Wait for running
			err = d.getClient().WaitForInstance(instanceId, ecs.Running, 300)
			if err == nil {
				instance, err := d.getInstance()

				if err == nil {
					if len(instance.InnerIpAddress.IpAddress) > 0 {
						d.PrivateIPAddress = instance.InnerIpAddress.IpAddress[0]
					}

					d.IPAddress = d.getIP(instance)

					ssh.SetDefaultClient(ssh.Native)

					d.uploadKeyPair()

					log.Debugf("created instance ID %s, IP address %s, Private IP address %s",
						d.InstanceId,
						d.IPAddress,
						d.PrivateIPAddress,
					)
				}
			} else {
				err = fmt.Errorf("Failed to wait instance to running state: %s", err)
			}
		} else {
			err = fmt.Errorf("Failed to start instance %s: %v", instanceId, err)
		}
	}

	if err != nil {
		log.Warn(err)
		d.Remove()
	}

	return err
}