id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
154,800 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | NewFacadeV4 | func NewFacadeV4(ctx facade.Context) (*MachineManagerAPIV4, error) {
machineManagerAPIV5, err := NewFacadeV5(ctx)
if err != nil {
return nil, errors.Trace(err)
}
return &MachineManagerAPIV4{machineManagerAPIV5}, nil
} | go | func NewFacadeV4(ctx facade.Context) (*MachineManagerAPIV4, error) {
machineManagerAPIV5, err := NewFacadeV5(ctx)
if err != nil {
return nil, errors.Trace(err)
}
return &MachineManagerAPIV4{machineManagerAPIV5}, nil
} | [
"func",
"NewFacadeV4",
"(",
"ctx",
"facade",
".",
"Context",
")",
"(",
"*",
"MachineManagerAPIV4",
",",
"error",
")",
"{",
"machineManagerAPIV5",
",",
"err",
":=",
"NewFacadeV5",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"MachineManagerAPIV4",
"{",
"machineManagerAPIV5",
"}",
",",
"nil",
"\n",
"}"
] | // NewFacadeV4 creates a new server-side MachineManager API facade. | [
"NewFacadeV4",
"creates",
"a",
"new",
"server",
"-",
"side",
"MachineManager",
"API",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L78-L84 |
154,801 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | NewFacadeV5 | func NewFacadeV5(ctx facade.Context) (*MachineManagerAPIV5, error) {
machineManagerAPIv6, err := NewFacadeV6(ctx)
if err != nil {
return nil, errors.Trace(err)
}
return &MachineManagerAPIV5{machineManagerAPIv6}, nil
} | go | func NewFacadeV5(ctx facade.Context) (*MachineManagerAPIV5, error) {
machineManagerAPIv6, err := NewFacadeV6(ctx)
if err != nil {
return nil, errors.Trace(err)
}
return &MachineManagerAPIV5{machineManagerAPIv6}, nil
} | [
"func",
"NewFacadeV5",
"(",
"ctx",
"facade",
".",
"Context",
")",
"(",
"*",
"MachineManagerAPIV5",
",",
"error",
")",
"{",
"machineManagerAPIv6",
",",
"err",
":=",
"NewFacadeV6",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"MachineManagerAPIV5",
"{",
"machineManagerAPIv6",
"}",
",",
"nil",
"\n",
"}"
] | // NewFacadeV5 creates a new server-side MachineManager API facade. | [
"NewFacadeV5",
"creates",
"a",
"new",
"server",
"-",
"side",
"MachineManager",
"API",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L87-L93 |
154,802 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | NewFacadeV6 | func NewFacadeV6(ctx facade.Context) (*MachineManagerAPIV6, error) {
machineManagerAPI, err := NewFacade(ctx)
if err != nil {
return nil, errors.Trace(err)
}
return &MachineManagerAPIV6{machineManagerAPI}, nil
} | go | func NewFacadeV6(ctx facade.Context) (*MachineManagerAPIV6, error) {
machineManagerAPI, err := NewFacade(ctx)
if err != nil {
return nil, errors.Trace(err)
}
return &MachineManagerAPIV6{machineManagerAPI}, nil
} | [
"func",
"NewFacadeV6",
"(",
"ctx",
"facade",
".",
"Context",
")",
"(",
"*",
"MachineManagerAPIV6",
",",
"error",
")",
"{",
"machineManagerAPI",
",",
"err",
":=",
"NewFacade",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"MachineManagerAPIV6",
"{",
"machineManagerAPI",
"}",
",",
"nil",
"\n",
"}"
] | // NewFacadeV6 creates a new server-side MachineManager API facade. | [
"NewFacadeV6",
"creates",
"a",
"new",
"server",
"-",
"side",
"MachineManager",
"API",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L96-L102 |
154,803 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | NewMachineManagerAPI | func NewMachineManagerAPI(
backend Backend,
storageAccess storageInterface,
pool Pool,
auth facade.Authorizer,
modelTag names.ModelTag,
callCtx context.ProviderCallContext,
resources facade.Resources,
) (*MachineManagerAPI, error) {
if !auth.AuthClient() {
return nil, common.ErrPerm
}
return &MachineManagerAPI{
st: backend,
storageAccess: storageAccess,
pool: pool,
authorizer: auth,
check: common.NewBlockChecker(backend),
modelTag: modelTag,
callContext: callCtx,
resources: resources,
}, nil
} | go | func NewMachineManagerAPI(
backend Backend,
storageAccess storageInterface,
pool Pool,
auth facade.Authorizer,
modelTag names.ModelTag,
callCtx context.ProviderCallContext,
resources facade.Resources,
) (*MachineManagerAPI, error) {
if !auth.AuthClient() {
return nil, common.ErrPerm
}
return &MachineManagerAPI{
st: backend,
storageAccess: storageAccess,
pool: pool,
authorizer: auth,
check: common.NewBlockChecker(backend),
modelTag: modelTag,
callContext: callCtx,
resources: resources,
}, nil
} | [
"func",
"NewMachineManagerAPI",
"(",
"backend",
"Backend",
",",
"storageAccess",
"storageInterface",
",",
"pool",
"Pool",
",",
"auth",
"facade",
".",
"Authorizer",
",",
"modelTag",
"names",
".",
"ModelTag",
",",
"callCtx",
"context",
".",
"ProviderCallContext",
",",
"resources",
"facade",
".",
"Resources",
",",
")",
"(",
"*",
"MachineManagerAPI",
",",
"error",
")",
"{",
"if",
"!",
"auth",
".",
"AuthClient",
"(",
")",
"{",
"return",
"nil",
",",
"common",
".",
"ErrPerm",
"\n",
"}",
"\n",
"return",
"&",
"MachineManagerAPI",
"{",
"st",
":",
"backend",
",",
"storageAccess",
":",
"storageAccess",
",",
"pool",
":",
"pool",
",",
"authorizer",
":",
"auth",
",",
"check",
":",
"common",
".",
"NewBlockChecker",
"(",
"backend",
")",
",",
"modelTag",
":",
"modelTag",
",",
"callContext",
":",
"callCtx",
",",
"resources",
":",
"resources",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewMachineManagerAPI creates a new server-side MachineManager API facade. | [
"NewMachineManagerAPI",
"creates",
"a",
"new",
"server",
"-",
"side",
"MachineManager",
"API",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L105-L127 |
154,804 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | DestroyMachine | func (mm *MachineManagerAPI) DestroyMachine(args params.Entities) (params.DestroyMachineResults, error) {
return mm.destroyMachine(args, false, false, time.Duration(0))
} | go | func (mm *MachineManagerAPI) DestroyMachine(args params.Entities) (params.DestroyMachineResults, error) {
return mm.destroyMachine(args, false, false, time.Duration(0))
} | [
"func",
"(",
"mm",
"*",
"MachineManagerAPI",
")",
"DestroyMachine",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"DestroyMachineResults",
",",
"error",
")",
"{",
"return",
"mm",
".",
"destroyMachine",
"(",
"args",
",",
"false",
",",
"false",
",",
"time",
".",
"Duration",
"(",
"0",
")",
")",
"\n",
"}"
] | // DestroyMachine removes a set of machines from the model. | [
"DestroyMachine",
"removes",
"a",
"set",
"of",
"machines",
"from",
"the",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L265-L267 |
154,805 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | DestroyMachineWithParams | func (mm *MachineManagerAPIV5) DestroyMachineWithParams(args params.DestroyMachinesParams) (params.DestroyMachineResults, error) {
entities := params.Entities{Entities: make([]params.Entity, len(args.MachineTags))}
for i, tag := range args.MachineTags {
entities.Entities[i].Tag = tag
}
return mm.destroyMachine(entities, args.Force, args.Keep, time.Duration(0))
} | go | func (mm *MachineManagerAPIV5) DestroyMachineWithParams(args params.DestroyMachinesParams) (params.DestroyMachineResults, error) {
entities := params.Entities{Entities: make([]params.Entity, len(args.MachineTags))}
for i, tag := range args.MachineTags {
entities.Entities[i].Tag = tag
}
return mm.destroyMachine(entities, args.Force, args.Keep, time.Duration(0))
} | [
"func",
"(",
"mm",
"*",
"MachineManagerAPIV5",
")",
"DestroyMachineWithParams",
"(",
"args",
"params",
".",
"DestroyMachinesParams",
")",
"(",
"params",
".",
"DestroyMachineResults",
",",
"error",
")",
"{",
"entities",
":=",
"params",
".",
"Entities",
"{",
"Entities",
":",
"make",
"(",
"[",
"]",
"params",
".",
"Entity",
",",
"len",
"(",
"args",
".",
"MachineTags",
")",
")",
"}",
"\n",
"for",
"i",
",",
"tag",
":=",
"range",
"args",
".",
"MachineTags",
"{",
"entities",
".",
"Entities",
"[",
"i",
"]",
".",
"Tag",
"=",
"tag",
"\n",
"}",
"\n",
"return",
"mm",
".",
"destroyMachine",
"(",
"entities",
",",
"args",
".",
"Force",
",",
"args",
".",
"Keep",
",",
"time",
".",
"Duration",
"(",
"0",
")",
")",
"\n",
"}"
] | // DestroyMachineWithParams removes a set of machines from the model.
// v5 and prior versions did not support MaxWait. | [
"DestroyMachineWithParams",
"removes",
"a",
"set",
"of",
"machines",
"from",
"the",
"model",
".",
"v5",
"and",
"prior",
"versions",
"did",
"not",
"support",
"MaxWait",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L278-L284 |
154,806 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | DestroyMachineWithParams | func (mm *MachineManagerAPI) DestroyMachineWithParams(args params.DestroyMachinesParams) (params.DestroyMachineResults, error) {
entities := params.Entities{Entities: make([]params.Entity, len(args.MachineTags))}
for i, tag := range args.MachineTags {
entities.Entities[i].Tag = tag
}
return mm.destroyMachine(entities, args.Force, args.Keep, common.MaxWait(args.MaxWait))
} | go | func (mm *MachineManagerAPI) DestroyMachineWithParams(args params.DestroyMachinesParams) (params.DestroyMachineResults, error) {
entities := params.Entities{Entities: make([]params.Entity, len(args.MachineTags))}
for i, tag := range args.MachineTags {
entities.Entities[i].Tag = tag
}
return mm.destroyMachine(entities, args.Force, args.Keep, common.MaxWait(args.MaxWait))
} | [
"func",
"(",
"mm",
"*",
"MachineManagerAPI",
")",
"DestroyMachineWithParams",
"(",
"args",
"params",
".",
"DestroyMachinesParams",
")",
"(",
"params",
".",
"DestroyMachineResults",
",",
"error",
")",
"{",
"entities",
":=",
"params",
".",
"Entities",
"{",
"Entities",
":",
"make",
"(",
"[",
"]",
"params",
".",
"Entity",
",",
"len",
"(",
"args",
".",
"MachineTags",
")",
")",
"}",
"\n",
"for",
"i",
",",
"tag",
":=",
"range",
"args",
".",
"MachineTags",
"{",
"entities",
".",
"Entities",
"[",
"i",
"]",
".",
"Tag",
"=",
"tag",
"\n",
"}",
"\n",
"return",
"mm",
".",
"destroyMachine",
"(",
"entities",
",",
"args",
".",
"Force",
",",
"args",
".",
"Keep",
",",
"common",
".",
"MaxWait",
"(",
"args",
".",
"MaxWait",
")",
")",
"\n",
"}"
] | // DestroyMachineWithParams removes a set of machines from the model. | [
"DestroyMachineWithParams",
"removes",
"a",
"set",
"of",
"machines",
"from",
"the",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L287-L293 |
154,807 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | UpgradeSeriesValidate | func (mm *MachineManagerAPI) UpgradeSeriesValidate(
args params.UpdateSeriesArgs,
) (params.UpgradeSeriesUnitsResults, error) {
err := mm.checkCanRead()
if err != nil {
return params.UpgradeSeriesUnitsResults{}, err
}
results := make([]params.UpgradeSeriesUnitsResult, len(args.Args))
for i, arg := range args.Args {
tag := arg.Entity.Tag
machine, err := mm.machineFromTag(tag)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
if machine.IsManager() {
results[i].Error = common.ServerError(
errors.Errorf("%s is a controller and cannot be targeted for series upgrade", tag))
continue
}
err = mm.validateSeries(arg.Series, machine.Series(), tag)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
unitNames, err := mm.verifiedUnits(machine, arg.Series, arg.Force)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
results[i].UnitNames = unitNames
}
return params.UpgradeSeriesUnitsResults{Results: results}, nil
} | go | func (mm *MachineManagerAPI) UpgradeSeriesValidate(
args params.UpdateSeriesArgs,
) (params.UpgradeSeriesUnitsResults, error) {
err := mm.checkCanRead()
if err != nil {
return params.UpgradeSeriesUnitsResults{}, err
}
results := make([]params.UpgradeSeriesUnitsResult, len(args.Args))
for i, arg := range args.Args {
tag := arg.Entity.Tag
machine, err := mm.machineFromTag(tag)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
if machine.IsManager() {
results[i].Error = common.ServerError(
errors.Errorf("%s is a controller and cannot be targeted for series upgrade", tag))
continue
}
err = mm.validateSeries(arg.Series, machine.Series(), tag)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
unitNames, err := mm.verifiedUnits(machine, arg.Series, arg.Force)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
results[i].UnitNames = unitNames
}
return params.UpgradeSeriesUnitsResults{Results: results}, nil
} | [
"func",
"(",
"mm",
"*",
"MachineManagerAPI",
")",
"UpgradeSeriesValidate",
"(",
"args",
"params",
".",
"UpdateSeriesArgs",
",",
")",
"(",
"params",
".",
"UpgradeSeriesUnitsResults",
",",
"error",
")",
"{",
"err",
":=",
"mm",
".",
"checkCanRead",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"UpgradeSeriesUnitsResults",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"results",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"UpgradeSeriesUnitsResult",
",",
"len",
"(",
"args",
".",
"Args",
")",
")",
"\n",
"for",
"i",
",",
"arg",
":=",
"range",
"args",
".",
"Args",
"{",
"tag",
":=",
"arg",
".",
"Entity",
".",
"Tag",
"\n",
"machine",
",",
"err",
":=",
"mm",
".",
"machineFromTag",
"(",
"tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"if",
"machine",
".",
"IsManager",
"(",
")",
"{",
"results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tag",
")",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"err",
"=",
"mm",
".",
"validateSeries",
"(",
"arg",
".",
"Series",
",",
"machine",
".",
"Series",
"(",
")",
",",
"tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"unitNames",
",",
"err",
":=",
"mm",
".",
"verifiedUnits",
"(",
"machine",
",",
"arg",
".",
"Series",
",",
"arg",
".",
"Force",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"results",
"[",
"i",
"]",
".",
"UnitNames",
"=",
"unitNames",
"\n",
"}",
"\n\n",
"return",
"params",
".",
"UpgradeSeriesUnitsResults",
"{",
"Results",
":",
"results",
"}",
",",
"nil",
"\n",
"}"
] | // UpgradeSeriesValidate validates that the incoming arguments correspond to a
// valid series upgrade for the target machine.
// If they do, a list of the machine's current units is returned for use in
// soliciting user confirmation of the command. | [
"UpgradeSeriesValidate",
"validates",
"that",
"the",
"incoming",
"arguments",
"correspond",
"to",
"a",
"valid",
"series",
"upgrade",
"for",
"the",
"target",
"machine",
".",
"If",
"they",
"do",
"a",
"list",
"of",
"the",
"machine",
"s",
"current",
"units",
"is",
"returned",
"for",
"use",
"in",
"soliciting",
"user",
"confirmation",
"of",
"the",
"command",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L403-L441 |
154,808 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | UpgradeSeriesPrepare | func (mm *MachineManagerAPI) UpgradeSeriesPrepare(args params.UpdateSeriesArg) (params.ErrorResult, error) {
if err := mm.checkCanWrite(); err != nil {
return params.ErrorResult{}, err
}
if err := mm.check.ChangeAllowed(); err != nil {
return params.ErrorResult{}, err
}
err := mm.upgradeSeriesPrepare(args)
if err != nil {
return params.ErrorResult{Error: common.ServerError(err)}, nil
}
return params.ErrorResult{}, nil
} | go | func (mm *MachineManagerAPI) UpgradeSeriesPrepare(args params.UpdateSeriesArg) (params.ErrorResult, error) {
if err := mm.checkCanWrite(); err != nil {
return params.ErrorResult{}, err
}
if err := mm.check.ChangeAllowed(); err != nil {
return params.ErrorResult{}, err
}
err := mm.upgradeSeriesPrepare(args)
if err != nil {
return params.ErrorResult{Error: common.ServerError(err)}, nil
}
return params.ErrorResult{}, nil
} | [
"func",
"(",
"mm",
"*",
"MachineManagerAPI",
")",
"UpgradeSeriesPrepare",
"(",
"args",
"params",
".",
"UpdateSeriesArg",
")",
"(",
"params",
".",
"ErrorResult",
",",
"error",
")",
"{",
"if",
"err",
":=",
"mm",
".",
"checkCanWrite",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ErrorResult",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"mm",
".",
"check",
".",
"ChangeAllowed",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ErrorResult",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"err",
":=",
"mm",
".",
"upgradeSeriesPrepare",
"(",
"args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ErrorResult",
"{",
"Error",
":",
"common",
".",
"ServerError",
"(",
"err",
")",
"}",
",",
"nil",
"\n",
"}",
"\n",
"return",
"params",
".",
"ErrorResult",
"{",
"}",
",",
"nil",
"\n",
"}"
] | // UpgradeSeriesPrepare prepares a machine for a OS series upgrade. | [
"UpgradeSeriesPrepare",
"prepares",
"a",
"machine",
"for",
"a",
"OS",
"series",
"upgrade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L444-L456 |
154,809 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | UpgradeSeriesComplete | func (mm *MachineManagerAPI) UpgradeSeriesComplete(args params.UpdateSeriesArg) (params.ErrorResult, error) {
if err := mm.checkCanWrite(); err != nil {
return params.ErrorResult{}, err
}
if err := mm.check.ChangeAllowed(); err != nil {
return params.ErrorResult{}, err
}
if err := mm.check.ChangeAllowed(); err != nil {
return params.ErrorResult{}, err
}
err := mm.completeUpgradeSeries(args)
if err != nil {
return params.ErrorResult{Error: common.ServerError(err)}, nil
}
return params.ErrorResult{}, nil
} | go | func (mm *MachineManagerAPI) UpgradeSeriesComplete(args params.UpdateSeriesArg) (params.ErrorResult, error) {
if err := mm.checkCanWrite(); err != nil {
return params.ErrorResult{}, err
}
if err := mm.check.ChangeAllowed(); err != nil {
return params.ErrorResult{}, err
}
if err := mm.check.ChangeAllowed(); err != nil {
return params.ErrorResult{}, err
}
err := mm.completeUpgradeSeries(args)
if err != nil {
return params.ErrorResult{Error: common.ServerError(err)}, nil
}
return params.ErrorResult{}, nil
} | [
"func",
"(",
"mm",
"*",
"MachineManagerAPI",
")",
"UpgradeSeriesComplete",
"(",
"args",
"params",
".",
"UpdateSeriesArg",
")",
"(",
"params",
".",
"ErrorResult",
",",
"error",
")",
"{",
"if",
"err",
":=",
"mm",
".",
"checkCanWrite",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ErrorResult",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"mm",
".",
"check",
".",
"ChangeAllowed",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ErrorResult",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"mm",
".",
"check",
".",
"ChangeAllowed",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ErrorResult",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"err",
":=",
"mm",
".",
"completeUpgradeSeries",
"(",
"args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ErrorResult",
"{",
"Error",
":",
"common",
".",
"ServerError",
"(",
"err",
")",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"params",
".",
"ErrorResult",
"{",
"}",
",",
"nil",
"\n",
"}"
] | // UpgradeSeriesComplete marks a machine as having completed a managed series upgrade. | [
"UpgradeSeriesComplete",
"marks",
"a",
"machine",
"as",
"having",
"completed",
"a",
"managed",
"series",
"upgrade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L495-L511 |
154,810 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | WatchUpgradeSeriesNotifications | func (mm *MachineManagerAPI) WatchUpgradeSeriesNotifications(args params.Entities) (params.NotifyWatchResults, error) {
err := mm.checkCanRead()
if err != nil {
return params.NotifyWatchResults{}, err
}
result := params.NotifyWatchResults{
Results: make([]params.NotifyWatchResult, len(args.Entities)),
}
for i, entity := range args.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
watcherId := ""
machine, err := mm.st.Machine(tag.Id())
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
w, err := machine.WatchUpgradeSeriesNotifications()
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
watcherId = mm.resources.Register(w)
result.Results[i].NotifyWatcherId = watcherId
}
return result, nil
} | go | func (mm *MachineManagerAPI) WatchUpgradeSeriesNotifications(args params.Entities) (params.NotifyWatchResults, error) {
err := mm.checkCanRead()
if err != nil {
return params.NotifyWatchResults{}, err
}
result := params.NotifyWatchResults{
Results: make([]params.NotifyWatchResult, len(args.Entities)),
}
for i, entity := range args.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
watcherId := ""
machine, err := mm.st.Machine(tag.Id())
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
w, err := machine.WatchUpgradeSeriesNotifications()
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
watcherId = mm.resources.Register(w)
result.Results[i].NotifyWatcherId = watcherId
}
return result, nil
} | [
"func",
"(",
"mm",
"*",
"MachineManagerAPI",
")",
"WatchUpgradeSeriesNotifications",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"NotifyWatchResults",
",",
"error",
")",
"{",
"err",
":=",
"mm",
".",
"checkCanRead",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"NotifyWatchResults",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"result",
":=",
"params",
".",
"NotifyWatchResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"NotifyWatchResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"entity",
":=",
"range",
"args",
".",
"Entities",
"{",
"tag",
",",
"err",
":=",
"names",
".",
"ParseTag",
"(",
"entity",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"common",
".",
"ErrPerm",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"watcherId",
":=",
"\"",
"\"",
"\n",
"machine",
",",
"err",
":=",
"mm",
".",
"st",
".",
"Machine",
"(",
"tag",
".",
"Id",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"w",
",",
"err",
":=",
"machine",
".",
"WatchUpgradeSeriesNotifications",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"watcherId",
"=",
"mm",
".",
"resources",
".",
"Register",
"(",
"w",
")",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"NotifyWatcherId",
"=",
"watcherId",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // WatchUpgradeSeriesNotifications returns a watcher that fires on upgrade series events. | [
"WatchUpgradeSeriesNotifications",
"returns",
"a",
"watcher",
"that",
"fires",
"on",
"upgrade",
"series",
"events",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L530-L559 |
154,811 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | GetUpgradeSeriesMessages | func (mm *MachineManagerAPI) GetUpgradeSeriesMessages(args params.UpgradeSeriesNotificationParams) (params.StringsResults, error) {
if err := mm.checkCanRead(); err != nil {
return params.StringsResults{}, err
}
results := params.StringsResults{
Results: make([]params.StringsResult, len(args.Params)),
}
for i, param := range args.Params {
machine, err := mm.machineFromTag(param.Entity.Tag)
if err != nil {
err = errors.Trace(err)
results.Results[i].Error = common.ServerError(err)
continue
}
messages, finished, err := machine.GetUpgradeSeriesMessages()
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
if finished {
// If there are no more messages we stop the watcher resource.
err = mm.resources.Stop(param.WatcherId)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
}
results.Results[i].Result = messages
}
return results, nil
} | go | func (mm *MachineManagerAPI) GetUpgradeSeriesMessages(args params.UpgradeSeriesNotificationParams) (params.StringsResults, error) {
if err := mm.checkCanRead(); err != nil {
return params.StringsResults{}, err
}
results := params.StringsResults{
Results: make([]params.StringsResult, len(args.Params)),
}
for i, param := range args.Params {
machine, err := mm.machineFromTag(param.Entity.Tag)
if err != nil {
err = errors.Trace(err)
results.Results[i].Error = common.ServerError(err)
continue
}
messages, finished, err := machine.GetUpgradeSeriesMessages()
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
if finished {
// If there are no more messages we stop the watcher resource.
err = mm.resources.Stop(param.WatcherId)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
}
results.Results[i].Result = messages
}
return results, nil
} | [
"func",
"(",
"mm",
"*",
"MachineManagerAPI",
")",
"GetUpgradeSeriesMessages",
"(",
"args",
"params",
".",
"UpgradeSeriesNotificationParams",
")",
"(",
"params",
".",
"StringsResults",
",",
"error",
")",
"{",
"if",
"err",
":=",
"mm",
".",
"checkCanRead",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"StringsResults",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"results",
":=",
"params",
".",
"StringsResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"StringsResult",
",",
"len",
"(",
"args",
".",
"Params",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"param",
":=",
"range",
"args",
".",
"Params",
"{",
"machine",
",",
"err",
":=",
"mm",
".",
"machineFromTag",
"(",
"param",
".",
"Entity",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"messages",
",",
"finished",
",",
"err",
":=",
"machine",
".",
"GetUpgradeSeriesMessages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"finished",
"{",
"// If there are no more messages we stop the watcher resource.",
"err",
"=",
"mm",
".",
"resources",
".",
"Stop",
"(",
"param",
".",
"WatcherId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Result",
"=",
"messages",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // GetUpgradeSeriesMessages returns all new messages associated with upgrade
// series events. Messages that have already been retrieved once are not
// returned by this method. | [
"GetUpgradeSeriesMessages",
"returns",
"all",
"new",
"messages",
"associated",
"with",
"upgrade",
"series",
"events",
".",
"Messages",
"that",
"have",
"already",
"been",
"retrieved",
"once",
"are",
"not",
"returned",
"by",
"this",
"method",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L564-L594 |
154,812 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | verifiedUnits | func (mm *MachineManagerAPI) verifiedUnits(machine Machine, series string, force bool) ([]string, error) {
principals := machine.Principals()
units, err := machine.VerifyUnitsSeries(principals, series, force)
if err != nil {
return nil, errors.Trace(err)
}
unitNames := make([]string, len(units))
for i, u := range units {
agentStatus, err := u.AgentStatus()
if err != nil {
return nil, errors.Trace(err)
}
if agentStatus.Status != status.Idle {
return nil, errors.Errorf("unit %s is not ready to start a series upgrade; its agent status is: %q %s",
u.Name(), agentStatus.Status, agentStatus.Message)
}
unitStatus, err := u.Status()
if err != nil {
return nil, errors.Trace(err)
}
if unitStatus.Status == status.Error {
return nil, errors.Errorf("unit %s is not ready to start a series upgrade; its status is: \"error\" %s",
u.Name(), unitStatus.Message)
}
unitNames[i] = u.UnitTag().Id()
}
return unitNames, nil
} | go | func (mm *MachineManagerAPI) verifiedUnits(machine Machine, series string, force bool) ([]string, error) {
principals := machine.Principals()
units, err := machine.VerifyUnitsSeries(principals, series, force)
if err != nil {
return nil, errors.Trace(err)
}
unitNames := make([]string, len(units))
for i, u := range units {
agentStatus, err := u.AgentStatus()
if err != nil {
return nil, errors.Trace(err)
}
if agentStatus.Status != status.Idle {
return nil, errors.Errorf("unit %s is not ready to start a series upgrade; its agent status is: %q %s",
u.Name(), agentStatus.Status, agentStatus.Message)
}
unitStatus, err := u.Status()
if err != nil {
return nil, errors.Trace(err)
}
if unitStatus.Status == status.Error {
return nil, errors.Errorf("unit %s is not ready to start a series upgrade; its status is: \"error\" %s",
u.Name(), unitStatus.Message)
}
unitNames[i] = u.UnitTag().Id()
}
return unitNames, nil
} | [
"func",
"(",
"mm",
"*",
"MachineManagerAPI",
")",
"verifiedUnits",
"(",
"machine",
"Machine",
",",
"series",
"string",
",",
"force",
"bool",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"principals",
":=",
"machine",
".",
"Principals",
"(",
")",
"\n",
"units",
",",
"err",
":=",
"machine",
".",
"VerifyUnitsSeries",
"(",
"principals",
",",
"series",
",",
"force",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"unitNames",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"units",
")",
")",
"\n",
"for",
"i",
",",
"u",
":=",
"range",
"units",
"{",
"agentStatus",
",",
"err",
":=",
"u",
".",
"AgentStatus",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"agentStatus",
".",
"Status",
"!=",
"status",
".",
"Idle",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"u",
".",
"Name",
"(",
")",
",",
"agentStatus",
".",
"Status",
",",
"agentStatus",
".",
"Message",
")",
"\n",
"}",
"\n",
"unitStatus",
",",
"err",
":=",
"u",
".",
"Status",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"unitStatus",
".",
"Status",
"==",
"status",
".",
"Error",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"u",
".",
"Name",
"(",
")",
",",
"unitStatus",
".",
"Message",
")",
"\n",
"}",
"\n\n",
"unitNames",
"[",
"i",
"]",
"=",
"u",
".",
"UnitTag",
"(",
")",
".",
"Id",
"(",
")",
"\n",
"}",
"\n",
"return",
"unitNames",
",",
"nil",
"\n",
"}"
] | // verifiedUnits verifies that the machine units and their tree of subordinates
// all support the input series. If not, an error is returned.
// If they do, the agent statuses are checked to ensure that they are all in
// the idle state i.e. not installing, running hooks, or needing intervention.
// the final check is that the unit itself is not in an error state. | [
"verifiedUnits",
"verifies",
"that",
"the",
"machine",
"units",
"and",
"their",
"tree",
"of",
"subordinates",
"all",
"support",
"the",
"input",
"series",
".",
"If",
"not",
"an",
"error",
"is",
"returned",
".",
"If",
"they",
"do",
"the",
"agent",
"statuses",
"are",
"checked",
"to",
"ensure",
"that",
"they",
"are",
"all",
"in",
"the",
"idle",
"state",
"i",
".",
"e",
".",
"not",
"installing",
"running",
"hooks",
"or",
"needing",
"intervention",
".",
"the",
"final",
"check",
"is",
"that",
"the",
"unit",
"itself",
"is",
"not",
"in",
"an",
"error",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L613-L642 |
154,813 | juju/juju | apiserver/facades/client/machinemanager/machinemanager.go | isSeriesLessThan | func isSeriesLessThan(series1, series2 string) (bool, error) {
version1, err := series.SeriesVersion(series1)
if err != nil {
return false, err
}
version2, err := series.SeriesVersion(series2)
if err != nil {
return false, err
}
return version2 > version1, nil
} | go | func isSeriesLessThan(series1, series2 string) (bool, error) {
version1, err := series.SeriesVersion(series1)
if err != nil {
return false, err
}
version2, err := series.SeriesVersion(series2)
if err != nil {
return false, err
}
return version2 > version1, nil
} | [
"func",
"isSeriesLessThan",
"(",
"series1",
",",
"series2",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"version1",
",",
"err",
":=",
"series",
".",
"SeriesVersion",
"(",
"series1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"version2",
",",
"err",
":=",
"series",
".",
"SeriesVersion",
"(",
"series2",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"version2",
">",
"version1",
",",
"nil",
"\n",
"}"
] | // isSeriesLessThan returns a bool indicating whether the first argument's
// version is lexicographically less than the second argument's, thus indicating
// that the series represents an older version of the operating system. The
// output is only valid for Ubuntu series. | [
"isSeriesLessThan",
"returns",
"a",
"bool",
"indicating",
"whether",
"the",
"first",
"argument",
"s",
"version",
"is",
"lexicographically",
"less",
"than",
"the",
"second",
"argument",
"s",
"thus",
"indicating",
"that",
"the",
"series",
"represents",
"an",
"older",
"version",
"of",
"the",
"operating",
"system",
".",
"The",
"output",
"is",
"only",
"valid",
"for",
"Ubuntu",
"series",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L648-L658 |
154,814 | juju/juju | worker/uniter/runner/debug/client.go | ClientScript | func ClientScript(c *HooksContext, match []string) string {
// If any argument is "*", then the client is interested in all.
for _, m := range match {
if m == "*" {
match = nil
break
}
}
s := strings.Replace(debugHooksClientScript, "{unit_name}", c.Unit, -1)
s = strings.Replace(s, "{tmux_conf}", tmuxConf, 1)
s = strings.Replace(s, "{entry_flock}", c.ClientFileLock(), -1)
s = strings.Replace(s, "{exit_flock}", c.ClientExitFileLock(), -1)
yamlArgs := encodeArgs(match)
base64Args := base64.StdEncoding.EncodeToString(yamlArgs)
s = strings.Replace(s, "{hook_args}", base64Args, 1)
return s
} | go | func ClientScript(c *HooksContext, match []string) string {
// If any argument is "*", then the client is interested in all.
for _, m := range match {
if m == "*" {
match = nil
break
}
}
s := strings.Replace(debugHooksClientScript, "{unit_name}", c.Unit, -1)
s = strings.Replace(s, "{tmux_conf}", tmuxConf, 1)
s = strings.Replace(s, "{entry_flock}", c.ClientFileLock(), -1)
s = strings.Replace(s, "{exit_flock}", c.ClientExitFileLock(), -1)
yamlArgs := encodeArgs(match)
base64Args := base64.StdEncoding.EncodeToString(yamlArgs)
s = strings.Replace(s, "{hook_args}", base64Args, 1)
return s
} | [
"func",
"ClientScript",
"(",
"c",
"*",
"HooksContext",
",",
"match",
"[",
"]",
"string",
")",
"string",
"{",
"// If any argument is \"*\", then the client is interested in all.",
"for",
"_",
",",
"m",
":=",
"range",
"match",
"{",
"if",
"m",
"==",
"\"",
"\"",
"{",
"match",
"=",
"nil",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"s",
":=",
"strings",
".",
"Replace",
"(",
"debugHooksClientScript",
",",
"\"",
"\"",
",",
"c",
".",
"Unit",
",",
"-",
"1",
")",
"\n",
"s",
"=",
"strings",
".",
"Replace",
"(",
"s",
",",
"\"",
"\"",
",",
"tmuxConf",
",",
"1",
")",
"\n",
"s",
"=",
"strings",
".",
"Replace",
"(",
"s",
",",
"\"",
"\"",
",",
"c",
".",
"ClientFileLock",
"(",
")",
",",
"-",
"1",
")",
"\n",
"s",
"=",
"strings",
".",
"Replace",
"(",
"s",
",",
"\"",
"\"",
",",
"c",
".",
"ClientExitFileLock",
"(",
")",
",",
"-",
"1",
")",
"\n\n",
"yamlArgs",
":=",
"encodeArgs",
"(",
"match",
")",
"\n",
"base64Args",
":=",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"yamlArgs",
")",
"\n",
"s",
"=",
"strings",
".",
"Replace",
"(",
"s",
",",
"\"",
"\"",
",",
"base64Args",
",",
"1",
")",
"\n",
"return",
"s",
"\n",
"}"
] | // ClientScript returns a bash script suitable for executing
// on the unit system to intercept matching hooks or actions via tmux shell. | [
"ClientScript",
"returns",
"a",
"bash",
"script",
"suitable",
"for",
"executing",
"on",
"the",
"unit",
"system",
"to",
"intercept",
"matching",
"hooks",
"or",
"actions",
"via",
"tmux",
"shell",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/debug/client.go#L19-L37 |
154,815 | juju/juju | worker/agent/manifold.go | Manifold | func Manifold(a agent.Agent) dependency.Manifold {
return dependency.Manifold{
Start: startFunc(a),
Output: outputFunc,
}
} | go | func Manifold(a agent.Agent) dependency.Manifold {
return dependency.Manifold{
Start: startFunc(a),
Output: outputFunc,
}
} | [
"func",
"Manifold",
"(",
"a",
"agent",
".",
"Agent",
")",
"dependency",
".",
"Manifold",
"{",
"return",
"dependency",
".",
"Manifold",
"{",
"Start",
":",
"startFunc",
"(",
"a",
")",
",",
"Output",
":",
"outputFunc",
",",
"}",
"\n",
"}"
] | // Manifold returns a manifold that starts a worker proxying the supplied Agent
// for use by other workers. | [
"Manifold",
"returns",
"a",
"manifold",
"that",
"starts",
"a",
"worker",
"proxying",
"the",
"supplied",
"Agent",
"for",
"use",
"by",
"other",
"workers",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/agent/manifold.go#L18-L23 |
154,816 | juju/juju | worker/agent/manifold.go | startFunc | func startFunc(a agent.Agent) dependency.StartFunc {
return func(_ dependency.Context) (worker.Worker, error) {
w := &agentWorker{agent: a}
w.tomb.Go(func() error {
<-w.tomb.Dying()
return nil
})
return w, nil
}
} | go | func startFunc(a agent.Agent) dependency.StartFunc {
return func(_ dependency.Context) (worker.Worker, error) {
w := &agentWorker{agent: a}
w.tomb.Go(func() error {
<-w.tomb.Dying()
return nil
})
return w, nil
}
} | [
"func",
"startFunc",
"(",
"a",
"agent",
".",
"Agent",
")",
"dependency",
".",
"StartFunc",
"{",
"return",
"func",
"(",
"_",
"dependency",
".",
"Context",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"w",
":=",
"&",
"agentWorker",
"{",
"agent",
":",
"a",
"}",
"\n",
"w",
".",
"tomb",
".",
"Go",
"(",
"func",
"(",
")",
"error",
"{",
"<-",
"w",
".",
"tomb",
".",
"Dying",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"w",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // startFunc returns a StartFunc that starts a worker holding a reference to
// the supplied Agent. | [
"startFunc",
"returns",
"a",
"StartFunc",
"that",
"starts",
"a",
"worker",
"holding",
"a",
"reference",
"to",
"the",
"supplied",
"Agent",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/agent/manifold.go#L27-L36 |
154,817 | juju/juju | worker/conv2state/converter.go | New | func New(m *machiner.State, agent Agent) watcher.NotifyHandler {
return &converter{machiner: wrapper{m}, agent: agent}
} | go | func New(m *machiner.State, agent Agent) watcher.NotifyHandler {
return &converter{machiner: wrapper{m}, agent: agent}
} | [
"func",
"New",
"(",
"m",
"*",
"machiner",
".",
"State",
",",
"agent",
"Agent",
")",
"watcher",
".",
"NotifyHandler",
"{",
"return",
"&",
"converter",
"{",
"machiner",
":",
"wrapper",
"{",
"m",
"}",
",",
"agent",
":",
"agent",
"}",
"\n",
"}"
] | // New returns a new notify watch handler that will convert the given machine &
// agent to a controller. | [
"New",
"returns",
"a",
"new",
"notify",
"watch",
"handler",
"that",
"will",
"convert",
"the",
"given",
"machine",
"&",
"agent",
"to",
"a",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/conv2state/converter.go#L19-L21 |
154,818 | juju/juju | worker/conv2state/converter.go | SetUp | func (c *converter) SetUp() (watcher.NotifyWatcher, error) {
m, err := c.machiner.Machine(c.agent.Tag().(names.MachineTag))
if err != nil {
return nil, errors.Trace(err)
}
c.machine = m
return m.Watch()
} | go | func (c *converter) SetUp() (watcher.NotifyWatcher, error) {
m, err := c.machiner.Machine(c.agent.Tag().(names.MachineTag))
if err != nil {
return nil, errors.Trace(err)
}
c.machine = m
return m.Watch()
} | [
"func",
"(",
"c",
"*",
"converter",
")",
"SetUp",
"(",
")",
"(",
"watcher",
".",
"NotifyWatcher",
",",
"error",
")",
"{",
"m",
",",
"err",
":=",
"c",
".",
"machiner",
".",
"Machine",
"(",
"c",
".",
"agent",
".",
"Tag",
"(",
")",
".",
"(",
"names",
".",
"MachineTag",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"c",
".",
"machine",
"=",
"m",
"\n",
"return",
"m",
".",
"Watch",
"(",
")",
"\n",
"}"
] | // SetUp implements NotifyWatchHandler's SetUp method. It returns a watcher that
// checks for changes to the current machine. | [
"SetUp",
"implements",
"NotifyWatchHandler",
"s",
"SetUp",
"method",
".",
"It",
"returns",
"a",
"watcher",
"that",
"checks",
"for",
"changes",
"to",
"the",
"current",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/conv2state/converter.go#L63-L70 |
154,819 | juju/juju | worker/conv2state/converter.go | Handle | func (c *converter) Handle(_ <-chan struct{}) error {
results, err := c.machine.Jobs()
if err != nil {
return errors.Annotate(err, "can't get jobs for machine")
}
if !multiwatcher.AnyJobNeedsState(results.Jobs...) {
return nil
}
return &util.FatalError{"bounce agent to pick up new jobs"}
} | go | func (c *converter) Handle(_ <-chan struct{}) error {
results, err := c.machine.Jobs()
if err != nil {
return errors.Annotate(err, "can't get jobs for machine")
}
if !multiwatcher.AnyJobNeedsState(results.Jobs...) {
return nil
}
return &util.FatalError{"bounce agent to pick up new jobs"}
} | [
"func",
"(",
"c",
"*",
"converter",
")",
"Handle",
"(",
"_",
"<-",
"chan",
"struct",
"{",
"}",
")",
"error",
"{",
"results",
",",
"err",
":=",
"c",
".",
"machine",
".",
"Jobs",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"multiwatcher",
".",
"AnyJobNeedsState",
"(",
"results",
".",
"Jobs",
"...",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"&",
"util",
".",
"FatalError",
"{",
"\"",
"\"",
"}",
"\n",
"}"
] | // Handle implements NotifyWatchHandler's Handle method. If the change means
// that the machine is now expected to manage the environment,
// we throw a fatal error to instigate agent restart. | [
"Handle",
"implements",
"NotifyWatchHandler",
"s",
"Handle",
"method",
".",
"If",
"the",
"change",
"means",
"that",
"the",
"machine",
"is",
"now",
"expected",
"to",
"manage",
"the",
"environment",
"we",
"throw",
"a",
"fatal",
"error",
"to",
"instigate",
"agent",
"restart",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/conv2state/converter.go#L75-L85 |
154,820 | juju/juju | api/reboot/reboot.go | NewState | func NewState(caller base.APICaller, machineTag names.MachineTag) State {
return &state{
facade: base.NewFacadeCaller(caller, "Reboot"),
machineTag: machineTag,
}
} | go | func NewState(caller base.APICaller, machineTag names.MachineTag) State {
return &state{
facade: base.NewFacadeCaller(caller, "Reboot"),
machineTag: machineTag,
}
} | [
"func",
"NewState",
"(",
"caller",
"base",
".",
"APICaller",
",",
"machineTag",
"names",
".",
"MachineTag",
")",
"State",
"{",
"return",
"&",
"state",
"{",
"facade",
":",
"base",
".",
"NewFacadeCaller",
"(",
"caller",
",",
"\"",
"\"",
")",
",",
"machineTag",
":",
"machineTag",
",",
"}",
"\n",
"}"
] | // NewState returns a version of the state that provides functionality
// required by the reboot worker. | [
"NewState",
"returns",
"a",
"version",
"of",
"the",
"state",
"that",
"provides",
"functionality",
"required",
"by",
"the",
"reboot",
"worker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/reboot/reboot.go#L45-L50 |
154,821 | juju/juju | api/reboot/reboot.go | WatchForRebootEvent | func (st *state) WatchForRebootEvent() (watcher.NotifyWatcher, error) {
var result params.NotifyWatchResult
if err := st.facade.FacadeCall("WatchForRebootEvent", nil, &result); err != nil {
return nil, err
}
if result.Error != nil {
return nil, result.Error
}
w := apiwatcher.NewNotifyWatcher(st.facade.RawAPICaller(), result)
return w, nil
} | go | func (st *state) WatchForRebootEvent() (watcher.NotifyWatcher, error) {
var result params.NotifyWatchResult
if err := st.facade.FacadeCall("WatchForRebootEvent", nil, &result); err != nil {
return nil, err
}
if result.Error != nil {
return nil, result.Error
}
w := apiwatcher.NewNotifyWatcher(st.facade.RawAPICaller(), result)
return w, nil
} | [
"func",
"(",
"st",
"*",
"state",
")",
"WatchForRebootEvent",
"(",
")",
"(",
"watcher",
".",
"NotifyWatcher",
",",
"error",
")",
"{",
"var",
"result",
"params",
".",
"NotifyWatchResult",
"\n\n",
"if",
"err",
":=",
"st",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"nil",
",",
"&",
"result",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"result",
".",
"Error",
"!=",
"nil",
"{",
"return",
"nil",
",",
"result",
".",
"Error",
"\n",
"}",
"\n\n",
"w",
":=",
"apiwatcher",
".",
"NewNotifyWatcher",
"(",
"st",
".",
"facade",
".",
"RawAPICaller",
"(",
")",
",",
"result",
")",
"\n",
"return",
"w",
",",
"nil",
"\n",
"}"
] | // WatchForRebootEvent implements State.WatchForRebootEvent | [
"WatchForRebootEvent",
"implements",
"State",
".",
"WatchForRebootEvent"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/reboot/reboot.go#L53-L65 |
154,822 | juju/juju | api/reboot/reboot.go | RequestReboot | func (st *state) RequestReboot() error {
var results params.ErrorResults
args := params.Entities{
Entities: []params.Entity{{Tag: st.machineTag.String()}},
}
err := st.facade.FacadeCall("RequestReboot", args, &results)
if err != nil {
return errors.Trace(err)
}
if len(results.Results) != 1 {
return errors.Errorf("expected 1 result, got %d", len(results.Results))
}
if results.Results[0].Error != nil {
return errors.Trace(results.Results[0].Error)
}
return nil
} | go | func (st *state) RequestReboot() error {
var results params.ErrorResults
args := params.Entities{
Entities: []params.Entity{{Tag: st.machineTag.String()}},
}
err := st.facade.FacadeCall("RequestReboot", args, &results)
if err != nil {
return errors.Trace(err)
}
if len(results.Results) != 1 {
return errors.Errorf("expected 1 result, got %d", len(results.Results))
}
if results.Results[0].Error != nil {
return errors.Trace(results.Results[0].Error)
}
return nil
} | [
"func",
"(",
"st",
"*",
"state",
")",
"RequestReboot",
"(",
")",
"error",
"{",
"var",
"results",
"params",
".",
"ErrorResults",
"\n",
"args",
":=",
"params",
".",
"Entities",
"{",
"Entities",
":",
"[",
"]",
"params",
".",
"Entity",
"{",
"{",
"Tag",
":",
"st",
".",
"machineTag",
".",
"String",
"(",
")",
"}",
"}",
",",
"}",
"\n\n",
"err",
":=",
"st",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"results",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"results",
".",
"Results",
")",
"!=",
"1",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"results",
".",
"Results",
")",
")",
"\n",
"}",
"\n\n",
"if",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"Error",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"Error",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // RequestReboot implements State.RequestReboot | [
"RequestReboot",
"implements",
"State",
".",
"RequestReboot"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/reboot/reboot.go#L68-L86 |
154,823 | juju/juju | api/reboot/reboot.go | GetRebootAction | func (st *state) GetRebootAction() (params.RebootAction, error) {
var results params.RebootActionResults
args := params.Entities{
Entities: []params.Entity{{Tag: st.machineTag.String()}},
}
err := st.facade.FacadeCall("GetRebootAction", args, &results)
if err != nil {
return params.ShouldDoNothing, err
}
if len(results.Results) != 1 {
return params.ShouldDoNothing, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
if results.Results[0].Error != nil {
return params.ShouldDoNothing, errors.Trace(results.Results[0].Error)
}
return results.Results[0].Result, nil
} | go | func (st *state) GetRebootAction() (params.RebootAction, error) {
var results params.RebootActionResults
args := params.Entities{
Entities: []params.Entity{{Tag: st.machineTag.String()}},
}
err := st.facade.FacadeCall("GetRebootAction", args, &results)
if err != nil {
return params.ShouldDoNothing, err
}
if len(results.Results) != 1 {
return params.ShouldDoNothing, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
if results.Results[0].Error != nil {
return params.ShouldDoNothing, errors.Trace(results.Results[0].Error)
}
return results.Results[0].Result, nil
} | [
"func",
"(",
"st",
"*",
"state",
")",
"GetRebootAction",
"(",
")",
"(",
"params",
".",
"RebootAction",
",",
"error",
")",
"{",
"var",
"results",
"params",
".",
"RebootActionResults",
"\n",
"args",
":=",
"params",
".",
"Entities",
"{",
"Entities",
":",
"[",
"]",
"params",
".",
"Entity",
"{",
"{",
"Tag",
":",
"st",
".",
"machineTag",
".",
"String",
"(",
")",
"}",
"}",
",",
"}",
"\n\n",
"err",
":=",
"st",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"results",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ShouldDoNothing",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"results",
".",
"Results",
")",
"!=",
"1",
"{",
"return",
"params",
".",
"ShouldDoNothing",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"results",
".",
"Results",
")",
")",
"\n",
"}",
"\n\n",
"if",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"Error",
"!=",
"nil",
"{",
"return",
"params",
".",
"ShouldDoNothing",
",",
"errors",
".",
"Trace",
"(",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"Error",
")",
"\n",
"}",
"\n\n",
"return",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"Result",
",",
"nil",
"\n",
"}"
] | // GetRebootAction implements State.GetRebootAction | [
"GetRebootAction",
"implements",
"State",
".",
"GetRebootAction"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/reboot/reboot.go#L112-L131 |
154,824 | juju/juju | worker/fortress/interface.go | IsFortressError | func IsFortressError(err error) bool {
switch errors.Cause(err) {
case ErrAborted, ErrShutdown:
return true
default:
return false
}
} | go | func IsFortressError(err error) bool {
switch errors.Cause(err) {
case ErrAborted, ErrShutdown:
return true
default:
return false
}
} | [
"func",
"IsFortressError",
"(",
"err",
"error",
")",
"bool",
"{",
"switch",
"errors",
".",
"Cause",
"(",
"err",
")",
"{",
"case",
"ErrAborted",
",",
"ErrShutdown",
":",
"return",
"true",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}"
] | // IsFortressError returns true if the error provided is fortress related. | [
"IsFortressError",
"returns",
"true",
"if",
"the",
"error",
"provided",
"is",
"fortress",
"related",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/fortress/interface.go#L64-L71 |
154,825 | juju/juju | api/facadeversions.go | bestVersion | func bestVersion(desiredVersion int, versions []int) int {
best := 0
for _, version := range versions {
if version <= desiredVersion && version > best {
best = version
}
}
return best
} | go | func bestVersion(desiredVersion int, versions []int) int {
best := 0
for _, version := range versions {
if version <= desiredVersion && version > best {
best = version
}
}
return best
} | [
"func",
"bestVersion",
"(",
"desiredVersion",
"int",
",",
"versions",
"[",
"]",
"int",
")",
"int",
"{",
"best",
":=",
"0",
"\n",
"for",
"_",
",",
"version",
":=",
"range",
"versions",
"{",
"if",
"version",
"<=",
"desiredVersion",
"&&",
"version",
">",
"best",
"{",
"best",
"=",
"version",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"best",
"\n",
"}"
] | // bestVersion tries to find the newest version in the version list that we can
// use. | [
"bestVersion",
"tries",
"to",
"find",
"the",
"newest",
"version",
"in",
"the",
"version",
"list",
"that",
"we",
"can",
"use",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/facadeversions.go#L116-L124 |
154,826 | juju/juju | apiserver/facades/agent/leadership/settings.go | NewLeadershipSettingsAccessor | func NewLeadershipSettingsAccessor(
authorizer facade.Authorizer,
registerWatcherFn RegisterWatcherFn,
getSettingsFn GetSettingsFn,
leaderCheckFn LeaderCheckFn,
mergeSettingsChunkFn MergeSettingsChunkFn,
) *LeadershipSettingsAccessor {
return &LeadershipSettingsAccessor{
authorizer: authorizer,
registerWatcherFn: registerWatcherFn,
getSettingsFn: getSettingsFn,
leaderCheckFn: leaderCheckFn,
mergeSettingsChunkFn: mergeSettingsChunkFn,
}
} | go | func NewLeadershipSettingsAccessor(
authorizer facade.Authorizer,
registerWatcherFn RegisterWatcherFn,
getSettingsFn GetSettingsFn,
leaderCheckFn LeaderCheckFn,
mergeSettingsChunkFn MergeSettingsChunkFn,
) *LeadershipSettingsAccessor {
return &LeadershipSettingsAccessor{
authorizer: authorizer,
registerWatcherFn: registerWatcherFn,
getSettingsFn: getSettingsFn,
leaderCheckFn: leaderCheckFn,
mergeSettingsChunkFn: mergeSettingsChunkFn,
}
} | [
"func",
"NewLeadershipSettingsAccessor",
"(",
"authorizer",
"facade",
".",
"Authorizer",
",",
"registerWatcherFn",
"RegisterWatcherFn",
",",
"getSettingsFn",
"GetSettingsFn",
",",
"leaderCheckFn",
"LeaderCheckFn",
",",
"mergeSettingsChunkFn",
"MergeSettingsChunkFn",
",",
")",
"*",
"LeadershipSettingsAccessor",
"{",
"return",
"&",
"LeadershipSettingsAccessor",
"{",
"authorizer",
":",
"authorizer",
",",
"registerWatcherFn",
":",
"registerWatcherFn",
",",
"getSettingsFn",
":",
"getSettingsFn",
",",
"leaderCheckFn",
":",
"leaderCheckFn",
",",
"mergeSettingsChunkFn",
":",
"mergeSettingsChunkFn",
",",
"}",
"\n",
"}"
] | // NewLeadershipSettingsAccessor creates a new
// LeadershipSettingsAccessor. | [
"NewLeadershipSettingsAccessor",
"creates",
"a",
"new",
"LeadershipSettingsAccessor",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/leadership/settings.go#L18-L33 |
154,827 | juju/juju | apiserver/facades/agent/leadership/settings.go | Merge | func (lsa *LeadershipSettingsAccessor) Merge(bulkArgs params.MergeLeadershipSettingsBulkParams) (params.ErrorResults, error) {
requireAppName, err := lsa.callerApplication()
if err != nil {
return params.ErrorResults{}, err
}
// Start out assuming the caller is a unit (for older clients).
callerUnitId := lsa.authorizer.GetAuthTag().Id()
results := make([]params.ErrorResult, len(bulkArgs.Params))
for i, arg := range bulkArgs.Params {
result := &results[i]
// TODO(fwereade): we shoudn't assume a ApplicationTag: we should
// use an actual auth func to determine permissions.
applicationTag, err := names.ParseApplicationTag(arg.ApplicationTag)
if err != nil {
result.Error = common.ServerError(err)
continue
}
// If a unit is passed in as an arg, use that instead of the caller id.
if arg.UnitTag != "" {
unitTag, err := names.ParseUnitTag(arg.UnitTag)
if err != nil {
result.Error = common.ServerError(err)
continue
}
callerUnitId = unitTag.Id()
unitAppName, err := names.UnitApplication(callerUnitId)
if err != nil || unitAppName != requireAppName {
result.Error = common.ServerError(common.ErrPerm)
continue
}
}
appName := applicationTag.Id()
if appName != requireAppName {
result.Error = common.ServerError(common.ErrPerm)
continue
}
token := lsa.leaderCheckFn(appName, callerUnitId)
err = lsa.mergeSettingsChunkFn(token, appName, arg.Settings)
if err != nil {
result.Error = common.ServerError(err)
}
}
return params.ErrorResults{Results: results}, nil
} | go | func (lsa *LeadershipSettingsAccessor) Merge(bulkArgs params.MergeLeadershipSettingsBulkParams) (params.ErrorResults, error) {
requireAppName, err := lsa.callerApplication()
if err != nil {
return params.ErrorResults{}, err
}
// Start out assuming the caller is a unit (for older clients).
callerUnitId := lsa.authorizer.GetAuthTag().Id()
results := make([]params.ErrorResult, len(bulkArgs.Params))
for i, arg := range bulkArgs.Params {
result := &results[i]
// TODO(fwereade): we shoudn't assume a ApplicationTag: we should
// use an actual auth func to determine permissions.
applicationTag, err := names.ParseApplicationTag(arg.ApplicationTag)
if err != nil {
result.Error = common.ServerError(err)
continue
}
// If a unit is passed in as an arg, use that instead of the caller id.
if arg.UnitTag != "" {
unitTag, err := names.ParseUnitTag(arg.UnitTag)
if err != nil {
result.Error = common.ServerError(err)
continue
}
callerUnitId = unitTag.Id()
unitAppName, err := names.UnitApplication(callerUnitId)
if err != nil || unitAppName != requireAppName {
result.Error = common.ServerError(common.ErrPerm)
continue
}
}
appName := applicationTag.Id()
if appName != requireAppName {
result.Error = common.ServerError(common.ErrPerm)
continue
}
token := lsa.leaderCheckFn(appName, callerUnitId)
err = lsa.mergeSettingsChunkFn(token, appName, arg.Settings)
if err != nil {
result.Error = common.ServerError(err)
}
}
return params.ErrorResults{Results: results}, nil
} | [
"func",
"(",
"lsa",
"*",
"LeadershipSettingsAccessor",
")",
"Merge",
"(",
"bulkArgs",
"params",
".",
"MergeLeadershipSettingsBulkParams",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"requireAppName",
",",
"err",
":=",
"lsa",
".",
"callerApplication",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ErrorResults",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"// Start out assuming the caller is a unit (for older clients).",
"callerUnitId",
":=",
"lsa",
".",
"authorizer",
".",
"GetAuthTag",
"(",
")",
".",
"Id",
"(",
")",
"\n\n",
"results",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"ErrorResult",
",",
"len",
"(",
"bulkArgs",
".",
"Params",
")",
")",
"\n\n",
"for",
"i",
",",
"arg",
":=",
"range",
"bulkArgs",
".",
"Params",
"{",
"result",
":=",
"&",
"results",
"[",
"i",
"]",
"\n\n",
"// TODO(fwereade): we shoudn't assume a ApplicationTag: we should",
"// use an actual auth func to determine permissions.",
"applicationTag",
",",
"err",
":=",
"names",
".",
"ParseApplicationTag",
"(",
"arg",
".",
"ApplicationTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// If a unit is passed in as an arg, use that instead of the caller id.",
"if",
"arg",
".",
"UnitTag",
"!=",
"\"",
"\"",
"{",
"unitTag",
",",
"err",
":=",
"names",
".",
"ParseUnitTag",
"(",
"arg",
".",
"UnitTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"callerUnitId",
"=",
"unitTag",
".",
"Id",
"(",
")",
"\n",
"unitAppName",
",",
"err",
":=",
"names",
".",
"UnitApplication",
"(",
"callerUnitId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"unitAppName",
"!=",
"requireAppName",
"{",
"result",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"common",
".",
"ErrPerm",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"appName",
":=",
"applicationTag",
".",
"Id",
"(",
")",
"\n",
"if",
"appName",
"!=",
"requireAppName",
"{",
"result",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"common",
".",
"ErrPerm",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"token",
":=",
"lsa",
".",
"leaderCheckFn",
"(",
"appName",
",",
"callerUnitId",
")",
"\n",
"err",
"=",
"lsa",
".",
"mergeSettingsChunkFn",
"(",
"token",
",",
"appName",
",",
"arg",
".",
"Settings",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"params",
".",
"ErrorResults",
"{",
"Results",
":",
"results",
"}",
",",
"nil",
"\n",
"}"
] | // Merge merges in the provided leadership settings. Only leaders for
// the given service may perform this operation. | [
"Merge",
"merges",
"in",
"the",
"provided",
"leadership",
"settings",
".",
"Only",
"leaders",
"for",
"the",
"given",
"service",
"may",
"perform",
"this",
"operation",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/leadership/settings.go#L83-L134 |
154,828 | juju/juju | apiserver/facades/agent/leadership/settings.go | Read | func (lsa *LeadershipSettingsAccessor) Read(bulkArgs params.Entities) (params.GetLeadershipSettingsBulkResults, error) {
requireAppName, err := lsa.callerApplication()
if err != nil {
return params.GetLeadershipSettingsBulkResults{}, err
}
results := make([]params.GetLeadershipSettingsResult, len(bulkArgs.Entities))
for i, arg := range bulkArgs.Entities {
result := &results[i]
// TODO(fwereade): we shoudn't assume a ApplicationTag: we should
// use an actual auth func to determine permissions.
applicationTag, err := names.ParseApplicationTag(arg.Tag)
if err != nil {
result.Error = common.ServerError(err)
continue
}
appName := applicationTag.Id()
if appName != requireAppName {
result.Error = common.ServerError(common.ErrPerm)
continue
}
settings, err := lsa.getSettingsFn(appName)
if err != nil {
result.Error = common.ServerError(err)
continue
}
result.Settings = settings
}
return params.GetLeadershipSettingsBulkResults{results}, nil
} | go | func (lsa *LeadershipSettingsAccessor) Read(bulkArgs params.Entities) (params.GetLeadershipSettingsBulkResults, error) {
requireAppName, err := lsa.callerApplication()
if err != nil {
return params.GetLeadershipSettingsBulkResults{}, err
}
results := make([]params.GetLeadershipSettingsResult, len(bulkArgs.Entities))
for i, arg := range bulkArgs.Entities {
result := &results[i]
// TODO(fwereade): we shoudn't assume a ApplicationTag: we should
// use an actual auth func to determine permissions.
applicationTag, err := names.ParseApplicationTag(arg.Tag)
if err != nil {
result.Error = common.ServerError(err)
continue
}
appName := applicationTag.Id()
if appName != requireAppName {
result.Error = common.ServerError(common.ErrPerm)
continue
}
settings, err := lsa.getSettingsFn(appName)
if err != nil {
result.Error = common.ServerError(err)
continue
}
result.Settings = settings
}
return params.GetLeadershipSettingsBulkResults{results}, nil
} | [
"func",
"(",
"lsa",
"*",
"LeadershipSettingsAccessor",
")",
"Read",
"(",
"bulkArgs",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"GetLeadershipSettingsBulkResults",
",",
"error",
")",
"{",
"requireAppName",
",",
"err",
":=",
"lsa",
".",
"callerApplication",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"GetLeadershipSettingsBulkResults",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"results",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"GetLeadershipSettingsResult",
",",
"len",
"(",
"bulkArgs",
".",
"Entities",
")",
")",
"\n\n",
"for",
"i",
",",
"arg",
":=",
"range",
"bulkArgs",
".",
"Entities",
"{",
"result",
":=",
"&",
"results",
"[",
"i",
"]",
"\n\n",
"// TODO(fwereade): we shoudn't assume a ApplicationTag: we should",
"// use an actual auth func to determine permissions.",
"applicationTag",
",",
"err",
":=",
"names",
".",
"ParseApplicationTag",
"(",
"arg",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"appName",
":=",
"applicationTag",
".",
"Id",
"(",
")",
"\n",
"if",
"appName",
"!=",
"requireAppName",
"{",
"result",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"common",
".",
"ErrPerm",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"settings",
",",
"err",
":=",
"lsa",
".",
"getSettingsFn",
"(",
"appName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"result",
".",
"Settings",
"=",
"settings",
"\n",
"}",
"\n\n",
"return",
"params",
".",
"GetLeadershipSettingsBulkResults",
"{",
"results",
"}",
",",
"nil",
"\n",
"}"
] | // Read reads leadership settings for the provided service ID. Any
// unit of the service may perform this operation. | [
"Read",
"reads",
"leadership",
"settings",
"for",
"the",
"provided",
"service",
"ID",
".",
"Any",
"unit",
"of",
"the",
"service",
"may",
"perform",
"this",
"operation",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/leadership/settings.go#L138-L173 |
154,829 | juju/juju | apiserver/facades/agent/leadership/settings.go | WatchLeadershipSettings | func (lsa *LeadershipSettingsAccessor) WatchLeadershipSettings(bulkArgs params.Entities) (params.NotifyWatchResults, error) {
requireAppName, err := lsa.callerApplication()
if err != nil {
return params.NotifyWatchResults{}, err
}
results := make([]params.NotifyWatchResult, len(bulkArgs.Entities))
for i, arg := range bulkArgs.Entities {
result := &results[i]
// TODO(fwereade): we shoudn't assume a ApplicationTag: we should
// use an actual auth func to determine permissions.
applicationTag, err := names.ParseApplicationTag(arg.Tag)
if err != nil {
result.Error = common.ServerError(err)
continue
}
appName := applicationTag.Id()
if appName != requireAppName {
result.Error = common.ServerError(common.ErrPerm)
continue
}
watcherId, err := lsa.registerWatcherFn(appName)
if err != nil {
result.Error = common.ServerError(err)
continue
}
result.NotifyWatcherId = watcherId
}
return params.NotifyWatchResults{Results: results}, nil
} | go | func (lsa *LeadershipSettingsAccessor) WatchLeadershipSettings(bulkArgs params.Entities) (params.NotifyWatchResults, error) {
requireAppName, err := lsa.callerApplication()
if err != nil {
return params.NotifyWatchResults{}, err
}
results := make([]params.NotifyWatchResult, len(bulkArgs.Entities))
for i, arg := range bulkArgs.Entities {
result := &results[i]
// TODO(fwereade): we shoudn't assume a ApplicationTag: we should
// use an actual auth func to determine permissions.
applicationTag, err := names.ParseApplicationTag(arg.Tag)
if err != nil {
result.Error = common.ServerError(err)
continue
}
appName := applicationTag.Id()
if appName != requireAppName {
result.Error = common.ServerError(common.ErrPerm)
continue
}
watcherId, err := lsa.registerWatcherFn(appName)
if err != nil {
result.Error = common.ServerError(err)
continue
}
result.NotifyWatcherId = watcherId
}
return params.NotifyWatchResults{Results: results}, nil
} | [
"func",
"(",
"lsa",
"*",
"LeadershipSettingsAccessor",
")",
"WatchLeadershipSettings",
"(",
"bulkArgs",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"NotifyWatchResults",
",",
"error",
")",
"{",
"requireAppName",
",",
"err",
":=",
"lsa",
".",
"callerApplication",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"NotifyWatchResults",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"results",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"NotifyWatchResult",
",",
"len",
"(",
"bulkArgs",
".",
"Entities",
")",
")",
"\n\n",
"for",
"i",
",",
"arg",
":=",
"range",
"bulkArgs",
".",
"Entities",
"{",
"result",
":=",
"&",
"results",
"[",
"i",
"]",
"\n\n",
"// TODO(fwereade): we shoudn't assume a ApplicationTag: we should",
"// use an actual auth func to determine permissions.",
"applicationTag",
",",
"err",
":=",
"names",
".",
"ParseApplicationTag",
"(",
"arg",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"appName",
":=",
"applicationTag",
".",
"Id",
"(",
")",
"\n",
"if",
"appName",
"!=",
"requireAppName",
"{",
"result",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"common",
".",
"ErrPerm",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"watcherId",
",",
"err",
":=",
"lsa",
".",
"registerWatcherFn",
"(",
"appName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"result",
".",
"NotifyWatcherId",
"=",
"watcherId",
"\n",
"}",
"\n",
"return",
"params",
".",
"NotifyWatchResults",
"{",
"Results",
":",
"results",
"}",
",",
"nil",
"\n",
"}"
] | // WatchLeadershipSettings will block the caller until leadership settings
// for the given service ID change. | [
"WatchLeadershipSettings",
"will",
"block",
"the",
"caller",
"until",
"leadership",
"settings",
"for",
"the",
"given",
"service",
"ID",
"change",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/leadership/settings.go#L177-L211 |
154,830 | juju/juju | api/backups/list.go | List | func (c *Client) List() (*params.BackupsListResult, error) {
var result params.BackupsListResult
args := params.BackupsListArgs{}
if err := c.facade.FacadeCall("List", args, &result); err != nil {
return nil, errors.Trace(err)
}
return &result, nil
} | go | func (c *Client) List() (*params.BackupsListResult, error) {
var result params.BackupsListResult
args := params.BackupsListArgs{}
if err := c.facade.FacadeCall("List", args, &result); err != nil {
return nil, errors.Trace(err)
}
return &result, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"List",
"(",
")",
"(",
"*",
"params",
".",
"BackupsListResult",
",",
"error",
")",
"{",
"var",
"result",
"params",
".",
"BackupsListResult",
"\n",
"args",
":=",
"params",
".",
"BackupsListArgs",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"result",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"result",
",",
"nil",
"\n",
"}"
] | // List implements the API method. | [
"List",
"implements",
"the",
"API",
"method",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/backups/list.go#L13-L20 |
154,831 | juju/juju | cmd/juju/resource/upload.go | NewUploadCommand | func NewUploadCommand(deps UploadDeps) modelcmd.ModelCommand {
return modelcmd.Wrap(&UploadCommand{deps: deps})
} | go | func NewUploadCommand(deps UploadDeps) modelcmd.ModelCommand {
return modelcmd.Wrap(&UploadCommand{deps: deps})
} | [
"func",
"NewUploadCommand",
"(",
"deps",
"UploadDeps",
")",
"modelcmd",
".",
"ModelCommand",
"{",
"return",
"modelcmd",
".",
"Wrap",
"(",
"&",
"UploadCommand",
"{",
"deps",
":",
"deps",
"}",
")",
"\n",
"}"
] | // NewUploadCommand returns a new command that lists resources defined
// by a charm. | [
"NewUploadCommand",
"returns",
"a",
"new",
"command",
"that",
"lists",
"resources",
"defined",
"by",
"a",
"charm",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/resource/upload.go#L57-L59 |
154,832 | juju/juju | cmd/juju/resource/upload.go | Info | func (c *UploadCommand) Info() *cmd.Info {
return jujucmd.Info(&cmd.Info{
Name: "attach-resource",
Args: "application name=file|OCI image",
Purpose: "Update a resource for an application.",
Doc: attachDoc,
Aliases: []string{"attach"},
})
} | go | func (c *UploadCommand) Info() *cmd.Info {
return jujucmd.Info(&cmd.Info{
Name: "attach-resource",
Args: "application name=file|OCI image",
Purpose: "Update a resource for an application.",
Doc: attachDoc,
Aliases: []string{"attach"},
})
} | [
"func",
"(",
"c",
"*",
"UploadCommand",
")",
"Info",
"(",
")",
"*",
"cmd",
".",
"Info",
"{",
"return",
"jujucmd",
".",
"Info",
"(",
"&",
"cmd",
".",
"Info",
"{",
"Name",
":",
"\"",
"\"",
",",
"Args",
":",
"\"",
"\"",
",",
"Purpose",
":",
"\"",
"\"",
",",
"Doc",
":",
"attachDoc",
",",
"Aliases",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"}",
")",
"\n",
"}"
] | // Info implements cmd.Command.Info | [
"Info",
"implements",
"cmd",
".",
"Command",
".",
"Info"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/resource/upload.go#L75-L83 |
154,833 | juju/juju | cmd/juju/resource/upload.go | addResourceValue | func (c *UploadCommand) addResourceValue(arg string) error {
name, value, err := parseResourceValueArg(arg)
if err != nil {
return errors.Annotatef(err, "bad resource arg %q", arg)
}
c.resourceValue = resourceValue{
application: c.application,
name: name,
value: value,
// Default to file resource.
resourceType: charmresource.TypeFile,
}
return nil
} | go | func (c *UploadCommand) addResourceValue(arg string) error {
name, value, err := parseResourceValueArg(arg)
if err != nil {
return errors.Annotatef(err, "bad resource arg %q", arg)
}
c.resourceValue = resourceValue{
application: c.application,
name: name,
value: value,
// Default to file resource.
resourceType: charmresource.TypeFile,
}
return nil
} | [
"func",
"(",
"c",
"*",
"UploadCommand",
")",
"addResourceValue",
"(",
"arg",
"string",
")",
"error",
"{",
"name",
",",
"value",
",",
"err",
":=",
"parseResourceValueArg",
"(",
"arg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"arg",
")",
"\n",
"}",
"\n",
"c",
".",
"resourceValue",
"=",
"resourceValue",
"{",
"application",
":",
"c",
".",
"application",
",",
"name",
":",
"name",
",",
"value",
":",
"value",
",",
"// Default to file resource.",
"resourceType",
":",
"charmresource",
".",
"TypeFile",
",",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // addResourceValue parses the given arg into a name and a resource value,
// and saves it in c.resourceValue. | [
"addResourceValue",
"parses",
"the",
"given",
"arg",
"into",
"a",
"name",
"and",
"a",
"resource",
"value",
"and",
"saves",
"it",
"in",
"c",
".",
"resourceValue",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/resource/upload.go#L108-L122 |
154,834 | juju/juju | cmd/juju/resource/upload.go | upload | func (c *UploadCommand) upload(rf resourceValue, client UploadClient) error {
f, err := OpenResource(rf.value, rf.resourceType, c.deps.OpenResource)
if err != nil {
return errors.Trace(err)
}
defer f.Close()
err = client.Upload(rf.application, rf.name, rf.value, f)
return errors.Trace(err)
} | go | func (c *UploadCommand) upload(rf resourceValue, client UploadClient) error {
f, err := OpenResource(rf.value, rf.resourceType, c.deps.OpenResource)
if err != nil {
return errors.Trace(err)
}
defer f.Close()
err = client.Upload(rf.application, rf.name, rf.value, f)
return errors.Trace(err)
} | [
"func",
"(",
"c",
"*",
"UploadCommand",
")",
"upload",
"(",
"rf",
"resourceValue",
",",
"client",
"UploadClient",
")",
"error",
"{",
"f",
",",
"err",
":=",
"OpenResource",
"(",
"rf",
".",
"value",
",",
"rf",
".",
"resourceType",
",",
"c",
".",
"deps",
".",
"OpenResource",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"client",
".",
"Upload",
"(",
"rf",
".",
"application",
",",
"rf",
".",
"name",
",",
"rf",
".",
"value",
",",
"f",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // upload opens the given file and calls the apiclient to upload it to the given
// application with the given name. | [
"upload",
"opens",
"the",
"given",
"file",
"and",
"calls",
"the",
"apiclient",
"to",
"upload",
"it",
"to",
"the",
"given",
"application",
"with",
"the",
"given",
"name",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/resource/upload.go#L151-L159 |
154,835 | juju/juju | apiserver/gui.go | ensureFileHandler | func (gr *guiRouter) ensureFileHandler(h func(gh *guiHandler, w http.ResponseWriter, req *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
rootDir, hash, err := gr.ensureFiles(req)
if err != nil {
// Note that ensureFiles also checks that the model UUID is valid.
if err := sendError(w, err); err != nil {
logger.Errorf("%v", err)
}
return
}
qhash := req.URL.Query().Get(":hash")
if qhash != "" && qhash != hash {
if err := sendError(w, errors.NotFoundf("resource with %q hash", qhash)); err != nil {
logger.Errorf("%v", err)
}
return
}
gh := &guiHandler{
ctxt: gr.ctxt,
rootDir: rootDir,
basePath: guiURLPathPrefix,
hash: hash,
}
h(gh, w, req)
})
} | go | func (gr *guiRouter) ensureFileHandler(h func(gh *guiHandler, w http.ResponseWriter, req *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
rootDir, hash, err := gr.ensureFiles(req)
if err != nil {
// Note that ensureFiles also checks that the model UUID is valid.
if err := sendError(w, err); err != nil {
logger.Errorf("%v", err)
}
return
}
qhash := req.URL.Query().Get(":hash")
if qhash != "" && qhash != hash {
if err := sendError(w, errors.NotFoundf("resource with %q hash", qhash)); err != nil {
logger.Errorf("%v", err)
}
return
}
gh := &guiHandler{
ctxt: gr.ctxt,
rootDir: rootDir,
basePath: guiURLPathPrefix,
hash: hash,
}
h(gh, w, req)
})
} | [
"func",
"(",
"gr",
"*",
"guiRouter",
")",
"ensureFileHandler",
"(",
"h",
"func",
"(",
"gh",
"*",
"guiHandler",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"rootDir",
",",
"hash",
",",
"err",
":=",
"gr",
".",
"ensureFiles",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Note that ensureFiles also checks that the model UUID is valid.",
"if",
"err",
":=",
"sendError",
"(",
"w",
",",
"err",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"qhash",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"qhash",
"!=",
"\"",
"\"",
"&&",
"qhash",
"!=",
"hash",
"{",
"if",
"err",
":=",
"sendError",
"(",
"w",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"qhash",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"gh",
":=",
"&",
"guiHandler",
"{",
"ctxt",
":",
"gr",
".",
"ctxt",
",",
"rootDir",
":",
"rootDir",
",",
"basePath",
":",
"guiURLPathPrefix",
",",
"hash",
":",
"hash",
",",
"}",
"\n",
"h",
"(",
"gh",
",",
"w",
",",
"req",
")",
"\n",
"}",
")",
"\n",
"}"
] | // ensureFileHandler decorates the given function to ensure the Juju GUI files
// are available on disk. | [
"ensureFileHandler",
"decorates",
"the",
"given",
"function",
"to",
"ensure",
"the",
"Juju",
"GUI",
"files",
"are",
"available",
"on",
"disk",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L106-L131 |
154,836 | juju/juju | apiserver/gui.go | ensureFiles | func (gr *guiRouter) ensureFiles(req *http.Request) (rootDir string, hash string, err error) {
// Retrieve the Juju GUI info from the GUI storage.
st := gr.ctxt.srv.shared.statePool.SystemState()
storage, err := st.GUIStorage()
if err != nil {
return "", "", errors.Annotate(err, "cannot open GUI storage")
}
defer storage.Close()
vers, hash, err := guiVersionAndHash(st, storage)
if err != nil {
return "", "", errors.Trace(err)
}
logger.Debugf("serving Juju GUI version %s", vers)
// Check if the current Juju GUI archive has been already expanded on disk.
baseDir := agenttools.SharedGUIDir(gr.dataDir)
// Note that we include the hash in the root directory so that when the GUI
// archive changes we can be sure that clients will not use files from
// mixed versions.
rootDir = filepath.Join(baseDir, hash)
info, err := os.Stat(rootDir)
if err == nil {
if info.IsDir() {
return rootDir, hash, nil
}
return "", "", errors.Errorf("cannot use Juju GUI root directory %q: not a directory", rootDir)
}
if !os.IsNotExist(err) {
return "", "", errors.Annotate(err, "cannot stat Juju GUI root directory")
}
// Fetch the Juju GUI archive from the GUI storage and expand it.
_, r, err := storage.Open(vers)
if err != nil {
return "", "", errors.Annotatef(err, "cannot find GUI archive version %q", vers)
}
defer r.Close()
if err := os.MkdirAll(baseDir, 0755); err != nil {
return "", "", errors.Annotate(err, "cannot create Juju GUI base directory")
}
guiDir := "jujugui-" + vers + "/jujugui"
if err := uncompressGUI(r, guiDir, rootDir); err != nil {
return "", "", errors.Annotate(err, "cannot uncompress Juju GUI archive")
}
return rootDir, hash, nil
} | go | func (gr *guiRouter) ensureFiles(req *http.Request) (rootDir string, hash string, err error) {
// Retrieve the Juju GUI info from the GUI storage.
st := gr.ctxt.srv.shared.statePool.SystemState()
storage, err := st.GUIStorage()
if err != nil {
return "", "", errors.Annotate(err, "cannot open GUI storage")
}
defer storage.Close()
vers, hash, err := guiVersionAndHash(st, storage)
if err != nil {
return "", "", errors.Trace(err)
}
logger.Debugf("serving Juju GUI version %s", vers)
// Check if the current Juju GUI archive has been already expanded on disk.
baseDir := agenttools.SharedGUIDir(gr.dataDir)
// Note that we include the hash in the root directory so that when the GUI
// archive changes we can be sure that clients will not use files from
// mixed versions.
rootDir = filepath.Join(baseDir, hash)
info, err := os.Stat(rootDir)
if err == nil {
if info.IsDir() {
return rootDir, hash, nil
}
return "", "", errors.Errorf("cannot use Juju GUI root directory %q: not a directory", rootDir)
}
if !os.IsNotExist(err) {
return "", "", errors.Annotate(err, "cannot stat Juju GUI root directory")
}
// Fetch the Juju GUI archive from the GUI storage and expand it.
_, r, err := storage.Open(vers)
if err != nil {
return "", "", errors.Annotatef(err, "cannot find GUI archive version %q", vers)
}
defer r.Close()
if err := os.MkdirAll(baseDir, 0755); err != nil {
return "", "", errors.Annotate(err, "cannot create Juju GUI base directory")
}
guiDir := "jujugui-" + vers + "/jujugui"
if err := uncompressGUI(r, guiDir, rootDir); err != nil {
return "", "", errors.Annotate(err, "cannot uncompress Juju GUI archive")
}
return rootDir, hash, nil
} | [
"func",
"(",
"gr",
"*",
"guiRouter",
")",
"ensureFiles",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"rootDir",
"string",
",",
"hash",
"string",
",",
"err",
"error",
")",
"{",
"// Retrieve the Juju GUI info from the GUI storage.",
"st",
":=",
"gr",
".",
"ctxt",
".",
"srv",
".",
"shared",
".",
"statePool",
".",
"SystemState",
"(",
")",
"\n",
"storage",
",",
"err",
":=",
"st",
".",
"GUIStorage",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"storage",
".",
"Close",
"(",
")",
"\n",
"vers",
",",
"hash",
",",
"err",
":=",
"guiVersionAndHash",
"(",
"st",
",",
"storage",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"vers",
")",
"\n\n",
"// Check if the current Juju GUI archive has been already expanded on disk.",
"baseDir",
":=",
"agenttools",
".",
"SharedGUIDir",
"(",
"gr",
".",
"dataDir",
")",
"\n",
"// Note that we include the hash in the root directory so that when the GUI",
"// archive changes we can be sure that clients will not use files from",
"// mixed versions.",
"rootDir",
"=",
"filepath",
".",
"Join",
"(",
"baseDir",
",",
"hash",
")",
"\n",
"info",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"rootDir",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"if",
"info",
".",
"IsDir",
"(",
")",
"{",
"return",
"rootDir",
",",
"hash",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rootDir",
")",
"\n",
"}",
"\n",
"if",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Fetch the Juju GUI archive from the GUI storage and expand it.",
"_",
",",
"r",
",",
"err",
":=",
"storage",
".",
"Open",
"(",
"vers",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"vers",
")",
"\n",
"}",
"\n",
"defer",
"r",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"baseDir",
",",
"0755",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"guiDir",
":=",
"\"",
"\"",
"+",
"vers",
"+",
"\"",
"\"",
"\n",
"if",
"err",
":=",
"uncompressGUI",
"(",
"r",
",",
"guiDir",
",",
"rootDir",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"rootDir",
",",
"hash",
",",
"nil",
"\n",
"}"
] | // ensureFiles checks that the GUI files are available on disk.
// If they are not, it means this is the first time this Juju GUI version is
// accessed. In this case, retrieve the Juju GUI archive from the storage and
// uncompress it to disk. This function returns the current GUI root directory
// and archive hash. | [
"ensureFiles",
"checks",
"that",
"the",
"GUI",
"files",
"are",
"available",
"on",
"disk",
".",
"If",
"they",
"are",
"not",
"it",
"means",
"this",
"is",
"the",
"first",
"time",
"this",
"Juju",
"GUI",
"version",
"is",
"accessed",
".",
"In",
"this",
"case",
"retrieve",
"the",
"Juju",
"GUI",
"archive",
"from",
"the",
"storage",
"and",
"uncompress",
"it",
"to",
"disk",
".",
"This",
"function",
"returns",
"the",
"current",
"GUI",
"root",
"directory",
"and",
"archive",
"hash",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L138-L183 |
154,837 | juju/juju | apiserver/gui.go | guiVersionAndHash | func guiVersionAndHash(st *state.State, storage binarystorage.Storage) (vers, hash string, err error) {
currentVers, err := st.GUIVersion()
if errors.IsNotFound(err) {
return "", "", errors.NotFoundf("Juju GUI")
}
if err != nil {
return "", "", errors.Annotate(err, "cannot retrieve current GUI version")
}
metadata, err := storage.Metadata(currentVers.String())
if err != nil {
return "", "", errors.Annotate(err, "cannot retrieve GUI metadata")
}
return metadata.Version, metadata.SHA256, nil
} | go | func guiVersionAndHash(st *state.State, storage binarystorage.Storage) (vers, hash string, err error) {
currentVers, err := st.GUIVersion()
if errors.IsNotFound(err) {
return "", "", errors.NotFoundf("Juju GUI")
}
if err != nil {
return "", "", errors.Annotate(err, "cannot retrieve current GUI version")
}
metadata, err := storage.Metadata(currentVers.String())
if err != nil {
return "", "", errors.Annotate(err, "cannot retrieve GUI metadata")
}
return metadata.Version, metadata.SHA256, nil
} | [
"func",
"guiVersionAndHash",
"(",
"st",
"*",
"state",
".",
"State",
",",
"storage",
"binarystorage",
".",
"Storage",
")",
"(",
"vers",
",",
"hash",
"string",
",",
"err",
"error",
")",
"{",
"currentVers",
",",
"err",
":=",
"st",
".",
"GUIVersion",
"(",
")",
"\n",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"metadata",
",",
"err",
":=",
"storage",
".",
"Metadata",
"(",
"currentVers",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"metadata",
".",
"Version",
",",
"metadata",
".",
"SHA256",
",",
"nil",
"\n",
"}"
] | // guiVersionAndHash returns the version and the SHA256 hash of the current
// Juju GUI archive. | [
"guiVersionAndHash",
"returns",
"the",
"version",
"and",
"the",
"SHA256",
"hash",
"of",
"the",
"current",
"Juju",
"GUI",
"archive",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L187-L200 |
154,838 | juju/juju | apiserver/gui.go | uncompressGUI | func uncompressGUI(r io.Reader, sourceDir, targetDir string) error {
tempDir, err := ioutil.TempDir(filepath.Join(targetDir, ".."), "gui")
if err != nil {
return errors.Annotate(err, "cannot create Juju GUI temporary directory")
}
defer os.Remove(tempDir)
tr := tar.NewReader(bzip2.NewReader(r))
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return errors.Annotate(err, "cannot parse archive")
}
if hdr.Name != sourceDir && !strings.HasPrefix(hdr.Name, sourceDir+"/") {
continue
}
path := filepath.Join(tempDir, hdr.Name)
info := hdr.FileInfo()
if info.IsDir() {
if err := os.MkdirAll(path, info.Mode()); err != nil {
return errors.Annotate(err, "cannot create directory")
}
continue
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, info.Mode())
if err != nil {
return errors.Annotate(err, "cannot open file")
}
defer f.Close()
if _, err := io.Copy(f, tr); err != nil {
return errors.Annotate(err, "cannot copy file content")
}
}
if err := os.Rename(filepath.Join(tempDir, sourceDir), targetDir); err != nil {
return errors.Annotate(err, "cannot rename Juju GUI root directory")
}
return nil
} | go | func uncompressGUI(r io.Reader, sourceDir, targetDir string) error {
tempDir, err := ioutil.TempDir(filepath.Join(targetDir, ".."), "gui")
if err != nil {
return errors.Annotate(err, "cannot create Juju GUI temporary directory")
}
defer os.Remove(tempDir)
tr := tar.NewReader(bzip2.NewReader(r))
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return errors.Annotate(err, "cannot parse archive")
}
if hdr.Name != sourceDir && !strings.HasPrefix(hdr.Name, sourceDir+"/") {
continue
}
path := filepath.Join(tempDir, hdr.Name)
info := hdr.FileInfo()
if info.IsDir() {
if err := os.MkdirAll(path, info.Mode()); err != nil {
return errors.Annotate(err, "cannot create directory")
}
continue
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, info.Mode())
if err != nil {
return errors.Annotate(err, "cannot open file")
}
defer f.Close()
if _, err := io.Copy(f, tr); err != nil {
return errors.Annotate(err, "cannot copy file content")
}
}
if err := os.Rename(filepath.Join(tempDir, sourceDir), targetDir); err != nil {
return errors.Annotate(err, "cannot rename Juju GUI root directory")
}
return nil
} | [
"func",
"uncompressGUI",
"(",
"r",
"io",
".",
"Reader",
",",
"sourceDir",
",",
"targetDir",
"string",
")",
"error",
"{",
"tempDir",
",",
"err",
":=",
"ioutil",
".",
"TempDir",
"(",
"filepath",
".",
"Join",
"(",
"targetDir",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"os",
".",
"Remove",
"(",
"tempDir",
")",
"\n",
"tr",
":=",
"tar",
".",
"NewReader",
"(",
"bzip2",
".",
"NewReader",
"(",
"r",
")",
")",
"\n",
"for",
"{",
"hdr",
",",
"err",
":=",
"tr",
".",
"Next",
"(",
")",
"\n",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"break",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"hdr",
".",
"Name",
"!=",
"sourceDir",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"hdr",
".",
"Name",
",",
"sourceDir",
"+",
"\"",
"\"",
")",
"{",
"continue",
"\n",
"}",
"\n",
"path",
":=",
"filepath",
".",
"Join",
"(",
"tempDir",
",",
"hdr",
".",
"Name",
")",
"\n",
"info",
":=",
"hdr",
".",
"FileInfo",
"(",
")",
"\n",
"if",
"info",
".",
"IsDir",
"(",
")",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"path",
",",
"info",
".",
"Mode",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"path",
",",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_TRUNC",
"|",
"os",
".",
"O_WRONLY",
",",
"info",
".",
"Mode",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"f",
",",
"tr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"os",
".",
"Rename",
"(",
"filepath",
".",
"Join",
"(",
"tempDir",
",",
"sourceDir",
")",
",",
"targetDir",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // uncompressGUI uncompresses the tar.bz2 Juju GUI archive provided in r.
// The sourceDir directory included in the tar archive is copied to targetDir. | [
"uncompressGUI",
"uncompresses",
"the",
"tar",
".",
"bz2",
"Juju",
"GUI",
"archive",
"provided",
"in",
"r",
".",
"The",
"sourceDir",
"directory",
"included",
"in",
"the",
"tar",
"archive",
"is",
"copied",
"to",
"targetDir",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L204-L243 |
154,839 | juju/juju | apiserver/gui.go | serveStatic | func (h *guiHandler) serveStatic(w http.ResponseWriter, req *http.Request) {
logger.Debugf("serving Juju GUI static files")
staticDir := filepath.Join(h.rootDir, "static")
fs := http.FileServer(http.Dir(staticDir))
http.StripPrefix(h.hashedPath("static/"), fs).ServeHTTP(w, req)
} | go | func (h *guiHandler) serveStatic(w http.ResponseWriter, req *http.Request) {
logger.Debugf("serving Juju GUI static files")
staticDir := filepath.Join(h.rootDir, "static")
fs := http.FileServer(http.Dir(staticDir))
http.StripPrefix(h.hashedPath("static/"), fs).ServeHTTP(w, req)
} | [
"func",
"(",
"h",
"*",
"guiHandler",
")",
"serveStatic",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"staticDir",
":=",
"filepath",
".",
"Join",
"(",
"h",
".",
"rootDir",
",",
"\"",
"\"",
")",
"\n",
"fs",
":=",
"http",
".",
"FileServer",
"(",
"http",
".",
"Dir",
"(",
"staticDir",
")",
")",
"\n",
"http",
".",
"StripPrefix",
"(",
"h",
".",
"hashedPath",
"(",
"\"",
"\"",
")",
",",
"fs",
")",
".",
"ServeHTTP",
"(",
"w",
",",
"req",
")",
"\n",
"}"
] | // serveStatic serves the GUI static files. | [
"serveStatic",
"serves",
"the",
"GUI",
"static",
"files",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L254-L259 |
154,840 | juju/juju | apiserver/gui.go | serveCombo | func (h *guiHandler) serveCombo(w http.ResponseWriter, req *http.Request) {
logger.Debugf("serving Juju GUI combined files")
ctype := ""
// The combo query is like /combo/?path/to/file1&path/to/file2 ...
parts := strings.Split(req.URL.RawQuery, "&")
paths := make([]string, 0, len(parts))
for _, p := range parts {
fpath, err := getGUIComboPath(h.rootDir, p)
if err != nil {
writeError(w, errors.Annotate(err, "cannot combine files"))
return
}
if fpath == "" {
continue
}
paths = append(paths, fpath)
// Assume the Juju GUI does not mix different content types when
// combining contents.
if ctype == "" {
ctype = mime.TypeByExtension(filepath.Ext(fpath))
}
}
w.Header().Set("Content-Type", ctype)
for _, fpath := range paths {
sendGUIComboFile(w, fpath)
}
} | go | func (h *guiHandler) serveCombo(w http.ResponseWriter, req *http.Request) {
logger.Debugf("serving Juju GUI combined files")
ctype := ""
// The combo query is like /combo/?path/to/file1&path/to/file2 ...
parts := strings.Split(req.URL.RawQuery, "&")
paths := make([]string, 0, len(parts))
for _, p := range parts {
fpath, err := getGUIComboPath(h.rootDir, p)
if err != nil {
writeError(w, errors.Annotate(err, "cannot combine files"))
return
}
if fpath == "" {
continue
}
paths = append(paths, fpath)
// Assume the Juju GUI does not mix different content types when
// combining contents.
if ctype == "" {
ctype = mime.TypeByExtension(filepath.Ext(fpath))
}
}
w.Header().Set("Content-Type", ctype)
for _, fpath := range paths {
sendGUIComboFile(w, fpath)
}
} | [
"func",
"(",
"h",
"*",
"guiHandler",
")",
"serveCombo",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"ctype",
":=",
"\"",
"\"",
"\n",
"// The combo query is like /combo/?path/to/file1&path/to/file2 ...",
"parts",
":=",
"strings",
".",
"Split",
"(",
"req",
".",
"URL",
".",
"RawQuery",
",",
"\"",
"\"",
")",
"\n",
"paths",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"parts",
")",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"parts",
"{",
"fpath",
",",
"err",
":=",
"getGUIComboPath",
"(",
"h",
".",
"rootDir",
",",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"fpath",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"paths",
"=",
"append",
"(",
"paths",
",",
"fpath",
")",
"\n",
"// Assume the Juju GUI does not mix different content types when",
"// combining contents.",
"if",
"ctype",
"==",
"\"",
"\"",
"{",
"ctype",
"=",
"mime",
".",
"TypeByExtension",
"(",
"filepath",
".",
"Ext",
"(",
"fpath",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"ctype",
")",
"\n",
"for",
"_",
",",
"fpath",
":=",
"range",
"paths",
"{",
"sendGUIComboFile",
"(",
"w",
",",
"fpath",
")",
"\n",
"}",
"\n",
"}"
] | // serveCombo serves the GUI JavaScript and CSS files, dynamically combined. | [
"serveCombo",
"serves",
"the",
"GUI",
"JavaScript",
"and",
"CSS",
"files",
"dynamically",
"combined",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L262-L288 |
154,841 | juju/juju | apiserver/gui.go | serveIndex | func (h *guiHandler) serveIndex(w http.ResponseWriter, req *http.Request) {
logger.Debugf("serving Juju GUI index")
spriteFile := filepath.Join(h.rootDir, spritePath)
spriteContent, err := ioutil.ReadFile(spriteFile)
if err != nil {
writeError(w, errors.Annotate(err, "cannot read sprite file"))
return
}
tmpl := filepath.Join(h.rootDir, "templates", "index.html.go")
if err := renderGUITemplate(w, tmpl, map[string]interface{}{
// staticURL holds the root of the static hierarchy, hence why the
// empty string is used here.
"staticURL": h.hashedPath(""),
"comboURL": h.hashedPath("combo"),
"configURL": h.hashedPath(getConfigPath(req.URL.Path, h.ctxt)),
// TODO frankban: make it possible to enable debug.
"debug": false,
"spriteContent": string(spriteContent),
}); err != nil {
writeError(w, err)
}
} | go | func (h *guiHandler) serveIndex(w http.ResponseWriter, req *http.Request) {
logger.Debugf("serving Juju GUI index")
spriteFile := filepath.Join(h.rootDir, spritePath)
spriteContent, err := ioutil.ReadFile(spriteFile)
if err != nil {
writeError(w, errors.Annotate(err, "cannot read sprite file"))
return
}
tmpl := filepath.Join(h.rootDir, "templates", "index.html.go")
if err := renderGUITemplate(w, tmpl, map[string]interface{}{
// staticURL holds the root of the static hierarchy, hence why the
// empty string is used here.
"staticURL": h.hashedPath(""),
"comboURL": h.hashedPath("combo"),
"configURL": h.hashedPath(getConfigPath(req.URL.Path, h.ctxt)),
// TODO frankban: make it possible to enable debug.
"debug": false,
"spriteContent": string(spriteContent),
}); err != nil {
writeError(w, err)
}
} | [
"func",
"(",
"h",
"*",
"guiHandler",
")",
"serveIndex",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"spriteFile",
":=",
"filepath",
".",
"Join",
"(",
"h",
".",
"rootDir",
",",
"spritePath",
")",
"\n",
"spriteContent",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"spriteFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"tmpl",
":=",
"filepath",
".",
"Join",
"(",
"h",
".",
"rootDir",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"renderGUITemplate",
"(",
"w",
",",
"tmpl",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"// staticURL holds the root of the static hierarchy, hence why the",
"// empty string is used here.",
"\"",
"\"",
":",
"h",
".",
"hashedPath",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
":",
"h",
".",
"hashedPath",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
":",
"h",
".",
"hashedPath",
"(",
"getConfigPath",
"(",
"req",
".",
"URL",
".",
"Path",
",",
"h",
".",
"ctxt",
")",
")",
",",
"// TODO frankban: make it possible to enable debug.",
"\"",
"\"",
":",
"false",
",",
"\"",
"\"",
":",
"string",
"(",
"spriteContent",
")",
",",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // serveIndex serves the GUI index file. | [
"serveIndex",
"serves",
"the",
"GUI",
"index",
"file",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L324-L345 |
154,842 | juju/juju | apiserver/gui.go | getConfigPath | func getConfigPath(path string, ctxt httpContext) string {
configPath := "config.js"
// Handle requests from old clients, in which the model UUID is a fragment
// in the request path. If this is the case, we also need to include the
// UUID in the GUI base URL.
uuid := uuidFromPath(path)
if uuid != "" {
return fmt.Sprintf("%[1]s?model-uuid=%[2]s&base-postfix=%[2]s/", configPath, uuid)
}
st := ctxt.srv.shared.statePool.SystemState()
if isNewGUI(st) {
// This is the proper case in which a new GUI is being served from a
// new URL. No query must be included in the config path.
return configPath
}
// Possibly handle requests to the new "/u/{user}/{model}" path, but
// made from an old version of the GUI, which didn't connect to the
// model based on the path.
uuid, user, model := modelInfoFromPath(path, st, ctxt.srv.shared.statePool)
if uuid != "" {
return fmt.Sprintf("%s?model-uuid=%s&base-postfix=u/%s/%s/", configPath, uuid, user, model)
}
return configPath
} | go | func getConfigPath(path string, ctxt httpContext) string {
configPath := "config.js"
// Handle requests from old clients, in which the model UUID is a fragment
// in the request path. If this is the case, we also need to include the
// UUID in the GUI base URL.
uuid := uuidFromPath(path)
if uuid != "" {
return fmt.Sprintf("%[1]s?model-uuid=%[2]s&base-postfix=%[2]s/", configPath, uuid)
}
st := ctxt.srv.shared.statePool.SystemState()
if isNewGUI(st) {
// This is the proper case in which a new GUI is being served from a
// new URL. No query must be included in the config path.
return configPath
}
// Possibly handle requests to the new "/u/{user}/{model}" path, but
// made from an old version of the GUI, which didn't connect to the
// model based on the path.
uuid, user, model := modelInfoFromPath(path, st, ctxt.srv.shared.statePool)
if uuid != "" {
return fmt.Sprintf("%s?model-uuid=%s&base-postfix=u/%s/%s/", configPath, uuid, user, model)
}
return configPath
} | [
"func",
"getConfigPath",
"(",
"path",
"string",
",",
"ctxt",
"httpContext",
")",
"string",
"{",
"configPath",
":=",
"\"",
"\"",
"\n",
"// Handle requests from old clients, in which the model UUID is a fragment",
"// in the request path. If this is the case, we also need to include the",
"// UUID in the GUI base URL.",
"uuid",
":=",
"uuidFromPath",
"(",
"path",
")",
"\n",
"if",
"uuid",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"configPath",
",",
"uuid",
")",
"\n",
"}",
"\n",
"st",
":=",
"ctxt",
".",
"srv",
".",
"shared",
".",
"statePool",
".",
"SystemState",
"(",
")",
"\n",
"if",
"isNewGUI",
"(",
"st",
")",
"{",
"// This is the proper case in which a new GUI is being served from a",
"// new URL. No query must be included in the config path.",
"return",
"configPath",
"\n",
"}",
"\n",
"// Possibly handle requests to the new \"/u/{user}/{model}\" path, but",
"// made from an old version of the GUI, which didn't connect to the",
"// model based on the path.",
"uuid",
",",
"user",
",",
"model",
":=",
"modelInfoFromPath",
"(",
"path",
",",
"st",
",",
"ctxt",
".",
"srv",
".",
"shared",
".",
"statePool",
")",
"\n",
"if",
"uuid",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"configPath",
",",
"uuid",
",",
"user",
",",
"model",
")",
"\n",
"}",
"\n",
"return",
"configPath",
"\n",
"}"
] | // getConfigPath returns the appropriate GUI config path for the given request
// path. | [
"getConfigPath",
"returns",
"the",
"appropriate",
"GUI",
"config",
"path",
"for",
"the",
"given",
"request",
"path",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L349-L372 |
154,843 | juju/juju | apiserver/gui.go | uuidFromPath | func uuidFromPath(path string) string {
path = strings.TrimPrefix(path, guiURLPathPrefix)
uuid := strings.SplitN(path, "/", 2)[0]
if names.IsValidModel(uuid) {
return uuid
}
return ""
} | go | func uuidFromPath(path string) string {
path = strings.TrimPrefix(path, guiURLPathPrefix)
uuid := strings.SplitN(path, "/", 2)[0]
if names.IsValidModel(uuid) {
return uuid
}
return ""
} | [
"func",
"uuidFromPath",
"(",
"path",
"string",
")",
"string",
"{",
"path",
"=",
"strings",
".",
"TrimPrefix",
"(",
"path",
",",
"guiURLPathPrefix",
")",
"\n",
"uuid",
":=",
"strings",
".",
"SplitN",
"(",
"path",
",",
"\"",
"\"",
",",
"2",
")",
"[",
"0",
"]",
"\n",
"if",
"names",
".",
"IsValidModel",
"(",
"uuid",
")",
"{",
"return",
"uuid",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // uuidFromPath checks whether the given path includes a fragment with a
// valid model UUID. An empty string is returned if the model is not found. | [
"uuidFromPath",
"checks",
"whether",
"the",
"given",
"path",
"includes",
"a",
"fragment",
"with",
"a",
"valid",
"model",
"UUID",
".",
"An",
"empty",
"string",
"is",
"returned",
"if",
"the",
"model",
"is",
"not",
"found",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L376-L383 |
154,844 | juju/juju | apiserver/gui.go | isNewGUI | func isNewGUI(st *state.State) bool {
vers, err := st.GUIVersion()
if err != nil {
logger.Warningf("cannot retrieve GUI version: %v", err)
// Assume a recent version of the GUI is being served.
return true
}
return vers.Major > 2 || (vers.Major == 2 && vers.Minor >= 3)
} | go | func isNewGUI(st *state.State) bool {
vers, err := st.GUIVersion()
if err != nil {
logger.Warningf("cannot retrieve GUI version: %v", err)
// Assume a recent version of the GUI is being served.
return true
}
return vers.Major > 2 || (vers.Major == 2 && vers.Minor >= 3)
} | [
"func",
"isNewGUI",
"(",
"st",
"*",
"state",
".",
"State",
")",
"bool",
"{",
"vers",
",",
"err",
":=",
"st",
".",
"GUIVersion",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"// Assume a recent version of the GUI is being served.",
"return",
"true",
"\n",
"}",
"\n",
"return",
"vers",
".",
"Major",
">",
"2",
"||",
"(",
"vers",
".",
"Major",
"==",
"2",
"&&",
"vers",
".",
"Minor",
">=",
"3",
")",
"\n",
"}"
] | // isNewGUI reports whether the version of the current GUI is >= 2.3.0. | [
"isNewGUI",
"reports",
"whether",
"the",
"version",
"of",
"the",
"current",
"GUI",
"is",
">",
"=",
"2",
".",
"3",
".",
"0",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L413-L421 |
154,845 | juju/juju | apiserver/gui.go | serveConfig | func (h *guiHandler) serveConfig(w http.ResponseWriter, req *http.Request) {
logger.Debugf("serving Juju GUI configuration")
st, err := h.ctxt.stateForRequestUnauthenticated(req)
if err != nil {
writeError(w, errors.Annotate(err, "cannot open state"))
return
}
ctrl, err := st.ControllerConfig()
if err != nil {
writeError(w, errors.Annotate(err, "cannot open controller config"))
return
}
w.Header().Set("Content-Type", jsMimeType)
base := h.basePath
// These query parameters may be set by the index handler.
uuid := req.URL.Query().Get("model-uuid")
if uuid != "" {
base += req.URL.Query().Get("base-postfix")
}
tmpl := filepath.Join(h.rootDir, "templates", "config.js.go")
if err := renderGUITemplate(w, tmpl, map[string]interface{}{
"base": base,
"bakeryEnabled": ctrl.IdentityURL() != "",
"controllerSocket": "/api",
"charmstoreURL": ctrl.CharmStoreURL(),
"host": req.Host,
"socket": "/model/$uuid/api",
// staticURL holds the root of the static hierarchy, hence why the
// empty string is used here.
"staticURL": h.hashedPath(""),
"uuid": uuid,
"version": jujuversion.Current.String(),
}); err != nil {
writeError(w, err)
}
} | go | func (h *guiHandler) serveConfig(w http.ResponseWriter, req *http.Request) {
logger.Debugf("serving Juju GUI configuration")
st, err := h.ctxt.stateForRequestUnauthenticated(req)
if err != nil {
writeError(w, errors.Annotate(err, "cannot open state"))
return
}
ctrl, err := st.ControllerConfig()
if err != nil {
writeError(w, errors.Annotate(err, "cannot open controller config"))
return
}
w.Header().Set("Content-Type", jsMimeType)
base := h.basePath
// These query parameters may be set by the index handler.
uuid := req.URL.Query().Get("model-uuid")
if uuid != "" {
base += req.URL.Query().Get("base-postfix")
}
tmpl := filepath.Join(h.rootDir, "templates", "config.js.go")
if err := renderGUITemplate(w, tmpl, map[string]interface{}{
"base": base,
"bakeryEnabled": ctrl.IdentityURL() != "",
"controllerSocket": "/api",
"charmstoreURL": ctrl.CharmStoreURL(),
"host": req.Host,
"socket": "/model/$uuid/api",
// staticURL holds the root of the static hierarchy, hence why the
// empty string is used here.
"staticURL": h.hashedPath(""),
"uuid": uuid,
"version": jujuversion.Current.String(),
}); err != nil {
writeError(w, err)
}
} | [
"func",
"(",
"h",
"*",
"guiHandler",
")",
"serveConfig",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"st",
",",
"err",
":=",
"h",
".",
"ctxt",
".",
"stateForRequestUnauthenticated",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"ctrl",
",",
"err",
":=",
"st",
".",
"ControllerConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"jsMimeType",
")",
"\n",
"base",
":=",
"h",
".",
"basePath",
"\n",
"// These query parameters may be set by the index handler.",
"uuid",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"uuid",
"!=",
"\"",
"\"",
"{",
"base",
"+=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"tmpl",
":=",
"filepath",
".",
"Join",
"(",
"h",
".",
"rootDir",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"renderGUITemplate",
"(",
"w",
",",
"tmpl",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"base",
",",
"\"",
"\"",
":",
"ctrl",
".",
"IdentityURL",
"(",
")",
"!=",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"ctrl",
".",
"CharmStoreURL",
"(",
")",
",",
"\"",
"\"",
":",
"req",
".",
"Host",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"// staticURL holds the root of the static hierarchy, hence why the",
"// empty string is used here.",
"\"",
"\"",
":",
"h",
".",
"hashedPath",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
":",
"uuid",
",",
"\"",
"\"",
":",
"jujuversion",
".",
"Current",
".",
"String",
"(",
")",
",",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // serveConfig serves the Juju GUI JavaScript configuration file. | [
"serveConfig",
"serves",
"the",
"Juju",
"GUI",
"JavaScript",
"configuration",
"file",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L424-L459 |
154,846 | juju/juju | apiserver/gui.go | handleGet | func (h *guiArchiveHandler) handleGet(w http.ResponseWriter, req *http.Request) error {
// Open the GUI archive storage.
st, err := h.ctxt.stateForRequestUnauthenticated(req)
if err != nil {
return errors.Annotate(err, "cannot open state")
}
defer st.Release()
storage, err := st.GUIStorage()
if err != nil {
return errors.Annotate(err, "cannot open GUI storage")
}
defer storage.Close()
// Retrieve metadata information.
allMeta, err := storage.AllMetadata()
if err != nil {
return errors.Annotate(err, "cannot retrieve GUI metadata")
}
// Prepare and send the response.
var currentVersion string
vers, err := st.GUIVersion()
if err == nil {
currentVersion = vers.String()
} else if !errors.IsNotFound(err) {
return errors.Annotate(err, "cannot retrieve current GUI version")
}
versions := make([]params.GUIArchiveVersion, len(allMeta))
for i, m := range allMeta {
vers, err := version.Parse(m.Version)
if err != nil {
return errors.Annotate(err, "cannot parse GUI version")
}
versions[i] = params.GUIArchiveVersion{
Version: vers,
SHA256: m.SHA256,
Current: m.Version == currentVersion,
}
}
return errors.Trace(sendStatusAndJSON(w, http.StatusOK, params.GUIArchiveResponse{
Versions: versions,
}))
} | go | func (h *guiArchiveHandler) handleGet(w http.ResponseWriter, req *http.Request) error {
// Open the GUI archive storage.
st, err := h.ctxt.stateForRequestUnauthenticated(req)
if err != nil {
return errors.Annotate(err, "cannot open state")
}
defer st.Release()
storage, err := st.GUIStorage()
if err != nil {
return errors.Annotate(err, "cannot open GUI storage")
}
defer storage.Close()
// Retrieve metadata information.
allMeta, err := storage.AllMetadata()
if err != nil {
return errors.Annotate(err, "cannot retrieve GUI metadata")
}
// Prepare and send the response.
var currentVersion string
vers, err := st.GUIVersion()
if err == nil {
currentVersion = vers.String()
} else if !errors.IsNotFound(err) {
return errors.Annotate(err, "cannot retrieve current GUI version")
}
versions := make([]params.GUIArchiveVersion, len(allMeta))
for i, m := range allMeta {
vers, err := version.Parse(m.Version)
if err != nil {
return errors.Annotate(err, "cannot parse GUI version")
}
versions[i] = params.GUIArchiveVersion{
Version: vers,
SHA256: m.SHA256,
Current: m.Version == currentVersion,
}
}
return errors.Trace(sendStatusAndJSON(w, http.StatusOK, params.GUIArchiveResponse{
Versions: versions,
}))
} | [
"func",
"(",
"h",
"*",
"guiArchiveHandler",
")",
"handleGet",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"// Open the GUI archive storage.",
"st",
",",
"err",
":=",
"h",
".",
"ctxt",
".",
"stateForRequestUnauthenticated",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"st",
".",
"Release",
"(",
")",
"\n",
"storage",
",",
"err",
":=",
"st",
".",
"GUIStorage",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"storage",
".",
"Close",
"(",
")",
"\n\n",
"// Retrieve metadata information.",
"allMeta",
",",
"err",
":=",
"storage",
".",
"AllMetadata",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Prepare and send the response.",
"var",
"currentVersion",
"string",
"\n",
"vers",
",",
"err",
":=",
"st",
".",
"GUIVersion",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"currentVersion",
"=",
"vers",
".",
"String",
"(",
")",
"\n",
"}",
"else",
"if",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"versions",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"GUIArchiveVersion",
",",
"len",
"(",
"allMeta",
")",
")",
"\n",
"for",
"i",
",",
"m",
":=",
"range",
"allMeta",
"{",
"vers",
",",
"err",
":=",
"version",
".",
"Parse",
"(",
"m",
".",
"Version",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"versions",
"[",
"i",
"]",
"=",
"params",
".",
"GUIArchiveVersion",
"{",
"Version",
":",
"vers",
",",
"SHA256",
":",
"m",
".",
"SHA256",
",",
"Current",
":",
"m",
".",
"Version",
"==",
"currentVersion",
",",
"}",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"sendStatusAndJSON",
"(",
"w",
",",
"http",
".",
"StatusOK",
",",
"params",
".",
"GUIArchiveResponse",
"{",
"Versions",
":",
"versions",
",",
"}",
")",
")",
"\n",
"}"
] | // handleGet returns information on Juju GUI archives in the controller. | [
"handleGet",
"returns",
"information",
"on",
"Juju",
"GUI",
"archives",
"in",
"the",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L510-L552 |
154,847 | juju/juju | apiserver/gui.go | handlePost | func (h *guiArchiveHandler) handlePost(w http.ResponseWriter, req *http.Request) error {
// Validate the request.
if ctype := req.Header.Get("Content-Type"); ctype != bzMimeType {
return errors.BadRequestf("invalid content type %q: expected %q", ctype, bzMimeType)
}
if err := req.ParseForm(); err != nil {
return errors.Annotate(err, "cannot parse form")
}
versParam := req.Form.Get("version")
if versParam == "" {
return errors.BadRequestf("version parameter not provided")
}
vers, err := version.Parse(versParam)
if err != nil {
return errors.BadRequestf("invalid version parameter %q", versParam)
}
hashParam := req.Form.Get("hash")
if hashParam == "" {
return errors.BadRequestf("hash parameter not provided")
}
if req.ContentLength == -1 {
return errors.BadRequestf("content length not provided")
}
// Open the GUI archive storage.
st, err := h.ctxt.stateForRequestAuthenticatedUser(req)
if err != nil {
return errors.Annotate(err, "cannot open state")
}
defer st.Release()
storage, err := st.GUIStorage()
if err != nil {
return errors.Annotate(err, "cannot open GUI storage")
}
defer storage.Close()
// Read and validate the archive data.
data, hash, err := readAndHash(req.Body)
size := int64(len(data))
if size != req.ContentLength {
return errors.BadRequestf("archive does not match provided content length")
}
if hash != hashParam {
return errors.BadRequestf("archive does not match provided hash")
}
// Add the archive to the GUI storage.
metadata := binarystorage.Metadata{
Version: vers.String(),
Size: size,
SHA256: hash,
}
if err := storage.Add(bytes.NewReader(data), metadata); err != nil {
return errors.Annotate(err, "cannot add GUI archive to storage")
}
// Prepare and return the response.
resp := params.GUIArchiveVersion{
Version: vers,
SHA256: hash,
}
if currentVers, err := st.GUIVersion(); err == nil {
if currentVers == vers {
resp.Current = true
}
} else if !errors.IsNotFound(err) {
return errors.Annotate(err, "cannot retrieve current GUI version")
}
return errors.Trace(sendStatusAndJSON(w, http.StatusOK, resp))
} | go | func (h *guiArchiveHandler) handlePost(w http.ResponseWriter, req *http.Request) error {
// Validate the request.
if ctype := req.Header.Get("Content-Type"); ctype != bzMimeType {
return errors.BadRequestf("invalid content type %q: expected %q", ctype, bzMimeType)
}
if err := req.ParseForm(); err != nil {
return errors.Annotate(err, "cannot parse form")
}
versParam := req.Form.Get("version")
if versParam == "" {
return errors.BadRequestf("version parameter not provided")
}
vers, err := version.Parse(versParam)
if err != nil {
return errors.BadRequestf("invalid version parameter %q", versParam)
}
hashParam := req.Form.Get("hash")
if hashParam == "" {
return errors.BadRequestf("hash parameter not provided")
}
if req.ContentLength == -1 {
return errors.BadRequestf("content length not provided")
}
// Open the GUI archive storage.
st, err := h.ctxt.stateForRequestAuthenticatedUser(req)
if err != nil {
return errors.Annotate(err, "cannot open state")
}
defer st.Release()
storage, err := st.GUIStorage()
if err != nil {
return errors.Annotate(err, "cannot open GUI storage")
}
defer storage.Close()
// Read and validate the archive data.
data, hash, err := readAndHash(req.Body)
size := int64(len(data))
if size != req.ContentLength {
return errors.BadRequestf("archive does not match provided content length")
}
if hash != hashParam {
return errors.BadRequestf("archive does not match provided hash")
}
// Add the archive to the GUI storage.
metadata := binarystorage.Metadata{
Version: vers.String(),
Size: size,
SHA256: hash,
}
if err := storage.Add(bytes.NewReader(data), metadata); err != nil {
return errors.Annotate(err, "cannot add GUI archive to storage")
}
// Prepare and return the response.
resp := params.GUIArchiveVersion{
Version: vers,
SHA256: hash,
}
if currentVers, err := st.GUIVersion(); err == nil {
if currentVers == vers {
resp.Current = true
}
} else if !errors.IsNotFound(err) {
return errors.Annotate(err, "cannot retrieve current GUI version")
}
return errors.Trace(sendStatusAndJSON(w, http.StatusOK, resp))
} | [
"func",
"(",
"h",
"*",
"guiArchiveHandler",
")",
"handlePost",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"// Validate the request.",
"if",
"ctype",
":=",
"req",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
";",
"ctype",
"!=",
"bzMimeType",
"{",
"return",
"errors",
".",
"BadRequestf",
"(",
"\"",
"\"",
",",
"ctype",
",",
"bzMimeType",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"req",
".",
"ParseForm",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"versParam",
":=",
"req",
".",
"Form",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"versParam",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"BadRequestf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"vers",
",",
"err",
":=",
"version",
".",
"Parse",
"(",
"versParam",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"BadRequestf",
"(",
"\"",
"\"",
",",
"versParam",
")",
"\n",
"}",
"\n",
"hashParam",
":=",
"req",
".",
"Form",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"hashParam",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"BadRequestf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"req",
".",
"ContentLength",
"==",
"-",
"1",
"{",
"return",
"errors",
".",
"BadRequestf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Open the GUI archive storage.",
"st",
",",
"err",
":=",
"h",
".",
"ctxt",
".",
"stateForRequestAuthenticatedUser",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"st",
".",
"Release",
"(",
")",
"\n",
"storage",
",",
"err",
":=",
"st",
".",
"GUIStorage",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"storage",
".",
"Close",
"(",
")",
"\n\n",
"// Read and validate the archive data.",
"data",
",",
"hash",
",",
"err",
":=",
"readAndHash",
"(",
"req",
".",
"Body",
")",
"\n",
"size",
":=",
"int64",
"(",
"len",
"(",
"data",
")",
")",
"\n",
"if",
"size",
"!=",
"req",
".",
"ContentLength",
"{",
"return",
"errors",
".",
"BadRequestf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"hash",
"!=",
"hashParam",
"{",
"return",
"errors",
".",
"BadRequestf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Add the archive to the GUI storage.",
"metadata",
":=",
"binarystorage",
".",
"Metadata",
"{",
"Version",
":",
"vers",
".",
"String",
"(",
")",
",",
"Size",
":",
"size",
",",
"SHA256",
":",
"hash",
",",
"}",
"\n",
"if",
"err",
":=",
"storage",
".",
"Add",
"(",
"bytes",
".",
"NewReader",
"(",
"data",
")",
",",
"metadata",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Prepare and return the response.",
"resp",
":=",
"params",
".",
"GUIArchiveVersion",
"{",
"Version",
":",
"vers",
",",
"SHA256",
":",
"hash",
",",
"}",
"\n",
"if",
"currentVers",
",",
"err",
":=",
"st",
".",
"GUIVersion",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"if",
"currentVers",
"==",
"vers",
"{",
"resp",
".",
"Current",
"=",
"true",
"\n",
"}",
"\n",
"}",
"else",
"if",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"sendStatusAndJSON",
"(",
"w",
",",
"http",
".",
"StatusOK",
",",
"resp",
")",
")",
"\n",
"}"
] | // handlePost is used to upload new Juju GUI archives to the controller. | [
"handlePost",
"is",
"used",
"to",
"upload",
"new",
"Juju",
"GUI",
"archives",
"to",
"the",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L555-L625 |
154,848 | juju/juju | apiserver/gui.go | handlePut | func (h *guiVersionHandler) handlePut(w http.ResponseWriter, req *http.Request) error {
// Validate the request.
if ctype := req.Header.Get("Content-Type"); ctype != params.ContentTypeJSON {
return errors.BadRequestf("invalid content type %q: expected %q", ctype, params.ContentTypeJSON)
}
// Authenticate the request and retrieve the Juju state.
st, err := h.ctxt.stateForRequestAuthenticatedUser(req)
if err != nil {
return errors.Annotate(err, "cannot open state")
}
defer st.Release()
var selected params.GUIVersionRequest
decoder := json.NewDecoder(req.Body)
if err := decoder.Decode(&selected); err != nil {
return errors.NewBadRequest(err, "invalid request body")
}
// Switch to the provided GUI version.
if err = st.GUISetVersion(selected.Version); err != nil {
return errors.Trace(err)
}
return nil
} | go | func (h *guiVersionHandler) handlePut(w http.ResponseWriter, req *http.Request) error {
// Validate the request.
if ctype := req.Header.Get("Content-Type"); ctype != params.ContentTypeJSON {
return errors.BadRequestf("invalid content type %q: expected %q", ctype, params.ContentTypeJSON)
}
// Authenticate the request and retrieve the Juju state.
st, err := h.ctxt.stateForRequestAuthenticatedUser(req)
if err != nil {
return errors.Annotate(err, "cannot open state")
}
defer st.Release()
var selected params.GUIVersionRequest
decoder := json.NewDecoder(req.Body)
if err := decoder.Decode(&selected); err != nil {
return errors.NewBadRequest(err, "invalid request body")
}
// Switch to the provided GUI version.
if err = st.GUISetVersion(selected.Version); err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"(",
"h",
"*",
"guiVersionHandler",
")",
"handlePut",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"// Validate the request.",
"if",
"ctype",
":=",
"req",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
";",
"ctype",
"!=",
"params",
".",
"ContentTypeJSON",
"{",
"return",
"errors",
".",
"BadRequestf",
"(",
"\"",
"\"",
",",
"ctype",
",",
"params",
".",
"ContentTypeJSON",
")",
"\n",
"}",
"\n\n",
"// Authenticate the request and retrieve the Juju state.",
"st",
",",
"err",
":=",
"h",
".",
"ctxt",
".",
"stateForRequestAuthenticatedUser",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"st",
".",
"Release",
"(",
")",
"\n\n",
"var",
"selected",
"params",
".",
"GUIVersionRequest",
"\n",
"decoder",
":=",
"json",
".",
"NewDecoder",
"(",
"req",
".",
"Body",
")",
"\n",
"if",
"err",
":=",
"decoder",
".",
"Decode",
"(",
"&",
"selected",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"NewBadRequest",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Switch to the provided GUI version.",
"if",
"err",
"=",
"st",
".",
"GUISetVersion",
"(",
"selected",
".",
"Version",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // handlePut is used to switch to a specific Juju GUI version. | [
"handlePut",
"is",
"used",
"to",
"switch",
"to",
"a",
"specific",
"Juju",
"GUI",
"version",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/gui.go#L649-L673 |
154,849 | juju/juju | provider/gce/google/auth.go | newConnection | func newConnection(creds *Credentials) (*compute.Service, error) {
jsonKey := creds.JSONKey
if jsonKey == nil {
built, err := creds.buildJSONKey()
if err != nil {
return nil, errors.Trace(err)
}
jsonKey = built
}
cfg, err := goauth2.JWTConfigFromJSON(jsonKey, driverScopes...)
if err != nil {
return nil, errors.Trace(err)
}
client := cfg.Client(oauth2.NoContext)
service, err := compute.New(client)
return service, errors.Trace(err)
} | go | func newConnection(creds *Credentials) (*compute.Service, error) {
jsonKey := creds.JSONKey
if jsonKey == nil {
built, err := creds.buildJSONKey()
if err != nil {
return nil, errors.Trace(err)
}
jsonKey = built
}
cfg, err := goauth2.JWTConfigFromJSON(jsonKey, driverScopes...)
if err != nil {
return nil, errors.Trace(err)
}
client := cfg.Client(oauth2.NoContext)
service, err := compute.New(client)
return service, errors.Trace(err)
} | [
"func",
"newConnection",
"(",
"creds",
"*",
"Credentials",
")",
"(",
"*",
"compute",
".",
"Service",
",",
"error",
")",
"{",
"jsonKey",
":=",
"creds",
".",
"JSONKey",
"\n",
"if",
"jsonKey",
"==",
"nil",
"{",
"built",
",",
"err",
":=",
"creds",
".",
"buildJSONKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"jsonKey",
"=",
"built",
"\n",
"}",
"\n",
"cfg",
",",
"err",
":=",
"goauth2",
".",
"JWTConfigFromJSON",
"(",
"jsonKey",
",",
"driverScopes",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"client",
":=",
"cfg",
".",
"Client",
"(",
"oauth2",
".",
"NoContext",
")",
"\n",
"service",
",",
"err",
":=",
"compute",
".",
"New",
"(",
"client",
")",
"\n",
"return",
"service",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // newConnection opens a new low-level connection to the GCE API using
// the Auth's data and returns it. This includes building the
// OAuth-wrapping network transport. | [
"newConnection",
"opens",
"a",
"new",
"low",
"-",
"level",
"connection",
"to",
"the",
"GCE",
"API",
"using",
"the",
"Auth",
"s",
"data",
"and",
"returns",
"it",
".",
"This",
"includes",
"building",
"the",
"OAuth",
"-",
"wrapping",
"network",
"transport",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/auth.go#L23-L39 |
154,850 | juju/juju | apiserver/common/networkingcommon/networkconfigapi.go | SetObservedNetworkConfig | func (api *NetworkConfigAPI) SetObservedNetworkConfig(args params.SetMachineNetworkConfig) error {
m, err := api.getMachineForSettingNetworkConfig(args.Tag)
if err != nil {
return errors.Trace(err)
}
if m.IsContainer() {
return nil
}
observedConfig := args.Config
logger.Tracef("observed network config of machine %q: %+v", m.Id(), observedConfig)
if len(observedConfig) == 0 {
logger.Infof("not updating machine %q network config: no observed network config found", m.Id())
return nil
}
providerConfig, err := api.getOneMachineProviderNetworkConfig(m)
if errors.IsNotProvisioned(err) {
logger.Infof("not updating machine %q network config: %v", m.Id(), err)
return nil
}
if err != nil {
return errors.Trace(err)
}
mergedConfig := observedConfig
if len(providerConfig) != 0 {
mergedConfig = MergeProviderAndObservedNetworkConfigs(providerConfig, observedConfig)
logger.Tracef("merged observed and provider network config for machine %q: %+v", m.Id(), mergedConfig)
}
mergedConfig, err = api.fixUpFanSubnets(mergedConfig)
if err != nil {
return errors.Trace(err)
}
return api.setOneMachineNetworkConfig(m, mergedConfig)
} | go | func (api *NetworkConfigAPI) SetObservedNetworkConfig(args params.SetMachineNetworkConfig) error {
m, err := api.getMachineForSettingNetworkConfig(args.Tag)
if err != nil {
return errors.Trace(err)
}
if m.IsContainer() {
return nil
}
observedConfig := args.Config
logger.Tracef("observed network config of machine %q: %+v", m.Id(), observedConfig)
if len(observedConfig) == 0 {
logger.Infof("not updating machine %q network config: no observed network config found", m.Id())
return nil
}
providerConfig, err := api.getOneMachineProviderNetworkConfig(m)
if errors.IsNotProvisioned(err) {
logger.Infof("not updating machine %q network config: %v", m.Id(), err)
return nil
}
if err != nil {
return errors.Trace(err)
}
mergedConfig := observedConfig
if len(providerConfig) != 0 {
mergedConfig = MergeProviderAndObservedNetworkConfigs(providerConfig, observedConfig)
logger.Tracef("merged observed and provider network config for machine %q: %+v", m.Id(), mergedConfig)
}
mergedConfig, err = api.fixUpFanSubnets(mergedConfig)
if err != nil {
return errors.Trace(err)
}
return api.setOneMachineNetworkConfig(m, mergedConfig)
} | [
"func",
"(",
"api",
"*",
"NetworkConfigAPI",
")",
"SetObservedNetworkConfig",
"(",
"args",
"params",
".",
"SetMachineNetworkConfig",
")",
"error",
"{",
"m",
",",
"err",
":=",
"api",
".",
"getMachineForSettingNetworkConfig",
"(",
"args",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"m",
".",
"IsContainer",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"observedConfig",
":=",
"args",
".",
"Config",
"\n",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"m",
".",
"Id",
"(",
")",
",",
"observedConfig",
")",
"\n",
"if",
"len",
"(",
"observedConfig",
")",
"==",
"0",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"m",
".",
"Id",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"providerConfig",
",",
"err",
":=",
"api",
".",
"getOneMachineProviderNetworkConfig",
"(",
"m",
")",
"\n",
"if",
"errors",
".",
"IsNotProvisioned",
"(",
"err",
")",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"m",
".",
"Id",
"(",
")",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"mergedConfig",
":=",
"observedConfig",
"\n",
"if",
"len",
"(",
"providerConfig",
")",
"!=",
"0",
"{",
"mergedConfig",
"=",
"MergeProviderAndObservedNetworkConfigs",
"(",
"providerConfig",
",",
"observedConfig",
")",
"\n",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"m",
".",
"Id",
"(",
")",
",",
"mergedConfig",
")",
"\n",
"}",
"\n\n",
"mergedConfig",
",",
"err",
"=",
"api",
".",
"fixUpFanSubnets",
"(",
"mergedConfig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"api",
".",
"setOneMachineNetworkConfig",
"(",
"m",
",",
"mergedConfig",
")",
"\n",
"}"
] | // SetObservedNetworkConfig reads the network config for the machine identified
// by the input args. This config is merged with the new network config supplied
// in the same args and updated if it has changed. | [
"SetObservedNetworkConfig",
"reads",
"the",
"network",
"config",
"for",
"the",
"machine",
"identified",
"by",
"the",
"input",
"args",
".",
"This",
"config",
"is",
"merged",
"with",
"the",
"new",
"network",
"config",
"supplied",
"in",
"the",
"same",
"args",
"and",
"updated",
"if",
"it",
"has",
"changed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/networkingcommon/networkconfigapi.go#L40-L75 |
154,851 | juju/juju | apiserver/common/networkingcommon/networkconfigapi.go | SetProviderNetworkConfig | func (api *NetworkConfigAPI) SetProviderNetworkConfig(args params.Entities) (params.ErrorResults, error) {
logger.Tracef("SetProviderNetworkConfig %+v", args)
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
for i, arg := range args.Entities {
m, err := api.getMachineForSettingNetworkConfig(arg.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if m.IsContainer() {
continue
}
providerConfig, err := api.getOneMachineProviderNetworkConfig(m)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
} else if len(providerConfig) == 0 {
continue
}
logger.Tracef("provider network config for %q: %+v", m.Id(), providerConfig)
if err := api.setOneMachineNetworkConfig(m, providerConfig); err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
}
return result, nil
} | go | func (api *NetworkConfigAPI) SetProviderNetworkConfig(args params.Entities) (params.ErrorResults, error) {
logger.Tracef("SetProviderNetworkConfig %+v", args)
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
for i, arg := range args.Entities {
m, err := api.getMachineForSettingNetworkConfig(arg.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if m.IsContainer() {
continue
}
providerConfig, err := api.getOneMachineProviderNetworkConfig(m)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
} else if len(providerConfig) == 0 {
continue
}
logger.Tracef("provider network config for %q: %+v", m.Id(), providerConfig)
if err := api.setOneMachineNetworkConfig(m, providerConfig); err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
}
return result, nil
} | [
"func",
"(",
"api",
"*",
"NetworkConfigAPI",
")",
"SetProviderNetworkConfig",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"args",
")",
"\n",
"result",
":=",
"params",
".",
"ErrorResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"ErrorResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n\n",
"for",
"i",
",",
"arg",
":=",
"range",
"args",
".",
"Entities",
"{",
"m",
",",
"err",
":=",
"api",
".",
"getMachineForSettingNetworkConfig",
"(",
"arg",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"if",
"m",
".",
"IsContainer",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"providerConfig",
",",
"err",
":=",
"api",
".",
"getOneMachineProviderNetworkConfig",
"(",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"else",
"if",
"len",
"(",
"providerConfig",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"m",
".",
"Id",
"(",
")",
",",
"providerConfig",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"setOneMachineNetworkConfig",
"(",
"m",
",",
"providerConfig",
")",
";",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // SetProviderNetworkConfig sets the provider supplied network configuration
// contained in the input args against each machine supplied with said args. | [
"SetProviderNetworkConfig",
"sets",
"the",
"provider",
"supplied",
"network",
"configuration",
"contained",
"in",
"the",
"input",
"args",
"against",
"each",
"machine",
"supplied",
"with",
"said",
"args",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/networkingcommon/networkconfigapi.go#L114-L146 |
154,852 | juju/juju | state/presence/pingbatcher.go | NewPingBatcher | func NewPingBatcher(base *mgo.Collection, flushInterval time.Duration) *PingBatcher {
var pings *mgo.Collection
if base != nil {
pings = pingsC(base)
}
pb := &PingBatcher{
pings: pings,
pending: make(map[string]slot),
flushInterval: flushInterval,
pingChan: make(chan singlePing),
syncChan: make(chan chan struct{}),
syncDelay: defaultSyncDelay,
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
}
pb.useInc = checkMongoVersion(base)
pb.start()
return pb
} | go | func NewPingBatcher(base *mgo.Collection, flushInterval time.Duration) *PingBatcher {
var pings *mgo.Collection
if base != nil {
pings = pingsC(base)
}
pb := &PingBatcher{
pings: pings,
pending: make(map[string]slot),
flushInterval: flushInterval,
pingChan: make(chan singlePing),
syncChan: make(chan chan struct{}),
syncDelay: defaultSyncDelay,
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
}
pb.useInc = checkMongoVersion(base)
pb.start()
return pb
} | [
"func",
"NewPingBatcher",
"(",
"base",
"*",
"mgo",
".",
"Collection",
",",
"flushInterval",
"time",
".",
"Duration",
")",
"*",
"PingBatcher",
"{",
"var",
"pings",
"*",
"mgo",
".",
"Collection",
"\n",
"if",
"base",
"!=",
"nil",
"{",
"pings",
"=",
"pingsC",
"(",
"base",
")",
"\n",
"}",
"\n",
"pb",
":=",
"&",
"PingBatcher",
"{",
"pings",
":",
"pings",
",",
"pending",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"slot",
")",
",",
"flushInterval",
":",
"flushInterval",
",",
"pingChan",
":",
"make",
"(",
"chan",
"singlePing",
")",
",",
"syncChan",
":",
"make",
"(",
"chan",
"chan",
"struct",
"{",
"}",
")",
",",
"syncDelay",
":",
"defaultSyncDelay",
",",
"rand",
":",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
")",
",",
"}",
"\n",
"pb",
".",
"useInc",
"=",
"checkMongoVersion",
"(",
"base",
")",
"\n",
"pb",
".",
"start",
"(",
")",
"\n",
"return",
"pb",
"\n",
"}"
] | // NewPingBatcher creates a worker that will batch ping requests and prepare them
// for insertion into the Pings collection. Pass in the base "presence" collection.
// flushInterval is how often we will write the contents to the database.
// It should be shorter than the 30s slot window for us to not cause active
// pingers to show up as missing. The current default is 1s as it provides a good
// balance of significant-batching-for-performance while still having responsiveness
// to agents coming alive.
// Note that we don't strictly sync on flushInterval times, but use a range of
// times around that interval to avoid having all ping batchers get synchronized
// and still be issuing all requests concurrently. | [
"NewPingBatcher",
"creates",
"a",
"worker",
"that",
"will",
"batch",
"ping",
"requests",
"and",
"prepare",
"them",
"for",
"insertion",
"into",
"the",
"Pings",
"collection",
".",
"Pass",
"in",
"the",
"base",
"presence",
"collection",
".",
"flushInterval",
"is",
"how",
"often",
"we",
"will",
"write",
"the",
"contents",
"to",
"the",
"database",
".",
"It",
"should",
"be",
"shorter",
"than",
"the",
"30s",
"slot",
"window",
"for",
"us",
"to",
"not",
"cause",
"active",
"pingers",
"to",
"show",
"up",
"as",
"missing",
".",
"The",
"current",
"default",
"is",
"1s",
"as",
"it",
"provides",
"a",
"good",
"balance",
"of",
"significant",
"-",
"batching",
"-",
"for",
"-",
"performance",
"while",
"still",
"having",
"responsiveness",
"to",
"agents",
"coming",
"alive",
".",
"Note",
"that",
"we",
"don",
"t",
"strictly",
"sync",
"on",
"flushInterval",
"times",
"but",
"use",
"a",
"range",
"of",
"times",
"around",
"that",
"interval",
"to",
"avoid",
"having",
"all",
"ping",
"batchers",
"get",
"synchronized",
"and",
"still",
"be",
"issuing",
"all",
"requests",
"concurrently",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/pingbatcher.go#L45-L62 |
154,853 | juju/juju | state/presence/pingbatcher.go | NewDeadPingBatcher | func NewDeadPingBatcher(err error) *PingBatcher {
// we never start the loop, so the timeout doesn't matter.
pb := &PingBatcher{}
pb.tomb.Kill(err)
return pb
} | go | func NewDeadPingBatcher(err error) *PingBatcher {
// we never start the loop, so the timeout doesn't matter.
pb := &PingBatcher{}
pb.tomb.Kill(err)
return pb
} | [
"func",
"NewDeadPingBatcher",
"(",
"err",
"error",
")",
"*",
"PingBatcher",
"{",
"// we never start the loop, so the timeout doesn't matter.",
"pb",
":=",
"&",
"PingBatcher",
"{",
"}",
"\n",
"pb",
".",
"tomb",
".",
"Kill",
"(",
"err",
")",
"\n",
"return",
"pb",
"\n",
"}"
] | // NewDeadPingBatcher returns a PingBatcher that is already stopped with an error. | [
"NewDeadPingBatcher",
"returns",
"a",
"PingBatcher",
"that",
"is",
"already",
"stopped",
"with",
"an",
"error",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/pingbatcher.go#L65-L70 |
154,854 | juju/juju | state/presence/pingbatcher.go | start | func (pb *PingBatcher) start() {
pb.tomb.Go(func() error {
err := pb.loop()
cause := errors.Cause(err)
// tomb expects ErrDying or ErrStillAlive as
// exact values, so we need to log and unwrap
// the error first.
if err != nil && cause != tomb.ErrDying {
logger.Infof("ping batching loop failed: %v", err)
}
return cause
})
} | go | func (pb *PingBatcher) start() {
pb.tomb.Go(func() error {
err := pb.loop()
cause := errors.Cause(err)
// tomb expects ErrDying or ErrStillAlive as
// exact values, so we need to log and unwrap
// the error first.
if err != nil && cause != tomb.ErrDying {
logger.Infof("ping batching loop failed: %v", err)
}
return cause
})
} | [
"func",
"(",
"pb",
"*",
"PingBatcher",
")",
"start",
"(",
")",
"{",
"pb",
".",
"tomb",
".",
"Go",
"(",
"func",
"(",
")",
"error",
"{",
"err",
":=",
"pb",
".",
"loop",
"(",
")",
"\n",
"cause",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
"\n",
"// tomb expects ErrDying or ErrStillAlive as",
"// exact values, so we need to log and unwrap",
"// the error first.",
"if",
"err",
"!=",
"nil",
"&&",
"cause",
"!=",
"tomb",
".",
"ErrDying",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"cause",
"\n",
"}",
")",
"\n",
"}"
] | // Start the worker loop. | [
"Start",
"the",
"worker",
"loop",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/pingbatcher.go#L117-L129 |
154,855 | juju/juju | state/presence/pingbatcher.go | Stop | func (pb *PingBatcher) Stop() error {
if err := pb.tomb.Err(); err != tomb.ErrStillAlive {
return err
}
pb.tomb.Kill(nil)
err := pb.tomb.Wait()
return errors.Trace(err)
} | go | func (pb *PingBatcher) Stop() error {
if err := pb.tomb.Err(); err != tomb.ErrStillAlive {
return err
}
pb.tomb.Kill(nil)
err := pb.tomb.Wait()
return errors.Trace(err)
} | [
"func",
"(",
"pb",
"*",
"PingBatcher",
")",
"Stop",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"pb",
".",
"tomb",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"tomb",
".",
"ErrStillAlive",
"{",
"return",
"err",
"\n",
"}",
"\n",
"pb",
".",
"tomb",
".",
"Kill",
"(",
"nil",
")",
"\n",
"err",
":=",
"pb",
".",
"tomb",
".",
"Wait",
"(",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // Stop this PingBatcher, part of the extended Worker interface. | [
"Stop",
"this",
"PingBatcher",
"part",
"of",
"the",
"extended",
"Worker",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/pingbatcher.go#L143-L150 |
154,856 | juju/juju | state/presence/pingbatcher.go | nextSleep | func (pb *PingBatcher) nextSleep(r *rand.Rand) time.Duration {
sleepMin := float64(pb.flushInterval) * 0.8
sleepRange := float64(pb.flushInterval) * 0.4
offset := r.Int63n(int64(sleepRange))
return time.Duration(int64(sleepMin) + offset)
} | go | func (pb *PingBatcher) nextSleep(r *rand.Rand) time.Duration {
sleepMin := float64(pb.flushInterval) * 0.8
sleepRange := float64(pb.flushInterval) * 0.4
offset := r.Int63n(int64(sleepRange))
return time.Duration(int64(sleepMin) + offset)
} | [
"func",
"(",
"pb",
"*",
"PingBatcher",
")",
"nextSleep",
"(",
"r",
"*",
"rand",
".",
"Rand",
")",
"time",
".",
"Duration",
"{",
"sleepMin",
":=",
"float64",
"(",
"pb",
".",
"flushInterval",
")",
"*",
"0.8",
"\n",
"sleepRange",
":=",
"float64",
"(",
"pb",
".",
"flushInterval",
")",
"*",
"0.4",
"\n",
"offset",
":=",
"r",
".",
"Int63n",
"(",
"int64",
"(",
"sleepRange",
")",
")",
"\n",
"return",
"time",
".",
"Duration",
"(",
"int64",
"(",
"sleepMin",
")",
"+",
"offset",
")",
"\n",
"}"
] | // nextSleep determines how long we should wait before flushing our state to the database.
// We use a range of time around the requested 'flushInterval', so that we avoid having
// all requests to the database happen at exactly the same time across machines. | [
"nextSleep",
"determines",
"how",
"long",
"we",
"should",
"wait",
"before",
"flushing",
"our",
"state",
"to",
"the",
"database",
".",
"We",
"use",
"a",
"range",
"of",
"time",
"around",
"the",
"requested",
"flushInterval",
"so",
"that",
"we",
"avoid",
"having",
"all",
"requests",
"to",
"the",
"database",
"happen",
"at",
"exactly",
"the",
"same",
"time",
"across",
"machines",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/pingbatcher.go#L155-L160 |
154,857 | juju/juju | state/presence/pingbatcher.go | Sync | func (pb *PingBatcher) Sync() error {
request := make(chan struct{})
select {
case pb.syncChan <- request:
select {
case <-request:
return nil
case <-pb.tomb.Dying():
break
}
case <-pb.tomb.Dying():
break
}
if err := pb.tomb.Err(); err == nil {
return errors.Errorf("PingBatcher is stopped")
} else {
return err
}
} | go | func (pb *PingBatcher) Sync() error {
request := make(chan struct{})
select {
case pb.syncChan <- request:
select {
case <-request:
return nil
case <-pb.tomb.Dying():
break
}
case <-pb.tomb.Dying():
break
}
if err := pb.tomb.Err(); err == nil {
return errors.Errorf("PingBatcher is stopped")
} else {
return err
}
} | [
"func",
"(",
"pb",
"*",
"PingBatcher",
")",
"Sync",
"(",
")",
"error",
"{",
"request",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"select",
"{",
"case",
"pb",
".",
"syncChan",
"<-",
"request",
":",
"select",
"{",
"case",
"<-",
"request",
":",
"return",
"nil",
"\n",
"case",
"<-",
"pb",
".",
"tomb",
".",
"Dying",
"(",
")",
":",
"break",
"\n",
"}",
"\n",
"case",
"<-",
"pb",
".",
"tomb",
".",
"Dying",
"(",
")",
":",
"break",
"\n",
"}",
"\n",
"if",
"err",
":=",
"pb",
".",
"tomb",
".",
"Err",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}"
] | // Sync schedules a flush of the current state to the database.
// This is not immediate, but actually within a short timeout so that many calls
// to sync in a short time frame will only trigger one write to the database. | [
"Sync",
"schedules",
"a",
"flush",
"of",
"the",
"current",
"state",
"to",
"the",
"database",
".",
"This",
"is",
"not",
"immediate",
"but",
"actually",
"within",
"a",
"short",
"timeout",
"so",
"that",
"many",
"calls",
"to",
"sync",
"in",
"a",
"short",
"time",
"frame",
"will",
"only",
"trigger",
"one",
"write",
"to",
"the",
"database",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/pingbatcher.go#L268-L286 |
154,858 | juju/juju | state/presence/pingbatcher.go | handlePing | func (pb *PingBatcher) handlePing(ping singlePing) {
docId := docIDInt64(ping.ModelUUID, ping.Slot)
cur, slotExists := pb.pending[docId]
if !slotExists {
cur.Alive = make(map[string]uint64)
cur.Slot = ping.Slot
pb.pending[docId] = cur
}
alive := cur.Alive
alive[ping.FieldKey] |= ping.FieldBit
pb.pingCount++
} | go | func (pb *PingBatcher) handlePing(ping singlePing) {
docId := docIDInt64(ping.ModelUUID, ping.Slot)
cur, slotExists := pb.pending[docId]
if !slotExists {
cur.Alive = make(map[string]uint64)
cur.Slot = ping.Slot
pb.pending[docId] = cur
}
alive := cur.Alive
alive[ping.FieldKey] |= ping.FieldBit
pb.pingCount++
} | [
"func",
"(",
"pb",
"*",
"PingBatcher",
")",
"handlePing",
"(",
"ping",
"singlePing",
")",
"{",
"docId",
":=",
"docIDInt64",
"(",
"ping",
".",
"ModelUUID",
",",
"ping",
".",
"Slot",
")",
"\n",
"cur",
",",
"slotExists",
":=",
"pb",
".",
"pending",
"[",
"docId",
"]",
"\n",
"if",
"!",
"slotExists",
"{",
"cur",
".",
"Alive",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"uint64",
")",
"\n",
"cur",
".",
"Slot",
"=",
"ping",
".",
"Slot",
"\n",
"pb",
".",
"pending",
"[",
"docId",
"]",
"=",
"cur",
"\n",
"}",
"\n",
"alive",
":=",
"cur",
".",
"Alive",
"\n",
"alive",
"[",
"ping",
".",
"FieldKey",
"]",
"|=",
"ping",
".",
"FieldBit",
"\n",
"pb",
".",
"pingCount",
"++",
"\n",
"}"
] | // handlePing is where we actually update our internal structures after we
// get a ping request. | [
"handlePing",
"is",
"where",
"we",
"actually",
"update",
"our",
"internal",
"structures",
"after",
"we",
"get",
"a",
"ping",
"request",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/pingbatcher.go#L290-L301 |
154,859 | juju/juju | state/presence/pingbatcher.go | flush | func (pb *PingBatcher) flush() error {
pb.flushMutex.Lock()
defer pb.flushMutex.Unlock()
awaiting := pb.awaitingSync
pb.awaitingSync = nil
// We are doing a flush, make sure everyone waiting is told that it has been done
defer func() {
for _, waiting := range awaiting {
close(waiting)
}
}()
if pb.pingCount == 0 {
return nil
}
uuids := set.NewStrings()
// We treat all of these as 'consumed'. Even if the query fails, it is
// not safe to ever $inc the same fields a second time, so we just move on.
next := pb.pending
pingCount := pb.pingCount
pb.pending = make(map[string]slot)
pb.pingCount = 0
session := pb.pings.Database.Session.Copy()
defer session.Close()
pings := pb.pings.With(session)
docCount := 0
fieldCount := 0
t := time.Now()
for docId, slot := range next {
docCount++
fieldCount += len(slot.Alive)
var update bson.D
if pb.useInc {
update = pb.upsertFieldsUsingInc(slot)
} else {
update = pb.upsertFieldsUsingBit(slot)
}
// Note: UpsertId already handles hitting the DuplicateKey error internally
// We also just Upsert directly instead of using Bulk because for now each PingBatcher is actually
// only used by 1 model. Given 30s slots, we only ever hit 1 or 2 documents being updated at the same
// time. If we switch to sharing batchers between models, then it might make more sense to use bulk updates
// but then we need to handle when we get Duplicate Key errors during update.
_, err := pings.UpsertId(docId, update)
if err != nil {
return errors.Trace(err)
}
if logger.IsTraceEnabled() {
// the rest of Pings records the first 6 characters of
// model-uuids, so we include that here if we are TRACEing.
uuids.Add(docId[:6])
}
}
// usually we should only be processing 1 slot
logger.Tracef("%p [%v] recorded %d pings for %d ping slot(s) and %d fields in %.3fs",
pb, strings.Join(uuids.SortedValues(), ", "), pingCount, docCount, fieldCount, time.Since(t).Seconds())
return nil
} | go | func (pb *PingBatcher) flush() error {
pb.flushMutex.Lock()
defer pb.flushMutex.Unlock()
awaiting := pb.awaitingSync
pb.awaitingSync = nil
// We are doing a flush, make sure everyone waiting is told that it has been done
defer func() {
for _, waiting := range awaiting {
close(waiting)
}
}()
if pb.pingCount == 0 {
return nil
}
uuids := set.NewStrings()
// We treat all of these as 'consumed'. Even if the query fails, it is
// not safe to ever $inc the same fields a second time, so we just move on.
next := pb.pending
pingCount := pb.pingCount
pb.pending = make(map[string]slot)
pb.pingCount = 0
session := pb.pings.Database.Session.Copy()
defer session.Close()
pings := pb.pings.With(session)
docCount := 0
fieldCount := 0
t := time.Now()
for docId, slot := range next {
docCount++
fieldCount += len(slot.Alive)
var update bson.D
if pb.useInc {
update = pb.upsertFieldsUsingInc(slot)
} else {
update = pb.upsertFieldsUsingBit(slot)
}
// Note: UpsertId already handles hitting the DuplicateKey error internally
// We also just Upsert directly instead of using Bulk because for now each PingBatcher is actually
// only used by 1 model. Given 30s slots, we only ever hit 1 or 2 documents being updated at the same
// time. If we switch to sharing batchers between models, then it might make more sense to use bulk updates
// but then we need to handle when we get Duplicate Key errors during update.
_, err := pings.UpsertId(docId, update)
if err != nil {
return errors.Trace(err)
}
if logger.IsTraceEnabled() {
// the rest of Pings records the first 6 characters of
// model-uuids, so we include that here if we are TRACEing.
uuids.Add(docId[:6])
}
}
// usually we should only be processing 1 slot
logger.Tracef("%p [%v] recorded %d pings for %d ping slot(s) and %d fields in %.3fs",
pb, strings.Join(uuids.SortedValues(), ", "), pingCount, docCount, fieldCount, time.Since(t).Seconds())
return nil
} | [
"func",
"(",
"pb",
"*",
"PingBatcher",
")",
"flush",
"(",
")",
"error",
"{",
"pb",
".",
"flushMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"pb",
".",
"flushMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"awaiting",
":=",
"pb",
".",
"awaitingSync",
"\n",
"pb",
".",
"awaitingSync",
"=",
"nil",
"\n",
"// We are doing a flush, make sure everyone waiting is told that it has been done",
"defer",
"func",
"(",
")",
"{",
"for",
"_",
",",
"waiting",
":=",
"range",
"awaiting",
"{",
"close",
"(",
"waiting",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"if",
"pb",
".",
"pingCount",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"uuids",
":=",
"set",
".",
"NewStrings",
"(",
")",
"\n",
"// We treat all of these as 'consumed'. Even if the query fails, it is",
"// not safe to ever $inc the same fields a second time, so we just move on.",
"next",
":=",
"pb",
".",
"pending",
"\n",
"pingCount",
":=",
"pb",
".",
"pingCount",
"\n",
"pb",
".",
"pending",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"slot",
")",
"\n",
"pb",
".",
"pingCount",
"=",
"0",
"\n",
"session",
":=",
"pb",
".",
"pings",
".",
"Database",
".",
"Session",
".",
"Copy",
"(",
")",
"\n",
"defer",
"session",
".",
"Close",
"(",
")",
"\n",
"pings",
":=",
"pb",
".",
"pings",
".",
"With",
"(",
"session",
")",
"\n",
"docCount",
":=",
"0",
"\n",
"fieldCount",
":=",
"0",
"\n",
"t",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"for",
"docId",
",",
"slot",
":=",
"range",
"next",
"{",
"docCount",
"++",
"\n",
"fieldCount",
"+=",
"len",
"(",
"slot",
".",
"Alive",
")",
"\n",
"var",
"update",
"bson",
".",
"D",
"\n",
"if",
"pb",
".",
"useInc",
"{",
"update",
"=",
"pb",
".",
"upsertFieldsUsingInc",
"(",
"slot",
")",
"\n",
"}",
"else",
"{",
"update",
"=",
"pb",
".",
"upsertFieldsUsingBit",
"(",
"slot",
")",
"\n",
"}",
"\n",
"// Note: UpsertId already handles hitting the DuplicateKey error internally",
"// We also just Upsert directly instead of using Bulk because for now each PingBatcher is actually",
"// only used by 1 model. Given 30s slots, we only ever hit 1 or 2 documents being updated at the same",
"// time. If we switch to sharing batchers between models, then it might make more sense to use bulk updates",
"// but then we need to handle when we get Duplicate Key errors during update.",
"_",
",",
"err",
":=",
"pings",
".",
"UpsertId",
"(",
"docId",
",",
"update",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"logger",
".",
"IsTraceEnabled",
"(",
")",
"{",
"// the rest of Pings records the first 6 characters of",
"// model-uuids, so we include that here if we are TRACEing.",
"uuids",
".",
"Add",
"(",
"docId",
"[",
":",
"6",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// usually we should only be processing 1 slot",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"pb",
",",
"strings",
".",
"Join",
"(",
"uuids",
".",
"SortedValues",
"(",
")",
",",
"\"",
"\"",
")",
",",
"pingCount",
",",
"docCount",
",",
"fieldCount",
",",
"time",
".",
"Since",
"(",
"t",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // flush pushes the internal state to the database. Note that if the database
// updates fail, we will still wipe our internal state as it is unsafe to
// publish the same updates to the same slots. | [
"flush",
"pushes",
"the",
"internal",
"state",
"to",
"the",
"database",
".",
"Note",
"that",
"if",
"the",
"database",
"updates",
"fail",
"we",
"will",
"still",
"wipe",
"our",
"internal",
"state",
"as",
"it",
"is",
"unsafe",
"to",
"publish",
"the",
"same",
"updates",
"to",
"the",
"same",
"slots",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/pingbatcher.go#L328-L384 |
154,860 | juju/juju | cmd/juju/controller/showcontroller.go | NewShowControllerCommand | func NewShowControllerCommand() cmd.Command {
cmd := &showControllerCommand{
store: jujuclient.NewFileClientStore(),
}
return modelcmd.WrapBase(cmd)
} | go | func NewShowControllerCommand() cmd.Command {
cmd := &showControllerCommand{
store: jujuclient.NewFileClientStore(),
}
return modelcmd.WrapBase(cmd)
} | [
"func",
"NewShowControllerCommand",
"(",
")",
"cmd",
".",
"Command",
"{",
"cmd",
":=",
"&",
"showControllerCommand",
"{",
"store",
":",
"jujuclient",
".",
"NewFileClientStore",
"(",
")",
",",
"}",
"\n",
"return",
"modelcmd",
".",
"WrapBase",
"(",
"cmd",
")",
"\n",
"}"
] | // NewShowControllerCommand returns a command to show details of the desired controllers. | [
"NewShowControllerCommand",
"returns",
"a",
"command",
"to",
"show",
"details",
"of",
"the",
"desired",
"controllers",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/showcontroller.go#L55-L60 |
154,861 | juju/juju | environs/tools/urls.go | RegisterToolsDataSourceFunc | func RegisterToolsDataSourceFunc(id string, f ToolsDataSourceFunc) {
toolsDatasourceFuncsMu.Lock()
defer toolsDatasourceFuncsMu.Unlock()
for i := range toolsDatasourceFuncs {
if toolsDatasourceFuncs[i].id == id {
toolsDatasourceFuncs[i].f = f
return
}
}
toolsDatasourceFuncs = append(toolsDatasourceFuncs, toolsDatasourceFuncId{id, f})
} | go | func RegisterToolsDataSourceFunc(id string, f ToolsDataSourceFunc) {
toolsDatasourceFuncsMu.Lock()
defer toolsDatasourceFuncsMu.Unlock()
for i := range toolsDatasourceFuncs {
if toolsDatasourceFuncs[i].id == id {
toolsDatasourceFuncs[i].f = f
return
}
}
toolsDatasourceFuncs = append(toolsDatasourceFuncs, toolsDatasourceFuncId{id, f})
} | [
"func",
"RegisterToolsDataSourceFunc",
"(",
"id",
"string",
",",
"f",
"ToolsDataSourceFunc",
")",
"{",
"toolsDatasourceFuncsMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"toolsDatasourceFuncsMu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"i",
":=",
"range",
"toolsDatasourceFuncs",
"{",
"if",
"toolsDatasourceFuncs",
"[",
"i",
"]",
".",
"id",
"==",
"id",
"{",
"toolsDatasourceFuncs",
"[",
"i",
"]",
".",
"f",
"=",
"f",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"toolsDatasourceFuncs",
"=",
"append",
"(",
"toolsDatasourceFuncs",
",",
"toolsDatasourceFuncId",
"{",
"id",
",",
"f",
"}",
")",
"\n",
"}"
] | // RegisterToolsDataSourceFunc registers an ToolsDataSourceFunc
// with the specified id, overwriting any function previously registered
// with the same id. | [
"RegisterToolsDataSourceFunc",
"registers",
"an",
"ToolsDataSourceFunc",
"with",
"the",
"specified",
"id",
"overwriting",
"any",
"function",
"previously",
"registered",
"with",
"the",
"same",
"id",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/urls.go#L41-L51 |
154,862 | juju/juju | environs/tools/urls.go | UnregisterToolsDataSourceFunc | func UnregisterToolsDataSourceFunc(id string) {
toolsDatasourceFuncsMu.Lock()
defer toolsDatasourceFuncsMu.Unlock()
for i, f := range toolsDatasourceFuncs {
if f.id == id {
head := toolsDatasourceFuncs[:i]
tail := toolsDatasourceFuncs[i+1:]
toolsDatasourceFuncs = append(head, tail...)
return
}
}
} | go | func UnregisterToolsDataSourceFunc(id string) {
toolsDatasourceFuncsMu.Lock()
defer toolsDatasourceFuncsMu.Unlock()
for i, f := range toolsDatasourceFuncs {
if f.id == id {
head := toolsDatasourceFuncs[:i]
tail := toolsDatasourceFuncs[i+1:]
toolsDatasourceFuncs = append(head, tail...)
return
}
}
} | [
"func",
"UnregisterToolsDataSourceFunc",
"(",
"id",
"string",
")",
"{",
"toolsDatasourceFuncsMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"toolsDatasourceFuncsMu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"i",
",",
"f",
":=",
"range",
"toolsDatasourceFuncs",
"{",
"if",
"f",
".",
"id",
"==",
"id",
"{",
"head",
":=",
"toolsDatasourceFuncs",
"[",
":",
"i",
"]",
"\n",
"tail",
":=",
"toolsDatasourceFuncs",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"toolsDatasourceFuncs",
"=",
"append",
"(",
"head",
",",
"tail",
"...",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // UnregisterToolsDataSourceFunc unregisters an ToolsDataSourceFunc
// with the specified id. | [
"UnregisterToolsDataSourceFunc",
"unregisters",
"an",
"ToolsDataSourceFunc",
"with",
"the",
"specified",
"id",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/urls.go#L55-L66 |
154,863 | juju/juju | environs/tools/urls.go | GetMetadataSources | func GetMetadataSources(env environs.BootstrapEnviron) ([]simplestreams.DataSource, error) {
config := env.Config()
// Add configured and environment-specific datasources.
var sources []simplestreams.DataSource
if userURL, ok := config.AgentMetadataURL(); ok {
verify := utils.VerifySSLHostnames
if !config.SSLHostnameVerification() {
verify = utils.NoVerifySSLHostnames
}
sources = append(sources, simplestreams.NewURLSignedDataSource(conf.AgentMetadataURLKey, userURL, keys.JujuPublicKey, verify, simplestreams.SPECIFIC_CLOUD_DATA, false))
}
envDataSources, err := environmentDataSources(env)
if err != nil {
return nil, err
}
sources = append(sources, envDataSources...)
// Add the default, public datasource.
defaultURL, err := ToolsURL(DefaultBaseURL)
if err != nil {
return nil, err
}
if defaultURL != "" {
sources = append(sources,
simplestreams.NewURLSignedDataSource("default simplestreams", defaultURL, keys.JujuPublicKey, utils.VerifySSLHostnames, simplestreams.DEFAULT_CLOUD_DATA, true))
}
return sources, nil
} | go | func GetMetadataSources(env environs.BootstrapEnviron) ([]simplestreams.DataSource, error) {
config := env.Config()
// Add configured and environment-specific datasources.
var sources []simplestreams.DataSource
if userURL, ok := config.AgentMetadataURL(); ok {
verify := utils.VerifySSLHostnames
if !config.SSLHostnameVerification() {
verify = utils.NoVerifySSLHostnames
}
sources = append(sources, simplestreams.NewURLSignedDataSource(conf.AgentMetadataURLKey, userURL, keys.JujuPublicKey, verify, simplestreams.SPECIFIC_CLOUD_DATA, false))
}
envDataSources, err := environmentDataSources(env)
if err != nil {
return nil, err
}
sources = append(sources, envDataSources...)
// Add the default, public datasource.
defaultURL, err := ToolsURL(DefaultBaseURL)
if err != nil {
return nil, err
}
if defaultURL != "" {
sources = append(sources,
simplestreams.NewURLSignedDataSource("default simplestreams", defaultURL, keys.JujuPublicKey, utils.VerifySSLHostnames, simplestreams.DEFAULT_CLOUD_DATA, true))
}
return sources, nil
} | [
"func",
"GetMetadataSources",
"(",
"env",
"environs",
".",
"BootstrapEnviron",
")",
"(",
"[",
"]",
"simplestreams",
".",
"DataSource",
",",
"error",
")",
"{",
"config",
":=",
"env",
".",
"Config",
"(",
")",
"\n\n",
"// Add configured and environment-specific datasources.",
"var",
"sources",
"[",
"]",
"simplestreams",
".",
"DataSource",
"\n",
"if",
"userURL",
",",
"ok",
":=",
"config",
".",
"AgentMetadataURL",
"(",
")",
";",
"ok",
"{",
"verify",
":=",
"utils",
".",
"VerifySSLHostnames",
"\n",
"if",
"!",
"config",
".",
"SSLHostnameVerification",
"(",
")",
"{",
"verify",
"=",
"utils",
".",
"NoVerifySSLHostnames",
"\n",
"}",
"\n",
"sources",
"=",
"append",
"(",
"sources",
",",
"simplestreams",
".",
"NewURLSignedDataSource",
"(",
"conf",
".",
"AgentMetadataURLKey",
",",
"userURL",
",",
"keys",
".",
"JujuPublicKey",
",",
"verify",
",",
"simplestreams",
".",
"SPECIFIC_CLOUD_DATA",
",",
"false",
")",
")",
"\n",
"}",
"\n\n",
"envDataSources",
",",
"err",
":=",
"environmentDataSources",
"(",
"env",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"sources",
"=",
"append",
"(",
"sources",
",",
"envDataSources",
"...",
")",
"\n\n",
"// Add the default, public datasource.",
"defaultURL",
",",
"err",
":=",
"ToolsURL",
"(",
"DefaultBaseURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"defaultURL",
"!=",
"\"",
"\"",
"{",
"sources",
"=",
"append",
"(",
"sources",
",",
"simplestreams",
".",
"NewURLSignedDataSource",
"(",
"\"",
"\"",
",",
"defaultURL",
",",
"keys",
".",
"JujuPublicKey",
",",
"utils",
".",
"VerifySSLHostnames",
",",
"simplestreams",
".",
"DEFAULT_CLOUD_DATA",
",",
"true",
")",
")",
"\n",
"}",
"\n",
"return",
"sources",
",",
"nil",
"\n",
"}"
] | // GetMetadataSources returns the sources to use when looking for
// simplestreams tools metadata for the given stream. | [
"GetMetadataSources",
"returns",
"the",
"sources",
"to",
"use",
"when",
"looking",
"for",
"simplestreams",
"tools",
"metadata",
"for",
"the",
"given",
"stream",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/urls.go#L70-L99 |
154,864 | juju/juju | environs/tools/urls.go | environmentDataSources | func environmentDataSources(bootstrapEnviron environs.BootstrapEnviron) ([]simplestreams.DataSource, error) {
toolsDatasourceFuncsMu.RLock()
defer toolsDatasourceFuncsMu.RUnlock()
var datasources []simplestreams.DataSource
env, ok := bootstrapEnviron.(environs.Environ)
if !ok {
logger.Debugf("environmentDataSources is supported for IAAS, environ %#v is not Environ", bootstrapEnviron)
// ignore for CAAS
return datasources, nil
}
for _, f := range toolsDatasourceFuncs {
logger.Debugf("trying datasource %q", f.id)
datasource, err := f.f(env)
if err != nil {
if errors.IsNotSupported(err) {
continue
}
return nil, err
}
datasources = append(datasources, datasource)
}
return datasources, nil
} | go | func environmentDataSources(bootstrapEnviron environs.BootstrapEnviron) ([]simplestreams.DataSource, error) {
toolsDatasourceFuncsMu.RLock()
defer toolsDatasourceFuncsMu.RUnlock()
var datasources []simplestreams.DataSource
env, ok := bootstrapEnviron.(environs.Environ)
if !ok {
logger.Debugf("environmentDataSources is supported for IAAS, environ %#v is not Environ", bootstrapEnviron)
// ignore for CAAS
return datasources, nil
}
for _, f := range toolsDatasourceFuncs {
logger.Debugf("trying datasource %q", f.id)
datasource, err := f.f(env)
if err != nil {
if errors.IsNotSupported(err) {
continue
}
return nil, err
}
datasources = append(datasources, datasource)
}
return datasources, nil
} | [
"func",
"environmentDataSources",
"(",
"bootstrapEnviron",
"environs",
".",
"BootstrapEnviron",
")",
"(",
"[",
"]",
"simplestreams",
".",
"DataSource",
",",
"error",
")",
"{",
"toolsDatasourceFuncsMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"toolsDatasourceFuncsMu",
".",
"RUnlock",
"(",
")",
"\n\n",
"var",
"datasources",
"[",
"]",
"simplestreams",
".",
"DataSource",
"\n",
"env",
",",
"ok",
":=",
"bootstrapEnviron",
".",
"(",
"environs",
".",
"Environ",
")",
"\n",
"if",
"!",
"ok",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"bootstrapEnviron",
")",
"\n",
"// ignore for CAAS",
"return",
"datasources",
",",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"toolsDatasourceFuncs",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"f",
".",
"id",
")",
"\n",
"datasource",
",",
"err",
":=",
"f",
".",
"f",
"(",
"env",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"errors",
".",
"IsNotSupported",
"(",
"err",
")",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"datasources",
"=",
"append",
"(",
"datasources",
",",
"datasource",
")",
"\n",
"}",
"\n",
"return",
"datasources",
",",
"nil",
"\n",
"}"
] | // environmentDataSources returns simplestreams datasources for the environment
// by calling the functions registered in RegisterToolsDataSourceFunc.
// The datasources returned will be in the same order the functions were registered. | [
"environmentDataSources",
"returns",
"simplestreams",
"datasources",
"for",
"the",
"environment",
"by",
"calling",
"the",
"functions",
"registered",
"in",
"RegisterToolsDataSourceFunc",
".",
"The",
"datasources",
"returned",
"will",
"be",
"in",
"the",
"same",
"order",
"the",
"functions",
"were",
"registered",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/urls.go#L104-L127 |
154,865 | juju/juju | api/externalcontrollerupdater/externalcontrollerupdater.go | New | func New(caller base.APICaller) *Client {
return &Client{base.NewFacadeCaller(caller, Facade)}
} | go | func New(caller base.APICaller) *Client {
return &Client{base.NewFacadeCaller(caller, Facade)}
} | [
"func",
"New",
"(",
"caller",
"base",
".",
"APICaller",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"base",
".",
"NewFacadeCaller",
"(",
"caller",
",",
"Facade",
")",
"}",
"\n",
"}"
] | // New creates a new client-side ExternalControllerUpdater facade. | [
"New",
"creates",
"a",
"new",
"client",
"-",
"side",
"ExternalControllerUpdater",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/externalcontrollerupdater/externalcontrollerupdater.go#L25-L27 |
154,866 | juju/juju | api/externalcontrollerupdater/externalcontrollerupdater.go | WatchExternalControllers | func (c *Client) WatchExternalControllers() (watcher.StringsWatcher, error) {
var results params.StringsWatchResults
err := c.facade.FacadeCall("WatchExternalControllers", nil, &results)
if err != nil {
return nil, err
}
if n := len(results.Results); n != 1 {
return nil, errors.Errorf("expected 1 result, got %d", n)
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
w := apiwatcher.NewStringsWatcher(c.facade.RawAPICaller(), result)
return w, nil
} | go | func (c *Client) WatchExternalControllers() (watcher.StringsWatcher, error) {
var results params.StringsWatchResults
err := c.facade.FacadeCall("WatchExternalControllers", nil, &results)
if err != nil {
return nil, err
}
if n := len(results.Results); n != 1 {
return nil, errors.Errorf("expected 1 result, got %d", n)
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
w := apiwatcher.NewStringsWatcher(c.facade.RawAPICaller(), result)
return w, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"WatchExternalControllers",
"(",
")",
"(",
"watcher",
".",
"StringsWatcher",
",",
"error",
")",
"{",
"var",
"results",
"params",
".",
"StringsWatchResults",
"\n",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"nil",
",",
"&",
"results",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"n",
":=",
"len",
"(",
"results",
".",
"Results",
")",
";",
"n",
"!=",
"1",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"n",
")",
"\n",
"}",
"\n",
"result",
":=",
"results",
".",
"Results",
"[",
"0",
"]",
"\n",
"if",
"result",
".",
"Error",
"!=",
"nil",
"{",
"return",
"nil",
",",
"result",
".",
"Error",
"\n",
"}",
"\n",
"w",
":=",
"apiwatcher",
".",
"NewStringsWatcher",
"(",
"c",
".",
"facade",
".",
"RawAPICaller",
"(",
")",
",",
"result",
")",
"\n",
"return",
"w",
",",
"nil",
"\n",
"}"
] | // WatchExternalControllers watches for the addition and removal of external
// controllers. | [
"WatchExternalControllers",
"watches",
"for",
"the",
"addition",
"and",
"removal",
"of",
"external",
"controllers",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/externalcontrollerupdater/externalcontrollerupdater.go#L31-L46 |
154,867 | juju/juju | api/externalcontrollerupdater/externalcontrollerupdater.go | ExternalControllerInfo | func (c *Client) ExternalControllerInfo(controllerUUID string) (*crossmodel.ControllerInfo, error) {
if !names.IsValidController(controllerUUID) {
return nil, errors.NotValidf("controller UUID %q", controllerUUID)
}
controllerTag := names.NewControllerTag(controllerUUID)
args := params.Entities{[]params.Entity{{
Tag: controllerTag.String(),
}}}
var results params.ExternalControllerInfoResults
err := c.facade.FacadeCall("ExternalControllerInfo", args, &results)
if err != nil {
return nil, errors.Trace(err)
}
if len(results.Results) != 1 {
return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
return &crossmodel.ControllerInfo{
ControllerTag: controllerTag,
Alias: result.Result.Alias,
Addrs: result.Result.Addrs,
CACert: result.Result.CACert,
}, nil
} | go | func (c *Client) ExternalControllerInfo(controllerUUID string) (*crossmodel.ControllerInfo, error) {
if !names.IsValidController(controllerUUID) {
return nil, errors.NotValidf("controller UUID %q", controllerUUID)
}
controllerTag := names.NewControllerTag(controllerUUID)
args := params.Entities{[]params.Entity{{
Tag: controllerTag.String(),
}}}
var results params.ExternalControllerInfoResults
err := c.facade.FacadeCall("ExternalControllerInfo", args, &results)
if err != nil {
return nil, errors.Trace(err)
}
if len(results.Results) != 1 {
return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
return &crossmodel.ControllerInfo{
ControllerTag: controllerTag,
Alias: result.Result.Alias,
Addrs: result.Result.Addrs,
CACert: result.Result.CACert,
}, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ExternalControllerInfo",
"(",
"controllerUUID",
"string",
")",
"(",
"*",
"crossmodel",
".",
"ControllerInfo",
",",
"error",
")",
"{",
"if",
"!",
"names",
".",
"IsValidController",
"(",
"controllerUUID",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
",",
"controllerUUID",
")",
"\n",
"}",
"\n",
"controllerTag",
":=",
"names",
".",
"NewControllerTag",
"(",
"controllerUUID",
")",
"\n",
"args",
":=",
"params",
".",
"Entities",
"{",
"[",
"]",
"params",
".",
"Entity",
"{",
"{",
"Tag",
":",
"controllerTag",
".",
"String",
"(",
")",
",",
"}",
"}",
"}",
"\n",
"var",
"results",
"params",
".",
"ExternalControllerInfoResults",
"\n",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"results",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"results",
".",
"Results",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"results",
".",
"Results",
")",
")",
"\n",
"}",
"\n",
"result",
":=",
"results",
".",
"Results",
"[",
"0",
"]",
"\n",
"if",
"result",
".",
"Error",
"!=",
"nil",
"{",
"return",
"nil",
",",
"result",
".",
"Error",
"\n",
"}",
"\n",
"return",
"&",
"crossmodel",
".",
"ControllerInfo",
"{",
"ControllerTag",
":",
"controllerTag",
",",
"Alias",
":",
"result",
".",
"Result",
".",
"Alias",
",",
"Addrs",
":",
"result",
".",
"Result",
".",
"Addrs",
",",
"CACert",
":",
"result",
".",
"Result",
".",
"CACert",
",",
"}",
",",
"nil",
"\n",
"}"
] | // ExternalControllerInfo returns the info for the external controller with the specified UUID. | [
"ExternalControllerInfo",
"returns",
"the",
"info",
"for",
"the",
"external",
"controller",
"with",
"the",
"specified",
"UUID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/externalcontrollerupdater/externalcontrollerupdater.go#L49-L75 |
154,868 | juju/juju | api/externalcontrollerupdater/externalcontrollerupdater.go | SetExternalControllerInfo | func (c *Client) SetExternalControllerInfo(info crossmodel.ControllerInfo) error {
var results params.ErrorResults
args := params.SetExternalControllersInfoParams{
Controllers: []params.SetExternalControllerInfoParams{{
Info: params.ExternalControllerInfo{
ControllerTag: info.ControllerTag.String(),
Alias: info.Alias,
Addrs: info.Addrs,
CACert: info.CACert,
},
}},
}
err := c.facade.FacadeCall("SetExternalControllerInfo", args, &results)
if err != nil {
return errors.Trace(err)
}
return results.OneError()
} | go | func (c *Client) SetExternalControllerInfo(info crossmodel.ControllerInfo) error {
var results params.ErrorResults
args := params.SetExternalControllersInfoParams{
Controllers: []params.SetExternalControllerInfoParams{{
Info: params.ExternalControllerInfo{
ControllerTag: info.ControllerTag.String(),
Alias: info.Alias,
Addrs: info.Addrs,
CACert: info.CACert,
},
}},
}
err := c.facade.FacadeCall("SetExternalControllerInfo", args, &results)
if err != nil {
return errors.Trace(err)
}
return results.OneError()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SetExternalControllerInfo",
"(",
"info",
"crossmodel",
".",
"ControllerInfo",
")",
"error",
"{",
"var",
"results",
"params",
".",
"ErrorResults",
"\n",
"args",
":=",
"params",
".",
"SetExternalControllersInfoParams",
"{",
"Controllers",
":",
"[",
"]",
"params",
".",
"SetExternalControllerInfoParams",
"{",
"{",
"Info",
":",
"params",
".",
"ExternalControllerInfo",
"{",
"ControllerTag",
":",
"info",
".",
"ControllerTag",
".",
"String",
"(",
")",
",",
"Alias",
":",
"info",
".",
"Alias",
",",
"Addrs",
":",
"info",
".",
"Addrs",
",",
"CACert",
":",
"info",
".",
"CACert",
",",
"}",
",",
"}",
"}",
",",
"}",
"\n",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"results",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"results",
".",
"OneError",
"(",
")",
"\n",
"}"
] | // SetExternalControllerInfo saves the given controller info. | [
"SetExternalControllerInfo",
"saves",
"the",
"given",
"controller",
"info",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/externalcontrollerupdater/externalcontrollerupdater.go#L78-L95 |
154,869 | juju/juju | provider/azure/auth.go | WithAuthorization | func (c *cloudSpecAuth) WithAuthorization() autorest.PrepareDecorator {
return func(p autorest.Preparer) autorest.Preparer {
return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) {
r, err := p.Prepare(r)
if err != nil {
return nil, err
}
token, err := c.getToken()
if err != nil {
return nil, err
}
authorizer := autorest.NewBearerAuthorizer(token)
return autorest.CreatePreparer(authorizer.WithAuthorization()).Prepare(r)
})
}
} | go | func (c *cloudSpecAuth) WithAuthorization() autorest.PrepareDecorator {
return func(p autorest.Preparer) autorest.Preparer {
return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) {
r, err := p.Prepare(r)
if err != nil {
return nil, err
}
token, err := c.getToken()
if err != nil {
return nil, err
}
authorizer := autorest.NewBearerAuthorizer(token)
return autorest.CreatePreparer(authorizer.WithAuthorization()).Prepare(r)
})
}
} | [
"func",
"(",
"c",
"*",
"cloudSpecAuth",
")",
"WithAuthorization",
"(",
")",
"autorest",
".",
"PrepareDecorator",
"{",
"return",
"func",
"(",
"p",
"autorest",
".",
"Preparer",
")",
"autorest",
".",
"Preparer",
"{",
"return",
"autorest",
".",
"PreparerFunc",
"(",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"r",
",",
"err",
":=",
"p",
".",
"Prepare",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"token",
",",
"err",
":=",
"c",
".",
"getToken",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"authorizer",
":=",
"autorest",
".",
"NewBearerAuthorizer",
"(",
"token",
")",
"\n",
"return",
"autorest",
".",
"CreatePreparer",
"(",
"authorizer",
".",
"WithAuthorization",
"(",
")",
")",
".",
"Prepare",
"(",
"r",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // WithAuthorization is part of the autorest.Authorizer interface. | [
"WithAuthorization",
"is",
"part",
"of",
"the",
"autorest",
".",
"Authorizer",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/auth.go#L30-L45 |
154,870 | juju/juju | provider/azure/auth.go | AuthToken | func AuthToken(cloud environs.CloudSpec, sender autorest.Sender) (*adal.ServicePrincipalToken, error) {
if authType := cloud.Credential.AuthType(); authType != clientCredentialsAuthType {
// We currently only support a single auth-type for
// non-interactive authentication. Interactive auth
// is used only to generate a service-principal.
return nil, errors.NotSupportedf("auth-type %q", authType)
}
resourceId, err := azureauth.ResourceManagerResourceId(cloud.StorageEndpoint)
if err != nil {
return nil, errors.Trace(err)
}
credAttrs := cloud.Credential.Attributes()
subscriptionId := credAttrs[credAttrSubscriptionId]
appId := credAttrs[credAttrAppId]
appPassword := credAttrs[credAttrAppPassword]
client := subscriptions.Client{subscriptions.NewWithBaseURI(cloud.Endpoint)}
useragent.UpdateClient(&client.Client)
client.Sender = sender
sdkCtx := context.Background()
oauthConfig, _, err := azureauth.OAuthConfig(sdkCtx, client, cloud.Endpoint, subscriptionId)
if err != nil {
return nil, errors.Trace(err)
}
token, err := adal.NewServicePrincipalToken(
*oauthConfig,
appId,
appPassword,
resourceId,
)
if err != nil {
return nil, errors.Annotate(err, "constructing service principal token")
}
tokenClient := autorest.NewClientWithUserAgent("")
useragent.UpdateClient(&tokenClient)
tokenClient.Sender = sender
token.SetSender(&tokenClient)
return token, nil
} | go | func AuthToken(cloud environs.CloudSpec, sender autorest.Sender) (*adal.ServicePrincipalToken, error) {
if authType := cloud.Credential.AuthType(); authType != clientCredentialsAuthType {
// We currently only support a single auth-type for
// non-interactive authentication. Interactive auth
// is used only to generate a service-principal.
return nil, errors.NotSupportedf("auth-type %q", authType)
}
resourceId, err := azureauth.ResourceManagerResourceId(cloud.StorageEndpoint)
if err != nil {
return nil, errors.Trace(err)
}
credAttrs := cloud.Credential.Attributes()
subscriptionId := credAttrs[credAttrSubscriptionId]
appId := credAttrs[credAttrAppId]
appPassword := credAttrs[credAttrAppPassword]
client := subscriptions.Client{subscriptions.NewWithBaseURI(cloud.Endpoint)}
useragent.UpdateClient(&client.Client)
client.Sender = sender
sdkCtx := context.Background()
oauthConfig, _, err := azureauth.OAuthConfig(sdkCtx, client, cloud.Endpoint, subscriptionId)
if err != nil {
return nil, errors.Trace(err)
}
token, err := adal.NewServicePrincipalToken(
*oauthConfig,
appId,
appPassword,
resourceId,
)
if err != nil {
return nil, errors.Annotate(err, "constructing service principal token")
}
tokenClient := autorest.NewClientWithUserAgent("")
useragent.UpdateClient(&tokenClient)
tokenClient.Sender = sender
token.SetSender(&tokenClient)
return token, nil
} | [
"func",
"AuthToken",
"(",
"cloud",
"environs",
".",
"CloudSpec",
",",
"sender",
"autorest",
".",
"Sender",
")",
"(",
"*",
"adal",
".",
"ServicePrincipalToken",
",",
"error",
")",
"{",
"if",
"authType",
":=",
"cloud",
".",
"Credential",
".",
"AuthType",
"(",
")",
";",
"authType",
"!=",
"clientCredentialsAuthType",
"{",
"// We currently only support a single auth-type for",
"// non-interactive authentication. Interactive auth",
"// is used only to generate a service-principal.",
"return",
"nil",
",",
"errors",
".",
"NotSupportedf",
"(",
"\"",
"\"",
",",
"authType",
")",
"\n",
"}",
"\n\n",
"resourceId",
",",
"err",
":=",
"azureauth",
".",
"ResourceManagerResourceId",
"(",
"cloud",
".",
"StorageEndpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"credAttrs",
":=",
"cloud",
".",
"Credential",
".",
"Attributes",
"(",
")",
"\n",
"subscriptionId",
":=",
"credAttrs",
"[",
"credAttrSubscriptionId",
"]",
"\n",
"appId",
":=",
"credAttrs",
"[",
"credAttrAppId",
"]",
"\n",
"appPassword",
":=",
"credAttrs",
"[",
"credAttrAppPassword",
"]",
"\n",
"client",
":=",
"subscriptions",
".",
"Client",
"{",
"subscriptions",
".",
"NewWithBaseURI",
"(",
"cloud",
".",
"Endpoint",
")",
"}",
"\n",
"useragent",
".",
"UpdateClient",
"(",
"&",
"client",
".",
"Client",
")",
"\n",
"client",
".",
"Sender",
"=",
"sender",
"\n",
"sdkCtx",
":=",
"context",
".",
"Background",
"(",
")",
"\n",
"oauthConfig",
",",
"_",
",",
"err",
":=",
"azureauth",
".",
"OAuthConfig",
"(",
"sdkCtx",
",",
"client",
",",
"cloud",
".",
"Endpoint",
",",
"subscriptionId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"token",
",",
"err",
":=",
"adal",
".",
"NewServicePrincipalToken",
"(",
"*",
"oauthConfig",
",",
"appId",
",",
"appPassword",
",",
"resourceId",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"tokenClient",
":=",
"autorest",
".",
"NewClientWithUserAgent",
"(",
"\"",
"\"",
")",
"\n",
"useragent",
".",
"UpdateClient",
"(",
"&",
"tokenClient",
")",
"\n",
"tokenClient",
".",
"Sender",
"=",
"sender",
"\n",
"token",
".",
"SetSender",
"(",
"&",
"tokenClient",
")",
"\n",
"return",
"token",
",",
"nil",
"\n",
"}"
] | // AuthToken returns a service principal token, suitable for authorizing
// Resource Manager API requests, based on the supplied CloudSpec. | [
"AuthToken",
"returns",
"a",
"service",
"principal",
"token",
"suitable",
"for",
"authorizing",
"Resource",
"Manager",
"API",
"requests",
"based",
"on",
"the",
"supplied",
"CloudSpec",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/auth.go#L71-L111 |
154,871 | juju/juju | api/backups/upload.go | Upload | func (c *Client) Upload(archive io.ReadSeeker, meta params.BackupsMetadataResult) (string, error) {
// Empty out some of the metadata.
meta.ID = ""
meta.Stored = time.Time{}
req, err := http.NewRequest("PUT", "/backups", nil)
if err != nil {
return "", errors.Trace(err)
}
body, contentType, err := httpattachment.NewBody(archive, meta, "juju-backup.tar.gz")
if err != nil {
return "", errors.Annotatef(err, "cannot create multipart body")
}
req.Header.Set("Content-Type", contentType)
var result params.BackupsUploadResult
if err := c.client.Do(req, body, &result); err != nil {
return "", errors.Trace(err)
}
return result.ID, nil
} | go | func (c *Client) Upload(archive io.ReadSeeker, meta params.BackupsMetadataResult) (string, error) {
// Empty out some of the metadata.
meta.ID = ""
meta.Stored = time.Time{}
req, err := http.NewRequest("PUT", "/backups", nil)
if err != nil {
return "", errors.Trace(err)
}
body, contentType, err := httpattachment.NewBody(archive, meta, "juju-backup.tar.gz")
if err != nil {
return "", errors.Annotatef(err, "cannot create multipart body")
}
req.Header.Set("Content-Type", contentType)
var result params.BackupsUploadResult
if err := c.client.Do(req, body, &result); err != nil {
return "", errors.Trace(err)
}
return result.ID, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Upload",
"(",
"archive",
"io",
".",
"ReadSeeker",
",",
"meta",
"params",
".",
"BackupsMetadataResult",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Empty out some of the metadata.",
"meta",
".",
"ID",
"=",
"\"",
"\"",
"\n",
"meta",
".",
"Stored",
"=",
"time",
".",
"Time",
"{",
"}",
"\n\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"body",
",",
"contentType",
",",
"err",
":=",
"httpattachment",
".",
"NewBody",
"(",
"archive",
",",
"meta",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"contentType",
")",
"\n",
"var",
"result",
"params",
".",
"BackupsUploadResult",
"\n",
"if",
"err",
":=",
"c",
".",
"client",
".",
"Do",
"(",
"req",
",",
"body",
",",
"&",
"result",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
".",
"ID",
",",
"nil",
"\n",
"}"
] | // Upload sends the backup archive to remote storage. | [
"Upload",
"sends",
"the",
"backup",
"archive",
"to",
"remote",
"storage",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/backups/upload.go#L18-L37 |
154,872 | juju/juju | network/ssh/reachable.go | NewReachableChecker | func NewReachableChecker(dialer Dialer, timeout time.Duration) *reachableChecker {
return &reachableChecker{
dialer: dialer,
timeout: timeout,
}
} | go | func NewReachableChecker(dialer Dialer, timeout time.Duration) *reachableChecker {
return &reachableChecker{
dialer: dialer,
timeout: timeout,
}
} | [
"func",
"NewReachableChecker",
"(",
"dialer",
"Dialer",
",",
"timeout",
"time",
".",
"Duration",
")",
"*",
"reachableChecker",
"{",
"return",
"&",
"reachableChecker",
"{",
"dialer",
":",
"dialer",
",",
"timeout",
":",
"timeout",
",",
"}",
"\n",
"}"
] | // NewReachableChecker creates a ReachableChecker that can be used to check for
// Hosts that are viable SSH targets.
// When FindHost is called, we will dial the entries in the given hostPorts, in
// parallel, using the given dialer, closing successfully established
// connections after checking the ssh key. Individual connection errors are
// discarded, and an error is returned only if none of the hostPorts can be
// reached when the given timeout expires.
// If publicKeys is a non empty list, then the SSH host public key will be
// checked. If it is not in the list, that host is not considered valid.
//
// Usually, a net.Dialer initialized with a non-empty Timeout field is passed
// for dialer. | [
"NewReachableChecker",
"creates",
"a",
"ReachableChecker",
"that",
"can",
"be",
"used",
"to",
"check",
"for",
"Hosts",
"that",
"are",
"viable",
"SSH",
"targets",
".",
"When",
"FindHost",
"is",
"called",
"we",
"will",
"dial",
"the",
"entries",
"in",
"the",
"given",
"hostPorts",
"in",
"parallel",
"using",
"the",
"given",
"dialer",
"closing",
"successfully",
"established",
"connections",
"after",
"checking",
"the",
"ssh",
"key",
".",
"Individual",
"connection",
"errors",
"are",
"discarded",
"and",
"an",
"error",
"is",
"returned",
"only",
"if",
"none",
"of",
"the",
"hostPorts",
"can",
"be",
"reached",
"when",
"the",
"given",
"timeout",
"expires",
".",
"If",
"publicKeys",
"is",
"a",
"non",
"empty",
"list",
"then",
"the",
"SSH",
"host",
"public",
"key",
"will",
"be",
"checked",
".",
"If",
"it",
"is",
"not",
"in",
"the",
"list",
"that",
"host",
"is",
"not",
"considered",
"valid",
".",
"Usually",
"a",
"net",
".",
"Dialer",
"initialized",
"with",
"a",
"non",
"-",
"empty",
"Timeout",
"field",
"is",
"passed",
"for",
"dialer",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/ssh/reachable.go#L49-L54 |
154,873 | juju/juju | network/ssh/reachable.go | Check | func (h *hostKeyChecker) Check() {
defer func() {
// send a finished message unless we're already stopped and nobody
// is listening
if h.Finished != nil {
select {
case h.Finished <- struct{}{}:
case <-h.Stop:
}
}
}()
// TODO(jam): 2017-01-24 One limitation of our algorithm, is that we don't
// try to limit the negotiation of the keys to our set of possible keys.
// For example, say we only know about the RSA key for the remote host, but
// it has been updated to use a ECDSA key as well. Gocrypto/ssh might
// negotiate to use the "more secure" ECDSA key and we will see that
// as an invalid key.
sshconfig := &ssh.ClientConfig{
HostKeyCallback: h.hostKeyCallback,
}
addr := h.HostPort.NetAddr()
logger.Debugf("dialing %s to check host keys", addr)
conn, err := h.Dialer.Dial("tcp", addr)
if err != nil {
logger.Debugf("dial %s failed with: %v", addr, err)
return
}
// No need to do the key exchange if we're already stopping
select {
case <-h.Stop:
conn.Close()
return
default:
}
logger.Debugf("connected to %s, initiating ssh handshake", addr)
// NewClientConn will close the underlying net.Conn if it gets an error
client, _, _, err := ssh.NewClientConn(conn, addr, sshconfig)
if err == nil {
// We don't expect this case, because we don't support Auth,
// but make sure to close it anyway.
client.Close()
} else {
// no need to log these two messages, that's already been done
// in hostKeyCallback
if !strings.Contains(err.Error(), hostKeyAccepted.Error()) &&
!strings.Contains(err.Error(), hostKeyNotInList.Error()) {
logger.Debugf("%v", err)
}
}
} | go | func (h *hostKeyChecker) Check() {
defer func() {
// send a finished message unless we're already stopped and nobody
// is listening
if h.Finished != nil {
select {
case h.Finished <- struct{}{}:
case <-h.Stop:
}
}
}()
// TODO(jam): 2017-01-24 One limitation of our algorithm, is that we don't
// try to limit the negotiation of the keys to our set of possible keys.
// For example, say we only know about the RSA key for the remote host, but
// it has been updated to use a ECDSA key as well. Gocrypto/ssh might
// negotiate to use the "more secure" ECDSA key and we will see that
// as an invalid key.
sshconfig := &ssh.ClientConfig{
HostKeyCallback: h.hostKeyCallback,
}
addr := h.HostPort.NetAddr()
logger.Debugf("dialing %s to check host keys", addr)
conn, err := h.Dialer.Dial("tcp", addr)
if err != nil {
logger.Debugf("dial %s failed with: %v", addr, err)
return
}
// No need to do the key exchange if we're already stopping
select {
case <-h.Stop:
conn.Close()
return
default:
}
logger.Debugf("connected to %s, initiating ssh handshake", addr)
// NewClientConn will close the underlying net.Conn if it gets an error
client, _, _, err := ssh.NewClientConn(conn, addr, sshconfig)
if err == nil {
// We don't expect this case, because we don't support Auth,
// but make sure to close it anyway.
client.Close()
} else {
// no need to log these two messages, that's already been done
// in hostKeyCallback
if !strings.Contains(err.Error(), hostKeyAccepted.Error()) &&
!strings.Contains(err.Error(), hostKeyNotInList.Error()) {
logger.Debugf("%v", err)
}
}
} | [
"func",
"(",
"h",
"*",
"hostKeyChecker",
")",
"Check",
"(",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"// send a finished message unless we're already stopped and nobody",
"// is listening",
"if",
"h",
".",
"Finished",
"!=",
"nil",
"{",
"select",
"{",
"case",
"h",
".",
"Finished",
"<-",
"struct",
"{",
"}",
"{",
"}",
":",
"case",
"<-",
"h",
".",
"Stop",
":",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"// TODO(jam): 2017-01-24 One limitation of our algorithm, is that we don't",
"// try to limit the negotiation of the keys to our set of possible keys.",
"// For example, say we only know about the RSA key for the remote host, but",
"// it has been updated to use a ECDSA key as well. Gocrypto/ssh might",
"// negotiate to use the \"more secure\" ECDSA key and we will see that",
"// as an invalid key.",
"sshconfig",
":=",
"&",
"ssh",
".",
"ClientConfig",
"{",
"HostKeyCallback",
":",
"h",
".",
"hostKeyCallback",
",",
"}",
"\n",
"addr",
":=",
"h",
".",
"HostPort",
".",
"NetAddr",
"(",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"conn",
",",
"err",
":=",
"h",
".",
"Dialer",
".",
"Dial",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"addr",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// No need to do the key exchange if we're already stopping",
"select",
"{",
"case",
"<-",
"h",
".",
"Stop",
":",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"\n",
"default",
":",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"// NewClientConn will close the underlying net.Conn if it gets an error",
"client",
",",
"_",
",",
"_",
",",
"err",
":=",
"ssh",
".",
"NewClientConn",
"(",
"conn",
",",
"addr",
",",
"sshconfig",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"// We don't expect this case, because we don't support Auth,",
"// but make sure to close it anyway.",
"client",
".",
"Close",
"(",
")",
"\n",
"}",
"else",
"{",
"// no need to log these two messages, that's already been done",
"// in hostKeyCallback",
"if",
"!",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"hostKeyAccepted",
".",
"Error",
"(",
")",
")",
"&&",
"!",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"hostKeyNotInList",
".",
"Error",
"(",
")",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Check initiates a connection to HostPort and tries to do an SSH key
// exchange to determine the preferred public key of the remote host.
// It then checks if that key is in the accepted set of keys. | [
"Check",
"initiates",
"a",
"connection",
"to",
"HostPort",
"and",
"tries",
"to",
"do",
"an",
"SSH",
"key",
"exchange",
"to",
"determine",
"the",
"preferred",
"public",
"key",
"of",
"the",
"remote",
"host",
".",
"It",
"then",
"checks",
"if",
"that",
"key",
"is",
"in",
"the",
"accepted",
"set",
"of",
"keys",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/ssh/reachable.go#L133-L182 |
154,874 | juju/juju | network/ssh/reachable.go | FindHost | func (r *reachableChecker) FindHost(hostPorts []network.HostPort, publicKeys []string) (network.HostPort, error) {
uniqueHPs := network.UniqueHostPorts(hostPorts)
successful := make(chan network.HostPort)
stop := make(chan struct{})
// We use a channel instead of a sync.WaitGroup so that we can return as
// soon as we get one connected. We'll signal the rest to stop via the
// 'stop' channel.
finished := make(chan struct{}, len(uniqueHPs))
acceptedKeys := publicKeysToSet(publicKeys)
for _, hostPort := range uniqueHPs {
checker := &hostKeyChecker{
AcceptedKeys: acceptedKeys,
Stop: stop,
Accepted: successful,
HostPort: hostPort,
Dialer: r.dialer,
Finished: finished,
}
go checker.Check()
}
timeout := time.After(r.timeout)
for finishedCount := 0; finishedCount < len(uniqueHPs); {
select {
case result := <-successful:
logger.Infof("found %v has an acceptable ssh key", result)
close(stop)
return result, nil
case <-finished:
finishedCount++
case <-timeout:
break
}
}
close(stop)
return network.HostPort{}, errors.Errorf("cannot connect to any address: %v", hostPorts)
} | go | func (r *reachableChecker) FindHost(hostPorts []network.HostPort, publicKeys []string) (network.HostPort, error) {
uniqueHPs := network.UniqueHostPorts(hostPorts)
successful := make(chan network.HostPort)
stop := make(chan struct{})
// We use a channel instead of a sync.WaitGroup so that we can return as
// soon as we get one connected. We'll signal the rest to stop via the
// 'stop' channel.
finished := make(chan struct{}, len(uniqueHPs))
acceptedKeys := publicKeysToSet(publicKeys)
for _, hostPort := range uniqueHPs {
checker := &hostKeyChecker{
AcceptedKeys: acceptedKeys,
Stop: stop,
Accepted: successful,
HostPort: hostPort,
Dialer: r.dialer,
Finished: finished,
}
go checker.Check()
}
timeout := time.After(r.timeout)
for finishedCount := 0; finishedCount < len(uniqueHPs); {
select {
case result := <-successful:
logger.Infof("found %v has an acceptable ssh key", result)
close(stop)
return result, nil
case <-finished:
finishedCount++
case <-timeout:
break
}
}
close(stop)
return network.HostPort{}, errors.Errorf("cannot connect to any address: %v", hostPorts)
} | [
"func",
"(",
"r",
"*",
"reachableChecker",
")",
"FindHost",
"(",
"hostPorts",
"[",
"]",
"network",
".",
"HostPort",
",",
"publicKeys",
"[",
"]",
"string",
")",
"(",
"network",
".",
"HostPort",
",",
"error",
")",
"{",
"uniqueHPs",
":=",
"network",
".",
"UniqueHostPorts",
"(",
"hostPorts",
")",
"\n",
"successful",
":=",
"make",
"(",
"chan",
"network",
".",
"HostPort",
")",
"\n",
"stop",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"// We use a channel instead of a sync.WaitGroup so that we can return as",
"// soon as we get one connected. We'll signal the rest to stop via the",
"// 'stop' channel.",
"finished",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"len",
"(",
"uniqueHPs",
")",
")",
"\n\n",
"acceptedKeys",
":=",
"publicKeysToSet",
"(",
"publicKeys",
")",
"\n",
"for",
"_",
",",
"hostPort",
":=",
"range",
"uniqueHPs",
"{",
"checker",
":=",
"&",
"hostKeyChecker",
"{",
"AcceptedKeys",
":",
"acceptedKeys",
",",
"Stop",
":",
"stop",
",",
"Accepted",
":",
"successful",
",",
"HostPort",
":",
"hostPort",
",",
"Dialer",
":",
"r",
".",
"dialer",
",",
"Finished",
":",
"finished",
",",
"}",
"\n",
"go",
"checker",
".",
"Check",
"(",
")",
"\n",
"}",
"\n\n",
"timeout",
":=",
"time",
".",
"After",
"(",
"r",
".",
"timeout",
")",
"\n",
"for",
"finishedCount",
":=",
"0",
";",
"finishedCount",
"<",
"len",
"(",
"uniqueHPs",
")",
";",
"{",
"select",
"{",
"case",
"result",
":=",
"<-",
"successful",
":",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"result",
")",
"\n",
"close",
"(",
"stop",
")",
"\n",
"return",
"result",
",",
"nil",
"\n",
"case",
"<-",
"finished",
":",
"finishedCount",
"++",
"\n",
"case",
"<-",
"timeout",
":",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"close",
"(",
"stop",
")",
"\n",
"return",
"network",
".",
"HostPort",
"{",
"}",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hostPorts",
")",
"\n",
"}"
] | // FindHost takes a list of possible host+port combinations and possible public
// keys that the SSH server could be using. We make an attempt to connect to
// each of those addresses and do an SSH handshake negotiation. We then check
// if the SSH server's negotiated public key is in our allowed set. The first
// address to successfully negotiate will be returned. If none of them succeed,
// and error will be returned. | [
"FindHost",
"takes",
"a",
"list",
"of",
"possible",
"host",
"+",
"port",
"combinations",
"and",
"possible",
"public",
"keys",
"that",
"the",
"SSH",
"server",
"could",
"be",
"using",
".",
"We",
"make",
"an",
"attempt",
"to",
"connect",
"to",
"each",
"of",
"those",
"addresses",
"and",
"do",
"an",
"SSH",
"handshake",
"negotiation",
".",
"We",
"then",
"check",
"if",
"the",
"SSH",
"server",
"s",
"negotiated",
"public",
"key",
"is",
"in",
"our",
"allowed",
"set",
".",
"The",
"first",
"address",
"to",
"successfully",
"negotiate",
"will",
"be",
"returned",
".",
"If",
"none",
"of",
"them",
"succeed",
"and",
"error",
"will",
"be",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/ssh/reachable.go#L195-L232 |
154,875 | juju/juju | worker/uniter/storage/attachments.go | NewAttachments | func NewAttachments(
st StorageAccessor,
tag names.UnitTag,
storageStateDir string,
abort <-chan struct{},
) (*Attachments, error) {
a := &Attachments{
st: st,
unitTag: tag,
abort: abort,
storageAttachments: make(map[names.StorageTag]storageAttachment),
storageStateDir: storageStateDir,
pending: names.NewSet(),
}
if err := a.init(); err != nil {
return nil, err
}
return a, nil
} | go | func NewAttachments(
st StorageAccessor,
tag names.UnitTag,
storageStateDir string,
abort <-chan struct{},
) (*Attachments, error) {
a := &Attachments{
st: st,
unitTag: tag,
abort: abort,
storageAttachments: make(map[names.StorageTag]storageAttachment),
storageStateDir: storageStateDir,
pending: names.NewSet(),
}
if err := a.init(); err != nil {
return nil, err
}
return a, nil
} | [
"func",
"NewAttachments",
"(",
"st",
"StorageAccessor",
",",
"tag",
"names",
".",
"UnitTag",
",",
"storageStateDir",
"string",
",",
"abort",
"<-",
"chan",
"struct",
"{",
"}",
",",
")",
"(",
"*",
"Attachments",
",",
"error",
")",
"{",
"a",
":=",
"&",
"Attachments",
"{",
"st",
":",
"st",
",",
"unitTag",
":",
"tag",
",",
"abort",
":",
"abort",
",",
"storageAttachments",
":",
"make",
"(",
"map",
"[",
"names",
".",
"StorageTag",
"]",
"storageAttachment",
")",
",",
"storageStateDir",
":",
"storageStateDir",
",",
"pending",
":",
"names",
".",
"NewSet",
"(",
")",
",",
"}",
"\n",
"if",
"err",
":=",
"a",
".",
"init",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"a",
",",
"nil",
"\n",
"}"
] | // NewAttachments returns a new Attachments. | [
"NewAttachments",
"returns",
"a",
"new",
"Attachments",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/storage/attachments.go#L70-L88 |
154,876 | juju/juju | worker/uniter/storage/attachments.go | init | func (a *Attachments) init() error {
if err := os.MkdirAll(a.storageStateDir, 0755); err != nil {
return errors.Annotate(err, "creating storage state dir")
}
// Query all remote, known storage attachments for the unit,
// so we can cull state files, and store current context.
attachmentIds, err := a.st.UnitStorageAttachments(a.unitTag)
if err != nil {
return errors.Annotate(err, "getting unit attachments")
}
attachmentsByTag := make(map[names.StorageTag]struct{})
for _, attachmentId := range attachmentIds {
storageTag, err := names.ParseStorageTag(attachmentId.StorageTag)
if err != nil {
return errors.Trace(err)
}
attachmentsByTag[storageTag] = struct{}{}
}
stateFiles, err := readAllStateFiles(a.storageStateDir)
if err != nil {
return errors.Annotate(err, "reading storage state dirs")
}
for storageTag, stateFile := range stateFiles {
if _, ok := attachmentsByTag[storageTag]; !ok {
// We have previously removed the storage from state,
// but did not remove the state file. Remove the file.
if err := stateFile.Remove(); err != nil {
return errors.Trace(err)
}
continue
}
// Since there's a state file, we must previously have handled
// at least "storage-attached", so there is no possibility of
// short-circuiting the storage's removal.
attachment, err := a.st.StorageAttachment(storageTag, a.unitTag)
if err != nil {
return errors.Annotatef(
err, "querying storage attachment %q",
storageTag.Id(),
)
}
a.storageAttachments[storageTag] = storageAttachment{
stateFile,
&contextStorage{
tag: storageTag,
kind: storage.StorageKind(attachment.Kind),
location: attachment.Location,
},
}
}
for storageTag := range attachmentsByTag {
if _, ok := stateFiles[storageTag]; !ok {
// There is no state file for the attachment, so no
// hooks have been committed for it.
a.pending.Add(storageTag)
}
// Non-locally recorded attachments will be further handled
// by the resolver.
}
return nil
} | go | func (a *Attachments) init() error {
if err := os.MkdirAll(a.storageStateDir, 0755); err != nil {
return errors.Annotate(err, "creating storage state dir")
}
// Query all remote, known storage attachments for the unit,
// so we can cull state files, and store current context.
attachmentIds, err := a.st.UnitStorageAttachments(a.unitTag)
if err != nil {
return errors.Annotate(err, "getting unit attachments")
}
attachmentsByTag := make(map[names.StorageTag]struct{})
for _, attachmentId := range attachmentIds {
storageTag, err := names.ParseStorageTag(attachmentId.StorageTag)
if err != nil {
return errors.Trace(err)
}
attachmentsByTag[storageTag] = struct{}{}
}
stateFiles, err := readAllStateFiles(a.storageStateDir)
if err != nil {
return errors.Annotate(err, "reading storage state dirs")
}
for storageTag, stateFile := range stateFiles {
if _, ok := attachmentsByTag[storageTag]; !ok {
// We have previously removed the storage from state,
// but did not remove the state file. Remove the file.
if err := stateFile.Remove(); err != nil {
return errors.Trace(err)
}
continue
}
// Since there's a state file, we must previously have handled
// at least "storage-attached", so there is no possibility of
// short-circuiting the storage's removal.
attachment, err := a.st.StorageAttachment(storageTag, a.unitTag)
if err != nil {
return errors.Annotatef(
err, "querying storage attachment %q",
storageTag.Id(),
)
}
a.storageAttachments[storageTag] = storageAttachment{
stateFile,
&contextStorage{
tag: storageTag,
kind: storage.StorageKind(attachment.Kind),
location: attachment.Location,
},
}
}
for storageTag := range attachmentsByTag {
if _, ok := stateFiles[storageTag]; !ok {
// There is no state file for the attachment, so no
// hooks have been committed for it.
a.pending.Add(storageTag)
}
// Non-locally recorded attachments will be further handled
// by the resolver.
}
return nil
} | [
"func",
"(",
"a",
"*",
"Attachments",
")",
"init",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"a",
".",
"storageStateDir",
",",
"0755",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Query all remote, known storage attachments for the unit,",
"// so we can cull state files, and store current context.",
"attachmentIds",
",",
"err",
":=",
"a",
".",
"st",
".",
"UnitStorageAttachments",
"(",
"a",
".",
"unitTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"attachmentsByTag",
":=",
"make",
"(",
"map",
"[",
"names",
".",
"StorageTag",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"attachmentId",
":=",
"range",
"attachmentIds",
"{",
"storageTag",
",",
"err",
":=",
"names",
".",
"ParseStorageTag",
"(",
"attachmentId",
".",
"StorageTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"attachmentsByTag",
"[",
"storageTag",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"stateFiles",
",",
"err",
":=",
"readAllStateFiles",
"(",
"a",
".",
"storageStateDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"storageTag",
",",
"stateFile",
":=",
"range",
"stateFiles",
"{",
"if",
"_",
",",
"ok",
":=",
"attachmentsByTag",
"[",
"storageTag",
"]",
";",
"!",
"ok",
"{",
"// We have previously removed the storage from state,",
"// but did not remove the state file. Remove the file.",
"if",
"err",
":=",
"stateFile",
".",
"Remove",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"// Since there's a state file, we must previously have handled",
"// at least \"storage-attached\", so there is no possibility of",
"// short-circuiting the storage's removal.",
"attachment",
",",
"err",
":=",
"a",
".",
"st",
".",
"StorageAttachment",
"(",
"storageTag",
",",
"a",
".",
"unitTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"storageTag",
".",
"Id",
"(",
")",
",",
")",
"\n",
"}",
"\n",
"a",
".",
"storageAttachments",
"[",
"storageTag",
"]",
"=",
"storageAttachment",
"{",
"stateFile",
",",
"&",
"contextStorage",
"{",
"tag",
":",
"storageTag",
",",
"kind",
":",
"storage",
".",
"StorageKind",
"(",
"attachment",
".",
"Kind",
")",
",",
"location",
":",
"attachment",
".",
"Location",
",",
"}",
",",
"}",
"\n",
"}",
"\n",
"for",
"storageTag",
":=",
"range",
"attachmentsByTag",
"{",
"if",
"_",
",",
"ok",
":=",
"stateFiles",
"[",
"storageTag",
"]",
";",
"!",
"ok",
"{",
"// There is no state file for the attachment, so no",
"// hooks have been committed for it.",
"a",
".",
"pending",
".",
"Add",
"(",
"storageTag",
")",
"\n",
"}",
"\n",
"// Non-locally recorded attachments will be further handled",
"// by the resolver.",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // init processes the storage state directory and creates storagers
// for the state files found. | [
"init",
"processes",
"the",
"storage",
"state",
"directory",
"and",
"creates",
"storagers",
"for",
"the",
"state",
"files",
"found",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/storage/attachments.go#L92-L152 |
154,877 | juju/juju | worker/uniter/storage/attachments.go | SetDying | func (a *Attachments) SetDying() error {
if err := a.st.DestroyUnitStorageAttachments(a.unitTag); err != nil {
return errors.Trace(err)
}
return nil
} | go | func (a *Attachments) SetDying() error {
if err := a.st.DestroyUnitStorageAttachments(a.unitTag); err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"(",
"a",
"*",
"Attachments",
")",
"SetDying",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"a",
".",
"st",
".",
"DestroyUnitStorageAttachments",
"(",
"a",
".",
"unitTag",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetDying ensures that any unprovisioned storage attachments are removed
// from state. | [
"SetDying",
"ensures",
"that",
"any",
"unprovisioned",
"storage",
"attachments",
"are",
"removed",
"from",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/storage/attachments.go#L156-L161 |
154,878 | juju/juju | worker/uniter/storage/attachments.go | Storage | func (a *Attachments) Storage(tag names.StorageTag) (jujuc.ContextStorageAttachment, error) {
if attachment, ok := a.storageAttachments[tag]; ok {
return attachment, nil
}
return nil, errors.NotFoundf("storage")
} | go | func (a *Attachments) Storage(tag names.StorageTag) (jujuc.ContextStorageAttachment, error) {
if attachment, ok := a.storageAttachments[tag]; ok {
return attachment, nil
}
return nil, errors.NotFoundf("storage")
} | [
"func",
"(",
"a",
"*",
"Attachments",
")",
"Storage",
"(",
"tag",
"names",
".",
"StorageTag",
")",
"(",
"jujuc",
".",
"ContextStorageAttachment",
",",
"error",
")",
"{",
"if",
"attachment",
",",
"ok",
":=",
"a",
".",
"storageAttachments",
"[",
"tag",
"]",
";",
"ok",
"{",
"return",
"attachment",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Storage returns the ContextStorage with the supplied tag if it was
// found, and whether it was found. | [
"Storage",
"returns",
"the",
"ContextStorage",
"with",
"the",
"supplied",
"tag",
"if",
"it",
"was",
"found",
"and",
"whether",
"it",
"was",
"found",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/storage/attachments.go#L176-L181 |
154,879 | juju/juju | worker/uniter/storage/attachments.go | StorageTags | func (a *Attachments) StorageTags() ([]names.StorageTag, error) {
tags := names.NewSet()
for tag := range a.storageAttachments {
tags.Add(tag)
}
storageTags := make([]names.StorageTag, tags.Size())
for i, tag := range tags.SortedValues() {
storageTags[i] = tag.(names.StorageTag)
}
return storageTags, nil
} | go | func (a *Attachments) StorageTags() ([]names.StorageTag, error) {
tags := names.NewSet()
for tag := range a.storageAttachments {
tags.Add(tag)
}
storageTags := make([]names.StorageTag, tags.Size())
for i, tag := range tags.SortedValues() {
storageTags[i] = tag.(names.StorageTag)
}
return storageTags, nil
} | [
"func",
"(",
"a",
"*",
"Attachments",
")",
"StorageTags",
"(",
")",
"(",
"[",
"]",
"names",
".",
"StorageTag",
",",
"error",
")",
"{",
"tags",
":=",
"names",
".",
"NewSet",
"(",
")",
"\n",
"for",
"tag",
":=",
"range",
"a",
".",
"storageAttachments",
"{",
"tags",
".",
"Add",
"(",
"tag",
")",
"\n",
"}",
"\n",
"storageTags",
":=",
"make",
"(",
"[",
"]",
"names",
".",
"StorageTag",
",",
"tags",
".",
"Size",
"(",
")",
")",
"\n",
"for",
"i",
",",
"tag",
":=",
"range",
"tags",
".",
"SortedValues",
"(",
")",
"{",
"storageTags",
"[",
"i",
"]",
"=",
"tag",
".",
"(",
"names",
".",
"StorageTag",
")",
"\n",
"}",
"\n",
"return",
"storageTags",
",",
"nil",
"\n",
"}"
] | // StorageTags returns the names.StorageTags for the active storage attachments. | [
"StorageTags",
"returns",
"the",
"names",
".",
"StorageTags",
"for",
"the",
"active",
"storage",
"attachments",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/storage/attachments.go#L184-L194 |
154,880 | juju/juju | worker/uniter/storage/attachments.go | ValidateHook | func (a *Attachments) ValidateHook(hi hook.Info) error {
storageState, err := a.storageStateForHook(hi)
if err != nil {
return errors.Trace(err)
}
return storageState.ValidateHook(hi)
} | go | func (a *Attachments) ValidateHook(hi hook.Info) error {
storageState, err := a.storageStateForHook(hi)
if err != nil {
return errors.Trace(err)
}
return storageState.ValidateHook(hi)
} | [
"func",
"(",
"a",
"*",
"Attachments",
")",
"ValidateHook",
"(",
"hi",
"hook",
".",
"Info",
")",
"error",
"{",
"storageState",
",",
"err",
":=",
"a",
".",
"storageStateForHook",
"(",
"hi",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"storageState",
".",
"ValidateHook",
"(",
"hi",
")",
"\n",
"}"
] | // ValidateHook validates the hook against the current state. | [
"ValidateHook",
"validates",
"the",
"hook",
"against",
"the",
"current",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/storage/attachments.go#L197-L203 |
154,881 | juju/juju | worker/uniter/storage/attachments.go | CommitHook | func (a *Attachments) CommitHook(hi hook.Info) error {
storageState, err := a.storageStateForHook(hi)
if err != nil {
return errors.Trace(err)
}
if err := storageState.CommitHook(hi); err != nil {
return err
}
storageTag := names.NewStorageTag(hi.StorageId)
switch hi.Kind {
case hooks.StorageAttached:
a.pending.Remove(storageTag)
case hooks.StorageDetaching:
if err := a.removeStorageAttachment(storageTag); err != nil {
return errors.Trace(err)
}
}
return nil
} | go | func (a *Attachments) CommitHook(hi hook.Info) error {
storageState, err := a.storageStateForHook(hi)
if err != nil {
return errors.Trace(err)
}
if err := storageState.CommitHook(hi); err != nil {
return err
}
storageTag := names.NewStorageTag(hi.StorageId)
switch hi.Kind {
case hooks.StorageAttached:
a.pending.Remove(storageTag)
case hooks.StorageDetaching:
if err := a.removeStorageAttachment(storageTag); err != nil {
return errors.Trace(err)
}
}
return nil
} | [
"func",
"(",
"a",
"*",
"Attachments",
")",
"CommitHook",
"(",
"hi",
"hook",
".",
"Info",
")",
"error",
"{",
"storageState",
",",
"err",
":=",
"a",
".",
"storageStateForHook",
"(",
"hi",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"storageState",
".",
"CommitHook",
"(",
"hi",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"storageTag",
":=",
"names",
".",
"NewStorageTag",
"(",
"hi",
".",
"StorageId",
")",
"\n",
"switch",
"hi",
".",
"Kind",
"{",
"case",
"hooks",
".",
"StorageAttached",
":",
"a",
".",
"pending",
".",
"Remove",
"(",
"storageTag",
")",
"\n",
"case",
"hooks",
".",
"StorageDetaching",
":",
"if",
"err",
":=",
"a",
".",
"removeStorageAttachment",
"(",
"storageTag",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CommitHook persists the state change encoded in the supplied storage
// hook, or returns an error if the hook is invalid given current state. | [
"CommitHook",
"persists",
"the",
"state",
"change",
"encoded",
"in",
"the",
"supplied",
"storage",
"hook",
"or",
"returns",
"an",
"error",
"if",
"the",
"hook",
"is",
"invalid",
"given",
"current",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/storage/attachments.go#L207-L225 |
154,882 | juju/juju | rpc/client.go | UnmarshalInfo | func (e *RequestError) UnmarshalInfo(to interface{}) error {
if reflect.ValueOf(to).Kind() != reflect.Ptr {
return errors.New("UnmarshalInfo expects a pointer as an argument")
}
data, err := json.Marshal(e.Info)
if err != nil {
return errors.Annotate(err, "could not marshal error information")
}
err = json.Unmarshal(data, to)
if err != nil {
return errors.Annotate(err, "could not unmarshal error information to provided target")
}
return nil
} | go | func (e *RequestError) UnmarshalInfo(to interface{}) error {
if reflect.ValueOf(to).Kind() != reflect.Ptr {
return errors.New("UnmarshalInfo expects a pointer as an argument")
}
data, err := json.Marshal(e.Info)
if err != nil {
return errors.Annotate(err, "could not marshal error information")
}
err = json.Unmarshal(data, to)
if err != nil {
return errors.Annotate(err, "could not unmarshal error information to provided target")
}
return nil
} | [
"func",
"(",
"e",
"*",
"RequestError",
")",
"UnmarshalInfo",
"(",
"to",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"reflect",
".",
"ValueOf",
"(",
"to",
")",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"data",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"e",
".",
"Info",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"to",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalInfo attempts to unmarshal the information contained in the Info
// field of a RequestError into an object instance a pointer to which is passed
// via the to argument. The method will return an error if a non-pointer arg
// is provided. | [
"UnmarshalInfo",
"attempts",
"to",
"unmarshal",
"the",
"information",
"contained",
"in",
"the",
"Info",
"field",
"of",
"a",
"RequestError",
"into",
"an",
"object",
"instance",
"a",
"pointer",
"to",
"which",
"is",
"passed",
"via",
"the",
"to",
"argument",
".",
"The",
"method",
"will",
"return",
"an",
"error",
"if",
"a",
"non",
"-",
"pointer",
"arg",
"is",
"provided",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/rpc/client.go#L55-L70 |
154,883 | juju/juju | rpc/client.go | Call | func (conn *Conn) Call(req Request, params, response interface{}) error {
call := &Call{
Request: req,
Params: params,
Response: response,
Done: make(chan *Call, 1),
}
conn.send(call)
result := <-call.Done
return errors.Trace(result.Error)
} | go | func (conn *Conn) Call(req Request, params, response interface{}) error {
call := &Call{
Request: req,
Params: params,
Response: response,
Done: make(chan *Call, 1),
}
conn.send(call)
result := <-call.Done
return errors.Trace(result.Error)
} | [
"func",
"(",
"conn",
"*",
"Conn",
")",
"Call",
"(",
"req",
"Request",
",",
"params",
",",
"response",
"interface",
"{",
"}",
")",
"error",
"{",
"call",
":=",
"&",
"Call",
"{",
"Request",
":",
"req",
",",
"Params",
":",
"params",
",",
"Response",
":",
"response",
",",
"Done",
":",
"make",
"(",
"chan",
"*",
"Call",
",",
"1",
")",
",",
"}",
"\n",
"conn",
".",
"send",
"(",
"call",
")",
"\n",
"result",
":=",
"<-",
"call",
".",
"Done",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"result",
".",
"Error",
")",
"\n",
"}"
] | // Call invokes the named action on the object of the given type with the given
// id. The returned values will be stored in response, which should be a pointer.
// If the action fails remotely, the error will have a cause of type RequestError.
// The params value may be nil if no parameters are provided; the response value
// may be nil to indicate that any result should be discarded. | [
"Call",
"invokes",
"the",
"named",
"action",
"on",
"the",
"object",
"of",
"the",
"given",
"type",
"with",
"the",
"given",
"id",
".",
"The",
"returned",
"values",
"will",
"be",
"stored",
"in",
"response",
"which",
"should",
"be",
"a",
"pointer",
".",
"If",
"the",
"action",
"fails",
"remotely",
"the",
"error",
"will",
"have",
"a",
"cause",
"of",
"type",
"RequestError",
".",
"The",
"params",
"value",
"may",
"be",
"nil",
"if",
"no",
"parameters",
"are",
"provided",
";",
"the",
"response",
"value",
"may",
"be",
"nil",
"to",
"indicate",
"that",
"any",
"result",
"should",
"be",
"discarded",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/rpc/client.go#L169-L179 |
154,884 | juju/juju | state/modelcredential.go | InvalidateModelCredential | func (st *State) InvalidateModelCredential(reason string) error {
m, err := st.Model()
if err != nil {
return errors.Trace(err)
}
tag, exists := m.CloudCredential()
if !exists {
// Model is on the cloud that does not require auth - nothing to do.
return nil
}
return errors.Trace(st.InvalidateCloudCredential(tag, reason))
} | go | func (st *State) InvalidateModelCredential(reason string) error {
m, err := st.Model()
if err != nil {
return errors.Trace(err)
}
tag, exists := m.CloudCredential()
if !exists {
// Model is on the cloud that does not require auth - nothing to do.
return nil
}
return errors.Trace(st.InvalidateCloudCredential(tag, reason))
} | [
"func",
"(",
"st",
"*",
"State",
")",
"InvalidateModelCredential",
"(",
"reason",
"string",
")",
"error",
"{",
"m",
",",
"err",
":=",
"st",
".",
"Model",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"tag",
",",
"exists",
":=",
"m",
".",
"CloudCredential",
"(",
")",
"\n",
"if",
"!",
"exists",
"{",
"// Model is on the cloud that does not require auth - nothing to do.",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"errors",
".",
"Trace",
"(",
"st",
".",
"InvalidateCloudCredential",
"(",
"tag",
",",
"reason",
")",
")",
"\n",
"}"
] | // InvalidateModelCredential invalidate cloud credential for the model
// of the given state. | [
"InvalidateModelCredential",
"invalidate",
"cloud",
"credential",
"for",
"the",
"model",
"of",
"the",
"given",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelcredential.go#L18-L31 |
154,885 | juju/juju | state/modelcredential.go | ValidateCloudCredential | func (m *Model) ValidateCloudCredential(tag names.CloudCredentialTag, credential cloud.Credential) error {
cloud, err := m.st.Cloud(m.Cloud())
if err != nil {
return errors.Annotatef(err, "getting cloud %q", m.Cloud())
}
err = validateCredentialForCloud(cloud, tag, convertCloudCredentialToState(tag, credential))
if err != nil {
return errors.Annotatef(err, "validating credential %q for cloud %q", tag.Id(), cloud.Name)
}
return nil
} | go | func (m *Model) ValidateCloudCredential(tag names.CloudCredentialTag, credential cloud.Credential) error {
cloud, err := m.st.Cloud(m.Cloud())
if err != nil {
return errors.Annotatef(err, "getting cloud %q", m.Cloud())
}
err = validateCredentialForCloud(cloud, tag, convertCloudCredentialToState(tag, credential))
if err != nil {
return errors.Annotatef(err, "validating credential %q for cloud %q", tag.Id(), cloud.Name)
}
return nil
} | [
"func",
"(",
"m",
"*",
"Model",
")",
"ValidateCloudCredential",
"(",
"tag",
"names",
".",
"CloudCredentialTag",
",",
"credential",
"cloud",
".",
"Credential",
")",
"error",
"{",
"cloud",
",",
"err",
":=",
"m",
".",
"st",
".",
"Cloud",
"(",
"m",
".",
"Cloud",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"m",
".",
"Cloud",
"(",
")",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"validateCredentialForCloud",
"(",
"cloud",
",",
"tag",
",",
"convertCloudCredentialToState",
"(",
"tag",
",",
"credential",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"tag",
".",
"Id",
"(",
")",
",",
"cloud",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ValidateCloudCredential validates new cloud credential for this model. | [
"ValidateCloudCredential",
"validates",
"new",
"cloud",
"credential",
"for",
"this",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelcredential.go#L34-L45 |
154,886 | juju/juju | state/modelcredential.go | SetCloudCredential | func (m *Model) SetCloudCredential(tag names.CloudCredentialTag) (bool, error) {
cloud, err := m.st.Cloud(m.Cloud())
if err != nil {
return false, errors.Annotatef(err, "getting cloud %q", m.Cloud())
}
updating := true
buildTxn := func(attempt int) ([]txn.Op, error) {
if attempt > 0 {
if err := m.Refresh(); err != nil {
return nil, errors.Trace(err)
}
}
if tag.Id() == m.doc.CloudCredential {
updating = false
return nil, jujutxn.ErrNoOperations
}
// Must be a valid credential that is already on the controller.
credential, err := m.st.CloudCredential(tag)
if err != nil {
return nil, errors.Trace(err)
}
if !credential.IsValid() {
return nil, errors.NotValidf("credential %q", tag.Id())
}
if err := validateCredentialForCloud(cloud, tag, credential); err != nil {
return nil, errors.Trace(err)
}
return []txn.Op{{
C: modelsC,
Id: m.doc.UUID,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"cloud-credential", tag.Id()}}}},
}}, nil
}
if err := m.st.db().Run(buildTxn); err != nil {
return false, errors.Trace(err)
}
return updating, m.Refresh()
} | go | func (m *Model) SetCloudCredential(tag names.CloudCredentialTag) (bool, error) {
cloud, err := m.st.Cloud(m.Cloud())
if err != nil {
return false, errors.Annotatef(err, "getting cloud %q", m.Cloud())
}
updating := true
buildTxn := func(attempt int) ([]txn.Op, error) {
if attempt > 0 {
if err := m.Refresh(); err != nil {
return nil, errors.Trace(err)
}
}
if tag.Id() == m.doc.CloudCredential {
updating = false
return nil, jujutxn.ErrNoOperations
}
// Must be a valid credential that is already on the controller.
credential, err := m.st.CloudCredential(tag)
if err != nil {
return nil, errors.Trace(err)
}
if !credential.IsValid() {
return nil, errors.NotValidf("credential %q", tag.Id())
}
if err := validateCredentialForCloud(cloud, tag, credential); err != nil {
return nil, errors.Trace(err)
}
return []txn.Op{{
C: modelsC,
Id: m.doc.UUID,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"cloud-credential", tag.Id()}}}},
}}, nil
}
if err := m.st.db().Run(buildTxn); err != nil {
return false, errors.Trace(err)
}
return updating, m.Refresh()
} | [
"func",
"(",
"m",
"*",
"Model",
")",
"SetCloudCredential",
"(",
"tag",
"names",
".",
"CloudCredentialTag",
")",
"(",
"bool",
",",
"error",
")",
"{",
"cloud",
",",
"err",
":=",
"m",
".",
"st",
".",
"Cloud",
"(",
"m",
".",
"Cloud",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"m",
".",
"Cloud",
"(",
")",
")",
"\n",
"}",
"\n",
"updating",
":=",
"true",
"\n",
"buildTxn",
":=",
"func",
"(",
"attempt",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"if",
"attempt",
">",
"0",
"{",
"if",
"err",
":=",
"m",
".",
"Refresh",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"tag",
".",
"Id",
"(",
")",
"==",
"m",
".",
"doc",
".",
"CloudCredential",
"{",
"updating",
"=",
"false",
"\n",
"return",
"nil",
",",
"jujutxn",
".",
"ErrNoOperations",
"\n",
"}",
"\n",
"// Must be a valid credential that is already on the controller.",
"credential",
",",
"err",
":=",
"m",
".",
"st",
".",
"CloudCredential",
"(",
"tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"!",
"credential",
".",
"IsValid",
"(",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
",",
"tag",
".",
"Id",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"validateCredentialForCloud",
"(",
"cloud",
",",
"tag",
",",
"credential",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"[",
"]",
"txn",
".",
"Op",
"{",
"{",
"C",
":",
"modelsC",
",",
"Id",
":",
"m",
".",
"doc",
".",
"UUID",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"tag",
".",
"Id",
"(",
")",
"}",
"}",
"}",
"}",
",",
"}",
"}",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"m",
".",
"st",
".",
"db",
"(",
")",
".",
"Run",
"(",
"buildTxn",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"updating",
",",
"m",
".",
"Refresh",
"(",
")",
"\n",
"}"
] | // SetCloudCredential sets new cloud credential for this model.
// Returned bool indicates if model credential was set. | [
"SetCloudCredential",
"sets",
"new",
"cloud",
"credential",
"for",
"this",
"model",
".",
"Returned",
"bool",
"indicates",
"if",
"model",
"credential",
"was",
"set",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelcredential.go#L49-L87 |
154,887 | juju/juju | state/modelcredential.go | WatchModelCredential | func (m *Model) WatchModelCredential() NotifyWatcher {
current := m.doc.CloudCredential
filter := func(id interface{}) bool {
id, ok := id.(string)
if !ok || id != m.doc.UUID {
return false
}
models, closer := m.st.db().GetCollection(modelsC)
defer closer()
var doc *modelDoc
if err := models.FindId(id).One(&doc); err != nil {
return false
}
match := current != doc.CloudCredential
current = doc.CloudCredential
return match
}
return newNotifyCollWatcher(m.st, modelsC, filter)
} | go | func (m *Model) WatchModelCredential() NotifyWatcher {
current := m.doc.CloudCredential
filter := func(id interface{}) bool {
id, ok := id.(string)
if !ok || id != m.doc.UUID {
return false
}
models, closer := m.st.db().GetCollection(modelsC)
defer closer()
var doc *modelDoc
if err := models.FindId(id).One(&doc); err != nil {
return false
}
match := current != doc.CloudCredential
current = doc.CloudCredential
return match
}
return newNotifyCollWatcher(m.st, modelsC, filter)
} | [
"func",
"(",
"m",
"*",
"Model",
")",
"WatchModelCredential",
"(",
")",
"NotifyWatcher",
"{",
"current",
":=",
"m",
".",
"doc",
".",
"CloudCredential",
"\n",
"filter",
":=",
"func",
"(",
"id",
"interface",
"{",
"}",
")",
"bool",
"{",
"id",
",",
"ok",
":=",
"id",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"||",
"id",
"!=",
"m",
".",
"doc",
".",
"UUID",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"models",
",",
"closer",
":=",
"m",
".",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"modelsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"doc",
"*",
"modelDoc",
"\n",
"if",
"err",
":=",
"models",
".",
"FindId",
"(",
"id",
")",
".",
"One",
"(",
"&",
"doc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"match",
":=",
"current",
"!=",
"doc",
".",
"CloudCredential",
"\n",
"current",
"=",
"doc",
".",
"CloudCredential",
"\n",
"return",
"match",
"\n",
"}",
"\n",
"return",
"newNotifyCollWatcher",
"(",
"m",
".",
"st",
",",
"modelsC",
",",
"filter",
")",
"\n",
"}"
] | // WatchModelCredential returns a new NotifyWatcher that watches
// a model reference to a cloud credential. | [
"WatchModelCredential",
"returns",
"a",
"new",
"NotifyWatcher",
"that",
"watches",
"a",
"model",
"reference",
"to",
"a",
"cloud",
"credential",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelcredential.go#L91-L112 |
154,888 | juju/juju | api/pubsub/pubsub.go | OpenMessageWriter | func (api *API) OpenMessageWriter() (MessageWriter, error) {
conn, err := api.connector.ConnectStream("/pubsub", nil)
if err != nil {
return nil, errors.Annotatef(err, "cannot connect to /pubsub")
}
messageWriter := &writer{conn}
go messageWriter.readLoop()
return messageWriter, nil
} | go | func (api *API) OpenMessageWriter() (MessageWriter, error) {
conn, err := api.connector.ConnectStream("/pubsub", nil)
if err != nil {
return nil, errors.Annotatef(err, "cannot connect to /pubsub")
}
messageWriter := &writer{conn}
go messageWriter.readLoop()
return messageWriter, nil
} | [
"func",
"(",
"api",
"*",
"API",
")",
"OpenMessageWriter",
"(",
")",
"(",
"MessageWriter",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"api",
".",
"connector",
".",
"ConnectStream",
"(",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"messageWriter",
":=",
"&",
"writer",
"{",
"conn",
"}",
"\n",
"go",
"messageWriter",
".",
"readLoop",
"(",
")",
"\n",
"return",
"messageWriter",
",",
"nil",
"\n",
"}"
] | // OpenMessageWriter returns a new message writer interface value which must
// be closed when finished with. | [
"OpenMessageWriter",
"returns",
"a",
"new",
"message",
"writer",
"interface",
"value",
"which",
"must",
"be",
"closed",
"when",
"finished",
"with",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/pubsub/pubsub.go#L35-L43 |
154,889 | juju/juju | worker/storageprovisioner/internal/schedule/schedule.go | NewSchedule | func NewSchedule(clock clock.Clock) *Schedule {
return &Schedule{
time: clock,
m: make(map[interface{}]*scheduleItem),
}
} | go | func NewSchedule(clock clock.Clock) *Schedule {
return &Schedule{
time: clock,
m: make(map[interface{}]*scheduleItem),
}
} | [
"func",
"NewSchedule",
"(",
"clock",
"clock",
".",
"Clock",
")",
"*",
"Schedule",
"{",
"return",
"&",
"Schedule",
"{",
"time",
":",
"clock",
",",
"m",
":",
"make",
"(",
"map",
"[",
"interface",
"{",
"}",
"]",
"*",
"scheduleItem",
")",
",",
"}",
"\n",
"}"
] | // NewSchedule constructs a new schedule, using the given Clock for the Next
// method. | [
"NewSchedule",
"constructs",
"a",
"new",
"schedule",
"using",
"the",
"given",
"Clock",
"for",
"the",
"Next",
"method",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/internal/schedule/schedule.go#L26-L31 |
154,890 | juju/juju | worker/storageprovisioner/internal/schedule/schedule.go | Next | func (s *Schedule) Next() <-chan time.Time {
if len(s.items) > 0 {
return s.time.After(s.items[0].t.Sub(s.time.Now()))
}
return nil
} | go | func (s *Schedule) Next() <-chan time.Time {
if len(s.items) > 0 {
return s.time.After(s.items[0].t.Sub(s.time.Now()))
}
return nil
} | [
"func",
"(",
"s",
"*",
"Schedule",
")",
"Next",
"(",
")",
"<-",
"chan",
"time",
".",
"Time",
"{",
"if",
"len",
"(",
"s",
".",
"items",
")",
">",
"0",
"{",
"return",
"s",
".",
"time",
".",
"After",
"(",
"s",
".",
"items",
"[",
"0",
"]",
".",
"t",
".",
"Sub",
"(",
"s",
".",
"time",
".",
"Now",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Next returns a channel which will send after the next scheduled item's time
// has been reached. If there are no scheduled items, nil is returned. | [
"Next",
"returns",
"a",
"channel",
"which",
"will",
"send",
"after",
"the",
"next",
"scheduled",
"item",
"s",
"time",
"has",
"been",
"reached",
".",
"If",
"there",
"are",
"no",
"scheduled",
"items",
"nil",
"is",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/internal/schedule/schedule.go#L35-L40 |
154,891 | juju/juju | worker/storageprovisioner/internal/schedule/schedule.go | Ready | func (s *Schedule) Ready(now time.Time) []interface{} {
var ready []interface{}
for len(s.items) > 0 && !s.items[0].t.After(now) {
item := heap.Pop(&s.items).(*scheduleItem)
delete(s.m, item.key)
ready = append(ready, item.value)
}
return ready
} | go | func (s *Schedule) Ready(now time.Time) []interface{} {
var ready []interface{}
for len(s.items) > 0 && !s.items[0].t.After(now) {
item := heap.Pop(&s.items).(*scheduleItem)
delete(s.m, item.key)
ready = append(ready, item.value)
}
return ready
} | [
"func",
"(",
"s",
"*",
"Schedule",
")",
"Ready",
"(",
"now",
"time",
".",
"Time",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"var",
"ready",
"[",
"]",
"interface",
"{",
"}",
"\n",
"for",
"len",
"(",
"s",
".",
"items",
")",
">",
"0",
"&&",
"!",
"s",
".",
"items",
"[",
"0",
"]",
".",
"t",
".",
"After",
"(",
"now",
")",
"{",
"item",
":=",
"heap",
".",
"Pop",
"(",
"&",
"s",
".",
"items",
")",
".",
"(",
"*",
"scheduleItem",
")",
"\n",
"delete",
"(",
"s",
".",
"m",
",",
"item",
".",
"key",
")",
"\n",
"ready",
"=",
"append",
"(",
"ready",
",",
"item",
".",
"value",
")",
"\n",
"}",
"\n",
"return",
"ready",
"\n",
"}"
] | // Ready returns the parameters for items that are scheduled at or before
// "now", and removes them from the schedule. The resulting slices are in
// order of time; items scheduled for the same time have no defined relative
// order. | [
"Ready",
"returns",
"the",
"parameters",
"for",
"items",
"that",
"are",
"scheduled",
"at",
"or",
"before",
"now",
"and",
"removes",
"them",
"from",
"the",
"schedule",
".",
"The",
"resulting",
"slices",
"are",
"in",
"order",
"of",
"time",
";",
"items",
"scheduled",
"for",
"the",
"same",
"time",
"have",
"no",
"defined",
"relative",
"order",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/internal/schedule/schedule.go#L46-L54 |
154,892 | juju/juju | worker/storageprovisioner/internal/schedule/schedule.go | Add | func (s *Schedule) Add(key, value interface{}, t time.Time) {
if _, ok := s.m[key]; ok {
panic(errors.Errorf("duplicate key %v", key))
}
item := &scheduleItem{key: key, value: value, t: t}
s.m[key] = item
heap.Push(&s.items, item)
} | go | func (s *Schedule) Add(key, value interface{}, t time.Time) {
if _, ok := s.m[key]; ok {
panic(errors.Errorf("duplicate key %v", key))
}
item := &scheduleItem{key: key, value: value, t: t}
s.m[key] = item
heap.Push(&s.items, item)
} | [
"func",
"(",
"s",
"*",
"Schedule",
")",
"Add",
"(",
"key",
",",
"value",
"interface",
"{",
"}",
",",
"t",
"time",
".",
"Time",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"m",
"[",
"key",
"]",
";",
"ok",
"{",
"panic",
"(",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
")",
")",
"\n",
"}",
"\n",
"item",
":=",
"&",
"scheduleItem",
"{",
"key",
":",
"key",
",",
"value",
":",
"value",
",",
"t",
":",
"t",
"}",
"\n",
"s",
".",
"m",
"[",
"key",
"]",
"=",
"item",
"\n",
"heap",
".",
"Push",
"(",
"&",
"s",
".",
"items",
",",
"item",
")",
"\n",
"}"
] | // Add adds an item with the specified value, with the corresponding key
// and time to the schedule. Add will panic if there already exists an item
// with the same key. | [
"Add",
"adds",
"an",
"item",
"with",
"the",
"specified",
"value",
"with",
"the",
"corresponding",
"key",
"and",
"time",
"to",
"the",
"schedule",
".",
"Add",
"will",
"panic",
"if",
"there",
"already",
"exists",
"an",
"item",
"with",
"the",
"same",
"key",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/internal/schedule/schedule.go#L59-L66 |
154,893 | juju/juju | worker/storageprovisioner/internal/schedule/schedule.go | Remove | func (s *Schedule) Remove(key interface{}) {
if item, ok := s.m[key]; ok {
heap.Remove(&s.items, item.i)
delete(s.m, key)
}
} | go | func (s *Schedule) Remove(key interface{}) {
if item, ok := s.m[key]; ok {
heap.Remove(&s.items, item.i)
delete(s.m, key)
}
} | [
"func",
"(",
"s",
"*",
"Schedule",
")",
"Remove",
"(",
"key",
"interface",
"{",
"}",
")",
"{",
"if",
"item",
",",
"ok",
":=",
"s",
".",
"m",
"[",
"key",
"]",
";",
"ok",
"{",
"heap",
".",
"Remove",
"(",
"&",
"s",
".",
"items",
",",
"item",
".",
"i",
")",
"\n",
"delete",
"(",
"s",
".",
"m",
",",
"key",
")",
"\n",
"}",
"\n",
"}"
] | // Remove removes the item corresponding to the specified key from the
// schedule. If no item with the specified key exists, this is a no-op. | [
"Remove",
"removes",
"the",
"item",
"corresponding",
"to",
"the",
"specified",
"key",
"from",
"the",
"schedule",
".",
"If",
"no",
"item",
"with",
"the",
"specified",
"key",
"exists",
"this",
"is",
"a",
"no",
"-",
"op",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/internal/schedule/schedule.go#L70-L75 |
154,894 | juju/juju | apiserver/common/reboot.go | RequestReboot | func (r *RebootRequester) RequestReboot(args params.Entities) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
if len(args.Entities) == 0 {
return result, nil
}
auth, err := r.auth()
if err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
for i, entity := range args.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
result.Results[i].Error = ServerError(ErrPerm)
continue
}
err = ErrPerm
if auth(tag) {
err = r.oneRequest(tag)
}
result.Results[i].Error = ServerError(err)
}
return result, nil
} | go | func (r *RebootRequester) RequestReboot(args params.Entities) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
if len(args.Entities) == 0 {
return result, nil
}
auth, err := r.auth()
if err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
for i, entity := range args.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
result.Results[i].Error = ServerError(ErrPerm)
continue
}
err = ErrPerm
if auth(tag) {
err = r.oneRequest(tag)
}
result.Results[i].Error = ServerError(err)
}
return result, nil
} | [
"func",
"(",
"r",
"*",
"RebootRequester",
")",
"RequestReboot",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"ErrorResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"ErrorResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"if",
"len",
"(",
"args",
".",
"Entities",
")",
"==",
"0",
"{",
"return",
"result",
",",
"nil",
"\n",
"}",
"\n",
"auth",
",",
"err",
":=",
"r",
".",
"auth",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ErrorResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"entity",
":=",
"range",
"args",
".",
"Entities",
"{",
"tag",
",",
"err",
":=",
"names",
".",
"ParseTag",
"(",
"entity",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"ErrPerm",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"err",
"=",
"ErrPerm",
"\n",
"if",
"auth",
"(",
"tag",
")",
"{",
"err",
"=",
"r",
".",
"oneRequest",
"(",
"tag",
")",
"\n",
"}",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // RequestReboot sets the reboot flag on the provided machines | [
"RequestReboot",
"sets",
"the",
"reboot",
"flag",
"on",
"the",
"provided",
"machines"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/reboot.go#L41-L65 |
154,895 | juju/juju | state/open.go | Validate | func (p OpenParams) Validate() error {
if p.Clock == nil {
return errors.NotValidf("nil Clock")
}
if p.ControllerTag == (names.ControllerTag{}) {
return errors.NotValidf("empty ControllerTag")
}
if p.ControllerModelTag == (names.ModelTag{}) {
return errors.NotValidf("empty ControllerModelTag")
}
if p.MongoSession == nil {
return errors.NotValidf("nil MongoSession")
}
return nil
} | go | func (p OpenParams) Validate() error {
if p.Clock == nil {
return errors.NotValidf("nil Clock")
}
if p.ControllerTag == (names.ControllerTag{}) {
return errors.NotValidf("empty ControllerTag")
}
if p.ControllerModelTag == (names.ModelTag{}) {
return errors.NotValidf("empty ControllerModelTag")
}
if p.MongoSession == nil {
return errors.NotValidf("nil MongoSession")
}
return nil
} | [
"func",
"(",
"p",
"OpenParams",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"p",
".",
"Clock",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"p",
".",
"ControllerTag",
"==",
"(",
"names",
".",
"ControllerTag",
"{",
"}",
")",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"p",
".",
"ControllerModelTag",
"==",
"(",
"names",
".",
"ModelTag",
"{",
"}",
")",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"p",
".",
"MongoSession",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate validates the OpenParams. | [
"Validate",
"validates",
"the",
"OpenParams",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/open.go#L56-L70 |
154,896 | juju/juju | state/open.go | OpenController | func OpenController(args OpenParams) (*Controller, error) {
pool, err := OpenStatePool(args)
if err != nil {
return nil, errors.Trace(err)
}
return &Controller{
pool: pool,
ownsPool: true,
}, nil
} | go | func OpenController(args OpenParams) (*Controller, error) {
pool, err := OpenStatePool(args)
if err != nil {
return nil, errors.Trace(err)
}
return &Controller{
pool: pool,
ownsPool: true,
}, nil
} | [
"func",
"OpenController",
"(",
"args",
"OpenParams",
")",
"(",
"*",
"Controller",
",",
"error",
")",
"{",
"pool",
",",
"err",
":=",
"OpenStatePool",
"(",
"args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"Controller",
"{",
"pool",
":",
"pool",
",",
"ownsPool",
":",
"true",
",",
"}",
",",
"nil",
"\n",
"}"
] | // OpenController connects to the server with the given parameters, waits for it
// to be initialized, and returns a new Controller instance.
//
// OpenController returns unauthorizedError if access is unauthorized. | [
"OpenController",
"connects",
"to",
"the",
"server",
"with",
"the",
"given",
"parameters",
"waits",
"for",
"it",
"to",
"be",
"initialized",
"and",
"returns",
"a",
"new",
"Controller",
"instance",
".",
"OpenController",
"returns",
"unauthorizedError",
"if",
"access",
"is",
"unauthorized",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/open.go#L76-L86 |
154,897 | juju/juju | state/open.go | Open | func Open(args OpenParams) (*State, error) {
if err := args.Validate(); err != nil {
return nil, errors.Annotate(err, "validating args")
}
session := args.MongoSession.Copy()
st, err := open(
args.ControllerModelTag,
session,
args.InitDatabaseFunc,
nil,
args.NewPolicy,
args.Clock,
args.RunTransactionObserver,
)
if err != nil {
session.Close()
return nil, errors.Trace(err)
}
if _, err := st.Model(); err != nil {
if err := st.Close(); err != nil {
logger.Errorf("closing State for %s: %v", args.ControllerModelTag, err)
}
return nil, mongo.MaybeUnauthorizedf(err, "cannot read model %s", args.ControllerModelTag.Id())
}
// State should only be Opened on behalf of a controller environ; all
// other *States must be obtained via StatePool.
if err := st.start(args.ControllerTag, nil); err != nil {
return nil, errors.Trace(err)
}
return st, nil
} | go | func Open(args OpenParams) (*State, error) {
if err := args.Validate(); err != nil {
return nil, errors.Annotate(err, "validating args")
}
session := args.MongoSession.Copy()
st, err := open(
args.ControllerModelTag,
session,
args.InitDatabaseFunc,
nil,
args.NewPolicy,
args.Clock,
args.RunTransactionObserver,
)
if err != nil {
session.Close()
return nil, errors.Trace(err)
}
if _, err := st.Model(); err != nil {
if err := st.Close(); err != nil {
logger.Errorf("closing State for %s: %v", args.ControllerModelTag, err)
}
return nil, mongo.MaybeUnauthorizedf(err, "cannot read model %s", args.ControllerModelTag.Id())
}
// State should only be Opened on behalf of a controller environ; all
// other *States must be obtained via StatePool.
if err := st.start(args.ControllerTag, nil); err != nil {
return nil, errors.Trace(err)
}
return st, nil
} | [
"func",
"Open",
"(",
"args",
"OpenParams",
")",
"(",
"*",
"State",
",",
"error",
")",
"{",
"if",
"err",
":=",
"args",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"session",
":=",
"args",
".",
"MongoSession",
".",
"Copy",
"(",
")",
"\n",
"st",
",",
"err",
":=",
"open",
"(",
"args",
".",
"ControllerModelTag",
",",
"session",
",",
"args",
".",
"InitDatabaseFunc",
",",
"nil",
",",
"args",
".",
"NewPolicy",
",",
"args",
".",
"Clock",
",",
"args",
".",
"RunTransactionObserver",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"session",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"st",
".",
"Model",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
":=",
"st",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"args",
".",
"ControllerModelTag",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"mongo",
".",
"MaybeUnauthorizedf",
"(",
"err",
",",
"\"",
"\"",
",",
"args",
".",
"ControllerModelTag",
".",
"Id",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// State should only be Opened on behalf of a controller environ; all",
"// other *States must be obtained via StatePool.",
"if",
"err",
":=",
"st",
".",
"start",
"(",
"args",
".",
"ControllerTag",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"st",
",",
"nil",
"\n",
"}"
] | // Open connects to the server with the given parameters, waits for it
// to be initialized, and returns a new State representing the model
// connected to.
//
// Open returns unauthorizedError if access is unauthorized. | [
"Open",
"connects",
"to",
"the",
"server",
"with",
"the",
"given",
"parameters",
"waits",
"for",
"it",
"to",
"be",
"initialized",
"and",
"returns",
"a",
"new",
"State",
"representing",
"the",
"model",
"connected",
"to",
".",
"Open",
"returns",
"unauthorizedError",
"if",
"access",
"is",
"unauthorized",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/open.go#L93-L124 |
154,898 | juju/juju | apiserver/facades/agent/provisioner/mocks/profile_mock.go | NewMockProfileMachine | func NewMockProfileMachine(ctrl *gomock.Controller) *MockProfileMachine {
mock := &MockProfileMachine{ctrl: ctrl}
mock.recorder = &MockProfileMachineMockRecorder{mock}
return mock
} | go | func NewMockProfileMachine(ctrl *gomock.Controller) *MockProfileMachine {
mock := &MockProfileMachine{ctrl: ctrl}
mock.recorder = &MockProfileMachineMockRecorder{mock}
return mock
} | [
"func",
"NewMockProfileMachine",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockProfileMachine",
"{",
"mock",
":=",
"&",
"MockProfileMachine",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockProfileMachineMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockProfileMachine creates a new mock instance | [
"NewMockProfileMachine",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/mocks/profile_mock.go#L27-L31 |
154,899 | juju/juju | apiserver/facades/agent/provisioner/mocks/profile_mock.go | UpgradeCharmProfileCharmURL | func (m *MockProfileMachine) UpgradeCharmProfileCharmURL(arg0 string) (string, error) {
ret := m.ctrl.Call(m, "UpgradeCharmProfileCharmURL", arg0)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockProfileMachine) UpgradeCharmProfileCharmURL(arg0 string) (string, error) {
ret := m.ctrl.Call(m, "UpgradeCharmProfileCharmURL", arg0)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockProfileMachine",
")",
"UpgradeCharmProfileCharmURL",
"(",
"arg0",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"string",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // UpgradeCharmProfileCharmURL mocks base method | [
"UpgradeCharmProfileCharmURL",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/mocks/profile_mock.go#L76-L81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.