// Determines if a given InstanceState needs to be migrated by checking the
// stored version number with the current SchemaVersion
432500
func (r *Resource) checkSchemaVersion(is *terraform.InstanceState) (bool, int) {
	// Get the raw interface{} value for the schema version. If it doesn't
	// exist or is nil then set it to zero.
	raw := is.Meta["schema_version"]
	if raw == nil {
		raw = "0"
	}

	// Try to convert it to a string. If it isn't a string then we pretend
	// that it isn't set at all. It should never not be a string unless it
	// was manually tampered with.
	rawString, ok := raw.(string)
	if !ok {
		rawString = "0"
	}

	stateSchemaVersion, _ := strconv.Atoi(rawString)

	// Don't run MigrateState if the version is handled by a StateUpgrader,
	// since StateMigrateFuncs are not required to handle unknown versions
	maxVersion := r.SchemaVersion
	if len(r.StateUpgraders) > 0 {
		maxVersion = r.StateUpgraders[0].Version
	}

	return stateSchemaVersion < maxVersion, stateSchemaVersion
}
122904
func (ts *Server) MigrateServedType(ctx context.Context, keyspace string, shardsToAdd, shardsToRemove []*ShardInfo, tabletType topodatapb.TabletType, cells []string) (err error) {
	if err = CheckKeyspaceLocked(ctx, keyspace); err != nil {
		return err
	}

	// The caller intents to update all cells in this case
	if len(cells) == 0 {
		cells, err = ts.GetCellInfoNames(ctx)
		if err != nil {
			return err
		}
	}

	wg := sync.WaitGroup{}
	rec := concurrency.AllErrorRecorder{}
	for _, cell := range cells {
		wg.Add(1)
		go func(cell, keyspace string) {
			defer wg.Done()
			srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace)
			switch {
			case err == nil:
				for _, partition := range srvKeyspace.GetPartitions() {

					// We are finishing the migration, cleaning up tablet controls from the srvKeyspace
					if tabletType == topodatapb.TabletType_MASTER {
						partition.ShardTabletControls = nil
					}

					if partition.GetServedType() != tabletType {
						continue
					}

					shardReferences := make([]*topodatapb.ShardReference, 0)

					for _, shardReference := range partition.GetShardReferences() {
						inShardsToRemove := false
						for _, si := range shardsToRemove {
							if key.KeyRangeEqual(shardReference.GetKeyRange(), si.GetKeyRange()) {
								inShardsToRemove = true
								break
							}
						}

						if !inShardsToRemove {
							shardReferences = append(shardReferences, shardReference)
						}
					}

					for _, si := range shardsToAdd {
						alreadyAdded := false
						for _, shardReference := range partition.GetShardReferences() {
							if key.KeyRangeEqual(shardReference.GetKeyRange(), si.GetKeyRange()) {
								alreadyAdded = true
								break
							}
						}

						if !alreadyAdded {
							shardReference := &topodatapb.ShardReference{
								Name:     si.ShardName(),
								KeyRange: si.KeyRange,
							}
							shardReferences = append(shardReferences, shardReference)
						}
					}

					partition.ShardReferences = shardReferences
				}

				if err := OrderAndCheckPartitions(cell, srvKeyspace); err != nil {
					rec.RecordError(err)
					return
				}

				err = ts.UpdateSrvKeyspace(ctx, cell, keyspace, srvKeyspace)
				if err != nil {
					rec.RecordError(err)
					return
				}

			case IsErrType(err, NoNode):
				// Assuming this cell is not active, nothing to do.
			default:
				if err != nil {
					rec.RecordError(err)
					return
				}
			}
		}(cell, keyspace)
	}
	wg.Wait()
	if rec.HasErrors() {
		return NewError(PartialResult, rec.Error().Error())
	}
	return nil
}
1047653
func (cs *CSCloud) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error) {
	_, count, err := cs.client.VirtualMachine.GetVirtualMachineByID(
		providerID,
		cloudstack.WithProject(cs.projectID),
	)
	if err != nil {
		if count == 0 {
			return false, nil
		}
		return false, fmt.Errorf("error retrieving instance: %v", err)
	}

	return true, nil
}
149151
func (vdb *VersionedDB) GetStateRangeScanIteratorWithMetadata(namespace string, startKey string, endKey string, metadata map[string]interface{}) (statedb.QueryResultsIterator, error) {
	logger.Debugf("Entering GetStateRangeScanIteratorWithMetadata  namespace: %s  startKey: %s  endKey: %s  metadata: %v", namespace, startKey, endKey, metadata)
	// Get the internalQueryLimit from core.yaml
	internalQueryLimit := int32(ledgerconfig.GetInternalQueryLimit())
	requestedLimit := int32(0)
	// if metadata is provided, validate and apply options
	if metadata != nil {
		//validate the metadata
		err := statedb.ValidateRangeMetadata(metadata)
		if err != nil {
			return nil, err
		}
		if limitOption, ok := metadata[optionLimit]; ok {
			requestedLimit = limitOption.(int32)
		}
	}
	db, err := vdb.getNamespaceDBHandle(namespace)
	if err != nil {
		return nil, err
	}
	return newQueryScanner(namespace, db, "", internalQueryLimit, requestedLimit, "", startKey, endKey)
}
237142
func ValidateStatefulSetUpdate(statefulSet, oldStatefulSet *apps.StatefulSet) field.ErrorList {
	allErrs := apivalidation.ValidateObjectMetaUpdate(&statefulSet.ObjectMeta, &oldStatefulSet.ObjectMeta, field.NewPath("metadata"))

	restoreReplicas := statefulSet.Spec.Replicas
	statefulSet.Spec.Replicas = oldStatefulSet.Spec.Replicas

	restoreTemplate := statefulSet.Spec.Template
	statefulSet.Spec.Template = oldStatefulSet.Spec.Template

	restoreStrategy := statefulSet.Spec.UpdateStrategy
	statefulSet.Spec.UpdateStrategy = oldStatefulSet.Spec.UpdateStrategy

	if !apiequality.Semantic.DeepEqual(statefulSet.Spec, oldStatefulSet.Spec) {
		allErrs = append(allErrs, field.Forbidden(field.NewPath("spec"), "updates to statefulset spec for fields other than 'replicas', 'template', and 'updateStrategy' are forbidden"))
	}
	statefulSet.Spec.Replicas = restoreReplicas
	statefulSet.Spec.Template = restoreTemplate
	statefulSet.Spec.UpdateStrategy = restoreStrategy

	allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(statefulSet.Spec.Replicas), field.NewPath("spec", "replicas"))...)
	return allErrs
}
778279
func CheckInstanceExists(c context.Context, inst *Instance) error {
	switch err := datastore.Get(c, inst); {
	case err == datastore.ErrNoSuchEntity:
		// Maybe the package is missing completely?
		if err := CheckPackageExists(c, inst.Package.StringID()); err != nil {
			return err
		}
		return errors.Reason("no such instance").Tag(grpcutil.NotFoundTag).Err()
	case err != nil:
		return errors.Annotate(err, "failed to check the instance presence").Tag(transient.Tag).Err()
	default:
		return nil
	}
}
1326978
func InstanceStateRefreshFunc(conn *ec2.EC2, instanceID string, failStates []string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		resp, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{
			InstanceIds: []*string{aws.String(instanceID)},
		})
		if err != nil {
			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidInstanceID.NotFound" {
				// Set this to nil as if we didn't find anything.
				resp = nil
			} else {
				log.Printf("Error on InstanceStateRefresh: %s", err)
				return nil, "", err
			}
		}

		if resp == nil || len(resp.Reservations) == 0 || len(resp.Reservations[0].Instances) == 0 {
			// Sometimes AWS just has consistency issues and doesn't see
			// our instance yet. Return an empty state.
			return nil, "", nil
		}

		i := resp.Reservations[0].Instances[0]
		state := *i.State.Name

		for _, failState := range failStates {
			if state == failState {
				return i, state, fmt.Errorf("Failed to reach target state. Reason: %s",
					stringifyStateReason(i.StateReason))
			}
		}

		return i, state, nil
	}
}
483772
func (s *schemaVersionSyncer) MustGetGlobalVersion(ctx context.Context) (int64, error) {
	startTime := time.Now()
	var (
		err  error
		ver  int
		resp *clientv3.GetResponse
	)
	failedCnt := 0
	intervalCnt := int(time.Second / keyOpRetryInterval)

	defer func() {
		metrics.OwnerHandleSyncerHistogram.WithLabelValues(metrics.OwnerGetGlobalVersion, metrics.RetLabel(err)).Observe(time.Since(startTime).Seconds())
	}()
	for {
		if err != nil {
			if failedCnt%intervalCnt == 0 {
				logutil.Logger(ddlLogCtx).Info("[ddl] syncer get global version failed", zap.Error(err))
			}
			time.Sleep(keyOpRetryInterval)
			failedCnt++
		}

		if isContextDone(ctx) {
			err = errors.Trace(ctx.Err())
			return 0, err
		}

		resp, err = s.etcdCli.Get(ctx, DDLGlobalSchemaVersion)
		if err != nil {
			continue
		}
		if len(resp.Kvs) > 0 {
			ver, err = strconv.Atoi(string(resp.Kvs[0].Value))
			if err == nil {
				return int64(ver), nil
			}
		}
	}
}
182809
func IsVersionInconsistentError(e interface{}) bool {
	value := e
	// In case of a wrapped error, check the cause first.
	cause := errors.Cause(e.(error))
	if cause != nil {
		value = cause
	}
	_, ok := value.(*versionInconsistentError)
	return ok
}
879341
func (env *azureEnviron) getInstanceTypesLocked(ctx context.ProviderCallContext) (map[string]instances.InstanceType, error) {
	if env.instanceTypes != nil {
		return env.instanceTypes, nil
	}

	location := env.location
	client := compute.VirtualMachineSizesClient{env.compute}

	result, err := client.List(stdcontext.Background(), location)
	if err != nil {
		return nil, errorutils.HandleCredentialError(errors.Annotate(err, "listing VM sizes"), ctx)
	}
	instanceTypes := make(map[string]instances.InstanceType)
	if result.Value != nil {
		for _, size := range *result.Value {
			instanceType := newInstanceType(size)
			instanceTypes[instanceType.Name] = instanceType
			// Create aliases for standard role sizes.
			if strings.HasPrefix(instanceType.Name, "Standard_") {
				instanceTypes[instanceType.Name[len("Standard_"):]] = instanceType
			}
		}
	}
	env.instanceTypes = instanceTypes
	return instanceTypes, nil
}
1282006
func IsValid(senml SenML) bool {
	var bname string = ""
	var bver = -1

	//fmt.Println("In Validate")

	for _, r := range senml.Records {

		// Check version is same for all records
		if bver == -1 {
			// set the bver the first time it is seen
			if r.BaseVersion != 0 {
				bver = r.BaseVersion
			}
		} else {
			if r.BaseVersion != 0 {
				// next time a version in seen, check it has not changed
				if r.BaseVersion != bver {
					//fmt.Println("unallowed version change ")
					return false
				}
			}
		}

		// Check name
		if len(r.BaseName) > 0 {
			bname = r.BaseName
		}
		name := bname + r.Name
		if len(name) == 0 {
			//fmt.Println("empty name")

			return false
		}
		if (name[0] == '-') || (name[0] == ':') || (name[0] == '.') || (name[0] == '/') || (name[0] == '_') {
			//fmt.Println("Bad first char in name")
			return false
		}
		for _, l := range name {
			if (l < 'a' || l > 'z') && (l < 'A' || l > 'Z') && (l < '0' || l > '9') && (l != '-') && (l != ':') && (l != '.') && (l != '/') && (l != '_') {
				//fmt.Println("Bad char in name")
				return false
			}
		}

		valueCount := 0
		if r.Value != nil {
			valueCount = valueCount + 1
		}
		if r.BoolValue != nil {
			valueCount = valueCount + 1
		}
		if len(r.DataValue) > 0 {
			valueCount = valueCount + 1
		}
		if len(r.StringValue) > 0 {
			valueCount = valueCount + 1
		}
		if valueCount > 1 {
			//fmt.Println("Too many values ")
			return false
		}
		if r.Sum != nil {
			valueCount = valueCount + 1
		}
		if valueCount < 1 {
			//fmt.Println("No value or sum")
			return false
		}

		// Check if name is known Mandatory To Understand
		//for k :=  r {
		// 	fmt.Println( "key=" , k  )
		//         if k[ len(k)-1 ] == '_' {
		//         	fmt.Println("unknown MTU in record")
		//		return false
		//        }
		// }
	}

	return true
}
610764
func IsVersionGreaterOrEqual(verBase, verLower string) (bool, error) {
	r1, err := CompareVersions(verBase, verLower)
	if err != nil {
		return false, err
	}
	if r1 == 1 {
		return false, nil
	}

	return true, nil
}
1124562
func (e *environ) AllInstancesByState(ctx context.ProviderCallContext, states ...string) ([]instances.Instance, error) {
	// NOTE(axw) we use security group filtering here because instances
	// start out untagged. If Juju were to abort after starting an instance,
	// but before tagging it, it would be leaked. We only need to do this
	// for AllInstances, as it is the result of AllInstances that is used
	// in "harvesting" unknown instances by the provisioner.
	//
	// One possible alternative is to modify ec2.RunInstances to allow the
	// caller to specify ClientToken, and then format it like
	//     <controller-uuid>:<model-uuid>:<machine-id>
	//     (with base64-encoding to keep the size under the 64-byte limit)
	//
	// It is possible to filter on "client-token", and specify wildcards;
	// therefore we could use client-token filters everywhere in the ec2
	// provider instead of tags or security groups. The only danger is if
	// we need to make non-idempotent calls to RunInstances for the machine
	// ID. I don't think this is needed, but I am not confident enough to
	// change this fundamental right now.
	//
	// An EC2 API call is required to resolve the group name to an id, as
	// VPC enabled accounts do not support name based filtering.
	groupName := e.jujuGroupName()
	group, err := e.groupByName(ctx, groupName)
	if isNotFoundError(err) {
		// If there's no group, then there cannot be any instances.
		return nil, nil
	} else if err != nil {
		return nil, errors.Trace(maybeConvertCredentialError(err, ctx))
	}
	filter := ec2.NewFilter()
	filter.Add("instance-state-name", states...)
	filter.Add("instance.group-id", group.Id)
	return e.allInstances(ctx, filter)
}
1261794
func IsMigrationComplete(db *bolt.DB, id string) (bool, error) {
	complete := false
	if err := db.View(func(tx *bolt.Tx) error {
		migration := tx.Bucket(SchemaVersionBucket).Get([]byte(id))
		if migration != nil {
			complete = true
		}
		return nil
	}); err != nil {
		return true, err
	}

	return complete, nil
}
1155026
func (wr *Wrangler) ValidateVersionShard(ctx context.Context, keyspace, shard string) error {
	si, err := wr.ts.GetShard(ctx, keyspace, shard)
	if err != nil {
		return err
	}

	// get version from the master, or error
	if !si.HasMaster() {
		return fmt.Errorf("no master in shard %v/%v", keyspace, shard)
	}
	log.Infof("Gathering version for master %v", topoproto.TabletAliasString(si.MasterAlias))
	masterVersion, err := wr.GetVersion(ctx, si.MasterAlias)
	if err != nil {
		return err
	}

	// read all the aliases in the shard, that is all tablets that are
	// replicating from the master
	aliases, err := wr.ts.FindAllTabletAliasesInShard(ctx, keyspace, shard)
	if err != nil {
		return err
	}

	// then diff with all slaves
	er := concurrency.AllErrorRecorder{}
	wg := sync.WaitGroup{}
	for _, alias := range aliases {
		if topoproto.TabletAliasEqual(alias, si.MasterAlias) {
			continue
		}

		wg.Add(1)
		go wr.diffVersion(ctx, masterVersion, si.MasterAlias, alias, &wg, &er)
	}
	wg.Wait()
	if er.HasErrors() {
		return fmt.Errorf("version diffs: %v", er.Error().Error())
	}
	return nil
}
946719
func (db *schemaUpdater) updateSchema6to7() {
	t := db.newReadWriteTransaction()
	defer t.close()

	var gk []byte
	var nk []byte

	for _, folderStr := range db.ListFolders() {
		folder := []byte(folderStr)
		db.withNeedLocal(folder, false, func(f FileIntf) bool {
			name := []byte(f.FileName())
			global := f.(protocol.FileInfo)
			gk = db.keyer.GenerateGlobalVersionKey(gk, folder, name)
			svl, err := t.Get(gk, nil)
			if err != nil {
				// If there is no global list, we hardly need it.
				t.Delete(t.keyer.GenerateNeedFileKey(nk, folder, name))
				return true
			}
			var fl VersionList
			err = fl.Unmarshal(svl)
			if err != nil {
				// This can't happen, but it's ignored everywhere else too,
				// so lets not act on it.
				return true
			}
			if localFV, haveLocalFV := fl.Get(protocol.LocalDeviceID[:]); !need(global, haveLocalFV, localFV.Version) {
				t.Delete(t.keyer.GenerateNeedFileKey(nk, folder, name))
			}
			return true
		})
	}
}
272747
func (s *schemaVersionSyncer) UpdateSelfVersion(ctx context.Context, version int64) error {
	startTime := time.Now()
	ver := strconv.FormatInt(version, 10)
	err := PutKVToEtcd(ctx, s.etcdCli, putKeyNoRetry, s.selfSchemaVerPath, ver,
		clientv3.WithLease(s.loadSession().Lease()))

	metrics.UpdateSelfVersionHistogram.WithLabelValues(metrics.RetLabel(err)).Observe(time.Since(startTime).Seconds())
	return errors.Trace(err)
}