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
|
---|---|---|---|---|---|---|---|---|---|---|---|
4,000 | juju/juju | state/controlleruser.go | setControllerAccess | func (st *State) setControllerAccess(access permission.Access, userGlobalKey string) error {
if err := permission.ValidateControllerAccess(access); err != nil {
return errors.Trace(err)
}
op := updatePermissionOp(controllerKey(st.ControllerUUID()), userGlobalKey, access)
err := st.db().RunTransaction([]txn.Op{op})
if err == txn.ErrAborted {
return errors.NotFoundf("existing permissions")
}
return errors.Trace(err)
} | go | func (st *State) setControllerAccess(access permission.Access, userGlobalKey string) error {
if err := permission.ValidateControllerAccess(access); err != nil {
return errors.Trace(err)
}
op := updatePermissionOp(controllerKey(st.ControllerUUID()), userGlobalKey, access)
err := st.db().RunTransaction([]txn.Op{op})
if err == txn.ErrAborted {
return errors.NotFoundf("existing permissions")
}
return errors.Trace(err)
} | [
"func",
"(",
"st",
"*",
"State",
")",
"setControllerAccess",
"(",
"access",
"permission",
".",
"Access",
",",
"userGlobalKey",
"string",
")",
"error",
"{",
"if",
"err",
":=",
"permission",
".",
"ValidateControllerAccess",
"(",
"access",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"op",
":=",
"updatePermissionOp",
"(",
"controllerKey",
"(",
"st",
".",
"ControllerUUID",
"(",
")",
")",
",",
"userGlobalKey",
",",
"access",
")",
"\n\n",
"err",
":=",
"st",
".",
"db",
"(",
")",
".",
"RunTransaction",
"(",
"[",
"]",
"txn",
".",
"Op",
"{",
"op",
"}",
")",
"\n",
"if",
"err",
"==",
"txn",
".",
"ErrAborted",
"{",
"return",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // setAccess changes the user's access permissions on the controller. | [
"setAccess",
"changes",
"the",
"user",
"s",
"access",
"permissions",
"on",
"the",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/controlleruser.go#L22-L33 |
4,001 | juju/juju | state/controlleruser.go | controllerUser | func (st *State) controllerUser(user names.UserTag) (userAccessDoc, error) {
controllerUser := userAccessDoc{}
controllerUsers, closer := st.db().GetCollection(controllerUsersC)
defer closer()
username := strings.ToLower(user.Id())
err := controllerUsers.FindId(username).One(&controllerUser)
if err == mgo.ErrNotFound {
return userAccessDoc{}, errors.NotFoundf("controller user %q", user.Id())
}
// DateCreated is inserted as UTC, but read out as local time. So we
// convert it back to UTC here.
controllerUser.DateCreated = controllerUser.DateCreated.UTC()
return controllerUser, nil
} | go | func (st *State) controllerUser(user names.UserTag) (userAccessDoc, error) {
controllerUser := userAccessDoc{}
controllerUsers, closer := st.db().GetCollection(controllerUsersC)
defer closer()
username := strings.ToLower(user.Id())
err := controllerUsers.FindId(username).One(&controllerUser)
if err == mgo.ErrNotFound {
return userAccessDoc{}, errors.NotFoundf("controller user %q", user.Id())
}
// DateCreated is inserted as UTC, but read out as local time. So we
// convert it back to UTC here.
controllerUser.DateCreated = controllerUser.DateCreated.UTC()
return controllerUser, nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"controllerUser",
"(",
"user",
"names",
".",
"UserTag",
")",
"(",
"userAccessDoc",
",",
"error",
")",
"{",
"controllerUser",
":=",
"userAccessDoc",
"{",
"}",
"\n",
"controllerUsers",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"controllerUsersC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"username",
":=",
"strings",
".",
"ToLower",
"(",
"user",
".",
"Id",
"(",
")",
")",
"\n",
"err",
":=",
"controllerUsers",
".",
"FindId",
"(",
"username",
")",
".",
"One",
"(",
"&",
"controllerUser",
")",
"\n",
"if",
"err",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"userAccessDoc",
"{",
"}",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"user",
".",
"Id",
"(",
")",
")",
"\n",
"}",
"\n",
"// DateCreated is inserted as UTC, but read out as local time. So we",
"// convert it back to UTC here.",
"controllerUser",
".",
"DateCreated",
"=",
"controllerUser",
".",
"DateCreated",
".",
"UTC",
"(",
")",
"\n",
"return",
"controllerUser",
",",
"nil",
"\n",
"}"
] | // controllerUser a model userAccessDoc. | [
"controllerUser",
"a",
"model",
"userAccessDoc",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/controlleruser.go#L36-L50 |
4,002 | juju/juju | state/controlleruser.go | removeControllerUser | func (st *State) removeControllerUser(user names.UserTag) error {
ops := removeControllerUserOps(st.ControllerUUID(), user)
err := st.db().RunTransaction(ops)
if err == txn.ErrAborted {
err = errors.NewNotFound(nil, fmt.Sprintf("controller user %q does not exist", user.Id()))
}
if err != nil {
return errors.Trace(err)
}
return nil
} | go | func (st *State) removeControllerUser(user names.UserTag) error {
ops := removeControllerUserOps(st.ControllerUUID(), user)
err := st.db().RunTransaction(ops)
if err == txn.ErrAborted {
err = errors.NewNotFound(nil, fmt.Sprintf("controller user %q does not exist", user.Id()))
}
if err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"removeControllerUser",
"(",
"user",
"names",
".",
"UserTag",
")",
"error",
"{",
"ops",
":=",
"removeControllerUserOps",
"(",
"st",
".",
"ControllerUUID",
"(",
")",
",",
"user",
")",
"\n",
"err",
":=",
"st",
".",
"db",
"(",
")",
".",
"RunTransaction",
"(",
"ops",
")",
"\n",
"if",
"err",
"==",
"txn",
".",
"ErrAborted",
"{",
"err",
"=",
"errors",
".",
"NewNotFound",
"(",
"nil",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"user",
".",
"Id",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // RemoveControllerUser removes a user from the database. | [
"RemoveControllerUser",
"removes",
"a",
"user",
"from",
"the",
"database",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/controlleruser.go#L87-L97 |
4,003 | juju/juju | api/backups/info.go | Info | func (c *Client) Info(id string) (*params.BackupsMetadataResult, error) {
var result params.BackupsMetadataResult
args := params.BackupsInfoArgs{ID: id}
if err := c.facade.FacadeCall("Info", args, &result); err != nil {
return nil, errors.Trace(err)
}
return &result, nil
} | go | func (c *Client) Info(id string) (*params.BackupsMetadataResult, error) {
var result params.BackupsMetadataResult
args := params.BackupsInfoArgs{ID: id}
if err := c.facade.FacadeCall("Info", args, &result); err != nil {
return nil, errors.Trace(err)
}
return &result, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Info",
"(",
"id",
"string",
")",
"(",
"*",
"params",
".",
"BackupsMetadataResult",
",",
"error",
")",
"{",
"var",
"result",
"params",
".",
"BackupsMetadataResult",
"\n",
"args",
":=",
"params",
".",
"BackupsInfoArgs",
"{",
"ID",
":",
"id",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"result",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"result",
",",
"nil",
"\n",
"}"
] | // Info implements the API method. | [
"Info",
"implements",
"the",
"API",
"method",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/backups/info.go#L13-L20 |
4,004 | juju/juju | apiserver/facades/client/application/get.go | Get | func (api *APIv5) Get(args params.ApplicationGet) (params.ApplicationGetResults, error) {
results, err := api.getConfig(args, describe)
if err != nil {
return params.ApplicationGetResults{}, err
}
results.ApplicationConfig = nil
return results, nil
} | go | func (api *APIv5) Get(args params.ApplicationGet) (params.ApplicationGetResults, error) {
results, err := api.getConfig(args, describe)
if err != nil {
return params.ApplicationGetResults{}, err
}
results.ApplicationConfig = nil
return results, nil
} | [
"func",
"(",
"api",
"*",
"APIv5",
")",
"Get",
"(",
"args",
"params",
".",
"ApplicationGet",
")",
"(",
"params",
".",
"ApplicationGetResults",
",",
"error",
")",
"{",
"results",
",",
"err",
":=",
"api",
".",
"getConfig",
"(",
"args",
",",
"describe",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ApplicationGetResults",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"results",
".",
"ApplicationConfig",
"=",
"nil",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // Get returns the charm configuration for an application.
// It zeros out any application config as that was not supported in v5. | [
"Get",
"returns",
"the",
"charm",
"configuration",
"for",
"an",
"application",
".",
"It",
"zeros",
"out",
"any",
"application",
"config",
"as",
"that",
"was",
"not",
"supported",
"in",
"v5",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/application/get.go#L25-L32 |
4,005 | juju/juju | apiserver/facades/client/application/get.go | Get | func (api *APIv4) Get(args params.ApplicationGet) (params.ApplicationGetResults, error) {
results, err := api.getConfig(args, describeV4)
if err != nil {
return params.ApplicationGetResults{}, err
}
results.ApplicationConfig = nil
return results, nil
} | go | func (api *APIv4) Get(args params.ApplicationGet) (params.ApplicationGetResults, error) {
results, err := api.getConfig(args, describeV4)
if err != nil {
return params.ApplicationGetResults{}, err
}
results.ApplicationConfig = nil
return results, nil
} | [
"func",
"(",
"api",
"*",
"APIv4",
")",
"Get",
"(",
"args",
"params",
".",
"ApplicationGet",
")",
"(",
"params",
".",
"ApplicationGetResults",
",",
"error",
")",
"{",
"results",
",",
"err",
":=",
"api",
".",
"getConfig",
"(",
"args",
",",
"describeV4",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ApplicationGetResults",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"results",
".",
"ApplicationConfig",
"=",
"nil",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // Get returns the charm configuration for an application.
// This used the confusing "default" boolean to mean the value was set from
// the charm defaults. Needs to be kept for backwards compatibility. | [
"Get",
"returns",
"the",
"charm",
"configuration",
"for",
"an",
"application",
".",
"This",
"used",
"the",
"confusing",
"default",
"boolean",
"to",
"mean",
"the",
"value",
"was",
"set",
"from",
"the",
"charm",
"defaults",
".",
"Needs",
"to",
"be",
"kept",
"for",
"backwards",
"compatibility",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/application/get.go#L37-L44 |
4,006 | juju/juju | state/useraccess.go | AddUser | func (m *Model) AddUser(spec UserAccessSpec) (permission.UserAccess, error) {
if err := permission.ValidateModelAccess(spec.Access); err != nil {
return permission.UserAccess{}, errors.Annotate(err, "adding model user")
}
target := userAccessTarget{
uuid: m.UUID(),
globalKey: modelGlobalKey,
}
return m.st.addUserAccess(spec, target)
} | go | func (m *Model) AddUser(spec UserAccessSpec) (permission.UserAccess, error) {
if err := permission.ValidateModelAccess(spec.Access); err != nil {
return permission.UserAccess{}, errors.Annotate(err, "adding model user")
}
target := userAccessTarget{
uuid: m.UUID(),
globalKey: modelGlobalKey,
}
return m.st.addUserAccess(spec, target)
} | [
"func",
"(",
"m",
"*",
"Model",
")",
"AddUser",
"(",
"spec",
"UserAccessSpec",
")",
"(",
"permission",
".",
"UserAccess",
",",
"error",
")",
"{",
"if",
"err",
":=",
"permission",
".",
"ValidateModelAccess",
"(",
"spec",
".",
"Access",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"permission",
".",
"UserAccess",
"{",
"}",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"target",
":=",
"userAccessTarget",
"{",
"uuid",
":",
"m",
".",
"UUID",
"(",
")",
",",
"globalKey",
":",
"modelGlobalKey",
",",
"}",
"\n",
"return",
"m",
".",
"st",
".",
"addUserAccess",
"(",
"spec",
",",
"target",
")",
"\n",
"}"
] | // AddUser adds a new user for the model to the database. | [
"AddUser",
"adds",
"a",
"new",
"user",
"for",
"the",
"model",
"to",
"the",
"database",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/useraccess.go#L43-L52 |
4,007 | juju/juju | state/useraccess.go | AddControllerUser | func (st *State) AddControllerUser(spec UserAccessSpec) (permission.UserAccess, error) {
if err := permission.ValidateControllerAccess(spec.Access); err != nil {
return permission.UserAccess{}, errors.Annotate(err, "adding controller user")
}
return st.addUserAccess(spec, userAccessTarget{globalKey: controllerGlobalKey})
} | go | func (st *State) AddControllerUser(spec UserAccessSpec) (permission.UserAccess, error) {
if err := permission.ValidateControllerAccess(spec.Access); err != nil {
return permission.UserAccess{}, errors.Annotate(err, "adding controller user")
}
return st.addUserAccess(spec, userAccessTarget{globalKey: controllerGlobalKey})
} | [
"func",
"(",
"st",
"*",
"State",
")",
"AddControllerUser",
"(",
"spec",
"UserAccessSpec",
")",
"(",
"permission",
".",
"UserAccess",
",",
"error",
")",
"{",
"if",
"err",
":=",
"permission",
".",
"ValidateControllerAccess",
"(",
"spec",
".",
"Access",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"permission",
".",
"UserAccess",
"{",
"}",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"st",
".",
"addUserAccess",
"(",
"spec",
",",
"userAccessTarget",
"{",
"globalKey",
":",
"controllerGlobalKey",
"}",
")",
"\n",
"}"
] | // AddControllerUser adds a new user for the current controller to the database. | [
"AddControllerUser",
"adds",
"a",
"new",
"user",
"for",
"the",
"current",
"controller",
"to",
"the",
"database",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/useraccess.go#L55-L60 |
4,008 | juju/juju | state/useraccess.go | userAccessID | func userAccessID(user names.UserTag) string {
username := user.Id()
return strings.ToLower(username)
} | go | func userAccessID(user names.UserTag) string {
username := user.Id()
return strings.ToLower(username)
} | [
"func",
"userAccessID",
"(",
"user",
"names",
".",
"UserTag",
")",
"string",
"{",
"username",
":=",
"user",
".",
"Id",
"(",
")",
"\n",
"return",
"strings",
".",
"ToLower",
"(",
"username",
")",
"\n",
"}"
] | // userAccessID returns the document id of the user access. | [
"userAccessID",
"returns",
"the",
"document",
"id",
"of",
"the",
"user",
"access",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/useraccess.go#L118-L121 |
4,009 | juju/juju | state/useraccess.go | NewModelUserAccess | func NewModelUserAccess(st *State, userDoc userAccessDoc) (permission.UserAccess, error) {
perm, err := st.userPermission(modelKey(userDoc.ObjectUUID), userGlobalKey(strings.ToLower(userDoc.UserName)))
if err != nil {
return permission.UserAccess{}, errors.Annotate(err, "obtaining model permission")
}
return newUserAccess(perm, userDoc, names.NewModelTag(userDoc.ObjectUUID)), nil
} | go | func NewModelUserAccess(st *State, userDoc userAccessDoc) (permission.UserAccess, error) {
perm, err := st.userPermission(modelKey(userDoc.ObjectUUID), userGlobalKey(strings.ToLower(userDoc.UserName)))
if err != nil {
return permission.UserAccess{}, errors.Annotate(err, "obtaining model permission")
}
return newUserAccess(perm, userDoc, names.NewModelTag(userDoc.ObjectUUID)), nil
} | [
"func",
"NewModelUserAccess",
"(",
"st",
"*",
"State",
",",
"userDoc",
"userAccessDoc",
")",
"(",
"permission",
".",
"UserAccess",
",",
"error",
")",
"{",
"perm",
",",
"err",
":=",
"st",
".",
"userPermission",
"(",
"modelKey",
"(",
"userDoc",
".",
"ObjectUUID",
")",
",",
"userGlobalKey",
"(",
"strings",
".",
"ToLower",
"(",
"userDoc",
".",
"UserName",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"permission",
".",
"UserAccess",
"{",
"}",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"newUserAccess",
"(",
"perm",
",",
"userDoc",
",",
"names",
".",
"NewModelTag",
"(",
"userDoc",
".",
"ObjectUUID",
")",
")",
",",
"nil",
"\n",
"}"
] | // NewModelUserAccess returns a new permission.UserAccess for the given userDoc and
// current Model. | [
"NewModelUserAccess",
"returns",
"a",
"new",
"permission",
".",
"UserAccess",
"for",
"the",
"given",
"userDoc",
"and",
"current",
"Model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/useraccess.go#L125-L131 |
4,010 | juju/juju | state/useraccess.go | NewControllerUserAccess | func NewControllerUserAccess(st *State, userDoc userAccessDoc) (permission.UserAccess, error) {
perm, err := st.userPermission(controllerKey(st.ControllerUUID()), userGlobalKey(strings.ToLower(userDoc.UserName)))
if err != nil {
return permission.UserAccess{}, errors.Annotate(err, "obtaining controller permission")
}
return newUserAccess(perm, userDoc, names.NewControllerTag(userDoc.ObjectUUID)), nil
} | go | func NewControllerUserAccess(st *State, userDoc userAccessDoc) (permission.UserAccess, error) {
perm, err := st.userPermission(controllerKey(st.ControllerUUID()), userGlobalKey(strings.ToLower(userDoc.UserName)))
if err != nil {
return permission.UserAccess{}, errors.Annotate(err, "obtaining controller permission")
}
return newUserAccess(perm, userDoc, names.NewControllerTag(userDoc.ObjectUUID)), nil
} | [
"func",
"NewControllerUserAccess",
"(",
"st",
"*",
"State",
",",
"userDoc",
"userAccessDoc",
")",
"(",
"permission",
".",
"UserAccess",
",",
"error",
")",
"{",
"perm",
",",
"err",
":=",
"st",
".",
"userPermission",
"(",
"controllerKey",
"(",
"st",
".",
"ControllerUUID",
"(",
")",
")",
",",
"userGlobalKey",
"(",
"strings",
".",
"ToLower",
"(",
"userDoc",
".",
"UserName",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"permission",
".",
"UserAccess",
"{",
"}",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"newUserAccess",
"(",
"perm",
",",
"userDoc",
",",
"names",
".",
"NewControllerTag",
"(",
"userDoc",
".",
"ObjectUUID",
")",
")",
",",
"nil",
"\n",
"}"
] | // NewControllerUserAccess returns a new permission.UserAccess for the given userDoc and
// current Controller. | [
"NewControllerUserAccess",
"returns",
"a",
"new",
"permission",
".",
"UserAccess",
"for",
"the",
"given",
"userDoc",
"and",
"current",
"Controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/useraccess.go#L135-L141 |
4,011 | juju/juju | state/useraccess.go | UserPermission | func (st *State) UserPermission(subject names.UserTag, target names.Tag) (permission.Access, error) {
if err := st.userMayHaveAccess(subject); err != nil {
return "", errors.Trace(err)
}
switch target.Kind() {
case names.ModelTagKind, names.ControllerTagKind:
access, err := st.UserAccess(subject, target)
if err != nil {
return "", errors.Trace(err)
}
return access.Access, nil
case names.ApplicationOfferTagKind:
offerUUID, err := applicationOfferUUID(st, target.Id())
if err != nil {
return "", errors.Trace(err)
}
return st.GetOfferAccess(offerUUID, subject)
case names.CloudTagKind:
return st.GetCloudAccess(target.Id(), subject)
default:
return "", errors.NotValidf("%q as a target", target.Kind())
}
} | go | func (st *State) UserPermission(subject names.UserTag, target names.Tag) (permission.Access, error) {
if err := st.userMayHaveAccess(subject); err != nil {
return "", errors.Trace(err)
}
switch target.Kind() {
case names.ModelTagKind, names.ControllerTagKind:
access, err := st.UserAccess(subject, target)
if err != nil {
return "", errors.Trace(err)
}
return access.Access, nil
case names.ApplicationOfferTagKind:
offerUUID, err := applicationOfferUUID(st, target.Id())
if err != nil {
return "", errors.Trace(err)
}
return st.GetOfferAccess(offerUUID, subject)
case names.CloudTagKind:
return st.GetCloudAccess(target.Id(), subject)
default:
return "", errors.NotValidf("%q as a target", target.Kind())
}
} | [
"func",
"(",
"st",
"*",
"State",
")",
"UserPermission",
"(",
"subject",
"names",
".",
"UserTag",
",",
"target",
"names",
".",
"Tag",
")",
"(",
"permission",
".",
"Access",
",",
"error",
")",
"{",
"if",
"err",
":=",
"st",
".",
"userMayHaveAccess",
"(",
"subject",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"switch",
"target",
".",
"Kind",
"(",
")",
"{",
"case",
"names",
".",
"ModelTagKind",
",",
"names",
".",
"ControllerTagKind",
":",
"access",
",",
"err",
":=",
"st",
".",
"UserAccess",
"(",
"subject",
",",
"target",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"access",
".",
"Access",
",",
"nil",
"\n",
"case",
"names",
".",
"ApplicationOfferTagKind",
":",
"offerUUID",
",",
"err",
":=",
"applicationOfferUUID",
"(",
"st",
",",
"target",
".",
"Id",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"st",
".",
"GetOfferAccess",
"(",
"offerUUID",
",",
"subject",
")",
"\n",
"case",
"names",
".",
"CloudTagKind",
":",
"return",
"st",
".",
"GetCloudAccess",
"(",
"target",
".",
"Id",
"(",
")",
",",
"subject",
")",
"\n",
"default",
":",
"return",
"\"",
"\"",
",",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
",",
"target",
".",
"Kind",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] | // UserPermission returns the access permission for the passed subject and target. | [
"UserPermission",
"returns",
"the",
"access",
"permission",
"for",
"the",
"passed",
"subject",
"and",
"target",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/useraccess.go#L144-L167 |
4,012 | juju/juju | state/useraccess.go | UserAccess | func (st *State) UserAccess(subject names.UserTag, target names.Tag) (permission.UserAccess, error) {
if err := st.userMayHaveAccess(subject); err != nil {
return permission.UserAccess{}, errors.Trace(err)
}
var (
userDoc userAccessDoc
err error
)
switch target.Kind() {
case names.ModelTagKind:
userDoc, err = st.modelUser(target.Id(), subject)
if err == nil {
return NewModelUserAccess(st, userDoc)
}
case names.ControllerTagKind:
userDoc, err = st.controllerUser(subject)
if err == nil {
return NewControllerUserAccess(st, userDoc)
}
default:
return permission.UserAccess{}, errors.NotValidf("%q as a target", target.Kind())
}
return permission.UserAccess{}, errors.Trace(err)
} | go | func (st *State) UserAccess(subject names.UserTag, target names.Tag) (permission.UserAccess, error) {
if err := st.userMayHaveAccess(subject); err != nil {
return permission.UserAccess{}, errors.Trace(err)
}
var (
userDoc userAccessDoc
err error
)
switch target.Kind() {
case names.ModelTagKind:
userDoc, err = st.modelUser(target.Id(), subject)
if err == nil {
return NewModelUserAccess(st, userDoc)
}
case names.ControllerTagKind:
userDoc, err = st.controllerUser(subject)
if err == nil {
return NewControllerUserAccess(st, userDoc)
}
default:
return permission.UserAccess{}, errors.NotValidf("%q as a target", target.Kind())
}
return permission.UserAccess{}, errors.Trace(err)
} | [
"func",
"(",
"st",
"*",
"State",
")",
"UserAccess",
"(",
"subject",
"names",
".",
"UserTag",
",",
"target",
"names",
".",
"Tag",
")",
"(",
"permission",
".",
"UserAccess",
",",
"error",
")",
"{",
"if",
"err",
":=",
"st",
".",
"userMayHaveAccess",
"(",
"subject",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"permission",
".",
"UserAccess",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"(",
"userDoc",
"userAccessDoc",
"\n",
"err",
"error",
"\n",
")",
"\n",
"switch",
"target",
".",
"Kind",
"(",
")",
"{",
"case",
"names",
".",
"ModelTagKind",
":",
"userDoc",
",",
"err",
"=",
"st",
".",
"modelUser",
"(",
"target",
".",
"Id",
"(",
")",
",",
"subject",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"NewModelUserAccess",
"(",
"st",
",",
"userDoc",
")",
"\n",
"}",
"\n",
"case",
"names",
".",
"ControllerTagKind",
":",
"userDoc",
",",
"err",
"=",
"st",
".",
"controllerUser",
"(",
"subject",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"NewControllerUserAccess",
"(",
"st",
",",
"userDoc",
")",
"\n",
"}",
"\n",
"default",
":",
"return",
"permission",
".",
"UserAccess",
"{",
"}",
",",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
",",
"target",
".",
"Kind",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"permission",
".",
"UserAccess",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // UserAccess returns a new permission.UserAccess for the passed subject and target. | [
"UserAccess",
"returns",
"a",
"new",
"permission",
".",
"UserAccess",
"for",
"the",
"passed",
"subject",
"and",
"target",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/useraccess.go#L199-L223 |
4,013 | juju/juju | state/useraccess.go | RemoveUserAccess | func (st *State) RemoveUserAccess(subject names.UserTag, target names.Tag) error {
switch target.Kind() {
case names.ModelTagKind:
return errors.Trace(st.removeModelUser(subject))
case names.ControllerTagKind:
return errors.Trace(st.removeControllerUser(subject))
}
return errors.NotValidf("%q as a target", target.Kind())
} | go | func (st *State) RemoveUserAccess(subject names.UserTag, target names.Tag) error {
switch target.Kind() {
case names.ModelTagKind:
return errors.Trace(st.removeModelUser(subject))
case names.ControllerTagKind:
return errors.Trace(st.removeControllerUser(subject))
}
return errors.NotValidf("%q as a target", target.Kind())
} | [
"func",
"(",
"st",
"*",
"State",
")",
"RemoveUserAccess",
"(",
"subject",
"names",
".",
"UserTag",
",",
"target",
"names",
".",
"Tag",
")",
"error",
"{",
"switch",
"target",
".",
"Kind",
"(",
")",
"{",
"case",
"names",
".",
"ModelTagKind",
":",
"return",
"errors",
".",
"Trace",
"(",
"st",
".",
"removeModelUser",
"(",
"subject",
")",
")",
"\n",
"case",
"names",
".",
"ControllerTagKind",
":",
"return",
"errors",
".",
"Trace",
"(",
"st",
".",
"removeControllerUser",
"(",
"subject",
")",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
",",
"target",
".",
"Kind",
"(",
")",
")",
"\n",
"}"
] | // RemoveUserAccess removes access for subject to the passed tag. | [
"RemoveUserAccess",
"removes",
"access",
"for",
"subject",
"to",
"the",
"passed",
"tag",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/useraccess.go#L246-L254 |
4,014 | juju/juju | worker/provisioner/provisioner_task.go | populateMachineMaps | func (task *provisionerTask) populateMachineMaps(ids []string) error {
task.instances = make(map[instance.Id]instances.Instance)
instances, err := task.broker.AllInstances(task.cloudCallCtx)
if err != nil {
return errors.Annotate(err, "failed to get all instances from broker")
}
for _, i := range instances {
task.instances[i.Id()] = i
}
// Update the machines map with new data for each of the machines in the
// change list.
machineTags := make([]names.MachineTag, len(ids))
for i, id := range ids {
machineTags[i] = names.NewMachineTag(id)
}
machines, err := task.machineGetter.Machines(machineTags...)
if err != nil {
return errors.Annotatef(err, "failed to get machines %v", ids)
}
task.machinesMutex.Lock()
defer task.machinesMutex.Unlock()
for i, result := range machines {
switch {
case result.Err == nil:
task.machines[result.Machine.Id()] = result.Machine
case params.IsCodeNotFoundOrCodeUnauthorized(result.Err):
logger.Debugf("machine %q not found in state", ids[i])
delete(task.machines, ids[i])
default:
return errors.Annotatef(result.Err, "failed to get machine %v", ids[i])
}
}
return nil
} | go | func (task *provisionerTask) populateMachineMaps(ids []string) error {
task.instances = make(map[instance.Id]instances.Instance)
instances, err := task.broker.AllInstances(task.cloudCallCtx)
if err != nil {
return errors.Annotate(err, "failed to get all instances from broker")
}
for _, i := range instances {
task.instances[i.Id()] = i
}
// Update the machines map with new data for each of the machines in the
// change list.
machineTags := make([]names.MachineTag, len(ids))
for i, id := range ids {
machineTags[i] = names.NewMachineTag(id)
}
machines, err := task.machineGetter.Machines(machineTags...)
if err != nil {
return errors.Annotatef(err, "failed to get machines %v", ids)
}
task.machinesMutex.Lock()
defer task.machinesMutex.Unlock()
for i, result := range machines {
switch {
case result.Err == nil:
task.machines[result.Machine.Id()] = result.Machine
case params.IsCodeNotFoundOrCodeUnauthorized(result.Err):
logger.Debugf("machine %q not found in state", ids[i])
delete(task.machines, ids[i])
default:
return errors.Annotatef(result.Err, "failed to get machine %v", ids[i])
}
}
return nil
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"populateMachineMaps",
"(",
"ids",
"[",
"]",
"string",
")",
"error",
"{",
"task",
".",
"instances",
"=",
"make",
"(",
"map",
"[",
"instance",
".",
"Id",
"]",
"instances",
".",
"Instance",
")",
"\n\n",
"instances",
",",
"err",
":=",
"task",
".",
"broker",
".",
"AllInstances",
"(",
"task",
".",
"cloudCallCtx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"i",
":=",
"range",
"instances",
"{",
"task",
".",
"instances",
"[",
"i",
".",
"Id",
"(",
")",
"]",
"=",
"i",
"\n",
"}",
"\n\n",
"// Update the machines map with new data for each of the machines in the",
"// change list.",
"machineTags",
":=",
"make",
"(",
"[",
"]",
"names",
".",
"MachineTag",
",",
"len",
"(",
"ids",
")",
")",
"\n",
"for",
"i",
",",
"id",
":=",
"range",
"ids",
"{",
"machineTags",
"[",
"i",
"]",
"=",
"names",
".",
"NewMachineTag",
"(",
"id",
")",
"\n",
"}",
"\n",
"machines",
",",
"err",
":=",
"task",
".",
"machineGetter",
".",
"Machines",
"(",
"machineTags",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"ids",
")",
"\n",
"}",
"\n",
"task",
".",
"machinesMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"task",
".",
"machinesMutex",
".",
"Unlock",
"(",
")",
"\n",
"for",
"i",
",",
"result",
":=",
"range",
"machines",
"{",
"switch",
"{",
"case",
"result",
".",
"Err",
"==",
"nil",
":",
"task",
".",
"machines",
"[",
"result",
".",
"Machine",
".",
"Id",
"(",
")",
"]",
"=",
"result",
".",
"Machine",
"\n",
"case",
"params",
".",
"IsCodeNotFoundOrCodeUnauthorized",
"(",
"result",
".",
"Err",
")",
":",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"ids",
"[",
"i",
"]",
")",
"\n",
"delete",
"(",
"task",
".",
"machines",
",",
"ids",
"[",
"i",
"]",
")",
"\n",
"default",
":",
"return",
"errors",
".",
"Annotatef",
"(",
"result",
".",
"Err",
",",
"\"",
"\"",
",",
"ids",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // populateMachineMaps updates task.instances. Also updates
// task.machines map if a list of IDs is given. | [
"populateMachineMaps",
"updates",
"task",
".",
"instances",
".",
"Also",
"updates",
"task",
".",
"machines",
"map",
"if",
"a",
"list",
"of",
"IDs",
"is",
"given",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L337-L372 |
4,015 | juju/juju | worker/provisioner/provisioner_task.go | pendingOrDeadOrMaintain | func (task *provisionerTask) pendingOrDeadOrMaintain(ids []string) (pending, dead, maintain []apiprovisioner.MachineProvisioner, err error) {
task.machinesMutex.RLock()
defer task.machinesMutex.RUnlock()
for _, id := range ids {
machine, found := task.machines[id]
if !found {
logger.Infof("machine %q not found", id)
continue
}
var classification MachineClassification
classification, err = classifyMachine(machine)
if err != nil {
return // return the error
}
switch classification {
case Pending:
pending = append(pending, machine)
case Dead:
dead = append(dead, machine)
case Maintain:
maintain = append(maintain, machine)
}
}
logger.Tracef("pending machines: %v", pending)
logger.Tracef("dead machines: %v", dead)
return
} | go | func (task *provisionerTask) pendingOrDeadOrMaintain(ids []string) (pending, dead, maintain []apiprovisioner.MachineProvisioner, err error) {
task.machinesMutex.RLock()
defer task.machinesMutex.RUnlock()
for _, id := range ids {
machine, found := task.machines[id]
if !found {
logger.Infof("machine %q not found", id)
continue
}
var classification MachineClassification
classification, err = classifyMachine(machine)
if err != nil {
return // return the error
}
switch classification {
case Pending:
pending = append(pending, machine)
case Dead:
dead = append(dead, machine)
case Maintain:
maintain = append(maintain, machine)
}
}
logger.Tracef("pending machines: %v", pending)
logger.Tracef("dead machines: %v", dead)
return
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"pendingOrDeadOrMaintain",
"(",
"ids",
"[",
"]",
"string",
")",
"(",
"pending",
",",
"dead",
",",
"maintain",
"[",
"]",
"apiprovisioner",
".",
"MachineProvisioner",
",",
"err",
"error",
")",
"{",
"task",
".",
"machinesMutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"task",
".",
"machinesMutex",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"ids",
"{",
"machine",
",",
"found",
":=",
"task",
".",
"machines",
"[",
"id",
"]",
"\n",
"if",
"!",
"found",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"var",
"classification",
"MachineClassification",
"\n",
"classification",
",",
"err",
"=",
"classifyMachine",
"(",
"machine",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"// return the error",
"\n",
"}",
"\n",
"switch",
"classification",
"{",
"case",
"Pending",
":",
"pending",
"=",
"append",
"(",
"pending",
",",
"machine",
")",
"\n",
"case",
"Dead",
":",
"dead",
"=",
"append",
"(",
"dead",
",",
"machine",
")",
"\n",
"case",
"Maintain",
":",
"maintain",
"=",
"append",
"(",
"maintain",
",",
"machine",
")",
"\n",
"}",
"\n",
"}",
"\n",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"pending",
")",
"\n",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"dead",
")",
"\n",
"return",
"\n",
"}"
] | // pendingOrDead looks up machines with ids and returns those that do not
// have an instance id assigned yet, and also those that are dead. | [
"pendingOrDead",
"looks",
"up",
"machines",
"with",
"ids",
"and",
"returns",
"those",
"that",
"do",
"not",
"have",
"an",
"instance",
"id",
"assigned",
"yet",
"and",
"also",
"those",
"that",
"are",
"dead",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L376-L402 |
4,016 | juju/juju | worker/provisioner/provisioner_task.go | findUnknownInstances | func (task *provisionerTask) findUnknownInstances(stopping []instances.Instance) ([]instances.Instance, error) {
// Make a copy of the instances we know about.
taskInstances := make(map[instance.Id]instances.Instance)
for k, v := range task.instances {
taskInstances[k] = v
}
task.machinesMutex.RLock()
defer task.machinesMutex.RUnlock()
for _, m := range task.machines {
instId, err := m.InstanceId()
switch {
case err == nil:
delete(taskInstances, instId)
case params.IsCodeNotProvisioned(err):
case params.IsCodeNotFoundOrCodeUnauthorized(err):
default:
return nil, err
}
}
// Now remove all those instances that we are stopping already as we
// know about those and don't want to include them in the unknown list.
for _, inst := range stopping {
delete(taskInstances, inst.Id())
}
var unknown []instances.Instance
for _, inst := range taskInstances {
unknown = append(unknown, inst)
}
return unknown, nil
} | go | func (task *provisionerTask) findUnknownInstances(stopping []instances.Instance) ([]instances.Instance, error) {
// Make a copy of the instances we know about.
taskInstances := make(map[instance.Id]instances.Instance)
for k, v := range task.instances {
taskInstances[k] = v
}
task.machinesMutex.RLock()
defer task.machinesMutex.RUnlock()
for _, m := range task.machines {
instId, err := m.InstanceId()
switch {
case err == nil:
delete(taskInstances, instId)
case params.IsCodeNotProvisioned(err):
case params.IsCodeNotFoundOrCodeUnauthorized(err):
default:
return nil, err
}
}
// Now remove all those instances that we are stopping already as we
// know about those and don't want to include them in the unknown list.
for _, inst := range stopping {
delete(taskInstances, inst.Id())
}
var unknown []instances.Instance
for _, inst := range taskInstances {
unknown = append(unknown, inst)
}
return unknown, nil
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"findUnknownInstances",
"(",
"stopping",
"[",
"]",
"instances",
".",
"Instance",
")",
"(",
"[",
"]",
"instances",
".",
"Instance",
",",
"error",
")",
"{",
"// Make a copy of the instances we know about.",
"taskInstances",
":=",
"make",
"(",
"map",
"[",
"instance",
".",
"Id",
"]",
"instances",
".",
"Instance",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"task",
".",
"instances",
"{",
"taskInstances",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"task",
".",
"machinesMutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"task",
".",
"machinesMutex",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"task",
".",
"machines",
"{",
"instId",
",",
"err",
":=",
"m",
".",
"InstanceId",
"(",
")",
"\n",
"switch",
"{",
"case",
"err",
"==",
"nil",
":",
"delete",
"(",
"taskInstances",
",",
"instId",
")",
"\n",
"case",
"params",
".",
"IsCodeNotProvisioned",
"(",
"err",
")",
":",
"case",
"params",
".",
"IsCodeNotFoundOrCodeUnauthorized",
"(",
"err",
")",
":",
"default",
":",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// Now remove all those instances that we are stopping already as we",
"// know about those and don't want to include them in the unknown list.",
"for",
"_",
",",
"inst",
":=",
"range",
"stopping",
"{",
"delete",
"(",
"taskInstances",
",",
"inst",
".",
"Id",
"(",
")",
")",
"\n",
"}",
"\n",
"var",
"unknown",
"[",
"]",
"instances",
".",
"Instance",
"\n",
"for",
"_",
",",
"inst",
":=",
"range",
"taskInstances",
"{",
"unknown",
"=",
"append",
"(",
"unknown",
",",
"inst",
")",
"\n",
"}",
"\n",
"return",
"unknown",
",",
"nil",
"\n",
"}"
] | // findUnknownInstances finds instances which are not associated with a machine. | [
"findUnknownInstances",
"finds",
"instances",
"which",
"are",
"not",
"associated",
"with",
"a",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L473-L503 |
4,017 | juju/juju | worker/provisioner/provisioner_task.go | instancesForDeadMachines | func (task *provisionerTask) instancesForDeadMachines(deadMachines []apiprovisioner.MachineProvisioner) []instances.Instance {
var instances []instances.Instance
for _, machine := range deadMachines {
instId, err := machine.InstanceId()
if err == nil {
keep, _ := machine.KeepInstance()
if keep {
logger.Debugf("machine %v is dead but keep-instance is true", instId)
continue
}
inst, found := task.instances[instId]
// If the instance is not found we can't stop it.
if found {
instances = append(instances, inst)
}
}
}
return instances
} | go | func (task *provisionerTask) instancesForDeadMachines(deadMachines []apiprovisioner.MachineProvisioner) []instances.Instance {
var instances []instances.Instance
for _, machine := range deadMachines {
instId, err := machine.InstanceId()
if err == nil {
keep, _ := machine.KeepInstance()
if keep {
logger.Debugf("machine %v is dead but keep-instance is true", instId)
continue
}
inst, found := task.instances[instId]
// If the instance is not found we can't stop it.
if found {
instances = append(instances, inst)
}
}
}
return instances
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"instancesForDeadMachines",
"(",
"deadMachines",
"[",
"]",
"apiprovisioner",
".",
"MachineProvisioner",
")",
"[",
"]",
"instances",
".",
"Instance",
"{",
"var",
"instances",
"[",
"]",
"instances",
".",
"Instance",
"\n",
"for",
"_",
",",
"machine",
":=",
"range",
"deadMachines",
"{",
"instId",
",",
"err",
":=",
"machine",
".",
"InstanceId",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"keep",
",",
"_",
":=",
"machine",
".",
"KeepInstance",
"(",
")",
"\n",
"if",
"keep",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"instId",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"inst",
",",
"found",
":=",
"task",
".",
"instances",
"[",
"instId",
"]",
"\n",
"// If the instance is not found we can't stop it.",
"if",
"found",
"{",
"instances",
"=",
"append",
"(",
"instances",
",",
"inst",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"instances",
"\n",
"}"
] | // instancesForDeadMachines returns a list of instances.Instance that represent
// the list of dead machines running in the provider. Missing machines are
// omitted from the list. | [
"instancesForDeadMachines",
"returns",
"a",
"list",
"of",
"instances",
".",
"Instance",
"that",
"represent",
"the",
"list",
"of",
"dead",
"machines",
"running",
"in",
"the",
"provider",
".",
"Missing",
"machines",
"are",
"omitted",
"from",
"the",
"list",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L508-L526 |
4,018 | juju/juju | worker/provisioner/provisioner_task.go | populateAvailabilityZoneMachines | func (task *provisionerTask) populateAvailabilityZoneMachines() error {
task.machinesMutex.Lock()
defer task.machinesMutex.Unlock()
if len(task.availabilityZoneMachines) > 0 {
return nil
}
zonedEnv, ok := task.broker.(providercommon.ZonedEnviron)
if !ok {
return nil
}
// In this case, AvailabilityZoneAllocations() will return all of the "available"
// availability zones and their instance allocations.
availabilityZoneInstances, err := providercommon.AvailabilityZoneAllocations(
zonedEnv, task.cloudCallCtx, []instance.Id{})
if err != nil {
return err
}
instanceMachines := make(map[instance.Id]string)
for _, machine := range task.machines {
instId, err := machine.InstanceId()
if err != nil {
continue
}
instanceMachines[instId] = machine.Id()
}
// convert instances IDs to machines IDs to aid distributing
// not yet created instances across availability zones.
task.availabilityZoneMachines = make([]*AvailabilityZoneMachine, len(availabilityZoneInstances))
for i, instances := range availabilityZoneInstances {
machineIds := set.NewStrings()
for _, instanceId := range instances.Instances {
if id, ok := instanceMachines[instanceId]; ok {
machineIds.Add(id)
}
}
task.availabilityZoneMachines[i] = &AvailabilityZoneMachine{
ZoneName: instances.ZoneName,
MachineIds: machineIds,
FailedMachineIds: set.NewStrings(),
ExcludedMachineIds: set.NewStrings(),
}
}
return nil
} | go | func (task *provisionerTask) populateAvailabilityZoneMachines() error {
task.machinesMutex.Lock()
defer task.machinesMutex.Unlock()
if len(task.availabilityZoneMachines) > 0 {
return nil
}
zonedEnv, ok := task.broker.(providercommon.ZonedEnviron)
if !ok {
return nil
}
// In this case, AvailabilityZoneAllocations() will return all of the "available"
// availability zones and their instance allocations.
availabilityZoneInstances, err := providercommon.AvailabilityZoneAllocations(
zonedEnv, task.cloudCallCtx, []instance.Id{})
if err != nil {
return err
}
instanceMachines := make(map[instance.Id]string)
for _, machine := range task.machines {
instId, err := machine.InstanceId()
if err != nil {
continue
}
instanceMachines[instId] = machine.Id()
}
// convert instances IDs to machines IDs to aid distributing
// not yet created instances across availability zones.
task.availabilityZoneMachines = make([]*AvailabilityZoneMachine, len(availabilityZoneInstances))
for i, instances := range availabilityZoneInstances {
machineIds := set.NewStrings()
for _, instanceId := range instances.Instances {
if id, ok := instanceMachines[instanceId]; ok {
machineIds.Add(id)
}
}
task.availabilityZoneMachines[i] = &AvailabilityZoneMachine{
ZoneName: instances.ZoneName,
MachineIds: machineIds,
FailedMachineIds: set.NewStrings(),
ExcludedMachineIds: set.NewStrings(),
}
}
return nil
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"populateAvailabilityZoneMachines",
"(",
")",
"error",
"{",
"task",
".",
"machinesMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"task",
".",
"machinesMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"len",
"(",
"task",
".",
"availabilityZoneMachines",
")",
">",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"zonedEnv",
",",
"ok",
":=",
"task",
".",
"broker",
".",
"(",
"providercommon",
".",
"ZonedEnviron",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// In this case, AvailabilityZoneAllocations() will return all of the \"available\"",
"// availability zones and their instance allocations.",
"availabilityZoneInstances",
",",
"err",
":=",
"providercommon",
".",
"AvailabilityZoneAllocations",
"(",
"zonedEnv",
",",
"task",
".",
"cloudCallCtx",
",",
"[",
"]",
"instance",
".",
"Id",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"instanceMachines",
":=",
"make",
"(",
"map",
"[",
"instance",
".",
"Id",
"]",
"string",
")",
"\n",
"for",
"_",
",",
"machine",
":=",
"range",
"task",
".",
"machines",
"{",
"instId",
",",
"err",
":=",
"machine",
".",
"InstanceId",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"instanceMachines",
"[",
"instId",
"]",
"=",
"machine",
".",
"Id",
"(",
")",
"\n",
"}",
"\n\n",
"// convert instances IDs to machines IDs to aid distributing",
"// not yet created instances across availability zones.",
"task",
".",
"availabilityZoneMachines",
"=",
"make",
"(",
"[",
"]",
"*",
"AvailabilityZoneMachine",
",",
"len",
"(",
"availabilityZoneInstances",
")",
")",
"\n",
"for",
"i",
",",
"instances",
":=",
"range",
"availabilityZoneInstances",
"{",
"machineIds",
":=",
"set",
".",
"NewStrings",
"(",
")",
"\n",
"for",
"_",
",",
"instanceId",
":=",
"range",
"instances",
".",
"Instances",
"{",
"if",
"id",
",",
"ok",
":=",
"instanceMachines",
"[",
"instanceId",
"]",
";",
"ok",
"{",
"machineIds",
".",
"Add",
"(",
"id",
")",
"\n",
"}",
"\n",
"}",
"\n",
"task",
".",
"availabilityZoneMachines",
"[",
"i",
"]",
"=",
"&",
"AvailabilityZoneMachine",
"{",
"ZoneName",
":",
"instances",
".",
"ZoneName",
",",
"MachineIds",
":",
"machineIds",
",",
"FailedMachineIds",
":",
"set",
".",
"NewStrings",
"(",
")",
",",
"ExcludedMachineIds",
":",
"set",
".",
"NewStrings",
"(",
")",
",",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // populateAvailabilityZoneMachines fills in the map, availabilityZoneMachines,
// if empty, with a current mapping of availability zone to IDs of machines
// running in that zone. If the provider does not implement the ZonedEnviron
// interface, return nil. | [
"populateAvailabilityZoneMachines",
"fills",
"in",
"the",
"map",
"availabilityZoneMachines",
"if",
"empty",
"with",
"a",
"current",
"mapping",
"of",
"availability",
"zone",
"to",
"IDs",
"of",
"machines",
"running",
"in",
"that",
"zone",
".",
"If",
"the",
"provider",
"does",
"not",
"implement",
"the",
"ZonedEnviron",
"interface",
"return",
"nil",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L756-L803 |
4,019 | juju/juju | worker/provisioner/provisioner_task.go | populateDistributionGroupZoneMap | func (task *provisionerTask) populateDistributionGroupZoneMap(machineIds []string) []*AvailabilityZoneMachine {
var dgAvailabilityZoneMachines []*AvailabilityZoneMachine
dgSet := set.NewStrings(machineIds...)
for _, azm := range task.availabilityZoneMachines {
dgAvailabilityZoneMachines = append(dgAvailabilityZoneMachines, &AvailabilityZoneMachine{
azm.ZoneName,
azm.MachineIds.Intersection(dgSet),
azm.FailedMachineIds,
azm.ExcludedMachineIds,
})
}
return dgAvailabilityZoneMachines
} | go | func (task *provisionerTask) populateDistributionGroupZoneMap(machineIds []string) []*AvailabilityZoneMachine {
var dgAvailabilityZoneMachines []*AvailabilityZoneMachine
dgSet := set.NewStrings(machineIds...)
for _, azm := range task.availabilityZoneMachines {
dgAvailabilityZoneMachines = append(dgAvailabilityZoneMachines, &AvailabilityZoneMachine{
azm.ZoneName,
azm.MachineIds.Intersection(dgSet),
azm.FailedMachineIds,
azm.ExcludedMachineIds,
})
}
return dgAvailabilityZoneMachines
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"populateDistributionGroupZoneMap",
"(",
"machineIds",
"[",
"]",
"string",
")",
"[",
"]",
"*",
"AvailabilityZoneMachine",
"{",
"var",
"dgAvailabilityZoneMachines",
"[",
"]",
"*",
"AvailabilityZoneMachine",
"\n",
"dgSet",
":=",
"set",
".",
"NewStrings",
"(",
"machineIds",
"...",
")",
"\n",
"for",
"_",
",",
"azm",
":=",
"range",
"task",
".",
"availabilityZoneMachines",
"{",
"dgAvailabilityZoneMachines",
"=",
"append",
"(",
"dgAvailabilityZoneMachines",
",",
"&",
"AvailabilityZoneMachine",
"{",
"azm",
".",
"ZoneName",
",",
"azm",
".",
"MachineIds",
".",
"Intersection",
"(",
"dgSet",
")",
",",
"azm",
".",
"FailedMachineIds",
",",
"azm",
".",
"ExcludedMachineIds",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"dgAvailabilityZoneMachines",
"\n",
"}"
] | // populateDistributionGroupZoneMap returns a zone mapping which only includes
// machines in the same distribution group. This is used to determine where new
// machines in that distribution group should be placed. | [
"populateDistributionGroupZoneMap",
"returns",
"a",
"zone",
"mapping",
"which",
"only",
"includes",
"machines",
"in",
"the",
"same",
"distribution",
"group",
".",
"This",
"is",
"used",
"to",
"determine",
"where",
"new",
"machines",
"in",
"that",
"distribution",
"group",
"should",
"be",
"placed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L808-L820 |
4,020 | juju/juju | worker/provisioner/provisioner_task.go | machineAvailabilityZoneDistribution | func (task *provisionerTask) machineAvailabilityZoneDistribution(
machineId string, distGroupMachineIds []string, cons constraints.Value,
) (string, error) {
task.machinesMutex.Lock()
defer task.machinesMutex.Unlock()
if len(task.availabilityZoneMachines) == 0 {
return "", nil
}
// Assign an initial zone to a machine based on lowest population,
// accommodating any supplied zone constraints.
// If the machine has a distribution group, assign based on lowest zone
// population of the distribution group machine.
var machineZone string
if len(distGroupMachineIds) > 0 {
dgZoneMap := azMachineFilterSort(task.populateDistributionGroupZoneMap(distGroupMachineIds)).FilterZones(cons)
sort.Sort(dgZoneMap)
for _, dgZoneMachines := range dgZoneMap {
if !dgZoneMachines.FailedMachineIds.Contains(machineId) &&
!dgZoneMachines.ExcludedMachineIds.Contains(machineId) {
machineZone = dgZoneMachines.ZoneName
for _, azm := range task.availabilityZoneMachines {
if azm.ZoneName == dgZoneMachines.ZoneName {
azm.MachineIds.Add(machineId)
break
}
}
break
}
}
} else {
zoneMap := azMachineFilterSort(task.availabilityZoneMachines).FilterZones(cons)
sort.Sort(zoneMap)
for _, zoneMachines := range zoneMap {
if !zoneMachines.FailedMachineIds.Contains(machineId) &&
!zoneMachines.ExcludedMachineIds.Contains(machineId) {
machineZone = zoneMachines.ZoneName
zoneMachines.MachineIds.Add(machineId)
break
}
}
}
if machineZone == "" {
return machineZone, errors.NotFoundf("suitable availability zone for machine %v", machineId)
}
return machineZone, nil
} | go | func (task *provisionerTask) machineAvailabilityZoneDistribution(
machineId string, distGroupMachineIds []string, cons constraints.Value,
) (string, error) {
task.machinesMutex.Lock()
defer task.machinesMutex.Unlock()
if len(task.availabilityZoneMachines) == 0 {
return "", nil
}
// Assign an initial zone to a machine based on lowest population,
// accommodating any supplied zone constraints.
// If the machine has a distribution group, assign based on lowest zone
// population of the distribution group machine.
var machineZone string
if len(distGroupMachineIds) > 0 {
dgZoneMap := azMachineFilterSort(task.populateDistributionGroupZoneMap(distGroupMachineIds)).FilterZones(cons)
sort.Sort(dgZoneMap)
for _, dgZoneMachines := range dgZoneMap {
if !dgZoneMachines.FailedMachineIds.Contains(machineId) &&
!dgZoneMachines.ExcludedMachineIds.Contains(machineId) {
machineZone = dgZoneMachines.ZoneName
for _, azm := range task.availabilityZoneMachines {
if azm.ZoneName == dgZoneMachines.ZoneName {
azm.MachineIds.Add(machineId)
break
}
}
break
}
}
} else {
zoneMap := azMachineFilterSort(task.availabilityZoneMachines).FilterZones(cons)
sort.Sort(zoneMap)
for _, zoneMachines := range zoneMap {
if !zoneMachines.FailedMachineIds.Contains(machineId) &&
!zoneMachines.ExcludedMachineIds.Contains(machineId) {
machineZone = zoneMachines.ZoneName
zoneMachines.MachineIds.Add(machineId)
break
}
}
}
if machineZone == "" {
return machineZone, errors.NotFoundf("suitable availability zone for machine %v", machineId)
}
return machineZone, nil
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"machineAvailabilityZoneDistribution",
"(",
"machineId",
"string",
",",
"distGroupMachineIds",
"[",
"]",
"string",
",",
"cons",
"constraints",
".",
"Value",
",",
")",
"(",
"string",
",",
"error",
")",
"{",
"task",
".",
"machinesMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"task",
".",
"machinesMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"len",
"(",
"task",
".",
"availabilityZoneMachines",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n\n",
"// Assign an initial zone to a machine based on lowest population,",
"// accommodating any supplied zone constraints.",
"// If the machine has a distribution group, assign based on lowest zone",
"// population of the distribution group machine.",
"var",
"machineZone",
"string",
"\n",
"if",
"len",
"(",
"distGroupMachineIds",
")",
">",
"0",
"{",
"dgZoneMap",
":=",
"azMachineFilterSort",
"(",
"task",
".",
"populateDistributionGroupZoneMap",
"(",
"distGroupMachineIds",
")",
")",
".",
"FilterZones",
"(",
"cons",
")",
"\n",
"sort",
".",
"Sort",
"(",
"dgZoneMap",
")",
"\n",
"for",
"_",
",",
"dgZoneMachines",
":=",
"range",
"dgZoneMap",
"{",
"if",
"!",
"dgZoneMachines",
".",
"FailedMachineIds",
".",
"Contains",
"(",
"machineId",
")",
"&&",
"!",
"dgZoneMachines",
".",
"ExcludedMachineIds",
".",
"Contains",
"(",
"machineId",
")",
"{",
"machineZone",
"=",
"dgZoneMachines",
".",
"ZoneName",
"\n",
"for",
"_",
",",
"azm",
":=",
"range",
"task",
".",
"availabilityZoneMachines",
"{",
"if",
"azm",
".",
"ZoneName",
"==",
"dgZoneMachines",
".",
"ZoneName",
"{",
"azm",
".",
"MachineIds",
".",
"Add",
"(",
"machineId",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"zoneMap",
":=",
"azMachineFilterSort",
"(",
"task",
".",
"availabilityZoneMachines",
")",
".",
"FilterZones",
"(",
"cons",
")",
"\n",
"sort",
".",
"Sort",
"(",
"zoneMap",
")",
"\n",
"for",
"_",
",",
"zoneMachines",
":=",
"range",
"zoneMap",
"{",
"if",
"!",
"zoneMachines",
".",
"FailedMachineIds",
".",
"Contains",
"(",
"machineId",
")",
"&&",
"!",
"zoneMachines",
".",
"ExcludedMachineIds",
".",
"Contains",
"(",
"machineId",
")",
"{",
"machineZone",
"=",
"zoneMachines",
".",
"ZoneName",
"\n",
"zoneMachines",
".",
"MachineIds",
".",
"Add",
"(",
"machineId",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"machineZone",
"==",
"\"",
"\"",
"{",
"return",
"machineZone",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"machineId",
")",
"\n",
"}",
"\n",
"return",
"machineZone",
",",
"nil",
"\n",
"}"
] | // machineAvailabilityZoneDistribution returns a suggested availability zone
// for the specified machine to start in.
// If the current provider does not implement availability zones, "" and no
// error will be returned.
// Machines are spread across availability zones based on lowest population of
// the "available" zones, and any supplied zone constraints.
// Machines in the same DistributionGroup are placed in different zones,
// distributed based on lowest population of machines in that DistributionGroup.
// Machines are not placed in a zone they are excluded from.
// If availability zones are implemented and one isn't found, return NotFound error. | [
"machineAvailabilityZoneDistribution",
"returns",
"a",
"suggested",
"availability",
"zone",
"for",
"the",
"specified",
"machine",
"to",
"start",
"in",
".",
"If",
"the",
"current",
"provider",
"does",
"not",
"implement",
"availability",
"zones",
"and",
"no",
"error",
"will",
"be",
"returned",
".",
"Machines",
"are",
"spread",
"across",
"availability",
"zones",
"based",
"on",
"lowest",
"population",
"of",
"the",
"available",
"zones",
"and",
"any",
"supplied",
"zone",
"constraints",
".",
"Machines",
"in",
"the",
"same",
"DistributionGroup",
"are",
"placed",
"in",
"different",
"zones",
"distributed",
"based",
"on",
"lowest",
"population",
"of",
"machines",
"in",
"that",
"DistributionGroup",
".",
"Machines",
"are",
"not",
"placed",
"in",
"a",
"zone",
"they",
"are",
"excluded",
"from",
".",
"If",
"availability",
"zones",
"are",
"implemented",
"and",
"one",
"isn",
"t",
"found",
"return",
"NotFound",
"error",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L832-L879 |
4,021 | juju/juju | worker/provisioner/provisioner_task.go | FilterZones | func (a azMachineFilterSort) FilterZones(cons constraints.Value) azMachineFilterSort {
if !cons.HasZones() {
return a
}
logger.Debugf("applying availability zone constraints: %s", strings.Join(*cons.Zones, ", "))
filtered := a[:0]
for _, azm := range a {
for _, zone := range *cons.Zones {
if azm.ZoneName == zone {
filtered = append(filtered, azm)
break
}
}
}
return filtered
} | go | func (a azMachineFilterSort) FilterZones(cons constraints.Value) azMachineFilterSort {
if !cons.HasZones() {
return a
}
logger.Debugf("applying availability zone constraints: %s", strings.Join(*cons.Zones, ", "))
filtered := a[:0]
for _, azm := range a {
for _, zone := range *cons.Zones {
if azm.ZoneName == zone {
filtered = append(filtered, azm)
break
}
}
}
return filtered
} | [
"func",
"(",
"a",
"azMachineFilterSort",
")",
"FilterZones",
"(",
"cons",
"constraints",
".",
"Value",
")",
"azMachineFilterSort",
"{",
"if",
"!",
"cons",
".",
"HasZones",
"(",
")",
"{",
"return",
"a",
"\n",
"}",
"\n\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"*",
"cons",
".",
"Zones",
",",
"\"",
"\"",
")",
")",
"\n",
"filtered",
":=",
"a",
"[",
":",
"0",
"]",
"\n",
"for",
"_",
",",
"azm",
":=",
"range",
"a",
"{",
"for",
"_",
",",
"zone",
":=",
"range",
"*",
"cons",
".",
"Zones",
"{",
"if",
"azm",
".",
"ZoneName",
"==",
"zone",
"{",
"filtered",
"=",
"append",
"(",
"filtered",
",",
"azm",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"filtered",
"\n",
"}"
] | // FilterZones returns a new instance consisting of slice members limited to
// zones expressed in the input constraints.
// Absence of zone constraints leaves the return unfiltered. | [
"FilterZones",
"returns",
"a",
"new",
"instance",
"consisting",
"of",
"slice",
"members",
"limited",
"to",
"zones",
"expressed",
"in",
"the",
"input",
"constraints",
".",
"Absence",
"of",
"zone",
"constraints",
"leaves",
"the",
"return",
"unfiltered",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L889-L905 |
4,022 | juju/juju | worker/provisioner/provisioner_task.go | startMachines | func (task *provisionerTask) startMachines(machines []apiprovisioner.MachineProvisioner) error {
if len(machines) == 0 {
return nil
}
// Get the distributionGroups for each machine now to avoid
// successive calls to DistributionGroupByMachineId which will
// return the same data.
machineTags := make([]names.MachineTag, len(machines))
for i, machine := range machines {
machineTags[i] = machine.MachineTag()
}
machineDistributionGroups, err := task.distributionGroupFinder.DistributionGroupByMachineId(machineTags...)
if err != nil {
return err
}
var wg sync.WaitGroup
errMachines := make([]error, len(machines))
for i, m := range machines {
if machineDistributionGroups[i].Err != nil {
task.setErrorStatus(
"fetching distribution groups for machine %q: %v",
m, machineDistributionGroups[i].Err,
)
continue
}
wg.Add(1)
go func(machine apiprovisioner.MachineProvisioner, dg []string, index int) {
defer wg.Done()
if err := task.startMachine(machine, dg); err != nil {
task.removeMachineFromAZMap(machine)
errMachines[index] = err
}
}(m, machineDistributionGroups[i].MachineIds, i)
}
wg.Wait()
select {
case <-task.catacomb.Dying():
return task.catacomb.ErrDying()
default:
}
var errorStrings []string
for _, err := range errMachines {
if err != nil {
errorStrings = append(errorStrings, err.Error())
}
}
if errorStrings != nil {
return errors.New(strings.Join(errorStrings, "\n"))
}
return nil
} | go | func (task *provisionerTask) startMachines(machines []apiprovisioner.MachineProvisioner) error {
if len(machines) == 0 {
return nil
}
// Get the distributionGroups for each machine now to avoid
// successive calls to DistributionGroupByMachineId which will
// return the same data.
machineTags := make([]names.MachineTag, len(machines))
for i, machine := range machines {
machineTags[i] = machine.MachineTag()
}
machineDistributionGroups, err := task.distributionGroupFinder.DistributionGroupByMachineId(machineTags...)
if err != nil {
return err
}
var wg sync.WaitGroup
errMachines := make([]error, len(machines))
for i, m := range machines {
if machineDistributionGroups[i].Err != nil {
task.setErrorStatus(
"fetching distribution groups for machine %q: %v",
m, machineDistributionGroups[i].Err,
)
continue
}
wg.Add(1)
go func(machine apiprovisioner.MachineProvisioner, dg []string, index int) {
defer wg.Done()
if err := task.startMachine(machine, dg); err != nil {
task.removeMachineFromAZMap(machine)
errMachines[index] = err
}
}(m, machineDistributionGroups[i].MachineIds, i)
}
wg.Wait()
select {
case <-task.catacomb.Dying():
return task.catacomb.ErrDying()
default:
}
var errorStrings []string
for _, err := range errMachines {
if err != nil {
errorStrings = append(errorStrings, err.Error())
}
}
if errorStrings != nil {
return errors.New(strings.Join(errorStrings, "\n"))
}
return nil
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"startMachines",
"(",
"machines",
"[",
"]",
"apiprovisioner",
".",
"MachineProvisioner",
")",
"error",
"{",
"if",
"len",
"(",
"machines",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Get the distributionGroups for each machine now to avoid",
"// successive calls to DistributionGroupByMachineId which will",
"// return the same data.",
"machineTags",
":=",
"make",
"(",
"[",
"]",
"names",
".",
"MachineTag",
",",
"len",
"(",
"machines",
")",
")",
"\n",
"for",
"i",
",",
"machine",
":=",
"range",
"machines",
"{",
"machineTags",
"[",
"i",
"]",
"=",
"machine",
".",
"MachineTag",
"(",
")",
"\n",
"}",
"\n",
"machineDistributionGroups",
",",
"err",
":=",
"task",
".",
"distributionGroupFinder",
".",
"DistributionGroupByMachineId",
"(",
"machineTags",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"errMachines",
":=",
"make",
"(",
"[",
"]",
"error",
",",
"len",
"(",
"machines",
")",
")",
"\n",
"for",
"i",
",",
"m",
":=",
"range",
"machines",
"{",
"if",
"machineDistributionGroups",
"[",
"i",
"]",
".",
"Err",
"!=",
"nil",
"{",
"task",
".",
"setErrorStatus",
"(",
"\"",
"\"",
",",
"m",
",",
"machineDistributionGroups",
"[",
"i",
"]",
".",
"Err",
",",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"machine",
"apiprovisioner",
".",
"MachineProvisioner",
",",
"dg",
"[",
"]",
"string",
",",
"index",
"int",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"if",
"err",
":=",
"task",
".",
"startMachine",
"(",
"machine",
",",
"dg",
")",
";",
"err",
"!=",
"nil",
"{",
"task",
".",
"removeMachineFromAZMap",
"(",
"machine",
")",
"\n",
"errMachines",
"[",
"index",
"]",
"=",
"err",
"\n",
"}",
"\n",
"}",
"(",
"m",
",",
"machineDistributionGroups",
"[",
"i",
"]",
".",
"MachineIds",
",",
"i",
")",
"\n",
"}",
"\n\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"task",
".",
"catacomb",
".",
"Dying",
"(",
")",
":",
"return",
"task",
".",
"catacomb",
".",
"ErrDying",
"(",
")",
"\n",
"default",
":",
"}",
"\n",
"var",
"errorStrings",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"err",
":=",
"range",
"errMachines",
"{",
"if",
"err",
"!=",
"nil",
"{",
"errorStrings",
"=",
"append",
"(",
"errorStrings",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"errorStrings",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"strings",
".",
"Join",
"(",
"errorStrings",
",",
"\"",
"\\n",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // startMachines starts a goroutine for each specified machine to
// start it. Errors from individual start machine attempts will be logged. | [
"startMachines",
"starts",
"a",
"goroutine",
"for",
"each",
"specified",
"machine",
"to",
"start",
"it",
".",
"Errors",
"from",
"individual",
"start",
"machine",
"attempts",
"will",
"be",
"logged",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L927-L980 |
4,023 | juju/juju | worker/provisioner/provisioner_task.go | setupToStartMachine | func (task *provisionerTask) setupToStartMachine(machine apiprovisioner.MachineProvisioner, version *version.Number) (
environs.StartInstanceParams,
error,
) {
pInfo, err := machine.ProvisioningInfo()
if err != nil {
return environs.StartInstanceParams{}, errors.Annotatef(err, "fetching provisioning info for machine %q", machine)
}
instanceCfg, err := task.constructInstanceConfig(machine, task.auth, pInfo)
if err != nil {
return environs.StartInstanceParams{}, errors.Annotatef(err, "creating instance config for machine %q", machine)
}
assocProvInfoAndMachCfg(pInfo, instanceCfg)
var arch string
if pInfo.Constraints.Arch != nil {
arch = *pInfo.Constraints.Arch
}
possibleTools, err := task.toolsFinder.FindTools(
*version,
pInfo.Series,
arch,
)
if err != nil {
return environs.StartInstanceParams{}, errors.Annotatef(err, "cannot find agent binaries for machine %q", machine)
}
startInstanceParams, err := task.constructStartInstanceParams(
task.controllerUUID,
machine,
instanceCfg,
pInfo,
possibleTools,
)
if err != nil {
return environs.StartInstanceParams{}, errors.Annotatef(err, "cannot construct params for machine %q", machine)
}
return startInstanceParams, nil
} | go | func (task *provisionerTask) setupToStartMachine(machine apiprovisioner.MachineProvisioner, version *version.Number) (
environs.StartInstanceParams,
error,
) {
pInfo, err := machine.ProvisioningInfo()
if err != nil {
return environs.StartInstanceParams{}, errors.Annotatef(err, "fetching provisioning info for machine %q", machine)
}
instanceCfg, err := task.constructInstanceConfig(machine, task.auth, pInfo)
if err != nil {
return environs.StartInstanceParams{}, errors.Annotatef(err, "creating instance config for machine %q", machine)
}
assocProvInfoAndMachCfg(pInfo, instanceCfg)
var arch string
if pInfo.Constraints.Arch != nil {
arch = *pInfo.Constraints.Arch
}
possibleTools, err := task.toolsFinder.FindTools(
*version,
pInfo.Series,
arch,
)
if err != nil {
return environs.StartInstanceParams{}, errors.Annotatef(err, "cannot find agent binaries for machine %q", machine)
}
startInstanceParams, err := task.constructStartInstanceParams(
task.controllerUUID,
machine,
instanceCfg,
pInfo,
possibleTools,
)
if err != nil {
return environs.StartInstanceParams{}, errors.Annotatef(err, "cannot construct params for machine %q", machine)
}
return startInstanceParams, nil
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"setupToStartMachine",
"(",
"machine",
"apiprovisioner",
".",
"MachineProvisioner",
",",
"version",
"*",
"version",
".",
"Number",
")",
"(",
"environs",
".",
"StartInstanceParams",
",",
"error",
",",
")",
"{",
"pInfo",
",",
"err",
":=",
"machine",
".",
"ProvisioningInfo",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"environs",
".",
"StartInstanceParams",
"{",
"}",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"machine",
")",
"\n",
"}",
"\n\n",
"instanceCfg",
",",
"err",
":=",
"task",
".",
"constructInstanceConfig",
"(",
"machine",
",",
"task",
".",
"auth",
",",
"pInfo",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"environs",
".",
"StartInstanceParams",
"{",
"}",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"machine",
")",
"\n",
"}",
"\n\n",
"assocProvInfoAndMachCfg",
"(",
"pInfo",
",",
"instanceCfg",
")",
"\n\n",
"var",
"arch",
"string",
"\n",
"if",
"pInfo",
".",
"Constraints",
".",
"Arch",
"!=",
"nil",
"{",
"arch",
"=",
"*",
"pInfo",
".",
"Constraints",
".",
"Arch",
"\n",
"}",
"\n\n",
"possibleTools",
",",
"err",
":=",
"task",
".",
"toolsFinder",
".",
"FindTools",
"(",
"*",
"version",
",",
"pInfo",
".",
"Series",
",",
"arch",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"environs",
".",
"StartInstanceParams",
"{",
"}",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"machine",
")",
"\n",
"}",
"\n\n",
"startInstanceParams",
",",
"err",
":=",
"task",
".",
"constructStartInstanceParams",
"(",
"task",
".",
"controllerUUID",
",",
"machine",
",",
"instanceCfg",
",",
"pInfo",
",",
"possibleTools",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"environs",
".",
"StartInstanceParams",
"{",
"}",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"machine",
")",
"\n",
"}",
"\n\n",
"return",
"startInstanceParams",
",",
"nil",
"\n",
"}"
] | // setupToStartMachine gathers the necessary information,
// based on the specified machine, to create ProvisioningInfo
// and StartInstanceParams to be used by startMachine. | [
"setupToStartMachine",
"gathers",
"the",
"necessary",
"information",
"based",
"on",
"the",
"specified",
"machine",
"to",
"create",
"ProvisioningInfo",
"and",
"StartInstanceParams",
"to",
"be",
"used",
"by",
"startMachine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L995-L1037 |
4,024 | juju/juju | worker/provisioner/provisioner_task.go | populateExcludedMachines | func (task *provisionerTask) populateExcludedMachines(machineId string, startInstanceParams environs.StartInstanceParams) error {
zonedEnv, ok := task.broker.(providercommon.ZonedEnviron)
if !ok {
return nil
}
derivedZones, err := zonedEnv.DeriveAvailabilityZones(task.cloudCallCtx, startInstanceParams)
if err != nil {
return errors.Trace(err)
}
if len(derivedZones) == 0 {
return nil
}
task.machinesMutex.Lock()
defer task.machinesMutex.Unlock()
useZones := set.NewStrings(derivedZones...)
for _, zoneMachines := range task.availabilityZoneMachines {
if !useZones.Contains(zoneMachines.ZoneName) {
zoneMachines.ExcludedMachineIds.Add(machineId)
}
}
return nil
} | go | func (task *provisionerTask) populateExcludedMachines(machineId string, startInstanceParams environs.StartInstanceParams) error {
zonedEnv, ok := task.broker.(providercommon.ZonedEnviron)
if !ok {
return nil
}
derivedZones, err := zonedEnv.DeriveAvailabilityZones(task.cloudCallCtx, startInstanceParams)
if err != nil {
return errors.Trace(err)
}
if len(derivedZones) == 0 {
return nil
}
task.machinesMutex.Lock()
defer task.machinesMutex.Unlock()
useZones := set.NewStrings(derivedZones...)
for _, zoneMachines := range task.availabilityZoneMachines {
if !useZones.Contains(zoneMachines.ZoneName) {
zoneMachines.ExcludedMachineIds.Add(machineId)
}
}
return nil
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"populateExcludedMachines",
"(",
"machineId",
"string",
",",
"startInstanceParams",
"environs",
".",
"StartInstanceParams",
")",
"error",
"{",
"zonedEnv",
",",
"ok",
":=",
"task",
".",
"broker",
".",
"(",
"providercommon",
".",
"ZonedEnviron",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"derivedZones",
",",
"err",
":=",
"zonedEnv",
".",
"DeriveAvailabilityZones",
"(",
"task",
".",
"cloudCallCtx",
",",
"startInstanceParams",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"derivedZones",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"task",
".",
"machinesMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"task",
".",
"machinesMutex",
".",
"Unlock",
"(",
")",
"\n",
"useZones",
":=",
"set",
".",
"NewStrings",
"(",
"derivedZones",
"...",
")",
"\n",
"for",
"_",
",",
"zoneMachines",
":=",
"range",
"task",
".",
"availabilityZoneMachines",
"{",
"if",
"!",
"useZones",
".",
"Contains",
"(",
"zoneMachines",
".",
"ZoneName",
")",
"{",
"zoneMachines",
".",
"ExcludedMachineIds",
".",
"Add",
"(",
"machineId",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // populateExcludedMachines, translates the results of DeriveAvailabilityZones
// into availabilityZoneMachines.ExcludedMachineIds for machines not to be used
// in the given zone. | [
"populateExcludedMachines",
"translates",
"the",
"results",
"of",
"DeriveAvailabilityZones",
"into",
"availabilityZoneMachines",
".",
"ExcludedMachineIds",
"for",
"machines",
"not",
"to",
"be",
"used",
"in",
"the",
"given",
"zone",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L1042-L1063 |
4,025 | juju/juju | worker/provisioner/provisioner_task.go | gatherCharmLXDProfiles | func (task *provisionerTask) gatherCharmLXDProfiles(instanceId, machineTag string, machineProfiles []string) []string {
if names.IsContainerMachine(machineTag) {
if manager, ok := task.broker.(container.LXDProfileNameRetriever); ok {
if profileNames, err := manager.LXDProfileNames(instanceId); err == nil {
return lxdprofile.LXDProfileNames(profileNames)
}
} else {
logger.Tracef("failed to gather profile names, broker didn't conform to LXDProfileNameRetriever")
}
}
return machineProfiles
} | go | func (task *provisionerTask) gatherCharmLXDProfiles(instanceId, machineTag string, machineProfiles []string) []string {
if names.IsContainerMachine(machineTag) {
if manager, ok := task.broker.(container.LXDProfileNameRetriever); ok {
if profileNames, err := manager.LXDProfileNames(instanceId); err == nil {
return lxdprofile.LXDProfileNames(profileNames)
}
} else {
logger.Tracef("failed to gather profile names, broker didn't conform to LXDProfileNameRetriever")
}
}
return machineProfiles
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"gatherCharmLXDProfiles",
"(",
"instanceId",
",",
"machineTag",
"string",
",",
"machineProfiles",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"if",
"names",
".",
"IsContainerMachine",
"(",
"machineTag",
")",
"{",
"if",
"manager",
",",
"ok",
":=",
"task",
".",
"broker",
".",
"(",
"container",
".",
"LXDProfileNameRetriever",
")",
";",
"ok",
"{",
"if",
"profileNames",
",",
"err",
":=",
"manager",
".",
"LXDProfileNames",
"(",
"instanceId",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"lxdprofile",
".",
"LXDProfileNames",
"(",
"profileNames",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"machineProfiles",
"\n",
"}"
] | // gatherCharmLXDProfiles consumes the charms LXD Profiles from the different
// sources. This includes getting the information from the broker. | [
"gatherCharmLXDProfiles",
"consumes",
"the",
"charms",
"LXD",
"Profiles",
"from",
"the",
"different",
"sources",
".",
"This",
"includes",
"getting",
"the",
"information",
"from",
"the",
"broker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L1219-L1230 |
4,026 | juju/juju | worker/provisioner/provisioner_task.go | markMachineFailedInAZ | func (task *provisionerTask) markMachineFailedInAZ(machine apiprovisioner.MachineProvisioner, zone string) (bool, error) {
if zone == "" {
return false, errors.New("no zone provided")
}
task.machinesMutex.Lock()
defer task.machinesMutex.Unlock()
azRemaining := false
for _, zoneMachines := range task.availabilityZoneMachines {
if zone == zoneMachines.ZoneName {
zoneMachines.MachineIds.Remove(machine.Id())
zoneMachines.FailedMachineIds.Add(machine.Id())
if azRemaining {
break
}
}
if !zoneMachines.FailedMachineIds.Contains(machine.Id()) &&
!zoneMachines.ExcludedMachineIds.Contains(machine.Id()) {
azRemaining = true
}
}
return azRemaining, nil
} | go | func (task *provisionerTask) markMachineFailedInAZ(machine apiprovisioner.MachineProvisioner, zone string) (bool, error) {
if zone == "" {
return false, errors.New("no zone provided")
}
task.machinesMutex.Lock()
defer task.machinesMutex.Unlock()
azRemaining := false
for _, zoneMachines := range task.availabilityZoneMachines {
if zone == zoneMachines.ZoneName {
zoneMachines.MachineIds.Remove(machine.Id())
zoneMachines.FailedMachineIds.Add(machine.Id())
if azRemaining {
break
}
}
if !zoneMachines.FailedMachineIds.Contains(machine.Id()) &&
!zoneMachines.ExcludedMachineIds.Contains(machine.Id()) {
azRemaining = true
}
}
return azRemaining, nil
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"markMachineFailedInAZ",
"(",
"machine",
"apiprovisioner",
".",
"MachineProvisioner",
",",
"zone",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"zone",
"==",
"\"",
"\"",
"{",
"return",
"false",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"task",
".",
"machinesMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"task",
".",
"machinesMutex",
".",
"Unlock",
"(",
")",
"\n",
"azRemaining",
":=",
"false",
"\n",
"for",
"_",
",",
"zoneMachines",
":=",
"range",
"task",
".",
"availabilityZoneMachines",
"{",
"if",
"zone",
"==",
"zoneMachines",
".",
"ZoneName",
"{",
"zoneMachines",
".",
"MachineIds",
".",
"Remove",
"(",
"machine",
".",
"Id",
"(",
")",
")",
"\n",
"zoneMachines",
".",
"FailedMachineIds",
".",
"Add",
"(",
"machine",
".",
"Id",
"(",
")",
")",
"\n",
"if",
"azRemaining",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"zoneMachines",
".",
"FailedMachineIds",
".",
"Contains",
"(",
"machine",
".",
"Id",
"(",
")",
")",
"&&",
"!",
"zoneMachines",
".",
"ExcludedMachineIds",
".",
"Contains",
"(",
"machine",
".",
"Id",
"(",
")",
")",
"{",
"azRemaining",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"azRemaining",
",",
"nil",
"\n",
"}"
] | // markMachineFailedInAZ moves the machine in zone from MachineIds to FailedMachineIds
// in availabilityZoneMachines, report if there are any availability zones not failed for
// the specified machine. | [
"markMachineFailedInAZ",
"moves",
"the",
"machine",
"in",
"zone",
"from",
"MachineIds",
"to",
"FailedMachineIds",
"in",
"availabilityZoneMachines",
"report",
"if",
"there",
"are",
"any",
"availability",
"zones",
"not",
"failed",
"for",
"the",
"specified",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L1235-L1256 |
4,027 | juju/juju | worker/provisioner/provisioner_task.go | removeMachineFromAZMap | func (task *provisionerTask) removeMachineFromAZMap(machine apiprovisioner.MachineProvisioner) {
machineId := machine.Id()
task.machinesMutex.Lock()
defer task.machinesMutex.Unlock()
for _, zoneMachines := range task.availabilityZoneMachines {
zoneMachines.MachineIds.Remove(machineId)
zoneMachines.FailedMachineIds.Remove(machineId)
}
} | go | func (task *provisionerTask) removeMachineFromAZMap(machine apiprovisioner.MachineProvisioner) {
machineId := machine.Id()
task.machinesMutex.Lock()
defer task.machinesMutex.Unlock()
for _, zoneMachines := range task.availabilityZoneMachines {
zoneMachines.MachineIds.Remove(machineId)
zoneMachines.FailedMachineIds.Remove(machineId)
}
} | [
"func",
"(",
"task",
"*",
"provisionerTask",
")",
"removeMachineFromAZMap",
"(",
"machine",
"apiprovisioner",
".",
"MachineProvisioner",
")",
"{",
"machineId",
":=",
"machine",
".",
"Id",
"(",
")",
"\n",
"task",
".",
"machinesMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"task",
".",
"machinesMutex",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"zoneMachines",
":=",
"range",
"task",
".",
"availabilityZoneMachines",
"{",
"zoneMachines",
".",
"MachineIds",
".",
"Remove",
"(",
"machineId",
")",
"\n",
"zoneMachines",
".",
"FailedMachineIds",
".",
"Remove",
"(",
"machineId",
")",
"\n",
"}",
"\n",
"}"
] | // removeMachineFromAZMap removes the specified machine from availabilityZoneMachines.
// It is assumed this is called when the machines are being deleted from state, or failed
// provisioning. | [
"removeMachineFromAZMap",
"removes",
"the",
"specified",
"machine",
"from",
"availabilityZoneMachines",
".",
"It",
"is",
"assumed",
"this",
"is",
"called",
"when",
"the",
"machines",
"are",
"being",
"deleted",
"from",
"state",
"or",
"failed",
"provisioning",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner_task.go#L1281-L1289 |
4,028 | juju/juju | cmd/modelcmd/credentials.go | GetCredentials | func GetCredentials(
ctx *cmd.Context,
store jujuclient.CredentialGetter,
args GetCredentialsParams,
) (_ *cloud.Credential, chosenCredentialName, regionName string, _ error) {
credential, credentialName, defaultRegion, err := credentialByName(
store, args.Cloud.Name, args.CredentialName,
)
if err != nil {
return nil, "", "", errors.Trace(err)
}
regionName = args.CloudRegion
if regionName == "" {
regionName = defaultRegion
}
cloudEndpoint := args.Cloud.Endpoint
cloudStorageEndpoint := args.Cloud.StorageEndpoint
cloudIdentityEndpoint := args.Cloud.IdentityEndpoint
if regionName != "" {
region, err := cloud.RegionByName(args.Cloud.Regions, regionName)
if err != nil {
return nil, "", "", errors.Trace(err)
}
cloudEndpoint = region.Endpoint
cloudStorageEndpoint = region.StorageEndpoint
cloudIdentityEndpoint = region.IdentityEndpoint
}
// Finalize credential against schemas supported by the provider.
provider, err := environs.Provider(args.Cloud.Type)
if err != nil {
return nil, "", "", errors.Trace(err)
}
credential, err = FinalizeFileContent(credential, provider)
if err != nil {
return nil, "", "", AnnotateWithFinalizationError(err, credentialName, args.Cloud.Name)
}
credential, err = provider.FinalizeCredential(
ctx, environs.FinalizeCredentialParams{
Credential: *credential,
CloudEndpoint: cloudEndpoint,
CloudStorageEndpoint: cloudStorageEndpoint,
CloudIdentityEndpoint: cloudIdentityEndpoint,
},
)
if err != nil {
return nil, "", "", AnnotateWithFinalizationError(err, credentialName, args.Cloud.Name)
}
return credential, credentialName, regionName, nil
} | go | func GetCredentials(
ctx *cmd.Context,
store jujuclient.CredentialGetter,
args GetCredentialsParams,
) (_ *cloud.Credential, chosenCredentialName, regionName string, _ error) {
credential, credentialName, defaultRegion, err := credentialByName(
store, args.Cloud.Name, args.CredentialName,
)
if err != nil {
return nil, "", "", errors.Trace(err)
}
regionName = args.CloudRegion
if regionName == "" {
regionName = defaultRegion
}
cloudEndpoint := args.Cloud.Endpoint
cloudStorageEndpoint := args.Cloud.StorageEndpoint
cloudIdentityEndpoint := args.Cloud.IdentityEndpoint
if regionName != "" {
region, err := cloud.RegionByName(args.Cloud.Regions, regionName)
if err != nil {
return nil, "", "", errors.Trace(err)
}
cloudEndpoint = region.Endpoint
cloudStorageEndpoint = region.StorageEndpoint
cloudIdentityEndpoint = region.IdentityEndpoint
}
// Finalize credential against schemas supported by the provider.
provider, err := environs.Provider(args.Cloud.Type)
if err != nil {
return nil, "", "", errors.Trace(err)
}
credential, err = FinalizeFileContent(credential, provider)
if err != nil {
return nil, "", "", AnnotateWithFinalizationError(err, credentialName, args.Cloud.Name)
}
credential, err = provider.FinalizeCredential(
ctx, environs.FinalizeCredentialParams{
Credential: *credential,
CloudEndpoint: cloudEndpoint,
CloudStorageEndpoint: cloudStorageEndpoint,
CloudIdentityEndpoint: cloudIdentityEndpoint,
},
)
if err != nil {
return nil, "", "", AnnotateWithFinalizationError(err, credentialName, args.Cloud.Name)
}
return credential, credentialName, regionName, nil
} | [
"func",
"GetCredentials",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
",",
"store",
"jujuclient",
".",
"CredentialGetter",
",",
"args",
"GetCredentialsParams",
",",
")",
"(",
"_",
"*",
"cloud",
".",
"Credential",
",",
"chosenCredentialName",
",",
"regionName",
"string",
",",
"_",
"error",
")",
"{",
"credential",
",",
"credentialName",
",",
"defaultRegion",
",",
"err",
":=",
"credentialByName",
"(",
"store",
",",
"args",
".",
"Cloud",
".",
"Name",
",",
"args",
".",
"CredentialName",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"regionName",
"=",
"args",
".",
"CloudRegion",
"\n",
"if",
"regionName",
"==",
"\"",
"\"",
"{",
"regionName",
"=",
"defaultRegion",
"\n",
"}",
"\n\n",
"cloudEndpoint",
":=",
"args",
".",
"Cloud",
".",
"Endpoint",
"\n",
"cloudStorageEndpoint",
":=",
"args",
".",
"Cloud",
".",
"StorageEndpoint",
"\n",
"cloudIdentityEndpoint",
":=",
"args",
".",
"Cloud",
".",
"IdentityEndpoint",
"\n",
"if",
"regionName",
"!=",
"\"",
"\"",
"{",
"region",
",",
"err",
":=",
"cloud",
".",
"RegionByName",
"(",
"args",
".",
"Cloud",
".",
"Regions",
",",
"regionName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"cloudEndpoint",
"=",
"region",
".",
"Endpoint",
"\n",
"cloudStorageEndpoint",
"=",
"region",
".",
"StorageEndpoint",
"\n",
"cloudIdentityEndpoint",
"=",
"region",
".",
"IdentityEndpoint",
"\n",
"}",
"\n\n",
"// Finalize credential against schemas supported by the provider.",
"provider",
",",
"err",
":=",
"environs",
".",
"Provider",
"(",
"args",
".",
"Cloud",
".",
"Type",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"credential",
",",
"err",
"=",
"FinalizeFileContent",
"(",
"credential",
",",
"provider",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"AnnotateWithFinalizationError",
"(",
"err",
",",
"credentialName",
",",
"args",
".",
"Cloud",
".",
"Name",
")",
"\n",
"}",
"\n\n",
"credential",
",",
"err",
"=",
"provider",
".",
"FinalizeCredential",
"(",
"ctx",
",",
"environs",
".",
"FinalizeCredentialParams",
"{",
"Credential",
":",
"*",
"credential",
",",
"CloudEndpoint",
":",
"cloudEndpoint",
",",
"CloudStorageEndpoint",
":",
"cloudStorageEndpoint",
",",
"CloudIdentityEndpoint",
":",
"cloudIdentityEndpoint",
",",
"}",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"AnnotateWithFinalizationError",
"(",
"err",
",",
"credentialName",
",",
"args",
".",
"Cloud",
".",
"Name",
")",
"\n",
"}",
"\n\n",
"return",
"credential",
",",
"credentialName",
",",
"regionName",
",",
"nil",
"\n",
"}"
] | // GetCredentials returns a curated set of credential values for a given cloud.
// The credential key values are read from the credentials store and the provider
// finalises the values to resolve things like json files.
// If region is not specified, the default credential region is used. | [
"GetCredentials",
"returns",
"a",
"curated",
"set",
"of",
"credential",
"values",
"for",
"a",
"given",
"cloud",
".",
"The",
"credential",
"key",
"values",
"are",
"read",
"from",
"the",
"credentials",
"store",
"and",
"the",
"provider",
"finalises",
"the",
"values",
"to",
"resolve",
"things",
"like",
"json",
"files",
".",
"If",
"region",
"is",
"not",
"specified",
"the",
"default",
"credential",
"region",
"is",
"used",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/credentials.go#L44-L98 |
4,029 | juju/juju | cmd/modelcmd/credentials.go | FinalizeFileContent | func FinalizeFileContent(credential *cloud.Credential, provider environs.EnvironProvider) (*cloud.Credential, error) {
readFile := func(f string) ([]byte, error) {
f, err := utils.NormalizePath(f)
if err != nil {
return nil, errors.Trace(err)
}
return ioutil.ReadFile(f)
}
var err error
credential, err = cloud.FinalizeCredential(
*credential, provider.CredentialSchemas(), readFile,
)
if err != nil {
return nil, err
}
return credential, nil
} | go | func FinalizeFileContent(credential *cloud.Credential, provider environs.EnvironProvider) (*cloud.Credential, error) {
readFile := func(f string) ([]byte, error) {
f, err := utils.NormalizePath(f)
if err != nil {
return nil, errors.Trace(err)
}
return ioutil.ReadFile(f)
}
var err error
credential, err = cloud.FinalizeCredential(
*credential, provider.CredentialSchemas(), readFile,
)
if err != nil {
return nil, err
}
return credential, nil
} | [
"func",
"FinalizeFileContent",
"(",
"credential",
"*",
"cloud",
".",
"Credential",
",",
"provider",
"environs",
".",
"EnvironProvider",
")",
"(",
"*",
"cloud",
".",
"Credential",
",",
"error",
")",
"{",
"readFile",
":=",
"func",
"(",
"f",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"utils",
".",
"NormalizePath",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"ioutil",
".",
"ReadFile",
"(",
"f",
")",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"\n",
"credential",
",",
"err",
"=",
"cloud",
".",
"FinalizeCredential",
"(",
"*",
"credential",
",",
"provider",
".",
"CredentialSchemas",
"(",
")",
",",
"readFile",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"credential",
",",
"nil",
"\n",
"}"
] | // FinalizeFileContent replaces the path content of cloud credentials "file" attribute with its content. | [
"FinalizeFileContent",
"replaces",
"the",
"path",
"content",
"of",
"cloud",
"credentials",
"file",
"attribute",
"with",
"its",
"content",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/credentials.go#L101-L119 |
4,030 | juju/juju | cmd/modelcmd/credentials.go | credentialByName | func credentialByName(
store jujuclient.CredentialGetter, cloudName, credentialName string,
) (_ *cloud.Credential, credentialNameUsed string, defaultRegion string, _ error) {
cloudCredentials, err := store.CredentialForCloud(cloudName)
if err != nil {
return nil, "", "", errors.Annotate(err, "loading credentials")
}
if credentialName == "" {
credentialName = cloudCredentials.DefaultCredential
if credentialName == "" {
// No credential specified, but there's more than one.
if len(cloudCredentials.AuthCredentials) > 1 {
return nil, "", "", ErrMultipleCredentials
}
// No credential specified, so use the default for the cloud.
for credentialName = range cloudCredentials.AuthCredentials {
}
}
}
credential, ok := cloudCredentials.AuthCredentials[credentialName]
if !ok {
return nil, "", "", errors.NotFoundf(
"%q credential for cloud %q", credentialName, cloudName,
)
}
return &credential, credentialName, cloudCredentials.DefaultRegion, nil
} | go | func credentialByName(
store jujuclient.CredentialGetter, cloudName, credentialName string,
) (_ *cloud.Credential, credentialNameUsed string, defaultRegion string, _ error) {
cloudCredentials, err := store.CredentialForCloud(cloudName)
if err != nil {
return nil, "", "", errors.Annotate(err, "loading credentials")
}
if credentialName == "" {
credentialName = cloudCredentials.DefaultCredential
if credentialName == "" {
// No credential specified, but there's more than one.
if len(cloudCredentials.AuthCredentials) > 1 {
return nil, "", "", ErrMultipleCredentials
}
// No credential specified, so use the default for the cloud.
for credentialName = range cloudCredentials.AuthCredentials {
}
}
}
credential, ok := cloudCredentials.AuthCredentials[credentialName]
if !ok {
return nil, "", "", errors.NotFoundf(
"%q credential for cloud %q", credentialName, cloudName,
)
}
return &credential, credentialName, cloudCredentials.DefaultRegion, nil
} | [
"func",
"credentialByName",
"(",
"store",
"jujuclient",
".",
"CredentialGetter",
",",
"cloudName",
",",
"credentialName",
"string",
",",
")",
"(",
"_",
"*",
"cloud",
".",
"Credential",
",",
"credentialNameUsed",
"string",
",",
"defaultRegion",
"string",
",",
"_",
"error",
")",
"{",
"cloudCredentials",
",",
"err",
":=",
"store",
".",
"CredentialForCloud",
"(",
"cloudName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"credentialName",
"==",
"\"",
"\"",
"{",
"credentialName",
"=",
"cloudCredentials",
".",
"DefaultCredential",
"\n",
"if",
"credentialName",
"==",
"\"",
"\"",
"{",
"// No credential specified, but there's more than one.",
"if",
"len",
"(",
"cloudCredentials",
".",
"AuthCredentials",
")",
">",
"1",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"ErrMultipleCredentials",
"\n",
"}",
"\n",
"// No credential specified, so use the default for the cloud.",
"for",
"credentialName",
"=",
"range",
"cloudCredentials",
".",
"AuthCredentials",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"credential",
",",
"ok",
":=",
"cloudCredentials",
".",
"AuthCredentials",
"[",
"credentialName",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"credentialName",
",",
"cloudName",
",",
")",
"\n",
"}",
"\n",
"return",
"&",
"credential",
",",
"credentialName",
",",
"cloudCredentials",
".",
"DefaultRegion",
",",
"nil",
"\n",
"}"
] | // credentialByName returns the credential and default region to use for the
// specified cloud, optionally specifying a credential name. If no credential
// name is specified, then use the default credential for the cloud if one has
// been specified. The credential name is returned also, in case the default
// credential is used. If there is only one credential, it is implicitly the
// default.
//
// If there exists no matching credentials, an error satisfying
// errors.IsNotFound will be returned. | [
"credentialByName",
"returns",
"the",
"credential",
"and",
"default",
"region",
"to",
"use",
"for",
"the",
"specified",
"cloud",
"optionally",
"specifying",
"a",
"credential",
"name",
".",
"If",
"no",
"credential",
"name",
"is",
"specified",
"then",
"use",
"the",
"default",
"credential",
"for",
"the",
"cloud",
"if",
"one",
"has",
"been",
"specified",
".",
"The",
"credential",
"name",
"is",
"returned",
"also",
"in",
"case",
"the",
"default",
"credential",
"is",
"used",
".",
"If",
"there",
"is",
"only",
"one",
"credential",
"it",
"is",
"implicitly",
"the",
"default",
".",
"If",
"there",
"exists",
"no",
"matching",
"credentials",
"an",
"error",
"satisfying",
"errors",
".",
"IsNotFound",
"will",
"be",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/credentials.go#L137-L164 |
4,031 | juju/juju | cmd/modelcmd/credentials.go | DetectCredential | func DetectCredential(cloudName string, provider environs.EnvironProvider) (*cloud.CloudCredential, error) {
detected, err := provider.DetectCredentials()
if err != nil {
return nil, errors.Annotatef(
err, "detecting credentials for %q cloud provider", cloudName,
)
}
logger.Tracef("provider detected credentials: %v", detected)
if len(detected.AuthCredentials) == 0 {
return nil, errors.NotFoundf("credentials for cloud %q", cloudName)
}
if len(detected.AuthCredentials) > 1 {
return nil, ErrMultipleCredentials
}
return detected, nil
} | go | func DetectCredential(cloudName string, provider environs.EnvironProvider) (*cloud.CloudCredential, error) {
detected, err := provider.DetectCredentials()
if err != nil {
return nil, errors.Annotatef(
err, "detecting credentials for %q cloud provider", cloudName,
)
}
logger.Tracef("provider detected credentials: %v", detected)
if len(detected.AuthCredentials) == 0 {
return nil, errors.NotFoundf("credentials for cloud %q", cloudName)
}
if len(detected.AuthCredentials) > 1 {
return nil, ErrMultipleCredentials
}
return detected, nil
} | [
"func",
"DetectCredential",
"(",
"cloudName",
"string",
",",
"provider",
"environs",
".",
"EnvironProvider",
")",
"(",
"*",
"cloud",
".",
"CloudCredential",
",",
"error",
")",
"{",
"detected",
",",
"err",
":=",
"provider",
".",
"DetectCredentials",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"cloudName",
",",
")",
"\n",
"}",
"\n",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"detected",
")",
"\n",
"if",
"len",
"(",
"detected",
".",
"AuthCredentials",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"cloudName",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"detected",
".",
"AuthCredentials",
")",
">",
"1",
"{",
"return",
"nil",
",",
"ErrMultipleCredentials",
"\n",
"}",
"\n",
"return",
"detected",
",",
"nil",
"\n",
"}"
] | // DetectCredential detects credentials for the specified cloud type, and, if
// exactly one is detected, returns it.
//
// If no credentials are detected, an error satisfying errors.IsNotFound will
// be returned. If more than one credential is detected, ErrMultipleCredentials
// will be returned. | [
"DetectCredential",
"detects",
"credentials",
"for",
"the",
"specified",
"cloud",
"type",
"and",
"if",
"exactly",
"one",
"is",
"detected",
"returns",
"it",
".",
"If",
"no",
"credentials",
"are",
"detected",
"an",
"error",
"satisfying",
"errors",
".",
"IsNotFound",
"will",
"be",
"returned",
".",
"If",
"more",
"than",
"one",
"credential",
"is",
"detected",
"ErrMultipleCredentials",
"will",
"be",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/credentials.go#L172-L187 |
4,032 | juju/juju | cmd/modelcmd/credentials.go | RegisterCredentials | func RegisterCredentials(provider environs.EnvironProvider, args RegisterCredentialsParams) (map[string]*cloud.CloudCredential, error) {
if register, ok := provider.(environs.ProviderCredentialsRegister); ok {
found, err := register.RegisterCredentials(args.Cloud)
if err != nil {
return nil, errors.Annotatef(
err, "registering credentials for provider",
)
}
logger.Tracef("provider registered credentials: %v", found)
if len(found) == 0 {
return nil, errors.NotFoundf("credentials for provider")
}
return found, errors.Trace(err)
}
return nil, nil
} | go | func RegisterCredentials(provider environs.EnvironProvider, args RegisterCredentialsParams) (map[string]*cloud.CloudCredential, error) {
if register, ok := provider.(environs.ProviderCredentialsRegister); ok {
found, err := register.RegisterCredentials(args.Cloud)
if err != nil {
return nil, errors.Annotatef(
err, "registering credentials for provider",
)
}
logger.Tracef("provider registered credentials: %v", found)
if len(found) == 0 {
return nil, errors.NotFoundf("credentials for provider")
}
return found, errors.Trace(err)
}
return nil, nil
} | [
"func",
"RegisterCredentials",
"(",
"provider",
"environs",
".",
"EnvironProvider",
",",
"args",
"RegisterCredentialsParams",
")",
"(",
"map",
"[",
"string",
"]",
"*",
"cloud",
".",
"CloudCredential",
",",
"error",
")",
"{",
"if",
"register",
",",
"ok",
":=",
"provider",
".",
"(",
"environs",
".",
"ProviderCredentialsRegister",
")",
";",
"ok",
"{",
"found",
",",
"err",
":=",
"register",
".",
"RegisterCredentials",
"(",
"args",
".",
"Cloud",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
")",
"\n",
"}",
"\n",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"found",
")",
"\n",
"if",
"len",
"(",
"found",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"found",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // RegisterCredentials returns any credentials that need to be registered for
// a provider. | [
"RegisterCredentials",
"returns",
"any",
"credentials",
"that",
"need",
"to",
"be",
"registered",
"for",
"a",
"provider",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/credentials.go#L197-L212 |
4,033 | juju/juju | container/broker/mocks/apicalls_mock.go | NewMockAPICalls | func NewMockAPICalls(ctrl *gomock.Controller) *MockAPICalls {
mock := &MockAPICalls{ctrl: ctrl}
mock.recorder = &MockAPICallsMockRecorder{mock}
return mock
} | go | func NewMockAPICalls(ctrl *gomock.Controller) *MockAPICalls {
mock := &MockAPICalls{ctrl: ctrl}
mock.recorder = &MockAPICallsMockRecorder{mock}
return mock
} | [
"func",
"NewMockAPICalls",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockAPICalls",
"{",
"mock",
":=",
"&",
"MockAPICalls",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockAPICallsMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockAPICalls creates a new mock instance | [
"NewMockAPICalls",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/broker/mocks/apicalls_mock.go#L29-L33 |
4,034 | juju/juju | container/broker/mocks/apicalls_mock.go | ContainerConfig | func (m *MockAPICalls) ContainerConfig() (params.ContainerConfig, error) {
ret := m.ctrl.Call(m, "ContainerConfig")
ret0, _ := ret[0].(params.ContainerConfig)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockAPICalls) ContainerConfig() (params.ContainerConfig, error) {
ret := m.ctrl.Call(m, "ContainerConfig")
ret0, _ := ret[0].(params.ContainerConfig)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockAPICalls",
")",
"ContainerConfig",
"(",
")",
"(",
"params",
".",
"ContainerConfig",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"params",
".",
"ContainerConfig",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // ContainerConfig mocks base method | [
"ContainerConfig",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/broker/mocks/apicalls_mock.go#L41-L46 |
4,035 | juju/juju | container/broker/mocks/apicalls_mock.go | ContainerConfig | func (mr *MockAPICallsMockRecorder) ContainerConfig() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerConfig", reflect.TypeOf((*MockAPICalls)(nil).ContainerConfig))
} | go | func (mr *MockAPICallsMockRecorder) ContainerConfig() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerConfig", reflect.TypeOf((*MockAPICalls)(nil).ContainerConfig))
} | [
"func",
"(",
"mr",
"*",
"MockAPICallsMockRecorder",
")",
"ContainerConfig",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockAPICalls",
")",
"(",
"nil",
")",
".",
"ContainerConfig",
")",
")",
"\n",
"}"
] | // ContainerConfig indicates an expected call of ContainerConfig | [
"ContainerConfig",
"indicates",
"an",
"expected",
"call",
"of",
"ContainerConfig"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/broker/mocks/apicalls_mock.go#L49-L51 |
4,036 | juju/juju | container/broker/mocks/apicalls_mock.go | GetContainerInterfaceInfo | func (mr *MockAPICallsMockRecorder) GetContainerInterfaceInfo(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetContainerInterfaceInfo", reflect.TypeOf((*MockAPICalls)(nil).GetContainerInterfaceInfo), arg0)
} | go | func (mr *MockAPICallsMockRecorder) GetContainerInterfaceInfo(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetContainerInterfaceInfo", reflect.TypeOf((*MockAPICalls)(nil).GetContainerInterfaceInfo), arg0)
} | [
"func",
"(",
"mr",
"*",
"MockAPICallsMockRecorder",
")",
"GetContainerInterfaceInfo",
"(",
"arg0",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockAPICalls",
")",
"(",
"nil",
")",
".",
"GetContainerInterfaceInfo",
")",
",",
"arg0",
")",
"\n",
"}"
] | // GetContainerInterfaceInfo indicates an expected call of GetContainerInterfaceInfo | [
"GetContainerInterfaceInfo",
"indicates",
"an",
"expected",
"call",
"of",
"GetContainerInterfaceInfo"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/broker/mocks/apicalls_mock.go#L62-L64 |
4,037 | juju/juju | container/broker/mocks/apicalls_mock.go | GetContainerProfileInfo | func (m *MockAPICalls) GetContainerProfileInfo(arg0 names_v2.MachineTag) ([]*provisioner.LXDProfileResult, error) {
ret := m.ctrl.Call(m, "GetContainerProfileInfo", arg0)
ret0, _ := ret[0].([]*provisioner.LXDProfileResult)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockAPICalls) GetContainerProfileInfo(arg0 names_v2.MachineTag) ([]*provisioner.LXDProfileResult, error) {
ret := m.ctrl.Call(m, "GetContainerProfileInfo", arg0)
ret0, _ := ret[0].([]*provisioner.LXDProfileResult)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockAPICalls",
")",
"GetContainerProfileInfo",
"(",
"arg0",
"names_v2",
".",
"MachineTag",
")",
"(",
"[",
"]",
"*",
"provisioner",
".",
"LXDProfileResult",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"[",
"]",
"*",
"provisioner",
".",
"LXDProfileResult",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // GetContainerProfileInfo mocks base method | [
"GetContainerProfileInfo",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/broker/mocks/apicalls_mock.go#L67-L72 |
4,038 | juju/juju | container/broker/mocks/apicalls_mock.go | HostChangesForContainer | func (m *MockAPICalls) HostChangesForContainer(arg0 names_v2.MachineTag) ([]network.DeviceToBridge, int, error) {
ret := m.ctrl.Call(m, "HostChangesForContainer", arg0)
ret0, _ := ret[0].([]network.DeviceToBridge)
ret1, _ := ret[1].(int)
ret2, _ := ret[2].(error)
return ret0, ret1, ret2
} | go | func (m *MockAPICalls) HostChangesForContainer(arg0 names_v2.MachineTag) ([]network.DeviceToBridge, int, error) {
ret := m.ctrl.Call(m, "HostChangesForContainer", arg0)
ret0, _ := ret[0].([]network.DeviceToBridge)
ret1, _ := ret[1].(int)
ret2, _ := ret[2].(error)
return ret0, ret1, ret2
} | [
"func",
"(",
"m",
"*",
"MockAPICalls",
")",
"HostChangesForContainer",
"(",
"arg0",
"names_v2",
".",
"MachineTag",
")",
"(",
"[",
"]",
"network",
".",
"DeviceToBridge",
",",
"int",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"[",
"]",
"network",
".",
"DeviceToBridge",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"int",
")",
"\n",
"ret2",
",",
"_",
":=",
"ret",
"[",
"2",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
",",
"ret2",
"\n",
"}"
] | // HostChangesForContainer mocks base method | [
"HostChangesForContainer",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/broker/mocks/apicalls_mock.go#L80-L86 |
4,039 | juju/juju | container/broker/mocks/apicalls_mock.go | PrepareContainerInterfaceInfo | func (m *MockAPICalls) PrepareContainerInterfaceInfo(arg0 names_v2.MachineTag) ([]network.InterfaceInfo, error) {
ret := m.ctrl.Call(m, "PrepareContainerInterfaceInfo", arg0)
ret0, _ := ret[0].([]network.InterfaceInfo)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockAPICalls) PrepareContainerInterfaceInfo(arg0 names_v2.MachineTag) ([]network.InterfaceInfo, error) {
ret := m.ctrl.Call(m, "PrepareContainerInterfaceInfo", arg0)
ret0, _ := ret[0].([]network.InterfaceInfo)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockAPICalls",
")",
"PrepareContainerInterfaceInfo",
"(",
"arg0",
"names_v2",
".",
"MachineTag",
")",
"(",
"[",
"]",
"network",
".",
"InterfaceInfo",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"[",
"]",
"network",
".",
"InterfaceInfo",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // PrepareContainerInterfaceInfo mocks base method | [
"PrepareContainerInterfaceInfo",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/broker/mocks/apicalls_mock.go#L94-L99 |
4,040 | juju/juju | container/broker/mocks/apicalls_mock.go | ReleaseContainerAddresses | func (m *MockAPICalls) ReleaseContainerAddresses(arg0 names_v2.MachineTag) error {
ret := m.ctrl.Call(m, "ReleaseContainerAddresses", arg0)
ret0, _ := ret[0].(error)
return ret0
} | go | func (m *MockAPICalls) ReleaseContainerAddresses(arg0 names_v2.MachineTag) error {
ret := m.ctrl.Call(m, "ReleaseContainerAddresses", arg0)
ret0, _ := ret[0].(error)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockAPICalls",
")",
"ReleaseContainerAddresses",
"(",
"arg0",
"names_v2",
".",
"MachineTag",
")",
"error",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // ReleaseContainerAddresses mocks base method | [
"ReleaseContainerAddresses",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/broker/mocks/apicalls_mock.go#L107-L111 |
4,041 | juju/juju | container/broker/mocks/apicalls_mock.go | SetHostMachineNetworkConfig | func (m *MockAPICalls) SetHostMachineNetworkConfig(arg0 names_v2.MachineTag, arg1 []params.NetworkConfig) error {
ret := m.ctrl.Call(m, "SetHostMachineNetworkConfig", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
} | go | func (m *MockAPICalls) SetHostMachineNetworkConfig(arg0 names_v2.MachineTag, arg1 []params.NetworkConfig) error {
ret := m.ctrl.Call(m, "SetHostMachineNetworkConfig", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockAPICalls",
")",
"SetHostMachineNetworkConfig",
"(",
"arg0",
"names_v2",
".",
"MachineTag",
",",
"arg1",
"[",
"]",
"params",
".",
"NetworkConfig",
")",
"error",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
",",
"arg1",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // SetHostMachineNetworkConfig mocks base method | [
"SetHostMachineNetworkConfig",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/broker/mocks/apicalls_mock.go#L119-L123 |
4,042 | juju/juju | state/sequence.go | sequence | func sequence(mb modelBackend, name string) (int, error) {
sequences, closer := mb.db().GetCollection(sequenceC)
defer closer()
query := sequences.FindId(name)
inc := mgo.Change{
Update: bson.M{
"$set": bson.M{
"name": name,
"model-uuid": mb.modelUUID(),
},
"$inc": bson.M{"counter": 1},
},
Upsert: true,
}
result := &sequenceDoc{}
_, err := query.Apply(inc, result)
if err != nil {
return -1, fmt.Errorf("cannot increment %q sequence number: %v", name, err)
}
return result.Counter, nil
} | go | func sequence(mb modelBackend, name string) (int, error) {
sequences, closer := mb.db().GetCollection(sequenceC)
defer closer()
query := sequences.FindId(name)
inc := mgo.Change{
Update: bson.M{
"$set": bson.M{
"name": name,
"model-uuid": mb.modelUUID(),
},
"$inc": bson.M{"counter": 1},
},
Upsert: true,
}
result := &sequenceDoc{}
_, err := query.Apply(inc, result)
if err != nil {
return -1, fmt.Errorf("cannot increment %q sequence number: %v", name, err)
}
return result.Counter, nil
} | [
"func",
"sequence",
"(",
"mb",
"modelBackend",
",",
"name",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"sequences",
",",
"closer",
":=",
"mb",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"sequenceC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"query",
":=",
"sequences",
".",
"FindId",
"(",
"name",
")",
"\n",
"inc",
":=",
"mgo",
".",
"Change",
"{",
"Update",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"name",
",",
"\"",
"\"",
":",
"mb",
".",
"modelUUID",
"(",
")",
",",
"}",
",",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"1",
"}",
",",
"}",
",",
"Upsert",
":",
"true",
",",
"}",
"\n",
"result",
":=",
"&",
"sequenceDoc",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"query",
".",
"Apply",
"(",
"inc",
",",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
".",
"Counter",
",",
"nil",
"\n",
"}"
] | // sequence safely increments a database backed sequence, returning
// the next value. | [
"sequence",
"safely",
"increments",
"a",
"database",
"backed",
"sequence",
"returning",
"the",
"next",
"value",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/sequence.go#L23-L43 |
4,043 | juju/juju | state/sequence.go | sequenceWithMin | func sequenceWithMin(mb modelBackend, name string, minVal int) (int, error) {
sequences, closer := mb.db().GetRawCollection(sequenceC)
defer closer()
updater := newDbSeqUpdater(sequences, mb.modelUUID(), name)
return updateSeqWithMin(updater, minVal)
} | go | func sequenceWithMin(mb modelBackend, name string, minVal int) (int, error) {
sequences, closer := mb.db().GetRawCollection(sequenceC)
defer closer()
updater := newDbSeqUpdater(sequences, mb.modelUUID(), name)
return updateSeqWithMin(updater, minVal)
} | [
"func",
"sequenceWithMin",
"(",
"mb",
"modelBackend",
",",
"name",
"string",
",",
"minVal",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"sequences",
",",
"closer",
":=",
"mb",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"sequenceC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"updater",
":=",
"newDbSeqUpdater",
"(",
"sequences",
",",
"mb",
".",
"modelUUID",
"(",
")",
",",
"name",
")",
"\n",
"return",
"updateSeqWithMin",
"(",
"updater",
",",
"minVal",
")",
"\n",
"}"
] | // sequenceWithMin safely increments a database backed sequence,
// allowing for a minimum value for the sequence to be specified. The
// minimum value is used as an initial value for the first use of a
// particular sequence. The minimum value will also cause a sequence
// value to jump ahead if the minimum is provided that is higher than
// the current sequence value.
//
// The data manipulated by `sequence` and `sequenceWithMin` is the
// same. It is safe to mix the 2 methods for the same sequence.
//
// `sequence` is more efficient than `sequenceWithMin` and should be
// preferred if there is no minimum value requirement. | [
"sequenceWithMin",
"safely",
"increments",
"a",
"database",
"backed",
"sequence",
"allowing",
"for",
"a",
"minimum",
"value",
"for",
"the",
"sequence",
"to",
"be",
"specified",
".",
"The",
"minimum",
"value",
"is",
"used",
"as",
"an",
"initial",
"value",
"for",
"the",
"first",
"use",
"of",
"a",
"particular",
"sequence",
".",
"The",
"minimum",
"value",
"will",
"also",
"cause",
"a",
"sequence",
"value",
"to",
"jump",
"ahead",
"if",
"the",
"minimum",
"is",
"provided",
"that",
"is",
"higher",
"than",
"the",
"current",
"sequence",
"value",
".",
"The",
"data",
"manipulated",
"by",
"sequence",
"and",
"sequenceWithMin",
"is",
"the",
"same",
".",
"It",
"is",
"safe",
"to",
"mix",
"the",
"2",
"methods",
"for",
"the",
"same",
"sequence",
".",
"sequence",
"is",
"more",
"efficient",
"than",
"sequenceWithMin",
"and",
"should",
"be",
"preferred",
"if",
"there",
"is",
"no",
"minimum",
"value",
"requirement",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/sequence.go#L57-L62 |
4,044 | juju/juju | state/sequence.go | Sequences | func (st *State) Sequences() (map[string]int, error) {
sequences, closer := st.db().GetCollection(sequenceC)
defer closer()
var docs []sequenceDoc
if err := sequences.Find(nil).All(&docs); err != nil {
return nil, errors.Trace(err)
}
result := make(map[string]int)
for _, doc := range docs {
result[doc.Name] = doc.Counter
}
return result, nil
} | go | func (st *State) Sequences() (map[string]int, error) {
sequences, closer := st.db().GetCollection(sequenceC)
defer closer()
var docs []sequenceDoc
if err := sequences.Find(nil).All(&docs); err != nil {
return nil, errors.Trace(err)
}
result := make(map[string]int)
for _, doc := range docs {
result[doc.Name] = doc.Counter
}
return result, nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"Sequences",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"int",
",",
"error",
")",
"{",
"sequences",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"sequenceC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"docs",
"[",
"]",
"sequenceDoc",
"\n",
"if",
"err",
":=",
"sequences",
".",
"Find",
"(",
"nil",
")",
".",
"All",
"(",
"&",
"docs",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"result",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"int",
")",
"\n",
"for",
"_",
",",
"doc",
":=",
"range",
"docs",
"{",
"result",
"[",
"doc",
".",
"Name",
"]",
"=",
"doc",
".",
"Counter",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // Sequences returns the model's sequence names and their next values. | [
"Sequences",
"returns",
"the",
"model",
"s",
"sequence",
"names",
"and",
"their",
"next",
"values",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/sequence.go#L88-L102 |
4,045 | juju/juju | state/sequence.go | updateSeqWithMin | func updateSeqWithMin(sequence seqUpdater, minVal int) (int, error) {
for try := 0; try < maxSeqRetries; try++ {
curVal, err := sequence.read()
if err != nil {
return -1, errors.Annotate(err, "could not read sequence")
}
if curVal == 0 {
// No sequence document exists, create one.
ok, err := sequence.create(minVal + 1)
if err != nil {
return -1, errors.Annotate(err, "could not create sequence")
}
if ok {
return minVal, nil
}
// Someone else created the sequence document at the same
// time, try again.
} else {
// Increment an existing sequence document, respecting the
// minimum value provided.
nextVal := curVal + 1
if nextVal < minVal {
nextVal = minVal + 1
}
ok, err := sequence.set(curVal, nextVal)
if err != nil {
return -1, errors.Annotate(err, "could not set sequence")
}
if ok {
return nextVal - 1, nil
}
// Someone else incremented the sequence at the same time,
// try again.
}
}
return -1, errors.New("too much contention while updating sequence")
} | go | func updateSeqWithMin(sequence seqUpdater, minVal int) (int, error) {
for try := 0; try < maxSeqRetries; try++ {
curVal, err := sequence.read()
if err != nil {
return -1, errors.Annotate(err, "could not read sequence")
}
if curVal == 0 {
// No sequence document exists, create one.
ok, err := sequence.create(minVal + 1)
if err != nil {
return -1, errors.Annotate(err, "could not create sequence")
}
if ok {
return minVal, nil
}
// Someone else created the sequence document at the same
// time, try again.
} else {
// Increment an existing sequence document, respecting the
// minimum value provided.
nextVal := curVal + 1
if nextVal < minVal {
nextVal = minVal + 1
}
ok, err := sequence.set(curVal, nextVal)
if err != nil {
return -1, errors.Annotate(err, "could not set sequence")
}
if ok {
return nextVal - 1, nil
}
// Someone else incremented the sequence at the same time,
// try again.
}
}
return -1, errors.New("too much contention while updating sequence")
} | [
"func",
"updateSeqWithMin",
"(",
"sequence",
"seqUpdater",
",",
"minVal",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"for",
"try",
":=",
"0",
";",
"try",
"<",
"maxSeqRetries",
";",
"try",
"++",
"{",
"curVal",
",",
"err",
":=",
"sequence",
".",
"read",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"curVal",
"==",
"0",
"{",
"// No sequence document exists, create one.",
"ok",
",",
"err",
":=",
"sequence",
".",
"create",
"(",
"minVal",
"+",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ok",
"{",
"return",
"minVal",
",",
"nil",
"\n",
"}",
"\n",
"// Someone else created the sequence document at the same",
"// time, try again.",
"}",
"else",
"{",
"// Increment an existing sequence document, respecting the",
"// minimum value provided.",
"nextVal",
":=",
"curVal",
"+",
"1",
"\n",
"if",
"nextVal",
"<",
"minVal",
"{",
"nextVal",
"=",
"minVal",
"+",
"1",
"\n",
"}",
"\n",
"ok",
",",
"err",
":=",
"sequence",
".",
"set",
"(",
"curVal",
",",
"nextVal",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ok",
"{",
"return",
"nextVal",
"-",
"1",
",",
"nil",
"\n",
"}",
"\n",
"// Someone else incremented the sequence at the same time,",
"// try again.",
"}",
"\n",
"}",
"\n",
"return",
"-",
"1",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // updateSeqWithMin implements the abstract logic for incrementing a
// database backed sequence in a concurrency aware way.
//
// It is complicated because MongoDB's atomic update primitives don't
// provide a way to upsert a counter while also providing an initial
// value. Instead, a number of database operations are used for each
// sequence update, relying on the atomicity guarantees that MongoDB
// offers. Optimistic database updates are attempted with retries when
// contention is observed. | [
"updateSeqWithMin",
"implements",
"the",
"abstract",
"logic",
"for",
"incrementing",
"a",
"database",
"backed",
"sequence",
"in",
"a",
"concurrency",
"aware",
"way",
".",
"It",
"is",
"complicated",
"because",
"MongoDB",
"s",
"atomic",
"update",
"primitives",
"don",
"t",
"provide",
"a",
"way",
"to",
"upsert",
"a",
"counter",
"while",
"also",
"providing",
"an",
"initial",
"value",
".",
"Instead",
"a",
"number",
"of",
"database",
"operations",
"are",
"used",
"for",
"each",
"sequence",
"update",
"relying",
"on",
"the",
"atomicity",
"guarantees",
"that",
"MongoDB",
"offers",
".",
"Optimistic",
"database",
"updates",
"are",
"attempted",
"with",
"retries",
"when",
"contention",
"is",
"observed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/sequence.go#L115-L151 |
4,046 | juju/juju | agent/tools/symlinks.go | EnsureSymlinks | func EnsureSymlinks(jujuDir, dir string, commands []string) (err error) {
logger.Infof("ensure jujuc symlinks in %s", dir)
defer func() {
if err != nil {
err = errors.Annotatef(err, "cannot initialize commands in %q", dir)
}
}()
isSymlink, err := symlink.IsSymlink(jujuDir)
if err != nil {
return err
}
if isSymlink {
link, err := symlink.Read(jujuDir)
if err != nil {
return err
}
if !filepath.IsAbs(link) {
logger.Infof("%s is relative", link)
link = filepath.Join(filepath.Dir(dir), link)
}
jujuDir = link
logger.Infof("was a symlink, now looking at %s", jujuDir)
}
jujudPath := filepath.Join(jujuDir, names.Jujud)
logger.Debugf("jujud path %s", jujudPath)
for _, name := range commands {
// The link operation fails when the target already exists,
// so this is a no-op when the command names already
// exist.
err := symlink.New(jujudPath, filepath.Join(dir, name))
if err != nil && !os.IsExist(err) {
return err
}
}
return nil
} | go | func EnsureSymlinks(jujuDir, dir string, commands []string) (err error) {
logger.Infof("ensure jujuc symlinks in %s", dir)
defer func() {
if err != nil {
err = errors.Annotatef(err, "cannot initialize commands in %q", dir)
}
}()
isSymlink, err := symlink.IsSymlink(jujuDir)
if err != nil {
return err
}
if isSymlink {
link, err := symlink.Read(jujuDir)
if err != nil {
return err
}
if !filepath.IsAbs(link) {
logger.Infof("%s is relative", link)
link = filepath.Join(filepath.Dir(dir), link)
}
jujuDir = link
logger.Infof("was a symlink, now looking at %s", jujuDir)
}
jujudPath := filepath.Join(jujuDir, names.Jujud)
logger.Debugf("jujud path %s", jujudPath)
for _, name := range commands {
// The link operation fails when the target already exists,
// so this is a no-op when the command names already
// exist.
err := symlink.New(jujudPath, filepath.Join(dir, name))
if err != nil && !os.IsExist(err) {
return err
}
}
return nil
} | [
"func",
"EnsureSymlinks",
"(",
"jujuDir",
",",
"dir",
"string",
",",
"commands",
"[",
"]",
"string",
")",
"(",
"err",
"error",
")",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"dir",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"dir",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"isSymlink",
",",
"err",
":=",
"symlink",
".",
"IsSymlink",
"(",
"jujuDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"isSymlink",
"{",
"link",
",",
"err",
":=",
"symlink",
".",
"Read",
"(",
"jujuDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"filepath",
".",
"IsAbs",
"(",
"link",
")",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"link",
")",
"\n",
"link",
"=",
"filepath",
".",
"Join",
"(",
"filepath",
".",
"Dir",
"(",
"dir",
")",
",",
"link",
")",
"\n",
"}",
"\n",
"jujuDir",
"=",
"link",
"\n",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"jujuDir",
")",
"\n",
"}",
"\n\n",
"jujudPath",
":=",
"filepath",
".",
"Join",
"(",
"jujuDir",
",",
"names",
".",
"Jujud",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"jujudPath",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"commands",
"{",
"// The link operation fails when the target already exists,",
"// so this is a no-op when the command names already",
"// exist.",
"err",
":=",
"symlink",
".",
"New",
"(",
"jujudPath",
",",
"filepath",
".",
"Join",
"(",
"dir",
",",
"name",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // EnsureSymlinks creates a symbolic link to jujud within dir for each
// command. If the commands already exist, this operation does nothing.
// If dir is a symbolic link, it will be dereferenced first. | [
"EnsureSymlinks",
"creates",
"a",
"symbolic",
"link",
"to",
"jujud",
"within",
"dir",
"for",
"each",
"command",
".",
"If",
"the",
"commands",
"already",
"exist",
"this",
"operation",
"does",
"nothing",
".",
"If",
"dir",
"is",
"a",
"symbolic",
"link",
"it",
"will",
"be",
"dereferenced",
"first",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/agent/tools/symlinks.go#L19-L55 |
4,047 | juju/juju | environs/bootstrap/bootstrap.go | Validate | func (p BootstrapParams) Validate() error {
if p.AdminSecret == "" {
return errors.New("admin-secret is empty")
}
if p.ControllerConfig.ControllerUUID() == "" {
return errors.New("controller configuration has no controller UUID")
}
if _, hasCACert := p.ControllerConfig.CACert(); !hasCACert {
return errors.New("controller configuration has no ca-cert")
}
if p.CAPrivateKey == "" {
return errors.New("empty ca-private-key")
}
// TODO(axw) validate other things.
return nil
} | go | func (p BootstrapParams) Validate() error {
if p.AdminSecret == "" {
return errors.New("admin-secret is empty")
}
if p.ControllerConfig.ControllerUUID() == "" {
return errors.New("controller configuration has no controller UUID")
}
if _, hasCACert := p.ControllerConfig.CACert(); !hasCACert {
return errors.New("controller configuration has no ca-cert")
}
if p.CAPrivateKey == "" {
return errors.New("empty ca-private-key")
}
// TODO(axw) validate other things.
return nil
} | [
"func",
"(",
"p",
"BootstrapParams",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"p",
".",
"AdminSecret",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"p",
".",
"ControllerConfig",
".",
"ControllerUUID",
"(",
")",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"hasCACert",
":=",
"p",
".",
"ControllerConfig",
".",
"CACert",
"(",
")",
";",
"!",
"hasCACert",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"p",
".",
"CAPrivateKey",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// TODO(axw) validate other things.",
"return",
"nil",
"\n",
"}"
] | // Validate validates the bootstrap parameters. | [
"Validate",
"validates",
"the",
"bootstrap",
"parameters",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/bootstrap.go#L160-L175 |
4,048 | juju/juju | environs/bootstrap/bootstrap.go | withDefaultControllerConstraints | func withDefaultControllerConstraints(cons constraints.Value) constraints.Value {
if !cons.HasInstanceType() && !cons.HasCpuCores() && !cons.HasCpuPower() && !cons.HasMem() {
// A default of 3.5GiB will result in machines with up to 4GiB of memory, eg
// - 3.75GiB on AWS, Google
// - 3.5GiB on Azure
// - 4GiB on Rackspace etc
var mem uint64 = 3.5 * 1024
cons.Mem = &mem
}
return cons
} | go | func withDefaultControllerConstraints(cons constraints.Value) constraints.Value {
if !cons.HasInstanceType() && !cons.HasCpuCores() && !cons.HasCpuPower() && !cons.HasMem() {
// A default of 3.5GiB will result in machines with up to 4GiB of memory, eg
// - 3.75GiB on AWS, Google
// - 3.5GiB on Azure
// - 4GiB on Rackspace etc
var mem uint64 = 3.5 * 1024
cons.Mem = &mem
}
return cons
} | [
"func",
"withDefaultControllerConstraints",
"(",
"cons",
"constraints",
".",
"Value",
")",
"constraints",
".",
"Value",
"{",
"if",
"!",
"cons",
".",
"HasInstanceType",
"(",
")",
"&&",
"!",
"cons",
".",
"HasCpuCores",
"(",
")",
"&&",
"!",
"cons",
".",
"HasCpuPower",
"(",
")",
"&&",
"!",
"cons",
".",
"HasMem",
"(",
")",
"{",
"// A default of 3.5GiB will result in machines with up to 4GiB of memory, eg",
"// - 3.75GiB on AWS, Google",
"// - 3.5GiB on Azure",
"// - 4GiB on Rackspace etc",
"var",
"mem",
"uint64",
"=",
"3.5",
"*",
"1024",
"\n",
"cons",
".",
"Mem",
"=",
"&",
"mem",
"\n",
"}",
"\n",
"return",
"cons",
"\n",
"}"
] | // withDefaultControllerConstraints returns the given constraints,
// updated to choose a default instance type appropriate for a
// controller machine. We use this only if the user does not specify
// any constraints that would otherwise control the instance type
// selection. | [
"withDefaultControllerConstraints",
"returns",
"the",
"given",
"constraints",
"updated",
"to",
"choose",
"a",
"default",
"instance",
"type",
"appropriate",
"for",
"a",
"controller",
"machine",
".",
"We",
"use",
"this",
"only",
"if",
"the",
"user",
"does",
"not",
"specify",
"any",
"constraints",
"that",
"would",
"otherwise",
"control",
"the",
"instance",
"type",
"selection",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/bootstrap.go#L182-L192 |
4,049 | juju/juju | environs/bootstrap/bootstrap.go | Bootstrap | func Bootstrap(
ctx environs.BootstrapContext,
environ environs.BootstrapEnviron,
callCtx context.ProviderCallContext,
args BootstrapParams,
) error {
if err := args.Validate(); err != nil {
return errors.Annotate(err, "validating bootstrap parameters")
}
bootstrapParams := environs.BootstrapParams{
CloudName: args.Cloud.Name,
CloudRegion: args.CloudRegion,
ControllerConfig: args.ControllerConfig,
ModelConstraints: args.ModelConstraints,
BootstrapSeries: args.BootstrapSeries,
Placement: args.Placement,
}
doBootstrap := bootstrapIAAS
if jujucloud.CloudIsCAAS(args.Cloud) {
doBootstrap = bootstrapCAAS
}
if err := doBootstrap(ctx, environ, callCtx, args, bootstrapParams); err != nil {
return errors.Trace(err)
}
ctx.Infof("Bootstrap agent now started")
return nil
} | go | func Bootstrap(
ctx environs.BootstrapContext,
environ environs.BootstrapEnviron,
callCtx context.ProviderCallContext,
args BootstrapParams,
) error {
if err := args.Validate(); err != nil {
return errors.Annotate(err, "validating bootstrap parameters")
}
bootstrapParams := environs.BootstrapParams{
CloudName: args.Cloud.Name,
CloudRegion: args.CloudRegion,
ControllerConfig: args.ControllerConfig,
ModelConstraints: args.ModelConstraints,
BootstrapSeries: args.BootstrapSeries,
Placement: args.Placement,
}
doBootstrap := bootstrapIAAS
if jujucloud.CloudIsCAAS(args.Cloud) {
doBootstrap = bootstrapCAAS
}
if err := doBootstrap(ctx, environ, callCtx, args, bootstrapParams); err != nil {
return errors.Trace(err)
}
ctx.Infof("Bootstrap agent now started")
return nil
} | [
"func",
"Bootstrap",
"(",
"ctx",
"environs",
".",
"BootstrapContext",
",",
"environ",
"environs",
".",
"BootstrapEnviron",
",",
"callCtx",
"context",
".",
"ProviderCallContext",
",",
"args",
"BootstrapParams",
",",
")",
"error",
"{",
"if",
"err",
":=",
"args",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"bootstrapParams",
":=",
"environs",
".",
"BootstrapParams",
"{",
"CloudName",
":",
"args",
".",
"Cloud",
".",
"Name",
",",
"CloudRegion",
":",
"args",
".",
"CloudRegion",
",",
"ControllerConfig",
":",
"args",
".",
"ControllerConfig",
",",
"ModelConstraints",
":",
"args",
".",
"ModelConstraints",
",",
"BootstrapSeries",
":",
"args",
".",
"BootstrapSeries",
",",
"Placement",
":",
"args",
".",
"Placement",
",",
"}",
"\n",
"doBootstrap",
":=",
"bootstrapIAAS",
"\n",
"if",
"jujucloud",
".",
"CloudIsCAAS",
"(",
"args",
".",
"Cloud",
")",
"{",
"doBootstrap",
"=",
"bootstrapCAAS",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"doBootstrap",
"(",
"ctx",
",",
"environ",
",",
"callCtx",
",",
"args",
",",
"bootstrapParams",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"ctx",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Bootstrap bootstraps the given environment. The supplied constraints are
// used to provision the instance, and are also set within the bootstrapped
// environment. | [
"Bootstrap",
"bootstraps",
"the",
"given",
"environment",
".",
"The",
"supplied",
"constraints",
"are",
"used",
"to",
"provision",
"the",
"instance",
"and",
"are",
"also",
"set",
"within",
"the",
"bootstrapped",
"environment",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/bootstrap.go#L538-L566 |
4,050 | juju/juju | environs/bootstrap/bootstrap.go | bootstrapImageMetadata | func bootstrapImageMetadata(
environ environs.BootstrapEnviron,
bootstrapSeries *string,
bootstrapArch string,
bootstrapImageId string,
customImageMetadata *[]*imagemetadata.ImageMetadata,
) ([]*imagemetadata.ImageMetadata, error) {
hasRegion, ok := environ.(simplestreams.HasRegion)
if !ok {
if bootstrapImageId != "" {
// We only support specifying image IDs for providers
// that use simplestreams for now.
return nil, errors.NotSupportedf(
"specifying bootstrap image for %q provider",
environ.Config().Type(),
)
}
// No region, no metadata.
return nil, nil
}
region, err := hasRegion.Region()
if err != nil {
return nil, errors.Trace(err)
}
if bootstrapImageId != "" {
if bootstrapSeries == nil {
return nil, errors.NotValidf("no series specified with bootstrap image")
}
seriesVersion, err := series.SeriesVersion(*bootstrapSeries)
if err != nil {
return nil, errors.Trace(err)
}
// The returned metadata does not have information about the
// storage or virtualisation type. Any provider that wants to
// filter on those properties should allow for empty values.
meta := &imagemetadata.ImageMetadata{
Id: bootstrapImageId,
Arch: bootstrapArch,
Version: seriesVersion,
RegionName: region.Region,
Endpoint: region.Endpoint,
Stream: environ.Config().ImageStream(),
}
*customImageMetadata = append(*customImageMetadata, meta)
return []*imagemetadata.ImageMetadata{meta}, nil
}
// For providers that support making use of simplestreams
// image metadata, search public image metadata. We need
// to pass this onto Bootstrap for selecting images.
sources, err := environs.ImageMetadataSources(environ)
if err != nil {
return nil, errors.Trace(err)
}
// This constraint will search image metadata for all supported architectures and series.
imageConstraint := imagemetadata.NewImageConstraint(simplestreams.LookupParams{
CloudSpec: region,
Stream: environ.Config().ImageStream(),
})
logger.Debugf("constraints for image metadata lookup %v", imageConstraint)
// Get image metadata from all data sources.
// Since order of data source matters, order of image metadata matters too. Append is important here.
var publicImageMetadata []*imagemetadata.ImageMetadata
for _, source := range sources {
sourceMetadata, _, err := imagemetadata.Fetch([]simplestreams.DataSource{source}, imageConstraint)
if err != nil {
logger.Debugf("ignoring image metadata in %s: %v", source.Description(), err)
// Just keep looking...
continue
}
logger.Debugf("found %d image metadata in %s", len(sourceMetadata), source.Description())
publicImageMetadata = append(publicImageMetadata, sourceMetadata...)
}
logger.Debugf("found %d image metadata from all image data sources", len(publicImageMetadata))
if len(publicImageMetadata) == 0 {
return nil, errors.New("no image metadata found")
}
return publicImageMetadata, nil
} | go | func bootstrapImageMetadata(
environ environs.BootstrapEnviron,
bootstrapSeries *string,
bootstrapArch string,
bootstrapImageId string,
customImageMetadata *[]*imagemetadata.ImageMetadata,
) ([]*imagemetadata.ImageMetadata, error) {
hasRegion, ok := environ.(simplestreams.HasRegion)
if !ok {
if bootstrapImageId != "" {
// We only support specifying image IDs for providers
// that use simplestreams for now.
return nil, errors.NotSupportedf(
"specifying bootstrap image for %q provider",
environ.Config().Type(),
)
}
// No region, no metadata.
return nil, nil
}
region, err := hasRegion.Region()
if err != nil {
return nil, errors.Trace(err)
}
if bootstrapImageId != "" {
if bootstrapSeries == nil {
return nil, errors.NotValidf("no series specified with bootstrap image")
}
seriesVersion, err := series.SeriesVersion(*bootstrapSeries)
if err != nil {
return nil, errors.Trace(err)
}
// The returned metadata does not have information about the
// storage or virtualisation type. Any provider that wants to
// filter on those properties should allow for empty values.
meta := &imagemetadata.ImageMetadata{
Id: bootstrapImageId,
Arch: bootstrapArch,
Version: seriesVersion,
RegionName: region.Region,
Endpoint: region.Endpoint,
Stream: environ.Config().ImageStream(),
}
*customImageMetadata = append(*customImageMetadata, meta)
return []*imagemetadata.ImageMetadata{meta}, nil
}
// For providers that support making use of simplestreams
// image metadata, search public image metadata. We need
// to pass this onto Bootstrap for selecting images.
sources, err := environs.ImageMetadataSources(environ)
if err != nil {
return nil, errors.Trace(err)
}
// This constraint will search image metadata for all supported architectures and series.
imageConstraint := imagemetadata.NewImageConstraint(simplestreams.LookupParams{
CloudSpec: region,
Stream: environ.Config().ImageStream(),
})
logger.Debugf("constraints for image metadata lookup %v", imageConstraint)
// Get image metadata from all data sources.
// Since order of data source matters, order of image metadata matters too. Append is important here.
var publicImageMetadata []*imagemetadata.ImageMetadata
for _, source := range sources {
sourceMetadata, _, err := imagemetadata.Fetch([]simplestreams.DataSource{source}, imageConstraint)
if err != nil {
logger.Debugf("ignoring image metadata in %s: %v", source.Description(), err)
// Just keep looking...
continue
}
logger.Debugf("found %d image metadata in %s", len(sourceMetadata), source.Description())
publicImageMetadata = append(publicImageMetadata, sourceMetadata...)
}
logger.Debugf("found %d image metadata from all image data sources", len(publicImageMetadata))
if len(publicImageMetadata) == 0 {
return nil, errors.New("no image metadata found")
}
return publicImageMetadata, nil
} | [
"func",
"bootstrapImageMetadata",
"(",
"environ",
"environs",
".",
"BootstrapEnviron",
",",
"bootstrapSeries",
"*",
"string",
",",
"bootstrapArch",
"string",
",",
"bootstrapImageId",
"string",
",",
"customImageMetadata",
"*",
"[",
"]",
"*",
"imagemetadata",
".",
"ImageMetadata",
",",
")",
"(",
"[",
"]",
"*",
"imagemetadata",
".",
"ImageMetadata",
",",
"error",
")",
"{",
"hasRegion",
",",
"ok",
":=",
"environ",
".",
"(",
"simplestreams",
".",
"HasRegion",
")",
"\n",
"if",
"!",
"ok",
"{",
"if",
"bootstrapImageId",
"!=",
"\"",
"\"",
"{",
"// We only support specifying image IDs for providers",
"// that use simplestreams for now.",
"return",
"nil",
",",
"errors",
".",
"NotSupportedf",
"(",
"\"",
"\"",
",",
"environ",
".",
"Config",
"(",
")",
".",
"Type",
"(",
")",
",",
")",
"\n",
"}",
"\n",
"// No region, no metadata.",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"region",
",",
"err",
":=",
"hasRegion",
".",
"Region",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"bootstrapImageId",
"!=",
"\"",
"\"",
"{",
"if",
"bootstrapSeries",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"seriesVersion",
",",
"err",
":=",
"series",
".",
"SeriesVersion",
"(",
"*",
"bootstrapSeries",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"// The returned metadata does not have information about the",
"// storage or virtualisation type. Any provider that wants to",
"// filter on those properties should allow for empty values.",
"meta",
":=",
"&",
"imagemetadata",
".",
"ImageMetadata",
"{",
"Id",
":",
"bootstrapImageId",
",",
"Arch",
":",
"bootstrapArch",
",",
"Version",
":",
"seriesVersion",
",",
"RegionName",
":",
"region",
".",
"Region",
",",
"Endpoint",
":",
"region",
".",
"Endpoint",
",",
"Stream",
":",
"environ",
".",
"Config",
"(",
")",
".",
"ImageStream",
"(",
")",
",",
"}",
"\n",
"*",
"customImageMetadata",
"=",
"append",
"(",
"*",
"customImageMetadata",
",",
"meta",
")",
"\n",
"return",
"[",
"]",
"*",
"imagemetadata",
".",
"ImageMetadata",
"{",
"meta",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"// For providers that support making use of simplestreams",
"// image metadata, search public image metadata. We need",
"// to pass this onto Bootstrap for selecting images.",
"sources",
",",
"err",
":=",
"environs",
".",
"ImageMetadataSources",
"(",
"environ",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"// This constraint will search image metadata for all supported architectures and series.",
"imageConstraint",
":=",
"imagemetadata",
".",
"NewImageConstraint",
"(",
"simplestreams",
".",
"LookupParams",
"{",
"CloudSpec",
":",
"region",
",",
"Stream",
":",
"environ",
".",
"Config",
"(",
")",
".",
"ImageStream",
"(",
")",
",",
"}",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"imageConstraint",
")",
"\n\n",
"// Get image metadata from all data sources.",
"// Since order of data source matters, order of image metadata matters too. Append is important here.",
"var",
"publicImageMetadata",
"[",
"]",
"*",
"imagemetadata",
".",
"ImageMetadata",
"\n",
"for",
"_",
",",
"source",
":=",
"range",
"sources",
"{",
"sourceMetadata",
",",
"_",
",",
"err",
":=",
"imagemetadata",
".",
"Fetch",
"(",
"[",
"]",
"simplestreams",
".",
"DataSource",
"{",
"source",
"}",
",",
"imageConstraint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"source",
".",
"Description",
"(",
")",
",",
"err",
")",
"\n",
"// Just keep looking...",
"continue",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"len",
"(",
"sourceMetadata",
")",
",",
"source",
".",
"Description",
"(",
")",
")",
"\n",
"publicImageMetadata",
"=",
"append",
"(",
"publicImageMetadata",
",",
"sourceMetadata",
"...",
")",
"\n",
"}",
"\n\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"len",
"(",
"publicImageMetadata",
")",
")",
"\n",
"if",
"len",
"(",
"publicImageMetadata",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"publicImageMetadata",
",",
"nil",
"\n",
"}"
] | // bootstrapImageMetadata returns the image metadata to use for bootstrapping
// the given environment. If the environment provider does not make use of
// simplestreams, no metadata will be returned.
//
// If a bootstrap image ID is specified, image metadata will be synthesised
// using that image ID, and the architecture and series specified by the
// initiator. In addition, the custom image metadata that is saved into the
// state database will have the synthesised image metadata added to it. | [
"bootstrapImageMetadata",
"returns",
"the",
"image",
"metadata",
"to",
"use",
"for",
"bootstrapping",
"the",
"given",
"environment",
".",
"If",
"the",
"environment",
"provider",
"does",
"not",
"make",
"use",
"of",
"simplestreams",
"no",
"metadata",
"will",
"be",
"returned",
".",
"If",
"a",
"bootstrap",
"image",
"ID",
"is",
"specified",
"image",
"metadata",
"will",
"be",
"synthesised",
"using",
"that",
"image",
"ID",
"and",
"the",
"architecture",
"and",
"series",
"specified",
"by",
"the",
"initiator",
".",
"In",
"addition",
"the",
"custom",
"image",
"metadata",
"that",
"is",
"saved",
"into",
"the",
"state",
"database",
"will",
"have",
"the",
"synthesised",
"image",
"metadata",
"added",
"to",
"it",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/bootstrap.go#L714-L796 |
4,051 | juju/juju | environs/bootstrap/bootstrap.go | getBootstrapToolsVersion | func getBootstrapToolsVersion(possibleTools coretools.List) (coretools.List, error) {
if len(possibleTools) == 0 {
return nil, errors.New("no bootstrap agent binaries available")
}
var newVersion version.Number
newVersion, toolsList := possibleTools.Newest()
logger.Infof("newest version: %s", newVersion)
bootstrapVersion := newVersion
// We should only ever bootstrap the exact same version as the client,
// or we risk bootstrap incompatibility.
if !isCompatibleVersion(newVersion, jujuversion.Current) {
compatibleVersion, compatibleTools := findCompatibleTools(possibleTools, jujuversion.Current)
if len(compatibleTools) == 0 {
logger.Infof(
"failed to find %s agent binaries, will attempt to use %s",
jujuversion.Current, newVersion,
)
} else {
bootstrapVersion, toolsList = compatibleVersion, compatibleTools
}
}
logger.Infof("picked bootstrap agent binary version: %s", bootstrapVersion)
return toolsList, nil
} | go | func getBootstrapToolsVersion(possibleTools coretools.List) (coretools.List, error) {
if len(possibleTools) == 0 {
return nil, errors.New("no bootstrap agent binaries available")
}
var newVersion version.Number
newVersion, toolsList := possibleTools.Newest()
logger.Infof("newest version: %s", newVersion)
bootstrapVersion := newVersion
// We should only ever bootstrap the exact same version as the client,
// or we risk bootstrap incompatibility.
if !isCompatibleVersion(newVersion, jujuversion.Current) {
compatibleVersion, compatibleTools := findCompatibleTools(possibleTools, jujuversion.Current)
if len(compatibleTools) == 0 {
logger.Infof(
"failed to find %s agent binaries, will attempt to use %s",
jujuversion.Current, newVersion,
)
} else {
bootstrapVersion, toolsList = compatibleVersion, compatibleTools
}
}
logger.Infof("picked bootstrap agent binary version: %s", bootstrapVersion)
return toolsList, nil
} | [
"func",
"getBootstrapToolsVersion",
"(",
"possibleTools",
"coretools",
".",
"List",
")",
"(",
"coretools",
".",
"List",
",",
"error",
")",
"{",
"if",
"len",
"(",
"possibleTools",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"var",
"newVersion",
"version",
".",
"Number",
"\n",
"newVersion",
",",
"toolsList",
":=",
"possibleTools",
".",
"Newest",
"(",
")",
"\n",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"newVersion",
")",
"\n",
"bootstrapVersion",
":=",
"newVersion",
"\n",
"// We should only ever bootstrap the exact same version as the client,",
"// or we risk bootstrap incompatibility.",
"if",
"!",
"isCompatibleVersion",
"(",
"newVersion",
",",
"jujuversion",
".",
"Current",
")",
"{",
"compatibleVersion",
",",
"compatibleTools",
":=",
"findCompatibleTools",
"(",
"possibleTools",
",",
"jujuversion",
".",
"Current",
")",
"\n",
"if",
"len",
"(",
"compatibleTools",
")",
"==",
"0",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"jujuversion",
".",
"Current",
",",
"newVersion",
",",
")",
"\n",
"}",
"else",
"{",
"bootstrapVersion",
",",
"toolsList",
"=",
"compatibleVersion",
",",
"compatibleTools",
"\n",
"}",
"\n",
"}",
"\n",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"bootstrapVersion",
")",
"\n",
"return",
"toolsList",
",",
"nil",
"\n",
"}"
] | // getBootstrapToolsVersion returns the newest tools from the given tools list. | [
"getBootstrapToolsVersion",
"returns",
"the",
"newest",
"tools",
"from",
"the",
"given",
"tools",
"list",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/bootstrap.go#L799-L822 |
4,052 | juju/juju | environs/bootstrap/bootstrap.go | setBootstrapToolsVersion | func setBootstrapToolsVersion(environ environs.Configer, toolsVersion version.Number) error {
cfg := environ.Config()
if agentVersion, _ := cfg.AgentVersion(); agentVersion != toolsVersion {
cfg, err := cfg.Apply(map[string]interface{}{
"agent-version": toolsVersion.String(),
})
if err == nil {
err = environ.SetConfig(cfg)
}
if err != nil {
return errors.Errorf("failed to update model configuration: %v", err)
}
}
return nil
} | go | func setBootstrapToolsVersion(environ environs.Configer, toolsVersion version.Number) error {
cfg := environ.Config()
if agentVersion, _ := cfg.AgentVersion(); agentVersion != toolsVersion {
cfg, err := cfg.Apply(map[string]interface{}{
"agent-version": toolsVersion.String(),
})
if err == nil {
err = environ.SetConfig(cfg)
}
if err != nil {
return errors.Errorf("failed to update model configuration: %v", err)
}
}
return nil
} | [
"func",
"setBootstrapToolsVersion",
"(",
"environ",
"environs",
".",
"Configer",
",",
"toolsVersion",
"version",
".",
"Number",
")",
"error",
"{",
"cfg",
":=",
"environ",
".",
"Config",
"(",
")",
"\n",
"if",
"agentVersion",
",",
"_",
":=",
"cfg",
".",
"AgentVersion",
"(",
")",
";",
"agentVersion",
"!=",
"toolsVersion",
"{",
"cfg",
",",
"err",
":=",
"cfg",
".",
"Apply",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"toolsVersion",
".",
"String",
"(",
")",
",",
"}",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"environ",
".",
"SetConfig",
"(",
"cfg",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // setBootstrapToolsVersion updates the agent-version configuration attribute. | [
"setBootstrapToolsVersion",
"updates",
"the",
"agent",
"-",
"version",
"configuration",
"attribute",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/bootstrap.go#L825-L839 |
4,053 | juju/juju | environs/bootstrap/bootstrap.go | findCompatibleTools | func findCompatibleTools(possibleTools coretools.List, version version.Number) (version.Number, coretools.List) {
var compatibleTools coretools.List
for _, tools := range possibleTools {
if isCompatibleVersion(tools.Version.Number, version) {
compatibleTools = append(compatibleTools, tools)
}
}
return compatibleTools.Newest()
} | go | func findCompatibleTools(possibleTools coretools.List, version version.Number) (version.Number, coretools.List) {
var compatibleTools coretools.List
for _, tools := range possibleTools {
if isCompatibleVersion(tools.Version.Number, version) {
compatibleTools = append(compatibleTools, tools)
}
}
return compatibleTools.Newest()
} | [
"func",
"findCompatibleTools",
"(",
"possibleTools",
"coretools",
".",
"List",
",",
"version",
"version",
".",
"Number",
")",
"(",
"version",
".",
"Number",
",",
"coretools",
".",
"List",
")",
"{",
"var",
"compatibleTools",
"coretools",
".",
"List",
"\n",
"for",
"_",
",",
"tools",
":=",
"range",
"possibleTools",
"{",
"if",
"isCompatibleVersion",
"(",
"tools",
".",
"Version",
".",
"Number",
",",
"version",
")",
"{",
"compatibleTools",
"=",
"append",
"(",
"compatibleTools",
",",
"tools",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"compatibleTools",
".",
"Newest",
"(",
")",
"\n",
"}"
] | // findCompatibleTools finds tools in the list that have the same major, minor
// and patch level as jujuversion.Current.
//
// Build number is not important to match; uploaded tools will have
// incremented build number, and we want to match them. | [
"findCompatibleTools",
"finds",
"tools",
"in",
"the",
"list",
"that",
"have",
"the",
"same",
"major",
"minor",
"and",
"patch",
"level",
"as",
"jujuversion",
".",
"Current",
".",
"Build",
"number",
"is",
"not",
"important",
"to",
"match",
";",
"uploaded",
"tools",
"will",
"have",
"incremented",
"build",
"number",
"and",
"we",
"want",
"to",
"match",
"them",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/bootstrap.go#L846-L854 |
4,054 | juju/juju | environs/bootstrap/bootstrap.go | setPrivateMetadataSources | func setPrivateMetadataSources(metadataDir string) ([]*imagemetadata.ImageMetadata, error) {
if _, err := os.Stat(metadataDir); err != nil {
if !os.IsNotExist(err) {
return nil, errors.Annotate(err, "cannot access simplestreams metadata directory")
}
return nil, errors.NotFoundf("simplestreams metadata source: %s", metadataDir)
}
agentBinaryMetadataDir := metadataDir
ending := filepath.Base(agentBinaryMetadataDir)
if ending != storage.BaseToolsPath {
agentBinaryMetadataDir = filepath.Join(metadataDir, storage.BaseToolsPath)
}
if _, err := os.Stat(agentBinaryMetadataDir); err != nil {
if !os.IsNotExist(err) {
return nil, errors.Annotate(err, "cannot access agent metadata")
}
logger.Debugf("no agent directory found, using default agent metadata source: %s", tools.DefaultBaseURL)
} else {
if ending == storage.BaseToolsPath {
// As the specified metadataDir ended in 'tools'
// assume that is the only metadata to find and return.
tools.DefaultBaseURL = filepath.Dir(metadataDir)
logger.Debugf("setting default agent metadata source: %s", tools.DefaultBaseURL)
return nil, nil
} else {
tools.DefaultBaseURL = metadataDir
logger.Debugf("setting default agent metadata source: %s", tools.DefaultBaseURL)
}
}
imageMetadataDir := metadataDir
ending = filepath.Base(imageMetadataDir)
if ending != storage.BaseImagesPath {
imageMetadataDir = filepath.Join(metadataDir, storage.BaseImagesPath)
}
if _, err := os.Stat(imageMetadataDir); err != nil {
if !os.IsNotExist(err) {
return nil, errors.Annotate(err, "cannot access image metadata")
}
return nil, nil
} else {
logger.Debugf("setting default image metadata source: %s", imageMetadataDir)
}
baseURL := fmt.Sprintf("file://%s", filepath.ToSlash(imageMetadataDir))
publicKey, _ := simplestreams.UserPublicSigningKey()
datasource := simplestreams.NewURLSignedDataSource("bootstrap metadata", baseURL, publicKey, utils.NoVerifySSLHostnames, simplestreams.CUSTOM_CLOUD_DATA, false)
// Read the image metadata, as we'll want to upload it to the environment.
imageConstraint := imagemetadata.NewImageConstraint(simplestreams.LookupParams{})
existingMetadata, _, err := imagemetadata.Fetch([]simplestreams.DataSource{datasource}, imageConstraint)
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Annotate(err, "cannot read image metadata")
}
// Add an image metadata datasource for constraint validation, etc.
environs.RegisterUserImageDataSourceFunc("bootstrap metadata", func(environs.Environ) (simplestreams.DataSource, error) {
return datasource, nil
})
logger.Infof("custom image metadata added to search path")
return existingMetadata, nil
} | go | func setPrivateMetadataSources(metadataDir string) ([]*imagemetadata.ImageMetadata, error) {
if _, err := os.Stat(metadataDir); err != nil {
if !os.IsNotExist(err) {
return nil, errors.Annotate(err, "cannot access simplestreams metadata directory")
}
return nil, errors.NotFoundf("simplestreams metadata source: %s", metadataDir)
}
agentBinaryMetadataDir := metadataDir
ending := filepath.Base(agentBinaryMetadataDir)
if ending != storage.BaseToolsPath {
agentBinaryMetadataDir = filepath.Join(metadataDir, storage.BaseToolsPath)
}
if _, err := os.Stat(agentBinaryMetadataDir); err != nil {
if !os.IsNotExist(err) {
return nil, errors.Annotate(err, "cannot access agent metadata")
}
logger.Debugf("no agent directory found, using default agent metadata source: %s", tools.DefaultBaseURL)
} else {
if ending == storage.BaseToolsPath {
// As the specified metadataDir ended in 'tools'
// assume that is the only metadata to find and return.
tools.DefaultBaseURL = filepath.Dir(metadataDir)
logger.Debugf("setting default agent metadata source: %s", tools.DefaultBaseURL)
return nil, nil
} else {
tools.DefaultBaseURL = metadataDir
logger.Debugf("setting default agent metadata source: %s", tools.DefaultBaseURL)
}
}
imageMetadataDir := metadataDir
ending = filepath.Base(imageMetadataDir)
if ending != storage.BaseImagesPath {
imageMetadataDir = filepath.Join(metadataDir, storage.BaseImagesPath)
}
if _, err := os.Stat(imageMetadataDir); err != nil {
if !os.IsNotExist(err) {
return nil, errors.Annotate(err, "cannot access image metadata")
}
return nil, nil
} else {
logger.Debugf("setting default image metadata source: %s", imageMetadataDir)
}
baseURL := fmt.Sprintf("file://%s", filepath.ToSlash(imageMetadataDir))
publicKey, _ := simplestreams.UserPublicSigningKey()
datasource := simplestreams.NewURLSignedDataSource("bootstrap metadata", baseURL, publicKey, utils.NoVerifySSLHostnames, simplestreams.CUSTOM_CLOUD_DATA, false)
// Read the image metadata, as we'll want to upload it to the environment.
imageConstraint := imagemetadata.NewImageConstraint(simplestreams.LookupParams{})
existingMetadata, _, err := imagemetadata.Fetch([]simplestreams.DataSource{datasource}, imageConstraint)
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Annotate(err, "cannot read image metadata")
}
// Add an image metadata datasource for constraint validation, etc.
environs.RegisterUserImageDataSourceFunc("bootstrap metadata", func(environs.Environ) (simplestreams.DataSource, error) {
return datasource, nil
})
logger.Infof("custom image metadata added to search path")
return existingMetadata, nil
} | [
"func",
"setPrivateMetadataSources",
"(",
"metadataDir",
"string",
")",
"(",
"[",
"]",
"*",
"imagemetadata",
".",
"ImageMetadata",
",",
"error",
")",
"{",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"metadataDir",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"metadataDir",
")",
"\n",
"}",
"\n\n",
"agentBinaryMetadataDir",
":=",
"metadataDir",
"\n",
"ending",
":=",
"filepath",
".",
"Base",
"(",
"agentBinaryMetadataDir",
")",
"\n",
"if",
"ending",
"!=",
"storage",
".",
"BaseToolsPath",
"{",
"agentBinaryMetadataDir",
"=",
"filepath",
".",
"Join",
"(",
"metadataDir",
",",
"storage",
".",
"BaseToolsPath",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"agentBinaryMetadataDir",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"tools",
".",
"DefaultBaseURL",
")",
"\n",
"}",
"else",
"{",
"if",
"ending",
"==",
"storage",
".",
"BaseToolsPath",
"{",
"// As the specified metadataDir ended in 'tools'",
"// assume that is the only metadata to find and return.",
"tools",
".",
"DefaultBaseURL",
"=",
"filepath",
".",
"Dir",
"(",
"metadataDir",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"tools",
".",
"DefaultBaseURL",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"else",
"{",
"tools",
".",
"DefaultBaseURL",
"=",
"metadataDir",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"tools",
".",
"DefaultBaseURL",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"imageMetadataDir",
":=",
"metadataDir",
"\n",
"ending",
"=",
"filepath",
".",
"Base",
"(",
"imageMetadataDir",
")",
"\n",
"if",
"ending",
"!=",
"storage",
".",
"BaseImagesPath",
"{",
"imageMetadataDir",
"=",
"filepath",
".",
"Join",
"(",
"metadataDir",
",",
"storage",
".",
"BaseImagesPath",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"imageMetadataDir",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"else",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"imageMetadataDir",
")",
"\n",
"}",
"\n\n",
"baseURL",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"filepath",
".",
"ToSlash",
"(",
"imageMetadataDir",
")",
")",
"\n",
"publicKey",
",",
"_",
":=",
"simplestreams",
".",
"UserPublicSigningKey",
"(",
")",
"\n",
"datasource",
":=",
"simplestreams",
".",
"NewURLSignedDataSource",
"(",
"\"",
"\"",
",",
"baseURL",
",",
"publicKey",
",",
"utils",
".",
"NoVerifySSLHostnames",
",",
"simplestreams",
".",
"CUSTOM_CLOUD_DATA",
",",
"false",
")",
"\n\n",
"// Read the image metadata, as we'll want to upload it to the environment.",
"imageConstraint",
":=",
"imagemetadata",
".",
"NewImageConstraint",
"(",
"simplestreams",
".",
"LookupParams",
"{",
"}",
")",
"\n",
"existingMetadata",
",",
"_",
",",
"err",
":=",
"imagemetadata",
".",
"Fetch",
"(",
"[",
"]",
"simplestreams",
".",
"DataSource",
"{",
"datasource",
"}",
",",
"imageConstraint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Add an image metadata datasource for constraint validation, etc.",
"environs",
".",
"RegisterUserImageDataSourceFunc",
"(",
"\"",
"\"",
",",
"func",
"(",
"environs",
".",
"Environ",
")",
"(",
"simplestreams",
".",
"DataSource",
",",
"error",
")",
"{",
"return",
"datasource",
",",
"nil",
"\n",
"}",
")",
"\n",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"return",
"existingMetadata",
",",
"nil",
"\n",
"}"
] | // setPrivateMetadataSources verifies the specified metadataDir exists,
// uses it to set the default agent metadata source for agent binaries,
// and adds an image metadata source after verifying the contents. If the
// directory ends in tools, only the default tools metadata source will be
// set. Same for images. | [
"setPrivateMetadataSources",
"verifies",
"the",
"specified",
"metadataDir",
"exists",
"uses",
"it",
"to",
"set",
"the",
"default",
"agent",
"metadata",
"source",
"for",
"agent",
"binaries",
"and",
"adds",
"an",
"image",
"metadata",
"source",
"after",
"verifying",
"the",
"contents",
".",
"If",
"the",
"directory",
"ends",
"in",
"tools",
"only",
"the",
"default",
"tools",
"metadata",
"source",
"will",
"be",
"set",
".",
"Same",
"for",
"images",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/bootstrap.go#L867-L929 |
4,055 | juju/juju | environs/bootstrap/bootstrap.go | guiArchive | func guiArchive(dataSourceBaseURL string, logProgress func(string)) *coretools.GUIArchive {
// The environment variable is only used for development purposes.
path := os.Getenv("JUJU_GUI")
if path != "" {
vers, err := guiVersion(path)
if err != nil {
logProgress(fmt.Sprintf("Cannot use Juju GUI at %q: %s", path, err))
return nil
}
hash, size, err := hashAndSize(path)
if err != nil {
logProgress(fmt.Sprintf("Cannot use Juju GUI at %q: %s", path, err))
return nil
}
logProgress(fmt.Sprintf("Fetching Juju GUI %s from local archive", vers))
return &coretools.GUIArchive{
Version: vers,
URL: "file://" + filepath.ToSlash(path),
SHA256: hash,
Size: size,
}
}
// Check if the user requested to bootstrap with no GUI.
if dataSourceBaseURL == "" {
logProgress("Juju GUI installation has been disabled")
return nil
}
// Fetch GUI archives info from simplestreams.
source := gui.NewDataSource(dataSourceBaseURL)
allMeta, err := guiFetchMetadata(gui.ReleasedStream, source)
if err != nil {
logProgress(fmt.Sprintf("Unable to fetch Juju GUI info: %s", err))
return nil
}
if len(allMeta) == 0 {
logProgress("No available Juju GUI archives found")
return nil
}
// Metadata info are returned in descending version order.
logProgress(fmt.Sprintf("Fetching Juju GUI %s", allMeta[0].Version))
return &coretools.GUIArchive{
Version: allMeta[0].Version,
URL: allMeta[0].FullPath,
SHA256: allMeta[0].SHA256,
Size: allMeta[0].Size,
}
} | go | func guiArchive(dataSourceBaseURL string, logProgress func(string)) *coretools.GUIArchive {
// The environment variable is only used for development purposes.
path := os.Getenv("JUJU_GUI")
if path != "" {
vers, err := guiVersion(path)
if err != nil {
logProgress(fmt.Sprintf("Cannot use Juju GUI at %q: %s", path, err))
return nil
}
hash, size, err := hashAndSize(path)
if err != nil {
logProgress(fmt.Sprintf("Cannot use Juju GUI at %q: %s", path, err))
return nil
}
logProgress(fmt.Sprintf("Fetching Juju GUI %s from local archive", vers))
return &coretools.GUIArchive{
Version: vers,
URL: "file://" + filepath.ToSlash(path),
SHA256: hash,
Size: size,
}
}
// Check if the user requested to bootstrap with no GUI.
if dataSourceBaseURL == "" {
logProgress("Juju GUI installation has been disabled")
return nil
}
// Fetch GUI archives info from simplestreams.
source := gui.NewDataSource(dataSourceBaseURL)
allMeta, err := guiFetchMetadata(gui.ReleasedStream, source)
if err != nil {
logProgress(fmt.Sprintf("Unable to fetch Juju GUI info: %s", err))
return nil
}
if len(allMeta) == 0 {
logProgress("No available Juju GUI archives found")
return nil
}
// Metadata info are returned in descending version order.
logProgress(fmt.Sprintf("Fetching Juju GUI %s", allMeta[0].Version))
return &coretools.GUIArchive{
Version: allMeta[0].Version,
URL: allMeta[0].FullPath,
SHA256: allMeta[0].SHA256,
Size: allMeta[0].Size,
}
} | [
"func",
"guiArchive",
"(",
"dataSourceBaseURL",
"string",
",",
"logProgress",
"func",
"(",
"string",
")",
")",
"*",
"coretools",
".",
"GUIArchive",
"{",
"// The environment variable is only used for development purposes.",
"path",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"path",
"!=",
"\"",
"\"",
"{",
"vers",
",",
"err",
":=",
"guiVersion",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logProgress",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
",",
"err",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"hash",
",",
"size",
",",
"err",
":=",
"hashAndSize",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logProgress",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
",",
"err",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"logProgress",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"vers",
")",
")",
"\n",
"return",
"&",
"coretools",
".",
"GUIArchive",
"{",
"Version",
":",
"vers",
",",
"URL",
":",
"\"",
"\"",
"+",
"filepath",
".",
"ToSlash",
"(",
"path",
")",
",",
"SHA256",
":",
"hash",
",",
"Size",
":",
"size",
",",
"}",
"\n",
"}",
"\n",
"// Check if the user requested to bootstrap with no GUI.",
"if",
"dataSourceBaseURL",
"==",
"\"",
"\"",
"{",
"logProgress",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"// Fetch GUI archives info from simplestreams.",
"source",
":=",
"gui",
".",
"NewDataSource",
"(",
"dataSourceBaseURL",
")",
"\n",
"allMeta",
",",
"err",
":=",
"guiFetchMetadata",
"(",
"gui",
".",
"ReleasedStream",
",",
"source",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logProgress",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"len",
"(",
"allMeta",
")",
"==",
"0",
"{",
"logProgress",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"// Metadata info are returned in descending version order.",
"logProgress",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"allMeta",
"[",
"0",
"]",
".",
"Version",
")",
")",
"\n",
"return",
"&",
"coretools",
".",
"GUIArchive",
"{",
"Version",
":",
"allMeta",
"[",
"0",
"]",
".",
"Version",
",",
"URL",
":",
"allMeta",
"[",
"0",
"]",
".",
"FullPath",
",",
"SHA256",
":",
"allMeta",
"[",
"0",
"]",
".",
"SHA256",
",",
"Size",
":",
"allMeta",
"[",
"0",
"]",
".",
"Size",
",",
"}",
"\n",
"}"
] | // guiArchive returns information on the GUI archive that will be uploaded
// to the controller. Possible errors in retrieving the GUI archive information
// do not prevent the model to be bootstrapped. If dataSourceBaseURL is
// non-empty, remote GUI archive info is retrieved from simplestreams using it
// as the base URL. The given logProgress function is used to inform users
// about errors or progress in setting up the Juju GUI. | [
"guiArchive",
"returns",
"information",
"on",
"the",
"GUI",
"archive",
"that",
"will",
"be",
"uploaded",
"to",
"the",
"controller",
".",
"Possible",
"errors",
"in",
"retrieving",
"the",
"GUI",
"archive",
"information",
"do",
"not",
"prevent",
"the",
"model",
"to",
"be",
"bootstrapped",
".",
"If",
"dataSourceBaseURL",
"is",
"non",
"-",
"empty",
"remote",
"GUI",
"archive",
"info",
"is",
"retrieved",
"from",
"simplestreams",
"using",
"it",
"as",
"the",
"base",
"URL",
".",
"The",
"given",
"logProgress",
"function",
"is",
"used",
"to",
"inform",
"users",
"about",
"errors",
"or",
"progress",
"in",
"setting",
"up",
"the",
"Juju",
"GUI",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/bootstrap.go#L937-L983 |
4,056 | juju/juju | environs/bootstrap/bootstrap.go | hashAndSize | func hashAndSize(path string) (hash string, size int64, err error) {
f, err := os.Open(path)
if err != nil {
return "", 0, errors.Mask(err)
}
defer f.Close()
h := sha256.New()
size, err = io.Copy(h, f)
if err != nil {
return "", 0, errors.Mask(err)
}
return fmt.Sprintf("%x", h.Sum(nil)), size, nil
} | go | func hashAndSize(path string) (hash string, size int64, err error) {
f, err := os.Open(path)
if err != nil {
return "", 0, errors.Mask(err)
}
defer f.Close()
h := sha256.New()
size, err = io.Copy(h, f)
if err != nil {
return "", 0, errors.Mask(err)
}
return fmt.Sprintf("%x", h.Sum(nil)), size, nil
} | [
"func",
"hashAndSize",
"(",
"path",
"string",
")",
"(",
"hash",
"string",
",",
"size",
"int64",
",",
"err",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"errors",
".",
"Mask",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"h",
":=",
"sha256",
".",
"New",
"(",
")",
"\n",
"size",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"h",
",",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"errors",
".",
"Mask",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"h",
".",
"Sum",
"(",
"nil",
")",
")",
",",
"size",
",",
"nil",
"\n",
"}"
] | // hashAndSize calculates and returns the SHA256 hash and the size of the file
// located at the given path. | [
"hashAndSize",
"calculates",
"and",
"returns",
"the",
"SHA256",
"hash",
"and",
"the",
"size",
"of",
"the",
"file",
"located",
"at",
"the",
"given",
"path",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/bootstrap.go#L1023-L1035 |
4,057 | juju/juju | cmd/juju/crossmodel/list.go | NewListEndpointsCommand | func NewListEndpointsCommand() cmd.Command {
listCmd := &listCommand{}
listCmd.newAPIFunc = func() (ListAPI, error) {
return listCmd.NewApplicationOffersAPI()
}
listCmd.refreshModels = listCmd.ModelCommandBase.RefreshModels
return modelcmd.Wrap(listCmd)
} | go | func NewListEndpointsCommand() cmd.Command {
listCmd := &listCommand{}
listCmd.newAPIFunc = func() (ListAPI, error) {
return listCmd.NewApplicationOffersAPI()
}
listCmd.refreshModels = listCmd.ModelCommandBase.RefreshModels
return modelcmd.Wrap(listCmd)
} | [
"func",
"NewListEndpointsCommand",
"(",
")",
"cmd",
".",
"Command",
"{",
"listCmd",
":=",
"&",
"listCommand",
"{",
"}",
"\n",
"listCmd",
".",
"newAPIFunc",
"=",
"func",
"(",
")",
"(",
"ListAPI",
",",
"error",
")",
"{",
"return",
"listCmd",
".",
"NewApplicationOffersAPI",
"(",
")",
"\n",
"}",
"\n",
"listCmd",
".",
"refreshModels",
"=",
"listCmd",
".",
"ModelCommandBase",
".",
"RefreshModels",
"\n",
"return",
"modelcmd",
".",
"Wrap",
"(",
"listCmd",
")",
"\n",
"}"
] | // NewListEndpointsCommand constructs new list endpoint command. | [
"NewListEndpointsCommand",
"constructs",
"new",
"list",
"endpoint",
"command",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/list.go#L76-L83 |
4,058 | juju/juju | cmd/juju/crossmodel/list.go | convertCharmEndpoints | func convertCharmEndpoints(relations ...charm.Relation) map[string]RemoteEndpoint {
if len(relations) == 0 {
return nil
}
output := make(map[string]RemoteEndpoint, len(relations))
for _, one := range relations {
output[one.Name] = RemoteEndpoint{one.Name, one.Interface, string(one.Role)}
}
return output
} | go | func convertCharmEndpoints(relations ...charm.Relation) map[string]RemoteEndpoint {
if len(relations) == 0 {
return nil
}
output := make(map[string]RemoteEndpoint, len(relations))
for _, one := range relations {
output[one.Name] = RemoteEndpoint{one.Name, one.Interface, string(one.Role)}
}
return output
} | [
"func",
"convertCharmEndpoints",
"(",
"relations",
"...",
"charm",
".",
"Relation",
")",
"map",
"[",
"string",
"]",
"RemoteEndpoint",
"{",
"if",
"len",
"(",
"relations",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"output",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"RemoteEndpoint",
",",
"len",
"(",
"relations",
")",
")",
"\n",
"for",
"_",
",",
"one",
":=",
"range",
"relations",
"{",
"output",
"[",
"one",
".",
"Name",
"]",
"=",
"RemoteEndpoint",
"{",
"one",
".",
"Name",
",",
"one",
".",
"Interface",
",",
"string",
"(",
"one",
".",
"Role",
")",
"}",
"\n",
"}",
"\n",
"return",
"output",
"\n",
"}"
] | // convertCharmEndpoints takes any number of charm relations and
// creates a collection of ui-formatted endpoints. | [
"convertCharmEndpoints",
"takes",
"any",
"number",
"of",
"charm",
"relations",
"and",
"creates",
"a",
"collection",
"of",
"ui",
"-",
"formatted",
"endpoints",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/list.go#L302-L311 |
4,059 | juju/juju | state/controller.go | GetState | func (ctlr *Controller) GetState(modelTag names.ModelTag) (*PooledState, error) {
return ctlr.pool.Get(modelTag.Id())
} | go | func (ctlr *Controller) GetState(modelTag names.ModelTag) (*PooledState, error) {
return ctlr.pool.Get(modelTag.Id())
} | [
"func",
"(",
"ctlr",
"*",
"Controller",
")",
"GetState",
"(",
"modelTag",
"names",
".",
"ModelTag",
")",
"(",
"*",
"PooledState",
",",
"error",
")",
"{",
"return",
"ctlr",
".",
"pool",
".",
"Get",
"(",
"modelTag",
".",
"Id",
"(",
")",
")",
"\n",
"}"
] | // GetState returns a new State instance for the specified model. The
// connection uses the same credentials and policy as the Controller. | [
"GetState",
"returns",
"a",
"new",
"State",
"instance",
"for",
"the",
"specified",
"model",
".",
"The",
"connection",
"uses",
"the",
"same",
"credentials",
"and",
"policy",
"as",
"the",
"Controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/controller.go#L68-L70 |
4,060 | juju/juju | state/controller.go | Ping | func (ctlr *Controller) Ping() error {
if ctlr.pool.SystemState() == nil {
return errors.New("pool is closed")
}
return ctlr.pool.SystemState().Ping()
} | go | func (ctlr *Controller) Ping() error {
if ctlr.pool.SystemState() == nil {
return errors.New("pool is closed")
}
return ctlr.pool.SystemState().Ping()
} | [
"func",
"(",
"ctlr",
"*",
"Controller",
")",
"Ping",
"(",
")",
"error",
"{",
"if",
"ctlr",
".",
"pool",
".",
"SystemState",
"(",
")",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"ctlr",
".",
"pool",
".",
"SystemState",
"(",
")",
".",
"Ping",
"(",
")",
"\n",
"}"
] | // Ping probes the Controllers's database connection to ensure that it
// is still alive. | [
"Ping",
"probes",
"the",
"Controllers",
"s",
"database",
"connection",
"to",
"ensure",
"that",
"it",
"is",
"still",
"alive",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/controller.go#L74-L79 |
4,061 | juju/juju | state/controller.go | ControllerConfig | func (st *State) ControllerConfig() (jujucontroller.Config, error) {
settings, err := readSettings(st.db(), controllersC, controllerSettingsGlobalKey)
if err != nil {
return nil, errors.Annotatef(err, "controller %q", st.ControllerUUID())
}
return settings.Map(), nil
} | go | func (st *State) ControllerConfig() (jujucontroller.Config, error) {
settings, err := readSettings(st.db(), controllersC, controllerSettingsGlobalKey)
if err != nil {
return nil, errors.Annotatef(err, "controller %q", st.ControllerUUID())
}
return settings.Map(), nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"ControllerConfig",
"(",
")",
"(",
"jujucontroller",
".",
"Config",
",",
"error",
")",
"{",
"settings",
",",
"err",
":=",
"readSettings",
"(",
"st",
".",
"db",
"(",
")",
",",
"controllersC",
",",
"controllerSettingsGlobalKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"st",
".",
"ControllerUUID",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"settings",
".",
"Map",
"(",
")",
",",
"nil",
"\n",
"}"
] | // ControllerConfig returns the config values for the controller. | [
"ControllerConfig",
"returns",
"the",
"config",
"values",
"for",
"the",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/controller.go#L82-L88 |
4,062 | juju/juju | state/controller.go | checkSpaceIsAvailableToAllControllers | func (st *State) checkSpaceIsAvailableToAllControllers(configSpace string) error {
info, err := st.ControllerInfo()
if err != nil {
return errors.Annotate(err, "cannot get controller info")
}
var missing []string
spaceName := network.SpaceName(configSpace)
for _, id := range info.MachineIds {
m, err := st.Machine(id)
if err != nil {
return errors.Annotate(err, "cannot get machine")
}
if _, ok := network.SelectAddressesBySpaceNames(m.Addresses(), spaceName); !ok {
missing = append(missing, id)
}
}
if len(missing) > 0 {
return errors.Errorf("machines with no addresses in this space: %s", strings.Join(missing, ", "))
}
return nil
} | go | func (st *State) checkSpaceIsAvailableToAllControllers(configSpace string) error {
info, err := st.ControllerInfo()
if err != nil {
return errors.Annotate(err, "cannot get controller info")
}
var missing []string
spaceName := network.SpaceName(configSpace)
for _, id := range info.MachineIds {
m, err := st.Machine(id)
if err != nil {
return errors.Annotate(err, "cannot get machine")
}
if _, ok := network.SelectAddressesBySpaceNames(m.Addresses(), spaceName); !ok {
missing = append(missing, id)
}
}
if len(missing) > 0 {
return errors.Errorf("machines with no addresses in this space: %s", strings.Join(missing, ", "))
}
return nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"checkSpaceIsAvailableToAllControllers",
"(",
"configSpace",
"string",
")",
"error",
"{",
"info",
",",
"err",
":=",
"st",
".",
"ControllerInfo",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"missing",
"[",
"]",
"string",
"\n",
"spaceName",
":=",
"network",
".",
"SpaceName",
"(",
"configSpace",
")",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"info",
".",
"MachineIds",
"{",
"m",
",",
"err",
":=",
"st",
".",
"Machine",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"network",
".",
"SelectAddressesBySpaceNames",
"(",
"m",
".",
"Addresses",
"(",
")",
",",
"spaceName",
")",
";",
"!",
"ok",
"{",
"missing",
"=",
"append",
"(",
"missing",
",",
"id",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"missing",
")",
">",
"0",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"missing",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // checkSpaceIsAvailableToAllControllers checks if each controller machine has
// at least one address in the input space. If not, an error is returned. | [
"checkSpaceIsAvailableToAllControllers",
"checks",
"if",
"each",
"controller",
"machine",
"has",
"at",
"least",
"one",
"address",
"in",
"the",
"input",
"space",
".",
"If",
"not",
"an",
"error",
"is",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/controller.go#L157-L179 |
4,063 | juju/juju | provider/oracle/storage_provider.go | Supports | func (s storageProvider) Supports(kind storage.StorageKind) bool {
return kind == storage.StorageKindBlock
} | go | func (s storageProvider) Supports(kind storage.StorageKind) bool {
return kind == storage.StorageKindBlock
} | [
"func",
"(",
"s",
"storageProvider",
")",
"Supports",
"(",
"kind",
"storage",
".",
"StorageKind",
")",
"bool",
"{",
"return",
"kind",
"==",
"storage",
".",
"StorageKindBlock",
"\n",
"}"
] | // Supports is defined on the storage.Provider interface. | [
"Supports",
"is",
"defined",
"on",
"the",
"storage",
".",
"Provider",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/storage_provider.go#L43-L45 |
4,064 | juju/juju | provider/oracle/storage_provider.go | DefaultPools | func (s storageProvider) DefaultPools() []*storage.Config {
latencyPool, _ := storage.NewConfig("oracle-latency", oracleStorageProviderType, map[string]interface{}{
oracleVolumeType: latencyPool,
})
return []*storage.Config{latencyPool}
} | go | func (s storageProvider) DefaultPools() []*storage.Config {
latencyPool, _ := storage.NewConfig("oracle-latency", oracleStorageProviderType, map[string]interface{}{
oracleVolumeType: latencyPool,
})
return []*storage.Config{latencyPool}
} | [
"func",
"(",
"s",
"storageProvider",
")",
"DefaultPools",
"(",
")",
"[",
"]",
"*",
"storage",
".",
"Config",
"{",
"latencyPool",
",",
"_",
":=",
"storage",
".",
"NewConfig",
"(",
"\"",
"\"",
",",
"oracleStorageProviderType",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"oracleVolumeType",
":",
"latencyPool",
",",
"}",
")",
"\n",
"return",
"[",
"]",
"*",
"storage",
".",
"Config",
"{",
"latencyPool",
"}",
"\n",
"}"
] | // DefaultPools is defined on the storage.Provider interface. | [
"DefaultPools",
"is",
"defined",
"on",
"the",
"storage",
".",
"Provider",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/storage_provider.go#L64-L69 |
4,065 | juju/juju | core/model/generation.go | ValidateBranchName | func ValidateBranchName(name string) error {
if name == "" {
return errors.NotValidf("empty branch name")
}
if name == GenerationMaster {
return errors.NotValidf("branch name %q", GenerationMaster)
}
return nil
} | go | func ValidateBranchName(name string) error {
if name == "" {
return errors.NotValidf("empty branch name")
}
if name == GenerationMaster {
return errors.NotValidf("branch name %q", GenerationMaster)
}
return nil
} | [
"func",
"ValidateBranchName",
"(",
"name",
"string",
")",
"error",
"{",
"if",
"name",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"name",
"==",
"GenerationMaster",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
",",
"GenerationMaster",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ValidateBranchName returns an error if the input name is not suitable for
// identifying a new in-flight branch. | [
"ValidateBranchName",
"returns",
"an",
"error",
"if",
"the",
"input",
"name",
"is",
"not",
"suitable",
"for",
"identifying",
"a",
"new",
"in",
"-",
"flight",
"branch",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/model/generation.go#L19-L27 |
4,066 | juju/juju | state/imagestorage/image.go | NewStorage | func NewStorage(
session *mgo.Session,
modelUUID string,
) Storage {
blobDb := session.DB(ImagesDB)
metadataCollection := blobDb.C(imagemetadataC)
return &imageStorage{
modelUUID,
metadataCollection,
blobDb,
}
} | go | func NewStorage(
session *mgo.Session,
modelUUID string,
) Storage {
blobDb := session.DB(ImagesDB)
metadataCollection := blobDb.C(imagemetadataC)
return &imageStorage{
modelUUID,
metadataCollection,
blobDb,
}
} | [
"func",
"NewStorage",
"(",
"session",
"*",
"mgo",
".",
"Session",
",",
"modelUUID",
"string",
",",
")",
"Storage",
"{",
"blobDb",
":=",
"session",
".",
"DB",
"(",
"ImagesDB",
")",
"\n",
"metadataCollection",
":=",
"blobDb",
".",
"C",
"(",
"imagemetadataC",
")",
"\n",
"return",
"&",
"imageStorage",
"{",
"modelUUID",
",",
"metadataCollection",
",",
"blobDb",
",",
"}",
"\n",
"}"
] | // NewStorage constructs a new Storage that stores image blobs
// in an "osimages" database. Image metadata is also stored in this
// database in the "imagemetadata" collection. | [
"NewStorage",
"constructs",
"a",
"new",
"Storage",
"that",
"stores",
"image",
"blobs",
"in",
"an",
"osimages",
"database",
".",
"Image",
"metadata",
"is",
"also",
"stored",
"in",
"this",
"database",
"in",
"the",
"imagemetadata",
"collection",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/imagestorage/image.go#L43-L54 |
4,067 | juju/juju | state/imagestorage/image.go | AddImage | func (s *imageStorage) AddImage(r io.Reader, metadata *Metadata) (resultErr error) {
session := s.blobDb.Session.Copy()
defer session.Close()
managedStorage := s.getManagedStorage(session)
path := imagePath(metadata.Kind, metadata.Series, metadata.Arch, metadata.SHA256)
if err := managedStorage.PutForBucket(s.modelUUID, path, r, metadata.Size); err != nil {
return errors.Annotate(err, "cannot store image")
}
defer func() {
if resultErr == nil {
return
}
err := managedStorage.RemoveForBucket(s.modelUUID, path)
if err != nil {
logger.Errorf("failed to remove image blob: %v", err)
}
}()
newDoc := imageMetadataDoc{
Id: docId(metadata),
ModelUUID: s.modelUUID,
Kind: metadata.Kind,
Series: metadata.Series,
Arch: metadata.Arch,
Size: metadata.Size,
SHA256: metadata.SHA256,
SourceURL: metadata.SourceURL,
Path: path,
// TODO(fwereade): 2016-03-17 lp:1558657
Created: time.Now(),
}
// Add or replace metadata. If replacing, record the
// existing path so we can remove the blob later.
var oldPath string
buildTxn := func(attempt int) ([]txn.Op, error) {
op := txn.Op{
C: imagemetadataC,
Id: newDoc.Id,
}
// On the first attempt we assume we're adding a new image blob.
// Subsequent attempts to add image will fetch the existing
// doc, record the old path, and attempt to update the
// size, path and hash fields.
if attempt == 0 {
op.Assert = txn.DocMissing
op.Insert = &newDoc
} else {
oldDoc, err := s.imageMetadataDoc(metadata.ModelUUID, metadata.Kind, metadata.Series, metadata.Arch)
if err != nil {
return nil, err
}
oldPath = oldDoc.Path
op.Assert = bson.D{{"path", oldPath}}
if oldPath != path {
op.Update = bson.D{{
"$set", bson.D{
{"size", metadata.Size},
{"sha256", metadata.SHA256},
{"path", path},
},
}}
}
}
return []txn.Op{op}, nil
}
txnRunner := s.txnRunner(session)
err := txnRunner.Run(buildTxn)
if err != nil {
return errors.Annotate(err, "cannot store image metadata")
}
if oldPath != "" && oldPath != path {
// Attempt to remove the old path. Failure is non-fatal.
err := managedStorage.RemoveForBucket(s.modelUUID, oldPath)
if err != nil {
logger.Errorf("failed to remove old image blob: %v", err)
} else {
logger.Debugf("removed old image blob")
}
}
return nil
} | go | func (s *imageStorage) AddImage(r io.Reader, metadata *Metadata) (resultErr error) {
session := s.blobDb.Session.Copy()
defer session.Close()
managedStorage := s.getManagedStorage(session)
path := imagePath(metadata.Kind, metadata.Series, metadata.Arch, metadata.SHA256)
if err := managedStorage.PutForBucket(s.modelUUID, path, r, metadata.Size); err != nil {
return errors.Annotate(err, "cannot store image")
}
defer func() {
if resultErr == nil {
return
}
err := managedStorage.RemoveForBucket(s.modelUUID, path)
if err != nil {
logger.Errorf("failed to remove image blob: %v", err)
}
}()
newDoc := imageMetadataDoc{
Id: docId(metadata),
ModelUUID: s.modelUUID,
Kind: metadata.Kind,
Series: metadata.Series,
Arch: metadata.Arch,
Size: metadata.Size,
SHA256: metadata.SHA256,
SourceURL: metadata.SourceURL,
Path: path,
// TODO(fwereade): 2016-03-17 lp:1558657
Created: time.Now(),
}
// Add or replace metadata. If replacing, record the
// existing path so we can remove the blob later.
var oldPath string
buildTxn := func(attempt int) ([]txn.Op, error) {
op := txn.Op{
C: imagemetadataC,
Id: newDoc.Id,
}
// On the first attempt we assume we're adding a new image blob.
// Subsequent attempts to add image will fetch the existing
// doc, record the old path, and attempt to update the
// size, path and hash fields.
if attempt == 0 {
op.Assert = txn.DocMissing
op.Insert = &newDoc
} else {
oldDoc, err := s.imageMetadataDoc(metadata.ModelUUID, metadata.Kind, metadata.Series, metadata.Arch)
if err != nil {
return nil, err
}
oldPath = oldDoc.Path
op.Assert = bson.D{{"path", oldPath}}
if oldPath != path {
op.Update = bson.D{{
"$set", bson.D{
{"size", metadata.Size},
{"sha256", metadata.SHA256},
{"path", path},
},
}}
}
}
return []txn.Op{op}, nil
}
txnRunner := s.txnRunner(session)
err := txnRunner.Run(buildTxn)
if err != nil {
return errors.Annotate(err, "cannot store image metadata")
}
if oldPath != "" && oldPath != path {
// Attempt to remove the old path. Failure is non-fatal.
err := managedStorage.RemoveForBucket(s.modelUUID, oldPath)
if err != nil {
logger.Errorf("failed to remove old image blob: %v", err)
} else {
logger.Debugf("removed old image blob")
}
}
return nil
} | [
"func",
"(",
"s",
"*",
"imageStorage",
")",
"AddImage",
"(",
"r",
"io",
".",
"Reader",
",",
"metadata",
"*",
"Metadata",
")",
"(",
"resultErr",
"error",
")",
"{",
"session",
":=",
"s",
".",
"blobDb",
".",
"Session",
".",
"Copy",
"(",
")",
"\n",
"defer",
"session",
".",
"Close",
"(",
")",
"\n",
"managedStorage",
":=",
"s",
".",
"getManagedStorage",
"(",
"session",
")",
"\n",
"path",
":=",
"imagePath",
"(",
"metadata",
".",
"Kind",
",",
"metadata",
".",
"Series",
",",
"metadata",
".",
"Arch",
",",
"metadata",
".",
"SHA256",
")",
"\n",
"if",
"err",
":=",
"managedStorage",
".",
"PutForBucket",
"(",
"s",
".",
"modelUUID",
",",
"path",
",",
"r",
",",
"metadata",
".",
"Size",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"resultErr",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"err",
":=",
"managedStorage",
".",
"RemoveForBucket",
"(",
"s",
".",
"modelUUID",
",",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"newDoc",
":=",
"imageMetadataDoc",
"{",
"Id",
":",
"docId",
"(",
"metadata",
")",
",",
"ModelUUID",
":",
"s",
".",
"modelUUID",
",",
"Kind",
":",
"metadata",
".",
"Kind",
",",
"Series",
":",
"metadata",
".",
"Series",
",",
"Arch",
":",
"metadata",
".",
"Arch",
",",
"Size",
":",
"metadata",
".",
"Size",
",",
"SHA256",
":",
"metadata",
".",
"SHA256",
",",
"SourceURL",
":",
"metadata",
".",
"SourceURL",
",",
"Path",
":",
"path",
",",
"// TODO(fwereade): 2016-03-17 lp:1558657",
"Created",
":",
"time",
".",
"Now",
"(",
")",
",",
"}",
"\n\n",
"// Add or replace metadata. If replacing, record the",
"// existing path so we can remove the blob later.",
"var",
"oldPath",
"string",
"\n",
"buildTxn",
":=",
"func",
"(",
"attempt",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"op",
":=",
"txn",
".",
"Op",
"{",
"C",
":",
"imagemetadataC",
",",
"Id",
":",
"newDoc",
".",
"Id",
",",
"}",
"\n\n",
"// On the first attempt we assume we're adding a new image blob.",
"// Subsequent attempts to add image will fetch the existing",
"// doc, record the old path, and attempt to update the",
"// size, path and hash fields.",
"if",
"attempt",
"==",
"0",
"{",
"op",
".",
"Assert",
"=",
"txn",
".",
"DocMissing",
"\n",
"op",
".",
"Insert",
"=",
"&",
"newDoc",
"\n",
"}",
"else",
"{",
"oldDoc",
",",
"err",
":=",
"s",
".",
"imageMetadataDoc",
"(",
"metadata",
".",
"ModelUUID",
",",
"metadata",
".",
"Kind",
",",
"metadata",
".",
"Series",
",",
"metadata",
".",
"Arch",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"oldPath",
"=",
"oldDoc",
".",
"Path",
"\n",
"op",
".",
"Assert",
"=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"oldPath",
"}",
"}",
"\n",
"if",
"oldPath",
"!=",
"path",
"{",
"op",
".",
"Update",
"=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"metadata",
".",
"Size",
"}",
",",
"{",
"\"",
"\"",
",",
"metadata",
".",
"SHA256",
"}",
",",
"{",
"\"",
"\"",
",",
"path",
"}",
",",
"}",
",",
"}",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"[",
"]",
"txn",
".",
"Op",
"{",
"op",
"}",
",",
"nil",
"\n",
"}",
"\n",
"txnRunner",
":=",
"s",
".",
"txnRunner",
"(",
"session",
")",
"\n",
"err",
":=",
"txnRunner",
".",
"Run",
"(",
"buildTxn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"oldPath",
"!=",
"\"",
"\"",
"&&",
"oldPath",
"!=",
"path",
"{",
"// Attempt to remove the old path. Failure is non-fatal.",
"err",
":=",
"managedStorage",
".",
"RemoveForBucket",
"(",
"s",
".",
"modelUUID",
",",
"oldPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddImage is defined on the Storage interface. | [
"AddImage",
"is",
"defined",
"on",
"the",
"Storage",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/imagestorage/image.go#L83-L166 |
4,068 | juju/juju | state/imagestorage/image.go | ListImages | func (s *imageStorage) ListImages(filter ImageFilter) ([]*Metadata, error) {
metadataDocs, err := s.listImageMetadataDocs(s.modelUUID, filter.Kind, filter.Series, filter.Arch)
if err != nil {
return nil, errors.Annotate(err, "cannot list image metadata")
}
result := make([]*Metadata, len(metadataDocs))
for i, metadataDoc := range metadataDocs {
result[i] = &Metadata{
ModelUUID: s.modelUUID,
Kind: metadataDoc.Kind,
Series: metadataDoc.Series,
Arch: metadataDoc.Arch,
Size: metadataDoc.Size,
SHA256: metadataDoc.SHA256,
Created: metadataDoc.Created,
SourceURL: metadataDoc.SourceURL,
}
}
return result, nil
} | go | func (s *imageStorage) ListImages(filter ImageFilter) ([]*Metadata, error) {
metadataDocs, err := s.listImageMetadataDocs(s.modelUUID, filter.Kind, filter.Series, filter.Arch)
if err != nil {
return nil, errors.Annotate(err, "cannot list image metadata")
}
result := make([]*Metadata, len(metadataDocs))
for i, metadataDoc := range metadataDocs {
result[i] = &Metadata{
ModelUUID: s.modelUUID,
Kind: metadataDoc.Kind,
Series: metadataDoc.Series,
Arch: metadataDoc.Arch,
Size: metadataDoc.Size,
SHA256: metadataDoc.SHA256,
Created: metadataDoc.Created,
SourceURL: metadataDoc.SourceURL,
}
}
return result, nil
} | [
"func",
"(",
"s",
"*",
"imageStorage",
")",
"ListImages",
"(",
"filter",
"ImageFilter",
")",
"(",
"[",
"]",
"*",
"Metadata",
",",
"error",
")",
"{",
"metadataDocs",
",",
"err",
":=",
"s",
".",
"listImageMetadataDocs",
"(",
"s",
".",
"modelUUID",
",",
"filter",
".",
"Kind",
",",
"filter",
".",
"Series",
",",
"filter",
".",
"Arch",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"*",
"Metadata",
",",
"len",
"(",
"metadataDocs",
")",
")",
"\n",
"for",
"i",
",",
"metadataDoc",
":=",
"range",
"metadataDocs",
"{",
"result",
"[",
"i",
"]",
"=",
"&",
"Metadata",
"{",
"ModelUUID",
":",
"s",
".",
"modelUUID",
",",
"Kind",
":",
"metadataDoc",
".",
"Kind",
",",
"Series",
":",
"metadataDoc",
".",
"Series",
",",
"Arch",
":",
"metadataDoc",
".",
"Arch",
",",
"Size",
":",
"metadataDoc",
".",
"Size",
",",
"SHA256",
":",
"metadataDoc",
".",
"SHA256",
",",
"Created",
":",
"metadataDoc",
".",
"Created",
",",
"SourceURL",
":",
"metadataDoc",
".",
"SourceURL",
",",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // ListImages is defined on the Storage interface. | [
"ListImages",
"is",
"defined",
"on",
"the",
"Storage",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/imagestorage/image.go#L169-L188 |
4,069 | juju/juju | state/imagestorage/image.go | DeleteImage | func (s *imageStorage) DeleteImage(metadata *Metadata) (resultErr error) {
session := s.blobDb.Session.Copy()
defer session.Close()
managedStorage := s.getManagedStorage(session)
path := imagePath(metadata.Kind, metadata.Series, metadata.Arch, metadata.SHA256)
if err := managedStorage.RemoveForBucket(s.modelUUID, path); err != nil {
return errors.Annotate(err, "cannot remove image blob")
}
// Remove the metadata.
buildTxn := func(attempt int) ([]txn.Op, error) {
op := txn.Op{
C: imagemetadataC,
Id: docId(metadata),
Remove: true,
}
return []txn.Op{op}, nil
}
txnRunner := s.txnRunner(session)
err := txnRunner.Run(buildTxn)
// Metadata already removed, we don't care.
if err == mgo.ErrNotFound {
return nil
}
return errors.Annotate(err, "cannot remove image metadata")
} | go | func (s *imageStorage) DeleteImage(metadata *Metadata) (resultErr error) {
session := s.blobDb.Session.Copy()
defer session.Close()
managedStorage := s.getManagedStorage(session)
path := imagePath(metadata.Kind, metadata.Series, metadata.Arch, metadata.SHA256)
if err := managedStorage.RemoveForBucket(s.modelUUID, path); err != nil {
return errors.Annotate(err, "cannot remove image blob")
}
// Remove the metadata.
buildTxn := func(attempt int) ([]txn.Op, error) {
op := txn.Op{
C: imagemetadataC,
Id: docId(metadata),
Remove: true,
}
return []txn.Op{op}, nil
}
txnRunner := s.txnRunner(session)
err := txnRunner.Run(buildTxn)
// Metadata already removed, we don't care.
if err == mgo.ErrNotFound {
return nil
}
return errors.Annotate(err, "cannot remove image metadata")
} | [
"func",
"(",
"s",
"*",
"imageStorage",
")",
"DeleteImage",
"(",
"metadata",
"*",
"Metadata",
")",
"(",
"resultErr",
"error",
")",
"{",
"session",
":=",
"s",
".",
"blobDb",
".",
"Session",
".",
"Copy",
"(",
")",
"\n",
"defer",
"session",
".",
"Close",
"(",
")",
"\n",
"managedStorage",
":=",
"s",
".",
"getManagedStorage",
"(",
"session",
")",
"\n",
"path",
":=",
"imagePath",
"(",
"metadata",
".",
"Kind",
",",
"metadata",
".",
"Series",
",",
"metadata",
".",
"Arch",
",",
"metadata",
".",
"SHA256",
")",
"\n",
"if",
"err",
":=",
"managedStorage",
".",
"RemoveForBucket",
"(",
"s",
".",
"modelUUID",
",",
"path",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Remove the metadata.",
"buildTxn",
":=",
"func",
"(",
"attempt",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"op",
":=",
"txn",
".",
"Op",
"{",
"C",
":",
"imagemetadataC",
",",
"Id",
":",
"docId",
"(",
"metadata",
")",
",",
"Remove",
":",
"true",
",",
"}",
"\n",
"return",
"[",
"]",
"txn",
".",
"Op",
"{",
"op",
"}",
",",
"nil",
"\n",
"}",
"\n",
"txnRunner",
":=",
"s",
".",
"txnRunner",
"(",
"session",
")",
"\n",
"err",
":=",
"txnRunner",
".",
"Run",
"(",
"buildTxn",
")",
"\n",
"// Metadata already removed, we don't care.",
"if",
"err",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // DeleteImage is defined on the Storage interface. | [
"DeleteImage",
"is",
"defined",
"on",
"the",
"Storage",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/imagestorage/image.go#L191-L215 |
4,070 | juju/juju | state/imagestorage/image.go | Image | func (s *imageStorage) Image(kind, series, arch string) (*Metadata, io.ReadCloser, error) {
metadataDoc, err := s.imageMetadataDoc(s.modelUUID, kind, series, arch)
if err != nil {
return nil, nil, err
}
session := s.blobDb.Session.Copy()
managedStorage := s.getManagedStorage(session)
image, err := s.imageBlob(managedStorage, metadataDoc.Path)
if err != nil {
return nil, nil, err
}
metadata := &Metadata{
ModelUUID: s.modelUUID,
Kind: metadataDoc.Kind,
Series: metadataDoc.Series,
Arch: metadataDoc.Arch,
Size: metadataDoc.Size,
SHA256: metadataDoc.SHA256,
SourceURL: metadataDoc.SourceURL,
Created: metadataDoc.Created,
}
imageResult := &imageCloser{
image,
session,
}
return metadata, imageResult, nil
} | go | func (s *imageStorage) Image(kind, series, arch string) (*Metadata, io.ReadCloser, error) {
metadataDoc, err := s.imageMetadataDoc(s.modelUUID, kind, series, arch)
if err != nil {
return nil, nil, err
}
session := s.blobDb.Session.Copy()
managedStorage := s.getManagedStorage(session)
image, err := s.imageBlob(managedStorage, metadataDoc.Path)
if err != nil {
return nil, nil, err
}
metadata := &Metadata{
ModelUUID: s.modelUUID,
Kind: metadataDoc.Kind,
Series: metadataDoc.Series,
Arch: metadataDoc.Arch,
Size: metadataDoc.Size,
SHA256: metadataDoc.SHA256,
SourceURL: metadataDoc.SourceURL,
Created: metadataDoc.Created,
}
imageResult := &imageCloser{
image,
session,
}
return metadata, imageResult, nil
} | [
"func",
"(",
"s",
"*",
"imageStorage",
")",
"Image",
"(",
"kind",
",",
"series",
",",
"arch",
"string",
")",
"(",
"*",
"Metadata",
",",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"metadataDoc",
",",
"err",
":=",
"s",
".",
"imageMetadataDoc",
"(",
"s",
".",
"modelUUID",
",",
"kind",
",",
"series",
",",
"arch",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"session",
":=",
"s",
".",
"blobDb",
".",
"Session",
".",
"Copy",
"(",
")",
"\n",
"managedStorage",
":=",
"s",
".",
"getManagedStorage",
"(",
"session",
")",
"\n",
"image",
",",
"err",
":=",
"s",
".",
"imageBlob",
"(",
"managedStorage",
",",
"metadataDoc",
".",
"Path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"metadata",
":=",
"&",
"Metadata",
"{",
"ModelUUID",
":",
"s",
".",
"modelUUID",
",",
"Kind",
":",
"metadataDoc",
".",
"Kind",
",",
"Series",
":",
"metadataDoc",
".",
"Series",
",",
"Arch",
":",
"metadataDoc",
".",
"Arch",
",",
"Size",
":",
"metadataDoc",
".",
"Size",
",",
"SHA256",
":",
"metadataDoc",
".",
"SHA256",
",",
"SourceURL",
":",
"metadataDoc",
".",
"SourceURL",
",",
"Created",
":",
"metadataDoc",
".",
"Created",
",",
"}",
"\n",
"imageResult",
":=",
"&",
"imageCloser",
"{",
"image",
",",
"session",
",",
"}",
"\n",
"return",
"metadata",
",",
"imageResult",
",",
"nil",
"\n",
"}"
] | // Image is defined on the Storage interface. | [
"Image",
"is",
"defined",
"on",
"the",
"Storage",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/imagestorage/image.go#L230-L256 |
4,071 | juju/juju | state/imagestorage/image.go | imagePath | func imagePath(kind, series, arch, checksum string) string {
return fmt.Sprintf("images/%s-%s-%s:%s", kind, series, arch, checksum)
} | go | func imagePath(kind, series, arch, checksum string) string {
return fmt.Sprintf("images/%s-%s-%s:%s", kind, series, arch, checksum)
} | [
"func",
"imagePath",
"(",
"kind",
",",
"series",
",",
"arch",
",",
"checksum",
"string",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"kind",
",",
"series",
",",
"arch",
",",
"checksum",
")",
"\n",
"}"
] | // imagePath returns the storage path for the specified image. | [
"imagePath",
"returns",
"the",
"storage",
"path",
"for",
"the",
"specified",
"image",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/imagestorage/image.go#L309-L311 |
4,072 | juju/juju | state/imagestorage/image.go | docId | func docId(metadata *Metadata) string {
return fmt.Sprintf("%s-%s-%s-%s", metadata.ModelUUID, metadata.Kind, metadata.Series, metadata.Arch)
} | go | func docId(metadata *Metadata) string {
return fmt.Sprintf("%s-%s-%s-%s", metadata.ModelUUID, metadata.Kind, metadata.Series, metadata.Arch)
} | [
"func",
"docId",
"(",
"metadata",
"*",
"Metadata",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"metadata",
".",
"ModelUUID",
",",
"metadata",
".",
"Kind",
",",
"metadata",
".",
"Series",
",",
"metadata",
".",
"Arch",
")",
"\n",
"}"
] | // docId returns an id for the mongo image metadata document. | [
"docId",
"returns",
"an",
"id",
"for",
"the",
"mongo",
"image",
"metadata",
"document",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/imagestorage/image.go#L314-L316 |
4,073 | juju/juju | worker/uniter/charm/charm.go | ReadCharmURL | func ReadCharmURL(path string) (*charm.URL, error) {
surl := ""
if err := utils.ReadYaml(path, &surl); err != nil {
return nil, err
}
return charm.ParseURL(surl)
} | go | func ReadCharmURL(path string) (*charm.URL, error) {
surl := ""
if err := utils.ReadYaml(path, &surl); err != nil {
return nil, err
}
return charm.ParseURL(surl)
} | [
"func",
"ReadCharmURL",
"(",
"path",
"string",
")",
"(",
"*",
"charm",
".",
"URL",
",",
"error",
")",
"{",
"surl",
":=",
"\"",
"\"",
"\n",
"if",
"err",
":=",
"utils",
".",
"ReadYaml",
"(",
"path",
",",
"&",
"surl",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"charm",
".",
"ParseURL",
"(",
"surl",
")",
"\n",
"}"
] | // ReadCharmURL reads a charm identity file from the supplied path. | [
"ReadCharmURL",
"reads",
"a",
"charm",
"identity",
"file",
"from",
"the",
"supplied",
"path",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/charm.go#L76-L82 |
4,074 | juju/juju | worker/uniter/charm/charm.go | WriteCharmURL | func WriteCharmURL(path string, url *charm.URL) error {
return utils.WriteYaml(path, url.String())
} | go | func WriteCharmURL(path string, url *charm.URL) error {
return utils.WriteYaml(path, url.String())
} | [
"func",
"WriteCharmURL",
"(",
"path",
"string",
",",
"url",
"*",
"charm",
".",
"URL",
")",
"error",
"{",
"return",
"utils",
".",
"WriteYaml",
"(",
"path",
",",
"url",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // WriteCharmURL writes a charm identity file into the supplied path. | [
"WriteCharmURL",
"writes",
"a",
"charm",
"identity",
"file",
"into",
"the",
"supplied",
"path",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/charm.go#L85-L87 |
4,075 | juju/juju | core/cache/charm.go | LXDProfile | func (c *Charm) LXDProfile() lxdprofile.Profile {
c.mu.Lock()
defer c.mu.Unlock()
return c.details.LXDProfile
} | go | func (c *Charm) LXDProfile() lxdprofile.Profile {
c.mu.Lock()
defer c.mu.Unlock()
return c.details.LXDProfile
} | [
"func",
"(",
"c",
"*",
"Charm",
")",
"LXDProfile",
"(",
")",
"lxdprofile",
".",
"Profile",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"c",
".",
"details",
".",
"LXDProfile",
"\n",
"}"
] | // LXDProfile returns the lxd profile of this charm. | [
"LXDProfile",
"returns",
"the",
"lxd",
"profile",
"of",
"this",
"charm",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/charm.go#L38-L42 |
4,076 | juju/juju | cmd/juju/firewall/setrule.go | NewSetFirewallRuleCommand | func NewSetFirewallRuleCommand() cmd.Command {
cmd := &setFirewallRuleCommand{}
cmd.newAPIFunc = func() (SetFirewallRuleAPI, error) {
root, err := cmd.NewAPIRoot()
if err != nil {
return nil, errors.Trace(err)
}
return firewallrules.NewClient(root), nil
}
return modelcmd.Wrap(cmd)
} | go | func NewSetFirewallRuleCommand() cmd.Command {
cmd := &setFirewallRuleCommand{}
cmd.newAPIFunc = func() (SetFirewallRuleAPI, error) {
root, err := cmd.NewAPIRoot()
if err != nil {
return nil, errors.Trace(err)
}
return firewallrules.NewClient(root), nil
}
return modelcmd.Wrap(cmd)
} | [
"func",
"NewSetFirewallRuleCommand",
"(",
")",
"cmd",
".",
"Command",
"{",
"cmd",
":=",
"&",
"setFirewallRuleCommand",
"{",
"}",
"\n",
"cmd",
".",
"newAPIFunc",
"=",
"func",
"(",
")",
"(",
"SetFirewallRuleAPI",
",",
"error",
")",
"{",
"root",
",",
"err",
":=",
"cmd",
".",
"NewAPIRoot",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"firewallrules",
".",
"NewClient",
"(",
"root",
")",
",",
"nil",
"\n\n",
"}",
"\n",
"return",
"modelcmd",
".",
"Wrap",
"(",
"cmd",
")",
"\n",
"}"
] | // NewSetFirewallRuleCommand returns a command to set firewall rules. | [
"NewSetFirewallRuleCommand",
"returns",
"a",
"command",
"to",
"set",
"firewall",
"rules",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/firewall/setrule.go#L41-L52 |
4,077 | juju/juju | worker/controller/tracker.go | Use | func (c *tracker) Use() (*state.Controller, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.references == 0 {
return nil, ErrControllerClosed
}
c.references++
return c.st, nil
} | go | func (c *tracker) Use() (*state.Controller, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.references == 0 {
return nil, ErrControllerClosed
}
c.references++
return c.st, nil
} | [
"func",
"(",
"c",
"*",
"tracker",
")",
"Use",
"(",
")",
"(",
"*",
"state",
".",
"Controller",
",",
"error",
")",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"c",
".",
"references",
"==",
"0",
"{",
"return",
"nil",
",",
"ErrControllerClosed",
"\n",
"}",
"\n",
"c",
".",
"references",
"++",
"\n",
"return",
"c",
".",
"st",
",",
"nil",
"\n",
"}"
] | // Use implements Tracker. | [
"Use",
"implements",
"Tracker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/controller/tracker.go#L50-L59 |
4,078 | juju/juju | worker/controller/tracker.go | Done | func (c *tracker) Done() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.references == 0 {
return ErrControllerClosed
}
c.references--
if c.references == 0 {
err := c.st.Close()
if err != nil {
logger.Errorf("error when closing controller: %v", err)
}
}
return nil
} | go | func (c *tracker) Done() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.references == 0 {
return ErrControllerClosed
}
c.references--
if c.references == 0 {
err := c.st.Close()
if err != nil {
logger.Errorf("error when closing controller: %v", err)
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"tracker",
")",
"Done",
"(",
")",
"error",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"c",
".",
"references",
"==",
"0",
"{",
"return",
"ErrControllerClosed",
"\n",
"}",
"\n",
"c",
".",
"references",
"--",
"\n",
"if",
"c",
".",
"references",
"==",
"0",
"{",
"err",
":=",
"c",
".",
"st",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Done implements Tracker. | [
"Done",
"implements",
"Tracker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/controller/tracker.go#L62-L77 |
4,079 | juju/juju | state/resources_mongo.go | resourceID | func resourceID(id, subType, subID string) string {
if subType == "" {
return fmt.Sprintf("resource#%s", id)
}
return fmt.Sprintf("resource#%s#%s-%s", id, subType, subID)
} | go | func resourceID(id, subType, subID string) string {
if subType == "" {
return fmt.Sprintf("resource#%s", id)
}
return fmt.Sprintf("resource#%s#%s-%s", id, subType, subID)
} | [
"func",
"resourceID",
"(",
"id",
",",
"subType",
",",
"subID",
"string",
")",
"string",
"{",
"if",
"subType",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"id",
",",
"subType",
",",
"subID",
")",
"\n",
"}"
] | // resourceID converts an external resource ID into an internal one. | [
"resourceID",
"converts",
"an",
"external",
"resource",
"ID",
"into",
"an",
"internal",
"one",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_mongo.go#L27-L32 |
4,080 | juju/juju | state/resources_mongo.go | newResolvePendingResourceOps | func newResolvePendingResourceOps(pending storedResource, exists bool) []txn.Op {
oldID := pendingResourceID(pending.ID, pending.PendingID)
newRes := pending
newRes.PendingID = ""
// TODO(ericsnow) Update newRes.StoragePath? Doing so would require
// moving the resource in the blobstore to the correct path, which
// we cannot do in the transaction...
ops := []txn.Op{{
C: resourcesC,
Id: oldID,
Assert: txn.DocExists,
Remove: true,
}}
// TODO(perrito666) 2016-05-02 lp:1558657
csRes := charmStoreResource{
Resource: newRes.Resource.Resource,
id: newRes.ID,
applicationID: newRes.ApplicationID,
// Truncate the time to remove monotonic time for Go 1.9+
// to make it easier for tests to compare the time.
lastPolled: time.Now().Truncate(1).UTC(),
}
if exists {
ops = append(ops, newUpdateResourceOps(newRes)...)
return append(ops, newUpdateCharmStoreResourceOps(csRes)...)
} else {
ops = append(ops, newInsertResourceOps(newRes)...)
return append(ops, newInsertCharmStoreResourceOps(csRes)...)
}
} | go | func newResolvePendingResourceOps(pending storedResource, exists bool) []txn.Op {
oldID := pendingResourceID(pending.ID, pending.PendingID)
newRes := pending
newRes.PendingID = ""
// TODO(ericsnow) Update newRes.StoragePath? Doing so would require
// moving the resource in the blobstore to the correct path, which
// we cannot do in the transaction...
ops := []txn.Op{{
C: resourcesC,
Id: oldID,
Assert: txn.DocExists,
Remove: true,
}}
// TODO(perrito666) 2016-05-02 lp:1558657
csRes := charmStoreResource{
Resource: newRes.Resource.Resource,
id: newRes.ID,
applicationID: newRes.ApplicationID,
// Truncate the time to remove monotonic time for Go 1.9+
// to make it easier for tests to compare the time.
lastPolled: time.Now().Truncate(1).UTC(),
}
if exists {
ops = append(ops, newUpdateResourceOps(newRes)...)
return append(ops, newUpdateCharmStoreResourceOps(csRes)...)
} else {
ops = append(ops, newInsertResourceOps(newRes)...)
return append(ops, newInsertCharmStoreResourceOps(csRes)...)
}
} | [
"func",
"newResolvePendingResourceOps",
"(",
"pending",
"storedResource",
",",
"exists",
"bool",
")",
"[",
"]",
"txn",
".",
"Op",
"{",
"oldID",
":=",
"pendingResourceID",
"(",
"pending",
".",
"ID",
",",
"pending",
".",
"PendingID",
")",
"\n",
"newRes",
":=",
"pending",
"\n",
"newRes",
".",
"PendingID",
"=",
"\"",
"\"",
"\n",
"// TODO(ericsnow) Update newRes.StoragePath? Doing so would require",
"// moving the resource in the blobstore to the correct path, which",
"// we cannot do in the transaction...",
"ops",
":=",
"[",
"]",
"txn",
".",
"Op",
"{",
"{",
"C",
":",
"resourcesC",
",",
"Id",
":",
"oldID",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Remove",
":",
"true",
",",
"}",
"}",
"\n\n",
"// TODO(perrito666) 2016-05-02 lp:1558657",
"csRes",
":=",
"charmStoreResource",
"{",
"Resource",
":",
"newRes",
".",
"Resource",
".",
"Resource",
",",
"id",
":",
"newRes",
".",
"ID",
",",
"applicationID",
":",
"newRes",
".",
"ApplicationID",
",",
"// Truncate the time to remove monotonic time for Go 1.9+",
"// to make it easier for tests to compare the time.",
"lastPolled",
":",
"time",
".",
"Now",
"(",
")",
".",
"Truncate",
"(",
"1",
")",
".",
"UTC",
"(",
")",
",",
"}",
"\n\n",
"if",
"exists",
"{",
"ops",
"=",
"append",
"(",
"ops",
",",
"newUpdateResourceOps",
"(",
"newRes",
")",
"...",
")",
"\n",
"return",
"append",
"(",
"ops",
",",
"newUpdateCharmStoreResourceOps",
"(",
"csRes",
")",
"...",
")",
"\n",
"}",
"else",
"{",
"ops",
"=",
"append",
"(",
"ops",
",",
"newInsertResourceOps",
"(",
"newRes",
")",
"...",
")",
"\n",
"return",
"append",
"(",
"ops",
",",
"newInsertCharmStoreResourceOps",
"(",
"csRes",
")",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // newResolvePendingResourceOps generates transaction operations that
// will resolve a pending resource doc and make it active.
//
// We trust that the provided resource really is pending
// and that it matches the existing doc with the same ID. | [
"newResolvePendingResourceOps",
"generates",
"transaction",
"operations",
"that",
"will",
"resolve",
"a",
"pending",
"resource",
"doc",
"and",
"make",
"it",
"active",
".",
"We",
"trust",
"that",
"the",
"provided",
"resource",
"really",
"is",
"pending",
"and",
"that",
"it",
"matches",
"the",
"existing",
"doc",
"with",
"the",
"same",
"ID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_mongo.go#L223-L254 |
4,081 | juju/juju | state/resources_mongo.go | newCharmStoreResourceDoc | func newCharmStoreResourceDoc(res charmStoreResource) *resourceDoc {
fullID := charmStoreResourceID(res.id)
return charmStoreResource2Doc(fullID, res)
} | go | func newCharmStoreResourceDoc(res charmStoreResource) *resourceDoc {
fullID := charmStoreResourceID(res.id)
return charmStoreResource2Doc(fullID, res)
} | [
"func",
"newCharmStoreResourceDoc",
"(",
"res",
"charmStoreResource",
")",
"*",
"resourceDoc",
"{",
"fullID",
":=",
"charmStoreResourceID",
"(",
"res",
".",
"id",
")",
"\n",
"return",
"charmStoreResource2Doc",
"(",
"fullID",
",",
"res",
")",
"\n",
"}"
] | // newCharmStoreResourceDoc generates a doc that represents the given resource. | [
"newCharmStoreResourceDoc",
"generates",
"a",
"doc",
"that",
"represents",
"the",
"given",
"resource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_mongo.go#L257-L260 |
4,082 | juju/juju | state/resources_mongo.go | newUnitResourceDoc | func newUnitResourceDoc(unitID string, stored storedResource) *resourceDoc {
fullID := unitResourceID(stored.ID, unitID)
return unitResource2Doc(fullID, unitID, stored)
} | go | func newUnitResourceDoc(unitID string, stored storedResource) *resourceDoc {
fullID := unitResourceID(stored.ID, unitID)
return unitResource2Doc(fullID, unitID, stored)
} | [
"func",
"newUnitResourceDoc",
"(",
"unitID",
"string",
",",
"stored",
"storedResource",
")",
"*",
"resourceDoc",
"{",
"fullID",
":=",
"unitResourceID",
"(",
"stored",
".",
"ID",
",",
"unitID",
")",
"\n",
"return",
"unitResource2Doc",
"(",
"fullID",
",",
"unitID",
",",
"stored",
")",
"\n",
"}"
] | // newUnitResourceDoc generates a doc that represents the given resource. | [
"newUnitResourceDoc",
"generates",
"a",
"doc",
"that",
"represents",
"the",
"given",
"resource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_mongo.go#L263-L266 |
4,083 | juju/juju | state/resources_mongo.go | newResourceDoc | func newResourceDoc(stored storedResource) *resourceDoc {
fullID := applicationResourceID(stored.ID)
if stored.PendingID != "" {
fullID = pendingResourceID(stored.ID, stored.PendingID)
}
return resource2doc(fullID, stored)
} | go | func newResourceDoc(stored storedResource) *resourceDoc {
fullID := applicationResourceID(stored.ID)
if stored.PendingID != "" {
fullID = pendingResourceID(stored.ID, stored.PendingID)
}
return resource2doc(fullID, stored)
} | [
"func",
"newResourceDoc",
"(",
"stored",
"storedResource",
")",
"*",
"resourceDoc",
"{",
"fullID",
":=",
"applicationResourceID",
"(",
"stored",
".",
"ID",
")",
"\n",
"if",
"stored",
".",
"PendingID",
"!=",
"\"",
"\"",
"{",
"fullID",
"=",
"pendingResourceID",
"(",
"stored",
".",
"ID",
",",
"stored",
".",
"PendingID",
")",
"\n",
"}",
"\n",
"return",
"resource2doc",
"(",
"fullID",
",",
"stored",
")",
"\n",
"}"
] | // newResourceDoc generates a doc that represents the given resource. | [
"newResourceDoc",
"generates",
"a",
"doc",
"that",
"represents",
"the",
"given",
"resource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_mongo.go#L269-L275 |
4,084 | juju/juju | state/resources_mongo.go | newStagedResourceDoc | func newStagedResourceDoc(stored storedResource) *resourceDoc {
stagedID := stagedResourceID(stored.ID)
return resource2doc(stagedID, stored)
} | go | func newStagedResourceDoc(stored storedResource) *resourceDoc {
stagedID := stagedResourceID(stored.ID)
return resource2doc(stagedID, stored)
} | [
"func",
"newStagedResourceDoc",
"(",
"stored",
"storedResource",
")",
"*",
"resourceDoc",
"{",
"stagedID",
":=",
"stagedResourceID",
"(",
"stored",
".",
"ID",
")",
"\n",
"return",
"resource2doc",
"(",
"stagedID",
",",
"stored",
")",
"\n",
"}"
] | // newStagedResourceDoc generates a staging doc that represents
// the given resource. | [
"newStagedResourceDoc",
"generates",
"a",
"staging",
"doc",
"that",
"represents",
"the",
"given",
"resource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_mongo.go#L279-L282 |
4,085 | juju/juju | state/resources_mongo.go | resources | func (p ResourcePersistence) resources(applicationID string) ([]resourceDoc, error) {
logger.Tracef("querying db for resources for %q", applicationID)
var docs []resourceDoc
query := bson.D{{"application-id", applicationID}}
if err := p.base.All(resourcesC, query, &docs); err != nil {
return nil, errors.Trace(err)
}
logger.Tracef("found %d resources", len(docs))
return docs, nil
} | go | func (p ResourcePersistence) resources(applicationID string) ([]resourceDoc, error) {
logger.Tracef("querying db for resources for %q", applicationID)
var docs []resourceDoc
query := bson.D{{"application-id", applicationID}}
if err := p.base.All(resourcesC, query, &docs); err != nil {
return nil, errors.Trace(err)
}
logger.Tracef("found %d resources", len(docs))
return docs, nil
} | [
"func",
"(",
"p",
"ResourcePersistence",
")",
"resources",
"(",
"applicationID",
"string",
")",
"(",
"[",
"]",
"resourceDoc",
",",
"error",
")",
"{",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"applicationID",
")",
"\n",
"var",
"docs",
"[",
"]",
"resourceDoc",
"\n",
"query",
":=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"applicationID",
"}",
"}",
"\n",
"if",
"err",
":=",
"p",
".",
"base",
".",
"All",
"(",
"resourcesC",
",",
"query",
",",
"&",
"docs",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"len",
"(",
"docs",
")",
")",
"\n",
"return",
"docs",
",",
"nil",
"\n",
"}"
] | // resources returns the resource docs for the given application. | [
"resources",
"returns",
"the",
"resource",
"docs",
"for",
"the",
"given",
"application",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_mongo.go#L285-L294 |
4,086 | juju/juju | state/resources_mongo.go | getOne | func (p ResourcePersistence) getOne(resID string) (resourceDoc, error) {
logger.Tracef("querying db for resource %q", resID)
id := applicationResourceID(resID)
var doc resourceDoc
if err := p.base.One(resourcesC, id, &doc); err != nil {
return doc, errors.Trace(err)
}
return doc, nil
} | go | func (p ResourcePersistence) getOne(resID string) (resourceDoc, error) {
logger.Tracef("querying db for resource %q", resID)
id := applicationResourceID(resID)
var doc resourceDoc
if err := p.base.One(resourcesC, id, &doc); err != nil {
return doc, errors.Trace(err)
}
return doc, nil
} | [
"func",
"(",
"p",
"ResourcePersistence",
")",
"getOne",
"(",
"resID",
"string",
")",
"(",
"resourceDoc",
",",
"error",
")",
"{",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"resID",
")",
"\n",
"id",
":=",
"applicationResourceID",
"(",
"resID",
")",
"\n",
"var",
"doc",
"resourceDoc",
"\n",
"if",
"err",
":=",
"p",
".",
"base",
".",
"One",
"(",
"resourcesC",
",",
"id",
",",
"&",
"doc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"doc",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"doc",
",",
"nil",
"\n",
"}"
] | // getOne returns the resource that matches the provided model ID. | [
"getOne",
"returns",
"the",
"resource",
"that",
"matches",
"the",
"provided",
"model",
"ID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_mongo.go#L306-L314 |
4,087 | juju/juju | state/resources_mongo.go | getOnePending | func (p ResourcePersistence) getOnePending(resID, pendingID string) (resourceDoc, error) {
logger.Tracef("querying db for resource %q (pending %q)", resID, pendingID)
id := pendingResourceID(resID, pendingID)
var doc resourceDoc
if err := p.base.One(resourcesC, id, &doc); err != nil {
return doc, errors.Trace(err)
}
return doc, nil
} | go | func (p ResourcePersistence) getOnePending(resID, pendingID string) (resourceDoc, error) {
logger.Tracef("querying db for resource %q (pending %q)", resID, pendingID)
id := pendingResourceID(resID, pendingID)
var doc resourceDoc
if err := p.base.One(resourcesC, id, &doc); err != nil {
return doc, errors.Trace(err)
}
return doc, nil
} | [
"func",
"(",
"p",
"ResourcePersistence",
")",
"getOnePending",
"(",
"resID",
",",
"pendingID",
"string",
")",
"(",
"resourceDoc",
",",
"error",
")",
"{",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"resID",
",",
"pendingID",
")",
"\n",
"id",
":=",
"pendingResourceID",
"(",
"resID",
",",
"pendingID",
")",
"\n",
"var",
"doc",
"resourceDoc",
"\n",
"if",
"err",
":=",
"p",
".",
"base",
".",
"One",
"(",
"resourcesC",
",",
"id",
",",
"&",
"doc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"doc",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"doc",
",",
"nil",
"\n",
"}"
] | // getOnePending returns the resource that matches the provided model ID. | [
"getOnePending",
"returns",
"the",
"resource",
"that",
"matches",
"the",
"provided",
"model",
"ID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_mongo.go#L317-L325 |
4,088 | juju/juju | state/resources_mongo.go | resource2doc | func resource2doc(id string, stored storedResource) *resourceDoc {
res := stored.Resource
// TODO(ericsnow) We may need to limit the resolution of timestamps
// in order to avoid some conversion problems from Mongo.
return &resourceDoc{
DocID: id,
ID: res.ID,
PendingID: res.PendingID,
ApplicationID: res.ApplicationID,
Name: res.Name,
Type: res.Type.String(),
Path: res.Path,
Description: res.Description,
Origin: res.Origin.String(),
Revision: res.Revision,
Fingerprint: res.Fingerprint.Bytes(),
Size: res.Size,
Username: res.Username,
Timestamp: res.Timestamp,
StoragePath: stored.storagePath,
}
} | go | func resource2doc(id string, stored storedResource) *resourceDoc {
res := stored.Resource
// TODO(ericsnow) We may need to limit the resolution of timestamps
// in order to avoid some conversion problems from Mongo.
return &resourceDoc{
DocID: id,
ID: res.ID,
PendingID: res.PendingID,
ApplicationID: res.ApplicationID,
Name: res.Name,
Type: res.Type.String(),
Path: res.Path,
Description: res.Description,
Origin: res.Origin.String(),
Revision: res.Revision,
Fingerprint: res.Fingerprint.Bytes(),
Size: res.Size,
Username: res.Username,
Timestamp: res.Timestamp,
StoragePath: stored.storagePath,
}
} | [
"func",
"resource2doc",
"(",
"id",
"string",
",",
"stored",
"storedResource",
")",
"*",
"resourceDoc",
"{",
"res",
":=",
"stored",
".",
"Resource",
"\n",
"// TODO(ericsnow) We may need to limit the resolution of timestamps",
"// in order to avoid some conversion problems from Mongo.",
"return",
"&",
"resourceDoc",
"{",
"DocID",
":",
"id",
",",
"ID",
":",
"res",
".",
"ID",
",",
"PendingID",
":",
"res",
".",
"PendingID",
",",
"ApplicationID",
":",
"res",
".",
"ApplicationID",
",",
"Name",
":",
"res",
".",
"Name",
",",
"Type",
":",
"res",
".",
"Type",
".",
"String",
"(",
")",
",",
"Path",
":",
"res",
".",
"Path",
",",
"Description",
":",
"res",
".",
"Description",
",",
"Origin",
":",
"res",
".",
"Origin",
".",
"String",
"(",
")",
",",
"Revision",
":",
"res",
".",
"Revision",
",",
"Fingerprint",
":",
"res",
".",
"Fingerprint",
".",
"Bytes",
"(",
")",
",",
"Size",
":",
"res",
".",
"Size",
",",
"Username",
":",
"res",
".",
"Username",
",",
"Timestamp",
":",
"res",
".",
"Timestamp",
",",
"StoragePath",
":",
"stored",
".",
"storagePath",
",",
"}",
"\n",
"}"
] | // resource2doc converts the resource into a DB doc. | [
"resource2doc",
"converts",
"the",
"resource",
"into",
"a",
"DB",
"doc",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_mongo.go#L376-L402 |
4,089 | juju/juju | state/resources_mongo.go | doc2resource | func doc2resource(doc resourceDoc) (storedResource, error) {
res, err := doc2basicResource(doc)
if err != nil {
return storedResource{}, errors.Trace(err)
}
stored := storedResource{
Resource: res,
storagePath: doc.StoragePath,
}
return stored, nil
} | go | func doc2resource(doc resourceDoc) (storedResource, error) {
res, err := doc2basicResource(doc)
if err != nil {
return storedResource{}, errors.Trace(err)
}
stored := storedResource{
Resource: res,
storagePath: doc.StoragePath,
}
return stored, nil
} | [
"func",
"doc2resource",
"(",
"doc",
"resourceDoc",
")",
"(",
"storedResource",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"doc2basicResource",
"(",
"doc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"storedResource",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"stored",
":=",
"storedResource",
"{",
"Resource",
":",
"res",
",",
"storagePath",
":",
"doc",
".",
"StoragePath",
",",
"}",
"\n",
"return",
"stored",
",",
"nil",
"\n",
"}"
] | // doc2resource returns the resource info represented by the doc. | [
"doc2resource",
"returns",
"the",
"resource",
"info",
"represented",
"by",
"the",
"doc",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_mongo.go#L405-L416 |
4,090 | juju/juju | state/resources_mongo.go | doc2basicResource | func doc2basicResource(doc resourceDoc) (resource.Resource, error) {
var res resource.Resource
resType, err := charmresource.ParseType(doc.Type)
if err != nil {
return res, errors.Annotate(err, "got invalid data from DB")
}
origin, err := charmresource.ParseOrigin(doc.Origin)
if err != nil {
return res, errors.Annotate(err, "got invalid data from DB")
}
fp, err := resource.DeserializeFingerprint(doc.Fingerprint)
if err != nil {
return res, errors.Annotate(err, "got invalid data from DB")
}
res = resource.Resource{
Resource: charmresource.Resource{
Meta: charmresource.Meta{
Name: doc.Name,
Type: resType,
Path: doc.Path,
Description: doc.Description,
},
Origin: origin,
Revision: doc.Revision,
Fingerprint: fp,
Size: doc.Size,
},
ID: doc.ID,
PendingID: doc.PendingID,
ApplicationID: doc.ApplicationID,
Username: doc.Username,
Timestamp: doc.Timestamp,
}
if err := res.Validate(); err != nil {
return res, errors.Annotate(err, "got invalid data from DB")
}
return res, nil
} | go | func doc2basicResource(doc resourceDoc) (resource.Resource, error) {
var res resource.Resource
resType, err := charmresource.ParseType(doc.Type)
if err != nil {
return res, errors.Annotate(err, "got invalid data from DB")
}
origin, err := charmresource.ParseOrigin(doc.Origin)
if err != nil {
return res, errors.Annotate(err, "got invalid data from DB")
}
fp, err := resource.DeserializeFingerprint(doc.Fingerprint)
if err != nil {
return res, errors.Annotate(err, "got invalid data from DB")
}
res = resource.Resource{
Resource: charmresource.Resource{
Meta: charmresource.Meta{
Name: doc.Name,
Type: resType,
Path: doc.Path,
Description: doc.Description,
},
Origin: origin,
Revision: doc.Revision,
Fingerprint: fp,
Size: doc.Size,
},
ID: doc.ID,
PendingID: doc.PendingID,
ApplicationID: doc.ApplicationID,
Username: doc.Username,
Timestamp: doc.Timestamp,
}
if err := res.Validate(); err != nil {
return res, errors.Annotate(err, "got invalid data from DB")
}
return res, nil
} | [
"func",
"doc2basicResource",
"(",
"doc",
"resourceDoc",
")",
"(",
"resource",
".",
"Resource",
",",
"error",
")",
"{",
"var",
"res",
"resource",
".",
"Resource",
"\n\n",
"resType",
",",
"err",
":=",
"charmresource",
".",
"ParseType",
"(",
"doc",
".",
"Type",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"res",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"origin",
",",
"err",
":=",
"charmresource",
".",
"ParseOrigin",
"(",
"doc",
".",
"Origin",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"res",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"fp",
",",
"err",
":=",
"resource",
".",
"DeserializeFingerprint",
"(",
"doc",
".",
"Fingerprint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"res",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"res",
"=",
"resource",
".",
"Resource",
"{",
"Resource",
":",
"charmresource",
".",
"Resource",
"{",
"Meta",
":",
"charmresource",
".",
"Meta",
"{",
"Name",
":",
"doc",
".",
"Name",
",",
"Type",
":",
"resType",
",",
"Path",
":",
"doc",
".",
"Path",
",",
"Description",
":",
"doc",
".",
"Description",
",",
"}",
",",
"Origin",
":",
"origin",
",",
"Revision",
":",
"doc",
".",
"Revision",
",",
"Fingerprint",
":",
"fp",
",",
"Size",
":",
"doc",
".",
"Size",
",",
"}",
",",
"ID",
":",
"doc",
".",
"ID",
",",
"PendingID",
":",
"doc",
".",
"PendingID",
",",
"ApplicationID",
":",
"doc",
".",
"ApplicationID",
",",
"Username",
":",
"doc",
".",
"Username",
",",
"Timestamp",
":",
"doc",
".",
"Timestamp",
",",
"}",
"\n",
"if",
"err",
":=",
"res",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"res",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"res",
",",
"nil",
"\n",
"}"
] | // doc2basicResource returns the resource info represented by the doc. | [
"doc2basicResource",
"returns",
"the",
"resource",
"info",
"represented",
"by",
"the",
"doc",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_mongo.go#L419-L460 |
4,091 | juju/juju | api/logstream/logstream.go | Close | func (ls *LogStream) Close() error {
ls.mu.Lock()
defer ls.mu.Unlock()
if ls.stream == nil {
return nil
}
if err := ls.stream.Close(); err != nil {
return errors.Trace(err)
}
ls.stream = nil
return nil
} | go | func (ls *LogStream) Close() error {
ls.mu.Lock()
defer ls.mu.Unlock()
if ls.stream == nil {
return nil
}
if err := ls.stream.Close(); err != nil {
return errors.Trace(err)
}
ls.stream = nil
return nil
} | [
"func",
"(",
"ls",
"*",
"LogStream",
")",
"Close",
"(",
")",
"error",
"{",
"ls",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ls",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"ls",
".",
"stream",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"ls",
".",
"stream",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"ls",
".",
"stream",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close closes the stream. | [
"Close",
"closes",
"the",
"stream",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/logstream/logstream.go#L106-L118 |
4,092 | juju/juju | worker/upgradeseries/worker.go | Validate | func (config Config) Validate() error {
if config.Logger == nil {
return errors.NotValidf("nil Logger")
}
if config.Tag == nil {
return errors.NotValidf("nil machine tag")
}
k := config.Tag.Kind()
if k != names.MachineTagKind {
return errors.NotValidf("%q tag kind", k)
}
if config.FacadeFactory == nil {
return errors.NotValidf("nil FacadeFactory")
}
if config.Service == nil {
return errors.NotValidf("nil Service")
}
return nil
} | go | func (config Config) Validate() error {
if config.Logger == nil {
return errors.NotValidf("nil Logger")
}
if config.Tag == nil {
return errors.NotValidf("nil machine tag")
}
k := config.Tag.Kind()
if k != names.MachineTagKind {
return errors.NotValidf("%q tag kind", k)
}
if config.FacadeFactory == nil {
return errors.NotValidf("nil FacadeFactory")
}
if config.Service == nil {
return errors.NotValidf("nil Service")
}
return nil
} | [
"func",
"(",
"config",
"Config",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"config",
".",
"Logger",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"Tag",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"k",
":=",
"config",
".",
"Tag",
".",
"Kind",
"(",
")",
"\n",
"if",
"k",
"!=",
"names",
".",
"MachineTagKind",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
",",
"k",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"FacadeFactory",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"Service",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate validates the upgrade-series worker configuration. | [
"Validate",
"validates",
"the",
"upgrade",
"-",
"series",
"worker",
"configuration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/worker.go#L55-L73 |
4,093 | juju/juju | worker/upgradeseries/worker.go | NewWorker | func NewWorker(config Config) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
w := &upgradeSeriesWorker{
Facade: config.FacadeFactory(config.Tag),
facadeFactory: config.FacadeFactory,
logger: config.Logger,
service: config.Service,
upgraderFactory: config.UpgraderFactory,
machineStatus: model.UpgradeSeriesNotStarted,
leadersPinned: false,
}
if err := catacomb.Invoke(catacomb.Plan{
Site: &w.catacomb,
Work: w.loop,
}); err != nil {
return nil, errors.Trace(err)
}
return w, nil
} | go | func NewWorker(config Config) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
w := &upgradeSeriesWorker{
Facade: config.FacadeFactory(config.Tag),
facadeFactory: config.FacadeFactory,
logger: config.Logger,
service: config.Service,
upgraderFactory: config.UpgraderFactory,
machineStatus: model.UpgradeSeriesNotStarted,
leadersPinned: false,
}
if err := catacomb.Invoke(catacomb.Plan{
Site: &w.catacomb,
Work: w.loop,
}); err != nil {
return nil, errors.Trace(err)
}
return w, nil
} | [
"func",
"NewWorker",
"(",
"config",
"Config",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"if",
"err",
":=",
"config",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"w",
":=",
"&",
"upgradeSeriesWorker",
"{",
"Facade",
":",
"config",
".",
"FacadeFactory",
"(",
"config",
".",
"Tag",
")",
",",
"facadeFactory",
":",
"config",
".",
"FacadeFactory",
",",
"logger",
":",
"config",
".",
"Logger",
",",
"service",
":",
"config",
".",
"Service",
",",
"upgraderFactory",
":",
"config",
".",
"UpgraderFactory",
",",
"machineStatus",
":",
"model",
".",
"UpgradeSeriesNotStarted",
",",
"leadersPinned",
":",
"false",
",",
"}",
"\n\n",
"if",
"err",
":=",
"catacomb",
".",
"Invoke",
"(",
"catacomb",
".",
"Plan",
"{",
"Site",
":",
"&",
"w",
".",
"catacomb",
",",
"Work",
":",
"w",
".",
"loop",
",",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"w",
",",
"nil",
"\n",
"}"
] | // NewWorker creates, starts and returns a new upgrade-series worker based on
// the input configuration. | [
"NewWorker",
"creates",
"starts",
"and",
"returns",
"a",
"new",
"upgrade",
"-",
"series",
"worker",
"based",
"on",
"the",
"input",
"configuration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/worker.go#L105-L128 |
4,094 | juju/juju | worker/upgradeseries/worker.go | handleUpgradeSeriesChange | func (w *upgradeSeriesWorker) handleUpgradeSeriesChange() error {
w.mu.Lock()
defer w.mu.Unlock()
var err error
if w.machineStatus, err = w.MachineStatus(); err != nil {
if errors.IsNotFound(err) {
// No upgrade-series lock. This can happen when:
// - The first watch call is made.
// - The lock is removed after a completed upgrade.
w.logger.Infof("no series upgrade lock present")
w.machineStatus = model.UpgradeSeriesNotStarted
w.preparedUnits = nil
w.completedUnits = nil
return nil
}
return errors.Trace(err)
}
w.logger.Infof("machine series upgrade status is %q", w.machineStatus)
switch w.machineStatus {
case model.UpgradeSeriesPrepareStarted:
err = w.handlePrepareStarted()
case model.UpgradeSeriesCompleteStarted:
err = w.handleCompleteStarted()
case model.UpgradeSeriesCompleted:
err = w.handleCompleted()
}
return errors.Trace(err)
} | go | func (w *upgradeSeriesWorker) handleUpgradeSeriesChange() error {
w.mu.Lock()
defer w.mu.Unlock()
var err error
if w.machineStatus, err = w.MachineStatus(); err != nil {
if errors.IsNotFound(err) {
// No upgrade-series lock. This can happen when:
// - The first watch call is made.
// - The lock is removed after a completed upgrade.
w.logger.Infof("no series upgrade lock present")
w.machineStatus = model.UpgradeSeriesNotStarted
w.preparedUnits = nil
w.completedUnits = nil
return nil
}
return errors.Trace(err)
}
w.logger.Infof("machine series upgrade status is %q", w.machineStatus)
switch w.machineStatus {
case model.UpgradeSeriesPrepareStarted:
err = w.handlePrepareStarted()
case model.UpgradeSeriesCompleteStarted:
err = w.handleCompleteStarted()
case model.UpgradeSeriesCompleted:
err = w.handleCompleted()
}
return errors.Trace(err)
} | [
"func",
"(",
"w",
"*",
"upgradeSeriesWorker",
")",
"handleUpgradeSeriesChange",
"(",
")",
"error",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"err",
"error",
"\n",
"if",
"w",
".",
"machineStatus",
",",
"err",
"=",
"w",
".",
"MachineStatus",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"// No upgrade-series lock. This can happen when:",
"// - The first watch call is made.",
"// - The lock is removed after a completed upgrade.",
"w",
".",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"w",
".",
"machineStatus",
"=",
"model",
".",
"UpgradeSeriesNotStarted",
"\n",
"w",
".",
"preparedUnits",
"=",
"nil",
"\n",
"w",
".",
"completedUnits",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"w",
".",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"w",
".",
"machineStatus",
")",
"\n\n",
"switch",
"w",
".",
"machineStatus",
"{",
"case",
"model",
".",
"UpgradeSeriesPrepareStarted",
":",
"err",
"=",
"w",
".",
"handlePrepareStarted",
"(",
")",
"\n",
"case",
"model",
".",
"UpgradeSeriesCompleteStarted",
":",
"err",
"=",
"w",
".",
"handleCompleteStarted",
"(",
")",
"\n",
"case",
"model",
".",
"UpgradeSeriesCompleted",
":",
"err",
"=",
"w",
".",
"handleCompleted",
"(",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // handleUpgradeSeriesChange retrieves the current upgrade-series status for
// this machine and based on the status, calls methods that will progress
// the workflow accordingly. | [
"handleUpgradeSeriesChange",
"retrieves",
"the",
"current",
"upgrade",
"-",
"series",
"status",
"for",
"this",
"machine",
"and",
"based",
"on",
"the",
"status",
"calls",
"methods",
"that",
"will",
"progress",
"the",
"workflow",
"accordingly",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/worker.go#L154-L183 |
4,095 | juju/juju | worker/upgradeseries/worker.go | handlePrepareStarted | func (w *upgradeSeriesWorker) handlePrepareStarted() error {
var err error
if !w.leadersPinned {
if err = w.pinLeaders(); err != nil {
return errors.Trace(err)
}
}
if w.preparedUnits, err = w.UnitsPrepared(); err != nil {
return errors.Trace(err)
}
unitServices, allConfirmed, err := w.compareUnitAgentServices(w.preparedUnits)
if err != nil {
return errors.Trace(err)
}
if !allConfirmed {
w.logger.Debugf(
"waiting for units to complete series upgrade preparation; known unit agent services: %s",
unitNames(unitServices),
)
return nil
}
return errors.Trace(w.transitionPrepareComplete(unitServices))
} | go | func (w *upgradeSeriesWorker) handlePrepareStarted() error {
var err error
if !w.leadersPinned {
if err = w.pinLeaders(); err != nil {
return errors.Trace(err)
}
}
if w.preparedUnits, err = w.UnitsPrepared(); err != nil {
return errors.Trace(err)
}
unitServices, allConfirmed, err := w.compareUnitAgentServices(w.preparedUnits)
if err != nil {
return errors.Trace(err)
}
if !allConfirmed {
w.logger.Debugf(
"waiting for units to complete series upgrade preparation; known unit agent services: %s",
unitNames(unitServices),
)
return nil
}
return errors.Trace(w.transitionPrepareComplete(unitServices))
} | [
"func",
"(",
"w",
"*",
"upgradeSeriesWorker",
")",
"handlePrepareStarted",
"(",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"if",
"!",
"w",
".",
"leadersPinned",
"{",
"if",
"err",
"=",
"w",
".",
"pinLeaders",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"w",
".",
"preparedUnits",
",",
"err",
"=",
"w",
".",
"UnitsPrepared",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"unitServices",
",",
"allConfirmed",
",",
"err",
":=",
"w",
".",
"compareUnitAgentServices",
"(",
"w",
".",
"preparedUnits",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"!",
"allConfirmed",
"{",
"w",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"unitNames",
"(",
"unitServices",
")",
",",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"errors",
".",
"Trace",
"(",
"w",
".",
"transitionPrepareComplete",
"(",
"unitServices",
")",
")",
"\n",
"}"
] | // handlePrepareStarted handles workflow for the machine with an upgrade-series
// lock status of "UpgradeSeriesPrepareStarted" | [
"handlePrepareStarted",
"handles",
"workflow",
"for",
"the",
"machine",
"with",
"an",
"upgrade",
"-",
"series",
"lock",
"status",
"of",
"UpgradeSeriesPrepareStarted"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/worker.go#L187-L212 |
4,096 | juju/juju | worker/upgradeseries/worker.go | transitionPrepareComplete | func (w *upgradeSeriesWorker) transitionPrepareComplete(unitServices map[string]string) error {
w.logger.Infof("preparing service units for series upgrade")
toSeries, err := w.TargetSeries()
if err != nil {
return errors.Trace(err)
}
upgrader, err := w.upgraderFactory(toSeries)
if err != nil {
return errors.Trace(err)
}
if err := upgrader.PerformUpgrade(); err != nil {
return errors.Trace(err)
}
return errors.Trace(w.SetMachineStatus(model.UpgradeSeriesPrepareCompleted,
"binaries and service files written"))
} | go | func (w *upgradeSeriesWorker) transitionPrepareComplete(unitServices map[string]string) error {
w.logger.Infof("preparing service units for series upgrade")
toSeries, err := w.TargetSeries()
if err != nil {
return errors.Trace(err)
}
upgrader, err := w.upgraderFactory(toSeries)
if err != nil {
return errors.Trace(err)
}
if err := upgrader.PerformUpgrade(); err != nil {
return errors.Trace(err)
}
return errors.Trace(w.SetMachineStatus(model.UpgradeSeriesPrepareCompleted,
"binaries and service files written"))
} | [
"func",
"(",
"w",
"*",
"upgradeSeriesWorker",
")",
"transitionPrepareComplete",
"(",
"unitServices",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"w",
".",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"toSeries",
",",
"err",
":=",
"w",
".",
"TargetSeries",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"upgrader",
",",
"err",
":=",
"w",
".",
"upgraderFactory",
"(",
"toSeries",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"upgrader",
".",
"PerformUpgrade",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"w",
".",
"SetMachineStatus",
"(",
"model",
".",
"UpgradeSeriesPrepareCompleted",
",",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // transitionPrepareComplete rewrites service unit files for unit agents running
// on this machine so that they are compatible with the init system of the
// series upgrade target. | [
"transitionPrepareComplete",
"rewrites",
"service",
"unit",
"files",
"for",
"unit",
"agents",
"running",
"on",
"this",
"machine",
"so",
"that",
"they",
"are",
"compatible",
"with",
"the",
"init",
"system",
"of",
"the",
"series",
"upgrade",
"target",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/worker.go#L217-L232 |
4,097 | juju/juju | worker/upgradeseries/worker.go | transitionUnitsStarted | func (w *upgradeSeriesWorker) transitionUnitsStarted(unitServices map[string]string) error {
w.logger.Infof("ensuring units are up after series upgrade")
for unit, serviceName := range unitServices {
svc, err := w.service.DiscoverService(serviceName)
if err != nil {
return errors.Trace(err)
}
running, err := svc.Running()
if err != nil {
return errors.Trace(err)
}
if running {
continue
}
if err := svc.Start(); err != nil {
return errors.Annotatef(err, "starting %q unit agent after series upgrade", unit)
}
}
return errors.Trace(w.StartUnitCompletion("started unit agents after series upgrade"))
} | go | func (w *upgradeSeriesWorker) transitionUnitsStarted(unitServices map[string]string) error {
w.logger.Infof("ensuring units are up after series upgrade")
for unit, serviceName := range unitServices {
svc, err := w.service.DiscoverService(serviceName)
if err != nil {
return errors.Trace(err)
}
running, err := svc.Running()
if err != nil {
return errors.Trace(err)
}
if running {
continue
}
if err := svc.Start(); err != nil {
return errors.Annotatef(err, "starting %q unit agent after series upgrade", unit)
}
}
return errors.Trace(w.StartUnitCompletion("started unit agents after series upgrade"))
} | [
"func",
"(",
"w",
"*",
"upgradeSeriesWorker",
")",
"transitionUnitsStarted",
"(",
"unitServices",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"w",
".",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n\n",
"for",
"unit",
",",
"serviceName",
":=",
"range",
"unitServices",
"{",
"svc",
",",
"err",
":=",
"w",
".",
"service",
".",
"DiscoverService",
"(",
"serviceName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"running",
",",
"err",
":=",
"svc",
".",
"Running",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"running",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"err",
":=",
"svc",
".",
"Start",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"unit",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"errors",
".",
"Trace",
"(",
"w",
".",
"StartUnitCompletion",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // transitionUnitsStarted iterates over units managed by this machine. Starts
// the unit's agent service, and transitions all unit subordinate statuses. | [
"transitionUnitsStarted",
"iterates",
"over",
"units",
"managed",
"by",
"this",
"machine",
".",
"Starts",
"the",
"unit",
"s",
"agent",
"service",
"and",
"transitions",
"all",
"unit",
"subordinate",
"statuses",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/worker.go#L278-L299 |
4,098 | juju/juju | worker/upgradeseries/worker.go | handleCompleted | func (w *upgradeSeriesWorker) handleCompleted() error {
s, err := hostSeries()
if err != nil {
return errors.Trace(err)
}
if err = w.FinishUpgradeSeries(s); err != nil {
return errors.Trace(err)
}
return errors.Trace(w.unpinLeaders())
} | go | func (w *upgradeSeriesWorker) handleCompleted() error {
s, err := hostSeries()
if err != nil {
return errors.Trace(err)
}
if err = w.FinishUpgradeSeries(s); err != nil {
return errors.Trace(err)
}
return errors.Trace(w.unpinLeaders())
} | [
"func",
"(",
"w",
"*",
"upgradeSeriesWorker",
")",
"handleCompleted",
"(",
")",
"error",
"{",
"s",
",",
"err",
":=",
"hostSeries",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
"=",
"w",
".",
"FinishUpgradeSeries",
"(",
"s",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"w",
".",
"unpinLeaders",
"(",
")",
")",
"\n",
"}"
] | // handleCompleted notifies the server that it has completed the upgrade
// workflow, then unpins leadership for applications running on the machine. | [
"handleCompleted",
"notifies",
"the",
"server",
"that",
"it",
"has",
"completed",
"the",
"upgrade",
"workflow",
"then",
"unpins",
"leadership",
"for",
"applications",
"running",
"on",
"the",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/worker.go#L303-L312 |
4,099 | juju/juju | worker/upgradeseries/worker.go | pinLeaders | func (w *upgradeSeriesWorker) pinLeaders() (err error) {
// if we encounter an error,
// attempt to ensure that no application leaders remain pinned.
defer func() {
if err != nil {
if unpinErr := w.unpinLeaders(); unpinErr != nil {
err = errors.Wrap(err, unpinErr)
}
}
}()
results, err := w.PinMachineApplications()
if err != nil {
// If pin machine applications method return not implemented because it's
// utilising the legacy leases store, then we should display the warning
// in the log and return out. Unpinning leaders should be safe as that
// should be considered a no-op
if params.IsCodeNotImplemented(err) {
w.logger.Infof("failed to pin machine applications, with legacy lease manager leadership pinning is not implemented")
return nil
}
return errors.Trace(err)
}
var lastErr error
for app, err := range results {
if err == nil {
w.logger.Infof("unpin leader for application %q", app)
continue
}
w.logger.Errorf("failed to pin leader for application %q: %s", app, err.Error())
lastErr = err
}
if lastErr == nil {
w.leadersPinned = true
return nil
}
return errors.Trace(lastErr)
} | go | func (w *upgradeSeriesWorker) pinLeaders() (err error) {
// if we encounter an error,
// attempt to ensure that no application leaders remain pinned.
defer func() {
if err != nil {
if unpinErr := w.unpinLeaders(); unpinErr != nil {
err = errors.Wrap(err, unpinErr)
}
}
}()
results, err := w.PinMachineApplications()
if err != nil {
// If pin machine applications method return not implemented because it's
// utilising the legacy leases store, then we should display the warning
// in the log and return out. Unpinning leaders should be safe as that
// should be considered a no-op
if params.IsCodeNotImplemented(err) {
w.logger.Infof("failed to pin machine applications, with legacy lease manager leadership pinning is not implemented")
return nil
}
return errors.Trace(err)
}
var lastErr error
for app, err := range results {
if err == nil {
w.logger.Infof("unpin leader for application %q", app)
continue
}
w.logger.Errorf("failed to pin leader for application %q: %s", app, err.Error())
lastErr = err
}
if lastErr == nil {
w.leadersPinned = true
return nil
}
return errors.Trace(lastErr)
} | [
"func",
"(",
"w",
"*",
"upgradeSeriesWorker",
")",
"pinLeaders",
"(",
")",
"(",
"err",
"error",
")",
"{",
"// if we encounter an error,",
"// attempt to ensure that no application leaders remain pinned.",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"if",
"unpinErr",
":=",
"w",
".",
"unpinLeaders",
"(",
")",
";",
"unpinErr",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"unpinErr",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"results",
",",
"err",
":=",
"w",
".",
"PinMachineApplications",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// If pin machine applications method return not implemented because it's",
"// utilising the legacy leases store, then we should display the warning",
"// in the log and return out. Unpinning leaders should be safe as that",
"// should be considered a no-op",
"if",
"params",
".",
"IsCodeNotImplemented",
"(",
"err",
")",
"{",
"w",
".",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"lastErr",
"error",
"\n",
"for",
"app",
",",
"err",
":=",
"range",
"results",
"{",
"if",
"err",
"==",
"nil",
"{",
"w",
".",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"app",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"w",
".",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"app",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"lastErr",
"=",
"err",
"\n",
"}",
"\n\n",
"if",
"lastErr",
"==",
"nil",
"{",
"w",
".",
"leadersPinned",
"=",
"true",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"lastErr",
")",
"\n",
"}"
] | // pinLeaders pins leadership for applications
// represented by units running on this machine. | [
"pinLeaders",
"pins",
"leadership",
"for",
"applications",
"represented",
"by",
"units",
"running",
"on",
"this",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/worker.go#L343-L382 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.