// validateUnitMachineAssignment validates the parameters for assigning a unit
// to a specified machine.
177343
func validateUnitMachineAssignment(
	m *Machine,
	series string,
	isSubordinate bool,
	storagePools set.Strings,
) (err error) {
	if m.Life() != Alive {
		return machineNotAliveErr
	}
	if isSubordinate {
		return fmt.Errorf("unit is a subordinate")
	}
	if series != m.doc.Series {
		return fmt.Errorf("series does not match")
	}
	canHost := false
	for _, j := range m.doc.Jobs {
		if j == JobHostUnits {
			canHost = true
			break
		}
	}
	if !canHost {
		return fmt.Errorf("machine %q cannot host units", m)
	}
	sb, err := NewStorageBackend(m.st)
	if err != nil {
		return errors.Trace(err)
	}
	if err := validateDynamicMachineStoragePools(sb, m, storagePools); err != nil {
		return errors.Trace(err)
	}
	return nil
}
684405
func (st *State) AssignUnit(u *Unit, policy AssignmentPolicy) (err error) {
	if !u.IsPrincipal() {
		return errors.Errorf("subordinate unit %q cannot be assigned directly to a machine", u)
	}
	defer errors.DeferredAnnotatef(&err, "cannot assign unit %q to machine", u)
	var m *Machine
	switch policy {
	case AssignLocal:
		m, err = st.Machine("0")
		if err != nil {
			return errors.Trace(err)
		}
		return u.AssignToMachine(m)
	case AssignClean:
		if _, err = u.AssignToCleanMachine(); errors.Cause(err) != noCleanMachines {
			return errors.Trace(err)
		}
		return u.AssignToNewMachineOrContainer()
	case AssignCleanEmpty:
		if _, err = u.AssignToCleanEmptyMachine(); errors.Cause(err) != noCleanMachines {
			return errors.Trace(err)
		}
		return u.AssignToNewMachineOrContainer()
	case AssignNew:
		return errors.Trace(u.AssignToNewMachine())
	}
	return errors.Errorf("unknown unit assignment policy: %q", policy)
}
990693
func (e *Exists) ValidateInitialization() error {
	if e.namespaceLister == nil {
		return fmt.Errorf("missing namespaceLister")
	}
	if e.client == nil {
		return fmt.Errorf("missing client")
	}
	return nil
}
882276
func ValidateInitConfiguration(c *kubeadm.InitConfiguration) field.ErrorList {
	allErrs := field.ErrorList{}
	allErrs = append(allErrs, ValidateNodeRegistrationOptions(&c.NodeRegistration, field.NewPath("nodeRegistration"))...)
	allErrs = append(allErrs, ValidateBootstrapTokens(c.BootstrapTokens, field.NewPath("bootstrapTokens"))...)
	allErrs = append(allErrs, ValidateClusterConfiguration(&c.ClusterConfiguration)...)
	allErrs = append(allErrs, ValidateAPIEndpoint(&c.LocalAPIEndpoint, field.NewPath("localAPIEndpoint"))...)
	return allErrs
}
162757
func RegisterMetrics() {
	prometheus.MustRegister(vsphereAPIMetric)
	prometheus.MustRegister(vsphereAPIErrorMetric)
	prometheus.MustRegister(vsphereOperationMetric)
	prometheus.MustRegister(vsphereOperationErrorMetric)
}
1017827
func (u *Unit) noAssignedMachineOp() txn.Op {
	id := u.doc.DocID
	if u.doc.Principal != "" {
		id = u.doc.Principal
	}
	return txn.Op{
		C:      unitsC,
		Id:     id,
		Assert: bson.D{{"machineid", ""}},
	}
}
1055463
func (a *imagePolicyPlugin) ValidateInitialization() error {
	if a.client == nil {
		return fmt.Errorf("%s needs an Openshift client", imagepolicy.PluginName)
	}
	if a.nsLister == nil {
		return fmt.Errorf("%s needs a namespace lister", imagepolicy.PluginName)
	}
	imageResolver, err := newImageResolutionCache(a.client, a.integratedRegistryMatcher)
	if err != nil {
		return fmt.Errorf("unable to create image policy controller: %v", err)
	}
	a.resolver = imageResolver
	return nil
}
999761
func (m *Machine) Validate() error {
	if m.MachineName == "" {
		return fmt.Errorf("a machine name is required")
	}

	if m.MachineVersion == "" {
		return fmt.Errorf("a machine version is required")
	}

	if m.InitialState == "" {
		return fmt.Errorf("an initial state is required")
	}

	if len(m.Transitions) == 0 {
		return fmt.Errorf("no transitions defined")
	}

	if len(m.WatcherDefs) == 0 {
		return fmt.Errorf("no watchers defined")
	}

	for _, w := range m.Watchers() {
		err := w.ParseAnnounceInterval()
		if err != nil {
			return err
		}
	}

	return nil
}
441097
func (d *DenyExec) ValidateInitialization() error {
	if d.client == nil {
		return fmt.Errorf("missing client")
	}
	return nil
}
266829
func (m *ClusterLoadAssignment) Validate() error {
	if m == nil {
		return nil
	}

	if len(m.GetClusterName()) < 1 {
		return ClusterLoadAssignmentValidationError{
			field:  "ClusterName",
			reason: "value length must be at least 1 bytes",
		}
	}

	for idx, item := range m.GetEndpoints() {
		_, _ = idx, item

		{
			tmp := item

			if v, ok := interface{}(&tmp).(interface{ Validate() error }); ok {

				if err := v.Validate(); err != nil {
					return ClusterLoadAssignmentValidationError{
						field:  fmt.Sprintf("Endpoints[%v]", idx),
						reason: "embedded message failed validation",
						cause:  err,
					}
				}
			}
		}

	}

	// no validation rules for NamedEndpoints

	{
		tmp := m.GetPolicy()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return ClusterLoadAssignmentValidationError{
					field:  "Policy",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	return nil
}
923603
func validateDynamicMachineStorageParams(m *Machine, params *storageParams) error {
	sb, err := NewStorageBackend(m.st)
	if err != nil {
		return errors.Trace(err)
	}
	pools, err := storagePools(sb, params)
	if err != nil {
		return err
	}
	if err := validateDynamicMachineStoragePools(sb, m, pools); err != nil {
		return err
	}
	// Validate the volume/filesystem attachments for the machine.
	for volumeTag := range params.volumeAttachments {
		volume, err := getVolumeByTag(sb.mb, volumeTag)
		if err != nil {
			return errors.Trace(err)
		}
		if !volume.Detachable() && volume.doc.HostId != m.Id() {
			return errors.Errorf(
				"storage is non-detachable (bound to machine %s)",
				volume.doc.HostId,
			)
		}
	}
	for filesystemTag := range params.filesystemAttachments {
		filesystem, err := getFilesystemByTag(sb.mb, filesystemTag)
		if err != nil {
			return errors.Trace(err)
		}
		if !filesystem.Detachable() && filesystem.doc.HostId != m.Id() {
			host := storageAttachmentHost(filesystem.doc.HostId)
			return errors.Errorf(
				"storage is non-detachable (bound to %s)",
				names.ReadableString(host),
			)
		}
	}
	return nil
}
1281393
func (d *DisallowFlunder) ValidateInitialization() error {
	if d.lister == nil {
		return fmt.Errorf("missing fischer lister")
	}
	return nil
}
562058
func (w *MachineLXDProfileWatcher) init(machine *Machine) error {
	units, err := machine.Units()
	if err != nil {
		return errors.Annotatef(err, "failed to get units to start MachineLXDProfileWatcher")
	}

	for _, unit := range units {
		appName := unit.Application()
		unitName := unit.Name()

		if info, found := w.applications[appName]; found {
			info.units.Add(unitName)
			continue
		}

		app, err := w.modeler.Application(appName)
		if errors.IsNotFound(err) {
			// This is unlikely, but could happen because Units()
			// added the parent'd machine id to subordinates.
			// If the unit has no machineId, it will be added
			// to what is watched when the machineId is assigned.
			// Otherwise return an error.
			if unit.MachineId() != "" {
				return errors.Errorf("programming error, unit %s has machineId but not application", unitName)
			}
			logger.Errorf("unit %s has no application, nor machine id, start watching when machine id assigned.", unitName)
			w.metrics.LXDProfileChangeError.Inc()
			continue
		}

		chURL := app.CharmURL()
		info := appInfo{
			charmURL: chURL,
			units:    set.NewStrings(unitName),
		}

		ch, err := w.modeler.Charm(chURL)
		if err != nil {
			return err
		}
		lxdProfile := ch.LXDProfile()
		if !lxdProfile.Empty() {
			info.charmProfile = lxdProfile
		}

		w.applications[appName] = info
	}
	return nil
}
1119658
func (u *Unit) AssignedMachine() (names.MachineTag, error) {
	var results params.StringResults
	args := params.Entities{
		Entities: []params.Entity{{Tag: u.tag.String()}},
	}
	emptyTag := names.NewMachineTag("")
	err := u.st.facade.FacadeCall("GetAssignedMachine", args, &results)
	if err != nil {
		return emptyTag, err
	}
	if len(results.Results) != 1 {
		return emptyTag, errors.Errorf("expected 1 result, got %d", len(results.Results))
	}
	result := results.Results[0]
	if result.Error != nil {
		return emptyTag, result.Error
	}
	return names.ParseMachineTag(result.Result)
}
309028
func (s *LoadBalancerService) NewAssignCertToLoadBalancerParams(certid string, lbruleid string) *AssignCertToLoadBalancerParams {
	p := &AssignCertToLoadBalancerParams{}
	p.p = make(map[string]interface{})
	p.p["certid"] = certid
	p.p["lbruleid"] = lbruleid
	return p
}
910690
func (m *Machine) StartUpgradeSeriesUnitCompletion(message string) error {
	buildTxn := func(attempt int) ([]txn.Op, error) {
		if attempt > 0 {
			if err := m.Refresh(); err != nil {
				return nil, errors.Trace(err)
			}
		}
		if err := m.isStillAlive(); err != nil {
			return nil, errors.Trace(err)
		}
		lock, err := m.getUpgradeSeriesLock()
		if err != nil {
			return nil, err
		}
		if lock.MachineStatus != model.UpgradeSeriesCompleteStarted {
			return nil, fmt.Errorf("machine %q can not complete its unit, the machine has not yet been marked as completed", m.Id())
		}
		timestamp := bson.Now()
		lock.Messages = append(lock.Messages, newUpgradeSeriesMessage(m.Tag().String(), message, timestamp))
		lock.TimeStamp = timestamp
		changeCount := 0
		for unitName, us := range lock.UnitStatuses {
			if us.Status == model.UpgradeSeriesCompleteStarted {
				continue
			}
			us.Status = model.UpgradeSeriesCompleteStarted
			us.Timestamp = timestamp
			lock.UnitStatuses[unitName] = us
			changeCount++
		}
		if changeCount == 0 {
			return nil, jujutxn.ErrNoOperations
		}
		return startUpgradeSeriesUnitCompletionTxnOps(m.doc.Id, lock), nil
	}
	err := m.st.db().Run(buildTxn)
	if err != nil {
		err = onAbort(err, ErrDead)
		return err
	}
	return nil
}
202132
func (v *Validator) validSignature(ts, rqp string, b []byte, rs string) bool {
	uqp, err := url.Parse("?" + rqp)
	if err != nil {
		return false
	}
	es, err := v.calculateSignature(ts, uqp.Query().Encode(), b)
	if err != nil {
		return false
	}
	drs, err := base64.StdEncoding.DecodeString(rs)
	if err != nil {
		return false
	}
	return hmac.Equal(drs, es)
}