func (d *Driver) extractKernelImages() error {
	log.Debugf("Mounting %s", isoFilename)

	err := hdiutil("attach", d.ResolveStorePath(isoFilename), "-mountpoint", d.ResolveStorePath("b2d-image"))
	if err != nil {
		return err
	}

	volumeRootDir := d.ResolveStorePath(isoMountPath)
	vmlinuz64 := volumeRootDir + "/boot/vmlinuz64"
	initrd := volumeRootDir + "/boot/initrd.img"

	log.Debugf("Extracting vmlinuz64 into %s", d.ResolveStorePath("."))
	if err := mcnutils.CopyFile(vmlinuz64, d.ResolveStorePath("vmlinuz64")); err != nil {
		return err
	}
	log.Debugf("Extracting initrd.img into %s", d.ResolveStorePath("."))
	if err := mcnutils.CopyFile(initrd, d.ResolveStorePath("initrd.img")); err != nil {
		return err
	}
	log.Debugf("Unmounting %s", isoFilename)
	if err := hdiutil("detach", volumeRootDir); err != nil {
		return err
	}

	return nil
}
Пример #2
0
func (d *Driver) extractKernelImages() error {
	log.Debugf("Mounting %s", isoFilename)

	volumeRootDir := d.ResolveStorePath(isoMountPath)
	err := hdiutil("attach", d.ResolveStorePath(isoFilename), "-mountpoint", volumeRootDir)
	if err != nil {
		return err
	}

	log.Debugf("Extracting Kernel Options...")
	if err := d.extractKernelOptions(); err != nil {
		return err
	}

	defer func() error {
		log.Debugf("Unmounting %s", isoFilename)
		return hdiutil("detach", volumeRootDir)
	}()

	if d.BootKernel == "" && d.BootInitrd == "" {
		err = filepath.Walk(volumeRootDir, func(path string, f os.FileInfo, err error) error {
			if kernelRegexp.MatchString(path) {
				d.BootKernel = path
				_, d.Vmlinuz = filepath.Split(path)
			}
			if strings.Contains(path, "initrd") {
				d.BootInitrd = path
				_, d.Initrd = filepath.Split(path)
			}
			return nil
		})
	}

	if err != nil {
		if err != nil || d.BootKernel == "" || d.BootInitrd == "" {
			err = fmt.Errorf("==== Can't extract Kernel and Ramdisk file ====")
			return err
		}
	}

	dest := d.ResolveStorePath(d.Vmlinuz)
	log.Debugf("Extracting %s into %s", d.BootKernel, dest)
	if err := mcnutils.CopyFile(d.BootKernel, dest); err != nil {
		return err
	}

	dest = d.ResolveStorePath(d.Initrd)
	log.Debugf("Extracting %s into %s", d.BootInitrd, dest)
	if err := mcnutils.CopyFile(d.BootInitrd, dest); err != nil {
		return err
	}

	return nil
}
Пример #3
0
func NewDockerMachine(config DockerMachineConfig) (DockerMachineAPI, error) {
	storePath := config.StorePath
	temp := false
	if storePath == "" {
		tempPath, err := ioutil.TempDir("", "")
		if err != nil {
			return nil, errors.Wrap(err, "failed to create temp dir")
		}
		storePath = tempPath
		temp = true
	}
	certsPath := filepath.Join(storePath, "certs")
	if _, err := os.Stat(certsPath); os.IsNotExist(err) {
		err := os.MkdirAll(certsPath, 0700)
		if err != nil {
			return nil, errors.WithMessage(err, "failed to create certs dir")
		}
	}
	if config.CaPath != "" {
		err := mcnutils.CopyFile(filepath.Join(config.CaPath, "ca.pem"), filepath.Join(certsPath, "ca.pem"))
		if err != nil {
			return nil, errors.Wrap(err, "failed to copy ca file")
		}
		err = mcnutils.CopyFile(filepath.Join(config.CaPath, "ca-key.pem"), filepath.Join(certsPath, "ca-key.pem"))
		if err != nil {
			return nil, errors.Wrap(err, "failed to copy ca key file")
		}
	}
	if config.OutWriter != nil {
		log.SetOutWriter(config.OutWriter)
	} else {
		log.SetOutWriter(ioutil.Discard)
	}
	if config.ErrWriter != nil {
		log.SetOutWriter(config.ErrWriter)
	} else {
		log.SetOutWriter(ioutil.Discard)
	}
	log.SetDebug(config.IsDebug)
	client := libmachine.NewClient(storePath, certsPath)
	client.IsDebug = config.IsDebug
	if _, err := os.Stat(client.GetMachinesDir()); os.IsNotExist(err) {
		err := os.MkdirAll(client.GetMachinesDir(), 0700)
		if err != nil {
			return nil, errors.WithMessage(err, "failed to create machines dir")
		}
	}
	return &DockerMachine{
		StorePath: storePath,
		CertsPath: certsPath,
		client:    client,
		temp:      temp,
	}, nil
}
func (d *Driver) extractKernelImages() error {
	log.Debugf("Mounting %s", isoFilename)
	if err := hdiutil("attach", d.ResolveStorePath(isoFilename)); err != nil {
		return err
	}

	log.Debugf("Getting Boot2docker version ...")
	iso, err := os.Open("/Volumes")
	if err != nil {
		return err
	}
	defer iso.Close()

	// TODO: More faster parse
	l, _ := ioutil.ReadDir(iso.Name())
	s := make([]string, 0, 100)
	for _, f := range l {
		re := regexp.MustCompile(`(.*)-(.*)`)
		re2 := regexp.MustCompile(`(^v.*)`)
		s = re.FindStringSubmatch(f.Name())
		for _, v := range s {
			if re2.MatchString(v) {
				d.Boot2DockerIsoVersion = v
				break
			}
		}
	}
	log.Debugf("Boot2docker version: %s", d.Boot2DockerIsoVersion)

	volumeRootDir := "/Volumes/Boot2Docker-" + d.Boot2DockerIsoVersion
	vmlinuz64 := volumeRootDir + "/boot/vmlinuz64"
	initrd := volumeRootDir + "/boot/initrd.img"

	log.Debugf("Extracting vmlinuz64 into %s", d.ResolveStorePath("."))
	if err := mcnutils.CopyFile(vmlinuz64, d.ResolveStorePath("vmlinuz64")); err != nil {
		return err
	}
	log.Debugf("Extracting initrd.img into %s", d.ResolveStorePath("."))
	if err := mcnutils.CopyFile(initrd, d.ResolveStorePath("initrd.img")); err != nil {
		return err
	}
	log.Debugf("Unmounting %s", isoFilename)
	if err := hdiutil("detach", volumeRootDir); err != nil {
		return err
	}

	return nil
}
Пример #5
0
func (d *Driver) extractKernelImages() error {
	var vmlinuz64 = "/Volumes/Boot2Docker-v1.8/boot/vmlinuz64"
	var initrd = "/Volumes/Boot2Docker-v1.8/boot/initrd.img"

	hdiutil("attach", d.ISO)
	log.Debugf("Mounting %s", isoFilename)

	log.Debugf("Extract vmlinuz64")
	if err := mcnutils.CopyFile(vmlinuz64, filepath.Join(d.LocalArtifactPath("."), "vmlinuz64")); err != nil {
		return err
	}
	log.Debugf("Extract initrd.img")
	if err := mcnutils.CopyFile(initrd, filepath.Join(d.LocalArtifactPath("."), "initrd.img")); err != nil {
		return err
	}

	return nil
}
Пример #6
0
// Create a host using the driver's config
func (d *Driver) Create() error {
	log.Infof("Importing SSH key...")

	if err := mcnutils.CopyFile(d.SSHKey, d.GetSSHKeyPath()); err != nil {
		return fmt.Errorf("unable to copy public ssh key: %s", err)
	}

	if err := os.Chmod(d.GetSSHKeyPath(), 0600); err != nil {
		return err
	}

	if err := mcnutils.CopyFile(fmt.Sprintf("%s.pub", d.SSHKey), d.publicSSHKeyPath()); err != nil {
		return fmt.Errorf("unable to copy public ssh key: %s", err)
	}

	log.Debugf("IP: %s", d.IPAddress)

	return nil
}
Пример #7
0
func (d *Driver) createKeyPair() error {
	keyPath := ""

	if d.SSHPrivateKeyPath == "" {
		log.Debugf("Creating New SSH Key")
		if err := ssh.GenerateSSHKey(d.GetSSHKeyPath()); err != nil {
			return err
		}
		keyPath = d.GetSSHKeyPath()
	} else {
		log.Debugf("Using SSHPrivateKeyPath: %s", d.SSHPrivateKeyPath)
		if err := mcnutils.CopyFile(d.SSHPrivateKeyPath, d.GetSSHKeyPath()); err != nil {
			return err
		}
		if err := mcnutils.CopyFile(d.SSHPrivateKeyPath+".pub", d.GetSSHKeyPath()+".pub"); err != nil {
			return err
		}
		if d.KeyName != "" {
			log.Debugf("Using existing EC2 key pair: %s", d.KeyName)
			return nil
		}
		keyPath = d.SSHPrivateKeyPath
	}

	publicKey, err := ioutil.ReadFile(keyPath + ".pub")
	if err != nil {
		return err
	}

	keyName := d.MachineName

	log.Debugf("creating key pair: %s", keyName)
	_, err = d.getClient().ImportKeyPair(&ec2.ImportKeyPairInput{
		KeyName:           &keyName,
		PublicKeyMaterial: publicKey,
	})
	if err != nil {
		return err
	}
	d.KeyName = keyName
	return nil
}
Пример #8
0
func copySSHKey(src, dst string) error {
	if err := mcnutils.CopyFile(src, dst); err != nil {
		return fmt.Errorf("unable to copy ssh key: %s", err)
	}

	if err := os.Chmod(dst, 0600); err != nil {
		return fmt.Errorf("unable to set permissions on the ssh key: %s", err)
	}

	return nil
}
Пример #9
0
func (d *Driver) extractKernelImages() error {
	var vmlinuz64 = "/Volumes/Boot2Docker-v1.8/boot/vmlinuz64" // TODO Do not hardcode boot2docker version
	var initrd = "/Volumes/Boot2Docker-v1.8/boot/initrd.img"   // TODO Do not hardcode boot2docker version

	log.Debugf("Mounting %s", isoFilename)
	hdiutil("attach", d.ResolveStorePath(isoFilename)) // TODO need parse attached disk identifier.

	log.Debugf("Extract vmlinuz64")
	if err := mcnutils.CopyFile(vmlinuz64, d.ResolveStorePath("vmlinuz64")); err != nil {
		return err
	}
	log.Debugf("Extract initrd.img")
	if err := mcnutils.CopyFile(initrd, d.ResolveStorePath("initrd.img")); err != nil {
		return err
	}
	log.Debugf("Unmounting %s", isoFilename)
	if err := hdiutil("detach", "/Volumes/Boot2Docker-v1.8/"); err != nil { // TODO Do not hardcode boot2docker version
		return err
	}

	return nil
}
Пример #10
0
func (d *Driver) Create() error {
	log.Info("Importing SSH key...")

	// TODO: validate the key is a valid key
	if err := mcnutils.CopyFile(d.SSHKey, d.GetSSHKeyPath()); err != nil {
		return fmt.Errorf("unable to copy ssh key: %s", err)
	}

	if err := os.Chmod(d.GetSSHKeyPath(), 0600); err != nil {
		return fmt.Errorf("unable to set permissions on the ssh key: %s", err)
	}

	log.Debugf("IP: %s", d.IPAddress)

	return nil
}
func (d *Driver) Create() error {

	log.Debugf("Creating a new Instance for Stack: %s", d.MachineName)

	if d.SSHKeyPath != "" {
		log.Debugf("Copying Key to Machine Directory: %s", d.GetSSHKeyPath)

		if err := mcnutils.CopyFile(d.SSHPrivateKeyPath, d.GetSSHKeyPath()); err != nil {
			return err
		}
	}

	svc := cloudformation.New(session.New())

	params := &cloudformation.CreateStackInput{
		StackName:   aws.String(d.MachineName),
		TemplateURL: aws.String(d.CloudFormationURL),
		Parameters:  d.createParams(),
		Tags:        d.createTags(),
	}
	_, err := svc.CreateStack(params)

	if err != nil {
		return err
	}

	if err := mcnutils.WaitForSpecificOrError(d.stackAvailable, 120, 3*time.Second); err != nil {
		return err
	}

	if err := d.getInstanceInfo(); err != nil {
		return err
	}
	if err := waitFor(sshAvailableFunc(d)); err != nil {
		return fmt.Errorf("Too many retries waiting for SSH to be available.  Last error: %s", err)
	}

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

	return nil
}
Пример #12
0
func (d *Driver) Create() error {
	if d.SSHKey == "" {
		log.Info("No SSH key specified. Assuming an existing key at the default location.")
	} else {
		log.Info("Importing SSH key...")
		// TODO: validate the key is a valid key
		if err := mcnutils.CopyFile(d.SSHKey, d.GetSSHKeyPath()); err != nil {
			return fmt.Errorf("unable to copy ssh key: %s", err)
		}

		if err := os.Chmod(d.GetSSHKeyPath(), 0600); err != nil {
			return fmt.Errorf("unable to set permissions on the ssh key: %s", err)
		}
	}

	log.Debugf("IP: %s", d.IPAddress)

	return nil
}
Пример #13
0
func (d *Driver) Create() error {
	if d.SSHKey == "" {
		log.Info("No SSH key specified. Connecting to this machine now and in the" +
			" future will require the ssh agent to contain the appropriate key.")
	} else {
		log.Info("Importing SSH key...")
		// TODO: validate the key is a valid key
		if err := mcnutils.CopyFile(d.SSHKey, d.GetSSHKeyPath()); err != nil {
			return fmt.Errorf("unable to copy ssh key: %s", err)
		}

		if err := os.Chmod(d.GetSSHKeyPath(), 0600); err != nil {
			return fmt.Errorf("unable to set permissions on the ssh key: %s", err)
		}
	}

	log.Debugf("IP: %s", d.IPAddress)

	return nil
}
Пример #14
0
func (d *Driver) Create() error {
	b2dutils := mcnutils.NewB2dUtils(d.StorePath)
	if err := b2dutils.CopyIsoToMachineDir(d.Boot2DockerURL, d.MachineName); err != nil {
		return err
	}

	if d.IsVTXDisabled() {
		// Let's log a warning to warn the user. When the vm is started, logs
		// will be checked for an error anyway.
		// We could fail right here but the method to check didn't prove being
		// bulletproof.
		log.Warn("This computer doesn't have VT-X/AMD-v enabled. Enabling it in the BIOS is mandatory.")
	}

	log.Infof("Creating VirtualBox VM...")

	// import b2d VM if requested
	if d.Boot2DockerImportVM != "" {
		name := d.Boot2DockerImportVM

		// make sure vm is stopped
		_ = d.vbm("controlvm", name, "poweroff")

		diskInfo, err := d.getVMDiskInfo(name)
		if err != nil {
			return err
		}

		if _, err := os.Stat(diskInfo.Path); err != nil {
			return err
		}

		if err := d.vbm("clonehd", diskInfo.Path, d.diskPath()); err != nil {
			return err
		}

		log.Debugf("Importing VM settings...")
		vmInfo, err := d.getVMInfo(name)
		if err != nil {
			return err
		}

		d.CPU = vmInfo.CPUs
		d.Memory = vmInfo.Memory

		log.Debugf("Importing SSH key...")
		keyPath := filepath.Join(mcnutils.GetHomeDir(), ".ssh", "id_boot2docker")
		if err := mcnutils.CopyFile(keyPath, d.GetSSHKeyPath()); err != nil {
			return err
		}
	} else {
		log.Infof("Creating SSH key...")
		if err := ssh.GenerateSSHKey(d.GetSSHKeyPath()); err != nil {
			return err
		}

		log.Debugf("Creating disk image...")
		if err := d.generateDiskImage(d.DiskSize); err != nil {
			return err
		}
	}

	if err := d.vbm("createvm",
		"--basefolder", d.ResolveStorePath("."),
		"--name", d.MachineName,
		"--register"); err != nil {
		return err
	}

	log.Debugf("VM CPUS: %d", d.CPU)
	log.Debugf("VM Memory: %d", d.Memory)

	cpus := d.CPU
	if cpus < 1 {
		cpus = int(runtime.NumCPU())
	}
	if cpus > 32 {
		cpus = 32
	}

	if err := d.vbm("modifyvm", d.MachineName,
		"--firmware", "bios",
		"--bioslogofadein", "off",
		"--bioslogofadeout", "off",
		"--bioslogodisplaytime", "0",
		"--biosbootmenu", "disabled",
		"--ostype", "Linux26_64",
		"--cpus", fmt.Sprintf("%d", cpus),
		"--memory", fmt.Sprintf("%d", d.Memory),
		"--acpi", "on",
		"--ioapic", "on",
		"--rtcuseutc", "on",
		"--natdnshostresolver1", "off",
		"--natdnsproxy1", "off",
		"--cpuhotplug", "off",
		"--pae", "on",
		"--hpet", "on",
		"--hwvirtex", "on",
		"--nestedpaging", "on",
		"--largepages", "on",
		"--vtxvpid", "on",
		"--accelerate3d", "off",
		"--boot1", "dvd"); err != nil {
		return err
	}

	if err := d.vbm("modifyvm", d.MachineName,
		"--nic1", "nat",
		"--nictype1", "82540EM",
		"--cableconnected1", "on"); err != nil {
		return err
	}

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

	if err := d.vbm("storagectl", d.MachineName,
		"--name", "SATA",
		"--add", "sata",
		"--hostiocache", "on"); err != nil {
		return err
	}

	if err := d.vbm("storageattach", d.MachineName,
		"--storagectl", "SATA",
		"--port", "0",
		"--device", "0",
		"--type", "dvddrive",
		"--medium", d.ResolveStorePath("boot2docker.iso")); err != nil {
		return err
	}

	if err := d.vbm("storageattach", d.MachineName,
		"--storagectl", "SATA",
		"--port", "1",
		"--device", "0",
		"--type", "hdd",
		"--medium", d.diskPath()); err != nil {
		return err
	}

	// let VBoxService do nice magic automounting (when it's used)
	if err := d.vbm("guestproperty", "set", d.MachineName, "/VirtualBox/GuestAdd/SharedFolders/MountPrefix", "/"); err != nil {
		return err
	}
	if err := d.vbm("guestproperty", "set", d.MachineName, "/VirtualBox/GuestAdd/SharedFolders/MountDir", "/"); err != nil {
		return err
	}

	var shareName, shareDir string // TODO configurable at some point
	switch runtime.GOOS {
	case "windows":
		shareName = "c/Users"
		shareDir = "c:\\Users"
	case "darwin":
		shareName = "Users"
		shareDir = "/Users"
		// TODO "linux"
	}

	if shareDir != "" && !d.NoShare {
		log.Debugf("setting up shareDir")
		if _, err := os.Stat(shareDir); err != nil && !os.IsNotExist(err) {
			return err
		} else if !os.IsNotExist(err) {
			if shareName == "" {
				// parts of the VBox internal code are buggy with share names that start with "/"
				shareName = strings.TrimLeft(shareDir, "/")
				// TODO do some basic Windows -> MSYS path conversion
				// ie, s!^([a-z]+):[/\\]+!\1/!; s!\\!/!g
			}

			// woo, shareDir exists!  let's carry on!
			if err := d.vbm("sharedfolder", "add", d.MachineName, "--name", shareName, "--hostpath", shareDir, "--automount"); err != nil {
				return err
			}

			// enable symlinks
			if err := d.vbm("setextradata", d.MachineName, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/"+shareName, "1"); err != nil {
				return err
			}
		}
	}

	log.Infof("Starting VirtualBox VM...")

	return d.Start()
}
// Create create server on sakuracloud
func (d *Driver) Create() error {
	spec := d.buildSakuraServerSpec()

	var publicKey = ""
	if d.SSHKey == "" {
		log.Infof("Creating SSH public key...")
		pKey, err := d.createSSHKey()
		if err != nil {
			return err
		}
		publicKey = pKey
	} else {
		log.Info("Importing SSH key...")
		if err := mcnutils.CopyFile(d.SSHKey, d.GetSSHKeyPath()); err != nil {
			return fmt.Errorf("unable to copy ssh key: %s", err)
		}
		if err := os.Chmod(d.GetSSHKeyPath(), 0600); err != nil {
			return fmt.Errorf("unable to set permissions on the ssh key: %s", err)
		}
		if err := mcnutils.CopyFile(d.SSHKey+".pub", d.GetSSHKeyPath()+".pub"); err != nil {
			return fmt.Errorf("unable to copy ssh key: %s", err)
		}

		pKey, err := ioutil.ReadFile(d.publicSSHKeyPath())
		if err != nil {
			return err
		}

		publicKey = string(pKey)
	}

	if d.serverConfig.Password == "" {
		d.serverConfig.Password = generateRandomPassword()
		log.Infof("password is not set, generated password:%s", d.serverConfig.Password)
	}

	//create server
	serverResponse, err := d.getClient().Create(spec, d.serverConfig.PrivateIP)
	if err != nil {
		return fmt.Errorf("Error creating host: %v", err)
	}
	id := serverResponse.ID
	log.Infof("Created Server ID: %s", id)
	d.ID = id

	var noteIDs []string

	noteID, err := d.getClient().GetAllowSudoNoteID(id)
	if err != nil || noteID == "" {
		return fmt.Errorf("Error creating custom note: %v", err)
	}
	noteIDs = append(noteIDs, noteID)

	var addIPNoteID = ""
	if d.serverConfig.PrivateIP != "" {
		var err error
		addIPNoteID, err = d.getClient().GetAddIPCustomizeNoteID(id, d.serverConfig.PrivateIP, d.serverConfig.PrivateIPSubnetMask)
		if err != nil {
			return fmt.Errorf("Error creating custom note: %v", err)
		}

		if addIPNoteID != "" {
			noteIDs = append(noteIDs, addIPNoteID)
		}
	}

	var changeGatewayNoteID = ""
	if d.serverConfig.Gateway != "" {
		var err error
		changeGatewayNoteID, err = d.getClient().GetChangeGatewayCustomizeNoteID(id, d.serverConfig.Gateway)
		if err != nil {
			return fmt.Errorf("Error creating custom note: %v", err)
		}

		if changeGatewayNoteID != "" {
			noteIDs = append(noteIDs, changeGatewayNoteID)
		}

	}

	var disableEth0NoteID = ""
	if d.serverConfig.PrivateIPOnly {
		var err error
		disableEth0NoteID, err = d.getClient().GetDisableEth0CustomizeNoteID(id)
		if err != nil {
			return fmt.Errorf("Error creating custom note: %v", err)
		}

		if disableEth0NoteID != "" {
			noteIDs = append(noteIDs, disableEth0NoteID)
		}

	}

	// create disk( from public archive 'Ubuntu')
	diskSpec := d.buildSakuraDiskSpec()
	diskID, err := d.getClient().CreateDisk(diskSpec)
	if err != nil {
		return fmt.Errorf("Error creating disk: %v", err)
	}
	log.Infof("Created Disk ID: %v", diskID)
	d.DiskID = diskID

	//wait for disk available
	d.waitForDiskAvailable()

	//connect disk for server
	connectSuccess, err := d.getClient().ConnectDisk(diskID, id)
	if err != nil || !connectSuccess {
		return fmt.Errorf("Error connecting disk to server: %v", err)
	}

	//edit disk
	editDiskSpec := d.buildSakuraDiskEditSpec(publicKey, noteIDs[:])
	editSuccess, err := d.getClient().EditDisk(diskID, editDiskSpec)
	if err != nil || !editSuccess {
		return fmt.Errorf("Error editting disk: %v", err)
	}
	log.Infof("Editted Disk Id: %v", diskID)
	d.waitForDiskAvailable()

	//connect packet filter
	if d.serverConfig.PacketFilter != "" {
		log.Infof("Connecting Packet Filter(shared): %v", d.serverConfig.PacketFilter)
		err := d.getClient().ConnectPacketFilterToSharedNIC(serverResponse, d.serverConfig.PacketFilter)
		if err != nil {
			return fmt.Errorf("Error connecting PacketFilter(shared): %v", err)
		}
	}

	if d.serverConfig.PrivatePacketFilter != "" {
		log.Infof("Connecting Packet Filter(private): %v", d.serverConfig.PrivatePacketFilter)
		err := d.getClient().ConnectPacketFilterToPrivateNIC(serverResponse, d.serverConfig.PrivatePacketFilter)
		if err != nil {
			return fmt.Errorf("Error connecting PacketFilter(prvate): %v", err)
		}

	}

	if d.DNSZone != "" {
		log.Infof("Setting SakuraCloud DNS: %v", d.DNSZone)
		ip, _ := d.GetIP()
		ns, err := d.getClient().SetupDnsRecord(d.DNSZone, d.GetMachineName(), ip)
		if err != nil {
			return fmt.Errorf("Error setting SakuraCloud DNS: %v", err)
		}

		if ns != nil {
			log.Infof("Added DNS Zone,Please Set Whois NameServer to [%s]", strings.Join(ns, ","))
		}

	}

	if d.GSLB != "" {
		log.Infof("Setting SakuraCloud GSLB: %v", d.GSLB)
		ip, _ := d.GetIP()
		fqdn, err := d.getClient().SetupGslbRecord(d.GSLB, ip)
		if err != nil {
			return fmt.Errorf("Error setting SakuraCloud GSLV: %v", err)
		}

		if fqdn != nil {
			log.Infof("Added GSLB,Please Set CNAME Record : ex. 'your-lb-hostname IN CNAME %s'", fqdn)
		}
	}

	//start
	err = d.getClient().PowerOn(id)
	if err != nil {
		return fmt.Errorf("Error starting server: %v", err)
	}
	//wait for startup
	d.waitForServerByState(state.Running)

	// wait for reboot (only upgradeKernel option is true)
	//if d.serverConfig.UpgradeKernel {
	//wait for applay startup script and shutdown
	d.waitForServerByState(state.Stopped)

	//restart
	err = d.getClient().PowerOn(id)
	if err != nil {
		return fmt.Errorf("Error starting server: %v", err)
	}
	//wait for startup
	d.waitForServerByState(state.Running)
	//}

	//cleanup notes
	for n := range noteIDs {
		err = d.getClient().DeleteNote(noteIDs[n])
		if err != nil {
			return fmt.Errorf("Error deleting note: %v", err)
		}

	}

	return nil
}
Пример #16
0
func (d *Driver) CreateVM() error {
	if err := d.b2dUpdater.CopyIsoToMachineDir(d.StorePath, d.MachineName, d.Boot2DockerURL); err != nil {
		return err
	}

	log.Info("Creating VirtualBox VM...")

	// import b2d VM if requested
	if d.Boot2DockerImportVM != "" {
		name := d.Boot2DockerImportVM

		// make sure vm is stopped
		_ = d.vbm("controlvm", name, "poweroff")

		diskInfo, err := getVMDiskInfo(name, d.VBoxManager)
		if err != nil {
			return err
		}

		if _, err := os.Stat(diskInfo.Path); err != nil {
			return err
		}

		if err := d.vbm("clonehd", diskInfo.Path, d.diskPath()); err != nil {
			return err
		}

		log.Debugf("Importing VM settings...")
		vmInfo, err := getVMInfo(name, d.VBoxManager)
		if err != nil {
			return err
		}

		d.CPU = vmInfo.CPUs
		d.Memory = vmInfo.Memory

		log.Debugf("Importing SSH key...")
		keyPath := filepath.Join(mcnutils.GetHomeDir(), ".ssh", "id_boot2docker")
		if err := mcnutils.CopyFile(keyPath, d.GetSSHKeyPath()); err != nil {
			return err
		}
	} else {
		log.Infof("Creating SSH key...")
		if err := d.sshKeyGenerator.Generate(d.GetSSHKeyPath()); err != nil {
			return err
		}

		log.Debugf("Creating disk image...")
		if err := d.diskCreator.Create(d.DiskSize, d.publicSSHKeyPath(), d.diskPath()); err != nil {
			return err
		}
	}

	if err := d.vbm("createvm",
		"--basefolder", d.ResolveStorePath("."),
		"--name", d.MachineName,
		"--register"); err != nil {
		return err
	}

	log.Debugf("VM CPUS: %d", d.CPU)
	log.Debugf("VM Memory: %d", d.Memory)

	cpus := d.CPU
	if cpus < 1 {
		cpus = int(runtime.NumCPU())
	}
	if cpus > 32 {
		cpus = 32
	}

	hostDNSResolver := "off"
	if d.HostDNSResolver {
		hostDNSResolver = "on"
	}

	dnsProxy := "off"
	if d.DNSProxy {
		dnsProxy = "on"
	}

	if err := d.vbm("modifyvm", d.MachineName,
		"--firmware", "bios",
		"--bioslogofadein", "off",
		"--bioslogofadeout", "off",
		"--bioslogodisplaytime", "0",
		"--biosbootmenu", "disabled",
		"--ostype", "Linux26_64",
		"--cpus", fmt.Sprintf("%d", cpus),
		"--memory", fmt.Sprintf("%d", d.Memory),
		"--acpi", "on",
		"--ioapic", "on",
		"--rtcuseutc", "on",
		"--natdnshostresolver1", hostDNSResolver,
		"--natdnsproxy1", dnsProxy,
		"--cpuhotplug", "off",
		"--pae", "on",
		"--hpet", "on",
		"--hwvirtex", "on",
		"--nestedpaging", "on",
		"--largepages", "on",
		"--vtxvpid", "on",
		"--accelerate3d", "off",
		"--boot1", "dvd"); err != nil {
		return err
	}

	if err := d.vbm("modifyvm", d.MachineName,
		"--nic1", "nat",
		"--nictype1", "82540EM",
		"--cableconnected1", "on"); err != nil {
		return err
	}

	if err := d.vbm("storagectl", d.MachineName,
		"--name", "SATA",
		"--add", "sata",
		"--hostiocache", "on"); err != nil {
		return err
	}

	if err := d.vbm("storageattach", d.MachineName,
		"--storagectl", "SATA",
		"--port", "0",
		"--device", "0",
		"--type", "dvddrive",
		"--medium", d.ResolveStorePath("boot2docker.iso")); err != nil {
		return err
	}

	if err := d.vbm("storageattach", d.MachineName,
		"--storagectl", "SATA",
		"--port", "1",
		"--device", "0",
		"--type", "hdd",
		"--medium", d.diskPath()); err != nil {
		return err
	}

	// let VBoxService do nice magic automounting (when it's used)
	if err := d.vbm("guestproperty", "set", d.MachineName, "/VirtualBox/GuestAdd/SharedFolders/MountPrefix", "/"); err != nil {
		return err
	}
	if err := d.vbm("guestproperty", "set", d.MachineName, "/VirtualBox/GuestAdd/SharedFolders/MountDir", "/"); err != nil {
		return err
	}

	shareName, shareDir := getShareDriveAndName()

	if shareDir != "" && !d.NoShare {
		log.Debugf("setting up shareDir")
		if _, err := os.Stat(shareDir); err != nil && !os.IsNotExist(err) {
			return err
		} else if !os.IsNotExist(err) {
			if shareName == "" {
				// parts of the VBox internal code are buggy with share names that start with "/"
				shareName = strings.TrimLeft(shareDir, "/")
				// TODO do some basic Windows -> MSYS path conversion
				// ie, s!^([a-z]+):[/\\]+!\1/!; s!\\!/!g
			}

			// woo, shareDir exists!  let's carry on!
			if err := d.vbm("sharedfolder", "add", d.MachineName, "--name", shareName, "--hostpath", shareDir, "--automount"); err != nil {
				return err
			}

			// enable symlinks
			if err := d.vbm("setextradata", d.MachineName, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/"+shareName, "1"); err != nil {
				return err
			}
		}
	}

	return nil
}
Пример #17
0
func ConfigureAuth(p Provisioner) error {
	var (
		err error
	)

	driver := p.GetDriver()
	machineName := driver.GetMachineName()
	authOptions := p.GetAuthOptions()
	org := mcnutils.GetUsername() + "." + machineName
	bits := 2048

	ip, err := driver.GetIP()
	if err != nil {
		return err
	}

	log.Info("Copying certs to the local machine directory...")

	if err := mcnutils.CopyFile(authOptions.CaCertPath, filepath.Join(authOptions.StorePath, "ca.pem")); err != nil {
		return fmt.Errorf("Copying ca.pem to machine dir failed: %s", err)
	}

	if err := mcnutils.CopyFile(authOptions.ClientCertPath, filepath.Join(authOptions.StorePath, "cert.pem")); err != nil {
		return fmt.Errorf("Copying cert.pem to machine dir failed: %s", err)
	}

	if err := mcnutils.CopyFile(authOptions.ClientKeyPath, filepath.Join(authOptions.StorePath, "key.pem")); err != nil {
		return fmt.Errorf("Copying key.pem to machine dir failed: %s", err)
	}

	// The Host IP is always added to the certificate's SANs list
	hosts := append(authOptions.ServerCertSANs, ip, "localhost")
	log.Debugf("generating server cert: %s ca-key=%s private-key=%s org=%s san=%s",
		authOptions.ServerCertPath,
		authOptions.CaCertPath,
		authOptions.CaPrivateKeyPath,
		org,
		hosts,
	)

	// TODO: Switch to passing just authOptions to this func
	// instead of all these individual fields
	err = cert.GenerateCert(
		hosts,
		authOptions.ServerCertPath,
		authOptions.ServerKeyPath,
		authOptions.CaCertPath,
		authOptions.CaPrivateKeyPath,
		org,
		bits,
	)

	if err != nil {
		return fmt.Errorf("error generating server cert: %s", err)
	}

	if err := p.Service("docker", serviceaction.Stop); err != nil {
		return err
	}

	if _, err := p.SSHCommand("sudo ip link delete docker0"); err != nil {
		return err
	}

	// upload certs and configure TLS auth
	caCert, err := ioutil.ReadFile(authOptions.CaCertPath)
	if err != nil {
		return err
	}

	serverCert, err := ioutil.ReadFile(authOptions.ServerCertPath)
	if err != nil {
		return err
	}
	serverKey, err := ioutil.ReadFile(authOptions.ServerKeyPath)
	if err != nil {
		return err
	}

	log.Info("Copying certs to the remote machine...")

	// printf will choke if we don't pass a format string because of the
	// dashes, so that's the reason for the '%%s'
	certTransferCmdFmt := "printf '%%s' '%s' | sudo tee %s"

	// These ones are for Jessie and Mike <3 <3 <3
	if _, err := p.SSHCommand(fmt.Sprintf(certTransferCmdFmt, string(caCert), authOptions.CaCertRemotePath)); err != nil {
		return err
	}

	if _, err := p.SSHCommand(fmt.Sprintf(certTransferCmdFmt, string(serverCert), authOptions.ServerCertRemotePath)); err != nil {
		return err
	}

	if _, err := p.SSHCommand(fmt.Sprintf(certTransferCmdFmt, string(serverKey), authOptions.ServerKeyRemotePath)); err != nil {
		return err
	}

	dockerURL, err := driver.GetURL()
	if err != nil {
		return err
	}
	u, err := url.Parse(dockerURL)
	if err != nil {
		return err
	}
	dockerPort := 2376
	parts := strings.Split(u.Host, ":")
	if len(parts) == 2 {
		dPort, err := strconv.Atoi(parts[1])
		if err != nil {
			return err
		}
		dockerPort = dPort
	}

	dkrcfg, err := p.GenerateDockerOptions(dockerPort)
	if err != nil {
		return err
	}

	log.Info("Setting Docker configuration on the remote daemon...")

	if _, err = p.SSHCommand(fmt.Sprintf("printf %%s \"%s\" | sudo tee %s", dkrcfg.EngineOptions, dkrcfg.EngineOptionsPath)); err != nil {
		return err
	}

	if err := p.Service("docker", serviceaction.Start); err != nil {
		return err
	}

	return waitForDocker(p, dockerPort)
}
Пример #18
0
func ConfigureAuth(p Provisioner) error {
	var (
		err error
	)

	driver := p.GetDriver()
	machineName := driver.GetMachineName()
	authOptions := p.GetAuthOptions()
	org := mcnutils.GetUsername() + "." + machineName
	bits := 2048

	ip, err := driver.GetIP()
	if err != nil {
		return err
	}

	log.Info("Copying certs to the local machine directory...")

	if err := mcnutils.CopyFile(authOptions.CaCertPath, filepath.Join(authOptions.StorePath, "ca.pem")); err != nil {
		return fmt.Errorf("Copying ca.pem to machine dir failed: %s", err)
	}

	if err := mcnutils.CopyFile(authOptions.ClientCertPath, filepath.Join(authOptions.StorePath, "cert.pem")); err != nil {
		return fmt.Errorf("Copying cert.pem to machine dir failed: %s", err)
	}

	if err := mcnutils.CopyFile(authOptions.ClientKeyPath, filepath.Join(authOptions.StorePath, "key.pem")); err != nil {
		return fmt.Errorf("Copying key.pem to machine dir failed: %s", err)
	}

	log.Debugf("generating server cert: %s ca-key=%s private-key=%s org=%s",
		authOptions.ServerCertPath,
		authOptions.CaCertPath,
		authOptions.CaPrivateKeyPath,
		org,
	)

	// TODO: Switch to passing just authOptions to this func
	// instead of all these individual fields
	err = cert.GenerateCert(
		[]string{ip, "localhost"},
		authOptions.ServerCertPath,
		authOptions.ServerKeyPath,
		authOptions.CaCertPath,
		authOptions.CaPrivateKeyPath,
		org,
		bits,
	)

	if err != nil {
		return fmt.Errorf("error generating server cert: %s", err)
	}

	if err := p.Service("docker", serviceaction.Stop); err != nil {
		return err
	}

	// upload certs and configure TLS auth
	caCert, err := ioutil.ReadFile(authOptions.CaCertPath)
	if err != nil {
		return err
	}

	serverCert, err := ioutil.ReadFile(authOptions.ServerCertPath)
	if err != nil {
		return err
	}
	serverKey, err := ioutil.ReadFile(authOptions.ServerKeyPath)
	if err != nil {
		return err
	}

	log.Info("Copying certs to the remote machine...")

	// Create the file with echo then move it to its proper location
	certTransferCmdFmt := fmt.Sprintf(
		"%s && %s",
		"echo -e %q > /tmp/docker_cert",
		p.GetDriver().SSHSudo("mv /tmp/docker_cert %s"),
	)

	// These ones are for Jessie and Mike <3 <3 <3
	if _, err := p.SSHCommand(fmt.Sprintf(certTransferCmdFmt, string(caCert), authOptions.CaCertRemotePath)); err != nil {
		return err
	}

	if _, err := p.SSHCommand(fmt.Sprintf(certTransferCmdFmt, string(serverCert), authOptions.ServerCertRemotePath)); err != nil {
		return err
	}

	if _, err := p.SSHCommand(fmt.Sprintf(certTransferCmdFmt, string(serverKey), authOptions.ServerKeyRemotePath)); err != nil {
		return err
	}

	dockerUrl, err := driver.GetURL()
	if err != nil {
		return err
	}
	u, err := url.Parse(dockerUrl)
	if err != nil {
		return err
	}
	dockerPort := 2376
	parts := strings.Split(u.Host, ":")
	if len(parts) == 2 {
		dPort, err := strconv.Atoi(parts[1])
		if err != nil {
			return err
		}
		dockerPort = dPort
	}

	dkrcfg, err := p.GenerateDockerOptions(dockerPort)
	if err != nil {
		return err
	}

	log.Info("Setting Docker configuration on the remote daemon...")

	// Create the file with echo then move it to its proper location
	move_config_command := fmt.Sprintf(
		"echo -e %q > /tmp/docker_defaults && %s",
		dkrcfg.EngineOptions,
		p.GetDriver().SSHSudo("mv /tmp/docker_defaults %s"),
	)
	if _, err = p.SSHCommand(fmt.Sprintf(
		move_config_command,
		dkrcfg.EngineOptionsPath,
	)); err != nil {
		return err
	}

	if err := p.Service("docker", serviceaction.Start); err != nil {
		return err
	}

	return waitForDocker(p, dockerPort)
}