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
|
---|---|---|---|---|---|---|---|---|---|---|---|
5,100 | juju/juju | cmd/juju/application/flags.go | String | func (m stringMap) String() string {
pairs := make([]string, 0, len(*m.mapping))
for name, value := range *m.mapping {
pairs = append(pairs, name+"="+value)
}
return strings.Join(pairs, ";")
} | go | func (m stringMap) String() string {
pairs := make([]string, 0, len(*m.mapping))
for name, value := range *m.mapping {
pairs = append(pairs, name+"="+value)
}
return strings.Join(pairs, ";")
} | [
"func",
"(",
"m",
"stringMap",
")",
"String",
"(",
")",
"string",
"{",
"pairs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"*",
"m",
".",
"mapping",
")",
")",
"\n",
"for",
"name",
",",
"value",
":=",
"range",
"*",
"m",
".",
"mapping",
"{",
"pairs",
"=",
"append",
"(",
"pairs",
",",
"name",
"+",
"\"",
"\"",
"+",
"value",
")",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"pairs",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // String implements gnuflag.Value's String method | [
"String",
"implements",
"gnuflag",
".",
"Value",
"s",
"String",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/flags.go#L196-L202 |
5,101 | juju/juju | cmd/jujud/agent/model/agent.go | CurrentConfig | func (a *modelAgent) CurrentConfig() agent.Config {
return &modelAgentConfig{
Config: a.Agent.CurrentConfig(),
modelUUID: a.modelUUID,
controllerUUID: a.controllerUUID,
}
} | go | func (a *modelAgent) CurrentConfig() agent.Config {
return &modelAgentConfig{
Config: a.Agent.CurrentConfig(),
modelUUID: a.modelUUID,
controllerUUID: a.controllerUUID,
}
} | [
"func",
"(",
"a",
"*",
"modelAgent",
")",
"CurrentConfig",
"(",
")",
"agent",
".",
"Config",
"{",
"return",
"&",
"modelAgentConfig",
"{",
"Config",
":",
"a",
".",
"Agent",
".",
"CurrentConfig",
"(",
")",
",",
"modelUUID",
":",
"a",
".",
"modelUUID",
",",
"controllerUUID",
":",
"a",
".",
"controllerUUID",
",",
"}",
"\n",
"}"
] | // CurrentConfig is part of the agent.Agent interface. This implementation
// returns an agent.Config that reports tweaked API connection information. | [
"CurrentConfig",
"is",
"part",
"of",
"the",
"agent",
".",
"Agent",
"interface",
".",
"This",
"implementation",
"returns",
"an",
"agent",
".",
"Config",
"that",
"reports",
"tweaked",
"API",
"connection",
"information",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/model/agent.go#L47-L53 |
5,102 | juju/juju | cmd/jujud/agent/model/agent.go | APIInfo | func (c *modelAgentConfig) APIInfo() (*api.Info, bool) {
info, ok := c.Config.APIInfo()
if !ok {
return nil, false
}
info.ModelTag = names.NewModelTag(c.modelUUID)
return info, true
} | go | func (c *modelAgentConfig) APIInfo() (*api.Info, bool) {
info, ok := c.Config.APIInfo()
if !ok {
return nil, false
}
info.ModelTag = names.NewModelTag(c.modelUUID)
return info, true
} | [
"func",
"(",
"c",
"*",
"modelAgentConfig",
")",
"APIInfo",
"(",
")",
"(",
"*",
"api",
".",
"Info",
",",
"bool",
")",
"{",
"info",
",",
"ok",
":=",
"c",
".",
"Config",
".",
"APIInfo",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"info",
".",
"ModelTag",
"=",
"names",
".",
"NewModelTag",
"(",
"c",
".",
"modelUUID",
")",
"\n",
"return",
"info",
",",
"true",
"\n",
"}"
] | // APIInfo is part of the agent.Config interface. This implementation always
// replaces the target model tag with the configured model tag. | [
"APIInfo",
"is",
"part",
"of",
"the",
"agent",
".",
"Config",
"interface",
".",
"This",
"implementation",
"always",
"replaces",
"the",
"target",
"model",
"tag",
"with",
"the",
"configured",
"model",
"tag",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/model/agent.go#L75-L82 |
5,103 | juju/juju | worker/caasoperator/caasoperator.go | NewWorker | func NewWorker(config Config) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
paths := NewPaths(config.DataDir, names.NewApplicationTag(config.Application))
deployer, err := jujucharm.NewDeployer(
paths.State.CharmDir,
paths.State.DeployerDir,
jujucharm.NewBundlesDir(paths.State.BundlesDir, config.Downloader),
)
if err != nil {
return nil, errors.Annotatef(err, "cannot create deployer")
}
op := &caasOperator{
config: config,
paths: paths,
deployer: deployer,
runner: worker.NewRunner(worker.RunnerParams{
Clock: config.Clock,
// One of the uniter workers failing should not
// prevent the others from running.
IsFatal: func(error) bool { return false },
// For any failures, try again in 3 seconds.
RestartDelay: 3 * time.Second,
}),
}
if err := catacomb.Invoke(catacomb.Plan{
Site: &op.catacomb,
Work: op.loop,
Init: []worker.Worker{op.runner},
}); err != nil {
return nil, errors.Trace(err)
}
return op, nil
} | go | func NewWorker(config Config) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
paths := NewPaths(config.DataDir, names.NewApplicationTag(config.Application))
deployer, err := jujucharm.NewDeployer(
paths.State.CharmDir,
paths.State.DeployerDir,
jujucharm.NewBundlesDir(paths.State.BundlesDir, config.Downloader),
)
if err != nil {
return nil, errors.Annotatef(err, "cannot create deployer")
}
op := &caasOperator{
config: config,
paths: paths,
deployer: deployer,
runner: worker.NewRunner(worker.RunnerParams{
Clock: config.Clock,
// One of the uniter workers failing should not
// prevent the others from running.
IsFatal: func(error) bool { return false },
// For any failures, try again in 3 seconds.
RestartDelay: 3 * time.Second,
}),
}
if err := catacomb.Invoke(catacomb.Plan{
Site: &op.catacomb,
Work: op.loop,
Init: []worker.Worker{op.runner},
}); err != nil {
return nil, errors.Trace(err)
}
return op, nil
} | [
"func",
"NewWorker",
"(",
"config",
"Config",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"if",
"err",
":=",
"config",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"paths",
":=",
"NewPaths",
"(",
"config",
".",
"DataDir",
",",
"names",
".",
"NewApplicationTag",
"(",
"config",
".",
"Application",
")",
")",
"\n",
"deployer",
",",
"err",
":=",
"jujucharm",
".",
"NewDeployer",
"(",
"paths",
".",
"State",
".",
"CharmDir",
",",
"paths",
".",
"State",
".",
"DeployerDir",
",",
"jujucharm",
".",
"NewBundlesDir",
"(",
"paths",
".",
"State",
".",
"BundlesDir",
",",
"config",
".",
"Downloader",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"op",
":=",
"&",
"caasOperator",
"{",
"config",
":",
"config",
",",
"paths",
":",
"paths",
",",
"deployer",
":",
"deployer",
",",
"runner",
":",
"worker",
".",
"NewRunner",
"(",
"worker",
".",
"RunnerParams",
"{",
"Clock",
":",
"config",
".",
"Clock",
",",
"// One of the uniter workers failing should not",
"// prevent the others from running.",
"IsFatal",
":",
"func",
"(",
"error",
")",
"bool",
"{",
"return",
"false",
"}",
",",
"// For any failures, try again in 3 seconds.",
"RestartDelay",
":",
"3",
"*",
"time",
".",
"Second",
",",
"}",
")",
",",
"}",
"\n",
"if",
"err",
":=",
"catacomb",
".",
"Invoke",
"(",
"catacomb",
".",
"Plan",
"{",
"Site",
":",
"&",
"op",
".",
"catacomb",
",",
"Work",
":",
"op",
".",
"loop",
",",
"Init",
":",
"[",
"]",
"worker",
".",
"Worker",
"{",
"op",
".",
"runner",
"}",
",",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"op",
",",
"nil",
"\n",
"}"
] | // NewWorker creates a new worker which will install and operate a
// CaaS-based application, by executing hooks and operations in
// response to application state changes. | [
"NewWorker",
"creates",
"a",
"new",
"worker",
"which",
"will",
"install",
"and",
"operate",
"a",
"CaaS",
"-",
"based",
"application",
"by",
"executing",
"hooks",
"and",
"operations",
"in",
"response",
"to",
"application",
"state",
"changes",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/caasoperator/caasoperator.go#L163-L200 |
5,104 | juju/juju | juju/osenv/old_home.go | Juju1xEnvConfigExists | func Juju1xEnvConfigExists() bool {
dir := OldJujuHomeDir()
if dir == "" {
return false
}
_, err := os.Stat(filepath.Join(dir, "environments.yaml"))
return err == nil
} | go | func Juju1xEnvConfigExists() bool {
dir := OldJujuHomeDir()
if dir == "" {
return false
}
_, err := os.Stat(filepath.Join(dir, "environments.yaml"))
return err == nil
} | [
"func",
"Juju1xEnvConfigExists",
"(",
")",
"bool",
"{",
"dir",
":=",
"OldJujuHomeDir",
"(",
")",
"\n",
"if",
"dir",
"==",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"",
"\"",
")",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] | // Juju1xEnvConfigExists returns true if there is an environments.yaml file in
// the expected juju 1.x directory. | [
"Juju1xEnvConfigExists",
"returns",
"true",
"if",
"there",
"is",
"an",
"environments",
".",
"yaml",
"file",
"in",
"the",
"expected",
"juju",
"1",
".",
"x",
"directory",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/juju/osenv/old_home.go#L16-L23 |
5,105 | juju/juju | juju/osenv/old_home.go | OldJujuHomeDir | func OldJujuHomeDir() string {
JujuHomeDir := os.Getenv(oldJujuHomeEnvKey)
if JujuHomeDir == "" {
if runtime.GOOS == "windows" {
JujuHomeDir = oldJujuHomeWin()
} else {
JujuHomeDir = oldJujuHomeLinux()
}
}
return JujuHomeDir
} | go | func OldJujuHomeDir() string {
JujuHomeDir := os.Getenv(oldJujuHomeEnvKey)
if JujuHomeDir == "" {
if runtime.GOOS == "windows" {
JujuHomeDir = oldJujuHomeWin()
} else {
JujuHomeDir = oldJujuHomeLinux()
}
}
return JujuHomeDir
} | [
"func",
"OldJujuHomeDir",
"(",
")",
"string",
"{",
"JujuHomeDir",
":=",
"os",
".",
"Getenv",
"(",
"oldJujuHomeEnvKey",
")",
"\n",
"if",
"JujuHomeDir",
"==",
"\"",
"\"",
"{",
"if",
"runtime",
".",
"GOOS",
"==",
"\"",
"\"",
"{",
"JujuHomeDir",
"=",
"oldJujuHomeWin",
"(",
")",
"\n",
"}",
"else",
"{",
"JujuHomeDir",
"=",
"oldJujuHomeLinux",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"JujuHomeDir",
"\n",
"}"
] | // OldJujuHomeDir returns the directory where juju 1.x stored
// application-specific files. | [
"OldJujuHomeDir",
"returns",
"the",
"directory",
"where",
"juju",
"1",
".",
"x",
"stored",
"application",
"-",
"specific",
"files",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/juju/osenv/old_home.go#L34-L44 |
5,106 | juju/juju | api/statushistory/pruner.go | Prune | func (s *Facade) Prune(maxHistoryTime time.Duration, maxHistoryMB int) error {
p := params.StatusHistoryPruneArgs{
MaxHistoryTime: maxHistoryTime,
MaxHistoryMB: maxHistoryMB,
}
return s.facade.FacadeCall("Prune", p, nil)
} | go | func (s *Facade) Prune(maxHistoryTime time.Duration, maxHistoryMB int) error {
p := params.StatusHistoryPruneArgs{
MaxHistoryTime: maxHistoryTime,
MaxHistoryMB: maxHistoryMB,
}
return s.facade.FacadeCall("Prune", p, nil)
} | [
"func",
"(",
"s",
"*",
"Facade",
")",
"Prune",
"(",
"maxHistoryTime",
"time",
".",
"Duration",
",",
"maxHistoryMB",
"int",
")",
"error",
"{",
"p",
":=",
"params",
".",
"StatusHistoryPruneArgs",
"{",
"MaxHistoryTime",
":",
"maxHistoryTime",
",",
"MaxHistoryMB",
":",
"maxHistoryMB",
",",
"}",
"\n",
"return",
"s",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"p",
",",
"nil",
")",
"\n",
"}"
] | // Prune calls "StatusHistory.Prune" | [
"Prune",
"calls",
"StatusHistory",
".",
"Prune"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/statushistory/pruner.go#L29-L35 |
5,107 | juju/juju | apiserver/observer/metricobserver/mocks/metrics_mock.go | NewMockSummary | func NewMockSummary(ctrl *gomock.Controller) *MockSummary {
mock := &MockSummary{ctrl: ctrl}
mock.recorder = &MockSummaryMockRecorder{mock}
return mock
} | go | func NewMockSummary(ctrl *gomock.Controller) *MockSummary {
mock := &MockSummary{ctrl: ctrl}
mock.recorder = &MockSummaryMockRecorder{mock}
return mock
} | [
"func",
"NewMockSummary",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockSummary",
"{",
"mock",
":=",
"&",
"MockSummary",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockSummaryMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockSummary creates a new mock instance | [
"NewMockSummary",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/metricobserver/mocks/metrics_mock.go#L113-L117 |
5,108 | juju/juju | apiserver/observer/metricobserver/mocks/metrics_mock.go | Collect | func (mr *MockSummaryMockRecorder) Collect(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Collect", reflect.TypeOf((*MockSummary)(nil).Collect), arg0)
} | go | func (mr *MockSummaryMockRecorder) Collect(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Collect", reflect.TypeOf((*MockSummary)(nil).Collect), arg0)
} | [
"func",
"(",
"mr",
"*",
"MockSummaryMockRecorder",
")",
"Collect",
"(",
"arg0",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockSummary",
")",
"(",
"nil",
")",
".",
"Collect",
")",
",",
"arg0",
")",
"\n",
"}"
] | // Collect indicates an expected call of Collect | [
"Collect",
"indicates",
"an",
"expected",
"call",
"of",
"Collect"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/metricobserver/mocks/metrics_mock.go#L130-L132 |
5,109 | juju/juju | apiserver/observer/metricobserver/mocks/metrics_mock.go | Observe | func (m *MockSummary) Observe(arg0 float64) {
m.ctrl.Call(m, "Observe", arg0)
} | go | func (m *MockSummary) Observe(arg0 float64) {
m.ctrl.Call(m, "Observe", arg0)
} | [
"func",
"(",
"m",
"*",
"MockSummary",
")",
"Observe",
"(",
"arg0",
"float64",
")",
"{",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"}"
] | // Observe mocks base method | [
"Observe",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/metricobserver/mocks/metrics_mock.go#L157-L159 |
5,110 | juju/juju | worker/metrics/collect/handler.go | Handle | func (l *handler) Handle(c net.Conn, abort <-chan struct{}) error {
defer c.Close()
// TODO(fwereade): 2016-03-17 lp:1558657
err := c.SetDeadline(time.Now().Add(spool.DefaultTimeout))
if err != nil {
return errors.Annotate(err, "failed to set the deadline")
}
err = l.config.charmdir.Visit(func() error {
return l.do(c)
}, abort)
if err != nil {
fmt.Fprintf(c, "error: %v\n", err.Error())
} else {
fmt.Fprintf(c, "ok\n")
}
return errors.Trace(err)
} | go | func (l *handler) Handle(c net.Conn, abort <-chan struct{}) error {
defer c.Close()
// TODO(fwereade): 2016-03-17 lp:1558657
err := c.SetDeadline(time.Now().Add(spool.DefaultTimeout))
if err != nil {
return errors.Annotate(err, "failed to set the deadline")
}
err = l.config.charmdir.Visit(func() error {
return l.do(c)
}, abort)
if err != nil {
fmt.Fprintf(c, "error: %v\n", err.Error())
} else {
fmt.Fprintf(c, "ok\n")
}
return errors.Trace(err)
} | [
"func",
"(",
"l",
"*",
"handler",
")",
"Handle",
"(",
"c",
"net",
".",
"Conn",
",",
"abort",
"<-",
"chan",
"struct",
"{",
"}",
")",
"error",
"{",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"// TODO(fwereade): 2016-03-17 lp:1558657",
"err",
":=",
"c",
".",
"SetDeadline",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"spool",
".",
"DefaultTimeout",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"l",
".",
"config",
".",
"charmdir",
".",
"Visit",
"(",
"func",
"(",
")",
"error",
"{",
"return",
"l",
".",
"do",
"(",
"c",
")",
"\n",
"}",
",",
"abort",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
",",
"\"",
"\\n",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // Handle triggers the collect-metrics hook and writes collected metrics
// to the specified connection. | [
"Handle",
"triggers",
"the",
"collect",
"-",
"metrics",
"hook",
"and",
"writes",
"collected",
"metrics",
"to",
"the",
"specified",
"connection",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/collect/handler.go#L39-L57 |
5,111 | juju/juju | worker/caasoperatorprovisioner/worker.go | NewProvisionerWorker | func NewProvisionerWorker(config Config) (worker.Worker, error) {
p := &provisioner{
provisionerFacade: config.Facade,
broker: config.Broker,
modelTag: config.ModelTag,
agentConfig: config.AgentConfig,
clock: config.Clock,
}
err := catacomb.Invoke(catacomb.Plan{
Site: &p.catacomb,
Work: p.loop,
})
return p, err
} | go | func NewProvisionerWorker(config Config) (worker.Worker, error) {
p := &provisioner{
provisionerFacade: config.Facade,
broker: config.Broker,
modelTag: config.ModelTag,
agentConfig: config.AgentConfig,
clock: config.Clock,
}
err := catacomb.Invoke(catacomb.Plan{
Site: &p.catacomb,
Work: p.loop,
})
return p, err
} | [
"func",
"NewProvisionerWorker",
"(",
"config",
"Config",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"p",
":=",
"&",
"provisioner",
"{",
"provisionerFacade",
":",
"config",
".",
"Facade",
",",
"broker",
":",
"config",
".",
"Broker",
",",
"modelTag",
":",
"config",
".",
"ModelTag",
",",
"agentConfig",
":",
"config",
".",
"AgentConfig",
",",
"clock",
":",
"config",
".",
"Clock",
",",
"}",
"\n",
"err",
":=",
"catacomb",
".",
"Invoke",
"(",
"catacomb",
".",
"Plan",
"{",
"Site",
":",
"&",
"p",
".",
"catacomb",
",",
"Work",
":",
"p",
".",
"loop",
",",
"}",
")",
"\n",
"return",
"p",
",",
"err",
"\n",
"}"
] | // NewProvisionerWorker starts and returns a new CAAS provisioner worker. | [
"NewProvisionerWorker",
"starts",
"and",
"returns",
"a",
"new",
"CAAS",
"provisioner",
"worker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/caasoperatorprovisioner/worker.go#L49-L62 |
5,112 | juju/juju | worker/caasoperatorprovisioner/worker.go | ensureOperators | func (p *provisioner) ensureOperators(apps []string) error {
var appPasswords []apicaasprovisioner.ApplicationPassword
operatorConfig := make([]*caas.OperatorConfig, len(apps))
for i, app := range apps {
opState, err := p.broker.OperatorExists(app)
if err != nil {
return errors.Annotatef(err, "failed to find operator for %q", app)
}
if opState.Exists && opState.Terminating {
// We can't deploy an app while a previous version is terminating.
// TODO(caas) - the remove application process should block until app terminated
// TODO(caas) - consider making this async, but ok for now as it's a corner case
if err := p.waitForOperatorTerminated(app); err != nil {
return errors.Annotatef(err, "operator for %q was terminating and there was an error waiting for it to stop", app)
}
opState.Exists = false
}
// If the operator does not exist already, we need to create an initial
// password for it.
var password string
if !opState.Exists {
if password, err = utils.RandomPassword(); err != nil {
return errors.Trace(err)
}
appPasswords = append(appPasswords, apicaasprovisioner.ApplicationPassword{Name: app, Password: password})
}
config, err := p.makeOperatorConfig(app, password)
if err != nil {
return errors.Annotatef(err, "failed to generate operator config for %q", app)
}
operatorConfig[i] = config
}
// If we did create any passwords for new operators, first they need
// to be saved so the agent can login when it starts up.
if len(appPasswords) > 0 {
errorResults, err := p.provisionerFacade.SetPasswords(appPasswords)
if err != nil {
return errors.Annotate(err, "failed to set application api passwords")
}
if err := errorResults.Combine(); err != nil {
return errors.Annotate(err, "failed to set application api passwords")
}
}
// Now that any new config/passwords are done, create or update
// the operators themselves.
var errorStrings []string
for i, app := range apps {
if err := p.ensureOperator(app, operatorConfig[i]); err != nil {
errorStrings = append(errorStrings, err.Error())
continue
}
}
if errorStrings != nil {
err := errors.New(strings.Join(errorStrings, "\n"))
return errors.Annotate(err, "failed to provision all operators")
}
return nil
} | go | func (p *provisioner) ensureOperators(apps []string) error {
var appPasswords []apicaasprovisioner.ApplicationPassword
operatorConfig := make([]*caas.OperatorConfig, len(apps))
for i, app := range apps {
opState, err := p.broker.OperatorExists(app)
if err != nil {
return errors.Annotatef(err, "failed to find operator for %q", app)
}
if opState.Exists && opState.Terminating {
// We can't deploy an app while a previous version is terminating.
// TODO(caas) - the remove application process should block until app terminated
// TODO(caas) - consider making this async, but ok for now as it's a corner case
if err := p.waitForOperatorTerminated(app); err != nil {
return errors.Annotatef(err, "operator for %q was terminating and there was an error waiting for it to stop", app)
}
opState.Exists = false
}
// If the operator does not exist already, we need to create an initial
// password for it.
var password string
if !opState.Exists {
if password, err = utils.RandomPassword(); err != nil {
return errors.Trace(err)
}
appPasswords = append(appPasswords, apicaasprovisioner.ApplicationPassword{Name: app, Password: password})
}
config, err := p.makeOperatorConfig(app, password)
if err != nil {
return errors.Annotatef(err, "failed to generate operator config for %q", app)
}
operatorConfig[i] = config
}
// If we did create any passwords for new operators, first they need
// to be saved so the agent can login when it starts up.
if len(appPasswords) > 0 {
errorResults, err := p.provisionerFacade.SetPasswords(appPasswords)
if err != nil {
return errors.Annotate(err, "failed to set application api passwords")
}
if err := errorResults.Combine(); err != nil {
return errors.Annotate(err, "failed to set application api passwords")
}
}
// Now that any new config/passwords are done, create or update
// the operators themselves.
var errorStrings []string
for i, app := range apps {
if err := p.ensureOperator(app, operatorConfig[i]); err != nil {
errorStrings = append(errorStrings, err.Error())
continue
}
}
if errorStrings != nil {
err := errors.New(strings.Join(errorStrings, "\n"))
return errors.Annotate(err, "failed to provision all operators")
}
return nil
} | [
"func",
"(",
"p",
"*",
"provisioner",
")",
"ensureOperators",
"(",
"apps",
"[",
"]",
"string",
")",
"error",
"{",
"var",
"appPasswords",
"[",
"]",
"apicaasprovisioner",
".",
"ApplicationPassword",
"\n",
"operatorConfig",
":=",
"make",
"(",
"[",
"]",
"*",
"caas",
".",
"OperatorConfig",
",",
"len",
"(",
"apps",
")",
")",
"\n",
"for",
"i",
",",
"app",
":=",
"range",
"apps",
"{",
"opState",
",",
"err",
":=",
"p",
".",
"broker",
".",
"OperatorExists",
"(",
"app",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"app",
")",
"\n",
"}",
"\n",
"if",
"opState",
".",
"Exists",
"&&",
"opState",
".",
"Terminating",
"{",
"// We can't deploy an app while a previous version is terminating.",
"// TODO(caas) - the remove application process should block until app terminated",
"// TODO(caas) - consider making this async, but ok for now as it's a corner case",
"if",
"err",
":=",
"p",
".",
"waitForOperatorTerminated",
"(",
"app",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"app",
")",
"\n",
"}",
"\n",
"opState",
".",
"Exists",
"=",
"false",
"\n",
"}",
"\n",
"// If the operator does not exist already, we need to create an initial",
"// password for it.",
"var",
"password",
"string",
"\n",
"if",
"!",
"opState",
".",
"Exists",
"{",
"if",
"password",
",",
"err",
"=",
"utils",
".",
"RandomPassword",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"appPasswords",
"=",
"append",
"(",
"appPasswords",
",",
"apicaasprovisioner",
".",
"ApplicationPassword",
"{",
"Name",
":",
"app",
",",
"Password",
":",
"password",
"}",
")",
"\n",
"}",
"\n\n",
"config",
",",
"err",
":=",
"p",
".",
"makeOperatorConfig",
"(",
"app",
",",
"password",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"app",
")",
"\n",
"}",
"\n",
"operatorConfig",
"[",
"i",
"]",
"=",
"config",
"\n",
"}",
"\n",
"// If we did create any passwords for new operators, first they need",
"// to be saved so the agent can login when it starts up.",
"if",
"len",
"(",
"appPasswords",
")",
">",
"0",
"{",
"errorResults",
",",
"err",
":=",
"p",
".",
"provisionerFacade",
".",
"SetPasswords",
"(",
"appPasswords",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"errorResults",
".",
"Combine",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Now that any new config/passwords are done, create or update",
"// the operators themselves.",
"var",
"errorStrings",
"[",
"]",
"string",
"\n",
"for",
"i",
",",
"app",
":=",
"range",
"apps",
"{",
"if",
"err",
":=",
"p",
".",
"ensureOperator",
"(",
"app",
",",
"operatorConfig",
"[",
"i",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"errorStrings",
"=",
"append",
"(",
"errorStrings",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"errorStrings",
"!=",
"nil",
"{",
"err",
":=",
"errors",
".",
"New",
"(",
"strings",
".",
"Join",
"(",
"errorStrings",
",",
"\"",
"\\n",
"\"",
")",
")",
"\n",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ensureOperators creates operator pods for the specified app names -> api passwords. | [
"ensureOperators",
"creates",
"operator",
"pods",
"for",
"the",
"specified",
"app",
"names",
"-",
">",
"api",
"passwords",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/caasoperatorprovisioner/worker.go#L162-L221 |
5,113 | juju/juju | worker/peergrouper/manifold.go | Manifold | func Manifold(config ManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{
config.AgentName,
config.ClockName,
config.ControllerPortName,
config.StateName,
},
Start: config.start,
}
} | go | func Manifold(config ManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{
config.AgentName,
config.ClockName,
config.ControllerPortName,
config.StateName,
},
Start: config.start,
}
} | [
"func",
"Manifold",
"(",
"config",
"ManifoldConfig",
")",
"dependency",
".",
"Manifold",
"{",
"return",
"dependency",
".",
"Manifold",
"{",
"Inputs",
":",
"[",
"]",
"string",
"{",
"config",
".",
"AgentName",
",",
"config",
".",
"ClockName",
",",
"config",
".",
"ControllerPortName",
",",
"config",
".",
"StateName",
",",
"}",
",",
"Start",
":",
"config",
".",
"start",
",",
"}",
"\n",
"}"
] | // Manifold returns a dependency.Manifold that will run a peergrouper. | [
"Manifold",
"returns",
"a",
"dependency",
".",
"Manifold",
"that",
"will",
"run",
"a",
"peergrouper",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/manifold.go#L53-L63 |
5,114 | juju/juju | cmd/juju/commands/enableha.go | Run | func (c *enableHACommand) Run(ctx *cmd.Context) error {
controllerName, err := c.ControllerName()
if err != nil {
return errors.Trace(err)
}
if err := common.ValidateIaasController(c.CommandBase, c.Info().Name, controllerName, c.ClientStore()); err != nil {
return errors.Trace(err)
}
c.Constraints, err = common.ParseConstraints(ctx, c.ConstraintsStr)
if err != nil {
return err
}
haClient, err := c.newHAClientFunc()
if err != nil {
return err
}
defer haClient.Close()
enableHAResult, err := haClient.EnableHA(
c.NumControllers,
c.Constraints,
c.Placement,
)
if err != nil {
return block.ProcessBlockedError(err, block.BlockChange)
}
result := availabilityInfo{
Added: machineTagsToIds(enableHAResult.Added...),
Removed: machineTagsToIds(enableHAResult.Removed...),
Maintained: machineTagsToIds(enableHAResult.Maintained...),
Promoted: machineTagsToIds(enableHAResult.Promoted...),
Demoted: machineTagsToIds(enableHAResult.Demoted...),
Converted: machineTagsToIds(enableHAResult.Converted...),
}
return c.out.Write(ctx, result)
} | go | func (c *enableHACommand) Run(ctx *cmd.Context) error {
controllerName, err := c.ControllerName()
if err != nil {
return errors.Trace(err)
}
if err := common.ValidateIaasController(c.CommandBase, c.Info().Name, controllerName, c.ClientStore()); err != nil {
return errors.Trace(err)
}
c.Constraints, err = common.ParseConstraints(ctx, c.ConstraintsStr)
if err != nil {
return err
}
haClient, err := c.newHAClientFunc()
if err != nil {
return err
}
defer haClient.Close()
enableHAResult, err := haClient.EnableHA(
c.NumControllers,
c.Constraints,
c.Placement,
)
if err != nil {
return block.ProcessBlockedError(err, block.BlockChange)
}
result := availabilityInfo{
Added: machineTagsToIds(enableHAResult.Added...),
Removed: machineTagsToIds(enableHAResult.Removed...),
Maintained: machineTagsToIds(enableHAResult.Maintained...),
Promoted: machineTagsToIds(enableHAResult.Promoted...),
Demoted: machineTagsToIds(enableHAResult.Demoted...),
Converted: machineTagsToIds(enableHAResult.Converted...),
}
return c.out.Write(ctx, result)
} | [
"func",
"(",
"c",
"*",
"enableHACommand",
")",
"Run",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
")",
"error",
"{",
"controllerName",
",",
"err",
":=",
"c",
".",
"ControllerName",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"common",
".",
"ValidateIaasController",
"(",
"c",
".",
"CommandBase",
",",
"c",
".",
"Info",
"(",
")",
".",
"Name",
",",
"controllerName",
",",
"c",
".",
"ClientStore",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"c",
".",
"Constraints",
",",
"err",
"=",
"common",
".",
"ParseConstraints",
"(",
"ctx",
",",
"c",
".",
"ConstraintsStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"haClient",
",",
"err",
":=",
"c",
".",
"newHAClientFunc",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"defer",
"haClient",
".",
"Close",
"(",
")",
"\n",
"enableHAResult",
",",
"err",
":=",
"haClient",
".",
"EnableHA",
"(",
"c",
".",
"NumControllers",
",",
"c",
".",
"Constraints",
",",
"c",
".",
"Placement",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"block",
".",
"ProcessBlockedError",
"(",
"err",
",",
"block",
".",
"BlockChange",
")",
"\n",
"}",
"\n\n",
"result",
":=",
"availabilityInfo",
"{",
"Added",
":",
"machineTagsToIds",
"(",
"enableHAResult",
".",
"Added",
"...",
")",
",",
"Removed",
":",
"machineTagsToIds",
"(",
"enableHAResult",
".",
"Removed",
"...",
")",
",",
"Maintained",
":",
"machineTagsToIds",
"(",
"enableHAResult",
".",
"Maintained",
"...",
")",
",",
"Promoted",
":",
"machineTagsToIds",
"(",
"enableHAResult",
".",
"Promoted",
"...",
")",
",",
"Demoted",
":",
"machineTagsToIds",
"(",
"enableHAResult",
".",
"Demoted",
"...",
")",
",",
"Converted",
":",
"machineTagsToIds",
"(",
"enableHAResult",
".",
"Converted",
"...",
")",
",",
"}",
"\n",
"return",
"c",
".",
"out",
".",
"Write",
"(",
"ctx",
",",
"result",
")",
"\n",
"}"
] | // Run connects to the environment specified on the command line
// and calls EnableHA. | [
"Run",
"connects",
"to",
"the",
"environment",
"specified",
"on",
"the",
"command",
"line",
"and",
"calls",
"EnableHA",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/enableha.go#L212-L249 |
5,115 | juju/juju | cmd/juju/commands/enableha.go | machineTagsToIds | func machineTagsToIds(tags ...string) []string {
var result []string
for _, rawTag := range tags {
tag, err := names.ParseTag(rawTag)
if err != nil {
continue
}
result = append(result, tag.Id())
}
return result
} | go | func machineTagsToIds(tags ...string) []string {
var result []string
for _, rawTag := range tags {
tag, err := names.ParseTag(rawTag)
if err != nil {
continue
}
result = append(result, tag.Id())
}
return result
} | [
"func",
"machineTagsToIds",
"(",
"tags",
"...",
"string",
")",
"[",
"]",
"string",
"{",
"var",
"result",
"[",
"]",
"string",
"\n\n",
"for",
"_",
",",
"rawTag",
":=",
"range",
"tags",
"{",
"tag",
",",
"err",
":=",
"names",
".",
"ParseTag",
"(",
"rawTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"result",
"=",
"append",
"(",
"result",
",",
"tag",
".",
"Id",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // Convert machine tags to ids, skipping any non-machine tags. | [
"Convert",
"machine",
"tags",
"to",
"ids",
"skipping",
"any",
"non",
"-",
"machine",
"tags",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/enableha.go#L252-L263 |
5,116 | juju/juju | resource/resourceadapters/opener.go | OpenResource | func (ro *resourceOpener) OpenResource(name string) (o resource.Opened, err error) {
if ro.unit == nil {
return resource.Opened{}, errors.Errorf("missing unit")
}
app, err := ro.unit.Application()
if err != nil {
return resource.Opened{}, errors.Trace(err)
}
cURL, _ := ro.unit.CharmURL()
id := csclient.CharmID{
URL: cURL,
Channel: app.Channel(),
}
csOpener := newCharmstoreOpener(ro.st)
client, err := csOpener.NewClient()
if err != nil {
return resource.Opened{}, errors.Trace(err)
}
cache := &charmstoreEntityCache{
st: ro.res,
userID: ro.userID,
unit: ro.unit,
applicationID: ro.unit.ApplicationName(),
}
res, reader, err := charmstore.GetResource(charmstore.GetResourceArgs{
Client: client,
Cache: cache,
CharmID: id,
Name: name,
})
if err != nil {
return resource.Opened{}, errors.Trace(err)
}
opened := resource.Opened{
Resource: res,
ReadCloser: reader,
}
return opened, nil
} | go | func (ro *resourceOpener) OpenResource(name string) (o resource.Opened, err error) {
if ro.unit == nil {
return resource.Opened{}, errors.Errorf("missing unit")
}
app, err := ro.unit.Application()
if err != nil {
return resource.Opened{}, errors.Trace(err)
}
cURL, _ := ro.unit.CharmURL()
id := csclient.CharmID{
URL: cURL,
Channel: app.Channel(),
}
csOpener := newCharmstoreOpener(ro.st)
client, err := csOpener.NewClient()
if err != nil {
return resource.Opened{}, errors.Trace(err)
}
cache := &charmstoreEntityCache{
st: ro.res,
userID: ro.userID,
unit: ro.unit,
applicationID: ro.unit.ApplicationName(),
}
res, reader, err := charmstore.GetResource(charmstore.GetResourceArgs{
Client: client,
Cache: cache,
CharmID: id,
Name: name,
})
if err != nil {
return resource.Opened{}, errors.Trace(err)
}
opened := resource.Opened{
Resource: res,
ReadCloser: reader,
}
return opened, nil
} | [
"func",
"(",
"ro",
"*",
"resourceOpener",
")",
"OpenResource",
"(",
"name",
"string",
")",
"(",
"o",
"resource",
".",
"Opened",
",",
"err",
"error",
")",
"{",
"if",
"ro",
".",
"unit",
"==",
"nil",
"{",
"return",
"resource",
".",
"Opened",
"{",
"}",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"app",
",",
"err",
":=",
"ro",
".",
"unit",
".",
"Application",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"resource",
".",
"Opened",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"cURL",
",",
"_",
":=",
"ro",
".",
"unit",
".",
"CharmURL",
"(",
")",
"\n",
"id",
":=",
"csclient",
".",
"CharmID",
"{",
"URL",
":",
"cURL",
",",
"Channel",
":",
"app",
".",
"Channel",
"(",
")",
",",
"}",
"\n\n",
"csOpener",
":=",
"newCharmstoreOpener",
"(",
"ro",
".",
"st",
")",
"\n",
"client",
",",
"err",
":=",
"csOpener",
".",
"NewClient",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"resource",
".",
"Opened",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"cache",
":=",
"&",
"charmstoreEntityCache",
"{",
"st",
":",
"ro",
".",
"res",
",",
"userID",
":",
"ro",
".",
"userID",
",",
"unit",
":",
"ro",
".",
"unit",
",",
"applicationID",
":",
"ro",
".",
"unit",
".",
"ApplicationName",
"(",
")",
",",
"}",
"\n\n",
"res",
",",
"reader",
",",
"err",
":=",
"charmstore",
".",
"GetResource",
"(",
"charmstore",
".",
"GetResourceArgs",
"{",
"Client",
":",
"client",
",",
"Cache",
":",
"cache",
",",
"CharmID",
":",
"id",
",",
"Name",
":",
"name",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"resource",
".",
"Opened",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"opened",
":=",
"resource",
".",
"Opened",
"{",
"Resource",
":",
"res",
",",
"ReadCloser",
":",
"reader",
",",
"}",
"\n",
"return",
"opened",
",",
"nil",
"\n",
"}"
] | // OpenResource implements server.ResourceOpener. | [
"OpenResource",
"implements",
"server",
".",
"ResourceOpener",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/resourceadapters/opener.go#L52-L94 |
5,117 | juju/juju | worker/undertaker/undertaker.go | Validate | func (config Config) Validate() error {
if config.Facade == nil {
return errors.NotValidf("nil Facade")
}
if config.CredentialAPI == nil {
return errors.NotValidf("nil CredentialAPI")
}
if config.Destroyer == nil {
return errors.NotValidf("nil Destroyer")
}
return nil
} | go | func (config Config) Validate() error {
if config.Facade == nil {
return errors.NotValidf("nil Facade")
}
if config.CredentialAPI == nil {
return errors.NotValidf("nil CredentialAPI")
}
if config.Destroyer == nil {
return errors.NotValidf("nil Destroyer")
}
return nil
} | [
"func",
"(",
"config",
"Config",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"config",
".",
"Facade",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"CredentialAPI",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"Destroyer",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate returns an error if the config cannot be expected to drive
// a functional undertaker worker. | [
"Validate",
"returns",
"an",
"error",
"if",
"the",
"config",
"cannot",
"be",
"expected",
"to",
"drive",
"a",
"functional",
"undertaker",
"worker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/undertaker/undertaker.go#L41-L52 |
5,118 | juju/juju | worker/undertaker/undertaker.go | NewUndertaker | func NewUndertaker(config Config) (*Undertaker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
u := &Undertaker{
config: config,
}
err := catacomb.Invoke(catacomb.Plan{
Site: &u.catacomb,
Work: u.run,
})
if err != nil {
return nil, errors.Trace(err)
}
u.setCallCtx(common.NewCloudCallContext(config.CredentialAPI, u.catacomb.Dying))
return u, nil
} | go | func NewUndertaker(config Config) (*Undertaker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
u := &Undertaker{
config: config,
}
err := catacomb.Invoke(catacomb.Plan{
Site: &u.catacomb,
Work: u.run,
})
if err != nil {
return nil, errors.Trace(err)
}
u.setCallCtx(common.NewCloudCallContext(config.CredentialAPI, u.catacomb.Dying))
return u, nil
} | [
"func",
"NewUndertaker",
"(",
"config",
"Config",
")",
"(",
"*",
"Undertaker",
",",
"error",
")",
"{",
"if",
"err",
":=",
"config",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"u",
":=",
"&",
"Undertaker",
"{",
"config",
":",
"config",
",",
"}",
"\n",
"err",
":=",
"catacomb",
".",
"Invoke",
"(",
"catacomb",
".",
"Plan",
"{",
"Site",
":",
"&",
"u",
".",
"catacomb",
",",
"Work",
":",
"u",
".",
"run",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"u",
".",
"setCallCtx",
"(",
"common",
".",
"NewCloudCallContext",
"(",
"config",
".",
"CredentialAPI",
",",
"u",
".",
"catacomb",
".",
"Dying",
")",
")",
"\n",
"return",
"u",
",",
"nil",
"\n",
"}"
] | // NewUndertaker returns a worker which processes a dying model. | [
"NewUndertaker",
"returns",
"a",
"worker",
"which",
"processes",
"a",
"dying",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/undertaker/undertaker.go#L55-L72 |
5,119 | juju/juju | migration/migration.go | ImportModel | func ImportModel(importer StateImporter, getClaimer ClaimerFunc, bytes []byte) (*state.Model, *state.State, error) {
model, err := description.Deserialize(bytes)
if err != nil {
return nil, nil, errors.Trace(err)
}
dbModel, dbState, err := importer.Import(model)
if err != nil {
return nil, nil, errors.Trace(err)
}
config, err := dbState.ControllerConfig()
if err != nil {
return nil, nil, errors.Trace(err)
}
// If we're using legacy-leases we get the claimer from the new
// state - otherwise use the function passed in.
//
var claimer leadership.Claimer
if config.Features().Contains(feature.LegacyLeases) {
claimer = dbState.LeadershipClaimer()
} else {
claimer, err = getClaimer(dbModel.UUID())
if err != nil {
return nil, nil, errors.Annotate(err, "getting leadership claimer")
}
}
logger.Debugf("importing leadership")
for _, application := range model.Applications() {
if application.Leader() == "" {
continue
}
// When we import a new model, we need to give the leaders
// some time to settle. We don't want to have leader switches
// just because we migrated a model, so this time needs to be
// long enough to make sure we cover the time taken to migrate
// a reasonable sized model. We don't yet know how long this
// is going to be, but we need something.
// TODO(babbageclunk): Handle this better - maybe a way to
// suppress leadership expiries for a model until it's
// finished importing?
logger.Debugf("%q is the leader for %q", application.Leader(), application.Name())
err := claimer.ClaimLeadership(
application.Name(),
application.Leader(),
state.InitialLeaderClaimTime,
)
if err != nil {
return nil, nil, errors.Annotatef(
err,
"claiming leadership for %q",
application.Leader(),
)
}
}
return dbModel, dbState, nil
} | go | func ImportModel(importer StateImporter, getClaimer ClaimerFunc, bytes []byte) (*state.Model, *state.State, error) {
model, err := description.Deserialize(bytes)
if err != nil {
return nil, nil, errors.Trace(err)
}
dbModel, dbState, err := importer.Import(model)
if err != nil {
return nil, nil, errors.Trace(err)
}
config, err := dbState.ControllerConfig()
if err != nil {
return nil, nil, errors.Trace(err)
}
// If we're using legacy-leases we get the claimer from the new
// state - otherwise use the function passed in.
//
var claimer leadership.Claimer
if config.Features().Contains(feature.LegacyLeases) {
claimer = dbState.LeadershipClaimer()
} else {
claimer, err = getClaimer(dbModel.UUID())
if err != nil {
return nil, nil, errors.Annotate(err, "getting leadership claimer")
}
}
logger.Debugf("importing leadership")
for _, application := range model.Applications() {
if application.Leader() == "" {
continue
}
// When we import a new model, we need to give the leaders
// some time to settle. We don't want to have leader switches
// just because we migrated a model, so this time needs to be
// long enough to make sure we cover the time taken to migrate
// a reasonable sized model. We don't yet know how long this
// is going to be, but we need something.
// TODO(babbageclunk): Handle this better - maybe a way to
// suppress leadership expiries for a model until it's
// finished importing?
logger.Debugf("%q is the leader for %q", application.Leader(), application.Name())
err := claimer.ClaimLeadership(
application.Name(),
application.Leader(),
state.InitialLeaderClaimTime,
)
if err != nil {
return nil, nil, errors.Annotatef(
err,
"claiming leadership for %q",
application.Leader(),
)
}
}
return dbModel, dbState, nil
} | [
"func",
"ImportModel",
"(",
"importer",
"StateImporter",
",",
"getClaimer",
"ClaimerFunc",
",",
"bytes",
"[",
"]",
"byte",
")",
"(",
"*",
"state",
".",
"Model",
",",
"*",
"state",
".",
"State",
",",
"error",
")",
"{",
"model",
",",
"err",
":=",
"description",
".",
"Deserialize",
"(",
"bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"dbModel",
",",
"dbState",
",",
"err",
":=",
"importer",
".",
"Import",
"(",
"model",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"config",
",",
"err",
":=",
"dbState",
".",
"ControllerConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// If we're using legacy-leases we get the claimer from the new",
"// state - otherwise use the function passed in.",
"//",
"var",
"claimer",
"leadership",
".",
"Claimer",
"\n",
"if",
"config",
".",
"Features",
"(",
")",
".",
"Contains",
"(",
"feature",
".",
"LegacyLeases",
")",
"{",
"claimer",
"=",
"dbState",
".",
"LeadershipClaimer",
"(",
")",
"\n",
"}",
"else",
"{",
"claimer",
",",
"err",
"=",
"getClaimer",
"(",
"dbModel",
".",
"UUID",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"application",
":=",
"range",
"model",
".",
"Applications",
"(",
")",
"{",
"if",
"application",
".",
"Leader",
"(",
")",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"// When we import a new model, we need to give the leaders",
"// some time to settle. We don't want to have leader switches",
"// just because we migrated a model, so this time needs to be",
"// long enough to make sure we cover the time taken to migrate",
"// a reasonable sized model. We don't yet know how long this",
"// is going to be, but we need something.",
"// TODO(babbageclunk): Handle this better - maybe a way to",
"// suppress leadership expiries for a model until it's",
"// finished importing?",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"application",
".",
"Leader",
"(",
")",
",",
"application",
".",
"Name",
"(",
")",
")",
"\n",
"err",
":=",
"claimer",
".",
"ClaimLeadership",
"(",
"application",
".",
"Name",
"(",
")",
",",
"application",
".",
"Leader",
"(",
")",
",",
"state",
".",
"InitialLeaderClaimTime",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"application",
".",
"Leader",
"(",
")",
",",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"dbModel",
",",
"dbState",
",",
"nil",
"\n",
"}"
] | // ImportModel deserializes a model description from the bytes, transforms
// the model config based on information from the controller model, and then
// imports that as a new database model. | [
"ImportModel",
"deserializes",
"a",
"model",
"description",
"from",
"the",
"bytes",
"transforms",
"the",
"model",
"config",
"based",
"on",
"information",
"from",
"the",
"controller",
"model",
"and",
"then",
"imports",
"that",
"as",
"a",
"new",
"database",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/migration/migration.go#L65-L124 |
5,120 | juju/juju | migration/migration.go | Validate | func (c *UploadBinariesConfig) Validate() error {
if c.CharmDownloader == nil {
return errors.NotValidf("missing CharmDownloader")
}
if c.CharmUploader == nil {
return errors.NotValidf("missing CharmUploader")
}
if c.ToolsDownloader == nil {
return errors.NotValidf("missing ToolsDownloader")
}
if c.ToolsUploader == nil {
return errors.NotValidf("missing ToolsUploader")
}
if c.ResourceDownloader == nil {
return errors.NotValidf("missing ResourceDownloader")
}
if c.ResourceUploader == nil {
return errors.NotValidf("missing ResourceUploader")
}
return nil
} | go | func (c *UploadBinariesConfig) Validate() error {
if c.CharmDownloader == nil {
return errors.NotValidf("missing CharmDownloader")
}
if c.CharmUploader == nil {
return errors.NotValidf("missing CharmUploader")
}
if c.ToolsDownloader == nil {
return errors.NotValidf("missing ToolsDownloader")
}
if c.ToolsUploader == nil {
return errors.NotValidf("missing ToolsUploader")
}
if c.ResourceDownloader == nil {
return errors.NotValidf("missing ResourceDownloader")
}
if c.ResourceUploader == nil {
return errors.NotValidf("missing ResourceUploader")
}
return nil
} | [
"func",
"(",
"c",
"*",
"UploadBinariesConfig",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"c",
".",
"CharmDownloader",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"CharmUploader",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"ToolsDownloader",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"ToolsUploader",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"ResourceDownloader",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"ResourceUploader",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate makes sure that all the config values are non-nil. | [
"Validate",
"makes",
"sure",
"that",
"all",
"the",
"config",
"values",
"are",
"non",
"-",
"nil",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/migration/migration.go#L182-L202 |
5,121 | juju/juju | migration/migration.go | UploadBinaries | func UploadBinaries(config UploadBinariesConfig) error {
if err := config.Validate(); err != nil {
return errors.Trace(err)
}
if err := uploadCharms(config); err != nil {
return errors.Trace(err)
}
if err := uploadTools(config); err != nil {
return errors.Trace(err)
}
if err := uploadResources(config); err != nil {
return errors.Trace(err)
}
return nil
} | go | func UploadBinaries(config UploadBinariesConfig) error {
if err := config.Validate(); err != nil {
return errors.Trace(err)
}
if err := uploadCharms(config); err != nil {
return errors.Trace(err)
}
if err := uploadTools(config); err != nil {
return errors.Trace(err)
}
if err := uploadResources(config); err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"UploadBinaries",
"(",
"config",
"UploadBinariesConfig",
")",
"error",
"{",
"if",
"err",
":=",
"config",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"uploadCharms",
"(",
"config",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"uploadTools",
"(",
"config",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"uploadResources",
"(",
"config",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // UploadBinaries will send binaries stored in the source blobstore to
// the target controller. | [
"UploadBinaries",
"will",
"send",
"binaries",
"stored",
"in",
"the",
"source",
"blobstore",
"to",
"the",
"target",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/migration/migration.go#L206-L220 |
5,122 | juju/juju | worker/metrics/spool/manifold.go | Recorder | func (f *factory) Recorder(declaredMetrics map[string]corecharm.Metric, charmURL, unitTag string) (MetricRecorder, error) {
return NewJSONMetricRecorder(MetricRecorderConfig{
SpoolDir: f.spoolDir,
Metrics: declaredMetrics,
CharmURL: charmURL,
UnitTag: unitTag,
})
} | go | func (f *factory) Recorder(declaredMetrics map[string]corecharm.Metric, charmURL, unitTag string) (MetricRecorder, error) {
return NewJSONMetricRecorder(MetricRecorderConfig{
SpoolDir: f.spoolDir,
Metrics: declaredMetrics,
CharmURL: charmURL,
UnitTag: unitTag,
})
} | [
"func",
"(",
"f",
"*",
"factory",
")",
"Recorder",
"(",
"declaredMetrics",
"map",
"[",
"string",
"]",
"corecharm",
".",
"Metric",
",",
"charmURL",
",",
"unitTag",
"string",
")",
"(",
"MetricRecorder",
",",
"error",
")",
"{",
"return",
"NewJSONMetricRecorder",
"(",
"MetricRecorderConfig",
"{",
"SpoolDir",
":",
"f",
".",
"spoolDir",
",",
"Metrics",
":",
"declaredMetrics",
",",
"CharmURL",
":",
"charmURL",
",",
"UnitTag",
":",
"unitTag",
",",
"}",
")",
"\n",
"}"
] | // Recorder implements the MetricFactory interface. | [
"Recorder",
"implements",
"the",
"MetricFactory",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/manifold.go#L66-L73 |
5,123 | juju/juju | worker/metrics/spool/manifold.go | Manifold | func Manifold(config ManifoldConfig) dependency.Manifold {
manifold := engine.AgentManifold(engine.AgentManifoldConfig(config), newWorker)
manifold.Output = outputFunc
return manifold
} | go | func Manifold(config ManifoldConfig) dependency.Manifold {
manifold := engine.AgentManifold(engine.AgentManifoldConfig(config), newWorker)
manifold.Output = outputFunc
return manifold
} | [
"func",
"Manifold",
"(",
"config",
"ManifoldConfig",
")",
"dependency",
".",
"Manifold",
"{",
"manifold",
":=",
"engine",
".",
"AgentManifold",
"(",
"engine",
".",
"AgentManifoldConfig",
"(",
"config",
")",
",",
"newWorker",
")",
"\n",
"manifold",
".",
"Output",
"=",
"outputFunc",
"\n",
"return",
"manifold",
"\n",
"}"
] | // Manifold returns a dependency.Manifold that extracts the metrics
// spool directory path from the agent. | [
"Manifold",
"returns",
"a",
"dependency",
".",
"Manifold",
"that",
"extracts",
"the",
"metrics",
"spool",
"directory",
"path",
"from",
"the",
"agent",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/manifold.go#L85-L89 |
5,124 | juju/juju | worker/metrics/spool/manifold.go | newWorker | func newWorker(a agent.Agent) (worker.Worker, error) {
metricsSpoolDir := a.CurrentConfig().MetricsSpoolDir()
err := checkSpoolDir(metricsSpoolDir)
if err != nil {
return nil, errors.Annotatef(err, "error checking spool directory %q", metricsSpoolDir)
}
w := &spoolWorker{factory: newFactory(metricsSpoolDir)}
w.tomb.Go(func() error {
<-w.tomb.Dying()
return nil
})
return w, nil
} | go | func newWorker(a agent.Agent) (worker.Worker, error) {
metricsSpoolDir := a.CurrentConfig().MetricsSpoolDir()
err := checkSpoolDir(metricsSpoolDir)
if err != nil {
return nil, errors.Annotatef(err, "error checking spool directory %q", metricsSpoolDir)
}
w := &spoolWorker{factory: newFactory(metricsSpoolDir)}
w.tomb.Go(func() error {
<-w.tomb.Dying()
return nil
})
return w, nil
} | [
"func",
"newWorker",
"(",
"a",
"agent",
".",
"Agent",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"metricsSpoolDir",
":=",
"a",
".",
"CurrentConfig",
"(",
")",
".",
"MetricsSpoolDir",
"(",
")",
"\n",
"err",
":=",
"checkSpoolDir",
"(",
"metricsSpoolDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"metricsSpoolDir",
")",
"\n",
"}",
"\n",
"w",
":=",
"&",
"spoolWorker",
"{",
"factory",
":",
"newFactory",
"(",
"metricsSpoolDir",
")",
"}",
"\n",
"w",
".",
"tomb",
".",
"Go",
"(",
"func",
"(",
")",
"error",
"{",
"<-",
"w",
".",
"tomb",
".",
"Dying",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"w",
",",
"nil",
"\n",
"}"
] | // newWorker creates a degenerate worker that provides access to the metrics
// spool directory path. | [
"newWorker",
"creates",
"a",
"degenerate",
"worker",
"that",
"provides",
"access",
"to",
"the",
"metrics",
"spool",
"directory",
"path",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/manifold.go#L93-L105 |
5,125 | juju/juju | payload/status/formatter.go | FormatPayload | func FormatPayload(payload payload.FullPayloadInfo) FormattedPayload {
var labels []string
if len(payload.Labels) > 0 {
labels = make([]string, len(payload.Labels))
copy(labels, payload.Labels)
}
return FormattedPayload{
Unit: payload.Unit,
Machine: payload.Machine,
ID: payload.ID,
Type: payload.Type,
Class: payload.Name,
Labels: labels,
// TODO(ericsnow) Explicitly convert to a string?
Status: payload.Status,
}
} | go | func FormatPayload(payload payload.FullPayloadInfo) FormattedPayload {
var labels []string
if len(payload.Labels) > 0 {
labels = make([]string, len(payload.Labels))
copy(labels, payload.Labels)
}
return FormattedPayload{
Unit: payload.Unit,
Machine: payload.Machine,
ID: payload.ID,
Type: payload.Type,
Class: payload.Name,
Labels: labels,
// TODO(ericsnow) Explicitly convert to a string?
Status: payload.Status,
}
} | [
"func",
"FormatPayload",
"(",
"payload",
"payload",
".",
"FullPayloadInfo",
")",
"FormattedPayload",
"{",
"var",
"labels",
"[",
"]",
"string",
"\n",
"if",
"len",
"(",
"payload",
".",
"Labels",
")",
">",
"0",
"{",
"labels",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"payload",
".",
"Labels",
")",
")",
"\n",
"copy",
"(",
"labels",
",",
"payload",
".",
"Labels",
")",
"\n",
"}",
"\n",
"return",
"FormattedPayload",
"{",
"Unit",
":",
"payload",
".",
"Unit",
",",
"Machine",
":",
"payload",
".",
"Machine",
",",
"ID",
":",
"payload",
".",
"ID",
",",
"Type",
":",
"payload",
".",
"Type",
",",
"Class",
":",
"payload",
".",
"Name",
",",
"Labels",
":",
"labels",
",",
"// TODO(ericsnow) Explicitly convert to a string?",
"Status",
":",
"payload",
".",
"Status",
",",
"}",
"\n",
"}"
] | // FormatPayload converts the Payload into a FormattedPayload. | [
"FormatPayload",
"converts",
"the",
"Payload",
"into",
"a",
"FormattedPayload",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/status/formatter.go#L34-L50 |
5,126 | juju/juju | container/kvm/mock/mock-kvm.go | EnsureCachedImage | func (mock *MockContainer) EnsureCachedImage(params kvm.StartParams) error {
imageCacheCalls++
mock.StartParams = params
return nil
} | go | func (mock *MockContainer) EnsureCachedImage(params kvm.StartParams) error {
imageCacheCalls++
mock.StartParams = params
return nil
} | [
"func",
"(",
"mock",
"*",
"MockContainer",
")",
"EnsureCachedImage",
"(",
"params",
"kvm",
".",
"StartParams",
")",
"error",
"{",
"imageCacheCalls",
"++",
"\n",
"mock",
".",
"StartParams",
"=",
"params",
"\n",
"return",
"nil",
"\n",
"}"
] | // EnsureCachedImage is the first supply of start-params to the container.
// We set it here for subsequent test assertions.
// Start is called by the manager immediately after, with the same argument. | [
"EnsureCachedImage",
"is",
"the",
"first",
"supply",
"of",
"start",
"-",
"params",
"to",
"the",
"container",
".",
"We",
"set",
"it",
"here",
"for",
"subsequent",
"test",
"assertions",
".",
"Start",
"is",
"called",
"by",
"the",
"manager",
"immediately",
"after",
"with",
"the",
"same",
"argument",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/mock/mock-kvm.go#L82-L86 |
5,127 | juju/juju | container/kvm/mock/mock-kvm.go | Stop | func (mock *MockContainer) Stop() error {
if !mock.started {
return fmt.Errorf("container is not running")
}
mock.started = false
mock.factory.notify(Stopped, mock.name)
return nil
} | go | func (mock *MockContainer) Stop() error {
if !mock.started {
return fmt.Errorf("container is not running")
}
mock.started = false
mock.factory.notify(Stopped, mock.name)
return nil
} | [
"func",
"(",
"mock",
"*",
"MockContainer",
")",
"Stop",
"(",
")",
"error",
"{",
"if",
"!",
"mock",
".",
"started",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"mock",
".",
"started",
"=",
"false",
"\n",
"mock",
".",
"factory",
".",
"notify",
"(",
"Stopped",
",",
"mock",
".",
"name",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Stop terminates the running container. | [
"Stop",
"terminates",
"the",
"running",
"container",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/mock/mock-kvm.go#L98-L105 |
5,128 | juju/juju | migration/precheck.go | SourcePrecheck | func SourcePrecheck(
backend PrecheckBackend,
modelPresence ModelPresence,
controllerPresence ModelPresence,
) error {
ctx := precheckContext{backend, modelPresence}
if err := ctx.checkModel(); err != nil {
return errors.Trace(err)
}
if err := ctx.checkMachines(); err != nil {
return errors.Trace(err)
}
appUnits, err := ctx.checkApplications()
if err != nil {
return errors.Trace(err)
}
if err := ctx.checkRelations(appUnits); err != nil {
return errors.Trace(err)
}
if cleanupNeeded, err := backend.NeedsCleanup(); err != nil {
return errors.Annotate(err, "checking cleanups")
} else if cleanupNeeded {
return errors.New("cleanup needed")
}
// Check the source controller.
controllerBackend, err := backend.ControllerBackend()
if err != nil {
return errors.Trace(err)
}
controllerCtx := precheckContext{controllerBackend, controllerPresence}
if err := controllerCtx.checkController(); err != nil {
return errors.Annotate(err, "controller")
}
return nil
} | go | func SourcePrecheck(
backend PrecheckBackend,
modelPresence ModelPresence,
controllerPresence ModelPresence,
) error {
ctx := precheckContext{backend, modelPresence}
if err := ctx.checkModel(); err != nil {
return errors.Trace(err)
}
if err := ctx.checkMachines(); err != nil {
return errors.Trace(err)
}
appUnits, err := ctx.checkApplications()
if err != nil {
return errors.Trace(err)
}
if err := ctx.checkRelations(appUnits); err != nil {
return errors.Trace(err)
}
if cleanupNeeded, err := backend.NeedsCleanup(); err != nil {
return errors.Annotate(err, "checking cleanups")
} else if cleanupNeeded {
return errors.New("cleanup needed")
}
// Check the source controller.
controllerBackend, err := backend.ControllerBackend()
if err != nil {
return errors.Trace(err)
}
controllerCtx := precheckContext{controllerBackend, controllerPresence}
if err := controllerCtx.checkController(); err != nil {
return errors.Annotate(err, "controller")
}
return nil
} | [
"func",
"SourcePrecheck",
"(",
"backend",
"PrecheckBackend",
",",
"modelPresence",
"ModelPresence",
",",
"controllerPresence",
"ModelPresence",
",",
")",
"error",
"{",
"ctx",
":=",
"precheckContext",
"{",
"backend",
",",
"modelPresence",
"}",
"\n",
"if",
"err",
":=",
"ctx",
".",
"checkModel",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"ctx",
".",
"checkMachines",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"appUnits",
",",
"err",
":=",
"ctx",
".",
"checkApplications",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"ctx",
".",
"checkRelations",
"(",
"appUnits",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"cleanupNeeded",
",",
"err",
":=",
"backend",
".",
"NeedsCleanup",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"cleanupNeeded",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Check the source controller.",
"controllerBackend",
",",
"err",
":=",
"backend",
".",
"ControllerBackend",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"controllerCtx",
":=",
"precheckContext",
"{",
"controllerBackend",
",",
"controllerPresence",
"}",
"\n",
"if",
"err",
":=",
"controllerCtx",
".",
"checkController",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SourcePrecheck checks the state of the source controller to make
// sure that the preconditions for model migration are met. The
// backend provided must be for the model to be migrated. | [
"SourcePrecheck",
"checks",
"the",
"state",
"of",
"the",
"source",
"controller",
"to",
"make",
"sure",
"that",
"the",
"preconditions",
"for",
"model",
"migration",
"are",
"met",
".",
"The",
"backend",
"provided",
"must",
"be",
"for",
"the",
"model",
"to",
"be",
"migrated",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/migration/precheck.go#L118-L157 |
5,129 | juju/juju | migration/precheck.go | TargetPrecheck | func TargetPrecheck(backend PrecheckBackend, pool Pool, modelInfo coremigration.ModelInfo, presence ModelPresence) error {
if err := modelInfo.Validate(); err != nil {
return errors.Trace(err)
}
// This check is necessary because there is a window between the
// REAP phase and then end of the DONE phase where a model's
// documents have been deleted but the migration isn't quite done
// yet. Migrating a model back into the controller during this
// window can upset the migrationmaster worker.
//
// See also https://lpad.tv/1611391
if migrating, err := backend.IsMigrationActive(modelInfo.UUID); err != nil {
return errors.Annotate(err, "checking for active migration")
} else if migrating {
return errors.New("model is being migrated out of target controller")
}
controllerVersion, err := backend.AgentVersion()
if err != nil {
return errors.Annotate(err, "retrieving model version")
}
if controllerVersion.Compare(modelInfo.AgentVersion) < 0 {
return errors.Errorf("model has higher version than target controller (%s > %s)",
modelInfo.AgentVersion, controllerVersion)
}
if !controllerVersionCompatible(modelInfo.ControllerAgentVersion, controllerVersion) {
return errors.Errorf("source controller has higher version than target controller (%s > %s)",
modelInfo.ControllerAgentVersion, controllerVersion)
}
controllerCtx := precheckContext{backend, presence}
if err := controllerCtx.checkController(); err != nil {
return errors.Trace(err)
}
// Check for conflicts with existing models
modelUUIDs, err := backend.AllModelUUIDs()
if err != nil {
return errors.Annotate(err, "retrieving models")
}
for _, modelUUID := range modelUUIDs {
model, release, err := pool.GetModel(modelUUID)
if err != nil {
return errors.Trace(err)
}
defer release()
// If the model is importing then it's probably left behind
// from a previous migration attempt. It will be removed
// before the next import.
if model.UUID() == modelInfo.UUID && model.MigrationMode() != state.MigrationModeImporting {
return errors.Errorf("model with same UUID already exists (%s)", modelInfo.UUID)
}
if model.Name() == modelInfo.Name && model.Owner() == modelInfo.Owner {
return errors.Errorf("model named %q already exists", model.Name())
}
}
return nil
} | go | func TargetPrecheck(backend PrecheckBackend, pool Pool, modelInfo coremigration.ModelInfo, presence ModelPresence) error {
if err := modelInfo.Validate(); err != nil {
return errors.Trace(err)
}
// This check is necessary because there is a window between the
// REAP phase and then end of the DONE phase where a model's
// documents have been deleted but the migration isn't quite done
// yet. Migrating a model back into the controller during this
// window can upset the migrationmaster worker.
//
// See also https://lpad.tv/1611391
if migrating, err := backend.IsMigrationActive(modelInfo.UUID); err != nil {
return errors.Annotate(err, "checking for active migration")
} else if migrating {
return errors.New("model is being migrated out of target controller")
}
controllerVersion, err := backend.AgentVersion()
if err != nil {
return errors.Annotate(err, "retrieving model version")
}
if controllerVersion.Compare(modelInfo.AgentVersion) < 0 {
return errors.Errorf("model has higher version than target controller (%s > %s)",
modelInfo.AgentVersion, controllerVersion)
}
if !controllerVersionCompatible(modelInfo.ControllerAgentVersion, controllerVersion) {
return errors.Errorf("source controller has higher version than target controller (%s > %s)",
modelInfo.ControllerAgentVersion, controllerVersion)
}
controllerCtx := precheckContext{backend, presence}
if err := controllerCtx.checkController(); err != nil {
return errors.Trace(err)
}
// Check for conflicts with existing models
modelUUIDs, err := backend.AllModelUUIDs()
if err != nil {
return errors.Annotate(err, "retrieving models")
}
for _, modelUUID := range modelUUIDs {
model, release, err := pool.GetModel(modelUUID)
if err != nil {
return errors.Trace(err)
}
defer release()
// If the model is importing then it's probably left behind
// from a previous migration attempt. It will be removed
// before the next import.
if model.UUID() == modelInfo.UUID && model.MigrationMode() != state.MigrationModeImporting {
return errors.Errorf("model with same UUID already exists (%s)", modelInfo.UUID)
}
if model.Name() == modelInfo.Name && model.Owner() == modelInfo.Owner {
return errors.Errorf("model named %q already exists", model.Name())
}
}
return nil
} | [
"func",
"TargetPrecheck",
"(",
"backend",
"PrecheckBackend",
",",
"pool",
"Pool",
",",
"modelInfo",
"coremigration",
".",
"ModelInfo",
",",
"presence",
"ModelPresence",
")",
"error",
"{",
"if",
"err",
":=",
"modelInfo",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// This check is necessary because there is a window between the",
"// REAP phase and then end of the DONE phase where a model's",
"// documents have been deleted but the migration isn't quite done",
"// yet. Migrating a model back into the controller during this",
"// window can upset the migrationmaster worker.",
"//",
"// See also https://lpad.tv/1611391",
"if",
"migrating",
",",
"err",
":=",
"backend",
".",
"IsMigrationActive",
"(",
"modelInfo",
".",
"UUID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"migrating",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"controllerVersion",
",",
"err",
":=",
"backend",
".",
"AgentVersion",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"controllerVersion",
".",
"Compare",
"(",
"modelInfo",
".",
"AgentVersion",
")",
"<",
"0",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"modelInfo",
".",
"AgentVersion",
",",
"controllerVersion",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"controllerVersionCompatible",
"(",
"modelInfo",
".",
"ControllerAgentVersion",
",",
"controllerVersion",
")",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"modelInfo",
".",
"ControllerAgentVersion",
",",
"controllerVersion",
")",
"\n",
"}",
"\n\n",
"controllerCtx",
":=",
"precheckContext",
"{",
"backend",
",",
"presence",
"}",
"\n",
"if",
"err",
":=",
"controllerCtx",
".",
"checkController",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Check for conflicts with existing models",
"modelUUIDs",
",",
"err",
":=",
"backend",
".",
"AllModelUUIDs",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"modelUUID",
":=",
"range",
"modelUUIDs",
"{",
"model",
",",
"release",
",",
"err",
":=",
"pool",
".",
"GetModel",
"(",
"modelUUID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"release",
"(",
")",
"\n\n",
"// If the model is importing then it's probably left behind",
"// from a previous migration attempt. It will be removed",
"// before the next import.",
"if",
"model",
".",
"UUID",
"(",
")",
"==",
"modelInfo",
".",
"UUID",
"&&",
"model",
".",
"MigrationMode",
"(",
")",
"!=",
"state",
".",
"MigrationModeImporting",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"modelInfo",
".",
"UUID",
")",
"\n",
"}",
"\n",
"if",
"model",
".",
"Name",
"(",
")",
"==",
"modelInfo",
".",
"Name",
"&&",
"model",
".",
"Owner",
"(",
")",
"==",
"modelInfo",
".",
"Owner",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"model",
".",
"Name",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // TargetPrecheck checks the state of the target controller to make
// sure that the preconditions for model migration are met. The
// backend provided must be for the target controller. | [
"TargetPrecheck",
"checks",
"the",
"state",
"of",
"the",
"target",
"controller",
"to",
"make",
"sure",
"that",
"the",
"preconditions",
"for",
"model",
"migration",
"are",
"met",
".",
"The",
"backend",
"provided",
"must",
"be",
"for",
"the",
"target",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/migration/precheck.go#L190-L252 |
5,130 | juju/juju | worker/metrics/spool/metrics.go | IsMetricsDataError | func IsMetricsDataError(err error) bool {
_, ok := errors.Cause(err).(*errMetricsData)
return ok
} | go | func IsMetricsDataError(err error) bool {
_, ok := errors.Cause(err).(*errMetricsData)
return ok
} | [
"func",
"IsMetricsDataError",
"(",
"err",
"error",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
".",
"(",
"*",
"errMetricsData",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsMetricsDataError returns true if the error
// cause is errMetricsData. | [
"IsMetricsDataError",
"returns",
"true",
"if",
"the",
"error",
"cause",
"is",
"errMetricsData",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/metrics.go#L34-L37 |
5,131 | juju/juju | worker/metrics/spool/metrics.go | APIMetricBatch | func APIMetricBatch(batch MetricBatch) params.MetricBatchParam {
metrics := make([]params.Metric, len(batch.Metrics))
for i, metric := range batch.Metrics {
metrics[i] = params.Metric{
Key: metric.Key,
Value: metric.Value,
Time: metric.Time,
Labels: metric.Labels,
}
}
return params.MetricBatchParam{
Tag: batch.UnitTag,
Batch: params.MetricBatch{
UUID: batch.UUID,
CharmURL: batch.CharmURL,
Created: batch.Created,
Metrics: metrics,
},
}
} | go | func APIMetricBatch(batch MetricBatch) params.MetricBatchParam {
metrics := make([]params.Metric, len(batch.Metrics))
for i, metric := range batch.Metrics {
metrics[i] = params.Metric{
Key: metric.Key,
Value: metric.Value,
Time: metric.Time,
Labels: metric.Labels,
}
}
return params.MetricBatchParam{
Tag: batch.UnitTag,
Batch: params.MetricBatch{
UUID: batch.UUID,
CharmURL: batch.CharmURL,
Created: batch.Created,
Metrics: metrics,
},
}
} | [
"func",
"APIMetricBatch",
"(",
"batch",
"MetricBatch",
")",
"params",
".",
"MetricBatchParam",
"{",
"metrics",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"Metric",
",",
"len",
"(",
"batch",
".",
"Metrics",
")",
")",
"\n",
"for",
"i",
",",
"metric",
":=",
"range",
"batch",
".",
"Metrics",
"{",
"metrics",
"[",
"i",
"]",
"=",
"params",
".",
"Metric",
"{",
"Key",
":",
"metric",
".",
"Key",
",",
"Value",
":",
"metric",
".",
"Value",
",",
"Time",
":",
"metric",
".",
"Time",
",",
"Labels",
":",
"metric",
".",
"Labels",
",",
"}",
"\n",
"}",
"\n",
"return",
"params",
".",
"MetricBatchParam",
"{",
"Tag",
":",
"batch",
".",
"UnitTag",
",",
"Batch",
":",
"params",
".",
"MetricBatch",
"{",
"UUID",
":",
"batch",
".",
"UUID",
",",
"CharmURL",
":",
"batch",
".",
"CharmURL",
",",
"Created",
":",
"batch",
".",
"Created",
",",
"Metrics",
":",
"metrics",
",",
"}",
",",
"}",
"\n",
"}"
] | // APIMetricBatch converts the specified MetricBatch to a params.MetricBatch,
// which can then be sent to the controller. | [
"APIMetricBatch",
"converts",
"the",
"specified",
"MetricBatch",
"to",
"a",
"params",
".",
"MetricBatch",
"which",
"can",
"then",
"be",
"sent",
"to",
"the",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/metrics.go#L100-L119 |
5,132 | juju/juju | worker/metrics/spool/metrics.go | NewJSONMetricRecorder | func NewJSONMetricRecorder(config MetricRecorderConfig) (rec *JSONMetricRecorder, rErr error) {
mbUUID, err := utils.NewUUID()
if err != nil {
return nil, errors.Trace(err)
}
recorder := &JSONMetricRecorder{
spoolDir: config.SpoolDir,
uuid: mbUUID,
charmURL: config.CharmURL,
// TODO(fwereade): 2016-03-17 lp:1558657
created: time.Now().UTC(),
validMetrics: config.Metrics,
unitTag: config.UnitTag,
}
if err := recorder.open(); err != nil {
return nil, errors.Trace(err)
}
return recorder, nil
} | go | func NewJSONMetricRecorder(config MetricRecorderConfig) (rec *JSONMetricRecorder, rErr error) {
mbUUID, err := utils.NewUUID()
if err != nil {
return nil, errors.Trace(err)
}
recorder := &JSONMetricRecorder{
spoolDir: config.SpoolDir,
uuid: mbUUID,
charmURL: config.CharmURL,
// TODO(fwereade): 2016-03-17 lp:1558657
created: time.Now().UTC(),
validMetrics: config.Metrics,
unitTag: config.UnitTag,
}
if err := recorder.open(); err != nil {
return nil, errors.Trace(err)
}
return recorder, nil
} | [
"func",
"NewJSONMetricRecorder",
"(",
"config",
"MetricRecorderConfig",
")",
"(",
"rec",
"*",
"JSONMetricRecorder",
",",
"rErr",
"error",
")",
"{",
"mbUUID",
",",
"err",
":=",
"utils",
".",
"NewUUID",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"recorder",
":=",
"&",
"JSONMetricRecorder",
"{",
"spoolDir",
":",
"config",
".",
"SpoolDir",
",",
"uuid",
":",
"mbUUID",
",",
"charmURL",
":",
"config",
".",
"CharmURL",
",",
"// TODO(fwereade): 2016-03-17 lp:1558657",
"created",
":",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
",",
"validMetrics",
":",
"config",
".",
"Metrics",
",",
"unitTag",
":",
"config",
".",
"UnitTag",
",",
"}",
"\n",
"if",
"err",
":=",
"recorder",
".",
"open",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"recorder",
",",
"nil",
"\n",
"}"
] | // NewJSONMetricRecorder creates a new JSON metrics recorder. | [
"NewJSONMetricRecorder",
"creates",
"a",
"new",
"JSON",
"metrics",
"recorder",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/metrics.go#L154-L173 |
5,133 | juju/juju | worker/metrics/spool/metrics.go | Close | func (m *JSONMetricRecorder) Close() error {
m.lock.Lock()
defer m.lock.Unlock()
err := m.file.Close()
if err != nil {
return errors.Trace(err)
}
// We have an exclusive lock on this metric batch here, because
// metricsFile.Close was able to rename the final filename atomically.
//
// Now write the meta file so that JSONMetricReader discovers a finished
// pair of files.
err = m.recordMetaData()
if err != nil {
return errors.Trace(err)
}
return nil
} | go | func (m *JSONMetricRecorder) Close() error {
m.lock.Lock()
defer m.lock.Unlock()
err := m.file.Close()
if err != nil {
return errors.Trace(err)
}
// We have an exclusive lock on this metric batch here, because
// metricsFile.Close was able to rename the final filename atomically.
//
// Now write the meta file so that JSONMetricReader discovers a finished
// pair of files.
err = m.recordMetaData()
if err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"(",
"m",
"*",
"JSONMetricRecorder",
")",
"Close",
"(",
")",
"error",
"{",
"m",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"err",
":=",
"m",
".",
"file",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// We have an exclusive lock on this metric batch here, because",
"// metricsFile.Close was able to rename the final filename atomically.",
"//",
"// Now write the meta file so that JSONMetricReader discovers a finished",
"// pair of files.",
"err",
"=",
"m",
".",
"recordMetaData",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Close implements the MetricsRecorder interface. | [
"Close",
"implements",
"the",
"MetricsRecorder",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/metrics.go#L176-L196 |
5,134 | juju/juju | worker/metrics/spool/metrics.go | AddMetric | func (m *JSONMetricRecorder) AddMetric(
key, value string, created time.Time, labels map[string]string) (err error) {
defer func() {
if err != nil {
err = &errMetricsData{err}
}
}()
err = m.validateMetric(key, value)
if err != nil {
return errors.Trace(err)
}
m.lock.Lock()
defer m.lock.Unlock()
return errors.Trace(m.enc.Encode(jujuc.Metric{
Key: key,
Value: value,
Time: created,
Labels: labels,
}))
} | go | func (m *JSONMetricRecorder) AddMetric(
key, value string, created time.Time, labels map[string]string) (err error) {
defer func() {
if err != nil {
err = &errMetricsData{err}
}
}()
err = m.validateMetric(key, value)
if err != nil {
return errors.Trace(err)
}
m.lock.Lock()
defer m.lock.Unlock()
return errors.Trace(m.enc.Encode(jujuc.Metric{
Key: key,
Value: value,
Time: created,
Labels: labels,
}))
} | [
"func",
"(",
"m",
"*",
"JSONMetricRecorder",
")",
"AddMetric",
"(",
"key",
",",
"value",
"string",
",",
"created",
"time",
".",
"Time",
",",
"labels",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"&",
"errMetricsData",
"{",
"err",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"err",
"=",
"m",
".",
"validateMetric",
"(",
"key",
",",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"m",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"m",
".",
"enc",
".",
"Encode",
"(",
"jujuc",
".",
"Metric",
"{",
"Key",
":",
"key",
",",
"Value",
":",
"value",
",",
"Time",
":",
"created",
",",
"Labels",
":",
"labels",
",",
"}",
")",
")",
"\n",
"}"
] | // AddMetric implements the MetricsRecorder interface. | [
"AddMetric",
"implements",
"the",
"MetricsRecorder",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/metrics.go#L199-L218 |
5,135 | juju/juju | worker/metrics/spool/metrics.go | IsDeclaredMetric | func (m *JSONMetricRecorder) IsDeclaredMetric(key string) bool {
_, ok := m.validMetrics[key]
return ok
} | go | func (m *JSONMetricRecorder) IsDeclaredMetric(key string) bool {
_, ok := m.validMetrics[key]
return ok
} | [
"func",
"(",
"m",
"*",
"JSONMetricRecorder",
")",
"IsDeclaredMetric",
"(",
"key",
"string",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"m",
".",
"validMetrics",
"[",
"key",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsDeclaredMetric returns true if the metric recorder is permitted to store this metric.
// Returns false if the uniter using this recorder doesn't define this metric. | [
"IsDeclaredMetric",
"returns",
"true",
"if",
"the",
"metric",
"recorder",
"is",
"permitted",
"to",
"store",
"this",
"metric",
".",
"Returns",
"false",
"if",
"the",
"uniter",
"using",
"this",
"recorder",
"doesn",
"t",
"define",
"this",
"metric",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/metrics.go#L241-L244 |
5,136 | juju/juju | worker/metrics/spool/metrics.go | NewJSONMetricReader | func NewJSONMetricReader(spoolDir string) (*JSONMetricReader, error) {
if _, err := os.Stat(spoolDir); err != nil {
return nil, errors.Annotatef(err, "failed to open spool directory %q", spoolDir)
}
return &JSONMetricReader{
dir: spoolDir,
}, nil
} | go | func NewJSONMetricReader(spoolDir string) (*JSONMetricReader, error) {
if _, err := os.Stat(spoolDir); err != nil {
return nil, errors.Annotatef(err, "failed to open spool directory %q", spoolDir)
}
return &JSONMetricReader{
dir: spoolDir,
}, nil
} | [
"func",
"NewJSONMetricReader",
"(",
"spoolDir",
"string",
")",
"(",
"*",
"JSONMetricReader",
",",
"error",
")",
"{",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"spoolDir",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"spoolDir",
")",
"\n",
"}",
"\n",
"return",
"&",
"JSONMetricReader",
"{",
"dir",
":",
"spoolDir",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewJSONMetricsReader creates a new JSON metrics reader for the specified spool directory. | [
"NewJSONMetricsReader",
"creates",
"a",
"new",
"JSON",
"metrics",
"reader",
"for",
"the",
"specified",
"spool",
"directory",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/metrics.go#L312-L319 |
5,137 | juju/juju | worker/metrics/spool/metrics.go | Read | func (r *JSONMetricReader) Read() (_ []MetricBatch, err error) {
defer func() {
if err != nil {
err = &errMetricsData{err}
}
}()
var batches []MetricBatch
walker := func(path string, info os.FileInfo, err error) error {
if err != nil {
return errors.Trace(err)
}
if info.IsDir() && path != r.dir {
return filepath.SkipDir
} else if !strings.HasSuffix(info.Name(), ".meta") {
return nil
}
batch, err := decodeBatch(path)
if err != nil {
return errors.Trace(err)
}
batch.Metrics, err = decodeMetrics(filepath.Join(r.dir, batch.UUID))
if err != nil {
return errors.Trace(err)
}
if len(batch.Metrics) > 0 {
batches = append(batches, batch)
}
return nil
}
if err := filepath.Walk(r.dir, walker); err != nil {
return nil, errors.Trace(err)
}
return batches, nil
} | go | func (r *JSONMetricReader) Read() (_ []MetricBatch, err error) {
defer func() {
if err != nil {
err = &errMetricsData{err}
}
}()
var batches []MetricBatch
walker := func(path string, info os.FileInfo, err error) error {
if err != nil {
return errors.Trace(err)
}
if info.IsDir() && path != r.dir {
return filepath.SkipDir
} else if !strings.HasSuffix(info.Name(), ".meta") {
return nil
}
batch, err := decodeBatch(path)
if err != nil {
return errors.Trace(err)
}
batch.Metrics, err = decodeMetrics(filepath.Join(r.dir, batch.UUID))
if err != nil {
return errors.Trace(err)
}
if len(batch.Metrics) > 0 {
batches = append(batches, batch)
}
return nil
}
if err := filepath.Walk(r.dir, walker); err != nil {
return nil, errors.Trace(err)
}
return batches, nil
} | [
"func",
"(",
"r",
"*",
"JSONMetricReader",
")",
"Read",
"(",
")",
"(",
"_",
"[",
"]",
"MetricBatch",
",",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"&",
"errMetricsData",
"{",
"err",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"var",
"batches",
"[",
"]",
"MetricBatch",
"\n\n",
"walker",
":=",
"func",
"(",
"path",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"info",
".",
"IsDir",
"(",
")",
"&&",
"path",
"!=",
"r",
".",
"dir",
"{",
"return",
"filepath",
".",
"SkipDir",
"\n",
"}",
"else",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"info",
".",
"Name",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"batch",
",",
"err",
":=",
"decodeBatch",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"batch",
".",
"Metrics",
",",
"err",
"=",
"decodeMetrics",
"(",
"filepath",
".",
"Join",
"(",
"r",
".",
"dir",
",",
"batch",
".",
"UUID",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"batch",
".",
"Metrics",
")",
">",
"0",
"{",
"batches",
"=",
"append",
"(",
"batches",
",",
"batch",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"filepath",
".",
"Walk",
"(",
"r",
".",
"dir",
",",
"walker",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"batches",
",",
"nil",
"\n",
"}"
] | // Read implements the MetricsReader interface.
// Due to the way the batches are stored in the file system,
// they will be returned in an arbitrary order. This does not affect the behavior. | [
"Read",
"implements",
"the",
"MetricsReader",
"interface",
".",
"Due",
"to",
"the",
"way",
"the",
"batches",
"are",
"stored",
"in",
"the",
"file",
"system",
"they",
"will",
"be",
"returned",
"in",
"an",
"arbitrary",
"order",
".",
"This",
"does",
"not",
"affect",
"the",
"behavior",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/metrics.go#L324-L360 |
5,138 | juju/juju | worker/metrics/spool/metrics.go | Remove | func (r *JSONMetricReader) Remove(uuid string) error {
metaFile := filepath.Join(r.dir, fmt.Sprintf("%s.meta", uuid))
dataFile := filepath.Join(r.dir, uuid)
err := os.Remove(metaFile)
if err != nil && !os.IsNotExist(err) {
return errors.Trace(err)
}
err = os.Remove(dataFile)
if err != nil {
return errors.Trace(err)
}
return nil
} | go | func (r *JSONMetricReader) Remove(uuid string) error {
metaFile := filepath.Join(r.dir, fmt.Sprintf("%s.meta", uuid))
dataFile := filepath.Join(r.dir, uuid)
err := os.Remove(metaFile)
if err != nil && !os.IsNotExist(err) {
return errors.Trace(err)
}
err = os.Remove(dataFile)
if err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"(",
"r",
"*",
"JSONMetricReader",
")",
"Remove",
"(",
"uuid",
"string",
")",
"error",
"{",
"metaFile",
":=",
"filepath",
".",
"Join",
"(",
"r",
".",
"dir",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"uuid",
")",
")",
"\n",
"dataFile",
":=",
"filepath",
".",
"Join",
"(",
"r",
".",
"dir",
",",
"uuid",
")",
"\n",
"err",
":=",
"os",
".",
"Remove",
"(",
"metaFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"os",
".",
"Remove",
"(",
"dataFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Remove implements the MetricsReader interface. | [
"Remove",
"implements",
"the",
"MetricsReader",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/metrics.go#L363-L375 |
5,139 | juju/juju | resource/resourceadapters/deploy.go | AddPendingResources | func (cl *deployClient) AddPendingResources(applicationID string, chID charmstore.CharmID, csMac *macaroon.Macaroon, resources []charmresource.Resource) ([]string, error) {
return cl.Client.AddPendingResources(client.AddPendingResourcesArgs{
ApplicationID: applicationID,
CharmID: chID,
CharmStoreMacaroon: csMac,
Resources: resources,
})
} | go | func (cl *deployClient) AddPendingResources(applicationID string, chID charmstore.CharmID, csMac *macaroon.Macaroon, resources []charmresource.Resource) ([]string, error) {
return cl.Client.AddPendingResources(client.AddPendingResourcesArgs{
ApplicationID: applicationID,
CharmID: chID,
CharmStoreMacaroon: csMac,
Resources: resources,
})
} | [
"func",
"(",
"cl",
"*",
"deployClient",
")",
"AddPendingResources",
"(",
"applicationID",
"string",
",",
"chID",
"charmstore",
".",
"CharmID",
",",
"csMac",
"*",
"macaroon",
".",
"Macaroon",
",",
"resources",
"[",
"]",
"charmresource",
".",
"Resource",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"return",
"cl",
".",
"Client",
".",
"AddPendingResources",
"(",
"client",
".",
"AddPendingResourcesArgs",
"{",
"ApplicationID",
":",
"applicationID",
",",
"CharmID",
":",
"chID",
",",
"CharmStoreMacaroon",
":",
"csMac",
",",
"Resources",
":",
"resources",
",",
"}",
")",
"\n",
"}"
] | // AddPendingResources adds pending metadata for store-based resources. | [
"AddPendingResources",
"adds",
"pending",
"metadata",
"for",
"store",
"-",
"based",
"resources",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/resourceadapters/deploy.go#L82-L89 |
5,140 | juju/juju | provider/gce/google/raw.go | checkOperation | func (rc *rawConn) checkOperation(projectID string, op *compute.Operation) (*compute.Operation, error) {
var call opDoer
if op.Zone != "" {
zoneName := path.Base(op.Zone)
call = rc.ZoneOperations.Get(projectID, zoneName, op.Name)
} else if op.Region != "" {
region := path.Base(op.Region)
call = rc.RegionOperations.Get(projectID, region, op.Name)
} else {
call = rc.GlobalOperations.Get(projectID, op.Name)
}
operation, err := doOpCall(call)
if err != nil {
return nil, errors.Annotatef(err, "request for GCE operation %q failed", op.Name)
}
return operation, nil
} | go | func (rc *rawConn) checkOperation(projectID string, op *compute.Operation) (*compute.Operation, error) {
var call opDoer
if op.Zone != "" {
zoneName := path.Base(op.Zone)
call = rc.ZoneOperations.Get(projectID, zoneName, op.Name)
} else if op.Region != "" {
region := path.Base(op.Region)
call = rc.RegionOperations.Get(projectID, region, op.Name)
} else {
call = rc.GlobalOperations.Get(projectID, op.Name)
}
operation, err := doOpCall(call)
if err != nil {
return nil, errors.Annotatef(err, "request for GCE operation %q failed", op.Name)
}
return operation, nil
} | [
"func",
"(",
"rc",
"*",
"rawConn",
")",
"checkOperation",
"(",
"projectID",
"string",
",",
"op",
"*",
"compute",
".",
"Operation",
")",
"(",
"*",
"compute",
".",
"Operation",
",",
"error",
")",
"{",
"var",
"call",
"opDoer",
"\n",
"if",
"op",
".",
"Zone",
"!=",
"\"",
"\"",
"{",
"zoneName",
":=",
"path",
".",
"Base",
"(",
"op",
".",
"Zone",
")",
"\n",
"call",
"=",
"rc",
".",
"ZoneOperations",
".",
"Get",
"(",
"projectID",
",",
"zoneName",
",",
"op",
".",
"Name",
")",
"\n",
"}",
"else",
"if",
"op",
".",
"Region",
"!=",
"\"",
"\"",
"{",
"region",
":=",
"path",
".",
"Base",
"(",
"op",
".",
"Region",
")",
"\n",
"call",
"=",
"rc",
".",
"RegionOperations",
".",
"Get",
"(",
"projectID",
",",
"region",
",",
"op",
".",
"Name",
")",
"\n",
"}",
"else",
"{",
"call",
"=",
"rc",
".",
"GlobalOperations",
".",
"Get",
"(",
"projectID",
",",
"op",
".",
"Name",
")",
"\n",
"}",
"\n\n",
"operation",
",",
"err",
":=",
"doOpCall",
"(",
"call",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"op",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"operation",
",",
"nil",
"\n",
"}"
] | // checkOperation requests a new copy of the given operation from the
// GCE API and returns it. The new copy will have the operation's
// current status. | [
"checkOperation",
"requests",
"a",
"new",
"copy",
"of",
"the",
"given",
"operation",
"from",
"the",
"GCE",
"API",
"and",
"returns",
"it",
".",
"The",
"new",
"copy",
"will",
"have",
"the",
"operation",
"s",
"current",
"status",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/raw.go#L318-L335 |
5,141 | juju/juju | provider/gce/google/raw.go | ListMachineTypes | func (rc *rawConn) ListMachineTypes(projectID, zone string) (*compute.MachineTypeList, error) {
op := rc.MachineTypes.List(projectID, zone)
machines, err := op.Do()
if err != nil {
return nil, errors.Annotatef(err, "listing machine types for project %q and zone %q", projectID, zone)
}
return machines, nil
} | go | func (rc *rawConn) ListMachineTypes(projectID, zone string) (*compute.MachineTypeList, error) {
op := rc.MachineTypes.List(projectID, zone)
machines, err := op.Do()
if err != nil {
return nil, errors.Annotatef(err, "listing machine types for project %q and zone %q", projectID, zone)
}
return machines, nil
} | [
"func",
"(",
"rc",
"*",
"rawConn",
")",
"ListMachineTypes",
"(",
"projectID",
",",
"zone",
"string",
")",
"(",
"*",
"compute",
".",
"MachineTypeList",
",",
"error",
")",
"{",
"op",
":=",
"rc",
".",
"MachineTypes",
".",
"List",
"(",
"projectID",
",",
"zone",
")",
"\n",
"machines",
",",
"err",
":=",
"op",
".",
"Do",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"projectID",
",",
"zone",
")",
"\n",
"}",
"\n",
"return",
"machines",
",",
"nil",
"\n",
"}"
] | // ListMachineTypes returns a list of machines available in the project and zone provided. | [
"ListMachineTypes",
"returns",
"a",
"list",
"of",
"machines",
"available",
"in",
"the",
"project",
"and",
"zone",
"provided",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/raw.go#L378-L385 |
5,142 | juju/juju | worker/modelcache/worker.go | Validate | func (c *Config) Validate() error {
if c.Logger == nil {
return errors.NotValidf("missing logger")
}
if c.WatcherFactory == nil {
return errors.NotValidf("missing watcher factory")
}
if c.PrometheusRegisterer == nil {
return errors.NotValidf("missing prometheus registerer")
}
if c.Cleanup == nil {
return errors.NotValidf("missing cleanup func")
}
return nil
} | go | func (c *Config) Validate() error {
if c.Logger == nil {
return errors.NotValidf("missing logger")
}
if c.WatcherFactory == nil {
return errors.NotValidf("missing watcher factory")
}
if c.PrometheusRegisterer == nil {
return errors.NotValidf("missing prometheus registerer")
}
if c.Cleanup == nil {
return errors.NotValidf("missing cleanup func")
}
return nil
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"c",
".",
"Logger",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"WatcherFactory",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"PrometheusRegisterer",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"Cleanup",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate ensures all the necessary values are specified | [
"Validate",
"ensures",
"all",
"the",
"necessary",
"values",
"are",
"specified"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/modelcache/worker.go#L50-L64 |
5,143 | juju/juju | worker/modelcache/worker.go | NewWorker | func NewWorker(config Config) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
w := &cacheWorker{
config: config,
changes: make(chan interface{}),
}
controller, err := cache.NewController(
cache.ControllerConfig{
Changes: w.changes,
Notify: config.Notify,
})
if err != nil {
return nil, errors.Trace(err)
}
w.controller = controller
if err := catacomb.Invoke(catacomb.Plan{
Site: &w.catacomb,
Work: w.loop,
Init: []worker.Worker{w.controller},
}); err != nil {
return nil, errors.Trace(err)
}
return w, nil
} | go | func NewWorker(config Config) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
w := &cacheWorker{
config: config,
changes: make(chan interface{}),
}
controller, err := cache.NewController(
cache.ControllerConfig{
Changes: w.changes,
Notify: config.Notify,
})
if err != nil {
return nil, errors.Trace(err)
}
w.controller = controller
if err := catacomb.Invoke(catacomb.Plan{
Site: &w.catacomb,
Work: w.loop,
Init: []worker.Worker{w.controller},
}); err != nil {
return nil, errors.Trace(err)
}
return w, nil
} | [
"func",
"NewWorker",
"(",
"config",
"Config",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"if",
"err",
":=",
"config",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"w",
":=",
"&",
"cacheWorker",
"{",
"config",
":",
"config",
",",
"changes",
":",
"make",
"(",
"chan",
"interface",
"{",
"}",
")",
",",
"}",
"\n",
"controller",
",",
"err",
":=",
"cache",
".",
"NewController",
"(",
"cache",
".",
"ControllerConfig",
"{",
"Changes",
":",
"w",
".",
"changes",
",",
"Notify",
":",
"config",
".",
"Notify",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"w",
".",
"controller",
"=",
"controller",
"\n",
"if",
"err",
":=",
"catacomb",
".",
"Invoke",
"(",
"catacomb",
".",
"Plan",
"{",
"Site",
":",
"&",
"w",
".",
"catacomb",
",",
"Work",
":",
"w",
".",
"loop",
",",
"Init",
":",
"[",
"]",
"worker",
".",
"Worker",
"{",
"w",
".",
"controller",
"}",
",",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"w",
",",
"nil",
"\n",
"}"
] | // NewWorker creates a new cacheWorker, and starts an
// all model watcher. | [
"NewWorker",
"creates",
"a",
"new",
"cacheWorker",
"and",
"starts",
"an",
"all",
"model",
"watcher",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/modelcache/worker.go#L77-L102 |
5,144 | juju/juju | state/upgrades.go | runForAllModelStates | func runForAllModelStates(pool *StatePool, runner func(st *State) error) error {
st := pool.SystemState()
models, closer := st.db().GetCollection(modelsC)
defer closer()
var modelDocs []bson.M
err := models.Find(nil).Select(bson.M{"_id": 1}).All(&modelDocs)
if err != nil {
return errors.Annotate(err, "failed to read models")
}
for _, modelDoc := range modelDocs {
modelUUID := modelDoc["_id"].(string)
model, err := pool.Get(modelUUID)
if err != nil {
return errors.Annotatef(err, "failed to open model %q", modelUUID)
}
defer func() {
model.Release()
}()
if err := runner(model.State); err != nil {
return errors.Annotatef(err, "model UUID %q", modelUUID)
}
}
return nil
} | go | func runForAllModelStates(pool *StatePool, runner func(st *State) error) error {
st := pool.SystemState()
models, closer := st.db().GetCollection(modelsC)
defer closer()
var modelDocs []bson.M
err := models.Find(nil).Select(bson.M{"_id": 1}).All(&modelDocs)
if err != nil {
return errors.Annotate(err, "failed to read models")
}
for _, modelDoc := range modelDocs {
modelUUID := modelDoc["_id"].(string)
model, err := pool.Get(modelUUID)
if err != nil {
return errors.Annotatef(err, "failed to open model %q", modelUUID)
}
defer func() {
model.Release()
}()
if err := runner(model.State); err != nil {
return errors.Annotatef(err, "model UUID %q", modelUUID)
}
}
return nil
} | [
"func",
"runForAllModelStates",
"(",
"pool",
"*",
"StatePool",
",",
"runner",
"func",
"(",
"st",
"*",
"State",
")",
"error",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"models",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"modelsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"modelDocs",
"[",
"]",
"bson",
".",
"M",
"\n",
"err",
":=",
"models",
".",
"Find",
"(",
"nil",
")",
".",
"Select",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"1",
"}",
")",
".",
"All",
"(",
"&",
"modelDocs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"modelDoc",
":=",
"range",
"modelDocs",
"{",
"modelUUID",
":=",
"modelDoc",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"model",
",",
"err",
":=",
"pool",
".",
"Get",
"(",
"modelUUID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"modelUUID",
")",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"model",
".",
"Release",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"if",
"err",
":=",
"runner",
"(",
"model",
".",
"State",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"modelUUID",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // runForAllModelStates will run runner function for every model passing a state
// for that model. | [
"runForAllModelStates",
"will",
"run",
"runner",
"function",
"for",
"every",
"model",
"passing",
"a",
"state",
"for",
"that",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L41-L66 |
5,145 | juju/juju | state/upgrades.go | readBsonDField | func readBsonDField(d bson.D, name string) (interface{}, bool) {
for i := range d {
field := &d[i]
if field.Name == name {
return field.Value, true
}
}
return nil, false
} | go | func readBsonDField(d bson.D, name string) (interface{}, bool) {
for i := range d {
field := &d[i]
if field.Name == name {
return field.Value, true
}
}
return nil, false
} | [
"func",
"readBsonDField",
"(",
"d",
"bson",
".",
"D",
",",
"name",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"for",
"i",
":=",
"range",
"d",
"{",
"field",
":=",
"&",
"d",
"[",
"i",
"]",
"\n",
"if",
"field",
".",
"Name",
"==",
"name",
"{",
"return",
"field",
".",
"Value",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}"
] | // readBsonDField returns the value of a given field in a bson.D. | [
"readBsonDField",
"returns",
"the",
"value",
"of",
"a",
"given",
"field",
"in",
"a",
"bson",
".",
"D",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L69-L77 |
5,146 | juju/juju | state/upgrades.go | replaceBsonDField | func replaceBsonDField(d bson.D, name string, value interface{}) error {
for i, field := range d {
if field.Name == name {
newField := field
newField.Value = value
d[i] = newField
return nil
}
}
return errors.NotFoundf("field %q", name)
} | go | func replaceBsonDField(d bson.D, name string, value interface{}) error {
for i, field := range d {
if field.Name == name {
newField := field
newField.Value = value
d[i] = newField
return nil
}
}
return errors.NotFoundf("field %q", name)
} | [
"func",
"replaceBsonDField",
"(",
"d",
"bson",
".",
"D",
",",
"name",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"for",
"i",
",",
"field",
":=",
"range",
"d",
"{",
"if",
"field",
".",
"Name",
"==",
"name",
"{",
"newField",
":=",
"field",
"\n",
"newField",
".",
"Value",
"=",
"value",
"\n",
"d",
"[",
"i",
"]",
"=",
"newField",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}"
] | // replaceBsonDField replaces a field in bson.D. | [
"replaceBsonDField",
"replaces",
"a",
"field",
"in",
"bson",
".",
"D",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L80-L90 |
5,147 | juju/juju | state/upgrades.go | RenameAddModelPermission | func RenameAddModelPermission(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(permissionsC)
defer closer()
upgradesLogger.Infof("migrating addmodel permission")
iter := coll.Find(bson.M{"access": "addmodel"}).Iter()
defer iter.Close()
var ops []txn.Op
var doc bson.M
for iter.Next(&doc) {
id, ok := doc["_id"]
if !ok {
return errors.New("no id found in permission doc")
}
ops = append(ops, txn.Op{
C: permissionsC,
Id: id,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"access", "add-model"}}}},
})
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
return st.runRawTransaction(ops)
} | go | func RenameAddModelPermission(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(permissionsC)
defer closer()
upgradesLogger.Infof("migrating addmodel permission")
iter := coll.Find(bson.M{"access": "addmodel"}).Iter()
defer iter.Close()
var ops []txn.Op
var doc bson.M
for iter.Next(&doc) {
id, ok := doc["_id"]
if !ok {
return errors.New("no id found in permission doc")
}
ops = append(ops, txn.Op{
C: permissionsC,
Id: id,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"access", "add-model"}}}},
})
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
return st.runRawTransaction(ops)
} | [
"func",
"RenameAddModelPermission",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"coll",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"permissionsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"upgradesLogger",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n\n",
"iter",
":=",
"coll",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"}",
")",
".",
"Iter",
"(",
")",
"\n",
"defer",
"iter",
".",
"Close",
"(",
")",
"\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"var",
"doc",
"bson",
".",
"M",
"\n",
"for",
"iter",
".",
"Next",
"(",
"&",
"doc",
")",
"{",
"id",
",",
"ok",
":=",
"doc",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"permissionsC",
",",
"Id",
":",
"id",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"}",
"}",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"iter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"st",
".",
"runRawTransaction",
"(",
"ops",
")",
"\n",
"}"
] | // RenameAddModelPermission renames any permissions called addmodel to add-model. | [
"RenameAddModelPermission",
"renames",
"any",
"permissions",
"called",
"addmodel",
"to",
"add",
"-",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L93-L120 |
5,148 | juju/juju | state/upgrades.go | StripLocalUserDomain | func StripLocalUserDomain(pool *StatePool) error {
st := pool.SystemState()
var ops []txn.Op
more, err := stripLocalFromFields(st, cloudCredentialsC, "_id", "owner")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, modelsC, "owner", "cloud-credential")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, usermodelnameC, "_id")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, controllerUsersC, "_id", "user", "createdby")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, modelUsersC, "_id", "user", "createdby")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, permissionsC, "_id", "subject-global-key")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, modelUserLastConnectionC, "_id", "user")
if err != nil {
return err
}
ops = append(ops, more...)
return st.runRawTransaction(ops)
} | go | func StripLocalUserDomain(pool *StatePool) error {
st := pool.SystemState()
var ops []txn.Op
more, err := stripLocalFromFields(st, cloudCredentialsC, "_id", "owner")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, modelsC, "owner", "cloud-credential")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, usermodelnameC, "_id")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, controllerUsersC, "_id", "user", "createdby")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, modelUsersC, "_id", "user", "createdby")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, permissionsC, "_id", "subject-global-key")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, modelUserLastConnectionC, "_id", "user")
if err != nil {
return err
}
ops = append(ops, more...)
return st.runRawTransaction(ops)
} | [
"func",
"StripLocalUserDomain",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"more",
",",
"err",
":=",
"stripLocalFromFields",
"(",
"st",
",",
"cloudCredentialsC",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"more",
"...",
")",
"\n\n",
"more",
",",
"err",
"=",
"stripLocalFromFields",
"(",
"st",
",",
"modelsC",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"more",
"...",
")",
"\n\n",
"more",
",",
"err",
"=",
"stripLocalFromFields",
"(",
"st",
",",
"usermodelnameC",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"more",
"...",
")",
"\n\n",
"more",
",",
"err",
"=",
"stripLocalFromFields",
"(",
"st",
",",
"controllerUsersC",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"more",
"...",
")",
"\n\n",
"more",
",",
"err",
"=",
"stripLocalFromFields",
"(",
"st",
",",
"modelUsersC",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"more",
"...",
")",
"\n\n",
"more",
",",
"err",
"=",
"stripLocalFromFields",
"(",
"st",
",",
"permissionsC",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"more",
"...",
")",
"\n\n",
"more",
",",
"err",
"=",
"stripLocalFromFields",
"(",
"st",
",",
"modelUserLastConnectionC",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"more",
"...",
")",
"\n",
"return",
"st",
".",
"runRawTransaction",
"(",
"ops",
")",
"\n",
"}"
] | // StripLocalUserDomain removes any @local suffix from any relevant document field values. | [
"StripLocalUserDomain",
"removes",
"any"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L123-L168 |
5,149 | juju/juju | state/upgrades.go | AddMigrationAttempt | func AddMigrationAttempt(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(migrationsC)
defer closer()
query := coll.Find(bson.M{"attempt": bson.M{"$exists": false}})
query = query.Select(bson.M{"_id": 1})
iter := query.Iter()
defer iter.Close()
var ops []txn.Op
var doc bson.M
for iter.Next(&doc) {
id := doc["_id"]
attempt, err := extractMigrationAttempt(id)
if err != nil {
upgradesLogger.Warningf("%s (skipping)", err)
continue
}
ops = append(ops, txn.Op{
C: migrationsC,
Id: id,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"attempt", attempt}}}},
})
}
if err := iter.Close(); err != nil {
return errors.Annotate(err, "iterating migrations")
}
return errors.Trace(st.runRawTransaction(ops))
} | go | func AddMigrationAttempt(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(migrationsC)
defer closer()
query := coll.Find(bson.M{"attempt": bson.M{"$exists": false}})
query = query.Select(bson.M{"_id": 1})
iter := query.Iter()
defer iter.Close()
var ops []txn.Op
var doc bson.M
for iter.Next(&doc) {
id := doc["_id"]
attempt, err := extractMigrationAttempt(id)
if err != nil {
upgradesLogger.Warningf("%s (skipping)", err)
continue
}
ops = append(ops, txn.Op{
C: migrationsC,
Id: id,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"attempt", attempt}}}},
})
}
if err := iter.Close(); err != nil {
return errors.Annotate(err, "iterating migrations")
}
return errors.Trace(st.runRawTransaction(ops))
} | [
"func",
"AddMigrationAttempt",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"coll",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"migrationsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"query",
":=",
"coll",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"false",
"}",
"}",
")",
"\n",
"query",
"=",
"query",
".",
"Select",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"1",
"}",
")",
"\n",
"iter",
":=",
"query",
".",
"Iter",
"(",
")",
"\n",
"defer",
"iter",
".",
"Close",
"(",
")",
"\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"var",
"doc",
"bson",
".",
"M",
"\n",
"for",
"iter",
".",
"Next",
"(",
"&",
"doc",
")",
"{",
"id",
":=",
"doc",
"[",
"\"",
"\"",
"]",
"\n",
"attempt",
",",
"err",
":=",
"extractMigrationAttempt",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"upgradesLogger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"migrationsC",
",",
"Id",
":",
"id",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"attempt",
"}",
"}",
"}",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"iter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"errors",
".",
"Trace",
"(",
"st",
".",
"runRawTransaction",
"(",
"ops",
")",
")",
"\n",
"}"
] | // AddMigrationAttempt adds an "attempt" field to migration documents
// which are missing one. | [
"AddMigrationAttempt",
"adds",
"an",
"attempt",
"field",
"to",
"migration",
"documents",
"which",
"are",
"missing",
"one",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L252-L283 |
5,150 | juju/juju | state/upgrades.go | AddLocalCharmSequences | func AddLocalCharmSequences(pool *StatePool) error {
st := pool.SystemState()
charmsColl, closer := st.db().GetRawCollection(charmsC)
defer closer()
query := bson.M{
"url": bson.M{"$regex": "^local:"},
}
var docs []bson.M
err := charmsColl.Find(query).Select(bson.M{
"_id": 1,
"life": 1,
}).All(&docs)
if err != nil {
return errors.Trace(err)
}
// model UUID -> charm URL base -> max revision
maxRevs := make(map[string]map[string]int)
var deadIds []string
for _, doc := range docs {
id, ok := doc["_id"].(string)
if !ok {
upgradesLogger.Errorf("invalid charm id: %v", doc["_id"])
continue
}
modelUUID, urlStr, ok := splitDocID(id)
if !ok {
upgradesLogger.Errorf("unable to split charm _id: %v", id)
continue
}
url, err := charm.ParseURL(urlStr)
if err != nil {
upgradesLogger.Errorf("unable to parse charm URL: %v", err)
continue
}
if _, exists := maxRevs[modelUUID]; !exists {
maxRevs[modelUUID] = make(map[string]int)
}
baseURL := url.WithRevision(-1).String()
curRev := maxRevs[modelUUID][baseURL]
if url.Revision > curRev {
maxRevs[modelUUID][baseURL] = url.Revision
}
if life, ok := doc["life"].(int); !ok {
upgradesLogger.Errorf("invalid life for charm: %s", id)
continue
} else if life == int(Dead) {
deadIds = append(deadIds, id)
}
}
sequences, closer := st.db().GetRawCollection(sequenceC)
defer closer()
for modelUUID, modelRevs := range maxRevs {
for baseURL, maxRevision := range modelRevs {
name := charmRevSeqName(baseURL)
updater := newDbSeqUpdater(sequences, modelUUID, name)
err := updater.ensure(maxRevision + 1)
if err != nil {
return errors.Annotatef(err, "setting sequence %s", name)
}
}
}
// Remove dead charm documents
var ops []txn.Op
for _, id := range deadIds {
ops = append(ops, txn.Op{
C: charmsC,
Id: id,
Remove: true,
})
}
err = st.runRawTransaction(ops)
return errors.Annotate(err, "removing dead charms")
} | go | func AddLocalCharmSequences(pool *StatePool) error {
st := pool.SystemState()
charmsColl, closer := st.db().GetRawCollection(charmsC)
defer closer()
query := bson.M{
"url": bson.M{"$regex": "^local:"},
}
var docs []bson.M
err := charmsColl.Find(query).Select(bson.M{
"_id": 1,
"life": 1,
}).All(&docs)
if err != nil {
return errors.Trace(err)
}
// model UUID -> charm URL base -> max revision
maxRevs := make(map[string]map[string]int)
var deadIds []string
for _, doc := range docs {
id, ok := doc["_id"].(string)
if !ok {
upgradesLogger.Errorf("invalid charm id: %v", doc["_id"])
continue
}
modelUUID, urlStr, ok := splitDocID(id)
if !ok {
upgradesLogger.Errorf("unable to split charm _id: %v", id)
continue
}
url, err := charm.ParseURL(urlStr)
if err != nil {
upgradesLogger.Errorf("unable to parse charm URL: %v", err)
continue
}
if _, exists := maxRevs[modelUUID]; !exists {
maxRevs[modelUUID] = make(map[string]int)
}
baseURL := url.WithRevision(-1).String()
curRev := maxRevs[modelUUID][baseURL]
if url.Revision > curRev {
maxRevs[modelUUID][baseURL] = url.Revision
}
if life, ok := doc["life"].(int); !ok {
upgradesLogger.Errorf("invalid life for charm: %s", id)
continue
} else if life == int(Dead) {
deadIds = append(deadIds, id)
}
}
sequences, closer := st.db().GetRawCollection(sequenceC)
defer closer()
for modelUUID, modelRevs := range maxRevs {
for baseURL, maxRevision := range modelRevs {
name := charmRevSeqName(baseURL)
updater := newDbSeqUpdater(sequences, modelUUID, name)
err := updater.ensure(maxRevision + 1)
if err != nil {
return errors.Annotatef(err, "setting sequence %s", name)
}
}
}
// Remove dead charm documents
var ops []txn.Op
for _, id := range deadIds {
ops = append(ops, txn.Op{
C: charmsC,
Id: id,
Remove: true,
})
}
err = st.runRawTransaction(ops)
return errors.Annotate(err, "removing dead charms")
} | [
"func",
"AddLocalCharmSequences",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"charmsColl",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"charmsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"query",
":=",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"}",
",",
"}",
"\n",
"var",
"docs",
"[",
"]",
"bson",
".",
"M",
"\n",
"err",
":=",
"charmsColl",
".",
"Find",
"(",
"query",
")",
".",
"Select",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"1",
",",
"\"",
"\"",
":",
"1",
",",
"}",
")",
".",
"All",
"(",
"&",
"docs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// model UUID -> charm URL base -> max revision",
"maxRevs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"int",
")",
"\n",
"var",
"deadIds",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"doc",
":=",
"range",
"docs",
"{",
"id",
",",
"ok",
":=",
"doc",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"upgradesLogger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"doc",
"[",
"\"",
"\"",
"]",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"modelUUID",
",",
"urlStr",
",",
"ok",
":=",
"splitDocID",
"(",
"id",
")",
"\n",
"if",
"!",
"ok",
"{",
"upgradesLogger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"url",
",",
"err",
":=",
"charm",
".",
"ParseURL",
"(",
"urlStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"upgradesLogger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"exists",
":=",
"maxRevs",
"[",
"modelUUID",
"]",
";",
"!",
"exists",
"{",
"maxRevs",
"[",
"modelUUID",
"]",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"int",
")",
"\n",
"}",
"\n\n",
"baseURL",
":=",
"url",
".",
"WithRevision",
"(",
"-",
"1",
")",
".",
"String",
"(",
")",
"\n",
"curRev",
":=",
"maxRevs",
"[",
"modelUUID",
"]",
"[",
"baseURL",
"]",
"\n",
"if",
"url",
".",
"Revision",
">",
"curRev",
"{",
"maxRevs",
"[",
"modelUUID",
"]",
"[",
"baseURL",
"]",
"=",
"url",
".",
"Revision",
"\n",
"}",
"\n\n",
"if",
"life",
",",
"ok",
":=",
"doc",
"[",
"\"",
"\"",
"]",
".",
"(",
"int",
")",
";",
"!",
"ok",
"{",
"upgradesLogger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"continue",
"\n",
"}",
"else",
"if",
"life",
"==",
"int",
"(",
"Dead",
")",
"{",
"deadIds",
"=",
"append",
"(",
"deadIds",
",",
"id",
")",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"sequences",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"sequenceC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"for",
"modelUUID",
",",
"modelRevs",
":=",
"range",
"maxRevs",
"{",
"for",
"baseURL",
",",
"maxRevision",
":=",
"range",
"modelRevs",
"{",
"name",
":=",
"charmRevSeqName",
"(",
"baseURL",
")",
"\n",
"updater",
":=",
"newDbSeqUpdater",
"(",
"sequences",
",",
"modelUUID",
",",
"name",
")",
"\n",
"err",
":=",
"updater",
".",
"ensure",
"(",
"maxRevision",
"+",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"// Remove dead charm documents",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"deadIds",
"{",
"ops",
"=",
"append",
"(",
"ops",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"charmsC",
",",
"Id",
":",
"id",
",",
"Remove",
":",
"true",
",",
"}",
")",
"\n",
"}",
"\n",
"err",
"=",
"st",
".",
"runRawTransaction",
"(",
"ops",
")",
"\n",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // AddLocalCharmSequences creates any missing sequences in the
// database for tracking already used local charm revisions. | [
"AddLocalCharmSequences",
"creates",
"any",
"missing",
"sequences",
"in",
"the",
"database",
"for",
"tracking",
"already",
"used",
"local",
"charm",
"revisions",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L306-L387 |
5,151 | juju/juju | state/upgrades.go | UpdateLegacyLXDCloudCredentials | func UpdateLegacyLXDCloudCredentials(
st *State,
endpoint string,
credential cloud.Credential,
) error {
cloudOps, err := updateLegacyLXDCloudsOps(st, endpoint)
if err != nil {
return errors.Trace(err)
}
credOps, err := updateLegacyLXDCredentialsOps(st, credential)
if err != nil {
return errors.Trace(err)
}
return st.db().RunTransaction(append(cloudOps, credOps...))
} | go | func UpdateLegacyLXDCloudCredentials(
st *State,
endpoint string,
credential cloud.Credential,
) error {
cloudOps, err := updateLegacyLXDCloudsOps(st, endpoint)
if err != nil {
return errors.Trace(err)
}
credOps, err := updateLegacyLXDCredentialsOps(st, credential)
if err != nil {
return errors.Trace(err)
}
return st.db().RunTransaction(append(cloudOps, credOps...))
} | [
"func",
"UpdateLegacyLXDCloudCredentials",
"(",
"st",
"*",
"State",
",",
"endpoint",
"string",
",",
"credential",
"cloud",
".",
"Credential",
",",
")",
"error",
"{",
"cloudOps",
",",
"err",
":=",
"updateLegacyLXDCloudsOps",
"(",
"st",
",",
"endpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"credOps",
",",
"err",
":=",
"updateLegacyLXDCredentialsOps",
"(",
"st",
",",
"credential",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"st",
".",
"db",
"(",
")",
".",
"RunTransaction",
"(",
"append",
"(",
"cloudOps",
",",
"credOps",
"...",
")",
")",
"\n",
"}"
] | // UpdateLegacyLXDCloudCredentials updates the cloud credentials for the
// LXD-based controller, and updates the cloud endpoint with the given
// value. | [
"UpdateLegacyLXDCloudCredentials",
"updates",
"the",
"cloud",
"credentials",
"for",
"the",
"LXD",
"-",
"based",
"controller",
"and",
"updates",
"the",
"cloud",
"endpoint",
"with",
"the",
"given",
"value",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L392-L406 |
5,152 | juju/juju | state/upgrades.go | UpgradeNoProxyDefaults | func UpgradeNoProxyDefaults(pool *StatePool) error {
st := pool.SystemState()
var ops []txn.Op
coll, closer := st.db().GetRawCollection(settingsC)
defer closer()
iter := coll.Find(bson.D{}).Iter()
defer iter.Close()
var doc settingsDoc
for iter.Next(&doc) {
noProxyVal := doc.Settings[config.NoProxyKey]
noProxy, ok := noProxyVal.(string)
if !ok {
continue
}
noProxy = upgradeNoProxy(noProxy)
doc.Settings[config.NoProxyKey] = noProxy
ops = append(ops, txn.Op{
C: settingsC,
Id: doc.DocID,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"settings": doc.Settings}},
})
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | go | func UpgradeNoProxyDefaults(pool *StatePool) error {
st := pool.SystemState()
var ops []txn.Op
coll, closer := st.db().GetRawCollection(settingsC)
defer closer()
iter := coll.Find(bson.D{}).Iter()
defer iter.Close()
var doc settingsDoc
for iter.Next(&doc) {
noProxyVal := doc.Settings[config.NoProxyKey]
noProxy, ok := noProxyVal.(string)
if !ok {
continue
}
noProxy = upgradeNoProxy(noProxy)
doc.Settings[config.NoProxyKey] = noProxy
ops = append(ops, txn.Op{
C: settingsC,
Id: doc.DocID,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"settings": doc.Settings}},
})
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | [
"func",
"UpgradeNoProxyDefaults",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"coll",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"settingsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"iter",
":=",
"coll",
".",
"Find",
"(",
"bson",
".",
"D",
"{",
"}",
")",
".",
"Iter",
"(",
")",
"\n",
"defer",
"iter",
".",
"Close",
"(",
")",
"\n",
"var",
"doc",
"settingsDoc",
"\n",
"for",
"iter",
".",
"Next",
"(",
"&",
"doc",
")",
"{",
"noProxyVal",
":=",
"doc",
".",
"Settings",
"[",
"config",
".",
"NoProxyKey",
"]",
"\n",
"noProxy",
",",
"ok",
":=",
"noProxyVal",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"noProxy",
"=",
"upgradeNoProxy",
"(",
"noProxy",
")",
"\n",
"doc",
".",
"Settings",
"[",
"config",
".",
"NoProxyKey",
"]",
"=",
"noProxy",
"\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"settingsC",
",",
"Id",
":",
"doc",
".",
"DocID",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"doc",
".",
"Settings",
"}",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"iter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ops",
")",
">",
"0",
"{",
"return",
"errors",
".",
"Trace",
"(",
"st",
".",
"runRawTransaction",
"(",
"ops",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpgradeNoProxyDefaults changes the default values of no_proxy
// to hold localhost values as defaults. | [
"UpgradeNoProxyDefaults",
"changes",
"the",
"default",
"values",
"of",
"no_proxy",
"to",
"hold",
"localhost",
"values",
"as",
"defaults",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L486-L516 |
5,153 | juju/juju | state/upgrades.go | RemoveNilValueApplicationSettings | func RemoveNilValueApplicationSettings(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(settingsC)
defer closer()
iter := coll.Find(bson.M{"_id": bson.M{"$regex": "^.*:a#.*"}}).Iter()
defer iter.Close()
var ops []txn.Op
var doc settingsDoc
for iter.Next(&doc) {
settingsChanged := false
for key, value := range doc.Settings {
if value != nil {
continue
}
settingsChanged = true
delete(doc.Settings, key)
}
if settingsChanged {
ops = append(ops, txn.Op{
C: settingsC,
Id: doc.DocID,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"settings": doc.Settings}},
})
}
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | go | func RemoveNilValueApplicationSettings(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(settingsC)
defer closer()
iter := coll.Find(bson.M{"_id": bson.M{"$regex": "^.*:a#.*"}}).Iter()
defer iter.Close()
var ops []txn.Op
var doc settingsDoc
for iter.Next(&doc) {
settingsChanged := false
for key, value := range doc.Settings {
if value != nil {
continue
}
settingsChanged = true
delete(doc.Settings, key)
}
if settingsChanged {
ops = append(ops, txn.Op{
C: settingsC,
Id: doc.DocID,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"settings": doc.Settings}},
})
}
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | [
"func",
"RemoveNilValueApplicationSettings",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"coll",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"settingsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"iter",
":=",
"coll",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"}",
"}",
")",
".",
"Iter",
"(",
")",
"\n",
"defer",
"iter",
".",
"Close",
"(",
")",
"\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"var",
"doc",
"settingsDoc",
"\n",
"for",
"iter",
".",
"Next",
"(",
"&",
"doc",
")",
"{",
"settingsChanged",
":=",
"false",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"doc",
".",
"Settings",
"{",
"if",
"value",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"settingsChanged",
"=",
"true",
"\n",
"delete",
"(",
"doc",
".",
"Settings",
",",
"key",
")",
"\n",
"}",
"\n",
"if",
"settingsChanged",
"{",
"ops",
"=",
"append",
"(",
"ops",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"settingsC",
",",
"Id",
":",
"doc",
".",
"DocID",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"doc",
".",
"Settings",
"}",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"iter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ops",
")",
">",
"0",
"{",
"return",
"errors",
".",
"Trace",
"(",
"st",
".",
"runRawTransaction",
"(",
"ops",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // RemoveNilValueApplicationSettings removes any application setting
// key-value pairs from "settings" where value is nil. | [
"RemoveNilValueApplicationSettings",
"removes",
"any",
"application",
"setting",
"key",
"-",
"value",
"pairs",
"from",
"settings",
"where",
"value",
"is",
"nil",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L665-L698 |
5,154 | juju/juju | state/upgrades.go | AddControllerLogCollectionsSizeSettings | func AddControllerLogCollectionsSizeSettings(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(controllersC)
defer closer()
var doc settingsDoc
if err := coll.FindId(controllerSettingsGlobalKey).One(&doc); err != nil {
if err == mgo.ErrNotFound {
return nil
}
return errors.Trace(err)
}
var ops []txn.Op
settingsChanged := maybeUpdateSettings(doc.Settings, controller.MaxLogsAge, fmt.Sprintf("%vh", controller.DefaultMaxLogsAgeDays*24))
settingsChanged =
maybeUpdateSettings(doc.Settings, controller.MaxLogsSize, fmt.Sprintf("%vM", controller.DefaultMaxLogCollectionMB)) || settingsChanged
settingsChanged =
maybeUpdateSettings(doc.Settings, controller.MaxTxnLogSize, fmt.Sprintf("%vM", controller.DefaultMaxTxnLogCollectionMB)) || settingsChanged
if settingsChanged {
ops = append(ops, txn.Op{
C: controllersC,
Id: doc.DocID,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"settings": doc.Settings}},
})
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | go | func AddControllerLogCollectionsSizeSettings(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(controllersC)
defer closer()
var doc settingsDoc
if err := coll.FindId(controllerSettingsGlobalKey).One(&doc); err != nil {
if err == mgo.ErrNotFound {
return nil
}
return errors.Trace(err)
}
var ops []txn.Op
settingsChanged := maybeUpdateSettings(doc.Settings, controller.MaxLogsAge, fmt.Sprintf("%vh", controller.DefaultMaxLogsAgeDays*24))
settingsChanged =
maybeUpdateSettings(doc.Settings, controller.MaxLogsSize, fmt.Sprintf("%vM", controller.DefaultMaxLogCollectionMB)) || settingsChanged
settingsChanged =
maybeUpdateSettings(doc.Settings, controller.MaxTxnLogSize, fmt.Sprintf("%vM", controller.DefaultMaxTxnLogCollectionMB)) || settingsChanged
if settingsChanged {
ops = append(ops, txn.Op{
C: controllersC,
Id: doc.DocID,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"settings": doc.Settings}},
})
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | [
"func",
"AddControllerLogCollectionsSizeSettings",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"coll",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"controllersC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"var",
"doc",
"settingsDoc",
"\n",
"if",
"err",
":=",
"coll",
".",
"FindId",
"(",
"controllerSettingsGlobalKey",
")",
".",
"One",
"(",
"&",
"doc",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"settingsChanged",
":=",
"maybeUpdateSettings",
"(",
"doc",
".",
"Settings",
",",
"controller",
".",
"MaxLogsAge",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"controller",
".",
"DefaultMaxLogsAgeDays",
"*",
"24",
")",
")",
"\n",
"settingsChanged",
"=",
"maybeUpdateSettings",
"(",
"doc",
".",
"Settings",
",",
"controller",
".",
"MaxLogsSize",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"controller",
".",
"DefaultMaxLogCollectionMB",
")",
")",
"||",
"settingsChanged",
"\n",
"settingsChanged",
"=",
"maybeUpdateSettings",
"(",
"doc",
".",
"Settings",
",",
"controller",
".",
"MaxTxnLogSize",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"controller",
".",
"DefaultMaxTxnLogCollectionMB",
")",
")",
"||",
"settingsChanged",
"\n",
"if",
"settingsChanged",
"{",
"ops",
"=",
"append",
"(",
"ops",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"controllersC",
",",
"Id",
":",
"doc",
".",
"DocID",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"doc",
".",
"Settings",
"}",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ops",
")",
">",
"0",
"{",
"return",
"errors",
".",
"Trace",
"(",
"st",
".",
"runRawTransaction",
"(",
"ops",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddControllerLogCollectionsSizeSettings adds the controller
// settings to control log pruning and txn log size if they are missing. | [
"AddControllerLogCollectionsSizeSettings",
"adds",
"the",
"controller",
"settings",
"to",
"control",
"log",
"pruning",
"and",
"txn",
"log",
"size",
"if",
"they",
"are",
"missing",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L702-L732 |
5,155 | juju/juju | state/upgrades.go | applyToAllModelSettings | func applyToAllModelSettings(st *State, change func(*settingsDoc) (bool, error)) error {
uuids, err := st.AllModelUUIDs()
if err != nil {
return errors.Trace(err)
}
coll, closer := st.db().GetRawCollection(settingsC)
defer closer()
var ids []string
for _, uuid := range uuids {
ids = append(ids, uuid+":e")
}
iter := coll.Find(bson.M{"_id": bson.M{"$in": ids}}).Iter()
defer iter.Close()
var ops []txn.Op
var doc settingsDoc
for iter.Next(&doc) {
settingsChanged, err := change(&doc)
if err != nil {
return errors.Trace(err)
}
if settingsChanged {
ops = append(ops, txn.Op{
C: settingsC,
Id: doc.DocID,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"settings": doc.Settings}},
})
}
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | go | func applyToAllModelSettings(st *State, change func(*settingsDoc) (bool, error)) error {
uuids, err := st.AllModelUUIDs()
if err != nil {
return errors.Trace(err)
}
coll, closer := st.db().GetRawCollection(settingsC)
defer closer()
var ids []string
for _, uuid := range uuids {
ids = append(ids, uuid+":e")
}
iter := coll.Find(bson.M{"_id": bson.M{"$in": ids}}).Iter()
defer iter.Close()
var ops []txn.Op
var doc settingsDoc
for iter.Next(&doc) {
settingsChanged, err := change(&doc)
if err != nil {
return errors.Trace(err)
}
if settingsChanged {
ops = append(ops, txn.Op{
C: settingsC,
Id: doc.DocID,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"settings": doc.Settings}},
})
}
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | [
"func",
"applyToAllModelSettings",
"(",
"st",
"*",
"State",
",",
"change",
"func",
"(",
"*",
"settingsDoc",
")",
"(",
"bool",
",",
"error",
")",
")",
"error",
"{",
"uuids",
",",
"err",
":=",
"st",
".",
"AllModelUUIDs",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"coll",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"settingsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"ids",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"uuid",
":=",
"range",
"uuids",
"{",
"ids",
"=",
"append",
"(",
"ids",
",",
"uuid",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"iter",
":=",
"coll",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"ids",
"}",
"}",
")",
".",
"Iter",
"(",
")",
"\n",
"defer",
"iter",
".",
"Close",
"(",
")",
"\n\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"var",
"doc",
"settingsDoc",
"\n",
"for",
"iter",
".",
"Next",
"(",
"&",
"doc",
")",
"{",
"settingsChanged",
",",
"err",
":=",
"change",
"(",
"&",
"doc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"settingsChanged",
"{",
"ops",
"=",
"append",
"(",
"ops",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"settingsC",
",",
"Id",
":",
"doc",
".",
"DocID",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"doc",
".",
"Settings",
"}",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"iter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ops",
")",
">",
"0",
"{",
"return",
"errors",
".",
"Trace",
"(",
"st",
".",
"runRawTransaction",
"(",
"ops",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // applyToAllModelSettings iterates the model settings documents and applys the
// passed in function to them. If the function returns 'true' it indicates the
// settings have been modified, and they should be written back to the
// database.
// Note that if there are any problems with updating settings, then none of the
// changes will be applied, as they are all updated in a single transaction. | [
"applyToAllModelSettings",
"iterates",
"the",
"model",
"settings",
"documents",
"and",
"applys",
"the",
"passed",
"in",
"function",
"to",
"them",
".",
"If",
"the",
"function",
"returns",
"true",
"it",
"indicates",
"the",
"settings",
"have",
"been",
"modified",
"and",
"they",
"should",
"be",
"written",
"back",
"to",
"the",
"database",
".",
"Note",
"that",
"if",
"there",
"are",
"any",
"problems",
"with",
"updating",
"settings",
"then",
"none",
"of",
"the",
"changes",
"will",
"be",
"applied",
"as",
"they",
"are",
"all",
"updated",
"in",
"a",
"single",
"transaction",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L748-L788 |
5,156 | juju/juju | state/upgrades.go | AddStatusHistoryPruneSettings | func AddStatusHistoryPruneSettings(pool *StatePool) error {
st := pool.SystemState()
err := applyToAllModelSettings(st, func(doc *settingsDoc) (bool, error) {
settingsChanged :=
maybeUpdateSettings(doc.Settings, config.MaxStatusHistoryAge, config.DefaultStatusHistoryAge)
settingsChanged =
maybeUpdateSettings(doc.Settings, config.MaxStatusHistorySize, config.DefaultStatusHistorySize) || settingsChanged
return settingsChanged, nil
})
if err != nil {
return errors.Trace(err)
}
return nil
} | go | func AddStatusHistoryPruneSettings(pool *StatePool) error {
st := pool.SystemState()
err := applyToAllModelSettings(st, func(doc *settingsDoc) (bool, error) {
settingsChanged :=
maybeUpdateSettings(doc.Settings, config.MaxStatusHistoryAge, config.DefaultStatusHistoryAge)
settingsChanged =
maybeUpdateSettings(doc.Settings, config.MaxStatusHistorySize, config.DefaultStatusHistorySize) || settingsChanged
return settingsChanged, nil
})
if err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"AddStatusHistoryPruneSettings",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"err",
":=",
"applyToAllModelSettings",
"(",
"st",
",",
"func",
"(",
"doc",
"*",
"settingsDoc",
")",
"(",
"bool",
",",
"error",
")",
"{",
"settingsChanged",
":=",
"maybeUpdateSettings",
"(",
"doc",
".",
"Settings",
",",
"config",
".",
"MaxStatusHistoryAge",
",",
"config",
".",
"DefaultStatusHistoryAge",
")",
"\n",
"settingsChanged",
"=",
"maybeUpdateSettings",
"(",
"doc",
".",
"Settings",
",",
"config",
".",
"MaxStatusHistorySize",
",",
"config",
".",
"DefaultStatusHistorySize",
")",
"||",
"settingsChanged",
"\n",
"return",
"settingsChanged",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddStatusHistoryPruneSettings adds the model settings
// to control log pruning if they are missing. | [
"AddStatusHistoryPruneSettings",
"adds",
"the",
"model",
"settings",
"to",
"control",
"log",
"pruning",
"if",
"they",
"are",
"missing",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L792-L805 |
5,157 | juju/juju | state/upgrades.go | AddActionPruneSettings | func AddActionPruneSettings(pool *StatePool) error {
st := pool.SystemState()
err := applyToAllModelSettings(st, func(doc *settingsDoc) (bool, error) {
settingsChanged :=
maybeUpdateSettings(doc.Settings, config.MaxActionResultsAge, config.DefaultActionResultsAge)
settingsChanged =
maybeUpdateSettings(doc.Settings, config.MaxActionResultsSize, config.DefaultActionResultsSize) || settingsChanged
return settingsChanged, nil
})
if err != nil {
return errors.Trace(err)
}
return nil
} | go | func AddActionPruneSettings(pool *StatePool) error {
st := pool.SystemState()
err := applyToAllModelSettings(st, func(doc *settingsDoc) (bool, error) {
settingsChanged :=
maybeUpdateSettings(doc.Settings, config.MaxActionResultsAge, config.DefaultActionResultsAge)
settingsChanged =
maybeUpdateSettings(doc.Settings, config.MaxActionResultsSize, config.DefaultActionResultsSize) || settingsChanged
return settingsChanged, nil
})
if err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"AddActionPruneSettings",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"err",
":=",
"applyToAllModelSettings",
"(",
"st",
",",
"func",
"(",
"doc",
"*",
"settingsDoc",
")",
"(",
"bool",
",",
"error",
")",
"{",
"settingsChanged",
":=",
"maybeUpdateSettings",
"(",
"doc",
".",
"Settings",
",",
"config",
".",
"MaxActionResultsAge",
",",
"config",
".",
"DefaultActionResultsAge",
")",
"\n",
"settingsChanged",
"=",
"maybeUpdateSettings",
"(",
"doc",
".",
"Settings",
",",
"config",
".",
"MaxActionResultsSize",
",",
"config",
".",
"DefaultActionResultsSize",
")",
"||",
"settingsChanged",
"\n",
"return",
"settingsChanged",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddActionPruneSettings adds the model settings
// to control log pruning if they are missing. | [
"AddActionPruneSettings",
"adds",
"the",
"model",
"settings",
"to",
"control",
"log",
"pruning",
"if",
"they",
"are",
"missing",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L809-L822 |
5,158 | juju/juju | state/upgrades.go | AddUpdateStatusHookSettings | func AddUpdateStatusHookSettings(pool *StatePool) error {
st := pool.SystemState()
err := applyToAllModelSettings(st, func(doc *settingsDoc) (bool, error) {
settingsChanged :=
maybeUpdateSettings(doc.Settings, config.UpdateStatusHookInterval, config.DefaultUpdateStatusHookInterval)
return settingsChanged, nil
})
if err != nil {
return errors.Trace(err)
}
return nil
} | go | func AddUpdateStatusHookSettings(pool *StatePool) error {
st := pool.SystemState()
err := applyToAllModelSettings(st, func(doc *settingsDoc) (bool, error) {
settingsChanged :=
maybeUpdateSettings(doc.Settings, config.UpdateStatusHookInterval, config.DefaultUpdateStatusHookInterval)
return settingsChanged, nil
})
if err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"AddUpdateStatusHookSettings",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"err",
":=",
"applyToAllModelSettings",
"(",
"st",
",",
"func",
"(",
"doc",
"*",
"settingsDoc",
")",
"(",
"bool",
",",
"error",
")",
"{",
"settingsChanged",
":=",
"maybeUpdateSettings",
"(",
"doc",
".",
"Settings",
",",
"config",
".",
"UpdateStatusHookInterval",
",",
"config",
".",
"DefaultUpdateStatusHookInterval",
")",
"\n",
"return",
"settingsChanged",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddUpdateStatusHookSettings adds the model settings
// to control how often to run the update-status hook
// if they are missing. | [
"AddUpdateStatusHookSettings",
"adds",
"the",
"model",
"settings",
"to",
"control",
"how",
"often",
"to",
"run",
"the",
"update",
"-",
"status",
"hook",
"if",
"they",
"are",
"missing",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L827-L838 |
5,159 | juju/juju | state/upgrades.go | SplitLogCollections | func SplitLogCollections(pool *StatePool) error {
st := pool.SystemState()
session := st.MongoSession()
db := session.DB(logsDB)
oldLogs := db.C("logs")
// If we haven't seen any particular model, we need to initialise
// the logs collection with the right indices.
seen := set.NewStrings()
iter := oldLogs.Find(nil).Iter()
defer iter.Close()
var doc bson.M
for iter.Next(&doc) {
modelUUID := doc["e"].(string)
newCollName := logCollectionName(modelUUID)
newLogs := db.C(newCollName)
if !seen.Contains(newCollName) {
if err := InitDbLogs(session, modelUUID); err != nil {
return errors.Annotatef(err, "failed to init new logs collection %q", newCollName)
}
seen.Add(newCollName)
}
delete(doc, "e") // old model uuid
if err := newLogs.Insert(doc); err != nil {
// In the case of a restart, we may have already moved
// some of these rows, in which case we'd get a duplicate
// id error (this is OK).
if !mgo.IsDup(err) {
return errors.Annotate(err, "failed to insert log record")
}
}
doc = nil
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
// drop the old collection
if err := oldLogs.DropCollection(); err != nil {
// If the namespace is already missing, that's fine.
if isMgoNamespaceNotFound(err) {
return nil
}
return errors.Annotate(err, "failed to drop old logs collection")
}
return nil
} | go | func SplitLogCollections(pool *StatePool) error {
st := pool.SystemState()
session := st.MongoSession()
db := session.DB(logsDB)
oldLogs := db.C("logs")
// If we haven't seen any particular model, we need to initialise
// the logs collection with the right indices.
seen := set.NewStrings()
iter := oldLogs.Find(nil).Iter()
defer iter.Close()
var doc bson.M
for iter.Next(&doc) {
modelUUID := doc["e"].(string)
newCollName := logCollectionName(modelUUID)
newLogs := db.C(newCollName)
if !seen.Contains(newCollName) {
if err := InitDbLogs(session, modelUUID); err != nil {
return errors.Annotatef(err, "failed to init new logs collection %q", newCollName)
}
seen.Add(newCollName)
}
delete(doc, "e") // old model uuid
if err := newLogs.Insert(doc); err != nil {
// In the case of a restart, we may have already moved
// some of these rows, in which case we'd get a duplicate
// id error (this is OK).
if !mgo.IsDup(err) {
return errors.Annotate(err, "failed to insert log record")
}
}
doc = nil
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
// drop the old collection
if err := oldLogs.DropCollection(); err != nil {
// If the namespace is already missing, that's fine.
if isMgoNamespaceNotFound(err) {
return nil
}
return errors.Annotate(err, "failed to drop old logs collection")
}
return nil
} | [
"func",
"SplitLogCollections",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"session",
":=",
"st",
".",
"MongoSession",
"(",
")",
"\n",
"db",
":=",
"session",
".",
"DB",
"(",
"logsDB",
")",
"\n",
"oldLogs",
":=",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
"\n\n",
"// If we haven't seen any particular model, we need to initialise",
"// the logs collection with the right indices.",
"seen",
":=",
"set",
".",
"NewStrings",
"(",
")",
"\n\n",
"iter",
":=",
"oldLogs",
".",
"Find",
"(",
"nil",
")",
".",
"Iter",
"(",
")",
"\n",
"defer",
"iter",
".",
"Close",
"(",
")",
"\n\n",
"var",
"doc",
"bson",
".",
"M",
"\n",
"for",
"iter",
".",
"Next",
"(",
"&",
"doc",
")",
"{",
"modelUUID",
":=",
"doc",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"newCollName",
":=",
"logCollectionName",
"(",
"modelUUID",
")",
"\n",
"newLogs",
":=",
"db",
".",
"C",
"(",
"newCollName",
")",
"\n\n",
"if",
"!",
"seen",
".",
"Contains",
"(",
"newCollName",
")",
"{",
"if",
"err",
":=",
"InitDbLogs",
"(",
"session",
",",
"modelUUID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"newCollName",
")",
"\n",
"}",
"\n",
"seen",
".",
"Add",
"(",
"newCollName",
")",
"\n",
"}",
"\n\n",
"delete",
"(",
"doc",
",",
"\"",
"\"",
")",
"// old model uuid",
"\n\n",
"if",
"err",
":=",
"newLogs",
".",
"Insert",
"(",
"doc",
")",
";",
"err",
"!=",
"nil",
"{",
"// In the case of a restart, we may have already moved",
"// some of these rows, in which case we'd get a duplicate",
"// id error (this is OK).",
"if",
"!",
"mgo",
".",
"IsDup",
"(",
"err",
")",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"doc",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"iter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// drop the old collection",
"if",
"err",
":=",
"oldLogs",
".",
"DropCollection",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"// If the namespace is already missing, that's fine.",
"if",
"isMgoNamespaceNotFound",
"(",
"err",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SplitLogCollections moves log entries from the old single log collection
// to the log collection per model. | [
"SplitLogCollections",
"moves",
"log",
"entries",
"from",
"the",
"old",
"single",
"log",
"collection",
"to",
"the",
"log",
"collection",
"per",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L947-L998 |
5,160 | juju/juju | state/upgrades.go | MoveOldAuditLog | func MoveOldAuditLog(pool *StatePool) error {
st := pool.SystemState()
names, err := st.MongoSession().DB("juju").CollectionNames()
if err != nil {
return errors.Trace(err)
}
if !set.NewStrings(names...).Contains("audit.log") {
// No audit log collection to move.
return nil
}
coll, closer := st.db().GetRawCollection("audit.log")
defer closer()
rows, err := coll.Count()
if err != nil {
return errors.Trace(err)
}
if rows == 0 {
return errors.Trace(coll.DropCollection())
}
session := st.MongoSession()
renameCommand := bson.D{
{"renameCollection", "juju.audit.log"},
{"to", "juju.old-audit.log"},
}
return errors.Trace(session.Run(renameCommand, nil))
} | go | func MoveOldAuditLog(pool *StatePool) error {
st := pool.SystemState()
names, err := st.MongoSession().DB("juju").CollectionNames()
if err != nil {
return errors.Trace(err)
}
if !set.NewStrings(names...).Contains("audit.log") {
// No audit log collection to move.
return nil
}
coll, closer := st.db().GetRawCollection("audit.log")
defer closer()
rows, err := coll.Count()
if err != nil {
return errors.Trace(err)
}
if rows == 0 {
return errors.Trace(coll.DropCollection())
}
session := st.MongoSession()
renameCommand := bson.D{
{"renameCollection", "juju.audit.log"},
{"to", "juju.old-audit.log"},
}
return errors.Trace(session.Run(renameCommand, nil))
} | [
"func",
"MoveOldAuditLog",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"names",
",",
"err",
":=",
"st",
".",
"MongoSession",
"(",
")",
".",
"DB",
"(",
"\"",
"\"",
")",
".",
"CollectionNames",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"!",
"set",
".",
"NewStrings",
"(",
"names",
"...",
")",
".",
"Contains",
"(",
"\"",
"\"",
")",
"{",
"// No audit log collection to move.",
"return",
"nil",
"\n",
"}",
"\n\n",
"coll",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"\"",
"\"",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"rows",
",",
"err",
":=",
"coll",
".",
"Count",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"rows",
"==",
"0",
"{",
"return",
"errors",
".",
"Trace",
"(",
"coll",
".",
"DropCollection",
"(",
")",
")",
"\n",
"}",
"\n",
"session",
":=",
"st",
".",
"MongoSession",
"(",
")",
"\n",
"renameCommand",
":=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"session",
".",
"Run",
"(",
"renameCommand",
",",
"nil",
")",
")",
"\n",
"}"
] | // MoveOldAuditLog renames the no-longer-needed audit.log collection
// to old-audit.log if it has any rows - if it's empty it deletes it. | [
"MoveOldAuditLog",
"renames",
"the",
"no",
"-",
"longer",
"-",
"needed",
"audit",
".",
"log",
"collection",
"to",
"old",
"-",
"audit",
".",
"log",
"if",
"it",
"has",
"any",
"rows",
"-",
"if",
"it",
"s",
"empty",
"it",
"deletes",
"it",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1400-L1427 |
5,161 | juju/juju | state/upgrades.go | DeleteCloudImageMetadata | func DeleteCloudImageMetadata(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(cloudimagemetadataC)
defer closer()
bulk := coll.Bulk()
bulk.Unordered()
bulk.RemoveAll(bson.D{{"source", bson.D{{"$ne", "custom"}}}})
_, err := bulk.Run()
return errors.Annotate(err, "deleting cloud image metadata records")
} | go | func DeleteCloudImageMetadata(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(cloudimagemetadataC)
defer closer()
bulk := coll.Bulk()
bulk.Unordered()
bulk.RemoveAll(bson.D{{"source", bson.D{{"$ne", "custom"}}}})
_, err := bulk.Run()
return errors.Annotate(err, "deleting cloud image metadata records")
} | [
"func",
"DeleteCloudImageMetadata",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"coll",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"cloudimagemetadataC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"bulk",
":=",
"coll",
".",
"Bulk",
"(",
")",
"\n",
"bulk",
".",
"Unordered",
"(",
")",
"\n",
"bulk",
".",
"RemoveAll",
"(",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"}",
"}",
"}",
")",
"\n",
"_",
",",
"err",
":=",
"bulk",
".",
"Run",
"(",
")",
"\n",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // DeleteCloudImageMetadata deletes any non-custom cloud
// image metadata records from the cloudimagemetadata collection. | [
"DeleteCloudImageMetadata",
"deletes",
"any",
"non",
"-",
"custom",
"cloud",
"image",
"metadata",
"records",
"from",
"the",
"cloudimagemetadata",
"collection",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1431-L1441 |
5,162 | juju/juju | state/upgrades.go | MoveMongoSpaceToHASpaceConfig | func MoveMongoSpaceToHASpaceConfig(pool *StatePool) error {
st := pool.SystemState()
// Holds Mongo space fields removed from controllersDoc.
type controllersUpgradeDoc struct {
MongoSpaceName string `bson:"mongo-space-name"`
MongoSpaceState string `bson:"mongo-space-state"`
}
var doc controllersUpgradeDoc
controllerColl, controllerCloser := st.db().GetRawCollection(controllersC)
defer controllerCloser()
err := controllerColl.Find(bson.D{{"_id", modelGlobalKey}}).One(&doc)
if err != nil {
return errors.Annotate(err, "retrieving controller info doc")
}
mongoSpace := doc.MongoSpaceName
if doc.MongoSpaceState == "valid" && mongoSpace != "" {
settings, err := readSettings(st.db(), controllersC, controllerSettingsGlobalKey)
if err != nil {
return errors.Annotate(err, "cannot get controller config")
}
// In the unlikely event that there is already a juju-ha-space
// configuration setting, we do not copy over it with the old Mongo
// space name.
if haSpace, ok := settings.Get(controller.JujuHASpace); ok {
upgradesLogger.Debugf("not copying mongo-space-name %q to juju-ha-space - already set to %q",
mongoSpace, haSpace)
} else {
settings.Set(controller.JujuHASpace, mongoSpace)
if _, err = settings.Write(); err != nil {
return errors.Annotate(err, "writing controller info")
}
}
}
err = controllerColl.UpdateId(modelGlobalKey, bson.M{"$unset": bson.M{
"mongo-space-name": 1,
"mongo-space-state": 1,
}})
return errors.Annotate(err, "removing mongo-space-state and mongo-space-name")
} | go | func MoveMongoSpaceToHASpaceConfig(pool *StatePool) error {
st := pool.SystemState()
// Holds Mongo space fields removed from controllersDoc.
type controllersUpgradeDoc struct {
MongoSpaceName string `bson:"mongo-space-name"`
MongoSpaceState string `bson:"mongo-space-state"`
}
var doc controllersUpgradeDoc
controllerColl, controllerCloser := st.db().GetRawCollection(controllersC)
defer controllerCloser()
err := controllerColl.Find(bson.D{{"_id", modelGlobalKey}}).One(&doc)
if err != nil {
return errors.Annotate(err, "retrieving controller info doc")
}
mongoSpace := doc.MongoSpaceName
if doc.MongoSpaceState == "valid" && mongoSpace != "" {
settings, err := readSettings(st.db(), controllersC, controllerSettingsGlobalKey)
if err != nil {
return errors.Annotate(err, "cannot get controller config")
}
// In the unlikely event that there is already a juju-ha-space
// configuration setting, we do not copy over it with the old Mongo
// space name.
if haSpace, ok := settings.Get(controller.JujuHASpace); ok {
upgradesLogger.Debugf("not copying mongo-space-name %q to juju-ha-space - already set to %q",
mongoSpace, haSpace)
} else {
settings.Set(controller.JujuHASpace, mongoSpace)
if _, err = settings.Write(); err != nil {
return errors.Annotate(err, "writing controller info")
}
}
}
err = controllerColl.UpdateId(modelGlobalKey, bson.M{"$unset": bson.M{
"mongo-space-name": 1,
"mongo-space-state": 1,
}})
return errors.Annotate(err, "removing mongo-space-state and mongo-space-name")
} | [
"func",
"MoveMongoSpaceToHASpaceConfig",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"// Holds Mongo space fields removed from controllersDoc.",
"type",
"controllersUpgradeDoc",
"struct",
"{",
"MongoSpaceName",
"string",
"`bson:\"mongo-space-name\"`",
"\n",
"MongoSpaceState",
"string",
"`bson:\"mongo-space-state\"`",
"\n",
"}",
"\n",
"var",
"doc",
"controllersUpgradeDoc",
"\n\n",
"controllerColl",
",",
"controllerCloser",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"controllersC",
")",
"\n",
"defer",
"controllerCloser",
"(",
")",
"\n",
"err",
":=",
"controllerColl",
".",
"Find",
"(",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"modelGlobalKey",
"}",
"}",
")",
".",
"One",
"(",
"&",
"doc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"mongoSpace",
":=",
"doc",
".",
"MongoSpaceName",
"\n",
"if",
"doc",
".",
"MongoSpaceState",
"==",
"\"",
"\"",
"&&",
"mongoSpace",
"!=",
"\"",
"\"",
"{",
"settings",
",",
"err",
":=",
"readSettings",
"(",
"st",
".",
"db",
"(",
")",
",",
"controllersC",
",",
"controllerSettingsGlobalKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// In the unlikely event that there is already a juju-ha-space",
"// configuration setting, we do not copy over it with the old Mongo",
"// space name.",
"if",
"haSpace",
",",
"ok",
":=",
"settings",
".",
"Get",
"(",
"controller",
".",
"JujuHASpace",
")",
";",
"ok",
"{",
"upgradesLogger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"mongoSpace",
",",
"haSpace",
")",
"\n",
"}",
"else",
"{",
"settings",
".",
"Set",
"(",
"controller",
".",
"JujuHASpace",
",",
"mongoSpace",
")",
"\n",
"if",
"_",
",",
"err",
"=",
"settings",
".",
"Write",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"err",
"=",
"controllerColl",
".",
"UpdateId",
"(",
"modelGlobalKey",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"1",
",",
"\"",
"\"",
":",
"1",
",",
"}",
"}",
")",
"\n",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // CopyMongoSpaceToHASpaceConfig copies the Mongo space name from
// ControllerInfo to the HA space name in ControllerConfig.
// This only happens if the Mongo space state is valid, it is not empty,
// and if there is no value already set for the HA space name.
// The old keys are then deleted from ControllerInfo. | [
"CopyMongoSpaceToHASpaceConfig",
"copies",
"the",
"Mongo",
"space",
"name",
"from",
"ControllerInfo",
"to",
"the",
"HA",
"space",
"name",
"in",
"ControllerConfig",
".",
"This",
"only",
"happens",
"if",
"the",
"Mongo",
"space",
"state",
"is",
"valid",
"it",
"is",
"not",
"empty",
"and",
"if",
"there",
"is",
"no",
"value",
"already",
"set",
"for",
"the",
"HA",
"space",
"name",
".",
"The",
"old",
"keys",
"are",
"then",
"deleted",
"from",
"ControllerInfo",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1448-L1490 |
5,163 | juju/juju | state/upgrades.go | CreateMissingApplicationConfig | func CreateMissingApplicationConfig(pool *StatePool) error {
st := pool.SystemState()
settingsColl, settingsCloser := st.db().GetRawCollection(settingsC)
defer settingsCloser()
var applicationConfigIDs []struct {
ID string `bson:"_id"`
}
settingsColl.Find(bson.M{
"_id": bson.M{"$regex": bson.RegEx{"#application$", ""}}}).All(&applicationConfigIDs)
allIDs := set.NewStrings()
for _, id := range applicationConfigIDs {
allIDs.Add(id.ID)
}
appsColl, appsCloser := st.db().GetRawCollection(applicationsC)
defer appsCloser()
var applicationNames []struct {
Name string `bson:"name"`
ModelUUID string `bson:"model-uuid"`
}
appsColl.Find(nil).All(&applicationNames)
var newAppConfigOps []txn.Op
emptySettings := make(map[string]interface{})
for _, app := range applicationNames {
appConfID := fmt.Sprintf("%s:%s", app.ModelUUID, applicationConfigKey(app.Name))
if !allIDs.Contains(appConfID) {
newOp := createSettingsOp(settingsC, appConfID, emptySettings)
// createSettingsOp assumes you're using a model-specific state, which will auto-inject the ModelUUID
// since we're doing this globally, cast it to the underlying type and add it.
newOp.Insert.(*settingsDoc).ModelUUID = app.ModelUUID
newAppConfigOps = append(newAppConfigOps, newOp)
}
}
err := st.db().RunRawTransaction(newAppConfigOps)
if err != nil {
return errors.Annotate(err, "writing application configs")
}
return nil
} | go | func CreateMissingApplicationConfig(pool *StatePool) error {
st := pool.SystemState()
settingsColl, settingsCloser := st.db().GetRawCollection(settingsC)
defer settingsCloser()
var applicationConfigIDs []struct {
ID string `bson:"_id"`
}
settingsColl.Find(bson.M{
"_id": bson.M{"$regex": bson.RegEx{"#application$", ""}}}).All(&applicationConfigIDs)
allIDs := set.NewStrings()
for _, id := range applicationConfigIDs {
allIDs.Add(id.ID)
}
appsColl, appsCloser := st.db().GetRawCollection(applicationsC)
defer appsCloser()
var applicationNames []struct {
Name string `bson:"name"`
ModelUUID string `bson:"model-uuid"`
}
appsColl.Find(nil).All(&applicationNames)
var newAppConfigOps []txn.Op
emptySettings := make(map[string]interface{})
for _, app := range applicationNames {
appConfID := fmt.Sprintf("%s:%s", app.ModelUUID, applicationConfigKey(app.Name))
if !allIDs.Contains(appConfID) {
newOp := createSettingsOp(settingsC, appConfID, emptySettings)
// createSettingsOp assumes you're using a model-specific state, which will auto-inject the ModelUUID
// since we're doing this globally, cast it to the underlying type and add it.
newOp.Insert.(*settingsDoc).ModelUUID = app.ModelUUID
newAppConfigOps = append(newAppConfigOps, newOp)
}
}
err := st.db().RunRawTransaction(newAppConfigOps)
if err != nil {
return errors.Annotate(err, "writing application configs")
}
return nil
} | [
"func",
"CreateMissingApplicationConfig",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"settingsColl",
",",
"settingsCloser",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"settingsC",
")",
"\n",
"defer",
"settingsCloser",
"(",
")",
"\n\n",
"var",
"applicationConfigIDs",
"[",
"]",
"struct",
"{",
"ID",
"string",
"`bson:\"_id\"`",
"\n",
"}",
"\n",
"settingsColl",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"RegEx",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"}",
"}",
")",
".",
"All",
"(",
"&",
"applicationConfigIDs",
")",
"\n\n",
"allIDs",
":=",
"set",
".",
"NewStrings",
"(",
")",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"applicationConfigIDs",
"{",
"allIDs",
".",
"Add",
"(",
"id",
".",
"ID",
")",
"\n",
"}",
"\n\n",
"appsColl",
",",
"appsCloser",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"applicationsC",
")",
"\n",
"defer",
"appsCloser",
"(",
")",
"\n\n",
"var",
"applicationNames",
"[",
"]",
"struct",
"{",
"Name",
"string",
"`bson:\"name\"`",
"\n",
"ModelUUID",
"string",
"`bson:\"model-uuid\"`",
"\n",
"}",
"\n",
"appsColl",
".",
"Find",
"(",
"nil",
")",
".",
"All",
"(",
"&",
"applicationNames",
")",
"\n\n",
"var",
"newAppConfigOps",
"[",
"]",
"txn",
".",
"Op",
"\n",
"emptySettings",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"app",
":=",
"range",
"applicationNames",
"{",
"appConfID",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"app",
".",
"ModelUUID",
",",
"applicationConfigKey",
"(",
"app",
".",
"Name",
")",
")",
"\n",
"if",
"!",
"allIDs",
".",
"Contains",
"(",
"appConfID",
")",
"{",
"newOp",
":=",
"createSettingsOp",
"(",
"settingsC",
",",
"appConfID",
",",
"emptySettings",
")",
"\n",
"// createSettingsOp assumes you're using a model-specific state, which will auto-inject the ModelUUID",
"// since we're doing this globally, cast it to the underlying type and add it.",
"newOp",
".",
"Insert",
".",
"(",
"*",
"settingsDoc",
")",
".",
"ModelUUID",
"=",
"app",
".",
"ModelUUID",
"\n",
"newAppConfigOps",
"=",
"append",
"(",
"newAppConfigOps",
",",
"newOp",
")",
"\n",
"}",
"\n",
"}",
"\n",
"err",
":=",
"st",
".",
"db",
"(",
")",
".",
"RunRawTransaction",
"(",
"newAppConfigOps",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CreateMissingApplicationConfig ensures that all models have an application config in the db. | [
"CreateMissingApplicationConfig",
"ensures",
"that",
"all",
"models",
"have",
"an",
"application",
"config",
"in",
"the",
"db",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1493-L1535 |
5,164 | juju/juju | state/upgrades.go | RemoveVotingMachineIds | func RemoveVotingMachineIds(pool *StatePool) error {
st := pool.SystemState()
controllerColl, controllerCloser := st.db().GetRawCollection(controllersC)
defer controllerCloser()
// The votingmachineids field is just a denormalization of Machine.WantsVote() so we can just
// remove it as being redundant
err := controllerColl.UpdateId(modelGlobalKey, bson.M{"$unset": bson.M{"votingmachineids": 1}})
if err != nil {
return errors.Annotate(err, "removing votingmachineids")
}
return nil
} | go | func RemoveVotingMachineIds(pool *StatePool) error {
st := pool.SystemState()
controllerColl, controllerCloser := st.db().GetRawCollection(controllersC)
defer controllerCloser()
// The votingmachineids field is just a denormalization of Machine.WantsVote() so we can just
// remove it as being redundant
err := controllerColl.UpdateId(modelGlobalKey, bson.M{"$unset": bson.M{"votingmachineids": 1}})
if err != nil {
return errors.Annotate(err, "removing votingmachineids")
}
return nil
} | [
"func",
"RemoveVotingMachineIds",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"controllerColl",
",",
"controllerCloser",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"controllersC",
")",
"\n",
"defer",
"controllerCloser",
"(",
")",
"\n",
"// The votingmachineids field is just a denormalization of Machine.WantsVote() so we can just",
"// remove it as being redundant",
"err",
":=",
"controllerColl",
".",
"UpdateId",
"(",
"modelGlobalKey",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"1",
"}",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // RemoveVotingMachineIds ensures that the 'votingmachineids' field on controller info has been removed | [
"RemoveVotingMachineIds",
"ensures",
"that",
"the",
"votingmachineids",
"field",
"on",
"controller",
"info",
"has",
"been",
"removed"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1538-L1549 |
5,165 | juju/juju | state/upgrades.go | AddCloudModelCounts | func AddCloudModelCounts(pool *StatePool) error {
st := pool.SystemState()
cloudsColl, closer := st.db().GetCollection(cloudsC)
defer closer()
var clouds []cloudDoc
err := cloudsColl.Find(nil).All(&clouds)
if err != nil {
return errors.Trace(err)
}
modelsColl, closer := st.db().GetCollection(modelsC)
defer closer()
refCountColl, closer := st.db().GetCollection(globalRefcountsC)
defer closer()
var updateOps []txn.Op
for _, c := range clouds {
n, err := modelsColl.Find(bson.D{{"cloud", c.Name}}).Count()
if err != nil {
return errors.Trace(err)
}
_, currentCount, err := countCloudModelRefOp(st, c.Name)
if err != nil {
return errors.Trace(err)
}
if n != currentCount {
op, err := nsRefcounts.CreateOrIncRefOp(refCountColl, cloudModelRefCountKey(c.Name), n-currentCount)
if err != nil {
return errors.Trace(err)
}
updateOps = append(updateOps, op)
}
}
return st.db().RunTransaction(updateOps)
} | go | func AddCloudModelCounts(pool *StatePool) error {
st := pool.SystemState()
cloudsColl, closer := st.db().GetCollection(cloudsC)
defer closer()
var clouds []cloudDoc
err := cloudsColl.Find(nil).All(&clouds)
if err != nil {
return errors.Trace(err)
}
modelsColl, closer := st.db().GetCollection(modelsC)
defer closer()
refCountColl, closer := st.db().GetCollection(globalRefcountsC)
defer closer()
var updateOps []txn.Op
for _, c := range clouds {
n, err := modelsColl.Find(bson.D{{"cloud", c.Name}}).Count()
if err != nil {
return errors.Trace(err)
}
_, currentCount, err := countCloudModelRefOp(st, c.Name)
if err != nil {
return errors.Trace(err)
}
if n != currentCount {
op, err := nsRefcounts.CreateOrIncRefOp(refCountColl, cloudModelRefCountKey(c.Name), n-currentCount)
if err != nil {
return errors.Trace(err)
}
updateOps = append(updateOps, op)
}
}
return st.db().RunTransaction(updateOps)
} | [
"func",
"AddCloudModelCounts",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"cloudsColl",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"cloudsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"clouds",
"[",
"]",
"cloudDoc",
"\n",
"err",
":=",
"cloudsColl",
".",
"Find",
"(",
"nil",
")",
".",
"All",
"(",
"&",
"clouds",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"modelsColl",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"modelsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"refCountColl",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"globalRefcountsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"updateOps",
"[",
"]",
"txn",
".",
"Op",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"clouds",
"{",
"n",
",",
"err",
":=",
"modelsColl",
".",
"Find",
"(",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"c",
".",
"Name",
"}",
"}",
")",
".",
"Count",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"_",
",",
"currentCount",
",",
"err",
":=",
"countCloudModelRefOp",
"(",
"st",
",",
"c",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"currentCount",
"{",
"op",
",",
"err",
":=",
"nsRefcounts",
".",
"CreateOrIncRefOp",
"(",
"refCountColl",
",",
"cloudModelRefCountKey",
"(",
"c",
".",
"Name",
")",
",",
"n",
"-",
"currentCount",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"updateOps",
"=",
"append",
"(",
"updateOps",
",",
"op",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"st",
".",
"db",
"(",
")",
".",
"RunTransaction",
"(",
"updateOps",
")",
"\n",
"}"
] | // AddCloudModelCounts updates cloud docs to ensure the model count field is set. | [
"AddCloudModelCounts",
"updates",
"cloud",
"docs",
"to",
"ensure",
"the",
"model",
"count",
"field",
"is",
"set",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1552-L1587 |
5,166 | juju/juju | state/upgrades.go | UpgradeContainerImageStreamDefault | func UpgradeContainerImageStreamDefault(pool *StatePool) error {
st := pool.SystemState()
err := applyToAllModelSettings(st, func(doc *settingsDoc) (bool, error) {
ciStreamVal, keySet := doc.Settings[config.ContainerImageStreamKey]
if keySet {
if ciStream, _ := ciStreamVal.(string); ciStream != "" {
return false, nil
}
}
doc.Settings[config.ContainerImageStreamKey] = "released"
return true, nil
})
if err != nil {
return errors.Trace(err)
}
return nil
} | go | func UpgradeContainerImageStreamDefault(pool *StatePool) error {
st := pool.SystemState()
err := applyToAllModelSettings(st, func(doc *settingsDoc) (bool, error) {
ciStreamVal, keySet := doc.Settings[config.ContainerImageStreamKey]
if keySet {
if ciStream, _ := ciStreamVal.(string); ciStream != "" {
return false, nil
}
}
doc.Settings[config.ContainerImageStreamKey] = "released"
return true, nil
})
if err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"UpgradeContainerImageStreamDefault",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"err",
":=",
"applyToAllModelSettings",
"(",
"st",
",",
"func",
"(",
"doc",
"*",
"settingsDoc",
")",
"(",
"bool",
",",
"error",
")",
"{",
"ciStreamVal",
",",
"keySet",
":=",
"doc",
".",
"Settings",
"[",
"config",
".",
"ContainerImageStreamKey",
"]",
"\n",
"if",
"keySet",
"{",
"if",
"ciStream",
",",
"_",
":=",
"ciStreamVal",
".",
"(",
"string",
")",
";",
"ciStream",
"!=",
"\"",
"\"",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"doc",
".",
"Settings",
"[",
"config",
".",
"ContainerImageStreamKey",
"]",
"=",
"\"",
"\"",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpgradeDefaultContainerImageStreamConfig ensures that the config value for
// container-image-stream is set to its default value, "released". | [
"UpgradeDefaultContainerImageStreamConfig",
"ensures",
"that",
"the",
"config",
"value",
"for",
"container",
"-",
"image",
"-",
"stream",
"is",
"set",
"to",
"its",
"default",
"value",
"released",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1591-L1607 |
5,167 | juju/juju | state/upgrades.go | ReplicaSetMembers | func ReplicaSetMembers(pool *StatePool) ([]replicaset.Member, error) {
return replicaset.CurrentMembers(pool.SystemState().MongoSession())
} | go | func ReplicaSetMembers(pool *StatePool) ([]replicaset.Member, error) {
return replicaset.CurrentMembers(pool.SystemState().MongoSession())
} | [
"func",
"ReplicaSetMembers",
"(",
"pool",
"*",
"StatePool",
")",
"(",
"[",
"]",
"replicaset",
".",
"Member",
",",
"error",
")",
"{",
"return",
"replicaset",
".",
"CurrentMembers",
"(",
"pool",
".",
"SystemState",
"(",
")",
".",
"MongoSession",
"(",
")",
")",
"\n",
"}"
] | // ReplicaSetMembers gets the members of the current Mongo replica
// set. These are needed to bootstrap the raft cluster in an upgrade
// and using MongoSession directly from an upgrade steps would make
// testing difficult. | [
"ReplicaSetMembers",
"gets",
"the",
"members",
"of",
"the",
"current",
"Mongo",
"replica",
"set",
".",
"These",
"are",
"needed",
"to",
"bootstrap",
"the",
"raft",
"cluster",
"in",
"an",
"upgrade",
"and",
"using",
"MongoSession",
"directly",
"from",
"an",
"upgrade",
"steps",
"would",
"make",
"testing",
"difficult",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1673-L1675 |
5,168 | juju/juju | state/upgrades.go | LegacyLeases | func LegacyLeases(pool *StatePool, localTime time.Time) (map[corelease.Key]corelease.Info, error) {
st := pool.SystemState()
reader, err := globalclock.NewReader(globalclock.ReaderConfig{
Config: globalclock.Config{
Collection: globalClockC,
Mongo: &environMongo{state: st},
},
})
if err != nil {
return nil, errors.Trace(err)
}
globalTime, err := reader.Now()
// This needs to be the raw collection so we see all leases across
// models.
leaseCollection, closer := st.db().GetRawCollection(leasesC)
defer closer()
iter := leaseCollection.Find(nil).Iter()
results := make(map[corelease.Key]corelease.Info)
var doc struct {
Namespace string `bson:"namespace"`
ModelUUID string `bson:"model-uuid"`
Name string `bson:"name"`
Holder string `bson:"holder"`
Start int64 `bson:"start"`
Duration time.Duration `bson:"duration"`
}
for iter.Next(&doc) {
startTime := time.Unix(0, doc.Start)
globalExpiry := startTime.Add(doc.Duration)
remaining := globalExpiry.Sub(globalTime)
localExpiry := localTime.Add(remaining)
key := corelease.Key{
Namespace: doc.Namespace,
ModelUUID: doc.ModelUUID,
Lease: doc.Name,
}
results[key] = corelease.Info{
Holder: doc.Holder,
Expiry: localExpiry,
Trapdoor: nil,
}
}
if err := iter.Close(); err != nil {
return nil, errors.Trace(err)
}
return results, nil
} | go | func LegacyLeases(pool *StatePool, localTime time.Time) (map[corelease.Key]corelease.Info, error) {
st := pool.SystemState()
reader, err := globalclock.NewReader(globalclock.ReaderConfig{
Config: globalclock.Config{
Collection: globalClockC,
Mongo: &environMongo{state: st},
},
})
if err != nil {
return nil, errors.Trace(err)
}
globalTime, err := reader.Now()
// This needs to be the raw collection so we see all leases across
// models.
leaseCollection, closer := st.db().GetRawCollection(leasesC)
defer closer()
iter := leaseCollection.Find(nil).Iter()
results := make(map[corelease.Key]corelease.Info)
var doc struct {
Namespace string `bson:"namespace"`
ModelUUID string `bson:"model-uuid"`
Name string `bson:"name"`
Holder string `bson:"holder"`
Start int64 `bson:"start"`
Duration time.Duration `bson:"duration"`
}
for iter.Next(&doc) {
startTime := time.Unix(0, doc.Start)
globalExpiry := startTime.Add(doc.Duration)
remaining := globalExpiry.Sub(globalTime)
localExpiry := localTime.Add(remaining)
key := corelease.Key{
Namespace: doc.Namespace,
ModelUUID: doc.ModelUUID,
Lease: doc.Name,
}
results[key] = corelease.Info{
Holder: doc.Holder,
Expiry: localExpiry,
Trapdoor: nil,
}
}
if err := iter.Close(); err != nil {
return nil, errors.Trace(err)
}
return results, nil
} | [
"func",
"LegacyLeases",
"(",
"pool",
"*",
"StatePool",
",",
"localTime",
"time",
".",
"Time",
")",
"(",
"map",
"[",
"corelease",
".",
"Key",
"]",
"corelease",
".",
"Info",
",",
"error",
")",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"reader",
",",
"err",
":=",
"globalclock",
".",
"NewReader",
"(",
"globalclock",
".",
"ReaderConfig",
"{",
"Config",
":",
"globalclock",
".",
"Config",
"{",
"Collection",
":",
"globalClockC",
",",
"Mongo",
":",
"&",
"environMongo",
"{",
"state",
":",
"st",
"}",
",",
"}",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"globalTime",
",",
"err",
":=",
"reader",
".",
"Now",
"(",
")",
"\n\n",
"// This needs to be the raw collection so we see all leases across",
"// models.",
"leaseCollection",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"leasesC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"iter",
":=",
"leaseCollection",
".",
"Find",
"(",
"nil",
")",
".",
"Iter",
"(",
")",
"\n",
"results",
":=",
"make",
"(",
"map",
"[",
"corelease",
".",
"Key",
"]",
"corelease",
".",
"Info",
")",
"\n\n",
"var",
"doc",
"struct",
"{",
"Namespace",
"string",
"`bson:\"namespace\"`",
"\n",
"ModelUUID",
"string",
"`bson:\"model-uuid\"`",
"\n",
"Name",
"string",
"`bson:\"name\"`",
"\n",
"Holder",
"string",
"`bson:\"holder\"`",
"\n",
"Start",
"int64",
"`bson:\"start\"`",
"\n",
"Duration",
"time",
".",
"Duration",
"`bson:\"duration\"`",
"\n",
"}",
"\n\n",
"for",
"iter",
".",
"Next",
"(",
"&",
"doc",
")",
"{",
"startTime",
":=",
"time",
".",
"Unix",
"(",
"0",
",",
"doc",
".",
"Start",
")",
"\n",
"globalExpiry",
":=",
"startTime",
".",
"Add",
"(",
"doc",
".",
"Duration",
")",
"\n",
"remaining",
":=",
"globalExpiry",
".",
"Sub",
"(",
"globalTime",
")",
"\n",
"localExpiry",
":=",
"localTime",
".",
"Add",
"(",
"remaining",
")",
"\n",
"key",
":=",
"corelease",
".",
"Key",
"{",
"Namespace",
":",
"doc",
".",
"Namespace",
",",
"ModelUUID",
":",
"doc",
".",
"ModelUUID",
",",
"Lease",
":",
"doc",
".",
"Name",
",",
"}",
"\n",
"results",
"[",
"key",
"]",
"=",
"corelease",
".",
"Info",
"{",
"Holder",
":",
"doc",
".",
"Holder",
",",
"Expiry",
":",
"localExpiry",
",",
"Trapdoor",
":",
"nil",
",",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"iter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // LegacyLeases returns information about all of the leases in the
// state-based lease store. | [
"LegacyLeases",
"returns",
"information",
"about",
"all",
"of",
"the",
"leases",
"in",
"the",
"state",
"-",
"based",
"lease",
"store",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1728-L1777 |
5,169 | juju/juju | state/upgrades.go | MigrateAddModelPermissions | func MigrateAddModelPermissions(pool *StatePool) error {
st := pool.SystemState()
controllerInfo, err := st.ControllerInfo()
if err != nil {
return errors.Trace(err)
}
coll, closer := st.db().GetRawCollection(permissionsC)
defer closer()
query := bson.M{
"_id": bson.M{"$regex": "^" + controllerKey(st.ControllerUUID()) + "#us#.*"},
"access": "add-model",
}
iter := coll.Find(query).Iter()
var doc struct {
DocId string `bson:"_id"`
ObjectGlobalKey string `bson:"object-global-key"`
SubjectGlobalKey string `bson:"subject-global-key"`
Access string `bson:"access"`
}
var ops []txn.Op
// Set all the existng controller add-model permissions back to login.
// Create a new cloud permission for add-model.
for iter.Next(&doc) {
ops = append(ops, txn.Op{
C: permissionsC,
Id: doc.DocId,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"access": "login"}},
})
ops = append(ops,
createPermissionOp(cloudGlobalKey(controllerInfo.CloudName), doc.SubjectGlobalKey, permission.AddModelAccess))
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | go | func MigrateAddModelPermissions(pool *StatePool) error {
st := pool.SystemState()
controllerInfo, err := st.ControllerInfo()
if err != nil {
return errors.Trace(err)
}
coll, closer := st.db().GetRawCollection(permissionsC)
defer closer()
query := bson.M{
"_id": bson.M{"$regex": "^" + controllerKey(st.ControllerUUID()) + "#us#.*"},
"access": "add-model",
}
iter := coll.Find(query).Iter()
var doc struct {
DocId string `bson:"_id"`
ObjectGlobalKey string `bson:"object-global-key"`
SubjectGlobalKey string `bson:"subject-global-key"`
Access string `bson:"access"`
}
var ops []txn.Op
// Set all the existng controller add-model permissions back to login.
// Create a new cloud permission for add-model.
for iter.Next(&doc) {
ops = append(ops, txn.Op{
C: permissionsC,
Id: doc.DocId,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"access": "login"}},
})
ops = append(ops,
createPermissionOp(cloudGlobalKey(controllerInfo.CloudName), doc.SubjectGlobalKey, permission.AddModelAccess))
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | [
"func",
"MigrateAddModelPermissions",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"controllerInfo",
",",
"err",
":=",
"st",
".",
"ControllerInfo",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"coll",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"permissionsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"query",
":=",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"+",
"controllerKey",
"(",
"st",
".",
"ControllerUUID",
"(",
")",
")",
"+",
"\"",
"\"",
"}",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"}",
"\n",
"iter",
":=",
"coll",
".",
"Find",
"(",
"query",
")",
".",
"Iter",
"(",
")",
"\n\n",
"var",
"doc",
"struct",
"{",
"DocId",
"string",
"`bson:\"_id\"`",
"\n",
"ObjectGlobalKey",
"string",
"`bson:\"object-global-key\"`",
"\n",
"SubjectGlobalKey",
"string",
"`bson:\"subject-global-key\"`",
"\n",
"Access",
"string",
"`bson:\"access\"`",
"\n",
"}",
"\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n\n",
"// Set all the existng controller add-model permissions back to login.",
"// Create a new cloud permission for add-model.",
"for",
"iter",
".",
"Next",
"(",
"&",
"doc",
")",
"{",
"ops",
"=",
"append",
"(",
"ops",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"permissionsC",
",",
"Id",
":",
"doc",
".",
"DocId",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"}",
"}",
",",
"}",
")",
"\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"createPermissionOp",
"(",
"cloudGlobalKey",
"(",
"controllerInfo",
".",
"CloudName",
")",
",",
"doc",
".",
"SubjectGlobalKey",
",",
"permission",
".",
"AddModelAccess",
")",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"iter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ops",
")",
">",
"0",
"{",
"return",
"errors",
".",
"Trace",
"(",
"st",
".",
"runRawTransaction",
"(",
"ops",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // MigrateAddModelPermissions converts add-model permissions on the controller
// to add-model permissions on the controller cloud. | [
"MigrateAddModelPermissions",
"converts",
"add",
"-",
"model",
"permissions",
"on",
"the",
"controller",
"to",
"add",
"-",
"model",
"permissions",
"on",
"the",
"controller",
"cloud",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1781-L1824 |
5,170 | juju/juju | state/upgrades.go | SetEnableDiskUUIDOnVsphere | func SetEnableDiskUUIDOnVsphere(pool *StatePool) error {
return errors.Trace(applyToAllModelSettings(pool.SystemState(), func(doc *settingsDoc) (bool, error) {
typeVal, found := doc.Settings["type"]
if !found {
return false, nil
}
typeStr, ok := typeVal.(string)
if !ok || typeStr != "vsphere" {
return false, nil
}
_, found = doc.Settings["enable-disk-uuid"]
if found {
// If the config option's already been set don't change
// it.
return false, nil
}
doc.Settings["enable-disk-uuid"] = false
return true, nil
}))
} | go | func SetEnableDiskUUIDOnVsphere(pool *StatePool) error {
return errors.Trace(applyToAllModelSettings(pool.SystemState(), func(doc *settingsDoc) (bool, error) {
typeVal, found := doc.Settings["type"]
if !found {
return false, nil
}
typeStr, ok := typeVal.(string)
if !ok || typeStr != "vsphere" {
return false, nil
}
_, found = doc.Settings["enable-disk-uuid"]
if found {
// If the config option's already been set don't change
// it.
return false, nil
}
doc.Settings["enable-disk-uuid"] = false
return true, nil
}))
} | [
"func",
"SetEnableDiskUUIDOnVsphere",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"return",
"errors",
".",
"Trace",
"(",
"applyToAllModelSettings",
"(",
"pool",
".",
"SystemState",
"(",
")",
",",
"func",
"(",
"doc",
"*",
"settingsDoc",
")",
"(",
"bool",
",",
"error",
")",
"{",
"typeVal",
",",
"found",
":=",
"doc",
".",
"Settings",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"typeStr",
",",
"ok",
":=",
"typeVal",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"||",
"typeStr",
"!=",
"\"",
"\"",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"_",
",",
"found",
"=",
"doc",
".",
"Settings",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"found",
"{",
"// If the config option's already been set don't change",
"// it.",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"doc",
".",
"Settings",
"[",
"\"",
"\"",
"]",
"=",
"false",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}",
")",
")",
"\n",
"}"
] | // SetEnableDiskUUIDOnVsphere updates the settings for all vsphere
// models to have enable-disk-uuid=false. The new default is true, but
// this maintains the previous behaviour for upgraded models. | [
"SetEnableDiskUUIDOnVsphere",
"updates",
"the",
"settings",
"for",
"all",
"vsphere",
"models",
"to",
"have",
"enable",
"-",
"disk",
"-",
"uuid",
"=",
"false",
".",
"The",
"new",
"default",
"is",
"true",
"but",
"this",
"maintains",
"the",
"previous",
"behaviour",
"for",
"upgraded",
"models",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1829-L1848 |
5,171 | juju/juju | state/upgrades.go | UpdateInheritedControllerConfig | func UpdateInheritedControllerConfig(pool *StatePool) error {
st := pool.SystemState()
model, err := st.Model()
if err != nil {
return errors.Trace(err)
}
key := cloudGlobalKey(model.Cloud())
var ops []txn.Op
coll, closer := st.db().GetRawCollection(globalSettingsC)
defer closer()
iter := coll.FindId("controller").Iter()
defer iter.Close()
var doc settingsDoc
for iter.Next(&doc) {
ops = append(ops, txn.Op{
C: globalSettingsC,
Id: doc.DocID,
Remove: true,
Assert: txn.DocExists,
})
doc.DocID = key
ops = append(ops, txn.Op{
C: globalSettingsC,
Id: key,
Insert: doc,
Assert: txn.DocMissing,
})
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
err = errors.Trace(st.runRawTransaction(ops))
return err
}
return nil
} | go | func UpdateInheritedControllerConfig(pool *StatePool) error {
st := pool.SystemState()
model, err := st.Model()
if err != nil {
return errors.Trace(err)
}
key := cloudGlobalKey(model.Cloud())
var ops []txn.Op
coll, closer := st.db().GetRawCollection(globalSettingsC)
defer closer()
iter := coll.FindId("controller").Iter()
defer iter.Close()
var doc settingsDoc
for iter.Next(&doc) {
ops = append(ops, txn.Op{
C: globalSettingsC,
Id: doc.DocID,
Remove: true,
Assert: txn.DocExists,
})
doc.DocID = key
ops = append(ops, txn.Op{
C: globalSettingsC,
Id: key,
Insert: doc,
Assert: txn.DocMissing,
})
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
err = errors.Trace(st.runRawTransaction(ops))
return err
}
return nil
} | [
"func",
"UpdateInheritedControllerConfig",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"model",
",",
"err",
":=",
"st",
".",
"Model",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"key",
":=",
"cloudGlobalKey",
"(",
"model",
".",
"Cloud",
"(",
")",
")",
"\n\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"coll",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetRawCollection",
"(",
"globalSettingsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"iter",
":=",
"coll",
".",
"FindId",
"(",
"\"",
"\"",
")",
".",
"Iter",
"(",
")",
"\n",
"defer",
"iter",
".",
"Close",
"(",
")",
"\n",
"var",
"doc",
"settingsDoc",
"\n",
"for",
"iter",
".",
"Next",
"(",
"&",
"doc",
")",
"{",
"ops",
"=",
"append",
"(",
"ops",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"globalSettingsC",
",",
"Id",
":",
"doc",
".",
"DocID",
",",
"Remove",
":",
"true",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"}",
")",
"\n",
"doc",
".",
"DocID",
"=",
"key",
"\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"globalSettingsC",
",",
"Id",
":",
"key",
",",
"Insert",
":",
"doc",
",",
"Assert",
":",
"txn",
".",
"DocMissing",
",",
"}",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"iter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ops",
")",
">",
"0",
"{",
"err",
"=",
"errors",
".",
"Trace",
"(",
"st",
".",
"runRawTransaction",
"(",
"ops",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpdateInheritedControllerConfig migrates the existing global
// settings doc keyed on "controller" to be keyed on the cloud name. | [
"UpdateInheritedControllerConfig",
"migrates",
"the",
"existing",
"global",
"settings",
"doc",
"keyed",
"on",
"controller",
"to",
"be",
"keyed",
"on",
"the",
"cloud",
"name",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1852-L1889 |
5,172 | juju/juju | state/upgrades.go | EnsureDefaultModificationStatus | func EnsureDefaultModificationStatus(pool *StatePool) error {
st := pool.SystemState()
db := st.db()
machineCol, machineCloser := db.GetRawCollection(machinesC)
defer machineCloser()
machineIter := machineCol.Find(nil).Iter()
defer machineIter.Close()
statusCol, statusCloser := db.GetRawCollection(statusesC)
defer statusCloser()
var ops []txn.Op
var machine machineDoc
updatedTime := st.clock().Now().UnixNano()
for machineIter.Next(&machine) {
// Since we are using a raw collection, we need to manually
// ensure that we prefix the IDs with the model-uuid.
localID := machineGlobalModificationKey(machine.Id)
key := ensureModelUUID(machine.ModelUUID, localID)
// We only need to migrate machines that don't have a modification
// status document. So we need to first check if there is one, before
// creating a txn.Op for the missing document.
var doc statusDoc
err := statusCol.Find(bson.D{{"_id", key}}).Select(bson.D{{"_id", 1}}).One(&doc)
if err == nil {
continue
} else if err != mgo.ErrNotFound {
return errors.Trace(err)
}
rawDoc := statusDoc{
ModelUUID: machine.ModelUUID,
Status: status.Idle,
Updated: updatedTime,
}
ops = append(ops, txn.Op{
C: statusesC,
Id: key,
Assert: txn.DocMissing,
Insert: rawDoc,
})
}
if err := machineIter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | go | func EnsureDefaultModificationStatus(pool *StatePool) error {
st := pool.SystemState()
db := st.db()
machineCol, machineCloser := db.GetRawCollection(machinesC)
defer machineCloser()
machineIter := machineCol.Find(nil).Iter()
defer machineIter.Close()
statusCol, statusCloser := db.GetRawCollection(statusesC)
defer statusCloser()
var ops []txn.Op
var machine machineDoc
updatedTime := st.clock().Now().UnixNano()
for machineIter.Next(&machine) {
// Since we are using a raw collection, we need to manually
// ensure that we prefix the IDs with the model-uuid.
localID := machineGlobalModificationKey(machine.Id)
key := ensureModelUUID(machine.ModelUUID, localID)
// We only need to migrate machines that don't have a modification
// status document. So we need to first check if there is one, before
// creating a txn.Op for the missing document.
var doc statusDoc
err := statusCol.Find(bson.D{{"_id", key}}).Select(bson.D{{"_id", 1}}).One(&doc)
if err == nil {
continue
} else if err != mgo.ErrNotFound {
return errors.Trace(err)
}
rawDoc := statusDoc{
ModelUUID: machine.ModelUUID,
Status: status.Idle,
Updated: updatedTime,
}
ops = append(ops, txn.Op{
C: statusesC,
Id: key,
Assert: txn.DocMissing,
Insert: rawDoc,
})
}
if err := machineIter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | [
"func",
"EnsureDefaultModificationStatus",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"db",
":=",
"st",
".",
"db",
"(",
")",
"\n\n",
"machineCol",
",",
"machineCloser",
":=",
"db",
".",
"GetRawCollection",
"(",
"machinesC",
")",
"\n",
"defer",
"machineCloser",
"(",
")",
"\n",
"machineIter",
":=",
"machineCol",
".",
"Find",
"(",
"nil",
")",
".",
"Iter",
"(",
")",
"\n",
"defer",
"machineIter",
".",
"Close",
"(",
")",
"\n\n",
"statusCol",
",",
"statusCloser",
":=",
"db",
".",
"GetRawCollection",
"(",
"statusesC",
")",
"\n",
"defer",
"statusCloser",
"(",
")",
"\n\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"var",
"machine",
"machineDoc",
"\n",
"updatedTime",
":=",
"st",
".",
"clock",
"(",
")",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
"\n",
"for",
"machineIter",
".",
"Next",
"(",
"&",
"machine",
")",
"{",
"// Since we are using a raw collection, we need to manually",
"// ensure that we prefix the IDs with the model-uuid.",
"localID",
":=",
"machineGlobalModificationKey",
"(",
"machine",
".",
"Id",
")",
"\n",
"key",
":=",
"ensureModelUUID",
"(",
"machine",
".",
"ModelUUID",
",",
"localID",
")",
"\n\n",
"// We only need to migrate machines that don't have a modification",
"// status document. So we need to first check if there is one, before",
"// creating a txn.Op for the missing document.",
"var",
"doc",
"statusDoc",
"\n",
"err",
":=",
"statusCol",
".",
"Find",
"(",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"key",
"}",
"}",
")",
".",
"Select",
"(",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"1",
"}",
"}",
")",
".",
"One",
"(",
"&",
"doc",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"else",
"if",
"err",
"!=",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"rawDoc",
":=",
"statusDoc",
"{",
"ModelUUID",
":",
"machine",
".",
"ModelUUID",
",",
"Status",
":",
"status",
".",
"Idle",
",",
"Updated",
":",
"updatedTime",
",",
"}",
"\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"statusesC",
",",
"Id",
":",
"key",
",",
"Assert",
":",
"txn",
".",
"DocMissing",
",",
"Insert",
":",
"rawDoc",
",",
"}",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"machineIter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ops",
")",
">",
"0",
"{",
"return",
"errors",
".",
"Trace",
"(",
"st",
".",
"runRawTransaction",
"(",
"ops",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // EnsureDefaultModificationStatus ensures that there is a modification status
// document for every machine in the statuses. | [
"EnsureDefaultModificationStatus",
"ensures",
"that",
"there",
"is",
"a",
"modification",
"status",
"document",
"for",
"every",
"machine",
"in",
"the",
"statuses",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L1988-L2039 |
5,173 | juju/juju | state/upgrades.go | EnsureApplicationDeviceConstraints | func EnsureApplicationDeviceConstraints(pool *StatePool) error {
st := pool.SystemState()
db := st.db()
applicationCol, applicationCloser := db.GetRawCollection(applicationsC)
defer applicationCloser()
applicationIter := applicationCol.Find(nil).Iter()
defer applicationIter.Close()
constraintsCol, constraintsCloser := db.GetRawCollection(deviceConstraintsC)
defer constraintsCloser()
var ops []txn.Op
var application applicationDoc
for applicationIter.Next(&application) {
// Since we are using a raw collection, we need to manually
// ensure that we prefix the IDs with the model-uuid.
localID := applicationDeviceConstraintsKey(application.Name, application.CharmURL)
key := ensureModelUUID(application.ModelUUID, localID)
// We only need to migrate applications that don't have a device
// constraints document. So we need to first check if there is one, before
// creating a txn.Op for the missing document.
var doc statusDoc
err := constraintsCol.Find(bson.D{{"_id", key}}).Select(bson.D{{"_id", 1}}).One(&doc)
if err == nil {
continue
} else if err != mgo.ErrNotFound {
return errors.Trace(err)
}
ops = append(ops, txn.Op{
C: deviceConstraintsC,
Id: key,
Assert: txn.DocMissing,
Insert: deviceConstraintsDoc{},
})
}
if err := applicationIter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | go | func EnsureApplicationDeviceConstraints(pool *StatePool) error {
st := pool.SystemState()
db := st.db()
applicationCol, applicationCloser := db.GetRawCollection(applicationsC)
defer applicationCloser()
applicationIter := applicationCol.Find(nil).Iter()
defer applicationIter.Close()
constraintsCol, constraintsCloser := db.GetRawCollection(deviceConstraintsC)
defer constraintsCloser()
var ops []txn.Op
var application applicationDoc
for applicationIter.Next(&application) {
// Since we are using a raw collection, we need to manually
// ensure that we prefix the IDs with the model-uuid.
localID := applicationDeviceConstraintsKey(application.Name, application.CharmURL)
key := ensureModelUUID(application.ModelUUID, localID)
// We only need to migrate applications that don't have a device
// constraints document. So we need to first check if there is one, before
// creating a txn.Op for the missing document.
var doc statusDoc
err := constraintsCol.Find(bson.D{{"_id", key}}).Select(bson.D{{"_id", 1}}).One(&doc)
if err == nil {
continue
} else if err != mgo.ErrNotFound {
return errors.Trace(err)
}
ops = append(ops, txn.Op{
C: deviceConstraintsC,
Id: key,
Assert: txn.DocMissing,
Insert: deviceConstraintsDoc{},
})
}
if err := applicationIter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
} | [
"func",
"EnsureApplicationDeviceConstraints",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"st",
":=",
"pool",
".",
"SystemState",
"(",
")",
"\n",
"db",
":=",
"st",
".",
"db",
"(",
")",
"\n\n",
"applicationCol",
",",
"applicationCloser",
":=",
"db",
".",
"GetRawCollection",
"(",
"applicationsC",
")",
"\n",
"defer",
"applicationCloser",
"(",
")",
"\n",
"applicationIter",
":=",
"applicationCol",
".",
"Find",
"(",
"nil",
")",
".",
"Iter",
"(",
")",
"\n",
"defer",
"applicationIter",
".",
"Close",
"(",
")",
"\n\n",
"constraintsCol",
",",
"constraintsCloser",
":=",
"db",
".",
"GetRawCollection",
"(",
"deviceConstraintsC",
")",
"\n",
"defer",
"constraintsCloser",
"(",
")",
"\n\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"var",
"application",
"applicationDoc",
"\n",
"for",
"applicationIter",
".",
"Next",
"(",
"&",
"application",
")",
"{",
"// Since we are using a raw collection, we need to manually",
"// ensure that we prefix the IDs with the model-uuid.",
"localID",
":=",
"applicationDeviceConstraintsKey",
"(",
"application",
".",
"Name",
",",
"application",
".",
"CharmURL",
")",
"\n",
"key",
":=",
"ensureModelUUID",
"(",
"application",
".",
"ModelUUID",
",",
"localID",
")",
"\n\n",
"// We only need to migrate applications that don't have a device",
"// constraints document. So we need to first check if there is one, before",
"// creating a txn.Op for the missing document.",
"var",
"doc",
"statusDoc",
"\n",
"err",
":=",
"constraintsCol",
".",
"Find",
"(",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"key",
"}",
"}",
")",
".",
"Select",
"(",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"1",
"}",
"}",
")",
".",
"One",
"(",
"&",
"doc",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"else",
"if",
"err",
"!=",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"deviceConstraintsC",
",",
"Id",
":",
"key",
",",
"Assert",
":",
"txn",
".",
"DocMissing",
",",
"Insert",
":",
"deviceConstraintsDoc",
"{",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"applicationIter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ops",
")",
">",
"0",
"{",
"return",
"errors",
".",
"Trace",
"(",
"st",
".",
"runRawTransaction",
"(",
"ops",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // EnsureApplicationDeviceConstraints ensures that there is a device
// constraints document for every application. | [
"EnsureApplicationDeviceConstraints",
"ensures",
"that",
"there",
"is",
"a",
"device",
"constraints",
"document",
"for",
"every",
"application",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L2043-L2088 |
5,174 | juju/juju | state/upgrades.go | RemoveInstanceCharmProfileDataCollection | func RemoveInstanceCharmProfileDataCollection(pool *StatePool) error {
db := pool.SystemState().MongoSession().DB(jujuDB)
instanceCharmProfileData := db.C("instanceCharmProfileData")
if err := instanceCharmProfileData.DropCollection(); err != nil {
// If the namespace is already missing, that's fine.
if isMgoNamespaceNotFound(err) {
return nil
}
return errors.Annotate(err, "failed to drop instanceCharmProfileData collection")
}
return nil
} | go | func RemoveInstanceCharmProfileDataCollection(pool *StatePool) error {
db := pool.SystemState().MongoSession().DB(jujuDB)
instanceCharmProfileData := db.C("instanceCharmProfileData")
if err := instanceCharmProfileData.DropCollection(); err != nil {
// If the namespace is already missing, that's fine.
if isMgoNamespaceNotFound(err) {
return nil
}
return errors.Annotate(err, "failed to drop instanceCharmProfileData collection")
}
return nil
} | [
"func",
"RemoveInstanceCharmProfileDataCollection",
"(",
"pool",
"*",
"StatePool",
")",
"error",
"{",
"db",
":=",
"pool",
".",
"SystemState",
"(",
")",
".",
"MongoSession",
"(",
")",
".",
"DB",
"(",
"jujuDB",
")",
"\n",
"instanceCharmProfileData",
":=",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"instanceCharmProfileData",
".",
"DropCollection",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"// If the namespace is already missing, that's fine.",
"if",
"isMgoNamespaceNotFound",
"(",
"err",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // RemoveInstanceCharmProfileDataCollection removes the
// instanceCharmProfileData collection on upgrade. | [
"RemoveInstanceCharmProfileDataCollection",
"removes",
"the",
"instanceCharmProfileData",
"collection",
"on",
"upgrade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrades.go#L2092-L2103 |
5,175 | juju/juju | storage/provider/dummy/volumesource.go | CreateVolumes | func (s *VolumeSource) CreateVolumes(ctx context.ProviderCallContext, params []storage.VolumeParams) ([]storage.CreateVolumesResult, error) {
s.MethodCall(s, "CreateVolumes", ctx, params)
if s.CreateVolumesFunc != nil {
return s.CreateVolumesFunc(ctx, params)
}
return nil, errors.NotImplementedf("CreateVolumes")
} | go | func (s *VolumeSource) CreateVolumes(ctx context.ProviderCallContext, params []storage.VolumeParams) ([]storage.CreateVolumesResult, error) {
s.MethodCall(s, "CreateVolumes", ctx, params)
if s.CreateVolumesFunc != nil {
return s.CreateVolumesFunc(ctx, params)
}
return nil, errors.NotImplementedf("CreateVolumes")
} | [
"func",
"(",
"s",
"*",
"VolumeSource",
")",
"CreateVolumes",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"params",
"[",
"]",
"storage",
".",
"VolumeParams",
")",
"(",
"[",
"]",
"storage",
".",
"CreateVolumesResult",
",",
"error",
")",
"{",
"s",
".",
"MethodCall",
"(",
"s",
",",
"\"",
"\"",
",",
"ctx",
",",
"params",
")",
"\n",
"if",
"s",
".",
"CreateVolumesFunc",
"!=",
"nil",
"{",
"return",
"s",
".",
"CreateVolumesFunc",
"(",
"ctx",
",",
"params",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"NotImplementedf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // CreateVolumes is defined on storage.VolumeSource. | [
"CreateVolumes",
"is",
"defined",
"on",
"storage",
".",
"VolumeSource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/volumesource.go#L31-L37 |
5,176 | juju/juju | storage/provider/dummy/volumesource.go | ListVolumes | func (s *VolumeSource) ListVolumes(ctx context.ProviderCallContext) ([]string, error) {
s.MethodCall(s, "ListVolumes", ctx)
if s.ListVolumesFunc != nil {
return s.ListVolumesFunc(ctx)
}
return nil, nil
} | go | func (s *VolumeSource) ListVolumes(ctx context.ProviderCallContext) ([]string, error) {
s.MethodCall(s, "ListVolumes", ctx)
if s.ListVolumesFunc != nil {
return s.ListVolumesFunc(ctx)
}
return nil, nil
} | [
"func",
"(",
"s",
"*",
"VolumeSource",
")",
"ListVolumes",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"s",
".",
"MethodCall",
"(",
"s",
",",
"\"",
"\"",
",",
"ctx",
")",
"\n",
"if",
"s",
".",
"ListVolumesFunc",
"!=",
"nil",
"{",
"return",
"s",
".",
"ListVolumesFunc",
"(",
"ctx",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // ListVolumes is defined on storage.VolumeSource. | [
"ListVolumes",
"is",
"defined",
"on",
"storage",
".",
"VolumeSource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/volumesource.go#L40-L46 |
5,177 | juju/juju | storage/provider/dummy/volumesource.go | DescribeVolumes | func (s *VolumeSource) DescribeVolumes(ctx context.ProviderCallContext, volIds []string) ([]storage.DescribeVolumesResult, error) {
s.MethodCall(s, "DescribeVolumes", ctx, volIds)
if s.DescribeVolumesFunc != nil {
return s.DescribeVolumesFunc(ctx, volIds)
}
return nil, errors.NotImplementedf("DescribeVolumes")
} | go | func (s *VolumeSource) DescribeVolumes(ctx context.ProviderCallContext, volIds []string) ([]storage.DescribeVolumesResult, error) {
s.MethodCall(s, "DescribeVolumes", ctx, volIds)
if s.DescribeVolumesFunc != nil {
return s.DescribeVolumesFunc(ctx, volIds)
}
return nil, errors.NotImplementedf("DescribeVolumes")
} | [
"func",
"(",
"s",
"*",
"VolumeSource",
")",
"DescribeVolumes",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"volIds",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"storage",
".",
"DescribeVolumesResult",
",",
"error",
")",
"{",
"s",
".",
"MethodCall",
"(",
"s",
",",
"\"",
"\"",
",",
"ctx",
",",
"volIds",
")",
"\n",
"if",
"s",
".",
"DescribeVolumesFunc",
"!=",
"nil",
"{",
"return",
"s",
".",
"DescribeVolumesFunc",
"(",
"ctx",
",",
"volIds",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"NotImplementedf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // DescribeVolumes is defined on storage.VolumeSource. | [
"DescribeVolumes",
"is",
"defined",
"on",
"storage",
".",
"VolumeSource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/volumesource.go#L49-L55 |
5,178 | juju/juju | storage/provider/dummy/volumesource.go | DestroyVolumes | func (s *VolumeSource) DestroyVolumes(ctx context.ProviderCallContext, volIds []string) ([]error, error) {
s.MethodCall(s, "DestroyVolumes", ctx, volIds)
if s.DestroyVolumesFunc != nil {
return s.DestroyVolumesFunc(ctx, volIds)
}
return nil, errors.NotImplementedf("DestroyVolumes")
} | go | func (s *VolumeSource) DestroyVolumes(ctx context.ProviderCallContext, volIds []string) ([]error, error) {
s.MethodCall(s, "DestroyVolumes", ctx, volIds)
if s.DestroyVolumesFunc != nil {
return s.DestroyVolumesFunc(ctx, volIds)
}
return nil, errors.NotImplementedf("DestroyVolumes")
} | [
"func",
"(",
"s",
"*",
"VolumeSource",
")",
"DestroyVolumes",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"volIds",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"error",
",",
"error",
")",
"{",
"s",
".",
"MethodCall",
"(",
"s",
",",
"\"",
"\"",
",",
"ctx",
",",
"volIds",
")",
"\n",
"if",
"s",
".",
"DestroyVolumesFunc",
"!=",
"nil",
"{",
"return",
"s",
".",
"DestroyVolumesFunc",
"(",
"ctx",
",",
"volIds",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"NotImplementedf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // DestroyVolumes is defined on storage.VolumeSource. | [
"DestroyVolumes",
"is",
"defined",
"on",
"storage",
".",
"VolumeSource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/volumesource.go#L58-L64 |
5,179 | juju/juju | storage/provider/dummy/volumesource.go | ReleaseVolumes | func (s *VolumeSource) ReleaseVolumes(ctx context.ProviderCallContext, volIds []string) ([]error, error) {
s.MethodCall(s, "ReleaseVolumes", ctx, volIds)
if s.ReleaseVolumesFunc != nil {
return s.ReleaseVolumesFunc(ctx, volIds)
}
return nil, errors.NotImplementedf("ReleaseVolumes")
} | go | func (s *VolumeSource) ReleaseVolumes(ctx context.ProviderCallContext, volIds []string) ([]error, error) {
s.MethodCall(s, "ReleaseVolumes", ctx, volIds)
if s.ReleaseVolumesFunc != nil {
return s.ReleaseVolumesFunc(ctx, volIds)
}
return nil, errors.NotImplementedf("ReleaseVolumes")
} | [
"func",
"(",
"s",
"*",
"VolumeSource",
")",
"ReleaseVolumes",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"volIds",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"error",
",",
"error",
")",
"{",
"s",
".",
"MethodCall",
"(",
"s",
",",
"\"",
"\"",
",",
"ctx",
",",
"volIds",
")",
"\n",
"if",
"s",
".",
"ReleaseVolumesFunc",
"!=",
"nil",
"{",
"return",
"s",
".",
"ReleaseVolumesFunc",
"(",
"ctx",
",",
"volIds",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"NotImplementedf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // ReleaseVolumes is defined on storage.VolumeSource. | [
"ReleaseVolumes",
"is",
"defined",
"on",
"storage",
".",
"VolumeSource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/volumesource.go#L67-L73 |
5,180 | juju/juju | storage/provider/dummy/volumesource.go | ValidateVolumeParams | func (s *VolumeSource) ValidateVolumeParams(params storage.VolumeParams) error {
s.MethodCall(s, "ValidateVolumeParams", params)
if s.ValidateVolumeParamsFunc != nil {
return s.ValidateVolumeParamsFunc(params)
}
return nil
} | go | func (s *VolumeSource) ValidateVolumeParams(params storage.VolumeParams) error {
s.MethodCall(s, "ValidateVolumeParams", params)
if s.ValidateVolumeParamsFunc != nil {
return s.ValidateVolumeParamsFunc(params)
}
return nil
} | [
"func",
"(",
"s",
"*",
"VolumeSource",
")",
"ValidateVolumeParams",
"(",
"params",
"storage",
".",
"VolumeParams",
")",
"error",
"{",
"s",
".",
"MethodCall",
"(",
"s",
",",
"\"",
"\"",
",",
"params",
")",
"\n",
"if",
"s",
".",
"ValidateVolumeParamsFunc",
"!=",
"nil",
"{",
"return",
"s",
".",
"ValidateVolumeParamsFunc",
"(",
"params",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ValidateVolumeParams is defined on storage.VolumeSource. | [
"ValidateVolumeParams",
"is",
"defined",
"on",
"storage",
".",
"VolumeSource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/volumesource.go#L76-L82 |
5,181 | juju/juju | storage/provider/dummy/volumesource.go | AttachVolumes | func (s *VolumeSource) AttachVolumes(ctx context.ProviderCallContext, params []storage.VolumeAttachmentParams) ([]storage.AttachVolumesResult, error) {
s.MethodCall(s, "AttachVolumes", ctx, params)
if s.AttachVolumesFunc != nil {
return s.AttachVolumesFunc(ctx, params)
}
return nil, errors.NotImplementedf("AttachVolumes")
} | go | func (s *VolumeSource) AttachVolumes(ctx context.ProviderCallContext, params []storage.VolumeAttachmentParams) ([]storage.AttachVolumesResult, error) {
s.MethodCall(s, "AttachVolumes", ctx, params)
if s.AttachVolumesFunc != nil {
return s.AttachVolumesFunc(ctx, params)
}
return nil, errors.NotImplementedf("AttachVolumes")
} | [
"func",
"(",
"s",
"*",
"VolumeSource",
")",
"AttachVolumes",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"params",
"[",
"]",
"storage",
".",
"VolumeAttachmentParams",
")",
"(",
"[",
"]",
"storage",
".",
"AttachVolumesResult",
",",
"error",
")",
"{",
"s",
".",
"MethodCall",
"(",
"s",
",",
"\"",
"\"",
",",
"ctx",
",",
"params",
")",
"\n",
"if",
"s",
".",
"AttachVolumesFunc",
"!=",
"nil",
"{",
"return",
"s",
".",
"AttachVolumesFunc",
"(",
"ctx",
",",
"params",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"NotImplementedf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // AttachVolumes is defined on storage.VolumeSource. | [
"AttachVolumes",
"is",
"defined",
"on",
"storage",
".",
"VolumeSource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/volumesource.go#L85-L91 |
5,182 | juju/juju | storage/provider/dummy/volumesource.go | DetachVolumes | func (s *VolumeSource) DetachVolumes(ctx context.ProviderCallContext, params []storage.VolumeAttachmentParams) ([]error, error) {
s.MethodCall(s, "DetachVolumes", ctx, params)
if s.DetachVolumesFunc != nil {
return s.DetachVolumesFunc(ctx, params)
}
return nil, errors.NotImplementedf("DetachVolumes")
} | go | func (s *VolumeSource) DetachVolumes(ctx context.ProviderCallContext, params []storage.VolumeAttachmentParams) ([]error, error) {
s.MethodCall(s, "DetachVolumes", ctx, params)
if s.DetachVolumesFunc != nil {
return s.DetachVolumesFunc(ctx, params)
}
return nil, errors.NotImplementedf("DetachVolumes")
} | [
"func",
"(",
"s",
"*",
"VolumeSource",
")",
"DetachVolumes",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"params",
"[",
"]",
"storage",
".",
"VolumeAttachmentParams",
")",
"(",
"[",
"]",
"error",
",",
"error",
")",
"{",
"s",
".",
"MethodCall",
"(",
"s",
",",
"\"",
"\"",
",",
"ctx",
",",
"params",
")",
"\n",
"if",
"s",
".",
"DetachVolumesFunc",
"!=",
"nil",
"{",
"return",
"s",
".",
"DetachVolumesFunc",
"(",
"ctx",
",",
"params",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"NotImplementedf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // DetachVolumes is defined on storage.VolumeSource. | [
"DetachVolumes",
"is",
"defined",
"on",
"storage",
".",
"VolumeSource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/volumesource.go#L94-L100 |
5,183 | juju/juju | apiserver/common/watch.go | NewAgentEntityWatcher | func NewAgentEntityWatcher(st state.EntityFinder, resources facade.Resources, getCanWatch GetAuthFunc) *AgentEntityWatcher {
return &AgentEntityWatcher{
st: st,
resources: resources,
getCanWatch: getCanWatch,
}
} | go | func NewAgentEntityWatcher(st state.EntityFinder, resources facade.Resources, getCanWatch GetAuthFunc) *AgentEntityWatcher {
return &AgentEntityWatcher{
st: st,
resources: resources,
getCanWatch: getCanWatch,
}
} | [
"func",
"NewAgentEntityWatcher",
"(",
"st",
"state",
".",
"EntityFinder",
",",
"resources",
"facade",
".",
"Resources",
",",
"getCanWatch",
"GetAuthFunc",
")",
"*",
"AgentEntityWatcher",
"{",
"return",
"&",
"AgentEntityWatcher",
"{",
"st",
":",
"st",
",",
"resources",
":",
"resources",
",",
"getCanWatch",
":",
"getCanWatch",
",",
"}",
"\n",
"}"
] | // NewAgentEntityWatcher returns a new AgentEntityWatcher. The
// GetAuthFunc will be used on each invocation of Watch to determine
// current permissions. | [
"NewAgentEntityWatcher",
"returns",
"a",
"new",
"AgentEntityWatcher",
".",
"The",
"GetAuthFunc",
"will",
"be",
"used",
"on",
"each",
"invocation",
"of",
"Watch",
"to",
"determine",
"current",
"permissions",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/watch.go#L31-L37 |
5,184 | juju/juju | apiserver/common/watch.go | Watch | func (a *AgentEntityWatcher) Watch(args params.Entities) (params.NotifyWatchResults, error) {
result := params.NotifyWatchResults{
Results: make([]params.NotifyWatchResult, len(args.Entities)),
}
if len(args.Entities) == 0 {
return result, nil
}
canWatch, err := a.getCanWatch()
if err != nil {
return params.NotifyWatchResults{}, errors.Trace(err)
}
for i, entity := range args.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
result.Results[i].Error = ServerError(ErrPerm)
continue
}
err = ErrPerm
watcherId := ""
if canWatch(tag) {
watcherId, err = a.watchEntity(tag)
}
result.Results[i].NotifyWatcherId = watcherId
result.Results[i].Error = ServerError(err)
}
return result, nil
} | go | func (a *AgentEntityWatcher) Watch(args params.Entities) (params.NotifyWatchResults, error) {
result := params.NotifyWatchResults{
Results: make([]params.NotifyWatchResult, len(args.Entities)),
}
if len(args.Entities) == 0 {
return result, nil
}
canWatch, err := a.getCanWatch()
if err != nil {
return params.NotifyWatchResults{}, errors.Trace(err)
}
for i, entity := range args.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
result.Results[i].Error = ServerError(ErrPerm)
continue
}
err = ErrPerm
watcherId := ""
if canWatch(tag) {
watcherId, err = a.watchEntity(tag)
}
result.Results[i].NotifyWatcherId = watcherId
result.Results[i].Error = ServerError(err)
}
return result, nil
} | [
"func",
"(",
"a",
"*",
"AgentEntityWatcher",
")",
"Watch",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"NotifyWatchResults",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"NotifyWatchResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"NotifyWatchResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"if",
"len",
"(",
"args",
".",
"Entities",
")",
"==",
"0",
"{",
"return",
"result",
",",
"nil",
"\n",
"}",
"\n",
"canWatch",
",",
"err",
":=",
"a",
".",
"getCanWatch",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"NotifyWatchResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"entity",
":=",
"range",
"args",
".",
"Entities",
"{",
"tag",
",",
"err",
":=",
"names",
".",
"ParseTag",
"(",
"entity",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"ErrPerm",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"err",
"=",
"ErrPerm",
"\n",
"watcherId",
":=",
"\"",
"\"",
"\n",
"if",
"canWatch",
"(",
"tag",
")",
"{",
"watcherId",
",",
"err",
"=",
"a",
".",
"watchEntity",
"(",
"tag",
")",
"\n",
"}",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"NotifyWatcherId",
"=",
"watcherId",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // Watch starts an NotifyWatcher for each given entity. | [
"Watch",
"starts",
"an",
"NotifyWatcher",
"for",
"each",
"given",
"entity",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/watch.go#L60-L86 |
5,185 | juju/juju | cmd/juju/backups/backups.go | dumpMetadata | func (c *CommandBase) dumpMetadata(ctx *cmd.Context, result *params.BackupsMetadataResult) {
// TODO: (hml) 2018-04-26
// fix how --quiet and --verbose are handled with backup/restore commands
// should be ctx.Verbosef() here
fmt.Fprintf(ctx.Stdout, "backup ID: %q\n", result.ID)
fmt.Fprintf(ctx.Stdout, "checksum: %q\n", result.Checksum)
fmt.Fprintf(ctx.Stdout, "checksum format: %q\n", result.ChecksumFormat)
fmt.Fprintf(ctx.Stdout, "size (B): %d\n", result.Size)
fmt.Fprintf(ctx.Stdout, "stored: %v\n", result.Stored)
fmt.Fprintf(ctx.Stdout, "started: %v\n", result.Started)
fmt.Fprintf(ctx.Stdout, "finished: %v\n", result.Finished)
fmt.Fprintf(ctx.Stdout, "notes: %q\n", result.Notes)
fmt.Fprintf(ctx.Stdout, "model ID: %q\n", result.Model)
fmt.Fprintf(ctx.Stdout, "machine ID: %q\n", result.Machine)
fmt.Fprintf(ctx.Stdout, "created on host: %q\n", result.Hostname)
fmt.Fprintf(ctx.Stdout, "juju version: %v\n", result.Version)
} | go | func (c *CommandBase) dumpMetadata(ctx *cmd.Context, result *params.BackupsMetadataResult) {
// TODO: (hml) 2018-04-26
// fix how --quiet and --verbose are handled with backup/restore commands
// should be ctx.Verbosef() here
fmt.Fprintf(ctx.Stdout, "backup ID: %q\n", result.ID)
fmt.Fprintf(ctx.Stdout, "checksum: %q\n", result.Checksum)
fmt.Fprintf(ctx.Stdout, "checksum format: %q\n", result.ChecksumFormat)
fmt.Fprintf(ctx.Stdout, "size (B): %d\n", result.Size)
fmt.Fprintf(ctx.Stdout, "stored: %v\n", result.Stored)
fmt.Fprintf(ctx.Stdout, "started: %v\n", result.Started)
fmt.Fprintf(ctx.Stdout, "finished: %v\n", result.Finished)
fmt.Fprintf(ctx.Stdout, "notes: %q\n", result.Notes)
fmt.Fprintf(ctx.Stdout, "model ID: %q\n", result.Model)
fmt.Fprintf(ctx.Stdout, "machine ID: %q\n", result.Machine)
fmt.Fprintf(ctx.Stdout, "created on host: %q\n", result.Hostname)
fmt.Fprintf(ctx.Stdout, "juju version: %v\n", result.Version)
} | [
"func",
"(",
"c",
"*",
"CommandBase",
")",
"dumpMetadata",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
",",
"result",
"*",
"params",
".",
"BackupsMetadataResult",
")",
"{",
"// TODO: (hml) 2018-04-26",
"// fix how --quiet and --verbose are handled with backup/restore commands",
"// should be ctx.Verbosef() here",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stdout",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"ID",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stdout",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"Checksum",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stdout",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"ChecksumFormat",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stdout",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"Size",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stdout",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"Stored",
")",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stdout",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"Started",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stdout",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"Finished",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stdout",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"Notes",
")",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stdout",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"Model",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stdout",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"Machine",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stdout",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"Hostname",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"ctx",
".",
"Stdout",
",",
"\"",
"\\n",
"\"",
",",
"result",
".",
"Version",
")",
"\n",
"}"
] | // dumpMetadata writes the formatted backup metadata to stdout. | [
"dumpMetadata",
"writes",
"the",
"formatted",
"backup",
"metadata",
"to",
"stdout",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/backups/backups.go#L102-L120 |
5,186 | juju/juju | provider/azure/environprovider.go | Validate | func (cfg ProviderConfig) Validate() error {
if cfg.NewStorageClient == nil {
return errors.NotValidf("nil NewStorageClient")
}
if cfg.RetryClock == nil {
return errors.NotValidf("nil RetryClock")
}
if cfg.RandomWindowsAdminPassword == nil {
return errors.NotValidf("nil RandomWindowsAdminPassword")
}
if cfg.GenerateSSHKey == nil {
return errors.NotValidf("nil GenerateSSHKey")
}
if cfg.ServicePrincipalCreator == nil {
return errors.NotValidf("nil ServicePrincipalCreator")
}
if cfg.AzureCLI == nil {
return errors.NotValidf("nil AzureCLI")
}
return nil
} | go | func (cfg ProviderConfig) Validate() error {
if cfg.NewStorageClient == nil {
return errors.NotValidf("nil NewStorageClient")
}
if cfg.RetryClock == nil {
return errors.NotValidf("nil RetryClock")
}
if cfg.RandomWindowsAdminPassword == nil {
return errors.NotValidf("nil RandomWindowsAdminPassword")
}
if cfg.GenerateSSHKey == nil {
return errors.NotValidf("nil GenerateSSHKey")
}
if cfg.ServicePrincipalCreator == nil {
return errors.NotValidf("nil ServicePrincipalCreator")
}
if cfg.AzureCLI == nil {
return errors.NotValidf("nil AzureCLI")
}
return nil
} | [
"func",
"(",
"cfg",
"ProviderConfig",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"cfg",
".",
"NewStorageClient",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"RetryClock",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"RandomWindowsAdminPassword",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"GenerateSSHKey",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"ServicePrincipalCreator",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"AzureCLI",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate validates the Azure provider configuration. | [
"Validate",
"validates",
"the",
"Azure",
"provider",
"configuration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/environprovider.go#L71-L91 |
5,187 | juju/juju | provider/azure/environprovider.go | NewEnvironProvider | func NewEnvironProvider(config ProviderConfig) (*azureEnvironProvider, error) {
if err := config.Validate(); err != nil {
return nil, errors.Annotate(err, "validating environ provider configuration")
}
return &azureEnvironProvider{
environProviderCredentials: environProviderCredentials{
servicePrincipalCreator: config.ServicePrincipalCreator,
azureCLI: config.AzureCLI,
},
config: config,
}, nil
} | go | func NewEnvironProvider(config ProviderConfig) (*azureEnvironProvider, error) {
if err := config.Validate(); err != nil {
return nil, errors.Annotate(err, "validating environ provider configuration")
}
return &azureEnvironProvider{
environProviderCredentials: environProviderCredentials{
servicePrincipalCreator: config.ServicePrincipalCreator,
azureCLI: config.AzureCLI,
},
config: config,
}, nil
} | [
"func",
"NewEnvironProvider",
"(",
"config",
"ProviderConfig",
")",
"(",
"*",
"azureEnvironProvider",
",",
"error",
")",
"{",
"if",
"err",
":=",
"config",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"azureEnvironProvider",
"{",
"environProviderCredentials",
":",
"environProviderCredentials",
"{",
"servicePrincipalCreator",
":",
"config",
".",
"ServicePrincipalCreator",
",",
"azureCLI",
":",
"config",
".",
"AzureCLI",
",",
"}",
",",
"config",
":",
"config",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewEnvironProvider returns a new EnvironProvider for Azure. | [
"NewEnvironProvider",
"returns",
"a",
"new",
"EnvironProvider",
"for",
"Azure",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/environprovider.go#L100-L111 |
5,188 | juju/juju | api/common/leadership.go | NewLeadershipPinningAPI | func NewLeadershipPinningAPI(caller base.APICaller) *LeadershipPinningAPI {
facadeCaller := base.NewFacadeCaller(
caller,
leadershipFacade,
)
return NewLeadershipPinningAPIFromFacade(facadeCaller)
} | go | func NewLeadershipPinningAPI(caller base.APICaller) *LeadershipPinningAPI {
facadeCaller := base.NewFacadeCaller(
caller,
leadershipFacade,
)
return NewLeadershipPinningAPIFromFacade(facadeCaller)
} | [
"func",
"NewLeadershipPinningAPI",
"(",
"caller",
"base",
".",
"APICaller",
")",
"*",
"LeadershipPinningAPI",
"{",
"facadeCaller",
":=",
"base",
".",
"NewFacadeCaller",
"(",
"caller",
",",
"leadershipFacade",
",",
")",
"\n",
"return",
"NewLeadershipPinningAPIFromFacade",
"(",
"facadeCaller",
")",
"\n",
"}"
] | // NewLeadershipPinningAPI creates and returns a new leadership API client. | [
"NewLeadershipPinningAPI",
"creates",
"and",
"returns",
"a",
"new",
"leadership",
"API",
"client",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/common/leadership.go#L23-L29 |
5,189 | juju/juju | api/common/leadership.go | PinnedLeadership | func (a *LeadershipPinningAPI) PinnedLeadership() (map[string][]names.Tag, error) {
var callResult params.PinnedLeadershipResult
err := a.facade.FacadeCall("PinnedLeadership", nil, &callResult)
if err != nil {
return nil, errors.Trace(err)
}
pinned := make(map[string][]names.Tag, len(callResult.Result))
for app, entities := range callResult.Result {
entityTags := make([]names.Tag, len(entities))
for i, e := range entities {
tag, err := names.ParseTag(e)
if err != nil {
return nil, errors.Trace(err)
}
entityTags[i] = tag
}
pinned[app] = entityTags
}
return pinned, nil
} | go | func (a *LeadershipPinningAPI) PinnedLeadership() (map[string][]names.Tag, error) {
var callResult params.PinnedLeadershipResult
err := a.facade.FacadeCall("PinnedLeadership", nil, &callResult)
if err != nil {
return nil, errors.Trace(err)
}
pinned := make(map[string][]names.Tag, len(callResult.Result))
for app, entities := range callResult.Result {
entityTags := make([]names.Tag, len(entities))
for i, e := range entities {
tag, err := names.ParseTag(e)
if err != nil {
return nil, errors.Trace(err)
}
entityTags[i] = tag
}
pinned[app] = entityTags
}
return pinned, nil
} | [
"func",
"(",
"a",
"*",
"LeadershipPinningAPI",
")",
"PinnedLeadership",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"names",
".",
"Tag",
",",
"error",
")",
"{",
"var",
"callResult",
"params",
".",
"PinnedLeadershipResult",
"\n",
"err",
":=",
"a",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"nil",
",",
"&",
"callResult",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"pinned",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"names",
".",
"Tag",
",",
"len",
"(",
"callResult",
".",
"Result",
")",
")",
"\n",
"for",
"app",
",",
"entities",
":=",
"range",
"callResult",
".",
"Result",
"{",
"entityTags",
":=",
"make",
"(",
"[",
"]",
"names",
".",
"Tag",
",",
"len",
"(",
"entities",
")",
")",
"\n",
"for",
"i",
",",
"e",
":=",
"range",
"entities",
"{",
"tag",
",",
"err",
":=",
"names",
".",
"ParseTag",
"(",
"e",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"entityTags",
"[",
"i",
"]",
"=",
"tag",
"\n",
"}",
"\n\n",
"pinned",
"[",
"app",
"]",
"=",
"entityTags",
"\n",
"}",
"\n",
"return",
"pinned",
",",
"nil",
"\n",
"}"
] | // PinnedLeadership returns a collection of application names for which
// leadership is currently pinned, with the entities requiring each
// application's pinned behaviour. | [
"PinnedLeadership",
"returns",
"a",
"collection",
"of",
"application",
"names",
"for",
"which",
"leadership",
"is",
"currently",
"pinned",
"with",
"the",
"entities",
"requiring",
"each",
"application",
"s",
"pinned",
"behaviour",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/common/leadership.go#L42-L63 |
5,190 | juju/juju | api/common/leadership.go | PinMachineApplications | func (a *LeadershipPinningAPI) PinMachineApplications() (map[string]error, error) {
res, err := a.pinMachineAppsOps("PinMachineApplications")
return res, errors.Trace(err)
} | go | func (a *LeadershipPinningAPI) PinMachineApplications() (map[string]error, error) {
res, err := a.pinMachineAppsOps("PinMachineApplications")
return res, errors.Trace(err)
} | [
"func",
"(",
"a",
"*",
"LeadershipPinningAPI",
")",
"PinMachineApplications",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"error",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"a",
".",
"pinMachineAppsOps",
"(",
"\"",
"\"",
")",
"\n",
"return",
"res",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // PinMachineApplications pins leadership for applications represented by units
// running on the local machine.
// If the caller is not a machine agent, an error will be returned.
// The return is a collection of applications determined to be running on the
// machine, with the result of each individual pin operation. | [
"PinMachineApplications",
"pins",
"leadership",
"for",
"applications",
"represented",
"by",
"units",
"running",
"on",
"the",
"local",
"machine",
".",
"If",
"the",
"caller",
"is",
"not",
"a",
"machine",
"agent",
"an",
"error",
"will",
"be",
"returned",
".",
"The",
"return",
"is",
"a",
"collection",
"of",
"applications",
"determined",
"to",
"be",
"running",
"on",
"the",
"machine",
"with",
"the",
"result",
"of",
"each",
"individual",
"pin",
"operation",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/common/leadership.go#L70-L73 |
5,191 | juju/juju | api/common/leadership.go | pinMachineAppsOps | func (a *LeadershipPinningAPI) pinMachineAppsOps(callName string) (map[string]error, error) {
var callResult params.PinApplicationsResults
err := a.facade.FacadeCall(callName, nil, &callResult)
if err != nil {
return nil, errors.Trace(err)
}
callResults := callResult.Results
result := make(map[string]error, len(callResults))
for _, res := range callResults {
var appErr error
if res.Error != nil {
appErr = res.Error
}
result[res.ApplicationName] = appErr
}
return result, nil
} | go | func (a *LeadershipPinningAPI) pinMachineAppsOps(callName string) (map[string]error, error) {
var callResult params.PinApplicationsResults
err := a.facade.FacadeCall(callName, nil, &callResult)
if err != nil {
return nil, errors.Trace(err)
}
callResults := callResult.Results
result := make(map[string]error, len(callResults))
for _, res := range callResults {
var appErr error
if res.Error != nil {
appErr = res.Error
}
result[res.ApplicationName] = appErr
}
return result, nil
} | [
"func",
"(",
"a",
"*",
"LeadershipPinningAPI",
")",
"pinMachineAppsOps",
"(",
"callName",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"error",
",",
"error",
")",
"{",
"var",
"callResult",
"params",
".",
"PinApplicationsResults",
"\n",
"err",
":=",
"a",
".",
"facade",
".",
"FacadeCall",
"(",
"callName",
",",
"nil",
",",
"&",
"callResult",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"callResults",
":=",
"callResult",
".",
"Results",
"\n",
"result",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"error",
",",
"len",
"(",
"callResults",
")",
")",
"\n",
"for",
"_",
",",
"res",
":=",
"range",
"callResults",
"{",
"var",
"appErr",
"error",
"\n",
"if",
"res",
".",
"Error",
"!=",
"nil",
"{",
"appErr",
"=",
"res",
".",
"Error",
"\n",
"}",
"\n",
"result",
"[",
"res",
".",
"ApplicationName",
"]",
"=",
"appErr",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // pinMachineAppsOps makes a facade call to the input method name and
// transforms the response into map. | [
"pinMachineAppsOps",
"makes",
"a",
"facade",
"call",
"to",
"the",
"input",
"method",
"name",
"and",
"transforms",
"the",
"response",
"into",
"map",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/common/leadership.go#L87-L104 |
5,192 | juju/juju | worker/uniter/resolver.go | NewUniterResolver | func NewUniterResolver(cfg ResolverConfig) resolver.Resolver {
return &uniterResolver{
config: cfg,
retryHookTimerStarted: false,
}
} | go | func NewUniterResolver(cfg ResolverConfig) resolver.Resolver {
return &uniterResolver{
config: cfg,
retryHookTimerStarted: false,
}
} | [
"func",
"NewUniterResolver",
"(",
"cfg",
"ResolverConfig",
")",
"resolver",
".",
"Resolver",
"{",
"return",
"&",
"uniterResolver",
"{",
"config",
":",
"cfg",
",",
"retryHookTimerStarted",
":",
"false",
",",
"}",
"\n",
"}"
] | // NewUniterResolver returns a new resolver.Resolver for the uniter. | [
"NewUniterResolver",
"returns",
"a",
"new",
"resolver",
".",
"Resolver",
"for",
"the",
"uniter",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/resolver.go#L40-L45 |
5,193 | juju/juju | worker/uniter/resolver.go | nextOpConflicted | func (s *uniterResolver) nextOpConflicted(
localState resolver.LocalState,
remoteState remotestate.Snapshot,
opFactory operation.Factory,
) (operation.Operation, error) {
if remoteState.ResolvedMode != params.ResolvedNone {
if err := s.config.ClearResolved(); err != nil {
return nil, errors.Trace(err)
}
return opFactory.NewResolvedUpgrade(localState.CharmURL)
}
if remoteState.ForceCharmUpgrade && charmModified(localState, remoteState) {
return opFactory.NewRevertUpgrade(remoteState.CharmURL)
}
return nil, resolver.ErrWaiting
} | go | func (s *uniterResolver) nextOpConflicted(
localState resolver.LocalState,
remoteState remotestate.Snapshot,
opFactory operation.Factory,
) (operation.Operation, error) {
if remoteState.ResolvedMode != params.ResolvedNone {
if err := s.config.ClearResolved(); err != nil {
return nil, errors.Trace(err)
}
return opFactory.NewResolvedUpgrade(localState.CharmURL)
}
if remoteState.ForceCharmUpgrade && charmModified(localState, remoteState) {
return opFactory.NewRevertUpgrade(remoteState.CharmURL)
}
return nil, resolver.ErrWaiting
} | [
"func",
"(",
"s",
"*",
"uniterResolver",
")",
"nextOpConflicted",
"(",
"localState",
"resolver",
".",
"LocalState",
",",
"remoteState",
"remotestate",
".",
"Snapshot",
",",
"opFactory",
"operation",
".",
"Factory",
",",
")",
"(",
"operation",
".",
"Operation",
",",
"error",
")",
"{",
"if",
"remoteState",
".",
"ResolvedMode",
"!=",
"params",
".",
"ResolvedNone",
"{",
"if",
"err",
":=",
"s",
".",
"config",
".",
"ClearResolved",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"opFactory",
".",
"NewResolvedUpgrade",
"(",
"localState",
".",
"CharmURL",
")",
"\n",
"}",
"\n",
"if",
"remoteState",
".",
"ForceCharmUpgrade",
"&&",
"charmModified",
"(",
"localState",
",",
"remoteState",
")",
"{",
"return",
"opFactory",
".",
"NewRevertUpgrade",
"(",
"remoteState",
".",
"CharmURL",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"resolver",
".",
"ErrWaiting",
"\n",
"}"
] | // nextOpConflicted is called after an upgrade operation has failed, and hasn't
// yet been resolved or reverted. When in this mode, the resolver will only
// consider those two possibilities for progressing. | [
"nextOpConflicted",
"is",
"called",
"after",
"an",
"upgrade",
"operation",
"has",
"failed",
"and",
"hasn",
"t",
"yet",
"been",
"resolved",
"or",
"reverted",
".",
"When",
"in",
"this",
"mode",
"the",
"resolver",
"will",
"only",
"consider",
"those",
"two",
"possibilities",
"for",
"progressing",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/resolver.go#L147-L162 |
5,194 | juju/juju | worker/uniter/resolver.go | NextOp | func (NopResolver) NextOp(resolver.LocalState, remotestate.Snapshot, operation.Factory) (operation.Operation, error) {
return nil, resolver.ErrNoOperation
} | go | func (NopResolver) NextOp(resolver.LocalState, remotestate.Snapshot, operation.Factory) (operation.Operation, error) {
return nil, resolver.ErrNoOperation
} | [
"func",
"(",
"NopResolver",
")",
"NextOp",
"(",
"resolver",
".",
"LocalState",
",",
"remotestate",
".",
"Snapshot",
",",
"operation",
".",
"Factory",
")",
"(",
"operation",
".",
"Operation",
",",
"error",
")",
"{",
"return",
"nil",
",",
"resolver",
".",
"ErrNoOperation",
"\n",
"}"
] | // The NopResolver's NextOp operation should always return the no operation error. | [
"The",
"NopResolver",
"s",
"NextOp",
"operation",
"should",
"always",
"return",
"the",
"no",
"operation",
"error",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/resolver.go#L311-L313 |
5,195 | juju/juju | worker/fortress/fortress.go | Lockdown | func (f *fortress) Lockdown(abort Abort) error {
return f.allowGuests(false, abort)
} | go | func (f *fortress) Lockdown(abort Abort) error {
return f.allowGuests(false, abort)
} | [
"func",
"(",
"f",
"*",
"fortress",
")",
"Lockdown",
"(",
"abort",
"Abort",
")",
"error",
"{",
"return",
"f",
".",
"allowGuests",
"(",
"false",
",",
"abort",
")",
"\n",
"}"
] | // Lockdown is part of the Guard interface. | [
"Lockdown",
"is",
"part",
"of",
"the",
"Guard",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/fortress/fortress.go#L47-L49 |
5,196 | juju/juju | worker/fortress/fortress.go | Visit | func (f *fortress) Visit(visit Visit, abort Abort) error {
result := make(chan error)
select {
case <-f.tomb.Dying():
return ErrShutdown
case <-abort:
return ErrAborted
case f.guestTickets <- guestTicket{visit, result}:
return <-result
}
} | go | func (f *fortress) Visit(visit Visit, abort Abort) error {
result := make(chan error)
select {
case <-f.tomb.Dying():
return ErrShutdown
case <-abort:
return ErrAborted
case f.guestTickets <- guestTicket{visit, result}:
return <-result
}
} | [
"func",
"(",
"f",
"*",
"fortress",
")",
"Visit",
"(",
"visit",
"Visit",
",",
"abort",
"Abort",
")",
"error",
"{",
"result",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"select",
"{",
"case",
"<-",
"f",
".",
"tomb",
".",
"Dying",
"(",
")",
":",
"return",
"ErrShutdown",
"\n",
"case",
"<-",
"abort",
":",
"return",
"ErrAborted",
"\n",
"case",
"f",
".",
"guestTickets",
"<-",
"guestTicket",
"{",
"visit",
",",
"result",
"}",
":",
"return",
"<-",
"result",
"\n",
"}",
"\n",
"}"
] | // Visit is part of the Guest interface. | [
"Visit",
"is",
"part",
"of",
"the",
"Guest",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/fortress/fortress.go#L52-L62 |
5,197 | juju/juju | worker/fortress/fortress.go | allowGuests | func (f *fortress) allowGuests(allowGuests bool, abort Abort) error {
result := make(chan error)
select {
case <-f.tomb.Dying():
return ErrShutdown
case f.guardTickets <- guardTicket{allowGuests, abort, result}:
return <-result
}
} | go | func (f *fortress) allowGuests(allowGuests bool, abort Abort) error {
result := make(chan error)
select {
case <-f.tomb.Dying():
return ErrShutdown
case f.guardTickets <- guardTicket{allowGuests, abort, result}:
return <-result
}
} | [
"func",
"(",
"f",
"*",
"fortress",
")",
"allowGuests",
"(",
"allowGuests",
"bool",
",",
"abort",
"Abort",
")",
"error",
"{",
"result",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"select",
"{",
"case",
"<-",
"f",
".",
"tomb",
".",
"Dying",
"(",
")",
":",
"return",
"ErrShutdown",
"\n",
"case",
"f",
".",
"guardTickets",
"<-",
"guardTicket",
"{",
"allowGuests",
",",
"abort",
",",
"result",
"}",
":",
"return",
"<-",
"result",
"\n",
"}",
"\n",
"}"
] | // allowGuests communicates Guard-interface requests to the main loop. | [
"allowGuests",
"communicates",
"Guard",
"-",
"interface",
"requests",
"to",
"the",
"main",
"loop",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/fortress/fortress.go#L65-L73 |
5,198 | juju/juju | worker/fortress/fortress.go | loop | func (f *fortress) loop() error {
var active sync.WaitGroup
defer active.Wait()
// guestTickets will be set on Unlock and cleared at the start of Lockdown.
var guestTickets <-chan guestTicket
for {
select {
case <-f.tomb.Dying():
return tomb.ErrDying
case ticket := <-guestTickets:
active.Add(1)
go ticket.complete(active.Done)
case ticket := <-f.guardTickets:
// guard ticket requests are idempotent; it's not worth building
// the extra mechanism needed to (1) complain about abuse but
// (2) remain comprehensible and functional in the face of aborted
// Lockdowns.
if ticket.allowGuests {
guestTickets = f.guestTickets
} else {
guestTickets = nil
}
go ticket.complete(active.Wait)
}
}
} | go | func (f *fortress) loop() error {
var active sync.WaitGroup
defer active.Wait()
// guestTickets will be set on Unlock and cleared at the start of Lockdown.
var guestTickets <-chan guestTicket
for {
select {
case <-f.tomb.Dying():
return tomb.ErrDying
case ticket := <-guestTickets:
active.Add(1)
go ticket.complete(active.Done)
case ticket := <-f.guardTickets:
// guard ticket requests are idempotent; it's not worth building
// the extra mechanism needed to (1) complain about abuse but
// (2) remain comprehensible and functional in the face of aborted
// Lockdowns.
if ticket.allowGuests {
guestTickets = f.guestTickets
} else {
guestTickets = nil
}
go ticket.complete(active.Wait)
}
}
} | [
"func",
"(",
"f",
"*",
"fortress",
")",
"loop",
"(",
")",
"error",
"{",
"var",
"active",
"sync",
".",
"WaitGroup",
"\n",
"defer",
"active",
".",
"Wait",
"(",
")",
"\n\n",
"// guestTickets will be set on Unlock and cleared at the start of Lockdown.",
"var",
"guestTickets",
"<-",
"chan",
"guestTicket",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"f",
".",
"tomb",
".",
"Dying",
"(",
")",
":",
"return",
"tomb",
".",
"ErrDying",
"\n",
"case",
"ticket",
":=",
"<-",
"guestTickets",
":",
"active",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"ticket",
".",
"complete",
"(",
"active",
".",
"Done",
")",
"\n",
"case",
"ticket",
":=",
"<-",
"f",
".",
"guardTickets",
":",
"// guard ticket requests are idempotent; it's not worth building",
"// the extra mechanism needed to (1) complain about abuse but",
"// (2) remain comprehensible and functional in the face of aborted",
"// Lockdowns.",
"if",
"ticket",
".",
"allowGuests",
"{",
"guestTickets",
"=",
"f",
".",
"guestTickets",
"\n",
"}",
"else",
"{",
"guestTickets",
"=",
"nil",
"\n",
"}",
"\n",
"go",
"ticket",
".",
"complete",
"(",
"active",
".",
"Wait",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // loop waits for a Guard to unlock the fortress, and then runs visit funcs in
// parallel until a Guard locks it down again; at which point, it waits for all
// outstanding visits to complete, and reverts to its original state. | [
"loop",
"waits",
"for",
"a",
"Guard",
"to",
"unlock",
"the",
"fortress",
"and",
"then",
"runs",
"visit",
"funcs",
"in",
"parallel",
"until",
"a",
"Guard",
"locks",
"it",
"down",
"again",
";",
"at",
"which",
"point",
"it",
"waits",
"for",
"all",
"outstanding",
"visits",
"to",
"complete",
"and",
"reverts",
"to",
"its",
"original",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/fortress/fortress.go#L78-L104 |
5,199 | juju/juju | container/lxd/certificate.go | GenerateClientCertificate | func GenerateClientCertificate() (*Certificate, error) {
cert, key, err := shared.GenerateMemCert(true)
if err != nil {
return nil, errors.Trace(err)
}
return NewCertificate(cert, key), nil
} | go | func GenerateClientCertificate() (*Certificate, error) {
cert, key, err := shared.GenerateMemCert(true)
if err != nil {
return nil, errors.Trace(err)
}
return NewCertificate(cert, key), nil
} | [
"func",
"GenerateClientCertificate",
"(",
")",
"(",
"*",
"Certificate",
",",
"error",
")",
"{",
"cert",
",",
"key",
",",
"err",
":=",
"shared",
".",
"GenerateMemCert",
"(",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"NewCertificate",
"(",
"cert",
",",
"key",
")",
",",
"nil",
"\n",
"}"
] | // GenerateClientCertificate creates and returns a new certificate for client
// communication with an LXD server. | [
"GenerateClientCertificate",
"creates",
"and",
"returns",
"a",
"new",
"certificate",
"for",
"client",
"communication",
"with",
"an",
"LXD",
"server",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/certificate.go#L32-L38 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.