示例#1
0
文件: install.go 项目: godrei/bitrise
func validateRequirements(requirements []Requirement, currentVersionMap map[string]ver.Version) error {
	var err error

	for _, requirement := range requirements {
		currentVersion := currentVersionMap[requirement.Tool]

		var minVersionPtr *ver.Version
		if requirement.MinVersion == "" {
			return fmt.Errorf("plugin requirement min version is required")
		}

		minVersionPtr, err = ver.NewVersion(requirement.MinVersion)
		if err != nil {
			return fmt.Errorf("failed to parse plugin required min version (%s) for tool (%s), error: %s", requirement.MinVersion, requirement.Tool, err)
		}

		var maxVersionPtr *ver.Version
		if requirement.MaxVersion != "" {
			maxVersionPtr, err = ver.NewVersion(requirement.MaxVersion)
			if err != nil {
				return fmt.Errorf("failed to parse plugin requirement version (%s) for tool (%s), error: %s", requirement.MaxVersion, requirement.Tool, err)
			}
		}

		if err := validateVersion(currentVersion, *minVersionPtr, maxVersionPtr); err != nil {
			return fmt.Errorf("checking plugin tool (%s) requirements failed, error: %s", requirement.Tool, err)
		}
	}

	return nil
}
示例#2
0
文件: config.go 项目: yext/edward
func LoadConfigWithDir(reader io.Reader, workingDir string, edwardVersion string, logger common.Logger) (Config, error) {
	config, err := loadConfigContents(reader, workingDir, logger)
	if err != nil {
		return Config{}, errors.WithStack(err)
	}
	if config.MinEdwardVersion != "" && edwardVersion != "" {
		// Check that this config is supported by this version
		minVersion, err1 := version.NewVersion(config.MinEdwardVersion)
		if err1 != nil {
			return Config{}, errors.WithStack(err)
		}
		currentVersion, err2 := version.NewVersion(edwardVersion)
		if err2 != nil {
			return Config{}, errors.WithStack(err)
		}
		if currentVersion.LessThan(minVersion) {
			return Config{}, errors.New("this config requires at least version " + config.MinEdwardVersion)
		}
	}
	err = config.initMaps()

	config.printf("Config loaded with: %d groups and %d services\n", len(config.GroupMap), len(config.ServiceMap))

	return config, errors.WithStack(err)
}
示例#3
0
func (p *PactFile) Validate() error {
	if p.Provider == nil || p.Provider.Name == "" {
		return errEmptyProvider
	}

	if p.Consumer == nil || p.Consumer.Name == "" {
		return errEmptyConsumer
	}

	psv, err := version.NewVersion(pactSpecificationVersion)
	if err != nil {
		return err
	}

	fpsv, err := version.NewVersion(p.Metadata.PactSpecificationVersion)
	if err != nil {
		return err
	}

	//should be backwards compatible with version 1.0.0
	if fpsv.GreaterThan(psv) {
		return errIncompatiblePact
	}

	return nil
}
示例#4
0
func VersionCompare(args []string) {
	v0, err := v.NewVersion(args[0])
	if err != nil {
		fatal("Can't parse version string" + err.Error())
	}

	v1, err := v.NewVersion(args[1])
	if err != nil {
		fatal("Can't parse version string" + err.Error())
	}
	fmt.Println(v0.Compare(v1))
}
示例#5
0
文件: parser.go 项目: dbilovd/iglo
func CheckVersion(v string) error {
	mv, _ := version.NewVersion("2.0.1")
	ov, err := version.NewVersion(v)
	if err != nil {
		return err
	}

	if ov.LessThan(mv) {
		return errors.New(fmt.Sprintf("You are using drafter version %s. Minimum version should be %s", ov, mv))
	}

	return nil
}
示例#6
0
文件: cmd.go 项目: tsuru/tsuru
// validateVersion checks whether current version is greater or equal to
// supported version.
func validateVersion(supported, current string) bool {
	if supported == "" {
		return true
	}
	vSupported, err := goVersion.NewVersion(supported)
	if err != nil {
		return false
	}
	vCurrent, err := goVersion.NewVersion(current)
	if err != nil {
		return false
	}
	return vCurrent.Compare(vSupported) >= 0
}
func enforceSemver(v string) *version.Version {
	semver, err := version.NewVersion(v)
	if err != nil {
		log.Fatalln(err)
	}

	var segments []string
	for i := 0; i < 3; i++ {
		segments = append(segments, strconv.Itoa(semver.Segments()[i]))
	}

	semver, _ = version.NewVersion(strings.Join(segments, "."))

	return semver
}
示例#8
0
// VersionTaggedCommits ...
func VersionTaggedCommits() ([]CommitModel, error) {
	out, err := NewPrintableCommand("git", "tag", "--list").Run()
	if err != nil {
		return []CommitModel{}, err
	}
	taggedCommits := []CommitModel{}
	tags := splitByNewLineAndStrip(out)
	for _, tag := range tags {
		// is tag sem-ver tag?
		_, err := version.NewVersion(tag)
		if err != nil {
			continue
		}

		out, err = NewPrintableCommand("git", "rev-list", "-n", "1", `--pretty=format:commit: %H%ndate: %ct%nauthor: %an%nmessage: %s`, tag).Run()
		if err != nil {
			return []CommitModel{}, err
		}

		commit, err := parseCommit(Strip(out))
		if err != nil {
			return []CommitModel{}, fmt.Errorf("Failed to parse commit: %#v", err)
		}
		commit.Tag = tag

		taggedCommits = append(taggedCommits, commit)
	}

	SortByDate(taggedCommits)

	return taggedCommits, nil
}
示例#9
0
// CheckNewVersion checks if a new version is available
func CheckNewVersion() {
	if Version == "dev" {
		return
	}
	client := github.NewClient(nil)
	updateURL, err := url.Parse("https://update.traefik.io")
	if err != nil {
		log.Warnf("Error checking new version: %s", err)
		return
	}
	client.BaseURL = updateURL
	releases, resp, err := client.Repositories.ListReleases("containous", "traefik", nil)
	if err != nil {
		log.Warnf("Error checking new version: %s", err)
		return
	}

	if resp.StatusCode != 200 {
		log.Warnf("Error checking new version: status=%s", resp.Status)
		return
	}

	currentVersion, err := goversion.NewVersion(Version)
	if err != nil {
		log.Warnf("Error checking new version: %s", err)
		return
	}

	for _, release := range releases {
		releaseVersion, err := goversion.NewVersion(*release.TagName)
		if err != nil {
			log.Warnf("Error checking new version: %s", err)
			return
		}

		if len(currentVersion.Prerelease()) == 0 && len(releaseVersion.Prerelease()) > 0 {
			continue
		}

		if releaseVersion.GreaterThan(currentVersion) {
			log.Warnf("A new release has been found: %s. Please consider updating.", releaseVersion.String())
			return
		}
	}
}
示例#10
0
文件: git.go 项目: bitrise-io/bitrise
func filterVersionTags(tagList []string) []*ver.Version {
	versionTags := []*ver.Version{}
	for _, tag := range tagList {
		versionTag, err := ver.NewVersion(tag)
		if err == nil && versionTag != nil {
			versionTags = append(versionTags, versionTag)
		}
	}
	return versionTags
}
func TestParseVersion(t *testing.T) {
	t.Parallel()

	infoBlob := []byte(`{
		"http_config": {
			"https_port": 8443,
			"http_port": 8080,
			"assets_path": null
		},
		"name": "marathon",
		"version": "0.11.1",
		"elected": true,
		"leader": "marathon-leader.example.com:8080",
		"frameworkId": "20150714-191408-4163031306-5050-1590-0000",
		"marathon_config": {
			"mesos_leader_ui_url": "http://marathon-leader.example.com:5050/",
			"leader_proxy_read_timeout_ms": 10000,
			"leader_proxy_connection_timeout_ms": 5000,
			"executor": "//cmd",
			"local_port_max": 20000,
			"local_port_min": 10000,
			"checkpoint": true,
			"ha": true,
			"framework_name": "marathon",
			"failover_timeout": 604800,
			"master": "zk://zk.example.com:2181/mesos",
			"hostname": "marathon-leader.example.com",
			"webui_url": null,
			"mesos_role": null,
			"task_launch_timeout": 300000,
			"reconciliation_initial_delay": 15000,
			"reconciliation_interval": 300000,
			"marathon_store_timeout": 2000,
			"mesos_user": "******"
		},
		"zookeeper_config": {
			"zk_max_versions": 25,
			"zk_session_timeout": 1800000,
			"zk_timeout": 10000,
			"zk": "zk://zk.example.com:2181/marathon"
		},
		"event_subscriber": {
			"http_endpoints": null,
			"type": "http_callback"
		}
  }`)
	m, _ := NewMarathon("localhost:8080", "http", nil)
	v, err := m.ParseVersion(infoBlob)
	assert.Equal(t, v, "0.11.1")
	assert.Nil(t, err)

	// quickly verify that this version can be parsed with the version library
	_, err = version.NewVersion(v)
	assert.Nil(t, err)
}
示例#12
0
func newArtifact(a *nexus.Artifact) (*Artifact, error) {
	v, err := version.NewVersion(a.Version)
	if err != nil {
		return nil, err

	}
	return &Artifact{
		Artifact: a,
		v:        v,
	}, nil
}
示例#13
0
func (c *Config) testDockerVersion() error {
	endpoint, err := c.GetDockerClient()
	if err != nil {
		return err
	}
	ev, err := endpoint.Version()
	if err != nil {

		return err
	}
	currVersion := ev.Get("ApiVersion")
	activeVersion, err := version.NewVersion(currVersion)
	supportedVersion, err := version.NewVersion(DockerApiVersion)
	if activeVersion.LessThan(supportedVersion) {
		return errors.New(currVersion + " version is lower than supported Docker version of " + DockerApiVersion + ". You will need to upgrade docker.")
	}

	Log.Debug("Found docker API version: ", currVersion)
	c.currentDockerApiVersion = currVersion
	return nil
}
示例#14
0
func (dc *DockerKernelCheck) AuditCheck() (bool, error) {

	cmd := exec.Command("uname", "-r")

	bytes, err := cmd.CombinedOutput()

	if err != nil {
		return false, err
	}

	lines := strings.Split(string(bytes), "\n")

	if len(lines) < 1 {
		return false, errors.New("Nothing returned from uname -r")
	}

	kernelstring := lines[0]
	parts := strings.Split(kernelstring, "-")

	if len(parts) < 1 {
		return false, errors.New("Malformed kernel string" + kernelstring)
	}
	kernelversion := parts[0]

	v1, err := version.NewVersion(kernelversion)
	if err != nil {
		return false, err
	}
	targetVersion, err := version.NewVersion("3.10")
	if err != nil {
		return false, err
	}

	if v1.Compare(targetVersion) >= 0 {
		return true, nil
	}
	// TODO: print out kernel version
	return false, nil
}
示例#15
0
文件: client.go 项目: thomasf/alkasir
// CheckBinaryUpgrade returns upgrade meta data if an upgrade is available.
func (c *Client) CheckBinaryUpgrade(request shared.BinaryUpgradeRequest) (shared.BinaryUpgradeResponse, bool, error) {
	data, err := json.Marshal(&request)
	var response shared.BinaryUpgradeResponse
	if err != nil {
		return response, false, err
	}
	resp, err := c.post("upgrades/", bytes.NewBuffer(data))
	if err != nil {
		return response, false, err
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusNotFound {
		return response, false, nil
	}

	if resp.StatusCode != http.StatusOK {
		return response, false,
			fmt.Errorf("Upgradeversion http status response: %d", resp.StatusCode)
	}
	if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
		return response, false, err
	}

	currentVersion, err := version.NewVersion(request.FromVersion)
	if err != nil {
		return response, false, fmt.Errorf("Cannot parse current version from %s", request.FromVersion)
	}
	newVersion, err := version.NewVersion(response.Version)
	if err != nil {
		return response, false, fmt.Errorf("Cannot parse new version from %s", response.Version)
	}
	if currentVersion.GreaterThan(newVersion) {
		return response, false, fmt.Errorf("Received version %s is older than current version %s", newVersion, currentVersion)
	}

	return response, true, nil
}
示例#16
0
// Validate ...
func (route PluginRoute) Validate() error {
	if route.Name == "" {
		return fmt.Errorf("invalid route: missing required name")
	}
	if route.Source == "" {
		return fmt.Errorf("invalid route: missing required source")
	}
	if route.Version != "" {
		if _, err := ver.NewVersion(route.Version); err != nil {
			return fmt.Errorf("invalid route: invalid version (%s)", route.Version)
		}
	}
	return nil
}
示例#17
0
func Constraint(constraint, version string) bool {
	c, err := semver.NewConstraint(constraint)
	if err != nil {
		idl.Err(err)
		return false
	}

	v, err := semver.NewVersion(version)
	if err != nil {
		idl.Debug(err)
		return false
	}

	return c.Check(v)
}
示例#18
0
文件: git.go 项目: bitrise-io/bitrise
// GitCloneAndCheckoutVersion ...
func GitCloneAndCheckoutVersion(cloneIntoDir, repositoryURL, checkoutVersion string) (*ver.Version, string, error) {
	if err := gitInitWithRemote(cloneIntoDir, repositoryURL); err != nil {
		return nil, "", err
	}

	var version ver.Version

	if checkoutVersion == "" {
		versionTagList, err := GitVersionTags(cloneIntoDir)
		if err != nil {
			return nil, "", fmt.Errorf("Could not get version tag list, error: %s", err)
		}

		if len(versionTagList) == 0 {
			return nil, "", fmt.Errorf("no version tag found")
		}

		versionPtr := versionTagList[len(versionTagList)-1]
		if versionPtr == nil {
			return nil, "", fmt.Errorf("uninitialized version found")
		}

		version = *versionPtr
	} else {
		versionPtr, err := ver.NewVersion(checkoutVersion)
		if err != nil {
			return nil, "", fmt.Errorf("failed to parse version (%s), error: %s", checkoutVersion, err)
		}

		if versionPtr == nil {
			return nil, "", errors.New("failed to parse version (%s), error: nil version")
		}

		version = *versionPtr
	}

	if err := gitCheckout(cloneIntoDir, version.String()); err != nil {
		return nil, "", fmt.Errorf("Could not checkout, err :%s", err)
	}

	hash, err := commitHashOfTag(cloneIntoDir, version.String())
	if err != nil {
		return nil, "", fmt.Errorf("Could get commit hash of tag (%s), err :%s", version.String(), err)
	}

	return &version, hash, nil
}
示例#19
0
func CheckDockerVersion(t Target) (res Result) {
	res.Name = "1.5 Keep Docker up to date"
	verConstr := os.Getenv("VERSION")
	info, err := t.Client.ServerVersion()
	if err != nil {
		log.Fatalf("Could not retrieve info for Docker host")
	}
	constraints, _ := version.NewConstraint(">= " + verConstr)
	hostVersion, _ := version.NewVersion(info.Version)
	if constraints.Check(hostVersion) {
		res.Pass()
	} else {
		output := fmt.Sprintf("Host is using an outdated Docker server: %s ",
			info.Version)
		res.Fail(output)
	}
	return
}
示例#20
0
// Compares sematic versions with 2 components (9.1, 9.2, ...)
// Return true if first version is greater then second
func isOsVersionGreater(osVersion, otherOsVersion string) (bool, error) {
	versionPtrs := []*ver.Version{}
	for _, osVer := range []string{osVersion, otherOsVersion} {
		osVersionSplit := strings.Split(osVer, " ")
		if len(osVersionSplit) != 2 {
			return false, fmt.Errorf("failed to parse version: %s", osVer)
		}

		version, err := ver.NewVersion(osVersionSplit[1])
		if err != nil {
			return false, err
		}

		versionPtrs = append(versionPtrs, version)
	}

	return versionPtrs[0].GreaterThan(versionPtrs[1]), nil
}
示例#21
0
func createXcodeVersionFromOutput(versionOut string) (XcodebuildVersionModel, error) {
	split := strings.Split(versionOut, "\n")
	if len(split) != 2 {
		return XcodebuildVersionModel{}, fmt.Errorf("invalid version output: %s", versionOut)
	}

	xcodeVersionStr := strings.TrimPrefix(split[0], "Xcode ")
	xcodeVersion, err := version.NewVersion(xcodeVersionStr)
	if err != nil {
		return XcodebuildVersionModel{}, fmt.Errorf("failed to parse xcode version (%s), error: %s", xcodeVersionStr, err)
	}

	buildVersion := strings.TrimPrefix(split[1], "Build version ")

	return XcodebuildVersionModel{
		XcodeVersion: xcodeVersion,
		BuildVersion: buildVersion,
	}, nil
}
示例#22
0
func (r *Rethinkdb) assertServerVersion(constraint version.Constraints) error {
	cursor, err := gorethink.DB("rethinkdb").Table("server_status").Run(r.client)
	if err != nil {
		return err
	}

	if cursor.IsNil() {
		return errors.New("could not determine the RethinkDB server version: no rows returned from the server_status table")
	}

	var serverStatus rethinkDbServerStatus
	cursor.Next(&serverStatus)

	if serverStatus.Process.Version == "" {
		return errors.New("could not determine the RethinkDB server version: process.version key missing")
	}

	pieces := strings.Split(serverStatus.Process.Version, " ")
	if len(pieces) < 2 {
		return fmt.Errorf("could not determine the RethinkDB server version: malformed version string (%v)", serverStatus.Process.Version)
	}

	versionString := rethinkDbVersionMatcher.FindString(pieces[1])
	if versionString == "" {
		return fmt.Errorf("could not determine the RethinkDB server version: malformed version string (%v)", serverStatus.Process.Version)
	}

	if r.debug {
		fmt.Printf("RethinkDB version: %v\n", versionString)
	}

	serverVersion, err := version.NewVersion(versionString)
	if err != nil {
		return fmt.Errorf("could not determine the RethinkDB server version: malformed version string (%v)", serverStatus.Process.Version)
	}

	if !constraint.Check(serverVersion) {
		return fmt.Errorf("RethinkDB server version too old: expected %v, but was %v", constraint, serverVersion)
	}

	return nil
}
示例#23
0
func CheckKernelVersion(t Target) (res Result) {
	res.Name = "1.2 Use the updated Linux Kernel"
	info := t.Info
	constraints, _ := version.NewConstraint(">= 3.10")
	hostVersion, err := version.NewVersion(info.KernelVersion)
	if err != nil {
		// necessary fix for incompatible kernel versions (e.g. Fedora 23)
		log.Print("Incompatible kernel version")
		output := "Incompatible kernel version reported"
		res.Info(output)
		return
	}
	if constraints.Check(hostVersion) {
		res.Pass()
	} else {
		output := fmt.Sprintf("Host is not using an updated kernel: %s",
			info.KernelVersion)
		res.Fail(output)
	}
	return
}
示例#24
0
func main() {
	config := config.New()
	apiConfig, err := config.Registry.Config()
	if err != nil {
		log.Fatal(err.Error())
	}

	kv, err := consul.NewKV(apiConfig)
	if err != nil {
		log.Fatal(err.Error())
	}

	consul := consul.NewConsul(kv, config.Registry.Prefix)

	// set up initial sync
	remote, err := config.Marathon.NewMarathon()
	if err != nil {
		log.Fatal(err.Error())
	}
	sync := marathon.NewMarathonSync(remote, consul)
	go sync.Sync()

	fh := &ForwardHandler{consul}

	v, err := remote.Version()
	if err != nil {
		log.WithError(err).Warn("version parsing failed, assuming >= 0.9.0")
		v, _ = version.NewVersion("0.9.0")
	}
	minVersion, _ := version.NewConstraint(">= 0.9.0")

	if minVersion.Check(v) {
		log.WithField("version", v).Info("detected Marathon events endpoint")
		SubscribeToEventStream(config, remote, fh)
	} else {
		log.WithField("version", v).Info("detected old Marathon version -- make sure to set up an eventSubscription for this process")
		ServeWebhookReceiver(config, fh)
	}
}
示例#25
0
文件: vcs.go 项目: Zordrak/terraform
// gitPreflight is the pre-flight command that runs for Git-based VCSs
func gitPreflight(path string) error {
	var stderr, stdout bytes.Buffer

	cmd := exec.Command("git", "--version")
	cmd.Dir = path
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("error getting git version: %s\nstdout: %s\nstderr: %s",
			err, stdout.String(), stderr.String())
	}

	// Check if the output is valid
	output := strings.Split(strings.TrimSpace(stdout.String()), " ")
	if len(output) < 1 {
		log.Printf("[WARN] could not extract version output from Git")
		return nil
	}

	// Parse the version
	gitv, err := version.NewVersion(output[len(output)-1])
	if err != nil {
		log.Printf("[WARN] could not parse version output from Git")
		return nil
	}

	constraint, err := version.NewConstraint("> 1.8")
	if err != nil {
		log.Printf("[WARN] could not create version constraint to check")
		return nil
	}
	if !constraint.Check(gitv) {
		return fmt.Errorf("git version (%s) is too old, please upgrade", gitv.String())
	}

	return nil
}
示例#26
0
func (m Marathon) Version() (*version.Version, error) {
	log.WithField("location", m.Location).Debug("asking Marathon for its version")
	client := m.getClient()

	request, err := http.NewRequest("GET", m.Url("/v2/info"), nil)
	if err != nil {
		log.Error(err.Error())
		return nil, err
	}
	request.Header.Add("Accept", "application/json")

	infoResponse, err := client.Do(request)
	if err != nil || (infoResponse.StatusCode != 200) {
		m.logHTTPError(infoResponse, err)
		return nil, err
	}

	body, err := ioutil.ReadAll(infoResponse.Body)
	if err != nil {
		m.logHTTPError(infoResponse, err)
		return nil, err
	}

	v, err := m.ParseVersion(body)
	if err != nil {
		m.logHTTPError(infoResponse, err)
		return nil, err
	}

	parsedVersion, err := version.NewVersion(v)
	if err != nil {
		log.WithError(err).Error("error parsing version: %s", v)
		return nil, err
	}

	return parsedVersion, err
}
示例#27
0
func TestValidateRequirements(t *testing.T) {
	bitriseVersion, err := ver.NewVersion("1.0.0")
	require.NoError(t, err)

	envmanVersion, err := ver.NewVersion("1.0.0")
	require.NoError(t, err)

	stepmanVersion, err := ver.NewVersion("1.0.0")
	require.NoError(t, err)

	currentVersionMap := map[string]ver.Version{
		"bitrise": *bitriseVersion,
		"envman":  *envmanVersion,
		"stepman": *stepmanVersion,
	}

	t.Log("valid requirements")
	{
		requirements := []Requirement{
			Requirement{
				Tool:       "bitrise",
				MinVersion: "1.0.0",
				MaxVersion: "1.0.0",
			},
			Requirement{
				Tool:       "envman",
				MinVersion: "0.9.0",
				MaxVersion: "1.1.0",
			},
			Requirement{
				Tool:       "stepman",
				MinVersion: "1.0.0",
				MaxVersion: "1.0.0",
			},
		}

		err := validateRequirements(requirements, currentVersionMap)
		require.NoError(t, err)
	}

	t.Log("invalid requirements")
	{
		requirements := []Requirement{
			Requirement{
				Tool:       "bitrise",
				MinVersion: "1.0.0",
				MaxVersion: "1.0.0",
			},
			Requirement{
				Tool:       "envman",
				MinVersion: "1.1.0",
				MaxVersion: "1.1.0",
			},
			Requirement{
				Tool:       "stepman",
				MinVersion: "1.0.0",
				MaxVersion: "1.0.0",
			},
		}

		err := validateRequirements(requirements, currentVersionMap)
		require.Error(t, err)
	}
}
示例#28
0
// CheckIsPluginInstalled ...
func CheckIsPluginInstalled(name string, dependency PluginDependency) error {
	_, found, err := plugins.LoadPlugin(name)
	if err != nil {
		return err
	}

	currentVersion := ""
	installOrUpdate := false

	if !found {
		fmt.Println()
		log.Warnf("Default plugin (%s) NOT found.", name)
		fmt.Println()

		fmt.Print("Installing...")
		installOrUpdate = true
		currentVersion = dependency.MinVersion
	} else {
		installedVersion, err := plugins.GetPluginVersion(name)
		if err != nil {
			return err
		}

		if installedVersion == nil {
			fmt.Println()
			log.Warnf("Default plugin (%s) is not installed from git, no version info available.", name)
			fmt.Println()

			currentVersion = "local"
		} else {
			currentVersion = installedVersion.String()

			minVersion, err := ver.NewVersion(dependency.MinVersion)
			if err != nil {
				return err
			}

			if installedVersion.LessThan(minVersion) {
				fmt.Println()
				log.Warnf("Default plugin (%s) version (%s) is lower than required (%s).", name, installedVersion.String(), minVersion.String())
				fmt.Println()

				log.Infoln("Updating...")
				installOrUpdate = true
				currentVersion = dependency.MinVersion
			}
		}
	}

	if installOrUpdate {
		var plugin plugins.Plugin
		err := progress.SimpleProgressE(".", 2*time.Second, func() error {
			return retry.Times(2).Wait(5 * time.Second).Try(func(attempt uint) error {
				if attempt > 0 {
					fmt.Println()
					fmt.Print("==> Download failed, retrying ...")
				}
				p, _, err := plugins.InstallPlugin(dependency.Source, dependency.Binary, dependency.MinVersion)
				plugin = p
				return err
			})
		})
		fmt.Println()

		if err != nil {
			return fmt.Errorf("Failed to install plugin, error: %s", err)
		}

		if len(plugin.Description) > 0 {
			fmt.Println()
			fmt.Println(plugin.Description)
			fmt.Println()
		}
	}

	pluginDir := plugins.GetPluginDir(name)

	log.Infof(" * %s Plugin (%s) : %s", colorstring.Green("[OK]"), name, pluginDir)
	log.Infof("        version : %s", currentVersion)

	return nil
}
示例#29
0
func TestValidateVersion(t *testing.T) {
	t.Log("required min - pass")
	{
		requiredMin, err := ver.NewVersion("1.0.0")
		require.NoError(t, err)

		current, err := ver.NewVersion("1.0.1")
		require.NoError(t, err)

		err = validateVersion(*current, *requiredMin, nil)
		require.NoError(t, err)
	}

	t.Log("required min - fail")
	{
		requiredMin, err := ver.NewVersion("1.0.2")
		require.NoError(t, err)

		current, err := ver.NewVersion("1.0.1")
		require.NoError(t, err)

		err = validateVersion(*current, *requiredMin, nil)
		require.Error(t, err)
	}

	t.Log("required min + required max - pass")
	{
		requiredMin, err := ver.NewVersion("1.0.0")
		require.NoError(t, err)

		requiredMax, err := ver.NewVersion("1.0.2")
		require.NoError(t, err)

		current, err := ver.NewVersion("1.0.1")
		require.NoError(t, err)

		err = validateVersion(*current, *requiredMin, requiredMax)
		require.NoError(t, err)
	}

	t.Log("required min + required max - pass")
	{
		requiredMin, err := ver.NewVersion("1.0.0")
		require.NoError(t, err)

		requiredMax, err := ver.NewVersion("1.0.0")
		require.NoError(t, err)

		current, err := ver.NewVersion("1.0.0")
		require.NoError(t, err)

		err = validateVersion(*current, *requiredMin, requiredMax)
		require.NoError(t, err)
	}

	t.Log("required min + required max - min fail")
	{
		requiredMin, err := ver.NewVersion("1.0.1")
		require.NoError(t, err)

		requiredMax, err := ver.NewVersion("1.0.2")
		require.NoError(t, err)

		current, err := ver.NewVersion("1.0.0")
		require.NoError(t, err)

		err = validateVersion(*current, *requiredMin, requiredMax)
		require.Error(t, err)
	}

	t.Log("required min + required max - max fail")
	{
		requiredMin, err := ver.NewVersion("1.0.0")
		require.NoError(t, err)

		requiredMax, err := ver.NewVersion("1.0.1")
		require.NoError(t, err)

		current, err := ver.NewVersion("1.0.2")
		require.NoError(t, err)

		err = validateVersion(*current, *requiredMin, requiredMax)
		require.Error(t, err)
	}
}
示例#30
0
文件: api.go 项目: thomasf/alkasir
// Update list of blocked hosts for an IP address.
func GetUpgrade(dbclients db.Clients) func(w rest.ResponseWriter, r *rest.Request) {
	return func(w rest.ResponseWriter, r *rest.Request) {
		req := shared.BinaryUpgradeRequest{}
		err := r.DecodeJsonPayload(&req)
		// TODO: proper validation response
		if err != nil {
			apiError(w, err.Error(), http.StatusInternalServerError)
			return
		}
		if req.FromVersion == "" {
			apiError(w, "fromversion required", http.StatusInternalServerError)
			return
		}
		v, err := version.NewVersion(req.FromVersion)
		if err != nil {
			lg.Warningln(err)
			apiError(w, fmt.Sprintf("invalid fromVersion %s", req.FromVersion), http.StatusInternalServerError)
			return
		}

		if req.Artifact == "" {
			apiError(w, "artifact required", http.StatusInternalServerError)
			return

		}
		res, found, err := dbclients.DB.GetUpgrade(
			db.GetUpgradeQuery{
				Artifact: req.Artifact,
			})
		if err != nil {
			apiError(w, err.Error(), http.StatusInternalServerError)
			return
		}
		if !found {
			apiutils.WriteRestError(w,
				apierrors.NewNotFound(
					"upgrade", fmt.Sprintf("%s-%s", req.Artifact, req.FromVersion)))
			return
		}

		serverVersion, err := version.NewVersion(res.Version)
		if err != nil {
			apiError(w, err.Error(), http.StatusInternalServerError)
			return
		}
		if serverVersion.LessThan(v) || serverVersion.Equal(v) {
			apiutils.WriteRestError(w,
				apierrors.NewNotFound(
					"upgrade", fmt.Sprintf("%s-%s", req.Artifact, req.FromVersion)))
			return

		}
		w.WriteJson(shared.BinaryUpgradeResponse{
			Artifact:         res.Artifact,
			Version:          res.Version,
			CreatedAt:        res.CreatedAt,
			SHA256Sum:        res.SHA256Sum,
			ED25519Signature: res.ED25519Signature,
		})

	}
}