// Create a tenant object
167343
func CreateTenant(obj *Tenant) error {
	// Validate parameters
	err := ValidateTenant(obj)
	if err != nil {
		log.Errorf("ValidateTenant retruned error for: %+v. Err: %v", obj, err)
		return err
	}

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

	saveObj := obj

	collections.tenantMutex.Lock()
	key := collections.tenants[obj.Key]
	collections.tenantMutex.Unlock()

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

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

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

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

	return nil
}
85007
func (b *EtcdBackend) Create(ctx context.Context, item backend.Item) (*backend.Lease, error) {
	var opts []clientv3.OpOption
	var lease backend.Lease
	if !item.Expires.IsZero() {
		if err := b.setupLease(ctx, item, &lease, &opts); err != nil {
			return nil, trace.Wrap(err)
		}
	}
	start := b.clock.Now()
	re, err := b.client.Txn(ctx).
		If(clientv3.Compare(clientv3.CreateRevision(prependPrefix(item.Key)), "=", 0)).
		Then(clientv3.OpPut(prependPrefix(item.Key), base64.StdEncoding.EncodeToString(item.Value), opts...)).
		Commit()
	txLatencies.Observe(time.Since(start).Seconds())
	txRequests.Inc()
	if err != nil {
		return nil, trace.Wrap(convertErr(err))
	}
	if !re.Succeeded {
		return nil, trace.AlreadyExists("%q already exists", string(item.Key))
	}
	return &lease, nil
}
1217694
func (ac *APIController) NetprofileCreate(netProfile *contivModel.Netprofile) error {
	log.Infof("Received NetprofileCreate: %+v", netProfile)

	// Check if the tenant exists
	if netProfile.TenantName == "" {
		return core.Errorf("Invalid tenant name")
	}

	if netProfile.Burst > 0 && netProfile.Burst < 2 {
		return core.Errorf("Invalid Burst size. burst size > 1500 bytes")
	}

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

	// Setup links & Linksets.
	modeldb.AddLink(&netProfile.Links.Tenant, tenant)
	modeldb.AddLinkSet(&tenant.LinkSets.NetProfiles, netProfile)

	// Save the tenant in etcd - This writes to etcd.
	err := tenant.Write()
	if err != nil {
		log.Errorf("Error updating tenant state(%+v). Err: %v", tenant, err)
		return err
	}

	return nil
}
373940
func (c *WorkitemsController) Create(ctx *app.CreateWorkitemsContext) error {
	currentUserIdentityID, err := login.ContextIdentity(ctx)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, errors.NewUnauthorizedError(err.Error()))
	}
	var space *space.Space
	err = application.Transactional(c.db, func(appl application.Application) error {
		// verify spaceID:
		// To be removed once we have endpoint like - /api/space/{spaceID}/workitems
		space, err = appl.Spaces().Load(ctx, ctx.SpaceID)
		if err != nil {
			log.Error(ctx, map[string]interface{}{
				"err":      err,
				"space_id": ctx.SpaceID,
			}, "unable to load space")
			return errors.NewBadParameterError("space", ctx.SpaceID.String()).Expected("valid space ID")
		}
		return nil
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	// FIXME
	// A workaround for https://github.com/fabric8-services/fabric8-wit/issues/1358
	// Allow any user to create a work item in spaces belong to the "openshiftio" user
	// Other spaces are open for the space collaborators only
	// ----
	spaceOwnerID := space.OwnerID.String()
	// check both the "openshiftio" user and the "test" user from the test realm.
	if "7b50ddb4-5e12-4031-bca7-3b88f92e2339" != spaceOwnerID && "ae68a343-c866-430c-b6ce-a36f0b38d8e5" != spaceOwnerID {
		authorized, err := authz.Authorize(ctx, ctx.SpaceID.String())
		if err != nil {
			return jsonapi.JSONErrorResponse(ctx, errors.NewInternalError(ctx, err))
		}
		if !authorized {
			return jsonapi.JSONErrorResponse(ctx, errors.NewForbiddenError("user is not authorized to access the space"))
		}
	}
	// ----

	var wit *uuid.UUID
	if ctx.Payload.Data != nil && ctx.Payload.Data.Relationships != nil &&
		ctx.Payload.Data.Relationships.BaseType != nil && ctx.Payload.Data.Relationships.BaseType.Data != nil {
		wit = &ctx.Payload.Data.Relationships.BaseType.Data.ID
	}
	if wit == nil { // TODO Figure out path source etc. Should be a required relation
		return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("Data.Relationships.BaseType.Data.ID", err))
	}

	// Set the space to the Payload
	if ctx.Payload.Data != nil && ctx.Payload.Data.Relationships != nil {
		// We overwrite or use the space ID in the URL to set the space of this WI
		spaceSelfURL := rest.AbsoluteURL(ctx.Request, app.SpaceHref(ctx.SpaceID.String()))
		ctx.Payload.Data.Relationships.Space = app.NewSpaceRelation(ctx.SpaceID, spaceSelfURL)
	}
	wi := &workitem.WorkItem{
		Fields: make(map[string]interface{}),
	}
	var rev *workitem.Revision
	err = application.Transactional(c.db, func(appl application.Application) error {
		//verify spaceID:
		// To be removed once we have endpoint like - /api/space/{spaceID}/workitems
		var err error
		err = appl.Spaces().CheckExists(ctx, ctx.SpaceID)
		if err != nil {
			return err
		}

		err = ConvertJSONAPIToWorkItem(ctx, ctx.Method, appl, *ctx.Payload.Data, wi, *wit, ctx.SpaceID)
		if err != nil {
			return errs.Wrap(err, fmt.Sprintf("Error creating work item"))
		}

		wi, rev, err = appl.WorkItems().Create(ctx, ctx.SpaceID, *wit, wi.Fields, *currentUserIdentityID)
		if err != nil {
			return errs.Wrap(err, fmt.Sprintf("Error creating work item"))
		}
		return nil
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	hasChildren := workItemIncludeHasChildren(ctx, c.db)
	workItemType, err := c.db.WorkItemTypes().Load(ctx, *wit)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	wi2, err := ConvertWorkItem(ctx.Request, *workItemType, *wi, hasChildren)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	resp := &app.WorkItemSingle{
		Data: wi2,
		Links: &app.WorkItemLinks{
			Self: buildAbsoluteURL(ctx.Request),
		},
	}
	ctx.ResponseData.Header().Set("Last-Modified", lastModified(*wi))
	ctx.ResponseData.Header().Set("Location", app.WorkitemHref(wi2.ID))
	c.notification.Send(ctx, notification.NewWorkItemCreated(wi.ID.String(), rev.ID))
	return ctx.Created(resp)
}
443527
func (env *environ) Create(ctx callcontext.ProviderCallContext, args environs.CreateParams) error {
	return env.withSession(ctx, func(env *sessionEnviron) error {
		return env.Create(ctx, args)
	})
}
929696
func (c *Client) CreateLogentries(i *CreateLogentriesInput) (*Logentries, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == 0 {
		return nil, ErrMissingVersion
	}

	path := fmt.Sprintf("/service/%s/version/%d/logging/logentries", i.Service, i.Version)
	resp, err := c.PostForm(path, i, nil)
	if err != nil {
		return nil, err
	}

	var l *Logentries
	if err := decodeJSON(&l, resp.Body); err != nil {
		return nil, err
	}
	return l, nil
}
1189516
func createEP(req *epSpec) (*epAttr, error) {

	// if the ep already exists, treat as error for now.
	netID := req.Network + "." + req.Tenant
	ep, err := utils.GetEndpoint(netID + "-" + req.EndpointID)
	if err == nil {
		return nil, fmt.Errorf("the EP %s already exists", req.EndpointID)
	}

	// Build endpoint request
	mreq := master.CreateEndpointRequest{
		TenantName:   req.Tenant,
		NetworkName:  req.Network,
		ServiceName:  req.Group,
		EndpointID:   req.EndpointID,
		EPCommonName: req.Name,
		ConfigEP: intent.ConfigEP{
			Container:   req.EndpointID,
			Host:        pluginHost,
			ServiceName: req.Group,
		},
	}

	var mresp master.CreateEndpointResponse
	err = cluster.MasterPostReq("/plugin/createEndpoint", &mreq, &mresp)
	if err != nil {
		epCleanUp(req)
		return nil, err
	}

	// this response should contain IPv6 if the underlying network is configured with IPv6
	log.Infof("Got endpoint create resp from master: %+v", mresp)

	// Ask netplugin to create the endpoint
	err = netPlugin.CreateEndpoint(netID + "-" + req.EndpointID)
	if err != nil {
		log.Errorf("Endpoint creation failed. Error: %s", err)
		epCleanUp(req)
		return nil, err
	}

	ep, err = utils.GetEndpoint(netID + "-" + req.EndpointID)
	if err != nil {
		epCleanUp(req)
		return nil, err
	}

	log.Debug(ep)
	// need to get the subnetlen from nw state.
	nw, err := utils.GetNetwork(netID)
	if err != nil {
		epCleanUp(req)
		return nil, err
	}

	epResponse := epAttr{}
	epResponse.PortName = ep.PortName
	epResponse.IPAddress = ep.IPAddress + "/" + strconv.Itoa(int(nw.SubnetLen))
	epResponse.Gateway = nw.Gateway

	if ep.IPv6Address != "" {
		epResponse.IPv6Address = ep.IPv6Address + "/" + strconv.Itoa(int(nw.IPv6SubnetLen))
		epResponse.IPv6Gateway = nw.IPv6Gateway
	}

	return &epResponse, nil
}
716628
func (c *QueryController) Create(ctx *app.CreateQueryContext) error {
	currentUserIdentityID, err := login.ContextIdentity(ctx)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, goa.ErrUnauthorized(err.Error()))
	}
	var q query.Query
	err = application.Transactional(c.db, func(appl application.Application) error {
		err = appl.Spaces().CheckExists(ctx, ctx.SpaceID)
		if err != nil {
			return err
		}
		q = query.Query{
			SpaceID: ctx.SpaceID,
			Fields:  ctx.Payload.Data.Attributes.Fields,
			Title:   strings.TrimSpace(ctx.Payload.Data.Attributes.Title),
			Creator: *currentUserIdentityID,
		}
		err = appl.Queries().Create(ctx, &q)
		return errs.WithStack(err)
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	res := &app.QuerySingle{
		Data: ConvertQuery(ctx.Request, q),
	}
	ctx.ResponseData.Header().Set("Location", rest.AbsoluteURL(ctx.Request, app.QueryHref(ctx.SpaceID, res.Data.ID)))
	return ctx.Created(res)
}
630040
func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {
	namespace, ok := apirequest.NamespaceFrom(ctx)
	if !ok {
		return nil, apierrors.NewBadRequest("namespace parameter required.")
	}
	rollback, ok := obj.(*appsapi.DeploymentConfigRollback)
	if !ok {
		return nil, apierrors.NewBadRequest(fmt.Sprintf("not a rollback spec: %#v", obj))
	}

	if errs := validation.ValidateDeploymentConfigRollback(rollback); len(errs) > 0 {
		return nil, apierrors.NewInvalid(apps.Kind("DeploymentConfigRollback"), rollback.Name, errs)
	}
	if err := createValidation(obj); err != nil {
		return nil, err
	}

	from, err := r.dn.DeploymentConfigs(namespace).Get(rollback.Name, metav1.GetOptions{})
	if err != nil {
		return nil, newInvalidError(rollback, fmt.Sprintf("cannot get deployment config %q: %v", rollback.Name, err))
	}

	switch from.Status.LatestVersion {
	case 0:
		return nil, newInvalidError(rollback, "cannot rollback an undeployed config")
	case 1:
		return nil, newInvalidError(rollback, fmt.Sprintf("no previous deployment exists for %q", appsutil.LabelForDeploymentConfig(from)))
	case rollback.Spec.Revision:
		return nil, newInvalidError(rollback, fmt.Sprintf("version %d is already the latest", rollback.Spec.Revision))
	}

	revision := from.Status.LatestVersion - 1
	if rollback.Spec.Revision > 0 {
		revision = rollback.Spec.Revision
	}

	// Find the target deployment and decode its config.
	name := appsutil.DeploymentNameForConfigVersion(from.Name, revision)
	targetDeployment, err := r.rn.ReplicationControllers(namespace).Get(name, metav1.GetOptions{})
	if err != nil {
		return nil, newInvalidError(rollback, err.Error())
	}

	to, err := appsutil.DecodeDeploymentConfig(targetDeployment)
	if err != nil {
		return nil, newInvalidError(rollback, fmt.Sprintf("couldn't decode deployment config from deployment: %v", err))
	}

	toInternal := &appsapi.DeploymentConfig{}
	if err := legacyscheme.Scheme.Convert(to, toInternal, nil); err != nil {
		return nil, apierrors.NewInternalError(err)
	}

	if from.Annotations == nil && len(rollback.UpdatedAnnotations) > 0 {
		from.Annotations = make(map[string]string)
	}
	for key, value := range rollback.UpdatedAnnotations {
		from.Annotations[key] = value
	}

	fromInternal := &appsapi.DeploymentConfig{}
	if err := legacyscheme.Scheme.Convert(from, fromInternal, nil); err != nil {
		return nil, apierrors.NewInternalError(err)
	}

	return r.generator.GenerateRollback(fromInternal, toInternal, &rollback.Spec)
}
38690
func (k *kubernetesClient) Create(context.ProviderCallContext, environs.CreateParams) error {
	// must raise errors.AlreadyExistsf if it's already exist.
	return k.createNamespace(k.namespace)
}
1319367
func (ps *PropertiesService) Create(ctx context.Context, name string, value string, pr *PropertyRequest) (responseIsValid bool, resp *APIResponse, err error) {
	responseBuffer := bytes.NewBuffer([]byte(""))

	ps.log.WithField("endpoint", "PropertiesServices.Create").Info("Calling endpoint")
	_, resp, err = ps.client.postAction(ctx, &APIClientRequest{
		Path: fmt.Sprintf("/properties/%s/%d/%s/%d/%s/%s",
			pr.Pipeline, pr.PipelineCounter,
			pr.Stage, pr.StageCounter,
			pr.Job, name,
		),
		ResponseType: responseTypeText,
		ResponseBody: responseBuffer,
		RequestBody:  fmt.Sprintf("%s=%s", name, value),
		Headers: map[string]string{
			"Confirm": "true",
		},
	})
	resp.Body = responseBuffer.String()
	responseIsValid = resp.Body == fmt.Sprintf("Property '%s' created with value '%s'", name, value)

	return
}
7907
def tenant_create(name, description=None, enabled=True, profile=None,
                  **connection_args):
    '''
    
    '''
    kstone = auth(profile, **connection_args)
    new = getattr(kstone, _TENANTS, None).create(name, description, enabled)
    return tenant_get(new.id, profile=profile, **connection_args)
1142477
func (s *CloneREST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {
	if err := rest.BeforeCreate(Strategy, ctx, obj); err != nil {
		return nil, err
	}
	if err := createValidation(obj); err != nil {
		return nil, err
	}

	return s.generator.CloneInternal(ctx, obj.(*buildapi.BuildRequest))
}
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
}
64044
func (c *FakeLeases) Create(lease *v1beta1.Lease) (result *v1beta1.Lease, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewCreateAction(leasesResource, c.ns, lease), &v1beta1.Lease{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.Lease), err
}
1240433
func (c *Client) createRequest() *http.Request {
	req := &http.Request{
		Proto:      "HTTP/1.1",
		ProtoMajor: 1,
		ProtoMinor: 1,
		Header:     make(http.Header),
		Host:       c.url.Host,
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add(tenantHeader, c.Tenant)

	if len(c.Credentials) > 0 {
		req.Header.Add("Authorization", fmt.Sprintf("Basic %s", c.Credentials))
	}

	if len(c.Token) > 0 {
		req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.Token))
	}

	return req
}
754132
func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
	contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
	return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
}