id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
157,700
juju/juju
state/application.go
SetAgentPresence
func (a *Application) SetAgentPresence() (*presence.Pinger, error) { presenceCollection := a.st.getPresenceCollection() recorder := a.st.getPingBatcher() m, err := a.st.Model() if err != nil { return nil, errors.Trace(err) } p := presence.NewPinger(presenceCollection, m.ModelTag(), a.globalKey(), func() presence.PingRecorder { return a.st.getPingBatcher() }) err = p.Start() if err != nil { return nil, err } // Make sure this Agent status is written to the database before returning. recorder.Sync() return p, nil }
go
func (a *Application) SetAgentPresence() (*presence.Pinger, error) { presenceCollection := a.st.getPresenceCollection() recorder := a.st.getPingBatcher() m, err := a.st.Model() if err != nil { return nil, errors.Trace(err) } p := presence.NewPinger(presenceCollection, m.ModelTag(), a.globalKey(), func() presence.PingRecorder { return a.st.getPingBatcher() }) err = p.Start() if err != nil { return nil, err } // Make sure this Agent status is written to the database before returning. recorder.Sync() return p, nil }
[ "func", "(", "a", "*", "Application", ")", "SetAgentPresence", "(", ")", "(", "*", "presence", ".", "Pinger", ",", "error", ")", "{", "presenceCollection", ":=", "a", ".", "st", ".", "getPresenceCollection", "(", ")", "\n", "recorder", ":=", "a", ".", "st", ".", "getPingBatcher", "(", ")", "\n", "m", ",", "err", ":=", "a", ".", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "p", ":=", "presence", ".", "NewPinger", "(", "presenceCollection", ",", "m", ".", "ModelTag", "(", ")", ",", "a", ".", "globalKey", "(", ")", ",", "func", "(", ")", "presence", ".", "PingRecorder", "{", "return", "a", ".", "st", ".", "getPingBatcher", "(", ")", "}", ")", "\n", "err", "=", "p", ".", "Start", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Make sure this Agent status is written to the database before returning.", "recorder", ".", "Sync", "(", ")", "\n", "return", "p", ",", "nil", "\n", "}" ]
// SetAgentPresence signals that the agent for application a is alive. // It returns the started pinger.
[ "SetAgentPresence", "signals", "that", "the", "agent", "for", "application", "a", "is", "alive", ".", "It", "returns", "the", "started", "pinger", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/application.go#L2982-L2998
157,701
juju/juju
state/application.go
UpdateCloudService
func (a *Application) UpdateCloudService(providerId string, addresses []network.Address) error { _, err := a.st.SaveCloudService(SaveCloudServiceArgs{ Id: a.Name(), ProviderId: providerId, Addresses: addresses, }) return errors.Trace(err) }
go
func (a *Application) UpdateCloudService(providerId string, addresses []network.Address) error { _, err := a.st.SaveCloudService(SaveCloudServiceArgs{ Id: a.Name(), ProviderId: providerId, Addresses: addresses, }) return errors.Trace(err) }
[ "func", "(", "a", "*", "Application", ")", "UpdateCloudService", "(", "providerId", "string", ",", "addresses", "[", "]", "network", ".", "Address", ")", "error", "{", "_", ",", "err", ":=", "a", ".", "st", ".", "SaveCloudService", "(", "SaveCloudServiceArgs", "{", "Id", ":", "a", ".", "Name", "(", ")", ",", "ProviderId", ":", "providerId", ",", "Addresses", ":", "addresses", ",", "}", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// UpdateCloudService updates the cloud service details for the application.
[ "UpdateCloudService", "updates", "the", "cloud", "service", "details", "for", "the", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/application.go#L3001-L3008
157,702
juju/juju
state/application.go
ServiceInfo
func (a *Application) ServiceInfo() (CloudService, error) { svc, err := a.st.CloudService(a.Name()) if err != nil { return CloudService{}, errors.Trace(err) } return *svc, nil }
go
func (a *Application) ServiceInfo() (CloudService, error) { svc, err := a.st.CloudService(a.Name()) if err != nil { return CloudService{}, errors.Trace(err) } return *svc, nil }
[ "func", "(", "a", "*", "Application", ")", "ServiceInfo", "(", ")", "(", "CloudService", ",", "error", ")", "{", "svc", ",", "err", ":=", "a", ".", "st", ".", "CloudService", "(", "a", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "CloudService", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "*", "svc", ",", "nil", "\n", "}" ]
// ServiceInfo returns information about this application's cloud service. // This is only used for CAAS models.
[ "ServiceInfo", "returns", "information", "about", "this", "application", "s", "cloud", "service", ".", "This", "is", "only", "used", "for", "CAAS", "models", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/application.go#L3012-L3018
157,703
juju/juju
state/application.go
UnitNames
func (a *Application) UnitNames() ([]string, error) { u, err := appUnitNames(a.st, a.Name()) return u, errors.Trace(err) }
go
func (a *Application) UnitNames() ([]string, error) { u, err := appUnitNames(a.st, a.Name()) return u, errors.Trace(err) }
[ "func", "(", "a", "*", "Application", ")", "UnitNames", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "u", ",", "err", ":=", "appUnitNames", "(", "a", ".", "st", ",", "a", ".", "Name", "(", ")", ")", "\n", "return", "u", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// UnitNames returns the of this application's units.
[ "UnitNames", "returns", "the", "of", "this", "application", "s", "units", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/application.go#L3032-L3035
157,704
juju/juju
apiserver/facades/client/modelgeneration/shim.go
Branch
func (g *modelShim) Branch(name string) (Generation, error) { m, err := g.Model.Branch(name) return m, errors.Trace(err) }
go
func (g *modelShim) Branch(name string) (Generation, error) { m, err := g.Model.Branch(name) return m, errors.Trace(err) }
[ "func", "(", "g", "*", "modelShim", ")", "Branch", "(", "name", "string", ")", "(", "Generation", ",", "error", ")", "{", "m", ",", "err", ":=", "g", ".", "Model", ".", "Branch", "(", "name", ")", "\n", "return", "m", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// Branch wraps the state model branch method, // returning the locally defined Generation interface.
[ "Branch", "wraps", "the", "state", "model", "branch", "method", "returning", "the", "locally", "defined", "Generation", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelgeneration/shim.go#L19-L22
157,705
juju/juju
apiserver/facades/client/modelgeneration/shim.go
Branches
func (g *modelShim) Branches() ([]Generation, error) { branches, err := g.Model.Branches() if err != nil { return nil, errors.Trace(err) } res := make([]Generation, len(branches)) for i, b := range branches { res[i] = b } return res, nil }
go
func (g *modelShim) Branches() ([]Generation, error) { branches, err := g.Model.Branches() if err != nil { return nil, errors.Trace(err) } res := make([]Generation, len(branches)) for i, b := range branches { res[i] = b } return res, nil }
[ "func", "(", "g", "*", "modelShim", ")", "Branches", "(", ")", "(", "[", "]", "Generation", ",", "error", ")", "{", "branches", ",", "err", ":=", "g", ".", "Model", ".", "Branches", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "res", ":=", "make", "(", "[", "]", "Generation", ",", "len", "(", "branches", ")", ")", "\n", "for", "i", ",", "b", ":=", "range", "branches", "{", "res", "[", "i", "]", "=", "b", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// Branches wraps the state model branches method, // returning a collection of the Generation interface.
[ "Branches", "wraps", "the", "state", "model", "branches", "method", "returning", "a", "collection", "of", "the", "Generation", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelgeneration/shim.go#L26-L37
157,706
juju/juju
apiserver/facades/client/modelgeneration/shim.go
DefaultCharmConfig
func (a *applicationShim) DefaultCharmConfig() (charm.Settings, error) { ch, _, err := a.Charm() if err != nil { return nil, errors.Trace(err) } return ch.Config().DefaultSettings(), nil }
go
func (a *applicationShim) DefaultCharmConfig() (charm.Settings, error) { ch, _, err := a.Charm() if err != nil { return nil, errors.Trace(err) } return ch.Config().DefaultSettings(), nil }
[ "func", "(", "a", "*", "applicationShim", ")", "DefaultCharmConfig", "(", ")", "(", "charm", ".", "Settings", ",", "error", ")", "{", "ch", ",", "_", ",", "err", ":=", "a", ".", "Charm", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "ch", ".", "Config", "(", ")", ".", "DefaultSettings", "(", ")", ",", "nil", "\n", "}" ]
// DefaultCharmConfig returns the default configuration // for this application's charm.
[ "DefaultCharmConfig", "returns", "the", "default", "configuration", "for", "this", "application", "s", "charm", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelgeneration/shim.go#L45-L51
157,707
juju/juju
provider/joyent/environ_instance.go
FindInstanceSpec
func (env *joyentEnviron) FindInstanceSpec( ic *instances.InstanceConstraint, imageMetadata []*imagemetadata.ImageMetadata, ) (*instances.InstanceSpec, error) { // Require at least one VCPU so we get KVM rather than smart package. if ic.Constraints.CpuCores == nil { ic.Constraints.CpuCores = &defaultCpuCores } allInstanceTypes, err := env.listInstanceTypes() if err != nil { return nil, err } images := instances.ImageMetadataToImages(imageMetadata) spec, err := instances.FindInstanceSpec(images, ic, allInstanceTypes) if err != nil { return nil, err } return spec, nil }
go
func (env *joyentEnviron) FindInstanceSpec( ic *instances.InstanceConstraint, imageMetadata []*imagemetadata.ImageMetadata, ) (*instances.InstanceSpec, error) { // Require at least one VCPU so we get KVM rather than smart package. if ic.Constraints.CpuCores == nil { ic.Constraints.CpuCores = &defaultCpuCores } allInstanceTypes, err := env.listInstanceTypes() if err != nil { return nil, err } images := instances.ImageMetadataToImages(imageMetadata) spec, err := instances.FindInstanceSpec(images, ic, allInstanceTypes) if err != nil { return nil, err } return spec, nil }
[ "func", "(", "env", "*", "joyentEnviron", ")", "FindInstanceSpec", "(", "ic", "*", "instances", ".", "InstanceConstraint", ",", "imageMetadata", "[", "]", "*", "imagemetadata", ".", "ImageMetadata", ",", ")", "(", "*", "instances", ".", "InstanceSpec", ",", "error", ")", "{", "// Require at least one VCPU so we get KVM rather than smart package.", "if", "ic", ".", "Constraints", ".", "CpuCores", "==", "nil", "{", "ic", ".", "Constraints", ".", "CpuCores", "=", "&", "defaultCpuCores", "\n", "}", "\n", "allInstanceTypes", ",", "err", ":=", "env", ".", "listInstanceTypes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "images", ":=", "instances", ".", "ImageMetadataToImages", "(", "imageMetadata", ")", "\n", "spec", ",", "err", ":=", "instances", ".", "FindInstanceSpec", "(", "images", ",", "ic", ",", "allInstanceTypes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "spec", ",", "nil", "\n", "}" ]
// FindInstanceSpec returns an InstanceSpec satisfying the supplied instanceConstraint.
[ "FindInstanceSpec", "returns", "an", "InstanceSpec", "satisfying", "the", "supplied", "instanceConstraint", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/joyent/environ_instance.go#L338-L356
157,708
juju/juju
apiserver/facades/client/applicationoffers/base.go
checkPermission
func (api *BaseAPI) checkPermission(tag names.Tag, perm permission.Access) error { allowed, err := api.Authorizer.HasPermission(perm, tag) if err != nil { return errors.Trace(err) } if !allowed { return common.ErrPerm } return nil }
go
func (api *BaseAPI) checkPermission(tag names.Tag, perm permission.Access) error { allowed, err := api.Authorizer.HasPermission(perm, tag) if err != nil { return errors.Trace(err) } if !allowed { return common.ErrPerm } return nil }
[ "func", "(", "api", "*", "BaseAPI", ")", "checkPermission", "(", "tag", "names", ".", "Tag", ",", "perm", "permission", ".", "Access", ")", "error", "{", "allowed", ",", "err", ":=", "api", ".", "Authorizer", ".", "HasPermission", "(", "perm", ",", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "allowed", "{", "return", "common", ".", "ErrPerm", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkPermission ensures that the logged in user holds the given permission on an entity.
[ "checkPermission", "ensures", "that", "the", "logged", "in", "user", "holds", "the", "given", "permission", "on", "an", "entity", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/applicationoffers/base.go#L37-L46
157,709
juju/juju
apiserver/facades/client/applicationoffers/base.go
checkAdmin
func (api *BaseAPI) checkAdmin(backend Backend) error { allowed, err := api.Authorizer.HasPermission(permission.AdminAccess, backend.ModelTag()) if err != nil { return errors.Trace(err) } if !allowed { allowed, err = api.Authorizer.HasPermission(permission.SuperuserAccess, backend.ControllerTag()) } if err != nil { return errors.Trace(err) } if !allowed { return common.ErrPerm } return nil }
go
func (api *BaseAPI) checkAdmin(backend Backend) error { allowed, err := api.Authorizer.HasPermission(permission.AdminAccess, backend.ModelTag()) if err != nil { return errors.Trace(err) } if !allowed { allowed, err = api.Authorizer.HasPermission(permission.SuperuserAccess, backend.ControllerTag()) } if err != nil { return errors.Trace(err) } if !allowed { return common.ErrPerm } return nil }
[ "func", "(", "api", "*", "BaseAPI", ")", "checkAdmin", "(", "backend", "Backend", ")", "error", "{", "allowed", ",", "err", ":=", "api", ".", "Authorizer", ".", "HasPermission", "(", "permission", ".", "AdminAccess", ",", "backend", ".", "ModelTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "allowed", "{", "allowed", ",", "err", "=", "api", ".", "Authorizer", ".", "HasPermission", "(", "permission", ".", "SuperuserAccess", ",", "backend", ".", "ControllerTag", "(", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "allowed", "{", "return", "common", ".", "ErrPerm", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkAdmin ensures that the logged in user is a model or controller admin.
[ "checkAdmin", "ensures", "that", "the", "logged", "in", "user", "is", "a", "model", "or", "controller", "admin", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/applicationoffers/base.go#L49-L64
157,710
juju/juju
apiserver/facades/client/applicationoffers/base.go
applicationOffersFromModel
func (api *BaseAPI) applicationOffersFromModel( modelUUID string, requiredAccess permission.Access, filters ...jujucrossmodel.ApplicationOfferFilter, ) ([]params.ApplicationOfferAdminDetails, error) { // Get the relevant backend for the specified model. backend, releaser, err := api.StatePool.Get(modelUUID) if err != nil { return nil, errors.Trace(err) } defer releaser() // If requireAdmin is true, the user must be a controller superuser // or model admin to proceed. isAdmin := false err = api.checkAdmin(backend) if err != nil && err != common.ErrPerm { return nil, errors.Trace(err) } isAdmin = err == nil if requiredAccess == permission.AdminAccess && !isAdmin { return nil, common.ErrPerm } offers, err := api.GetApplicationOffers(backend).ListOffers(filters...) if err != nil { return nil, errors.Trace(err) } apiUserTag := api.Authorizer.GetAuthTag().(names.UserTag) apiUserDisplayName, err := api.userDisplayName(backend, apiUserTag) if err != nil { return nil, errors.Trace(err) } var results []params.ApplicationOfferAdminDetails for _, appOffer := range offers { userAccess := permission.AdminAccess // If the user is not a model admin, they need at least read // access on an offer to see it. if !isAdmin { if userAccess, err = api.checkOfferAccess(backend, appOffer.OfferUUID, requiredAccess); err != nil { return nil, errors.Trace(err) } if userAccess == permission.NoAccess { continue } isAdmin = userAccess == permission.AdminAccess } offerParams, app, err := api.makeOfferParams(backend, &appOffer) // Just because we can't compose the result for one offer, log // that and move on to the next one. if err != nil { logger.Warningf("cannot get application offer: %v", err) continue } offerParams.Users = []params.OfferUserDetails{{ UserName: apiUserTag.Id(), DisplayName: apiUserDisplayName, Access: string(userAccess), }} offer := params.ApplicationOfferAdminDetails{ ApplicationOfferDetails: *offerParams, } // Only admins can see some sensitive details of the offer. if isAdmin { if err := api.getOfferAdminDetails(backend, app, &offer); err != nil { logger.Warningf("cannot get offer admin details: %v", err) } } results = append(results, offer) } return results, nil }
go
func (api *BaseAPI) applicationOffersFromModel( modelUUID string, requiredAccess permission.Access, filters ...jujucrossmodel.ApplicationOfferFilter, ) ([]params.ApplicationOfferAdminDetails, error) { // Get the relevant backend for the specified model. backend, releaser, err := api.StatePool.Get(modelUUID) if err != nil { return nil, errors.Trace(err) } defer releaser() // If requireAdmin is true, the user must be a controller superuser // or model admin to proceed. isAdmin := false err = api.checkAdmin(backend) if err != nil && err != common.ErrPerm { return nil, errors.Trace(err) } isAdmin = err == nil if requiredAccess == permission.AdminAccess && !isAdmin { return nil, common.ErrPerm } offers, err := api.GetApplicationOffers(backend).ListOffers(filters...) if err != nil { return nil, errors.Trace(err) } apiUserTag := api.Authorizer.GetAuthTag().(names.UserTag) apiUserDisplayName, err := api.userDisplayName(backend, apiUserTag) if err != nil { return nil, errors.Trace(err) } var results []params.ApplicationOfferAdminDetails for _, appOffer := range offers { userAccess := permission.AdminAccess // If the user is not a model admin, they need at least read // access on an offer to see it. if !isAdmin { if userAccess, err = api.checkOfferAccess(backend, appOffer.OfferUUID, requiredAccess); err != nil { return nil, errors.Trace(err) } if userAccess == permission.NoAccess { continue } isAdmin = userAccess == permission.AdminAccess } offerParams, app, err := api.makeOfferParams(backend, &appOffer) // Just because we can't compose the result for one offer, log // that and move on to the next one. if err != nil { logger.Warningf("cannot get application offer: %v", err) continue } offerParams.Users = []params.OfferUserDetails{{ UserName: apiUserTag.Id(), DisplayName: apiUserDisplayName, Access: string(userAccess), }} offer := params.ApplicationOfferAdminDetails{ ApplicationOfferDetails: *offerParams, } // Only admins can see some sensitive details of the offer. if isAdmin { if err := api.getOfferAdminDetails(backend, app, &offer); err != nil { logger.Warningf("cannot get offer admin details: %v", err) } } results = append(results, offer) } return results, nil }
[ "func", "(", "api", "*", "BaseAPI", ")", "applicationOffersFromModel", "(", "modelUUID", "string", ",", "requiredAccess", "permission", ".", "Access", ",", "filters", "...", "jujucrossmodel", ".", "ApplicationOfferFilter", ",", ")", "(", "[", "]", "params", ".", "ApplicationOfferAdminDetails", ",", "error", ")", "{", "// Get the relevant backend for the specified model.", "backend", ",", "releaser", ",", "err", ":=", "api", ".", "StatePool", ".", "Get", "(", "modelUUID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "releaser", "(", ")", "\n\n", "// If requireAdmin is true, the user must be a controller superuser", "// or model admin to proceed.", "isAdmin", ":=", "false", "\n", "err", "=", "api", ".", "checkAdmin", "(", "backend", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "common", ".", "ErrPerm", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "isAdmin", "=", "err", "==", "nil", "\n", "if", "requiredAccess", "==", "permission", ".", "AdminAccess", "&&", "!", "isAdmin", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n\n", "offers", ",", "err", ":=", "api", ".", "GetApplicationOffers", "(", "backend", ")", ".", "ListOffers", "(", "filters", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "apiUserTag", ":=", "api", ".", "Authorizer", ".", "GetAuthTag", "(", ")", ".", "(", "names", ".", "UserTag", ")", "\n", "apiUserDisplayName", ",", "err", ":=", "api", ".", "userDisplayName", "(", "backend", ",", "apiUserTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "var", "results", "[", "]", "params", ".", "ApplicationOfferAdminDetails", "\n", "for", "_", ",", "appOffer", ":=", "range", "offers", "{", "userAccess", ":=", "permission", ".", "AdminAccess", "\n", "// If the user is not a model admin, they need at least read", "// access on an offer to see it.", "if", "!", "isAdmin", "{", "if", "userAccess", ",", "err", "=", "api", ".", "checkOfferAccess", "(", "backend", ",", "appOffer", ".", "OfferUUID", ",", "requiredAccess", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "userAccess", "==", "permission", ".", "NoAccess", "{", "continue", "\n", "}", "\n", "isAdmin", "=", "userAccess", "==", "permission", ".", "AdminAccess", "\n", "}", "\n", "offerParams", ",", "app", ",", "err", ":=", "api", ".", "makeOfferParams", "(", "backend", ",", "&", "appOffer", ")", "\n", "// Just because we can't compose the result for one offer, log", "// that and move on to the next one.", "if", "err", "!=", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "offerParams", ".", "Users", "=", "[", "]", "params", ".", "OfferUserDetails", "{", "{", "UserName", ":", "apiUserTag", ".", "Id", "(", ")", ",", "DisplayName", ":", "apiUserDisplayName", ",", "Access", ":", "string", "(", "userAccess", ")", ",", "}", "}", "\n", "offer", ":=", "params", ".", "ApplicationOfferAdminDetails", "{", "ApplicationOfferDetails", ":", "*", "offerParams", ",", "}", "\n", "// Only admins can see some sensitive details of the offer.", "if", "isAdmin", "{", "if", "err", ":=", "api", ".", "getOfferAdminDetails", "(", "backend", ",", "app", ",", "&", "offer", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "results", "=", "append", "(", "results", ",", "offer", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// applicationOffersFromModel gets details about remote applications that match given filters.
[ "applicationOffersFromModel", "gets", "details", "about", "remote", "applications", "that", "match", "given", "filters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/applicationoffers/base.go#L106-L179
157,711
juju/juju
apiserver/facades/client/applicationoffers/base.go
checkOfferAccess
func (api *BaseAPI) checkOfferAccess(backend Backend, offerUUID string, perm permission.Access) (permission.Access, error) { apiUser := api.Authorizer.GetAuthTag().(names.UserTag) access, err := backend.GetOfferAccess(offerUUID, apiUser) if err != nil && !errors.IsNotFound(err) { return permission.NoAccess, errors.Trace(err) } if !access.EqualOrGreaterOfferAccessThan(permission.ReadAccess) { return permission.NoAccess, nil } return access, nil }
go
func (api *BaseAPI) checkOfferAccess(backend Backend, offerUUID string, perm permission.Access) (permission.Access, error) { apiUser := api.Authorizer.GetAuthTag().(names.UserTag) access, err := backend.GetOfferAccess(offerUUID, apiUser) if err != nil && !errors.IsNotFound(err) { return permission.NoAccess, errors.Trace(err) } if !access.EqualOrGreaterOfferAccessThan(permission.ReadAccess) { return permission.NoAccess, nil } return access, nil }
[ "func", "(", "api", "*", "BaseAPI", ")", "checkOfferAccess", "(", "backend", "Backend", ",", "offerUUID", "string", ",", "perm", "permission", ".", "Access", ")", "(", "permission", ".", "Access", ",", "error", ")", "{", "apiUser", ":=", "api", ".", "Authorizer", ".", "GetAuthTag", "(", ")", ".", "(", "names", ".", "UserTag", ")", "\n", "access", ",", "err", ":=", "backend", ".", "GetOfferAccess", "(", "offerUUID", ",", "apiUser", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "permission", ".", "NoAccess", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "access", ".", "EqualOrGreaterOfferAccessThan", "(", "permission", ".", "ReadAccess", ")", "{", "return", "permission", ".", "NoAccess", ",", "nil", "\n", "}", "\n", "return", "access", ",", "nil", "\n", "}" ]
// checkOfferAccess returns the level of access the authenticated user has to the offer, // so long as it is greater than the requested perm.
[ "checkOfferAccess", "returns", "the", "level", "of", "access", "the", "authenticated", "user", "has", "to", "the", "offer", "so", "long", "as", "it", "is", "greater", "than", "the", "requested", "perm", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/applicationoffers/base.go#L249-L259
157,712
juju/juju
apiserver/facades/client/applicationoffers/base.go
getModelsFromOffers
func (api *BaseAPI) getModelsFromOffers(offerURLs ...string) ([]offerModel, error) { // Cache the models found so far so we don't look them up more than once. modelsCache := make(map[string]Model) oneModel := func(offerURL string) (Model, error) { url, err := jujucrossmodel.ParseOfferURL(offerURL) if err != nil { return nil, errors.Trace(err) } modelPath := fmt.Sprintf("%s/%s", url.User, url.ModelName) if model, ok := modelsCache[modelPath]; ok { return model, nil } model, absModelPath, ok, err := api.modelForName(url.ModelName, url.User) if err != nil { return nil, errors.Trace(err) } if !ok { return nil, errors.NotFoundf("model %q", absModelPath) } return model, nil } result := make([]offerModel, len(offerURLs)) for i, offerURL := range offerURLs { var om offerModel om.model, om.err = oneModel(offerURL) result[i] = om } return result, nil }
go
func (api *BaseAPI) getModelsFromOffers(offerURLs ...string) ([]offerModel, error) { // Cache the models found so far so we don't look them up more than once. modelsCache := make(map[string]Model) oneModel := func(offerURL string) (Model, error) { url, err := jujucrossmodel.ParseOfferURL(offerURL) if err != nil { return nil, errors.Trace(err) } modelPath := fmt.Sprintf("%s/%s", url.User, url.ModelName) if model, ok := modelsCache[modelPath]; ok { return model, nil } model, absModelPath, ok, err := api.modelForName(url.ModelName, url.User) if err != nil { return nil, errors.Trace(err) } if !ok { return nil, errors.NotFoundf("model %q", absModelPath) } return model, nil } result := make([]offerModel, len(offerURLs)) for i, offerURL := range offerURLs { var om offerModel om.model, om.err = oneModel(offerURL) result[i] = om } return result, nil }
[ "func", "(", "api", "*", "BaseAPI", ")", "getModelsFromOffers", "(", "offerURLs", "...", "string", ")", "(", "[", "]", "offerModel", ",", "error", ")", "{", "// Cache the models found so far so we don't look them up more than once.", "modelsCache", ":=", "make", "(", "map", "[", "string", "]", "Model", ")", "\n", "oneModel", ":=", "func", "(", "offerURL", "string", ")", "(", "Model", ",", "error", ")", "{", "url", ",", "err", ":=", "jujucrossmodel", ".", "ParseOfferURL", "(", "offerURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "modelPath", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "url", ".", "User", ",", "url", ".", "ModelName", ")", "\n", "if", "model", ",", "ok", ":=", "modelsCache", "[", "modelPath", "]", ";", "ok", "{", "return", "model", ",", "nil", "\n", "}", "\n\n", "model", ",", "absModelPath", ",", "ok", ",", "err", ":=", "api", ".", "modelForName", "(", "url", ".", "ModelName", ",", "url", ".", "User", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "absModelPath", ")", "\n", "}", "\n", "return", "model", ",", "nil", "\n", "}", "\n\n", "result", ":=", "make", "(", "[", "]", "offerModel", ",", "len", "(", "offerURLs", ")", ")", "\n", "for", "i", ",", "offerURL", ":=", "range", "offerURLs", "{", "var", "om", "offerModel", "\n", "om", ".", "model", ",", "om", ".", "err", "=", "oneModel", "(", "offerURL", ")", "\n", "result", "[", "i", "]", "=", "om", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// getModelsFromOffers returns a slice of models corresponding to the // specified offer URLs. Each result item has either a model or an error.
[ "getModelsFromOffers", "returns", "a", "slice", "of", "models", "corresponding", "to", "the", "specified", "offer", "URLs", ".", "Each", "result", "item", "has", "either", "a", "model", "or", "an", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/applicationoffers/base.go#L268-L298
157,713
juju/juju
apiserver/facades/client/applicationoffers/base.go
getModelFilters
func (api *BaseAPI) getModelFilters(filters params.OfferFilters) ( models map[string]Model, filtersPerModel map[string][]jujucrossmodel.ApplicationOfferFilter, _ error, ) { models = make(map[string]Model) filtersPerModel = make(map[string][]jujucrossmodel.ApplicationOfferFilter) // Group the filters per model and then query each model with the relevant filters // for that model. modelUUIDs := make(map[string]string) for _, f := range filters.Filters { if f.ModelName == "" { return nil, nil, errors.New("application offer filter must specify a model name") } var ( modelUUID string ok bool ) if modelUUID, ok = modelUUIDs[f.ModelName]; !ok { var err error model, absModelPath, ok, err := api.modelForName(f.ModelName, f.OwnerName) if err != nil { return nil, nil, errors.Trace(err) } if !ok { err := errors.NotFoundf("model %q", absModelPath) return nil, nil, errors.Trace(err) } // Record the UUID and model for next time. modelUUID = model.UUID() modelUUIDs[f.ModelName] = modelUUID models[modelUUID] = model } // Record the filter and model details against the model UUID. filters := filtersPerModel[modelUUID] filter, err := makeOfferFilterFromParams(f) if err != nil { return nil, nil, errors.Trace(err) } filters = append(filters, filter) filtersPerModel[modelUUID] = filters } return models, filtersPerModel, nil }
go
func (api *BaseAPI) getModelFilters(filters params.OfferFilters) ( models map[string]Model, filtersPerModel map[string][]jujucrossmodel.ApplicationOfferFilter, _ error, ) { models = make(map[string]Model) filtersPerModel = make(map[string][]jujucrossmodel.ApplicationOfferFilter) // Group the filters per model and then query each model with the relevant filters // for that model. modelUUIDs := make(map[string]string) for _, f := range filters.Filters { if f.ModelName == "" { return nil, nil, errors.New("application offer filter must specify a model name") } var ( modelUUID string ok bool ) if modelUUID, ok = modelUUIDs[f.ModelName]; !ok { var err error model, absModelPath, ok, err := api.modelForName(f.ModelName, f.OwnerName) if err != nil { return nil, nil, errors.Trace(err) } if !ok { err := errors.NotFoundf("model %q", absModelPath) return nil, nil, errors.Trace(err) } // Record the UUID and model for next time. modelUUID = model.UUID() modelUUIDs[f.ModelName] = modelUUID models[modelUUID] = model } // Record the filter and model details against the model UUID. filters := filtersPerModel[modelUUID] filter, err := makeOfferFilterFromParams(f) if err != nil { return nil, nil, errors.Trace(err) } filters = append(filters, filter) filtersPerModel[modelUUID] = filters } return models, filtersPerModel, nil }
[ "func", "(", "api", "*", "BaseAPI", ")", "getModelFilters", "(", "filters", "params", ".", "OfferFilters", ")", "(", "models", "map", "[", "string", "]", "Model", ",", "filtersPerModel", "map", "[", "string", "]", "[", "]", "jujucrossmodel", ".", "ApplicationOfferFilter", ",", "_", "error", ",", ")", "{", "models", "=", "make", "(", "map", "[", "string", "]", "Model", ")", "\n", "filtersPerModel", "=", "make", "(", "map", "[", "string", "]", "[", "]", "jujucrossmodel", ".", "ApplicationOfferFilter", ")", "\n\n", "// Group the filters per model and then query each model with the relevant filters", "// for that model.", "modelUUIDs", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "f", ":=", "range", "filters", ".", "Filters", "{", "if", "f", ".", "ModelName", "==", "\"", "\"", "{", "return", "nil", ",", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "(", "modelUUID", "string", "\n", "ok", "bool", "\n", ")", "\n", "if", "modelUUID", ",", "ok", "=", "modelUUIDs", "[", "f", ".", "ModelName", "]", ";", "!", "ok", "{", "var", "err", "error", "\n", "model", ",", "absModelPath", ",", "ok", ",", "err", ":=", "api", ".", "modelForName", "(", "f", ".", "ModelName", ",", "f", ".", "OwnerName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "ok", "{", "err", ":=", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "absModelPath", ")", "\n", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// Record the UUID and model for next time.", "modelUUID", "=", "model", ".", "UUID", "(", ")", "\n", "modelUUIDs", "[", "f", ".", "ModelName", "]", "=", "modelUUID", "\n", "models", "[", "modelUUID", "]", "=", "model", "\n", "}", "\n\n", "// Record the filter and model details against the model UUID.", "filters", ":=", "filtersPerModel", "[", "modelUUID", "]", "\n", "filter", ",", "err", ":=", "makeOfferFilterFromParams", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "filters", "=", "append", "(", "filters", ",", "filter", ")", "\n", "filtersPerModel", "[", "modelUUID", "]", "=", "filters", "\n", "}", "\n", "return", "models", ",", "filtersPerModel", ",", "nil", "\n", "}" ]
// getModelFilters splits the specified filters per model and returns // the model and filter details for each.
[ "getModelFilters", "splits", "the", "specified", "filters", "per", "model", "and", "returns", "the", "model", "and", "filter", "details", "for", "each", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/applicationoffers/base.go#L302-L347
157,714
juju/juju
apiserver/facades/client/applicationoffers/base.go
getApplicationOffersDetails
func (api *BaseAPI) getApplicationOffersDetails( filters params.OfferFilters, requiredPermission permission.Access, ) ([]params.ApplicationOfferAdminDetails, error) { // If there are no filters specified, that's an error since the // caller is expected to specify at the least one or more models // to avoid an unbounded query across all models. if len(filters.Filters) == 0 { return nil, errors.New("at least one offer filter is required") } // Gather all the filter details for doing a query for each model. models, filtersPerModel, err := api.getModelFilters(filters) if err != nil { return nil, errors.Trace(err) } // Ensure the result is deterministic. var allUUIDs []string for modelUUID := range filtersPerModel { allUUIDs = append(allUUIDs, modelUUID) } sort.Strings(allUUIDs) // Do the per model queries. var result []params.ApplicationOfferAdminDetails for _, modelUUID := range allUUIDs { filters := filtersPerModel[modelUUID] offers, err := api.applicationOffersFromModel(modelUUID, requiredPermission, filters...) if err != nil { return nil, errors.Trace(err) } model := models[modelUUID] for _, offerDetails := range offers { offerDetails.OfferURL = jujucrossmodel.MakeURL(model.Owner().Name(), model.Name(), offerDetails.OfferName, "") result = append(result, offerDetails) } } return result, nil }
go
func (api *BaseAPI) getApplicationOffersDetails( filters params.OfferFilters, requiredPermission permission.Access, ) ([]params.ApplicationOfferAdminDetails, error) { // If there are no filters specified, that's an error since the // caller is expected to specify at the least one or more models // to avoid an unbounded query across all models. if len(filters.Filters) == 0 { return nil, errors.New("at least one offer filter is required") } // Gather all the filter details for doing a query for each model. models, filtersPerModel, err := api.getModelFilters(filters) if err != nil { return nil, errors.Trace(err) } // Ensure the result is deterministic. var allUUIDs []string for modelUUID := range filtersPerModel { allUUIDs = append(allUUIDs, modelUUID) } sort.Strings(allUUIDs) // Do the per model queries. var result []params.ApplicationOfferAdminDetails for _, modelUUID := range allUUIDs { filters := filtersPerModel[modelUUID] offers, err := api.applicationOffersFromModel(modelUUID, requiredPermission, filters...) if err != nil { return nil, errors.Trace(err) } model := models[modelUUID] for _, offerDetails := range offers { offerDetails.OfferURL = jujucrossmodel.MakeURL(model.Owner().Name(), model.Name(), offerDetails.OfferName, "") result = append(result, offerDetails) } } return result, nil }
[ "func", "(", "api", "*", "BaseAPI", ")", "getApplicationOffersDetails", "(", "filters", "params", ".", "OfferFilters", ",", "requiredPermission", "permission", ".", "Access", ",", ")", "(", "[", "]", "params", ".", "ApplicationOfferAdminDetails", ",", "error", ")", "{", "// If there are no filters specified, that's an error since the", "// caller is expected to specify at the least one or more models", "// to avoid an unbounded query across all models.", "if", "len", "(", "filters", ".", "Filters", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Gather all the filter details for doing a query for each model.", "models", ",", "filtersPerModel", ",", "err", ":=", "api", ".", "getModelFilters", "(", "filters", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Ensure the result is deterministic.", "var", "allUUIDs", "[", "]", "string", "\n", "for", "modelUUID", ":=", "range", "filtersPerModel", "{", "allUUIDs", "=", "append", "(", "allUUIDs", ",", "modelUUID", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "allUUIDs", ")", "\n\n", "// Do the per model queries.", "var", "result", "[", "]", "params", ".", "ApplicationOfferAdminDetails", "\n", "for", "_", ",", "modelUUID", ":=", "range", "allUUIDs", "{", "filters", ":=", "filtersPerModel", "[", "modelUUID", "]", "\n", "offers", ",", "err", ":=", "api", ".", "applicationOffersFromModel", "(", "modelUUID", ",", "requiredPermission", ",", "filters", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "model", ":=", "models", "[", "modelUUID", "]", "\n\n", "for", "_", ",", "offerDetails", ":=", "range", "offers", "{", "offerDetails", ".", "OfferURL", "=", "jujucrossmodel", ".", "MakeURL", "(", "model", ".", "Owner", "(", ")", ".", "Name", "(", ")", ",", "model", ".", "Name", "(", ")", ",", "offerDetails", ".", "OfferName", ",", "\"", "\"", ")", "\n", "result", "=", "append", "(", "result", ",", "offerDetails", ")", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// getApplicationOffersDetails gets details about remote applications that match given filter.
[ "getApplicationOffersDetails", "gets", "details", "about", "remote", "applications", "that", "match", "given", "filter", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/applicationoffers/base.go#L350-L391
157,715
juju/juju
container/directory.go
NewDirectory
func NewDirectory(containerName string) (directory string, err error) { directory = dirForName(containerName) logger.Tracef("create directory: %s", directory) if err = os.MkdirAll(directory, 0755); err != nil { logger.Errorf("failed to create container directory: %v", err) return "", err } return directory, nil }
go
func NewDirectory(containerName string) (directory string, err error) { directory = dirForName(containerName) logger.Tracef("create directory: %s", directory) if err = os.MkdirAll(directory, 0755); err != nil { logger.Errorf("failed to create container directory: %v", err) return "", err } return directory, nil }
[ "func", "NewDirectory", "(", "containerName", "string", ")", "(", "directory", "string", ",", "err", "error", ")", "{", "directory", "=", "dirForName", "(", "containerName", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "directory", ")", "\n", "if", "err", "=", "os", ".", "MkdirAll", "(", "directory", ",", "0755", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "directory", ",", "nil", "\n", "}" ]
// NewDirectory creates a new directory for the container name in the // directory identified by `ContainerDir`.
[ "NewDirectory", "creates", "a", "new", "directory", "for", "the", "container", "name", "in", "the", "directory", "identified", "by", "ContainerDir", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/directory.go#L22-L30
157,716
juju/juju
container/directory.go
RemoveDirectory
func RemoveDirectory(containerName string) error { // Move the directory. logger.Tracef("create old container dir: %s", RemovedContainerDir) if err := os.MkdirAll(RemovedContainerDir, 0755); err != nil { logger.Errorf("failed to create removed container directory: %v", err) return err } removedDir, err := utils.UniqueDirectory(RemovedContainerDir, containerName) if err != nil { logger.Errorf("was not able to generate a unique directory: %v", err) return err } if err := os.Rename(dirForName(containerName), removedDir); err != nil { logger.Errorf("failed to rename container directory: %v", err) return err } return nil }
go
func RemoveDirectory(containerName string) error { // Move the directory. logger.Tracef("create old container dir: %s", RemovedContainerDir) if err := os.MkdirAll(RemovedContainerDir, 0755); err != nil { logger.Errorf("failed to create removed container directory: %v", err) return err } removedDir, err := utils.UniqueDirectory(RemovedContainerDir, containerName) if err != nil { logger.Errorf("was not able to generate a unique directory: %v", err) return err } if err := os.Rename(dirForName(containerName), removedDir); err != nil { logger.Errorf("failed to rename container directory: %v", err) return err } return nil }
[ "func", "RemoveDirectory", "(", "containerName", "string", ")", "error", "{", "// Move the directory.", "logger", ".", "Tracef", "(", "\"", "\"", ",", "RemovedContainerDir", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "RemovedContainerDir", ",", "0755", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "removedDir", ",", "err", ":=", "utils", ".", "UniqueDirectory", "(", "RemovedContainerDir", ",", "containerName", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Rename", "(", "dirForName", "(", "containerName", ")", ",", "removedDir", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n\n", "}" ]
// RemoveDirectory moves the container directory from `ContainerDir` // to `RemovedContainerDir` and makes sure that the names don't clash.
[ "RemoveDirectory", "moves", "the", "container", "directory", "from", "ContainerDir", "to", "RemovedContainerDir", "and", "makes", "sure", "that", "the", "names", "don", "t", "clash", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/directory.go#L34-L52
157,717
juju/juju
api/machiner/machiner.go
NewState
func NewState(caller base.APICaller) *State { facadeCaller := base.NewFacadeCaller(caller, machinerFacade) return &State{ facade: facadeCaller, APIAddresser: common.NewAPIAddresser(facadeCaller), } }
go
func NewState(caller base.APICaller) *State { facadeCaller := base.NewFacadeCaller(caller, machinerFacade) return &State{ facade: facadeCaller, APIAddresser: common.NewAPIAddresser(facadeCaller), } }
[ "func", "NewState", "(", "caller", "base", ".", "APICaller", ")", "*", "State", "{", "facadeCaller", ":=", "base", ".", "NewFacadeCaller", "(", "caller", ",", "machinerFacade", ")", "\n", "return", "&", "State", "{", "facade", ":", "facadeCaller", ",", "APIAddresser", ":", "common", ".", "NewAPIAddresser", "(", "facadeCaller", ")", ",", "}", "\n", "}" ]
// NewState creates a new client-side Machiner facade.
[ "NewState", "creates", "a", "new", "client", "-", "side", "Machiner", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/machiner/machiner.go#L24-L30
157,718
juju/juju
api/uniter/relationunit.go
Watch
func (ru *RelationUnit) Watch() (watcher.RelationUnitsWatcher, error) { return ru.st.WatchRelationUnits(ru.relation.tag, ru.unit.tag) }
go
func (ru *RelationUnit) Watch() (watcher.RelationUnitsWatcher, error) { return ru.st.WatchRelationUnits(ru.relation.tag, ru.unit.tag) }
[ "func", "(", "ru", "*", "RelationUnit", ")", "Watch", "(", ")", "(", "watcher", ".", "RelationUnitsWatcher", ",", "error", ")", "{", "return", "ru", ".", "st", ".", "WatchRelationUnits", "(", "ru", ".", "relation", ".", "tag", ",", "ru", ".", "unit", ".", "tag", ")", "\n", "}" ]
// Watch returns a watcher that notifies of changes to counterpart // units in the relation.
[ "Watch", "returns", "a", "watcher", "that", "notifies", "of", "changes", "to", "counterpart", "units", "in", "the", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/relationunit.go#L157-L159
157,719
juju/juju
state/cleanup.go
SetBSON
func (a *cleanupArg) SetBSON(raw bson.Raw) error { a.Value = raw return nil }
go
func (a *cleanupArg) SetBSON(raw bson.Raw) error { a.Value = raw return nil }
[ "func", "(", "a", "*", "cleanupArg", ")", "SetBSON", "(", "raw", "bson", ".", "Raw", ")", "error", "{", "a", ".", "Value", "=", "raw", "\n", "return", "nil", "\n", "}" ]
// SetBSON is part of the bson.Setter interface.
[ "SetBSON", "is", "part", "of", "the", "bson", ".", "Setter", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L80-L83
157,720
juju/juju
state/cleanup.go
newCleanupOp
func newCleanupOp(kind cleanupKind, prefix string, args ...interface{}) txn.Op { return newCleanupAtOp(asap, kind, prefix, args...) }
go
func newCleanupOp(kind cleanupKind, prefix string, args ...interface{}) txn.Op { return newCleanupAtOp(asap, kind, prefix, args...) }
[ "func", "newCleanupOp", "(", "kind", "cleanupKind", ",", "prefix", "string", ",", "args", "...", "interface", "{", "}", ")", "txn", ".", "Op", "{", "return", "newCleanupAtOp", "(", "asap", ",", "kind", ",", "prefix", ",", "args", "...", ")", "\n", "}" ]
// newCleanupOp returns a txn.Op that creates a cleanup document with a unique // id and the supplied kind and prefix.
[ "newCleanupOp", "returns", "a", "txn", ".", "Op", "that", "creates", "a", "cleanup", "document", "with", "a", "unique", "id", "and", "the", "supplied", "kind", "and", "prefix", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L87-L89
157,721
juju/juju
state/cleanup.go
NeedsCleanup
func (st *State) NeedsCleanup() (bool, error) { cleanups, closer := st.db().GetCollection(cleanupsC) defer closer() count, err := cleanups.Count() if err != nil { return false, err } return count > 0, nil }
go
func (st *State) NeedsCleanup() (bool, error) { cleanups, closer := st.db().GetCollection(cleanupsC) defer closer() count, err := cleanups.Count() if err != nil { return false, err } return count > 0, nil }
[ "func", "(", "st", "*", "State", ")", "NeedsCleanup", "(", ")", "(", "bool", ",", "error", ")", "{", "cleanups", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "cleanupsC", ")", "\n", "defer", "closer", "(", ")", "\n", "count", ",", "err", ":=", "cleanups", ".", "Count", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "count", ">", "0", ",", "nil", "\n", "}" ]
// NeedsCleanup returns true if documents previously marked for removal exist.
[ "NeedsCleanup", "returns", "true", "if", "documents", "previously", "marked", "for", "removal", "exist", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L114-L122
157,722
juju/juju
state/cleanup.go
cleanupModelsForDyingController
func (st *State) cleanupModelsForDyingController(cleanupArgs []bson.Raw) (err error) { var args DestroyModelParams switch n := len(cleanupArgs); n { case 0: // Old cleanups have no args, so follow the old behaviour. destroyStorage := true args.DestroyStorage = &destroyStorage case 1: if err := cleanupArgs[0].Unmarshal(&args); err != nil { return errors.Annotate(err, "unmarshalling cleanup args") } default: return errors.Errorf("expected 0-1 arguments, got %d", n) } modelUUIDs, err := st.AllModelUUIDs() if err != nil { return errors.Trace(err) } for _, modelUUID := range modelUUIDs { newSt, err := st.newStateNoWorkers(modelUUID) // We explicitly don't start the workers. if err != nil { // This model could have been removed. if errors.IsNotFound(err) { continue } return errors.Trace(err) } defer newSt.Close() model, err := newSt.Model() if err != nil { return errors.Trace(err) } if err := model.Destroy(args); err != nil { return errors.Trace(err) } } return nil }
go
func (st *State) cleanupModelsForDyingController(cleanupArgs []bson.Raw) (err error) { var args DestroyModelParams switch n := len(cleanupArgs); n { case 0: // Old cleanups have no args, so follow the old behaviour. destroyStorage := true args.DestroyStorage = &destroyStorage case 1: if err := cleanupArgs[0].Unmarshal(&args); err != nil { return errors.Annotate(err, "unmarshalling cleanup args") } default: return errors.Errorf("expected 0-1 arguments, got %d", n) } modelUUIDs, err := st.AllModelUUIDs() if err != nil { return errors.Trace(err) } for _, modelUUID := range modelUUIDs { newSt, err := st.newStateNoWorkers(modelUUID) // We explicitly don't start the workers. if err != nil { // This model could have been removed. if errors.IsNotFound(err) { continue } return errors.Trace(err) } defer newSt.Close() model, err := newSt.Model() if err != nil { return errors.Trace(err) } if err := model.Destroy(args); err != nil { return errors.Trace(err) } } return nil }
[ "func", "(", "st", "*", "State", ")", "cleanupModelsForDyingController", "(", "cleanupArgs", "[", "]", "bson", ".", "Raw", ")", "(", "err", "error", ")", "{", "var", "args", "DestroyModelParams", "\n", "switch", "n", ":=", "len", "(", "cleanupArgs", ")", ";", "n", "{", "case", "0", ":", "// Old cleanups have no args, so follow the old behaviour.", "destroyStorage", ":=", "true", "\n", "args", ".", "DestroyStorage", "=", "&", "destroyStorage", "\n", "case", "1", ":", "if", "err", ":=", "cleanupArgs", "[", "0", "]", ".", "Unmarshal", "(", "&", "args", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n", "modelUUIDs", ",", "err", ":=", "st", ".", "AllModelUUIDs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "modelUUID", ":=", "range", "modelUUIDs", "{", "newSt", ",", "err", ":=", "st", ".", "newStateNoWorkers", "(", "modelUUID", ")", "\n", "// We explicitly don't start the workers.", "if", "err", "!=", "nil", "{", "// This model could have been removed.", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "continue", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "newSt", ".", "Close", "(", ")", "\n\n", "model", ",", "err", ":=", "newSt", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "model", ".", "Destroy", "(", "args", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cleanupModelsForDyingController sets all models to dying, if // they are not already Dying or Dead. It's expected to be used when a // controller is destroyed.
[ "cleanupModelsForDyingController", "sets", "all", "models", "to", "dying", "if", "they", "are", "not", "already", "Dying", "or", "Dead", ".", "It", "s", "expected", "to", "be", "used", "when", "a", "controller", "is", "destroyed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L240-L280
157,723
juju/juju
state/cleanup.go
cleanupMachinesForDyingModel
func (st *State) cleanupMachinesForDyingModel(cleanupArgs []bson.Raw) (err error) { var args DestroyModelParams switch n := len(cleanupArgs); n { case 0: // Old cleanups have no args, so follow the old behaviour. case 1: if err := cleanupArgs[0].Unmarshal(&args); err != nil { return errors.Annotate(err, "unmarshalling cleanup 'destroy model' args") } default: return errors.Errorf("expected 0-1 arguments, got %d", n) } // This won't miss machines, because a Dying model cannot have // machines added to it. But we do have to remove the machines themselves // via individual transactions, because they could be in any state at all. machines, err := st.AllMachines() if err != nil { return errors.Trace(err) } force := args.Force != nil && *args.Force for _, m := range machines { if m.IsManager() { continue } if _, isContainer := m.ParentId(); isContainer { continue } manual, err := m.IsManual() if err != nil { // TODO (force 2019-4-24) we should not break out here but continue with other machines. return errors.Trace(err) } if manual { // Manually added machines should never be force- // destroyed automatically. That should be a user- // driven decision, since it may leak applications // and resources on the machine. If something is // stuck, then the user can still force-destroy // the manual machines. if err := m.Destroy(); err != nil { // Since we cannot delete a manual machine, we cannot proceed with model destruction even if it is forced. // TODO (force 2019-4-24) However, we should not break out here but continue with other machines. return errors.Trace(errors.Annotatef(err, "could not destroy manual machine %v", m.Id())) } return nil } // TODO (force 2019-04-26) Should this always be ForceDestroy or only when // 'destroy-model --force' is specified?... if err := m.ForceDestroy(args.MaxWait); err != nil { err = errors.Annotatef(err, "while destroying machine %v is", m.Id()) // TODO (force 2019-4-24) we should not break out here but continue with other machines. if !force { return errors.Trace(err) } logger.Warningf("%v", err) } } return nil }
go
func (st *State) cleanupMachinesForDyingModel(cleanupArgs []bson.Raw) (err error) { var args DestroyModelParams switch n := len(cleanupArgs); n { case 0: // Old cleanups have no args, so follow the old behaviour. case 1: if err := cleanupArgs[0].Unmarshal(&args); err != nil { return errors.Annotate(err, "unmarshalling cleanup 'destroy model' args") } default: return errors.Errorf("expected 0-1 arguments, got %d", n) } // This won't miss machines, because a Dying model cannot have // machines added to it. But we do have to remove the machines themselves // via individual transactions, because they could be in any state at all. machines, err := st.AllMachines() if err != nil { return errors.Trace(err) } force := args.Force != nil && *args.Force for _, m := range machines { if m.IsManager() { continue } if _, isContainer := m.ParentId(); isContainer { continue } manual, err := m.IsManual() if err != nil { // TODO (force 2019-4-24) we should not break out here but continue with other machines. return errors.Trace(err) } if manual { // Manually added machines should never be force- // destroyed automatically. That should be a user- // driven decision, since it may leak applications // and resources on the machine. If something is // stuck, then the user can still force-destroy // the manual machines. if err := m.Destroy(); err != nil { // Since we cannot delete a manual machine, we cannot proceed with model destruction even if it is forced. // TODO (force 2019-4-24) However, we should not break out here but continue with other machines. return errors.Trace(errors.Annotatef(err, "could not destroy manual machine %v", m.Id())) } return nil } // TODO (force 2019-04-26) Should this always be ForceDestroy or only when // 'destroy-model --force' is specified?... if err := m.ForceDestroy(args.MaxWait); err != nil { err = errors.Annotatef(err, "while destroying machine %v is", m.Id()) // TODO (force 2019-4-24) we should not break out here but continue with other machines. if !force { return errors.Trace(err) } logger.Warningf("%v", err) } } return nil }
[ "func", "(", "st", "*", "State", ")", "cleanupMachinesForDyingModel", "(", "cleanupArgs", "[", "]", "bson", ".", "Raw", ")", "(", "err", "error", ")", "{", "var", "args", "DestroyModelParams", "\n", "switch", "n", ":=", "len", "(", "cleanupArgs", ")", ";", "n", "{", "case", "0", ":", "// Old cleanups have no args, so follow the old behaviour.", "case", "1", ":", "if", "err", ":=", "cleanupArgs", "[", "0", "]", ".", "Unmarshal", "(", "&", "args", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n", "// This won't miss machines, because a Dying model cannot have", "// machines added to it. But we do have to remove the machines themselves", "// via individual transactions, because they could be in any state at all.", "machines", ",", "err", ":=", "st", ".", "AllMachines", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "force", ":=", "args", ".", "Force", "!=", "nil", "&&", "*", "args", ".", "Force", "\n", "for", "_", ",", "m", ":=", "range", "machines", "{", "if", "m", ".", "IsManager", "(", ")", "{", "continue", "\n", "}", "\n", "if", "_", ",", "isContainer", ":=", "m", ".", "ParentId", "(", ")", ";", "isContainer", "{", "continue", "\n", "}", "\n", "manual", ",", "err", ":=", "m", ".", "IsManual", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// TODO (force 2019-4-24) we should not break out here but continue with other machines.", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "manual", "{", "// Manually added machines should never be force-", "// destroyed automatically. That should be a user-", "// driven decision, since it may leak applications", "// and resources on the machine. If something is", "// stuck, then the user can still force-destroy", "// the manual machines.", "if", "err", ":=", "m", ".", "Destroy", "(", ")", ";", "err", "!=", "nil", "{", "// Since we cannot delete a manual machine, we cannot proceed with model destruction even if it is forced.", "// TODO (force 2019-4-24) However, we should not break out here but continue with other machines.", "return", "errors", ".", "Trace", "(", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "m", ".", "Id", "(", ")", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "// TODO (force 2019-04-26) Should this always be ForceDestroy or only when", "// 'destroy-model --force' is specified?...", "if", "err", ":=", "m", ".", "ForceDestroy", "(", "args", ".", "MaxWait", ")", ";", "err", "!=", "nil", "{", "err", "=", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "m", ".", "Id", "(", ")", ")", "\n", "// TODO (force 2019-4-24) we should not break out here but continue with other machines.", "if", "!", "force", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cleanupMachinesForDyingModel sets all non-manager machines to Dying, // if they are not already Dying or Dead. It's expected to be used when // a model is destroyed.
[ "cleanupMachinesForDyingModel", "sets", "all", "non", "-", "manager", "machines", "to", "Dying", "if", "they", "are", "not", "already", "Dying", "or", "Dead", ".", "It", "s", "expected", "to", "be", "used", "when", "a", "model", "is", "destroyed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L285-L343
157,724
juju/juju
state/cleanup.go
cleanupStorageForDyingModel
func (st *State) cleanupStorageForDyingModel(cleanupArgs []bson.Raw) (err error) { sb, err := NewStorageBackend(st) if err != nil { return errors.Trace(err) } var args DestroyModelParams switch n := len(cleanupArgs); n { case 0: // Old cleanups have no args, so follow the old behaviour. case 1: if err := cleanupArgs[0].Unmarshal(&args); err != nil { return errors.Annotate(err, "unmarshalling cleanup 'destroy model' args") } default: return errors.Errorf("expected 0-1 arguments, got %d", n) } destroyStorage := sb.DestroyStorageInstance if args.DestroyStorage == nil || !*args.DestroyStorage { destroyStorage = sb.ReleaseStorageInstance } storage, err := sb.AllStorageInstances() if err != nil { return errors.Trace(err) } force := args.Force != nil && *args.Force for _, s := range storage { const destroyAttached = true err := destroyStorage(s.StorageTag(), destroyAttached, force, args.MaxWait) if errors.IsNotFound(err) { continue } else if err != nil { return errors.Trace(err) } } return nil }
go
func (st *State) cleanupStorageForDyingModel(cleanupArgs []bson.Raw) (err error) { sb, err := NewStorageBackend(st) if err != nil { return errors.Trace(err) } var args DestroyModelParams switch n := len(cleanupArgs); n { case 0: // Old cleanups have no args, so follow the old behaviour. case 1: if err := cleanupArgs[0].Unmarshal(&args); err != nil { return errors.Annotate(err, "unmarshalling cleanup 'destroy model' args") } default: return errors.Errorf("expected 0-1 arguments, got %d", n) } destroyStorage := sb.DestroyStorageInstance if args.DestroyStorage == nil || !*args.DestroyStorage { destroyStorage = sb.ReleaseStorageInstance } storage, err := sb.AllStorageInstances() if err != nil { return errors.Trace(err) } force := args.Force != nil && *args.Force for _, s := range storage { const destroyAttached = true err := destroyStorage(s.StorageTag(), destroyAttached, force, args.MaxWait) if errors.IsNotFound(err) { continue } else if err != nil { return errors.Trace(err) } } return nil }
[ "func", "(", "st", "*", "State", ")", "cleanupStorageForDyingModel", "(", "cleanupArgs", "[", "]", "bson", ".", "Raw", ")", "(", "err", "error", ")", "{", "sb", ",", "err", ":=", "NewStorageBackend", "(", "st", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "args", "DestroyModelParams", "\n", "switch", "n", ":=", "len", "(", "cleanupArgs", ")", ";", "n", "{", "case", "0", ":", "// Old cleanups have no args, so follow the old behaviour.", "case", "1", ":", "if", "err", ":=", "cleanupArgs", "[", "0", "]", ".", "Unmarshal", "(", "&", "args", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n\n", "destroyStorage", ":=", "sb", ".", "DestroyStorageInstance", "\n", "if", "args", ".", "DestroyStorage", "==", "nil", "||", "!", "*", "args", ".", "DestroyStorage", "{", "destroyStorage", "=", "sb", ".", "ReleaseStorageInstance", "\n", "}", "\n\n", "storage", ",", "err", ":=", "sb", ".", "AllStorageInstances", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "force", ":=", "args", ".", "Force", "!=", "nil", "&&", "*", "args", ".", "Force", "\n", "for", "_", ",", "s", ":=", "range", "storage", "{", "const", "destroyAttached", "=", "true", "\n", "err", ":=", "destroyStorage", "(", "s", ".", "StorageTag", "(", ")", ",", "destroyAttached", ",", "force", ",", "args", ".", "MaxWait", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "continue", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cleanupStorageForDyingModel sets all storage to Dying, if they are not // already Dying or Dead. It's expected to be used when a model is destroyed.
[ "cleanupStorageForDyingModel", "sets", "all", "storage", "to", "Dying", "if", "they", "are", "not", "already", "Dying", "or", "Dead", ".", "It", "s", "expected", "to", "be", "used", "when", "a", "model", "is", "destroyed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L347-L384
157,725
juju/juju
state/cleanup.go
cleanupApplication
func (st *State) cleanupApplication(applicationname string, cleanupArgs []bson.Raw) (err error) { app, err := st.Application(applicationname) if err != nil { if errors.IsNotFound(err) { // Nothing to do, the application is already gone. logger.Tracef("cleanupApplication(%s): application already gone", applicationname) return nil } return errors.Trace(err) } if app.Life() == Alive { return errors.BadRequestf("cleanupApplication requested for an application (%s) that is still alive", applicationname) } // We know the app is at least Dying, so check if the unit/relation counts are no longer referencing this application. if app.UnitCount() > 0 || app.RelationCount() > 0 { // this is considered a no-op because whatever is currently referencing the application // should queue up a new cleanup once it stops logger.Tracef("cleanupApplication(%s) called, but it still has references: unitcount: %d relationcount: %d", applicationname, app.UnitCount(), app.RelationCount()) return nil } destroyStorage := false force := false if n := len(cleanupArgs); n != 2 { return errors.Errorf("expected 2 arguments, got %d", n) } if err := cleanupArgs[0].Unmarshal(&destroyStorage); err != nil { return errors.Annotate(err, "unmarshalling cleanup args") } if err := cleanupArgs[1].Unmarshal(&force); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'force'") } op := app.DestroyOperation() op.DestroyStorage = destroyStorage op.Force = force return st.ApplyOperation(op) }
go
func (st *State) cleanupApplication(applicationname string, cleanupArgs []bson.Raw) (err error) { app, err := st.Application(applicationname) if err != nil { if errors.IsNotFound(err) { // Nothing to do, the application is already gone. logger.Tracef("cleanupApplication(%s): application already gone", applicationname) return nil } return errors.Trace(err) } if app.Life() == Alive { return errors.BadRequestf("cleanupApplication requested for an application (%s) that is still alive", applicationname) } // We know the app is at least Dying, so check if the unit/relation counts are no longer referencing this application. if app.UnitCount() > 0 || app.RelationCount() > 0 { // this is considered a no-op because whatever is currently referencing the application // should queue up a new cleanup once it stops logger.Tracef("cleanupApplication(%s) called, but it still has references: unitcount: %d relationcount: %d", applicationname, app.UnitCount(), app.RelationCount()) return nil } destroyStorage := false force := false if n := len(cleanupArgs); n != 2 { return errors.Errorf("expected 2 arguments, got %d", n) } if err := cleanupArgs[0].Unmarshal(&destroyStorage); err != nil { return errors.Annotate(err, "unmarshalling cleanup args") } if err := cleanupArgs[1].Unmarshal(&force); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'force'") } op := app.DestroyOperation() op.DestroyStorage = destroyStorage op.Force = force return st.ApplyOperation(op) }
[ "func", "(", "st", "*", "State", ")", "cleanupApplication", "(", "applicationname", "string", ",", "cleanupArgs", "[", "]", "bson", ".", "Raw", ")", "(", "err", "error", ")", "{", "app", ",", "err", ":=", "st", ".", "Application", "(", "applicationname", ")", "\n", "if", "err", "!=", "nil", "{", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "// Nothing to do, the application is already gone.", "logger", ".", "Tracef", "(", "\"", "\"", ",", "applicationname", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "app", ".", "Life", "(", ")", "==", "Alive", "{", "return", "errors", ".", "BadRequestf", "(", "\"", "\"", ",", "applicationname", ")", "\n", "}", "\n", "// We know the app is at least Dying, so check if the unit/relation counts are no longer referencing this application.", "if", "app", ".", "UnitCount", "(", ")", ">", "0", "||", "app", ".", "RelationCount", "(", ")", ">", "0", "{", "// this is considered a no-op because whatever is currently referencing the application", "// should queue up a new cleanup once it stops", "logger", ".", "Tracef", "(", "\"", "\"", ",", "applicationname", ",", "app", ".", "UnitCount", "(", ")", ",", "app", ".", "RelationCount", "(", ")", ")", "\n", "return", "nil", "\n", "}", "\n", "destroyStorage", ":=", "false", "\n", "force", ":=", "false", "\n", "if", "n", ":=", "len", "(", "cleanupArgs", ")", ";", "n", "!=", "2", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n", "if", "err", ":=", "cleanupArgs", "[", "0", "]", ".", "Unmarshal", "(", "&", "destroyStorage", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "cleanupArgs", "[", "1", "]", ".", "Unmarshal", "(", "&", "force", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "op", ":=", "app", ".", "DestroyOperation", "(", ")", "\n", "op", ".", "DestroyStorage", "=", "destroyStorage", "\n", "op", ".", "Force", "=", "force", "\n", "return", "st", ".", "ApplyOperation", "(", "op", ")", "\n", "}" ]
// cleanupApplication checks if all references to a dying application have been removed, // and if so, removes the application.
[ "cleanupApplication", "checks", "if", "all", "references", "to", "a", "dying", "application", "have", "been", "removed", "and", "if", "so", "removes", "the", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L388-L424
157,726
juju/juju
state/cleanup.go
cleanupApplicationsForDyingModel
func (st *State) cleanupApplicationsForDyingModel(cleanupArgs []bson.Raw) (err error) { var args DestroyModelParams switch n := len(cleanupArgs); n { case 0: // Old cleanups have no args, so follow the old behaviour. case 1: if err := cleanupArgs[0].Unmarshal(&args); err != nil { return errors.Annotate(err, "unmarshalling cleanup 'destroy model' args") } default: return errors.Errorf("expected 0-1 arguments, got %d", n) } if err := st.removeRemoteApplicationsForDyingModel(args); err != nil { return err } return st.removeApplicationsForDyingModel(args) }
go
func (st *State) cleanupApplicationsForDyingModel(cleanupArgs []bson.Raw) (err error) { var args DestroyModelParams switch n := len(cleanupArgs); n { case 0: // Old cleanups have no args, so follow the old behaviour. case 1: if err := cleanupArgs[0].Unmarshal(&args); err != nil { return errors.Annotate(err, "unmarshalling cleanup 'destroy model' args") } default: return errors.Errorf("expected 0-1 arguments, got %d", n) } if err := st.removeRemoteApplicationsForDyingModel(args); err != nil { return err } return st.removeApplicationsForDyingModel(args) }
[ "func", "(", "st", "*", "State", ")", "cleanupApplicationsForDyingModel", "(", "cleanupArgs", "[", "]", "bson", ".", "Raw", ")", "(", "err", "error", ")", "{", "var", "args", "DestroyModelParams", "\n", "switch", "n", ":=", "len", "(", "cleanupArgs", ")", ";", "n", "{", "case", "0", ":", "// Old cleanups have no args, so follow the old behaviour.", "case", "1", ":", "if", "err", ":=", "cleanupArgs", "[", "0", "]", ".", "Unmarshal", "(", "&", "args", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n", "if", "err", ":=", "st", ".", "removeRemoteApplicationsForDyingModel", "(", "args", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "st", ".", "removeApplicationsForDyingModel", "(", "args", ")", "\n", "}" ]
// cleanupApplicationsForDyingModel sets all applications to Dying, if they are // not already Dying or Dead. It's expected to be used when a model is // destroyed.
[ "cleanupApplicationsForDyingModel", "sets", "all", "applications", "to", "Dying", "if", "they", "are", "not", "already", "Dying", "or", "Dead", ".", "It", "s", "expected", "to", "be", "used", "when", "a", "model", "is", "destroyed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L429-L445
157,727
juju/juju
state/cleanup.go
cleanupUnitsForDyingApplication
func (st *State) cleanupUnitsForDyingApplication(applicationname string, cleanupArgs []bson.Raw) (err error) { var destroyStorage bool destroyStorageArg := func() error { err := cleanupArgs[0].Unmarshal(&destroyStorage) return errors.Annotate(err, "unmarshalling cleanup arg 'destroyStorage'") } var force bool var maxWait time.Duration switch n := len(cleanupArgs); n { case 0: // It's valid to have no args: old cleanups have no args, so follow the old behaviour. case 1: if err := destroyStorageArg(); err != nil { return err } case 3: if err := destroyStorageArg(); err != nil { return err } if err := cleanupArgs[1].Unmarshal(&force); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'force'") } if err := cleanupArgs[2].Unmarshal(&maxWait); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'maxWait'") } default: return errors.Errorf("expected 0, 1 or 3 arguments, got %d", n) } // This won't miss units, because a Dying application cannot have units // added to it. But we do have to remove the units themselves via // individual transactions, because they could be in any state at all. units, closer := st.db().GetCollection(unitsC) defer closer() unit := Unit{st: st} sel := bson.D{{"application", applicationname}, {"life", Alive}} iter := units.Find(sel).Iter() defer closeIter(iter, &err, "reading unit document") for iter.Next(&unit.doc) { op := unit.DestroyOperation() op.DestroyStorage = destroyStorage op.Force = force op.MaxWait = maxWait if err := st.ApplyOperation(op); err != nil { return errors.Trace(err) } } return nil }
go
func (st *State) cleanupUnitsForDyingApplication(applicationname string, cleanupArgs []bson.Raw) (err error) { var destroyStorage bool destroyStorageArg := func() error { err := cleanupArgs[0].Unmarshal(&destroyStorage) return errors.Annotate(err, "unmarshalling cleanup arg 'destroyStorage'") } var force bool var maxWait time.Duration switch n := len(cleanupArgs); n { case 0: // It's valid to have no args: old cleanups have no args, so follow the old behaviour. case 1: if err := destroyStorageArg(); err != nil { return err } case 3: if err := destroyStorageArg(); err != nil { return err } if err := cleanupArgs[1].Unmarshal(&force); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'force'") } if err := cleanupArgs[2].Unmarshal(&maxWait); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'maxWait'") } default: return errors.Errorf("expected 0, 1 or 3 arguments, got %d", n) } // This won't miss units, because a Dying application cannot have units // added to it. But we do have to remove the units themselves via // individual transactions, because they could be in any state at all. units, closer := st.db().GetCollection(unitsC) defer closer() unit := Unit{st: st} sel := bson.D{{"application", applicationname}, {"life", Alive}} iter := units.Find(sel).Iter() defer closeIter(iter, &err, "reading unit document") for iter.Next(&unit.doc) { op := unit.DestroyOperation() op.DestroyStorage = destroyStorage op.Force = force op.MaxWait = maxWait if err := st.ApplyOperation(op); err != nil { return errors.Trace(err) } } return nil }
[ "func", "(", "st", "*", "State", ")", "cleanupUnitsForDyingApplication", "(", "applicationname", "string", ",", "cleanupArgs", "[", "]", "bson", ".", "Raw", ")", "(", "err", "error", ")", "{", "var", "destroyStorage", "bool", "\n", "destroyStorageArg", ":=", "func", "(", ")", "error", "{", "err", ":=", "cleanupArgs", "[", "0", "]", ".", "Unmarshal", "(", "&", "destroyStorage", ")", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "var", "force", "bool", "\n", "var", "maxWait", "time", ".", "Duration", "\n", "switch", "n", ":=", "len", "(", "cleanupArgs", ")", ";", "n", "{", "case", "0", ":", "// It's valid to have no args: old cleanups have no args, so follow the old behaviour.", "case", "1", ":", "if", "err", ":=", "destroyStorageArg", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "3", ":", "if", "err", ":=", "destroyStorageArg", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "cleanupArgs", "[", "1", "]", ".", "Unmarshal", "(", "&", "force", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "cleanupArgs", "[", "2", "]", ".", "Unmarshal", "(", "&", "maxWait", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n\n", "// This won't miss units, because a Dying application cannot have units", "// added to it. But we do have to remove the units themselves via", "// individual transactions, because they could be in any state at all.", "units", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "unitsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "unit", ":=", "Unit", "{", "st", ":", "st", "}", "\n", "sel", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "applicationname", "}", ",", "{", "\"", "\"", ",", "Alive", "}", "}", "\n", "iter", ":=", "units", ".", "Find", "(", "sel", ")", ".", "Iter", "(", ")", "\n", "defer", "closeIter", "(", "iter", ",", "&", "err", ",", "\"", "\"", ")", "\n", "for", "iter", ".", "Next", "(", "&", "unit", ".", "doc", ")", "{", "op", ":=", "unit", ".", "DestroyOperation", "(", ")", "\n", "op", ".", "DestroyStorage", "=", "destroyStorage", "\n", "op", ".", "Force", "=", "force", "\n", "op", ".", "MaxWait", "=", "maxWait", "\n", "if", "err", ":=", "st", ".", "ApplyOperation", "(", "op", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cleanupUnitsForDyingApplication sets all units with the given prefix to Dying, // if they are not already Dying or Dead. It's expected to be used when a // application is destroyed.
[ "cleanupUnitsForDyingApplication", "sets", "all", "units", "with", "the", "given", "prefix", "to", "Dying", "if", "they", "are", "not", "already", "Dying", "or", "Dead", ".", "It", "s", "expected", "to", "be", "used", "when", "a", "application", "is", "destroyed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L498-L547
157,728
juju/juju
state/cleanup.go
cleanupDyingUnit
func (st *State) cleanupDyingUnit(name string, cleanupArgs []bson.Raw) error { var destroyStorage bool destroyStorageArg := func() error { err := cleanupArgs[0].Unmarshal(&destroyStorage) return errors.Annotate(err, "unmarshalling cleanup arg 'destroyStorage'") } var force bool var maxWait time.Duration switch n := len(cleanupArgs); n { case 0: // It's valid to have no args: old cleanups have no args, so follow the old behaviour. case 1: if err := destroyStorageArg(); err != nil { return err } case 3: if err := destroyStorageArg(); err != nil { return err } if err := cleanupArgs[1].Unmarshal(&force); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'force'") } if err := cleanupArgs[2].Unmarshal(&maxWait); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'maxWait'") } default: return errors.Errorf("expected 0, 1 or 3 arguments, got %d", n) } unit, err := st.Unit(name) if errors.IsNotFound(err) { return nil } else if err != nil { return err } // Mark the unit as departing from its joined relations, allowing // related units to start converging to a state in which that unit // is gone as quickly as possible. relations, err := unit.RelationsJoined() if err != nil { if !force { return err } logger.Warningf("could not get joined relations for unit %v during dying unit cleanup: %v", unit.Name(), err) } for _, relation := range relations { relationUnit, err := relation.Unit(unit) if errors.IsNotFound(err) { continue } else if err != nil { if !force { return err } logger.Warningf("could not get unit relation for unit %v during dying unit cleanup: %v", unit.Name(), err) } else { if err := relationUnit.PrepareLeaveScope(); err != nil { if !force { return err } logger.Warningf("could not prepare to leave scope for relation %v for unit %v during dying unit cleanup: %v", relation, unit.Name(), err) } } } // If we're forcing, set up a backstop cleanup to really remove // the unit in the case that the unit and machine agents don't for // some reason. if force { st.scheduleForceCleanup(cleanupForceDestroyedUnit, name, maxWait) } if destroyStorage { // Detach and mark storage instances as dying, allowing the // unit to terminate. return st.cleanupUnitStorageInstances(unit.UnitTag(), force, maxWait) } else { // Mark storage attachments as dying, so that they are detached // and removed from state, allowing the unit to terminate. return st.cleanupUnitStorageAttachments(unit.UnitTag(), false, force, maxWait) } }
go
func (st *State) cleanupDyingUnit(name string, cleanupArgs []bson.Raw) error { var destroyStorage bool destroyStorageArg := func() error { err := cleanupArgs[0].Unmarshal(&destroyStorage) return errors.Annotate(err, "unmarshalling cleanup arg 'destroyStorage'") } var force bool var maxWait time.Duration switch n := len(cleanupArgs); n { case 0: // It's valid to have no args: old cleanups have no args, so follow the old behaviour. case 1: if err := destroyStorageArg(); err != nil { return err } case 3: if err := destroyStorageArg(); err != nil { return err } if err := cleanupArgs[1].Unmarshal(&force); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'force'") } if err := cleanupArgs[2].Unmarshal(&maxWait); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'maxWait'") } default: return errors.Errorf("expected 0, 1 or 3 arguments, got %d", n) } unit, err := st.Unit(name) if errors.IsNotFound(err) { return nil } else if err != nil { return err } // Mark the unit as departing from its joined relations, allowing // related units to start converging to a state in which that unit // is gone as quickly as possible. relations, err := unit.RelationsJoined() if err != nil { if !force { return err } logger.Warningf("could not get joined relations for unit %v during dying unit cleanup: %v", unit.Name(), err) } for _, relation := range relations { relationUnit, err := relation.Unit(unit) if errors.IsNotFound(err) { continue } else if err != nil { if !force { return err } logger.Warningf("could not get unit relation for unit %v during dying unit cleanup: %v", unit.Name(), err) } else { if err := relationUnit.PrepareLeaveScope(); err != nil { if !force { return err } logger.Warningf("could not prepare to leave scope for relation %v for unit %v during dying unit cleanup: %v", relation, unit.Name(), err) } } } // If we're forcing, set up a backstop cleanup to really remove // the unit in the case that the unit and machine agents don't for // some reason. if force { st.scheduleForceCleanup(cleanupForceDestroyedUnit, name, maxWait) } if destroyStorage { // Detach and mark storage instances as dying, allowing the // unit to terminate. return st.cleanupUnitStorageInstances(unit.UnitTag(), force, maxWait) } else { // Mark storage attachments as dying, so that they are detached // and removed from state, allowing the unit to terminate. return st.cleanupUnitStorageAttachments(unit.UnitTag(), false, force, maxWait) } }
[ "func", "(", "st", "*", "State", ")", "cleanupDyingUnit", "(", "name", "string", ",", "cleanupArgs", "[", "]", "bson", ".", "Raw", ")", "error", "{", "var", "destroyStorage", "bool", "\n", "destroyStorageArg", ":=", "func", "(", ")", "error", "{", "err", ":=", "cleanupArgs", "[", "0", "]", ".", "Unmarshal", "(", "&", "destroyStorage", ")", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "var", "force", "bool", "\n", "var", "maxWait", "time", ".", "Duration", "\n", "switch", "n", ":=", "len", "(", "cleanupArgs", ")", ";", "n", "{", "case", "0", ":", "// It's valid to have no args: old cleanups have no args, so follow the old behaviour.", "case", "1", ":", "if", "err", ":=", "destroyStorageArg", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "3", ":", "if", "err", ":=", "destroyStorageArg", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "cleanupArgs", "[", "1", "]", ".", "Unmarshal", "(", "&", "force", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "cleanupArgs", "[", "2", "]", ".", "Unmarshal", "(", "&", "maxWait", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n\n", "unit", ",", "err", ":=", "st", ".", "Unit", "(", "name", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Mark the unit as departing from its joined relations, allowing", "// related units to start converging to a state in which that unit", "// is gone as quickly as possible.", "relations", ",", "err", ":=", "unit", ".", "RelationsJoined", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "force", "{", "return", "err", "\n", "}", "\n", "logger", ".", "Warningf", "(", "\"", "\"", ",", "unit", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "relation", ":=", "range", "relations", "{", "relationUnit", ",", "err", ":=", "relation", ".", "Unit", "(", "unit", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "continue", "\n", "}", "else", "if", "err", "!=", "nil", "{", "if", "!", "force", "{", "return", "err", "\n", "}", "\n", "logger", ".", "Warningf", "(", "\"", "\"", ",", "unit", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "else", "{", "if", "err", ":=", "relationUnit", ".", "PrepareLeaveScope", "(", ")", ";", "err", "!=", "nil", "{", "if", "!", "force", "{", "return", "err", "\n", "}", "\n", "logger", ".", "Warningf", "(", "\"", "\"", ",", "relation", ",", "unit", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// If we're forcing, set up a backstop cleanup to really remove", "// the unit in the case that the unit and machine agents don't for", "// some reason.", "if", "force", "{", "st", ".", "scheduleForceCleanup", "(", "cleanupForceDestroyedUnit", ",", "name", ",", "maxWait", ")", "\n", "}", "\n\n", "if", "destroyStorage", "{", "// Detach and mark storage instances as dying, allowing the", "// unit to terminate.", "return", "st", ".", "cleanupUnitStorageInstances", "(", "unit", ".", "UnitTag", "(", ")", ",", "force", ",", "maxWait", ")", "\n", "}", "else", "{", "// Mark storage attachments as dying, so that they are detached", "// and removed from state, allowing the unit to terminate.", "return", "st", ".", "cleanupUnitStorageAttachments", "(", "unit", ".", "UnitTag", "(", ")", ",", "false", ",", "force", ",", "maxWait", ")", "\n", "}", "\n", "}" ]
// cleanupDyingUnit marks resources owned by the unit as dying, to ensure // they are cleaned up as well.
[ "cleanupDyingUnit", "marks", "resources", "owned", "by", "the", "unit", "as", "dying", "to", "ensure", "they", "are", "cleaned", "up", "as", "well", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L588-L669
157,729
juju/juju
state/cleanup.go
cleanupRemovedUnit
func (st *State) cleanupRemovedUnit(unitId string, cleanupArgs []bson.Raw) error { var force bool switch n := len(cleanupArgs); n { case 0: // Old cleanups have no args, so follow the old behaviour. case 1: if err := cleanupArgs[0].Unmarshal(&force); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'force'") } default: return errors.Errorf("expected 0-1 arguments, got %d", n) } actions, err := st.matchingActionsByReceiverId(unitId) if err != nil { if !force { return errors.Trace(err) } logger.Warningf("could not get unit actions for unit %v during cleanup of removed unit: %v", unitId, err) } cancelled := ActionResults{ Status: ActionCancelled, Message: "unit removed", } for _, action := range actions { switch action.Status() { case ActionCompleted, ActionCancelled, ActionFailed: // nothing to do here default: if _, err = action.Finish(cancelled); err != nil { if !force { return errors.Trace(err) } logger.Warningf("could not finish action %v for unit %v during cleanup of removed unit: %v", action.Name(), unitId, err) } } } change := payloadCleanupChange{ Unit: unitId, } if err := Apply(st.database, change); err != nil { if !force { return errors.Trace(err) } logger.Warningf("could not cleanup payload for unit %v during cleanup of removed unit: %v", unitId, err) } return nil }
go
func (st *State) cleanupRemovedUnit(unitId string, cleanupArgs []bson.Raw) error { var force bool switch n := len(cleanupArgs); n { case 0: // Old cleanups have no args, so follow the old behaviour. case 1: if err := cleanupArgs[0].Unmarshal(&force); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'force'") } default: return errors.Errorf("expected 0-1 arguments, got %d", n) } actions, err := st.matchingActionsByReceiverId(unitId) if err != nil { if !force { return errors.Trace(err) } logger.Warningf("could not get unit actions for unit %v during cleanup of removed unit: %v", unitId, err) } cancelled := ActionResults{ Status: ActionCancelled, Message: "unit removed", } for _, action := range actions { switch action.Status() { case ActionCompleted, ActionCancelled, ActionFailed: // nothing to do here default: if _, err = action.Finish(cancelled); err != nil { if !force { return errors.Trace(err) } logger.Warningf("could not finish action %v for unit %v during cleanup of removed unit: %v", action.Name(), unitId, err) } } } change := payloadCleanupChange{ Unit: unitId, } if err := Apply(st.database, change); err != nil { if !force { return errors.Trace(err) } logger.Warningf("could not cleanup payload for unit %v during cleanup of removed unit: %v", unitId, err) } return nil }
[ "func", "(", "st", "*", "State", ")", "cleanupRemovedUnit", "(", "unitId", "string", ",", "cleanupArgs", "[", "]", "bson", ".", "Raw", ")", "error", "{", "var", "force", "bool", "\n", "switch", "n", ":=", "len", "(", "cleanupArgs", ")", ";", "n", "{", "case", "0", ":", "// Old cleanups have no args, so follow the old behaviour.", "case", "1", ":", "if", "err", ":=", "cleanupArgs", "[", "0", "]", ".", "Unmarshal", "(", "&", "force", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n\n", "actions", ",", "err", ":=", "st", ".", "matchingActionsByReceiverId", "(", "unitId", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "force", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Warningf", "(", "\"", "\"", ",", "unitId", ",", "err", ")", "\n", "}", "\n", "cancelled", ":=", "ActionResults", "{", "Status", ":", "ActionCancelled", ",", "Message", ":", "\"", "\"", ",", "}", "\n", "for", "_", ",", "action", ":=", "range", "actions", "{", "switch", "action", ".", "Status", "(", ")", "{", "case", "ActionCompleted", ",", "ActionCancelled", ",", "ActionFailed", ":", "// nothing to do here", "default", ":", "if", "_", ",", "err", "=", "action", ".", "Finish", "(", "cancelled", ")", ";", "err", "!=", "nil", "{", "if", "!", "force", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Warningf", "(", "\"", "\"", ",", "action", ".", "Name", "(", ")", ",", "unitId", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "change", ":=", "payloadCleanupChange", "{", "Unit", ":", "unitId", ",", "}", "\n", "if", "err", ":=", "Apply", "(", "st", ".", "database", ",", "change", ")", ";", "err", "!=", "nil", "{", "if", "!", "force", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Warningf", "(", "\"", "\"", ",", "unitId", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cleanupRemovedUnit takes care of all the final cleanup required when // a unit is removed.
[ "cleanupRemovedUnit", "takes", "care", "of", "all", "the", "final", "cleanup", "required", "when", "a", "unit", "is", "removed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L903-L951
157,730
juju/juju
state/cleanup.go
cleanupDyingMachine
func (st *State) cleanupDyingMachine(machineId string, cleanupArgs []bson.Raw) error { var force bool switch n := len(cleanupArgs); n { case 0: // Old cleanups have no args, so follow the old behaviour. case 1: if err := cleanupArgs[0].Unmarshal(&force); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'force'") } default: return errors.Errorf("expected 0-1 arguments, got %d", n) } machine, err := st.Machine(machineId) if errors.IsNotFound(err) { return nil } else if err != nil { return err } return cleanupDyingMachineResources(machine, force) }
go
func (st *State) cleanupDyingMachine(machineId string, cleanupArgs []bson.Raw) error { var force bool switch n := len(cleanupArgs); n { case 0: // Old cleanups have no args, so follow the old behaviour. case 1: if err := cleanupArgs[0].Unmarshal(&force); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'force'") } default: return errors.Errorf("expected 0-1 arguments, got %d", n) } machine, err := st.Machine(machineId) if errors.IsNotFound(err) { return nil } else if err != nil { return err } return cleanupDyingMachineResources(machine, force) }
[ "func", "(", "st", "*", "State", ")", "cleanupDyingMachine", "(", "machineId", "string", ",", "cleanupArgs", "[", "]", "bson", ".", "Raw", ")", "error", "{", "var", "force", "bool", "\n", "switch", "n", ":=", "len", "(", "cleanupArgs", ")", ";", "n", "{", "case", "0", ":", "// Old cleanups have no args, so follow the old behaviour.", "case", "1", ":", "if", "err", ":=", "cleanupArgs", "[", "0", "]", ".", "Unmarshal", "(", "&", "force", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n", "machine", ",", "err", ":=", "st", ".", "Machine", "(", "machineId", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "cleanupDyingMachineResources", "(", "machine", ",", "force", ")", "\n", "}" ]
// cleanupDyingMachine marks resources owned by the machine as dying, to ensure // they are cleaned up as well.
[ "cleanupDyingMachine", "marks", "resources", "owned", "by", "the", "machine", "as", "dying", "to", "ensure", "they", "are", "cleaned", "up", "as", "well", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L955-L974
157,731
juju/juju
state/cleanup.go
cleanupContainers
func (st *State) cleanupContainers(machine *Machine, maxWait time.Duration) error { containerIds, err := machine.Containers() if errors.IsNotFound(err) { return nil } else if err != nil { return err } for _, containerId := range containerIds { if err := st.cleanupForceDestroyedMachineInternal(containerId, maxWait); err != nil { return err } container, err := st.Machine(containerId) if errors.IsNotFound(err) { return nil } else if err != nil { return err } if err := container.Remove(); err != nil { return err } } return nil }
go
func (st *State) cleanupContainers(machine *Machine, maxWait time.Duration) error { containerIds, err := machine.Containers() if errors.IsNotFound(err) { return nil } else if err != nil { return err } for _, containerId := range containerIds { if err := st.cleanupForceDestroyedMachineInternal(containerId, maxWait); err != nil { return err } container, err := st.Machine(containerId) if errors.IsNotFound(err) { return nil } else if err != nil { return err } if err := container.Remove(); err != nil { return err } } return nil }
[ "func", "(", "st", "*", "State", ")", "cleanupContainers", "(", "machine", "*", "Machine", ",", "maxWait", "time", ".", "Duration", ")", "error", "{", "containerIds", ",", "err", ":=", "machine", ".", "Containers", "(", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "containerId", ":=", "range", "containerIds", "{", "if", "err", ":=", "st", ".", "cleanupForceDestroyedMachineInternal", "(", "containerId", ",", "maxWait", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "container", ",", "err", ":=", "st", ".", "Machine", "(", "containerId", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "container", ".", "Remove", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cleanupContainers recursively calls cleanupForceDestroyedMachine on the supplied // machine's containers, and removes them from state entirely.
[ "cleanupContainers", "recursively", "calls", "cleanupForceDestroyedMachine", "on", "the", "supplied", "machine", "s", "containers", "and", "removes", "them", "from", "state", "entirely", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L1090-L1112
157,732
juju/juju
state/cleanup.go
obliterateUnit
func (st *State) obliterateUnit(unitName string, force bool, maxWait time.Duration) ([]error, error) { var opErrs []error unit, err := st.Unit(unitName) if errors.IsNotFound(err) { return opErrs, nil } else if err != nil { return opErrs, err } // Unlike the machine, we *can* always destroy the unit, and (at least) // prevent further dependencies being added. If we're really lucky, the // unit will be removed immediately. errs, err := unit.DestroyWithForce(force, maxWait) opErrs = append(opErrs, errs...) if err != nil { if !force { return opErrs, errors.Annotatef(err, "cannot destroy unit %q", unitName) } opErrs = append(opErrs, err) } if err := unit.Refresh(); errors.IsNotFound(err) { return opErrs, nil } else if err != nil { if !force { return opErrs, err } opErrs = append(opErrs, err) } // Destroy and remove all storage attachments for the unit. if err := st.cleanupUnitStorageAttachments(unit.UnitTag(), true, force, maxWait); err != nil { err := errors.Annotatef(err, "cannot destroy storage for unit %q", unitName) if !force { return opErrs, err } opErrs = append(opErrs, err) } for _, subName := range unit.SubordinateNames() { errs, err := st.obliterateUnit(subName, force, maxWait) opErrs = append(opErrs, errs...) if err != nil { if !force { return opErrs, err } opErrs = append(opErrs, err) } } if err := unit.EnsureDead(); err != nil { if !force { return opErrs, err } opErrs = append(opErrs, err) } errs, err = unit.RemoveWithForce(force, maxWait) opErrs = append(opErrs, errs...) return opErrs, err }
go
func (st *State) obliterateUnit(unitName string, force bool, maxWait time.Duration) ([]error, error) { var opErrs []error unit, err := st.Unit(unitName) if errors.IsNotFound(err) { return opErrs, nil } else if err != nil { return opErrs, err } // Unlike the machine, we *can* always destroy the unit, and (at least) // prevent further dependencies being added. If we're really lucky, the // unit will be removed immediately. errs, err := unit.DestroyWithForce(force, maxWait) opErrs = append(opErrs, errs...) if err != nil { if !force { return opErrs, errors.Annotatef(err, "cannot destroy unit %q", unitName) } opErrs = append(opErrs, err) } if err := unit.Refresh(); errors.IsNotFound(err) { return opErrs, nil } else if err != nil { if !force { return opErrs, err } opErrs = append(opErrs, err) } // Destroy and remove all storage attachments for the unit. if err := st.cleanupUnitStorageAttachments(unit.UnitTag(), true, force, maxWait); err != nil { err := errors.Annotatef(err, "cannot destroy storage for unit %q", unitName) if !force { return opErrs, err } opErrs = append(opErrs, err) } for _, subName := range unit.SubordinateNames() { errs, err := st.obliterateUnit(subName, force, maxWait) opErrs = append(opErrs, errs...) if err != nil { if !force { return opErrs, err } opErrs = append(opErrs, err) } } if err := unit.EnsureDead(); err != nil { if !force { return opErrs, err } opErrs = append(opErrs, err) } errs, err = unit.RemoveWithForce(force, maxWait) opErrs = append(opErrs, errs...) return opErrs, err }
[ "func", "(", "st", "*", "State", ")", "obliterateUnit", "(", "unitName", "string", ",", "force", "bool", ",", "maxWait", "time", ".", "Duration", ")", "(", "[", "]", "error", ",", "error", ")", "{", "var", "opErrs", "[", "]", "error", "\n", "unit", ",", "err", ":=", "st", ".", "Unit", "(", "unitName", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "opErrs", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "opErrs", ",", "err", "\n", "}", "\n", "// Unlike the machine, we *can* always destroy the unit, and (at least)", "// prevent further dependencies being added. If we're really lucky, the", "// unit will be removed immediately.", "errs", ",", "err", ":=", "unit", ".", "DestroyWithForce", "(", "force", ",", "maxWait", ")", "\n", "opErrs", "=", "append", "(", "opErrs", ",", "errs", "...", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "force", "{", "return", "opErrs", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "unitName", ")", "\n", "}", "\n", "opErrs", "=", "append", "(", "opErrs", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "unit", ".", "Refresh", "(", ")", ";", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "opErrs", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "if", "!", "force", "{", "return", "opErrs", ",", "err", "\n", "}", "\n", "opErrs", "=", "append", "(", "opErrs", ",", "err", ")", "\n", "}", "\n", "// Destroy and remove all storage attachments for the unit.", "if", "err", ":=", "st", ".", "cleanupUnitStorageAttachments", "(", "unit", ".", "UnitTag", "(", ")", ",", "true", ",", "force", ",", "maxWait", ")", ";", "err", "!=", "nil", "{", "err", ":=", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "unitName", ")", "\n", "if", "!", "force", "{", "return", "opErrs", ",", "err", "\n", "}", "\n", "opErrs", "=", "append", "(", "opErrs", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "subName", ":=", "range", "unit", ".", "SubordinateNames", "(", ")", "{", "errs", ",", "err", ":=", "st", ".", "obliterateUnit", "(", "subName", ",", "force", ",", "maxWait", ")", "\n", "opErrs", "=", "append", "(", "opErrs", ",", "errs", "...", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "force", "{", "return", "opErrs", ",", "err", "\n", "}", "\n", "opErrs", "=", "append", "(", "opErrs", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "unit", ".", "EnsureDead", "(", ")", ";", "err", "!=", "nil", "{", "if", "!", "force", "{", "return", "opErrs", ",", "err", "\n", "}", "\n", "opErrs", "=", "append", "(", "opErrs", ",", "err", ")", "\n", "}", "\n", "errs", ",", "err", "=", "unit", ".", "RemoveWithForce", "(", "force", ",", "maxWait", ")", "\n", "opErrs", "=", "append", "(", "opErrs", ",", "errs", "...", ")", "\n", "return", "opErrs", ",", "err", "\n", "}" ]
// obliterateUnit removes a unit from state completely. It is not safe or // sane to obliterate any unit in isolation; its only reasonable use is in // the context of machine obliteration, in which we can be sure that unclean // shutdown of units is not going to leave a machine in a difficult state.
[ "obliterateUnit", "removes", "a", "unit", "from", "state", "completely", ".", "It", "is", "not", "safe", "or", "sane", "to", "obliterate", "any", "unit", "in", "isolation", ";", "its", "only", "reasonable", "use", "is", "in", "the", "context", "of", "machine", "obliteration", "in", "which", "we", "can", "be", "sure", "that", "unclean", "shutdown", "of", "units", "is", "not", "going", "to", "leave", "a", "machine", "in", "a", "difficult", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L1291-L1345
157,733
juju/juju
state/cleanup.go
cleanupAttachmentsForDyingStorage
func (st *State) cleanupAttachmentsForDyingStorage(storageId string, cleanupArgs []bson.Raw) (err error) { var force bool var maxWait time.Duration switch n := len(cleanupArgs); n { case 0: // It's valid to have no args: old cleanups have no args, so follow the old behaviour. case 2: if err := cleanupArgs[0].Unmarshal(&force); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'force'") } if err := cleanupArgs[1].Unmarshal(&maxWait); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'maxWait'") } default: return errors.Errorf("expected 0 or 2 arguments, got %d", n) } sb, err := NewStorageBackend(st) if err != nil { return errors.Trace(err) } storageTag := names.NewStorageTag(storageId) // This won't miss attachments, because a Dying storage instance cannot // have attachments added to it. But we do have to remove the attachments // themselves via individual transactions, because they could be in // any state at all. coll, closer := st.db().GetCollection(storageAttachmentsC) defer closer() var doc storageAttachmentDoc fields := bson.D{{"unitid", 1}} iter := coll.Find(bson.D{{"storageid", storageId}}).Select(fields).Iter() defer closeIter(iter, &err, "reading storage attachment document") var detachErr error for iter.Next(&doc) { unitTag := names.NewUnitTag(doc.Unit) if err := sb.DetachStorage(storageTag, unitTag, force, maxWait); err != nil { detachErr = errors.Annotate(err, "destroying storage attachment") logger.Warningf("%v", detachErr) } } if !force && detachErr != nil { return detachErr } return nil }
go
func (st *State) cleanupAttachmentsForDyingStorage(storageId string, cleanupArgs []bson.Raw) (err error) { var force bool var maxWait time.Duration switch n := len(cleanupArgs); n { case 0: // It's valid to have no args: old cleanups have no args, so follow the old behaviour. case 2: if err := cleanupArgs[0].Unmarshal(&force); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'force'") } if err := cleanupArgs[1].Unmarshal(&maxWait); err != nil { return errors.Annotate(err, "unmarshalling cleanup arg 'maxWait'") } default: return errors.Errorf("expected 0 or 2 arguments, got %d", n) } sb, err := NewStorageBackend(st) if err != nil { return errors.Trace(err) } storageTag := names.NewStorageTag(storageId) // This won't miss attachments, because a Dying storage instance cannot // have attachments added to it. But we do have to remove the attachments // themselves via individual transactions, because they could be in // any state at all. coll, closer := st.db().GetCollection(storageAttachmentsC) defer closer() var doc storageAttachmentDoc fields := bson.D{{"unitid", 1}} iter := coll.Find(bson.D{{"storageid", storageId}}).Select(fields).Iter() defer closeIter(iter, &err, "reading storage attachment document") var detachErr error for iter.Next(&doc) { unitTag := names.NewUnitTag(doc.Unit) if err := sb.DetachStorage(storageTag, unitTag, force, maxWait); err != nil { detachErr = errors.Annotate(err, "destroying storage attachment") logger.Warningf("%v", detachErr) } } if !force && detachErr != nil { return detachErr } return nil }
[ "func", "(", "st", "*", "State", ")", "cleanupAttachmentsForDyingStorage", "(", "storageId", "string", ",", "cleanupArgs", "[", "]", "bson", ".", "Raw", ")", "(", "err", "error", ")", "{", "var", "force", "bool", "\n", "var", "maxWait", "time", ".", "Duration", "\n", "switch", "n", ":=", "len", "(", "cleanupArgs", ")", ";", "n", "{", "case", "0", ":", "// It's valid to have no args: old cleanups have no args, so follow the old behaviour.", "case", "2", ":", "if", "err", ":=", "cleanupArgs", "[", "0", "]", ".", "Unmarshal", "(", "&", "force", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "cleanupArgs", "[", "1", "]", ".", "Unmarshal", "(", "&", "maxWait", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n\n", "sb", ",", "err", ":=", "NewStorageBackend", "(", "st", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "storageTag", ":=", "names", ".", "NewStorageTag", "(", "storageId", ")", "\n\n", "// This won't miss attachments, because a Dying storage instance cannot", "// have attachments added to it. But we do have to remove the attachments", "// themselves via individual transactions, because they could be in", "// any state at all.", "coll", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "storageAttachmentsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "var", "doc", "storageAttachmentDoc", "\n", "fields", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "1", "}", "}", "\n", "iter", ":=", "coll", ".", "Find", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "storageId", "}", "}", ")", ".", "Select", "(", "fields", ")", ".", "Iter", "(", ")", "\n", "defer", "closeIter", "(", "iter", ",", "&", "err", ",", "\"", "\"", ")", "\n", "var", "detachErr", "error", "\n", "for", "iter", ".", "Next", "(", "&", "doc", ")", "{", "unitTag", ":=", "names", ".", "NewUnitTag", "(", "doc", ".", "Unit", ")", "\n", "if", "err", ":=", "sb", ".", "DetachStorage", "(", "storageTag", ",", "unitTag", ",", "force", ",", "maxWait", ")", ";", "err", "!=", "nil", "{", "detachErr", "=", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "logger", ".", "Warningf", "(", "\"", "\"", ",", "detachErr", ")", "\n", "}", "\n", "}", "\n", "if", "!", "force", "&&", "detachErr", "!=", "nil", "{", "return", "detachErr", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cleanupAttachmentsForDyingStorage sets all storage attachments related // to the specified storage instance to Dying, if they are not already Dying // or Dead. It's expected to be used when a storage instance is destroyed.
[ "cleanupAttachmentsForDyingStorage", "sets", "all", "storage", "attachments", "related", "to", "the", "specified", "storage", "instance", "to", "Dying", "if", "they", "are", "not", "already", "Dying", "or", "Dead", ".", "It", "s", "expected", "to", "be", "used", "when", "a", "storage", "instance", "is", "destroyed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L1350-L1396
157,734
juju/juju
state/cleanup.go
cleanupAttachmentsForDyingVolume
func (st *State) cleanupAttachmentsForDyingVolume(volumeId string) (err error) { volumeTag := names.NewVolumeTag(volumeId) // This won't miss attachments, because a Dying volume cannot have // attachments added to it. But we do have to remove the attachments // themselves via individual transactions, because they could be in // any state at all. coll, closer := st.db().GetCollection(volumeAttachmentsC) defer closer() sb, err := NewStorageBackend(st) if err != nil { return errors.Trace(err) } var doc volumeAttachmentDoc fields := bson.D{{"hostid", 1}} iter := coll.Find(bson.D{{"volumeid", volumeId}}).Select(fields).Iter() defer closeIter(iter, &err, "reading volume attachment document") for iter.Next(&doc) { hostTag := storageAttachmentHost(doc.Host) if err := sb.DetachVolume(hostTag, volumeTag); err != nil { return errors.Annotate(err, "destroying volume attachment") } } return nil }
go
func (st *State) cleanupAttachmentsForDyingVolume(volumeId string) (err error) { volumeTag := names.NewVolumeTag(volumeId) // This won't miss attachments, because a Dying volume cannot have // attachments added to it. But we do have to remove the attachments // themselves via individual transactions, because they could be in // any state at all. coll, closer := st.db().GetCollection(volumeAttachmentsC) defer closer() sb, err := NewStorageBackend(st) if err != nil { return errors.Trace(err) } var doc volumeAttachmentDoc fields := bson.D{{"hostid", 1}} iter := coll.Find(bson.D{{"volumeid", volumeId}}).Select(fields).Iter() defer closeIter(iter, &err, "reading volume attachment document") for iter.Next(&doc) { hostTag := storageAttachmentHost(doc.Host) if err := sb.DetachVolume(hostTag, volumeTag); err != nil { return errors.Annotate(err, "destroying volume attachment") } } return nil }
[ "func", "(", "st", "*", "State", ")", "cleanupAttachmentsForDyingVolume", "(", "volumeId", "string", ")", "(", "err", "error", ")", "{", "volumeTag", ":=", "names", ".", "NewVolumeTag", "(", "volumeId", ")", "\n\n", "// This won't miss attachments, because a Dying volume cannot have", "// attachments added to it. But we do have to remove the attachments", "// themselves via individual transactions, because they could be in", "// any state at all.", "coll", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "volumeAttachmentsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "sb", ",", "err", ":=", "NewStorageBackend", "(", "st", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "var", "doc", "volumeAttachmentDoc", "\n", "fields", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "1", "}", "}", "\n", "iter", ":=", "coll", ".", "Find", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "volumeId", "}", "}", ")", ".", "Select", "(", "fields", ")", ".", "Iter", "(", ")", "\n", "defer", "closeIter", "(", "iter", ",", "&", "err", ",", "\"", "\"", ")", "\n", "for", "iter", ".", "Next", "(", "&", "doc", ")", "{", "hostTag", ":=", "storageAttachmentHost", "(", "doc", ".", "Host", ")", "\n", "if", "err", ":=", "sb", ".", "DetachVolume", "(", "hostTag", ",", "volumeTag", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cleanupAttachmentsForDyingVolume sets all volume attachments related // to the specified volume to Dying, if they are not already Dying or // Dead. It's expected to be used when a volume is destroyed.
[ "cleanupAttachmentsForDyingVolume", "sets", "all", "volume", "attachments", "related", "to", "the", "specified", "volume", "to", "Dying", "if", "they", "are", "not", "already", "Dying", "or", "Dead", ".", "It", "s", "expected", "to", "be", "used", "when", "a", "volume", "is", "destroyed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L1401-L1427
157,735
juju/juju
state/cleanup.go
cleanupAttachmentsForDyingFilesystem
func (st *State) cleanupAttachmentsForDyingFilesystem(filesystemId string) (err error) { sb, err := NewStorageBackend(st) if err != nil { return errors.Trace(err) } filesystemTag := names.NewFilesystemTag(filesystemId) // This won't miss attachments, because a Dying filesystem cannot have // attachments added to it. But we do have to remove the attachments // themselves via individual transactions, because they could be in // any state at all. coll, closer := sb.mb.db().GetCollection(filesystemAttachmentsC) defer closer() var doc filesystemAttachmentDoc fields := bson.D{{"hostid", 1}} iter := coll.Find(bson.D{{"filesystemid", filesystemId}}).Select(fields).Iter() defer closeIter(iter, &err, "reading filesystem attachment document") for iter.Next(&doc) { hostTag := storageAttachmentHost(doc.Host) if err := sb.DetachFilesystem(hostTag, filesystemTag); err != nil { return errors.Annotate(err, "destroying filesystem attachment") } } return nil }
go
func (st *State) cleanupAttachmentsForDyingFilesystem(filesystemId string) (err error) { sb, err := NewStorageBackend(st) if err != nil { return errors.Trace(err) } filesystemTag := names.NewFilesystemTag(filesystemId) // This won't miss attachments, because a Dying filesystem cannot have // attachments added to it. But we do have to remove the attachments // themselves via individual transactions, because they could be in // any state at all. coll, closer := sb.mb.db().GetCollection(filesystemAttachmentsC) defer closer() var doc filesystemAttachmentDoc fields := bson.D{{"hostid", 1}} iter := coll.Find(bson.D{{"filesystemid", filesystemId}}).Select(fields).Iter() defer closeIter(iter, &err, "reading filesystem attachment document") for iter.Next(&doc) { hostTag := storageAttachmentHost(doc.Host) if err := sb.DetachFilesystem(hostTag, filesystemTag); err != nil { return errors.Annotate(err, "destroying filesystem attachment") } } return nil }
[ "func", "(", "st", "*", "State", ")", "cleanupAttachmentsForDyingFilesystem", "(", "filesystemId", "string", ")", "(", "err", "error", ")", "{", "sb", ",", "err", ":=", "NewStorageBackend", "(", "st", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "filesystemTag", ":=", "names", ".", "NewFilesystemTag", "(", "filesystemId", ")", "\n\n", "// This won't miss attachments, because a Dying filesystem cannot have", "// attachments added to it. But we do have to remove the attachments", "// themselves via individual transactions, because they could be in", "// any state at all.", "coll", ",", "closer", ":=", "sb", ".", "mb", ".", "db", "(", ")", ".", "GetCollection", "(", "filesystemAttachmentsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "var", "doc", "filesystemAttachmentDoc", "\n", "fields", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "1", "}", "}", "\n", "iter", ":=", "coll", ".", "Find", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "filesystemId", "}", "}", ")", ".", "Select", "(", "fields", ")", ".", "Iter", "(", ")", "\n", "defer", "closeIter", "(", "iter", ",", "&", "err", ",", "\"", "\"", ")", "\n", "for", "iter", ".", "Next", "(", "&", "doc", ")", "{", "hostTag", ":=", "storageAttachmentHost", "(", "doc", ".", "Host", ")", "\n", "if", "err", ":=", "sb", ".", "DetachFilesystem", "(", "hostTag", ",", "filesystemTag", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cleanupAttachmentsForDyingFilesystem sets all filesystem attachments related // to the specified filesystem to Dying, if they are not already Dying or // Dead. It's expected to be used when a filesystem is destroyed.
[ "cleanupAttachmentsForDyingFilesystem", "sets", "all", "filesystem", "attachments", "related", "to", "the", "specified", "filesystem", "to", "Dying", "if", "they", "are", "not", "already", "Dying", "or", "Dead", ".", "It", "s", "expected", "to", "be", "used", "when", "a", "filesystem", "is", "destroyed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cleanup.go#L1432-L1458
157,736
juju/juju
state/charm.go
Set
func (m MacaroonCache) Set(u *charm.URL, ms macaroon.Slice) error { c, err := m.Charm(u) if err != nil { return errors.Trace(err) } return c.UpdateMacaroon(ms) }
go
func (m MacaroonCache) Set(u *charm.URL, ms macaroon.Slice) error { c, err := m.Charm(u) if err != nil { return errors.Trace(err) } return c.UpdateMacaroon(ms) }
[ "func", "(", "m", "MacaroonCache", ")", "Set", "(", "u", "*", "charm", ".", "URL", ",", "ms", "macaroon", ".", "Slice", ")", "error", "{", "c", ",", "err", ":=", "m", ".", "Charm", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "c", ".", "UpdateMacaroon", "(", "ms", ")", "\n", "}" ]
// Set stores the macaroon on the charm.
[ "Set", "stores", "the", "macaroon", "on", "the", "charm", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L33-L39
157,737
juju/juju
state/charm.go
insertCharmOps
func insertCharmOps(mb modelBackend, info CharmInfo) ([]txn.Op, error) { if info.ID == nil { return nil, errors.New("*charm.URL was nil") } doc := charmDoc{ DocID: info.ID.String(), URL: info.ID, CharmVersion: info.Version, Meta: info.Charm.Meta(), Config: safeConfig(info.Charm), Metrics: info.Charm.Metrics(), Actions: info.Charm.Actions(), BundleSha256: info.SHA256, StoragePath: info.StoragePath, } lpc, ok := info.Charm.(charm.LXDProfiler) if !ok { return nil, errors.New("charm does no implement LXDProfiler") } doc.LXDProfile = safeLXDProfile(lpc.LXDProfile()) if err := checkCharmDataIsStorable(doc); err != nil { return nil, errors.Trace(err) } if info.Macaroon != nil { mac, err := info.Macaroon.MarshalBinary() if err != nil { return nil, errors.Annotate(err, "can't convert macaroon to binary for storage") } doc.Macaroon = mac } return insertAnyCharmOps(mb, &doc) }
go
func insertCharmOps(mb modelBackend, info CharmInfo) ([]txn.Op, error) { if info.ID == nil { return nil, errors.New("*charm.URL was nil") } doc := charmDoc{ DocID: info.ID.String(), URL: info.ID, CharmVersion: info.Version, Meta: info.Charm.Meta(), Config: safeConfig(info.Charm), Metrics: info.Charm.Metrics(), Actions: info.Charm.Actions(), BundleSha256: info.SHA256, StoragePath: info.StoragePath, } lpc, ok := info.Charm.(charm.LXDProfiler) if !ok { return nil, errors.New("charm does no implement LXDProfiler") } doc.LXDProfile = safeLXDProfile(lpc.LXDProfile()) if err := checkCharmDataIsStorable(doc); err != nil { return nil, errors.Trace(err) } if info.Macaroon != nil { mac, err := info.Macaroon.MarshalBinary() if err != nil { return nil, errors.Annotate(err, "can't convert macaroon to binary for storage") } doc.Macaroon = mac } return insertAnyCharmOps(mb, &doc) }
[ "func", "insertCharmOps", "(", "mb", "modelBackend", ",", "info", "CharmInfo", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "info", ".", "ID", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "doc", ":=", "charmDoc", "{", "DocID", ":", "info", ".", "ID", ".", "String", "(", ")", ",", "URL", ":", "info", ".", "ID", ",", "CharmVersion", ":", "info", ".", "Version", ",", "Meta", ":", "info", ".", "Charm", ".", "Meta", "(", ")", ",", "Config", ":", "safeConfig", "(", "info", ".", "Charm", ")", ",", "Metrics", ":", "info", ".", "Charm", ".", "Metrics", "(", ")", ",", "Actions", ":", "info", ".", "Charm", ".", "Actions", "(", ")", ",", "BundleSha256", ":", "info", ".", "SHA256", ",", "StoragePath", ":", "info", ".", "StoragePath", ",", "}", "\n", "lpc", ",", "ok", ":=", "info", ".", "Charm", ".", "(", "charm", ".", "LXDProfiler", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "doc", ".", "LXDProfile", "=", "safeLXDProfile", "(", "lpc", ".", "LXDProfile", "(", ")", ")", "\n\n", "if", "err", ":=", "checkCharmDataIsStorable", "(", "doc", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "info", ".", "Macaroon", "!=", "nil", "{", "mac", ",", "err", ":=", "info", ".", "Macaroon", ".", "MarshalBinary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "doc", ".", "Macaroon", "=", "mac", "\n", "}", "\n", "return", "insertAnyCharmOps", "(", "mb", ",", "&", "doc", ")", "\n", "}" ]
// insertCharmOps returns the txn operations necessary to insert the supplied // charm data. If curl is nil, an error will be returned.
[ "insertCharmOps", "returns", "the", "txn", "operations", "necessary", "to", "insert", "the", "supplied", "charm", "data", ".", "If", "curl", "is", "nil", "an", "error", "will", "be", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L103-L137
157,738
juju/juju
state/charm.go
insertPlaceholderCharmOps
func insertPlaceholderCharmOps(mb modelBackend, curl *charm.URL) ([]txn.Op, error) { if curl == nil { return nil, errors.New("*charm.URL was nil") } return insertAnyCharmOps(mb, &charmDoc{ DocID: curl.String(), URL: curl, Placeholder: true, }) }
go
func insertPlaceholderCharmOps(mb modelBackend, curl *charm.URL) ([]txn.Op, error) { if curl == nil { return nil, errors.New("*charm.URL was nil") } return insertAnyCharmOps(mb, &charmDoc{ DocID: curl.String(), URL: curl, Placeholder: true, }) }
[ "func", "insertPlaceholderCharmOps", "(", "mb", "modelBackend", ",", "curl", "*", "charm", ".", "URL", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "curl", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "insertAnyCharmOps", "(", "mb", ",", "&", "charmDoc", "{", "DocID", ":", "curl", ".", "String", "(", ")", ",", "URL", ":", "curl", ",", "Placeholder", ":", "true", ",", "}", ")", "\n", "}" ]
// insertPlaceholderCharmOps returns the txn operations necessary to insert a // charm document referencing a store charm that is not yet directly accessible // within the model. If curl is nil, an error will be returned.
[ "insertPlaceholderCharmOps", "returns", "the", "txn", "operations", "necessary", "to", "insert", "a", "charm", "document", "referencing", "a", "store", "charm", "that", "is", "not", "yet", "directly", "accessible", "within", "the", "model", ".", "If", "curl", "is", "nil", "an", "error", "will", "be", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L142-L151
157,739
juju/juju
state/charm.go
insertAnyCharmOps
func insertAnyCharmOps(mb modelBackend, cdoc *charmDoc) ([]txn.Op, error) { charms, closer := mb.db().GetCollection(charmsC) defer closer() life, err := nsLife.read(charms, cdoc.DocID) if errors.IsNotFound(err) { // everything is as it should be } else if err != nil { return nil, errors.Trace(err) } else if life == Dead { return nil, errors.New("url already consumed") } else { return nil, errors.New("already exists") } charmOp := txn.Op{ C: charmsC, Id: cdoc.DocID, Assert: txn.DocMissing, Insert: cdoc, } refcounts, closer := mb.db().GetCollection(refcountsC) defer closer() charmKey := charmGlobalKey(cdoc.URL) refOp, required, err := nsRefcounts.LazyCreateOp(refcounts, charmKey) if err != nil { return nil, errors.Trace(err) } else if required { return []txn.Op{refOp, charmOp}, nil } return []txn.Op{charmOp}, nil }
go
func insertAnyCharmOps(mb modelBackend, cdoc *charmDoc) ([]txn.Op, error) { charms, closer := mb.db().GetCollection(charmsC) defer closer() life, err := nsLife.read(charms, cdoc.DocID) if errors.IsNotFound(err) { // everything is as it should be } else if err != nil { return nil, errors.Trace(err) } else if life == Dead { return nil, errors.New("url already consumed") } else { return nil, errors.New("already exists") } charmOp := txn.Op{ C: charmsC, Id: cdoc.DocID, Assert: txn.DocMissing, Insert: cdoc, } refcounts, closer := mb.db().GetCollection(refcountsC) defer closer() charmKey := charmGlobalKey(cdoc.URL) refOp, required, err := nsRefcounts.LazyCreateOp(refcounts, charmKey) if err != nil { return nil, errors.Trace(err) } else if required { return []txn.Op{refOp, charmOp}, nil } return []txn.Op{charmOp}, nil }
[ "func", "insertAnyCharmOps", "(", "mb", "modelBackend", ",", "cdoc", "*", "charmDoc", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "charms", ",", "closer", ":=", "mb", ".", "db", "(", ")", ".", "GetCollection", "(", "charmsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "life", ",", "err", ":=", "nsLife", ".", "read", "(", "charms", ",", "cdoc", ".", "DocID", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "// everything is as it should be", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "else", "if", "life", "==", "Dead", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "charmOp", ":=", "txn", ".", "Op", "{", "C", ":", "charmsC", ",", "Id", ":", "cdoc", ".", "DocID", ",", "Assert", ":", "txn", ".", "DocMissing", ",", "Insert", ":", "cdoc", ",", "}", "\n\n", "refcounts", ",", "closer", ":=", "mb", ".", "db", "(", ")", ".", "GetCollection", "(", "refcountsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "charmKey", ":=", "charmGlobalKey", "(", "cdoc", ".", "URL", ")", "\n", "refOp", ",", "required", ",", "err", ":=", "nsRefcounts", ".", "LazyCreateOp", "(", "refcounts", ",", "charmKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "else", "if", "required", "{", "return", "[", "]", "txn", ".", "Op", "{", "refOp", ",", "charmOp", "}", ",", "nil", "\n", "}", "\n", "return", "[", "]", "txn", ".", "Op", "{", "charmOp", "}", ",", "nil", "\n", "}" ]
// insertAnyCharmOps returns the txn operations necessary to insert the supplied // charm document.
[ "insertAnyCharmOps", "returns", "the", "txn", "operations", "necessary", "to", "insert", "the", "supplied", "charm", "document", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L169-L201
157,740
juju/juju
state/charm.go
updateCharmOps
func updateCharmOps(mb modelBackend, info CharmInfo, assert bson.D) ([]txn.Op, error) { charms, closer := mb.db().GetCollection(charmsC) defer closer() charmKey := info.ID.String() op, err := nsLife.aliveOp(charms, charmKey) if err != nil { return nil, errors.Annotate(err, "charm") } lifeAssert, ok := op.Assert.(bson.D) if !ok { return nil, errors.Errorf("expected bson.D, got %#v", op.Assert) } op.Assert = append(lifeAssert, assert...) data := bson.D{ {"charm-version", info.Version}, {"meta", info.Charm.Meta()}, {"config", safeConfig(info.Charm)}, {"actions", info.Charm.Actions()}, {"metrics", info.Charm.Metrics()}, {"storagepath", info.StoragePath}, {"bundlesha256", info.SHA256}, {"pendingupload", false}, {"placeholder", false}, } lpc, ok := info.Charm.(charm.LXDProfiler) if !ok { return nil, errors.New("charm doesn't have LXDCharmProfile()") } data = append(data, bson.DocElem{"lxd-profile", safeLXDProfile(lpc.LXDProfile())}) if err := checkCharmDataIsStorable(data); err != nil { return nil, errors.Trace(err) } if len(info.Macaroon) > 0 { mac, err := info.Macaroon.MarshalBinary() if err != nil { return nil, errors.Annotate(err, "can't convert macaroon to binary for storage") } data = append(data, bson.DocElem{"macaroon", mac}) } op.Update = bson.D{{"$set", data}} return []txn.Op{op}, nil }
go
func updateCharmOps(mb modelBackend, info CharmInfo, assert bson.D) ([]txn.Op, error) { charms, closer := mb.db().GetCollection(charmsC) defer closer() charmKey := info.ID.String() op, err := nsLife.aliveOp(charms, charmKey) if err != nil { return nil, errors.Annotate(err, "charm") } lifeAssert, ok := op.Assert.(bson.D) if !ok { return nil, errors.Errorf("expected bson.D, got %#v", op.Assert) } op.Assert = append(lifeAssert, assert...) data := bson.D{ {"charm-version", info.Version}, {"meta", info.Charm.Meta()}, {"config", safeConfig(info.Charm)}, {"actions", info.Charm.Actions()}, {"metrics", info.Charm.Metrics()}, {"storagepath", info.StoragePath}, {"bundlesha256", info.SHA256}, {"pendingupload", false}, {"placeholder", false}, } lpc, ok := info.Charm.(charm.LXDProfiler) if !ok { return nil, errors.New("charm doesn't have LXDCharmProfile()") } data = append(data, bson.DocElem{"lxd-profile", safeLXDProfile(lpc.LXDProfile())}) if err := checkCharmDataIsStorable(data); err != nil { return nil, errors.Trace(err) } if len(info.Macaroon) > 0 { mac, err := info.Macaroon.MarshalBinary() if err != nil { return nil, errors.Annotate(err, "can't convert macaroon to binary for storage") } data = append(data, bson.DocElem{"macaroon", mac}) } op.Update = bson.D{{"$set", data}} return []txn.Op{op}, nil }
[ "func", "updateCharmOps", "(", "mb", "modelBackend", ",", "info", "CharmInfo", ",", "assert", "bson", ".", "D", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "charms", ",", "closer", ":=", "mb", ".", "db", "(", ")", ".", "GetCollection", "(", "charmsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "charmKey", ":=", "info", ".", "ID", ".", "String", "(", ")", "\n", "op", ",", "err", ":=", "nsLife", ".", "aliveOp", "(", "charms", ",", "charmKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "lifeAssert", ",", "ok", ":=", "op", ".", "Assert", ".", "(", "bson", ".", "D", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "op", ".", "Assert", ")", "\n", "}", "\n", "op", ".", "Assert", "=", "append", "(", "lifeAssert", ",", "assert", "...", ")", "\n\n", "data", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "info", ".", "Version", "}", ",", "{", "\"", "\"", ",", "info", ".", "Charm", ".", "Meta", "(", ")", "}", ",", "{", "\"", "\"", ",", "safeConfig", "(", "info", ".", "Charm", ")", "}", ",", "{", "\"", "\"", ",", "info", ".", "Charm", ".", "Actions", "(", ")", "}", ",", "{", "\"", "\"", ",", "info", ".", "Charm", ".", "Metrics", "(", ")", "}", ",", "{", "\"", "\"", ",", "info", ".", "StoragePath", "}", ",", "{", "\"", "\"", ",", "info", ".", "SHA256", "}", ",", "{", "\"", "\"", ",", "false", "}", ",", "{", "\"", "\"", ",", "false", "}", ",", "}", "\n\n", "lpc", ",", "ok", ":=", "info", ".", "Charm", ".", "(", "charm", ".", "LXDProfiler", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "data", "=", "append", "(", "data", ",", "bson", ".", "DocElem", "{", "\"", "\"", ",", "safeLXDProfile", "(", "lpc", ".", "LXDProfile", "(", ")", ")", "}", ")", "\n\n", "if", "err", ":=", "checkCharmDataIsStorable", "(", "data", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "len", "(", "info", ".", "Macaroon", ")", ">", "0", "{", "mac", ",", "err", ":=", "info", ".", "Macaroon", ".", "MarshalBinary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "data", "=", "append", "(", "data", ",", "bson", ".", "DocElem", "{", "\"", "\"", ",", "mac", "}", ")", "\n", "}", "\n\n", "op", ".", "Update", "=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "data", "}", "}", "\n", "return", "[", "]", "txn", ".", "Op", "{", "op", "}", ",", "nil", "\n", "}" ]
// updateCharmOps returns the txn operations necessary to update the charm // document with the supplied data, so long as the supplied assert still holds // true.
[ "updateCharmOps", "returns", "the", "txn", "operations", "necessary", "to", "update", "the", "charm", "document", "with", "the", "supplied", "data", "so", "long", "as", "the", "supplied", "assert", "still", "holds", "true", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L206-L253
157,741
juju/juju
state/charm.go
convertPlaceholderCharmOps
func convertPlaceholderCharmOps(docID string) ([]txn.Op, error) { return []txn.Op{{ C: charmsC, Id: docID, Assert: bson.D{ {"bundlesha256", ""}, {"pendingupload", false}, {"placeholder", true}, }, Update: bson.D{{"$set", bson.D{ {"pendingupload", true}, {"placeholder", false}, }}}, }}, nil }
go
func convertPlaceholderCharmOps(docID string) ([]txn.Op, error) { return []txn.Op{{ C: charmsC, Id: docID, Assert: bson.D{ {"bundlesha256", ""}, {"pendingupload", false}, {"placeholder", true}, }, Update: bson.D{{"$set", bson.D{ {"pendingupload", true}, {"placeholder", false}, }}}, }}, nil }
[ "func", "convertPlaceholderCharmOps", "(", "docID", "string", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "return", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "charmsC", ",", "Id", ":", "docID", ",", "Assert", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "{", "\"", "\"", ",", "false", "}", ",", "{", "\"", "\"", ",", "true", "}", ",", "}", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "true", "}", ",", "{", "\"", "\"", ",", "false", "}", ",", "}", "}", "}", ",", "}", "}", ",", "nil", "\n\n", "}" ]
// convertPlaceholderCharmOps returns the txn operations necessary to convert // the charm with the supplied docId from a placeholder to one marked for // pending upload.
[ "convertPlaceholderCharmOps", "returns", "the", "txn", "operations", "necessary", "to", "convert", "the", "charm", "with", "the", "supplied", "docId", "from", "a", "placeholder", "to", "one", "marked", "for", "pending", "upload", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L258-L273
157,742
juju/juju
state/charm.go
deleteOldPlaceholderCharmsOps
func deleteOldPlaceholderCharmsOps(mb modelBackend, charms mongo.Collection, curl *charm.URL) ([]txn.Op, error) { // Get a regex with the charm URL and no revision. noRevURL := curl.WithRevision(-1) curlRegex := "^" + regexp.QuoteMeta(mb.docID(noRevURL.String())) var docs []charmDoc query := bson.D{{"_id", bson.D{{"$regex", curlRegex}}}, {"placeholder", true}} err := charms.Find(query).Select(bson.D{{"_id", 1}, {"url", 1}}).All(&docs) if err != nil { return nil, errors.Trace(err) } refcounts, closer := mb.db().GetCollection(refcountsC) defer closer() var ops []txn.Op for _, doc := range docs { if doc.URL.Revision >= curl.Revision { continue } key := charmGlobalKey(doc.URL) refOp, err := nsRefcounts.RemoveOp(refcounts, key, 0) if err != nil { return nil, errors.Trace(err) } ops = append(ops, refOp, txn.Op{ C: charms.Name(), Id: doc.DocID, Assert: stillPlaceholder, Remove: true, }) } return ops, nil }
go
func deleteOldPlaceholderCharmsOps(mb modelBackend, charms mongo.Collection, curl *charm.URL) ([]txn.Op, error) { // Get a regex with the charm URL and no revision. noRevURL := curl.WithRevision(-1) curlRegex := "^" + regexp.QuoteMeta(mb.docID(noRevURL.String())) var docs []charmDoc query := bson.D{{"_id", bson.D{{"$regex", curlRegex}}}, {"placeholder", true}} err := charms.Find(query).Select(bson.D{{"_id", 1}, {"url", 1}}).All(&docs) if err != nil { return nil, errors.Trace(err) } refcounts, closer := mb.db().GetCollection(refcountsC) defer closer() var ops []txn.Op for _, doc := range docs { if doc.URL.Revision >= curl.Revision { continue } key := charmGlobalKey(doc.URL) refOp, err := nsRefcounts.RemoveOp(refcounts, key, 0) if err != nil { return nil, errors.Trace(err) } ops = append(ops, refOp, txn.Op{ C: charms.Name(), Id: doc.DocID, Assert: stillPlaceholder, Remove: true, }) } return ops, nil }
[ "func", "deleteOldPlaceholderCharmsOps", "(", "mb", "modelBackend", ",", "charms", "mongo", ".", "Collection", ",", "curl", "*", "charm", ".", "URL", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "// Get a regex with the charm URL and no revision.", "noRevURL", ":=", "curl", ".", "WithRevision", "(", "-", "1", ")", "\n", "curlRegex", ":=", "\"", "\"", "+", "regexp", ".", "QuoteMeta", "(", "mb", ".", "docID", "(", "noRevURL", ".", "String", "(", ")", ")", ")", "\n\n", "var", "docs", "[", "]", "charmDoc", "\n", "query", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "curlRegex", "}", "}", "}", ",", "{", "\"", "\"", ",", "true", "}", "}", "\n", "err", ":=", "charms", ".", "Find", "(", "query", ")", ".", "Select", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "1", "}", ",", "{", "\"", "\"", ",", "1", "}", "}", ")", ".", "All", "(", "&", "docs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "refcounts", ",", "closer", ":=", "mb", ".", "db", "(", ")", ".", "GetCollection", "(", "refcountsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "var", "ops", "[", "]", "txn", ".", "Op", "\n", "for", "_", ",", "doc", ":=", "range", "docs", "{", "if", "doc", ".", "URL", ".", "Revision", ">=", "curl", ".", "Revision", "{", "continue", "\n", "}", "\n", "key", ":=", "charmGlobalKey", "(", "doc", ".", "URL", ")", "\n", "refOp", ",", "err", ":=", "nsRefcounts", ".", "RemoveOp", "(", "refcounts", ",", "key", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "refOp", ",", "txn", ".", "Op", "{", "C", ":", "charms", ".", "Name", "(", ")", ",", "Id", ":", "doc", ".", "DocID", ",", "Assert", ":", "stillPlaceholder", ",", "Remove", ":", "true", ",", "}", ")", "\n", "}", "\n", "return", "ops", ",", "nil", "\n", "}" ]
// deleteOldPlaceholderCharmsOps returns the txn ops required to delete all placeholder charm // records older than the specified charm URL.
[ "deleteOldPlaceholderCharmsOps", "returns", "the", "txn", "ops", "required", "to", "delete", "all", "placeholder", "charm", "records", "older", "than", "the", "specified", "charm", "URL", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L277-L310
157,743
juju/juju
state/charm.go
safeLXDProfile
func safeLXDProfile(profile *charm.LXDProfile) *charm.LXDProfile { if profile == nil { return nil } escapedProfile := charm.NewLXDProfile() escapedProfile.Description = profile.Description // we know the size and shape of the type, so let's use EscapeKey escapedConfig := make(map[string]string, len(profile.Config)) for k, v := range profile.Config { escapedConfig[mongoutils.EscapeKey(k)] = v } escapedProfile.Config = escapedConfig // this is more easy to reason about than using mongoutils.EscapeKeys, which // requires looping from map[string]interface{} -> map[string]map[string]string escapedDevices := make(map[string]map[string]string, len(profile.Devices)) for k, v := range profile.Devices { nested := make(map[string]string, len(v)) for vk, vv := range v { nested[mongoutils.EscapeKey(vk)] = vv } escapedDevices[mongoutils.EscapeKey(k)] = nested } escapedProfile.Devices = escapedDevices return escapedProfile }
go
func safeLXDProfile(profile *charm.LXDProfile) *charm.LXDProfile { if profile == nil { return nil } escapedProfile := charm.NewLXDProfile() escapedProfile.Description = profile.Description // we know the size and shape of the type, so let's use EscapeKey escapedConfig := make(map[string]string, len(profile.Config)) for k, v := range profile.Config { escapedConfig[mongoutils.EscapeKey(k)] = v } escapedProfile.Config = escapedConfig // this is more easy to reason about than using mongoutils.EscapeKeys, which // requires looping from map[string]interface{} -> map[string]map[string]string escapedDevices := make(map[string]map[string]string, len(profile.Devices)) for k, v := range profile.Devices { nested := make(map[string]string, len(v)) for vk, vv := range v { nested[mongoutils.EscapeKey(vk)] = vv } escapedDevices[mongoutils.EscapeKey(k)] = nested } escapedProfile.Devices = escapedDevices return escapedProfile }
[ "func", "safeLXDProfile", "(", "profile", "*", "charm", ".", "LXDProfile", ")", "*", "charm", ".", "LXDProfile", "{", "if", "profile", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "escapedProfile", ":=", "charm", ".", "NewLXDProfile", "(", ")", "\n", "escapedProfile", ".", "Description", "=", "profile", ".", "Description", "\n", "// we know the size and shape of the type, so let's use EscapeKey", "escapedConfig", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "profile", ".", "Config", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "profile", ".", "Config", "{", "escapedConfig", "[", "mongoutils", ".", "EscapeKey", "(", "k", ")", "]", "=", "v", "\n", "}", "\n", "escapedProfile", ".", "Config", "=", "escapedConfig", "\n", "// this is more easy to reason about than using mongoutils.EscapeKeys, which", "// requires looping from map[string]interface{} -> map[string]map[string]string", "escapedDevices", ":=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "string", ",", "len", "(", "profile", ".", "Devices", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "profile", ".", "Devices", "{", "nested", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "v", ")", ")", "\n", "for", "vk", ",", "vv", ":=", "range", "v", "{", "nested", "[", "mongoutils", ".", "EscapeKey", "(", "vk", ")", "]", "=", "vv", "\n", "}", "\n", "escapedDevices", "[", "mongoutils", ".", "EscapeKey", "(", "k", ")", "]", "=", "nested", "\n", "}", "\n", "escapedProfile", ".", "Devices", "=", "escapedDevices", "\n", "return", "escapedProfile", "\n", "}" ]
// safeLXDProfile ensures that the LXDProfile that we put into the mongo data // store, can in fact store the profile safely by escaping mongo- // significant characters in config options.
[ "safeLXDProfile", "ensures", "that", "the", "LXDProfile", "that", "we", "put", "into", "the", "mongo", "data", "store", "can", "in", "fact", "store", "the", "profile", "safely", "by", "escaping", "mongo", "-", "significant", "characters", "in", "config", "options", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L335-L359
157,744
juju/juju
state/charm.go
unescapeLXDProfile
func unescapeLXDProfile(profile *charm.LXDProfile) *charm.LXDProfile { if profile == nil { return nil } unescapedProfile := charm.NewLXDProfile() unescapedProfile.Description = profile.Description // we know the size and shape of the type, so let's use UnescapeKey unescapedConfig := make(map[string]string, len(profile.Config)) for k, v := range profile.Config { unescapedConfig[mongoutils.UnescapeKey(k)] = v } unescapedProfile.Config = unescapedConfig // this is more easy to reason about than using mongoutils.UnescapeKeys, which // requires looping from map[string]interface{} -> map[string]map[string]string unescapedDevices := make(map[string]map[string]string, len(profile.Devices)) for k, v := range profile.Devices { nested := make(map[string]string, len(v)) for vk, vv := range v { nested[mongoutils.UnescapeKey(vk)] = vv } unescapedDevices[mongoutils.UnescapeKey(k)] = nested } unescapedProfile.Devices = unescapedDevices return unescapedProfile }
go
func unescapeLXDProfile(profile *charm.LXDProfile) *charm.LXDProfile { if profile == nil { return nil } unescapedProfile := charm.NewLXDProfile() unescapedProfile.Description = profile.Description // we know the size and shape of the type, so let's use UnescapeKey unescapedConfig := make(map[string]string, len(profile.Config)) for k, v := range profile.Config { unescapedConfig[mongoutils.UnescapeKey(k)] = v } unescapedProfile.Config = unescapedConfig // this is more easy to reason about than using mongoutils.UnescapeKeys, which // requires looping from map[string]interface{} -> map[string]map[string]string unescapedDevices := make(map[string]map[string]string, len(profile.Devices)) for k, v := range profile.Devices { nested := make(map[string]string, len(v)) for vk, vv := range v { nested[mongoutils.UnescapeKey(vk)] = vv } unescapedDevices[mongoutils.UnescapeKey(k)] = nested } unescapedProfile.Devices = unescapedDevices return unescapedProfile }
[ "func", "unescapeLXDProfile", "(", "profile", "*", "charm", ".", "LXDProfile", ")", "*", "charm", ".", "LXDProfile", "{", "if", "profile", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "unescapedProfile", ":=", "charm", ".", "NewLXDProfile", "(", ")", "\n", "unescapedProfile", ".", "Description", "=", "profile", ".", "Description", "\n", "// we know the size and shape of the type, so let's use UnescapeKey", "unescapedConfig", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "profile", ".", "Config", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "profile", ".", "Config", "{", "unescapedConfig", "[", "mongoutils", ".", "UnescapeKey", "(", "k", ")", "]", "=", "v", "\n", "}", "\n", "unescapedProfile", ".", "Config", "=", "unescapedConfig", "\n", "// this is more easy to reason about than using mongoutils.UnescapeKeys, which", "// requires looping from map[string]interface{} -> map[string]map[string]string", "unescapedDevices", ":=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "string", ",", "len", "(", "profile", ".", "Devices", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "profile", ".", "Devices", "{", "nested", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "v", ")", ")", "\n", "for", "vk", ",", "vv", ":=", "range", "v", "{", "nested", "[", "mongoutils", ".", "UnescapeKey", "(", "vk", ")", "]", "=", "vv", "\n", "}", "\n", "unescapedDevices", "[", "mongoutils", ".", "UnescapeKey", "(", "k", ")", "]", "=", "nested", "\n", "}", "\n", "unescapedProfile", ".", "Devices", "=", "unescapedDevices", "\n", "return", "unescapedProfile", "\n", "}" ]
// unescapeLXDProfile returns the LXDProfile back to normal after // reading from state.
[ "unescapeLXDProfile", "returns", "the", "LXDProfile", "back", "to", "normal", "after", "reading", "from", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L392-L416
157,745
juju/juju
state/charm.go
Tag
func (c *Charm) Tag() names.Tag { return names.NewCharmTag(c.URL().String()) }
go
func (c *Charm) Tag() names.Tag { return names.NewCharmTag(c.URL().String()) }
[ "func", "(", "c", "*", "Charm", ")", "Tag", "(", ")", "names", ".", "Tag", "{", "return", "names", ".", "NewCharmTag", "(", "c", ".", "URL", "(", ")", ".", "String", "(", ")", ")", "\n", "}" ]
// Tag returns a tag identifying the charm. // Implementing state.GlobalEntity interface.
[ "Tag", "returns", "a", "tag", "identifying", "the", "charm", ".", "Implementing", "state", ".", "GlobalEntity", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L420-L422
157,746
juju/juju
state/charm.go
Refresh
func (c *Charm) Refresh() error { ch, err := c.st.Charm(c.doc.URL) if err != nil { return errors.Trace(err) } c.doc = ch.doc return nil }
go
func (c *Charm) Refresh() error { ch, err := c.st.Charm(c.doc.URL) if err != nil { return errors.Trace(err) } c.doc = ch.doc return nil }
[ "func", "(", "c", "*", "Charm", ")", "Refresh", "(", ")", "error", "{", "ch", ",", "err", ":=", "c", ".", "st", ".", "Charm", "(", "c", ".", "doc", ".", "URL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "c", ".", "doc", "=", "ch", ".", "doc", "\n", "return", "nil", "\n", "}" ]
// Refresh loads fresh charm data from the database. In practice, the // only observable change should be to its Life value.
[ "Refresh", "loads", "fresh", "charm", "data", "from", "the", "database", ".", "In", "practice", "the", "only", "observable", "change", "should", "be", "to", "its", "Life", "value", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L431-L438
157,747
juju/juju
state/charm.go
Destroy
func (c *Charm) Destroy() error { buildTxn := func(_ int) ([]txn.Op, error) { ops, err := charmDestroyOps(c.st, c.doc.URL) if IsNotAlive(err) { return nil, jujutxn.ErrNoOperations } else if err != nil { return nil, errors.Trace(err) } return ops, nil } if err := c.st.db().Run(buildTxn); err != nil { return errors.Trace(err) } c.doc.Life = Dying return nil }
go
func (c *Charm) Destroy() error { buildTxn := func(_ int) ([]txn.Op, error) { ops, err := charmDestroyOps(c.st, c.doc.URL) if IsNotAlive(err) { return nil, jujutxn.ErrNoOperations } else if err != nil { return nil, errors.Trace(err) } return ops, nil } if err := c.st.db().Run(buildTxn); err != nil { return errors.Trace(err) } c.doc.Life = Dying return nil }
[ "func", "(", "c", "*", "Charm", ")", "Destroy", "(", ")", "error", "{", "buildTxn", ":=", "func", "(", "_", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "ops", ",", "err", ":=", "charmDestroyOps", "(", "c", ".", "st", ",", "c", ".", "doc", ".", "URL", ")", "\n", "if", "IsNotAlive", "(", "err", ")", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "ops", ",", "nil", "\n", "}", "\n", "if", "err", ":=", "c", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "c", ".", "doc", ".", "Life", "=", "Dying", "\n", "return", "nil", "\n", "}" ]
// Destroy sets the charm to Dying and prevents it from being used by // applications or units. It only works on local charms, and only when // the charm is not referenced by any application.
[ "Destroy", "sets", "the", "charm", "to", "Dying", "and", "prevents", "it", "from", "being", "used", "by", "applications", "or", "units", ".", "It", "only", "works", "on", "local", "charms", "and", "only", "when", "the", "charm", "is", "not", "referenced", "by", "any", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L443-L458
157,748
juju/juju
state/charm.go
URL
func (c *Charm) URL() *charm.URL { clone := *c.doc.URL return &clone }
go
func (c *Charm) URL() *charm.URL { clone := *c.doc.URL return &clone }
[ "func", "(", "c", "*", "Charm", ")", "URL", "(", ")", "*", "charm", ".", "URL", "{", "clone", ":=", "*", "c", ".", "doc", ".", "URL", "\n", "return", "&", "clone", "\n", "}" ]
// URL returns the URL that identifies the charm.
[ "URL", "returns", "the", "URL", "that", "identifies", "the", "charm", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L509-L512
157,749
juju/juju
state/charm.go
Macaroon
func (c *Charm) Macaroon() (macaroon.Slice, error) { if len(c.doc.Macaroon) == 0 { return nil, nil } var m macaroon.Slice if err := m.UnmarshalBinary(c.doc.Macaroon); err != nil { return nil, errors.Trace(err) } return m, nil }
go
func (c *Charm) Macaroon() (macaroon.Slice, error) { if len(c.doc.Macaroon) == 0 { return nil, nil } var m macaroon.Slice if err := m.UnmarshalBinary(c.doc.Macaroon); err != nil { return nil, errors.Trace(err) } return m, nil }
[ "func", "(", "c", "*", "Charm", ")", "Macaroon", "(", ")", "(", "macaroon", ".", "Slice", ",", "error", ")", "{", "if", "len", "(", "c", ".", "doc", ".", "Macaroon", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "var", "m", "macaroon", ".", "Slice", "\n", "if", "err", ":=", "m", ".", "UnmarshalBinary", "(", "c", ".", "doc", ".", "Macaroon", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "m", ",", "nil", "\n", "}" ]
// Macaroon return the macaroon that can be used to request data about the charm // from the charmstore, or nil if the charm is not private.
[ "Macaroon", "return", "the", "macaroon", "that", "can", "be", "used", "to", "request", "data", "about", "the", "charm", "from", "the", "charmstore", "or", "nil", "if", "the", "charm", "is", "not", "private", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L574-L584
157,750
juju/juju
state/charm.go
UpdateMacaroon
func (c *Charm) UpdateMacaroon(m macaroon.Slice) error { info := CharmInfo{ Charm: c, ID: c.URL(), StoragePath: c.StoragePath(), SHA256: c.BundleSha256(), Macaroon: m, } ops, err := updateCharmOps(c.st, info, nil) if err != nil { return errors.Trace(err) } if err := c.st.db().RunTransaction(ops); err != nil { return errors.Trace(err) } return nil }
go
func (c *Charm) UpdateMacaroon(m macaroon.Slice) error { info := CharmInfo{ Charm: c, ID: c.URL(), StoragePath: c.StoragePath(), SHA256: c.BundleSha256(), Macaroon: m, } ops, err := updateCharmOps(c.st, info, nil) if err != nil { return errors.Trace(err) } if err := c.st.db().RunTransaction(ops); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "c", "*", "Charm", ")", "UpdateMacaroon", "(", "m", "macaroon", ".", "Slice", ")", "error", "{", "info", ":=", "CharmInfo", "{", "Charm", ":", "c", ",", "ID", ":", "c", ".", "URL", "(", ")", ",", "StoragePath", ":", "c", ".", "StoragePath", "(", ")", ",", "SHA256", ":", "c", ".", "BundleSha256", "(", ")", ",", "Macaroon", ":", "m", ",", "}", "\n", "ops", ",", "err", ":=", "updateCharmOps", "(", "c", ".", "st", ",", "info", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "c", ".", "st", ".", "db", "(", ")", ".", "RunTransaction", "(", "ops", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateMacaroon updates the stored macaroon for this charm.
[ "UpdateMacaroon", "updates", "the", "stored", "macaroon", "for", "this", "charm", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L587-L603
157,751
juju/juju
state/charm.go
AddCharm
func (st *State) AddCharm(info CharmInfo) (stch *Charm, err error) { charms, closer := st.db().GetCollection(charmsC) defer closer() if err := validateCharmVersion(info.Charm); err != nil { return nil, errors.Trace(err) } model, err := st.Model() if err != nil { return nil, errors.Trace(err) } if err := validateCharmSeries(model.Type(), info.ID.Series, info.Charm); err != nil { return nil, errors.Trace(err) } query := charms.FindId(info.ID.String()).Select(bson.M{ "placeholder": 1, "pendingupload": 1, }) buildTxn := func(attempt int) ([]txn.Op, error) { var doc charmDoc if err := query.One(&doc); err == mgo.ErrNotFound { if info.ID.Schema == "local" { curl, err := st.PrepareLocalCharmUpload(info.ID) if err != nil { return nil, errors.Trace(err) } info.ID = curl return updateCharmOps(st, info, stillPending) } return insertCharmOps(st, info) } else if err != nil { return nil, errors.Trace(err) } else if doc.PendingUpload { return updateCharmOps(st, info, stillPending) } else if doc.Placeholder { return updateCharmOps(st, info, stillPlaceholder) } return nil, errors.AlreadyExistsf("charm %q", info.ID) } if err = st.db().Run(buildTxn); err == nil { return st.Charm(info.ID) } return nil, errors.Trace(err) }
go
func (st *State) AddCharm(info CharmInfo) (stch *Charm, err error) { charms, closer := st.db().GetCollection(charmsC) defer closer() if err := validateCharmVersion(info.Charm); err != nil { return nil, errors.Trace(err) } model, err := st.Model() if err != nil { return nil, errors.Trace(err) } if err := validateCharmSeries(model.Type(), info.ID.Series, info.Charm); err != nil { return nil, errors.Trace(err) } query := charms.FindId(info.ID.String()).Select(bson.M{ "placeholder": 1, "pendingupload": 1, }) buildTxn := func(attempt int) ([]txn.Op, error) { var doc charmDoc if err := query.One(&doc); err == mgo.ErrNotFound { if info.ID.Schema == "local" { curl, err := st.PrepareLocalCharmUpload(info.ID) if err != nil { return nil, errors.Trace(err) } info.ID = curl return updateCharmOps(st, info, stillPending) } return insertCharmOps(st, info) } else if err != nil { return nil, errors.Trace(err) } else if doc.PendingUpload { return updateCharmOps(st, info, stillPending) } else if doc.Placeholder { return updateCharmOps(st, info, stillPlaceholder) } return nil, errors.AlreadyExistsf("charm %q", info.ID) } if err = st.db().Run(buildTxn); err == nil { return st.Charm(info.ID) } return nil, errors.Trace(err) }
[ "func", "(", "st", "*", "State", ")", "AddCharm", "(", "info", "CharmInfo", ")", "(", "stch", "*", "Charm", ",", "err", "error", ")", "{", "charms", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "charmsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "if", "err", ":=", "validateCharmVersion", "(", "info", ".", "Charm", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "model", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "validateCharmSeries", "(", "model", ".", "Type", "(", ")", ",", "info", ".", "ID", ".", "Series", ",", "info", ".", "Charm", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "query", ":=", "charms", ".", "FindId", "(", "info", ".", "ID", ".", "String", "(", ")", ")", ".", "Select", "(", "bson", ".", "M", "{", "\"", "\"", ":", "1", ",", "\"", "\"", ":", "1", ",", "}", ")", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "var", "doc", "charmDoc", "\n", "if", "err", ":=", "query", ".", "One", "(", "&", "doc", ")", ";", "err", "==", "mgo", ".", "ErrNotFound", "{", "if", "info", ".", "ID", ".", "Schema", "==", "\"", "\"", "{", "curl", ",", "err", ":=", "st", ".", "PrepareLocalCharmUpload", "(", "info", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "info", ".", "ID", "=", "curl", "\n", "return", "updateCharmOps", "(", "st", ",", "info", ",", "stillPending", ")", "\n", "}", "\n", "return", "insertCharmOps", "(", "st", ",", "info", ")", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "else", "if", "doc", ".", "PendingUpload", "{", "return", "updateCharmOps", "(", "st", ",", "info", ",", "stillPending", ")", "\n", "}", "else", "if", "doc", ".", "Placeholder", "{", "return", "updateCharmOps", "(", "st", ",", "info", ",", "stillPlaceholder", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "AlreadyExistsf", "(", "\"", "\"", ",", "info", ".", "ID", ")", "\n", "}", "\n", "if", "err", "=", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", ";", "err", "==", "nil", "{", "return", "st", ".", "Charm", "(", "info", ".", "ID", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// AddCharm adds the ch charm with curl to the state. // On success the newly added charm state is returned.
[ "AddCharm", "adds", "the", "ch", "charm", "with", "curl", "to", "the", "state", ".", "On", "success", "the", "newly", "added", "charm", "state", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L607-L651
157,752
juju/juju
state/charm.go
AllCharms
func (st *State) AllCharms() ([]*Charm, error) { charmsCollection, closer := st.db().GetCollection(charmsC) defer closer() var cdoc charmDoc var charms []*Charm iter := charmsCollection.Find(nsLife.notDead()).Iter() for iter.Next(&cdoc) { ch := newCharm(st, &cdoc) charms = append(charms, ch) } return charms, errors.Trace(iter.Close()) }
go
func (st *State) AllCharms() ([]*Charm, error) { charmsCollection, closer := st.db().GetCollection(charmsC) defer closer() var cdoc charmDoc var charms []*Charm iter := charmsCollection.Find(nsLife.notDead()).Iter() for iter.Next(&cdoc) { ch := newCharm(st, &cdoc) charms = append(charms, ch) } return charms, errors.Trace(iter.Close()) }
[ "func", "(", "st", "*", "State", ")", "AllCharms", "(", ")", "(", "[", "]", "*", "Charm", ",", "error", ")", "{", "charmsCollection", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "charmsC", ")", "\n", "defer", "closer", "(", ")", "\n", "var", "cdoc", "charmDoc", "\n", "var", "charms", "[", "]", "*", "Charm", "\n", "iter", ":=", "charmsCollection", ".", "Find", "(", "nsLife", ".", "notDead", "(", ")", ")", ".", "Iter", "(", ")", "\n", "for", "iter", ".", "Next", "(", "&", "cdoc", ")", "{", "ch", ":=", "newCharm", "(", "st", ",", "&", "cdoc", ")", "\n", "charms", "=", "append", "(", "charms", ",", "ch", ")", "\n", "}", "\n", "return", "charms", ",", "errors", ".", "Trace", "(", "iter", ".", "Close", "(", ")", ")", "\n", "}" ]
// AllCharms returns all charms in state.
[ "AllCharms", "returns", "all", "charms", "in", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L683-L694
157,753
juju/juju
state/charm.go
Charm
func (st *State) Charm(curl *charm.URL) (*Charm, error) { charms, closer := st.db().GetCollection(charmsC) defer closer() cdoc := &charmDoc{} what := bson.D{ {"_id", curl.String()}, {"placeholder", bson.D{{"$ne", true}}}, {"pendingupload", bson.D{{"$ne", true}}}, } what = append(what, nsLife.notDead()...) err := charms.Find(what).One(&cdoc) if err == mgo.ErrNotFound { return nil, errors.NotFoundf("charm %q", curl) } if err != nil { return nil, errors.Annotatef(err, "cannot get charm %q", curl) } if err := cdoc.Meta.Check(); err != nil { return nil, errors.Annotatef(err, "malformed charm metadata found in state") } return newCharm(st, cdoc), nil }
go
func (st *State) Charm(curl *charm.URL) (*Charm, error) { charms, closer := st.db().GetCollection(charmsC) defer closer() cdoc := &charmDoc{} what := bson.D{ {"_id", curl.String()}, {"placeholder", bson.D{{"$ne", true}}}, {"pendingupload", bson.D{{"$ne", true}}}, } what = append(what, nsLife.notDead()...) err := charms.Find(what).One(&cdoc) if err == mgo.ErrNotFound { return nil, errors.NotFoundf("charm %q", curl) } if err != nil { return nil, errors.Annotatef(err, "cannot get charm %q", curl) } if err := cdoc.Meta.Check(); err != nil { return nil, errors.Annotatef(err, "malformed charm metadata found in state") } return newCharm(st, cdoc), nil }
[ "func", "(", "st", "*", "State", ")", "Charm", "(", "curl", "*", "charm", ".", "URL", ")", "(", "*", "Charm", ",", "error", ")", "{", "charms", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "charmsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "cdoc", ":=", "&", "charmDoc", "{", "}", "\n", "what", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "curl", ".", "String", "(", ")", "}", ",", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "true", "}", "}", "}", ",", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "true", "}", "}", "}", ",", "}", "\n", "what", "=", "append", "(", "what", ",", "nsLife", ".", "notDead", "(", ")", "...", ")", "\n", "err", ":=", "charms", ".", "Find", "(", "what", ")", ".", "One", "(", "&", "cdoc", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "curl", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "curl", ")", "\n", "}", "\n", "if", "err", ":=", "cdoc", ".", "Meta", ".", "Check", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "newCharm", "(", "st", ",", "cdoc", ")", ",", "nil", "\n", "}" ]
// Charm returns the charm with the given URL. Charms pending upload // to storage and placeholders are never returned.
[ "Charm", "returns", "the", "charm", "with", "the", "given", "URL", ".", "Charms", "pending", "upload", "to", "storage", "and", "placeholders", "are", "never", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L698-L720
157,754
juju/juju
state/charm.go
PrepareLocalCharmUpload
func (st *State) PrepareLocalCharmUpload(curl *charm.URL) (chosenURL *charm.URL, err error) { // Perform a few sanity checks first. if curl.Schema != "local" { return nil, errors.Errorf("expected charm URL with local schema, got %q", curl) } if curl.Revision < 0 { return nil, errors.Errorf("expected charm URL with revision, got %q", curl) } revisionSeq := charmRevSeqName(curl.WithRevision(-1).String()) revision, err := sequenceWithMin(st, revisionSeq, curl.Revision) if err != nil { return nil, errors.Annotate(err, "unable to allocate charm revision") } allocatedURL := curl.WithRevision(revision) ops, err := insertPendingCharmOps(st, allocatedURL) if err != nil { return nil, errors.Trace(err) } if err := st.db().RunTransaction(ops); err != nil { return nil, errors.Trace(err) } return allocatedURL, nil }
go
func (st *State) PrepareLocalCharmUpload(curl *charm.URL) (chosenURL *charm.URL, err error) { // Perform a few sanity checks first. if curl.Schema != "local" { return nil, errors.Errorf("expected charm URL with local schema, got %q", curl) } if curl.Revision < 0 { return nil, errors.Errorf("expected charm URL with revision, got %q", curl) } revisionSeq := charmRevSeqName(curl.WithRevision(-1).String()) revision, err := sequenceWithMin(st, revisionSeq, curl.Revision) if err != nil { return nil, errors.Annotate(err, "unable to allocate charm revision") } allocatedURL := curl.WithRevision(revision) ops, err := insertPendingCharmOps(st, allocatedURL) if err != nil { return nil, errors.Trace(err) } if err := st.db().RunTransaction(ops); err != nil { return nil, errors.Trace(err) } return allocatedURL, nil }
[ "func", "(", "st", "*", "State", ")", "PrepareLocalCharmUpload", "(", "curl", "*", "charm", ".", "URL", ")", "(", "chosenURL", "*", "charm", ".", "URL", ",", "err", "error", ")", "{", "// Perform a few sanity checks first.", "if", "curl", ".", "Schema", "!=", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "curl", ")", "\n", "}", "\n", "if", "curl", ".", "Revision", "<", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "curl", ")", "\n", "}", "\n\n", "revisionSeq", ":=", "charmRevSeqName", "(", "curl", ".", "WithRevision", "(", "-", "1", ")", ".", "String", "(", ")", ")", "\n", "revision", ",", "err", ":=", "sequenceWithMin", "(", "st", ",", "revisionSeq", ",", "curl", ".", "Revision", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "allocatedURL", ":=", "curl", ".", "WithRevision", "(", "revision", ")", "\n\n", "ops", ",", "err", ":=", "insertPendingCharmOps", "(", "st", ",", "allocatedURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "st", ".", "db", "(", ")", ".", "RunTransaction", "(", "ops", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "allocatedURL", ",", "nil", "\n", "}" ]
// PrepareLocalCharmUpload must be called before a local charm is // uploaded to the provider storage in order to create a charm // document in state. It returns the chosen unique charm URL reserved // in state for the charm. // // The url's schema must be "local" and it must include a revision.
[ "PrepareLocalCharmUpload", "must", "be", "called", "before", "a", "local", "charm", "is", "uploaded", "to", "the", "provider", "storage", "in", "order", "to", "create", "a", "charm", "document", "in", "state", ".", "It", "returns", "the", "chosen", "unique", "charm", "URL", "reserved", "in", "state", "for", "the", "charm", ".", "The", "url", "s", "schema", "must", "be", "local", "and", "it", "must", "include", "a", "revision", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L754-L779
157,755
juju/juju
state/charm.go
AddStoreCharmPlaceholder
func (st *State) AddStoreCharmPlaceholder(curl *charm.URL) (err error) { // Perform sanity checks first. if curl.Schema != "cs" { return errors.Errorf("expected charm URL with cs schema, got %q", curl) } if curl.Revision < 0 { return errors.Errorf("expected charm URL with revision, got %q", curl) } charms, closer := st.db().GetCollection(charmsC) defer closer() buildTxn := func(attempt int) ([]txn.Op, error) { // See if the charm already exists in state and exit early if that's the case. var doc charmDoc err := charms.Find(bson.D{{"_id", curl.String()}}).Select(bson.D{{"_id", 1}}).One(&doc) if err != nil && err != mgo.ErrNotFound { return nil, errors.Trace(err) } if err == nil { return nil, jujutxn.ErrNoOperations } // Delete all previous placeholders so we don't fill up the database with unused data. deleteOps, err := deleteOldPlaceholderCharmsOps(st, charms, curl) if err != nil { return nil, errors.Trace(err) } insertOps, err := insertPlaceholderCharmOps(st, curl) if err != nil { return nil, errors.Trace(err) } ops := append(deleteOps, insertOps...) return ops, nil } return errors.Trace(st.db().Run(buildTxn)) }
go
func (st *State) AddStoreCharmPlaceholder(curl *charm.URL) (err error) { // Perform sanity checks first. if curl.Schema != "cs" { return errors.Errorf("expected charm URL with cs schema, got %q", curl) } if curl.Revision < 0 { return errors.Errorf("expected charm URL with revision, got %q", curl) } charms, closer := st.db().GetCollection(charmsC) defer closer() buildTxn := func(attempt int) ([]txn.Op, error) { // See if the charm already exists in state and exit early if that's the case. var doc charmDoc err := charms.Find(bson.D{{"_id", curl.String()}}).Select(bson.D{{"_id", 1}}).One(&doc) if err != nil && err != mgo.ErrNotFound { return nil, errors.Trace(err) } if err == nil { return nil, jujutxn.ErrNoOperations } // Delete all previous placeholders so we don't fill up the database with unused data. deleteOps, err := deleteOldPlaceholderCharmsOps(st, charms, curl) if err != nil { return nil, errors.Trace(err) } insertOps, err := insertPlaceholderCharmOps(st, curl) if err != nil { return nil, errors.Trace(err) } ops := append(deleteOps, insertOps...) return ops, nil } return errors.Trace(st.db().Run(buildTxn)) }
[ "func", "(", "st", "*", "State", ")", "AddStoreCharmPlaceholder", "(", "curl", "*", "charm", ".", "URL", ")", "(", "err", "error", ")", "{", "// Perform sanity checks first.", "if", "curl", ".", "Schema", "!=", "\"", "\"", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "curl", ")", "\n", "}", "\n", "if", "curl", ".", "Revision", "<", "0", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "curl", ")", "\n", "}", "\n", "charms", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "charmsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "// See if the charm already exists in state and exit early if that's the case.", "var", "doc", "charmDoc", "\n", "err", ":=", "charms", ".", "Find", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "curl", ".", "String", "(", ")", "}", "}", ")", ".", "Select", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "1", "}", "}", ")", ".", "One", "(", "&", "doc", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "mgo", ".", "ErrNotFound", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "\n\n", "// Delete all previous placeholders so we don't fill up the database with unused data.", "deleteOps", ",", "err", ":=", "deleteOldPlaceholderCharmsOps", "(", "st", ",", "charms", ",", "curl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "insertOps", ",", "err", ":=", "insertPlaceholderCharmOps", "(", "st", ",", "curl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ops", ":=", "append", "(", "deleteOps", ",", "insertOps", "...", ")", "\n", "return", "ops", ",", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", ")", "\n", "}" ]
// AddStoreCharmPlaceholder creates a charm document in state for the given charm URL which // must reference a charm from the store. The charm document is marked as a placeholder which // means that if the charm is to be deployed, it will need to first be uploaded to model storage.
[ "AddStoreCharmPlaceholder", "creates", "a", "charm", "document", "in", "state", "for", "the", "given", "charm", "URL", "which", "must", "reference", "a", "charm", "from", "the", "store", ".", "The", "charm", "document", "is", "marked", "as", "a", "placeholder", "which", "means", "that", "if", "the", "charm", "is", "to", "be", "deployed", "it", "will", "need", "to", "first", "be", "uploaded", "to", "model", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/charm.go#L855-L890
157,756
juju/juju
resource/context/internal/download.go
Download
func Download(target DownloadTarget, remote ContentSource) error { resDir, err := target.Initialize() if err != nil { return errors.Trace(err) } if err := resDir.Write(remote); err != nil { return errors.Trace(err) } return nil }
go
func Download(target DownloadTarget, remote ContentSource) error { resDir, err := target.Initialize() if err != nil { return errors.Trace(err) } if err := resDir.Write(remote); err != nil { return errors.Trace(err) } return nil }
[ "func", "Download", "(", "target", "DownloadTarget", ",", "remote", "ContentSource", ")", "error", "{", "resDir", ",", "err", ":=", "target", ".", "Initialize", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "resDir", ".", "Write", "(", "remote", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Download downloads the resource from the provied source to the target.
[ "Download", "downloads", "the", "resource", "from", "the", "provied", "source", "to", "the", "target", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/download.go#L14-L25
157,757
juju/juju
provider/gce/google/config.go
NewCredentials
func NewCredentials(values map[string]string) (*Credentials, error) { var creds Credentials for k, v := range values { switch k { case OSEnvClientID: creds.ClientID = v case OSEnvClientEmail: creds.ClientEmail = v case OSEnvProjectID: creds.ProjectID = v case OSEnvPrivateKey: creds.PrivateKey = []byte(v) default: return nil, errors.NotSupportedf("key %q", k) } } if err := creds.Validate(); err != nil { return nil, errors.Trace(err) } jk, err := creds.buildJSONKey() if err != nil { return nil, errors.Trace(err) } creds.JSONKey = jk return &creds, nil }
go
func NewCredentials(values map[string]string) (*Credentials, error) { var creds Credentials for k, v := range values { switch k { case OSEnvClientID: creds.ClientID = v case OSEnvClientEmail: creds.ClientEmail = v case OSEnvProjectID: creds.ProjectID = v case OSEnvPrivateKey: creds.PrivateKey = []byte(v) default: return nil, errors.NotSupportedf("key %q", k) } } if err := creds.Validate(); err != nil { return nil, errors.Trace(err) } jk, err := creds.buildJSONKey() if err != nil { return nil, errors.Trace(err) } creds.JSONKey = jk return &creds, nil }
[ "func", "NewCredentials", "(", "values", "map", "[", "string", "]", "string", ")", "(", "*", "Credentials", ",", "error", ")", "{", "var", "creds", "Credentials", "\n", "for", "k", ",", "v", ":=", "range", "values", "{", "switch", "k", "{", "case", "OSEnvClientID", ":", "creds", ".", "ClientID", "=", "v", "\n", "case", "OSEnvClientEmail", ":", "creds", ".", "ClientEmail", "=", "v", "\n", "case", "OSEnvProjectID", ":", "creds", ".", "ProjectID", "=", "v", "\n", "case", "OSEnvPrivateKey", ":", "creds", ".", "PrivateKey", "=", "[", "]", "byte", "(", "v", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "NotSupportedf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "creds", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "jk", ",", "err", ":=", "creds", ".", "buildJSONKey", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "creds", ".", "JSONKey", "=", "jk", "\n", "return", "&", "creds", ",", "nil", "\n", "}" ]
// NewCredentials returns a new Credentials based on the provided // values. The keys must be recognized OS env var names for the // different credential fields.
[ "NewCredentials", "returns", "a", "new", "Credentials", "based", "on", "the", "provided", "values", ".", "The", "keys", "must", "be", "recognized", "OS", "env", "var", "names", "for", "the", "different", "credential", "fields", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/config.go#L59-L84
157,758
juju/juju
provider/gce/google/config.go
ParseJSONKey
func ParseJSONKey(jsonKeyFile io.Reader) (*Credentials, error) { jsonKey, err := ioutil.ReadAll(jsonKeyFile) if err != nil { return nil, errors.Trace(err) } values, err := parseJSONKey(jsonKey) if err != nil { return nil, errors.Trace(err) } creds, err := NewCredentials(values) if err != nil { return nil, errors.Trace(err) } creds.JSONKey = jsonKey return creds, nil }
go
func ParseJSONKey(jsonKeyFile io.Reader) (*Credentials, error) { jsonKey, err := ioutil.ReadAll(jsonKeyFile) if err != nil { return nil, errors.Trace(err) } values, err := parseJSONKey(jsonKey) if err != nil { return nil, errors.Trace(err) } creds, err := NewCredentials(values) if err != nil { return nil, errors.Trace(err) } creds.JSONKey = jsonKey return creds, nil }
[ "func", "ParseJSONKey", "(", "jsonKeyFile", "io", ".", "Reader", ")", "(", "*", "Credentials", ",", "error", ")", "{", "jsonKey", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "jsonKeyFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "values", ",", "err", ":=", "parseJSONKey", "(", "jsonKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "creds", ",", "err", ":=", "NewCredentials", "(", "values", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "creds", ".", "JSONKey", "=", "jsonKey", "\n", "return", "creds", ",", "nil", "\n", "}" ]
// ParseJSONKey returns a new Credentials with values based on the // provided JSON key file contents.
[ "ParseJSONKey", "returns", "a", "new", "Credentials", "with", "values", "based", "on", "the", "provided", "JSON", "key", "file", "contents", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/config.go#L88-L103
157,759
juju/juju
provider/gce/google/config.go
buildJSONKey
func (gc Credentials) buildJSONKey() ([]byte, error) { return json.Marshal(&map[string]string{ "type": jsonKeyTypeServiceAccount, "client_id": gc.ClientID, "client_email": gc.ClientEmail, "private_key": string(gc.PrivateKey), }) }
go
func (gc Credentials) buildJSONKey() ([]byte, error) { return json.Marshal(&map[string]string{ "type": jsonKeyTypeServiceAccount, "client_id": gc.ClientID, "client_email": gc.ClientEmail, "private_key": string(gc.PrivateKey), }) }
[ "func", "(", "gc", "Credentials", ")", "buildJSONKey", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "&", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "jsonKeyTypeServiceAccount", ",", "\"", "\"", ":", "gc", ".", "ClientID", ",", "\"", "\"", ":", "gc", ".", "ClientEmail", ",", "\"", "\"", ":", "string", "(", "gc", ".", "PrivateKey", ")", ",", "}", ")", "\n", "}" ]
// buildJSONKey returns the content of the JSON key file for the // credential values.
[ "buildJSONKey", "returns", "the", "content", "of", "the", "JSON", "key", "file", "for", "the", "credential", "values", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/config.go#L140-L147
157,760
juju/juju
provider/gce/google/config.go
Values
func (gc Credentials) Values() map[string]string { return map[string]string{ OSEnvClientID: gc.ClientID, OSEnvClientEmail: gc.ClientEmail, OSEnvPrivateKey: string(gc.PrivateKey), OSEnvProjectID: gc.ProjectID, } }
go
func (gc Credentials) Values() map[string]string { return map[string]string{ OSEnvClientID: gc.ClientID, OSEnvClientEmail: gc.ClientEmail, OSEnvPrivateKey: string(gc.PrivateKey), OSEnvProjectID: gc.ProjectID, } }
[ "func", "(", "gc", "Credentials", ")", "Values", "(", ")", "map", "[", "string", "]", "string", "{", "return", "map", "[", "string", "]", "string", "{", "OSEnvClientID", ":", "gc", ".", "ClientID", ",", "OSEnvClientEmail", ":", "gc", ".", "ClientEmail", ",", "OSEnvPrivateKey", ":", "string", "(", "gc", ".", "PrivateKey", ")", ",", "OSEnvProjectID", ":", "gc", ".", "ProjectID", ",", "}", "\n", "}" ]
// Values returns the credentials as a simple mapping with the // corresponding OS env variable names as the keys.
[ "Values", "returns", "the", "credentials", "as", "a", "simple", "mapping", "with", "the", "corresponding", "OS", "env", "variable", "names", "as", "the", "keys", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/config.go#L151-L158
157,761
juju/juju
provider/gce/google/config.go
Validate
func (gc Credentials) Validate() error { if gc.ClientID == "" { return NewMissingConfigValue(OSEnvClientID, "ClientID") } if gc.ClientEmail == "" { return NewMissingConfigValue(OSEnvClientEmail, "ClientEmail") } if _, err := mail.ParseAddress(gc.ClientEmail); err != nil { return NewInvalidConfigValueError(OSEnvClientEmail, gc.ClientEmail, err) } if len(gc.PrivateKey) == 0 { return NewMissingConfigValue(OSEnvPrivateKey, "PrivateKey") } return nil }
go
func (gc Credentials) Validate() error { if gc.ClientID == "" { return NewMissingConfigValue(OSEnvClientID, "ClientID") } if gc.ClientEmail == "" { return NewMissingConfigValue(OSEnvClientEmail, "ClientEmail") } if _, err := mail.ParseAddress(gc.ClientEmail); err != nil { return NewInvalidConfigValueError(OSEnvClientEmail, gc.ClientEmail, err) } if len(gc.PrivateKey) == 0 { return NewMissingConfigValue(OSEnvPrivateKey, "PrivateKey") } return nil }
[ "func", "(", "gc", "Credentials", ")", "Validate", "(", ")", "error", "{", "if", "gc", ".", "ClientID", "==", "\"", "\"", "{", "return", "NewMissingConfigValue", "(", "OSEnvClientID", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "gc", ".", "ClientEmail", "==", "\"", "\"", "{", "return", "NewMissingConfigValue", "(", "OSEnvClientEmail", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "mail", ".", "ParseAddress", "(", "gc", ".", "ClientEmail", ")", ";", "err", "!=", "nil", "{", "return", "NewInvalidConfigValueError", "(", "OSEnvClientEmail", ",", "gc", ".", "ClientEmail", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "gc", ".", "PrivateKey", ")", "==", "0", "{", "return", "NewMissingConfigValue", "(", "OSEnvPrivateKey", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate checks the credentialss for invalid values. If the values // are not valid, it returns errors.NotValid with the message set to // the corresponding OS environment variable name. // // To be considered valid, each of the credentials must be set to some // non-empty value. Furthermore, ClientEmail must be a proper email // address.
[ "Validate", "checks", "the", "credentialss", "for", "invalid", "values", ".", "If", "the", "values", "are", "not", "valid", "it", "returns", "errors", ".", "NotValid", "with", "the", "message", "set", "to", "the", "corresponding", "OS", "environment", "variable", "name", ".", "To", "be", "considered", "valid", "each", "of", "the", "credentials", "must", "be", "set", "to", "some", "non", "-", "empty", "value", ".", "Furthermore", "ClientEmail", "must", "be", "a", "proper", "email", "address", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/config.go#L167-L181
157,762
juju/juju
provider/gce/google/config.go
Validate
func (gc ConnectionConfig) Validate() error { if gc.Region == "" { return NewMissingConfigValue(OSEnvRegion, "Region") } if gc.ProjectID == "" { return NewMissingConfigValue(OSEnvProjectID, "ProjectID") } return nil }
go
func (gc ConnectionConfig) Validate() error { if gc.Region == "" { return NewMissingConfigValue(OSEnvRegion, "Region") } if gc.ProjectID == "" { return NewMissingConfigValue(OSEnvProjectID, "ProjectID") } return nil }
[ "func", "(", "gc", "ConnectionConfig", ")", "Validate", "(", ")", "error", "{", "if", "gc", ".", "Region", "==", "\"", "\"", "{", "return", "NewMissingConfigValue", "(", "OSEnvRegion", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "gc", ".", "ProjectID", "==", "\"", "\"", "{", "return", "NewMissingConfigValue", "(", "OSEnvProjectID", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate checks the connection's fields for invalid values. // If the values are not valid, it returns a config.InvalidConfigValueError // error with the key set to the corresponding OS environment variable // name. // // To be considered valid, each of the connection's must be set to some // non-empty value.
[ "Validate", "checks", "the", "connection", "s", "fields", "for", "invalid", "values", ".", "If", "the", "values", "are", "not", "valid", "it", "returns", "a", "config", ".", "InvalidConfigValueError", "error", "with", "the", "key", "set", "to", "the", "corresponding", "OS", "environment", "variable", "name", ".", "To", "be", "considered", "valid", "each", "of", "the", "connection", "s", "must", "be", "set", "to", "some", "non", "-", "empty", "value", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/config.go#L201-L209
157,763
juju/juju
provider/ec2/subnet.go
CreateSubnetMatcher
func CreateSubnetMatcher(subnetQuery string) SubnetMatcher { logger.Debugf("searching for subnet matching placement directive %q", subnetQuery) _, ipNet, err := net.ParseCIDR(subnetQuery) if err == nil { return &cidrSubnetMatcher{ ipNet: ipNet, CIDR: ipNet.String(), } } if strings.HasPrefix(subnetQuery, "subnet-") { return &subnetIDMatcher{ subnetID: subnetQuery, } } return &subnetNameMatcher{ name: subnetQuery, } }
go
func CreateSubnetMatcher(subnetQuery string) SubnetMatcher { logger.Debugf("searching for subnet matching placement directive %q", subnetQuery) _, ipNet, err := net.ParseCIDR(subnetQuery) if err == nil { return &cidrSubnetMatcher{ ipNet: ipNet, CIDR: ipNet.String(), } } if strings.HasPrefix(subnetQuery, "subnet-") { return &subnetIDMatcher{ subnetID: subnetQuery, } } return &subnetNameMatcher{ name: subnetQuery, } }
[ "func", "CreateSubnetMatcher", "(", "subnetQuery", "string", ")", "SubnetMatcher", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "subnetQuery", ")", "\n", "_", ",", "ipNet", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "subnetQuery", ")", "\n", "if", "err", "==", "nil", "{", "return", "&", "cidrSubnetMatcher", "{", "ipNet", ":", "ipNet", ",", "CIDR", ":", "ipNet", ".", "String", "(", ")", ",", "}", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "subnetQuery", ",", "\"", "\"", ")", "{", "return", "&", "subnetIDMatcher", "{", "subnetID", ":", "subnetQuery", ",", "}", "\n", "}", "\n", "return", "&", "subnetNameMatcher", "{", "name", ":", "subnetQuery", ",", "}", "\n", "}" ]
// CreateSubnetMatcher creates a SubnetMatcher that handles a particular method // of comparison based on the content of the subnet query. If the query looks // like a CIDR, then we will match subnets with the same CIDR. If it follows // the syntax of a "subnet-XXXX" then we will match the Subnet ID. Everything // else is just matched as a Name.
[ "CreateSubnetMatcher", "creates", "a", "SubnetMatcher", "that", "handles", "a", "particular", "method", "of", "comparison", "based", "on", "the", "content", "of", "the", "subnet", "query", ".", "If", "the", "query", "looks", "like", "a", "CIDR", "then", "we", "will", "match", "subnets", "with", "the", "same", "CIDR", ".", "If", "it", "follows", "the", "syntax", "of", "a", "subnet", "-", "XXXX", "then", "we", "will", "match", "the", "Subnet", "ID", ".", "Everything", "else", "is", "just", "matched", "as", "a", "Name", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/subnet.go#L22-L39
157,764
juju/juju
worker/metrics/collect/context.go
Flush
func (ctx *hookContext) Flush(process string, ctxErr error) (err error) { return ctx.recorder.Close() }
go
func (ctx *hookContext) Flush(process string, ctxErr error) (err error) { return ctx.recorder.Close() }
[ "func", "(", "ctx", "*", "hookContext", ")", "Flush", "(", "process", "string", ",", "ctxErr", "error", ")", "(", "err", "error", ")", "{", "return", "ctx", ".", "recorder", ".", "Close", "(", ")", "\n", "}" ]
// Flush implements runner.Context.
[ "Flush", "implements", "runner", ".", "Context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/collect/context.go#L50-L52
157,765
juju/juju
worker/metrics/collect/context.go
AddMetric
func (ctx *hookContext) AddMetric(key string, value string, created time.Time) error { return ctx.recorder.AddMetric(key, value, created, nil) }
go
func (ctx *hookContext) AddMetric(key string, value string, created time.Time) error { return ctx.recorder.AddMetric(key, value, created, nil) }
[ "func", "(", "ctx", "*", "hookContext", ")", "AddMetric", "(", "key", "string", ",", "value", "string", ",", "created", "time", ".", "Time", ")", "error", "{", "return", "ctx", ".", "recorder", ".", "AddMetric", "(", "key", ",", "value", ",", "created", ",", "nil", ")", "\n", "}" ]
// AddMetric implements runner.Context.
[ "AddMetric", "implements", "runner", ".", "Context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/collect/context.go#L55-L57
157,766
juju/juju
worker/metrics/collect/context.go
AddMetricLabels
func (ctx *hookContext) AddMetricLabels(key string, value string, created time.Time, labels map[string]string) error { return ctx.recorder.AddMetric(key, value, created, labels) }
go
func (ctx *hookContext) AddMetricLabels(key string, value string, created time.Time, labels map[string]string) error { return ctx.recorder.AddMetric(key, value, created, labels) }
[ "func", "(", "ctx", "*", "hookContext", ")", "AddMetricLabels", "(", "key", "string", ",", "value", "string", ",", "created", "time", ".", "Time", ",", "labels", "map", "[", "string", "]", "string", ")", "error", "{", "return", "ctx", ".", "recorder", ".", "AddMetric", "(", "key", ",", "value", ",", "created", ",", "labels", ")", "\n", "}" ]
// AddMetricLabels implements runner.Context.
[ "AddMetricLabels", "implements", "runner", ".", "Context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/collect/context.go#L60-L62
157,767
juju/juju
worker/metrics/collect/context.go
addJujuUnitsMetric
func (ctx *hookContext) addJujuUnitsMetric() error { if ctx.recorder.IsDeclaredMetric("juju-units") { // TODO(fwereade): 2016-03-17 lp:1558657 err := ctx.recorder.AddMetric("juju-units", "1", time.Now().UTC(), nil) if err != nil { return errors.Trace(err) } } return nil }
go
func (ctx *hookContext) addJujuUnitsMetric() error { if ctx.recorder.IsDeclaredMetric("juju-units") { // TODO(fwereade): 2016-03-17 lp:1558657 err := ctx.recorder.AddMetric("juju-units", "1", time.Now().UTC(), nil) if err != nil { return errors.Trace(err) } } return nil }
[ "func", "(", "ctx", "*", "hookContext", ")", "addJujuUnitsMetric", "(", ")", "error", "{", "if", "ctx", ".", "recorder", ".", "IsDeclaredMetric", "(", "\"", "\"", ")", "{", "// TODO(fwereade): 2016-03-17 lp:1558657", "err", ":=", "ctx", ".", "recorder", ".", "AddMetric", "(", "\"", "\"", ",", "\"", "\"", ",", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// addJujuUnitsMetric adds the juju-units built in metric if it // is defined for this context.
[ "addJujuUnitsMetric", "adds", "the", "juju", "-", "units", "built", "in", "metric", "if", "it", "is", "defined", "for", "this", "context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/collect/context.go#L66-L75
157,768
juju/juju
worker/metrics/collect/context.go
Component
func (ctx *hookContext) Component(name string) (jujuc.ContextComponent, error) { return nil, errors.NotFoundf("context component %q", name) }
go
func (ctx *hookContext) Component(name string) (jujuc.ContextComponent, error) { return nil, errors.NotFoundf("context component %q", name) }
[ "func", "(", "ctx", "*", "hookContext", ")", "Component", "(", "name", "string", ")", "(", "jujuc", ".", "ContextComponent", ",", "error", ")", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "name", ")", "\n", "}" ]
// Component implements runner.Context.
[ "Component", "implements", "runner", ".", "Context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/collect/context.go#L100-L102
157,769
juju/juju
provider/azure/init.go
NewProvider
func NewProvider(config ProviderConfig) (environs.CloudEnvironProvider, error) { environProvider, err := NewEnvironProvider(config) if err != nil { return nil, errors.Trace(err) } return environProvider, nil }
go
func NewProvider(config ProviderConfig) (environs.CloudEnvironProvider, error) { environProvider, err := NewEnvironProvider(config) if err != nil { return nil, errors.Trace(err) } return environProvider, nil }
[ "func", "NewProvider", "(", "config", "ProviderConfig", ")", "(", "environs", ".", "CloudEnvironProvider", ",", "error", ")", "{", "environProvider", ",", "err", ":=", "NewEnvironProvider", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "environProvider", ",", "nil", "\n", "}" ]
// NewProvider instantiates and returns the Azure EnvironProvider using the // given configuration.
[ "NewProvider", "instantiates", "and", "returns", "the", "Azure", "EnvironProvider", "using", "the", "given", "configuration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/init.go#L23-L29
157,770
juju/juju
api/migrationflag/facade.go
NewFacade
func NewFacade(apiCaller base.APICaller, newWatcher NewWatcherFunc) *Facade { facadeCaller := base.NewFacadeCaller(apiCaller, "MigrationFlag") return &Facade{ caller: facadeCaller, newWatcher: newWatcher, } }
go
func NewFacade(apiCaller base.APICaller, newWatcher NewWatcherFunc) *Facade { facadeCaller := base.NewFacadeCaller(apiCaller, "MigrationFlag") return &Facade{ caller: facadeCaller, newWatcher: newWatcher, } }
[ "func", "NewFacade", "(", "apiCaller", "base", ".", "APICaller", ",", "newWatcher", "NewWatcherFunc", ")", "*", "Facade", "{", "facadeCaller", ":=", "base", ".", "NewFacadeCaller", "(", "apiCaller", ",", "\"", "\"", ")", "\n", "return", "&", "Facade", "{", "caller", ":", "facadeCaller", ",", "newWatcher", ":", "newWatcher", ",", "}", "\n", "}" ]
// NewFacade returns a Facade backed by the supplied api caller.
[ "NewFacade", "returns", "a", "Facade", "backed", "by", "the", "supplied", "api", "caller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/migrationflag/facade.go#L20-L26
157,771
juju/juju
api/migrationflag/facade.go
Phase
func (facade *Facade) Phase(uuid string) (migration.Phase, error) { results := params.PhaseResults{} err := facade.call("Phase", uuid, &results) if err != nil { return migration.UNKNOWN, errors.Trace(err) } if count := len(results.Results); count != 1 { return migration.UNKNOWN, countError(count) } result := results.Results[0] if result.Error != nil { return migration.UNKNOWN, errors.Trace(result.Error) } phase, ok := migration.ParsePhase(result.Phase) if !ok { err := errors.Errorf("unknown phase %q", result.Phase) return migration.UNKNOWN, err } return phase, nil }
go
func (facade *Facade) Phase(uuid string) (migration.Phase, error) { results := params.PhaseResults{} err := facade.call("Phase", uuid, &results) if err != nil { return migration.UNKNOWN, errors.Trace(err) } if count := len(results.Results); count != 1 { return migration.UNKNOWN, countError(count) } result := results.Results[0] if result.Error != nil { return migration.UNKNOWN, errors.Trace(result.Error) } phase, ok := migration.ParsePhase(result.Phase) if !ok { err := errors.Errorf("unknown phase %q", result.Phase) return migration.UNKNOWN, err } return phase, nil }
[ "func", "(", "facade", "*", "Facade", ")", "Phase", "(", "uuid", "string", ")", "(", "migration", ".", "Phase", ",", "error", ")", "{", "results", ":=", "params", ".", "PhaseResults", "{", "}", "\n", "err", ":=", "facade", ".", "call", "(", "\"", "\"", ",", "uuid", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "migration", ".", "UNKNOWN", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "count", ":=", "len", "(", "results", ".", "Results", ")", ";", "count", "!=", "1", "{", "return", "migration", ".", "UNKNOWN", ",", "countError", "(", "count", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "migration", ".", "UNKNOWN", ",", "errors", ".", "Trace", "(", "result", ".", "Error", ")", "\n", "}", "\n", "phase", ",", "ok", ":=", "migration", ".", "ParsePhase", "(", "result", ".", "Phase", ")", "\n", "if", "!", "ok", "{", "err", ":=", "errors", ".", "Errorf", "(", "\"", "\"", ",", "result", ".", "Phase", ")", "\n", "return", "migration", ".", "UNKNOWN", ",", "err", "\n", "}", "\n", "return", "phase", ",", "nil", "\n", "}" ]
// Phase returns the current migration.Phase for the supplied model UUID.
[ "Phase", "returns", "the", "current", "migration", ".", "Phase", "for", "the", "supplied", "model", "UUID", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/migrationflag/facade.go#L35-L54
157,772
juju/juju
api/migrationflag/facade.go
Watch
func (facade *Facade) Watch(uuid string) (watcher.NotifyWatcher, error) { results := params.NotifyWatchResults{} err := facade.call("Watch", uuid, &results) if err != nil { return nil, errors.Trace(err) } if count := len(results.Results); count != 1 { return nil, countError(count) } result := results.Results[0] if result.Error != nil { return nil, errors.Trace(result.Error) } apiCaller := facade.caller.RawAPICaller() watcher := facade.newWatcher(apiCaller, result) return watcher, nil }
go
func (facade *Facade) Watch(uuid string) (watcher.NotifyWatcher, error) { results := params.NotifyWatchResults{} err := facade.call("Watch", uuid, &results) if err != nil { return nil, errors.Trace(err) } if count := len(results.Results); count != 1 { return nil, countError(count) } result := results.Results[0] if result.Error != nil { return nil, errors.Trace(result.Error) } apiCaller := facade.caller.RawAPICaller() watcher := facade.newWatcher(apiCaller, result) return watcher, nil }
[ "func", "(", "facade", "*", "Facade", ")", "Watch", "(", "uuid", "string", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "results", ":=", "params", ".", "NotifyWatchResults", "{", "}", "\n", "err", ":=", "facade", ".", "call", "(", "\"", "\"", ",", "uuid", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "count", ":=", "len", "(", "results", ".", "Results", ")", ";", "count", "!=", "1", "{", "return", "nil", ",", "countError", "(", "count", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "result", ".", "Error", ")", "\n", "}", "\n", "apiCaller", ":=", "facade", ".", "caller", ".", "RawAPICaller", "(", ")", "\n", "watcher", ":=", "facade", ".", "newWatcher", "(", "apiCaller", ",", "result", ")", "\n", "return", "watcher", ",", "nil", "\n", "}" ]
// Watch returns a NotifyWatcher that will inform of potential changes // to the result of Phase for the supplied model UUID.
[ "Watch", "returns", "a", "NotifyWatcher", "that", "will", "inform", "of", "potential", "changes", "to", "the", "result", "of", "Phase", "for", "the", "supplied", "model", "UUID", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/migrationflag/facade.go#L58-L74
157,773
juju/juju
api/migrationflag/facade.go
call
func (facade *Facade) call(name, uuid string, results interface{}) error { model := names.NewModelTag(uuid).String() args := params.Entities{[]params.Entity{{model}}} err := facade.caller.FacadeCall(name, args, results) return errors.Trace(err) }
go
func (facade *Facade) call(name, uuid string, results interface{}) error { model := names.NewModelTag(uuid).String() args := params.Entities{[]params.Entity{{model}}} err := facade.caller.FacadeCall(name, args, results) return errors.Trace(err) }
[ "func", "(", "facade", "*", "Facade", ")", "call", "(", "name", ",", "uuid", "string", ",", "results", "interface", "{", "}", ")", "error", "{", "model", ":=", "names", ".", "NewModelTag", "(", "uuid", ")", ".", "String", "(", ")", "\n", "args", ":=", "params", ".", "Entities", "{", "[", "]", "params", ".", "Entity", "{", "{", "model", "}", "}", "}", "\n", "err", ":=", "facade", ".", "caller", ".", "FacadeCall", "(", "name", ",", "args", ",", "results", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// call converts the supplied model uuid into a params.Entities and // invokes the facade caller.
[ "call", "converts", "the", "supplied", "model", "uuid", "into", "a", "params", ".", "Entities", "and", "invokes", "the", "facade", "caller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/migrationflag/facade.go#L78-L83
157,774
juju/juju
apiserver/debuglog.go
sendError
func (s *debugLogSocketImpl) sendError(err error) { if sendErr := s.conn.SendInitialErrorV0(err); sendErr != nil { logger.Errorf("closing websocket, %v", err) s.conn.Close() return } }
go
func (s *debugLogSocketImpl) sendError(err error) { if sendErr := s.conn.SendInitialErrorV0(err); sendErr != nil { logger.Errorf("closing websocket, %v", err) s.conn.Close() return } }
[ "func", "(", "s", "*", "debugLogSocketImpl", ")", "sendError", "(", "err", "error", ")", "{", "if", "sendErr", ":=", "s", ".", "conn", ".", "SendInitialErrorV0", "(", "err", ")", ";", "sendErr", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "s", ".", "conn", ".", "Close", "(", ")", "\n", "return", "\n", "}", "\n", "}" ]
// sendError implements debugLogSocket.
[ "sendError", "implements", "debugLogSocket", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/debuglog.go#L163-L169
157,775
juju/juju
apiserver/facades/agent/meterstatus/mocks/meterstatus_mock.go
NewMockMeterStatusState
func NewMockMeterStatusState(ctrl *gomock.Controller) *MockMeterStatusState { mock := &MockMeterStatusState{ctrl: ctrl} mock.recorder = &MockMeterStatusStateMockRecorder{mock} return mock }
go
func NewMockMeterStatusState(ctrl *gomock.Controller) *MockMeterStatusState { mock := &MockMeterStatusState{ctrl: ctrl} mock.recorder = &MockMeterStatusStateMockRecorder{mock} return mock }
[ "func", "NewMockMeterStatusState", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockMeterStatusState", "{", "mock", ":=", "&", "MockMeterStatusState", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockMeterStatusStateMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockMeterStatusState creates a new mock instance
[ "NewMockMeterStatusState", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/meterstatus/mocks/meterstatus_mock.go#L26-L30
157,776
juju/juju
worker/metricworker/metricmanager.go
newMetricsManager
func newMetricsManager(client metricsmanager.MetricsManagerClient, notify chan string) (*worker.Runner, error) { // TODO(fwereade): break this out into separate manifolds (with their own facades). // Periodic workers automatically retry so none should return an error. If they do // it's ok to restart them individually. isFatal := func(error) bool { return false } runner := worker.NewRunner(worker.RunnerParams{ IsFatal: isFatal, RestartDelay: jworker.RestartDelay, }) err := runner.StartWorker("sender", func() (worker.Worker, error) { return newSender(client, notify), nil }) if err != nil { return nil, errors.Trace(err) } err = runner.StartWorker("cleanup", func() (worker.Worker, error) { return newCleanup(client, notify), nil }) if err != nil { return nil, errors.Trace(err) } return runner, nil }
go
func newMetricsManager(client metricsmanager.MetricsManagerClient, notify chan string) (*worker.Runner, error) { // TODO(fwereade): break this out into separate manifolds (with their own facades). // Periodic workers automatically retry so none should return an error. If they do // it's ok to restart them individually. isFatal := func(error) bool { return false } runner := worker.NewRunner(worker.RunnerParams{ IsFatal: isFatal, RestartDelay: jworker.RestartDelay, }) err := runner.StartWorker("sender", func() (worker.Worker, error) { return newSender(client, notify), nil }) if err != nil { return nil, errors.Trace(err) } err = runner.StartWorker("cleanup", func() (worker.Worker, error) { return newCleanup(client, notify), nil }) if err != nil { return nil, errors.Trace(err) } return runner, nil }
[ "func", "newMetricsManager", "(", "client", "metricsmanager", ".", "MetricsManagerClient", ",", "notify", "chan", "string", ")", "(", "*", "worker", ".", "Runner", ",", "error", ")", "{", "// TODO(fwereade): break this out into separate manifolds (with their own facades).", "// Periodic workers automatically retry so none should return an error. If they do", "// it's ok to restart them individually.", "isFatal", ":=", "func", "(", "error", ")", "bool", "{", "return", "false", "\n", "}", "\n", "runner", ":=", "worker", ".", "NewRunner", "(", "worker", ".", "RunnerParams", "{", "IsFatal", ":", "isFatal", ",", "RestartDelay", ":", "jworker", ".", "RestartDelay", ",", "}", ")", "\n", "err", ":=", "runner", ".", "StartWorker", "(", "\"", "\"", ",", "func", "(", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "return", "newSender", "(", "client", ",", "notify", ")", ",", "nil", "\n", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "err", "=", "runner", ".", "StartWorker", "(", "\"", "\"", ",", "func", "(", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "return", "newCleanup", "(", "client", ",", "notify", ")", ",", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "runner", ",", "nil", "\n", "}" ]
// NewMetricsManager creates a runner that will run the metricsmanagement workers.
[ "NewMetricsManager", "creates", "a", "runner", "that", "will", "run", "the", "metricsmanagement", "workers", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metricworker/metricmanager.go#L15-L42
157,777
juju/juju
apiserver/facades/agent/leadership/leadership.go
NewLeadershipServiceFacade
func NewLeadershipServiceFacade(context facade.Context) (LeadershipService, error) { claimer, err := context.LeadershipClaimer(context.State().ModelUUID()) if err != nil { return nil, errors.Trace(err) } return NewLeadershipService(claimer, context.Auth()) }
go
func NewLeadershipServiceFacade(context facade.Context) (LeadershipService, error) { claimer, err := context.LeadershipClaimer(context.State().ModelUUID()) if err != nil { return nil, errors.Trace(err) } return NewLeadershipService(claimer, context.Auth()) }
[ "func", "NewLeadershipServiceFacade", "(", "context", "facade", ".", "Context", ")", "(", "LeadershipService", ",", "error", ")", "{", "claimer", ",", "err", ":=", "context", ".", "LeadershipClaimer", "(", "context", ".", "State", "(", ")", ".", "ModelUUID", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "NewLeadershipService", "(", "claimer", ",", "context", ".", "Auth", "(", ")", ")", "\n", "}" ]
// NewLeadershipServiceFacade constructs a new LeadershipService and presents // a signature that can be used for facade registration.
[ "NewLeadershipServiceFacade", "constructs", "a", "new", "LeadershipService", "and", "presents", "a", "signature", "that", "can", "be", "used", "for", "facade", "registration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/leadership/leadership.go#L36-L42
157,778
juju/juju
apiserver/facades/agent/leadership/leadership.go
NewLeadershipService
func NewLeadershipService( claimer leadership.Claimer, authorizer facade.Authorizer, ) (LeadershipService, error) { if !authorizer.AuthUnitAgent() && !authorizer.AuthApplicationAgent() { return nil, errors.Unauthorizedf("permission denied") } return &leadershipService{ claimer: claimer, authorizer: authorizer, }, nil }
go
func NewLeadershipService( claimer leadership.Claimer, authorizer facade.Authorizer, ) (LeadershipService, error) { if !authorizer.AuthUnitAgent() && !authorizer.AuthApplicationAgent() { return nil, errors.Unauthorizedf("permission denied") } return &leadershipService{ claimer: claimer, authorizer: authorizer, }, nil }
[ "func", "NewLeadershipService", "(", "claimer", "leadership", ".", "Claimer", ",", "authorizer", "facade", ".", "Authorizer", ",", ")", "(", "LeadershipService", ",", "error", ")", "{", "if", "!", "authorizer", ".", "AuthUnitAgent", "(", ")", "&&", "!", "authorizer", ".", "AuthApplicationAgent", "(", ")", "{", "return", "nil", ",", "errors", ".", "Unauthorizedf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "leadershipService", "{", "claimer", ":", "claimer", ",", "authorizer", ":", "authorizer", ",", "}", ",", "nil", "\n", "}" ]
// NewLeadershipService constructs a new LeadershipService.
[ "NewLeadershipService", "constructs", "a", "new", "LeadershipService", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/leadership/leadership.go#L45-L57
157,779
juju/juju
apiserver/facades/agent/leadership/leadership.go
ClaimLeadership
func (m *leadershipService) ClaimLeadership(args params.ClaimLeadershipBulkParams) (params.ClaimLeadershipBulkResults, error) { results := make([]params.ErrorResult, len(args.Params)) for pIdx, p := range args.Params { result := &results[pIdx] applicationTag, unitTag, err := parseApplicationAndUnitTags(p.ApplicationTag, p.UnitTag) if err != nil { result.Error = common.ServerError(err) continue } duration := time.Duration(p.DurationSeconds * float64(time.Second)) if duration > MaxLeaseRequest || duration < MinLeaseRequest { result.Error = common.ServerError(errors.New("invalid duration")) continue } // In the future, situations may arise wherein units will make // leadership claims for other units. For now, units can only // claim leadership for themselves, for their own service. authTag := m.authorizer.GetAuthTag() canClaim := false switch authTag.(type) { case names.UnitTag: canClaim = m.authorizer.AuthOwner(unitTag) && m.authMember(applicationTag) case names.ApplicationTag: canClaim = m.authorizer.AuthOwner(applicationTag) } if !canClaim { result.Error = common.ServerError(common.ErrPerm) continue } if err = m.claimer.ClaimLeadership(applicationTag.Id(), unitTag.Id(), duration); err != nil { result.Error = common.ServerError(err) } } return params.ClaimLeadershipBulkResults{results}, nil }
go
func (m *leadershipService) ClaimLeadership(args params.ClaimLeadershipBulkParams) (params.ClaimLeadershipBulkResults, error) { results := make([]params.ErrorResult, len(args.Params)) for pIdx, p := range args.Params { result := &results[pIdx] applicationTag, unitTag, err := parseApplicationAndUnitTags(p.ApplicationTag, p.UnitTag) if err != nil { result.Error = common.ServerError(err) continue } duration := time.Duration(p.DurationSeconds * float64(time.Second)) if duration > MaxLeaseRequest || duration < MinLeaseRequest { result.Error = common.ServerError(errors.New("invalid duration")) continue } // In the future, situations may arise wherein units will make // leadership claims for other units. For now, units can only // claim leadership for themselves, for their own service. authTag := m.authorizer.GetAuthTag() canClaim := false switch authTag.(type) { case names.UnitTag: canClaim = m.authorizer.AuthOwner(unitTag) && m.authMember(applicationTag) case names.ApplicationTag: canClaim = m.authorizer.AuthOwner(applicationTag) } if !canClaim { result.Error = common.ServerError(common.ErrPerm) continue } if err = m.claimer.ClaimLeadership(applicationTag.Id(), unitTag.Id(), duration); err != nil { result.Error = common.ServerError(err) } } return params.ClaimLeadershipBulkResults{results}, nil }
[ "func", "(", "m", "*", "leadershipService", ")", "ClaimLeadership", "(", "args", "params", ".", "ClaimLeadershipBulkParams", ")", "(", "params", ".", "ClaimLeadershipBulkResults", ",", "error", ")", "{", "results", ":=", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Params", ")", ")", "\n", "for", "pIdx", ",", "p", ":=", "range", "args", ".", "Params", "{", "result", ":=", "&", "results", "[", "pIdx", "]", "\n", "applicationTag", ",", "unitTag", ",", "err", ":=", "parseApplicationAndUnitTags", "(", "p", ".", "ApplicationTag", ",", "p", ".", "UnitTag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "duration", ":=", "time", ".", "Duration", "(", "p", ".", "DurationSeconds", "*", "float64", "(", "time", ".", "Second", ")", ")", "\n", "if", "duration", ">", "MaxLeaseRequest", "||", "duration", "<", "MinLeaseRequest", "{", "result", ".", "Error", "=", "common", ".", "ServerError", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "continue", "\n", "}", "\n\n", "// In the future, situations may arise wherein units will make", "// leadership claims for other units. For now, units can only", "// claim leadership for themselves, for their own service.", "authTag", ":=", "m", ".", "authorizer", ".", "GetAuthTag", "(", ")", "\n", "canClaim", ":=", "false", "\n", "switch", "authTag", ".", "(", "type", ")", "{", "case", "names", ".", "UnitTag", ":", "canClaim", "=", "m", ".", "authorizer", ".", "AuthOwner", "(", "unitTag", ")", "&&", "m", ".", "authMember", "(", "applicationTag", ")", "\n", "case", "names", ".", "ApplicationTag", ":", "canClaim", "=", "m", ".", "authorizer", ".", "AuthOwner", "(", "applicationTag", ")", "\n", "}", "\n", "if", "!", "canClaim", "{", "result", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "if", "err", "=", "m", ".", "claimer", ".", "ClaimLeadership", "(", "applicationTag", ".", "Id", "(", ")", ",", "unitTag", ".", "Id", "(", ")", ",", "duration", ")", ";", "err", "!=", "nil", "{", "result", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "params", ".", "ClaimLeadershipBulkResults", "{", "results", "}", ",", "nil", "\n", "}" ]
// ClaimLeadership is part of the LeadershipService interface.
[ "ClaimLeadership", "is", "part", "of", "the", "LeadershipService", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/leadership/leadership.go#L67-L105
157,780
juju/juju
apiserver/facades/agent/leadership/leadership.go
BlockUntilLeadershipReleased
func (m *leadershipService) BlockUntilLeadershipReleased(ctx context.Context, applicationTag names.ApplicationTag) (params.ErrorResult, error) { authTag := m.authorizer.GetAuthTag() hasPerm := false switch authTag.(type) { case names.UnitTag: hasPerm = m.authMember(applicationTag) case names.ApplicationTag: hasPerm = m.authorizer.AuthOwner(applicationTag) } if !hasPerm { return params.ErrorResult{Error: common.ServerError(common.ErrPerm)}, nil } if err := m.claimer.BlockUntilLeadershipReleased(applicationTag.Id(), ctx.Done()); err != nil { return params.ErrorResult{Error: common.ServerError(err)}, nil } return params.ErrorResult{}, nil }
go
func (m *leadershipService) BlockUntilLeadershipReleased(ctx context.Context, applicationTag names.ApplicationTag) (params.ErrorResult, error) { authTag := m.authorizer.GetAuthTag() hasPerm := false switch authTag.(type) { case names.UnitTag: hasPerm = m.authMember(applicationTag) case names.ApplicationTag: hasPerm = m.authorizer.AuthOwner(applicationTag) } if !hasPerm { return params.ErrorResult{Error: common.ServerError(common.ErrPerm)}, nil } if err := m.claimer.BlockUntilLeadershipReleased(applicationTag.Id(), ctx.Done()); err != nil { return params.ErrorResult{Error: common.ServerError(err)}, nil } return params.ErrorResult{}, nil }
[ "func", "(", "m", "*", "leadershipService", ")", "BlockUntilLeadershipReleased", "(", "ctx", "context", ".", "Context", ",", "applicationTag", "names", ".", "ApplicationTag", ")", "(", "params", ".", "ErrorResult", ",", "error", ")", "{", "authTag", ":=", "m", ".", "authorizer", ".", "GetAuthTag", "(", ")", "\n", "hasPerm", ":=", "false", "\n", "switch", "authTag", ".", "(", "type", ")", "{", "case", "names", ".", "UnitTag", ":", "hasPerm", "=", "m", ".", "authMember", "(", "applicationTag", ")", "\n", "case", "names", ".", "ApplicationTag", ":", "hasPerm", "=", "m", ".", "authorizer", ".", "AuthOwner", "(", "applicationTag", ")", "\n", "}", "\n\n", "if", "!", "hasPerm", "{", "return", "params", ".", "ErrorResult", "{", "Error", ":", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "}", ",", "nil", "\n", "}", "\n\n", "if", "err", ":=", "m", ".", "claimer", ".", "BlockUntilLeadershipReleased", "(", "applicationTag", ".", "Id", "(", ")", ",", "ctx", ".", "Done", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResult", "{", "Error", ":", "common", ".", "ServerError", "(", "err", ")", "}", ",", "nil", "\n", "}", "\n", "return", "params", ".", "ErrorResult", "{", "}", ",", "nil", "\n", "}" ]
// BlockUntilLeadershipReleased implements the LeadershipService interface.
[ "BlockUntilLeadershipReleased", "implements", "the", "LeadershipService", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/leadership/leadership.go#L108-L126
157,781
juju/juju
apiserver/facades/agent/leadership/leadership.go
parseApplicationAndUnitTags
func parseApplicationAndUnitTags( applicationTagString, unitTagString string, ) ( names.ApplicationTag, names.UnitTag, error, ) { // TODO(fwereade) 2015-02-25 bug #1425506 // These permissions errors are not appropriate -- there's no permission or // security issue in play here, because our tag format is public, and the // error only triggers when the strings fail to match that format. applicationTag, err := names.ParseApplicationTag(applicationTagString) if err != nil { return names.ApplicationTag{}, names.UnitTag{}, common.ErrPerm } unitTag, err := names.ParseUnitTag(unitTagString) if err != nil { return names.ApplicationTag{}, names.UnitTag{}, common.ErrPerm } return applicationTag, unitTag, nil }
go
func parseApplicationAndUnitTags( applicationTagString, unitTagString string, ) ( names.ApplicationTag, names.UnitTag, error, ) { // TODO(fwereade) 2015-02-25 bug #1425506 // These permissions errors are not appropriate -- there's no permission or // security issue in play here, because our tag format is public, and the // error only triggers when the strings fail to match that format. applicationTag, err := names.ParseApplicationTag(applicationTagString) if err != nil { return names.ApplicationTag{}, names.UnitTag{}, common.ErrPerm } unitTag, err := names.ParseUnitTag(unitTagString) if err != nil { return names.ApplicationTag{}, names.UnitTag{}, common.ErrPerm } return applicationTag, unitTag, nil }
[ "func", "parseApplicationAndUnitTags", "(", "applicationTagString", ",", "unitTagString", "string", ",", ")", "(", "names", ".", "ApplicationTag", ",", "names", ".", "UnitTag", ",", "error", ",", ")", "{", "// TODO(fwereade) 2015-02-25 bug #1425506", "// These permissions errors are not appropriate -- there's no permission or", "// security issue in play here, because our tag format is public, and the", "// error only triggers when the strings fail to match that format.", "applicationTag", ",", "err", ":=", "names", ".", "ParseApplicationTag", "(", "applicationTagString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "names", ".", "ApplicationTag", "{", "}", ",", "names", ".", "UnitTag", "{", "}", ",", "common", ".", "ErrPerm", "\n", "}", "\n\n", "unitTag", ",", "err", ":=", "names", ".", "ParseUnitTag", "(", "unitTagString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "names", ".", "ApplicationTag", "{", "}", ",", "names", ".", "UnitTag", "{", "}", ",", "common", ".", "ErrPerm", "\n", "}", "\n\n", "return", "applicationTag", ",", "unitTag", ",", "nil", "\n", "}" ]
// parseApplicationAndUnitTags takes in string representations of application // and unit tags and returns their corresponding tags.
[ "parseApplicationAndUnitTags", "takes", "in", "string", "representations", "of", "application", "and", "unit", "tags", "and", "returns", "their", "corresponding", "tags", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/leadership/leadership.go#L144-L164
157,782
juju/juju
state/relationunit.go
subordinateOps
func (ru *RelationUnit) subordinateOps() ([]txn.Op, string, error) { units, closer := ru.st.db().GetCollection(unitsC) defer closer() if !ru.isPrincipal || ru.endpoint.Scope != charm.ScopeContainer { return nil, "", nil } related, err := ru.relation.RelatedEndpoints(ru.endpoint.ApplicationName) if err != nil { return nil, "", err } if len(related) != 1 { return nil, "", fmt.Errorf("expected single related endpoint, got %v", related) } applicationname, unitName := related[0].ApplicationName, ru.unitName selSubordinate := bson.D{{"application", applicationname}, {"principal", unitName}} var lDoc lifeDoc if err := units.Find(selSubordinate).One(&lDoc); err == mgo.ErrNotFound { application, err := ru.st.Application(applicationname) if err != nil { return nil, "", err } _, ops, err := application.addUnitOps(unitName, AddUnitParams{}, nil) return ops, "", err } else if err != nil { return nil, "", err } else if lDoc.Life != Alive { return nil, "", ErrCannotEnterScopeYet } return []txn.Op{{ C: unitsC, Id: lDoc.Id, Assert: isAliveDoc, }}, lDoc.Id, nil }
go
func (ru *RelationUnit) subordinateOps() ([]txn.Op, string, error) { units, closer := ru.st.db().GetCollection(unitsC) defer closer() if !ru.isPrincipal || ru.endpoint.Scope != charm.ScopeContainer { return nil, "", nil } related, err := ru.relation.RelatedEndpoints(ru.endpoint.ApplicationName) if err != nil { return nil, "", err } if len(related) != 1 { return nil, "", fmt.Errorf("expected single related endpoint, got %v", related) } applicationname, unitName := related[0].ApplicationName, ru.unitName selSubordinate := bson.D{{"application", applicationname}, {"principal", unitName}} var lDoc lifeDoc if err := units.Find(selSubordinate).One(&lDoc); err == mgo.ErrNotFound { application, err := ru.st.Application(applicationname) if err != nil { return nil, "", err } _, ops, err := application.addUnitOps(unitName, AddUnitParams{}, nil) return ops, "", err } else if err != nil { return nil, "", err } else if lDoc.Life != Alive { return nil, "", ErrCannotEnterScopeYet } return []txn.Op{{ C: unitsC, Id: lDoc.Id, Assert: isAliveDoc, }}, lDoc.Id, nil }
[ "func", "(", "ru", "*", "RelationUnit", ")", "subordinateOps", "(", ")", "(", "[", "]", "txn", ".", "Op", ",", "string", ",", "error", ")", "{", "units", ",", "closer", ":=", "ru", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "unitsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "if", "!", "ru", ".", "isPrincipal", "||", "ru", ".", "endpoint", ".", "Scope", "!=", "charm", ".", "ScopeContainer", "{", "return", "nil", ",", "\"", "\"", ",", "nil", "\n", "}", "\n", "related", ",", "err", ":=", "ru", ".", "relation", ".", "RelatedEndpoints", "(", "ru", ".", "endpoint", ".", "ApplicationName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "len", "(", "related", ")", "!=", "1", "{", "return", "nil", ",", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "related", ")", "\n", "}", "\n", "applicationname", ",", "unitName", ":=", "related", "[", "0", "]", ".", "ApplicationName", ",", "ru", ".", "unitName", "\n", "selSubordinate", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "applicationname", "}", ",", "{", "\"", "\"", ",", "unitName", "}", "}", "\n", "var", "lDoc", "lifeDoc", "\n", "if", "err", ":=", "units", ".", "Find", "(", "selSubordinate", ")", ".", "One", "(", "&", "lDoc", ")", ";", "err", "==", "mgo", ".", "ErrNotFound", "{", "application", ",", "err", ":=", "ru", ".", "st", ".", "Application", "(", "applicationname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "_", ",", "ops", ",", "err", ":=", "application", ".", "addUnitOps", "(", "unitName", ",", "AddUnitParams", "{", "}", ",", "nil", ")", "\n", "return", "ops", ",", "\"", "\"", ",", "err", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "else", "if", "lDoc", ".", "Life", "!=", "Alive", "{", "return", "nil", ",", "\"", "\"", ",", "ErrCannotEnterScopeYet", "\n", "}", "\n", "return", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "unitsC", ",", "Id", ":", "lDoc", ".", "Id", ",", "Assert", ":", "isAliveDoc", ",", "}", "}", ",", "lDoc", ".", "Id", ",", "nil", "\n", "}" ]
// subordinateOps returns any txn operations necessary to ensure sane // subordinate state when entering scope. If a required subordinate unit // exists and is Alive, its name will be returned as well; if one exists // but is not Alive, ErrCannotEnterScopeYet is returned.
[ "subordinateOps", "returns", "any", "txn", "operations", "necessary", "to", "ensure", "sane", "subordinate", "state", "when", "entering", "scope", ".", "If", "a", "required", "subordinate", "unit", "exists", "and", "is", "Alive", "its", "name", "will", "be", "returned", "as", "well", ";", "if", "one", "exists", "but", "is", "not", "Alive", "ErrCannotEnterScopeYet", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relationunit.go#L217-L251
157,783
juju/juju
state/relationunit.go
LeaveScopeOperation
func (ru *RelationUnit) LeaveScopeOperation(force bool) *LeaveScopeOperation { return &LeaveScopeOperation{ ru: &RelationUnit{ st: ru.st, relation: ru.relation, unitName: ru.unitName, isPrincipal: ru.isPrincipal, endpoint: ru.endpoint, scope: ru.scope, isLocalUnit: ru.isLocalUnit, }, ForcedOperation: ForcedOperation{Force: force}, } }
go
func (ru *RelationUnit) LeaveScopeOperation(force bool) *LeaveScopeOperation { return &LeaveScopeOperation{ ru: &RelationUnit{ st: ru.st, relation: ru.relation, unitName: ru.unitName, isPrincipal: ru.isPrincipal, endpoint: ru.endpoint, scope: ru.scope, isLocalUnit: ru.isLocalUnit, }, ForcedOperation: ForcedOperation{Force: force}, } }
[ "func", "(", "ru", "*", "RelationUnit", ")", "LeaveScopeOperation", "(", "force", "bool", ")", "*", "LeaveScopeOperation", "{", "return", "&", "LeaveScopeOperation", "{", "ru", ":", "&", "RelationUnit", "{", "st", ":", "ru", ".", "st", ",", "relation", ":", "ru", ".", "relation", ",", "unitName", ":", "ru", ".", "unitName", ",", "isPrincipal", ":", "ru", ".", "isPrincipal", ",", "endpoint", ":", "ru", ".", "endpoint", ",", "scope", ":", "ru", ".", "scope", ",", "isLocalUnit", ":", "ru", ".", "isLocalUnit", ",", "}", ",", "ForcedOperation", ":", "ForcedOperation", "{", "Force", ":", "force", "}", ",", "}", "\n", "}" ]
// LeaveScopeOperation returns a model operation that will allow relation to leave scope.
[ "LeaveScopeOperation", "returns", "a", "model", "operation", "that", "will", "allow", "relation", "to", "leave", "scope", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relationunit.go#L275-L288
157,784
juju/juju
state/relationunit.go
leaveScopeForcedOps
func (ru *RelationUnit) leaveScopeForcedOps(existingOperation *ForcedOperation) ([]txn.Op, error) { // It does not matter that we are say false to force here- we'll overwrite the whole ForcedOperation. leaveScopeOperation := ru.LeaveScopeOperation(false) leaveScopeOperation.ForcedOperation = *existingOperation return leaveScopeOperation.internalLeaveScope() }
go
func (ru *RelationUnit) leaveScopeForcedOps(existingOperation *ForcedOperation) ([]txn.Op, error) { // It does not matter that we are say false to force here- we'll overwrite the whole ForcedOperation. leaveScopeOperation := ru.LeaveScopeOperation(false) leaveScopeOperation.ForcedOperation = *existingOperation return leaveScopeOperation.internalLeaveScope() }
[ "func", "(", "ru", "*", "RelationUnit", ")", "leaveScopeForcedOps", "(", "existingOperation", "*", "ForcedOperation", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "// It does not matter that we are say false to force here- we'll overwrite the whole ForcedOperation.", "leaveScopeOperation", ":=", "ru", ".", "LeaveScopeOperation", "(", "false", ")", "\n", "leaveScopeOperation", ".", "ForcedOperation", "=", "*", "existingOperation", "\n", "return", "leaveScopeOperation", ".", "internalLeaveScope", "(", ")", "\n", "}" ]
// leaveScopeForcedOps is an internal method used by other state objects when they just want // to get database operations that are involved in leaving scop without // the actual immeiate act of leaving scope.
[ "leaveScopeForcedOps", "is", "an", "internal", "method", "used", "by", "other", "state", "objects", "when", "they", "just", "want", "to", "get", "database", "operations", "that", "are", "involved", "in", "leaving", "scop", "without", "the", "actual", "immeiate", "act", "of", "leaving", "scope", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relationunit.go#L365-L370
157,785
juju/juju
state/relationunit.go
internalLeaveScope
func (op *LeaveScopeOperation) internalLeaveScope() ([]txn.Op, error) { relationScopes, closer := op.ru.st.db().GetCollection(relationScopesC) defer closer() key := op.ru.key() // The logic below is involved because we remove a dying relation // with the last unit that leaves a scope in it. It handles three // possible cases: // // 1. Relation is alive: just leave the scope. // // 2. Relation is dying, and other units remain: just leave the scope. // // 3. Relation is dying, and this is the last unit: leave the scope // and remove the relation. // // In each of those cases, proper assertions are done to guarantee // that the condition observed is still valid when the transaction is // applied. If an abort happens, it observes the new condition and // retries. In theory, a worst case will try at most all of the // conditions once, because units cannot join a scope once its relation // is dying. // // Keep in mind that in the first iteration of the loop it's possible // to have a Dying relation with a smaller-than-real unit count, because // Destroy changes the Life attribute in memory (units could join before // the database is actually changed). logger.Debugf("%v leaving scope", op.Description()) count, err := relationScopes.FindId(key).Count() if err != nil { err := fmt.Errorf("cannot examine scope for %s: %v", op.Description(), err) if !op.Force { return nil, err } op.AddError(err) } else if count == 0 { return nil, jujutxn.ErrNoOperations } ops := []txn.Op{{ C: relationScopesC, Id: key, Assert: txn.DocExists, Remove: true, }} if op.ru.relation.doc.Life == Alive { ops = append(ops, txn.Op{ C: relationsC, Id: op.ru.relation.doc.DocID, Assert: bson.D{{"life", Alive}}, Update: bson.D{{"$inc", bson.D{{"unitcount", -1}}}}, }) } else if op.ru.relation.doc.UnitCount > 1 { ops = append(ops, txn.Op{ C: relationsC, Id: op.ru.relation.doc.DocID, Assert: bson.D{{"unitcount", bson.D{{"$gt", 1}}}}, Update: bson.D{{"$inc", bson.D{{"unitcount", -1}}}}, }) } else { // When 'force' is set, this call will return needed operations // and accumulate all operational errors encountered in the operation. // If the 'force' is not set, any error will be fatal and no operations will be returned. relOps, err := op.ru.relation.removeOps("", op.ru.unitName, &op.ForcedOperation) if err != nil { if !op.Force { return nil, err } op.AddError(err) } ops = append(ops, relOps...) } return ops, nil }
go
func (op *LeaveScopeOperation) internalLeaveScope() ([]txn.Op, error) { relationScopes, closer := op.ru.st.db().GetCollection(relationScopesC) defer closer() key := op.ru.key() // The logic below is involved because we remove a dying relation // with the last unit that leaves a scope in it. It handles three // possible cases: // // 1. Relation is alive: just leave the scope. // // 2. Relation is dying, and other units remain: just leave the scope. // // 3. Relation is dying, and this is the last unit: leave the scope // and remove the relation. // // In each of those cases, proper assertions are done to guarantee // that the condition observed is still valid when the transaction is // applied. If an abort happens, it observes the new condition and // retries. In theory, a worst case will try at most all of the // conditions once, because units cannot join a scope once its relation // is dying. // // Keep in mind that in the first iteration of the loop it's possible // to have a Dying relation with a smaller-than-real unit count, because // Destroy changes the Life attribute in memory (units could join before // the database is actually changed). logger.Debugf("%v leaving scope", op.Description()) count, err := relationScopes.FindId(key).Count() if err != nil { err := fmt.Errorf("cannot examine scope for %s: %v", op.Description(), err) if !op.Force { return nil, err } op.AddError(err) } else if count == 0 { return nil, jujutxn.ErrNoOperations } ops := []txn.Op{{ C: relationScopesC, Id: key, Assert: txn.DocExists, Remove: true, }} if op.ru.relation.doc.Life == Alive { ops = append(ops, txn.Op{ C: relationsC, Id: op.ru.relation.doc.DocID, Assert: bson.D{{"life", Alive}}, Update: bson.D{{"$inc", bson.D{{"unitcount", -1}}}}, }) } else if op.ru.relation.doc.UnitCount > 1 { ops = append(ops, txn.Op{ C: relationsC, Id: op.ru.relation.doc.DocID, Assert: bson.D{{"unitcount", bson.D{{"$gt", 1}}}}, Update: bson.D{{"$inc", bson.D{{"unitcount", -1}}}}, }) } else { // When 'force' is set, this call will return needed operations // and accumulate all operational errors encountered in the operation. // If the 'force' is not set, any error will be fatal and no operations will be returned. relOps, err := op.ru.relation.removeOps("", op.ru.unitName, &op.ForcedOperation) if err != nil { if !op.Force { return nil, err } op.AddError(err) } ops = append(ops, relOps...) } return ops, nil }
[ "func", "(", "op", "*", "LeaveScopeOperation", ")", "internalLeaveScope", "(", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "relationScopes", ",", "closer", ":=", "op", ".", "ru", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "relationScopesC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "key", ":=", "op", ".", "ru", ".", "key", "(", ")", "\n", "// The logic below is involved because we remove a dying relation", "// with the last unit that leaves a scope in it. It handles three", "// possible cases:", "//", "// 1. Relation is alive: just leave the scope.", "//", "// 2. Relation is dying, and other units remain: just leave the scope.", "//", "// 3. Relation is dying, and this is the last unit: leave the scope", "// and remove the relation.", "//", "// In each of those cases, proper assertions are done to guarantee", "// that the condition observed is still valid when the transaction is", "// applied. If an abort happens, it observes the new condition and", "// retries. In theory, a worst case will try at most all of the", "// conditions once, because units cannot join a scope once its relation", "// is dying.", "//", "// Keep in mind that in the first iteration of the loop it's possible", "// to have a Dying relation with a smaller-than-real unit count, because", "// Destroy changes the Life attribute in memory (units could join before", "// the database is actually changed).", "logger", ".", "Debugf", "(", "\"", "\"", ",", "op", ".", "Description", "(", ")", ")", "\n", "count", ",", "err", ":=", "relationScopes", ".", "FindId", "(", "key", ")", ".", "Count", "(", ")", "\n", "if", "err", "!=", "nil", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "op", ".", "Description", "(", ")", ",", "err", ")", "\n", "if", "!", "op", ".", "Force", "{", "return", "nil", ",", "err", "\n", "}", "\n", "op", ".", "AddError", "(", "err", ")", "\n", "}", "else", "if", "count", "==", "0", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "\n", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "relationScopesC", ",", "Id", ":", "key", ",", "Assert", ":", "txn", ".", "DocExists", ",", "Remove", ":", "true", ",", "}", "}", "\n", "if", "op", ".", "ru", ".", "relation", ".", "doc", ".", "Life", "==", "Alive", "{", "ops", "=", "append", "(", "ops", ",", "txn", ".", "Op", "{", "C", ":", "relationsC", ",", "Id", ":", "op", ".", "ru", ".", "relation", ".", "doc", ".", "DocID", ",", "Assert", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "Alive", "}", "}", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "-", "1", "}", "}", "}", "}", ",", "}", ")", "\n", "}", "else", "if", "op", ".", "ru", ".", "relation", ".", "doc", ".", "UnitCount", ">", "1", "{", "ops", "=", "append", "(", "ops", ",", "txn", ".", "Op", "{", "C", ":", "relationsC", ",", "Id", ":", "op", ".", "ru", ".", "relation", ".", "doc", ".", "DocID", ",", "Assert", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "1", "}", "}", "}", "}", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "-", "1", "}", "}", "}", "}", ",", "}", ")", "\n", "}", "else", "{", "// When 'force' is set, this call will return needed operations", "// and accumulate all operational errors encountered in the operation.", "// If the 'force' is not set, any error will be fatal and no operations will be returned.", "relOps", ",", "err", ":=", "op", ".", "ru", ".", "relation", ".", "removeOps", "(", "\"", "\"", ",", "op", ".", "ru", ".", "unitName", ",", "&", "op", ".", "ForcedOperation", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "op", ".", "Force", "{", "return", "nil", ",", "err", "\n", "}", "\n", "op", ".", "AddError", "(", "err", ")", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "relOps", "...", ")", "\n", "}", "\n", "return", "ops", ",", "nil", "\n", "}" ]
// When 'force' is set, this call will return needed operations // and will accumulate all operational errors encountered in the operation. // If the 'force' is not set, any error will be fatal and no operations will be applied.
[ "When", "force", "is", "set", "this", "call", "will", "return", "needed", "operations", "and", "will", "accumulate", "all", "operational", "errors", "encountered", "in", "the", "operation", ".", "If", "the", "force", "is", "not", "set", "any", "error", "will", "be", "fatal", "and", "no", "operations", "will", "be", "applied", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relationunit.go#L375-L447
157,786
juju/juju
state/relationunit.go
Joined
func (ru *RelationUnit) Joined() (bool, error) { return ru.inScope(bson.D{{"departing", bson.D{{"$ne", true}}}}) }
go
func (ru *RelationUnit) Joined() (bool, error) { return ru.inScope(bson.D{{"departing", bson.D{{"$ne", true}}}}) }
[ "func", "(", "ru", "*", "RelationUnit", ")", "Joined", "(", ")", "(", "bool", ",", "error", ")", "{", "return", "ru", ".", "inScope", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "true", "}", "}", "}", "}", ")", "\n", "}" ]
// Joined returns whether the relation unit has entered scope and neither left // it nor prepared to leave it.
[ "Joined", "returns", "whether", "the", "relation", "unit", "has", "entered", "scope", "and", "neither", "left", "it", "nor", "prepared", "to", "leave", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relationunit.go#L512-L514
157,787
juju/juju
state/relationunit.go
inScope
func (ru *RelationUnit) inScope(sel bson.D) (bool, error) { relationScopes, closer := ru.st.db().GetCollection(relationScopesC) defer closer() sel = append(sel, bson.D{{"_id", ru.key()}}...) count, err := relationScopes.Find(sel).Count() if err != nil { return false, err } return count > 0, nil }
go
func (ru *RelationUnit) inScope(sel bson.D) (bool, error) { relationScopes, closer := ru.st.db().GetCollection(relationScopesC) defer closer() sel = append(sel, bson.D{{"_id", ru.key()}}...) count, err := relationScopes.Find(sel).Count() if err != nil { return false, err } return count > 0, nil }
[ "func", "(", "ru", "*", "RelationUnit", ")", "inScope", "(", "sel", "bson", ".", "D", ")", "(", "bool", ",", "error", ")", "{", "relationScopes", ",", "closer", ":=", "ru", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "relationScopesC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "sel", "=", "append", "(", "sel", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "ru", ".", "key", "(", ")", "}", "}", "...", ")", "\n", "count", ",", "err", ":=", "relationScopes", ".", "Find", "(", "sel", ")", ".", "Count", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "count", ">", "0", ",", "nil", "\n", "}" ]
// inScope returns whether a scope document exists satisfying the supplied // selector.
[ "inScope", "returns", "whether", "a", "scope", "document", "exists", "satisfying", "the", "supplied", "selector", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relationunit.go#L518-L528
157,788
juju/juju
state/relationunit.go
WatchScope
func (ru *RelationUnit) WatchScope() *RelationScopeWatcher { role := counterpartRole(ru.endpoint.Role) return watchRelationScope(ru.st, ru.scope, role, ru.unitName) }
go
func (ru *RelationUnit) WatchScope() *RelationScopeWatcher { role := counterpartRole(ru.endpoint.Role) return watchRelationScope(ru.st, ru.scope, role, ru.unitName) }
[ "func", "(", "ru", "*", "RelationUnit", ")", "WatchScope", "(", ")", "*", "RelationScopeWatcher", "{", "role", ":=", "counterpartRole", "(", "ru", ".", "endpoint", ".", "Role", ")", "\n", "return", "watchRelationScope", "(", "ru", ".", "st", ",", "ru", ".", "scope", ",", "role", ",", "ru", ".", "unitName", ")", "\n", "}" ]
// WatchScope returns a watcher which notifies of counterpart units // entering and leaving the unit's scope.
[ "WatchScope", "returns", "a", "watcher", "which", "notifies", "of", "counterpart", "units", "entering", "and", "leaving", "the", "unit", "s", "scope", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relationunit.go#L532-L535
157,789
juju/juju
state/relationunit.go
unitKey
func (ru *RelationUnit) unitKey(uname string) (string, error) { uparts := strings.Split(uname, "/") sname := uparts[0] ep, err := ru.relation.Endpoint(sname) if err != nil { return "", err } return ru._key(string(ep.Role), uname), nil }
go
func (ru *RelationUnit) unitKey(uname string) (string, error) { uparts := strings.Split(uname, "/") sname := uparts[0] ep, err := ru.relation.Endpoint(sname) if err != nil { return "", err } return ru._key(string(ep.Role), uname), nil }
[ "func", "(", "ru", "*", "RelationUnit", ")", "unitKey", "(", "uname", "string", ")", "(", "string", ",", "error", ")", "{", "uparts", ":=", "strings", ".", "Split", "(", "uname", ",", "\"", "\"", ")", "\n", "sname", ":=", "uparts", "[", "0", "]", "\n", "ep", ",", "err", ":=", "ru", ".", "relation", ".", "Endpoint", "(", "sname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "ru", ".", "_key", "(", "string", "(", "ep", ".", "Role", ")", ",", "uname", ")", ",", "nil", "\n", "}" ]
// unitKey returns a string, based on the relation and the supplied unit name, // which is used as a key for that unit within this relation in the settings, // presence, and relationScopes collections.
[ "unitKey", "returns", "a", "string", "based", "on", "the", "relation", "and", "the", "supplied", "unit", "name", "which", "is", "used", "as", "a", "key", "for", "that", "unit", "within", "this", "relation", "in", "the", "settings", "presence", "and", "relationScopes", "collections", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relationunit.go#L696-L704
157,790
juju/juju
state/relationunit.go
key
func (ru *RelationUnit) key() string { return ru._key(string(ru.endpoint.Role), ru.unitName) }
go
func (ru *RelationUnit) key() string { return ru._key(string(ru.endpoint.Role), ru.unitName) }
[ "func", "(", "ru", "*", "RelationUnit", ")", "key", "(", ")", "string", "{", "return", "ru", ".", "_key", "(", "string", "(", "ru", ".", "endpoint", ".", "Role", ")", ",", "ru", ".", "unitName", ")", "\n", "}" ]
// key returns a string, based on the relation and the current unit name, // which is used as a key for that unit within this relation in the settings, // presence, and relationScopes collections.
[ "key", "returns", "a", "string", "based", "on", "the", "relation", "and", "the", "current", "unit", "name", "which", "is", "used", "as", "a", "key", "for", "that", "unit", "within", "this", "relation", "in", "the", "settings", "presence", "and", "relationScopes", "collections", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relationunit.go#L709-L711
157,791
juju/juju
worker/uniter/paths.go
ComponentDir
func (paths Paths) ComponentDir(name string) string { return filepath.Join(paths.State.BaseDir, name) }
go
func (paths Paths) ComponentDir(name string) string { return filepath.Join(paths.State.BaseDir, name) }
[ "func", "(", "paths", "Paths", ")", "ComponentDir", "(", "name", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "paths", ".", "State", ".", "BaseDir", ",", "name", ")", "\n", "}" ]
// ComponentDir returns the filesystem path to the directory // containing all data files for a component.
[ "ComponentDir", "returns", "the", "filesystem", "path", "to", "the", "directory", "containing", "all", "data", "files", "for", "a", "component", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/paths.go#L58-L60
157,792
juju/juju
worker/uniter/paths.go
NewWorkerPaths
func NewWorkerPaths(dataDir string, unitTag names.UnitTag, worker string) Paths { join := filepath.Join baseDir := join(dataDir, "agents", unitTag.String()) stateDir := join(baseDir, "state") socket := func(name string, abstract bool) string { if os.HostOS() == os.Windows { base := fmt.Sprintf("%s", unitTag) if worker != "" { base = fmt.Sprintf("%s-%s", unitTag, worker) } return fmt.Sprintf(`\\.\pipe\%s-%s`, base, name) } path := join(baseDir, name+".socket") if worker != "" { path = join(baseDir, fmt.Sprintf("%s-%s.socket", worker, name)) } if abstract { path = "@" + path } return path } toolsDir := tools.ToolsDir(dataDir, unitTag.String()) return Paths{ ToolsDir: filepath.FromSlash(toolsDir), Runtime: RuntimePaths{ JujuRunSocket: socket("run", false), JujucServerSocket: socket("agent", true), }, State: StatePaths{ BaseDir: baseDir, CharmDir: join(baseDir, "charm"), OperationsFile: join(stateDir, "uniter"), RelationsDir: join(stateDir, "relations"), BundlesDir: join(stateDir, "bundles"), DeployerDir: join(stateDir, "deployer"), StorageDir: join(stateDir, "storage"), MetricsSpoolDir: join(stateDir, "spool", "metrics"), }, } }
go
func NewWorkerPaths(dataDir string, unitTag names.UnitTag, worker string) Paths { join := filepath.Join baseDir := join(dataDir, "agents", unitTag.String()) stateDir := join(baseDir, "state") socket := func(name string, abstract bool) string { if os.HostOS() == os.Windows { base := fmt.Sprintf("%s", unitTag) if worker != "" { base = fmt.Sprintf("%s-%s", unitTag, worker) } return fmt.Sprintf(`\\.\pipe\%s-%s`, base, name) } path := join(baseDir, name+".socket") if worker != "" { path = join(baseDir, fmt.Sprintf("%s-%s.socket", worker, name)) } if abstract { path = "@" + path } return path } toolsDir := tools.ToolsDir(dataDir, unitTag.String()) return Paths{ ToolsDir: filepath.FromSlash(toolsDir), Runtime: RuntimePaths{ JujuRunSocket: socket("run", false), JujucServerSocket: socket("agent", true), }, State: StatePaths{ BaseDir: baseDir, CharmDir: join(baseDir, "charm"), OperationsFile: join(stateDir, "uniter"), RelationsDir: join(stateDir, "relations"), BundlesDir: join(stateDir, "bundles"), DeployerDir: join(stateDir, "deployer"), StorageDir: join(stateDir, "storage"), MetricsSpoolDir: join(stateDir, "spool", "metrics"), }, } }
[ "func", "NewWorkerPaths", "(", "dataDir", "string", ",", "unitTag", "names", ".", "UnitTag", ",", "worker", "string", ")", "Paths", "{", "join", ":=", "filepath", ".", "Join", "\n", "baseDir", ":=", "join", "(", "dataDir", ",", "\"", "\"", ",", "unitTag", ".", "String", "(", ")", ")", "\n", "stateDir", ":=", "join", "(", "baseDir", ",", "\"", "\"", ")", "\n\n", "socket", ":=", "func", "(", "name", "string", ",", "abstract", "bool", ")", "string", "{", "if", "os", ".", "HostOS", "(", ")", "==", "os", ".", "Windows", "{", "base", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "unitTag", ")", "\n", "if", "worker", "!=", "\"", "\"", "{", "base", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "unitTag", ",", "worker", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "`\\\\.\\pipe\\%s-%s`", ",", "base", ",", "name", ")", "\n", "}", "\n", "path", ":=", "join", "(", "baseDir", ",", "name", "+", "\"", "\"", ")", "\n", "if", "worker", "!=", "\"", "\"", "{", "path", "=", "join", "(", "baseDir", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "worker", ",", "name", ")", ")", "\n", "}", "\n", "if", "abstract", "{", "path", "=", "\"", "\"", "+", "path", "\n", "}", "\n", "return", "path", "\n", "}", "\n\n", "toolsDir", ":=", "tools", ".", "ToolsDir", "(", "dataDir", ",", "unitTag", ".", "String", "(", ")", ")", "\n", "return", "Paths", "{", "ToolsDir", ":", "filepath", ".", "FromSlash", "(", "toolsDir", ")", ",", "Runtime", ":", "RuntimePaths", "{", "JujuRunSocket", ":", "socket", "(", "\"", "\"", ",", "false", ")", ",", "JujucServerSocket", ":", "socket", "(", "\"", "\"", ",", "true", ")", ",", "}", ",", "State", ":", "StatePaths", "{", "BaseDir", ":", "baseDir", ",", "CharmDir", ":", "join", "(", "baseDir", ",", "\"", "\"", ")", ",", "OperationsFile", ":", "join", "(", "stateDir", ",", "\"", "\"", ")", ",", "RelationsDir", ":", "join", "(", "stateDir", ",", "\"", "\"", ")", ",", "BundlesDir", ":", "join", "(", "stateDir", ",", "\"", "\"", ")", ",", "DeployerDir", ":", "join", "(", "stateDir", ",", "\"", "\"", ")", ",", "StorageDir", ":", "join", "(", "stateDir", ",", "\"", "\"", ")", ",", "MetricsSpoolDir", ":", "join", "(", "stateDir", ",", "\"", "\"", ",", "\"", "\"", ")", ",", "}", ",", "}", "\n", "}" ]
// NewWorkerPaths returns the set of filesystem paths that the supplied unit worker should // use, given the supplied root juju data directory path and worker identifier. // Distinct worker identifiers ensure that runtime paths of different worker do not interfere.
[ "NewWorkerPaths", "returns", "the", "set", "of", "filesystem", "paths", "that", "the", "supplied", "unit", "worker", "should", "use", "given", "the", "supplied", "root", "juju", "data", "directory", "path", "and", "worker", "identifier", ".", "Distinct", "worker", "identifiers", "ensure", "that", "runtime", "paths", "of", "different", "worker", "do", "not", "interfere", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/paths.go#L117-L158
157,793
juju/juju
api/meterstatus/client.go
NewClient
func NewClient(caller base.APICaller, tag names.UnitTag) MeterStatusClient { return &Client{ facade: base.NewFacadeCaller(caller, "MeterStatus"), tag: tag, } }
go
func NewClient(caller base.APICaller, tag names.UnitTag) MeterStatusClient { return &Client{ facade: base.NewFacadeCaller(caller, "MeterStatus"), tag: tag, } }
[ "func", "NewClient", "(", "caller", "base", ".", "APICaller", ",", "tag", "names", ".", "UnitTag", ")", "MeterStatusClient", "{", "return", "&", "Client", "{", "facade", ":", "base", ".", "NewFacadeCaller", "(", "caller", ",", "\"", "\"", ")", ",", "tag", ":", "tag", ",", "}", "\n", "}" ]
// NewClient creates a new client for accessing the MeterStatus API.
[ "NewClient", "creates", "a", "new", "client", "for", "accessing", "the", "MeterStatus", "API", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/meterstatus/client.go#L29-L34
157,794
juju/juju
api/meterstatus/client.go
MeterStatus
func (c *Client) MeterStatus() (statusCode, statusInfo string, rErr error) { var results params.MeterStatusResults args := params.Entities{ Entities: []params.Entity{{Tag: c.tag.String()}}, } err := c.facade.FacadeCall("GetMeterStatus", args, &results) if err != nil { return "", "", errors.Trace(err) } if len(results.Results) != 1 { return "", "", errors.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return "", "", errors.Trace(result.Error) } return result.Code, result.Info, nil }
go
func (c *Client) MeterStatus() (statusCode, statusInfo string, rErr error) { var results params.MeterStatusResults args := params.Entities{ Entities: []params.Entity{{Tag: c.tag.String()}}, } err := c.facade.FacadeCall("GetMeterStatus", args, &results) if err != nil { return "", "", errors.Trace(err) } if len(results.Results) != 1 { return "", "", errors.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return "", "", errors.Trace(result.Error) } return result.Code, result.Info, nil }
[ "func", "(", "c", "*", "Client", ")", "MeterStatus", "(", ")", "(", "statusCode", ",", "statusInfo", "string", ",", "rErr", "error", ")", "{", "var", "results", "params", ".", "MeterStatusResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "Tag", ":", "c", ".", "tag", ".", "String", "(", ")", "}", "}", ",", "}", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errors", ".", "Trace", "(", "result", ".", "Error", ")", "\n", "}", "\n", "return", "result", ".", "Code", ",", "result", ".", "Info", ",", "nil", "\n", "}" ]
// MeterStatus is part of the MeterStatusClient interface.
[ "MeterStatus", "is", "part", "of", "the", "MeterStatusClient", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/meterstatus/client.go#L45-L62
157,795
juju/juju
apiserver/facades/client/cloud/backend.go
Get
func (s statePoolShim) Get(modelUUID string) (PooledModelBackend, error) { m, err := s.StatePool.Get(modelUUID) return NewPooledModelBackend(m), err }
go
func (s statePoolShim) Get(modelUUID string) (PooledModelBackend, error) { m, err := s.StatePool.Get(modelUUID) return NewPooledModelBackend(m), err }
[ "func", "(", "s", "statePoolShim", ")", "Get", "(", "modelUUID", "string", ")", "(", "PooledModelBackend", ",", "error", ")", "{", "m", ",", "err", ":=", "s", ".", "StatePool", ".", "Get", "(", "modelUUID", ")", "\n", "return", "NewPooledModelBackend", "(", "m", ")", ",", "err", "\n", "}" ]
// Get implements ModelPoolBackend.Get.
[ "Get", "implements", "ModelPoolBackend", ".", "Get", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/backend.go#L98-L101
157,796
juju/juju
apiserver/facades/client/cloud/backend.go
Model
func (s modelShim) Model() credentialcommon.PersistentBackend { return credentialcommon.NewPersistentBackend(s.PooledState.State) }
go
func (s modelShim) Model() credentialcommon.PersistentBackend { return credentialcommon.NewPersistentBackend(s.PooledState.State) }
[ "func", "(", "s", "modelShim", ")", "Model", "(", ")", "credentialcommon", ".", "PersistentBackend", "{", "return", "credentialcommon", ".", "NewPersistentBackend", "(", "s", ".", "PooledState", ".", "State", ")", "\n", "}" ]
// Model implements PooledModelBackend.Model.
[ "Model", "implements", "PooledModelBackend", ".", "Model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/backend.go#L121-L123
157,797
juju/juju
apiserver/params/http.go
EncodeChecksum
func EncodeChecksum(checksum string) string { return fmt.Sprintf("%s=%s", DigestSHA256, base64.StdEncoding.EncodeToString([]byte(checksum))) }
go
func EncodeChecksum(checksum string) string { return fmt.Sprintf("%s=%s", DigestSHA256, base64.StdEncoding.EncodeToString([]byte(checksum))) }
[ "func", "EncodeChecksum", "(", "checksum", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "DigestSHA256", ",", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "[", "]", "byte", "(", "checksum", ")", ")", ")", "\n", "}" ]
// EncodeChecksum base64 encodes a sha256 checksum according to RFC 4648 and // returns a value that can be added to the "Digest" http header.
[ "EncodeChecksum", "base64", "encodes", "a", "sha256", "checksum", "according", "to", "RFC", "4648", "and", "returns", "a", "value", "that", "can", "be", "added", "to", "the", "Digest", "http", "header", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/http.go#L36-L38
157,798
juju/juju
api/base/caller.go
NewFacadeCaller
func NewFacadeCaller(caller APICaller, facadeName string) FacadeCaller { return NewFacadeCallerForVersion(caller, facadeName, caller.BestFacadeVersion(facadeName)) }
go
func NewFacadeCaller(caller APICaller, facadeName string) FacadeCaller { return NewFacadeCallerForVersion(caller, facadeName, caller.BestFacadeVersion(facadeName)) }
[ "func", "NewFacadeCaller", "(", "caller", "APICaller", ",", "facadeName", "string", ")", "FacadeCaller", "{", "return", "NewFacadeCallerForVersion", "(", "caller", ",", "facadeName", ",", "caller", ".", "BestFacadeVersion", "(", "facadeName", ")", ")", "\n", "}" ]
// NewFacadeCaller wraps an APICaller for a given facade name and the // best available version.
[ "NewFacadeCaller", "wraps", "an", "APICaller", "for", "a", "given", "facade", "name", "and", "the", "best", "available", "version", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/base/caller.go#L155-L157
157,799
juju/juju
api/base/caller.go
NewFacadeCallerForVersion
func NewFacadeCallerForVersion(caller APICaller, facadeName string, version int) FacadeCaller { return facadeCaller{ facadeName: facadeName, bestVersion: version, caller: caller, } }
go
func NewFacadeCallerForVersion(caller APICaller, facadeName string, version int) FacadeCaller { return facadeCaller{ facadeName: facadeName, bestVersion: version, caller: caller, } }
[ "func", "NewFacadeCallerForVersion", "(", "caller", "APICaller", ",", "facadeName", "string", ",", "version", "int", ")", "FacadeCaller", "{", "return", "facadeCaller", "{", "facadeName", ":", "facadeName", ",", "bestVersion", ":", "version", ",", "caller", ":", "caller", ",", "}", "\n", "}" ]
// NewFacadeCallerForVersion wraps an APICaller for a given facade // name and version.
[ "NewFacadeCallerForVersion", "wraps", "an", "APICaller", "for", "a", "given", "facade", "name", "and", "version", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/base/caller.go#L161-L167