func providerConfigure(d *schema.ResourceData) (interface{}, error) {
	remote := d.Get("remote").(string)
	scheme := d.Get("scheme").(string)

	daemon_addr := ""
	switch scheme {
	case "unix":
		daemon_addr = fmt.Sprintf("unix:%s", d.Get("address"))
	case "https":
		daemon_addr = fmt.Sprintf("https://%s:%s", d.Get("address"), d.Get("port"))
	default:
		log.Fatal("Invalid scheme: %s", scheme)
	}

	// build LXD config
	config := lxd.Config{
		ConfigDir: os.ExpandEnv("$HOME/.config/lxc"),
		Remotes:   make(map[string]lxd.RemoteConfig),
	}
	config.Remotes[remote] = lxd.RemoteConfig{Addr: daemon_addr}

	if scheme == "https" {
		// validate certifictes exist
		certf := config.ConfigPath("client.crt")
		keyf := config.ConfigPath("client.key")
		if !shared.PathExists(certf) || !shared.PathExists(keyf) {
			log.Error("Certificate or key not found:\n\t%s\n\t%s", certf, keyf)
		}
		serverCertf := config.ServerCertPath(remote)
		if !shared.PathExists(serverCertf) {
			log.Error("Server certificate not found:\n\t%s", serverCertf)
		}
	}

	client, err := lxd.NewClient(&config, remote)
	if err != nil {
		log.Error("Could not create LXD client: %s", err)
		return nil, err
	}

	if err := validateClient(client); err != nil {
		return nil, err
	}

	lxdProv := LxdProvider{
		Remote: remote,
		Client: client,
	}

	return &lxdProv, nil
}
Example #2
0
File: cmd.go Project: juqkai/gopm
func execCmd(gopath, curPath string, args ...string) error {
	oldGopath := os.Getenv("GOPATH")
	log.Info("Setting GOPATH to %s", gopath)

	sep := ":"
	if runtime.GOOS == "windows" {
		sep = ";"
	}

	if err := os.Setenv("GOPATH", gopath+sep+oldGopath); err != nil {
		if setting.LibraryMode {
			return fmt.Errorf("Fail to setting GOPATH: %v", err)
		}
		log.Error("", "Fail to setting GOPATH:")
		log.Fatal("", "\t"+err.Error())
	}
	if setting.HasGOPATHSetting {
		defer func() {
			log.Info("Setting GOPATH back to %s", oldGopath)
			os.Setenv("GOPATH", oldGopath)
		}()
	}

	cmd := exec.Command(args[0], args[1:]...)
	cmd.Dir = curPath
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	log.Info("===== application outputs start =====\n")

	err := cmd.Run()

	log.Info("====== application outputs end ======")
	return err
}
Example #3
0
// If vcs has been detected, use corresponding command to update package.
func (n *Node) UpdateByVcs(vcs string) error {
	switch vcs {
	case "git":
		branch, stderr, err := base.ExecCmdDir(n.InstallGopath,
			"git", "rev-parse", "--abbrev-ref", "HEAD")
		if err != nil {
			log.Error("", "Error occurs when 'git rev-parse --abbrev-ref HEAD'")
			log.Error("", "\t"+stderr)
			return errors.New(stderr)
		}
		branch = strings.TrimSpace(branch)

		_, stderr, err = base.ExecCmdDir(n.InstallGopath,
			"git", "pull", "origin", branch)
		if err != nil {
			log.Error("", "Error occurs when 'git pull origin "+branch+"'")
			log.Error("", "\t"+stderr)
			return errors.New(stderr)
		}
	case "hg":
		_, stderr, err := base.ExecCmdDir(n.InstallGopath,
			"hg", "pull")
		if err != nil {
			log.Error("", "Error occurs when 'hg pull'")
			log.Error("", "\t"+stderr)
			return errors.New(stderr)
		}

		_, stderr, err = base.ExecCmdDir(n.InstallGopath,
			"hg", "up")
		if err != nil {
			log.Error("", "Error occurs when 'hg up'")
			log.Error("", "\t"+stderr)
			return errors.New(stderr)
		}
	case "svn":
		_, stderr, err := base.ExecCmdDir(n.InstallGopath,
			"svn", "update")
		if err != nil {
			log.Error("", "Error occurs when 'svn update'")
			log.Error("", "\t"+stderr)
			return errors.New(stderr)
		}
	}
	return nil
}
Example #4
0
File: gopm.go Project: juqkai/gopm
func main() {
	setting.LibraryMode = false
	if err := lib.Run(os.Args); err.HasError {
		if err.Fatal != nil {
			log.Fatal("%v", err.Fatal)
		}
		for _, e := range err.Errors {
			log.Error("%v", e)
		}
	}
}
Example #5
0
func loadLocalVerInfo() (ver version) {
	verPath := path.Join(setting.HomeDir, setting.VERINFO)

	// First time run should not exist.
	if !base.IsExist(verPath) {
		return ver
	}

	f, err := os.Open(verPath)
	if err != nil {
		log.Error("Update", "Fail to open VERSION.json")
		log.Fatal("", err.Error())
	}

	if err := json.NewDecoder(f).Decode(&ver); err != nil {
		log.Error("Update", "Fail to decode VERSION.json")
		log.Fatal("", err.Error())
	}
	return ver
}
Example #6
0
File: http.go Project: RouGang/gopm
func (t *transport) SetProxy(proxy string) error {
	if len(proxy) == 0 {
		return nil
	}

	proxyUrl, err := url.Parse(proxy)
	if err != nil {
		if setting.LibraryMode {
			return fmt.Errorf("Fail to set HTTP proxy: %v", err)
		}
		log.Error("", "Fail to set HTTP proxy:")
		log.Fatal("", "\t"+err.Error())
	}
	t.t.Proxy = http.ProxyURL(proxyUrl)
	return nil
}
Example #7
0
func (n *Node) CopyToGopath() error {
	if n.HasVcs() {
		log.Warn("Package in GOPATH has version control: %s", n.RootPath)
		return nil
	}

	os.RemoveAll(n.InstallGopath)
	if err := base.CopyDir(n.InstallPath, n.InstallGopath); err != nil {
		if setting.LibraryMode {
			return fmt.Errorf("Fail to copy to GOPATH: %v", err)
		}
		log.Error("", "Fail to copy to GOPATH:")
		log.Fatal("", "\t"+err.Error())
	}
	log.Info("Package copied to GOPATH: %s", n.RootPath)
	return nil
}
Example #8
0
// downloadPackages downloads packages with certain commit,
// if the commit is empty string, then it downloads all dependencies,
// otherwise, it only downloada package with specific commit only.
func downloadPackages(target string, ctx *cli.Context, nodes []*doc.Node) (err error) {
	for _, n := range nodes {
		// Check if it is a valid remote path or C.
		if n.ImportPath == "C" {
			continue
		} else if !base.IsValidRemotePath(n.ImportPath) {
			// Invalid import path.
			if setting.LibraryMode {
				errors.AppendError(errors.NewErrInvalidPackage(n.VerString()))
			}
			log.Error("Skipped invalid package: " + n.VerString())
			failConut++
			continue
		}

		// Valid import path.
		if isSubpackage(n.RootPath, target) {
			continue
		}

		// Indicates whether need to download package or update.
		if n.IsFixed() && n.IsExist() {
			n.IsGetDepsOnly = true
		}

		if downloadCache.Get(n.VerString()) {
			if !skipCache.Get(n.VerString()) {
				skipCache.Set(n.VerString())
				log.Debug("Skipped downloaded package: %s", n.VerString())
			}
			continue
		}

		if !ctx.Bool("update") {
			// Check if package has been downloaded.
			if n.IsExist() {
				if !skipCache.Get(n.VerString()) {
					skipCache.Set(n.VerString())
					log.Info("%s", n.InstallPath)
					log.Debug("Skipped installed package: %s", n.VerString())
				}

				// Only copy when no version control.
				if !copyCache.Get(n.VerString()) && (ctx.Bool("gopath") || ctx.Bool("local")) {
					copyCache.Set(n.VerString())
					if err = n.CopyToGopath(); err != nil {
						return err
					}
				}
				continue
			} else {
				setting.LocalNodes.SetValue(n.RootPath, "value", "")
			}
		}
		// Download package.
		nod, imports, err := downloadPackage(ctx, n)
		if err != nil {
			return err
		}
		for _, name := range imports {
			var gf *goconfig.ConfigFile
			gfPath := path.Join(n.InstallPath, setting.GOPMFILE)

			// Check if has gopmfile.
			if base.IsFile(gfPath) {
				log.Info("Found gopmfile: %s", n.VerString())
				var err error
				gf, _, err = parseGopmfile(gfPath)
				if err != nil {
					return fmt.Errorf("fail to parse gopmfile(%s): %v", gfPath, err)
				}
			}

			// Need to download dependencies.
			// Generate temporary nodes.
			nodes := make([]*doc.Node, len(imports))
			for i := range nodes {
				nodes[i] = doc.NewNode(name, doc.BRANCH, "", !ctx.Bool("download"))

				if gf == nil {
					continue
				}

				// Check if user specified the version.
				if v := gf.MustValue("deps", imports[i]); len(v) > 0 {
					nodes[i].Type, nodes[i].Value, err = validPkgInfo(v)
					if err != nil {
						return err
					}
				}
			}
			if err = downloadPackages(target, ctx, nodes); err != nil {
				return err
			}
		}

		// Only save package information with specific commit.
		if nod == nil {
			continue
		}

		// Save record in local nodes.
		log.Info("Got %s", n.VerString())
		downloadCount++

		// Only save non-commit node.
		if nod.IsEmptyVal() && len(nod.Revision) > 0 {
			setting.LocalNodes.SetValue(nod.RootPath, "value", nod.Revision)
		}

		// If update set downloadPackage will use VSC tools to download the package,
		// else just download to local repository and copy to GOPATH.
		if !nod.HasVcs() && !copyCache.Get(n.RootPath) && (ctx.Bool("gopath") || ctx.Bool("local")) {
			copyCache.Set(n.RootPath)
			if err = nod.CopyToGopath(); err != nil {
				return err
			}
		}
	}
	return nil
}
Example #9
0
func runUpdate(ctx *cli.Context) {
	if setting.LibraryMode {
		errors.SetError(fmt.Errorf("Library mode does not support update command"))
		return
	}
	if err := setup(ctx); err != nil {
		errors.SetError(err)
		return
	}

	isAnythingUpdated := false
	localVerInfo := loadLocalVerInfo()

	// Get remote version info.
	var remoteVerInfo version
	if err := base.HttpGetJSON(doc.HttpClient, "http://gopm.io/VERSION.json", &remoteVerInfo); err != nil {
		log.Fatal("Fail to fetch VERSION.json: %v", err)
	}

	// Package name list.
	if remoteVerInfo.PackageNameList > localVerInfo.PackageNameList {
		log.Info("Updating pkgname.list...%v > %v",
			localVerInfo.PackageNameList, remoteVerInfo.PackageNameList)
		data, err := base.HttpGetBytes(doc.HttpClient, "https://raw.githubusercontent.com/gpmgo/docs/master/pkgname.list", nil)
		if err != nil {
			log.Warn("Fail to update pkgname.list: %v", err)
		} else {
			if err = ioutil.WriteFile(setting.PkgNameListFile, data, os.ModePerm); err != nil {
				log.Fatal("Fail to save pkgname.list: %v", err)
			}
			log.Info("Update pkgname.list to %v succeed!", remoteVerInfo.PackageNameList)
			isAnythingUpdated = true
		}
	}

	// Gopm.
	if remoteVerInfo.Gopm > setting.VERSION {
		log.Info("Updating gopm...%v > %v", setting.VERSION, remoteVerInfo.Gopm)

		tmpDir := base.GetTempDir()
		tmpBinPath := path.Join(tmpDir, "gopm")
		if runtime.GOOS == "windows" {
			tmpBinPath += ".exe"
		}

		os.MkdirAll(path.Dir(tmpBinPath), os.ModePerm)
		os.Remove(tmpBinPath)

		// Fetch code.
		args := []string{"bin", "-u", "-r", "-d=" + tmpDir}
		if ctx.Bool("verbose") {
			args = append(args, "-v")
		}
		args = append(args, "github.com/gpmgo/gopm")
		stdout, stderr, err := base.ExecCmd("gopm", args...)
		if err != nil {
			log.Fatal("Fail to execute 'bin -u -r -d=/Users/jiahuachen/.gopm/temp -v github.com/gpmgo/gopm: %s", stderr)
		}
		if len(stdout) > 0 {
			fmt.Print(stdout)
		}

		// Check if previous steps were successful.
		if !base.IsExist(tmpBinPath) {
			log.Error("Fail to continue command")
			log.Fatal("Previous steps weren't successful, no binary produced")
		}

		movePath, err := execPath()
		if err != nil {
			log.Fatal("Fail to get execute path: %v", err)
		}
		log.Info("New binary will be replaced for %s", movePath)
		// Move binary to given directory.
		if runtime.GOOS != "windows" {
			err := os.Rename(tmpBinPath, movePath)
			if err != nil {
				log.Fatal("Fail to move binary: %v", err)
			}
			os.Chmod(movePath+"/"+path.Base(tmpBinPath), os.ModePerm)
		} else {
			batPath := path.Join(tmpDir, "update.bat")
			f, err := os.Create(batPath)
			if err != nil {
				log.Error("Update", "Fail to generate bat file")
				log.Fatal("", err.Error())
			}
			f.WriteString("@echo off\r\n")
			f.WriteString(fmt.Sprintf("ping -n 1 127.0.0.1>nul\r\ncopy \"%v\" \"%v\" >nul\r\ndel \"%v\" >nul\r\n\r\n",
				tmpBinPath, movePath, tmpBinPath))
			f.Close()

			attr := &os.ProcAttr{
				Dir:   setting.WorkDir,
				Env:   os.Environ(),
				Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
			}

			if _, err = os.StartProcess(batPath, []string{batPath}, attr); err != nil {
				log.Error("Update", "Fail to start bat process")
				log.Fatal("", err.Error())
			}
		}

		log.Info("Command execute successfully!")
		isAnythingUpdated = true
	}

	if isAnythingUpdated {
		// Save JSON.
		verPath := path.Join(setting.HomeDir, setting.VERINFO)
		os.MkdirAll(path.Dir(verPath), os.ModePerm)
		f, err := os.Create(verPath)
		if err != nil {
			log.Fatal("Fail to create VERSION.json: %v", err)
		}
		if err := json.NewEncoder(f).Encode(&remoteVerInfo); err != nil {
			log.Fatal("Fail to encode VERSION.json: %v", err)
		}
	} else {
		log.Info("Nothing need to be updated")
	}
	log.Info("Exit old gopm")
}