// ValidateNew checks if a new bundle's contained configuration is valid to be derived from the current bundle.
// This allows checks of the nature "Make sure that the consensus type did not change".
199846
func (b *Bundle) ValidateNew(nb Resources) error {
	if oc, ok := b.OrdererConfig(); ok {
		noc, ok := nb.OrdererConfig()
		if !ok {
			return errors.New("current config has orderer section, but new config does not")
		}

		// Prevent consensus-type migration when capabilities Kafka2RaftMigration is disabled
		if !oc.Capabilities().Kafka2RaftMigration() {
			if oc.ConsensusType() != noc.ConsensusType() {
				return errors.Errorf("attempted to change consensus type from %s to %s",
					oc.ConsensusType(), noc.ConsensusType())
			}
			if noc.ConsensusMigrationState() != ab.ConsensusType_MIG_STATE_NONE || noc.ConsensusMigrationContext() != 0 {
				return errors.Errorf("new config has unexpected consensus-migration state or context: (%s/%d) should be (MIG_STATE_NONE/0)",
					noc.ConsensusMigrationState().String(), noc.ConsensusMigrationContext())
			}
		} else {
			if err := b.validateMigrationStep(oc, noc); err != nil {
				return err
			}
		}

		for orgName, org := range oc.Organizations() {
			norg, ok := noc.Organizations()[orgName]
			if !ok {
				continue
			}
			mspID := org.MSPID()
			if mspID != norg.MSPID() {
				return errors.Errorf("orderer org %s attempted to change MSP ID from %s to %s", orgName, mspID, norg.MSPID())
			}
		}
	}

	if ac, ok := b.ApplicationConfig(); ok {
		nac, ok := nb.ApplicationConfig()
		if !ok {
			return errors.New("current config has application section, but new config does not")
		}

		for orgName, org := range ac.Organizations() {
			norg, ok := nac.Organizations()[orgName]
			if !ok {
				continue
			}
			mspID := org.MSPID()
			if mspID != norg.MSPID() {
				return errors.Errorf("application org %s attempted to change MSP ID from %s to %s", orgName, mspID, norg.MSPID())
			}
		}
	}

	if cc, ok := b.ConsortiumsConfig(); ok {
		ncc, ok := nb.ConsortiumsConfig()
		if !ok {
			return errors.Errorf("current config has consortiums section, but new config does not")
		}

		for consortiumName, consortium := range cc.Consortiums() {
			nconsortium, ok := ncc.Consortiums()[consortiumName]
			if !ok {
				continue
			}

			for orgName, org := range consortium.Organizations() {
				norg, ok := nconsortium.Organizations()[orgName]
				if !ok {
					continue
				}
				mspID := org.MSPID()
				if mspID != norg.MSPID() {
					return errors.Errorf("consortium %s org %s attempted to change MSP ID from %s to %s", consortiumName, orgName, mspID, norg.MSPID())
				}
			}
		}
	} else if _, okNew := nb.ConsortiumsConfig(); okNew {
		return errors.Errorf("current config has no consortiums section, but new config does")
	}

	return nil
}
1272815
func MustNewValue(v interface{}) *Value {
	ret, err := NewValue(v)
	if err != nil {
		panic(err)
	}
	return ret
}
983604
func ValidateBuild(build *buildapi.Build) field.ErrorList {
	allErrs := field.ErrorList{}
	allErrs = append(allErrs, validation.ValidateObjectMeta(&build.ObjectMeta, true, apimachineryvalidation.NameIsDNSSubdomain, field.NewPath("metadata"))...)
	allErrs = append(allErrs, validateCommonSpec(&build.Spec.CommonSpec, field.NewPath("spec"))...)
	return allErrs
}
802228
func (e *EncryptedRaftLogger) BootstrapNew(metadata []byte) error {
	e.encoderMu.Lock()
	defer e.encoderMu.Unlock()
	encrypter, decrypter := encryption.Defaults(e.EncryptionKey, e.FIPS)
	walFactory := NewWALFactory(encrypter, decrypter)

	for _, dirpath := range []string{filepath.Dir(e.walDir()), e.snapDir()} {
		if err := os.MkdirAll(dirpath, 0700); err != nil {
			return errors.Wrapf(err, "failed to create %s", dirpath)
		}
	}
	var err error
	// the wal directory must not already exist upon creation
	e.wal, err = walFactory.Create(e.walDir(), metadata)
	if err != nil {
		return errors.Wrap(err, "failed to create WAL")
	}

	e.snapshotter = NewSnapFactory(encrypter, decrypter).New(e.snapDir())
	return nil
}
162915
func hackedNew(t reflect.Type) reflect.Value {
	return reflect.New(unhackType(t))
}
989636
func validatePlatforms(c *validation.Context, cfg *configPB.Platforms) {
	// Platform names must be unique.
	// Keep records of ones we've already seen.
	names := stringset.New(len(cfg.Platform))
	for _, p := range cfg.Platform {
		switch {
		case p.Name == "":
			c.Errorf("platform names are required and must be non-empty")
		case !names.Add(p.Name):
			c.Errorf("duplicate platform %q", p.Name)
		}
	}
}
1287511
func validateKubeConfig(outDir, filename string, config *clientcmdapi.Config) error {
	kubeConfigFilePath := filepath.Join(outDir, filename)

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

	// The kubeconfig already exists, let's check if it has got the same CA and server URL
	currentConfig, err := clientcmd.LoadFromFile(kubeConfigFilePath)
	if err != nil {
		return errors.Wrapf(err, "failed to load kubeconfig file %s that already exists on disk", kubeConfigFilePath)
	}

	expectedCtx := config.CurrentContext
	expectedCluster := config.Contexts[expectedCtx].Cluster
	currentCtx := currentConfig.CurrentContext
	currentCluster := currentConfig.Contexts[currentCtx].Cluster

	// If the current CA cert on disk doesn't match the expected CA cert, error out because we have a file, but it's stale
	if !bytes.Equal(currentConfig.Clusters[currentCluster].CertificateAuthorityData, config.Clusters[expectedCluster].CertificateAuthorityData) {
		return errors.Errorf("a kubeconfig file %q exists already but has got the wrong CA cert", kubeConfigFilePath)
	}
	// If the current API Server location on disk doesn't match the expected API server, error out because we have a file, but it's stale
	if currentConfig.Clusters[currentCluster].Server != config.Clusters[expectedCluster].Server {
		return errors.Errorf("a kubeconfig file %q exists already but has got the wrong API Server URL", kubeConfigFilePath)
	}

	return nil
}
373949
func NewError(packageType string, method string, message string, args ...interface{}) Error {
	return Error{
		PackageType: packageType,
		Method:      method,
		Message:     fmt.Sprintf(message, args...),
	}
}
1101325
func (v *flagValidator) validateNextFlag() (bool, error) {
	if len(v.args) == 0 {
		return false, nil
	}
	s := v.args[0]
	if len(s) < 2 || s[0] != '-' {
		return false, fmt.Errorf("invalid flag: %s", s)
	}
	numMinuses := 1
	if s[1] == '-' {
		numMinuses++
		if len(s) == 2 { // "--" terminates the flags
			v.args = v.args[1:]
			return false, errors.New("'--' flag with no name is not allowed")
		}
	}
	name := s[numMinuses:]
	if len(name) == 0 || name[0] == '-' || name[0] == '=' {
		return false, fmt.Errorf("bad flag syntax: %s", s)
	}

	// it's a flag. does it have an argument?
	v.args = v.args[1:]
	hasValue := false
	value := ""
	for i := 1; i < len(name); i++ { // equals cannot be first
		if name[i] == '=' {
			value = name[i+1:]
			hasValue = true
			name = name[0:i]
			break
		}
	}

	flag := v.flagset.Lookup(name)
	if flag == nil {
		return false, fmt.Errorf("undefined flag: -%s", name)
	}

	if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg
		if len(v.args) > 0 {
			nextArg := v.args[0]
			if nextArg[0] != '-' {
				return false, fmt.Errorf("invalid value following flag -%s: %q; boolean flags must be passed as -flag=x", name, nextArg)
			}
		}
	} else {
		// It must have a value, which might be the next argument.
		if !hasValue && len(v.args) > 0 {
			// value is the next arg
			hasValue = true
			value, v.args = v.args[0], v.args[1:]
		}
		if !hasValue {
			return false, fmt.Errorf("flag needs an argument: -%s", name)
		}
	}
	_ = value
	return true, nil
}
375592
func NewSaltpackVerify(g *libkb.GlobalContext, arg *SaltpackVerifyArg) *SaltpackVerify {
	return &SaltpackVerify{
		arg:          arg,
		Contextified: libkb.NewContextified(g),
	}
}
323978
func (templateStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
	return validation.ValidateTemplateUpdate(obj.(*templateapi.Template), old.(*templateapi.Template))
}
708820
func (n *Graph) AddNew(processName string, componentName string, f *Factory) error {
	proc, err := f.Create(componentName)
	if err != nil {
		return err
	}
	return n.Add(processName, proc)
}
619527
func NewValidatorFromPath(bundlePath string, hostSpecific bool, platform string) (Validator, error) {
	if bundlePath == "" {
		return Validator{}, fmt.Errorf("bundle path shouldn't be empty")
	}

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

	configPath := filepath.Join(bundlePath, specConfig)
	content, err := ioutil.ReadFile(configPath)
	if err != nil {
		return Validator{}, specerror.NewError(specerror.ConfigInRootBundleDir, err, rspec.Version)
	}
	if !utf8.Valid(content) {
		return Validator{}, fmt.Errorf("%q is not encoded in UTF-8", configPath)
	}
	var spec rspec.Spec
	if err = json.Unmarshal(content, &spec); err != nil {
		return Validator{}, err
	}

	return NewValidator(&spec, bundlePath, hostSpecific, platform)
}
653113
func NewValidator(spec *rspec.Spec, bundlePath string, hostSpecific bool, platform string) (Validator, error) {
	if hostSpecific && platform != runtime.GOOS {
		return Validator{}, fmt.Errorf("When hostSpecific is set, platform must be same as the host platform")
	}
	return Validator{
		spec:         spec,
		bundlePath:   bundlePath,
		HostSpecific: hostSpecific,
		platform:     platform,
	}, nil
}
1298369
func (p *cinderProvider) ValidateConfig(cfg *storage.Config) error {
	// TODO(axw) 2015-05-01 #1450737
	// Reject attempts to create non-persistent volumes.
	_, err := newCinderConfig(cfg.Attrs())
	return errors.Trace(err)
}
40742
func (vr *validateRun) validateGenerated(ctx context.Context, path string) (*validateResult, error) {
	// -config-set flag must not be used in this mode, config sets are defined
	// on Starlark level.
	if vr.configSet != "" {
		return nil, base.NewCLIError("-config-set can't be used when validating Starlark-based configs")
	}

	meta := vr.DefaultMeta()
	output, err := base.GenerateConfigs(ctx, path, &meta, &vr.Meta)
	if err != nil {
		return nil, err
	}

	result := &validateResult{}

	if meta.ConfigDir != "-" {
		// Find files that are present on disk, but no longer in the output.
		tracked, err := lucicfg.FindTrackedFiles(meta.ConfigDir, meta.TrackedFiles)
		if err != nil {
			return result, err
		}
		for _, f := range tracked {
			if _, present := output.Data[f]; !present {
				result.Stale = append(result.Stale, f)
			}
		}
		// Find files that are newer in the output or do not exist on disk.
		changed, _ := output.Compare(meta.ConfigDir)
		result.Stale = append(result.Stale, changed...)
	}

	if len(result.Stale) != 0 {
		return result, fmt.Errorf(
			"following files on disk are out-of-date: %s.\n"+
				"  Run `lucicfg generate %q` to update them",
			strings.Join(result.Stale, ", "), path)
	}

	// Validate via LUCI Config RPC. This silently skips configs not belonging to
	// any config sets.
	result.Validation, err = base.ValidateOutput(
		ctx,
		output,
		vr.ConfigService,
		meta.ConfigServiceHost,
		meta.FailOnWarnings)
	return result, err
}
133699
func ValidateConditionalNetworkPolicy(np, oldNP *networking.NetworkPolicy) field.ErrorList {
	var errs field.ErrorList
	// If the SCTPSupport feature is disabled, and the old object isn't using the SCTP feature, prevent the new object from using it
	if !utilfeature.DefaultFeatureGate.Enabled(features.SCTPSupport) && len(sctpFields(oldNP)) == 0 {
		for _, f := range sctpFields(np) {
			errs = append(errs, field.NotSupported(f, api.ProtocolSCTP, []string{string(api.ProtocolTCP), string(api.ProtocolUDP)}))
		}
	}
	return errs
}