id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
4,200 | juju/juju | cmd/jujud/agent/unit.go | Run | func (a *UnitAgent) Run(ctx *cmd.Context) (err error) {
defer a.Done(err)
if err := a.ReadConfig(a.Tag().String()); err != nil {
return err
}
setupAgentLogging(a.CurrentConfig())
a.runner.StartWorker("api", a.APIWorkers)
err = cmdutil.AgentDone(logger, a.runner.Wait())
return err
} | go | func (a *UnitAgent) Run(ctx *cmd.Context) (err error) {
defer a.Done(err)
if err := a.ReadConfig(a.Tag().String()); err != nil {
return err
}
setupAgentLogging(a.CurrentConfig())
a.runner.StartWorker("api", a.APIWorkers)
err = cmdutil.AgentDone(logger, a.runner.Wait())
return err
} | [
"func",
"(",
"a",
"*",
"UnitAgent",
")",
"Run",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"a",
".",
"Done",
"(",
"err",
")",
"\n",
"if",
"err",
":=",
"a",
".",
"ReadConfig",
"(",
"a",
".",
"Tag",
"(",
")",
".",
"String",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"setupAgentLogging",
"(",
"a",
".",
"CurrentConfig",
"(",
")",
")",
"\n\n",
"a",
".",
"runner",
".",
"StartWorker",
"(",
"\"",
"\"",
",",
"a",
".",
"APIWorkers",
")",
"\n",
"err",
"=",
"cmdutil",
".",
"AgentDone",
"(",
"logger",
",",
"a",
".",
"runner",
".",
"Wait",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Run runs a unit agent. | [
"Run",
"runs",
"a",
"unit",
"agent",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/unit.go#L159-L169 |
4,201 | juju/juju | cmd/jujud/agent/unit.go | APIWorkers | func (a *UnitAgent) APIWorkers() (worker.Worker, error) {
updateAgentConfLogging := func(loggingConfig string) error {
return a.AgentConf.ChangeConfig(func(setter agent.ConfigSetter) error {
setter.SetLoggingConfig(loggingConfig)
return nil
})
}
agentConfig := a.AgentConf.CurrentConfig()
a.upgradeComplete = upgradesteps.NewLock(agentConfig)
machineLock, err := machinelock.New(machinelock.Config{
AgentName: a.Tag().String(),
Clock: clock.WallClock,
Logger: loggo.GetLogger("juju.machinelock"),
LogFilename: agent.MachineLockLogFilename(agentConfig),
})
// There will only be an error if the required configuration
// values are not passed in.
if err != nil {
return nil, errors.Trace(err)
}
manifolds := unitManifolds(unit.ManifoldsConfig{
Agent: agent.APIHostPortsSetter{a},
LogSource: a.bufferedLogger.Logs(),
LeadershipGuarantee: 30 * time.Second,
AgentConfigChanged: a.configChangedVal,
ValidateMigration: a.validateMigration,
PrometheusRegisterer: a.prometheusRegistry,
UpdateLoggerConfig: updateAgentConfLogging,
PreviousAgentVersion: agentConfig.UpgradedToVersion(),
PreUpgradeSteps: a.preUpgradeSteps,
UpgradeStepsLock: a.upgradeComplete,
UpgradeCheckLock: a.initialUpgradeCheckComplete,
MachineLock: machineLock,
})
engine, err := dependency.NewEngine(dependencyEngineConfig())
if err != nil {
return nil, err
}
if err := dependency.Install(engine, manifolds); err != nil {
if err := worker.Stop(engine); err != nil {
logger.Errorf("while stopping engine with bad manifolds: %v", err)
}
return nil, err
}
if err := startIntrospection(introspectionConfig{
Agent: a,
Engine: engine,
NewSocketName: DefaultIntrospectionSocketName,
PrometheusGatherer: a.prometheusRegistry,
MachineLock: machineLock,
WorkerFunc: introspection.NewWorker,
}); err != nil {
// If the introspection worker failed to start, we just log error
// but continue. It is very unlikely to happen in the real world
// as the only issue is connecting to the abstract domain socket
// and the agent is controlled by by the OS to only have one.
logger.Errorf("failed to start introspection worker: %v", err)
}
return engine, nil
} | go | func (a *UnitAgent) APIWorkers() (worker.Worker, error) {
updateAgentConfLogging := func(loggingConfig string) error {
return a.AgentConf.ChangeConfig(func(setter agent.ConfigSetter) error {
setter.SetLoggingConfig(loggingConfig)
return nil
})
}
agentConfig := a.AgentConf.CurrentConfig()
a.upgradeComplete = upgradesteps.NewLock(agentConfig)
machineLock, err := machinelock.New(machinelock.Config{
AgentName: a.Tag().String(),
Clock: clock.WallClock,
Logger: loggo.GetLogger("juju.machinelock"),
LogFilename: agent.MachineLockLogFilename(agentConfig),
})
// There will only be an error if the required configuration
// values are not passed in.
if err != nil {
return nil, errors.Trace(err)
}
manifolds := unitManifolds(unit.ManifoldsConfig{
Agent: agent.APIHostPortsSetter{a},
LogSource: a.bufferedLogger.Logs(),
LeadershipGuarantee: 30 * time.Second,
AgentConfigChanged: a.configChangedVal,
ValidateMigration: a.validateMigration,
PrometheusRegisterer: a.prometheusRegistry,
UpdateLoggerConfig: updateAgentConfLogging,
PreviousAgentVersion: agentConfig.UpgradedToVersion(),
PreUpgradeSteps: a.preUpgradeSteps,
UpgradeStepsLock: a.upgradeComplete,
UpgradeCheckLock: a.initialUpgradeCheckComplete,
MachineLock: machineLock,
})
engine, err := dependency.NewEngine(dependencyEngineConfig())
if err != nil {
return nil, err
}
if err := dependency.Install(engine, manifolds); err != nil {
if err := worker.Stop(engine); err != nil {
logger.Errorf("while stopping engine with bad manifolds: %v", err)
}
return nil, err
}
if err := startIntrospection(introspectionConfig{
Agent: a,
Engine: engine,
NewSocketName: DefaultIntrospectionSocketName,
PrometheusGatherer: a.prometheusRegistry,
MachineLock: machineLock,
WorkerFunc: introspection.NewWorker,
}); err != nil {
// If the introspection worker failed to start, we just log error
// but continue. It is very unlikely to happen in the real world
// as the only issue is connecting to the abstract domain socket
// and the agent is controlled by by the OS to only have one.
logger.Errorf("failed to start introspection worker: %v", err)
}
return engine, nil
} | [
"func",
"(",
"a",
"*",
"UnitAgent",
")",
"APIWorkers",
"(",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"updateAgentConfLogging",
":=",
"func",
"(",
"loggingConfig",
"string",
")",
"error",
"{",
"return",
"a",
".",
"AgentConf",
".",
"ChangeConfig",
"(",
"func",
"(",
"setter",
"agent",
".",
"ConfigSetter",
")",
"error",
"{",
"setter",
".",
"SetLoggingConfig",
"(",
"loggingConfig",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}",
"\n\n",
"agentConfig",
":=",
"a",
".",
"AgentConf",
".",
"CurrentConfig",
"(",
")",
"\n",
"a",
".",
"upgradeComplete",
"=",
"upgradesteps",
".",
"NewLock",
"(",
"agentConfig",
")",
"\n",
"machineLock",
",",
"err",
":=",
"machinelock",
".",
"New",
"(",
"machinelock",
".",
"Config",
"{",
"AgentName",
":",
"a",
".",
"Tag",
"(",
")",
".",
"String",
"(",
")",
",",
"Clock",
":",
"clock",
".",
"WallClock",
",",
"Logger",
":",
"loggo",
".",
"GetLogger",
"(",
"\"",
"\"",
")",
",",
"LogFilename",
":",
"agent",
".",
"MachineLockLogFilename",
"(",
"agentConfig",
")",
",",
"}",
")",
"\n",
"// There will only be an error if the required configuration",
"// values are not passed in.",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"manifolds",
":=",
"unitManifolds",
"(",
"unit",
".",
"ManifoldsConfig",
"{",
"Agent",
":",
"agent",
".",
"APIHostPortsSetter",
"{",
"a",
"}",
",",
"LogSource",
":",
"a",
".",
"bufferedLogger",
".",
"Logs",
"(",
")",
",",
"LeadershipGuarantee",
":",
"30",
"*",
"time",
".",
"Second",
",",
"AgentConfigChanged",
":",
"a",
".",
"configChangedVal",
",",
"ValidateMigration",
":",
"a",
".",
"validateMigration",
",",
"PrometheusRegisterer",
":",
"a",
".",
"prometheusRegistry",
",",
"UpdateLoggerConfig",
":",
"updateAgentConfLogging",
",",
"PreviousAgentVersion",
":",
"agentConfig",
".",
"UpgradedToVersion",
"(",
")",
",",
"PreUpgradeSteps",
":",
"a",
".",
"preUpgradeSteps",
",",
"UpgradeStepsLock",
":",
"a",
".",
"upgradeComplete",
",",
"UpgradeCheckLock",
":",
"a",
".",
"initialUpgradeCheckComplete",
",",
"MachineLock",
":",
"machineLock",
",",
"}",
")",
"\n\n",
"engine",
",",
"err",
":=",
"dependency",
".",
"NewEngine",
"(",
"dependencyEngineConfig",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"dependency",
".",
"Install",
"(",
"engine",
",",
"manifolds",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
":=",
"worker",
".",
"Stop",
"(",
"engine",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"startIntrospection",
"(",
"introspectionConfig",
"{",
"Agent",
":",
"a",
",",
"Engine",
":",
"engine",
",",
"NewSocketName",
":",
"DefaultIntrospectionSocketName",
",",
"PrometheusGatherer",
":",
"a",
".",
"prometheusRegistry",
",",
"MachineLock",
":",
"machineLock",
",",
"WorkerFunc",
":",
"introspection",
".",
"NewWorker",
",",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"// If the introspection worker failed to start, we just log error",
"// but continue. It is very unlikely to happen in the real world",
"// as the only issue is connecting to the abstract domain socket",
"// and the agent is controlled by by the OS to only have one.",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"engine",
",",
"nil",
"\n",
"}"
] | // APIWorkers returns a dependency.Engine running the unit agent's responsibilities. | [
"APIWorkers",
"returns",
"a",
"dependency",
".",
"Engine",
"running",
"the",
"unit",
"agent",
"s",
"responsibilities",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/unit.go#L172-L234 |
4,202 | juju/juju | apiserver/facades/controller/crosscontroller/crosscontroller.go | NewStateCrossControllerAPI | func NewStateCrossControllerAPI(ctx facade.Context) (*CrossControllerAPI, error) {
st := ctx.State()
return NewCrossControllerAPI(
ctx.Resources(),
func() ([]string, string, error) { return common.StateControllerInfo(st) },
st.WatchAPIHostPortsForClients,
)
} | go | func NewStateCrossControllerAPI(ctx facade.Context) (*CrossControllerAPI, error) {
st := ctx.State()
return NewCrossControllerAPI(
ctx.Resources(),
func() ([]string, string, error) { return common.StateControllerInfo(st) },
st.WatchAPIHostPortsForClients,
)
} | [
"func",
"NewStateCrossControllerAPI",
"(",
"ctx",
"facade",
".",
"Context",
")",
"(",
"*",
"CrossControllerAPI",
",",
"error",
")",
"{",
"st",
":=",
"ctx",
".",
"State",
"(",
")",
"\n",
"return",
"NewCrossControllerAPI",
"(",
"ctx",
".",
"Resources",
"(",
")",
",",
"func",
"(",
")",
"(",
"[",
"]",
"string",
",",
"string",
",",
"error",
")",
"{",
"return",
"common",
".",
"StateControllerInfo",
"(",
"st",
")",
"}",
",",
"st",
".",
"WatchAPIHostPortsForClients",
",",
")",
"\n",
"}"
] | // NewStateCrossControllerAPI creates a new server-side CrossModelRelations API facade
// backed by global state. | [
"NewStateCrossControllerAPI",
"creates",
"a",
"new",
"server",
"-",
"side",
"CrossModelRelations",
"API",
"facade",
"backed",
"by",
"global",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crosscontroller/crosscontroller.go#L30-L37 |
4,203 | juju/juju | apiserver/facades/controller/crosscontroller/crosscontroller.go | NewCrossControllerAPI | func NewCrossControllerAPI(
resources facade.Resources,
localControllerInfo localControllerInfoFunc,
watchLocalControllerInfo watchLocalControllerInfoFunc,
) (*CrossControllerAPI, error) {
return &CrossControllerAPI{
resources: resources,
localControllerInfo: localControllerInfo,
watchLocalControllerInfo: watchLocalControllerInfo,
}, nil
} | go | func NewCrossControllerAPI(
resources facade.Resources,
localControllerInfo localControllerInfoFunc,
watchLocalControllerInfo watchLocalControllerInfoFunc,
) (*CrossControllerAPI, error) {
return &CrossControllerAPI{
resources: resources,
localControllerInfo: localControllerInfo,
watchLocalControllerInfo: watchLocalControllerInfo,
}, nil
} | [
"func",
"NewCrossControllerAPI",
"(",
"resources",
"facade",
".",
"Resources",
",",
"localControllerInfo",
"localControllerInfoFunc",
",",
"watchLocalControllerInfo",
"watchLocalControllerInfoFunc",
",",
")",
"(",
"*",
"CrossControllerAPI",
",",
"error",
")",
"{",
"return",
"&",
"CrossControllerAPI",
"{",
"resources",
":",
"resources",
",",
"localControllerInfo",
":",
"localControllerInfo",
",",
"watchLocalControllerInfo",
":",
"watchLocalControllerInfo",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewCrossControllerAPI returns a new server-side CrossControllerAPI facade. | [
"NewCrossControllerAPI",
"returns",
"a",
"new",
"server",
"-",
"side",
"CrossControllerAPI",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crosscontroller/crosscontroller.go#L40-L50 |
4,204 | juju/juju | apiserver/facades/controller/crosscontroller/crosscontroller.go | WatchControllerInfo | func (api *CrossControllerAPI) WatchControllerInfo() (params.NotifyWatchResults, error) {
results := params.NotifyWatchResults{
Results: make([]params.NotifyWatchResult, 1),
}
w := api.watchLocalControllerInfo()
if _, ok := <-w.Changes(); !ok {
results.Results[0].Error = common.ServerError(watcher.EnsureErr(w))
return results, nil
}
results.Results[0].NotifyWatcherId = api.resources.Register(w)
return results, nil
} | go | func (api *CrossControllerAPI) WatchControllerInfo() (params.NotifyWatchResults, error) {
results := params.NotifyWatchResults{
Results: make([]params.NotifyWatchResult, 1),
}
w := api.watchLocalControllerInfo()
if _, ok := <-w.Changes(); !ok {
results.Results[0].Error = common.ServerError(watcher.EnsureErr(w))
return results, nil
}
results.Results[0].NotifyWatcherId = api.resources.Register(w)
return results, nil
} | [
"func",
"(",
"api",
"*",
"CrossControllerAPI",
")",
"WatchControllerInfo",
"(",
")",
"(",
"params",
".",
"NotifyWatchResults",
",",
"error",
")",
"{",
"results",
":=",
"params",
".",
"NotifyWatchResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"NotifyWatchResult",
",",
"1",
")",
",",
"}",
"\n",
"w",
":=",
"api",
".",
"watchLocalControllerInfo",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"<-",
"w",
".",
"Changes",
"(",
")",
";",
"!",
"ok",
"{",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"watcher",
".",
"EnsureErr",
"(",
"w",
")",
")",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}",
"\n",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"NotifyWatcherId",
"=",
"api",
".",
"resources",
".",
"Register",
"(",
"w",
")",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // WatchControllerInfo creates a watcher that notifies when the API info
// for the controller changes. | [
"WatchControllerInfo",
"creates",
"a",
"watcher",
"that",
"notifies",
"when",
"the",
"API",
"info",
"for",
"the",
"controller",
"changes",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crosscontroller/crosscontroller.go#L54-L65 |
4,205 | juju/juju | apiserver/facades/controller/crosscontroller/crosscontroller.go | ControllerInfo | func (api *CrossControllerAPI) ControllerInfo() (params.ControllerAPIInfoResults, error) {
results := params.ControllerAPIInfoResults{
Results: make([]params.ControllerAPIInfoResult, 1),
}
addrs, caCert, err := api.localControllerInfo()
if err != nil {
results.Results[0].Error = common.ServerError(err)
return results, nil
}
results.Results[0].Addresses = addrs
results.Results[0].CACert = caCert
return results, nil
} | go | func (api *CrossControllerAPI) ControllerInfo() (params.ControllerAPIInfoResults, error) {
results := params.ControllerAPIInfoResults{
Results: make([]params.ControllerAPIInfoResult, 1),
}
addrs, caCert, err := api.localControllerInfo()
if err != nil {
results.Results[0].Error = common.ServerError(err)
return results, nil
}
results.Results[0].Addresses = addrs
results.Results[0].CACert = caCert
return results, nil
} | [
"func",
"(",
"api",
"*",
"CrossControllerAPI",
")",
"ControllerInfo",
"(",
")",
"(",
"params",
".",
"ControllerAPIInfoResults",
",",
"error",
")",
"{",
"results",
":=",
"params",
".",
"ControllerAPIInfoResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"ControllerAPIInfoResult",
",",
"1",
")",
",",
"}",
"\n",
"addrs",
",",
"caCert",
",",
"err",
":=",
"api",
".",
"localControllerInfo",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}",
"\n",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"Addresses",
"=",
"addrs",
"\n",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"CACert",
"=",
"caCert",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // ControllerInfo returns the API info for the controller. | [
"ControllerInfo",
"returns",
"the",
"API",
"info",
"for",
"the",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crosscontroller/crosscontroller.go#L68-L80 |
4,206 | juju/juju | resource/context/context.go | NewContextAPI | func NewContextAPI(apiClient APIClient, dataDir string) *Context {
return &Context{
apiClient: apiClient,
dataDir: dataDir,
}
} | go | func NewContextAPI(apiClient APIClient, dataDir string) *Context {
return &Context{
apiClient: apiClient,
dataDir: dataDir,
}
} | [
"func",
"NewContextAPI",
"(",
"apiClient",
"APIClient",
",",
"dataDir",
"string",
")",
"*",
"Context",
"{",
"return",
"&",
"Context",
"{",
"apiClient",
":",
"apiClient",
",",
"dataDir",
":",
"dataDir",
",",
"}",
"\n",
"}"
] | // NewContextAPI returns a new Content for the given API client and data dir. | [
"NewContextAPI",
"returns",
"a",
"new",
"Content",
"for",
"the",
"given",
"API",
"client",
"and",
"data",
"dir",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/context.go#L44-L49 |
4,207 | juju/juju | resource/context/context.go | Download | func (c *Context) Download(name string) (string, error) {
deps := &contextDeps{
APIClient: c.apiClient,
name: name,
dataDir: c.dataDir,
}
path, err := internal.ContextDownload(deps)
if err != nil {
return "", errors.Trace(err)
}
return path, nil
} | go | func (c *Context) Download(name string) (string, error) {
deps := &contextDeps{
APIClient: c.apiClient,
name: name,
dataDir: c.dataDir,
}
path, err := internal.ContextDownload(deps)
if err != nil {
return "", errors.Trace(err)
}
return path, nil
} | [
"func",
"(",
"c",
"*",
"Context",
")",
"Download",
"(",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"deps",
":=",
"&",
"contextDeps",
"{",
"APIClient",
":",
"c",
".",
"apiClient",
",",
"name",
":",
"name",
",",
"dataDir",
":",
"c",
".",
"dataDir",
",",
"}",
"\n",
"path",
",",
"err",
":=",
"internal",
".",
"ContextDownload",
"(",
"deps",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"path",
",",
"nil",
"\n",
"}"
] | // Download downloads the named resource and returns the path
// to which it was downloaded. If the resource does not exist or has
// not been uploaded yet then errors.NotFound is returned.
//
// Note that the downloaded file is checked for correctness. | [
"Download",
"downloads",
"the",
"named",
"resource",
"and",
"returns",
"the",
"path",
"to",
"which",
"it",
"was",
"downloaded",
".",
"If",
"the",
"resource",
"does",
"not",
"exist",
"or",
"has",
"not",
"been",
"uploaded",
"yet",
"then",
"errors",
".",
"NotFound",
"is",
"returned",
".",
"Note",
"that",
"the",
"downloaded",
"file",
"is",
"checked",
"for",
"correctness",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/context.go#L61-L72 |
4,208 | juju/juju | worker/storageprovisioner/common.go | attachmentLife | func attachmentLife(ctx *context, ids []params.MachineStorageId) (
alive, dying, dead []params.MachineStorageId, _ error,
) {
lifeResults, err := ctx.config.Life.AttachmentLife(ids)
if err != nil {
return nil, nil, nil, errors.Annotate(err, "getting machine attachment life")
}
for i, result := range lifeResults {
life := result.Life
if result.Error != nil {
if !params.IsCodeNotFound(result.Error) {
return nil, nil, nil, errors.Annotatef(
result.Error, "getting life of %s attached to %s",
ids[i].AttachmentTag, ids[i].MachineTag,
)
}
life = params.Dead
}
switch life {
case params.Alive:
alive = append(alive, ids[i])
case params.Dying:
dying = append(dying, ids[i])
case params.Dead:
dead = append(dead, ids[i])
}
}
return alive, dying, dead, nil
} | go | func attachmentLife(ctx *context, ids []params.MachineStorageId) (
alive, dying, dead []params.MachineStorageId, _ error,
) {
lifeResults, err := ctx.config.Life.AttachmentLife(ids)
if err != nil {
return nil, nil, nil, errors.Annotate(err, "getting machine attachment life")
}
for i, result := range lifeResults {
life := result.Life
if result.Error != nil {
if !params.IsCodeNotFound(result.Error) {
return nil, nil, nil, errors.Annotatef(
result.Error, "getting life of %s attached to %s",
ids[i].AttachmentTag, ids[i].MachineTag,
)
}
life = params.Dead
}
switch life {
case params.Alive:
alive = append(alive, ids[i])
case params.Dying:
dying = append(dying, ids[i])
case params.Dead:
dead = append(dead, ids[i])
}
}
return alive, dying, dead, nil
} | [
"func",
"attachmentLife",
"(",
"ctx",
"*",
"context",
",",
"ids",
"[",
"]",
"params",
".",
"MachineStorageId",
")",
"(",
"alive",
",",
"dying",
",",
"dead",
"[",
"]",
"params",
".",
"MachineStorageId",
",",
"_",
"error",
",",
")",
"{",
"lifeResults",
",",
"err",
":=",
"ctx",
".",
"config",
".",
"Life",
".",
"AttachmentLife",
"(",
"ids",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"result",
":=",
"range",
"lifeResults",
"{",
"life",
":=",
"result",
".",
"Life",
"\n",
"if",
"result",
".",
"Error",
"!=",
"nil",
"{",
"if",
"!",
"params",
".",
"IsCodeNotFound",
"(",
"result",
".",
"Error",
")",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"result",
".",
"Error",
",",
"\"",
"\"",
",",
"ids",
"[",
"i",
"]",
".",
"AttachmentTag",
",",
"ids",
"[",
"i",
"]",
".",
"MachineTag",
",",
")",
"\n",
"}",
"\n",
"life",
"=",
"params",
".",
"Dead",
"\n",
"}",
"\n",
"switch",
"life",
"{",
"case",
"params",
".",
"Alive",
":",
"alive",
"=",
"append",
"(",
"alive",
",",
"ids",
"[",
"i",
"]",
")",
"\n",
"case",
"params",
".",
"Dying",
":",
"dying",
"=",
"append",
"(",
"dying",
",",
"ids",
"[",
"i",
"]",
")",
"\n",
"case",
"params",
".",
"Dead",
":",
"dead",
"=",
"append",
"(",
"dead",
",",
"ids",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"alive",
",",
"dying",
",",
"dead",
",",
"nil",
"\n",
"}"
] | // attachmentLife queries the lifecycle state of each specified
// attachment, and then partitions the IDs by them. | [
"attachmentLife",
"queries",
"the",
"lifecycle",
"state",
"of",
"each",
"specified",
"attachment",
"and",
"then",
"partitions",
"the",
"IDs",
"by",
"them",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/common.go#L50-L78 |
4,209 | juju/juju | worker/storageprovisioner/common.go | removeEntities | func removeEntities(ctx *context, tags []names.Tag) error {
if len(tags) == 0 {
return nil
}
logger.Debugf("removing entities: %v", tags)
errorResults, err := ctx.config.Life.Remove(tags)
if err != nil {
return errors.Annotate(err, "removing storage entities")
}
for i, result := range errorResults {
if result.Error != nil {
return errors.Annotatef(result.Error, "removing %s from state", names.ReadableString(tags[i]))
}
}
return nil
} | go | func removeEntities(ctx *context, tags []names.Tag) error {
if len(tags) == 0 {
return nil
}
logger.Debugf("removing entities: %v", tags)
errorResults, err := ctx.config.Life.Remove(tags)
if err != nil {
return errors.Annotate(err, "removing storage entities")
}
for i, result := range errorResults {
if result.Error != nil {
return errors.Annotatef(result.Error, "removing %s from state", names.ReadableString(tags[i]))
}
}
return nil
} | [
"func",
"removeEntities",
"(",
"ctx",
"*",
"context",
",",
"tags",
"[",
"]",
"names",
".",
"Tag",
")",
"error",
"{",
"if",
"len",
"(",
"tags",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"tags",
")",
"\n",
"errorResults",
",",
"err",
":=",
"ctx",
".",
"config",
".",
"Life",
".",
"Remove",
"(",
"tags",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"result",
":=",
"range",
"errorResults",
"{",
"if",
"result",
".",
"Error",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"result",
".",
"Error",
",",
"\"",
"\"",
",",
"names",
".",
"ReadableString",
"(",
"tags",
"[",
"i",
"]",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // removeEntities removes each specified Dead entity from state. | [
"removeEntities",
"removes",
"each",
"specified",
"Dead",
"entity",
"from",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/common.go#L81-L96 |
4,210 | juju/juju | worker/storageprovisioner/common.go | removeAttachments | func removeAttachments(ctx *context, ids []params.MachineStorageId) error {
if len(ids) == 0 {
return nil
}
errorResults, err := ctx.config.Life.RemoveAttachments(ids)
if err != nil {
return errors.Annotate(err, "removing attachments")
}
for i, result := range errorResults {
if result.Error != nil && !params.IsCodeNotFound(result.Error) {
// ignore not found error.
return errors.Annotatef(
result.Error, "removing attachment of %s to %s from state",
ids[i].AttachmentTag, ids[i].MachineTag,
)
}
}
return nil
} | go | func removeAttachments(ctx *context, ids []params.MachineStorageId) error {
if len(ids) == 0 {
return nil
}
errorResults, err := ctx.config.Life.RemoveAttachments(ids)
if err != nil {
return errors.Annotate(err, "removing attachments")
}
for i, result := range errorResults {
if result.Error != nil && !params.IsCodeNotFound(result.Error) {
// ignore not found error.
return errors.Annotatef(
result.Error, "removing attachment of %s to %s from state",
ids[i].AttachmentTag, ids[i].MachineTag,
)
}
}
return nil
} | [
"func",
"removeAttachments",
"(",
"ctx",
"*",
"context",
",",
"ids",
"[",
"]",
"params",
".",
"MachineStorageId",
")",
"error",
"{",
"if",
"len",
"(",
"ids",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"errorResults",
",",
"err",
":=",
"ctx",
".",
"config",
".",
"Life",
".",
"RemoveAttachments",
"(",
"ids",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"result",
":=",
"range",
"errorResults",
"{",
"if",
"result",
".",
"Error",
"!=",
"nil",
"&&",
"!",
"params",
".",
"IsCodeNotFound",
"(",
"result",
".",
"Error",
")",
"{",
"// ignore not found error.",
"return",
"errors",
".",
"Annotatef",
"(",
"result",
".",
"Error",
",",
"\"",
"\"",
",",
"ids",
"[",
"i",
"]",
".",
"AttachmentTag",
",",
"ids",
"[",
"i",
"]",
".",
"MachineTag",
",",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // removeAttachments removes each specified attachment from state. | [
"removeAttachments",
"removes",
"each",
"specified",
"attachment",
"from",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/common.go#L99-L117 |
4,211 | juju/juju | worker/storageprovisioner/common.go | setStatus | func setStatus(ctx *context, statuses []params.EntityStatusArgs) {
if len(statuses) > 0 {
if err := ctx.config.Status.SetStatus(statuses); err != nil {
logger.Errorf("failed to set status: %v", err)
}
}
} | go | func setStatus(ctx *context, statuses []params.EntityStatusArgs) {
if len(statuses) > 0 {
if err := ctx.config.Status.SetStatus(statuses); err != nil {
logger.Errorf("failed to set status: %v", err)
}
}
} | [
"func",
"setStatus",
"(",
"ctx",
"*",
"context",
",",
"statuses",
"[",
"]",
"params",
".",
"EntityStatusArgs",
")",
"{",
"if",
"len",
"(",
"statuses",
")",
">",
"0",
"{",
"if",
"err",
":=",
"ctx",
".",
"config",
".",
"Status",
".",
"SetStatus",
"(",
"statuses",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // setStatus sets the given entity statuses, if any. If setting
// the status fails the error is logged but otherwise ignored. | [
"setStatus",
"sets",
"the",
"given",
"entity",
"statuses",
"if",
"any",
".",
"If",
"setting",
"the",
"status",
"fails",
"the",
"error",
"is",
"logged",
"but",
"otherwise",
"ignored",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/common.go#L121-L127 |
4,212 | juju/juju | state/backups/archive.go | NewNonCanonicalArchivePaths | func NewNonCanonicalArchivePaths(rootDir string) ArchivePaths {
return ArchivePaths{
ContentDir: filepath.Join(rootDir, contentDir),
FilesBundle: filepath.Join(rootDir, contentDir, filesBundle),
DBDumpDir: filepath.Join(rootDir, contentDir, dbDumpDir),
MetadataFile: filepath.Join(rootDir, contentDir, metadataFile),
}
} | go | func NewNonCanonicalArchivePaths(rootDir string) ArchivePaths {
return ArchivePaths{
ContentDir: filepath.Join(rootDir, contentDir),
FilesBundle: filepath.Join(rootDir, contentDir, filesBundle),
DBDumpDir: filepath.Join(rootDir, contentDir, dbDumpDir),
MetadataFile: filepath.Join(rootDir, contentDir, metadataFile),
}
} | [
"func",
"NewNonCanonicalArchivePaths",
"(",
"rootDir",
"string",
")",
"ArchivePaths",
"{",
"return",
"ArchivePaths",
"{",
"ContentDir",
":",
"filepath",
".",
"Join",
"(",
"rootDir",
",",
"contentDir",
")",
",",
"FilesBundle",
":",
"filepath",
".",
"Join",
"(",
"rootDir",
",",
"contentDir",
",",
"filesBundle",
")",
",",
"DBDumpDir",
":",
"filepath",
".",
"Join",
"(",
"rootDir",
",",
"contentDir",
",",
"dbDumpDir",
")",
",",
"MetadataFile",
":",
"filepath",
".",
"Join",
"(",
"rootDir",
",",
"contentDir",
",",
"metadataFile",
")",
",",
"}",
"\n",
"}"
] | // NonCanonicalArchivePaths builds a new ArchivePaths using default
// values, rooted at the provided rootDir. The path separator used is
// platform-dependent. The resulting paths are suitable for locating
// backup archive contents in a directory into which an archive has
// been unpacked. | [
"NonCanonicalArchivePaths",
"builds",
"a",
"new",
"ArchivePaths",
"using",
"default",
"values",
"rooted",
"at",
"the",
"provided",
"rootDir",
".",
"The",
"path",
"separator",
"used",
"is",
"platform",
"-",
"dependent",
".",
"The",
"resulting",
"paths",
"are",
"suitable",
"for",
"locating",
"backup",
"archive",
"contents",
"in",
"a",
"directory",
"into",
"which",
"an",
"archive",
"has",
"been",
"unpacked",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L70-L77 |
4,213 | juju/juju | state/backups/archive.go | NewArchiveWorkspaceReader | func NewArchiveWorkspaceReader(archive io.Reader) (*ArchiveWorkspace, error) {
ws, err := newArchiveWorkspace()
if err != nil {
return nil, errors.Trace(err)
}
err = unpackCompressedReader(ws.RootDir, archive)
return ws, errors.Trace(err)
} | go | func NewArchiveWorkspaceReader(archive io.Reader) (*ArchiveWorkspace, error) {
ws, err := newArchiveWorkspace()
if err != nil {
return nil, errors.Trace(err)
}
err = unpackCompressedReader(ws.RootDir, archive)
return ws, errors.Trace(err)
} | [
"func",
"NewArchiveWorkspaceReader",
"(",
"archive",
"io",
".",
"Reader",
")",
"(",
"*",
"ArchiveWorkspace",
",",
"error",
")",
"{",
"ws",
",",
"err",
":=",
"newArchiveWorkspace",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"unpackCompressedReader",
"(",
"ws",
".",
"RootDir",
",",
"archive",
")",
"\n",
"return",
"ws",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // NewArchiveWorkspaceReader returns a new archive workspace with a new
// workspace dir populated from the archive. Note that this involves
// unpacking the entire archive into a directory under the host's
// "temporary" directory. For relatively large archives this could have
// adverse effects on hosts with little disk space. | [
"NewArchiveWorkspaceReader",
"returns",
"a",
"new",
"archive",
"workspace",
"with",
"a",
"new",
"workspace",
"dir",
"populated",
"from",
"the",
"archive",
".",
"Note",
"that",
"this",
"involves",
"unpacking",
"the",
"entire",
"archive",
"into",
"a",
"directory",
"under",
"the",
"host",
"s",
"temporary",
"directory",
".",
"For",
"relatively",
"large",
"archives",
"this",
"could",
"have",
"adverse",
"effects",
"on",
"hosts",
"with",
"little",
"disk",
"space",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L104-L111 |
4,214 | juju/juju | state/backups/archive.go | Close | func (ws *ArchiveWorkspace) Close() error {
err := os.RemoveAll(ws.RootDir)
return errors.Trace(err)
} | go | func (ws *ArchiveWorkspace) Close() error {
err := os.RemoveAll(ws.RootDir)
return errors.Trace(err)
} | [
"func",
"(",
"ws",
"*",
"ArchiveWorkspace",
")",
"Close",
"(",
")",
"error",
"{",
"err",
":=",
"os",
".",
"RemoveAll",
"(",
"ws",
".",
"RootDir",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // Close cleans up the workspace dir. | [
"Close",
"cleans",
"up",
"the",
"workspace",
"dir",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L123-L126 |
4,215 | juju/juju | state/backups/archive.go | UnpackFilesBundle | func (ws *ArchiveWorkspace) UnpackFilesBundle(targetRoot string) error {
tarFile, err := os.Open(ws.FilesBundle)
if err != nil {
return errors.Trace(err)
}
defer tarFile.Close()
err = tar.UntarFiles(tarFile, targetRoot)
return errors.Trace(err)
} | go | func (ws *ArchiveWorkspace) UnpackFilesBundle(targetRoot string) error {
tarFile, err := os.Open(ws.FilesBundle)
if err != nil {
return errors.Trace(err)
}
defer tarFile.Close()
err = tar.UntarFiles(tarFile, targetRoot)
return errors.Trace(err)
} | [
"func",
"(",
"ws",
"*",
"ArchiveWorkspace",
")",
"UnpackFilesBundle",
"(",
"targetRoot",
"string",
")",
"error",
"{",
"tarFile",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"ws",
".",
"FilesBundle",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"tarFile",
".",
"Close",
"(",
")",
"\n\n",
"err",
"=",
"tar",
".",
"UntarFiles",
"(",
"tarFile",
",",
"targetRoot",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // UnpackFilesBundle unpacks the archived files bundle into the targeted dir. | [
"UnpackFilesBundle",
"unpacks",
"the",
"archived",
"files",
"bundle",
"into",
"the",
"targeted",
"dir",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L129-L138 |
4,216 | juju/juju | state/backups/archive.go | OpenBundledFile | func (ws *ArchiveWorkspace) OpenBundledFile(filename string) (io.Reader, error) {
if filepath.IsAbs(filename) {
return nil, errors.Errorf("filename must be relative, got %q", filename)
}
tarFile, err := os.Open(ws.FilesBundle)
if err != nil {
return nil, errors.Trace(err)
}
_, file, err := tar.FindFile(tarFile, filename)
if err != nil {
tarFile.Close()
return nil, errors.Trace(err)
}
return file, nil
} | go | func (ws *ArchiveWorkspace) OpenBundledFile(filename string) (io.Reader, error) {
if filepath.IsAbs(filename) {
return nil, errors.Errorf("filename must be relative, got %q", filename)
}
tarFile, err := os.Open(ws.FilesBundle)
if err != nil {
return nil, errors.Trace(err)
}
_, file, err := tar.FindFile(tarFile, filename)
if err != nil {
tarFile.Close()
return nil, errors.Trace(err)
}
return file, nil
} | [
"func",
"(",
"ws",
"*",
"ArchiveWorkspace",
")",
"OpenBundledFile",
"(",
"filename",
"string",
")",
"(",
"io",
".",
"Reader",
",",
"error",
")",
"{",
"if",
"filepath",
".",
"IsAbs",
"(",
"filename",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"filename",
")",
"\n",
"}",
"\n\n",
"tarFile",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"ws",
".",
"FilesBundle",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"_",
",",
"file",
",",
"err",
":=",
"tar",
".",
"FindFile",
"(",
"tarFile",
",",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"tarFile",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"file",
",",
"nil",
"\n",
"}"
] | // OpenBundledFile returns an open ReadCloser for the corresponding file in
// the archived files bundle. | [
"OpenBundledFile",
"returns",
"an",
"open",
"ReadCloser",
"for",
"the",
"corresponding",
"file",
"in",
"the",
"archived",
"files",
"bundle",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L142-L158 |
4,217 | juju/juju | state/backups/archive.go | Metadata | func (ws *ArchiveWorkspace) Metadata() (*Metadata, error) {
metaFile, err := os.Open(ws.MetadataFile)
if err != nil {
return nil, errors.Trace(err)
}
defer metaFile.Close()
meta, err := NewMetadataJSONReader(metaFile)
return meta, errors.Trace(err)
} | go | func (ws *ArchiveWorkspace) Metadata() (*Metadata, error) {
metaFile, err := os.Open(ws.MetadataFile)
if err != nil {
return nil, errors.Trace(err)
}
defer metaFile.Close()
meta, err := NewMetadataJSONReader(metaFile)
return meta, errors.Trace(err)
} | [
"func",
"(",
"ws",
"*",
"ArchiveWorkspace",
")",
"Metadata",
"(",
")",
"(",
"*",
"Metadata",
",",
"error",
")",
"{",
"metaFile",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"ws",
".",
"MetadataFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"metaFile",
".",
"Close",
"(",
")",
"\n\n",
"meta",
",",
"err",
":=",
"NewMetadataJSONReader",
"(",
"metaFile",
")",
"\n",
"return",
"meta",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // Metadata returns the metadata derived from the JSON file in the archive. | [
"Metadata",
"returns",
"the",
"metadata",
"derived",
"from",
"the",
"JSON",
"file",
"in",
"the",
"archive",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L161-L170 |
4,218 | juju/juju | state/backups/archive.go | NewArchiveDataReader | func NewArchiveDataReader(r io.Reader) (*ArchiveData, error) {
gzr, err := gzip.NewReader(r)
if err != nil {
return nil, errors.Trace(err)
}
defer gzr.Close()
data, err := ioutil.ReadAll(gzr)
if err != nil {
return nil, errors.Trace(err)
}
return NewArchiveData(data), nil
} | go | func NewArchiveDataReader(r io.Reader) (*ArchiveData, error) {
gzr, err := gzip.NewReader(r)
if err != nil {
return nil, errors.Trace(err)
}
defer gzr.Close()
data, err := ioutil.ReadAll(gzr)
if err != nil {
return nil, errors.Trace(err)
}
return NewArchiveData(data), nil
} | [
"func",
"NewArchiveDataReader",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"ArchiveData",
",",
"error",
")",
"{",
"gzr",
",",
"err",
":=",
"gzip",
".",
"NewReader",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"gzr",
".",
"Close",
"(",
")",
"\n\n",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"gzr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"NewArchiveData",
"(",
"data",
")",
",",
"nil",
"\n",
"}"
] | // NewArchiveReader returns a new archive data wrapper for the data in
// the provided reader. Note that the entire archive will be read into
// memory and kept there. So for relatively large archives it will often
// be more appropriate to use ArchiveWorkspace instead. | [
"NewArchiveReader",
"returns",
"a",
"new",
"archive",
"data",
"wrapper",
"for",
"the",
"data",
"in",
"the",
"provided",
"reader",
".",
"Note",
"that",
"the",
"entire",
"archive",
"will",
"be",
"read",
"into",
"memory",
"and",
"kept",
"there",
".",
"So",
"for",
"relatively",
"large",
"archives",
"it",
"will",
"often",
"be",
"more",
"appropriate",
"to",
"use",
"ArchiveWorkspace",
"instead",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L196-L209 |
4,219 | juju/juju | state/backups/archive.go | Metadata | func (ad *ArchiveData) Metadata() (*Metadata, error) {
buf := ad.NewBuffer()
_, metaFile, err := tar.FindFile(buf, ad.MetadataFile)
if err != nil {
return nil, errors.Trace(err)
}
meta, err := NewMetadataJSONReader(metaFile)
return meta, errors.Trace(err)
} | go | func (ad *ArchiveData) Metadata() (*Metadata, error) {
buf := ad.NewBuffer()
_, metaFile, err := tar.FindFile(buf, ad.MetadataFile)
if err != nil {
return nil, errors.Trace(err)
}
meta, err := NewMetadataJSONReader(metaFile)
return meta, errors.Trace(err)
} | [
"func",
"(",
"ad",
"*",
"ArchiveData",
")",
"Metadata",
"(",
")",
"(",
"*",
"Metadata",
",",
"error",
")",
"{",
"buf",
":=",
"ad",
".",
"NewBuffer",
"(",
")",
"\n",
"_",
",",
"metaFile",
",",
"err",
":=",
"tar",
".",
"FindFile",
"(",
"buf",
",",
"ad",
".",
"MetadataFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"meta",
",",
"err",
":=",
"NewMetadataJSONReader",
"(",
"metaFile",
")",
"\n",
"return",
"meta",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // Metadata returns the metadata stored in the backup archive. If no
// metadata is there, errors.NotFound is returned. | [
"Metadata",
"returns",
"the",
"metadata",
"stored",
"in",
"the",
"backup",
"archive",
".",
"If",
"no",
"metadata",
"is",
"there",
"errors",
".",
"NotFound",
"is",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L218-L227 |
4,220 | juju/juju | state/backups/archive.go | Version | func (ad *ArchiveData) Version() (*version.Number, error) {
meta, err := ad.Metadata()
if errors.IsNotFound(err) {
return &legacyVersion, nil
}
if err != nil {
return nil, errors.Trace(err)
}
return &meta.Origin.Version, nil
} | go | func (ad *ArchiveData) Version() (*version.Number, error) {
meta, err := ad.Metadata()
if errors.IsNotFound(err) {
return &legacyVersion, nil
}
if err != nil {
return nil, errors.Trace(err)
}
return &meta.Origin.Version, nil
} | [
"func",
"(",
"ad",
"*",
"ArchiveData",
")",
"Version",
"(",
")",
"(",
"*",
"version",
".",
"Number",
",",
"error",
")",
"{",
"meta",
",",
"err",
":=",
"ad",
".",
"Metadata",
"(",
")",
"\n",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"&",
"legacyVersion",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"meta",
".",
"Origin",
".",
"Version",
",",
"nil",
"\n",
"}"
] | // Version returns the juju version under which the backup archive
// was created. If no version is found in the archive, it must come
// from before backup archives included the version. In that case we
// return version 1.20. | [
"Version",
"returns",
"the",
"juju",
"version",
"under",
"which",
"the",
"backup",
"archive",
"was",
"created",
".",
"If",
"no",
"version",
"is",
"found",
"in",
"the",
"archive",
"it",
"must",
"come",
"from",
"before",
"backup",
"archives",
"included",
"the",
"version",
".",
"In",
"that",
"case",
"we",
"return",
"version",
"1",
".",
"20",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L233-L243 |
4,221 | juju/juju | worker/uniter/runner/args.go | searchHook | func searchHook(charmDir, hook string) (string, error) {
hookFile := filepath.Join(charmDir, hook)
if jujuos.HostOS() != jujuos.Windows {
// we are not running on windows,
// there is no need to look for suffixed hooks
return lookPath(hookFile)
}
for _, suffix := range windowsSuffixOrder {
file := fmt.Sprintf("%s%s", hookFile, suffix)
foundHook, err := lookPath(file)
if err != nil {
if charmrunner.IsMissingHookError(err) {
// look for next suffix
continue
}
return "", err
}
return foundHook, nil
}
return "", charmrunner.NewMissingHookError(hook)
} | go | func searchHook(charmDir, hook string) (string, error) {
hookFile := filepath.Join(charmDir, hook)
if jujuos.HostOS() != jujuos.Windows {
// we are not running on windows,
// there is no need to look for suffixed hooks
return lookPath(hookFile)
}
for _, suffix := range windowsSuffixOrder {
file := fmt.Sprintf("%s%s", hookFile, suffix)
foundHook, err := lookPath(file)
if err != nil {
if charmrunner.IsMissingHookError(err) {
// look for next suffix
continue
}
return "", err
}
return foundHook, nil
}
return "", charmrunner.NewMissingHookError(hook)
} | [
"func",
"searchHook",
"(",
"charmDir",
",",
"hook",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"hookFile",
":=",
"filepath",
".",
"Join",
"(",
"charmDir",
",",
"hook",
")",
"\n",
"if",
"jujuos",
".",
"HostOS",
"(",
")",
"!=",
"jujuos",
".",
"Windows",
"{",
"// we are not running on windows,",
"// there is no need to look for suffixed hooks",
"return",
"lookPath",
"(",
"hookFile",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"suffix",
":=",
"range",
"windowsSuffixOrder",
"{",
"file",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"hookFile",
",",
"suffix",
")",
"\n",
"foundHook",
",",
"err",
":=",
"lookPath",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"charmrunner",
".",
"IsMissingHookError",
"(",
"err",
")",
"{",
"// look for next suffix",
"continue",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"foundHook",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"charmrunner",
".",
"NewMissingHookError",
"(",
"hook",
")",
"\n",
"}"
] | // searchHook will search, in order, hooks suffixed with extensions
// in windowsSuffixOrder. As windows cares about extensions to determine
// how to execute a file, we will allow several suffixes, with powershell
// being default. | [
"searchHook",
"will",
"search",
"in",
"order",
"hooks",
"suffixed",
"with",
"extensions",
"in",
"windowsSuffixOrder",
".",
"As",
"windows",
"cares",
"about",
"extensions",
"to",
"determine",
"how",
"to",
"execute",
"a",
"file",
"we",
"will",
"allow",
"several",
"suffixes",
"with",
"powershell",
"being",
"default",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/args.go#L40-L60 |
4,222 | juju/juju | apiserver/facades/agent/provisioner/provisioninginfo.go | ProvisioningInfo | func (p *ProvisionerAPI) ProvisioningInfo(args params.Entities) (params.ProvisioningInfoResults, error) {
result := params.ProvisioningInfoResults{
Results: make([]params.ProvisioningInfoResult, len(args.Entities)),
}
canAccess, err := p.getAuthFunc()
if err != nil {
return result, errors.Trace(err)
}
env, err := environs.GetEnviron(p.configGetter, environs.New)
if err != nil {
return result, errors.Annotate(err, "could not get environ")
}
for i, entity := range args.Entities {
tag, err := names.ParseMachineTag(entity.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
machine, err := p.getMachine(canAccess, tag)
if err == nil {
result.Results[i].Result, err = p.getProvisioningInfo(machine, env)
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
} | go | func (p *ProvisionerAPI) ProvisioningInfo(args params.Entities) (params.ProvisioningInfoResults, error) {
result := params.ProvisioningInfoResults{
Results: make([]params.ProvisioningInfoResult, len(args.Entities)),
}
canAccess, err := p.getAuthFunc()
if err != nil {
return result, errors.Trace(err)
}
env, err := environs.GetEnviron(p.configGetter, environs.New)
if err != nil {
return result, errors.Annotate(err, "could not get environ")
}
for i, entity := range args.Entities {
tag, err := names.ParseMachineTag(entity.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
machine, err := p.getMachine(canAccess, tag)
if err == nil {
result.Results[i].Result, err = p.getProvisioningInfo(machine, env)
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
} | [
"func",
"(",
"p",
"*",
"ProvisionerAPI",
")",
"ProvisioningInfo",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"ProvisioningInfoResults",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"ProvisioningInfoResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"ProvisioningInfoResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"canAccess",
",",
"err",
":=",
"p",
".",
"getAuthFunc",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"env",
",",
"err",
":=",
"environs",
".",
"GetEnviron",
"(",
"p",
".",
"configGetter",
",",
"environs",
".",
"New",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"entity",
":=",
"range",
"args",
".",
"Entities",
"{",
"tag",
",",
"err",
":=",
"names",
".",
"ParseMachineTag",
"(",
"entity",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"common",
".",
"ErrPerm",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"machine",
",",
"err",
":=",
"p",
".",
"getMachine",
"(",
"canAccess",
",",
"tag",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Result",
",",
"err",
"=",
"p",
".",
"getProvisioningInfo",
"(",
"machine",
",",
"env",
")",
"\n",
"}",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // ProvisioningInfo returns the provisioning information for each given machine entity. | [
"ProvisioningInfo",
"returns",
"the",
"provisioning",
"information",
"for",
"each",
"given",
"machine",
"entity",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L32-L57 |
4,223 | juju/juju | apiserver/facades/agent/provisioner/provisioninginfo.go | machineTags | func (p *ProvisionerAPI) machineTags(m *state.Machine, jobs []multiwatcher.MachineJob) (map[string]string, error) {
// Names of all units deployed to the machine.
//
// TODO(axw) 2015-06-02 #1461358
// We need a worker that periodically updates
// instance tags with current deployment info.
units, err := m.Units()
if err != nil {
return nil, errors.Trace(err)
}
unitNames := make([]string, 0, len(units))
for _, unit := range units {
if !unit.IsPrincipal() {
continue
}
unitNames = append(unitNames, unit.Name())
}
sort.Strings(unitNames)
cfg, err := p.m.ModelConfig()
if err != nil {
return nil, errors.Trace(err)
}
controllerCfg, err := p.st.ControllerConfig()
if err != nil {
return nil, errors.Trace(err)
}
machineTags := instancecfg.InstanceTags(cfg.UUID(), controllerCfg.ControllerUUID(), cfg, jobs)
if len(unitNames) > 0 {
machineTags[tags.JujuUnitsDeployed] = strings.Join(unitNames, " ")
}
machineId := fmt.Sprintf("%s-%s", cfg.Name(), m.Tag().String())
machineTags[tags.JujuMachine] = machineId
return machineTags, nil
} | go | func (p *ProvisionerAPI) machineTags(m *state.Machine, jobs []multiwatcher.MachineJob) (map[string]string, error) {
// Names of all units deployed to the machine.
//
// TODO(axw) 2015-06-02 #1461358
// We need a worker that periodically updates
// instance tags with current deployment info.
units, err := m.Units()
if err != nil {
return nil, errors.Trace(err)
}
unitNames := make([]string, 0, len(units))
for _, unit := range units {
if !unit.IsPrincipal() {
continue
}
unitNames = append(unitNames, unit.Name())
}
sort.Strings(unitNames)
cfg, err := p.m.ModelConfig()
if err != nil {
return nil, errors.Trace(err)
}
controllerCfg, err := p.st.ControllerConfig()
if err != nil {
return nil, errors.Trace(err)
}
machineTags := instancecfg.InstanceTags(cfg.UUID(), controllerCfg.ControllerUUID(), cfg, jobs)
if len(unitNames) > 0 {
machineTags[tags.JujuUnitsDeployed] = strings.Join(unitNames, " ")
}
machineId := fmt.Sprintf("%s-%s", cfg.Name(), m.Tag().String())
machineTags[tags.JujuMachine] = machineId
return machineTags, nil
} | [
"func",
"(",
"p",
"*",
"ProvisionerAPI",
")",
"machineTags",
"(",
"m",
"*",
"state",
".",
"Machine",
",",
"jobs",
"[",
"]",
"multiwatcher",
".",
"MachineJob",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"// Names of all units deployed to the machine.",
"//",
"// TODO(axw) 2015-06-02 #1461358",
"// We need a worker that periodically updates",
"// instance tags with current deployment info.",
"units",
",",
"err",
":=",
"m",
".",
"Units",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"unitNames",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"units",
")",
")",
"\n",
"for",
"_",
",",
"unit",
":=",
"range",
"units",
"{",
"if",
"!",
"unit",
".",
"IsPrincipal",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"unitNames",
"=",
"append",
"(",
"unitNames",
",",
"unit",
".",
"Name",
"(",
")",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"unitNames",
")",
"\n\n",
"cfg",
",",
"err",
":=",
"p",
".",
"m",
".",
"ModelConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"controllerCfg",
",",
"err",
":=",
"p",
".",
"st",
".",
"ControllerConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"machineTags",
":=",
"instancecfg",
".",
"InstanceTags",
"(",
"cfg",
".",
"UUID",
"(",
")",
",",
"controllerCfg",
".",
"ControllerUUID",
"(",
")",
",",
"cfg",
",",
"jobs",
")",
"\n",
"if",
"len",
"(",
"unitNames",
")",
">",
"0",
"{",
"machineTags",
"[",
"tags",
".",
"JujuUnitsDeployed",
"]",
"=",
"strings",
".",
"Join",
"(",
"unitNames",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"machineId",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"cfg",
".",
"Name",
"(",
")",
",",
"m",
".",
"Tag",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"machineTags",
"[",
"tags",
".",
"JujuMachine",
"]",
"=",
"machineId",
"\n",
"return",
"machineTags",
",",
"nil",
"\n",
"}"
] | // machineTags returns machine-specific tags to set on the instance. | [
"machineTags",
"returns",
"machine",
"-",
"specific",
"tags",
"to",
"set",
"on",
"the",
"instance",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L214-L248 |
4,224 | juju/juju | apiserver/facades/agent/provisioner/provisioninginfo.go | machineSubnetsAndZones | func (p *ProvisionerAPI) machineSubnetsAndZones(m *state.Machine) (map[string][]string, error) {
mcons, err := m.Constraints()
if err != nil {
return nil, errors.Annotate(err, "cannot get machine constraints")
}
includeSpaces := mcons.IncludeSpaces()
if len(includeSpaces) < 1 {
// Nothing to do.
return nil, nil
}
// TODO(dimitern): For the network model MVP we only use the first
// included space and ignore the rest.
//
// LKK Card: https://canonical.leankit.com/Boards/View/101652562/117352306
// LP Bug: http://pad.lv/1498232
spaceName := includeSpaces[0]
if len(includeSpaces) > 1 {
logger.Debugf(
"using space %q from constraints for machine %q (ignoring remaining: %v)",
spaceName, m.Id(), includeSpaces[1:],
)
}
space, err := p.st.Space(spaceName)
if err != nil {
return nil, errors.Trace(err)
}
subnets, err := space.Subnets()
if err != nil {
return nil, errors.Trace(err)
}
if len(subnets) == 0 {
return nil, errors.Errorf("cannot use space %q as deployment target: no subnets", spaceName)
}
subnetsToZones := make(map[string][]string, len(subnets))
for _, subnet := range subnets {
warningPrefix := fmt.Sprintf(
"not using subnet %q in space %q for machine %q provisioning: ",
subnet.CIDR(), spaceName, m.Id(),
)
providerId := subnet.ProviderId()
if providerId == "" {
logger.Warningf(warningPrefix + "no ProviderId set")
continue
}
// TODO(dimitern): Once state.Subnet supports multiple zones,
// use all of them below.
//
// LKK Card: https://canonical.leankit.com/Boards/View/101652562/119979611
zone := subnet.AvailabilityZone()
if zone == "" {
logger.Warningf(warningPrefix + "no availability zone(s) set")
continue
}
subnetsToZones[string(providerId)] = []string{zone}
}
return subnetsToZones, nil
} | go | func (p *ProvisionerAPI) machineSubnetsAndZones(m *state.Machine) (map[string][]string, error) {
mcons, err := m.Constraints()
if err != nil {
return nil, errors.Annotate(err, "cannot get machine constraints")
}
includeSpaces := mcons.IncludeSpaces()
if len(includeSpaces) < 1 {
// Nothing to do.
return nil, nil
}
// TODO(dimitern): For the network model MVP we only use the first
// included space and ignore the rest.
//
// LKK Card: https://canonical.leankit.com/Boards/View/101652562/117352306
// LP Bug: http://pad.lv/1498232
spaceName := includeSpaces[0]
if len(includeSpaces) > 1 {
logger.Debugf(
"using space %q from constraints for machine %q (ignoring remaining: %v)",
spaceName, m.Id(), includeSpaces[1:],
)
}
space, err := p.st.Space(spaceName)
if err != nil {
return nil, errors.Trace(err)
}
subnets, err := space.Subnets()
if err != nil {
return nil, errors.Trace(err)
}
if len(subnets) == 0 {
return nil, errors.Errorf("cannot use space %q as deployment target: no subnets", spaceName)
}
subnetsToZones := make(map[string][]string, len(subnets))
for _, subnet := range subnets {
warningPrefix := fmt.Sprintf(
"not using subnet %q in space %q for machine %q provisioning: ",
subnet.CIDR(), spaceName, m.Id(),
)
providerId := subnet.ProviderId()
if providerId == "" {
logger.Warningf(warningPrefix + "no ProviderId set")
continue
}
// TODO(dimitern): Once state.Subnet supports multiple zones,
// use all of them below.
//
// LKK Card: https://canonical.leankit.com/Boards/View/101652562/119979611
zone := subnet.AvailabilityZone()
if zone == "" {
logger.Warningf(warningPrefix + "no availability zone(s) set")
continue
}
subnetsToZones[string(providerId)] = []string{zone}
}
return subnetsToZones, nil
} | [
"func",
"(",
"p",
"*",
"ProvisionerAPI",
")",
"machineSubnetsAndZones",
"(",
"m",
"*",
"state",
".",
"Machine",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
",",
"error",
")",
"{",
"mcons",
",",
"err",
":=",
"m",
".",
"Constraints",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"includeSpaces",
":=",
"mcons",
".",
"IncludeSpaces",
"(",
")",
"\n",
"if",
"len",
"(",
"includeSpaces",
")",
"<",
"1",
"{",
"// Nothing to do.",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"// TODO(dimitern): For the network model MVP we only use the first",
"// included space and ignore the rest.",
"//",
"// LKK Card: https://canonical.leankit.com/Boards/View/101652562/117352306",
"// LP Bug: http://pad.lv/1498232",
"spaceName",
":=",
"includeSpaces",
"[",
"0",
"]",
"\n",
"if",
"len",
"(",
"includeSpaces",
")",
">",
"1",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"spaceName",
",",
"m",
".",
"Id",
"(",
")",
",",
"includeSpaces",
"[",
"1",
":",
"]",
",",
")",
"\n",
"}",
"\n",
"space",
",",
"err",
":=",
"p",
".",
"st",
".",
"Space",
"(",
"spaceName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"subnets",
",",
"err",
":=",
"space",
".",
"Subnets",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"subnets",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"spaceName",
")",
"\n",
"}",
"\n",
"subnetsToZones",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
",",
"len",
"(",
"subnets",
")",
")",
"\n",
"for",
"_",
",",
"subnet",
":=",
"range",
"subnets",
"{",
"warningPrefix",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"subnet",
".",
"CIDR",
"(",
")",
",",
"spaceName",
",",
"m",
".",
"Id",
"(",
")",
",",
")",
"\n",
"providerId",
":=",
"subnet",
".",
"ProviderId",
"(",
")",
"\n",
"if",
"providerId",
"==",
"\"",
"\"",
"{",
"logger",
".",
"Warningf",
"(",
"warningPrefix",
"+",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"// TODO(dimitern): Once state.Subnet supports multiple zones,",
"// use all of them below.",
"//",
"// LKK Card: https://canonical.leankit.com/Boards/View/101652562/119979611",
"zone",
":=",
"subnet",
".",
"AvailabilityZone",
"(",
")",
"\n",
"if",
"zone",
"==",
"\"",
"\"",
"{",
"logger",
".",
"Warningf",
"(",
"warningPrefix",
"+",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"subnetsToZones",
"[",
"string",
"(",
"providerId",
")",
"]",
"=",
"[",
"]",
"string",
"{",
"zone",
"}",
"\n",
"}",
"\n",
"return",
"subnetsToZones",
",",
"nil",
"\n",
"}"
] | // machineSubnetsAndZones returns a map of subnet provider-specific id
// to list of availability zone names for that subnet. The result can
// be empty if there are no spaces constraints specified for the
// machine, or there's an error fetching them. | [
"machineSubnetsAndZones",
"returns",
"a",
"map",
"of",
"subnet",
"provider",
"-",
"specific",
"id",
"to",
"list",
"of",
"availability",
"zone",
"names",
"for",
"that",
"subnet",
".",
"The",
"result",
"can",
"be",
"empty",
"if",
"there",
"are",
"no",
"spaces",
"constraints",
"specified",
"for",
"the",
"machine",
"or",
"there",
"s",
"an",
"error",
"fetching",
"them",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L254-L310 |
4,225 | juju/juju | apiserver/facades/agent/provisioner/provisioninginfo.go | machineLXDProfileNames | func (p *ProvisionerAPI) machineLXDProfileNames(m *state.Machine, env environs.Environ) ([]string, error) {
profileEnv, ok := env.(environs.LXDProfiler)
if !ok {
logger.Tracef("LXDProfiler not implemented by environ")
return nil, nil
}
units, err := m.Units()
if err != nil {
return nil, errors.Trace(err)
}
var names []string
for _, unit := range units {
app, err := unit.Application()
if err != nil {
return nil, errors.Trace(err)
}
ch, _, err := app.Charm()
if err != nil {
return nil, errors.Trace(err)
}
profile := ch.LXDProfile()
if profile == nil || (profile != nil && profile.Empty()) {
continue
}
pName := lxdprofile.Name(p.m.Name(), app.Name(), ch.Revision())
// Lock here, we get a new env for every call to ProvisioningInfo().
p.mu.Lock()
if err := profileEnv.MaybeWriteLXDProfile(pName, profile); err != nil {
p.mu.Unlock()
return nil, errors.Trace(err)
}
p.mu.Unlock()
names = append(names, pName)
}
return names, nil
} | go | func (p *ProvisionerAPI) machineLXDProfileNames(m *state.Machine, env environs.Environ) ([]string, error) {
profileEnv, ok := env.(environs.LXDProfiler)
if !ok {
logger.Tracef("LXDProfiler not implemented by environ")
return nil, nil
}
units, err := m.Units()
if err != nil {
return nil, errors.Trace(err)
}
var names []string
for _, unit := range units {
app, err := unit.Application()
if err != nil {
return nil, errors.Trace(err)
}
ch, _, err := app.Charm()
if err != nil {
return nil, errors.Trace(err)
}
profile := ch.LXDProfile()
if profile == nil || (profile != nil && profile.Empty()) {
continue
}
pName := lxdprofile.Name(p.m.Name(), app.Name(), ch.Revision())
// Lock here, we get a new env for every call to ProvisioningInfo().
p.mu.Lock()
if err := profileEnv.MaybeWriteLXDProfile(pName, profile); err != nil {
p.mu.Unlock()
return nil, errors.Trace(err)
}
p.mu.Unlock()
names = append(names, pName)
}
return names, nil
} | [
"func",
"(",
"p",
"*",
"ProvisionerAPI",
")",
"machineLXDProfileNames",
"(",
"m",
"*",
"state",
".",
"Machine",
",",
"env",
"environs",
".",
"Environ",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"profileEnv",
",",
"ok",
":=",
"env",
".",
"(",
"environs",
".",
"LXDProfiler",
")",
"\n",
"if",
"!",
"ok",
"{",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"units",
",",
"err",
":=",
"m",
".",
"Units",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"var",
"names",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"unit",
":=",
"range",
"units",
"{",
"app",
",",
"err",
":=",
"unit",
".",
"Application",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"ch",
",",
"_",
",",
"err",
":=",
"app",
".",
"Charm",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"profile",
":=",
"ch",
".",
"LXDProfile",
"(",
")",
"\n",
"if",
"profile",
"==",
"nil",
"||",
"(",
"profile",
"!=",
"nil",
"&&",
"profile",
".",
"Empty",
"(",
")",
")",
"{",
"continue",
"\n",
"}",
"\n",
"pName",
":=",
"lxdprofile",
".",
"Name",
"(",
"p",
".",
"m",
".",
"Name",
"(",
")",
",",
"app",
".",
"Name",
"(",
")",
",",
"ch",
".",
"Revision",
"(",
")",
")",
"\n",
"// Lock here, we get a new env for every call to ProvisioningInfo().",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"err",
":=",
"profileEnv",
".",
"MaybeWriteLXDProfile",
"(",
"pName",
",",
"profile",
")",
";",
"err",
"!=",
"nil",
"{",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"names",
"=",
"append",
"(",
"names",
",",
"pName",
")",
"\n",
"}",
"\n",
"return",
"names",
",",
"nil",
"\n",
"}"
] | // machineLXDProfileNames give the environ info to write lxd profiles needed for
// the given machine and returns the names of profiles. Unlike
// containerLXDProfilesInfo which returns the info necessary to write lxd profiles
// via the lxd broker. | [
"machineLXDProfileNames",
"give",
"the",
"environ",
"info",
"to",
"write",
"lxd",
"profiles",
"needed",
"for",
"the",
"given",
"machine",
"and",
"returns",
"the",
"names",
"of",
"profiles",
".",
"Unlike",
"containerLXDProfilesInfo",
"which",
"returns",
"the",
"info",
"necessary",
"to",
"write",
"lxd",
"profiles",
"via",
"the",
"lxd",
"broker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L316-L351 |
4,226 | juju/juju | apiserver/facades/agent/provisioner/provisioninginfo.go | availableImageMetadata | func (p *ProvisionerAPI) availableImageMetadata(m *state.Machine, env environs.Environ) ([]params.CloudImageMetadata, error) {
imageConstraint, err := p.constructImageConstraint(m, env)
if err != nil {
return nil, errors.Annotate(err, "could not construct image constraint")
}
// Look for image metadata in state.
data, err := p.findImageMetadata(imageConstraint, env)
if err != nil {
return nil, errors.Trace(err)
}
sort.Sort(metadataList(data))
logger.Debugf("available image metadata for provisioning: %v", data)
return data, nil
} | go | func (p *ProvisionerAPI) availableImageMetadata(m *state.Machine, env environs.Environ) ([]params.CloudImageMetadata, error) {
imageConstraint, err := p.constructImageConstraint(m, env)
if err != nil {
return nil, errors.Annotate(err, "could not construct image constraint")
}
// Look for image metadata in state.
data, err := p.findImageMetadata(imageConstraint, env)
if err != nil {
return nil, errors.Trace(err)
}
sort.Sort(metadataList(data))
logger.Debugf("available image metadata for provisioning: %v", data)
return data, nil
} | [
"func",
"(",
"p",
"*",
"ProvisionerAPI",
")",
"availableImageMetadata",
"(",
"m",
"*",
"state",
".",
"Machine",
",",
"env",
"environs",
".",
"Environ",
")",
"(",
"[",
"]",
"params",
".",
"CloudImageMetadata",
",",
"error",
")",
"{",
"imageConstraint",
",",
"err",
":=",
"p",
".",
"constructImageConstraint",
"(",
"m",
",",
"env",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Look for image metadata in state.",
"data",
",",
"err",
":=",
"p",
".",
"findImageMetadata",
"(",
"imageConstraint",
",",
"env",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"metadataList",
"(",
"data",
")",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"data",
")",
"\n",
"return",
"data",
",",
"nil",
"\n",
"}"
] | // availableImageMetadata returns all image metadata available to this machine
// or an error fetching them. | [
"availableImageMetadata",
"returns",
"all",
"image",
"metadata",
"available",
"to",
"this",
"machine",
"or",
"an",
"error",
"fetching",
"them",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L436-L450 |
4,227 | juju/juju | apiserver/facades/agent/provisioner/provisioninginfo.go | constructImageConstraint | func (p *ProvisionerAPI) constructImageConstraint(m *state.Machine, env environs.Environ) (*imagemetadata.ImageConstraint, error) {
lookup := simplestreams.LookupParams{
Series: []string{m.Series()},
Stream: env.Config().ImageStream(),
}
mcons, err := m.Constraints()
if err != nil {
return nil, errors.Annotatef(err, "cannot get machine constraints for machine %v", m.MachineTag().Id())
}
if mcons.Arch != nil {
lookup.Arches = []string{*mcons.Arch}
}
if hasRegion, ok := env.(simplestreams.HasRegion); ok {
// We can determine current region; we want only
// metadata specific to this region.
spec, err := hasRegion.Region()
if err != nil {
// can't really find images if we cannot determine cloud region
// TODO (anastasiamac 2015-12-03) or can we?
return nil, errors.Annotate(err, "getting provider region information (cloud spec)")
}
lookup.CloudSpec = spec
}
return imagemetadata.NewImageConstraint(lookup), nil
} | go | func (p *ProvisionerAPI) constructImageConstraint(m *state.Machine, env environs.Environ) (*imagemetadata.ImageConstraint, error) {
lookup := simplestreams.LookupParams{
Series: []string{m.Series()},
Stream: env.Config().ImageStream(),
}
mcons, err := m.Constraints()
if err != nil {
return nil, errors.Annotatef(err, "cannot get machine constraints for machine %v", m.MachineTag().Id())
}
if mcons.Arch != nil {
lookup.Arches = []string{*mcons.Arch}
}
if hasRegion, ok := env.(simplestreams.HasRegion); ok {
// We can determine current region; we want only
// metadata specific to this region.
spec, err := hasRegion.Region()
if err != nil {
// can't really find images if we cannot determine cloud region
// TODO (anastasiamac 2015-12-03) or can we?
return nil, errors.Annotate(err, "getting provider region information (cloud spec)")
}
lookup.CloudSpec = spec
}
return imagemetadata.NewImageConstraint(lookup), nil
} | [
"func",
"(",
"p",
"*",
"ProvisionerAPI",
")",
"constructImageConstraint",
"(",
"m",
"*",
"state",
".",
"Machine",
",",
"env",
"environs",
".",
"Environ",
")",
"(",
"*",
"imagemetadata",
".",
"ImageConstraint",
",",
"error",
")",
"{",
"lookup",
":=",
"simplestreams",
".",
"LookupParams",
"{",
"Series",
":",
"[",
"]",
"string",
"{",
"m",
".",
"Series",
"(",
")",
"}",
",",
"Stream",
":",
"env",
".",
"Config",
"(",
")",
".",
"ImageStream",
"(",
")",
",",
"}",
"\n\n",
"mcons",
",",
"err",
":=",
"m",
".",
"Constraints",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"m",
".",
"MachineTag",
"(",
")",
".",
"Id",
"(",
")",
")",
"\n",
"}",
"\n\n",
"if",
"mcons",
".",
"Arch",
"!=",
"nil",
"{",
"lookup",
".",
"Arches",
"=",
"[",
"]",
"string",
"{",
"*",
"mcons",
".",
"Arch",
"}",
"\n",
"}",
"\n\n",
"if",
"hasRegion",
",",
"ok",
":=",
"env",
".",
"(",
"simplestreams",
".",
"HasRegion",
")",
";",
"ok",
"{",
"// We can determine current region; we want only",
"// metadata specific to this region.",
"spec",
",",
"err",
":=",
"hasRegion",
".",
"Region",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// can't really find images if we cannot determine cloud region",
"// TODO (anastasiamac 2015-12-03) or can we?",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"lookup",
".",
"CloudSpec",
"=",
"spec",
"\n",
"}",
"\n\n",
"return",
"imagemetadata",
".",
"NewImageConstraint",
"(",
"lookup",
")",
",",
"nil",
"\n",
"}"
] | // constructImageConstraint returns model-specific criteria used to look for image metadata. | [
"constructImageConstraint",
"returns",
"model",
"-",
"specific",
"criteria",
"used",
"to",
"look",
"for",
"image",
"metadata",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L453-L481 |
4,228 | juju/juju | apiserver/facades/agent/provisioner/provisioninginfo.go | findImageMetadata | func (p *ProvisionerAPI) findImageMetadata(imageConstraint *imagemetadata.ImageConstraint, env environs.Environ) ([]params.CloudImageMetadata, error) {
// Look for image metadata in state.
stateMetadata, err := p.imageMetadataFromState(imageConstraint)
if err != nil && !errors.IsNotFound(err) {
// look into simple stream if for some reason can't get from controller,
// so do not exit on error.
logger.Infof("could not get image metadata from controller: %v", err)
}
logger.Debugf("got from controller %d metadata", len(stateMetadata))
// No need to look in data sources if found in state.
if len(stateMetadata) != 0 {
return stateMetadata, nil
}
// If no metadata is found in state, fall back to original simple stream search.
// Currently, an image metadata worker picks up this metadata periodically (daily),
// and stores it in state. So potentially, this collection could be different
// to what is in state.
dsMetadata, err := p.imageMetadataFromDataSources(env, imageConstraint)
if err != nil {
if !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
}
logger.Debugf("got from data sources %d metadata", len(dsMetadata))
return dsMetadata, nil
} | go | func (p *ProvisionerAPI) findImageMetadata(imageConstraint *imagemetadata.ImageConstraint, env environs.Environ) ([]params.CloudImageMetadata, error) {
// Look for image metadata in state.
stateMetadata, err := p.imageMetadataFromState(imageConstraint)
if err != nil && !errors.IsNotFound(err) {
// look into simple stream if for some reason can't get from controller,
// so do not exit on error.
logger.Infof("could not get image metadata from controller: %v", err)
}
logger.Debugf("got from controller %d metadata", len(stateMetadata))
// No need to look in data sources if found in state.
if len(stateMetadata) != 0 {
return stateMetadata, nil
}
// If no metadata is found in state, fall back to original simple stream search.
// Currently, an image metadata worker picks up this metadata periodically (daily),
// and stores it in state. So potentially, this collection could be different
// to what is in state.
dsMetadata, err := p.imageMetadataFromDataSources(env, imageConstraint)
if err != nil {
if !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
}
logger.Debugf("got from data sources %d metadata", len(dsMetadata))
return dsMetadata, nil
} | [
"func",
"(",
"p",
"*",
"ProvisionerAPI",
")",
"findImageMetadata",
"(",
"imageConstraint",
"*",
"imagemetadata",
".",
"ImageConstraint",
",",
"env",
"environs",
".",
"Environ",
")",
"(",
"[",
"]",
"params",
".",
"CloudImageMetadata",
",",
"error",
")",
"{",
"// Look for image metadata in state.",
"stateMetadata",
",",
"err",
":=",
"p",
".",
"imageMetadataFromState",
"(",
"imageConstraint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"// look into simple stream if for some reason can't get from controller,",
"// so do not exit on error.",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"len",
"(",
"stateMetadata",
")",
")",
"\n",
"// No need to look in data sources if found in state.",
"if",
"len",
"(",
"stateMetadata",
")",
"!=",
"0",
"{",
"return",
"stateMetadata",
",",
"nil",
"\n",
"}",
"\n\n",
"// If no metadata is found in state, fall back to original simple stream search.",
"// Currently, an image metadata worker picks up this metadata periodically (daily),",
"// and stores it in state. So potentially, this collection could be different",
"// to what is in state.",
"dsMetadata",
",",
"err",
":=",
"p",
".",
"imageMetadataFromDataSources",
"(",
"env",
",",
"imageConstraint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"len",
"(",
"dsMetadata",
")",
")",
"\n\n",
"return",
"dsMetadata",
",",
"nil",
"\n",
"}"
] | // findImageMetadata returns all image metadata or an error fetching them.
// It looks for image metadata in state.
// If none are found, we fall back on original image search in simple streams. | [
"findImageMetadata",
"returns",
"all",
"image",
"metadata",
"or",
"an",
"error",
"fetching",
"them",
".",
"It",
"looks",
"for",
"image",
"metadata",
"in",
"state",
".",
"If",
"none",
"are",
"found",
"we",
"fall",
"back",
"on",
"original",
"image",
"search",
"in",
"simple",
"streams",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L486-L513 |
4,229 | juju/juju | apiserver/facades/agent/provisioner/provisioninginfo.go | imageMetadataFromState | func (p *ProvisionerAPI) imageMetadataFromState(constraint *imagemetadata.ImageConstraint) ([]params.CloudImageMetadata, error) {
filter := cloudimagemetadata.MetadataFilter{
Series: constraint.Series,
Arches: constraint.Arches,
Region: constraint.Region,
Stream: constraint.Stream,
}
stored, err := p.st.CloudImageMetadataStorage.FindMetadata(filter)
if err != nil {
return nil, errors.Trace(err)
}
toParams := func(m cloudimagemetadata.Metadata) params.CloudImageMetadata {
return params.CloudImageMetadata{
ImageId: m.ImageId,
Stream: m.Stream,
Region: m.Region,
Version: m.Version,
Series: m.Series,
Arch: m.Arch,
VirtType: m.VirtType,
RootStorageType: m.RootStorageType,
RootStorageSize: m.RootStorageSize,
Source: m.Source,
Priority: m.Priority,
}
}
var all []params.CloudImageMetadata
for _, ms := range stored {
for _, m := range ms {
all = append(all, toParams(m))
}
}
return all, nil
} | go | func (p *ProvisionerAPI) imageMetadataFromState(constraint *imagemetadata.ImageConstraint) ([]params.CloudImageMetadata, error) {
filter := cloudimagemetadata.MetadataFilter{
Series: constraint.Series,
Arches: constraint.Arches,
Region: constraint.Region,
Stream: constraint.Stream,
}
stored, err := p.st.CloudImageMetadataStorage.FindMetadata(filter)
if err != nil {
return nil, errors.Trace(err)
}
toParams := func(m cloudimagemetadata.Metadata) params.CloudImageMetadata {
return params.CloudImageMetadata{
ImageId: m.ImageId,
Stream: m.Stream,
Region: m.Region,
Version: m.Version,
Series: m.Series,
Arch: m.Arch,
VirtType: m.VirtType,
RootStorageType: m.RootStorageType,
RootStorageSize: m.RootStorageSize,
Source: m.Source,
Priority: m.Priority,
}
}
var all []params.CloudImageMetadata
for _, ms := range stored {
for _, m := range ms {
all = append(all, toParams(m))
}
}
return all, nil
} | [
"func",
"(",
"p",
"*",
"ProvisionerAPI",
")",
"imageMetadataFromState",
"(",
"constraint",
"*",
"imagemetadata",
".",
"ImageConstraint",
")",
"(",
"[",
"]",
"params",
".",
"CloudImageMetadata",
",",
"error",
")",
"{",
"filter",
":=",
"cloudimagemetadata",
".",
"MetadataFilter",
"{",
"Series",
":",
"constraint",
".",
"Series",
",",
"Arches",
":",
"constraint",
".",
"Arches",
",",
"Region",
":",
"constraint",
".",
"Region",
",",
"Stream",
":",
"constraint",
".",
"Stream",
",",
"}",
"\n",
"stored",
",",
"err",
":=",
"p",
".",
"st",
".",
"CloudImageMetadataStorage",
".",
"FindMetadata",
"(",
"filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"toParams",
":=",
"func",
"(",
"m",
"cloudimagemetadata",
".",
"Metadata",
")",
"params",
".",
"CloudImageMetadata",
"{",
"return",
"params",
".",
"CloudImageMetadata",
"{",
"ImageId",
":",
"m",
".",
"ImageId",
",",
"Stream",
":",
"m",
".",
"Stream",
",",
"Region",
":",
"m",
".",
"Region",
",",
"Version",
":",
"m",
".",
"Version",
",",
"Series",
":",
"m",
".",
"Series",
",",
"Arch",
":",
"m",
".",
"Arch",
",",
"VirtType",
":",
"m",
".",
"VirtType",
",",
"RootStorageType",
":",
"m",
".",
"RootStorageType",
",",
"RootStorageSize",
":",
"m",
".",
"RootStorageSize",
",",
"Source",
":",
"m",
".",
"Source",
",",
"Priority",
":",
"m",
".",
"Priority",
",",
"}",
"\n",
"}",
"\n\n",
"var",
"all",
"[",
"]",
"params",
".",
"CloudImageMetadata",
"\n",
"for",
"_",
",",
"ms",
":=",
"range",
"stored",
"{",
"for",
"_",
",",
"m",
":=",
"range",
"ms",
"{",
"all",
"=",
"append",
"(",
"all",
",",
"toParams",
"(",
"m",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"all",
",",
"nil",
"\n",
"}"
] | // imageMetadataFromState returns image metadata stored in state
// that matches given criteria. | [
"imageMetadataFromState",
"returns",
"image",
"metadata",
"stored",
"in",
"state",
"that",
"matches",
"given",
"criteria",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L517-L552 |
4,230 | juju/juju | apiserver/facades/agent/provisioner/provisioninginfo.go | imageMetadataFromDataSources | func (p *ProvisionerAPI) imageMetadataFromDataSources(env environs.Environ, constraint *imagemetadata.ImageConstraint) ([]params.CloudImageMetadata, error) {
sources, err := environs.ImageMetadataSources(env)
if err != nil {
return nil, errors.Trace(err)
}
cfg := env.Config()
toModel := func(m *imagemetadata.ImageMetadata, mSeries string, source string, priority int) cloudimagemetadata.Metadata {
result := cloudimagemetadata.Metadata{
MetadataAttributes: cloudimagemetadata.MetadataAttributes{
Region: m.RegionName,
Arch: m.Arch,
VirtType: m.VirtType,
RootStorageType: m.Storage,
Source: source,
Series: mSeries,
Stream: m.Stream,
Version: m.Version,
},
Priority: priority,
ImageId: m.Id,
}
// TODO (anastasiamac 2016-08-24) This is a band-aid solution.
// Once correct value is read from simplestreams, this needs to go.
// Bug# 1616295
if result.Stream == "" {
result.Stream = constraint.Stream
}
if result.Stream == "" {
result.Stream = cfg.ImageStream()
}
return result
}
var metadataState []cloudimagemetadata.Metadata
for _, source := range sources {
logger.Debugf("looking in data source %v", source.Description())
found, info, err := imagemetadata.Fetch([]simplestreams.DataSource{source}, constraint)
if err != nil {
// Do not stop looking in other data sources if there is an issue here.
logger.Warningf("encountered %v while getting published images metadata from %v", err, source.Description())
continue
}
for _, m := range found {
mSeries, err := series.VersionSeries(m.Version)
if err != nil {
logger.Warningf("could not determine series for image id %s: %v", m.Id, err)
continue
}
metadataState = append(metadataState, toModel(m, mSeries, info.Source, source.Priority()))
}
}
if len(metadataState) > 0 {
if err := p.st.CloudImageMetadataStorage.SaveMetadata(metadataState); err != nil {
// No need to react here, just take note
logger.Warningf("failed to save published image metadata: %v", err)
}
}
// Since we've fallen through to data sources search and have saved all needed images into controller,
// let's try to get them from controller to avoid duplication of conversion logic here.
all, err := p.imageMetadataFromState(constraint)
if err != nil {
return nil, errors.Annotate(err, "could not read metadata from controller after saving it there from data sources")
}
if len(all) == 0 {
return nil, errors.NotFoundf("image metadata for series %v, arch %v", constraint.Series, constraint.Arches)
}
return all, nil
} | go | func (p *ProvisionerAPI) imageMetadataFromDataSources(env environs.Environ, constraint *imagemetadata.ImageConstraint) ([]params.CloudImageMetadata, error) {
sources, err := environs.ImageMetadataSources(env)
if err != nil {
return nil, errors.Trace(err)
}
cfg := env.Config()
toModel := func(m *imagemetadata.ImageMetadata, mSeries string, source string, priority int) cloudimagemetadata.Metadata {
result := cloudimagemetadata.Metadata{
MetadataAttributes: cloudimagemetadata.MetadataAttributes{
Region: m.RegionName,
Arch: m.Arch,
VirtType: m.VirtType,
RootStorageType: m.Storage,
Source: source,
Series: mSeries,
Stream: m.Stream,
Version: m.Version,
},
Priority: priority,
ImageId: m.Id,
}
// TODO (anastasiamac 2016-08-24) This is a band-aid solution.
// Once correct value is read from simplestreams, this needs to go.
// Bug# 1616295
if result.Stream == "" {
result.Stream = constraint.Stream
}
if result.Stream == "" {
result.Stream = cfg.ImageStream()
}
return result
}
var metadataState []cloudimagemetadata.Metadata
for _, source := range sources {
logger.Debugf("looking in data source %v", source.Description())
found, info, err := imagemetadata.Fetch([]simplestreams.DataSource{source}, constraint)
if err != nil {
// Do not stop looking in other data sources if there is an issue here.
logger.Warningf("encountered %v while getting published images metadata from %v", err, source.Description())
continue
}
for _, m := range found {
mSeries, err := series.VersionSeries(m.Version)
if err != nil {
logger.Warningf("could not determine series for image id %s: %v", m.Id, err)
continue
}
metadataState = append(metadataState, toModel(m, mSeries, info.Source, source.Priority()))
}
}
if len(metadataState) > 0 {
if err := p.st.CloudImageMetadataStorage.SaveMetadata(metadataState); err != nil {
// No need to react here, just take note
logger.Warningf("failed to save published image metadata: %v", err)
}
}
// Since we've fallen through to data sources search and have saved all needed images into controller,
// let's try to get them from controller to avoid duplication of conversion logic here.
all, err := p.imageMetadataFromState(constraint)
if err != nil {
return nil, errors.Annotate(err, "could not read metadata from controller after saving it there from data sources")
}
if len(all) == 0 {
return nil, errors.NotFoundf("image metadata for series %v, arch %v", constraint.Series, constraint.Arches)
}
return all, nil
} | [
"func",
"(",
"p",
"*",
"ProvisionerAPI",
")",
"imageMetadataFromDataSources",
"(",
"env",
"environs",
".",
"Environ",
",",
"constraint",
"*",
"imagemetadata",
".",
"ImageConstraint",
")",
"(",
"[",
"]",
"params",
".",
"CloudImageMetadata",
",",
"error",
")",
"{",
"sources",
",",
"err",
":=",
"environs",
".",
"ImageMetadataSources",
"(",
"env",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"cfg",
":=",
"env",
".",
"Config",
"(",
")",
"\n",
"toModel",
":=",
"func",
"(",
"m",
"*",
"imagemetadata",
".",
"ImageMetadata",
",",
"mSeries",
"string",
",",
"source",
"string",
",",
"priority",
"int",
")",
"cloudimagemetadata",
".",
"Metadata",
"{",
"result",
":=",
"cloudimagemetadata",
".",
"Metadata",
"{",
"MetadataAttributes",
":",
"cloudimagemetadata",
".",
"MetadataAttributes",
"{",
"Region",
":",
"m",
".",
"RegionName",
",",
"Arch",
":",
"m",
".",
"Arch",
",",
"VirtType",
":",
"m",
".",
"VirtType",
",",
"RootStorageType",
":",
"m",
".",
"Storage",
",",
"Source",
":",
"source",
",",
"Series",
":",
"mSeries",
",",
"Stream",
":",
"m",
".",
"Stream",
",",
"Version",
":",
"m",
".",
"Version",
",",
"}",
",",
"Priority",
":",
"priority",
",",
"ImageId",
":",
"m",
".",
"Id",
",",
"}",
"\n",
"// TODO (anastasiamac 2016-08-24) This is a band-aid solution.",
"// Once correct value is read from simplestreams, this needs to go.",
"// Bug# 1616295",
"if",
"result",
".",
"Stream",
"==",
"\"",
"\"",
"{",
"result",
".",
"Stream",
"=",
"constraint",
".",
"Stream",
"\n",
"}",
"\n",
"if",
"result",
".",
"Stream",
"==",
"\"",
"\"",
"{",
"result",
".",
"Stream",
"=",
"cfg",
".",
"ImageStream",
"(",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}",
"\n\n",
"var",
"metadataState",
"[",
"]",
"cloudimagemetadata",
".",
"Metadata",
"\n",
"for",
"_",
",",
"source",
":=",
"range",
"sources",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"source",
".",
"Description",
"(",
")",
")",
"\n",
"found",
",",
"info",
",",
"err",
":=",
"imagemetadata",
".",
"Fetch",
"(",
"[",
"]",
"simplestreams",
".",
"DataSource",
"{",
"source",
"}",
",",
"constraint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Do not stop looking in other data sources if there is an issue here.",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"err",
",",
"source",
".",
"Description",
"(",
")",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"found",
"{",
"mSeries",
",",
"err",
":=",
"series",
".",
"VersionSeries",
"(",
"m",
".",
"Version",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"m",
".",
"Id",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"metadataState",
"=",
"append",
"(",
"metadataState",
",",
"toModel",
"(",
"m",
",",
"mSeries",
",",
"info",
".",
"Source",
",",
"source",
".",
"Priority",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"metadataState",
")",
">",
"0",
"{",
"if",
"err",
":=",
"p",
".",
"st",
".",
"CloudImageMetadataStorage",
".",
"SaveMetadata",
"(",
"metadataState",
")",
";",
"err",
"!=",
"nil",
"{",
"// No need to react here, just take note",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Since we've fallen through to data sources search and have saved all needed images into controller,",
"// let's try to get them from controller to avoid duplication of conversion logic here.",
"all",
",",
"err",
":=",
"p",
".",
"imageMetadataFromState",
"(",
"constraint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"all",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"constraint",
".",
"Series",
",",
"constraint",
".",
"Arches",
")",
"\n",
"}",
"\n\n",
"return",
"all",
",",
"nil",
"\n",
"}"
] | // imageMetadataFromDataSources finds image metadata that match specified criteria in existing data sources. | [
"imageMetadataFromDataSources",
"finds",
"image",
"metadata",
"that",
"match",
"specified",
"criteria",
"in",
"existing",
"data",
"sources",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L555-L626 |
4,231 | juju/juju | apiserver/facades/agent/provisioner/provisioninginfo.go | Less | func (m metadataList) Less(i, j int) bool {
return m[i].Priority < m[j].Priority
} | go | func (m metadataList) Less(i, j int) bool {
return m[i].Priority < m[j].Priority
} | [
"func",
"(",
"m",
"metadataList",
")",
"Less",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"m",
"[",
"i",
"]",
".",
"Priority",
"<",
"m",
"[",
"j",
"]",
".",
"Priority",
"\n",
"}"
] | // Implements sort.Interface and sorts image metadata by priority. | [
"Implements",
"sort",
".",
"Interface",
"and",
"sorts",
"image",
"metadata",
"by",
"priority",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L638-L640 |
4,232 | juju/juju | downloader/utils.go | NewHTTPBlobOpener | func NewHTTPBlobOpener(hostnameVerification utils.SSLHostnameVerification) func(*url.URL) (io.ReadCloser, error) {
return func(url *url.URL) (io.ReadCloser, error) {
// TODO(rog) make the download operation interruptible.
client := utils.GetHTTPClient(hostnameVerification)
resp, err := client.Get(url.String())
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
// resp.Body is always non-nil. (see https://golang.org/pkg/net/http/#Response)
resp.Body.Close()
return nil, errors.Errorf("bad http response: %v", resp.Status)
}
return resp.Body, nil
}
} | go | func NewHTTPBlobOpener(hostnameVerification utils.SSLHostnameVerification) func(*url.URL) (io.ReadCloser, error) {
return func(url *url.URL) (io.ReadCloser, error) {
// TODO(rog) make the download operation interruptible.
client := utils.GetHTTPClient(hostnameVerification)
resp, err := client.Get(url.String())
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
// resp.Body is always non-nil. (see https://golang.org/pkg/net/http/#Response)
resp.Body.Close()
return nil, errors.Errorf("bad http response: %v", resp.Status)
}
return resp.Body, nil
}
} | [
"func",
"NewHTTPBlobOpener",
"(",
"hostnameVerification",
"utils",
".",
"SSLHostnameVerification",
")",
"func",
"(",
"*",
"url",
".",
"URL",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"return",
"func",
"(",
"url",
"*",
"url",
".",
"URL",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"// TODO(rog) make the download operation interruptible.",
"client",
":=",
"utils",
".",
"GetHTTPClient",
"(",
"hostnameVerification",
")",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"Get",
"(",
"url",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"// resp.Body is always non-nil. (see https://golang.org/pkg/net/http/#Response)",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
".",
"Status",
")",
"\n",
"}",
"\n",
"return",
"resp",
".",
"Body",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // NewHTTPBlobOpener returns a blob opener func suitable for use with
// Download. The opener func uses an HTTP client that enforces the
// provided SSL hostname verification policy. | [
"NewHTTPBlobOpener",
"returns",
"a",
"blob",
"opener",
"func",
"suitable",
"for",
"use",
"with",
"Download",
".",
"The",
"opener",
"func",
"uses",
"an",
"HTTP",
"client",
"that",
"enforces",
"the",
"provided",
"SSL",
"hostname",
"verification",
"policy",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/downloader/utils.go#L19-L34 |
4,233 | juju/juju | downloader/utils.go | NewSha256Verifier | func NewSha256Verifier(expected string) func(*os.File) error {
return func(file *os.File) error {
actual, _, err := utils.ReadSHA256(file)
if err != nil {
return errors.Trace(err)
}
if actual != expected {
err := errors.Errorf("expected sha256 %q, got %q", expected, actual)
return errors.NewNotValid(err, "")
}
return nil
}
} | go | func NewSha256Verifier(expected string) func(*os.File) error {
return func(file *os.File) error {
actual, _, err := utils.ReadSHA256(file)
if err != nil {
return errors.Trace(err)
}
if actual != expected {
err := errors.Errorf("expected sha256 %q, got %q", expected, actual)
return errors.NewNotValid(err, "")
}
return nil
}
} | [
"func",
"NewSha256Verifier",
"(",
"expected",
"string",
")",
"func",
"(",
"*",
"os",
".",
"File",
")",
"error",
"{",
"return",
"func",
"(",
"file",
"*",
"os",
".",
"File",
")",
"error",
"{",
"actual",
",",
"_",
",",
"err",
":=",
"utils",
".",
"ReadSHA256",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"actual",
"!=",
"expected",
"{",
"err",
":=",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"expected",
",",
"actual",
")",
"\n",
"return",
"errors",
".",
"NewNotValid",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // NewSha256Verifier returns a verifier suitable for Request. The
// verifier checks the SHA-256 checksum of the file to ensure that it
// matches the one returned by the provided func. | [
"NewSha256Verifier",
"returns",
"a",
"verifier",
"suitable",
"for",
"Request",
".",
"The",
"verifier",
"checks",
"the",
"SHA",
"-",
"256",
"checksum",
"of",
"the",
"file",
"to",
"ensure",
"that",
"it",
"matches",
"the",
"one",
"returned",
"by",
"the",
"provided",
"func",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/downloader/utils.go#L39-L51 |
4,234 | juju/juju | api/uniter/application.go | Refresh | func (s *Application) Refresh() error {
life, err := s.st.life(s.tag)
if err != nil {
return err
}
s.life = life
return nil
} | go | func (s *Application) Refresh() error {
life, err := s.st.life(s.tag)
if err != nil {
return err
}
s.life = life
return nil
} | [
"func",
"(",
"s",
"*",
"Application",
")",
"Refresh",
"(",
")",
"error",
"{",
"life",
",",
"err",
":=",
"s",
".",
"st",
".",
"life",
"(",
"s",
".",
"tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"life",
"=",
"life",
"\n",
"return",
"nil",
"\n",
"}"
] | // Refresh refreshes the contents of the application from the underlying
// state. | [
"Refresh",
"refreshes",
"the",
"contents",
"of",
"the",
"application",
"from",
"the",
"underlying",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/application.go#L56-L63 |
4,235 | juju/juju | api/uniter/application.go | CharmModifiedVersion | func (s *Application) CharmModifiedVersion() (int, error) {
var results params.IntResults
args := params.Entities{
Entities: []params.Entity{{Tag: s.tag.String()}},
}
err := s.st.facade.FacadeCall("CharmModifiedVersion", args, &results)
if err != nil {
return -1, err
}
if len(results.Results) != 1 {
return -1, fmt.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return -1, result.Error
}
return result.Result, nil
} | go | func (s *Application) CharmModifiedVersion() (int, error) {
var results params.IntResults
args := params.Entities{
Entities: []params.Entity{{Tag: s.tag.String()}},
}
err := s.st.facade.FacadeCall("CharmModifiedVersion", args, &results)
if err != nil {
return -1, err
}
if len(results.Results) != 1 {
return -1, fmt.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return -1, result.Error
}
return result.Result, nil
} | [
"func",
"(",
"s",
"*",
"Application",
")",
"CharmModifiedVersion",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"var",
"results",
"params",
".",
"IntResults",
"\n",
"args",
":=",
"params",
".",
"Entities",
"{",
"Entities",
":",
"[",
"]",
"params",
".",
"Entity",
"{",
"{",
"Tag",
":",
"s",
".",
"tag",
".",
"String",
"(",
")",
"}",
"}",
",",
"}",
"\n",
"err",
":=",
"s",
".",
"st",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"results",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"results",
".",
"Results",
")",
"!=",
"1",
"{",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"results",
".",
"Results",
")",
")",
"\n",
"}",
"\n",
"result",
":=",
"results",
".",
"Results",
"[",
"0",
"]",
"\n",
"if",
"result",
".",
"Error",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"result",
".",
"Error",
"\n",
"}",
"\n\n",
"return",
"result",
".",
"Result",
",",
"nil",
"\n",
"}"
] | // CharmModifiedVersion increments every time the charm, or any part of it, is
// changed in some way. | [
"CharmModifiedVersion",
"increments",
"every",
"time",
"the",
"charm",
"or",
"any",
"part",
"of",
"it",
"is",
"changed",
"in",
"some",
"way",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/application.go#L67-L86 |
4,236 | juju/juju | api/uniter/application.go | SetStatus | func (s *Application) SetStatus(unitName string, appStatus status.Status, info string, data map[string]interface{}) error {
tag := names.NewUnitTag(unitName)
var result params.ErrorResults
args := params.SetStatus{
Entities: []params.EntityStatusArgs{
{
Tag: tag.String(),
Status: appStatus.String(),
Info: info,
Data: data,
},
},
}
err := s.st.facade.FacadeCall("SetApplicationStatus", args, &result)
if err != nil {
return errors.Trace(err)
}
return result.OneError()
} | go | func (s *Application) SetStatus(unitName string, appStatus status.Status, info string, data map[string]interface{}) error {
tag := names.NewUnitTag(unitName)
var result params.ErrorResults
args := params.SetStatus{
Entities: []params.EntityStatusArgs{
{
Tag: tag.String(),
Status: appStatus.String(),
Info: info,
Data: data,
},
},
}
err := s.st.facade.FacadeCall("SetApplicationStatus", args, &result)
if err != nil {
return errors.Trace(err)
}
return result.OneError()
} | [
"func",
"(",
"s",
"*",
"Application",
")",
"SetStatus",
"(",
"unitName",
"string",
",",
"appStatus",
"status",
".",
"Status",
",",
"info",
"string",
",",
"data",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"error",
"{",
"tag",
":=",
"names",
".",
"NewUnitTag",
"(",
"unitName",
")",
"\n",
"var",
"result",
"params",
".",
"ErrorResults",
"\n",
"args",
":=",
"params",
".",
"SetStatus",
"{",
"Entities",
":",
"[",
"]",
"params",
".",
"EntityStatusArgs",
"{",
"{",
"Tag",
":",
"tag",
".",
"String",
"(",
")",
",",
"Status",
":",
"appStatus",
".",
"String",
"(",
")",
",",
"Info",
":",
"info",
",",
"Data",
":",
"data",
",",
"}",
",",
"}",
",",
"}",
"\n",
"err",
":=",
"s",
".",
"st",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
".",
"OneError",
"(",
")",
"\n",
"}"
] | // SetStatus sets the status of the application if the passed unitName,
// corresponding to the calling unit, is of the leader. | [
"SetStatus",
"sets",
"the",
"status",
"of",
"the",
"application",
"if",
"the",
"passed",
"unitName",
"corresponding",
"to",
"the",
"calling",
"unit",
"is",
"of",
"the",
"leader",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/application.go#L122-L140 |
4,237 | juju/juju | api/uniter/application.go | Status | func (s *Application) Status(unitName string) (params.ApplicationStatusResult, error) {
tag := names.NewUnitTag(unitName)
var results params.ApplicationStatusResults
args := params.Entities{
Entities: []params.Entity{
{
Tag: tag.String(),
},
},
}
err := s.st.facade.FacadeCall("ApplicationStatus", args, &results)
if err != nil {
return params.ApplicationStatusResult{}, errors.Trace(err)
}
result := results.Results[0]
if result.Error != nil {
return params.ApplicationStatusResult{}, result.Error
}
return result, nil
} | go | func (s *Application) Status(unitName string) (params.ApplicationStatusResult, error) {
tag := names.NewUnitTag(unitName)
var results params.ApplicationStatusResults
args := params.Entities{
Entities: []params.Entity{
{
Tag: tag.String(),
},
},
}
err := s.st.facade.FacadeCall("ApplicationStatus", args, &results)
if err != nil {
return params.ApplicationStatusResult{}, errors.Trace(err)
}
result := results.Results[0]
if result.Error != nil {
return params.ApplicationStatusResult{}, result.Error
}
return result, nil
} | [
"func",
"(",
"s",
"*",
"Application",
")",
"Status",
"(",
"unitName",
"string",
")",
"(",
"params",
".",
"ApplicationStatusResult",
",",
"error",
")",
"{",
"tag",
":=",
"names",
".",
"NewUnitTag",
"(",
"unitName",
")",
"\n",
"var",
"results",
"params",
".",
"ApplicationStatusResults",
"\n",
"args",
":=",
"params",
".",
"Entities",
"{",
"Entities",
":",
"[",
"]",
"params",
".",
"Entity",
"{",
"{",
"Tag",
":",
"tag",
".",
"String",
"(",
")",
",",
"}",
",",
"}",
",",
"}",
"\n",
"err",
":=",
"s",
".",
"st",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"results",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ApplicationStatusResult",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"result",
":=",
"results",
".",
"Results",
"[",
"0",
"]",
"\n",
"if",
"result",
".",
"Error",
"!=",
"nil",
"{",
"return",
"params",
".",
"ApplicationStatusResult",
"{",
"}",
",",
"result",
".",
"Error",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // Status returns the status of the application if the passed unitName,
// corresponding to the calling unit, is of the leader. | [
"Status",
"returns",
"the",
"status",
"of",
"the",
"application",
"if",
"the",
"passed",
"unitName",
"corresponding",
"to",
"the",
"calling",
"unit",
"is",
"of",
"the",
"leader",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/application.go#L144-L163 |
4,238 | juju/juju | api/uniter/application.go | WatchLeadershipSettings | func (s *Application) WatchLeadershipSettings() (watcher.NotifyWatcher, error) {
return s.st.LeadershipSettings.WatchLeadershipSettings(s.tag.Id())
} | go | func (s *Application) WatchLeadershipSettings() (watcher.NotifyWatcher, error) {
return s.st.LeadershipSettings.WatchLeadershipSettings(s.tag.Id())
} | [
"func",
"(",
"s",
"*",
"Application",
")",
"WatchLeadershipSettings",
"(",
")",
"(",
"watcher",
".",
"NotifyWatcher",
",",
"error",
")",
"{",
"return",
"s",
".",
"st",
".",
"LeadershipSettings",
".",
"WatchLeadershipSettings",
"(",
"s",
".",
"tag",
".",
"Id",
"(",
")",
")",
"\n",
"}"
] | // WatchLeadershipSettings returns a watcher which can be used to wait
// for leadership settings changes to be made for the application. | [
"WatchLeadershipSettings",
"returns",
"a",
"watcher",
"which",
"can",
"be",
"used",
"to",
"wait",
"for",
"leadership",
"settings",
"changes",
"to",
"be",
"made",
"for",
"the",
"application",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/application.go#L167-L169 |
4,239 | juju/juju | network/iptables/iptables.go | ParseIngressRules | func ParseIngressRules(r io.Reader) ([]network.IngressRule, error) {
var rules []network.IngressRule
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
rule, ok, err := parseIngressRule(strings.TrimSpace(line))
if err != nil {
logger.Warningf("failed to parse iptables line %q: %v", line, err)
continue
}
if !ok {
continue
}
rules = append(rules, rule)
}
if err := scanner.Err(); err != nil {
return nil, errors.Annotate(err, "reading iptables output")
}
return rules, nil
} | go | func ParseIngressRules(r io.Reader) ([]network.IngressRule, error) {
var rules []network.IngressRule
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
rule, ok, err := parseIngressRule(strings.TrimSpace(line))
if err != nil {
logger.Warningf("failed to parse iptables line %q: %v", line, err)
continue
}
if !ok {
continue
}
rules = append(rules, rule)
}
if err := scanner.Err(); err != nil {
return nil, errors.Annotate(err, "reading iptables output")
}
return rules, nil
} | [
"func",
"ParseIngressRules",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"[",
"]",
"network",
".",
"IngressRule",
",",
"error",
")",
"{",
"var",
"rules",
"[",
"]",
"network",
".",
"IngressRule",
"\n",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"r",
")",
"\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"line",
":=",
"scanner",
".",
"Text",
"(",
")",
"\n",
"rule",
",",
"ok",
",",
"err",
":=",
"parseIngressRule",
"(",
"strings",
".",
"TrimSpace",
"(",
"line",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"line",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"rules",
"=",
"append",
"(",
"rules",
",",
"rule",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"scanner",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"rules",
",",
"nil",
"\n",
"}"
] | // ParseIngressRules parses the output of "iptables -L INPUT -n",
// extracting previously added ingress rules, as rendered by
// IngressRuleCommand. | [
"ParseIngressRules",
"parses",
"the",
"output",
"of",
"iptables",
"-",
"L",
"INPUT",
"-",
"n",
"extracting",
"previously",
"added",
"ingress",
"rules",
"as",
"rendered",
"by",
"IngressRuleCommand",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/iptables/iptables.go#L151-L170 |
4,240 | juju/juju | network/iptables/iptables.go | popField | func popField(s string) (field, remainder string, ok bool) {
i := strings.IndexRune(s, ' ')
if i == -1 {
return s, "", s != ""
}
field, remainder = s[:i], strings.TrimLeft(s[i+1:], " ")
return field, remainder, true
} | go | func popField(s string) (field, remainder string, ok bool) {
i := strings.IndexRune(s, ' ')
if i == -1 {
return s, "", s != ""
}
field, remainder = s[:i], strings.TrimLeft(s[i+1:], " ")
return field, remainder, true
} | [
"func",
"popField",
"(",
"s",
"string",
")",
"(",
"field",
",",
"remainder",
"string",
",",
"ok",
"bool",
")",
"{",
"i",
":=",
"strings",
".",
"IndexRune",
"(",
"s",
",",
"' '",
")",
"\n",
"if",
"i",
"==",
"-",
"1",
"{",
"return",
"s",
",",
"\"",
"\"",
",",
"s",
"!=",
"\"",
"\"",
"\n",
"}",
"\n",
"field",
",",
"remainder",
"=",
"s",
"[",
":",
"i",
"]",
",",
"strings",
".",
"TrimLeft",
"(",
"s",
"[",
"i",
"+",
"1",
":",
"]",
",",
"\"",
"\"",
")",
"\n",
"return",
"field",
",",
"remainder",
",",
"true",
"\n",
"}"
] | // popField pops a pops a field off the front of the given string
// by splitting on the first run of whitespace, and returns the
// field and remainder. A boolean result is returned indicating
// whether or not a field was found. | [
"popField",
"pops",
"a",
"pops",
"a",
"field",
"off",
"the",
"front",
"of",
"the",
"given",
"string",
"by",
"splitting",
"on",
"the",
"first",
"run",
"of",
"whitespace",
"and",
"returns",
"the",
"field",
"and",
"remainder",
".",
"A",
"boolean",
"result",
"is",
"returned",
"indicating",
"whether",
"or",
"not",
"a",
"field",
"was",
"found",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/iptables/iptables.go#L275-L282 |
4,241 | juju/juju | provider/azure/internal/azureauth/oauth.go | OAuthConfig | func OAuthConfig(
sdkCtx context.Context,
client subscriptions.Client,
resourceManagerEndpoint string,
subscriptionId string,
) (*adal.OAuthConfig, string, error) {
authURI, err := DiscoverAuthorizationURI(sdkCtx, client, subscriptionId)
if err != nil {
return nil, "", errors.Annotate(err, "detecting auth URI")
}
logger.Debugf("discovered auth URI: %s", authURI)
// The authorization URI scheme and host identifies the AD endpoint.
// The authorization URI path identifies the AD tenant.
tenantId, err := AuthorizationURITenantID(authURI)
if err != nil {
return nil, "", errors.Annotate(err, "getting tenant ID")
}
authURI.Path = ""
adEndpoint := authURI.String()
oauthConfig, err := adal.NewOAuthConfig(adEndpoint, tenantId)
if err != nil {
return nil, "", errors.Annotate(err, "getting OAuth configuration")
}
return oauthConfig, tenantId, nil
} | go | func OAuthConfig(
sdkCtx context.Context,
client subscriptions.Client,
resourceManagerEndpoint string,
subscriptionId string,
) (*adal.OAuthConfig, string, error) {
authURI, err := DiscoverAuthorizationURI(sdkCtx, client, subscriptionId)
if err != nil {
return nil, "", errors.Annotate(err, "detecting auth URI")
}
logger.Debugf("discovered auth URI: %s", authURI)
// The authorization URI scheme and host identifies the AD endpoint.
// The authorization URI path identifies the AD tenant.
tenantId, err := AuthorizationURITenantID(authURI)
if err != nil {
return nil, "", errors.Annotate(err, "getting tenant ID")
}
authURI.Path = ""
adEndpoint := authURI.String()
oauthConfig, err := adal.NewOAuthConfig(adEndpoint, tenantId)
if err != nil {
return nil, "", errors.Annotate(err, "getting OAuth configuration")
}
return oauthConfig, tenantId, nil
} | [
"func",
"OAuthConfig",
"(",
"sdkCtx",
"context",
".",
"Context",
",",
"client",
"subscriptions",
".",
"Client",
",",
"resourceManagerEndpoint",
"string",
",",
"subscriptionId",
"string",
",",
")",
"(",
"*",
"adal",
".",
"OAuthConfig",
",",
"string",
",",
"error",
")",
"{",
"authURI",
",",
"err",
":=",
"DiscoverAuthorizationURI",
"(",
"sdkCtx",
",",
"client",
",",
"subscriptionId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"authURI",
")",
"\n\n",
"// The authorization URI scheme and host identifies the AD endpoint.",
"// The authorization URI path identifies the AD tenant.",
"tenantId",
",",
"err",
":=",
"AuthorizationURITenantID",
"(",
"authURI",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"authURI",
".",
"Path",
"=",
"\"",
"\"",
"\n",
"adEndpoint",
":=",
"authURI",
".",
"String",
"(",
")",
"\n\n",
"oauthConfig",
",",
"err",
":=",
"adal",
".",
"NewOAuthConfig",
"(",
"adEndpoint",
",",
"tenantId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"oauthConfig",
",",
"tenantId",
",",
"nil",
"\n",
"}"
] | // OAuthConfig returns an azure.OAuthConfig based on the given resource
// manager endpoint and subscription ID. This will make a request to the
// resource manager API to discover the Active Directory tenant ID. | [
"OAuthConfig",
"returns",
"an",
"azure",
".",
"OAuthConfig",
"based",
"on",
"the",
"given",
"resource",
"manager",
"endpoint",
"and",
"subscription",
"ID",
".",
"This",
"will",
"make",
"a",
"request",
"to",
"the",
"resource",
"manager",
"API",
"to",
"discover",
"the",
"Active",
"Directory",
"tenant",
"ID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/internal/azureauth/oauth.go#L17-L43 |
4,242 | juju/juju | provider/joyent/environ.go | newEnviron | func newEnviron(cloud environs.CloudSpec, cfg *config.Config) (*joyentEnviron, error) {
env := &joyentEnviron{
name: cfg.Name(),
cloud: cloud,
}
if err := env.SetConfig(cfg); err != nil {
return nil, err
}
var err error
env.compute, err = newCompute(cloud)
if err != nil {
return nil, err
}
return env, nil
} | go | func newEnviron(cloud environs.CloudSpec, cfg *config.Config) (*joyentEnviron, error) {
env := &joyentEnviron{
name: cfg.Name(),
cloud: cloud,
}
if err := env.SetConfig(cfg); err != nil {
return nil, err
}
var err error
env.compute, err = newCompute(cloud)
if err != nil {
return nil, err
}
return env, nil
} | [
"func",
"newEnviron",
"(",
"cloud",
"environs",
".",
"CloudSpec",
",",
"cfg",
"*",
"config",
".",
"Config",
")",
"(",
"*",
"joyentEnviron",
",",
"error",
")",
"{",
"env",
":=",
"&",
"joyentEnviron",
"{",
"name",
":",
"cfg",
".",
"Name",
"(",
")",
",",
"cloud",
":",
"cloud",
",",
"}",
"\n",
"if",
"err",
":=",
"env",
".",
"SetConfig",
"(",
"cfg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"env",
".",
"compute",
",",
"err",
"=",
"newCompute",
"(",
"cloud",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"env",
",",
"nil",
"\n",
"}"
] | // newEnviron create a new Joyent environ instance from config. | [
"newEnviron",
"create",
"a",
"new",
"Joyent",
"environ",
"instance",
"from",
"config",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/joyent/environ.go#L36-L50 |
4,243 | juju/juju | api/logfwd/lastsent.go | GetLastSent | func (c LastSentClient) GetLastSent(ids []LastSentID) ([]LastSentResult, error) {
var args params.LogForwardingGetLastSentParams
args.IDs = make([]params.LogForwardingID, len(ids))
for i, id := range ids {
args.IDs[i] = params.LogForwardingID{
ModelTag: id.Model.String(),
Sink: id.Sink,
}
}
var apiResults params.LogForwardingGetLastSentResults
err := c.caller.FacadeCall("GetLastSent", args, &apiResults)
if err != nil {
return nil, errors.Trace(err)
}
results := make([]LastSentResult, len(ids))
for i, apiRes := range apiResults.Results {
results[i] = LastSentResult{
LastSentInfo: LastSentInfo{
LastSentID: ids[i],
RecordID: apiRes.RecordID,
},
Error: common.RestoreError(apiRes.Error),
}
if apiRes.RecordTimestamp > 0 {
results[i].RecordTimestamp = time.Unix(0, apiRes.RecordTimestamp)
}
}
return results, nil
} | go | func (c LastSentClient) GetLastSent(ids []LastSentID) ([]LastSentResult, error) {
var args params.LogForwardingGetLastSentParams
args.IDs = make([]params.LogForwardingID, len(ids))
for i, id := range ids {
args.IDs[i] = params.LogForwardingID{
ModelTag: id.Model.String(),
Sink: id.Sink,
}
}
var apiResults params.LogForwardingGetLastSentResults
err := c.caller.FacadeCall("GetLastSent", args, &apiResults)
if err != nil {
return nil, errors.Trace(err)
}
results := make([]LastSentResult, len(ids))
for i, apiRes := range apiResults.Results {
results[i] = LastSentResult{
LastSentInfo: LastSentInfo{
LastSentID: ids[i],
RecordID: apiRes.RecordID,
},
Error: common.RestoreError(apiRes.Error),
}
if apiRes.RecordTimestamp > 0 {
results[i].RecordTimestamp = time.Unix(0, apiRes.RecordTimestamp)
}
}
return results, nil
} | [
"func",
"(",
"c",
"LastSentClient",
")",
"GetLastSent",
"(",
"ids",
"[",
"]",
"LastSentID",
")",
"(",
"[",
"]",
"LastSentResult",
",",
"error",
")",
"{",
"var",
"args",
"params",
".",
"LogForwardingGetLastSentParams",
"\n",
"args",
".",
"IDs",
"=",
"make",
"(",
"[",
"]",
"params",
".",
"LogForwardingID",
",",
"len",
"(",
"ids",
")",
")",
"\n",
"for",
"i",
",",
"id",
":=",
"range",
"ids",
"{",
"args",
".",
"IDs",
"[",
"i",
"]",
"=",
"params",
".",
"LogForwardingID",
"{",
"ModelTag",
":",
"id",
".",
"Model",
".",
"String",
"(",
")",
",",
"Sink",
":",
"id",
".",
"Sink",
",",
"}",
"\n",
"}",
"\n\n",
"var",
"apiResults",
"params",
".",
"LogForwardingGetLastSentResults",
"\n",
"err",
":=",
"c",
".",
"caller",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"apiResults",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"results",
":=",
"make",
"(",
"[",
"]",
"LastSentResult",
",",
"len",
"(",
"ids",
")",
")",
"\n",
"for",
"i",
",",
"apiRes",
":=",
"range",
"apiResults",
".",
"Results",
"{",
"results",
"[",
"i",
"]",
"=",
"LastSentResult",
"{",
"LastSentInfo",
":",
"LastSentInfo",
"{",
"LastSentID",
":",
"ids",
"[",
"i",
"]",
",",
"RecordID",
":",
"apiRes",
".",
"RecordID",
",",
"}",
",",
"Error",
":",
"common",
".",
"RestoreError",
"(",
"apiRes",
".",
"Error",
")",
",",
"}",
"\n",
"if",
"apiRes",
".",
"RecordTimestamp",
">",
"0",
"{",
"results",
"[",
"i",
"]",
".",
"RecordTimestamp",
"=",
"time",
".",
"Unix",
"(",
"0",
",",
"apiRes",
".",
"RecordTimestamp",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // GetLastSent makes a "GetLastSent" call on the facade and returns the
// results in the same order. | [
"GetLastSent",
"makes",
"a",
"GetLastSent",
"call",
"on",
"the",
"facade",
"and",
"returns",
"the",
"results",
"in",
"the",
"same",
"order",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/logfwd/lastsent.go#L73-L103 |
4,244 | juju/juju | api/logfwd/lastsent.go | SetLastSent | func (c LastSentClient) SetLastSent(reqs []LastSentInfo) ([]LastSentResult, error) {
var args params.LogForwardingSetLastSentParams
args.Params = make([]params.LogForwardingSetLastSentParam, len(reqs))
for i, req := range reqs {
args.Params[i] = params.LogForwardingSetLastSentParam{
LogForwardingID: params.LogForwardingID{
ModelTag: req.Model.String(),
Sink: req.Sink,
},
RecordID: req.RecordID,
RecordTimestamp: req.RecordTimestamp.UnixNano(),
}
}
var apiResults params.ErrorResults
err := c.caller.FacadeCall("SetLastSent", args, &apiResults)
if err != nil {
return nil, errors.Trace(err)
}
results := make([]LastSentResult, len(reqs))
for i, apiRes := range apiResults.Results {
results[i] = LastSentResult{
LastSentInfo: reqs[i],
Error: common.RestoreError(apiRes.Error),
}
}
return results, nil
} | go | func (c LastSentClient) SetLastSent(reqs []LastSentInfo) ([]LastSentResult, error) {
var args params.LogForwardingSetLastSentParams
args.Params = make([]params.LogForwardingSetLastSentParam, len(reqs))
for i, req := range reqs {
args.Params[i] = params.LogForwardingSetLastSentParam{
LogForwardingID: params.LogForwardingID{
ModelTag: req.Model.String(),
Sink: req.Sink,
},
RecordID: req.RecordID,
RecordTimestamp: req.RecordTimestamp.UnixNano(),
}
}
var apiResults params.ErrorResults
err := c.caller.FacadeCall("SetLastSent", args, &apiResults)
if err != nil {
return nil, errors.Trace(err)
}
results := make([]LastSentResult, len(reqs))
for i, apiRes := range apiResults.Results {
results[i] = LastSentResult{
LastSentInfo: reqs[i],
Error: common.RestoreError(apiRes.Error),
}
}
return results, nil
} | [
"func",
"(",
"c",
"LastSentClient",
")",
"SetLastSent",
"(",
"reqs",
"[",
"]",
"LastSentInfo",
")",
"(",
"[",
"]",
"LastSentResult",
",",
"error",
")",
"{",
"var",
"args",
"params",
".",
"LogForwardingSetLastSentParams",
"\n",
"args",
".",
"Params",
"=",
"make",
"(",
"[",
"]",
"params",
".",
"LogForwardingSetLastSentParam",
",",
"len",
"(",
"reqs",
")",
")",
"\n",
"for",
"i",
",",
"req",
":=",
"range",
"reqs",
"{",
"args",
".",
"Params",
"[",
"i",
"]",
"=",
"params",
".",
"LogForwardingSetLastSentParam",
"{",
"LogForwardingID",
":",
"params",
".",
"LogForwardingID",
"{",
"ModelTag",
":",
"req",
".",
"Model",
".",
"String",
"(",
")",
",",
"Sink",
":",
"req",
".",
"Sink",
",",
"}",
",",
"RecordID",
":",
"req",
".",
"RecordID",
",",
"RecordTimestamp",
":",
"req",
".",
"RecordTimestamp",
".",
"UnixNano",
"(",
")",
",",
"}",
"\n",
"}",
"\n\n",
"var",
"apiResults",
"params",
".",
"ErrorResults",
"\n",
"err",
":=",
"c",
".",
"caller",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"apiResults",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"results",
":=",
"make",
"(",
"[",
"]",
"LastSentResult",
",",
"len",
"(",
"reqs",
")",
")",
"\n",
"for",
"i",
",",
"apiRes",
":=",
"range",
"apiResults",
".",
"Results",
"{",
"results",
"[",
"i",
"]",
"=",
"LastSentResult",
"{",
"LastSentInfo",
":",
"reqs",
"[",
"i",
"]",
",",
"Error",
":",
"common",
".",
"RestoreError",
"(",
"apiRes",
".",
"Error",
")",
",",
"}",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // SetLastSent makes a "SetLastSent" call on the facade and returns the
// results in the same order. | [
"SetLastSent",
"makes",
"a",
"SetLastSent",
"call",
"on",
"the",
"facade",
"and",
"returns",
"the",
"results",
"in",
"the",
"same",
"order",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/logfwd/lastsent.go#L107-L135 |
4,245 | juju/juju | state/globalclock/reader.go | NewReader | func NewReader(config ReaderConfig) (*Reader, error) {
if err := config.validate(); err != nil {
return nil, errors.Trace(err)
}
r := &Reader{config: config}
return r, nil
} | go | func NewReader(config ReaderConfig) (*Reader, error) {
if err := config.validate(); err != nil {
return nil, errors.Trace(err)
}
r := &Reader{config: config}
return r, nil
} | [
"func",
"NewReader",
"(",
"config",
"ReaderConfig",
")",
"(",
"*",
"Reader",
",",
"error",
")",
"{",
"if",
"err",
":=",
"config",
".",
"validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"r",
":=",
"&",
"Reader",
"{",
"config",
":",
"config",
"}",
"\n",
"return",
"r",
",",
"nil",
"\n",
"}"
] | // NewReader returns a new Reader using the supplied config, or an error.
//
// Readers will not function past the lifetime of their configured Mongo. | [
"NewReader",
"returns",
"a",
"new",
"Reader",
"using",
"the",
"supplied",
"config",
"or",
"an",
"error",
".",
"Readers",
"will",
"not",
"function",
"past",
"the",
"lifetime",
"of",
"their",
"configured",
"Mongo",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/globalclock/reader.go#L23-L29 |
4,246 | juju/juju | state/globalclock/reader.go | Now | func (r *Reader) Now() (time.Time, error) {
coll, closer := r.config.Mongo.GetCollection(r.config.Collection)
defer closer()
t, err := readClock(coll)
if errors.Cause(err) == mgo.ErrNotFound {
// No time written yet. When it is written
// for the first time, it'll be globalEpoch.
t = globalEpoch
} else if err != nil {
return time.Time{}, errors.Trace(err)
}
return t, nil
} | go | func (r *Reader) Now() (time.Time, error) {
coll, closer := r.config.Mongo.GetCollection(r.config.Collection)
defer closer()
t, err := readClock(coll)
if errors.Cause(err) == mgo.ErrNotFound {
// No time written yet. When it is written
// for the first time, it'll be globalEpoch.
t = globalEpoch
} else if err != nil {
return time.Time{}, errors.Trace(err)
}
return t, nil
} | [
"func",
"(",
"r",
"*",
"Reader",
")",
"Now",
"(",
")",
"(",
"time",
".",
"Time",
",",
"error",
")",
"{",
"coll",
",",
"closer",
":=",
"r",
".",
"config",
".",
"Mongo",
".",
"GetCollection",
"(",
"r",
".",
"config",
".",
"Collection",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"t",
",",
"err",
":=",
"readClock",
"(",
"coll",
")",
"\n",
"if",
"errors",
".",
"Cause",
"(",
"err",
")",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"// No time written yet. When it is written",
"// for the first time, it'll be globalEpoch.",
"t",
"=",
"globalEpoch",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"t",
",",
"nil",
"\n",
"}"
] | // Now returns the current global time. | [
"Now",
"returns",
"the",
"current",
"global",
"time",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/globalclock/reader.go#L32-L45 |
4,247 | juju/juju | api/common/modelstatus.go | ModelStatus | func (c *ModelStatusAPI) ModelStatus(tags ...names.ModelTag) ([]base.ModelStatus, error) {
result := params.ModelStatusResults{}
models := make([]params.Entity, len(tags))
for i, tag := range tags {
models[i] = params.Entity{Tag: tag.String()}
}
req := params.Entities{
Entities: models,
}
if err := c.facade.FacadeCall("ModelStatus", req, &result); err != nil {
return nil, err
}
return c.processModelStatusResults(result.Results)
} | go | func (c *ModelStatusAPI) ModelStatus(tags ...names.ModelTag) ([]base.ModelStatus, error) {
result := params.ModelStatusResults{}
models := make([]params.Entity, len(tags))
for i, tag := range tags {
models[i] = params.Entity{Tag: tag.String()}
}
req := params.Entities{
Entities: models,
}
if err := c.facade.FacadeCall("ModelStatus", req, &result); err != nil {
return nil, err
}
return c.processModelStatusResults(result.Results)
} | [
"func",
"(",
"c",
"*",
"ModelStatusAPI",
")",
"ModelStatus",
"(",
"tags",
"...",
"names",
".",
"ModelTag",
")",
"(",
"[",
"]",
"base",
".",
"ModelStatus",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"ModelStatusResults",
"{",
"}",
"\n",
"models",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"Entity",
",",
"len",
"(",
"tags",
")",
")",
"\n",
"for",
"i",
",",
"tag",
":=",
"range",
"tags",
"{",
"models",
"[",
"i",
"]",
"=",
"params",
".",
"Entity",
"{",
"Tag",
":",
"tag",
".",
"String",
"(",
")",
"}",
"\n",
"}",
"\n",
"req",
":=",
"params",
".",
"Entities",
"{",
"Entities",
":",
"models",
",",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"req",
",",
"&",
"result",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"processModelStatusResults",
"(",
"result",
".",
"Results",
")",
"\n",
"}"
] | // ModelStatus returns a status summary for each model tag passed in. | [
"ModelStatus",
"returns",
"a",
"status",
"summary",
"for",
"each",
"model",
"tag",
"passed",
"in",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/common/modelstatus.go#L28-L42 |
4,248 | juju/juju | worker/apicaller/connect.go | OnlyConnect | func OnlyConnect(a agent.Agent, apiOpen api.OpenFunc) (api.Connection, error) {
agentConfig := a.CurrentConfig()
info, ok := agentConfig.APIInfo()
if !ok {
return nil, errors.New("API info not available")
}
conn, _, err := connectFallback(apiOpen, info, agentConfig.OldPassword())
if err != nil {
return nil, errors.Trace(err)
}
return conn, nil
} | go | func OnlyConnect(a agent.Agent, apiOpen api.OpenFunc) (api.Connection, error) {
agentConfig := a.CurrentConfig()
info, ok := agentConfig.APIInfo()
if !ok {
return nil, errors.New("API info not available")
}
conn, _, err := connectFallback(apiOpen, info, agentConfig.OldPassword())
if err != nil {
return nil, errors.Trace(err)
}
return conn, nil
} | [
"func",
"OnlyConnect",
"(",
"a",
"agent",
".",
"Agent",
",",
"apiOpen",
"api",
".",
"OpenFunc",
")",
"(",
"api",
".",
"Connection",
",",
"error",
")",
"{",
"agentConfig",
":=",
"a",
".",
"CurrentConfig",
"(",
")",
"\n",
"info",
",",
"ok",
":=",
"agentConfig",
".",
"APIInfo",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"conn",
",",
"_",
",",
"err",
":=",
"connectFallback",
"(",
"apiOpen",
",",
"info",
",",
"agentConfig",
".",
"OldPassword",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"conn",
",",
"nil",
"\n",
"}"
] | // OnlyConnect logs into the API using the supplied agent's credentials. | [
"OnlyConnect",
"logs",
"into",
"the",
"API",
"using",
"the",
"supplied",
"agent",
"s",
"credentials",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/apicaller/connect.go#L49-L60 |
4,249 | juju/juju | worker/apicaller/connect.go | NewExternalControllerConnection | func NewExternalControllerConnection(apiInfo *api.Info) (api.Connection, error) {
return api.Open(apiInfo, api.DialOpts{
Timeout: 2 * time.Second,
RetryDelay: 500 * time.Millisecond,
})
} | go | func NewExternalControllerConnection(apiInfo *api.Info) (api.Connection, error) {
return api.Open(apiInfo, api.DialOpts{
Timeout: 2 * time.Second,
RetryDelay: 500 * time.Millisecond,
})
} | [
"func",
"NewExternalControllerConnection",
"(",
"apiInfo",
"*",
"api",
".",
"Info",
")",
"(",
"api",
".",
"Connection",
",",
"error",
")",
"{",
"return",
"api",
".",
"Open",
"(",
"apiInfo",
",",
"api",
".",
"DialOpts",
"{",
"Timeout",
":",
"2",
"*",
"time",
".",
"Second",
",",
"RetryDelay",
":",
"500",
"*",
"time",
".",
"Millisecond",
",",
"}",
")",
"\n",
"}"
] | // NewExternalControllerConnection returns an api connection to a controller
// with the specified api info. | [
"NewExternalControllerConnection",
"returns",
"an",
"api",
"connection",
"to",
"a",
"controller",
"with",
"the",
"specified",
"api",
"info",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/apicaller/connect.go#L302-L307 |
4,250 | juju/juju | apiserver/facades/client/application/charmstore.go | StoreCharmArchive | func StoreCharmArchive(st State, archive CharmArchive) error {
storage := newStateStorage(st.ModelUUID(), st.MongoSession())
storagePath, err := charmArchiveStoragePath(archive.ID)
if err != nil {
return errors.Annotate(err, "cannot generate charm archive name")
}
if err := storage.Put(storagePath, archive.Data, archive.Size); err != nil {
return errors.Annotate(err, "cannot add charm to storage")
}
info := state.CharmInfo{
Charm: archive.Charm,
ID: archive.ID,
StoragePath: storagePath,
SHA256: archive.SHA256,
Macaroon: archive.Macaroon,
Version: archive.CharmVersion,
}
// Now update the charm data in state and mark it as no longer pending.
_, err = st.UpdateUploadedCharm(info)
if err != nil {
alreadyUploaded := err == state.ErrCharmRevisionAlreadyModified ||
errors.Cause(err) == state.ErrCharmRevisionAlreadyModified ||
state.IsCharmAlreadyUploadedError(err)
if err := storage.Remove(storagePath); err != nil {
if alreadyUploaded {
logger.Errorf("cannot remove duplicated charm archive from storage: %v", err)
} else {
logger.Errorf("cannot remove unsuccessfully recorded charm archive from storage: %v", err)
}
}
if alreadyUploaded {
// Somebody else managed to upload and update the charm in
// state before us. This is not an error.
return nil
}
return errors.Trace(err)
}
return nil
} | go | func StoreCharmArchive(st State, archive CharmArchive) error {
storage := newStateStorage(st.ModelUUID(), st.MongoSession())
storagePath, err := charmArchiveStoragePath(archive.ID)
if err != nil {
return errors.Annotate(err, "cannot generate charm archive name")
}
if err := storage.Put(storagePath, archive.Data, archive.Size); err != nil {
return errors.Annotate(err, "cannot add charm to storage")
}
info := state.CharmInfo{
Charm: archive.Charm,
ID: archive.ID,
StoragePath: storagePath,
SHA256: archive.SHA256,
Macaroon: archive.Macaroon,
Version: archive.CharmVersion,
}
// Now update the charm data in state and mark it as no longer pending.
_, err = st.UpdateUploadedCharm(info)
if err != nil {
alreadyUploaded := err == state.ErrCharmRevisionAlreadyModified ||
errors.Cause(err) == state.ErrCharmRevisionAlreadyModified ||
state.IsCharmAlreadyUploadedError(err)
if err := storage.Remove(storagePath); err != nil {
if alreadyUploaded {
logger.Errorf("cannot remove duplicated charm archive from storage: %v", err)
} else {
logger.Errorf("cannot remove unsuccessfully recorded charm archive from storage: %v", err)
}
}
if alreadyUploaded {
// Somebody else managed to upload and update the charm in
// state before us. This is not an error.
return nil
}
return errors.Trace(err)
}
return nil
} | [
"func",
"StoreCharmArchive",
"(",
"st",
"State",
",",
"archive",
"CharmArchive",
")",
"error",
"{",
"storage",
":=",
"newStateStorage",
"(",
"st",
".",
"ModelUUID",
"(",
")",
",",
"st",
".",
"MongoSession",
"(",
")",
")",
"\n",
"storagePath",
",",
"err",
":=",
"charmArchiveStoragePath",
"(",
"archive",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"storage",
".",
"Put",
"(",
"storagePath",
",",
"archive",
".",
"Data",
",",
"archive",
".",
"Size",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"info",
":=",
"state",
".",
"CharmInfo",
"{",
"Charm",
":",
"archive",
".",
"Charm",
",",
"ID",
":",
"archive",
".",
"ID",
",",
"StoragePath",
":",
"storagePath",
",",
"SHA256",
":",
"archive",
".",
"SHA256",
",",
"Macaroon",
":",
"archive",
".",
"Macaroon",
",",
"Version",
":",
"archive",
".",
"CharmVersion",
",",
"}",
"\n\n",
"// Now update the charm data in state and mark it as no longer pending.",
"_",
",",
"err",
"=",
"st",
".",
"UpdateUploadedCharm",
"(",
"info",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"alreadyUploaded",
":=",
"err",
"==",
"state",
".",
"ErrCharmRevisionAlreadyModified",
"||",
"errors",
".",
"Cause",
"(",
"err",
")",
"==",
"state",
".",
"ErrCharmRevisionAlreadyModified",
"||",
"state",
".",
"IsCharmAlreadyUploadedError",
"(",
"err",
")",
"\n",
"if",
"err",
":=",
"storage",
".",
"Remove",
"(",
"storagePath",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"alreadyUploaded",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"alreadyUploaded",
"{",
"// Somebody else managed to upload and update the charm in",
"// state before us. This is not an error.",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // StoreCharmArchive stores a charm archive in environment storage. | [
"StoreCharmArchive",
"stores",
"a",
"charm",
"archive",
"in",
"environment",
"storage",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/application/charmstore.go#L293-L333 |
4,251 | juju/juju | apiserver/facades/client/application/charmstore.go | charmArchiveStoragePath | func charmArchiveStoragePath(curl *charm.URL) (string, error) {
uuid, err := utils.NewUUID()
if err != nil {
return "", err
}
return fmt.Sprintf("charms/%s-%s", curl.String(), uuid), nil
} | go | func charmArchiveStoragePath(curl *charm.URL) (string, error) {
uuid, err := utils.NewUUID()
if err != nil {
return "", err
}
return fmt.Sprintf("charms/%s-%s", curl.String(), uuid), nil
} | [
"func",
"charmArchiveStoragePath",
"(",
"curl",
"*",
"charm",
".",
"URL",
")",
"(",
"string",
",",
"error",
")",
"{",
"uuid",
",",
"err",
":=",
"utils",
".",
"NewUUID",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"curl",
".",
"String",
"(",
")",
",",
"uuid",
")",
",",
"nil",
"\n",
"}"
] | // charmArchiveStoragePath returns a string that is suitable as a
// storage path, using a random UUID to avoid colliding with concurrent
// uploads. | [
"charmArchiveStoragePath",
"returns",
"a",
"string",
"that",
"is",
"suitable",
"as",
"a",
"storage",
"path",
"using",
"a",
"random",
"UUID",
"to",
"avoid",
"colliding",
"with",
"concurrent",
"uploads",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/application/charmstore.go#L338-L344 |
4,252 | juju/juju | api/subnets/subnets.go | NewAPI | func NewAPI(caller base.APICallCloser) *API {
if caller == nil {
panic("caller is nil")
}
clientFacade, facadeCaller := base.NewClientFacade(caller, subnetsFacade)
return &API{
ClientFacade: clientFacade,
facade: facadeCaller,
}
} | go | func NewAPI(caller base.APICallCloser) *API {
if caller == nil {
panic("caller is nil")
}
clientFacade, facadeCaller := base.NewClientFacade(caller, subnetsFacade)
return &API{
ClientFacade: clientFacade,
facade: facadeCaller,
}
} | [
"func",
"NewAPI",
"(",
"caller",
"base",
".",
"APICallCloser",
")",
"*",
"API",
"{",
"if",
"caller",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"clientFacade",
",",
"facadeCaller",
":=",
"base",
".",
"NewClientFacade",
"(",
"caller",
",",
"subnetsFacade",
")",
"\n",
"return",
"&",
"API",
"{",
"ClientFacade",
":",
"clientFacade",
",",
"facade",
":",
"facadeCaller",
",",
"}",
"\n",
"}"
] | // NewAPI creates a new client-side Subnets facade. | [
"NewAPI",
"creates",
"a",
"new",
"client",
"-",
"side",
"Subnets",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/subnets/subnets.go#L24-L33 |
4,253 | juju/juju | api/subnets/subnets.go | AddSubnet | func (api *API) AddSubnet(subnet names.SubnetTag, providerId network.Id, space names.SpaceTag, zones []string) error {
var response params.ErrorResults
// Prefer ProviderId when set over CIDR.
subnetTag := subnet.String()
if providerId != "" {
subnetTag = ""
}
params := params.AddSubnetsParams{
Subnets: []params.AddSubnetParams{{
SubnetTag: subnetTag,
SubnetProviderId: string(providerId),
SpaceTag: space.String(),
Zones: zones,
}},
}
err := api.facade.FacadeCall("AddSubnets", params, &response)
if err != nil {
return errors.Trace(err)
}
return response.OneError()
} | go | func (api *API) AddSubnet(subnet names.SubnetTag, providerId network.Id, space names.SpaceTag, zones []string) error {
var response params.ErrorResults
// Prefer ProviderId when set over CIDR.
subnetTag := subnet.String()
if providerId != "" {
subnetTag = ""
}
params := params.AddSubnetsParams{
Subnets: []params.AddSubnetParams{{
SubnetTag: subnetTag,
SubnetProviderId: string(providerId),
SpaceTag: space.String(),
Zones: zones,
}},
}
err := api.facade.FacadeCall("AddSubnets", params, &response)
if err != nil {
return errors.Trace(err)
}
return response.OneError()
} | [
"func",
"(",
"api",
"*",
"API",
")",
"AddSubnet",
"(",
"subnet",
"names",
".",
"SubnetTag",
",",
"providerId",
"network",
".",
"Id",
",",
"space",
"names",
".",
"SpaceTag",
",",
"zones",
"[",
"]",
"string",
")",
"error",
"{",
"var",
"response",
"params",
".",
"ErrorResults",
"\n",
"// Prefer ProviderId when set over CIDR.",
"subnetTag",
":=",
"subnet",
".",
"String",
"(",
")",
"\n",
"if",
"providerId",
"!=",
"\"",
"\"",
"{",
"subnetTag",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"params",
":=",
"params",
".",
"AddSubnetsParams",
"{",
"Subnets",
":",
"[",
"]",
"params",
".",
"AddSubnetParams",
"{",
"{",
"SubnetTag",
":",
"subnetTag",
",",
"SubnetProviderId",
":",
"string",
"(",
"providerId",
")",
",",
"SpaceTag",
":",
"space",
".",
"String",
"(",
")",
",",
"Zones",
":",
"zones",
",",
"}",
"}",
",",
"}",
"\n",
"err",
":=",
"api",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"params",
",",
"&",
"response",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"response",
".",
"OneError",
"(",
")",
"\n",
"}"
] | // AddSubnet adds an existing subnet to the model. | [
"AddSubnet",
"adds",
"an",
"existing",
"subnet",
"to",
"the",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/subnets/subnets.go#L36-L57 |
4,254 | juju/juju | api/subnets/subnets.go | CreateSubnet | func (api *API) CreateSubnet(subnet names.SubnetTag, space names.SpaceTag, zones []string, isPublic bool) error {
var response params.ErrorResults
params := params.CreateSubnetsParams{
Subnets: []params.CreateSubnetParams{{
SubnetTag: subnet.String(),
SpaceTag: space.String(),
Zones: zones,
IsPublic: isPublic,
}},
}
err := api.facade.FacadeCall("CreateSubnets", params, &response)
if err != nil {
return errors.Trace(err)
}
return response.OneError()
} | go | func (api *API) CreateSubnet(subnet names.SubnetTag, space names.SpaceTag, zones []string, isPublic bool) error {
var response params.ErrorResults
params := params.CreateSubnetsParams{
Subnets: []params.CreateSubnetParams{{
SubnetTag: subnet.String(),
SpaceTag: space.String(),
Zones: zones,
IsPublic: isPublic,
}},
}
err := api.facade.FacadeCall("CreateSubnets", params, &response)
if err != nil {
return errors.Trace(err)
}
return response.OneError()
} | [
"func",
"(",
"api",
"*",
"API",
")",
"CreateSubnet",
"(",
"subnet",
"names",
".",
"SubnetTag",
",",
"space",
"names",
".",
"SpaceTag",
",",
"zones",
"[",
"]",
"string",
",",
"isPublic",
"bool",
")",
"error",
"{",
"var",
"response",
"params",
".",
"ErrorResults",
"\n",
"params",
":=",
"params",
".",
"CreateSubnetsParams",
"{",
"Subnets",
":",
"[",
"]",
"params",
".",
"CreateSubnetParams",
"{",
"{",
"SubnetTag",
":",
"subnet",
".",
"String",
"(",
")",
",",
"SpaceTag",
":",
"space",
".",
"String",
"(",
")",
",",
"Zones",
":",
"zones",
",",
"IsPublic",
":",
"isPublic",
",",
"}",
"}",
",",
"}",
"\n",
"err",
":=",
"api",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"params",
",",
"&",
"response",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"response",
".",
"OneError",
"(",
")",
"\n",
"}"
] | // CreateSubnet creates a new subnet with the provider. | [
"CreateSubnet",
"creates",
"a",
"new",
"subnet",
"with",
"the",
"provider",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/subnets/subnets.go#L60-L75 |
4,255 | juju/juju | api/subnets/subnets.go | ListSubnets | func (api *API) ListSubnets(spaceTag *names.SpaceTag, zone string) ([]params.Subnet, error) {
var response params.ListSubnetsResults
var space string
if spaceTag != nil {
space = spaceTag.String()
}
args := params.SubnetsFilters{
SpaceTag: space,
Zone: zone,
}
err := api.facade.FacadeCall("ListSubnets", args, &response)
if err != nil {
return nil, errors.Trace(err)
}
return response.Results, nil
} | go | func (api *API) ListSubnets(spaceTag *names.SpaceTag, zone string) ([]params.Subnet, error) {
var response params.ListSubnetsResults
var space string
if spaceTag != nil {
space = spaceTag.String()
}
args := params.SubnetsFilters{
SpaceTag: space,
Zone: zone,
}
err := api.facade.FacadeCall("ListSubnets", args, &response)
if err != nil {
return nil, errors.Trace(err)
}
return response.Results, nil
} | [
"func",
"(",
"api",
"*",
"API",
")",
"ListSubnets",
"(",
"spaceTag",
"*",
"names",
".",
"SpaceTag",
",",
"zone",
"string",
")",
"(",
"[",
"]",
"params",
".",
"Subnet",
",",
"error",
")",
"{",
"var",
"response",
"params",
".",
"ListSubnetsResults",
"\n",
"var",
"space",
"string",
"\n",
"if",
"spaceTag",
"!=",
"nil",
"{",
"space",
"=",
"spaceTag",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"args",
":=",
"params",
".",
"SubnetsFilters",
"{",
"SpaceTag",
":",
"space",
",",
"Zone",
":",
"zone",
",",
"}",
"\n",
"err",
":=",
"api",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"response",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"response",
".",
"Results",
",",
"nil",
"\n",
"}"
] | // ListSubnets fetches all the subnets known by the model. | [
"ListSubnets",
"fetches",
"all",
"the",
"subnets",
"known",
"by",
"the",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/subnets/subnets.go#L78-L93 |
4,256 | juju/juju | state/cloudimagemetadata/image.go | MongoIndexes | func MongoIndexes() []mgo.Index {
return []mgo.Index{{
Key: []string{"expire-at"},
ExpireAfter: expiryTime,
Sparse: true,
}}
} | go | func MongoIndexes() []mgo.Index {
return []mgo.Index{{
Key: []string{"expire-at"},
ExpireAfter: expiryTime,
Sparse: true,
}}
} | [
"func",
"MongoIndexes",
"(",
")",
"[",
"]",
"mgo",
".",
"Index",
"{",
"return",
"[",
"]",
"mgo",
".",
"Index",
"{",
"{",
"Key",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"ExpireAfter",
":",
"expiryTime",
",",
"Sparse",
":",
"true",
",",
"}",
"}",
"\n",
"}"
] | // MongoIndexes returns the indexes to apply to the clouldimagemetadata collection.
// We return an index that expires records containing a created-at field after 5 minutes. | [
"MongoIndexes",
"returns",
"the",
"indexes",
"to",
"apply",
"to",
"the",
"clouldimagemetadata",
"collection",
".",
"We",
"return",
"an",
"index",
"that",
"expires",
"records",
"containing",
"a",
"created",
"-",
"at",
"field",
"after",
"5",
"minutes",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L35-L41 |
4,257 | juju/juju | state/cloudimagemetadata/image.go | SaveMetadataNoExpiry | func (s *storage) SaveMetadataNoExpiry(metadata []Metadata) error {
return s.saveMetadata(metadata, false)
} | go | func (s *storage) SaveMetadataNoExpiry(metadata []Metadata) error {
return s.saveMetadata(metadata, false)
} | [
"func",
"(",
"s",
"*",
"storage",
")",
"SaveMetadataNoExpiry",
"(",
"metadata",
"[",
"]",
"Metadata",
")",
"error",
"{",
"return",
"s",
".",
"saveMetadata",
"(",
"metadata",
",",
"false",
")",
"\n",
"}"
] | // SaveMetadataNoExpiry implements Storage.SaveMetadataNoExpiry and behaves as save-or-update.
// Records will not expire. | [
"SaveMetadataNoExpiry",
"implements",
"Storage",
".",
"SaveMetadataNoExpiry",
"and",
"behaves",
"as",
"save",
"-",
"or",
"-",
"update",
".",
"Records",
"will",
"not",
"expire",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L53-L55 |
4,258 | juju/juju | state/cloudimagemetadata/image.go | SaveMetadata | func (s *storage) SaveMetadata(metadata []Metadata) error {
return s.saveMetadata(metadata, true)
} | go | func (s *storage) SaveMetadata(metadata []Metadata) error {
return s.saveMetadata(metadata, true)
} | [
"func",
"(",
"s",
"*",
"storage",
")",
"SaveMetadata",
"(",
"metadata",
"[",
"]",
"Metadata",
")",
"error",
"{",
"return",
"s",
".",
"saveMetadata",
"(",
"metadata",
",",
"true",
")",
"\n",
"}"
] | // SaveMetadata implements Storage.SaveMetadata and behaves as save-or-update.
// Records will expire after a set time. | [
"SaveMetadata",
"implements",
"Storage",
".",
"SaveMetadata",
"and",
"behaves",
"as",
"save",
"-",
"or",
"-",
"update",
".",
"Records",
"will",
"expire",
"after",
"a",
"set",
"time",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L59-L61 |
4,259 | juju/juju | state/cloudimagemetadata/image.go | DeleteMetadata | func (s *storage) DeleteMetadata(imageId string) error {
deleteOperation := func(docId string) txn.Op {
logger.Debugf("deleting metadata (ID=%v) for image (ID=%v)", docId, imageId)
return txn.Op{
C: s.collection,
Id: docId,
Assert: txn.DocExists,
Remove: true,
}
}
noOp := func() ([]txn.Op, error) {
logger.Debugf("no metadata for image ID %v to delete", imageId)
return nil, jujutxn.ErrNoOperations
}
buildTxn := func(attempt int) ([]txn.Op, error) {
// find all metadata docs with given image id
imageMetadata, err := s.metadataForImageId(imageId)
if err != nil {
if err == mgo.ErrNotFound {
return noOp()
}
return nil, err
}
if len(imageMetadata) == 0 {
return noOp()
}
allTxn := make([]txn.Op, len(imageMetadata))
for i, doc := range imageMetadata {
allTxn[i] = deleteOperation(doc.Id)
}
return allTxn, nil
}
err := s.store.RunTransaction(buildTxn)
if err != nil {
return errors.Annotatef(err, "cannot delete metadata for cloud image %v", imageId)
}
return nil
} | go | func (s *storage) DeleteMetadata(imageId string) error {
deleteOperation := func(docId string) txn.Op {
logger.Debugf("deleting metadata (ID=%v) for image (ID=%v)", docId, imageId)
return txn.Op{
C: s.collection,
Id: docId,
Assert: txn.DocExists,
Remove: true,
}
}
noOp := func() ([]txn.Op, error) {
logger.Debugf("no metadata for image ID %v to delete", imageId)
return nil, jujutxn.ErrNoOperations
}
buildTxn := func(attempt int) ([]txn.Op, error) {
// find all metadata docs with given image id
imageMetadata, err := s.metadataForImageId(imageId)
if err != nil {
if err == mgo.ErrNotFound {
return noOp()
}
return nil, err
}
if len(imageMetadata) == 0 {
return noOp()
}
allTxn := make([]txn.Op, len(imageMetadata))
for i, doc := range imageMetadata {
allTxn[i] = deleteOperation(doc.Id)
}
return allTxn, nil
}
err := s.store.RunTransaction(buildTxn)
if err != nil {
return errors.Annotatef(err, "cannot delete metadata for cloud image %v", imageId)
}
return nil
} | [
"func",
"(",
"s",
"*",
"storage",
")",
"DeleteMetadata",
"(",
"imageId",
"string",
")",
"error",
"{",
"deleteOperation",
":=",
"func",
"(",
"docId",
"string",
")",
"txn",
".",
"Op",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"docId",
",",
"imageId",
")",
"\n",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"s",
".",
"collection",
",",
"Id",
":",
"docId",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Remove",
":",
"true",
",",
"}",
"\n",
"}",
"\n\n",
"noOp",
":=",
"func",
"(",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"imageId",
")",
"\n",
"return",
"nil",
",",
"jujutxn",
".",
"ErrNoOperations",
"\n",
"}",
"\n\n",
"buildTxn",
":=",
"func",
"(",
"attempt",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"// find all metadata docs with given image id",
"imageMetadata",
",",
"err",
":=",
"s",
".",
"metadataForImageId",
"(",
"imageId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"noOp",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"imageMetadata",
")",
"==",
"0",
"{",
"return",
"noOp",
"(",
")",
"\n",
"}",
"\n\n",
"allTxn",
":=",
"make",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"len",
"(",
"imageMetadata",
")",
")",
"\n",
"for",
"i",
",",
"doc",
":=",
"range",
"imageMetadata",
"{",
"allTxn",
"[",
"i",
"]",
"=",
"deleteOperation",
"(",
"doc",
".",
"Id",
")",
"\n",
"}",
"\n",
"return",
"allTxn",
",",
"nil",
"\n",
"}",
"\n\n",
"err",
":=",
"s",
".",
"store",
".",
"RunTransaction",
"(",
"buildTxn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"imageId",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // DeleteMetadata implements Storage.DeleteMetadata. | [
"DeleteMetadata",
"implements",
"Storage",
".",
"DeleteMetadata",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L124-L165 |
4,260 | juju/juju | state/cloudimagemetadata/image.go | AllCloudImageMetadata | func (s *storage) AllCloudImageMetadata() ([]Metadata, error) {
coll, closer := s.store.GetCollection(s.collection)
defer closer()
results := []Metadata{}
docs := []imagesMetadataDoc{}
err := coll.Find(nil).All(&docs)
if err != nil {
return nil, errors.Annotatef(err, "cannot get all image metadata")
}
for _, doc := range docs {
results = append(results, doc.metadata())
}
return results, nil
} | go | func (s *storage) AllCloudImageMetadata() ([]Metadata, error) {
coll, closer := s.store.GetCollection(s.collection)
defer closer()
results := []Metadata{}
docs := []imagesMetadataDoc{}
err := coll.Find(nil).All(&docs)
if err != nil {
return nil, errors.Annotatef(err, "cannot get all image metadata")
}
for _, doc := range docs {
results = append(results, doc.metadata())
}
return results, nil
} | [
"func",
"(",
"s",
"*",
"storage",
")",
"AllCloudImageMetadata",
"(",
")",
"(",
"[",
"]",
"Metadata",
",",
"error",
")",
"{",
"coll",
",",
"closer",
":=",
"s",
".",
"store",
".",
"GetCollection",
"(",
"s",
".",
"collection",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"results",
":=",
"[",
"]",
"Metadata",
"{",
"}",
"\n",
"docs",
":=",
"[",
"]",
"imagesMetadataDoc",
"{",
"}",
"\n",
"err",
":=",
"coll",
".",
"Find",
"(",
"nil",
")",
".",
"All",
"(",
"&",
"docs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"doc",
":=",
"range",
"docs",
"{",
"results",
"=",
"append",
"(",
"results",
",",
"doc",
".",
"metadata",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // AllCloudImageMetadata returns all cloud image metadata in the model. | [
"AllCloudImageMetadata",
"returns",
"all",
"cloud",
"image",
"metadata",
"in",
"the",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L194-L208 |
4,261 | juju/juju | state/cloudimagemetadata/image.go | FindMetadata | func (s *storage) FindMetadata(criteria MetadataFilter) (map[string][]Metadata, error) {
coll, closer := s.store.GetCollection(s.collection)
defer closer()
logger.Debugf("searching for image metadata %#v", criteria)
searchCriteria := buildSearchClauses(criteria)
var docs []imagesMetadataDoc
if err := coll.Find(searchCriteria).Sort("date_created").All(&docs); err != nil {
return nil, errors.Trace(err)
}
if len(docs) == 0 {
return nil, errors.NotFoundf("matching cloud image metadata")
}
metadata := make(map[string][]Metadata)
for _, doc := range docs {
one := doc.metadata()
metadata[one.Source] = append(metadata[one.Source], one)
}
return metadata, nil
} | go | func (s *storage) FindMetadata(criteria MetadataFilter) (map[string][]Metadata, error) {
coll, closer := s.store.GetCollection(s.collection)
defer closer()
logger.Debugf("searching for image metadata %#v", criteria)
searchCriteria := buildSearchClauses(criteria)
var docs []imagesMetadataDoc
if err := coll.Find(searchCriteria).Sort("date_created").All(&docs); err != nil {
return nil, errors.Trace(err)
}
if len(docs) == 0 {
return nil, errors.NotFoundf("matching cloud image metadata")
}
metadata := make(map[string][]Metadata)
for _, doc := range docs {
one := doc.metadata()
metadata[one.Source] = append(metadata[one.Source], one)
}
return metadata, nil
} | [
"func",
"(",
"s",
"*",
"storage",
")",
"FindMetadata",
"(",
"criteria",
"MetadataFilter",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"Metadata",
",",
"error",
")",
"{",
"coll",
",",
"closer",
":=",
"s",
".",
"store",
".",
"GetCollection",
"(",
"s",
".",
"collection",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"criteria",
")",
"\n",
"searchCriteria",
":=",
"buildSearchClauses",
"(",
"criteria",
")",
"\n",
"var",
"docs",
"[",
"]",
"imagesMetadataDoc",
"\n",
"if",
"err",
":=",
"coll",
".",
"Find",
"(",
"searchCriteria",
")",
".",
"Sort",
"(",
"\"",
"\"",
")",
".",
"All",
"(",
"&",
"docs",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"docs",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"metadata",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"Metadata",
")",
"\n",
"for",
"_",
",",
"doc",
":=",
"range",
"docs",
"{",
"one",
":=",
"doc",
".",
"metadata",
"(",
")",
"\n",
"metadata",
"[",
"one",
".",
"Source",
"]",
"=",
"append",
"(",
"metadata",
"[",
"one",
".",
"Source",
"]",
",",
"one",
")",
"\n",
"}",
"\n",
"return",
"metadata",
",",
"nil",
"\n",
"}"
] | // FindMetadata implements Storage.FindMetadata.
// Results are sorted by date created and grouped by source. | [
"FindMetadata",
"implements",
"Storage",
".",
"FindMetadata",
".",
"Results",
"are",
"sorted",
"by",
"date",
"created",
"and",
"grouped",
"by",
"source",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L353-L373 |
4,262 | juju/juju | state/cloudimagemetadata/image.go | SupportedArchitectures | func (s *storage) SupportedArchitectures(criteria MetadataFilter) ([]string, error) {
coll, closer := s.store.GetCollection(s.collection)
defer closer()
var arches []string
if err := coll.Find(buildSearchClauses(criteria)).Distinct("arch", &arches); err != nil {
return nil, errors.Trace(err)
}
return arches, nil
} | go | func (s *storage) SupportedArchitectures(criteria MetadataFilter) ([]string, error) {
coll, closer := s.store.GetCollection(s.collection)
defer closer()
var arches []string
if err := coll.Find(buildSearchClauses(criteria)).Distinct("arch", &arches); err != nil {
return nil, errors.Trace(err)
}
return arches, nil
} | [
"func",
"(",
"s",
"*",
"storage",
")",
"SupportedArchitectures",
"(",
"criteria",
"MetadataFilter",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"coll",
",",
"closer",
":=",
"s",
".",
"store",
".",
"GetCollection",
"(",
"s",
".",
"collection",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"arches",
"[",
"]",
"string",
"\n",
"if",
"err",
":=",
"coll",
".",
"Find",
"(",
"buildSearchClauses",
"(",
"criteria",
")",
")",
".",
"Distinct",
"(",
"\"",
"\"",
",",
"&",
"arches",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"arches",
",",
"nil",
"\n",
"}"
] | // SupportedArchitectures implements Storage.SupportedArchitectures. | [
"SupportedArchitectures",
"implements",
"Storage",
".",
"SupportedArchitectures",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L434-L443 |
4,263 | juju/juju | provider/common/state.go | putState | func putState(stor storage.StorageWriter, data []byte) error {
logger.Debugf("putting %q to bootstrap storage %T", StateFile, stor)
return stor.Put(StateFile, bytes.NewBuffer(data), int64(len(data)))
} | go | func putState(stor storage.StorageWriter, data []byte) error {
logger.Debugf("putting %q to bootstrap storage %T", StateFile, stor)
return stor.Put(StateFile, bytes.NewBuffer(data), int64(len(data)))
} | [
"func",
"putState",
"(",
"stor",
"storage",
".",
"StorageWriter",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"StateFile",
",",
"stor",
")",
"\n",
"return",
"stor",
".",
"Put",
"(",
"StateFile",
",",
"bytes",
".",
"NewBuffer",
"(",
"data",
")",
",",
"int64",
"(",
"len",
"(",
"data",
")",
")",
")",
"\n",
"}"
] | // putState writes the given data to the state file on the given storage.
// The file's name is as defined in StateFile. | [
"putState",
"writes",
"the",
"given",
"data",
"to",
"the",
"state",
"file",
"on",
"the",
"given",
"storage",
".",
"The",
"file",
"s",
"name",
"is",
"as",
"defined",
"in",
"StateFile",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L35-L38 |
4,264 | juju/juju | provider/common/state.go | CreateStateFile | func CreateStateFile(stor storage.Storage) (string, error) {
err := putState(stor, []byte{})
if err != nil {
return "", fmt.Errorf("cannot create initial state file: %v", err)
}
return stor.URL(StateFile)
} | go | func CreateStateFile(stor storage.Storage) (string, error) {
err := putState(stor, []byte{})
if err != nil {
return "", fmt.Errorf("cannot create initial state file: %v", err)
}
return stor.URL(StateFile)
} | [
"func",
"CreateStateFile",
"(",
"stor",
"storage",
".",
"Storage",
")",
"(",
"string",
",",
"error",
")",
"{",
"err",
":=",
"putState",
"(",
"stor",
",",
"[",
"]",
"byte",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"stor",
".",
"URL",
"(",
"StateFile",
")",
"\n",
"}"
] | // CreateStateFile creates an empty state file on the given storage, and
// returns its URL. | [
"CreateStateFile",
"creates",
"an",
"empty",
"state",
"file",
"on",
"the",
"given",
"storage",
"and",
"returns",
"its",
"URL",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L42-L48 |
4,265 | juju/juju | provider/common/state.go | SaveState | func SaveState(storage storage.StorageWriter, state *BootstrapState) error {
data, err := goyaml.Marshal(state)
if err != nil {
return err
}
return putState(storage, data)
} | go | func SaveState(storage storage.StorageWriter, state *BootstrapState) error {
data, err := goyaml.Marshal(state)
if err != nil {
return err
}
return putState(storage, data)
} | [
"func",
"SaveState",
"(",
"storage",
"storage",
".",
"StorageWriter",
",",
"state",
"*",
"BootstrapState",
")",
"error",
"{",
"data",
",",
"err",
":=",
"goyaml",
".",
"Marshal",
"(",
"state",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"putState",
"(",
"storage",
",",
"data",
")",
"\n",
"}"
] | // SaveState writes the given state to the given storage. | [
"SaveState",
"writes",
"the",
"given",
"state",
"to",
"the",
"given",
"storage",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L56-L62 |
4,266 | juju/juju | provider/common/state.go | LoadState | func LoadState(stor storage.StorageReader) (*BootstrapState, error) {
r, err := storage.Get(stor, StateFile)
if err != nil {
if errors.IsNotFound(err) {
return nil, environs.ErrNotBootstrapped
}
return nil, err
}
return loadState(r)
} | go | func LoadState(stor storage.StorageReader) (*BootstrapState, error) {
r, err := storage.Get(stor, StateFile)
if err != nil {
if errors.IsNotFound(err) {
return nil, environs.ErrNotBootstrapped
}
return nil, err
}
return loadState(r)
} | [
"func",
"LoadState",
"(",
"stor",
"storage",
".",
"StorageReader",
")",
"(",
"*",
"BootstrapState",
",",
"error",
")",
"{",
"r",
",",
"err",
":=",
"storage",
".",
"Get",
"(",
"stor",
",",
"StateFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"environs",
".",
"ErrNotBootstrapped",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"loadState",
"(",
"r",
")",
"\n",
"}"
] | // LoadState reads state from the given storage. | [
"LoadState",
"reads",
"state",
"from",
"the",
"given",
"storage",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L65-L74 |
4,267 | juju/juju | provider/common/state.go | AddStateInstance | func AddStateInstance(stor storage.Storage, id instance.Id) error {
state, err := LoadState(stor)
if err == environs.ErrNotBootstrapped {
state = &BootstrapState{}
} else if err != nil {
return errors.Annotate(err, "cannot record state instance-id")
}
state.StateInstances = append(state.StateInstances, id)
return SaveState(stor, state)
} | go | func AddStateInstance(stor storage.Storage, id instance.Id) error {
state, err := LoadState(stor)
if err == environs.ErrNotBootstrapped {
state = &BootstrapState{}
} else if err != nil {
return errors.Annotate(err, "cannot record state instance-id")
}
state.StateInstances = append(state.StateInstances, id)
return SaveState(stor, state)
} | [
"func",
"AddStateInstance",
"(",
"stor",
"storage",
".",
"Storage",
",",
"id",
"instance",
".",
"Id",
")",
"error",
"{",
"state",
",",
"err",
":=",
"LoadState",
"(",
"stor",
")",
"\n",
"if",
"err",
"==",
"environs",
".",
"ErrNotBootstrapped",
"{",
"state",
"=",
"&",
"BootstrapState",
"{",
"}",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"state",
".",
"StateInstances",
"=",
"append",
"(",
"state",
".",
"StateInstances",
",",
"id",
")",
"\n",
"return",
"SaveState",
"(",
"stor",
",",
"state",
")",
"\n",
"}"
] | // AddStateInstance adds a controller instance ID to the provider-state
// file in storage. | [
"AddStateInstance",
"adds",
"a",
"controller",
"instance",
"ID",
"to",
"the",
"provider",
"-",
"state",
"file",
"in",
"storage",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L92-L101 |
4,268 | juju/juju | provider/common/state.go | RemoveStateInstances | func RemoveStateInstances(stor storage.Storage, ids ...instance.Id) error {
state, err := LoadState(stor)
if err == environs.ErrNotBootstrapped {
return nil
} else if err != nil {
return errors.Annotate(err, "cannot remove recorded state instance-id")
}
var anyFound bool
for i := 0; i < len(state.StateInstances); i++ {
for _, id := range ids {
if state.StateInstances[i] == id {
head := state.StateInstances[:i]
tail := state.StateInstances[i+1:]
state.StateInstances = append(head, tail...)
anyFound = true
i--
break
}
}
}
if !anyFound {
return nil
}
return SaveState(stor, state)
} | go | func RemoveStateInstances(stor storage.Storage, ids ...instance.Id) error {
state, err := LoadState(stor)
if err == environs.ErrNotBootstrapped {
return nil
} else if err != nil {
return errors.Annotate(err, "cannot remove recorded state instance-id")
}
var anyFound bool
for i := 0; i < len(state.StateInstances); i++ {
for _, id := range ids {
if state.StateInstances[i] == id {
head := state.StateInstances[:i]
tail := state.StateInstances[i+1:]
state.StateInstances = append(head, tail...)
anyFound = true
i--
break
}
}
}
if !anyFound {
return nil
}
return SaveState(stor, state)
} | [
"func",
"RemoveStateInstances",
"(",
"stor",
"storage",
".",
"Storage",
",",
"ids",
"...",
"instance",
".",
"Id",
")",
"error",
"{",
"state",
",",
"err",
":=",
"LoadState",
"(",
"stor",
")",
"\n",
"if",
"err",
"==",
"environs",
".",
"ErrNotBootstrapped",
"{",
"return",
"nil",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"var",
"anyFound",
"bool",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"state",
".",
"StateInstances",
")",
";",
"i",
"++",
"{",
"for",
"_",
",",
"id",
":=",
"range",
"ids",
"{",
"if",
"state",
".",
"StateInstances",
"[",
"i",
"]",
"==",
"id",
"{",
"head",
":=",
"state",
".",
"StateInstances",
"[",
":",
"i",
"]",
"\n",
"tail",
":=",
"state",
".",
"StateInstances",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"state",
".",
"StateInstances",
"=",
"append",
"(",
"head",
",",
"tail",
"...",
")",
"\n",
"anyFound",
"=",
"true",
"\n",
"i",
"--",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"anyFound",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"SaveState",
"(",
"stor",
",",
"state",
")",
"\n",
"}"
] | // RemoveStateInstances removes controller instance IDs from the
// provider-state file in storage. Instance IDs that are not found
// in the file are ignored. | [
"RemoveStateInstances",
"removes",
"controller",
"instance",
"IDs",
"from",
"the",
"provider",
"-",
"state",
"file",
"in",
"storage",
".",
"Instance",
"IDs",
"that",
"are",
"not",
"found",
"in",
"the",
"file",
"are",
"ignored",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L106-L130 |
4,269 | juju/juju | provider/common/state.go | ProviderStateInstances | func ProviderStateInstances(stor storage.StorageReader) ([]instance.Id, error) {
st, err := LoadState(stor)
if err != nil {
return nil, err
}
return st.StateInstances, nil
} | go | func ProviderStateInstances(stor storage.StorageReader) ([]instance.Id, error) {
st, err := LoadState(stor)
if err != nil {
return nil, err
}
return st.StateInstances, nil
} | [
"func",
"ProviderStateInstances",
"(",
"stor",
"storage",
".",
"StorageReader",
")",
"(",
"[",
"]",
"instance",
".",
"Id",
",",
"error",
")",
"{",
"st",
",",
"err",
":=",
"LoadState",
"(",
"stor",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"st",
".",
"StateInstances",
",",
"nil",
"\n",
"}"
] | // ProviderStateInstances extracts the instance IDs from provider-state. | [
"ProviderStateInstances",
"extracts",
"the",
"instance",
"IDs",
"from",
"provider",
"-",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L133-L139 |
4,270 | juju/juju | apiserver/facades/controller/caasfirewaller/firewaller.go | NewFacade | func NewFacade(
resources facade.Resources,
authorizer facade.Authorizer,
st CAASFirewallerState,
) (*Facade, error) {
if !authorizer.AuthController() {
return nil, common.ErrPerm
}
accessApplication := common.AuthFuncForTagKind(names.ApplicationTagKind)
return &Facade{
LifeGetter: common.NewLifeGetter(
st, common.AuthAny(
common.AuthFuncForTagKind(names.ApplicationTagKind),
common.AuthFuncForTagKind(names.UnitTagKind),
),
),
AgentEntityWatcher: common.NewAgentEntityWatcher(
st,
resources,
accessApplication,
),
resources: resources,
state: st,
}, nil
} | go | func NewFacade(
resources facade.Resources,
authorizer facade.Authorizer,
st CAASFirewallerState,
) (*Facade, error) {
if !authorizer.AuthController() {
return nil, common.ErrPerm
}
accessApplication := common.AuthFuncForTagKind(names.ApplicationTagKind)
return &Facade{
LifeGetter: common.NewLifeGetter(
st, common.AuthAny(
common.AuthFuncForTagKind(names.ApplicationTagKind),
common.AuthFuncForTagKind(names.UnitTagKind),
),
),
AgentEntityWatcher: common.NewAgentEntityWatcher(
st,
resources,
accessApplication,
),
resources: resources,
state: st,
}, nil
} | [
"func",
"NewFacade",
"(",
"resources",
"facade",
".",
"Resources",
",",
"authorizer",
"facade",
".",
"Authorizer",
",",
"st",
"CAASFirewallerState",
",",
")",
"(",
"*",
"Facade",
",",
"error",
")",
"{",
"if",
"!",
"authorizer",
".",
"AuthController",
"(",
")",
"{",
"return",
"nil",
",",
"common",
".",
"ErrPerm",
"\n",
"}",
"\n",
"accessApplication",
":=",
"common",
".",
"AuthFuncForTagKind",
"(",
"names",
".",
"ApplicationTagKind",
")",
"\n",
"return",
"&",
"Facade",
"{",
"LifeGetter",
":",
"common",
".",
"NewLifeGetter",
"(",
"st",
",",
"common",
".",
"AuthAny",
"(",
"common",
".",
"AuthFuncForTagKind",
"(",
"names",
".",
"ApplicationTagKind",
")",
",",
"common",
".",
"AuthFuncForTagKind",
"(",
"names",
".",
"UnitTagKind",
")",
",",
")",
",",
")",
",",
"AgentEntityWatcher",
":",
"common",
".",
"NewAgentEntityWatcher",
"(",
"st",
",",
"resources",
",",
"accessApplication",
",",
")",
",",
"resources",
":",
"resources",
",",
"state",
":",
"st",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewFacade returns a new CAAS firewaller Facade facade. | [
"NewFacade",
"returns",
"a",
"new",
"CAAS",
"firewaller",
"Facade",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasfirewaller/firewaller.go#L35-L59 |
4,271 | juju/juju | apiserver/facades/controller/caasfirewaller/firewaller.go | IsExposed | func (f *Facade) IsExposed(args params.Entities) (params.BoolResults, error) {
results := params.BoolResults{
Results: make([]params.BoolResult, len(args.Entities)),
}
for i, arg := range args.Entities {
exposed, err := f.isExposed(f.state, arg.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = exposed
}
return results, nil
} | go | func (f *Facade) IsExposed(args params.Entities) (params.BoolResults, error) {
results := params.BoolResults{
Results: make([]params.BoolResult, len(args.Entities)),
}
for i, arg := range args.Entities {
exposed, err := f.isExposed(f.state, arg.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = exposed
}
return results, nil
} | [
"func",
"(",
"f",
"*",
"Facade",
")",
"IsExposed",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"BoolResults",
",",
"error",
")",
"{",
"results",
":=",
"params",
".",
"BoolResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"BoolResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"arg",
":=",
"range",
"args",
".",
"Entities",
"{",
"exposed",
",",
"err",
":=",
"f",
".",
"isExposed",
"(",
"f",
".",
"state",
",",
"arg",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Result",
"=",
"exposed",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // IsExposed returns whether the specified applications are exposed. | [
"IsExposed",
"returns",
"whether",
"the",
"specified",
"applications",
"are",
"exposed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasfirewaller/firewaller.go#L75-L88 |
4,272 | juju/juju | cmd/juju/commands/import_sshkeys.go | Run | func (c *importKeysCommand) Run(context *cmd.Context) error {
client, err := c.NewKeyManagerClient()
if err != nil {
return err
}
defer client.Close()
// TODO(alexisb) - currently keys are global which is not ideal.
// keymanager needs to be updated to allow keys per user
c.user = "admin"
results, err := client.ImportKeys(c.user, c.sshKeyIds...)
if err != nil {
return block.ProcessBlockedError(err, block.BlockChange)
}
for i, result := range results {
if result.Error != nil {
fmt.Fprintf(context.Stderr, "cannot import key id %q: %v\n", c.sshKeyIds[i], result.Error)
}
}
return nil
} | go | func (c *importKeysCommand) Run(context *cmd.Context) error {
client, err := c.NewKeyManagerClient()
if err != nil {
return err
}
defer client.Close()
// TODO(alexisb) - currently keys are global which is not ideal.
// keymanager needs to be updated to allow keys per user
c.user = "admin"
results, err := client.ImportKeys(c.user, c.sshKeyIds...)
if err != nil {
return block.ProcessBlockedError(err, block.BlockChange)
}
for i, result := range results {
if result.Error != nil {
fmt.Fprintf(context.Stderr, "cannot import key id %q: %v\n", c.sshKeyIds[i], result.Error)
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"importKeysCommand",
")",
"Run",
"(",
"context",
"*",
"cmd",
".",
"Context",
")",
"error",
"{",
"client",
",",
"err",
":=",
"c",
".",
"NewKeyManagerClient",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"client",
".",
"Close",
"(",
")",
"\n\n",
"// TODO(alexisb) - currently keys are global which is not ideal.",
"// keymanager needs to be updated to allow keys per user",
"c",
".",
"user",
"=",
"\"",
"\"",
"\n",
"results",
",",
"err",
":=",
"client",
".",
"ImportKeys",
"(",
"c",
".",
"user",
",",
"c",
".",
"sshKeyIds",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"block",
".",
"ProcessBlockedError",
"(",
"err",
",",
"block",
".",
"BlockChange",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"result",
":=",
"range",
"results",
"{",
"if",
"result",
".",
"Error",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"context",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"c",
".",
"sshKeyIds",
"[",
"i",
"]",
",",
"result",
".",
"Error",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Run implemetns Command.Run. | [
"Run",
"implemetns",
"Command",
".",
"Run",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/import_sshkeys.go#L92-L112 |
4,273 | juju/juju | environs/tools/validation.go | ValidateToolsMetadata | func ValidateToolsMetadata(params *ToolsMetadataLookupParams) ([]string, *simplestreams.ResolveInfo, error) {
if len(params.Sources) == 0 {
return nil, nil, fmt.Errorf("required parameter sources not specified")
}
if params.Version == "" && params.Major == 0 {
params.Version = jujuversion.Current.String()
}
var toolsConstraint *ToolsConstraint
if params.Version == "" {
toolsConstraint = NewGeneralToolsConstraint(params.Major, params.Minor, simplestreams.LookupParams{
CloudSpec: simplestreams.CloudSpec{
Region: params.Region,
Endpoint: params.Endpoint,
},
Stream: params.Stream,
Series: []string{params.Series},
Arches: params.Architectures,
})
} else {
versNum, err := version.Parse(params.Version)
if err != nil {
return nil, nil, err
}
toolsConstraint = NewVersionedToolsConstraint(versNum, simplestreams.LookupParams{
CloudSpec: simplestreams.CloudSpec{
Region: params.Region,
Endpoint: params.Endpoint,
},
Stream: params.Stream,
Series: []string{params.Series},
Arches: params.Architectures,
})
}
matchingTools, resolveInfo, err := Fetch(params.Sources, toolsConstraint)
if err != nil {
return nil, resolveInfo, err
}
if len(matchingTools) == 0 {
return nil, resolveInfo, fmt.Errorf("no matching agent binaries found for constraint %+v", toolsConstraint)
}
versions := make([]string, len(matchingTools))
for i, tm := range matchingTools {
vers := version.Binary{
Number: version.MustParse(tm.Version),
Series: tm.Release,
Arch: tm.Arch,
}
versions[i] = vers.String()
}
return versions, resolveInfo, nil
} | go | func ValidateToolsMetadata(params *ToolsMetadataLookupParams) ([]string, *simplestreams.ResolveInfo, error) {
if len(params.Sources) == 0 {
return nil, nil, fmt.Errorf("required parameter sources not specified")
}
if params.Version == "" && params.Major == 0 {
params.Version = jujuversion.Current.String()
}
var toolsConstraint *ToolsConstraint
if params.Version == "" {
toolsConstraint = NewGeneralToolsConstraint(params.Major, params.Minor, simplestreams.LookupParams{
CloudSpec: simplestreams.CloudSpec{
Region: params.Region,
Endpoint: params.Endpoint,
},
Stream: params.Stream,
Series: []string{params.Series},
Arches: params.Architectures,
})
} else {
versNum, err := version.Parse(params.Version)
if err != nil {
return nil, nil, err
}
toolsConstraint = NewVersionedToolsConstraint(versNum, simplestreams.LookupParams{
CloudSpec: simplestreams.CloudSpec{
Region: params.Region,
Endpoint: params.Endpoint,
},
Stream: params.Stream,
Series: []string{params.Series},
Arches: params.Architectures,
})
}
matchingTools, resolveInfo, err := Fetch(params.Sources, toolsConstraint)
if err != nil {
return nil, resolveInfo, err
}
if len(matchingTools) == 0 {
return nil, resolveInfo, fmt.Errorf("no matching agent binaries found for constraint %+v", toolsConstraint)
}
versions := make([]string, len(matchingTools))
for i, tm := range matchingTools {
vers := version.Binary{
Number: version.MustParse(tm.Version),
Series: tm.Release,
Arch: tm.Arch,
}
versions[i] = vers.String()
}
return versions, resolveInfo, nil
} | [
"func",
"ValidateToolsMetadata",
"(",
"params",
"*",
"ToolsMetadataLookupParams",
")",
"(",
"[",
"]",
"string",
",",
"*",
"simplestreams",
".",
"ResolveInfo",
",",
"error",
")",
"{",
"if",
"len",
"(",
"params",
".",
"Sources",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"params",
".",
"Version",
"==",
"\"",
"\"",
"&&",
"params",
".",
"Major",
"==",
"0",
"{",
"params",
".",
"Version",
"=",
"jujuversion",
".",
"Current",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"var",
"toolsConstraint",
"*",
"ToolsConstraint",
"\n",
"if",
"params",
".",
"Version",
"==",
"\"",
"\"",
"{",
"toolsConstraint",
"=",
"NewGeneralToolsConstraint",
"(",
"params",
".",
"Major",
",",
"params",
".",
"Minor",
",",
"simplestreams",
".",
"LookupParams",
"{",
"CloudSpec",
":",
"simplestreams",
".",
"CloudSpec",
"{",
"Region",
":",
"params",
".",
"Region",
",",
"Endpoint",
":",
"params",
".",
"Endpoint",
",",
"}",
",",
"Stream",
":",
"params",
".",
"Stream",
",",
"Series",
":",
"[",
"]",
"string",
"{",
"params",
".",
"Series",
"}",
",",
"Arches",
":",
"params",
".",
"Architectures",
",",
"}",
")",
"\n",
"}",
"else",
"{",
"versNum",
",",
"err",
":=",
"version",
".",
"Parse",
"(",
"params",
".",
"Version",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"toolsConstraint",
"=",
"NewVersionedToolsConstraint",
"(",
"versNum",
",",
"simplestreams",
".",
"LookupParams",
"{",
"CloudSpec",
":",
"simplestreams",
".",
"CloudSpec",
"{",
"Region",
":",
"params",
".",
"Region",
",",
"Endpoint",
":",
"params",
".",
"Endpoint",
",",
"}",
",",
"Stream",
":",
"params",
".",
"Stream",
",",
"Series",
":",
"[",
"]",
"string",
"{",
"params",
".",
"Series",
"}",
",",
"Arches",
":",
"params",
".",
"Architectures",
",",
"}",
")",
"\n",
"}",
"\n",
"matchingTools",
",",
"resolveInfo",
",",
"err",
":=",
"Fetch",
"(",
"params",
".",
"Sources",
",",
"toolsConstraint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"resolveInfo",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"matchingTools",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"resolveInfo",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"toolsConstraint",
")",
"\n",
"}",
"\n",
"versions",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"matchingTools",
")",
")",
"\n",
"for",
"i",
",",
"tm",
":=",
"range",
"matchingTools",
"{",
"vers",
":=",
"version",
".",
"Binary",
"{",
"Number",
":",
"version",
".",
"MustParse",
"(",
"tm",
".",
"Version",
")",
",",
"Series",
":",
"tm",
".",
"Release",
",",
"Arch",
":",
"tm",
".",
"Arch",
",",
"}",
"\n",
"versions",
"[",
"i",
"]",
"=",
"vers",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"return",
"versions",
",",
"resolveInfo",
",",
"nil",
"\n",
"}"
] | // ValidateToolsMetadata attempts to load tools metadata for the specified cloud attributes and returns
// any tools versions found, or an error if the metadata could not be loaded. | [
"ValidateToolsMetadata",
"attempts",
"to",
"load",
"tools",
"metadata",
"for",
"the",
"specified",
"cloud",
"attributes",
"and",
"returns",
"any",
"tools",
"versions",
"found",
"or",
"an",
"error",
"if",
"the",
"metadata",
"could",
"not",
"be",
"loaded",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/validation.go#L25-L75 |
4,274 | juju/juju | state/firewallrules.go | Save | func (fw *firewallRulesState) Save(rule FirewallRule) error {
if err := rule.WellKnownService.validate(); err != nil {
return errors.Trace(err)
}
for _, cidr := range rule.WhitelistCIDRs {
if _, _, err := net.ParseCIDR(cidr); err != nil {
return errors.NotValidf("CIDR %q", cidr)
}
}
serviceStr := string(rule.WellKnownService)
doc := firewallRulesDoc{
Id: serviceStr,
WellKnownService: serviceStr,
WhitelistCIDRS: rule.WhitelistCIDRs,
}
buildTxn := func(int) ([]txn.Op, error) {
model, err := fw.st.Model()
if err != nil {
return nil, errors.Annotate(err, "failed to load model")
}
if err := checkModelActive(fw.st); err != nil {
return nil, errors.Trace(err)
}
_, err = fw.Rule(rule.WellKnownService)
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
var ops []txn.Op
if err == nil {
ops = []txn.Op{{
C: firewallRulesC,
Id: serviceStr,
Assert: txn.DocExists,
Update: bson.D{
{"$set", bson.D{{"whitelist-cidrs", rule.WhitelistCIDRs}}},
},
}, model.assertActiveOp()}
} else {
doc.WhitelistCIDRS = rule.WhitelistCIDRs
ops = []txn.Op{{
C: firewallRulesC,
Id: doc.Id,
Assert: txn.DocMissing,
Insert: doc,
}, model.assertActiveOp()}
}
return ops, nil
}
if err := fw.st.db().Run(buildTxn); err != nil {
return errors.Annotate(err, "failed to create firewall rules")
}
return nil
} | go | func (fw *firewallRulesState) Save(rule FirewallRule) error {
if err := rule.WellKnownService.validate(); err != nil {
return errors.Trace(err)
}
for _, cidr := range rule.WhitelistCIDRs {
if _, _, err := net.ParseCIDR(cidr); err != nil {
return errors.NotValidf("CIDR %q", cidr)
}
}
serviceStr := string(rule.WellKnownService)
doc := firewallRulesDoc{
Id: serviceStr,
WellKnownService: serviceStr,
WhitelistCIDRS: rule.WhitelistCIDRs,
}
buildTxn := func(int) ([]txn.Op, error) {
model, err := fw.st.Model()
if err != nil {
return nil, errors.Annotate(err, "failed to load model")
}
if err := checkModelActive(fw.st); err != nil {
return nil, errors.Trace(err)
}
_, err = fw.Rule(rule.WellKnownService)
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
var ops []txn.Op
if err == nil {
ops = []txn.Op{{
C: firewallRulesC,
Id: serviceStr,
Assert: txn.DocExists,
Update: bson.D{
{"$set", bson.D{{"whitelist-cidrs", rule.WhitelistCIDRs}}},
},
}, model.assertActiveOp()}
} else {
doc.WhitelistCIDRS = rule.WhitelistCIDRs
ops = []txn.Op{{
C: firewallRulesC,
Id: doc.Id,
Assert: txn.DocMissing,
Insert: doc,
}, model.assertActiveOp()}
}
return ops, nil
}
if err := fw.st.db().Run(buildTxn); err != nil {
return errors.Annotate(err, "failed to create firewall rules")
}
return nil
} | [
"func",
"(",
"fw",
"*",
"firewallRulesState",
")",
"Save",
"(",
"rule",
"FirewallRule",
")",
"error",
"{",
"if",
"err",
":=",
"rule",
".",
"WellKnownService",
".",
"validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"cidr",
":=",
"range",
"rule",
".",
"WhitelistCIDRs",
"{",
"if",
"_",
",",
"_",
",",
"err",
":=",
"net",
".",
"ParseCIDR",
"(",
"cidr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
",",
"cidr",
")",
"\n",
"}",
"\n",
"}",
"\n",
"serviceStr",
":=",
"string",
"(",
"rule",
".",
"WellKnownService",
")",
"\n",
"doc",
":=",
"firewallRulesDoc",
"{",
"Id",
":",
"serviceStr",
",",
"WellKnownService",
":",
"serviceStr",
",",
"WhitelistCIDRS",
":",
"rule",
".",
"WhitelistCIDRs",
",",
"}",
"\n",
"buildTxn",
":=",
"func",
"(",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"model",
",",
"err",
":=",
"fw",
".",
"st",
".",
"Model",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"checkModelActive",
"(",
"fw",
".",
"st",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"fw",
".",
"Rule",
"(",
"rule",
".",
"WellKnownService",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"if",
"err",
"==",
"nil",
"{",
"ops",
"=",
"[",
"]",
"txn",
".",
"Op",
"{",
"{",
"C",
":",
"firewallRulesC",
",",
"Id",
":",
"serviceStr",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"rule",
".",
"WhitelistCIDRs",
"}",
"}",
"}",
",",
"}",
",",
"}",
",",
"model",
".",
"assertActiveOp",
"(",
")",
"}",
"\n",
"}",
"else",
"{",
"doc",
".",
"WhitelistCIDRS",
"=",
"rule",
".",
"WhitelistCIDRs",
"\n",
"ops",
"=",
"[",
"]",
"txn",
".",
"Op",
"{",
"{",
"C",
":",
"firewallRulesC",
",",
"Id",
":",
"doc",
".",
"Id",
",",
"Assert",
":",
"txn",
".",
"DocMissing",
",",
"Insert",
":",
"doc",
",",
"}",
",",
"model",
".",
"assertActiveOp",
"(",
")",
"}",
"\n",
"}",
"\n",
"return",
"ops",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"fw",
".",
"st",
".",
"db",
"(",
")",
".",
"Run",
"(",
"buildTxn",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Save stores the specified firewall rule. | [
"Save",
"stores",
"the",
"specified",
"firewall",
"rule",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/firewallrules.go#L88-L142 |
4,275 | juju/juju | state/firewallrules.go | Rule | func (fw *firewallRulesState) Rule(service WellKnownServiceType) (*FirewallRule, error) {
coll, closer := fw.st.db().GetCollection(firewallRulesC)
defer closer()
var doc firewallRulesDoc
err := coll.FindId(string(service)).One(&doc)
if err == mgo.ErrNotFound {
return nil, errors.NotFoundf("firewall rules for service %v", service)
}
if err != nil {
return nil, errors.Trace(err)
}
return doc.toRule(), nil
} | go | func (fw *firewallRulesState) Rule(service WellKnownServiceType) (*FirewallRule, error) {
coll, closer := fw.st.db().GetCollection(firewallRulesC)
defer closer()
var doc firewallRulesDoc
err := coll.FindId(string(service)).One(&doc)
if err == mgo.ErrNotFound {
return nil, errors.NotFoundf("firewall rules for service %v", service)
}
if err != nil {
return nil, errors.Trace(err)
}
return doc.toRule(), nil
} | [
"func",
"(",
"fw",
"*",
"firewallRulesState",
")",
"Rule",
"(",
"service",
"WellKnownServiceType",
")",
"(",
"*",
"FirewallRule",
",",
"error",
")",
"{",
"coll",
",",
"closer",
":=",
"fw",
".",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"firewallRulesC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"doc",
"firewallRulesDoc",
"\n",
"err",
":=",
"coll",
".",
"FindId",
"(",
"string",
"(",
"service",
")",
")",
".",
"One",
"(",
"&",
"doc",
")",
"\n",
"if",
"err",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"service",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"doc",
".",
"toRule",
"(",
")",
",",
"nil",
"\n",
"}"
] | // Rule returns the firewall rule for the specified service. | [
"Rule",
"returns",
"the",
"firewall",
"rule",
"for",
"the",
"specified",
"service",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/firewallrules.go#L145-L158 |
4,276 | juju/juju | state/firewallrules.go | AllRules | func (fw *firewallRulesState) AllRules() ([]*FirewallRule, error) {
coll, closer := fw.st.db().GetCollection(firewallRulesC)
defer closer()
var docs []firewallRulesDoc
err := coll.Find(nil).All(&docs)
if err != nil {
return nil, errors.Trace(err)
}
result := make([]*FirewallRule, len(docs))
for i, doc := range docs {
result[i] = doc.toRule()
}
return result, nil
} | go | func (fw *firewallRulesState) AllRules() ([]*FirewallRule, error) {
coll, closer := fw.st.db().GetCollection(firewallRulesC)
defer closer()
var docs []firewallRulesDoc
err := coll.Find(nil).All(&docs)
if err != nil {
return nil, errors.Trace(err)
}
result := make([]*FirewallRule, len(docs))
for i, doc := range docs {
result[i] = doc.toRule()
}
return result, nil
} | [
"func",
"(",
"fw",
"*",
"firewallRulesState",
")",
"AllRules",
"(",
")",
"(",
"[",
"]",
"*",
"FirewallRule",
",",
"error",
")",
"{",
"coll",
",",
"closer",
":=",
"fw",
".",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"firewallRulesC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"docs",
"[",
"]",
"firewallRulesDoc",
"\n",
"err",
":=",
"coll",
".",
"Find",
"(",
"nil",
")",
".",
"All",
"(",
"&",
"docs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"*",
"FirewallRule",
",",
"len",
"(",
"docs",
")",
")",
"\n",
"for",
"i",
",",
"doc",
":=",
"range",
"docs",
"{",
"result",
"[",
"i",
"]",
"=",
"doc",
".",
"toRule",
"(",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // AllRules returns all the firewall rules. | [
"AllRules",
"returns",
"all",
"the",
"firewall",
"rules",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/firewallrules.go#L161-L175 |
4,277 | juju/juju | worker/meterstatus/runner.go | acquireExecutionLock | func (w *hookRunner) acquireExecutionLock(action string, interrupt <-chan struct{}) (func(), error) {
spec := machinelock.Spec{
Cancel: interrupt,
Worker: "meterstatus",
Comment: action,
}
releaser, err := w.machineLock.Acquire(spec)
if err != nil {
return nil, errors.Trace(err)
}
return releaser, nil
} | go | func (w *hookRunner) acquireExecutionLock(action string, interrupt <-chan struct{}) (func(), error) {
spec := machinelock.Spec{
Cancel: interrupt,
Worker: "meterstatus",
Comment: action,
}
releaser, err := w.machineLock.Acquire(spec)
if err != nil {
return nil, errors.Trace(err)
}
return releaser, nil
} | [
"func",
"(",
"w",
"*",
"hookRunner",
")",
"acquireExecutionLock",
"(",
"action",
"string",
",",
"interrupt",
"<-",
"chan",
"struct",
"{",
"}",
")",
"(",
"func",
"(",
")",
",",
"error",
")",
"{",
"spec",
":=",
"machinelock",
".",
"Spec",
"{",
"Cancel",
":",
"interrupt",
",",
"Worker",
":",
"\"",
"\"",
",",
"Comment",
":",
"action",
",",
"}",
"\n",
"releaser",
",",
"err",
":=",
"w",
".",
"machineLock",
".",
"Acquire",
"(",
"spec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"releaser",
",",
"nil",
"\n",
"}"
] | // acquireExecutionLock acquires the machine-level execution lock and returns a function to be used
// to unlock it. | [
"acquireExecutionLock",
"acquires",
"the",
"machine",
"-",
"level",
"execution",
"lock",
"and",
"returns",
"a",
"function",
"to",
"be",
"used",
"to",
"unlock",
"it",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/meterstatus/runner.go#L42-L53 |
4,278 | juju/juju | state/clouduser.go | CreateCloudAccess | func (st *State) CreateCloudAccess(cloud string, user names.UserTag, access permission.Access) error {
if err := permission.ValidateCloudAccess(access); err != nil {
return errors.Trace(err)
}
// Local users must exist.
if user.IsLocal() {
_, err := st.User(user)
if err != nil {
if errors.IsNotFound(err) {
return errors.Annotatef(err, "user %q does not exist locally", user.Name())
}
return errors.Trace(err)
}
}
op := createPermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)), access)
err := st.db().RunTransaction([]txn.Op{op})
if err == txn.ErrAborted {
err = errors.AlreadyExistsf("permission for user %q for cloud %q", user.Id(), cloud)
}
return errors.Trace(err)
} | go | func (st *State) CreateCloudAccess(cloud string, user names.UserTag, access permission.Access) error {
if err := permission.ValidateCloudAccess(access); err != nil {
return errors.Trace(err)
}
// Local users must exist.
if user.IsLocal() {
_, err := st.User(user)
if err != nil {
if errors.IsNotFound(err) {
return errors.Annotatef(err, "user %q does not exist locally", user.Name())
}
return errors.Trace(err)
}
}
op := createPermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)), access)
err := st.db().RunTransaction([]txn.Op{op})
if err == txn.ErrAborted {
err = errors.AlreadyExistsf("permission for user %q for cloud %q", user.Id(), cloud)
}
return errors.Trace(err)
} | [
"func",
"(",
"st",
"*",
"State",
")",
"CreateCloudAccess",
"(",
"cloud",
"string",
",",
"user",
"names",
".",
"UserTag",
",",
"access",
"permission",
".",
"Access",
")",
"error",
"{",
"if",
"err",
":=",
"permission",
".",
"ValidateCloudAccess",
"(",
"access",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Local users must exist.",
"if",
"user",
".",
"IsLocal",
"(",
")",
"{",
"_",
",",
"err",
":=",
"st",
".",
"User",
"(",
"user",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"user",
".",
"Name",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"op",
":=",
"createPermissionOp",
"(",
"cloudGlobalKey",
"(",
"cloud",
")",
",",
"userGlobalKey",
"(",
"userAccessID",
"(",
"user",
")",
")",
",",
"access",
")",
"\n\n",
"err",
":=",
"st",
".",
"db",
"(",
")",
".",
"RunTransaction",
"(",
"[",
"]",
"txn",
".",
"Op",
"{",
"op",
"}",
")",
"\n",
"if",
"err",
"==",
"txn",
".",
"ErrAborted",
"{",
"err",
"=",
"errors",
".",
"AlreadyExistsf",
"(",
"\"",
"\"",
",",
"user",
".",
"Id",
"(",
")",
",",
"cloud",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // CreateCloudAccess creates a new access permission for a user on a cloud. | [
"CreateCloudAccess",
"creates",
"a",
"new",
"access",
"permission",
"for",
"a",
"user",
"on",
"a",
"cloud",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L21-L44 |
4,279 | juju/juju | state/clouduser.go | GetCloudAccess | func (st *State) GetCloudAccess(cloud string, user names.UserTag) (permission.Access, error) {
perm, err := st.userPermission(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)))
if err != nil {
return "", errors.Trace(err)
}
return perm.access(), nil
} | go | func (st *State) GetCloudAccess(cloud string, user names.UserTag) (permission.Access, error) {
perm, err := st.userPermission(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)))
if err != nil {
return "", errors.Trace(err)
}
return perm.access(), nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"GetCloudAccess",
"(",
"cloud",
"string",
",",
"user",
"names",
".",
"UserTag",
")",
"(",
"permission",
".",
"Access",
",",
"error",
")",
"{",
"perm",
",",
"err",
":=",
"st",
".",
"userPermission",
"(",
"cloudGlobalKey",
"(",
"cloud",
")",
",",
"userGlobalKey",
"(",
"userAccessID",
"(",
"user",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"perm",
".",
"access",
"(",
")",
",",
"nil",
"\n",
"}"
] | // GetCloudAccess gets the access permission for the specified user on a cloud. | [
"GetCloudAccess",
"gets",
"the",
"access",
"permission",
"for",
"the",
"specified",
"user",
"on",
"a",
"cloud",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L47-L53 |
4,280 | juju/juju | state/clouduser.go | GetCloudUsers | func (st *State) GetCloudUsers(cloud string) (map[string]permission.Access, error) {
perms, err := st.usersPermissions(cloudGlobalKey(cloud))
if err != nil {
return nil, errors.Trace(err)
}
result := make(map[string]permission.Access)
for _, p := range perms {
result[userIDFromGlobalKey(p.doc.SubjectGlobalKey)] = p.access()
}
return result, nil
} | go | func (st *State) GetCloudUsers(cloud string) (map[string]permission.Access, error) {
perms, err := st.usersPermissions(cloudGlobalKey(cloud))
if err != nil {
return nil, errors.Trace(err)
}
result := make(map[string]permission.Access)
for _, p := range perms {
result[userIDFromGlobalKey(p.doc.SubjectGlobalKey)] = p.access()
}
return result, nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"GetCloudUsers",
"(",
"cloud",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"permission",
".",
"Access",
",",
"error",
")",
"{",
"perms",
",",
"err",
":=",
"st",
".",
"usersPermissions",
"(",
"cloudGlobalKey",
"(",
"cloud",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"result",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"permission",
".",
"Access",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"perms",
"{",
"result",
"[",
"userIDFromGlobalKey",
"(",
"p",
".",
"doc",
".",
"SubjectGlobalKey",
")",
"]",
"=",
"p",
".",
"access",
"(",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // GetCloudUsers gets the access permissions on a cloud. | [
"GetCloudUsers",
"gets",
"the",
"access",
"permissions",
"on",
"a",
"cloud",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L56-L66 |
4,281 | juju/juju | state/clouduser.go | UpdateCloudAccess | func (st *State) UpdateCloudAccess(cloud string, user names.UserTag, access permission.Access) error {
if err := permission.ValidateCloudAccess(access); err != nil {
return errors.Trace(err)
}
buildTxn := func(int) ([]txn.Op, error) {
_, err := st.GetCloudAccess(cloud, user)
if err != nil {
return nil, errors.Trace(err)
}
ops := []txn.Op{updatePermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)), access)}
return ops, nil
}
err := st.db().Run(buildTxn)
return errors.Trace(err)
} | go | func (st *State) UpdateCloudAccess(cloud string, user names.UserTag, access permission.Access) error {
if err := permission.ValidateCloudAccess(access); err != nil {
return errors.Trace(err)
}
buildTxn := func(int) ([]txn.Op, error) {
_, err := st.GetCloudAccess(cloud, user)
if err != nil {
return nil, errors.Trace(err)
}
ops := []txn.Op{updatePermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)), access)}
return ops, nil
}
err := st.db().Run(buildTxn)
return errors.Trace(err)
} | [
"func",
"(",
"st",
"*",
"State",
")",
"UpdateCloudAccess",
"(",
"cloud",
"string",
",",
"user",
"names",
".",
"UserTag",
",",
"access",
"permission",
".",
"Access",
")",
"error",
"{",
"if",
"err",
":=",
"permission",
".",
"ValidateCloudAccess",
"(",
"access",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"buildTxn",
":=",
"func",
"(",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"_",
",",
"err",
":=",
"st",
".",
"GetCloudAccess",
"(",
"cloud",
",",
"user",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"ops",
":=",
"[",
"]",
"txn",
".",
"Op",
"{",
"updatePermissionOp",
"(",
"cloudGlobalKey",
"(",
"cloud",
")",
",",
"userGlobalKey",
"(",
"userAccessID",
"(",
"user",
")",
")",
",",
"access",
")",
"}",
"\n",
"return",
"ops",
",",
"nil",
"\n",
"}",
"\n\n",
"err",
":=",
"st",
".",
"db",
"(",
")",
".",
"Run",
"(",
"buildTxn",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // UpdateCloudAccess changes the user's access permissions on a cloud. | [
"UpdateCloudAccess",
"changes",
"the",
"user",
"s",
"access",
"permissions",
"on",
"a",
"cloud",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L69-L85 |
4,282 | juju/juju | state/clouduser.go | RemoveCloudAccess | func (st *State) RemoveCloudAccess(cloud string, user names.UserTag) error {
buildTxn := func(int) ([]txn.Op, error) {
_, err := st.GetCloudAccess(cloud, user)
if err != nil {
return nil, err
}
ops := []txn.Op{removePermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)))}
return ops, nil
}
err := st.db().Run(buildTxn)
return errors.Trace(err)
} | go | func (st *State) RemoveCloudAccess(cloud string, user names.UserTag) error {
buildTxn := func(int) ([]txn.Op, error) {
_, err := st.GetCloudAccess(cloud, user)
if err != nil {
return nil, err
}
ops := []txn.Op{removePermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)))}
return ops, nil
}
err := st.db().Run(buildTxn)
return errors.Trace(err)
} | [
"func",
"(",
"st",
"*",
"State",
")",
"RemoveCloudAccess",
"(",
"cloud",
"string",
",",
"user",
"names",
".",
"UserTag",
")",
"error",
"{",
"buildTxn",
":=",
"func",
"(",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"_",
",",
"err",
":=",
"st",
".",
"GetCloudAccess",
"(",
"cloud",
",",
"user",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ops",
":=",
"[",
"]",
"txn",
".",
"Op",
"{",
"removePermissionOp",
"(",
"cloudGlobalKey",
"(",
"cloud",
")",
",",
"userGlobalKey",
"(",
"userAccessID",
"(",
"user",
")",
")",
")",
"}",
"\n",
"return",
"ops",
",",
"nil",
"\n",
"}",
"\n\n",
"err",
":=",
"st",
".",
"db",
"(",
")",
".",
"Run",
"(",
"buildTxn",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // RemoveCloudAccess removes the access permission for a user on a cloud. | [
"RemoveCloudAccess",
"removes",
"the",
"access",
"permission",
"for",
"a",
"user",
"on",
"a",
"cloud",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L88-L100 |
4,283 | juju/juju | state/clouduser.go | CloudsForUser | func (st *State) CloudsForUser(user names.UserTag, all bool) ([]CloudInfo, error) {
// We only treat the user as a superuser if they pass --all
isControllerSuperuser := false
if all {
var err error
isControllerSuperuser, err = st.isUserSuperuser(user)
if err != nil {
return nil, errors.Trace(err)
}
}
clouds, closer := st.db().GetCollection(cloudsC)
defer closer()
var cloudQuery mongo.Query
if isControllerSuperuser {
// Fast path, we just get all the clouds.
cloudQuery = clouds.Find(nil)
} else {
cloudNames, err := st.cloudNamesForUser(user)
if err != nil {
return nil, errors.Trace(err)
}
cloudQuery = clouds.Find(bson.M{
"_id": bson.M{"$in": cloudNames},
})
}
cloudQuery = cloudQuery.Sort("name")
var cloudDocs []cloudDoc
if err := cloudQuery.All(&cloudDocs); err != nil {
return nil, errors.Trace(err)
}
result := make([]CloudInfo, len(cloudDocs))
for i, c := range cloudDocs {
result[i] = CloudInfo{
Cloud: c.toCloud(),
}
}
if err := st.fillInCloudUserAccess(user, result); err != nil {
return nil, errors.Trace(err)
}
return result, nil
} | go | func (st *State) CloudsForUser(user names.UserTag, all bool) ([]CloudInfo, error) {
// We only treat the user as a superuser if they pass --all
isControllerSuperuser := false
if all {
var err error
isControllerSuperuser, err = st.isUserSuperuser(user)
if err != nil {
return nil, errors.Trace(err)
}
}
clouds, closer := st.db().GetCollection(cloudsC)
defer closer()
var cloudQuery mongo.Query
if isControllerSuperuser {
// Fast path, we just get all the clouds.
cloudQuery = clouds.Find(nil)
} else {
cloudNames, err := st.cloudNamesForUser(user)
if err != nil {
return nil, errors.Trace(err)
}
cloudQuery = clouds.Find(bson.M{
"_id": bson.M{"$in": cloudNames},
})
}
cloudQuery = cloudQuery.Sort("name")
var cloudDocs []cloudDoc
if err := cloudQuery.All(&cloudDocs); err != nil {
return nil, errors.Trace(err)
}
result := make([]CloudInfo, len(cloudDocs))
for i, c := range cloudDocs {
result[i] = CloudInfo{
Cloud: c.toCloud(),
}
}
if err := st.fillInCloudUserAccess(user, result); err != nil {
return nil, errors.Trace(err)
}
return result, nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"CloudsForUser",
"(",
"user",
"names",
".",
"UserTag",
",",
"all",
"bool",
")",
"(",
"[",
"]",
"CloudInfo",
",",
"error",
")",
"{",
"// We only treat the user as a superuser if they pass --all",
"isControllerSuperuser",
":=",
"false",
"\n",
"if",
"all",
"{",
"var",
"err",
"error",
"\n",
"isControllerSuperuser",
",",
"err",
"=",
"st",
".",
"isUserSuperuser",
"(",
"user",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"clouds",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"cloudsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"cloudQuery",
"mongo",
".",
"Query",
"\n",
"if",
"isControllerSuperuser",
"{",
"// Fast path, we just get all the clouds.",
"cloudQuery",
"=",
"clouds",
".",
"Find",
"(",
"nil",
")",
"\n",
"}",
"else",
"{",
"cloudNames",
",",
"err",
":=",
"st",
".",
"cloudNamesForUser",
"(",
"user",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"cloudQuery",
"=",
"clouds",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"cloudNames",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"cloudQuery",
"=",
"cloudQuery",
".",
"Sort",
"(",
"\"",
"\"",
")",
"\n\n",
"var",
"cloudDocs",
"[",
"]",
"cloudDoc",
"\n",
"if",
"err",
":=",
"cloudQuery",
".",
"All",
"(",
"&",
"cloudDocs",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"CloudInfo",
",",
"len",
"(",
"cloudDocs",
")",
")",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
"cloudDocs",
"{",
"result",
"[",
"i",
"]",
"=",
"CloudInfo",
"{",
"Cloud",
":",
"c",
".",
"toCloud",
"(",
")",
",",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"st",
".",
"fillInCloudUserAccess",
"(",
"user",
",",
"result",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // CloudsForUser returns details including access level of clouds which can
// be seen by the specified user, or all users if the caller is a superuser. | [
"CloudsForUser",
"returns",
"details",
"including",
"access",
"level",
"of",
"clouds",
"which",
"can",
"be",
"seen",
"by",
"the",
"specified",
"user",
"or",
"all",
"users",
"if",
"the",
"caller",
"is",
"a",
"superuser",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L112-L155 |
4,284 | juju/juju | state/clouduser.go | cloudNamesForUser | func (st *State) cloudNamesForUser(user names.UserTag) ([]string, error) {
// Start by looking up cloud names that the user has access to, and then load only the records that are
// included in that set
permissions, permCloser := st.db().GetRawCollection(permissionsC)
defer permCloser()
findExpr := fmt.Sprintf("^.*#%s$", userGlobalKey(user.Id()))
query := permissions.Find(
bson.D{{"_id", bson.D{{"$regex", findExpr}}}},
).Batch(100)
var doc permissionDoc
iter := query.Iter()
var cloudNames []string
for iter.Next(&doc) {
cloudName := strings.TrimPrefix(doc.ObjectGlobalKey, "cloud#")
cloudNames = append(cloudNames, cloudName)
}
if err := iter.Close(); err != nil {
return nil, errors.Trace(err)
}
return cloudNames, nil
} | go | func (st *State) cloudNamesForUser(user names.UserTag) ([]string, error) {
// Start by looking up cloud names that the user has access to, and then load only the records that are
// included in that set
permissions, permCloser := st.db().GetRawCollection(permissionsC)
defer permCloser()
findExpr := fmt.Sprintf("^.*#%s$", userGlobalKey(user.Id()))
query := permissions.Find(
bson.D{{"_id", bson.D{{"$regex", findExpr}}}},
).Batch(100)
var doc permissionDoc
iter := query.Iter()
var cloudNames []string
for iter.Next(&doc) {
cloudName := strings.TrimPrefix(doc.ObjectGlobalKey, "cloud#")
cloudNames = append(cloudNames, cloudName)
}
if err := iter.Close(); err != nil {
return nil, errors.Trace(err)
}
return cloudNames, nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"cloudNamesForUser",
"(",
"user",
"names",
".",
"UserTag",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"// Start by looking up cloud names that the user has access to, and then load only the records that are",
"// included in that set",
"permissions",
",",
"permCloser",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"permissionsC",
")",
"\n",
"defer",
"permCloser",
"(",
")",
"\n\n",
"findExpr",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"userGlobalKey",
"(",
"user",
".",
"Id",
"(",
")",
")",
")",
"\n",
"query",
":=",
"permissions",
".",
"Find",
"(",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"findExpr",
"}",
"}",
"}",
"}",
",",
")",
".",
"Batch",
"(",
"100",
")",
"\n\n",
"var",
"doc",
"permissionDoc",
"\n",
"iter",
":=",
"query",
".",
"Iter",
"(",
")",
"\n",
"var",
"cloudNames",
"[",
"]",
"string",
"\n",
"for",
"iter",
".",
"Next",
"(",
"&",
"doc",
")",
"{",
"cloudName",
":=",
"strings",
".",
"TrimPrefix",
"(",
"doc",
".",
"ObjectGlobalKey",
",",
"\"",
"\"",
")",
"\n",
"cloudNames",
"=",
"append",
"(",
"cloudNames",
",",
"cloudName",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"iter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"cloudNames",
",",
"nil",
"\n",
"}"
] | // cloudNamesForUser returns the cloud names a user can see. | [
"cloudNamesForUser",
"returns",
"the",
"cloud",
"names",
"a",
"user",
"can",
"see",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L158-L180 |
4,285 | juju/juju | cloudconfig/machinecloudconfig.go | NewMachineInitReader | func NewMachineInitReader(series string) (InitReader, error) {
cloudInitConfigDir, err := paths.CloudInitCfgDir(series)
if err != nil {
return nil, errors.Annotate(err, "determining CloudInitCfgDir for the machine")
}
cloudInitInstanceConfigDir, err := paths.MachineCloudInitDir(series)
if err != nil {
return nil, errors.Annotate(err, "determining MachineCloudInitDir for the machine")
}
curtinInstallConfigFile, err := paths.CurtinInstallConfig(series)
if err != nil {
return nil, errors.Trace(err)
}
cfg := MachineInitReaderConfig{
Series: series,
CloudInitConfigDir: cloudInitConfigDir,
CloudInitInstanceConfigDir: cloudInitInstanceConfigDir,
CurtinInstallConfigFile: curtinInstallConfigFile,
}
return NewMachineInitReaderFromConfig(cfg), nil
} | go | func NewMachineInitReader(series string) (InitReader, error) {
cloudInitConfigDir, err := paths.CloudInitCfgDir(series)
if err != nil {
return nil, errors.Annotate(err, "determining CloudInitCfgDir for the machine")
}
cloudInitInstanceConfigDir, err := paths.MachineCloudInitDir(series)
if err != nil {
return nil, errors.Annotate(err, "determining MachineCloudInitDir for the machine")
}
curtinInstallConfigFile, err := paths.CurtinInstallConfig(series)
if err != nil {
return nil, errors.Trace(err)
}
cfg := MachineInitReaderConfig{
Series: series,
CloudInitConfigDir: cloudInitConfigDir,
CloudInitInstanceConfigDir: cloudInitInstanceConfigDir,
CurtinInstallConfigFile: curtinInstallConfigFile,
}
return NewMachineInitReaderFromConfig(cfg), nil
} | [
"func",
"NewMachineInitReader",
"(",
"series",
"string",
")",
"(",
"InitReader",
",",
"error",
")",
"{",
"cloudInitConfigDir",
",",
"err",
":=",
"paths",
".",
"CloudInitCfgDir",
"(",
"series",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"cloudInitInstanceConfigDir",
",",
"err",
":=",
"paths",
".",
"MachineCloudInitDir",
"(",
"series",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"curtinInstallConfigFile",
",",
"err",
":=",
"paths",
".",
"CurtinInstallConfig",
"(",
"series",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"cfg",
":=",
"MachineInitReaderConfig",
"{",
"Series",
":",
"series",
",",
"CloudInitConfigDir",
":",
"cloudInitConfigDir",
",",
"CloudInitInstanceConfigDir",
":",
"cloudInitInstanceConfigDir",
",",
"CurtinInstallConfigFile",
":",
"curtinInstallConfigFile",
",",
"}",
"\n",
"return",
"NewMachineInitReaderFromConfig",
"(",
"cfg",
")",
",",
"nil",
"\n",
"}"
] | // NewMachineInitReader creates and returns a new MachineInitReader for the
// input series. | [
"NewMachineInitReader",
"creates",
"and",
"returns",
"a",
"new",
"MachineInitReader",
"for",
"the",
"input",
"series",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L63-L84 |
4,286 | juju/juju | cloudconfig/machinecloudconfig.go | GetInitConfig | func (r *MachineInitReader) GetInitConfig() (map[string]interface{}, error) {
series := r.config.Series
containerOS, err := utilsseries.GetOSFromSeries(series)
if err != nil {
return nil, errors.Trace(err)
}
switch containerOS {
case utilsos.Ubuntu, utilsos.CentOS, utilsos.OpenSUSE:
if series != utilsseries.MustHostSeries() {
logger.Debugf("not attempting to get init config for %s, series of machine and container differ", series)
return nil, nil
}
default:
logger.Debugf("not attempting to get init config for %s container", series)
return nil, nil
}
machineCloudInitData, err := r.getMachineCloudCfgDirData()
if err != nil {
return nil, errors.Trace(err)
}
file := filepath.Join(r.config.CloudInitInstanceConfigDir, "vendor-data.txt")
vendorData, err := r.unmarshallConfigFile(file)
if err != nil {
return nil, errors.Trace(err)
}
for k, v := range vendorData {
machineCloudInitData[k] = v
}
_, curtinData, err := fileAsConfigMap(r.config.CurtinInstallConfigFile)
if err != nil {
return nil, errors.Trace(err)
}
for k, v := range curtinData {
machineCloudInitData[k] = v
}
return machineCloudInitData, nil
} | go | func (r *MachineInitReader) GetInitConfig() (map[string]interface{}, error) {
series := r.config.Series
containerOS, err := utilsseries.GetOSFromSeries(series)
if err != nil {
return nil, errors.Trace(err)
}
switch containerOS {
case utilsos.Ubuntu, utilsos.CentOS, utilsos.OpenSUSE:
if series != utilsseries.MustHostSeries() {
logger.Debugf("not attempting to get init config for %s, series of machine and container differ", series)
return nil, nil
}
default:
logger.Debugf("not attempting to get init config for %s container", series)
return nil, nil
}
machineCloudInitData, err := r.getMachineCloudCfgDirData()
if err != nil {
return nil, errors.Trace(err)
}
file := filepath.Join(r.config.CloudInitInstanceConfigDir, "vendor-data.txt")
vendorData, err := r.unmarshallConfigFile(file)
if err != nil {
return nil, errors.Trace(err)
}
for k, v := range vendorData {
machineCloudInitData[k] = v
}
_, curtinData, err := fileAsConfigMap(r.config.CurtinInstallConfigFile)
if err != nil {
return nil, errors.Trace(err)
}
for k, v := range curtinData {
machineCloudInitData[k] = v
}
return machineCloudInitData, nil
} | [
"func",
"(",
"r",
"*",
"MachineInitReader",
")",
"GetInitConfig",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"series",
":=",
"r",
".",
"config",
".",
"Series",
"\n\n",
"containerOS",
",",
"err",
":=",
"utilsseries",
".",
"GetOSFromSeries",
"(",
"series",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"switch",
"containerOS",
"{",
"case",
"utilsos",
".",
"Ubuntu",
",",
"utilsos",
".",
"CentOS",
",",
"utilsos",
".",
"OpenSUSE",
":",
"if",
"series",
"!=",
"utilsseries",
".",
"MustHostSeries",
"(",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"series",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"default",
":",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"series",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"machineCloudInitData",
",",
"err",
":=",
"r",
".",
"getMachineCloudCfgDirData",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"file",
":=",
"filepath",
".",
"Join",
"(",
"r",
".",
"config",
".",
"CloudInitInstanceConfigDir",
",",
"\"",
"\"",
")",
"\n",
"vendorData",
",",
"err",
":=",
"r",
".",
"unmarshallConfigFile",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"vendorData",
"{",
"machineCloudInitData",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"_",
",",
"curtinData",
",",
"err",
":=",
"fileAsConfigMap",
"(",
"r",
".",
"config",
".",
"CurtinInstallConfigFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"curtinData",
"{",
"machineCloudInitData",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"return",
"machineCloudInitData",
",",
"nil",
"\n",
"}"
] | // GetInitConfig returns a map of configuration data used to provision the
// machine. It is sourced from both Cloud-Init and Curtin data. | [
"GetInitConfig",
"returns",
"a",
"map",
"of",
"configuration",
"data",
"used",
"to",
"provision",
"the",
"machine",
".",
"It",
"is",
"sourced",
"from",
"both",
"Cloud",
"-",
"Init",
"and",
"Curtin",
"data",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L94-L135 |
4,287 | juju/juju | cloudconfig/machinecloudconfig.go | getMachineCloudCfgDirData | func (r *MachineInitReader) getMachineCloudCfgDirData() (map[string]interface{}, error) {
dir := r.config.CloudInitConfigDir
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, errors.Annotate(err, "determining files in CloudInitCfgDir for the machine")
}
sortedFiles := sortableFileInfos(files)
sort.Sort(sortedFiles)
cloudInit := make(map[string]interface{})
for _, file := range files {
name := file.Name()
if !strings.HasSuffix(name, ".cfg") {
continue
}
_, cloudCfgData, err := fileAsConfigMap(filepath.Join(dir, name))
if err != nil {
return nil, errors.Trace(err)
}
for k, v := range cloudCfgData {
cloudInit[k] = v
}
}
return cloudInit, nil
} | go | func (r *MachineInitReader) getMachineCloudCfgDirData() (map[string]interface{}, error) {
dir := r.config.CloudInitConfigDir
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, errors.Annotate(err, "determining files in CloudInitCfgDir for the machine")
}
sortedFiles := sortableFileInfos(files)
sort.Sort(sortedFiles)
cloudInit := make(map[string]interface{})
for _, file := range files {
name := file.Name()
if !strings.HasSuffix(name, ".cfg") {
continue
}
_, cloudCfgData, err := fileAsConfigMap(filepath.Join(dir, name))
if err != nil {
return nil, errors.Trace(err)
}
for k, v := range cloudCfgData {
cloudInit[k] = v
}
}
return cloudInit, nil
} | [
"func",
"(",
"r",
"*",
"MachineInitReader",
")",
"getMachineCloudCfgDirData",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"dir",
":=",
"r",
".",
"config",
".",
"CloudInitConfigDir",
"\n\n",
"files",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"sortedFiles",
":=",
"sortableFileInfos",
"(",
"files",
")",
"\n",
"sort",
".",
"Sort",
"(",
"sortedFiles",
")",
"\n\n",
"cloudInit",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"file",
":=",
"range",
"files",
"{",
"name",
":=",
"file",
".",
"Name",
"(",
")",
"\n",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"name",
",",
"\"",
"\"",
")",
"{",
"continue",
"\n",
"}",
"\n",
"_",
",",
"cloudCfgData",
",",
"err",
":=",
"fileAsConfigMap",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"name",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"cloudCfgData",
"{",
"cloudInit",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"cloudInit",
",",
"nil",
"\n",
"}"
] | // getMachineCloudCfgDirData returns a map of the combined machine's Cloud-Init
// cloud.cfg.d config files. Files are read in lexical order. | [
"getMachineCloudCfgDirData",
"returns",
"a",
"map",
"of",
"the",
"combined",
"machine",
"s",
"Cloud",
"-",
"Init",
"cloud",
".",
"cfg",
".",
"d",
"config",
"files",
".",
"Files",
"are",
"read",
"in",
"lexical",
"order",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L151-L176 |
4,288 | juju/juju | cloudconfig/machinecloudconfig.go | unmarshallConfigFile | func (r *MachineInitReader) unmarshallConfigFile(file string) (map[string]interface{}, error) {
raw, config, err := fileAsConfigMap(file)
if err == nil {
return config, nil
}
if !errors.IsNotValid(err) {
return nil, errors.Trace(err)
}
// The data maybe be gzipped, base64 encoded, both, or neither.
// If both, it has been gzipped, then base64 encoded.
logger.Tracef("unmarshall failed (%s), file may be compressed", err.Error())
zippedData, err := utils.Gunzip(raw)
if err == nil {
cfg, err := bytesAsConfigMap(zippedData)
return cfg, errors.Trace(err)
}
logger.Tracef("Gunzip of %q failed (%s), maybe it is encoded", file, err)
decodedData, err := base64.StdEncoding.DecodeString(string(raw))
if err == nil {
if buf, err := bytesAsConfigMap(decodedData); err == nil {
return buf, nil
}
}
logger.Tracef("Decoding of %q failed (%s), maybe it is encoded and gzipped", file, err)
decodedZippedBuf, err := utils.Gunzip(decodedData)
if err != nil {
// During testing, it was found that the trusty vendor-data.txt.i file
// can contain only the text "NONE", which doesn't unmarshall or decompress
// we don't want to fail in that case.
if r.config.Series == "trusty" {
logger.Debugf("failed to unmarshall or decompress %q: %s", file, err)
return nil, nil
}
return nil, errors.Annotatef(err, "cannot unmarshall or decompress %q", file)
}
cfg, err := bytesAsConfigMap(decodedZippedBuf)
return cfg, errors.Trace(err)
} | go | func (r *MachineInitReader) unmarshallConfigFile(file string) (map[string]interface{}, error) {
raw, config, err := fileAsConfigMap(file)
if err == nil {
return config, nil
}
if !errors.IsNotValid(err) {
return nil, errors.Trace(err)
}
// The data maybe be gzipped, base64 encoded, both, or neither.
// If both, it has been gzipped, then base64 encoded.
logger.Tracef("unmarshall failed (%s), file may be compressed", err.Error())
zippedData, err := utils.Gunzip(raw)
if err == nil {
cfg, err := bytesAsConfigMap(zippedData)
return cfg, errors.Trace(err)
}
logger.Tracef("Gunzip of %q failed (%s), maybe it is encoded", file, err)
decodedData, err := base64.StdEncoding.DecodeString(string(raw))
if err == nil {
if buf, err := bytesAsConfigMap(decodedData); err == nil {
return buf, nil
}
}
logger.Tracef("Decoding of %q failed (%s), maybe it is encoded and gzipped", file, err)
decodedZippedBuf, err := utils.Gunzip(decodedData)
if err != nil {
// During testing, it was found that the trusty vendor-data.txt.i file
// can contain only the text "NONE", which doesn't unmarshall or decompress
// we don't want to fail in that case.
if r.config.Series == "trusty" {
logger.Debugf("failed to unmarshall or decompress %q: %s", file, err)
return nil, nil
}
return nil, errors.Annotatef(err, "cannot unmarshall or decompress %q", file)
}
cfg, err := bytesAsConfigMap(decodedZippedBuf)
return cfg, errors.Trace(err)
} | [
"func",
"(",
"r",
"*",
"MachineInitReader",
")",
"unmarshallConfigFile",
"(",
"file",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"raw",
",",
"config",
",",
"err",
":=",
"fileAsConfigMap",
"(",
"file",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"config",
",",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"errors",
".",
"IsNotValid",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// The data maybe be gzipped, base64 encoded, both, or neither.",
"// If both, it has been gzipped, then base64 encoded.",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n\n",
"zippedData",
",",
"err",
":=",
"utils",
".",
"Gunzip",
"(",
"raw",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"cfg",
",",
"err",
":=",
"bytesAsConfigMap",
"(",
"zippedData",
")",
"\n",
"return",
"cfg",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"file",
",",
"err",
")",
"\n\n",
"decodedData",
",",
"err",
":=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"string",
"(",
"raw",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"if",
"buf",
",",
"err",
":=",
"bytesAsConfigMap",
"(",
"decodedData",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"buf",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"file",
",",
"err",
")",
"\n\n",
"decodedZippedBuf",
",",
"err",
":=",
"utils",
".",
"Gunzip",
"(",
"decodedData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// During testing, it was found that the trusty vendor-data.txt.i file",
"// can contain only the text \"NONE\", which doesn't unmarshall or decompress",
"// we don't want to fail in that case.",
"if",
"r",
".",
"config",
".",
"Series",
"==",
"\"",
"\"",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"file",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"file",
")",
"\n",
"}",
"\n\n",
"cfg",
",",
"err",
":=",
"bytesAsConfigMap",
"(",
"decodedZippedBuf",
")",
"\n",
"return",
"cfg",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // unmarshallConfigFile reads the file at the input path,
// decompressing it if required, and converts the contents to a map of
// configuration key-values. | [
"unmarshallConfigFile",
"reads",
"the",
"file",
"at",
"the",
"input",
"path",
"decompressing",
"it",
"if",
"required",
"and",
"converts",
"the",
"contents",
"to",
"a",
"map",
"of",
"configuration",
"key",
"-",
"values",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L181-L223 |
4,289 | juju/juju | cloudconfig/machinecloudconfig.go | fileAsConfigMap | func fileAsConfigMap(file string) ([]byte, map[string]interface{}, error) {
raw, err := ioutil.ReadFile(file)
if err != nil {
return nil, nil, errors.Annotatef(err, "reading config from %q", file)
}
if len(raw) == 0 {
return nil, nil, nil
}
cfg, err := bytesAsConfigMap(raw)
if err != nil {
return raw, cfg, errors.NotValidf("converting %q contents to map: %s", file, err.Error())
}
return raw, cfg, nil
} | go | func fileAsConfigMap(file string) ([]byte, map[string]interface{}, error) {
raw, err := ioutil.ReadFile(file)
if err != nil {
return nil, nil, errors.Annotatef(err, "reading config from %q", file)
}
if len(raw) == 0 {
return nil, nil, nil
}
cfg, err := bytesAsConfigMap(raw)
if err != nil {
return raw, cfg, errors.NotValidf("converting %q contents to map: %s", file, err.Error())
}
return raw, cfg, nil
} | [
"func",
"fileAsConfigMap",
"(",
"file",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"raw",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"file",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"raw",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"cfg",
",",
"err",
":=",
"bytesAsConfigMap",
"(",
"raw",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"raw",
",",
"cfg",
",",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
",",
"file",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"raw",
",",
"cfg",
",",
"nil",
"\n",
"}"
] | // fileAsConfigMap reads the file at the input path and returns its contents as
// raw bytes, and if possible a map of config key-values. | [
"fileAsConfigMap",
"reads",
"the",
"file",
"at",
"the",
"input",
"path",
"and",
"returns",
"its",
"contents",
"as",
"raw",
"bytes",
"and",
"if",
"possible",
"a",
"map",
"of",
"config",
"key",
"-",
"values",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L227-L241 |
4,290 | juju/juju | cloudconfig/machinecloudconfig.go | extractPropertiesFromConfig | func extractPropertiesFromConfig(props []string, cfg map[string]interface{}, log loggo.Logger) map[string]interface{} {
foundDataMap := make(map[string]interface{})
for _, k := range props {
key := strings.TrimSpace(k)
switch key {
case "apt-security", "apt-primary", "apt-sources", "apt-sources_list":
if val, ok := cfg["apt"]; ok {
for k, v := range nestedAptConfig(key, val, log) {
// security, sources, and primary all nest under apt, ensure
// we don't overwrite prior translated data.
if apt, ok := foundDataMap["apt"].(map[string]interface{}); ok {
apt[k] = v
} else {
foundDataMap["apt"] = map[string]interface{}{
k: v,
}
}
}
} else {
log.Debugf("%s not found in machine init data", key)
}
case "ca-certs":
// No translation needed, ca-certs the same in both versions of Cloud-Init.
if val, ok := cfg[key]; ok {
foundDataMap[key] = val
} else {
log.Debugf("%s not found in machine init data", key)
}
}
}
return foundDataMap
} | go | func extractPropertiesFromConfig(props []string, cfg map[string]interface{}, log loggo.Logger) map[string]interface{} {
foundDataMap := make(map[string]interface{})
for _, k := range props {
key := strings.TrimSpace(k)
switch key {
case "apt-security", "apt-primary", "apt-sources", "apt-sources_list":
if val, ok := cfg["apt"]; ok {
for k, v := range nestedAptConfig(key, val, log) {
// security, sources, and primary all nest under apt, ensure
// we don't overwrite prior translated data.
if apt, ok := foundDataMap["apt"].(map[string]interface{}); ok {
apt[k] = v
} else {
foundDataMap["apt"] = map[string]interface{}{
k: v,
}
}
}
} else {
log.Debugf("%s not found in machine init data", key)
}
case "ca-certs":
// No translation needed, ca-certs the same in both versions of Cloud-Init.
if val, ok := cfg[key]; ok {
foundDataMap[key] = val
} else {
log.Debugf("%s not found in machine init data", key)
}
}
}
return foundDataMap
} | [
"func",
"extractPropertiesFromConfig",
"(",
"props",
"[",
"]",
"string",
",",
"cfg",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"log",
"loggo",
".",
"Logger",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"foundDataMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"props",
"{",
"key",
":=",
"strings",
".",
"TrimSpace",
"(",
"k",
")",
"\n",
"switch",
"key",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"if",
"val",
",",
"ok",
":=",
"cfg",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"nestedAptConfig",
"(",
"key",
",",
"val",
",",
"log",
")",
"{",
"// security, sources, and primary all nest under apt, ensure",
"// we don't overwrite prior translated data.",
"if",
"apt",
",",
"ok",
":=",
"foundDataMap",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"apt",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"else",
"{",
"foundDataMap",
"[",
"\"",
"\"",
"]",
"=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"k",
":",
"v",
",",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"// No translation needed, ca-certs the same in both versions of Cloud-Init.",
"if",
"val",
",",
"ok",
":=",
"cfg",
"[",
"key",
"]",
";",
"ok",
"{",
"foundDataMap",
"[",
"key",
"]",
"=",
"val",
"\n",
"}",
"else",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"foundDataMap",
"\n",
"}"
] | // extractPropertiesFromConfig filters the input config based on the
// input properties and returns a map of cloud-init data, compatible with
// version 0.7.8 and above. | [
"extractPropertiesFromConfig",
"filters",
"the",
"input",
"config",
"based",
"on",
"the",
"input",
"properties",
"and",
"returns",
"a",
"map",
"of",
"cloud",
"-",
"init",
"data",
"compatible",
"with",
"version",
"0",
".",
"7",
".",
"8",
"and",
"above",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L246-L277 |
4,291 | juju/juju | cloudconfig/machinecloudconfig.go | extractPropertiesFromConfigLegacy | func extractPropertiesFromConfigLegacy(
props []string, cfg map[string]interface{}, log loggo.Logger,
) map[string]interface{} {
foundDataMap := make(map[string]interface{})
aptProcessed := false
for _, k := range props {
key := strings.TrimSpace(k)
switch key {
case "apt-primary", "apt-sources":
if aptProcessed {
continue
}
for _, aptKey := range []string{"apt_mirror", "apt_mirror_search", "apt_mirror_search_dns", "apt_sources"} {
if val, ok := cfg[aptKey]; ok {
foundDataMap[aptKey] = val
} else {
log.Debugf("%s not found in machine init data", aptKey)
}
}
aptProcessed = true
case "apt-sources_list":
// Testing series trusty on MAAS 2.5+ shows that this could be
// treated in the same way as the non-legacy property
// extraction, but we would then be mixing techniques.
// Legacy handling is left unchanged here under the assumption
// that provisioning trusty machines on much newer MAAS
// versions is highly unlikely.
log.Debugf("%q ignored for this machine series", key)
case "apt-security":
// Translation for apt-security unknown at this time.
log.Debugf("%q ignored for this machine series", key)
case "ca-certs":
// No translation needed, ca-certs the same in both versions of Cloud-Init.
if val, ok := cfg[key]; ok {
foundDataMap[key] = val
} else {
log.Debugf("%s not found in machine init data", key)
}
}
}
return foundDataMap
} | go | func extractPropertiesFromConfigLegacy(
props []string, cfg map[string]interface{}, log loggo.Logger,
) map[string]interface{} {
foundDataMap := make(map[string]interface{})
aptProcessed := false
for _, k := range props {
key := strings.TrimSpace(k)
switch key {
case "apt-primary", "apt-sources":
if aptProcessed {
continue
}
for _, aptKey := range []string{"apt_mirror", "apt_mirror_search", "apt_mirror_search_dns", "apt_sources"} {
if val, ok := cfg[aptKey]; ok {
foundDataMap[aptKey] = val
} else {
log.Debugf("%s not found in machine init data", aptKey)
}
}
aptProcessed = true
case "apt-sources_list":
// Testing series trusty on MAAS 2.5+ shows that this could be
// treated in the same way as the non-legacy property
// extraction, but we would then be mixing techniques.
// Legacy handling is left unchanged here under the assumption
// that provisioning trusty machines on much newer MAAS
// versions is highly unlikely.
log.Debugf("%q ignored for this machine series", key)
case "apt-security":
// Translation for apt-security unknown at this time.
log.Debugf("%q ignored for this machine series", key)
case "ca-certs":
// No translation needed, ca-certs the same in both versions of Cloud-Init.
if val, ok := cfg[key]; ok {
foundDataMap[key] = val
} else {
log.Debugf("%s not found in machine init data", key)
}
}
}
return foundDataMap
} | [
"func",
"extractPropertiesFromConfigLegacy",
"(",
"props",
"[",
"]",
"string",
",",
"cfg",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"log",
"loggo",
".",
"Logger",
",",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"foundDataMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"aptProcessed",
":=",
"false",
"\n\n",
"for",
"_",
",",
"k",
":=",
"range",
"props",
"{",
"key",
":=",
"strings",
".",
"TrimSpace",
"(",
"k",
")",
"\n",
"switch",
"key",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"if",
"aptProcessed",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"aptKey",
":=",
"range",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"{",
"if",
"val",
",",
"ok",
":=",
"cfg",
"[",
"aptKey",
"]",
";",
"ok",
"{",
"foundDataMap",
"[",
"aptKey",
"]",
"=",
"val",
"\n",
"}",
"else",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"aptKey",
")",
"\n",
"}",
"\n",
"}",
"\n",
"aptProcessed",
"=",
"true",
"\n",
"case",
"\"",
"\"",
":",
"// Testing series trusty on MAAS 2.5+ shows that this could be",
"// treated in the same way as the non-legacy property",
"// extraction, but we would then be mixing techniques.",
"// Legacy handling is left unchanged here under the assumption",
"// that provisioning trusty machines on much newer MAAS",
"// versions is highly unlikely.",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"case",
"\"",
"\"",
":",
"// Translation for apt-security unknown at this time.",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"case",
"\"",
"\"",
":",
"// No translation needed, ca-certs the same in both versions of Cloud-Init.",
"if",
"val",
",",
"ok",
":=",
"cfg",
"[",
"key",
"]",
";",
"ok",
"{",
"foundDataMap",
"[",
"key",
"]",
"=",
"val",
"\n",
"}",
"else",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"foundDataMap",
"\n",
"}"
] | // extractPropertiesFromConfigLegacy filters the input config based on the
// input properties and returns a map of cloud-init data, compatible with
// version 0.7.7 and below. | [
"extractPropertiesFromConfigLegacy",
"filters",
"the",
"input",
"config",
"based",
"on",
"the",
"input",
"properties",
"and",
"returns",
"a",
"map",
"of",
"cloud",
"-",
"init",
"data",
"compatible",
"with",
"version",
"0",
".",
"7",
".",
"7",
"and",
"below",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L298-L340 |
4,292 | juju/juju | cmd/juju/application/store.go | authorizeCharmStoreEntity | func authorizeCharmStoreEntity(csClient charmstoreForDeploy, curl *charm.URL) (*macaroon.Macaroon, error) {
endpoint := "/delegatable-macaroon?id=" + url.QueryEscape(curl.String())
var m *macaroon.Macaroon
if err := csClient.Get(endpoint, &m); err != nil {
return nil, errors.Trace(err)
}
return m, nil
} | go | func authorizeCharmStoreEntity(csClient charmstoreForDeploy, curl *charm.URL) (*macaroon.Macaroon, error) {
endpoint := "/delegatable-macaroon?id=" + url.QueryEscape(curl.String())
var m *macaroon.Macaroon
if err := csClient.Get(endpoint, &m); err != nil {
return nil, errors.Trace(err)
}
return m, nil
} | [
"func",
"authorizeCharmStoreEntity",
"(",
"csClient",
"charmstoreForDeploy",
",",
"curl",
"*",
"charm",
".",
"URL",
")",
"(",
"*",
"macaroon",
".",
"Macaroon",
",",
"error",
")",
"{",
"endpoint",
":=",
"\"",
"\"",
"+",
"url",
".",
"QueryEscape",
"(",
"curl",
".",
"String",
"(",
")",
")",
"\n",
"var",
"m",
"*",
"macaroon",
".",
"Macaroon",
"\n",
"if",
"err",
":=",
"csClient",
".",
"Get",
"(",
"endpoint",
",",
"&",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"m",
",",
"nil",
"\n",
"}"
] | // authorizeCharmStoreEntity acquires and return the charm store delegatable macaroon to be
// used to add the charm corresponding to the given URL.
// The macaroon is properly attenuated so that it can only be used to deploy
// the given charm URL. | [
"authorizeCharmStoreEntity",
"acquires",
"and",
"return",
"the",
"charm",
"store",
"delegatable",
"macaroon",
"to",
"be",
"used",
"to",
"add",
"the",
"charm",
"corresponding",
"to",
"the",
"given",
"URL",
".",
"The",
"macaroon",
"is",
"properly",
"attenuated",
"so",
"that",
"it",
"can",
"only",
"be",
"used",
"to",
"deploy",
"the",
"given",
"charm",
"URL",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/store.go#L91-L98 |
4,293 | juju/juju | api/caasfirewaller/client.go | WatchApplication | func (c *Client) WatchApplication(appName string) (watcher.NotifyWatcher, error) {
appTag, err := applicationTag(appName)
if err != nil {
return nil, errors.Trace(err)
}
return common.Watch(c.facade, "Watch", appTag)
} | go | func (c *Client) WatchApplication(appName string) (watcher.NotifyWatcher, error) {
appTag, err := applicationTag(appName)
if err != nil {
return nil, errors.Trace(err)
}
return common.Watch(c.facade, "Watch", appTag)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"WatchApplication",
"(",
"appName",
"string",
")",
"(",
"watcher",
".",
"NotifyWatcher",
",",
"error",
")",
"{",
"appTag",
",",
"err",
":=",
"applicationTag",
"(",
"appName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"common",
".",
"Watch",
"(",
"c",
".",
"facade",
",",
"\"",
"\"",
",",
"appTag",
")",
"\n",
"}"
] | // WatchApplication returns a NotifyWatcher that notifies of
// changes to the application in the current model. | [
"WatchApplication",
"returns",
"a",
"NotifyWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"application",
"in",
"the",
"current",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasfirewaller/client.go#L65-L71 |
4,294 | juju/juju | api/caasfirewaller/client.go | Life | func (c *Client) Life(appName string) (life.Value, error) {
appTag, err := applicationTag(appName)
if err != nil {
return "", errors.Trace(err)
}
args := entities(appTag)
var results params.LifeResults
if err := c.facade.FacadeCall("Life", args, &results); err != nil {
return "", err
}
if n := len(results.Results); n != 1 {
return "", errors.Errorf("expected 1 result, got %d", n)
}
if err := results.Results[0].Error; err != nil {
return "", maybeNotFound(err)
}
return life.Value(results.Results[0].Life), nil
} | go | func (c *Client) Life(appName string) (life.Value, error) {
appTag, err := applicationTag(appName)
if err != nil {
return "", errors.Trace(err)
}
args := entities(appTag)
var results params.LifeResults
if err := c.facade.FacadeCall("Life", args, &results); err != nil {
return "", err
}
if n := len(results.Results); n != 1 {
return "", errors.Errorf("expected 1 result, got %d", n)
}
if err := results.Results[0].Error; err != nil {
return "", maybeNotFound(err)
}
return life.Value(results.Results[0].Life), nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Life",
"(",
"appName",
"string",
")",
"(",
"life",
".",
"Value",
",",
"error",
")",
"{",
"appTag",
",",
"err",
":=",
"applicationTag",
"(",
"appName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"args",
":=",
"entities",
"(",
"appTag",
")",
"\n\n",
"var",
"results",
"params",
".",
"LifeResults",
"\n",
"if",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"results",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"n",
":=",
"len",
"(",
"results",
".",
"Results",
")",
";",
"n",
"!=",
"1",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"n",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"Error",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"maybeNotFound",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"life",
".",
"Value",
"(",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"Life",
")",
",",
"nil",
"\n",
"}"
] | // Life returns the lifecycle state for the specified CAAS application
// in the current model. | [
"Life",
"returns",
"the",
"lifecycle",
"state",
"for",
"the",
"specified",
"CAAS",
"application",
"in",
"the",
"current",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasfirewaller/client.go#L75-L93 |
4,295 | juju/juju | api/caasfirewaller/client.go | IsExposed | func (c *Client) IsExposed(appName string) (bool, error) {
appTag, err := applicationTag(appName)
if err != nil {
return false, errors.Trace(err)
}
args := entities(appTag)
var results params.BoolResults
if err := c.facade.FacadeCall("IsExposed", args, &results); err != nil {
return false, err
}
if n := len(results.Results); n != 1 {
return false, errors.Errorf("expected 1 result, got %d", n)
}
if err := results.Results[0].Error; err != nil {
return false, maybeNotFound(err)
}
return results.Results[0].Result, nil
} | go | func (c *Client) IsExposed(appName string) (bool, error) {
appTag, err := applicationTag(appName)
if err != nil {
return false, errors.Trace(err)
}
args := entities(appTag)
var results params.BoolResults
if err := c.facade.FacadeCall("IsExposed", args, &results); err != nil {
return false, err
}
if n := len(results.Results); n != 1 {
return false, errors.Errorf("expected 1 result, got %d", n)
}
if err := results.Results[0].Error; err != nil {
return false, maybeNotFound(err)
}
return results.Results[0].Result, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"IsExposed",
"(",
"appName",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"appTag",
",",
"err",
":=",
"applicationTag",
"(",
"appName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"args",
":=",
"entities",
"(",
"appTag",
")",
"\n\n",
"var",
"results",
"params",
".",
"BoolResults",
"\n",
"if",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"results",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"n",
":=",
"len",
"(",
"results",
".",
"Results",
")",
";",
"n",
"!=",
"1",
"{",
"return",
"false",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"n",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"Error",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"maybeNotFound",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"results",
".",
"Results",
"[",
"0",
"]",
".",
"Result",
",",
"nil",
"\n",
"}"
] | // IsExposed returns whether the specified CAAS application
// in the current model is exposed. | [
"IsExposed",
"returns",
"whether",
"the",
"specified",
"CAAS",
"application",
"in",
"the",
"current",
"model",
"is",
"exposed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasfirewaller/client.go#L113-L131 |
4,296 | juju/juju | container/kvm/wrappedcmds.go | Arch | func (p CreateMachineParams) Arch() string {
if p.arch != "" {
return p.arch
}
return arch.HostArch()
} | go | func (p CreateMachineParams) Arch() string {
if p.arch != "" {
return p.arch
}
return arch.HostArch()
} | [
"func",
"(",
"p",
"CreateMachineParams",
")",
"Arch",
"(",
")",
"string",
"{",
"if",
"p",
".",
"arch",
"!=",
"\"",
"\"",
"{",
"return",
"p",
".",
"arch",
"\n",
"}",
"\n",
"return",
"arch",
".",
"HostArch",
"(",
")",
"\n",
"}"
] | // Arch returns the architecture to be used. | [
"Arch",
"returns",
"the",
"architecture",
"to",
"be",
"used",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L82-L87 |
4,297 | juju/juju | container/kvm/wrappedcmds.go | ValidateDomainParams | func (p CreateMachineParams) ValidateDomainParams() error {
if p.Hostname == "" {
return errors.Errorf("missing required hostname")
}
if len(p.disks) < 2 {
// We need at least the drive and the data source disk.
return errors.Errorf("got %d disks, need at least 2", len(p.disks))
}
var ds, fs bool
for _, d := range p.disks {
if d.Driver() == "qcow2" {
fs = true
}
if d.Driver() == "raw" {
ds = true
}
}
if !ds {
return errors.Trace(errors.Errorf("missing data source disk"))
}
if !fs {
return errors.Trace(errors.Errorf("missing system disk"))
}
return nil
} | go | func (p CreateMachineParams) ValidateDomainParams() error {
if p.Hostname == "" {
return errors.Errorf("missing required hostname")
}
if len(p.disks) < 2 {
// We need at least the drive and the data source disk.
return errors.Errorf("got %d disks, need at least 2", len(p.disks))
}
var ds, fs bool
for _, d := range p.disks {
if d.Driver() == "qcow2" {
fs = true
}
if d.Driver() == "raw" {
ds = true
}
}
if !ds {
return errors.Trace(errors.Errorf("missing data source disk"))
}
if !fs {
return errors.Trace(errors.Errorf("missing system disk"))
}
return nil
} | [
"func",
"(",
"p",
"CreateMachineParams",
")",
"ValidateDomainParams",
"(",
")",
"error",
"{",
"if",
"p",
".",
"Hostname",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"p",
".",
"disks",
")",
"<",
"2",
"{",
"// We need at least the drive and the data source disk.",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"p",
".",
"disks",
")",
")",
"\n",
"}",
"\n",
"var",
"ds",
",",
"fs",
"bool",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"p",
".",
"disks",
"{",
"if",
"d",
".",
"Driver",
"(",
")",
"==",
"\"",
"\"",
"{",
"fs",
"=",
"true",
"\n",
"}",
"\n",
"if",
"d",
".",
"Driver",
"(",
")",
"==",
"\"",
"\"",
"{",
"ds",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"ds",
"{",
"return",
"errors",
".",
"Trace",
"(",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"if",
"!",
"fs",
"{",
"return",
"errors",
".",
"Trace",
"(",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ValidateDomainParams implements libvirt.domainParams. | [
"ValidateDomainParams",
"implements",
"libvirt",
".",
"domainParams",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L127-L151 |
4,298 | juju/juju | container/kvm/wrappedcmds.go | CreateMachine | func CreateMachine(params CreateMachineParams) error {
if params.Hostname == "" {
return fmt.Errorf("hostname is required")
}
setDefaults(¶ms)
templateDir := filepath.Dir(params.UserDataFile)
err := writeMetadata(templateDir)
if err != nil {
return errors.Annotate(err, "failed to write instance metadata")
}
dsPath, err := writeDataSourceVolume(params)
if err != nil {
return errors.Annotatef(err, "failed to write data source volume for %q", params.Host())
}
imgPath, err := writeRootDisk(params)
if err != nil {
return errors.Annotatef(err, "failed to write root volume for %q", params.Host())
}
params.disks = append(params.disks, diskInfo{source: imgPath, driver: "qcow2"})
params.disks = append(params.disks, diskInfo{source: dsPath, driver: "raw"})
domainPath, err := writeDomainXML(templateDir, params)
if err != nil {
return errors.Annotatef(err, "failed to write domain xml for %q", params.Host())
}
out, err := params.runCmdAsRoot("", virsh, "define", domainPath)
if err != nil {
return errors.Annotatef(err, "failed to defined the domain for %q from %s", params.Host(), domainPath)
}
logger.Debugf("created domain: %s", out)
out, err = params.runCmdAsRoot("", virsh, "start", params.Host())
if err != nil {
return errors.Annotatef(err, "failed to start domain %q", params.Host())
}
logger.Debugf("started domain: %s", out)
return err
} | go | func CreateMachine(params CreateMachineParams) error {
if params.Hostname == "" {
return fmt.Errorf("hostname is required")
}
setDefaults(¶ms)
templateDir := filepath.Dir(params.UserDataFile)
err := writeMetadata(templateDir)
if err != nil {
return errors.Annotate(err, "failed to write instance metadata")
}
dsPath, err := writeDataSourceVolume(params)
if err != nil {
return errors.Annotatef(err, "failed to write data source volume for %q", params.Host())
}
imgPath, err := writeRootDisk(params)
if err != nil {
return errors.Annotatef(err, "failed to write root volume for %q", params.Host())
}
params.disks = append(params.disks, diskInfo{source: imgPath, driver: "qcow2"})
params.disks = append(params.disks, diskInfo{source: dsPath, driver: "raw"})
domainPath, err := writeDomainXML(templateDir, params)
if err != nil {
return errors.Annotatef(err, "failed to write domain xml for %q", params.Host())
}
out, err := params.runCmdAsRoot("", virsh, "define", domainPath)
if err != nil {
return errors.Annotatef(err, "failed to defined the domain for %q from %s", params.Host(), domainPath)
}
logger.Debugf("created domain: %s", out)
out, err = params.runCmdAsRoot("", virsh, "start", params.Host())
if err != nil {
return errors.Annotatef(err, "failed to start domain %q", params.Host())
}
logger.Debugf("started domain: %s", out)
return err
} | [
"func",
"CreateMachine",
"(",
"params",
"CreateMachineParams",
")",
"error",
"{",
"if",
"params",
".",
"Hostname",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"setDefaults",
"(",
"&",
"params",
")",
"\n\n",
"templateDir",
":=",
"filepath",
".",
"Dir",
"(",
"params",
".",
"UserDataFile",
")",
"\n\n",
"err",
":=",
"writeMetadata",
"(",
"templateDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"dsPath",
",",
"err",
":=",
"writeDataSourceVolume",
"(",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"params",
".",
"Host",
"(",
")",
")",
"\n",
"}",
"\n\n",
"imgPath",
",",
"err",
":=",
"writeRootDisk",
"(",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"params",
".",
"Host",
"(",
")",
")",
"\n",
"}",
"\n\n",
"params",
".",
"disks",
"=",
"append",
"(",
"params",
".",
"disks",
",",
"diskInfo",
"{",
"source",
":",
"imgPath",
",",
"driver",
":",
"\"",
"\"",
"}",
")",
"\n",
"params",
".",
"disks",
"=",
"append",
"(",
"params",
".",
"disks",
",",
"diskInfo",
"{",
"source",
":",
"dsPath",
",",
"driver",
":",
"\"",
"\"",
"}",
")",
"\n\n",
"domainPath",
",",
"err",
":=",
"writeDomainXML",
"(",
"templateDir",
",",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"params",
".",
"Host",
"(",
")",
")",
"\n",
"}",
"\n\n",
"out",
",",
"err",
":=",
"params",
".",
"runCmdAsRoot",
"(",
"\"",
"\"",
",",
"virsh",
",",
"\"",
"\"",
",",
"domainPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"params",
".",
"Host",
"(",
")",
",",
"domainPath",
")",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"out",
")",
"\n\n",
"out",
",",
"err",
"=",
"params",
".",
"runCmdAsRoot",
"(",
"\"",
"\"",
",",
"virsh",
",",
"\"",
"\"",
",",
"params",
".",
"Host",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"params",
".",
"Host",
"(",
")",
")",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"out",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] | // CreateMachine creates a virtual machine and starts it. | [
"CreateMachine",
"creates",
"a",
"virtual",
"machine",
"and",
"starts",
"it",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L169-L214 |
4,299 | juju/juju | container/kvm/wrappedcmds.go | setDefaults | func setDefaults(p *CreateMachineParams) {
if p.findPath == nil {
p.findPath = paths.DataDir
}
if p.runCmd == nil {
p.runCmd = runAsLibvirt
}
if p.runCmdAsRoot == nil {
p.runCmdAsRoot = run
}
} | go | func setDefaults(p *CreateMachineParams) {
if p.findPath == nil {
p.findPath = paths.DataDir
}
if p.runCmd == nil {
p.runCmd = runAsLibvirt
}
if p.runCmdAsRoot == nil {
p.runCmdAsRoot = run
}
} | [
"func",
"setDefaults",
"(",
"p",
"*",
"CreateMachineParams",
")",
"{",
"if",
"p",
".",
"findPath",
"==",
"nil",
"{",
"p",
".",
"findPath",
"=",
"paths",
".",
"DataDir",
"\n",
"}",
"\n",
"if",
"p",
".",
"runCmd",
"==",
"nil",
"{",
"p",
".",
"runCmd",
"=",
"runAsLibvirt",
"\n",
"}",
"\n",
"if",
"p",
".",
"runCmdAsRoot",
"==",
"nil",
"{",
"p",
".",
"runCmdAsRoot",
"=",
"run",
"\n",
"}",
"\n",
"}"
] | // Setup the default values for params. | [
"Setup",
"the",
"default",
"values",
"for",
"params",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L217-L227 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.