// upgradeOldAllocMutable upgrades Nomad 0.8 alloc runner state.
502099
func upgradeOldAllocMutable(tx *boltdd.Tx, allocID string, oldBytes []byte) error {
	var oldMutable allocRunnerMutableState08
	err := codec.NewDecoderBytes(oldBytes, structs.MsgpackHandle).Decode(&oldMutable)
	if err != nil {
		return err
	}

	// Upgrade Deployment Status
	if err := putDeploymentStatusImpl(tx, allocID, oldMutable.DeploymentStatus); err != nil {
		return err
	}

	// Upgrade Task States
	for taskName, taskState := range oldMutable.TaskStates {
		if err := putTaskStateImpl(tx, allocID, taskName, taskState); err != nil {
			return err
		}
	}

	return nil
}
1019499
func DryRunStaticPodUpgrade(internalcfg *kubeadmapi.InitConfiguration) error {

	dryRunManifestDir, err := constants.CreateTempDirForKubeadm("kubeadm-upgrade-dryrun")
	if err != nil {
		return err
	}
	defer os.RemoveAll(dryRunManifestDir)

	if err := controlplane.CreateInitStaticPodManifestFiles(dryRunManifestDir, internalcfg); err != nil {
		return err
	}

	// Print the contents of the upgraded manifests and pretend like they were in /etc/kubernetes/manifests
	files := []dryrunutil.FileToPrint{}
	for _, component := range constants.ControlPlaneComponents {
		realPath := constants.GetStaticPodFilepath(component, dryRunManifestDir)
		outputPath := constants.GetStaticPodFilepath(component, constants.GetStaticPodDirectory())
		files = append(files, dryrunutil.NewFileToPrint(realPath, outputPath))
	}

	return dryrunutil.PrintDryRunFiles(files, os.Stdout)
}
229863
func (m *Machine) UpgradeSeriesUnitStatuses() (map[string]UpgradeSeriesUnitStatus, error) {
	lock, err := m.getUpgradeSeriesLock()
	if err != nil {
		return nil, errors.Trace(err)
	}
	return lock.UnitStatuses, nil
}
170015
func (s *UpdateBrokerRequest) SetAutoMinorVersionUpgrade(v bool) *UpdateBrokerRequest {
	s.AutoMinorVersionUpgrade = &v
	return s
}
186064
func upgradeToVer3(s Session) {
	// Version 3 fix tx_read_only variable value.
	sql := fmt.Sprintf("UPDATE HIGH_PRIORITY %s.%s set variable_value = '0' where variable_name = 'tx_read_only';",
		mysql.SystemDB, mysql.GlobalVariablesTable)
	mustExecute(s, sql)
}
694213
func (n *nomadFSM) applyAllocUpdateDesiredTransition(buf []byte, index uint64) interface{} {
	defer metrics.MeasureSince([]string{"nomad", "fsm", "alloc_update_desired_transition"}, time.Now())
	var req structs.AllocUpdateDesiredTransitionRequest
	if err := structs.Decode(buf, &req); err != nil {
		panic(fmt.Errorf("failed to decode request: %v", err))
	}

	if err := n.state.UpdateAllocsDesiredTransitions(index, req.Allocs, req.Evals); err != nil {
		n.logger.Error("UpdateAllocsDesiredTransitions failed", "error", err)
		return err
	}

	n.handleUpsertedEvals(req.Evals)
	return nil
}
332919
func (tc *UpgradePathTC) BeforeAll(f *framework.F) {
	// Upgrade tests currently fail because the nomad binary isn't found by
	// discover.NomadExecutable().  Ensure that nomad binary is available
	// and discoverable and enable this test
	f.T().Skip("upgrade tests are expected to fail.  TODO: Fix")

	bin, err := discover.NomadExecutable()
	f.NoError(err)
	tc.bin = bin
	dir, err := ioutil.TempDir("", "")
	f.NoError(err)

	tc.binDir = dir
	for _, ver := range nomadVersions {
		verBin := filepath.Join(tc.binDir, ver)
		f.NoError(os.Mkdir(verBin, 0755))
		f.NoError(
			getter.Get(verBin, fmt.Sprintf(
				"https://releases.hashicorp.com/nomad/%s/nomad_%s_linux_amd64.zip",
				ver, ver,
			)))
		f.T().Logf("downloaded nomad version %s to %s", ver, verBin)
	}
}
448520
func (k *kubernetesClient) Upgrade(appName string, vers version.Number) error {
	var resourceName string
	if appName == JujuControllerStackName {
		// upgrading controller.
		resourceName = appName
	} else {
		// upgrading operator.
		resourceName = k.operatorName(appName)
	}
	logger.Debugf("Upgrading %q", resourceName)

	statefulsets := k.client().AppsV1().StatefulSets(k.namespace)
	existingStatefulSet, err := statefulsets.Get(resourceName, v1.GetOptions{IncludeUninitialized: true})
	if err != nil && !k8serrors.IsNotFound(err) {
		return errors.Trace(err)
	}
	// TODO(wallyworld) - only support stateful set at the moment
	if err != nil {
		return errors.NotSupportedf("upgrading %v", appName)
	}
	for i, c := range existingStatefulSet.Spec.Template.Spec.Containers {
		if !podcfg.IsJujuOCIImage(c.Image) {
			continue
		}
		tagSep := strings.LastIndex(c.Image, ":")
		c.Image = fmt.Sprintf("%s:%s", c.Image[:tagSep], vers.String())
		existingStatefulSet.Spec.Template.Spec.Containers[i] = c
	}
	_, err = statefulsets.Update(existingStatefulSet)
	return errors.Trace(err)
}
840808
func GetAvailableUpgrades(versionGetterImpl VersionGetter, experimentalUpgradesAllowed, rcUpgradesAllowed bool, etcdClient etcdutil.ClusterInterrogator, dnsType kubeadmapi.DNSAddOnType, client clientset.Interface) ([]Upgrade, error) {
	fmt.Println("[upgrade] Fetching available versions to upgrade to")

	// Collect the upgrades kubeadm can do in this list
	upgrades := []Upgrade{}

	// Get the cluster version
	clusterVersionStr, clusterVersion, err := versionGetterImpl.ClusterVersion()
	if err != nil {
		return upgrades, err
	}

	// Get current kubeadm CLI version
	kubeadmVersionStr, kubeadmVersion, err := versionGetterImpl.KubeadmVersion()
	if err != nil {
		return upgrades, err
	}

	// Get and output the current latest stable version
	stableVersionStr, stableVersion, err := versionGetterImpl.VersionFromCILabel("stable", "stable version")
	if err != nil {
		fmt.Printf("[upgrade/versions] WARNING: %v\n", err)
		fmt.Println("[upgrade/versions] WARNING: Falling back to current kubeadm version as latest stable version")
		stableVersionStr, stableVersion = kubeadmVersionStr, kubeadmVersion
	}

	// Get the kubelet versions in the cluster
	kubeletVersions, err := versionGetterImpl.KubeletVersions()
	if err != nil {
		return upgrades, err
	}

	// Get current etcd version
	etcdVersion, err := etcdClient.GetVersion()
	if err != nil {
		return upgrades, err
	}

	currentDNSType, dnsVersion, err := dns.DeployedDNSAddon(client)
	if err != nil {
		return nil, err
	}

	// Construct a descriptor for the current state of the world
	beforeState := ClusterState{
		KubeVersion:     clusterVersionStr,
		DNSType:         currentDNSType,
		DNSVersion:      dnsVersion,
		KubeadmVersion:  kubeadmVersionStr,
		KubeletVersions: kubeletVersions,
		EtcdVersion:     etcdVersion,
	}

	// Do a "dumb guess" that a new minor upgrade is available just because the latest stable version is higher than the cluster version
	// This guess will be corrected once we know if there is a patch version available
	canDoMinorUpgrade := clusterVersion.LessThan(stableVersion)

	// A patch version doesn't exist if the cluster version is higher than or equal to the current stable version
	// in the case that a user is trying to upgrade from, let's say, v1.8.0-beta.2 to v1.8.0-rc.1 (given we support such upgrades experimentally)
	// a stable-1.8 branch doesn't exist yet. Hence this check.
	if patchVersionBranchExists(clusterVersion, stableVersion) {
		currentBranch := getBranchFromVersion(clusterVersionStr)
		versionLabel := fmt.Sprintf("stable-%s", currentBranch)
		description := fmt.Sprintf("version in the v%s series", currentBranch)

		// Get and output the latest patch version for the cluster branch
		patchVersionStr, patchVersion, err := versionGetterImpl.VersionFromCILabel(versionLabel, description)
		if err != nil {
			fmt.Printf("[upgrade/versions] WARNING: %v\n", err)
		} else {
			// Check if a minor version upgrade is possible when a patch release exists
			// It's only possible if the latest patch version is higher than the current patch version
			// If that's the case, they must be on different branches => a newer minor version can be upgraded to
			canDoMinorUpgrade = minorUpgradePossibleWithPatchRelease(stableVersion, patchVersion)

			// If the cluster version is lower than the newest patch version, we should inform about the possible upgrade
			if patchUpgradePossible(clusterVersion, patchVersion) {

				// The kubeadm version has to be upgraded to the latest patch version
				newKubeadmVer := patchVersionStr
				if kubeadmVersion.AtLeast(patchVersion) {
					// In this case, the kubeadm CLI version is new enough. Don't display an update suggestion for kubeadm by making .NewKubeadmVersion equal .CurrentKubeadmVersion
					newKubeadmVer = kubeadmVersionStr
				}

				upgrades = append(upgrades, Upgrade{
					Description: description,
					Before:      beforeState,
					After: ClusterState{
						KubeVersion:    patchVersionStr,
						DNSType:        dnsType,
						DNSVersion:     kubeadmconstants.GetDNSVersion(dnsType),
						KubeadmVersion: newKubeadmVer,
						EtcdVersion:    getSuggestedEtcdVersion(patchVersionStr),
						// KubeletVersions is unset here as it is not used anywhere in .After
					},
				})
			}
		}
	}

	if canDoMinorUpgrade {
		upgrades = append(upgrades, Upgrade{
			Description: "stable version",
			Before:      beforeState,
			After: ClusterState{
				KubeVersion:    stableVersionStr,
				DNSType:        dnsType,
				DNSVersion:     kubeadmconstants.GetDNSVersion(dnsType),
				KubeadmVersion: stableVersionStr,
				EtcdVersion:    getSuggestedEtcdVersion(stableVersionStr),
				// KubeletVersions is unset here as it is not used anywhere in .After
			},
		})
	}

	if experimentalUpgradesAllowed || rcUpgradesAllowed {
		// dl.k8s.io/release/latest.txt is ALWAYS an alpha.X version
		// dl.k8s.io/release/latest-1.X.txt is first v1.X.0-alpha.0 -> v1.X.0-alpha.Y, then v1.X.0-beta.0 to v1.X.0-beta.Z, then v1.X.0-rc.1 to v1.X.0-rc.W.
		// After the v1.X.0 release, latest-1.X.txt is always a beta.0 version. Let's say the latest stable version on the v1.7 branch is v1.7.3, then the
		// latest-1.7 version is v1.7.4-beta.0

		// Worth noticing is that when the release-1.X branch is cut; there are two versions tagged: v1.X.0-beta.0 AND v1.(X+1).alpha.0
		// The v1.(X+1).alpha.0 is pretty much useless and should just be ignored, as more betas may be released that have more features than the initial v1.(X+1).alpha.0

		// So what we do below is getting the latest overall version, always an v1.X.0-alpha.Y version. Then we get latest-1.(X-1) version. This version may be anything
		// between v1.(X-1).0-beta.0 and v1.(X-1).Z-beta.0. At some point in time, latest-1.(X-1) will point to v1.(X-1).0-rc.1. Then we should show it.

		// The flow looks like this (with time on the X axis):
		// v1.8.0-alpha.1 -> v1.8.0-alpha.2 -> v1.8.0-alpha.3 | release-1.8 branch | v1.8.0-beta.0 -> v1.8.0-beta.1 -> v1.8.0-beta.2 -> v1.8.0-rc.1 -> v1.8.0 -> v1.8.1
		//                                                                           v1.9.0-alpha.0                                             -> v1.9.0-alpha.1 -> v1.9.0-alpha.2

		// Get and output the current latest unstable version
		latestVersionStr, latestVersion, err := versionGetterImpl.VersionFromCILabel("latest", "experimental version")
		if err != nil {
			return upgrades, err
		}

		minorUnstable := latestVersion.Components()[1]
		// Get and output the current latest unstable version
		previousBranch := fmt.Sprintf("latest-1.%d", minorUnstable-1)
		previousBranchLatestVersionStr, previousBranchLatestVersion, err := versionGetterImpl.VersionFromCILabel(previousBranch, "")
		if err != nil {
			return upgrades, err
		}

		// If that previous latest version is an RC, RCs are allowed and the cluster version is lower than the RC version, show the upgrade
		if rcUpgradesAllowed && rcUpgradePossible(clusterVersion, previousBranchLatestVersion) {
			upgrades = append(upgrades, Upgrade{
				Description: "release candidate version",
				Before:      beforeState,
				After: ClusterState{
					KubeVersion:    previousBranchLatestVersionStr,
					DNSType:        dnsType,
					DNSVersion:     kubeadmconstants.GetDNSVersion(dnsType),
					KubeadmVersion: previousBranchLatestVersionStr,
					EtcdVersion:    getSuggestedEtcdVersion(previousBranchLatestVersionStr),
					// KubeletVersions is unset here as it is not used anywhere in .After
				},
			})
		}

		// Show the possibility if experimental upgrades are allowed
		if experimentalUpgradesAllowed && clusterVersion.LessThan(latestVersion) {

			// Default to assume that the experimental version to show is the unstable one
			unstableKubeVersion := latestVersionStr
			unstableKubeDNSVersion := kubeadmconstants.GetDNSVersion(dnsType)

			// Ẃe should not display alpha.0. The previous branch's beta/rc versions are more relevant due how the kube branching process works.
			if latestVersion.PreRelease() == "alpha.0" {
				unstableKubeVersion = previousBranchLatestVersionStr
				unstableKubeDNSVersion = kubeadmconstants.GetDNSVersion(dnsType)
			}

			upgrades = append(upgrades, Upgrade{
				Description: "experimental version",
				Before:      beforeState,
				After: ClusterState{
					KubeVersion:    unstableKubeVersion,
					DNSType:        dnsType,
					DNSVersion:     unstableKubeDNSVersion,
					KubeadmVersion: unstableKubeVersion,
					EtcdVersion:    getSuggestedEtcdVersion(unstableKubeVersion),
					// KubeletVersions is unset here as it is not used anywhere in .After
				},
			})
		}
	}

	// Add a newline in the end of this output to leave some space to the next output section
	fmt.Println("")

	return upgrades, nil
}
503870
func (n *managedNode) UpgradeSoftwareVersion(version string) (bool, error) {
	n.Lock()
	defer n.Unlock()
	ctx, _ := context.WithTimeout(context.Background(), DEFAULT_CTX_TIMEOUT)
	status, err := n.client.SelfUpgrade(ctx, &cc.SelfUpgradeMsg{Version: version})
	return status.Status, err
}
1034891
func upgradeToVersion2(ns walletdb.ReadWriteBucket) error {
	currentMgrVersion := uint32(2)

	_, err := ns.CreateBucketIfNotExists(usedAddrBucketName)
	if err != nil {
		str := "failed to create used addresses bucket"
		return managerError(ErrDatabase, str, err)
	}

	return putManagerVersion(ns, currentMgrVersion)
}
284950
func (c *Client) addAlloc(alloc *structs.Allocation, migrateToken string) error {
	c.allocLock.Lock()
	defer c.allocLock.Unlock()

	// Check if we already have an alloc runner
	if _, ok := c.allocs[alloc.ID]; ok {
		c.logger.Debug("dropping duplicate add allocation request", "alloc_id", alloc.ID)
		return nil
	}

	// Initialize local copy of alloc before creating the alloc runner so
	// we can't end up with an alloc runner that does not have an alloc.
	if err := c.stateDB.PutAllocation(alloc); err != nil {
		return err
	}

	// Collect any preempted allocations to pass into the previous alloc watcher
	var preemptedAllocs map[string]allocwatcher.AllocRunnerMeta
	if len(alloc.PreemptedAllocations) > 0 {
		preemptedAllocs = make(map[string]allocwatcher.AllocRunnerMeta)
		for _, palloc := range alloc.PreemptedAllocations {
			preemptedAllocs[palloc] = c.allocs[palloc]
		}
	}

	// Since only the Client has access to other AllocRunners and the RPC
	// client, create the previous allocation watcher here.
	watcherConfig := allocwatcher.Config{
		Alloc:            alloc,
		PreviousRunner:   c.allocs[alloc.PreviousAllocation],
		PreemptedRunners: preemptedAllocs,
		RPC:              c,
		Config:           c.configCopy,
		MigrateToken:     migrateToken,
		Logger:           c.logger,
	}
	prevAllocWatcher, prevAllocMigrator := allocwatcher.NewAllocWatcher(watcherConfig)

	// Copy the config since the node can be swapped out as it is being updated.
	// The long term fix is to pass in the config and node separately and then
	// we don't have to do a copy.
	c.configLock.RLock()
	arConf := &allocrunner.Config{
		Alloc:               alloc,
		Logger:              c.logger,
		ClientConfig:        c.configCopy,
		StateDB:             c.stateDB,
		Consul:              c.consulService,
		Vault:               c.vaultClient,
		StateUpdater:        c,
		DeviceStatsReporter: c,
		PrevAllocWatcher:    prevAllocWatcher,
		PrevAllocMigrator:   prevAllocMigrator,
		DeviceManager:       c.devicemanager,
		DriverManager:       c.drivermanager,
	}
	c.configLock.RUnlock()

	ar, err := allocrunner.NewAllocRunner(arConf)
	if err != nil {
		return err
	}

	// Store the alloc runner.
	c.allocs[alloc.ID] = ar

	go ar.Run()
	return nil
}
981763
func (c *Client) AllocStateUpdated(alloc *structs.Allocation) {
	if alloc.Terminated() {
		// Terminated, mark for GC if we're still tracking this alloc
		// runner. If it's not being tracked that means the server has
		// already GC'd it (see removeAlloc).
		ar, err := c.getAllocRunner(alloc.ID)

		if err == nil {
			c.garbageCollector.MarkForCollection(alloc.ID, ar)

			// Trigger a GC in case we're over thresholds and just
			// waiting for eligible allocs.
			c.garbageCollector.Trigger()
		}
	}

	// Strip all the information that can be reconstructed at the server.  Only
	// send the fields that are updatable by the client.
	stripped := new(structs.Allocation)
	stripped.ID = alloc.ID
	stripped.NodeID = c.NodeID()
	stripped.TaskStates = alloc.TaskStates
	stripped.ClientStatus = alloc.ClientStatus
	stripped.ClientDescription = alloc.ClientDescription
	stripped.DeploymentStatus = alloc.DeploymentStatus

	select {
	case c.allocUpdates <- stripped:
	case <-c.shutdownCh:
	}
}
791947
func (w *deploymentWatcher) handleAllocUpdate(allocs []*structs.AllocListStub) (allocUpdateResult, error) {
	var res allocUpdateResult

	// Get the latest evaluation index
	latestEval, err := w.jobEvalStatus()
	if err != nil {
		if err == context.Canceled || w.ctx.Err() == context.Canceled {
			return res, err
		}

		return res, fmt.Errorf("failed to determine last evaluation index for job %q: %v", w.j.ID, err)
	}

	deployment := w.getDeployment()
	for _, alloc := range allocs {
		dstate, ok := deployment.TaskGroups[alloc.TaskGroup]
		if !ok {
			continue
		}

		// Determine if the update stanza for this group is progress based
		progressBased := dstate.ProgressDeadline != 0

		// Check if the allocation has failed and we need to mark it for allow
		// replacements
		if progressBased && alloc.DeploymentStatus.IsUnhealthy() &&
			deployment.Active() && !alloc.DesiredTransition.ShouldReschedule() {
			res.allowReplacements = append(res.allowReplacements, alloc.ID)
			continue
		}

		// We need to create an eval so the job can progress.
		if alloc.DeploymentStatus.IsHealthy() && alloc.DeploymentStatus.ModifyIndex > latestEval {
			res.createEval = true
		}

		// If the group is using a progress deadline, we don't have to do anything.
		if progressBased {
			continue
		}

		// Fail on the first bad allocation
		if alloc.DeploymentStatus.IsUnhealthy() {
			// Check if the group has autorevert set
			if dstate.AutoRevert {
				res.rollback = true
			}

			// Since we have an unhealthy allocation, fail the deployment
			res.failDeployment = true
		}

		// All conditions have been hit so we can break
		if res.createEval && res.failDeployment && res.rollback {
			break
		}
	}

	return res, nil
}
708114
func upgrade(mgr Manager) error {
	// We'll start by fetching the service's current and latest version.
	ns := mgr.Namespace()
	currentVersion, err := mgr.CurrentVersion(ns)
	if err != nil {
		return err
	}
	versions := mgr.Versions()
	latestVersion := GetLatestVersion(versions)

	switch {
	// If the current version is greater than the latest, then the service
	// is attempting to revert to a previous version that's possibly
	// backwards-incompatible. To prevent this, we'll return an error
	// indicating so.
	case currentVersion > latestVersion:
		return ErrReversion

	// If the current version is behind the latest version, we'll need to
	// apply all of the newer versions in order to catch up to the latest.
	case currentVersion < latestVersion:
		versions := VersionsToApply(currentVersion, versions)
		mgrName := mgr.Name()
		ns := mgr.Namespace()

		for _, version := range versions {
			log.Infof("Applying %v migration #%d", mgrName,
				version.Number)

			// We'll only run a migration if there is one available
			// for this version.
			if version.Migration != nil {
				err := version.Migration(ns)
				if err != nil {
					log.Errorf("Unable to apply %v "+
						"migration #%d: %v", mgrName,
						version.Number, err)
					return err
				}
			}
		}

		// With all of the versions applied, we can now reflect the
		// latest version upon the service.
		if err := mgr.SetVersion(ns, latestVersion); err != nil {
			return err
		}

	// If the current version matches the latest one, there's no upgrade
	// needed and we can safely exit.
	case currentVersion == latestVersion:
	}

	return nil
}
359189
func UpgradeRequired(w http.ResponseWriter, response interface{}) {
	Respond(w, http.StatusUpgradeRequired, response)
}
1207515
func (h *Hook) Upgrade() error {
	match, err := h.matchesCurrent()
	if err != nil {
		return err
	}

	if !match {
		return nil
	}

	return h.write()
}