// ModelUserInfoFromParams translates []params.ModelUserInfo to a map of
// user names to ModelUserInfo.
421202
func ModelUserInfoFromParams(users []params.ModelUserInfo, now time.Time) map[string]ModelUserInfo {
	output := make(map[string]ModelUserInfo)
	for _, info := range users {
		outInfo := ModelUserInfo{
			DisplayName: info.DisplayName,
			Access:      string(info.Access),
		}
		if info.LastConnection != nil {
			outInfo.LastConnection = UserFriendlyDuration(*info.LastConnection, now)
		} else {
			outInfo.LastConnection = "never connected"
		}
		output[names.NewUserTag(info.UserName).Id()] = outInfo
	}
	return output
}
149600
func ModelUserInfo(user permission.UserAccess, st modelConnectionAbleBackend) (params.ModelUserInfo, error) {
	access, err := StateToParamsUserAccessPermission(user.Access)
	if err != nil {
		return params.ModelUserInfo{}, errors.Trace(err)
	}

	userLastConn, err := st.LastModelConnection(user.UserTag)
	if err != nil && !state.IsNeverConnectedError(err) {
		return params.ModelUserInfo{}, errors.Trace(err)
	}
	var lastConn *time.Time
	if err == nil {
		lastConn = &userLastConn
	}

	userInfo := params.ModelUserInfo{
		UserName:       user.UserName,
		DisplayName:    user.DisplayName,
		LastConnection: lastConn,
		Access:         access,
	}
	return userInfo, nil
}
269809
func (o *LocaleOptions) getParameters() (params map[string]string, err error) {
	params = make(map[string]string)
	if o.cc != "" {
		params["cc"] = o.cc
	}
	if o.lang != "" {
		params["lang"] = o.lang
	}
	return params, nil
}
498233
func (m *Model) Users() ([]permission.UserAccess, error) {
	coll, closer := m.st.db().GetCollection(modelUsersC)
	defer closer()

	var userDocs []userAccessDoc
	err := coll.Find(nil).All(&userDocs)
	if err != nil {
		return nil, errors.Trace(err)
	}

	var modelUsers []permission.UserAccess
	for _, doc := range userDocs {
		// check if the User belonging to this model user has
		// been deleted, in this case we should not return it.
		userTag := names.NewUserTag(doc.UserName)
		if userTag.IsLocal() {
			_, err := m.st.User(userTag)
			if err != nil {
				if _, ok := err.(DeletedUserError); !ok {
					// We ignore deleted users for now. So if it is not a
					// DeletedUserError we return the error.
					return nil, errors.Trace(err)
				}
				continue
			}
		}
		mu, err := NewModelUserAccess(m.st, doc)
		if err != nil {
			return nil, errors.Trace(err)
		}
		modelUsers = append(modelUsers, mu)
	}

	return modelUsers, nil
}
1280281
func (st *State) ModelBasicInfoForUser(user names.UserTag) ([]ModelAccessInfo, error) {
	isSuperuser, err := st.isUserSuperuser(user)
	if err != nil {
		return nil, errors.Trace(err)
	}
	modelQuery, closer1, err := st.modelQueryForUser(user, isSuperuser)
	if err != nil {
		return nil, errors.Trace(err)
	}
	defer closer1()
	modelQuery.Select(bson.M{"_id": 1, "name": 1, "owner": 1, "type": 1})
	var accessInfo []ModelAccessInfo
	if err := modelQuery.All(&accessInfo); err != nil {
		return nil, errors.Trace(err)
	}
	// Now we need to find the last-connection time for each model for this user
	username := user.Id()
	connDocIds := make([]string, len(accessInfo))
	for i, acc := range accessInfo {
		connDocIds[i] = acc.UUID + ":" + username
	}
	lastConnections, closer2 := st.db().GetRawCollection(modelUserLastConnectionC)
	defer closer2()
	query := lastConnections.Find(bson.M{"_id": bson.M{"$in": connDocIds}})
	query.Select(bson.M{"last-connection": 1, "_id": 0, "model-uuid": 1})
	query.Batch(100)
	iter := query.Iter()
	lastConns := make(map[string]time.Time, len(connDocIds))
	var connInfo modelUserLastConnectionDoc
	for iter.Next(&connInfo) {
		lastConns[connInfo.ModelUUID] = connInfo.LastConnection
	}
	if err := iter.Close(); err != nil {
		return nil, errors.Trace(err)
	}
	for i := range accessInfo {
		uuid := accessInfo[i].UUID
		accessInfo[i].LastConnection = lastConns[uuid]
	}
	return accessInfo, nil
}
1208319
func (r *Registry) LookupParameterInfo(resource, name string) (param SearchParamInfo, err error) {
	r.infosLock.RLock()
	defer r.infosLock.RUnlock()
	param, ok := r.infos[resource][name]
	if !ok {
		return SearchParamInfo{}, fmt.Errorf("Could not find info for parameter %s for resource %s", name, resource)
	}
	return param, nil
}
1244141
func (m *ModelManagerAPI) ListModels(user params.Entity) (params.UserModelList, error) {
	result := params.UserModelList{}

	userTag, err := names.ParseUserTag(user.Tag)
	if err != nil {
		return result, errors.Trace(err)
	}

	err = m.authCheck(userTag)
	if err != nil {
		return result, errors.Trace(err)
	}

	modelInfos, err := m.state.ModelBasicInfoForUser(userTag)
	if err != nil {
		return result, errors.Trace(err)
	}

	for _, mi := range modelInfos {
		var ownerTag names.UserTag
		if names.IsValidUser(mi.Owner) {
			ownerTag = names.NewUserTag(mi.Owner)
		} else {
			// no reason to fail the request here, as it wasn't the users fault
			logger.Warningf("for model %v, got an invalid owner: %q", mi.UUID, mi.Owner)
		}
		result.UserModels = append(result.UserModels, params.UserModel{
			Model: params.Model{
				Name:     mi.Name,
				UUID:     mi.UUID,
				Type:     string(mi.Type),
				OwnerTag: ownerTag.String(),
			},
			LastConnection: &mi.LastConnection,
		})
	}

	return result, nil
}
910906
func migrateLocalModelUsers(usermodels map[string]*ControllerModels) error {
	changes := false
	for _, modelDetails := range usermodels {
		for name, model := range modelDetails.Models {
			migratedName, changed, err := migrateModelName(name)
			if err != nil {
				return errors.Trace(err)
			}
			if !changed {
				continue
			}
			delete(modelDetails.Models, name)
			modelDetails.Models[migratedName] = model
			changes = true
		}
		migratedName, changed, err := migrateModelName(modelDetails.CurrentModel)
		if err != nil {
			return errors.Trace(err)
		}
		if !changed {
			continue
		}
		modelDetails.CurrentModel = migratedName
	}
	if changes {
		return WriteModelsFile(usermodels)
	}
	return nil
}
1013712
func InitModels() {
	index := mgo.Index{
		Key:      []string{"username"},
		Unique:   true,
		DropDups: true,
	}

	db.EnsureIndex(mongoUsersCollectionName, index)

	// Removes users without valid 2 factor authentication after 3 days
	automaticUserExpiration := mgo.Index{
		Key:         []string{"expire"},
		ExpireAfter: time.Second * 3600 * 24 * 3,
		Background:  true,
	}
	db.EnsureIndex(mongoUsersCollectionName, automaticUserExpiration)

	avatarIndex := mgo.Index{
		Key:      []string{"hash"},
		Unique:   true,
		DropDups: true,
	}
	db.EnsureIndex(mongoAvatarFileCollectionName, avatarIndex)

	emailIndex := mgo.Index{
		Key: []string{"emailaddresses.emailaddress"},
	}
	db.EnsureIndex(mongoUsersCollectionName, emailIndex)
}
660967
func (st *State) modelQueryForUser(user names.UserTag, isSuperuser bool) (mongo.Query, SessionCloser, error) {
	var modelQuery mongo.Query
	models, closer := st.db().GetCollection(modelsC)
	if isSuperuser {
		// Fast path, we just return all the models that aren't Importing
		modelQuery = models.Find(bson.M{"migration-mode": bson.M{"$ne": MigrationModeImporting}})
	} else {
		// Start by looking up model uuids that the user has access to, and then load only the records that are
		// included in that set
		var modelUUID struct {
			UUID string `bson:"object-uuid"`
		}
		modelUsers, userCloser := st.db().GetRawCollection(modelUsersC)
		defer userCloser()
		query := modelUsers.Find(bson.D{{"user", user.Id()}})
		query.Select(bson.M{"object-uuid": 1, "_id": 0})
		query.Batch(100)
		iter := query.Iter()
		var modelUUIDs []string
		for iter.Next(&modelUUID) {
			modelUUIDs = append(modelUUIDs, modelUUID.UUID)
		}
		if err := iter.Close(); err != nil {
			closer()
			return nil, nil, errors.Trace(err)
		}
		modelQuery = models.Find(bson.M{
			"_id":            bson.M{"$in": modelUUIDs},
			"migration-mode": bson.M{"$ne": MigrationModeImporting},
		})
	}
	modelQuery.Sort("name", "owner")
	return modelQuery, closer, nil
}
547659
func (s *TrainingJobDefinition) SetHyperParameters(v map[string]*string) *TrainingJobDefinition {
	s.HyperParameters = v
	return s
}
875735
func StateFromParam(paramValue string) (*common.State, error) {

	stateMap, err := objx.FromSignedBase64(paramValue, GetSecurityKey())

	if err != nil {
		return nil, err
	}

	return &common.State{Map: stateMap}, nil
}
1020471
func (b *OpenAPI3Builder) buildTypeFromParameters(
	name string,
	parameters []*openapiv3.ParameterOrReference,
	requestBody *openapiv3.RequestBodyOrReference) (typeName string, err error) {
	t := &Type{}
	t.Name = name + "Parameters"
	t.Description = t.Name + " holds parameters to " + name
	t.Kind = TypeKind_STRUCT
	t.Fields = make([]*Field, 0)
	for _, parametersItem := range parameters {
		var f Field
		f.Type = fmt.Sprintf("%+v", parametersItem)
		parameter := parametersItem.GetParameter()
		if parameter != nil {
			switch parameter.In {
			case "body":
				f.Position = Position_BODY
			case "header":
				f.Position = Position_HEADER
			case "formdata":
				f.Position = Position_FORMDATA
			case "query":
				f.Position = Position_QUERY
			case "path":
				f.Position = Position_PATH
			}
			f.Name = parameter.Name
			if parameter.GetSchema() != nil && parameter.GetSchema() != nil {
				f.Kind, f.Type, f.Format = b.typeForSchemaOrReference(parameter.GetSchema())
			}
			f.Serialize = true
			t.addField(&f)
		}
	}
	if requestBody != nil {
		content := requestBody.GetRequestBody().GetContent()
		if content != nil {
			for _, pair2 := range content.GetAdditionalProperties() {
				if pair2.Name != "application/json" {
					log.Printf("unimplemented: %q requestBody(%s)", name, pair2.Name)
					continue
				}
				var f Field
				f.Position = Position_BODY
				f.Kind, f.Type, f.Format = b.typeForSchemaOrReference(pair2.GetValue().GetSchema())
				f.Name = strings.ToLower(f.Type) // use the schema name as the parameter name, since none is directly specified
				f.Serialize = true
				t.addField(&f)
			}
		}
	}
	if len(t.Fields) > 0 {
		b.model.addType(t)
		return t.Name, err
	}
	return "", err
}
708571
func InitModels() {
	// TODO: Use model tags to ensure indices/constraints.
	index := mgo.Index{
		Key:    []string{"globalid"},
		Unique: true,
	}

	db.EnsureIndex(mongoCollectionName, index)

	// Add indexes to search organizations based on user access ...
	index = mgo.Index{
		Key:        []string{"owners"},
		Background: true,
	}
	db.EnsureIndex(mongoCollectionName, index)

	index = mgo.Index{
		Key:        []string{"members"},
		Background: true,
	}
	db.EnsureIndex(mongoCollectionName, index)

	index = mgo.Index{
		Key:        []string{"orgowners"},
		Background: true,
	}
	db.EnsureIndex(mongoCollectionName, index)

	index = mgo.Index{
		Key:        []string{"orgmembers"},
		Background: true,
	}
	db.EnsureIndex(mongoCollectionName, index)

	// Index the logo collection
	index = mgo.Index{
		Key:    []string{"globalid"},
		Unique: true,
	}

	db.EnsureIndex(logoCollectionName, index)

	index = mgo.Index{
		Key:    []string{"globalid", "username"},
		Unique: true,
	}

	db.EnsureIndex(last2FACollectionName, index)

	// remove last2fa entries after 31 days
	automatic2FAExpiration := mgo.Index{
		Key:         []string{"last2fa"},
		ExpireAfter: time.Second * 3600 * 24 * 31,
		Background:  true,
	}
	db.EnsureIndex(last2FACollectionName, automatic2FAExpiration)

	// Index the info texts
	index = mgo.Index{
		Key:    []string{"globalid"},
		Unique: true,
	}

	db.EnsureIndex(descriptionCollectionName, index)
}
371902
func (c *ControllerAPI) AllModels() (params.UserModelList, error) {
	result := params.UserModelList{}
	if err := c.checkHasAdmin(); err != nil {
		return result, errors.Trace(err)
	}

	modelUUIDs, err := c.state.AllModelUUIDs()
	if err != nil {
		return result, errors.Trace(err)
	}
	for _, modelUUID := range modelUUIDs {
		st, err := c.statePool.Get(modelUUID)
		if err != nil {
			// This model could have been removed.
			if errors.IsNotFound(err) {
				continue
			}
			return result, errors.Trace(err)
		}
		defer st.Release()

		model, err := st.Model()
		if err != nil {
			return result, errors.Trace(err)
		}

		userModel := params.UserModel{
			Model: params.Model{
				Name:     model.Name(),
				UUID:     model.UUID(),
				Type:     string(model.Type()),
				OwnerTag: model.Owner().String(),
			},
		}

		lastConn, err := model.LastModelConnection(c.apiUser)
		if err != nil {
			if !state.IsNeverConnectedError(err) {
				return result, errors.Trace(err)
			}
		} else {
			userModel.LastConnection = &lastConn
		}

		result.UserModels = append(result.UserModels, userModel)
	}

	return result, nil
}
548962
func ModelMachineInfoFromParams(machines []params.ModelMachineInfo) map[string]ModelMachineInfo {
	output := make(map[string]ModelMachineInfo, len(machines))
	for _, info := range machines {
		mInfo := ModelMachineInfo{}
		if info.Hardware != nil && info.Hardware.Cores != nil {
			mInfo.Cores = *info.Hardware.Cores
		}
		output[info.Id] = mInfo
	}
	return output
}
443614
func InjectParamsUser() macaron.Handler {
	return func(c *Context) {
		user, err := models.GetUserByName(c.Params(":username"))
		if err != nil {
			c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
			return
		}
		c.Map(&ParamsUser{user})
	}
}