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
|
---|---|---|---|---|---|---|---|---|---|---|---|
154,500 | juju/juju | worker/uniter/relation/relations.go | GetInfo | func (r *relations) GetInfo() map[int]*context.RelationInfo {
relationInfos := map[int]*context.RelationInfo{}
for id, relationer := range r.relationers {
relationInfos[id] = relationer.ContextInfo()
}
return relationInfos
} | go | func (r *relations) GetInfo() map[int]*context.RelationInfo {
relationInfos := map[int]*context.RelationInfo{}
for id, relationer := range r.relationers {
relationInfos[id] = relationer.ContextInfo()
}
return relationInfos
} | [
"func",
"(",
"r",
"*",
"relations",
")",
"GetInfo",
"(",
")",
"map",
"[",
"int",
"]",
"*",
"context",
".",
"RelationInfo",
"{",
"relationInfos",
":=",
"map",
"[",
"int",
"]",
"*",
"context",
".",
"RelationInfo",
"{",
"}",
"\n",
"for",
"id",
",",
"relationer",
":=",
"range",
"r",
".",
"relationers",
"{",
"relationInfos",
"[",
"id",
"]",
"=",
"relationer",
".",
"ContextInfo",
"(",
")",
"\n",
"}",
"\n",
"return",
"relationInfos",
"\n",
"}"
] | // GetInfo is part of the Relations interface. | [
"GetInfo",
"is",
"part",
"of",
"the",
"Relations",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relations.go#L406-L412 |
154,501 | juju/juju | worker/uniter/relation/relations.go | add | func (r *relations) add(rel *uniter.Relation, dir *StateDir) (err error) {
logger.Infof("joining relation %q", rel)
ru, err := rel.Unit(r.unit)
if err != nil {
return errors.Trace(err)
}
relationer := NewRelationer(ru, dir)
unitWatcher, err := r.unit.Watch()
if err != nil {
return errors.Trace(err)
}
defer func() {
if e := worker.Stop(unitWatcher); e != nil {
if err == nil {
err = e
} else {
logger.Errorf("while stopping unit watcher: %v", e)
}
}
}()
for {
select {
case <-r.abort:
// Should this be a different error? e.g. resolver.ErrAborted, that
// Loop translates into ErrLoopAborted?
return resolver.ErrLoopAborted
case _, ok := <-unitWatcher.Changes():
if !ok {
return errors.New("unit watcher closed")
}
err := relationer.Join()
if params.IsCodeCannotEnterScopeYet(err) {
logger.Infof("cannot enter scope for relation %q; waiting for subordinate to be removed", rel)
continue
} else if err != nil {
return errors.Trace(err)
}
logger.Infof("joined relation %q", rel)
// Leaders get to set the relation status.
var isLeader bool
isLeader, err = r.leaderCtx.IsLeader()
if err != nil {
return errors.Trace(err)
}
if isLeader {
err = rel.SetStatus(relation.Joined)
if err != nil {
return errors.Trace(err)
}
}
r.relationers[rel.Id()] = relationer
return nil
}
}
} | go | func (r *relations) add(rel *uniter.Relation, dir *StateDir) (err error) {
logger.Infof("joining relation %q", rel)
ru, err := rel.Unit(r.unit)
if err != nil {
return errors.Trace(err)
}
relationer := NewRelationer(ru, dir)
unitWatcher, err := r.unit.Watch()
if err != nil {
return errors.Trace(err)
}
defer func() {
if e := worker.Stop(unitWatcher); e != nil {
if err == nil {
err = e
} else {
logger.Errorf("while stopping unit watcher: %v", e)
}
}
}()
for {
select {
case <-r.abort:
// Should this be a different error? e.g. resolver.ErrAborted, that
// Loop translates into ErrLoopAborted?
return resolver.ErrLoopAborted
case _, ok := <-unitWatcher.Changes():
if !ok {
return errors.New("unit watcher closed")
}
err := relationer.Join()
if params.IsCodeCannotEnterScopeYet(err) {
logger.Infof("cannot enter scope for relation %q; waiting for subordinate to be removed", rel)
continue
} else if err != nil {
return errors.Trace(err)
}
logger.Infof("joined relation %q", rel)
// Leaders get to set the relation status.
var isLeader bool
isLeader, err = r.leaderCtx.IsLeader()
if err != nil {
return errors.Trace(err)
}
if isLeader {
err = rel.SetStatus(relation.Joined)
if err != nil {
return errors.Trace(err)
}
}
r.relationers[rel.Id()] = relationer
return nil
}
}
} | [
"func",
"(",
"r",
"*",
"relations",
")",
"add",
"(",
"rel",
"*",
"uniter",
".",
"Relation",
",",
"dir",
"*",
"StateDir",
")",
"(",
"err",
"error",
")",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"rel",
")",
"\n",
"ru",
",",
"err",
":=",
"rel",
".",
"Unit",
"(",
"r",
".",
"unit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"relationer",
":=",
"NewRelationer",
"(",
"ru",
",",
"dir",
")",
"\n",
"unitWatcher",
",",
"err",
":=",
"r",
".",
"unit",
".",
"Watch",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"e",
":=",
"worker",
".",
"Stop",
"(",
"unitWatcher",
")",
";",
"e",
"!=",
"nil",
"{",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"e",
"\n",
"}",
"else",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"e",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"r",
".",
"abort",
":",
"// Should this be a different error? e.g. resolver.ErrAborted, that",
"// Loop translates into ErrLoopAborted?",
"return",
"resolver",
".",
"ErrLoopAborted",
"\n",
"case",
"_",
",",
"ok",
":=",
"<-",
"unitWatcher",
".",
"Changes",
"(",
")",
":",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"err",
":=",
"relationer",
".",
"Join",
"(",
")",
"\n",
"if",
"params",
".",
"IsCodeCannotEnterScopeYet",
"(",
"err",
")",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"rel",
")",
"\n",
"continue",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"rel",
")",
"\n",
"// Leaders get to set the relation status.",
"var",
"isLeader",
"bool",
"\n",
"isLeader",
",",
"err",
"=",
"r",
".",
"leaderCtx",
".",
"IsLeader",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"isLeader",
"{",
"err",
"=",
"rel",
".",
"SetStatus",
"(",
"relation",
".",
"Joined",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"r",
".",
"relationers",
"[",
"rel",
".",
"Id",
"(",
")",
"]",
"=",
"relationer",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // add causes the unit agent to join the supplied relation, and to
// store persistent state in the supplied dir. It will block until the
// operation succeeds or fails; or until the abort chan is closed, in
// which case it will return resolver.ErrLoopAborted. | [
"add",
"causes",
"the",
"unit",
"agent",
"to",
"join",
"the",
"supplied",
"relation",
"and",
"to",
"store",
"persistent",
"state",
"in",
"the",
"supplied",
"dir",
".",
"It",
"will",
"block",
"until",
"the",
"operation",
"succeeds",
"or",
"fails",
";",
"or",
"until",
"the",
"abort",
"chan",
"is",
"closed",
"in",
"which",
"case",
"it",
"will",
"return",
"resolver",
".",
"ErrLoopAborted",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relations.go#L494-L548 |
154,502 | juju/juju | worker/uniter/relation/relations.go | setDying | func (r *relations) setDying(id int) error {
relationer, found := r.relationers[id]
if !found {
return nil
}
if err := relationer.SetDying(); err != nil {
return errors.Trace(err)
}
if relationer.IsImplicit() {
delete(r.relationers, id)
}
return nil
} | go | func (r *relations) setDying(id int) error {
relationer, found := r.relationers[id]
if !found {
return nil
}
if err := relationer.SetDying(); err != nil {
return errors.Trace(err)
}
if relationer.IsImplicit() {
delete(r.relationers, id)
}
return nil
} | [
"func",
"(",
"r",
"*",
"relations",
")",
"setDying",
"(",
"id",
"int",
")",
"error",
"{",
"relationer",
",",
"found",
":=",
"r",
".",
"relationers",
"[",
"id",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"relationer",
".",
"SetDying",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"relationer",
".",
"IsImplicit",
"(",
")",
"{",
"delete",
"(",
"r",
".",
"relationers",
",",
"id",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // setDying notifies the relationer identified by the supplied id that the
// only hook executions to be requested should be those necessary to cleanly
// exit the relation. | [
"setDying",
"notifies",
"the",
"relationer",
"identified",
"by",
"the",
"supplied",
"id",
"that",
"the",
"only",
"hook",
"executions",
"to",
"be",
"requested",
"should",
"be",
"those",
"necessary",
"to",
"cleanly",
"exit",
"the",
"relation",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relations.go#L553-L565 |
154,503 | juju/juju | apiserver/common/interfaces.go | AuthAny | func AuthAny(getFuncs ...GetAuthFunc) GetAuthFunc {
return func() (AuthFunc, error) {
funcs := make([]AuthFunc, len(getFuncs))
for i, getFunc := range getFuncs {
f, err := getFunc()
if err != nil {
return nil, errors.Trace(err)
}
funcs[i] = f
}
combined := func(tag names.Tag) bool {
for _, f := range funcs {
if f(tag) {
return true
}
}
return false
}
return combined, nil
}
} | go | func AuthAny(getFuncs ...GetAuthFunc) GetAuthFunc {
return func() (AuthFunc, error) {
funcs := make([]AuthFunc, len(getFuncs))
for i, getFunc := range getFuncs {
f, err := getFunc()
if err != nil {
return nil, errors.Trace(err)
}
funcs[i] = f
}
combined := func(tag names.Tag) bool {
for _, f := range funcs {
if f(tag) {
return true
}
}
return false
}
return combined, nil
}
} | [
"func",
"AuthAny",
"(",
"getFuncs",
"...",
"GetAuthFunc",
")",
"GetAuthFunc",
"{",
"return",
"func",
"(",
")",
"(",
"AuthFunc",
",",
"error",
")",
"{",
"funcs",
":=",
"make",
"(",
"[",
"]",
"AuthFunc",
",",
"len",
"(",
"getFuncs",
")",
")",
"\n",
"for",
"i",
",",
"getFunc",
":=",
"range",
"getFuncs",
"{",
"f",
",",
"err",
":=",
"getFunc",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"funcs",
"[",
"i",
"]",
"=",
"f",
"\n",
"}",
"\n",
"combined",
":=",
"func",
"(",
"tag",
"names",
".",
"Tag",
")",
"bool",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"funcs",
"{",
"if",
"f",
"(",
"tag",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"combined",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // AuthAny returns an AuthFunc generator that returns an AuthFunc that
// accepts any tag authorized by any of its arguments. If no arguments
// are passed this is equivalent to AuthNever. | [
"AuthAny",
"returns",
"an",
"AuthFunc",
"generator",
"that",
"returns",
"an",
"AuthFunc",
"that",
"accepts",
"any",
"tag",
"authorized",
"by",
"any",
"of",
"its",
"arguments",
".",
"If",
"no",
"arguments",
"are",
"passed",
"this",
"is",
"equivalent",
"to",
"AuthNever",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/interfaces.go#L22-L42 |
154,504 | juju/juju | apiserver/common/interfaces.go | AuthAlways | func AuthAlways() GetAuthFunc {
return func() (AuthFunc, error) {
return func(tag names.Tag) bool {
return true
}, nil
}
} | go | func AuthAlways() GetAuthFunc {
return func() (AuthFunc, error) {
return func(tag names.Tag) bool {
return true
}, nil
}
} | [
"func",
"AuthAlways",
"(",
")",
"GetAuthFunc",
"{",
"return",
"func",
"(",
")",
"(",
"AuthFunc",
",",
"error",
")",
"{",
"return",
"func",
"(",
"tag",
"names",
".",
"Tag",
")",
"bool",
"{",
"return",
"true",
"\n",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // AuthAlways returns an authentication function that always returns true iff it is passed a valid tag. | [
"AuthAlways",
"returns",
"an",
"authentication",
"function",
"that",
"always",
"returns",
"true",
"iff",
"it",
"is",
"passed",
"a",
"valid",
"tag",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/interfaces.go#L45-L51 |
154,505 | juju/juju | apiserver/common/interfaces.go | AuthFuncForTag | func AuthFuncForTag(valid names.Tag) GetAuthFunc {
return func() (AuthFunc, error) {
return func(tag names.Tag) bool {
return tag == valid
}, nil
}
} | go | func AuthFuncForTag(valid names.Tag) GetAuthFunc {
return func() (AuthFunc, error) {
return func(tag names.Tag) bool {
return tag == valid
}, nil
}
} | [
"func",
"AuthFuncForTag",
"(",
"valid",
"names",
".",
"Tag",
")",
"GetAuthFunc",
"{",
"return",
"func",
"(",
")",
"(",
"AuthFunc",
",",
"error",
")",
"{",
"return",
"func",
"(",
"tag",
"names",
".",
"Tag",
")",
"bool",
"{",
"return",
"tag",
"==",
"valid",
"\n",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // AuthFuncForTag returns an authentication function that always returns true iff it is passed a specific tag. | [
"AuthFuncForTag",
"returns",
"an",
"authentication",
"function",
"that",
"always",
"returns",
"true",
"iff",
"it",
"is",
"passed",
"a",
"specific",
"tag",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/interfaces.go#L54-L60 |
154,506 | juju/juju | apiserver/common/interfaces.go | AuthFuncForTagKind | func AuthFuncForTagKind(kind string) GetAuthFunc {
return func() (AuthFunc, error) {
if kind == "" {
return nil, errors.Errorf("tag kind cannot be empty")
}
return func(tag names.Tag) bool {
// Allow only the given tag kind.
if tag == nil {
return false
}
return tag.Kind() == kind
}, nil
}
} | go | func AuthFuncForTagKind(kind string) GetAuthFunc {
return func() (AuthFunc, error) {
if kind == "" {
return nil, errors.Errorf("tag kind cannot be empty")
}
return func(tag names.Tag) bool {
// Allow only the given tag kind.
if tag == nil {
return false
}
return tag.Kind() == kind
}, nil
}
} | [
"func",
"AuthFuncForTagKind",
"(",
"kind",
"string",
")",
"GetAuthFunc",
"{",
"return",
"func",
"(",
")",
"(",
"AuthFunc",
",",
"error",
")",
"{",
"if",
"kind",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"func",
"(",
"tag",
"names",
".",
"Tag",
")",
"bool",
"{",
"// Allow only the given tag kind.",
"if",
"tag",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"tag",
".",
"Kind",
"(",
")",
"==",
"kind",
"\n",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // AuthFuncForTagKind returns a GetAuthFunc which creates an AuthFunc
// allowing only the given tag kind and denies all others. Passing an
// empty kind is an error. | [
"AuthFuncForTagKind",
"returns",
"a",
"GetAuthFunc",
"which",
"creates",
"an",
"AuthFunc",
"allowing",
"only",
"the",
"given",
"tag",
"kind",
"and",
"denies",
"all",
"others",
".",
"Passing",
"an",
"empty",
"kind",
"is",
"an",
"error",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/interfaces.go#L65-L78 |
154,507 | juju/juju | apiserver/common/interfaces.go | AuthFuncForMachineAgent | func AuthFuncForMachineAgent(authorizer Authorizer) GetAuthFunc {
return func() (AuthFunc, error) {
isModelManager := authorizer.AuthController()
isMachineAgent := authorizer.AuthMachineAgent()
authEntityTag := authorizer.GetAuthTag()
return func(tag names.Tag) bool {
if isMachineAgent && tag == authEntityTag {
// A machine agent can always access its own machine.
return true
}
switch tag := tag.(type) {
case names.MachineTag:
parentId := state.ParentId(tag.Id())
if parentId == "" {
// All top-level machines are accessible by the controller.
return isModelManager
}
// All containers with the authenticated machine as a
// parent are accessible by it.
// TODO(dfc) sometimes authEntity tag is nil, which is fine because nil is
// only equal to nil, but it suggests someone is passing an authorizer
// with a nil tag.
return isMachineAgent && names.NewMachineTag(parentId) == authEntityTag
default:
return false
}
}, nil
}
} | go | func AuthFuncForMachineAgent(authorizer Authorizer) GetAuthFunc {
return func() (AuthFunc, error) {
isModelManager := authorizer.AuthController()
isMachineAgent := authorizer.AuthMachineAgent()
authEntityTag := authorizer.GetAuthTag()
return func(tag names.Tag) bool {
if isMachineAgent && tag == authEntityTag {
// A machine agent can always access its own machine.
return true
}
switch tag := tag.(type) {
case names.MachineTag:
parentId := state.ParentId(tag.Id())
if parentId == "" {
// All top-level machines are accessible by the controller.
return isModelManager
}
// All containers with the authenticated machine as a
// parent are accessible by it.
// TODO(dfc) sometimes authEntity tag is nil, which is fine because nil is
// only equal to nil, but it suggests someone is passing an authorizer
// with a nil tag.
return isMachineAgent && names.NewMachineTag(parentId) == authEntityTag
default:
return false
}
}, nil
}
} | [
"func",
"AuthFuncForMachineAgent",
"(",
"authorizer",
"Authorizer",
")",
"GetAuthFunc",
"{",
"return",
"func",
"(",
")",
"(",
"AuthFunc",
",",
"error",
")",
"{",
"isModelManager",
":=",
"authorizer",
".",
"AuthController",
"(",
")",
"\n",
"isMachineAgent",
":=",
"authorizer",
".",
"AuthMachineAgent",
"(",
")",
"\n",
"authEntityTag",
":=",
"authorizer",
".",
"GetAuthTag",
"(",
")",
"\n\n",
"return",
"func",
"(",
"tag",
"names",
".",
"Tag",
")",
"bool",
"{",
"if",
"isMachineAgent",
"&&",
"tag",
"==",
"authEntityTag",
"{",
"// A machine agent can always access its own machine.",
"return",
"true",
"\n",
"}",
"\n\n",
"switch",
"tag",
":=",
"tag",
".",
"(",
"type",
")",
"{",
"case",
"names",
".",
"MachineTag",
":",
"parentId",
":=",
"state",
".",
"ParentId",
"(",
"tag",
".",
"Id",
"(",
")",
")",
"\n",
"if",
"parentId",
"==",
"\"",
"\"",
"{",
"// All top-level machines are accessible by the controller.",
"return",
"isModelManager",
"\n",
"}",
"\n",
"// All containers with the authenticated machine as a",
"// parent are accessible by it.",
"// TODO(dfc) sometimes authEntity tag is nil, which is fine because nil is",
"// only equal to nil, but it suggests someone is passing an authorizer",
"// with a nil tag.",
"return",
"isMachineAgent",
"&&",
"names",
".",
"NewMachineTag",
"(",
"parentId",
")",
"==",
"authEntityTag",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // AuthFuncForMachineAgent returns a GetAuthFunc which creates an AuthFunc
// allowing only machine agents and their controllers | [
"AuthFuncForMachineAgent",
"returns",
"a",
"GetAuthFunc",
"which",
"creates",
"an",
"AuthFunc",
"allowing",
"only",
"machine",
"agents",
"and",
"their",
"controllers"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/interfaces.go#L101-L131 |
154,508 | juju/juju | provider/maas/constraints.go | convertConstraints | func convertConstraints(cons constraints.Value) url.Values {
params := url.Values{}
if cons.Arch != nil {
// Note: Juju and MAAS use the same architecture names.
// MAAS also accepts a subarchitecture (e.g. "highbank"
// for ARM), which defaults to "generic" if unspecified.
params.Add("arch", *cons.Arch)
}
if cons.CpuCores != nil {
params.Add("cpu_count", fmt.Sprintf("%d", *cons.CpuCores))
}
if cons.Mem != nil {
params.Add("mem", fmt.Sprintf("%d", *cons.Mem))
}
convertTagsToParams(params, cons.Tags)
if cons.CpuPower != nil {
logger.Warningf("ignoring unsupported constraint 'cpu-power'")
}
return params
} | go | func convertConstraints(cons constraints.Value) url.Values {
params := url.Values{}
if cons.Arch != nil {
// Note: Juju and MAAS use the same architecture names.
// MAAS also accepts a subarchitecture (e.g. "highbank"
// for ARM), which defaults to "generic" if unspecified.
params.Add("arch", *cons.Arch)
}
if cons.CpuCores != nil {
params.Add("cpu_count", fmt.Sprintf("%d", *cons.CpuCores))
}
if cons.Mem != nil {
params.Add("mem", fmt.Sprintf("%d", *cons.Mem))
}
convertTagsToParams(params, cons.Tags)
if cons.CpuPower != nil {
logger.Warningf("ignoring unsupported constraint 'cpu-power'")
}
return params
} | [
"func",
"convertConstraints",
"(",
"cons",
"constraints",
".",
"Value",
")",
"url",
".",
"Values",
"{",
"params",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"if",
"cons",
".",
"Arch",
"!=",
"nil",
"{",
"// Note: Juju and MAAS use the same architecture names.",
"// MAAS also accepts a subarchitecture (e.g. \"highbank\"",
"// for ARM), which defaults to \"generic\" if unspecified.",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"*",
"cons",
".",
"Arch",
")",
"\n",
"}",
"\n",
"if",
"cons",
".",
"CpuCores",
"!=",
"nil",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"*",
"cons",
".",
"CpuCores",
")",
")",
"\n",
"}",
"\n",
"if",
"cons",
".",
"Mem",
"!=",
"nil",
"{",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"*",
"cons",
".",
"Mem",
")",
")",
"\n",
"}",
"\n",
"convertTagsToParams",
"(",
"params",
",",
"cons",
".",
"Tags",
")",
"\n",
"if",
"cons",
".",
"CpuPower",
"!=",
"nil",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"params",
"\n",
"}"
] | // convertConstraints converts the given constraints into an url.Values object
// suitable to pass to MAAS when acquiring a node. CpuPower is ignored because
// it cannot be translated into something meaningful for MAAS right now. | [
"convertConstraints",
"converts",
"the",
"given",
"constraints",
"into",
"an",
"url",
".",
"Values",
"object",
"suitable",
"to",
"pass",
"to",
"MAAS",
"when",
"acquiring",
"a",
"node",
".",
"CpuPower",
"is",
"ignored",
"because",
"it",
"cannot",
"be",
"translated",
"into",
"something",
"meaningful",
"for",
"MAAS",
"right",
"now",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/constraints.go#L41-L60 |
154,509 | juju/juju | provider/maas/constraints.go | convertConstraints2 | func convertConstraints2(cons constraints.Value) gomaasapi.AllocateMachineArgs {
params := gomaasapi.AllocateMachineArgs{}
if cons.Arch != nil {
params.Architecture = *cons.Arch
}
if cons.CpuCores != nil {
params.MinCPUCount = int(*cons.CpuCores)
}
if cons.Mem != nil {
params.MinMemory = int(*cons.Mem)
}
if cons.Tags != nil {
positives, negatives := parseDelimitedValues(*cons.Tags)
if len(positives) > 0 {
params.Tags = positives
}
if len(negatives) > 0 {
params.NotTags = negatives
}
}
if cons.CpuPower != nil {
logger.Warningf("ignoring unsupported constraint 'cpu-power'")
}
return params
} | go | func convertConstraints2(cons constraints.Value) gomaasapi.AllocateMachineArgs {
params := gomaasapi.AllocateMachineArgs{}
if cons.Arch != nil {
params.Architecture = *cons.Arch
}
if cons.CpuCores != nil {
params.MinCPUCount = int(*cons.CpuCores)
}
if cons.Mem != nil {
params.MinMemory = int(*cons.Mem)
}
if cons.Tags != nil {
positives, negatives := parseDelimitedValues(*cons.Tags)
if len(positives) > 0 {
params.Tags = positives
}
if len(negatives) > 0 {
params.NotTags = negatives
}
}
if cons.CpuPower != nil {
logger.Warningf("ignoring unsupported constraint 'cpu-power'")
}
return params
} | [
"func",
"convertConstraints2",
"(",
"cons",
"constraints",
".",
"Value",
")",
"gomaasapi",
".",
"AllocateMachineArgs",
"{",
"params",
":=",
"gomaasapi",
".",
"AllocateMachineArgs",
"{",
"}",
"\n",
"if",
"cons",
".",
"Arch",
"!=",
"nil",
"{",
"params",
".",
"Architecture",
"=",
"*",
"cons",
".",
"Arch",
"\n",
"}",
"\n",
"if",
"cons",
".",
"CpuCores",
"!=",
"nil",
"{",
"params",
".",
"MinCPUCount",
"=",
"int",
"(",
"*",
"cons",
".",
"CpuCores",
")",
"\n",
"}",
"\n",
"if",
"cons",
".",
"Mem",
"!=",
"nil",
"{",
"params",
".",
"MinMemory",
"=",
"int",
"(",
"*",
"cons",
".",
"Mem",
")",
"\n",
"}",
"\n",
"if",
"cons",
".",
"Tags",
"!=",
"nil",
"{",
"positives",
",",
"negatives",
":=",
"parseDelimitedValues",
"(",
"*",
"cons",
".",
"Tags",
")",
"\n",
"if",
"len",
"(",
"positives",
")",
">",
"0",
"{",
"params",
".",
"Tags",
"=",
"positives",
"\n",
"}",
"\n",
"if",
"len",
"(",
"negatives",
")",
">",
"0",
"{",
"params",
".",
"NotTags",
"=",
"negatives",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"cons",
".",
"CpuPower",
"!=",
"nil",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"params",
"\n",
"}"
] | // convertConstraints2 converts the given constraints into a
// gomaasapi.AllocateMachineArgs for paasing to MAAS 2. | [
"convertConstraints2",
"converts",
"the",
"given",
"constraints",
"into",
"a",
"gomaasapi",
".",
"AllocateMachineArgs",
"for",
"paasing",
"to",
"MAAS",
"2",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/constraints.go#L64-L88 |
154,510 | juju/juju | provider/maas/constraints.go | convertSpacesFromConstraints | func convertSpacesFromConstraints(spaces *[]string) ([]string, []string) {
if spaces == nil || len(*spaces) == 0 {
return nil, nil
}
return parseDelimitedValues(*spaces)
} | go | func convertSpacesFromConstraints(spaces *[]string) ([]string, []string) {
if spaces == nil || len(*spaces) == 0 {
return nil, nil
}
return parseDelimitedValues(*spaces)
} | [
"func",
"convertSpacesFromConstraints",
"(",
"spaces",
"*",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"string",
",",
"[",
"]",
"string",
")",
"{",
"if",
"spaces",
"==",
"nil",
"||",
"len",
"(",
"*",
"spaces",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"parseDelimitedValues",
"(",
"*",
"spaces",
")",
"\n",
"}"
] | // convertSpacesFromConstraints extracts spaces from constraints and converts
// them to two lists of positive and negative spaces. | [
"convertSpacesFromConstraints",
"extracts",
"spaces",
"from",
"constraints",
"and",
"converts",
"them",
"to",
"two",
"lists",
"of",
"positive",
"and",
"negative",
"spaces",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/constraints.go#L109-L114 |
154,511 | juju/juju | provider/maas/constraints.go | addStorage | func addStorage(params url.Values, volumes []volumeInfo) {
if len(volumes) == 0 {
return
}
// Requests for specific values are passed to the acquire URL
// as a storage URL parameter of the form:
// [volume-name:]sizeinGB[tag,...]
// See http://maas.ubuntu.com/docs/api.html#nodes
// eg storage=root:0(ssd),data:20(magnetic,5400rpm),45
makeVolumeParams := func(v volumeInfo) string {
var params string
if v.name != "" {
params = v.name + ":"
}
params += fmt.Sprintf("%d", v.sizeInGB)
if len(v.tags) > 0 {
params += fmt.Sprintf("(%s)", strings.Join(v.tags, ","))
}
return params
}
var volParms []string
for _, v := range volumes {
params := makeVolumeParams(v)
volParms = append(volParms, params)
}
params.Add("storage", strings.Join(volParms, ","))
} | go | func addStorage(params url.Values, volumes []volumeInfo) {
if len(volumes) == 0 {
return
}
// Requests for specific values are passed to the acquire URL
// as a storage URL parameter of the form:
// [volume-name:]sizeinGB[tag,...]
// See http://maas.ubuntu.com/docs/api.html#nodes
// eg storage=root:0(ssd),data:20(magnetic,5400rpm),45
makeVolumeParams := func(v volumeInfo) string {
var params string
if v.name != "" {
params = v.name + ":"
}
params += fmt.Sprintf("%d", v.sizeInGB)
if len(v.tags) > 0 {
params += fmt.Sprintf("(%s)", strings.Join(v.tags, ","))
}
return params
}
var volParms []string
for _, v := range volumes {
params := makeVolumeParams(v)
volParms = append(volParms, params)
}
params.Add("storage", strings.Join(volParms, ","))
} | [
"func",
"addStorage",
"(",
"params",
"url",
".",
"Values",
",",
"volumes",
"[",
"]",
"volumeInfo",
")",
"{",
"if",
"len",
"(",
"volumes",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"// Requests for specific values are passed to the acquire URL",
"// as a storage URL parameter of the form:",
"// [volume-name:]sizeinGB[tag,...]",
"// See http://maas.ubuntu.com/docs/api.html#nodes",
"// eg storage=root:0(ssd),data:20(magnetic,5400rpm),45",
"makeVolumeParams",
":=",
"func",
"(",
"v",
"volumeInfo",
")",
"string",
"{",
"var",
"params",
"string",
"\n",
"if",
"v",
".",
"name",
"!=",
"\"",
"\"",
"{",
"params",
"=",
"v",
".",
"name",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"params",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"sizeInGB",
")",
"\n",
"if",
"len",
"(",
"v",
".",
"tags",
")",
">",
"0",
"{",
"params",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"v",
".",
"tags",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"params",
"\n",
"}",
"\n",
"var",
"volParms",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"volumes",
"{",
"params",
":=",
"makeVolumeParams",
"(",
"v",
")",
"\n",
"volParms",
"=",
"append",
"(",
"volParms",
",",
"params",
")",
"\n",
"}",
"\n",
"params",
".",
"Add",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"volParms",
",",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // addStorage converts volume information into url.Values object suitable to
// pass to MAAS when acquiring a node. | [
"addStorage",
"converts",
"volume",
"information",
"into",
"url",
".",
"Values",
"object",
"suitable",
"to",
"pass",
"to",
"MAAS",
"when",
"acquiring",
"a",
"node",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/constraints.go#L306-L333 |
154,512 | juju/juju | provider/maas/constraints.go | addStorage2 | func addStorage2(params *gomaasapi.AllocateMachineArgs, volumes []volumeInfo) {
if len(volumes) == 0 {
return
}
var volParams []gomaasapi.StorageSpec
for _, v := range volumes {
volSpec := gomaasapi.StorageSpec{
Label: v.name,
Size: int(v.sizeInGB),
Tags: v.tags,
}
volParams = append(volParams, volSpec)
}
params.Storage = volParams
} | go | func addStorage2(params *gomaasapi.AllocateMachineArgs, volumes []volumeInfo) {
if len(volumes) == 0 {
return
}
var volParams []gomaasapi.StorageSpec
for _, v := range volumes {
volSpec := gomaasapi.StorageSpec{
Label: v.name,
Size: int(v.sizeInGB),
Tags: v.tags,
}
volParams = append(volParams, volSpec)
}
params.Storage = volParams
} | [
"func",
"addStorage2",
"(",
"params",
"*",
"gomaasapi",
".",
"AllocateMachineArgs",
",",
"volumes",
"[",
"]",
"volumeInfo",
")",
"{",
"if",
"len",
"(",
"volumes",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"var",
"volParams",
"[",
"]",
"gomaasapi",
".",
"StorageSpec",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"volumes",
"{",
"volSpec",
":=",
"gomaasapi",
".",
"StorageSpec",
"{",
"Label",
":",
"v",
".",
"name",
",",
"Size",
":",
"int",
"(",
"v",
".",
"sizeInGB",
")",
",",
"Tags",
":",
"v",
".",
"tags",
",",
"}",
"\n",
"volParams",
"=",
"append",
"(",
"volParams",
",",
"volSpec",
")",
"\n",
"}",
"\n",
"params",
".",
"Storage",
"=",
"volParams",
"\n",
"}"
] | // addStorage2 adds volume information onto a gomaasapi.AllocateMachineArgs
// object suitable to pass to MAAS 2 when acquiring a node. | [
"addStorage2",
"adds",
"volume",
"information",
"onto",
"a",
"gomaasapi",
".",
"AllocateMachineArgs",
"object",
"suitable",
"to",
"pass",
"to",
"MAAS",
"2",
"when",
"acquiring",
"a",
"node",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/constraints.go#L337-L351 |
154,513 | juju/juju | provider/gce/disks.go | resourceTagsToDiskLabels | func resourceTagsToDiskLabels(in map[string]string) map[string]string {
out := make(map[string]string)
for k, v := range in {
// Only the controller and model UUID tags are carried
// over, as they're known not to conflict with GCE's
// rules regarding label values.
switch k {
case tags.JujuController, tags.JujuModel:
out[k] = v
}
}
return out
} | go | func resourceTagsToDiskLabels(in map[string]string) map[string]string {
out := make(map[string]string)
for k, v := range in {
// Only the controller and model UUID tags are carried
// over, as they're known not to conflict with GCE's
// rules regarding label values.
switch k {
case tags.JujuController, tags.JujuModel:
out[k] = v
}
}
return out
} | [
"func",
"resourceTagsToDiskLabels",
"(",
"in",
"map",
"[",
"string",
"]",
"string",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"out",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"in",
"{",
"// Only the controller and model UUID tags are carried",
"// over, as they're known not to conflict with GCE's",
"// rules regarding label values.",
"switch",
"k",
"{",
"case",
"tags",
".",
"JujuController",
",",
"tags",
".",
"JujuModel",
":",
"out",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"out",
"\n",
"}"
] | // resourceTagsToDiskLabels translates a set of
// resource tags, provided by Juju, to disk labels. | [
"resourceTagsToDiskLabels",
"translates",
"a",
"set",
"of",
"resource",
"tags",
"provided",
"by",
"Juju",
"to",
"disk",
"labels",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/disks.go#L510-L522 |
154,514 | juju/juju | worker/gate/flag.go | start | func (config FlagManifoldConfig) start(context dependency.Context) (worker.Worker, error) {
var gate Waiter
if err := context.Get(config.GateName, &gate); err != nil {
return nil, errors.Trace(err)
}
worker, err := config.NewWorker(gate)
if err != nil {
return nil, errors.Trace(err)
}
return worker, nil
} | go | func (config FlagManifoldConfig) start(context dependency.Context) (worker.Worker, error) {
var gate Waiter
if err := context.Get(config.GateName, &gate); err != nil {
return nil, errors.Trace(err)
}
worker, err := config.NewWorker(gate)
if err != nil {
return nil, errors.Trace(err)
}
return worker, nil
} | [
"func",
"(",
"config",
"FlagManifoldConfig",
")",
"start",
"(",
"context",
"dependency",
".",
"Context",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"var",
"gate",
"Waiter",
"\n",
"if",
"err",
":=",
"context",
".",
"Get",
"(",
"config",
".",
"GateName",
",",
"&",
"gate",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"worker",
",",
"err",
":=",
"config",
".",
"NewWorker",
"(",
"gate",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"worker",
",",
"nil",
"\n\n",
"}"
] | // start is a dependency.StartFunc that uses config. | [
"start",
"is",
"a",
"dependency",
".",
"StartFunc",
"that",
"uses",
"config",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/gate/flag.go#L23-L34 |
154,515 | juju/juju | worker/gate/flag.go | FlagManifold | func FlagManifold(config FlagManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{config.GateName},
Start: config.start,
Output: engine.FlagOutput,
Filter: bounceUnlocked,
}
} | go | func FlagManifold(config FlagManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{config.GateName},
Start: config.start,
Output: engine.FlagOutput,
Filter: bounceUnlocked,
}
} | [
"func",
"FlagManifold",
"(",
"config",
"FlagManifoldConfig",
")",
"dependency",
".",
"Manifold",
"{",
"return",
"dependency",
".",
"Manifold",
"{",
"Inputs",
":",
"[",
"]",
"string",
"{",
"config",
".",
"GateName",
"}",
",",
"Start",
":",
"config",
".",
"start",
",",
"Output",
":",
"engine",
".",
"FlagOutput",
",",
"Filter",
":",
"bounceUnlocked",
",",
"}",
"\n",
"}"
] | // FlagManifold runs a worker that implements engine.Flag such that
// it's only considered set when the referenced gate is unlocked. | [
"FlagManifold",
"runs",
"a",
"worker",
"that",
"implements",
"engine",
".",
"Flag",
"such",
"that",
"it",
"s",
"only",
"considered",
"set",
"when",
"the",
"referenced",
"gate",
"is",
"unlocked",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/gate/flag.go#L38-L45 |
154,516 | juju/juju | worker/gate/flag.go | NewFlag | func NewFlag(gate Waiter) (*Flag, error) {
w := &Flag{
gate: gate,
unlocked: gate.IsUnlocked(),
}
w.tomb.Go(w.run)
return w, nil
} | go | func NewFlag(gate Waiter) (*Flag, error) {
w := &Flag{
gate: gate,
unlocked: gate.IsUnlocked(),
}
w.tomb.Go(w.run)
return w, nil
} | [
"func",
"NewFlag",
"(",
"gate",
"Waiter",
")",
"(",
"*",
"Flag",
",",
"error",
")",
"{",
"w",
":=",
"&",
"Flag",
"{",
"gate",
":",
"gate",
",",
"unlocked",
":",
"gate",
".",
"IsUnlocked",
"(",
")",
",",
"}",
"\n",
"w",
".",
"tomb",
".",
"Go",
"(",
"w",
".",
"run",
")",
"\n",
"return",
"w",
",",
"nil",
"\n",
"}"
] | // NewFlag returns a worker that implements engine.Flag,
// backed by the supplied gate's unlockedness. | [
"NewFlag",
"returns",
"a",
"worker",
"that",
"implements",
"engine",
".",
"Flag",
"backed",
"by",
"the",
"supplied",
"gate",
"s",
"unlockedness",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/gate/flag.go#L49-L56 |
154,517 | juju/juju | worker/gate/flag.go | bounceUnlocked | func bounceUnlocked(err error) error {
if errors.Cause(err) == ErrUnlocked {
return dependency.ErrBounce
}
return err
} | go | func bounceUnlocked(err error) error {
if errors.Cause(err) == ErrUnlocked {
return dependency.ErrBounce
}
return err
} | [
"func",
"bounceUnlocked",
"(",
"err",
"error",
")",
"error",
"{",
"if",
"errors",
".",
"Cause",
"(",
"err",
")",
"==",
"ErrUnlocked",
"{",
"return",
"dependency",
".",
"ErrBounce",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // bounceUnlocked returns dependency.ErrBounce if passed an error caused
// by ErrUnlocked; and otherwise returns the original error. | [
"bounceUnlocked",
"returns",
"dependency",
".",
"ErrBounce",
"if",
"passed",
"an",
"error",
"caused",
"by",
"ErrUnlocked",
";",
"and",
"otherwise",
"returns",
"the",
"original",
"error",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/gate/flag.go#L99-L104 |
154,518 | juju/juju | provider/manual/environ.go | Instances | func (e *manualEnviron) Instances(ctx context.ProviderCallContext, ids []instance.Id) ([]instances.Instance, error) {
result := make([]instances.Instance, len(ids))
var found bool
var err error
for i, id := range ids {
if id == BootstrapInstanceId {
result[i] = manualBootstrapInstance{e.host}
found = true
} else {
err = environs.ErrPartialInstances
}
}
if !found {
err = environs.ErrNoInstances
}
return result, err
} | go | func (e *manualEnviron) Instances(ctx context.ProviderCallContext, ids []instance.Id) ([]instances.Instance, error) {
result := make([]instances.Instance, len(ids))
var found bool
var err error
for i, id := range ids {
if id == BootstrapInstanceId {
result[i] = manualBootstrapInstance{e.host}
found = true
} else {
err = environs.ErrPartialInstances
}
}
if !found {
err = environs.ErrNoInstances
}
return result, err
} | [
"func",
"(",
"e",
"*",
"manualEnviron",
")",
"Instances",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"ids",
"[",
"]",
"instance",
".",
"Id",
")",
"(",
"[",
"]",
"instances",
".",
"Instance",
",",
"error",
")",
"{",
"result",
":=",
"make",
"(",
"[",
"]",
"instances",
".",
"Instance",
",",
"len",
"(",
"ids",
")",
")",
"\n",
"var",
"found",
"bool",
"\n",
"var",
"err",
"error",
"\n",
"for",
"i",
",",
"id",
":=",
"range",
"ids",
"{",
"if",
"id",
"==",
"BootstrapInstanceId",
"{",
"result",
"[",
"i",
"]",
"=",
"manualBootstrapInstance",
"{",
"e",
".",
"host",
"}",
"\n",
"found",
"=",
"true",
"\n",
"}",
"else",
"{",
"err",
"=",
"environs",
".",
"ErrPartialInstances",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"err",
"=",
"environs",
".",
"ErrNoInstances",
"\n",
"}",
"\n",
"return",
"result",
",",
"err",
"\n",
"}"
] | // Instances implements environs.Environ.
//
// This method will only ever return an Instance for the Id
// BootstrapInstanceId. If any others are specified, then
// ErrPartialInstances or ErrNoInstances will result. | [
"Instances",
"implements",
"environs",
".",
"Environ",
".",
"This",
"method",
"will",
"only",
"ever",
"return",
"an",
"Instance",
"for",
"the",
"Id",
"BootstrapInstanceId",
".",
"If",
"any",
"others",
"are",
"specified",
"then",
"ErrPartialInstances",
"or",
"ErrNoInstances",
"will",
"result",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/manual/environ.go#L200-L216 |
154,519 | juju/juju | cloudconfig/cloudinit/progress.go | LogProgressCmd | func LogProgressCmd(format string, args ...interface{}) string {
msg := utils.ShQuote(fmt.Sprintf(format, args...))
return fmt.Sprintf("echo %s >&$%s", msg, progressFdEnvVar)
} | go | func LogProgressCmd(format string, args ...interface{}) string {
msg := utils.ShQuote(fmt.Sprintf(format, args...))
return fmt.Sprintf("echo %s >&$%s", msg, progressFdEnvVar)
} | [
"func",
"LogProgressCmd",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"string",
"{",
"msg",
":=",
"utils",
".",
"ShQuote",
"(",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"msg",
",",
"progressFdEnvVar",
")",
"\n",
"}"
] | // LogProgressCmd will return a command to log the specified progress
// message to stderr; the resultant command should be added to the
// configuration as a runcmd or bootcmd as appropriate.
//
// If there are any uses of LogProgressCmd in a configuration, the
// configuration MUST precede the command with the result of
// InitProgressCmd. | [
"LogProgressCmd",
"will",
"return",
"a",
"command",
"to",
"log",
"the",
"specified",
"progress",
"message",
"to",
"stderr",
";",
"the",
"resultant",
"command",
"should",
"be",
"added",
"to",
"the",
"configuration",
"as",
"a",
"runcmd",
"or",
"bootcmd",
"as",
"appropriate",
".",
"If",
"there",
"are",
"any",
"uses",
"of",
"LogProgressCmd",
"in",
"a",
"configuration",
"the",
"configuration",
"MUST",
"precede",
"the",
"command",
"with",
"the",
"result",
"of",
"InitProgressCmd",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/cloudinit/progress.go#L49-L52 |
154,520 | juju/juju | worker/uniter/runner/jujuc/is-leader.go | NewIsLeaderCommand | func NewIsLeaderCommand(ctx Context) (cmd.Command, error) {
return &isLeaderCommand{ctx: ctx}, nil
} | go | func NewIsLeaderCommand(ctx Context) (cmd.Command, error) {
return &isLeaderCommand{ctx: ctx}, nil
} | [
"func",
"NewIsLeaderCommand",
"(",
"ctx",
"Context",
")",
"(",
"cmd",
".",
"Command",
",",
"error",
")",
"{",
"return",
"&",
"isLeaderCommand",
"{",
"ctx",
":",
"ctx",
"}",
",",
"nil",
"\n",
"}"
] | // NewIsLeaderCommand returns a new isLeaderCommand with the given context. | [
"NewIsLeaderCommand",
"returns",
"a",
"new",
"isLeaderCommand",
"with",
"the",
"given",
"context",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/is-leader.go#L22-L24 |
154,521 | juju/juju | cmd/juju/storage/filesystem.go | generateListFilesystemsOutput | func generateListFilesystemsOutput(ctx *cmd.Context, api StorageListAPI, ids []string) (map[string]FilesystemInfo, error) {
results, err := api.ListFilesystems(ids)
if err != nil {
return nil, errors.Trace(err)
}
// filter out valid output, if any
var valid []params.FilesystemDetails
for _, result := range results {
if result.Error == nil {
valid = append(valid, result.Result...)
continue
}
// display individual error
fmt.Fprintf(ctx.Stderr, "%v\n", result.Error)
}
if len(valid) == 0 {
return nil, nil
}
return convertToFilesystemInfo(valid)
} | go | func generateListFilesystemsOutput(ctx *cmd.Context, api StorageListAPI, ids []string) (map[string]FilesystemInfo, error) {
results, err := api.ListFilesystems(ids)
if err != nil {
return nil, errors.Trace(err)
}
// filter out valid output, if any
var valid []params.FilesystemDetails
for _, result := range results {
if result.Error == nil {
valid = append(valid, result.Result...)
continue
}
// display individual error
fmt.Fprintf(ctx.Stderr, "%v\n", result.Error)
}
if len(valid) == 0 {
return nil, nil
}
return convertToFilesystemInfo(valid)
} | [
"func",
"generateListFilesystemsOutput",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
",",
"api",
"StorageListAPI",
",",
"ids",
"[",
"]",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"FilesystemInfo",
",",
"error",
")",
"{",
"results",
",",
"err",
":=",
"api",
".",
"ListFilesystems",
"(",
"ids",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// filter out valid output, if any",
"var",
"valid",
"[",
"]",
"params",
".",
"FilesystemDetails",
"\n",
"for",
"_",
",",
"result",
":=",
"range",
"results",
"{",
"if",
"result",
".",
"Error",
"==",
"nil",
"{",
"valid",
"=",
"append",
"(",
"valid",
",",
"result",
".",
"Result",
"...",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"// display individual error",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"Error",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"valid",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"convertToFilesystemInfo",
"(",
"valid",
")",
"\n",
"}"
] | // generateListFilesystemOutput returns a map filesystem IDs to filesystem info | [
"generateListFilesystemOutput",
"returns",
"a",
"map",
"filesystem",
"IDs",
"to",
"filesystem",
"info"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/storage/filesystem.go#L63-L84 |
154,522 | juju/juju | cmd/juju/storage/filesystem.go | convertToFilesystemInfo | func convertToFilesystemInfo(all []params.FilesystemDetails) (map[string]FilesystemInfo, error) {
result := make(map[string]FilesystemInfo)
for _, one := range all {
filesystemTag, info, err := createFilesystemInfo(one)
if err != nil {
return nil, errors.Trace(err)
}
result[filesystemTag.Id()] = info
}
return result, nil
} | go | func convertToFilesystemInfo(all []params.FilesystemDetails) (map[string]FilesystemInfo, error) {
result := make(map[string]FilesystemInfo)
for _, one := range all {
filesystemTag, info, err := createFilesystemInfo(one)
if err != nil {
return nil, errors.Trace(err)
}
result[filesystemTag.Id()] = info
}
return result, nil
} | [
"func",
"convertToFilesystemInfo",
"(",
"all",
"[",
"]",
"params",
".",
"FilesystemDetails",
")",
"(",
"map",
"[",
"string",
"]",
"FilesystemInfo",
",",
"error",
")",
"{",
"result",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"FilesystemInfo",
")",
"\n",
"for",
"_",
",",
"one",
":=",
"range",
"all",
"{",
"filesystemTag",
",",
"info",
",",
"err",
":=",
"createFilesystemInfo",
"(",
"one",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"result",
"[",
"filesystemTag",
".",
"Id",
"(",
")",
"]",
"=",
"info",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // convertToFilesystemInfo returns a map of filesystem IDs to filesystem info. | [
"convertToFilesystemInfo",
"returns",
"a",
"map",
"of",
"filesystem",
"IDs",
"to",
"filesystem",
"info",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/storage/filesystem.go#L87-L97 |
154,523 | juju/juju | apiserver/common/getstatus.go | NewStatusGetter | func NewStatusGetter(st state.EntityFinder, getCanAccess GetAuthFunc) *StatusGetter {
return &StatusGetter{
st: st,
getCanAccess: getCanAccess,
}
} | go | func NewStatusGetter(st state.EntityFinder, getCanAccess GetAuthFunc) *StatusGetter {
return &StatusGetter{
st: st,
getCanAccess: getCanAccess,
}
} | [
"func",
"NewStatusGetter",
"(",
"st",
"state",
".",
"EntityFinder",
",",
"getCanAccess",
"GetAuthFunc",
")",
"*",
"StatusGetter",
"{",
"return",
"&",
"StatusGetter",
"{",
"st",
":",
"st",
",",
"getCanAccess",
":",
"getCanAccess",
",",
"}",
"\n",
"}"
] | // NewStatusGetter returns a new StatusGetter. The GetAuthFunc will be
// used on each invocation of Status to determine current
// permissions. | [
"NewStatusGetter",
"returns",
"a",
"new",
"StatusGetter",
".",
"The",
"GetAuthFunc",
"will",
"be",
"used",
"on",
"each",
"invocation",
"of",
"Status",
"to",
"determine",
"current",
"permissions",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/getstatus.go#L27-L32 |
154,524 | juju/juju | apiserver/common/getstatus.go | Status | func (s *StatusGetter) Status(args params.Entities) (params.StatusResults, error) {
result := params.StatusResults{
Results: make([]params.StatusResult, len(args.Entities)),
}
canAccess, err := s.getCanAccess()
if err != nil {
return params.StatusResults{}, err
}
for i, entity := range args.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
result.Results[i].Error = ServerError(err)
continue
}
if !canAccess(tag) {
result.Results[i].Error = ServerError(ErrPerm)
continue
}
result.Results[i] = s.getEntityStatus(tag)
}
return result, nil
} | go | func (s *StatusGetter) Status(args params.Entities) (params.StatusResults, error) {
result := params.StatusResults{
Results: make([]params.StatusResult, len(args.Entities)),
}
canAccess, err := s.getCanAccess()
if err != nil {
return params.StatusResults{}, err
}
for i, entity := range args.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
result.Results[i].Error = ServerError(err)
continue
}
if !canAccess(tag) {
result.Results[i].Error = ServerError(ErrPerm)
continue
}
result.Results[i] = s.getEntityStatus(tag)
}
return result, nil
} | [
"func",
"(",
"s",
"*",
"StatusGetter",
")",
"Status",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"StatusResults",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"StatusResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"StatusResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"canAccess",
",",
"err",
":=",
"s",
".",
"getCanAccess",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"StatusResults",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"for",
"i",
",",
"entity",
":=",
"range",
"args",
".",
"Entities",
"{",
"tag",
",",
"err",
":=",
"names",
".",
"ParseTag",
"(",
"entity",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"canAccess",
"(",
"tag",
")",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"ErrPerm",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
"=",
"s",
".",
"getEntityStatus",
"(",
"tag",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // Status returns the status of each given entity. | [
"Status",
"returns",
"the",
"status",
"of",
"each",
"given",
"entity",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/getstatus.go#L56-L77 |
154,525 | juju/juju | apiserver/common/getstatus.go | NewApplicationStatusGetter | func NewApplicationStatusGetter(st *state.State, getCanAccess GetAuthFunc, leadershipChecker leadership.Checker) *ApplicationStatusGetter {
return &ApplicationStatusGetter{
leadershipChecker: leadershipChecker,
st: st,
getCanAccess: getCanAccess,
}
} | go | func NewApplicationStatusGetter(st *state.State, getCanAccess GetAuthFunc, leadershipChecker leadership.Checker) *ApplicationStatusGetter {
return &ApplicationStatusGetter{
leadershipChecker: leadershipChecker,
st: st,
getCanAccess: getCanAccess,
}
} | [
"func",
"NewApplicationStatusGetter",
"(",
"st",
"*",
"state",
".",
"State",
",",
"getCanAccess",
"GetAuthFunc",
",",
"leadershipChecker",
"leadership",
".",
"Checker",
")",
"*",
"ApplicationStatusGetter",
"{",
"return",
"&",
"ApplicationStatusGetter",
"{",
"leadershipChecker",
":",
"leadershipChecker",
",",
"st",
":",
"st",
",",
"getCanAccess",
":",
"getCanAccess",
",",
"}",
"\n",
"}"
] | // NewApplicationStatusGetter returns a ApplicationStatusGetter. | [
"NewApplicationStatusGetter",
"returns",
"a",
"ApplicationStatusGetter",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/getstatus.go#L91-L97 |
154,526 | juju/juju | apiserver/common/getstatus.go | Status | func (s *ApplicationStatusGetter) Status(args params.Entities) (params.ApplicationStatusResults, error) {
result := params.ApplicationStatusResults{
Results: make([]params.ApplicationStatusResult, len(args.Entities)),
}
canAccess, err := s.getCanAccess()
if err != nil {
return params.ApplicationStatusResults{}, err
}
for i, arg := range args.Entities {
// TODO(fwereade): the auth is basically nonsense, and basically only
// works by coincidence (and is happening at the wrong layer anyway).
// Read carefully.
// We "know" that arg.Tag is either the calling unit or its application
// (because getCanAccess is authUnitOrApplication, and we'll fail out if
// it isn't); and, in practice, it's always going to be the calling
// unit (because, /sigh, we don't actually use application tags to refer
// to applications in this method).
tag, err := names.ParseTag(arg.Tag)
if err != nil {
result.Results[i].Error = ServerError(err)
continue
}
if !canAccess(tag) {
result.Results[i].Error = ServerError(ErrPerm)
continue
}
unitTag, ok := tag.(names.UnitTag)
if !ok {
// No matter what the canAccess says, if this entity is not
// a unit, we say "NO".
result.Results[i].Error = ServerError(ErrPerm)
continue
}
unitId := unitTag.Id()
// Now we have the unit, we can get the application that should have been
// specified in the first place...
applicationId, err := names.UnitApplication(unitId)
if err != nil {
result.Results[i].Error = ServerError(err)
continue
}
application, err := s.st.Application(applicationId)
if err != nil {
result.Results[i].Error = ServerError(err)
continue
}
// ...so we can check the unit's application leadership...
token := s.leadershipChecker.LeadershipCheck(applicationId, unitId)
if err := token.Check(0, nil); err != nil {
// TODO(fwereade) this should probably be ErrPerm is certain cases,
// but I don't think I implemented an exported ErrNotLeader. I
// should have done, though.
result.Results[i].Error = ServerError(err)
continue
}
// ...and collect the results.
applicationStatus, unitStatuses, err := application.ApplicationAndUnitsStatus()
if err != nil {
result.Results[i].Application.Error = ServerError(err)
result.Results[i].Error = ServerError(err)
continue
}
result.Results[i].Application.Status = applicationStatus.Status.String()
result.Results[i].Application.Info = applicationStatus.Message
result.Results[i].Application.Data = applicationStatus.Data
result.Results[i].Application.Since = applicationStatus.Since
result.Results[i].Units = make(map[string]params.StatusResult, len(unitStatuses))
for uTag, r := range unitStatuses {
ur := params.StatusResult{
Status: r.Status.String(),
Info: r.Message,
Data: r.Data,
Since: r.Since,
}
result.Results[i].Units[uTag] = ur
}
}
return result, nil
} | go | func (s *ApplicationStatusGetter) Status(args params.Entities) (params.ApplicationStatusResults, error) {
result := params.ApplicationStatusResults{
Results: make([]params.ApplicationStatusResult, len(args.Entities)),
}
canAccess, err := s.getCanAccess()
if err != nil {
return params.ApplicationStatusResults{}, err
}
for i, arg := range args.Entities {
// TODO(fwereade): the auth is basically nonsense, and basically only
// works by coincidence (and is happening at the wrong layer anyway).
// Read carefully.
// We "know" that arg.Tag is either the calling unit or its application
// (because getCanAccess is authUnitOrApplication, and we'll fail out if
// it isn't); and, in practice, it's always going to be the calling
// unit (because, /sigh, we don't actually use application tags to refer
// to applications in this method).
tag, err := names.ParseTag(arg.Tag)
if err != nil {
result.Results[i].Error = ServerError(err)
continue
}
if !canAccess(tag) {
result.Results[i].Error = ServerError(ErrPerm)
continue
}
unitTag, ok := tag.(names.UnitTag)
if !ok {
// No matter what the canAccess says, if this entity is not
// a unit, we say "NO".
result.Results[i].Error = ServerError(ErrPerm)
continue
}
unitId := unitTag.Id()
// Now we have the unit, we can get the application that should have been
// specified in the first place...
applicationId, err := names.UnitApplication(unitId)
if err != nil {
result.Results[i].Error = ServerError(err)
continue
}
application, err := s.st.Application(applicationId)
if err != nil {
result.Results[i].Error = ServerError(err)
continue
}
// ...so we can check the unit's application leadership...
token := s.leadershipChecker.LeadershipCheck(applicationId, unitId)
if err := token.Check(0, nil); err != nil {
// TODO(fwereade) this should probably be ErrPerm is certain cases,
// but I don't think I implemented an exported ErrNotLeader. I
// should have done, though.
result.Results[i].Error = ServerError(err)
continue
}
// ...and collect the results.
applicationStatus, unitStatuses, err := application.ApplicationAndUnitsStatus()
if err != nil {
result.Results[i].Application.Error = ServerError(err)
result.Results[i].Error = ServerError(err)
continue
}
result.Results[i].Application.Status = applicationStatus.Status.String()
result.Results[i].Application.Info = applicationStatus.Message
result.Results[i].Application.Data = applicationStatus.Data
result.Results[i].Application.Since = applicationStatus.Since
result.Results[i].Units = make(map[string]params.StatusResult, len(unitStatuses))
for uTag, r := range unitStatuses {
ur := params.StatusResult{
Status: r.Status.String(),
Info: r.Message,
Data: r.Data,
Since: r.Since,
}
result.Results[i].Units[uTag] = ur
}
}
return result, nil
} | [
"func",
"(",
"s",
"*",
"ApplicationStatusGetter",
")",
"Status",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"ApplicationStatusResults",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"ApplicationStatusResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"ApplicationStatusResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"canAccess",
",",
"err",
":=",
"s",
".",
"getCanAccess",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ApplicationStatusResults",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"arg",
":=",
"range",
"args",
".",
"Entities",
"{",
"// TODO(fwereade): the auth is basically nonsense, and basically only",
"// works by coincidence (and is happening at the wrong layer anyway).",
"// Read carefully.",
"// We \"know\" that arg.Tag is either the calling unit or its application",
"// (because getCanAccess is authUnitOrApplication, and we'll fail out if",
"// it isn't); and, in practice, it's always going to be the calling",
"// unit (because, /sigh, we don't actually use application tags to refer",
"// to applications in this method).",
"tag",
",",
"err",
":=",
"names",
".",
"ParseTag",
"(",
"arg",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"canAccess",
"(",
"tag",
")",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"ErrPerm",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"unitTag",
",",
"ok",
":=",
"tag",
".",
"(",
"names",
".",
"UnitTag",
")",
"\n",
"if",
"!",
"ok",
"{",
"// No matter what the canAccess says, if this entity is not",
"// a unit, we say \"NO\".",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"ErrPerm",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"unitId",
":=",
"unitTag",
".",
"Id",
"(",
")",
"\n\n",
"// Now we have the unit, we can get the application that should have been",
"// specified in the first place...",
"applicationId",
",",
"err",
":=",
"names",
".",
"UnitApplication",
"(",
"unitId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"application",
",",
"err",
":=",
"s",
".",
"st",
".",
"Application",
"(",
"applicationId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// ...so we can check the unit's application leadership...",
"token",
":=",
"s",
".",
"leadershipChecker",
".",
"LeadershipCheck",
"(",
"applicationId",
",",
"unitId",
")",
"\n",
"if",
"err",
":=",
"token",
".",
"Check",
"(",
"0",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"// TODO(fwereade) this should probably be ErrPerm is certain cases,",
"// but I don't think I implemented an exported ErrNotLeader. I",
"// should have done, though.",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// ...and collect the results.",
"applicationStatus",
",",
"unitStatuses",
",",
"err",
":=",
"application",
".",
"ApplicationAndUnitsStatus",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Application",
".",
"Error",
"=",
"ServerError",
"(",
"err",
")",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Application",
".",
"Status",
"=",
"applicationStatus",
".",
"Status",
".",
"String",
"(",
")",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Application",
".",
"Info",
"=",
"applicationStatus",
".",
"Message",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Application",
".",
"Data",
"=",
"applicationStatus",
".",
"Data",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Application",
".",
"Since",
"=",
"applicationStatus",
".",
"Since",
"\n\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Units",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"params",
".",
"StatusResult",
",",
"len",
"(",
"unitStatuses",
")",
")",
"\n",
"for",
"uTag",
",",
"r",
":=",
"range",
"unitStatuses",
"{",
"ur",
":=",
"params",
".",
"StatusResult",
"{",
"Status",
":",
"r",
".",
"Status",
".",
"String",
"(",
")",
",",
"Info",
":",
"r",
".",
"Message",
",",
"Data",
":",
"r",
".",
"Data",
",",
"Since",
":",
"r",
".",
"Since",
",",
"}",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Units",
"[",
"uTag",
"]",
"=",
"ur",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // Status returns the status of the Application for each given Unit tag. | [
"Status",
"returns",
"the",
"status",
"of",
"the",
"Application",
"for",
"each",
"given",
"Unit",
"tag",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/getstatus.go#L100-L184 |
154,527 | juju/juju | apiserver/common/getstatus.go | EntityStatusFromState | func EntityStatusFromState(statusInfo status.StatusInfo) params.EntityStatus {
return params.EntityStatus{
Status: statusInfo.Status,
Info: statusInfo.Message,
Data: statusInfo.Data,
Since: statusInfo.Since,
}
} | go | func EntityStatusFromState(statusInfo status.StatusInfo) params.EntityStatus {
return params.EntityStatus{
Status: statusInfo.Status,
Info: statusInfo.Message,
Data: statusInfo.Data,
Since: statusInfo.Since,
}
} | [
"func",
"EntityStatusFromState",
"(",
"statusInfo",
"status",
".",
"StatusInfo",
")",
"params",
".",
"EntityStatus",
"{",
"return",
"params",
".",
"EntityStatus",
"{",
"Status",
":",
"statusInfo",
".",
"Status",
",",
"Info",
":",
"statusInfo",
".",
"Message",
",",
"Data",
":",
"statusInfo",
".",
"Data",
",",
"Since",
":",
"statusInfo",
".",
"Since",
",",
"}",
"\n",
"}"
] | // EntityStatusFromState converts a state.StatusInfo into a params.EntityStatus. | [
"EntityStatusFromState",
"converts",
"a",
"state",
".",
"StatusInfo",
"into",
"a",
"params",
".",
"EntityStatus",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/getstatus.go#L187-L194 |
154,528 | juju/juju | cmd/juju/interact/errwriter.go | NewErrWriter | func NewErrWriter(w io.Writer) io.Writer {
return errWriter{ansiterm.NewWriter(w)}
} | go | func NewErrWriter(w io.Writer) io.Writer {
return errWriter{ansiterm.NewWriter(w)}
} | [
"func",
"NewErrWriter",
"(",
"w",
"io",
".",
"Writer",
")",
"io",
".",
"Writer",
"{",
"return",
"errWriter",
"{",
"ansiterm",
".",
"NewWriter",
"(",
"w",
")",
"}",
"\n",
"}"
] | // NewErrWriter wraps w in a type that will cause all writes to be written as
// ansi terminal BrightRed. | [
"NewErrWriter",
"wraps",
"w",
"in",
"a",
"type",
"that",
"will",
"cause",
"all",
"writes",
"to",
"be",
"written",
"as",
"ansi",
"terminal",
"BrightRed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/errwriter.go#L14-L16 |
154,529 | juju/juju | provider/ec2/ebs.go | Supports | func (e *ebsProvider) Supports(k storage.StorageKind) bool {
return k == storage.StorageKindBlock
} | go | func (e *ebsProvider) Supports(k storage.StorageKind) bool {
return k == storage.StorageKindBlock
} | [
"func",
"(",
"e",
"*",
"ebsProvider",
")",
"Supports",
"(",
"k",
"storage",
".",
"StorageKind",
")",
"bool",
"{",
"return",
"k",
"==",
"storage",
".",
"StorageKindBlock",
"\n",
"}"
] | // Supports is defined on the Provider interface. | [
"Supports",
"is",
"defined",
"on",
"the",
"Provider",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/ebs.go#L239-L241 |
154,530 | juju/juju | provider/ec2/ebs.go | DefaultPools | func (e *ebsProvider) DefaultPools() []*storage.Config {
ssdPool, _ := storage.NewConfig("ebs-ssd", EBS_ProviderType, map[string]interface{}{
EBS_VolumeType: volumeAliasSSD,
})
return []*storage.Config{ssdPool}
} | go | func (e *ebsProvider) DefaultPools() []*storage.Config {
ssdPool, _ := storage.NewConfig("ebs-ssd", EBS_ProviderType, map[string]interface{}{
EBS_VolumeType: volumeAliasSSD,
})
return []*storage.Config{ssdPool}
} | [
"func",
"(",
"e",
"*",
"ebsProvider",
")",
"DefaultPools",
"(",
")",
"[",
"]",
"*",
"storage",
".",
"Config",
"{",
"ssdPool",
",",
"_",
":=",
"storage",
".",
"NewConfig",
"(",
"\"",
"\"",
",",
"EBS_ProviderType",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"EBS_VolumeType",
":",
"volumeAliasSSD",
",",
"}",
")",
"\n",
"return",
"[",
"]",
"*",
"storage",
".",
"Config",
"{",
"ssdPool",
"}",
"\n",
"}"
] | // DefaultPools is defined on the Provider interface. | [
"DefaultPools",
"is",
"defined",
"on",
"the",
"Provider",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/ebs.go#L259-L264 |
154,531 | juju/juju | provider/ec2/ebs.go | parseVolumeOptions | func parseVolumeOptions(size uint64, attrs map[string]interface{}) (_ ec2.CreateVolume, _ error) {
ebsConfig, err := newEbsConfig(attrs)
if err != nil {
return ec2.CreateVolume{}, errors.Trace(err)
}
if ebsConfig.iops > maxProvisionedIopsSizeRatio {
return ec2.CreateVolume{}, errors.Errorf(
"specified IOPS ratio is %d/GiB, maximum is %d/GiB",
ebsConfig.iops, maxProvisionedIopsSizeRatio,
)
}
sizeInGib := mibToGib(size)
iops := uint64(ebsConfig.iops) * sizeInGib
if iops > maxProvisionedIops {
iops = maxProvisionedIops
}
vol := ec2.CreateVolume{
// Juju size is MiB, AWS size is GiB.
VolumeSize: int(sizeInGib),
VolumeType: ebsConfig.volumeType,
Encrypted: ebsConfig.encrypted,
IOPS: int64(iops),
}
return vol, nil
} | go | func parseVolumeOptions(size uint64, attrs map[string]interface{}) (_ ec2.CreateVolume, _ error) {
ebsConfig, err := newEbsConfig(attrs)
if err != nil {
return ec2.CreateVolume{}, errors.Trace(err)
}
if ebsConfig.iops > maxProvisionedIopsSizeRatio {
return ec2.CreateVolume{}, errors.Errorf(
"specified IOPS ratio is %d/GiB, maximum is %d/GiB",
ebsConfig.iops, maxProvisionedIopsSizeRatio,
)
}
sizeInGib := mibToGib(size)
iops := uint64(ebsConfig.iops) * sizeInGib
if iops > maxProvisionedIops {
iops = maxProvisionedIops
}
vol := ec2.CreateVolume{
// Juju size is MiB, AWS size is GiB.
VolumeSize: int(sizeInGib),
VolumeType: ebsConfig.volumeType,
Encrypted: ebsConfig.encrypted,
IOPS: int64(iops),
}
return vol, nil
} | [
"func",
"parseVolumeOptions",
"(",
"size",
"uint64",
",",
"attrs",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"_",
"ec2",
".",
"CreateVolume",
",",
"_",
"error",
")",
"{",
"ebsConfig",
",",
"err",
":=",
"newEbsConfig",
"(",
"attrs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ec2",
".",
"CreateVolume",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"ebsConfig",
".",
"iops",
">",
"maxProvisionedIopsSizeRatio",
"{",
"return",
"ec2",
".",
"CreateVolume",
"{",
"}",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ebsConfig",
".",
"iops",
",",
"maxProvisionedIopsSizeRatio",
",",
")",
"\n",
"}",
"\n\n",
"sizeInGib",
":=",
"mibToGib",
"(",
"size",
")",
"\n",
"iops",
":=",
"uint64",
"(",
"ebsConfig",
".",
"iops",
")",
"*",
"sizeInGib",
"\n",
"if",
"iops",
">",
"maxProvisionedIops",
"{",
"iops",
"=",
"maxProvisionedIops",
"\n",
"}",
"\n",
"vol",
":=",
"ec2",
".",
"CreateVolume",
"{",
"// Juju size is MiB, AWS size is GiB.",
"VolumeSize",
":",
"int",
"(",
"sizeInGib",
")",
",",
"VolumeType",
":",
"ebsConfig",
".",
"volumeType",
",",
"Encrypted",
":",
"ebsConfig",
".",
"encrypted",
",",
"IOPS",
":",
"int64",
"(",
"iops",
")",
",",
"}",
"\n",
"return",
"vol",
",",
"nil",
"\n",
"}"
] | // parseVolumeOptions uses storage volume parameters to make a struct used to create volumes. | [
"parseVolumeOptions",
"uses",
"storage",
"volume",
"parameters",
"to",
"make",
"a",
"struct",
"used",
"to",
"create",
"volumes",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/ebs.go#L291-L316 |
154,532 | juju/juju | worker/lease/config.go | Validate | func (config ManagerConfig) Validate() error {
if config.Secretary == nil {
return errors.NotValidf("nil Secretary")
}
if config.Store == nil {
return errors.NotValidf("nil Store")
}
if config.Logger == nil {
return errors.NotValidf("nil Logger")
}
if config.Clock == nil {
return errors.NotValidf("nil Clock")
}
if config.MaxSleep <= 0 {
return errors.NotValidf("non-positive MaxSleep")
}
// TODO: make the PrometheusRegisterer required when we no longer
// have state workers managing leases.
return nil
} | go | func (config ManagerConfig) Validate() error {
if config.Secretary == nil {
return errors.NotValidf("nil Secretary")
}
if config.Store == nil {
return errors.NotValidf("nil Store")
}
if config.Logger == nil {
return errors.NotValidf("nil Logger")
}
if config.Clock == nil {
return errors.NotValidf("nil Clock")
}
if config.MaxSleep <= 0 {
return errors.NotValidf("non-positive MaxSleep")
}
// TODO: make the PrometheusRegisterer required when we no longer
// have state workers managing leases.
return nil
} | [
"func",
"(",
"config",
"ManagerConfig",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"config",
".",
"Secretary",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"Store",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"Logger",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"Clock",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"MaxSleep",
"<=",
"0",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// TODO: make the PrometheusRegisterer required when we no longer",
"// have state workers managing leases.",
"return",
"nil",
"\n",
"}"
] | // Validate returns an error if the configuration contains invalid information
// or missing resources. | [
"Validate",
"returns",
"an",
"error",
"if",
"the",
"configuration",
"contains",
"invalid",
"information",
"or",
"missing",
"resources",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/lease/config.go#L71-L90 |
154,533 | juju/juju | worker/logsender/bufferedlogwriter.go | InstallBufferedLogWriter | func InstallBufferedLogWriter(maxLen int) (*BufferedLogWriter, error) {
writer := NewBufferedLogWriter(maxLen)
err := loggo.RegisterWriter(writerName, writer)
if err != nil {
return nil, errors.Annotate(err, "failed to set up log buffering")
}
return writer, nil
} | go | func InstallBufferedLogWriter(maxLen int) (*BufferedLogWriter, error) {
writer := NewBufferedLogWriter(maxLen)
err := loggo.RegisterWriter(writerName, writer)
if err != nil {
return nil, errors.Annotate(err, "failed to set up log buffering")
}
return writer, nil
} | [
"func",
"InstallBufferedLogWriter",
"(",
"maxLen",
"int",
")",
"(",
"*",
"BufferedLogWriter",
",",
"error",
")",
"{",
"writer",
":=",
"NewBufferedLogWriter",
"(",
"maxLen",
")",
"\n",
"err",
":=",
"loggo",
".",
"RegisterWriter",
"(",
"writerName",
",",
"writer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"writer",
",",
"nil",
"\n",
"}"
] | // InstallBufferedLogWriter creates and returns a new BufferedLogWriter,
// registering it with Loggo. | [
"InstallBufferedLogWriter",
"creates",
"and",
"returns",
"a",
"new",
"BufferedLogWriter",
"registering",
"it",
"with",
"Loggo",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/logsender/bufferedlogwriter.go#L50-L57 |
154,534 | juju/juju | worker/logsender/bufferedlogwriter.go | UninstallBufferedLogWriter | func UninstallBufferedLogWriter() error {
writer, err := loggo.RemoveWriter(writerName)
if err != nil {
return errors.Annotate(err, "failed to uninstall log buffering")
}
bufWriter, ok := writer.(*BufferedLogWriter)
if !ok {
return errors.New("unexpected writer installed as buffered log writer")
}
bufWriter.Close()
return nil
} | go | func UninstallBufferedLogWriter() error {
writer, err := loggo.RemoveWriter(writerName)
if err != nil {
return errors.Annotate(err, "failed to uninstall log buffering")
}
bufWriter, ok := writer.(*BufferedLogWriter)
if !ok {
return errors.New("unexpected writer installed as buffered log writer")
}
bufWriter.Close()
return nil
} | [
"func",
"UninstallBufferedLogWriter",
"(",
")",
"error",
"{",
"writer",
",",
"err",
":=",
"loggo",
".",
"RemoveWriter",
"(",
"writerName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"bufWriter",
",",
"ok",
":=",
"writer",
".",
"(",
"*",
"BufferedLogWriter",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"bufWriter",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // UninstallBufferedLogWriter removes the BufferedLogWriter previously
// installed by InstallBufferedLogWriter and closes it. | [
"UninstallBufferedLogWriter",
"removes",
"the",
"BufferedLogWriter",
"previously",
"installed",
"by",
"InstallBufferedLogWriter",
"and",
"closes",
"it",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/logsender/bufferedlogwriter.go#L61-L72 |
154,535 | juju/juju | worker/logsender/bufferedlogwriter.go | NewBufferedLogWriter | func NewBufferedLogWriter(maxLen int) *BufferedLogWriter {
w := &BufferedLogWriter{
maxLen: maxLen,
in: make(LogRecordCh),
out: make(LogRecordCh),
}
go w.loop()
return w
} | go | func NewBufferedLogWriter(maxLen int) *BufferedLogWriter {
w := &BufferedLogWriter{
maxLen: maxLen,
in: make(LogRecordCh),
out: make(LogRecordCh),
}
go w.loop()
return w
} | [
"func",
"NewBufferedLogWriter",
"(",
"maxLen",
"int",
")",
"*",
"BufferedLogWriter",
"{",
"w",
":=",
"&",
"BufferedLogWriter",
"{",
"maxLen",
":",
"maxLen",
",",
"in",
":",
"make",
"(",
"LogRecordCh",
")",
",",
"out",
":",
"make",
"(",
"LogRecordCh",
")",
",",
"}",
"\n",
"go",
"w",
".",
"loop",
"(",
")",
"\n",
"return",
"w",
"\n",
"}"
] | // NewBufferedLogWriter returns a new BufferedLogWriter which will
// cache up to maxLen log messages. | [
"NewBufferedLogWriter",
"returns",
"a",
"new",
"BufferedLogWriter",
"which",
"will",
"cache",
"up",
"to",
"maxLen",
"log",
"messages",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/logsender/bufferedlogwriter.go#L91-L99 |
154,536 | juju/juju | worker/logsender/bufferedlogwriter.go | Write | func (w *BufferedLogWriter) Write(entry loggo.Entry) {
w.in <- &LogRecord{
Time: entry.Timestamp,
Module: entry.Module,
Location: fmt.Sprintf("%s:%d", filepath.Base(entry.Filename), entry.Line),
Level: entry.Level,
Message: entry.Message,
}
} | go | func (w *BufferedLogWriter) Write(entry loggo.Entry) {
w.in <- &LogRecord{
Time: entry.Timestamp,
Module: entry.Module,
Location: fmt.Sprintf("%s:%d", filepath.Base(entry.Filename), entry.Line),
Level: entry.Level,
Message: entry.Message,
}
} | [
"func",
"(",
"w",
"*",
"BufferedLogWriter",
")",
"Write",
"(",
"entry",
"loggo",
".",
"Entry",
")",
"{",
"w",
".",
"in",
"<-",
"&",
"LogRecord",
"{",
"Time",
":",
"entry",
".",
"Timestamp",
",",
"Module",
":",
"entry",
".",
"Module",
",",
"Location",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"filepath",
".",
"Base",
"(",
"entry",
".",
"Filename",
")",
",",
"entry",
".",
"Line",
")",
",",
"Level",
":",
"entry",
".",
"Level",
",",
"Message",
":",
"entry",
".",
"Message",
",",
"}",
"\n",
"}"
] | // Write sends a new log message to the writer. This implements the loggo.Writer interface. | [
"Write",
"sends",
"a",
"new",
"log",
"message",
"to",
"the",
"writer",
".",
"This",
"implements",
"the",
"loggo",
".",
"Writer",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/logsender/bufferedlogwriter.go#L149-L157 |
154,537 | juju/juju | worker/logsender/bufferedlogwriter.go | Stats | func (w *BufferedLogWriter) Stats() LogStats {
w.mu.Lock()
defer w.mu.Unlock()
return w.stats
} | go | func (w *BufferedLogWriter) Stats() LogStats {
w.mu.Lock()
defer w.mu.Unlock()
return w.stats
} | [
"func",
"(",
"w",
"*",
"BufferedLogWriter",
")",
"Stats",
"(",
")",
"LogStats",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"w",
".",
"stats",
"\n",
"}"
] | // Stats returns the current LogStats for this BufferedLogWriter. | [
"Stats",
"returns",
"the",
"current",
"LogStats",
"for",
"this",
"BufferedLogWriter",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/logsender/bufferedlogwriter.go#L171-L175 |
154,538 | juju/juju | core/settings/settings.go | String | func (c *ItemChange) String() string {
switch c.Type {
case added:
return fmt.Sprintf("setting added: %v = %v", c.Key, c.NewValue)
case modified:
return fmt.Sprintf("setting modified: %v = %v (was %v)",
c.Key, c.NewValue, c.OldValue)
case deleted:
return fmt.Sprintf("setting deleted: %v (was %v)", c.Key, c.OldValue)
}
return fmt.Sprintf("unknown setting change type %d: %v = %v (was %v)", c.Type, c.Key, c.NewValue, c.OldValue)
} | go | func (c *ItemChange) String() string {
switch c.Type {
case added:
return fmt.Sprintf("setting added: %v = %v", c.Key, c.NewValue)
case modified:
return fmt.Sprintf("setting modified: %v = %v (was %v)",
c.Key, c.NewValue, c.OldValue)
case deleted:
return fmt.Sprintf("setting deleted: %v (was %v)", c.Key, c.OldValue)
}
return fmt.Sprintf("unknown setting change type %d: %v = %v (was %v)", c.Type, c.Key, c.NewValue, c.OldValue)
} | [
"func",
"(",
"c",
"*",
"ItemChange",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"c",
".",
"Type",
"{",
"case",
"added",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Key",
",",
"c",
".",
"NewValue",
")",
"\n",
"case",
"modified",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Key",
",",
"c",
".",
"NewValue",
",",
"c",
".",
"OldValue",
")",
"\n",
"case",
"deleted",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Key",
",",
"c",
".",
"OldValue",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Type",
",",
"c",
".",
"Key",
",",
"c",
".",
"NewValue",
",",
"c",
".",
"OldValue",
")",
"\n",
"}"
] | // String returns the item change in a readable format. | [
"String",
"returns",
"the",
"item",
"change",
"in",
"a",
"readable",
"format",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/settings/settings.go#L51-L62 |
154,539 | juju/juju | core/settings/settings.go | MakeAddition | func MakeAddition(key string, newVal interface{}) ItemChange {
return ItemChange{
Type: added,
Key: key,
NewValue: newVal,
}
} | go | func MakeAddition(key string, newVal interface{}) ItemChange {
return ItemChange{
Type: added,
Key: key,
NewValue: newVal,
}
} | [
"func",
"MakeAddition",
"(",
"key",
"string",
",",
"newVal",
"interface",
"{",
"}",
")",
"ItemChange",
"{",
"return",
"ItemChange",
"{",
"Type",
":",
"added",
",",
"Key",
":",
"key",
",",
"NewValue",
":",
"newVal",
",",
"}",
"\n",
"}"
] | // MakeAddition returns an itemChange indicating a modification of the input
// key, with its new value. | [
"MakeAddition",
"returns",
"an",
"itemChange",
"indicating",
"a",
"modification",
"of",
"the",
"input",
"key",
"with",
"its",
"new",
"value",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/settings/settings.go#L66-L72 |
154,540 | juju/juju | core/settings/settings.go | MakeModification | func MakeModification(key string, oldVal, newVal interface{}) ItemChange {
return ItemChange{
Type: modified,
Key: key,
OldValue: oldVal,
NewValue: newVal,
}
} | go | func MakeModification(key string, oldVal, newVal interface{}) ItemChange {
return ItemChange{
Type: modified,
Key: key,
OldValue: oldVal,
NewValue: newVal,
}
} | [
"func",
"MakeModification",
"(",
"key",
"string",
",",
"oldVal",
",",
"newVal",
"interface",
"{",
"}",
")",
"ItemChange",
"{",
"return",
"ItemChange",
"{",
"Type",
":",
"modified",
",",
"Key",
":",
"key",
",",
"OldValue",
":",
"oldVal",
",",
"NewValue",
":",
"newVal",
",",
"}",
"\n",
"}"
] | // MakeModification returns an ItemChange indicating a modification of the
// input key, with its old and new values. | [
"MakeModification",
"returns",
"an",
"ItemChange",
"indicating",
"a",
"modification",
"of",
"the",
"input",
"key",
"with",
"its",
"old",
"and",
"new",
"values",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/settings/settings.go#L76-L83 |
154,541 | juju/juju | core/settings/settings.go | MakeDeletion | func MakeDeletion(key string, oldVal interface{}) ItemChange {
return ItemChange{
Type: deleted,
Key: key,
OldValue: oldVal,
}
} | go | func MakeDeletion(key string, oldVal interface{}) ItemChange {
return ItemChange{
Type: deleted,
Key: key,
OldValue: oldVal,
}
} | [
"func",
"MakeDeletion",
"(",
"key",
"string",
",",
"oldVal",
"interface",
"{",
"}",
")",
"ItemChange",
"{",
"return",
"ItemChange",
"{",
"Type",
":",
"deleted",
",",
"Key",
":",
"key",
",",
"OldValue",
":",
"oldVal",
",",
"}",
"\n",
"}"
] | // MakeDeletion returns an ItemChange indicating a deletion of the input key,
// with its old value. | [
"MakeDeletion",
"returns",
"an",
"ItemChange",
"indicating",
"a",
"deletion",
"of",
"the",
"input",
"key",
"with",
"its",
"old",
"value",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/settings/settings.go#L87-L93 |
154,542 | juju/juju | core/settings/settings.go | ApplyDeltaSource | func (c ItemChanges) ApplyDeltaSource(oldChanges ItemChanges) (ItemChanges, error) {
m, err := oldChanges.Map()
if err != nil {
return nil, errors.Trace(err)
}
res := make(ItemChanges, len(c))
copy(res, c)
for i, ch := range res {
if old, ok := m[ch.Key]; ok {
switch {
case old.OldValue == nil && ch.IsModification():
// Any previous change with no old value indicates that the key
// was not defined in settings when the branch was created.
// Indicate the modification as an addition.
res[i] = MakeAddition(ch.Key, ch.NewValue)
case old.OldValue != nil && c[i].IsAddition():
// If a setting that existed at branch creation time has been
// deleted and re-added, indicate it as a modification.
res[i] = MakeModification(ch.Key, old.OldValue, ch.NewValue)
default:
// Preserve all old values.
res[i].OldValue = old.OldValue
}
// Remove the map entry to indicate we have dealt with the key.
delete(m, ch.Key)
}
}
// If there is an old change not present in this collection,
// then we know that the setting was reset to its original value.
// If this setting is subsequently reinstated, it is possible to lose the
// original "from" value if master is updated in the meantime.
// So we maintain a no-op entry (same from/to) in order to retain the old
// value from when the configuration setting was first touched.
// These values are not shown to an operator who views a "diff"
// for the branch.
for key, old := range m {
res = append(res, MakeModification(key, old.OldValue, old.OldValue))
}
return res, nil
} | go | func (c ItemChanges) ApplyDeltaSource(oldChanges ItemChanges) (ItemChanges, error) {
m, err := oldChanges.Map()
if err != nil {
return nil, errors.Trace(err)
}
res := make(ItemChanges, len(c))
copy(res, c)
for i, ch := range res {
if old, ok := m[ch.Key]; ok {
switch {
case old.OldValue == nil && ch.IsModification():
// Any previous change with no old value indicates that the key
// was not defined in settings when the branch was created.
// Indicate the modification as an addition.
res[i] = MakeAddition(ch.Key, ch.NewValue)
case old.OldValue != nil && c[i].IsAddition():
// If a setting that existed at branch creation time has been
// deleted and re-added, indicate it as a modification.
res[i] = MakeModification(ch.Key, old.OldValue, ch.NewValue)
default:
// Preserve all old values.
res[i].OldValue = old.OldValue
}
// Remove the map entry to indicate we have dealt with the key.
delete(m, ch.Key)
}
}
// If there is an old change not present in this collection,
// then we know that the setting was reset to its original value.
// If this setting is subsequently reinstated, it is possible to lose the
// original "from" value if master is updated in the meantime.
// So we maintain a no-op entry (same from/to) in order to retain the old
// value from when the configuration setting was first touched.
// These values are not shown to an operator who views a "diff"
// for the branch.
for key, old := range m {
res = append(res, MakeModification(key, old.OldValue, old.OldValue))
}
return res, nil
} | [
"func",
"(",
"c",
"ItemChanges",
")",
"ApplyDeltaSource",
"(",
"oldChanges",
"ItemChanges",
")",
"(",
"ItemChanges",
",",
"error",
")",
"{",
"m",
",",
"err",
":=",
"oldChanges",
".",
"Map",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"res",
":=",
"make",
"(",
"ItemChanges",
",",
"len",
"(",
"c",
")",
")",
"\n",
"copy",
"(",
"res",
",",
"c",
")",
"\n\n",
"for",
"i",
",",
"ch",
":=",
"range",
"res",
"{",
"if",
"old",
",",
"ok",
":=",
"m",
"[",
"ch",
".",
"Key",
"]",
";",
"ok",
"{",
"switch",
"{",
"case",
"old",
".",
"OldValue",
"==",
"nil",
"&&",
"ch",
".",
"IsModification",
"(",
")",
":",
"// Any previous change with no old value indicates that the key",
"// was not defined in settings when the branch was created.",
"// Indicate the modification as an addition.",
"res",
"[",
"i",
"]",
"=",
"MakeAddition",
"(",
"ch",
".",
"Key",
",",
"ch",
".",
"NewValue",
")",
"\n",
"case",
"old",
".",
"OldValue",
"!=",
"nil",
"&&",
"c",
"[",
"i",
"]",
".",
"IsAddition",
"(",
")",
":",
"// If a setting that existed at branch creation time has been",
"// deleted and re-added, indicate it as a modification.",
"res",
"[",
"i",
"]",
"=",
"MakeModification",
"(",
"ch",
".",
"Key",
",",
"old",
".",
"OldValue",
",",
"ch",
".",
"NewValue",
")",
"\n",
"default",
":",
"// Preserve all old values.",
"res",
"[",
"i",
"]",
".",
"OldValue",
"=",
"old",
".",
"OldValue",
"\n",
"}",
"\n\n",
"// Remove the map entry to indicate we have dealt with the key.",
"delete",
"(",
"m",
",",
"ch",
".",
"Key",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If there is an old change not present in this collection,",
"// then we know that the setting was reset to its original value.",
"// If this setting is subsequently reinstated, it is possible to lose the",
"// original \"from\" value if master is updated in the meantime.",
"// So we maintain a no-op entry (same from/to) in order to retain the old",
"// value from when the configuration setting was first touched.",
"// These values are not shown to an operator who views a \"diff\"",
"// for the branch.",
"for",
"key",
",",
"old",
":=",
"range",
"m",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"MakeModification",
"(",
"key",
",",
"old",
".",
"OldValue",
",",
"old",
".",
"OldValue",
")",
")",
"\n",
"}",
"\n\n",
"return",
"res",
",",
"nil",
"\n",
"}"
] | // ApplyDeltaSource uses this second-order delta to generate a first-older
// delta.
// It accepts a collection of changes representing a previous state.
// These are combined with the current changes to generate a new collection.
// It addresses a requirement that each branch change should represent the
// "from" state of master config at the time it is first created. | [
"ApplyDeltaSource",
"uses",
"this",
"second",
"-",
"order",
"delta",
"to",
"generate",
"a",
"first",
"-",
"older",
"delta",
".",
"It",
"accepts",
"a",
"collection",
"of",
"changes",
"representing",
"a",
"previous",
"state",
".",
"These",
"are",
"combined",
"with",
"the",
"current",
"changes",
"to",
"generate",
"a",
"new",
"collection",
".",
"It",
"addresses",
"a",
"requirement",
"that",
"each",
"branch",
"change",
"should",
"represent",
"the",
"from",
"state",
"of",
"master",
"config",
"at",
"the",
"time",
"it",
"is",
"first",
"created",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/settings/settings.go#L105-L149 |
154,543 | juju/juju | core/settings/settings.go | CurrentSettings | func (c ItemChanges) CurrentSettings(defaults charm.Settings) map[string]interface{} {
result := make(map[string]interface{})
for _, change := range c {
key := change.Key
switch {
case change.IsModification() && reflect.DeepEqual(change.OldValue, change.NewValue):
// These are placeholders that we do not apply.
// See comment in ApplyDeltaSource, above.
case change.IsDeletion():
result[key] = defaults[key]
default:
result[key] = change.NewValue
}
}
return result
} | go | func (c ItemChanges) CurrentSettings(defaults charm.Settings) map[string]interface{} {
result := make(map[string]interface{})
for _, change := range c {
key := change.Key
switch {
case change.IsModification() && reflect.DeepEqual(change.OldValue, change.NewValue):
// These are placeholders that we do not apply.
// See comment in ApplyDeltaSource, above.
case change.IsDeletion():
result[key] = defaults[key]
default:
result[key] = change.NewValue
}
}
return result
} | [
"func",
"(",
"c",
"ItemChanges",
")",
"CurrentSettings",
"(",
"defaults",
"charm",
".",
"Settings",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"result",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"change",
":=",
"range",
"c",
"{",
"key",
":=",
"change",
".",
"Key",
"\n\n",
"switch",
"{",
"case",
"change",
".",
"IsModification",
"(",
")",
"&&",
"reflect",
".",
"DeepEqual",
"(",
"change",
".",
"OldValue",
",",
"change",
".",
"NewValue",
")",
":",
"// These are placeholders that we do not apply.",
"// See comment in ApplyDeltaSource, above.",
"case",
"change",
".",
"IsDeletion",
"(",
")",
":",
"result",
"[",
"key",
"]",
"=",
"defaults",
"[",
"key",
"]",
"\n",
"default",
":",
"result",
"[",
"key",
"]",
"=",
"change",
".",
"NewValue",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // CurrentSettings returns the current effective values indicated by this set
// of changes. It uses the input default settings to return a value for items
// that have been deleted. | [
"CurrentSettings",
"returns",
"the",
"current",
"effective",
"values",
"indicated",
"by",
"this",
"set",
"of",
"changes",
".",
"It",
"uses",
"the",
"input",
"default",
"settings",
"to",
"return",
"a",
"value",
"for",
"items",
"that",
"have",
"been",
"deleted",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/settings/settings.go#L154-L170 |
154,544 | juju/juju | core/settings/settings.go | Map | func (c ItemChanges) Map() (map[string]ItemChange, error) {
m := make(map[string]ItemChange, len(c))
for _, ch := range c {
k := ch.Key
if _, ok := m[k]; ok {
return nil, errors.Errorf("duplicated key in settings collection: %q", k)
}
m[k] = ch
}
return m, nil
} | go | func (c ItemChanges) Map() (map[string]ItemChange, error) {
m := make(map[string]ItemChange, len(c))
for _, ch := range c {
k := ch.Key
if _, ok := m[k]; ok {
return nil, errors.Errorf("duplicated key in settings collection: %q", k)
}
m[k] = ch
}
return m, nil
} | [
"func",
"(",
"c",
"ItemChanges",
")",
"Map",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"ItemChange",
",",
"error",
")",
"{",
"m",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"ItemChange",
",",
"len",
"(",
"c",
")",
")",
"\n",
"for",
"_",
",",
"ch",
":=",
"range",
"c",
"{",
"k",
":=",
"ch",
".",
"Key",
"\n",
"if",
"_",
",",
"ok",
":=",
"m",
"[",
"k",
"]",
";",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"k",
")",
"\n",
"}",
"\n",
"m",
"[",
"k",
"]",
"=",
"ch",
"\n",
"}",
"\n",
"return",
"m",
",",
"nil",
"\n",
"}"
] | // Map is a convenience method for working with collections of changes.
// It returns a map representation of the change collection,
// indexed with the change key.
// An error return indicates that the collection had duplicate keys. | [
"Map",
"is",
"a",
"convenience",
"method",
"for",
"working",
"with",
"collections",
"of",
"changes",
".",
"It",
"returns",
"a",
"map",
"representation",
"of",
"the",
"change",
"collection",
"indexed",
"with",
"the",
"change",
"key",
".",
"An",
"error",
"return",
"indicates",
"that",
"the",
"collection",
"had",
"duplicate",
"keys",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/settings/settings.go#L176-L186 |
154,545 | juju/juju | apiserver/stateauthenticator/context.go | newAuthContext | func newAuthContext(
st *state.State,
clock clock.Clock,
) (*authContext, error) {
ctxt := &authContext{
st: st,
clock: clock,
localUserInteractions: authentication.NewInteractions(),
}
// Create a bakery service for discharging third-party caveats for
// local user authentication. This service does not persist keys;
// its macaroons should be very short-lived.
localUserThirdPartyBakeryService, _, err := bakeryutil.NewBakeryService(st, nil, nil)
if err != nil {
return nil, errors.Trace(err)
}
ctxt.localUserThirdPartyBakeryService = localUserThirdPartyBakeryService
// Create a bakery service for local user authentication. This service
// persists keys into MongoDB in a TTL collection.
store, err := st.NewBakeryStorage()
if err != nil {
return nil, errors.Trace(err)
}
locator := bakeryutil.BakeryServicePublicKeyLocator{ctxt.localUserThirdPartyBakeryService}
localUserBakeryService, localUserBakeryServiceKey, err := bakeryutil.NewBakeryService(
st, store, locator,
)
if err != nil {
return nil, errors.Trace(err)
}
ctxt.localUserBakeryService = &bakeryutil.ExpirableStorageBakeryService{
localUserBakeryService, localUserBakeryServiceKey, store, locator,
}
return ctxt, nil
} | go | func newAuthContext(
st *state.State,
clock clock.Clock,
) (*authContext, error) {
ctxt := &authContext{
st: st,
clock: clock,
localUserInteractions: authentication.NewInteractions(),
}
// Create a bakery service for discharging third-party caveats for
// local user authentication. This service does not persist keys;
// its macaroons should be very short-lived.
localUserThirdPartyBakeryService, _, err := bakeryutil.NewBakeryService(st, nil, nil)
if err != nil {
return nil, errors.Trace(err)
}
ctxt.localUserThirdPartyBakeryService = localUserThirdPartyBakeryService
// Create a bakery service for local user authentication. This service
// persists keys into MongoDB in a TTL collection.
store, err := st.NewBakeryStorage()
if err != nil {
return nil, errors.Trace(err)
}
locator := bakeryutil.BakeryServicePublicKeyLocator{ctxt.localUserThirdPartyBakeryService}
localUserBakeryService, localUserBakeryServiceKey, err := bakeryutil.NewBakeryService(
st, store, locator,
)
if err != nil {
return nil, errors.Trace(err)
}
ctxt.localUserBakeryService = &bakeryutil.ExpirableStorageBakeryService{
localUserBakeryService, localUserBakeryServiceKey, store, locator,
}
return ctxt, nil
} | [
"func",
"newAuthContext",
"(",
"st",
"*",
"state",
".",
"State",
",",
"clock",
"clock",
".",
"Clock",
",",
")",
"(",
"*",
"authContext",
",",
"error",
")",
"{",
"ctxt",
":=",
"&",
"authContext",
"{",
"st",
":",
"st",
",",
"clock",
":",
"clock",
",",
"localUserInteractions",
":",
"authentication",
".",
"NewInteractions",
"(",
")",
",",
"}",
"\n\n",
"// Create a bakery service for discharging third-party caveats for",
"// local user authentication. This service does not persist keys;",
"// its macaroons should be very short-lived.",
"localUserThirdPartyBakeryService",
",",
"_",
",",
"err",
":=",
"bakeryutil",
".",
"NewBakeryService",
"(",
"st",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"ctxt",
".",
"localUserThirdPartyBakeryService",
"=",
"localUserThirdPartyBakeryService",
"\n\n",
"// Create a bakery service for local user authentication. This service",
"// persists keys into MongoDB in a TTL collection.",
"store",
",",
"err",
":=",
"st",
".",
"NewBakeryStorage",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"locator",
":=",
"bakeryutil",
".",
"BakeryServicePublicKeyLocator",
"{",
"ctxt",
".",
"localUserThirdPartyBakeryService",
"}",
"\n",
"localUserBakeryService",
",",
"localUserBakeryServiceKey",
",",
"err",
":=",
"bakeryutil",
".",
"NewBakeryService",
"(",
"st",
",",
"store",
",",
"locator",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"ctxt",
".",
"localUserBakeryService",
"=",
"&",
"bakeryutil",
".",
"ExpirableStorageBakeryService",
"{",
"localUserBakeryService",
",",
"localUserBakeryServiceKey",
",",
"store",
",",
"locator",
",",
"}",
"\n",
"return",
"ctxt",
",",
"nil",
"\n",
"}"
] | // newAuthContext creates a new authentication context for st. | [
"newAuthContext",
"creates",
"a",
"new",
"authentication",
"context",
"for",
"st",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/stateauthenticator/context.go#L59-L95 |
154,546 | juju/juju | apiserver/stateauthenticator/context.go | authenticator | func (ctxt *authContext) authenticator(serverHost string) authenticator {
return authenticator{ctxt: ctxt, serverHost: serverHost}
} | go | func (ctxt *authContext) authenticator(serverHost string) authenticator {
return authenticator{ctxt: ctxt, serverHost: serverHost}
} | [
"func",
"(",
"ctxt",
"*",
"authContext",
")",
"authenticator",
"(",
"serverHost",
"string",
")",
"authenticator",
"{",
"return",
"authenticator",
"{",
"ctxt",
":",
"ctxt",
",",
"serverHost",
":",
"serverHost",
"}",
"\n",
"}"
] | // authenticator returns an authenticator.EntityAuthenticator for the API
// connection associated with the specified API server host. | [
"authenticator",
"returns",
"an",
"authenticator",
".",
"EntityAuthenticator",
"for",
"the",
"API",
"connection",
"associated",
"with",
"the",
"specified",
"API",
"server",
"host",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/stateauthenticator/context.go#L124-L126 |
154,547 | juju/juju | apiserver/stateauthenticator/context.go | Authenticate | func (a authenticator) Authenticate(
entityFinder authentication.EntityFinder,
tag names.Tag,
req params.LoginRequest,
) (state.Entity, error) {
auth, err := a.authenticatorForTag(tag)
if err != nil {
return nil, errors.Trace(err)
}
return auth.Authenticate(entityFinder, tag, req)
} | go | func (a authenticator) Authenticate(
entityFinder authentication.EntityFinder,
tag names.Tag,
req params.LoginRequest,
) (state.Entity, error) {
auth, err := a.authenticatorForTag(tag)
if err != nil {
return nil, errors.Trace(err)
}
return auth.Authenticate(entityFinder, tag, req)
} | [
"func",
"(",
"a",
"authenticator",
")",
"Authenticate",
"(",
"entityFinder",
"authentication",
".",
"EntityFinder",
",",
"tag",
"names",
".",
"Tag",
",",
"req",
"params",
".",
"LoginRequest",
",",
")",
"(",
"state",
".",
"Entity",
",",
"error",
")",
"{",
"auth",
",",
"err",
":=",
"a",
".",
"authenticatorForTag",
"(",
"tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"auth",
".",
"Authenticate",
"(",
"entityFinder",
",",
"tag",
",",
"req",
")",
"\n",
"}"
] | // Authenticate implements authentication.EntityAuthenticator
// by choosing the right kind of authentication for the given
// tag. | [
"Authenticate",
"implements",
"authentication",
".",
"EntityAuthenticator",
"by",
"choosing",
"the",
"right",
"kind",
"of",
"authentication",
"for",
"the",
"given",
"tag",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/stateauthenticator/context.go#L138-L148 |
154,548 | juju/juju | apiserver/stateauthenticator/context.go | authenticatorForTag | func (a authenticator) authenticatorForTag(tag names.Tag) (authentication.EntityAuthenticator, error) {
if tag == nil {
auth, err := a.ctxt.externalMacaroonAuth()
if errors.Cause(err) == errMacaroonAuthNotConfigured {
err = errors.Trace(common.ErrNoCreds)
}
if err != nil {
return nil, errors.Trace(err)
}
return auth, nil
}
switch tag.Kind() {
case names.UnitTagKind, names.MachineTagKind, names.ApplicationTagKind:
return &a.ctxt.agentAuth, nil
case names.UserTagKind:
return a.localUserAuth(), nil
default:
return nil, errors.Annotatef(common.ErrBadRequest, "unexpected login entity tag")
}
} | go | func (a authenticator) authenticatorForTag(tag names.Tag) (authentication.EntityAuthenticator, error) {
if tag == nil {
auth, err := a.ctxt.externalMacaroonAuth()
if errors.Cause(err) == errMacaroonAuthNotConfigured {
err = errors.Trace(common.ErrNoCreds)
}
if err != nil {
return nil, errors.Trace(err)
}
return auth, nil
}
switch tag.Kind() {
case names.UnitTagKind, names.MachineTagKind, names.ApplicationTagKind:
return &a.ctxt.agentAuth, nil
case names.UserTagKind:
return a.localUserAuth(), nil
default:
return nil, errors.Annotatef(common.ErrBadRequest, "unexpected login entity tag")
}
} | [
"func",
"(",
"a",
"authenticator",
")",
"authenticatorForTag",
"(",
"tag",
"names",
".",
"Tag",
")",
"(",
"authentication",
".",
"EntityAuthenticator",
",",
"error",
")",
"{",
"if",
"tag",
"==",
"nil",
"{",
"auth",
",",
"err",
":=",
"a",
".",
"ctxt",
".",
"externalMacaroonAuth",
"(",
")",
"\n",
"if",
"errors",
".",
"Cause",
"(",
"err",
")",
"==",
"errMacaroonAuthNotConfigured",
"{",
"err",
"=",
"errors",
".",
"Trace",
"(",
"common",
".",
"ErrNoCreds",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"auth",
",",
"nil",
"\n",
"}",
"\n",
"switch",
"tag",
".",
"Kind",
"(",
")",
"{",
"case",
"names",
".",
"UnitTagKind",
",",
"names",
".",
"MachineTagKind",
",",
"names",
".",
"ApplicationTagKind",
":",
"return",
"&",
"a",
".",
"ctxt",
".",
"agentAuth",
",",
"nil",
"\n",
"case",
"names",
".",
"UserTagKind",
":",
"return",
"a",
".",
"localUserAuth",
"(",
")",
",",
"nil",
"\n",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"common",
".",
"ErrBadRequest",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // authenticatorForTag returns the authenticator appropriate
// to use for a login with the given possibly-nil tag. | [
"authenticatorForTag",
"returns",
"the",
"authenticator",
"appropriate",
"to",
"use",
"for",
"a",
"login",
"with",
"the",
"given",
"possibly",
"-",
"nil",
"tag",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/stateauthenticator/context.go#L152-L171 |
154,549 | juju/juju | apiserver/stateauthenticator/context.go | localUserAuth | func (a authenticator) localUserAuth() *authentication.UserAuthenticator {
localUserIdentityLocation := url.URL{
Scheme: "https",
Host: a.serverHost,
Path: localUserIdentityLocationPath,
}
return &authentication.UserAuthenticator{
Service: a.ctxt.localUserBakeryService,
Clock: a.ctxt.clock,
LocalUserIdentityLocation: localUserIdentityLocation.String(),
}
} | go | func (a authenticator) localUserAuth() *authentication.UserAuthenticator {
localUserIdentityLocation := url.URL{
Scheme: "https",
Host: a.serverHost,
Path: localUserIdentityLocationPath,
}
return &authentication.UserAuthenticator{
Service: a.ctxt.localUserBakeryService,
Clock: a.ctxt.clock,
LocalUserIdentityLocation: localUserIdentityLocation.String(),
}
} | [
"func",
"(",
"a",
"authenticator",
")",
"localUserAuth",
"(",
")",
"*",
"authentication",
".",
"UserAuthenticator",
"{",
"localUserIdentityLocation",
":=",
"url",
".",
"URL",
"{",
"Scheme",
":",
"\"",
"\"",
",",
"Host",
":",
"a",
".",
"serverHost",
",",
"Path",
":",
"localUserIdentityLocationPath",
",",
"}",
"\n",
"return",
"&",
"authentication",
".",
"UserAuthenticator",
"{",
"Service",
":",
"a",
".",
"ctxt",
".",
"localUserBakeryService",
",",
"Clock",
":",
"a",
".",
"ctxt",
".",
"clock",
",",
"LocalUserIdentityLocation",
":",
"localUserIdentityLocation",
".",
"String",
"(",
")",
",",
"}",
"\n",
"}"
] | // localUserAuth returns an authenticator that can authenticate logins for
// local users with either passwords or macaroons. | [
"localUserAuth",
"returns",
"an",
"authenticator",
"that",
"can",
"authenticate",
"logins",
"for",
"local",
"users",
"with",
"either",
"passwords",
"or",
"macaroons",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/stateauthenticator/context.go#L175-L186 |
154,550 | juju/juju | apiserver/stateauthenticator/context.go | externalMacaroonAuth | func (ctxt *authContext) externalMacaroonAuth() (authentication.EntityAuthenticator, error) {
ctxt.macaroonAuthOnce.Do(func() {
ctxt._macaroonAuth, ctxt._macaroonAuthError = newExternalMacaroonAuth(ctxt.st)
})
if ctxt._macaroonAuth == nil {
return nil, errors.Trace(ctxt._macaroonAuthError)
}
return ctxt._macaroonAuth, nil
} | go | func (ctxt *authContext) externalMacaroonAuth() (authentication.EntityAuthenticator, error) {
ctxt.macaroonAuthOnce.Do(func() {
ctxt._macaroonAuth, ctxt._macaroonAuthError = newExternalMacaroonAuth(ctxt.st)
})
if ctxt._macaroonAuth == nil {
return nil, errors.Trace(ctxt._macaroonAuthError)
}
return ctxt._macaroonAuth, nil
} | [
"func",
"(",
"ctxt",
"*",
"authContext",
")",
"externalMacaroonAuth",
"(",
")",
"(",
"authentication",
".",
"EntityAuthenticator",
",",
"error",
")",
"{",
"ctxt",
".",
"macaroonAuthOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"ctxt",
".",
"_macaroonAuth",
",",
"ctxt",
".",
"_macaroonAuthError",
"=",
"newExternalMacaroonAuth",
"(",
"ctxt",
".",
"st",
")",
"\n",
"}",
")",
"\n",
"if",
"ctxt",
".",
"_macaroonAuth",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"ctxt",
".",
"_macaroonAuthError",
")",
"\n",
"}",
"\n",
"return",
"ctxt",
".",
"_macaroonAuth",
",",
"nil",
"\n",
"}"
] | // externalMacaroonAuth returns an authenticator that can authenticate macaroon-based
// logins for external users. If it fails once, it will always fail. | [
"externalMacaroonAuth",
"returns",
"an",
"authenticator",
"that",
"can",
"authenticate",
"macaroon",
"-",
"based",
"logins",
"for",
"external",
"users",
".",
"If",
"it",
"fails",
"once",
"it",
"will",
"always",
"fail",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/stateauthenticator/context.go#L190-L198 |
154,551 | juju/juju | apiserver/stateauthenticator/context.go | newExternalMacaroonAuth | func newExternalMacaroonAuth(st *state.State) (*authentication.ExternalMacaroonAuthenticator, error) {
controllerCfg, err := st.ControllerConfig()
if err != nil {
return nil, errors.Annotate(err, "cannot get model config")
}
idURL := controllerCfg.IdentityURL()
if idURL == "" {
return nil, errMacaroonAuthNotConfigured
}
var locator bakery.PublicKeyLocator
// The identity server has been configured,
// so configure the bakery service appropriately.
idPK := controllerCfg.IdentityPublicKey()
if idPK != nil {
locator = bakery.PublicKeyLocatorMap{idURL: idPK}
} else {
// No public key supplied - retrieve it from the identity manager on demand.
// Note that we don't fetch it immediately because then we'll fail
// forever if the initial fetch fails (because newExternalMacaroonAuth
// only ever called once).
locator = httpbakery.NewPublicKeyRing(nil, nil)
}
// We pass in nil for the storage, which leads to in-memory storage
// being used. We only use in-memory storage for now, since we never
// expire the keys, and don't want garbage to accumulate.
//
// TODO(axw) we should store the key in mongo, so that multiple servers
// can authenticate. That will require that we encode the server's ID
// in the macaroon ID so that servers don't overwrite each others' keys.
svc, _, err := bakeryutil.NewBakeryService(st, nil, locator)
if err != nil {
return nil, errors.Annotate(err, "cannot make bakery service")
}
var auth authentication.ExternalMacaroonAuthenticator
auth.Service = svc
auth.Macaroon, err = svc.NewMacaroon(nil)
if err != nil {
return nil, errors.Annotate(err, "cannot make macaroon")
}
auth.IdentityLocation = idURL
return &auth, nil
} | go | func newExternalMacaroonAuth(st *state.State) (*authentication.ExternalMacaroonAuthenticator, error) {
controllerCfg, err := st.ControllerConfig()
if err != nil {
return nil, errors.Annotate(err, "cannot get model config")
}
idURL := controllerCfg.IdentityURL()
if idURL == "" {
return nil, errMacaroonAuthNotConfigured
}
var locator bakery.PublicKeyLocator
// The identity server has been configured,
// so configure the bakery service appropriately.
idPK := controllerCfg.IdentityPublicKey()
if idPK != nil {
locator = bakery.PublicKeyLocatorMap{idURL: idPK}
} else {
// No public key supplied - retrieve it from the identity manager on demand.
// Note that we don't fetch it immediately because then we'll fail
// forever if the initial fetch fails (because newExternalMacaroonAuth
// only ever called once).
locator = httpbakery.NewPublicKeyRing(nil, nil)
}
// We pass in nil for the storage, which leads to in-memory storage
// being used. We only use in-memory storage for now, since we never
// expire the keys, and don't want garbage to accumulate.
//
// TODO(axw) we should store the key in mongo, so that multiple servers
// can authenticate. That will require that we encode the server's ID
// in the macaroon ID so that servers don't overwrite each others' keys.
svc, _, err := bakeryutil.NewBakeryService(st, nil, locator)
if err != nil {
return nil, errors.Annotate(err, "cannot make bakery service")
}
var auth authentication.ExternalMacaroonAuthenticator
auth.Service = svc
auth.Macaroon, err = svc.NewMacaroon(nil)
if err != nil {
return nil, errors.Annotate(err, "cannot make macaroon")
}
auth.IdentityLocation = idURL
return &auth, nil
} | [
"func",
"newExternalMacaroonAuth",
"(",
"st",
"*",
"state",
".",
"State",
")",
"(",
"*",
"authentication",
".",
"ExternalMacaroonAuthenticator",
",",
"error",
")",
"{",
"controllerCfg",
",",
"err",
":=",
"st",
".",
"ControllerConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"idURL",
":=",
"controllerCfg",
".",
"IdentityURL",
"(",
")",
"\n",
"if",
"idURL",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errMacaroonAuthNotConfigured",
"\n",
"}",
"\n",
"var",
"locator",
"bakery",
".",
"PublicKeyLocator",
"\n",
"// The identity server has been configured,",
"// so configure the bakery service appropriately.",
"idPK",
":=",
"controllerCfg",
".",
"IdentityPublicKey",
"(",
")",
"\n",
"if",
"idPK",
"!=",
"nil",
"{",
"locator",
"=",
"bakery",
".",
"PublicKeyLocatorMap",
"{",
"idURL",
":",
"idPK",
"}",
"\n",
"}",
"else",
"{",
"// No public key supplied - retrieve it from the identity manager on demand.",
"// Note that we don't fetch it immediately because then we'll fail",
"// forever if the initial fetch fails (because newExternalMacaroonAuth",
"// only ever called once).",
"locator",
"=",
"httpbakery",
".",
"NewPublicKeyRing",
"(",
"nil",
",",
"nil",
")",
"\n",
"}",
"\n",
"// We pass in nil for the storage, which leads to in-memory storage",
"// being used. We only use in-memory storage for now, since we never",
"// expire the keys, and don't want garbage to accumulate.",
"//",
"// TODO(axw) we should store the key in mongo, so that multiple servers",
"// can authenticate. That will require that we encode the server's ID",
"// in the macaroon ID so that servers don't overwrite each others' keys.",
"svc",
",",
"_",
",",
"err",
":=",
"bakeryutil",
".",
"NewBakeryService",
"(",
"st",
",",
"nil",
",",
"locator",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"var",
"auth",
"authentication",
".",
"ExternalMacaroonAuthenticator",
"\n",
"auth",
".",
"Service",
"=",
"svc",
"\n",
"auth",
".",
"Macaroon",
",",
"err",
"=",
"svc",
".",
"NewMacaroon",
"(",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"auth",
".",
"IdentityLocation",
"=",
"idURL",
"\n",
"return",
"&",
"auth",
",",
"nil",
"\n",
"}"
] | // newExternalMacaroonAuth returns an authenticator that can authenticate
// macaroon-based logins for external users. This is just a helper function
// for authCtxt.externalMacaroonAuth. | [
"newExternalMacaroonAuth",
"returns",
"an",
"authenticator",
"that",
"can",
"authenticate",
"macaroon",
"-",
"based",
"logins",
"for",
"external",
"users",
".",
"This",
"is",
"just",
"a",
"helper",
"function",
"for",
"authCtxt",
".",
"externalMacaroonAuth",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/stateauthenticator/context.go#L205-L246 |
154,552 | juju/juju | state/status.go | LoadModelStatus | func (m *Model) LoadModelStatus() (*ModelStatus, error) {
statuses, closer := m.st.db().GetCollection(statusesC)
defer closer()
var docs []statusDocWithID
err := statuses.Find(nil).All(&docs)
if err != nil {
return nil, errors.Annotate(err, "failed to read status collection")
}
result := &ModelStatus{
model: m,
docs: make(map[string]statusDocWithID),
}
for _, doc := range docs {
id := m.localID(doc.ID)
result.docs[id] = doc
}
return result, nil
} | go | func (m *Model) LoadModelStatus() (*ModelStatus, error) {
statuses, closer := m.st.db().GetCollection(statusesC)
defer closer()
var docs []statusDocWithID
err := statuses.Find(nil).All(&docs)
if err != nil {
return nil, errors.Annotate(err, "failed to read status collection")
}
result := &ModelStatus{
model: m,
docs: make(map[string]statusDocWithID),
}
for _, doc := range docs {
id := m.localID(doc.ID)
result.docs[id] = doc
}
return result, nil
} | [
"func",
"(",
"m",
"*",
"Model",
")",
"LoadModelStatus",
"(",
")",
"(",
"*",
"ModelStatus",
",",
"error",
")",
"{",
"statuses",
",",
"closer",
":=",
"m",
".",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"statusesC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"docs",
"[",
"]",
"statusDocWithID",
"\n",
"err",
":=",
"statuses",
".",
"Find",
"(",
"nil",
")",
".",
"All",
"(",
"&",
"docs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"result",
":=",
"&",
"ModelStatus",
"{",
"model",
":",
"m",
",",
"docs",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"statusDocWithID",
")",
",",
"}",
"\n",
"for",
"_",
",",
"doc",
":=",
"range",
"docs",
"{",
"id",
":=",
"m",
".",
"localID",
"(",
"doc",
".",
"ID",
")",
"\n",
"result",
".",
"docs",
"[",
"id",
"]",
"=",
"doc",
"\n",
"}",
"\n\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // LoadModelStatus retrieves all the status documents for the model
// at once. Used to primarily speed up status. | [
"LoadModelStatus",
"retrieves",
"all",
"the",
"status",
"documents",
"for",
"the",
"model",
"at",
"once",
".",
"Used",
"to",
"primarily",
"speed",
"up",
"status",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L36-L56 |
154,553 | juju/juju | state/status.go | Model | func (m *ModelStatus) Model() (status.StatusInfo, error) {
return m.getStatus(m.model.globalKey(), "model")
} | go | func (m *ModelStatus) Model() (status.StatusInfo, error) {
return m.getStatus(m.model.globalKey(), "model")
} | [
"func",
"(",
"m",
"*",
"ModelStatus",
")",
"Model",
"(",
")",
"(",
"status",
".",
"StatusInfo",
",",
"error",
")",
"{",
"return",
"m",
".",
"getStatus",
"(",
"m",
".",
"model",
".",
"globalKey",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // Model returns the status of the model. | [
"Model",
"returns",
"the",
"status",
"of",
"the",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L75-L77 |
154,554 | juju/juju | state/status.go | MachineAgent | func (m *ModelStatus) MachineAgent(machineID string) (status.StatusInfo, error) {
return m.getStatus(machineGlobalKey(machineID), "machine")
} | go | func (m *ModelStatus) MachineAgent(machineID string) (status.StatusInfo, error) {
return m.getStatus(machineGlobalKey(machineID), "machine")
} | [
"func",
"(",
"m",
"*",
"ModelStatus",
")",
"MachineAgent",
"(",
"machineID",
"string",
")",
"(",
"status",
".",
"StatusInfo",
",",
"error",
")",
"{",
"return",
"m",
".",
"getStatus",
"(",
"machineGlobalKey",
"(",
"machineID",
")",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // MachineAgent returns the status of the machine agent. | [
"MachineAgent",
"returns",
"the",
"status",
"of",
"the",
"machine",
"agent",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L121-L123 |
154,555 | juju/juju | state/status.go | MachineInstance | func (m *ModelStatus) MachineInstance(machineID string) (status.StatusInfo, error) {
return m.getStatus(machineGlobalInstanceKey(machineID), "instance")
} | go | func (m *ModelStatus) MachineInstance(machineID string) (status.StatusInfo, error) {
return m.getStatus(machineGlobalInstanceKey(machineID), "instance")
} | [
"func",
"(",
"m",
"*",
"ModelStatus",
")",
"MachineInstance",
"(",
"machineID",
"string",
")",
"(",
"status",
".",
"StatusInfo",
",",
"error",
")",
"{",
"return",
"m",
".",
"getStatus",
"(",
"machineGlobalInstanceKey",
"(",
"machineID",
")",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // MachineInstance returns the status of the machine instance. | [
"MachineInstance",
"returns",
"the",
"status",
"of",
"the",
"machine",
"instance",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L126-L128 |
154,556 | juju/juju | state/status.go | MachineModification | func (m *ModelStatus) MachineModification(machineID string) (status.StatusInfo, error) {
return m.getStatus(machineGlobalModificationKey(machineID), "modification")
} | go | func (m *ModelStatus) MachineModification(machineID string) (status.StatusInfo, error) {
return m.getStatus(machineGlobalModificationKey(machineID), "modification")
} | [
"func",
"(",
"m",
"*",
"ModelStatus",
")",
"MachineModification",
"(",
"machineID",
"string",
")",
"(",
"status",
".",
"StatusInfo",
",",
"error",
")",
"{",
"return",
"m",
".",
"getStatus",
"(",
"machineGlobalModificationKey",
"(",
"machineID",
")",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // MachineModification returns the status of the machine modification | [
"MachineModification",
"returns",
"the",
"status",
"of",
"the",
"machine",
"modification"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L131-L133 |
154,557 | juju/juju | state/status.go | FullUnitWorkloadVersion | func (m *ModelStatus) FullUnitWorkloadVersion(unitName string) (status.StatusInfo, error) {
return m.getStatus(globalWorkloadVersionKey(unitName), "workload")
} | go | func (m *ModelStatus) FullUnitWorkloadVersion(unitName string) (status.StatusInfo, error) {
return m.getStatus(globalWorkloadVersionKey(unitName), "workload")
} | [
"func",
"(",
"m",
"*",
"ModelStatus",
")",
"FullUnitWorkloadVersion",
"(",
"unitName",
"string",
")",
"(",
"status",
".",
"StatusInfo",
",",
"error",
")",
"{",
"return",
"m",
".",
"getStatus",
"(",
"globalWorkloadVersionKey",
"(",
"unitName",
")",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // FullUnitWorkloadVersion returns the full status info for the workload
// version of a unit. This is used for selecting the workload version for
// an application. | [
"FullUnitWorkloadVersion",
"returns",
"the",
"full",
"status",
"info",
"for",
"the",
"workload",
"version",
"of",
"a",
"unit",
".",
"This",
"is",
"used",
"for",
"selecting",
"the",
"workload",
"version",
"for",
"an",
"application",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L138-L140 |
154,558 | juju/juju | state/status.go | UnitWorkloadVersion | func (m *ModelStatus) UnitWorkloadVersion(unitName string) (string, error) {
info, err := m.getStatus(globalWorkloadVersionKey(unitName), "workload")
if err != nil {
return "", err
}
return info.Message, nil
} | go | func (m *ModelStatus) UnitWorkloadVersion(unitName string) (string, error) {
info, err := m.getStatus(globalWorkloadVersionKey(unitName), "workload")
if err != nil {
return "", err
}
return info.Message, nil
} | [
"func",
"(",
"m",
"*",
"ModelStatus",
")",
"UnitWorkloadVersion",
"(",
"unitName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"info",
",",
"err",
":=",
"m",
".",
"getStatus",
"(",
"globalWorkloadVersionKey",
"(",
"unitName",
")",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"info",
".",
"Message",
",",
"nil",
"\n",
"}"
] | // UnitWorkloadVersion returns workload version for the unit | [
"UnitWorkloadVersion",
"returns",
"workload",
"version",
"for",
"the",
"unit"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L143-L149 |
154,559 | juju/juju | state/status.go | UnitAgent | func (m *ModelStatus) UnitAgent(unitName string) (status.StatusInfo, error) {
// We do horrible things with unit status.
// See notes in unitagent.go.
info, err := m.getStatus(unitAgentGlobalKey(unitName), "agent")
if err != nil {
return info, err
}
if info.Status == status.Error {
return status.StatusInfo{
Status: status.Idle,
Message: "",
Data: map[string]interface{}{},
Since: info.Since,
}, nil
}
return info, nil
} | go | func (m *ModelStatus) UnitAgent(unitName string) (status.StatusInfo, error) {
// We do horrible things with unit status.
// See notes in unitagent.go.
info, err := m.getStatus(unitAgentGlobalKey(unitName), "agent")
if err != nil {
return info, err
}
if info.Status == status.Error {
return status.StatusInfo{
Status: status.Idle,
Message: "",
Data: map[string]interface{}{},
Since: info.Since,
}, nil
}
return info, nil
} | [
"func",
"(",
"m",
"*",
"ModelStatus",
")",
"UnitAgent",
"(",
"unitName",
"string",
")",
"(",
"status",
".",
"StatusInfo",
",",
"error",
")",
"{",
"// We do horrible things with unit status.",
"// See notes in unitagent.go.",
"info",
",",
"err",
":=",
"m",
".",
"getStatus",
"(",
"unitAgentGlobalKey",
"(",
"unitName",
")",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"info",
",",
"err",
"\n",
"}",
"\n",
"if",
"info",
".",
"Status",
"==",
"status",
".",
"Error",
"{",
"return",
"status",
".",
"StatusInfo",
"{",
"Status",
":",
"status",
".",
"Idle",
",",
"Message",
":",
"\"",
"\"",
",",
"Data",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"Since",
":",
"info",
".",
"Since",
",",
"}",
",",
"nil",
"\n",
"}",
"\n",
"return",
"info",
",",
"nil",
"\n",
"}"
] | // UnitAgent returns the status of the Unit's agent. | [
"UnitAgent",
"returns",
"the",
"status",
"of",
"the",
"Unit",
"s",
"agent",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L152-L168 |
154,560 | juju/juju | state/status.go | UnitWorkload | func (m *ModelStatus) UnitWorkload(unitName string, expectWorkload bool) (status.StatusInfo, error) {
// We do horrible things with unit status.
// See notes in unit.go.
info, err := m.getStatus(unitAgentGlobalKey(unitName), "unit")
if err != nil {
return info, err
} else if info.Status == status.Error {
return info, nil
}
// (for CAAS models) Use cloud container status over unit if the cloud
// container status is error or active or the unit status hasn't shifted
// from 'allocating'
info, err = m.getStatus(unitGlobalKey(unitName), "workload")
if err != nil {
return info, errors.Trace(err)
}
if m.model.Type() == ModelTypeIAAS {
return info, nil
}
containerInfo, err := m.getStatus(globalCloudContainerKey(unitName), "cloud container")
if err != nil && !errors.IsNotFound(err) {
return info, err
}
return caasUnitDisplayStatus(info, containerInfo, expectWorkload), nil
} | go | func (m *ModelStatus) UnitWorkload(unitName string, expectWorkload bool) (status.StatusInfo, error) {
// We do horrible things with unit status.
// See notes in unit.go.
info, err := m.getStatus(unitAgentGlobalKey(unitName), "unit")
if err != nil {
return info, err
} else if info.Status == status.Error {
return info, nil
}
// (for CAAS models) Use cloud container status over unit if the cloud
// container status is error or active or the unit status hasn't shifted
// from 'allocating'
info, err = m.getStatus(unitGlobalKey(unitName), "workload")
if err != nil {
return info, errors.Trace(err)
}
if m.model.Type() == ModelTypeIAAS {
return info, nil
}
containerInfo, err := m.getStatus(globalCloudContainerKey(unitName), "cloud container")
if err != nil && !errors.IsNotFound(err) {
return info, err
}
return caasUnitDisplayStatus(info, containerInfo, expectWorkload), nil
} | [
"func",
"(",
"m",
"*",
"ModelStatus",
")",
"UnitWorkload",
"(",
"unitName",
"string",
",",
"expectWorkload",
"bool",
")",
"(",
"status",
".",
"StatusInfo",
",",
"error",
")",
"{",
"// We do horrible things with unit status.",
"// See notes in unit.go.",
"info",
",",
"err",
":=",
"m",
".",
"getStatus",
"(",
"unitAgentGlobalKey",
"(",
"unitName",
")",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"info",
",",
"err",
"\n",
"}",
"else",
"if",
"info",
".",
"Status",
"==",
"status",
".",
"Error",
"{",
"return",
"info",
",",
"nil",
"\n",
"}",
"\n\n",
"// (for CAAS models) Use cloud container status over unit if the cloud",
"// container status is error or active or the unit status hasn't shifted",
"// from 'allocating'",
"info",
",",
"err",
"=",
"m",
".",
"getStatus",
"(",
"unitGlobalKey",
"(",
"unitName",
")",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"info",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"m",
".",
"model",
".",
"Type",
"(",
")",
"==",
"ModelTypeIAAS",
"{",
"return",
"info",
",",
"nil",
"\n",
"}",
"\n\n",
"containerInfo",
",",
"err",
":=",
"m",
".",
"getStatus",
"(",
"globalCloudContainerKey",
"(",
"unitName",
")",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"info",
",",
"err",
"\n",
"}",
"\n",
"return",
"caasUnitDisplayStatus",
"(",
"info",
",",
"containerInfo",
",",
"expectWorkload",
")",
",",
"nil",
"\n",
"}"
] | // UnitWorkload returns the status of the unit's workload. | [
"UnitWorkload",
"returns",
"the",
"status",
"of",
"the",
"unit",
"s",
"workload",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L171-L198 |
154,561 | juju/juju | state/status.go | caasApplicationDisplayStatus | func caasApplicationDisplayStatus(applicationStatus, operatorStatus status.StatusInfo, expectWorkload bool) status.StatusInfo {
if applicationStatus.Status == status.Terminated {
return applicationStatus
}
// Only interested in the operator status if it's not running/active.
if operatorStatus.Status != status.Running && operatorStatus.Status != status.Active {
if operatorStatus.Status == status.Waiting && !expectWorkload {
operatorStatus.Message = status.MessageInitializingAgent
}
return operatorStatus
}
return applicationStatus
} | go | func caasApplicationDisplayStatus(applicationStatus, operatorStatus status.StatusInfo, expectWorkload bool) status.StatusInfo {
if applicationStatus.Status == status.Terminated {
return applicationStatus
}
// Only interested in the operator status if it's not running/active.
if operatorStatus.Status != status.Running && operatorStatus.Status != status.Active {
if operatorStatus.Status == status.Waiting && !expectWorkload {
operatorStatus.Message = status.MessageInitializingAgent
}
return operatorStatus
}
return applicationStatus
} | [
"func",
"caasApplicationDisplayStatus",
"(",
"applicationStatus",
",",
"operatorStatus",
"status",
".",
"StatusInfo",
",",
"expectWorkload",
"bool",
")",
"status",
".",
"StatusInfo",
"{",
"if",
"applicationStatus",
".",
"Status",
"==",
"status",
".",
"Terminated",
"{",
"return",
"applicationStatus",
"\n",
"}",
"\n",
"// Only interested in the operator status if it's not running/active.",
"if",
"operatorStatus",
".",
"Status",
"!=",
"status",
".",
"Running",
"&&",
"operatorStatus",
".",
"Status",
"!=",
"status",
".",
"Active",
"{",
"if",
"operatorStatus",
".",
"Status",
"==",
"status",
".",
"Waiting",
"&&",
"!",
"expectWorkload",
"{",
"operatorStatus",
".",
"Message",
"=",
"status",
".",
"MessageInitializingAgent",
"\n",
"}",
"\n",
"return",
"operatorStatus",
"\n",
"}",
"\n\n",
"return",
"applicationStatus",
"\n",
"}"
] | // caasApplicationDisplayStatus determines which of the two statuses to use when displaying application status in a CAAS model. | [
"caasApplicationDisplayStatus",
"determines",
"which",
"of",
"the",
"two",
"statuses",
"to",
"use",
"when",
"displaying",
"application",
"status",
"in",
"a",
"CAAS",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L257-L270 |
154,562 | juju/juju | state/status.go | caasHistoryRewriteDoc | func caasHistoryRewriteDoc(jujuStatus, caasStatus status.StatusInfo, expectWorkload bool, displayStatus displayStatusFunc, clock clock.Clock) (*statusDoc, error) {
modifiedStatus := displayStatus(jujuStatus, caasStatus, expectWorkload)
if modifiedStatus.Status == jujuStatus.Status && modifiedStatus.Message == jujuStatus.Message {
return nil, nil
}
return &statusDoc{
Status: modifiedStatus.Status,
StatusInfo: modifiedStatus.Message,
StatusData: utils.EscapeKeys(modifiedStatus.Data),
Updated: timeOrNow(modifiedStatus.Since, clock).UnixNano(),
}, nil
} | go | func caasHistoryRewriteDoc(jujuStatus, caasStatus status.StatusInfo, expectWorkload bool, displayStatus displayStatusFunc, clock clock.Clock) (*statusDoc, error) {
modifiedStatus := displayStatus(jujuStatus, caasStatus, expectWorkload)
if modifiedStatus.Status == jujuStatus.Status && modifiedStatus.Message == jujuStatus.Message {
return nil, nil
}
return &statusDoc{
Status: modifiedStatus.Status,
StatusInfo: modifiedStatus.Message,
StatusData: utils.EscapeKeys(modifiedStatus.Data),
Updated: timeOrNow(modifiedStatus.Since, clock).UnixNano(),
}, nil
} | [
"func",
"caasHistoryRewriteDoc",
"(",
"jujuStatus",
",",
"caasStatus",
"status",
".",
"StatusInfo",
",",
"expectWorkload",
"bool",
",",
"displayStatus",
"displayStatusFunc",
",",
"clock",
"clock",
".",
"Clock",
")",
"(",
"*",
"statusDoc",
",",
"error",
")",
"{",
"modifiedStatus",
":=",
"displayStatus",
"(",
"jujuStatus",
",",
"caasStatus",
",",
"expectWorkload",
")",
"\n",
"if",
"modifiedStatus",
".",
"Status",
"==",
"jujuStatus",
".",
"Status",
"&&",
"modifiedStatus",
".",
"Message",
"==",
"jujuStatus",
".",
"Message",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"statusDoc",
"{",
"Status",
":",
"modifiedStatus",
".",
"Status",
",",
"StatusInfo",
":",
"modifiedStatus",
".",
"Message",
",",
"StatusData",
":",
"utils",
".",
"EscapeKeys",
"(",
"modifiedStatus",
".",
"Data",
")",
",",
"Updated",
":",
"timeOrNow",
"(",
"modifiedStatus",
".",
"Since",
",",
"clock",
")",
".",
"UnixNano",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // caasHistoryRewriteDoc determines which status should be stored as history. | [
"caasHistoryRewriteDoc",
"determines",
"which",
"status",
"should",
"be",
"stored",
"as",
"history",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L273-L284 |
154,563 | juju/juju | state/status.go | getStatus | func getStatus(db Database, globalKey, badge string) (_ status.StatusInfo, err error) {
defer errors.DeferredAnnotatef(&err, "cannot get status")
statuses, closer := db.GetCollection(statusesC)
defer closer()
var doc statusDoc
err = statuses.FindId(globalKey).One(&doc)
if err == mgo.ErrNotFound {
return status.StatusInfo{}, errors.NotFoundf(badge)
} else if err != nil {
return status.StatusInfo{}, errors.Trace(err)
}
return status.StatusInfo{
Status: doc.Status,
Message: doc.StatusInfo,
Data: utils.UnescapeKeys(doc.StatusData),
Since: unixNanoToTime(doc.Updated),
}, nil
} | go | func getStatus(db Database, globalKey, badge string) (_ status.StatusInfo, err error) {
defer errors.DeferredAnnotatef(&err, "cannot get status")
statuses, closer := db.GetCollection(statusesC)
defer closer()
var doc statusDoc
err = statuses.FindId(globalKey).One(&doc)
if err == mgo.ErrNotFound {
return status.StatusInfo{}, errors.NotFoundf(badge)
} else if err != nil {
return status.StatusInfo{}, errors.Trace(err)
}
return status.StatusInfo{
Status: doc.Status,
Message: doc.StatusInfo,
Data: utils.UnescapeKeys(doc.StatusData),
Since: unixNanoToTime(doc.Updated),
}, nil
} | [
"func",
"getStatus",
"(",
"db",
"Database",
",",
"globalKey",
",",
"badge",
"string",
")",
"(",
"_",
"status",
".",
"StatusInfo",
",",
"err",
"error",
")",
"{",
"defer",
"errors",
".",
"DeferredAnnotatef",
"(",
"&",
"err",
",",
"\"",
"\"",
")",
"\n",
"statuses",
",",
"closer",
":=",
"db",
".",
"GetCollection",
"(",
"statusesC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"doc",
"statusDoc",
"\n",
"err",
"=",
"statuses",
".",
"FindId",
"(",
"globalKey",
")",
".",
"One",
"(",
"&",
"doc",
")",
"\n",
"if",
"err",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"status",
".",
"StatusInfo",
"{",
"}",
",",
"errors",
".",
"NotFoundf",
"(",
"badge",
")",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"status",
".",
"StatusInfo",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"status",
".",
"StatusInfo",
"{",
"Status",
":",
"doc",
".",
"Status",
",",
"Message",
":",
"doc",
".",
"StatusInfo",
",",
"Data",
":",
"utils",
".",
"UnescapeKeys",
"(",
"doc",
".",
"StatusData",
")",
",",
"Since",
":",
"unixNanoToTime",
"(",
"doc",
".",
"Updated",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // getStatus retrieves the status document associated with the given
// globalKey and converts it to a StatusInfo. If the status document
// is not found, a NotFoundError referencing badge will be returned. | [
"getStatus",
"retrieves",
"the",
"status",
"document",
"associated",
"with",
"the",
"given",
"globalKey",
"and",
"converts",
"it",
"to",
"a",
"StatusInfo",
".",
"If",
"the",
"status",
"document",
"is",
"not",
"found",
"a",
"NotFoundError",
"referencing",
"badge",
"will",
"be",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L336-L355 |
154,564 | juju/juju | state/status.go | setStatus | func setStatus(db Database, params setStatusParams) (err error) {
defer errors.DeferredAnnotatef(&err, "cannot set status")
if params.updated == nil {
return errors.NotValidf("nil updated time")
}
doc := statusDoc{
Status: params.status,
StatusInfo: params.message,
StatusData: utils.EscapeKeys(params.rawData),
Updated: params.updated.UnixNano(),
}
historyDoc := &doc
if params.historyOverwrite != nil {
historyDoc = params.historyOverwrite
}
newStatus, historyErr := probablyUpdateStatusHistory(db, params.globalKey, *historyDoc)
if params.historyOverwrite == nil && (!newStatus && historyErr == nil) {
// If this status is not new (i.e. it is exactly the same as
// our last status), there is no need to update the record.
// Update here will only reset the 'Since' field.
return err
}
// Set the authoritative status document, or fail trying.
var buildTxn jujutxn.TransactionSource = func(int) ([]txn.Op, error) {
return statusSetOps(db, doc, params.globalKey)
}
if params.token != nil {
buildTxn = buildTxnWithLeadership(buildTxn, params.token)
}
err = db.Run(buildTxn)
if cause := errors.Cause(err); cause == mgo.ErrNotFound {
return errors.NotFoundf(params.badge)
}
return errors.Trace(err)
} | go | func setStatus(db Database, params setStatusParams) (err error) {
defer errors.DeferredAnnotatef(&err, "cannot set status")
if params.updated == nil {
return errors.NotValidf("nil updated time")
}
doc := statusDoc{
Status: params.status,
StatusInfo: params.message,
StatusData: utils.EscapeKeys(params.rawData),
Updated: params.updated.UnixNano(),
}
historyDoc := &doc
if params.historyOverwrite != nil {
historyDoc = params.historyOverwrite
}
newStatus, historyErr := probablyUpdateStatusHistory(db, params.globalKey, *historyDoc)
if params.historyOverwrite == nil && (!newStatus && historyErr == nil) {
// If this status is not new (i.e. it is exactly the same as
// our last status), there is no need to update the record.
// Update here will only reset the 'Since' field.
return err
}
// Set the authoritative status document, or fail trying.
var buildTxn jujutxn.TransactionSource = func(int) ([]txn.Op, error) {
return statusSetOps(db, doc, params.globalKey)
}
if params.token != nil {
buildTxn = buildTxnWithLeadership(buildTxn, params.token)
}
err = db.Run(buildTxn)
if cause := errors.Cause(err); cause == mgo.ErrNotFound {
return errors.NotFoundf(params.badge)
}
return errors.Trace(err)
} | [
"func",
"setStatus",
"(",
"db",
"Database",
",",
"params",
"setStatusParams",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"errors",
".",
"DeferredAnnotatef",
"(",
"&",
"err",
",",
"\"",
"\"",
")",
"\n",
"if",
"params",
".",
"updated",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"doc",
":=",
"statusDoc",
"{",
"Status",
":",
"params",
".",
"status",
",",
"StatusInfo",
":",
"params",
".",
"message",
",",
"StatusData",
":",
"utils",
".",
"EscapeKeys",
"(",
"params",
".",
"rawData",
")",
",",
"Updated",
":",
"params",
".",
"updated",
".",
"UnixNano",
"(",
")",
",",
"}",
"\n\n",
"historyDoc",
":=",
"&",
"doc",
"\n",
"if",
"params",
".",
"historyOverwrite",
"!=",
"nil",
"{",
"historyDoc",
"=",
"params",
".",
"historyOverwrite",
"\n",
"}",
"\n\n",
"newStatus",
",",
"historyErr",
":=",
"probablyUpdateStatusHistory",
"(",
"db",
",",
"params",
".",
"globalKey",
",",
"*",
"historyDoc",
")",
"\n",
"if",
"params",
".",
"historyOverwrite",
"==",
"nil",
"&&",
"(",
"!",
"newStatus",
"&&",
"historyErr",
"==",
"nil",
")",
"{",
"// If this status is not new (i.e. it is exactly the same as",
"// our last status), there is no need to update the record.",
"// Update here will only reset the 'Since' field.",
"return",
"err",
"\n",
"}",
"\n\n",
"// Set the authoritative status document, or fail trying.",
"var",
"buildTxn",
"jujutxn",
".",
"TransactionSource",
"=",
"func",
"(",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"return",
"statusSetOps",
"(",
"db",
",",
"doc",
",",
"params",
".",
"globalKey",
")",
"\n",
"}",
"\n",
"if",
"params",
".",
"token",
"!=",
"nil",
"{",
"buildTxn",
"=",
"buildTxnWithLeadership",
"(",
"buildTxn",
",",
"params",
".",
"token",
")",
"\n",
"}",
"\n",
"err",
"=",
"db",
".",
"Run",
"(",
"buildTxn",
")",
"\n",
"if",
"cause",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
";",
"cause",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"errors",
".",
"NotFoundf",
"(",
"params",
".",
"badge",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // setStatus inteprets the supplied params as documented on the type. | [
"setStatus",
"inteprets",
"the",
"supplied",
"params",
"as",
"documented",
"on",
"the",
"type",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L422-L460 |
154,565 | juju/juju | state/status.go | createStatusOp | func createStatusOp(mb modelBackend, globalKey string, doc statusDoc) txn.Op {
return txn.Op{
C: statusesC,
Id: mb.docID(globalKey),
Assert: txn.DocMissing,
Insert: &doc,
}
} | go | func createStatusOp(mb modelBackend, globalKey string, doc statusDoc) txn.Op {
return txn.Op{
C: statusesC,
Id: mb.docID(globalKey),
Assert: txn.DocMissing,
Insert: &doc,
}
} | [
"func",
"createStatusOp",
"(",
"mb",
"modelBackend",
",",
"globalKey",
"string",
",",
"doc",
"statusDoc",
")",
"txn",
".",
"Op",
"{",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"statusesC",
",",
"Id",
":",
"mb",
".",
"docID",
"(",
"globalKey",
")",
",",
"Assert",
":",
"txn",
".",
"DocMissing",
",",
"Insert",
":",
"&",
"doc",
",",
"}",
"\n",
"}"
] | // createStatusOp returns the operation needed to create the given status
// document associated with the given globalKey. | [
"createStatusOp",
"returns",
"the",
"operation",
"needed",
"to",
"create",
"the",
"given",
"status",
"document",
"associated",
"with",
"the",
"given",
"globalKey",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L479-L486 |
154,566 | juju/juju | state/status.go | removeStatusOp | func removeStatusOp(mb modelBackend, globalKey string) txn.Op {
return txn.Op{
C: statusesC,
Id: mb.docID(globalKey),
Remove: true,
}
} | go | func removeStatusOp(mb modelBackend, globalKey string) txn.Op {
return txn.Op{
C: statusesC,
Id: mb.docID(globalKey),
Remove: true,
}
} | [
"func",
"removeStatusOp",
"(",
"mb",
"modelBackend",
",",
"globalKey",
"string",
")",
"txn",
".",
"Op",
"{",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"statusesC",
",",
"Id",
":",
"mb",
".",
"docID",
"(",
"globalKey",
")",
",",
"Remove",
":",
"true",
",",
"}",
"\n",
"}"
] | // removeStatusOp returns the operation needed to remove the status
// document associated with the given globalKey. | [
"removeStatusOp",
"returns",
"the",
"operation",
"needed",
"to",
"remove",
"the",
"status",
"document",
"associated",
"with",
"the",
"given",
"globalKey",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L490-L496 |
154,567 | juju/juju | state/status.go | probablyUpdateStatusHistory | func probablyUpdateStatusHistory(db Database, globalKey string, doc statusDoc) (bool, error) {
historyDoc := &historicalStatusDoc{
Status: doc.Status,
StatusInfo: doc.StatusInfo,
StatusData: doc.StatusData, // coming from a statusDoc, already escaped
Updated: doc.Updated,
GlobalKey: globalKey,
}
history, closer := db.GetCollection(statusesHistoryC)
defer closer()
exists, currentID := statusHistoryExists(db, historyDoc)
if exists {
// If the status values have not changed since the last run,
// update history record with this timestamp
// to keep correct track of when SetStatus ran.
historyW := history.Writeable()
err := historyW.Update(
bson.D{{"_id", currentID}},
bson.D{{"$set", bson.D{{"updated", doc.Updated}}}})
if err != nil {
logger.Errorf("failed to update status history: %v", err)
return false, err
}
return false, nil
}
historyW := history.Writeable()
err := historyW.Insert(historyDoc)
if err != nil {
logger.Errorf("failed to write status history: %v", err)
return false, err
}
return true, nil
} | go | func probablyUpdateStatusHistory(db Database, globalKey string, doc statusDoc) (bool, error) {
historyDoc := &historicalStatusDoc{
Status: doc.Status,
StatusInfo: doc.StatusInfo,
StatusData: doc.StatusData, // coming from a statusDoc, already escaped
Updated: doc.Updated,
GlobalKey: globalKey,
}
history, closer := db.GetCollection(statusesHistoryC)
defer closer()
exists, currentID := statusHistoryExists(db, historyDoc)
if exists {
// If the status values have not changed since the last run,
// update history record with this timestamp
// to keep correct track of when SetStatus ran.
historyW := history.Writeable()
err := historyW.Update(
bson.D{{"_id", currentID}},
bson.D{{"$set", bson.D{{"updated", doc.Updated}}}})
if err != nil {
logger.Errorf("failed to update status history: %v", err)
return false, err
}
return false, nil
}
historyW := history.Writeable()
err := historyW.Insert(historyDoc)
if err != nil {
logger.Errorf("failed to write status history: %v", err)
return false, err
}
return true, nil
} | [
"func",
"probablyUpdateStatusHistory",
"(",
"db",
"Database",
",",
"globalKey",
"string",
",",
"doc",
"statusDoc",
")",
"(",
"bool",
",",
"error",
")",
"{",
"historyDoc",
":=",
"&",
"historicalStatusDoc",
"{",
"Status",
":",
"doc",
".",
"Status",
",",
"StatusInfo",
":",
"doc",
".",
"StatusInfo",
",",
"StatusData",
":",
"doc",
".",
"StatusData",
",",
"// coming from a statusDoc, already escaped",
"Updated",
":",
"doc",
".",
"Updated",
",",
"GlobalKey",
":",
"globalKey",
",",
"}",
"\n",
"history",
",",
"closer",
":=",
"db",
".",
"GetCollection",
"(",
"statusesHistoryC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"exists",
",",
"currentID",
":=",
"statusHistoryExists",
"(",
"db",
",",
"historyDoc",
")",
"\n",
"if",
"exists",
"{",
"// If the status values have not changed since the last run,",
"// update history record with this timestamp",
"// to keep correct track of when SetStatus ran.",
"historyW",
":=",
"history",
".",
"Writeable",
"(",
")",
"\n",
"err",
":=",
"historyW",
".",
"Update",
"(",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"currentID",
"}",
"}",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"doc",
".",
"Updated",
"}",
"}",
"}",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"historyW",
":=",
"history",
".",
"Writeable",
"(",
")",
"\n",
"err",
":=",
"historyW",
".",
"Insert",
"(",
"historyDoc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // probablyUpdateStatusHistory inspects existing status-history
// and determines if this status is new or the same as the last recorded.
// If this is a new status, a new status history record will be added.
// If this status is the same as the last status we've received,
// we update that record to have a new timestamp.
// Status messages are considered to be the same if they only differ in their timestamps.
// The call returns true if a new status history record has been created. | [
"probablyUpdateStatusHistory",
"inspects",
"existing",
"status",
"-",
"history",
"and",
"determines",
"if",
"this",
"status",
"is",
"new",
"or",
"the",
"same",
"as",
"the",
"last",
"recorded",
".",
"If",
"this",
"is",
"a",
"new",
"status",
"a",
"new",
"status",
"history",
"record",
"will",
"be",
"added",
".",
"If",
"this",
"status",
"is",
"the",
"same",
"as",
"the",
"last",
"status",
"we",
"ve",
"received",
"we",
"update",
"that",
"record",
"to",
"have",
"a",
"new",
"timestamp",
".",
"Status",
"messages",
"are",
"considered",
"to",
"be",
"the",
"same",
"if",
"they",
"only",
"differ",
"in",
"their",
"timestamps",
".",
"The",
"call",
"returns",
"true",
"if",
"a",
"new",
"status",
"history",
"record",
"has",
"been",
"created",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L528-L562 |
154,568 | juju/juju | state/status.go | eraseStatusHistory | func eraseStatusHistory(mb modelBackend, globalKey string) error {
// TODO(axw) restructure status history so we have one
// document per global key, and sub-documents per status
// recording. This method would then become a single
// Remove operation.
history, closer := mb.db().GetCollection(statusesHistoryC)
defer closer()
iter := history.Find(bson.D{{
globalKeyField, globalKey,
}}).Select(bson.M{"_id": 1}).Iter()
defer iter.Close()
logFormat := "deleted %d status history documents for " + fmt.Sprintf("%q", globalKey)
deleted, err := deleteInBatches(
history.Writeable().Underlying(), iter,
logFormat, loggo.DEBUG,
noEarlyFinish,
)
if err != nil {
return errors.Trace(err)
}
if deleted > 0 {
logger.Debugf(logFormat, deleted)
}
return nil
} | go | func eraseStatusHistory(mb modelBackend, globalKey string) error {
// TODO(axw) restructure status history so we have one
// document per global key, and sub-documents per status
// recording. This method would then become a single
// Remove operation.
history, closer := mb.db().GetCollection(statusesHistoryC)
defer closer()
iter := history.Find(bson.D{{
globalKeyField, globalKey,
}}).Select(bson.M{"_id": 1}).Iter()
defer iter.Close()
logFormat := "deleted %d status history documents for " + fmt.Sprintf("%q", globalKey)
deleted, err := deleteInBatches(
history.Writeable().Underlying(), iter,
logFormat, loggo.DEBUG,
noEarlyFinish,
)
if err != nil {
return errors.Trace(err)
}
if deleted > 0 {
logger.Debugf(logFormat, deleted)
}
return nil
} | [
"func",
"eraseStatusHistory",
"(",
"mb",
"modelBackend",
",",
"globalKey",
"string",
")",
"error",
"{",
"// TODO(axw) restructure status history so we have one",
"// document per global key, and sub-documents per status",
"// recording. This method would then become a single",
"// Remove operation.",
"history",
",",
"closer",
":=",
"mb",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"statusesHistoryC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"iter",
":=",
"history",
".",
"Find",
"(",
"bson",
".",
"D",
"{",
"{",
"globalKeyField",
",",
"globalKey",
",",
"}",
"}",
")",
".",
"Select",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"1",
"}",
")",
".",
"Iter",
"(",
")",
"\n",
"defer",
"iter",
".",
"Close",
"(",
")",
"\n\n",
"logFormat",
":=",
"\"",
"\"",
"+",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"globalKey",
")",
"\n",
"deleted",
",",
"err",
":=",
"deleteInBatches",
"(",
"history",
".",
"Writeable",
"(",
")",
".",
"Underlying",
"(",
")",
",",
"iter",
",",
"logFormat",
",",
"loggo",
".",
"DEBUG",
",",
"noEarlyFinish",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"deleted",
">",
"0",
"{",
"logger",
".",
"Debugf",
"(",
"logFormat",
",",
"deleted",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // eraseStatusHistory removes all status history documents for
// the given global key. The documents are removed in batches
// to avoid locking the status history collection for extended
// periods of time, preventing status history being recorded
// for other entities. | [
"eraseStatusHistory",
"removes",
"all",
"status",
"history",
"documents",
"for",
"the",
"given",
"global",
"key",
".",
"The",
"documents",
"are",
"removed",
"in",
"batches",
"to",
"avoid",
"locking",
"the",
"status",
"history",
"collection",
"for",
"extended",
"periods",
"of",
"time",
"preventing",
"status",
"history",
"being",
"recorded",
"for",
"other",
"entities",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L606-L633 |
154,569 | juju/juju | state/status.go | fetchNStatusResults | func fetchNStatusResults(col mongo.Collection, key string,
filter status.StatusHistoryFilter) ([]historicalStatusDoc, error) {
var (
docs []historicalStatusDoc
query mongo.Query
)
baseQuery := bson.M{"globalkey": key}
if filter.Delta != nil {
delta := *filter.Delta
// TODO(perrito666) 2016-10-06 lp:1558657
updated := time.Now().Add(-delta)
baseQuery["updated"] = bson.M{"$gt": updated.UnixNano()}
}
if filter.FromDate != nil {
baseQuery["updated"] = bson.M{"$gt": filter.FromDate.UnixNano()}
}
excludes := []string{}
excludes = append(excludes, filter.Exclude.Values()...)
if len(excludes) > 0 {
baseQuery["statusinfo"] = bson.M{"$nin": excludes}
}
query = col.Find(baseQuery).Sort("-updated")
if filter.Size > 0 {
query = query.Limit(filter.Size)
}
err := query.All(&docs)
if err == mgo.ErrNotFound {
return []historicalStatusDoc{}, errors.NotFoundf("status history")
} else if err != nil {
return []historicalStatusDoc{}, errors.Annotatef(err, "cannot get status history")
}
return docs, nil
} | go | func fetchNStatusResults(col mongo.Collection, key string,
filter status.StatusHistoryFilter) ([]historicalStatusDoc, error) {
var (
docs []historicalStatusDoc
query mongo.Query
)
baseQuery := bson.M{"globalkey": key}
if filter.Delta != nil {
delta := *filter.Delta
// TODO(perrito666) 2016-10-06 lp:1558657
updated := time.Now().Add(-delta)
baseQuery["updated"] = bson.M{"$gt": updated.UnixNano()}
}
if filter.FromDate != nil {
baseQuery["updated"] = bson.M{"$gt": filter.FromDate.UnixNano()}
}
excludes := []string{}
excludes = append(excludes, filter.Exclude.Values()...)
if len(excludes) > 0 {
baseQuery["statusinfo"] = bson.M{"$nin": excludes}
}
query = col.Find(baseQuery).Sort("-updated")
if filter.Size > 0 {
query = query.Limit(filter.Size)
}
err := query.All(&docs)
if err == mgo.ErrNotFound {
return []historicalStatusDoc{}, errors.NotFoundf("status history")
} else if err != nil {
return []historicalStatusDoc{}, errors.Annotatef(err, "cannot get status history")
}
return docs, nil
} | [
"func",
"fetchNStatusResults",
"(",
"col",
"mongo",
".",
"Collection",
",",
"key",
"string",
",",
"filter",
"status",
".",
"StatusHistoryFilter",
")",
"(",
"[",
"]",
"historicalStatusDoc",
",",
"error",
")",
"{",
"var",
"(",
"docs",
"[",
"]",
"historicalStatusDoc",
"\n",
"query",
"mongo",
".",
"Query",
"\n",
")",
"\n",
"baseQuery",
":=",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"key",
"}",
"\n",
"if",
"filter",
".",
"Delta",
"!=",
"nil",
"{",
"delta",
":=",
"*",
"filter",
".",
"Delta",
"\n",
"// TODO(perrito666) 2016-10-06 lp:1558657",
"updated",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"-",
"delta",
")",
"\n",
"baseQuery",
"[",
"\"",
"\"",
"]",
"=",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"updated",
".",
"UnixNano",
"(",
")",
"}",
"\n",
"}",
"\n",
"if",
"filter",
".",
"FromDate",
"!=",
"nil",
"{",
"baseQuery",
"[",
"\"",
"\"",
"]",
"=",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"filter",
".",
"FromDate",
".",
"UnixNano",
"(",
")",
"}",
"\n",
"}",
"\n",
"excludes",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"excludes",
"=",
"append",
"(",
"excludes",
",",
"filter",
".",
"Exclude",
".",
"Values",
"(",
")",
"...",
")",
"\n",
"if",
"len",
"(",
"excludes",
")",
">",
"0",
"{",
"baseQuery",
"[",
"\"",
"\"",
"]",
"=",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"excludes",
"}",
"\n",
"}",
"\n\n",
"query",
"=",
"col",
".",
"Find",
"(",
"baseQuery",
")",
".",
"Sort",
"(",
"\"",
"\"",
")",
"\n",
"if",
"filter",
".",
"Size",
">",
"0",
"{",
"query",
"=",
"query",
".",
"Limit",
"(",
"filter",
".",
"Size",
")",
"\n",
"}",
"\n",
"err",
":=",
"query",
".",
"All",
"(",
"&",
"docs",
")",
"\n\n",
"if",
"err",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"[",
"]",
"historicalStatusDoc",
"{",
"}",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"[",
"]",
"historicalStatusDoc",
"{",
"}",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"docs",
",",
"nil",
"\n\n",
"}"
] | // fetchNStatusResults will return status for the given key filtered with the
// given filter or error. | [
"fetchNStatusResults",
"will",
"return",
"status",
"for",
"the",
"given",
"key",
"filtered",
"with",
"the",
"given",
"filter",
"or",
"error",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/status.go#L644-L679 |
154,570 | juju/juju | apiserver/facades/client/storage/storage.go | NewStorageAPI | func NewStorageAPI(context facade.Context) (*StorageAPI, error) {
st := context.State()
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
registry, err := stateenvirons.NewStorageProviderRegistryForModel(
model,
stateenvirons.GetNewEnvironFunc(environs.New),
stateenvirons.GetNewCAASBrokerFunc(caas.New))
if err != nil {
return nil, errors.Trace(err)
}
pm := poolmanager.New(state.NewStateSettings(st), registry)
storageAccessor, err := getStorageAccessor(st)
if err != nil {
return nil, errors.Annotate(err, "getting backend")
}
authorizer := context.Auth()
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
return newStorageAPI(stateShim{st}, model.Type(), storageAccessor, registry, pm, authorizer, state.CallContext(st)), nil
} | go | func NewStorageAPI(context facade.Context) (*StorageAPI, error) {
st := context.State()
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
registry, err := stateenvirons.NewStorageProviderRegistryForModel(
model,
stateenvirons.GetNewEnvironFunc(environs.New),
stateenvirons.GetNewCAASBrokerFunc(caas.New))
if err != nil {
return nil, errors.Trace(err)
}
pm := poolmanager.New(state.NewStateSettings(st), registry)
storageAccessor, err := getStorageAccessor(st)
if err != nil {
return nil, errors.Annotate(err, "getting backend")
}
authorizer := context.Auth()
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
return newStorageAPI(stateShim{st}, model.Type(), storageAccessor, registry, pm, authorizer, state.CallContext(st)), nil
} | [
"func",
"NewStorageAPI",
"(",
"context",
"facade",
".",
"Context",
")",
"(",
"*",
"StorageAPI",
",",
"error",
")",
"{",
"st",
":=",
"context",
".",
"State",
"(",
")",
"\n",
"model",
",",
"err",
":=",
"st",
".",
"Model",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"registry",
",",
"err",
":=",
"stateenvirons",
".",
"NewStorageProviderRegistryForModel",
"(",
"model",
",",
"stateenvirons",
".",
"GetNewEnvironFunc",
"(",
"environs",
".",
"New",
")",
",",
"stateenvirons",
".",
"GetNewCAASBrokerFunc",
"(",
"caas",
".",
"New",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"pm",
":=",
"poolmanager",
".",
"New",
"(",
"state",
".",
"NewStateSettings",
"(",
"st",
")",
",",
"registry",
")",
"\n\n",
"storageAccessor",
",",
"err",
":=",
"getStorageAccessor",
"(",
"st",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"authorizer",
":=",
"context",
".",
"Auth",
"(",
")",
"\n",
"if",
"!",
"authorizer",
".",
"AuthClient",
"(",
")",
"{",
"return",
"nil",
",",
"common",
".",
"ErrPerm",
"\n",
"}",
"\n",
"return",
"newStorageAPI",
"(",
"stateShim",
"{",
"st",
"}",
",",
"model",
".",
"Type",
"(",
")",
",",
"storageAccessor",
",",
"registry",
",",
"pm",
",",
"authorizer",
",",
"state",
".",
"CallContext",
"(",
"st",
")",
")",
",",
"nil",
"\n",
"}"
] | // NewStorageAPI returns a new storage API facade. | [
"NewStorageAPI",
"returns",
"a",
"new",
"storage",
"API",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L59-L84 |
154,571 | juju/juju | apiserver/facades/client/storage/storage.go | NewStorageAPIV5 | func NewStorageAPIV5(context facade.Context) (*StorageAPIv5, error) {
storageAPI, err := NewStorageAPI(context)
if err != nil {
return nil, err
}
return &StorageAPIv5{
StorageAPI: *storageAPI,
}, nil
} | go | func NewStorageAPIV5(context facade.Context) (*StorageAPIv5, error) {
storageAPI, err := NewStorageAPI(context)
if err != nil {
return nil, err
}
return &StorageAPIv5{
StorageAPI: *storageAPI,
}, nil
} | [
"func",
"NewStorageAPIV5",
"(",
"context",
"facade",
".",
"Context",
")",
"(",
"*",
"StorageAPIv5",
",",
"error",
")",
"{",
"storageAPI",
",",
"err",
":=",
"NewStorageAPI",
"(",
"context",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"StorageAPIv5",
"{",
"StorageAPI",
":",
"*",
"storageAPI",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewStorageAPIV5 returns a new storage v5 API facade. | [
"NewStorageAPIV5",
"returns",
"a",
"new",
"storage",
"v5",
"API",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L107-L115 |
154,572 | juju/juju | apiserver/facades/client/storage/storage.go | NewStorageAPIV4 | func NewStorageAPIV4(context facade.Context) (*StorageAPIv4, error) {
storageAPI, err := NewStorageAPIV5(context)
if err != nil {
return nil, err
}
return &StorageAPIv4{
StorageAPIv5: *storageAPI,
}, nil
} | go | func NewStorageAPIV4(context facade.Context) (*StorageAPIv4, error) {
storageAPI, err := NewStorageAPIV5(context)
if err != nil {
return nil, err
}
return &StorageAPIv4{
StorageAPIv5: *storageAPI,
}, nil
} | [
"func",
"NewStorageAPIV4",
"(",
"context",
"facade",
".",
"Context",
")",
"(",
"*",
"StorageAPIv4",
",",
"error",
")",
"{",
"storageAPI",
",",
"err",
":=",
"NewStorageAPIV5",
"(",
"context",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"StorageAPIv4",
"{",
"StorageAPIv5",
":",
"*",
"storageAPI",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewStorageAPIV4 returns a new storage v4 API facade. | [
"NewStorageAPIV4",
"returns",
"a",
"new",
"storage",
"v4",
"API",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L118-L126 |
154,573 | juju/juju | apiserver/facades/client/storage/storage.go | NewStorageAPIV3 | func NewStorageAPIV3(context facade.Context) (*StorageAPIv3, error) {
storageAPI, err := NewStorageAPIV4(context)
if err != nil {
return nil, err
}
return &StorageAPIv3{
StorageAPIv4: *storageAPI,
}, nil
} | go | func NewStorageAPIV3(context facade.Context) (*StorageAPIv3, error) {
storageAPI, err := NewStorageAPIV4(context)
if err != nil {
return nil, err
}
return &StorageAPIv3{
StorageAPIv4: *storageAPI,
}, nil
} | [
"func",
"NewStorageAPIV3",
"(",
"context",
"facade",
".",
"Context",
")",
"(",
"*",
"StorageAPIv3",
",",
"error",
")",
"{",
"storageAPI",
",",
"err",
":=",
"NewStorageAPIV4",
"(",
"context",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"StorageAPIv3",
"{",
"StorageAPIv4",
":",
"*",
"storageAPI",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewStorageAPIV3 returns a new storage v3 API facade. | [
"NewStorageAPIV3",
"returns",
"a",
"new",
"storage",
"v3",
"API",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L129-L137 |
154,574 | juju/juju | apiserver/facades/client/storage/storage.go | StorageDetails | func (a *StorageAPI) StorageDetails(entities params.Entities) (params.StorageDetailsResults, error) {
if err := a.checkCanRead(); err != nil {
return params.StorageDetailsResults{}, errors.Trace(err)
}
results := make([]params.StorageDetailsResult, len(entities.Entities))
for i, entity := range entities.Entities {
storageTag, err := names.ParseStorageTag(entity.Tag)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
storageInstance, err := a.storageAccess.StorageInstance(storageTag)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
details, err := createStorageDetails(a.backend, a.storageAccess, storageInstance)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
results[i].Result = details
}
return params.StorageDetailsResults{Results: results}, nil
} | go | func (a *StorageAPI) StorageDetails(entities params.Entities) (params.StorageDetailsResults, error) {
if err := a.checkCanRead(); err != nil {
return params.StorageDetailsResults{}, errors.Trace(err)
}
results := make([]params.StorageDetailsResult, len(entities.Entities))
for i, entity := range entities.Entities {
storageTag, err := names.ParseStorageTag(entity.Tag)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
storageInstance, err := a.storageAccess.StorageInstance(storageTag)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
details, err := createStorageDetails(a.backend, a.storageAccess, storageInstance)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
results[i].Result = details
}
return params.StorageDetailsResults{Results: results}, nil
} | [
"func",
"(",
"a",
"*",
"StorageAPI",
")",
"StorageDetails",
"(",
"entities",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"StorageDetailsResults",
",",
"error",
")",
"{",
"if",
"err",
":=",
"a",
".",
"checkCanRead",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"StorageDetailsResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"results",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"StorageDetailsResult",
",",
"len",
"(",
"entities",
".",
"Entities",
")",
")",
"\n",
"for",
"i",
",",
"entity",
":=",
"range",
"entities",
".",
"Entities",
"{",
"storageTag",
",",
"err",
":=",
"names",
".",
"ParseStorageTag",
"(",
"entity",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"storageInstance",
",",
"err",
":=",
"a",
".",
"storageAccess",
".",
"StorageInstance",
"(",
"storageTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"details",
",",
"err",
":=",
"createStorageDetails",
"(",
"a",
".",
"backend",
",",
"a",
".",
"storageAccess",
",",
"storageInstance",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"results",
"[",
"i",
"]",
".",
"Result",
"=",
"details",
"\n",
"}",
"\n",
"return",
"params",
".",
"StorageDetailsResults",
"{",
"Results",
":",
"results",
"}",
",",
"nil",
"\n",
"}"
] | // StorageDetails retrieves and returns detailed information about desired
// storage identified by supplied tags. If specified storage cannot be
// retrieved, individual error is returned instead of storage information. | [
"StorageDetails",
"retrieves",
"and",
"returns",
"detailed",
"information",
"about",
"desired",
"storage",
"identified",
"by",
"supplied",
"tags",
".",
"If",
"specified",
"storage",
"cannot",
"be",
"retrieved",
"individual",
"error",
"is",
"returned",
"instead",
"of",
"storage",
"information",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L171-L195 |
154,575 | juju/juju | apiserver/facades/client/storage/storage.go | ListStorageDetails | func (a *StorageAPI) ListStorageDetails(filters params.StorageFilters) (params.StorageDetailsListResults, error) {
if err := a.checkCanRead(); err != nil {
return params.StorageDetailsListResults{}, errors.Trace(err)
}
results := params.StorageDetailsListResults{
Results: make([]params.StorageDetailsListResult, len(filters.Filters)),
}
for i, filter := range filters.Filters {
list, err := a.listStorageDetails(filter)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = list
}
return results, nil
} | go | func (a *StorageAPI) ListStorageDetails(filters params.StorageFilters) (params.StorageDetailsListResults, error) {
if err := a.checkCanRead(); err != nil {
return params.StorageDetailsListResults{}, errors.Trace(err)
}
results := params.StorageDetailsListResults{
Results: make([]params.StorageDetailsListResult, len(filters.Filters)),
}
for i, filter := range filters.Filters {
list, err := a.listStorageDetails(filter)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = list
}
return results, nil
} | [
"func",
"(",
"a",
"*",
"StorageAPI",
")",
"ListStorageDetails",
"(",
"filters",
"params",
".",
"StorageFilters",
")",
"(",
"params",
".",
"StorageDetailsListResults",
",",
"error",
")",
"{",
"if",
"err",
":=",
"a",
".",
"checkCanRead",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"StorageDetailsListResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"results",
":=",
"params",
".",
"StorageDetailsListResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"StorageDetailsListResult",
",",
"len",
"(",
"filters",
".",
"Filters",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"filter",
":=",
"range",
"filters",
".",
"Filters",
"{",
"list",
",",
"err",
":=",
"a",
".",
"listStorageDetails",
"(",
"filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Result",
"=",
"list",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // ListStorageDetails returns storage matching a filter. | [
"ListStorageDetails",
"returns",
"storage",
"matching",
"a",
"filter",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L198-L214 |
154,576 | juju/juju | apiserver/facades/client/storage/storage.go | ListPools | func (a *StorageAPI) ListPools(
filters params.StoragePoolFilters,
) (params.StoragePoolsResults, error) {
if err := a.checkCanRead(); err != nil {
return params.StoragePoolsResults{}, errors.Trace(err)
}
results := params.StoragePoolsResults{
Results: make([]params.StoragePoolsResult, len(filters.Filters)),
}
for i, filter := range filters.Filters {
pools, err := a.listPools(a.ensureStoragePoolFilter(filter))
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = pools
}
return results, nil
} | go | func (a *StorageAPI) ListPools(
filters params.StoragePoolFilters,
) (params.StoragePoolsResults, error) {
if err := a.checkCanRead(); err != nil {
return params.StoragePoolsResults{}, errors.Trace(err)
}
results := params.StoragePoolsResults{
Results: make([]params.StoragePoolsResult, len(filters.Filters)),
}
for i, filter := range filters.Filters {
pools, err := a.listPools(a.ensureStoragePoolFilter(filter))
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = pools
}
return results, nil
} | [
"func",
"(",
"a",
"*",
"StorageAPI",
")",
"ListPools",
"(",
"filters",
"params",
".",
"StoragePoolFilters",
",",
")",
"(",
"params",
".",
"StoragePoolsResults",
",",
"error",
")",
"{",
"if",
"err",
":=",
"a",
".",
"checkCanRead",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"StoragePoolsResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"results",
":=",
"params",
".",
"StoragePoolsResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"StoragePoolsResult",
",",
"len",
"(",
"filters",
".",
"Filters",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"filter",
":=",
"range",
"filters",
".",
"Filters",
"{",
"pools",
",",
"err",
":=",
"a",
".",
"listPools",
"(",
"a",
".",
"ensureStoragePoolFilter",
"(",
"filter",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Result",
"=",
"pools",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // ListPools returns a list of pools.
// If filter is provided, returned list only contains pools that match
// the filter.
// Pools can be filtered on names and provider types.
// If both names and types are provided as filter,
// pools that match either are returned.
// This method lists union of pools and environment provider types.
// If no filter is provided, all pools are returned. | [
"ListPools",
"returns",
"a",
"list",
"of",
"pools",
".",
"If",
"filter",
"is",
"provided",
"returned",
"list",
"only",
"contains",
"pools",
"that",
"match",
"the",
"filter",
".",
"Pools",
"can",
"be",
"filtered",
"on",
"names",
"and",
"provider",
"types",
".",
"If",
"both",
"names",
"and",
"types",
"are",
"provided",
"as",
"filter",
"pools",
"that",
"match",
"either",
"are",
"returned",
".",
"This",
"method",
"lists",
"union",
"of",
"pools",
"and",
"environment",
"provider",
"types",
".",
"If",
"no",
"filter",
"is",
"provided",
"all",
"pools",
"are",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L352-L371 |
154,577 | juju/juju | apiserver/facades/client/storage/storage.go | ListVolumes | func (a *StorageAPI) ListVolumes(filters params.VolumeFilters) (params.VolumeDetailsListResults, error) {
if err := a.checkCanRead(); err != nil {
return params.VolumeDetailsListResults{}, errors.Trace(err)
}
results := params.VolumeDetailsListResults{
Results: make([]params.VolumeDetailsListResult, len(filters.Filters)),
}
stVolumeAccess := a.storageAccess.VolumeAccess()
for i, filter := range filters.Filters {
volumes, volumeAttachments, err := filterVolumes(stVolumeAccess, filter)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
details, err := createVolumeDetailsList(
a.backend, a.storageAccess, volumes, volumeAttachments,
)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = details
}
return results, nil
} | go | func (a *StorageAPI) ListVolumes(filters params.VolumeFilters) (params.VolumeDetailsListResults, error) {
if err := a.checkCanRead(); err != nil {
return params.VolumeDetailsListResults{}, errors.Trace(err)
}
results := params.VolumeDetailsListResults{
Results: make([]params.VolumeDetailsListResult, len(filters.Filters)),
}
stVolumeAccess := a.storageAccess.VolumeAccess()
for i, filter := range filters.Filters {
volumes, volumeAttachments, err := filterVolumes(stVolumeAccess, filter)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
details, err := createVolumeDetailsList(
a.backend, a.storageAccess, volumes, volumeAttachments,
)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = details
}
return results, nil
} | [
"func",
"(",
"a",
"*",
"StorageAPI",
")",
"ListVolumes",
"(",
"filters",
"params",
".",
"VolumeFilters",
")",
"(",
"params",
".",
"VolumeDetailsListResults",
",",
"error",
")",
"{",
"if",
"err",
":=",
"a",
".",
"checkCanRead",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"VolumeDetailsListResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"results",
":=",
"params",
".",
"VolumeDetailsListResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"VolumeDetailsListResult",
",",
"len",
"(",
"filters",
".",
"Filters",
")",
")",
",",
"}",
"\n",
"stVolumeAccess",
":=",
"a",
".",
"storageAccess",
".",
"VolumeAccess",
"(",
")",
"\n",
"for",
"i",
",",
"filter",
":=",
"range",
"filters",
".",
"Filters",
"{",
"volumes",
",",
"volumeAttachments",
",",
"err",
":=",
"filterVolumes",
"(",
"stVolumeAccess",
",",
"filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"details",
",",
"err",
":=",
"createVolumeDetailsList",
"(",
"a",
".",
"backend",
",",
"a",
".",
"storageAccess",
",",
"volumes",
",",
"volumeAttachments",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Result",
"=",
"details",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // ListVolumes lists volumes with the given filters. Each filter produces
// an independent list of volumes, or an error if the filter is invalid
// or the volumes could not be listed. | [
"ListVolumes",
"lists",
"volumes",
"with",
"the",
"given",
"filters",
".",
"Each",
"filter",
"produces",
"an",
"independent",
"list",
"of",
"volumes",
"or",
"an",
"error",
"if",
"the",
"filter",
"is",
"invalid",
"or",
"the",
"volumes",
"could",
"not",
"be",
"listed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L512-L536 |
154,578 | juju/juju | apiserver/facades/client/storage/storage.go | ListFilesystems | func (a *StorageAPI) ListFilesystems(filters params.FilesystemFilters) (params.FilesystemDetailsListResults, error) {
results := params.FilesystemDetailsListResults{
Results: make([]params.FilesystemDetailsListResult, len(filters.Filters)),
}
if err := a.checkCanRead(); err != nil {
return results, errors.Trace(err)
}
stFileAccess := a.storageAccess.FilesystemAccess()
for i, filter := range filters.Filters {
filesystems, filesystemAttachments, err := filterFilesystems(stFileAccess, filter)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
details, err := createFilesystemDetailsList(
a.backend, a.storageAccess, filesystems, filesystemAttachments,
)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = details
}
return results, nil
} | go | func (a *StorageAPI) ListFilesystems(filters params.FilesystemFilters) (params.FilesystemDetailsListResults, error) {
results := params.FilesystemDetailsListResults{
Results: make([]params.FilesystemDetailsListResult, len(filters.Filters)),
}
if err := a.checkCanRead(); err != nil {
return results, errors.Trace(err)
}
stFileAccess := a.storageAccess.FilesystemAccess()
for i, filter := range filters.Filters {
filesystems, filesystemAttachments, err := filterFilesystems(stFileAccess, filter)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
details, err := createFilesystemDetailsList(
a.backend, a.storageAccess, filesystems, filesystemAttachments,
)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = details
}
return results, nil
} | [
"func",
"(",
"a",
"*",
"StorageAPI",
")",
"ListFilesystems",
"(",
"filters",
"params",
".",
"FilesystemFilters",
")",
"(",
"params",
".",
"FilesystemDetailsListResults",
",",
"error",
")",
"{",
"results",
":=",
"params",
".",
"FilesystemDetailsListResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"FilesystemDetailsListResult",
",",
"len",
"(",
"filters",
".",
"Filters",
")",
")",
",",
"}",
"\n",
"if",
"err",
":=",
"a",
".",
"checkCanRead",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"results",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"stFileAccess",
":=",
"a",
".",
"storageAccess",
".",
"FilesystemAccess",
"(",
")",
"\n",
"for",
"i",
",",
"filter",
":=",
"range",
"filters",
".",
"Filters",
"{",
"filesystems",
",",
"filesystemAttachments",
",",
"err",
":=",
"filterFilesystems",
"(",
"stFileAccess",
",",
"filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"details",
",",
"err",
":=",
"createFilesystemDetailsList",
"(",
"a",
".",
"backend",
",",
"a",
".",
"storageAccess",
",",
"filesystems",
",",
"filesystemAttachments",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Result",
"=",
"details",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // ListFilesystems returns a list of filesystems in the environment matching
// the provided filter. Each result describes a filesystem in detail, including
// the filesystem's attachments. | [
"ListFilesystems",
"returns",
"a",
"list",
"of",
"filesystems",
"in",
"the",
"environment",
"matching",
"the",
"provided",
"filter",
".",
"Each",
"result",
"describes",
"a",
"filesystem",
"in",
"detail",
"including",
"the",
"filesystem",
"s",
"attachments",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L677-L702 |
154,579 | juju/juju | apiserver/facades/client/storage/storage.go | Remove | func (a *StorageAPI) Remove(args params.RemoveStorage) (params.ErrorResults, error) {
return a.remove(args)
} | go | func (a *StorageAPI) Remove(args params.RemoveStorage) (params.ErrorResults, error) {
return a.remove(args)
} | [
"func",
"(",
"a",
"*",
"StorageAPI",
")",
"Remove",
"(",
"args",
"params",
".",
"RemoveStorage",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"return",
"a",
".",
"remove",
"(",
"args",
")",
"\n",
"}"
] | // Remove sets the specified storage entities to Dying, unless they are
// already Dying or Dead, such that the storage will eventually be removed
// from the model. If the arguments specify that the storage should be
// destroyed, then the associated cloud storage will be destroyed first;
// otherwise it will only be released from Juju's control. | [
"Remove",
"sets",
"the",
"specified",
"storage",
"entities",
"to",
"Dying",
"unless",
"they",
"are",
"already",
"Dying",
"or",
"Dead",
"such",
"that",
"the",
"storage",
"will",
"eventually",
"be",
"removed",
"from",
"the",
"model",
".",
"If",
"the",
"arguments",
"specify",
"that",
"the",
"storage",
"should",
"be",
"destroyed",
"then",
"the",
"associated",
"cloud",
"storage",
"will",
"be",
"destroyed",
"first",
";",
"otherwise",
"it",
"will",
"only",
"be",
"released",
"from",
"Juju",
"s",
"control",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L912-L914 |
154,580 | juju/juju | apiserver/facades/client/storage/storage.go | DetachStorage | func (a *StorageAPI) DetachStorage(args params.StorageDetachmentParams) (params.ErrorResults, error) {
return a.internalDetach(args.StorageIds, args.Force, args.MaxWait)
} | go | func (a *StorageAPI) DetachStorage(args params.StorageDetachmentParams) (params.ErrorResults, error) {
return a.internalDetach(args.StorageIds, args.Force, args.MaxWait)
} | [
"func",
"(",
"a",
"*",
"StorageAPI",
")",
"DetachStorage",
"(",
"args",
"params",
".",
"StorageDetachmentParams",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"return",
"a",
".",
"internalDetach",
"(",
"args",
".",
"StorageIds",
",",
"args",
".",
"Force",
",",
"args",
".",
"MaxWait",
")",
"\n",
"}"
] | // DetachStorage sets the specified storage attachments to Dying, unless they are
// already Dying or Dead. Any associated, persistent storage will remain
// alive. This call can be forced. | [
"DetachStorage",
"sets",
"the",
"specified",
"storage",
"attachments",
"to",
"Dying",
"unless",
"they",
"are",
"already",
"Dying",
"or",
"Dead",
".",
"Any",
"associated",
"persistent",
"storage",
"will",
"remain",
"alive",
".",
"This",
"call",
"can",
"be",
"forced",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L946-L948 |
154,581 | juju/juju | apiserver/facades/client/storage/storage.go | Detach | func (a *StorageAPIv5) Detach(args params.StorageAttachmentIds) (params.ErrorResults, error) {
return a.internalDetach(args, nil, nil)
} | go | func (a *StorageAPIv5) Detach(args params.StorageAttachmentIds) (params.ErrorResults, error) {
return a.internalDetach(args, nil, nil)
} | [
"func",
"(",
"a",
"*",
"StorageAPIv5",
")",
"Detach",
"(",
"args",
"params",
".",
"StorageAttachmentIds",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"return",
"a",
".",
"internalDetach",
"(",
"args",
",",
"nil",
",",
"nil",
")",
"\n",
"}"
] | // Detach sets the specified storage attachments to Dying, unless they are
// already Dying or Dead. Any associated, persistent storage will remain
// alive. | [
"Detach",
"sets",
"the",
"specified",
"storage",
"attachments",
"to",
"Dying",
"unless",
"they",
"are",
"already",
"Dying",
"or",
"Dead",
".",
"Any",
"associated",
"persistent",
"storage",
"will",
"remain",
"alive",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L986-L988 |
154,582 | juju/juju | apiserver/facades/client/storage/storage.go | Attach | func (a *StorageAPI) Attach(args params.StorageAttachmentIds) (params.ErrorResults, error) {
if err := a.checkCanWrite(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
blockChecker := common.NewBlockChecker(a.backend)
if err := blockChecker.ChangeAllowed(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
attachOne := func(arg params.StorageAttachmentId) error {
storageTag, err := names.ParseStorageTag(arg.StorageTag)
if err != nil {
return err
}
unitTag, err := names.ParseUnitTag(arg.UnitTag)
if err != nil {
return err
}
return a.attachStorage(storageTag, unitTag)
}
result := make([]params.ErrorResult, len(args.Ids))
for i, arg := range args.Ids {
result[i].Error = common.ServerError(attachOne(arg))
}
return params.ErrorResults{Results: result}, nil
} | go | func (a *StorageAPI) Attach(args params.StorageAttachmentIds) (params.ErrorResults, error) {
if err := a.checkCanWrite(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
blockChecker := common.NewBlockChecker(a.backend)
if err := blockChecker.ChangeAllowed(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
attachOne := func(arg params.StorageAttachmentId) error {
storageTag, err := names.ParseStorageTag(arg.StorageTag)
if err != nil {
return err
}
unitTag, err := names.ParseUnitTag(arg.UnitTag)
if err != nil {
return err
}
return a.attachStorage(storageTag, unitTag)
}
result := make([]params.ErrorResult, len(args.Ids))
for i, arg := range args.Ids {
result[i].Error = common.ServerError(attachOne(arg))
}
return params.ErrorResults{Results: result}, nil
} | [
"func",
"(",
"a",
"*",
"StorageAPI",
")",
"Attach",
"(",
"args",
"params",
".",
"StorageAttachmentIds",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"if",
"err",
":=",
"a",
".",
"checkCanWrite",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ErrorResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"blockChecker",
":=",
"common",
".",
"NewBlockChecker",
"(",
"a",
".",
"backend",
")",
"\n",
"if",
"err",
":=",
"blockChecker",
".",
"ChangeAllowed",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ErrorResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"attachOne",
":=",
"func",
"(",
"arg",
"params",
".",
"StorageAttachmentId",
")",
"error",
"{",
"storageTag",
",",
"err",
":=",
"names",
".",
"ParseStorageTag",
"(",
"arg",
".",
"StorageTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"unitTag",
",",
"err",
":=",
"names",
".",
"ParseUnitTag",
"(",
"arg",
".",
"UnitTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"a",
".",
"attachStorage",
"(",
"storageTag",
",",
"unitTag",
")",
"\n",
"}",
"\n\n",
"result",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"ErrorResult",
",",
"len",
"(",
"args",
".",
"Ids",
")",
")",
"\n",
"for",
"i",
",",
"arg",
":=",
"range",
"args",
".",
"Ids",
"{",
"result",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"attachOne",
"(",
"arg",
")",
")",
"\n",
"}",
"\n",
"return",
"params",
".",
"ErrorResults",
"{",
"Results",
":",
"result",
"}",
",",
"nil",
"\n",
"}"
] | // Attach attaches existing storage instances to units.
// A "CHANGE" block can block this operation. | [
"Attach",
"attaches",
"existing",
"storage",
"instances",
"to",
"units",
".",
"A",
"CHANGE",
"block",
"can",
"block",
"this",
"operation",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L1023-L1050 |
154,583 | juju/juju | apiserver/facades/client/storage/storage.go | Import | func (a *StorageAPI) Import(args params.BulkImportStorageParams) (params.ImportStorageResults, error) {
if err := a.checkCanWrite(); err != nil {
return params.ImportStorageResults{}, errors.Trace(err)
}
blockChecker := common.NewBlockChecker(a.backend)
if err := blockChecker.ChangeAllowed(); err != nil {
return params.ImportStorageResults{}, errors.Trace(err)
}
results := make([]params.ImportStorageResult, len(args.Storage))
for i, arg := range args.Storage {
details, err := a.importStorage(arg)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
results[i].Result = details
}
return params.ImportStorageResults{Results: results}, nil
} | go | func (a *StorageAPI) Import(args params.BulkImportStorageParams) (params.ImportStorageResults, error) {
if err := a.checkCanWrite(); err != nil {
return params.ImportStorageResults{}, errors.Trace(err)
}
blockChecker := common.NewBlockChecker(a.backend)
if err := blockChecker.ChangeAllowed(); err != nil {
return params.ImportStorageResults{}, errors.Trace(err)
}
results := make([]params.ImportStorageResult, len(args.Storage))
for i, arg := range args.Storage {
details, err := a.importStorage(arg)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
results[i].Result = details
}
return params.ImportStorageResults{Results: results}, nil
} | [
"func",
"(",
"a",
"*",
"StorageAPI",
")",
"Import",
"(",
"args",
"params",
".",
"BulkImportStorageParams",
")",
"(",
"params",
".",
"ImportStorageResults",
",",
"error",
")",
"{",
"if",
"err",
":=",
"a",
".",
"checkCanWrite",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ImportStorageResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"blockChecker",
":=",
"common",
".",
"NewBlockChecker",
"(",
"a",
".",
"backend",
")",
"\n",
"if",
"err",
":=",
"blockChecker",
".",
"ChangeAllowed",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ImportStorageResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"results",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"ImportStorageResult",
",",
"len",
"(",
"args",
".",
"Storage",
")",
")",
"\n",
"for",
"i",
",",
"arg",
":=",
"range",
"args",
".",
"Storage",
"{",
"details",
",",
"err",
":=",
"a",
".",
"importStorage",
"(",
"arg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"results",
"[",
"i",
"]",
".",
"Result",
"=",
"details",
"\n",
"}",
"\n",
"return",
"params",
".",
"ImportStorageResults",
"{",
"Results",
":",
"results",
"}",
",",
"nil",
"\n",
"}"
] | // Import imports existing storage into the model.
// A "CHANGE" block can block this operation. | [
"Import",
"imports",
"existing",
"storage",
"into",
"the",
"model",
".",
"A",
"CHANGE",
"block",
"can",
"block",
"this",
"operation",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L1058-L1078 |
154,584 | juju/juju | apiserver/facades/client/storage/storage.go | RemovePool | func (a *StorageAPI) RemovePool(p params.StoragePoolDeleteArgs) (params.ErrorResults, error) {
results := params.ErrorResults{
Results: make([]params.ErrorResult, len(p.Pools)),
}
if err := a.checkCanWrite(); err != nil {
return results, errors.Trace(err)
}
for i, pool := range p.Pools {
err := a.storageAccess.RemoveStoragePool(pool.Name)
if err != nil {
results.Results[i].Error = common.ServerError(err)
}
}
return results, nil
} | go | func (a *StorageAPI) RemovePool(p params.StoragePoolDeleteArgs) (params.ErrorResults, error) {
results := params.ErrorResults{
Results: make([]params.ErrorResult, len(p.Pools)),
}
if err := a.checkCanWrite(); err != nil {
return results, errors.Trace(err)
}
for i, pool := range p.Pools {
err := a.storageAccess.RemoveStoragePool(pool.Name)
if err != nil {
results.Results[i].Error = common.ServerError(err)
}
}
return results, nil
} | [
"func",
"(",
"a",
"*",
"StorageAPI",
")",
"RemovePool",
"(",
"p",
"params",
".",
"StoragePoolDeleteArgs",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"results",
":=",
"params",
".",
"ErrorResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"ErrorResult",
",",
"len",
"(",
"p",
".",
"Pools",
")",
")",
",",
"}",
"\n",
"if",
"err",
":=",
"a",
".",
"checkCanWrite",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"results",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"pool",
":=",
"range",
"p",
".",
"Pools",
"{",
"err",
":=",
"a",
".",
"storageAccess",
".",
"RemoveStoragePool",
"(",
"pool",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // RemovePool deletes the named pool | [
"RemovePool",
"deletes",
"the",
"named",
"pool"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L1178-L1192 |
154,585 | juju/juju | apiserver/facades/client/storage/storage.go | UpdatePool | func (a *StorageAPI) UpdatePool(p params.StoragePoolArgs) (params.ErrorResults, error) {
results := params.ErrorResults{
Results: make([]params.ErrorResult, len(p.Pools)),
}
if err := a.checkCanWrite(); err != nil {
return results, errors.Trace(err)
}
for i, pool := range p.Pools {
err := a.poolManager.Replace(pool.Name, pool.Provider, pool.Attrs)
if err != nil {
results.Results[i].Error = common.ServerError(err)
}
}
return results, nil
} | go | func (a *StorageAPI) UpdatePool(p params.StoragePoolArgs) (params.ErrorResults, error) {
results := params.ErrorResults{
Results: make([]params.ErrorResult, len(p.Pools)),
}
if err := a.checkCanWrite(); err != nil {
return results, errors.Trace(err)
}
for i, pool := range p.Pools {
err := a.poolManager.Replace(pool.Name, pool.Provider, pool.Attrs)
if err != nil {
results.Results[i].Error = common.ServerError(err)
}
}
return results, nil
} | [
"func",
"(",
"a",
"*",
"StorageAPI",
")",
"UpdatePool",
"(",
"p",
"params",
".",
"StoragePoolArgs",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"results",
":=",
"params",
".",
"ErrorResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"ErrorResult",
",",
"len",
"(",
"p",
".",
"Pools",
")",
")",
",",
"}",
"\n",
"if",
"err",
":=",
"a",
".",
"checkCanWrite",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"results",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"pool",
":=",
"range",
"p",
".",
"Pools",
"{",
"err",
":=",
"a",
".",
"poolManager",
".",
"Replace",
"(",
"pool",
".",
"Name",
",",
"pool",
".",
"Provider",
",",
"pool",
".",
"Attrs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // UpdatePool deletes the named pool | [
"UpdatePool",
"deletes",
"the",
"named",
"pool"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L1195-L1209 |
154,586 | juju/juju | apiserver/facades/client/storage/storage.go | Destroy | func (a *StorageAPIv3) Destroy(args params.Entities) (params.ErrorResults, error) {
v4Args := params.RemoveStorage{
Storage: make([]params.RemoveStorageInstance, len(args.Entities)),
}
for i, arg := range args.Entities {
v4Args.Storage[i] = params.RemoveStorageInstance{
Tag: arg.Tag,
// The v3 behaviour was to detach the storage
// at the same time as marking the storage Dying.
DestroyAttachments: true,
DestroyStorage: true,
}
}
return a.remove(v4Args)
} | go | func (a *StorageAPIv3) Destroy(args params.Entities) (params.ErrorResults, error) {
v4Args := params.RemoveStorage{
Storage: make([]params.RemoveStorageInstance, len(args.Entities)),
}
for i, arg := range args.Entities {
v4Args.Storage[i] = params.RemoveStorageInstance{
Tag: arg.Tag,
// The v3 behaviour was to detach the storage
// at the same time as marking the storage Dying.
DestroyAttachments: true,
DestroyStorage: true,
}
}
return a.remove(v4Args)
} | [
"func",
"(",
"a",
"*",
"StorageAPIv3",
")",
"Destroy",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"v4Args",
":=",
"params",
".",
"RemoveStorage",
"{",
"Storage",
":",
"make",
"(",
"[",
"]",
"params",
".",
"RemoveStorageInstance",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"arg",
":=",
"range",
"args",
".",
"Entities",
"{",
"v4Args",
".",
"Storage",
"[",
"i",
"]",
"=",
"params",
".",
"RemoveStorageInstance",
"{",
"Tag",
":",
"arg",
".",
"Tag",
",",
"// The v3 behaviour was to detach the storage",
"// at the same time as marking the storage Dying.",
"DestroyAttachments",
":",
"true",
",",
"DestroyStorage",
":",
"true",
",",
"}",
"\n",
"}",
"\n",
"return",
"a",
".",
"remove",
"(",
"v4Args",
")",
"\n",
"}"
] | // Destroy sets the specified storage entities to Dying, unless they are
// already Dying or Dead. | [
"Destroy",
"sets",
"the",
"specified",
"storage",
"entities",
"to",
"Dying",
"unless",
"they",
"are",
"already",
"Dying",
"or",
"Dead",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/storage.go#L1231-L1245 |
154,587 | juju/juju | state/watcher/hubwatcher.go | NewHubWatcher | func NewHubWatcher(config HubWatcherConfig) (*HubWatcher, error) {
if err := config.Validate(); err != nil {
return nil, errors.Annotate(err, "new HubWatcher invalid config")
}
watcher, _ := newHubWatcher(config.Hub, config.Clock, config.ModelUUID, config.Logger)
return watcher, nil
} | go | func NewHubWatcher(config HubWatcherConfig) (*HubWatcher, error) {
if err := config.Validate(); err != nil {
return nil, errors.Annotate(err, "new HubWatcher invalid config")
}
watcher, _ := newHubWatcher(config.Hub, config.Clock, config.ModelUUID, config.Logger)
return watcher, nil
} | [
"func",
"NewHubWatcher",
"(",
"config",
"HubWatcherConfig",
")",
"(",
"*",
"HubWatcher",
",",
"error",
")",
"{",
"if",
"err",
":=",
"config",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"watcher",
",",
"_",
":=",
"newHubWatcher",
"(",
"config",
".",
"Hub",
",",
"config",
".",
"Clock",
",",
"config",
".",
"ModelUUID",
",",
"config",
".",
"Logger",
")",
"\n",
"return",
"watcher",
",",
"nil",
"\n",
"}"
] | // NewHubWatcher returns a new watcher observing Change events published to the
// hub. | [
"NewHubWatcher",
"returns",
"a",
"new",
"watcher",
"observing",
"Change",
"events",
"published",
"to",
"the",
"hub",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher/hubwatcher.go#L118-L124 |
154,588 | juju/juju | state/watcher/hubwatcher.go | Watch | func (w *HubWatcher) Watch(collection string, id interface{}, ch chan<- Change) {
if id == nil {
panic("watcher: cannot watch a document with nil id")
}
// We use a value of -2 to indicate that we don't know the state of the document.
// -1 would indicate that we think the document is deleted (and won't trigger
// a change event if the document really is deleted).
w.sendAndWaitReq(reqWatch{
key: watchKey{collection, id},
info: watchInfo{ch, -2, nil},
registeredCh: make(chan error),
})
} | go | func (w *HubWatcher) Watch(collection string, id interface{}, ch chan<- Change) {
if id == nil {
panic("watcher: cannot watch a document with nil id")
}
// We use a value of -2 to indicate that we don't know the state of the document.
// -1 would indicate that we think the document is deleted (and won't trigger
// a change event if the document really is deleted).
w.sendAndWaitReq(reqWatch{
key: watchKey{collection, id},
info: watchInfo{ch, -2, nil},
registeredCh: make(chan error),
})
} | [
"func",
"(",
"w",
"*",
"HubWatcher",
")",
"Watch",
"(",
"collection",
"string",
",",
"id",
"interface",
"{",
"}",
",",
"ch",
"chan",
"<-",
"Change",
")",
"{",
"if",
"id",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// We use a value of -2 to indicate that we don't know the state of the document.",
"// -1 would indicate that we think the document is deleted (and won't trigger",
"// a change event if the document really is deleted).",
"w",
".",
"sendAndWaitReq",
"(",
"reqWatch",
"{",
"key",
":",
"watchKey",
"{",
"collection",
",",
"id",
"}",
",",
"info",
":",
"watchInfo",
"{",
"ch",
",",
"-",
"2",
",",
"nil",
"}",
",",
"registeredCh",
":",
"make",
"(",
"chan",
"error",
")",
",",
"}",
")",
"\n",
"}"
] | // Watch starts watching the given collection and document id.
// An event will be sent onto ch whenever a matching document's txn-revno
// field is observed to change after a transaction is applied. | [
"Watch",
"starts",
"watching",
"the",
"given",
"collection",
"and",
"document",
"id",
".",
"An",
"event",
"will",
"be",
"sent",
"onto",
"ch",
"whenever",
"a",
"matching",
"document",
"s",
"txn",
"-",
"revno",
"field",
"is",
"observed",
"to",
"change",
"after",
"a",
"transaction",
"is",
"applied",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher/hubwatcher.go#L253-L265 |
154,589 | juju/juju | state/watcher/hubwatcher.go | UnwatchCollection | func (w *HubWatcher) UnwatchCollection(collection string, ch chan<- Change) {
w.sendReq(reqUnwatch{watchKey{collection, nil}, ch})
} | go | func (w *HubWatcher) UnwatchCollection(collection string, ch chan<- Change) {
w.sendReq(reqUnwatch{watchKey{collection, nil}, ch})
} | [
"func",
"(",
"w",
"*",
"HubWatcher",
")",
"UnwatchCollection",
"(",
"collection",
"string",
",",
"ch",
"chan",
"<-",
"Change",
")",
"{",
"w",
".",
"sendReq",
"(",
"reqUnwatch",
"{",
"watchKey",
"{",
"collection",
",",
"nil",
"}",
",",
"ch",
"}",
")",
"\n",
"}"
] | // UnwatchCollection stops watching the given collection via ch. | [
"UnwatchCollection",
"stops",
"watching",
"the",
"given",
"collection",
"via",
"ch",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher/hubwatcher.go#L295-L297 |
154,590 | juju/juju | state/watcher/hubwatcher.go | Report | func (w *HubWatcher) Report() map[string]interface{} {
stats := w.Stats()
return map[string]interface{}{
"watch-count": stats.WatchCount,
"watch-key-count": stats.WatchKeyCount,
"sync-queue-cap": stats.SyncQueueCap,
"sync-queue-len": stats.SyncQueueLen,
"sync-last-len": stats.SyncLastLen,
"sync-avg-len": stats.SyncAvgLen,
"sync-max-len": stats.SyncMaxLen,
"sync-event-doc-count": stats.SyncEventDocCount,
"sync-event-coll-count": stats.SyncEventCollCount,
"request-count": stats.RequestCount,
"change-count": stats.ChangeCount,
}
} | go | func (w *HubWatcher) Report() map[string]interface{} {
stats := w.Stats()
return map[string]interface{}{
"watch-count": stats.WatchCount,
"watch-key-count": stats.WatchKeyCount,
"sync-queue-cap": stats.SyncQueueCap,
"sync-queue-len": stats.SyncQueueLen,
"sync-last-len": stats.SyncLastLen,
"sync-avg-len": stats.SyncAvgLen,
"sync-max-len": stats.SyncMaxLen,
"sync-event-doc-count": stats.SyncEventDocCount,
"sync-event-coll-count": stats.SyncEventCollCount,
"request-count": stats.RequestCount,
"change-count": stats.ChangeCount,
}
} | [
"func",
"(",
"w",
"*",
"HubWatcher",
")",
"Report",
"(",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"stats",
":=",
"w",
".",
"Stats",
"(",
")",
"\n",
"return",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"stats",
".",
"WatchCount",
",",
"\"",
"\"",
":",
"stats",
".",
"WatchKeyCount",
",",
"\"",
"\"",
":",
"stats",
".",
"SyncQueueCap",
",",
"\"",
"\"",
":",
"stats",
".",
"SyncQueueLen",
",",
"\"",
"\"",
":",
"stats",
".",
"SyncLastLen",
",",
"\"",
"\"",
":",
"stats",
".",
"SyncAvgLen",
",",
"\"",
"\"",
":",
"stats",
".",
"SyncMaxLen",
",",
"\"",
"\"",
":",
"stats",
".",
"SyncEventDocCount",
",",
"\"",
"\"",
":",
"stats",
".",
"SyncEventCollCount",
",",
"\"",
"\"",
":",
"stats",
".",
"RequestCount",
",",
"\"",
"\"",
":",
"stats",
".",
"ChangeCount",
",",
"}",
"\n",
"}"
] | // Report conforms to the worker.Runner.Report interface for returning information about the active worker. | [
"Report",
"conforms",
"to",
"the",
"worker",
".",
"Runner",
".",
"Report",
"interface",
"for",
"returning",
"information",
"about",
"the",
"active",
"worker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher/hubwatcher.go#L341-L356 |
154,591 | juju/juju | state/watcher/hubwatcher.go | queueChange | func (w *HubWatcher) queueChange(change Change) {
w.changeCount++
w.logger.Tracef("%p got change document: %#v", w, change)
key := watchKey{change.C, change.Id}
revno := change.Revno
// Queue notifications for per-collection watches.
for _, info := range w.watches[watchKey{change.C, nil}] {
if info.filter != nil && !info.filter(change.Id) {
continue
}
evt := event{
ch: info.ch,
key: key,
revno: revno,
}
w.syncEvents = append(w.syncEvents, evt)
w.syncEventCollectionCount++
w.logger.Tracef("%p adding event for collection %q watch %v, syncEvents: len(%d), cap(%d)", w, change.C, info.ch, len(w.syncEvents), cap(w.syncEvents))
}
// Queue notifications for per-document watches.
infos := w.watches[key]
for i, info := range infos {
if revno > info.revno || revno < 0 && info.revno >= 0 {
infos[i].revno = revno
evt := event{
ch: info.ch,
key: key,
revno: revno,
}
w.syncEvents = append(w.syncEvents, evt)
w.syncEventDocCount++
w.logger.Tracef("%p adding event for %v watch %v, syncEvents: len(%d), cap(%d)", w, key, info.ch, len(w.syncEvents), cap(w.syncEvents))
}
}
} | go | func (w *HubWatcher) queueChange(change Change) {
w.changeCount++
w.logger.Tracef("%p got change document: %#v", w, change)
key := watchKey{change.C, change.Id}
revno := change.Revno
// Queue notifications for per-collection watches.
for _, info := range w.watches[watchKey{change.C, nil}] {
if info.filter != nil && !info.filter(change.Id) {
continue
}
evt := event{
ch: info.ch,
key: key,
revno: revno,
}
w.syncEvents = append(w.syncEvents, evt)
w.syncEventCollectionCount++
w.logger.Tracef("%p adding event for collection %q watch %v, syncEvents: len(%d), cap(%d)", w, change.C, info.ch, len(w.syncEvents), cap(w.syncEvents))
}
// Queue notifications for per-document watches.
infos := w.watches[key]
for i, info := range infos {
if revno > info.revno || revno < 0 && info.revno >= 0 {
infos[i].revno = revno
evt := event{
ch: info.ch,
key: key,
revno: revno,
}
w.syncEvents = append(w.syncEvents, evt)
w.syncEventDocCount++
w.logger.Tracef("%p adding event for %v watch %v, syncEvents: len(%d), cap(%d)", w, key, info.ch, len(w.syncEvents), cap(w.syncEvents))
}
}
} | [
"func",
"(",
"w",
"*",
"HubWatcher",
")",
"queueChange",
"(",
"change",
"Change",
")",
"{",
"w",
".",
"changeCount",
"++",
"\n",
"w",
".",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"w",
",",
"change",
")",
"\n",
"key",
":=",
"watchKey",
"{",
"change",
".",
"C",
",",
"change",
".",
"Id",
"}",
"\n",
"revno",
":=",
"change",
".",
"Revno",
"\n\n",
"// Queue notifications for per-collection watches.",
"for",
"_",
",",
"info",
":=",
"range",
"w",
".",
"watches",
"[",
"watchKey",
"{",
"change",
".",
"C",
",",
"nil",
"}",
"]",
"{",
"if",
"info",
".",
"filter",
"!=",
"nil",
"&&",
"!",
"info",
".",
"filter",
"(",
"change",
".",
"Id",
")",
"{",
"continue",
"\n",
"}",
"\n",
"evt",
":=",
"event",
"{",
"ch",
":",
"info",
".",
"ch",
",",
"key",
":",
"key",
",",
"revno",
":",
"revno",
",",
"}",
"\n",
"w",
".",
"syncEvents",
"=",
"append",
"(",
"w",
".",
"syncEvents",
",",
"evt",
")",
"\n",
"w",
".",
"syncEventCollectionCount",
"++",
"\n",
"w",
".",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"w",
",",
"change",
".",
"C",
",",
"info",
".",
"ch",
",",
"len",
"(",
"w",
".",
"syncEvents",
")",
",",
"cap",
"(",
"w",
".",
"syncEvents",
")",
")",
"\n",
"}",
"\n\n",
"// Queue notifications for per-document watches.",
"infos",
":=",
"w",
".",
"watches",
"[",
"key",
"]",
"\n",
"for",
"i",
",",
"info",
":=",
"range",
"infos",
"{",
"if",
"revno",
">",
"info",
".",
"revno",
"||",
"revno",
"<",
"0",
"&&",
"info",
".",
"revno",
">=",
"0",
"{",
"infos",
"[",
"i",
"]",
".",
"revno",
"=",
"revno",
"\n",
"evt",
":=",
"event",
"{",
"ch",
":",
"info",
".",
"ch",
",",
"key",
":",
"key",
",",
"revno",
":",
"revno",
",",
"}",
"\n",
"w",
".",
"syncEvents",
"=",
"append",
"(",
"w",
".",
"syncEvents",
",",
"evt",
")",
"\n",
"w",
".",
"syncEventDocCount",
"++",
"\n",
"w",
".",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"w",
",",
"key",
",",
"info",
".",
"ch",
",",
"len",
"(",
"w",
".",
"syncEvents",
")",
",",
"cap",
"(",
"w",
".",
"syncEvents",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // queueChange queues up the change for the registered watchers. | [
"queueChange",
"queues",
"up",
"the",
"change",
"for",
"the",
"registered",
"watchers",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher/hubwatcher.go#L576-L612 |
154,592 | juju/juju | environs/bootstrap/prepare.go | Validate | func (p PrepareParams) Validate() error {
if err := p.ControllerConfig.Validate(); err != nil {
return errors.Annotate(err, "validating controller config")
}
if p.ControllerName == "" {
return errors.NotValidf("empty controller name")
}
if p.Cloud.Name == "" {
return errors.NotValidf("empty cloud name")
}
if p.AdminSecret == "" {
return errors.NotValidf("empty admin-secret")
}
return nil
} | go | func (p PrepareParams) Validate() error {
if err := p.ControllerConfig.Validate(); err != nil {
return errors.Annotate(err, "validating controller config")
}
if p.ControllerName == "" {
return errors.NotValidf("empty controller name")
}
if p.Cloud.Name == "" {
return errors.NotValidf("empty cloud name")
}
if p.AdminSecret == "" {
return errors.NotValidf("empty admin-secret")
}
return nil
} | [
"func",
"(",
"p",
"PrepareParams",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"p",
".",
"ControllerConfig",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"p",
".",
"ControllerName",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"p",
".",
"Cloud",
".",
"Name",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"p",
".",
"AdminSecret",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate validates the PrepareParams. | [
"Validate",
"validates",
"the",
"PrepareParams",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/prepare.go#L52-L66 |
154,593 | juju/juju | environs/bootstrap/prepare.go | PrepareController | func PrepareController(
isCAASController bool,
ctx environs.BootstrapContext,
store jujuclient.ClientStore,
args PrepareParams,
) (environs.BootstrapEnviron, error) {
if err := args.Validate(); err != nil {
return nil, errors.Trace(err)
}
_, err := store.ControllerByName(args.ControllerName)
if err == nil {
return nil, errors.AlreadyExistsf("controller %q", args.ControllerName)
} else if !errors.IsNotFound(err) {
return nil, errors.Annotatef(err, "error reading controller %q info", args.ControllerName)
}
cloudType, ok := args.ModelConfig["type"].(string)
if !ok {
return nil, errors.NotFoundf("cloud type in base configuration")
}
p, err := environs.Provider(cloudType)
if err != nil {
return nil, errors.Trace(err)
}
cfg, details, err := prepare(ctx, p, args)
if err != nil {
return nil, errors.Trace(err)
}
do := func() error {
if err := decorateAndWriteInfo(
store, details, args.ControllerName, cfg.Name(),
); err != nil {
return errors.Annotatef(err, "cannot create controller %q info", args.ControllerName)
}
return nil
}
var env environs.BootstrapEnviron
openParams := environs.OpenParams{
ControllerUUID: args.ControllerConfig.ControllerUUID(),
Cloud: args.Cloud,
Config: cfg,
}
if isCAASController {
details.ModelType = model.CAAS
env, err = caas.Open(p, openParams)
} else {
details.ModelType = model.IAAS
env, err = environs.Open(p, openParams)
}
if err != nil {
return nil, errors.Trace(err)
}
if err := env.PrepareForBootstrap(ctx, args.ControllerName); err != nil {
return nil, errors.Trace(err)
}
if err := do(); err != nil {
return nil, errors.Trace(err)
}
return env, nil
} | go | func PrepareController(
isCAASController bool,
ctx environs.BootstrapContext,
store jujuclient.ClientStore,
args PrepareParams,
) (environs.BootstrapEnviron, error) {
if err := args.Validate(); err != nil {
return nil, errors.Trace(err)
}
_, err := store.ControllerByName(args.ControllerName)
if err == nil {
return nil, errors.AlreadyExistsf("controller %q", args.ControllerName)
} else if !errors.IsNotFound(err) {
return nil, errors.Annotatef(err, "error reading controller %q info", args.ControllerName)
}
cloudType, ok := args.ModelConfig["type"].(string)
if !ok {
return nil, errors.NotFoundf("cloud type in base configuration")
}
p, err := environs.Provider(cloudType)
if err != nil {
return nil, errors.Trace(err)
}
cfg, details, err := prepare(ctx, p, args)
if err != nil {
return nil, errors.Trace(err)
}
do := func() error {
if err := decorateAndWriteInfo(
store, details, args.ControllerName, cfg.Name(),
); err != nil {
return errors.Annotatef(err, "cannot create controller %q info", args.ControllerName)
}
return nil
}
var env environs.BootstrapEnviron
openParams := environs.OpenParams{
ControllerUUID: args.ControllerConfig.ControllerUUID(),
Cloud: args.Cloud,
Config: cfg,
}
if isCAASController {
details.ModelType = model.CAAS
env, err = caas.Open(p, openParams)
} else {
details.ModelType = model.IAAS
env, err = environs.Open(p, openParams)
}
if err != nil {
return nil, errors.Trace(err)
}
if err := env.PrepareForBootstrap(ctx, args.ControllerName); err != nil {
return nil, errors.Trace(err)
}
if err := do(); err != nil {
return nil, errors.Trace(err)
}
return env, nil
} | [
"func",
"PrepareController",
"(",
"isCAASController",
"bool",
",",
"ctx",
"environs",
".",
"BootstrapContext",
",",
"store",
"jujuclient",
".",
"ClientStore",
",",
"args",
"PrepareParams",
",",
")",
"(",
"environs",
".",
"BootstrapEnviron",
",",
"error",
")",
"{",
"if",
"err",
":=",
"args",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
":=",
"store",
".",
"ControllerByName",
"(",
"args",
".",
"ControllerName",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"AlreadyExistsf",
"(",
"\"",
"\"",
",",
"args",
".",
"ControllerName",
")",
"\n",
"}",
"else",
"if",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"args",
".",
"ControllerName",
")",
"\n",
"}",
"\n\n",
"cloudType",
",",
"ok",
":=",
"args",
".",
"ModelConfig",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"p",
",",
"err",
":=",
"environs",
".",
"Provider",
"(",
"cloudType",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"cfg",
",",
"details",
",",
"err",
":=",
"prepare",
"(",
"ctx",
",",
"p",
",",
"args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"do",
":=",
"func",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"decorateAndWriteInfo",
"(",
"store",
",",
"details",
",",
"args",
".",
"ControllerName",
",",
"cfg",
".",
"Name",
"(",
")",
",",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"args",
".",
"ControllerName",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"var",
"env",
"environs",
".",
"BootstrapEnviron",
"\n",
"openParams",
":=",
"environs",
".",
"OpenParams",
"{",
"ControllerUUID",
":",
"args",
".",
"ControllerConfig",
".",
"ControllerUUID",
"(",
")",
",",
"Cloud",
":",
"args",
".",
"Cloud",
",",
"Config",
":",
"cfg",
",",
"}",
"\n",
"if",
"isCAASController",
"{",
"details",
".",
"ModelType",
"=",
"model",
".",
"CAAS",
"\n",
"env",
",",
"err",
"=",
"caas",
".",
"Open",
"(",
"p",
",",
"openParams",
")",
"\n",
"}",
"else",
"{",
"details",
".",
"ModelType",
"=",
"model",
".",
"IAAS",
"\n",
"env",
",",
"err",
"=",
"environs",
".",
"Open",
"(",
"p",
",",
"openParams",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"env",
".",
"PrepareForBootstrap",
"(",
"ctx",
",",
"args",
".",
"ControllerName",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"do",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"env",
",",
"nil",
"\n",
"}"
] | // PrepareController prepares a new controller based on the provided configuration.
// It is an error to prepare a controller if there already exists an
// entry in the client store with the same name.
//
// Upon success, Prepare will update the ClientStore with the details of
// the controller, admin account, and admin model. | [
"PrepareController",
"prepares",
"a",
"new",
"controller",
"based",
"on",
"the",
"provided",
"configuration",
".",
"It",
"is",
"an",
"error",
"to",
"prepare",
"a",
"controller",
"if",
"there",
"already",
"exists",
"an",
"entry",
"in",
"the",
"client",
"store",
"with",
"the",
"same",
"name",
".",
"Upon",
"success",
"Prepare",
"will",
"update",
"the",
"ClientStore",
"with",
"the",
"details",
"of",
"the",
"controller",
"admin",
"account",
"and",
"admin",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/prepare.go#L74-L139 |
154,594 | juju/juju | environs/bootstrap/prepare.go | decorateAndWriteInfo | func decorateAndWriteInfo(
store jujuclient.ClientStore,
details prepareDetails,
controllerName, modelName string,
) error {
qualifiedModelName := jujuclient.JoinOwnerModelName(
names.NewUserTag(details.AccountDetails.User),
modelName,
)
if err := store.AddController(controllerName, details.ControllerDetails); err != nil {
return errors.Trace(err)
}
if err := store.UpdateBootstrapConfig(controllerName, details.BootstrapConfig); err != nil {
return errors.Trace(err)
}
if err := store.UpdateAccount(controllerName, details.AccountDetails); err != nil {
return errors.Trace(err)
}
if err := store.UpdateModel(controllerName, qualifiedModelName, details.ModelDetails); err != nil {
return errors.Trace(err)
}
if err := store.SetCurrentModel(controllerName, qualifiedModelName); err != nil {
return errors.Trace(err)
}
return nil
} | go | func decorateAndWriteInfo(
store jujuclient.ClientStore,
details prepareDetails,
controllerName, modelName string,
) error {
qualifiedModelName := jujuclient.JoinOwnerModelName(
names.NewUserTag(details.AccountDetails.User),
modelName,
)
if err := store.AddController(controllerName, details.ControllerDetails); err != nil {
return errors.Trace(err)
}
if err := store.UpdateBootstrapConfig(controllerName, details.BootstrapConfig); err != nil {
return errors.Trace(err)
}
if err := store.UpdateAccount(controllerName, details.AccountDetails); err != nil {
return errors.Trace(err)
}
if err := store.UpdateModel(controllerName, qualifiedModelName, details.ModelDetails); err != nil {
return errors.Trace(err)
}
if err := store.SetCurrentModel(controllerName, qualifiedModelName); err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"decorateAndWriteInfo",
"(",
"store",
"jujuclient",
".",
"ClientStore",
",",
"details",
"prepareDetails",
",",
"controllerName",
",",
"modelName",
"string",
",",
")",
"error",
"{",
"qualifiedModelName",
":=",
"jujuclient",
".",
"JoinOwnerModelName",
"(",
"names",
".",
"NewUserTag",
"(",
"details",
".",
"AccountDetails",
".",
"User",
")",
",",
"modelName",
",",
")",
"\n",
"if",
"err",
":=",
"store",
".",
"AddController",
"(",
"controllerName",
",",
"details",
".",
"ControllerDetails",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"store",
".",
"UpdateBootstrapConfig",
"(",
"controllerName",
",",
"details",
".",
"BootstrapConfig",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"store",
".",
"UpdateAccount",
"(",
"controllerName",
",",
"details",
".",
"AccountDetails",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"store",
".",
"UpdateModel",
"(",
"controllerName",
",",
"qualifiedModelName",
",",
"details",
".",
"ModelDetails",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"store",
".",
"SetCurrentModel",
"(",
"controllerName",
",",
"qualifiedModelName",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // decorateAndWriteInfo decorates the info struct with information
// from the given cfg, and the writes that out to the filesystem. | [
"decorateAndWriteInfo",
"decorates",
"the",
"info",
"struct",
"with",
"information",
"from",
"the",
"given",
"cfg",
"and",
"the",
"writes",
"that",
"out",
"to",
"the",
"filesystem",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/prepare.go#L143-L168 |
154,595 | juju/juju | apiserver/facades/agent/metricsender/sender.go | Send | func (s *HTTPSender) Send(metrics []*wireformat.MetricBatch) (*wireformat.Response, error) {
b, err := json.Marshal(metrics)
if err != nil {
return nil, errors.Trace(err)
}
r := bytes.NewBuffer(b)
client := &http.Client{}
resp, err := client.Post(s.url, "application/json", r)
if err != nil {
return nil, errors.Trace(err)
}
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("failed to send metrics http %v", resp.StatusCode)
}
defer resp.Body.Close()
respReader := json.NewDecoder(resp.Body)
metricsResponse := wireformat.Response{}
err = respReader.Decode(&metricsResponse)
if err != nil {
return nil, errors.Trace(err)
}
return &metricsResponse, nil
} | go | func (s *HTTPSender) Send(metrics []*wireformat.MetricBatch) (*wireformat.Response, error) {
b, err := json.Marshal(metrics)
if err != nil {
return nil, errors.Trace(err)
}
r := bytes.NewBuffer(b)
client := &http.Client{}
resp, err := client.Post(s.url, "application/json", r)
if err != nil {
return nil, errors.Trace(err)
}
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("failed to send metrics http %v", resp.StatusCode)
}
defer resp.Body.Close()
respReader := json.NewDecoder(resp.Body)
metricsResponse := wireformat.Response{}
err = respReader.Decode(&metricsResponse)
if err != nil {
return nil, errors.Trace(err)
}
return &metricsResponse, nil
} | [
"func",
"(",
"s",
"*",
"HTTPSender",
")",
"Send",
"(",
"metrics",
"[",
"]",
"*",
"wireformat",
".",
"MetricBatch",
")",
"(",
"*",
"wireformat",
".",
"Response",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"metrics",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"r",
":=",
"bytes",
".",
"NewBuffer",
"(",
"b",
")",
"\n",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"}",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"Post",
"(",
"s",
".",
"url",
",",
"\"",
"\"",
",",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
".",
"StatusCode",
")",
"\n",
"}",
"\n\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"respReader",
":=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
"\n",
"metricsResponse",
":=",
"wireformat",
".",
"Response",
"{",
"}",
"\n",
"err",
"=",
"respReader",
".",
"Decode",
"(",
"&",
"metricsResponse",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"metricsResponse",
",",
"nil",
"\n",
"}"
] | // Send sends the given metrics to the collector service. | [
"Send",
"sends",
"the",
"given",
"metrics",
"to",
"the",
"collector",
"service",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/metricsender/sender.go#L22-L45 |
154,596 | juju/juju | apiserver/common/permissions.go | HasPermission | func HasPermission(
accessGetter userAccessFunc, utag names.Tag,
requestedPermission permission.Access, target names.Tag,
) (bool, error) {
var validate func(permission.Access) error
switch target.Kind() {
case names.ControllerTagKind:
validate = permission.ValidateControllerAccess
case names.ModelTagKind:
validate = permission.ValidateModelAccess
case names.ApplicationOfferTagKind:
validate = permission.ValidateOfferAccess
case names.CloudTagKind:
validate = permission.ValidateCloudAccess
default:
return false, nil
}
if err := validate(requestedPermission); err != nil {
return false, nil
}
userTag, ok := utag.(names.UserTag)
if !ok {
// lets not reveal more than is strictly necessary
return false, nil
}
userAccess, err := GetPermission(accessGetter, userTag, target)
if err != nil && !errors.IsNotFound(err) {
return false, errors.Annotatef(err, "while obtaining %s user", target.Kind())
}
// returning this kind of information would be too much information to reveal too.
if errors.IsNotFound(err) || userAccess == permission.NoAccess {
return false, nil
}
modelPermission := userAccess.EqualOrGreaterModelAccessThan(requestedPermission) && target.Kind() == names.ModelTagKind
controllerPermission := userAccess.EqualOrGreaterControllerAccessThan(requestedPermission) && target.Kind() == names.ControllerTagKind
offerPermission := userAccess.EqualOrGreaterOfferAccessThan(requestedPermission) && target.Kind() == names.ApplicationOfferTagKind
cloudPermission := userAccess.EqualOrGreaterCloudAccessThan(requestedPermission) && target.Kind() == names.CloudTagKind
if !controllerPermission && !modelPermission && !offerPermission && !cloudPermission {
return false, nil
}
return true, nil
} | go | func HasPermission(
accessGetter userAccessFunc, utag names.Tag,
requestedPermission permission.Access, target names.Tag,
) (bool, error) {
var validate func(permission.Access) error
switch target.Kind() {
case names.ControllerTagKind:
validate = permission.ValidateControllerAccess
case names.ModelTagKind:
validate = permission.ValidateModelAccess
case names.ApplicationOfferTagKind:
validate = permission.ValidateOfferAccess
case names.CloudTagKind:
validate = permission.ValidateCloudAccess
default:
return false, nil
}
if err := validate(requestedPermission); err != nil {
return false, nil
}
userTag, ok := utag.(names.UserTag)
if !ok {
// lets not reveal more than is strictly necessary
return false, nil
}
userAccess, err := GetPermission(accessGetter, userTag, target)
if err != nil && !errors.IsNotFound(err) {
return false, errors.Annotatef(err, "while obtaining %s user", target.Kind())
}
// returning this kind of information would be too much information to reveal too.
if errors.IsNotFound(err) || userAccess == permission.NoAccess {
return false, nil
}
modelPermission := userAccess.EqualOrGreaterModelAccessThan(requestedPermission) && target.Kind() == names.ModelTagKind
controllerPermission := userAccess.EqualOrGreaterControllerAccessThan(requestedPermission) && target.Kind() == names.ControllerTagKind
offerPermission := userAccess.EqualOrGreaterOfferAccessThan(requestedPermission) && target.Kind() == names.ApplicationOfferTagKind
cloudPermission := userAccess.EqualOrGreaterCloudAccessThan(requestedPermission) && target.Kind() == names.CloudTagKind
if !controllerPermission && !modelPermission && !offerPermission && !cloudPermission {
return false, nil
}
return true, nil
} | [
"func",
"HasPermission",
"(",
"accessGetter",
"userAccessFunc",
",",
"utag",
"names",
".",
"Tag",
",",
"requestedPermission",
"permission",
".",
"Access",
",",
"target",
"names",
".",
"Tag",
",",
")",
"(",
"bool",
",",
"error",
")",
"{",
"var",
"validate",
"func",
"(",
"permission",
".",
"Access",
")",
"error",
"\n",
"switch",
"target",
".",
"Kind",
"(",
")",
"{",
"case",
"names",
".",
"ControllerTagKind",
":",
"validate",
"=",
"permission",
".",
"ValidateControllerAccess",
"\n",
"case",
"names",
".",
"ModelTagKind",
":",
"validate",
"=",
"permission",
".",
"ValidateModelAccess",
"\n",
"case",
"names",
".",
"ApplicationOfferTagKind",
":",
"validate",
"=",
"permission",
".",
"ValidateOfferAccess",
"\n",
"case",
"names",
".",
"CloudTagKind",
":",
"validate",
"=",
"permission",
".",
"ValidateCloudAccess",
"\n",
"default",
":",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"validate",
"(",
"requestedPermission",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"userTag",
",",
"ok",
":=",
"utag",
".",
"(",
"names",
".",
"UserTag",
")",
"\n",
"if",
"!",
"ok",
"{",
"// lets not reveal more than is strictly necessary",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"userAccess",
",",
"err",
":=",
"GetPermission",
"(",
"accessGetter",
",",
"userTag",
",",
"target",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"false",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"target",
".",
"Kind",
"(",
")",
")",
"\n",
"}",
"\n",
"// returning this kind of information would be too much information to reveal too.",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"||",
"userAccess",
"==",
"permission",
".",
"NoAccess",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"modelPermission",
":=",
"userAccess",
".",
"EqualOrGreaterModelAccessThan",
"(",
"requestedPermission",
")",
"&&",
"target",
".",
"Kind",
"(",
")",
"==",
"names",
".",
"ModelTagKind",
"\n",
"controllerPermission",
":=",
"userAccess",
".",
"EqualOrGreaterControllerAccessThan",
"(",
"requestedPermission",
")",
"&&",
"target",
".",
"Kind",
"(",
")",
"==",
"names",
".",
"ControllerTagKind",
"\n",
"offerPermission",
":=",
"userAccess",
".",
"EqualOrGreaterOfferAccessThan",
"(",
"requestedPermission",
")",
"&&",
"target",
".",
"Kind",
"(",
")",
"==",
"names",
".",
"ApplicationOfferTagKind",
"\n",
"cloudPermission",
":=",
"userAccess",
".",
"EqualOrGreaterCloudAccessThan",
"(",
"requestedPermission",
")",
"&&",
"target",
".",
"Kind",
"(",
")",
"==",
"names",
".",
"CloudTagKind",
"\n",
"if",
"!",
"controllerPermission",
"&&",
"!",
"modelPermission",
"&&",
"!",
"offerPermission",
"&&",
"!",
"cloudPermission",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // HasPermission returns true if the specified user has the specified
// permission on target. | [
"HasPermission",
"returns",
"true",
"if",
"the",
"specified",
"user",
"has",
"the",
"specified",
"permission",
"on",
"target",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/permissions.go#L22-L66 |
154,597 | juju/juju | apiserver/common/permissions.go | GetPermission | func GetPermission(accessGetter userAccessFunc, userTag names.UserTag, target names.Tag) (permission.Access, error) {
userAccess, err := accessGetter(userTag, target)
if err != nil && !errors.IsNotFound(err) {
return permission.NoAccess, errors.Annotatef(err, "while obtaining %s user", target.Kind())
}
// there is a special case for external users, a group called everyone@external
if !userTag.IsLocal() {
// TODO(perrito666) remove the following section about everyone group
// when groups are implemented.
everyoneTag := names.NewUserTag(EveryoneTagName)
everyoneAccess, err := accessGetter(everyoneTag, target)
if err != nil && !errors.IsNotFound(err) {
return permission.NoAccess, errors.Trace(err)
}
if userAccess == permission.NoAccess && everyoneAccess != permission.NoAccess {
userAccess = everyoneAccess
}
if everyoneAccess.EqualOrGreaterControllerAccessThan(userAccess) {
userAccess = everyoneAccess
}
}
return userAccess, nil
} | go | func GetPermission(accessGetter userAccessFunc, userTag names.UserTag, target names.Tag) (permission.Access, error) {
userAccess, err := accessGetter(userTag, target)
if err != nil && !errors.IsNotFound(err) {
return permission.NoAccess, errors.Annotatef(err, "while obtaining %s user", target.Kind())
}
// there is a special case for external users, a group called everyone@external
if !userTag.IsLocal() {
// TODO(perrito666) remove the following section about everyone group
// when groups are implemented.
everyoneTag := names.NewUserTag(EveryoneTagName)
everyoneAccess, err := accessGetter(everyoneTag, target)
if err != nil && !errors.IsNotFound(err) {
return permission.NoAccess, errors.Trace(err)
}
if userAccess == permission.NoAccess && everyoneAccess != permission.NoAccess {
userAccess = everyoneAccess
}
if everyoneAccess.EqualOrGreaterControllerAccessThan(userAccess) {
userAccess = everyoneAccess
}
}
return userAccess, nil
} | [
"func",
"GetPermission",
"(",
"accessGetter",
"userAccessFunc",
",",
"userTag",
"names",
".",
"UserTag",
",",
"target",
"names",
".",
"Tag",
")",
"(",
"permission",
".",
"Access",
",",
"error",
")",
"{",
"userAccess",
",",
"err",
":=",
"accessGetter",
"(",
"userTag",
",",
"target",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"permission",
".",
"NoAccess",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"target",
".",
"Kind",
"(",
")",
")",
"\n",
"}",
"\n",
"// there is a special case for external users, a group called everyone@external",
"if",
"!",
"userTag",
".",
"IsLocal",
"(",
")",
"{",
"// TODO(perrito666) remove the following section about everyone group",
"// when groups are implemented.",
"everyoneTag",
":=",
"names",
".",
"NewUserTag",
"(",
"EveryoneTagName",
")",
"\n",
"everyoneAccess",
",",
"err",
":=",
"accessGetter",
"(",
"everyoneTag",
",",
"target",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"permission",
".",
"NoAccess",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"userAccess",
"==",
"permission",
".",
"NoAccess",
"&&",
"everyoneAccess",
"!=",
"permission",
".",
"NoAccess",
"{",
"userAccess",
"=",
"everyoneAccess",
"\n",
"}",
"\n",
"if",
"everyoneAccess",
".",
"EqualOrGreaterControllerAccessThan",
"(",
"userAccess",
")",
"{",
"userAccess",
"=",
"everyoneAccess",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"userAccess",
",",
"nil",
"\n",
"}"
] | // GetPermission returns the permission a user has on the specified target. | [
"GetPermission",
"returns",
"the",
"permission",
"a",
"user",
"has",
"on",
"the",
"specified",
"target",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/permissions.go#L69-L91 |
154,598 | juju/juju | apiserver/common/permissions.go | HasModelAdmin | func HasModelAdmin(
authorizer facade.Authorizer,
user names.UserTag,
controllerTag names.ControllerTag,
model Model,
) (bool, error) {
// superusers have admin for all models.
if isSuperUser, err := authorizer.HasPermission(permission.SuperuserAccess, controllerTag); err != nil || isSuperUser {
return isSuperUser, err
}
return authorizer.HasPermission(permission.AdminAccess, model.ModelTag())
} | go | func HasModelAdmin(
authorizer facade.Authorizer,
user names.UserTag,
controllerTag names.ControllerTag,
model Model,
) (bool, error) {
// superusers have admin for all models.
if isSuperUser, err := authorizer.HasPermission(permission.SuperuserAccess, controllerTag); err != nil || isSuperUser {
return isSuperUser, err
}
return authorizer.HasPermission(permission.AdminAccess, model.ModelTag())
} | [
"func",
"HasModelAdmin",
"(",
"authorizer",
"facade",
".",
"Authorizer",
",",
"user",
"names",
".",
"UserTag",
",",
"controllerTag",
"names",
".",
"ControllerTag",
",",
"model",
"Model",
",",
")",
"(",
"bool",
",",
"error",
")",
"{",
"// superusers have admin for all models.",
"if",
"isSuperUser",
",",
"err",
":=",
"authorizer",
".",
"HasPermission",
"(",
"permission",
".",
"SuperuserAccess",
",",
"controllerTag",
")",
";",
"err",
"!=",
"nil",
"||",
"isSuperUser",
"{",
"return",
"isSuperUser",
",",
"err",
"\n",
"}",
"\n",
"return",
"authorizer",
".",
"HasPermission",
"(",
"permission",
".",
"AdminAccess",
",",
"model",
".",
"ModelTag",
"(",
")",
")",
"\n",
"}"
] | // HasModelAdmin reports whether or not a user has admin access to the
// specified model. A user has model access if they are a controller
// superuser, or if they have been explicitly granted admin access to the
// model. | [
"HasModelAdmin",
"reports",
"whether",
"or",
"not",
"a",
"user",
"has",
"admin",
"access",
"to",
"the",
"specified",
"model",
".",
"A",
"user",
"has",
"model",
"access",
"if",
"they",
"are",
"a",
"controller",
"superuser",
"or",
"if",
"they",
"have",
"been",
"explicitly",
"granted",
"admin",
"access",
"to",
"the",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/permissions.go#L97-L108 |
154,599 | juju/juju | state/resources_state_resource.go | ListResources | func (st resourceState) ListResources(applicationID string) (resource.ApplicationResources, error) {
resources, err := st.persist.ListResources(applicationID)
if err != nil {
if err := st.raw.VerifyApplication(applicationID); err != nil {
return resource.ApplicationResources{}, errors.Trace(err)
}
return resource.ApplicationResources{}, errors.Trace(err)
}
unitIDs, err := st.raw.Units(applicationID)
if err != nil {
return resource.ApplicationResources{}, errors.Trace(err)
}
for _, unitID := range unitIDs {
found := false
for _, unitRes := range resources.UnitResources {
if unitID.String() == unitRes.Tag.String() {
found = true
break
}
}
if !found {
unitRes := resource.UnitResources{
Tag: unitID,
}
resources.UnitResources = append(resources.UnitResources, unitRes)
}
}
return resources, nil
} | go | func (st resourceState) ListResources(applicationID string) (resource.ApplicationResources, error) {
resources, err := st.persist.ListResources(applicationID)
if err != nil {
if err := st.raw.VerifyApplication(applicationID); err != nil {
return resource.ApplicationResources{}, errors.Trace(err)
}
return resource.ApplicationResources{}, errors.Trace(err)
}
unitIDs, err := st.raw.Units(applicationID)
if err != nil {
return resource.ApplicationResources{}, errors.Trace(err)
}
for _, unitID := range unitIDs {
found := false
for _, unitRes := range resources.UnitResources {
if unitID.String() == unitRes.Tag.String() {
found = true
break
}
}
if !found {
unitRes := resource.UnitResources{
Tag: unitID,
}
resources.UnitResources = append(resources.UnitResources, unitRes)
}
}
return resources, nil
} | [
"func",
"(",
"st",
"resourceState",
")",
"ListResources",
"(",
"applicationID",
"string",
")",
"(",
"resource",
".",
"ApplicationResources",
",",
"error",
")",
"{",
"resources",
",",
"err",
":=",
"st",
".",
"persist",
".",
"ListResources",
"(",
"applicationID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
":=",
"st",
".",
"raw",
".",
"VerifyApplication",
"(",
"applicationID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"resource",
".",
"ApplicationResources",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"resource",
".",
"ApplicationResources",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"unitIDs",
",",
"err",
":=",
"st",
".",
"raw",
".",
"Units",
"(",
"applicationID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"resource",
".",
"ApplicationResources",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"unitID",
":=",
"range",
"unitIDs",
"{",
"found",
":=",
"false",
"\n",
"for",
"_",
",",
"unitRes",
":=",
"range",
"resources",
".",
"UnitResources",
"{",
"if",
"unitID",
".",
"String",
"(",
")",
"==",
"unitRes",
".",
"Tag",
".",
"String",
"(",
")",
"{",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"unitRes",
":=",
"resource",
".",
"UnitResources",
"{",
"Tag",
":",
"unitID",
",",
"}",
"\n",
"resources",
".",
"UnitResources",
"=",
"append",
"(",
"resources",
".",
"UnitResources",
",",
"unitRes",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"resources",
",",
"nil",
"\n",
"}"
] | // ListResources returns the resource data for the given application ID. | [
"ListResources",
"returns",
"the",
"resource",
"data",
"for",
"the",
"given",
"application",
"ID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_state_resource.go#L89-L119 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.