// addDefaultStorageConstraints fills in default constraint values, replacing any empty/missing values
// in the specified constraints.
429126
func addDefaultStorageConstraints(sb *storageBackend, allCons map[string]StorageConstraints, charmMeta *charm.Meta) error {
	conf, err := sb.config()
	if err != nil {
		return errors.Trace(err)
	}

	for name, charmStorage := range charmMeta.Storage {
		cons, ok := allCons[name]
		if !ok {
			if charmStorage.Shared {
				// TODO(axw) get the model's default shared storage
				// pool, and create constraints here.
				return errors.Errorf(
					"no constraints specified for shared charm storage %q",
					name,
				)
			}
		}
		cons, err := storageConstraintsWithDefaults(sb.modelType, conf, charmStorage, name, cons)
		if err != nil {
			return errors.Trace(err)
		}
		// Replace in case pool or size were updated.
		allCons[name] = cons
	}
	return nil
}
209826
func (l *Logger) SetDefaults(d map[string]interface{}) error {
	for key := range d {
		if !IsValidKey(key) {
			return ErrInvalidKey
		}
	}

	l.defaults.Store(d)
	return nil
}
153008
func validateRoleConstraints(role *roleStorageEntry) error {
	if role == nil {
		return fmt.Errorf("nil role")
	}

	// At least one constraint should be enabled on the role
	switch {
	case role.BindSecretID:
	case len(role.BoundCIDRList) != 0:
	case len(role.SecretIDBoundCIDRs) != 0:
	case len(role.TokenBoundCIDRs) != 0:
	default:
		return fmt.Errorf("at least one constraint should be enabled on the role")
	}

	return nil
}
463226
func (a *Application) StorageConstraints() (map[string]StorageConstraints, error) {
	cons, err := readStorageConstraints(a.st, a.storageConstraintsKey())
	if errors.IsNotFound(err) {
		return nil, nil
	} else if err != nil {
		return nil, errors.Annotatef(err, "application %q", a.doc.Name)
	}
	return cons, nil
}
1355377
func (s *OrderableReplicationInstance) SetDefaultAllocatedStorage(v int64) *OrderableReplicationInstance {
	s.DefaultAllocatedStorage = &v
	return s
}
211871
func SetupDefaultConfig(uidConfig *Config) *Config {

	defaultConfig := DefaultConfig()

	if uidConfig.ReleasePath == "" {
		uidConfig.ReleasePath = defaultConfig.ReleasePath
	}
	if uidConfig.StoredPath == "" {
		uidConfig.StoredPath = defaultConfig.StoredPath
	}
	if uidConfig.EventMetadataExtractor == nil {
		uidConfig.EventMetadataExtractor = defaultConfig.EventMetadataExtractor
	}

	return uidConfig
}
130670
func ConfigDefaults(providerDefaults schema.Defaults) schema.Defaults {
	defaults := schema.Defaults{
		JujuApplicationPath: JujuDefaultApplicationPath,
	}
	for key, value := range providerDefaults {
		if value == schema.Omit {
			continue
		}
		defaults[key] = value
	}
	return defaults
}
1338347
func (a *Application) storageConstraintsKey() string {
	return applicationStorageConstraintsKey(a.doc.Name, a.doc.CharmURL)
}
302928
func AddFlagsWithDefaults(
	flags *flag.FlagSet, defaultParams InitParams,
	defaultLogPath string) *InitParams {
	var params InitParams
	flags.BoolVar(&params.Debug, "debug", defaultParams.Debug,
		"Print debug messages")

	flags.StringVar(&params.BServerAddr, "bserver", defaultParams.BServerAddr,
		"host:port of the block server, 'memory', or 'dir:/path/to/dir'")
	flags.StringVar(&params.MDServerAddr, "mdserver",
		defaultParams.MDServerAddr,
		"host:port of the metadata server, 'memory', or 'dir:/path/to/dir'")
	flags.StringVar(&params.LocalUser, "localuser", defaultParams.LocalUser,
		"fake local user")
	flags.StringVar(&params.LocalFavoriteStorage, "local-fav-storage",
		defaultParams.LocalFavoriteStorage,
		"where to put favorites; used only when -localuser is set, then must "+
			"either be 'memory' or 'dir:/path/to/dir'")
	flags.DurationVar(&params.TLFValidDuration, "tlf-valid",
		defaultParams.TLFValidDuration,
		"time tlfs are valid before redoing identification")
	flags.BoolVar(&params.LogToFile, "log-to-file", defaultParams.LogToFile,
		fmt.Sprintf("Log to default file: %s", defaultLogPath))
	flags.StringVar(&params.LogFileConfig.Path, "log-file", "",
		"Path to log file")
	flags.DurationVar(&params.LogFileConfig.MaxAge, "log-file-max-age",
		defaultParams.LogFileConfig.MaxAge,
		"Maximum age of a log file before rotation")
	params.LogFileConfig.MaxSize = defaultParams.LogFileConfig.MaxSize
	flags.Var(SizeFlag{&params.LogFileConfig.MaxSize}, "log-file-max-size",
		"Maximum size of a log file before rotation")
	// The default is to *DELETE* old log files for kbfs.
	flags.IntVar(&params.LogFileConfig.MaxKeepFiles, "log-file-max-keep-files",
		defaultParams.LogFileConfig.MaxKeepFiles, "Maximum number of log "+
			"files for this service, older ones are deleted. 0 for infinite.")
	flags.Uint64Var(&params.CleanBlockCacheCapacity, "clean-bcache-cap",
		defaultParams.CleanBlockCacheCapacity,
		"If non-zero, specify the capacity of clean block cache. If zero, "+
			"the capacity is set based on system RAM.")
	flags.StringVar(&params.StorageRoot, "storage-root",
		defaultParams.StorageRoot, "Specifies where Keybase will store its "+
			"local databases for the journal and disk cache.")
	params.DiskCacheMode = defaultParams.DiskCacheMode
	flags.Var(&params.DiskCacheMode, "disk-cache-mode",
		"Sets the mode for the disk cache. If 'local', then it uses a "+
			"subdirectory of -storage-root to store the cache. If 'remote', "+
			"then it connects to the local KBFS instance and delegates disk "+
			"cache operations to it.")
	flags.BoolVar(&params.EnableJournal, "enable-journal",
		defaultParams.EnableJournal, "Enables write journaling for TLFs.")

	// No real need to enable setting
	// params.TLFJournalBackgroundWorkStatus via a flag.
	params.TLFJournalBackgroundWorkStatus =
		defaultParams.TLFJournalBackgroundWorkStatus

	flags.DurationVar(&params.BGFlushPeriod, "sync-batch-period",
		defaultParams.BGFlushPeriod,
		"The amount of time to wait before syncing data in a TLF, if the "+
			"batch size doesn't fill up.")
	flags.IntVar((*int)(&params.BGFlushDirOpBatchSize), "sync-batch-size",
		int(defaultParams.BGFlushDirOpBatchSize),
		"The number of unflushed directory operations in a TLF that will "+
			"trigger an immediate data sync.")

	flags.IntVar((*int)(&params.MetadataVersion), "md-version",
		int(defaultParams.MetadataVersion),
		"Metadata version to use when creating new metadata")
	flags.IntVar((*int)(&params.BlockCryptVersion), "block-crypt-version",
		int(defaultParams.BlockCryptVersion),
		"Encryption version to use when encrypting new blocks")
	flags.StringVar(&params.Mode, "mode", defaultParams.Mode,
		fmt.Sprintf("Overall initialization mode for KBFS, indicating how "+
			"heavy-weight it can be (%s, %s, %s, %s or %s)", InitDefaultString,
			InitMinimalString, InitSingleOpString, InitConstrainedString,
			InitMemoryLimitedString))

	flags.Float64Var((*float64)(&params.DiskBlockCacheFraction),
		"disk-block-cache-fraction", defaultParams.DiskBlockCacheFraction,
		"The portion of the free disk space that KBFS will use for caching ")

	flags.Float64Var((*float64)(&params.SyncBlockCacheFraction),
		"sync-block-cache-fraction", defaultParams.SyncBlockCacheFraction,
		"The portion of the free disk space that KBFS will use for offline storage")

	return &params
}
1091521
func (u *Unit) AddStorage(constraints map[string][]params.StorageConstraints) error {
	if u.st.facade.BestAPIVersion() < 2 {
		return errors.NotImplementedf("AddStorage() (need V2+)")
	}

	all := make([]params.StorageAddParams, 0, len(constraints))
	for storage, cons := range constraints {
		for _, one := range cons {
			all = append(all, params.StorageAddParams{
				UnitTag:     u.Tag().String(),
				StorageName: storage,
				Constraints: one,
			})
		}
	}

	args := params.StoragesAddParams{Storages: all}
	var results params.ErrorResults
	err := u.st.facade.FacadeCall("AddUnitStorage", args, &results)
	if err != nil {
		return err
	}

	return results.Combine()
}
90962
func (api *APIBase) SetConstraints(args params.SetConstraints) error {
	if err := api.checkCanWrite(); err != nil {
		return err
	}
	if err := api.check.ChangeAllowed(); err != nil {
		return errors.Trace(err)
	}
	app, err := api.backend.Application(args.ApplicationName)
	if err != nil {
		return err
	}
	return app.SetConstraints(args.Constraints)
}
1048309
func AddDefaultHandlers(h printers.PrintHandler) {
	// types without defined columns
	objectMetaColumnDefinitions := []metav1beta1.TableColumnDefinition{
		{Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]},
		{Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]},
	}
	h.DefaultTableHandler(objectMetaColumnDefinitions, printObjectMeta)
}
738409
func PutDefault(ch *Changeset, field string, value interface{}, opts ...Option) {
	options := Options{
		message: PutDefaultErrorMessage,
	}
	options.apply(opts)

	if typ, exist := ch.types[field]; exist {
		valTyp := reflect.TypeOf(value)
		if valTyp.ConvertibleTo(typ) {
			if ch.changes[field] == nil {
				ch.changes[field] = value
			}
			return
		}
	}

	msg := strings.Replace(options.message, "{field}", field, 1)
	AddError(ch, field, msg)
}
419964
func RegisterDefaults(scheme *runtime.Scheme) error {
	scheme.AddTypeDefaultingFunc(&Configuration{}, func(obj interface{}) { SetObjectDefaults_Configuration(obj.(*Configuration)) })
	return nil
}
678956
func NewDefaultRestrictionManager(maxValueLength int) *DefaultRestrictionManager {
	if maxValueLength == 0 {
		maxValueLength = defaultMaxValueLength
	}
	return &DefaultRestrictionManager{
		defaultRestriction: &Restriction{keyAllowed: true, maxValueLength: maxValueLength},
	}
}
930862
func (c *Client) ModelDefaults(cloud string) (config.ModelDefaultAttributes, error) {
	if c.BestAPIVersion() < 6 {
		if cloud != "" {
			return nil, errors.Errorf("model defaults for cloud %s not supported for this version of Juju", cloud)
		}
		return c.legacyModelDefaults()
	}

	results := params.ModelDefaultsResults{}
	args := params.Entities{
		Entities: []params.Entity{{Tag: names.NewCloudTag(cloud).String()}},
	}
	err := c.facade.FacadeCall("ModelDefaultsForClouds", args, &results)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if len(results.Results) != 1 {
		return nil, errors.Errorf("expected one result, got %d", len(results.Results))
	}
	result := results.Results[0]
	if result.Error != nil {
		return nil, errors.Trace(result.Error)
	}
	values := make(config.ModelDefaultAttributes)
	for name, val := range result.Config {
		setting := config.AttributeDefaultValues{
			Default:    val.Default,
			Controller: val.Controller,
		}
		for _, region := range val.Regions {
			setting.Regions = append(setting.Regions, config.RegionDefaultValue{
				Name:  region.RegionName,
				Value: region.Value})
		}
		values[name] = setting
	}
	return values, nil
}
955331
func RegisterDefaults(scheme *runtime.Scheme) error {
	scheme.AddTypeDefaultingFunc(&v1beta1.KubeletConfiguration{}, func(obj interface{}) { SetObjectDefaults_KubeletConfiguration(obj.(*v1beta1.KubeletConfiguration)) })
	return nil
}