// PermCreate adds a user to an app or makes them an administrator.
554977
func PermCreate(appID string, username string, admin bool) error {

	c, appID, err := permsLoad(appID, admin)

	if err != nil {
		return err
	}

	if admin {
		fmt.Printf("Adding %s to system administrators... ", username)
		err = perms.NewAdmin(c, username)
	} else {
		fmt.Printf("Adding %s to %s collaborators... ", username, appID)
		err = perms.New(c, appID, username)
	}

	if err != nil {
		return err
	}

	fmt.Println("done")

	return nil
}
1172451
func (s *UserService) CreateUser(ctx context.Context, o *influxdb.User) error {
	p, err := influxdb.NewGlobalPermission(influxdb.WriteAction, influxdb.UsersResourceType)
	if err != nil {
		return err
	}

	if err := IsAllowed(ctx, *p); err != nil {
		return err
	}

	return s.s.CreateUser(ctx, o)
}
1250693
func (c *Client) CreateApp(user, name string) (*App, error) {
	log.Printf("[INFO] creating application %s/%s", user, name)

	body, err := json.Marshal(&appWrapper{&App{
		User: user,
		Name: name,
	}})
	if err != nil {
		return nil, err
	}

	endpoint := "/api/v1/vagrant/applications"
	request, err := c.Request("POST", endpoint, &RequestOptions{
		Body: bytes.NewReader(body),
		Headers: map[string]string{
			"Content-Type": "application/json",
		},
	})
	if err != nil {
		return nil, err
	}

	response, err := checkResp(c.HTTPClient.Do(request))
	if err != nil {
		return nil, err
	}

	var app App
	if err := decodeJSON(response, &app); err != nil {
		return nil, err
	}

	return &app, nil
}
1128728
func (ac *APIController) AciGwCreate(aci *contivModel.AciGw) error {
	log.Infof("Received AciGwCreate: %+v", aci)
	// Fail the create if app profiles exist
	profCount := contivModel.GetAppProfileCount()
	if profCount != 0 {
		log.Warnf("AciGwCreate: %d existing App-Profiles found.",
			profCount)
	}

	return nil
}
1178327
func PermDelete(appID string, username string, admin bool) error {

	c, appID, err := permsLoad(appID, admin)

	if err != nil {
		return err
	}

	if admin {
		fmt.Printf("Removing %s from system administrators... ", username)
		err = perms.DeleteAdmin(c, username)
	} else {
		fmt.Printf("Removing %s from %s collaborators... ", username, appID)
		err = perms.Delete(c, appID, username)
	}

	if err != nil {
		return err
	}

	fmt.Println("done")

	return nil
}
1272424
func (c *Client) DynoCreate(appIdentity string, command string, options *DynoCreateOpts) (*Dyno, error) {
	params := struct {
		Command string             `json:"command"`
		Attach  *bool              `json:"attach,omitempty"`
		Env     *map[string]string `json:"env,omitempty"`
		Size    *string            `json:"size,omitempty"`
	}{
		Command: command,
	}
	if options != nil {
		params.Attach = options.Attach
		params.Env = options.Env
		params.Size = options.Size
	}

	rh := RequestHeaders{CommitMessage: options.Message}
	var dynoRes Dyno
	return &dynoRes, c.PostWithHeaders(&dynoRes, "/apps/"+appIdentity+"/dynos", params, rh.Headers())
}
1106647
func (ac *APIController) AppProfileCreate(prof *contivModel.AppProfile) error {
	log.Infof("Received AppProfileCreate: %+v", prof)

	// Make sure tenant exists
	if prof.TenantName == "" {
		return core.Errorf("Invalid tenant name")
	}

	tenant := contivModel.FindTenant(prof.TenantName)
	if tenant == nil {
		return core.Errorf("Tenant %s not found", prof.TenantName)
	}

	for _, epg := range prof.EndpointGroups {
		epgKey := prof.TenantName + ":" + epg
		epgObj := contivModel.FindEndpointGroup(epgKey)
		if epgObj == nil {
			return core.Errorf("EndpointGroup %s not found", epgKey)
		}
		modeldb.AddLinkSet(&prof.LinkSets.EndpointGroups, epgObj)
		modeldb.AddLink(&epgObj.Links.AppProfile, prof)
		err := epgObj.Write()
		if err != nil {
			log.Errorf("Error updating epg state(%+v). Err: %v", epgObj, err)
			return err
		}
	}

	// Setup links
	modeldb.AddLink(&prof.Links.Tenant, tenant)
	modeldb.AddLinkSet(&tenant.LinkSets.AppProfiles, prof)

	err := tenant.Write()
	if err != nil {
		log.Errorf("Error updating tenant state(%+v). Err: %v", tenant, err)
		return err
	}

	err = CreateAppNw(prof)
	return err
}
829634
func (o *L2Domain) CreateApplicationperformancemanagementbinding(child *Applicationperformancemanagementbinding) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
379431
func (n *nessusImpl) CreateUser(username, password, userType, permissions, name, email string) (*User, error) {
	if n.verbose {
		log.Println("Creating new user...")
	}
	data := createUserRequest{
		Username:    username,
		Password:    password,
		Permissions: permissions,
		Type:        userType,
	}
	if name != "" {
		data.Name = name
	}
	if email != "" {
		data.Email = email
	}

	resp, err := n.doRequest("POST", "/users", data, []int{http.StatusOK})
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	reply := &User{}
	if err = json.NewDecoder(resp.Body).Decode(&reply); err != nil {
		return nil, err
	}
	return reply, nil
}
1240990
func (r *EvictionREST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {
	eviction := obj.(*policy.Eviction)

	deletionOptions, err := propagateDryRun(eviction, options)
	if err != nil {
		return nil, err
	}

	obj, err = r.store.Get(ctx, eviction.Name, &metav1.GetOptions{})
	if err != nil {
		return nil, err
	}
	pod := obj.(*api.Pod)

	if createValidation != nil {
		if err := createValidation(eviction.DeepCopyObject()); err != nil {
			return nil, err
		}
	}

	// Evicting a terminal pod should result in direct deletion of pod as it already caused disruption by the time we are evicting.
	// There is no need to check for pdb.
	if pod.Status.Phase == api.PodSucceeded || pod.Status.Phase == api.PodFailed {
		_, _, err = r.store.Delete(ctx, eviction.Name, deletionOptions)
		if err != nil {
			return nil, err
		}
		return &metav1.Status{
			Status: metav1.StatusSuccess}, nil
	}
	var rtStatus *metav1.Status
	var pdbName string
	err = retry.RetryOnConflict(EvictionsRetry, func() error {
		pdbs, err := r.getPodDisruptionBudgets(ctx, pod)
		if err != nil {
			return err
		}

		if len(pdbs) > 1 {
			rtStatus = &metav1.Status{
				Status:  metav1.StatusFailure,
				Message: "This pod has more than one PodDisruptionBudget, which the eviction subresource does not support.",
				Code:    500,
			}
			return nil
		} else if len(pdbs) == 1 {
			pdb := pdbs[0]
			pdbName = pdb.Name
			// Try to verify-and-decrement

			// If it was false already, or if it becomes false during the course of our retries,
			// raise an error marked as a 429.
			if err := r.checkAndDecrement(pod.Namespace, pod.Name, pdb, dryrun.IsDryRun(deletionOptions.DryRun)); err != nil {
				return err
			}
		}
		return nil
	})
	if err == wait.ErrWaitTimeout {
		err = errors.NewTimeoutError(fmt.Sprintf("couldn't update PodDisruptionBudget %q due to conflicts", pdbName), 10)
	}
	if err != nil {
		return nil, err
	}

	if rtStatus != nil {
		return rtStatus, nil
	}

	// At this point there was either no PDB or we succeeded in decrementing

	// Try the delete
	_, _, err = r.store.Delete(ctx, eviction.Name, deletionOptions)
	if err != nil {
		return nil, err
	}

	// Success!
	return &metav1.Status{Status: metav1.StatusSuccess}, nil
}
1167278
func Create(c *context.APIContext, opt api.CreateRepoOption) {
	// Shouldn't reach this condition, but just in case.
	if c.User.IsOrganization() {
		c.Error(422, "", "not allowed creating repository for organization")
		return
	}
	CreateUserRepo(c, c.User, opt)
}
89815
func (us UsersService) Create(username, email, token string) (User, error) {
	resp, err := newNetworkClient(us.config).MakeRequest(network.Request{
		Method:        "POST",
		Path:          "/Users",
		Authorization: network.NewTokenAuthorization(token),
		Body: network.NewJSONRequestBody(documents.CreateUserRequest{
			UserName: username,
			Emails: []documents.Email{
				{Value: email},
			},
		}),
		AcceptableStatusCodes: []int{http.StatusCreated},
	})
	if err != nil {
		return User{}, translateError(err)
	}

	var response documents.UserResponse
	err = json.Unmarshal(resp.Body, &response)
	if err != nil {
		return User{}, MalformedResponseError{err}
	}

	return newUserFromResponse(us.config, response), nil
}
406359
func CreateMyOrg(c *context.APIContext, apiForm api.CreateOrgOption) {
	CreateOrgForUser(c, apiForm, c.User)
}
1364432
func (s *Server) Create(ctx context.Context, q *RepoCreateRequest) (*appsv1.Repository, error) {
	if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceRepositories, rbacpolicy.ActionCreate, q.Repo.Repo); err != nil {
		return nil, err
	}
	r := q.Repo
	err := git.TestRepo(r.Repo, r.Username, r.Password, r.SSHPrivateKey, r.InsecureIgnoreHostKey)
	if err != nil {
		return nil, err
	}

	r.ConnectionState = appsv1.ConnectionState{Status: appsv1.ConnectionStatusSuccessful}
	repo, err := s.db.CreateRepository(ctx, r)
	if status.Convert(err).Code() == codes.AlreadyExists {
		// act idempotent if existing spec matches new spec
		existing, getErr := s.db.GetRepository(ctx, r.Repo)
		if getErr != nil {
			return nil, status.Errorf(codes.Internal, "unable to check existing repository details: %v", getErr)
		}

		// repository ConnectionState may differ, so make consistent before testing
		existing.ConnectionState = r.ConnectionState
		if reflect.DeepEqual(existing, r) {
			repo, err = existing, nil
		} else if q.Upsert {
			return s.Update(ctx, &RepoUpdateRequest{Repo: r})
		} else {
			return nil, status.Errorf(codes.InvalidArgument, "existing repository spec is different; use upsert flag to force update")
		}
	}
	return &appsv1.Repository{Repo: repo.Repo}, err
}
374726
func CreateAppProfile(obj *AppProfile) error {
	// Validate parameters
	err := ValidateAppProfile(obj)
	if err != nil {
		log.Errorf("ValidateAppProfile retruned error for: %+v. Err: %v", obj, err)
		return err
	}

	// Check if we handle this object
	if objCallbackHandler.AppProfileCb == nil {
		log.Errorf("No callback registered for appProfile object")
		return errors.New("Invalid object type")
	}

	saveObj := obj

	collections.appProfileMutex.Lock()
	key := collections.appProfiles[obj.Key]
	collections.appProfileMutex.Unlock()

	// Check if object already exists
	if key != nil {
		// Perform Update callback
		err = objCallbackHandler.AppProfileCb.AppProfileUpdate(collections.appProfiles[obj.Key], obj)
		if err != nil {
			log.Errorf("AppProfileUpdate retruned error for: %+v. Err: %v", obj, err)
			return err
		}

		// save the original object after update
		collections.appProfileMutex.Lock()
		saveObj = collections.appProfiles[obj.Key]
		collections.appProfileMutex.Unlock()
	} else {
		// save it in cache
		collections.appProfileMutex.Lock()
		collections.appProfiles[obj.Key] = obj
		collections.appProfileMutex.Unlock()

		// Perform Create callback
		err = objCallbackHandler.AppProfileCb.AppProfileCreate(obj)
		if err != nil {
			log.Errorf("AppProfileCreate retruned error for: %+v. Err: %v", obj, err)
			collections.appProfileMutex.Lock()
			delete(collections.appProfiles, obj.Key)
			collections.appProfileMutex.Unlock()
			return err
		}
	}

	// Write it to modeldb
	collections.appProfileMutex.Lock()
	err = saveObj.Write()
	collections.appProfileMutex.Unlock()
	if err != nil {
		log.Errorf("Error saving appProfile %s to db. Err: %v", saveObj.Key, err)
		return err
	}

	return nil
}
467525
func CreatePidFile(name string, perm os.FileMode) (lock *LockFile, err error) {
	if lock, err = OpenLockFile(name, perm); err != nil {
		return
	}
	if err = lock.Lock(); err != nil {
		lock.Remove()
		return
	}
	if err = lock.WritePid(); err != nil {
		lock.Remove()
	}
	return
}
753071
func (e *Enforcer) DeletePermissionForUser(user string, permission ...string) bool {
	params := make([]interface{}, 0, len(permission)+1)

	params = append(params, user)
	for _, perm := range permission {
		params = append(params, perm)
	}

	return e.RemovePolicy(params...)
}