id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
154,900 | juju/juju | apiserver/facades/agent/provisioner/mocks/profile_mock.go | UpgradeCharmProfileCharmURL | func (mr *MockProfileMachineMockRecorder) UpgradeCharmProfileCharmURL(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpgradeCharmProfileCharmURL", reflect.TypeOf((*MockProfileMachine)(nil).UpgradeCharmProfileCharmURL), arg0)
} | go | func (mr *MockProfileMachineMockRecorder) UpgradeCharmProfileCharmURL(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpgradeCharmProfileCharmURL", reflect.TypeOf((*MockProfileMachine)(nil).UpgradeCharmProfileCharmURL), arg0)
} | [
"func",
"(",
"mr",
"*",
"MockProfileMachineMockRecorder",
")",
"UpgradeCharmProfileCharmURL",
"(",
"arg0",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockProfileMachine",
")",
"(",
"nil",
")",
".",
"UpgradeCharmProfileCharmURL",
")",
",",
"arg0",
")",
"\n",
"}"
] | // UpgradeCharmProfileCharmURL indicates an expected call of UpgradeCharmProfileCharmURL | [
"UpgradeCharmProfileCharmURL",
"indicates",
"an",
"expected",
"call",
"of",
"UpgradeCharmProfileCharmURL"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/mocks/profile_mock.go#L84-L86 |
154,901 | juju/juju | apiserver/facades/agent/provisioner/mocks/profile_mock.go | NewMockProfileBackend | func NewMockProfileBackend(ctrl *gomock.Controller) *MockProfileBackend {
mock := &MockProfileBackend{ctrl: ctrl}
mock.recorder = &MockProfileBackendMockRecorder{mock}
return mock
} | go | func NewMockProfileBackend(ctrl *gomock.Controller) *MockProfileBackend {
mock := &MockProfileBackend{ctrl: ctrl}
mock.recorder = &MockProfileBackendMockRecorder{mock}
return mock
} | [
"func",
"NewMockProfileBackend",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockProfileBackend",
"{",
"mock",
":=",
"&",
"MockProfileBackend",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockProfileBackendMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockProfileBackend creates a new mock instance | [
"NewMockProfileBackend",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/mocks/profile_mock.go#L100-L104 |
154,902 | juju/juju | apiserver/facades/agent/provisioner/mocks/profile_mock.go | Charm | func (mr *MockProfileBackendMockRecorder) Charm(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Charm", reflect.TypeOf((*MockProfileBackend)(nil).Charm), arg0)
} | go | func (mr *MockProfileBackendMockRecorder) Charm(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Charm", reflect.TypeOf((*MockProfileBackend)(nil).Charm), arg0)
} | [
"func",
"(",
"mr",
"*",
"MockProfileBackendMockRecorder",
")",
"Charm",
"(",
"arg0",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockProfileBackend",
")",
"(",
"nil",
")",
".",
"Charm",
")",
",",
"arg0",
")",
"\n",
"}"
] | // Charm indicates an expected call of Charm | [
"Charm",
"indicates",
"an",
"expected",
"call",
"of",
"Charm"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/mocks/profile_mock.go#L120-L122 |
154,903 | juju/juju | apiserver/facades/agent/provisioner/mocks/profile_mock.go | NewMockProfileCharm | func NewMockProfileCharm(ctrl *gomock.Controller) *MockProfileCharm {
mock := &MockProfileCharm{ctrl: ctrl}
mock.recorder = &MockProfileCharmMockRecorder{mock}
return mock
} | go | func NewMockProfileCharm(ctrl *gomock.Controller) *MockProfileCharm {
mock := &MockProfileCharm{ctrl: ctrl}
mock.recorder = &MockProfileCharmMockRecorder{mock}
return mock
} | [
"func",
"NewMockProfileCharm",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockProfileCharm",
"{",
"mock",
":=",
"&",
"MockProfileCharm",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockProfileCharmMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockProfileCharm creates a new mock instance | [
"NewMockProfileCharm",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/mocks/profile_mock.go#L136-L140 |
154,904 | juju/juju | apiserver/facades/agent/provisioner/mocks/profile_mock.go | Meta | func (m *MockProfileCharm) Meta() *charm_v6.Meta {
ret := m.ctrl.Call(m, "Meta")
ret0, _ := ret[0].(*charm_v6.Meta)
return ret0
} | go | func (m *MockProfileCharm) Meta() *charm_v6.Meta {
ret := m.ctrl.Call(m, "Meta")
ret0, _ := ret[0].(*charm_v6.Meta)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockProfileCharm",
")",
"Meta",
"(",
")",
"*",
"charm_v6",
".",
"Meta",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"*",
"charm_v6",
".",
"Meta",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // Meta mocks base method | [
"Meta",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/mocks/profile_mock.go#L160-L164 |
154,905 | juju/juju | apiserver/facades/agent/provisioner/mocks/profile_mock.go | Meta | func (mr *MockProfileCharmMockRecorder) Meta() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Meta", reflect.TypeOf((*MockProfileCharm)(nil).Meta))
} | go | func (mr *MockProfileCharmMockRecorder) Meta() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Meta", reflect.TypeOf((*MockProfileCharm)(nil).Meta))
} | [
"func",
"(",
"mr",
"*",
"MockProfileCharmMockRecorder",
")",
"Meta",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockProfileCharm",
")",
"(",
"nil",
")",
".",
"Meta",
")",
")",
"\n",
"}"
] | // Meta indicates an expected call of Meta | [
"Meta",
"indicates",
"an",
"expected",
"call",
"of",
"Meta"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/mocks/profile_mock.go#L167-L169 |
154,906 | juju/juju | apiserver/facades/agent/provisioner/mocks/profile_mock.go | Revision | func (m *MockProfileCharm) Revision() int {
ret := m.ctrl.Call(m, "Revision")
ret0, _ := ret[0].(int)
return ret0
} | go | func (m *MockProfileCharm) Revision() int {
ret := m.ctrl.Call(m, "Revision")
ret0, _ := ret[0].(int)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockProfileCharm",
")",
"Revision",
"(",
")",
"int",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"int",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // Revision mocks base method | [
"Revision",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/mocks/profile_mock.go#L172-L176 |
154,907 | juju/juju | apiserver/facades/client/storage/shim.go | unitAssignedMachine | func unitAssignedMachine(backend backend, tag names.UnitTag) (names.MachineTag, error) {
unit, err := backend.Unit(tag.Id())
if err != nil {
return names.MachineTag{}, errors.Trace(err)
}
mid, err := unit.AssignedMachineId()
if err != nil {
return names.MachineTag{}, errors.Trace(err)
}
return names.NewMachineTag(mid), nil
} | go | func unitAssignedMachine(backend backend, tag names.UnitTag) (names.MachineTag, error) {
unit, err := backend.Unit(tag.Id())
if err != nil {
return names.MachineTag{}, errors.Trace(err)
}
mid, err := unit.AssignedMachineId()
if err != nil {
return names.MachineTag{}, errors.Trace(err)
}
return names.NewMachineTag(mid), nil
} | [
"func",
"unitAssignedMachine",
"(",
"backend",
"backend",
",",
"tag",
"names",
".",
"UnitTag",
")",
"(",
"names",
".",
"MachineTag",
",",
"error",
")",
"{",
"unit",
",",
"err",
":=",
"backend",
".",
"Unit",
"(",
"tag",
".",
"Id",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"names",
".",
"MachineTag",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"mid",
",",
"err",
":=",
"unit",
".",
"AssignedMachineId",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"names",
".",
"MachineTag",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"names",
".",
"NewMachineTag",
"(",
"mid",
")",
",",
"nil",
"\n",
"}"
] | // unitAssignedMachine returns the tag of the machine that the unit
// is assigned to, or an error if the unit cannot be obtained or is
// not assigned to a machine. | [
"unitAssignedMachine",
"returns",
"the",
"tag",
"of",
"the",
"machine",
"that",
"the",
"unit",
"is",
"assigned",
"to",
"or",
"an",
"error",
"if",
"the",
"unit",
"cannot",
"be",
"obtained",
"or",
"is",
"not",
"assigned",
"to",
"a",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/storage/shim.go#L136-L146 |
154,908 | juju/juju | state/autocertcache.go | Put | func (cache autocertCache) Put(ctx context.Context, name string, data []byte) error {
coll, closeColl := cache.coll()
defer closeColl()
_, err := coll.UpsertId(name, autocertCacheDoc{
Name: name,
Data: data,
})
if err != nil {
return errors.Annotatef(err, "cannot store autocert key %q", name)
}
return nil
} | go | func (cache autocertCache) Put(ctx context.Context, name string, data []byte) error {
coll, closeColl := cache.coll()
defer closeColl()
_, err := coll.UpsertId(name, autocertCacheDoc{
Name: name,
Data: data,
})
if err != nil {
return errors.Annotatef(err, "cannot store autocert key %q", name)
}
return nil
} | [
"func",
"(",
"cache",
"autocertCache",
")",
"Put",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"coll",
",",
"closeColl",
":=",
"cache",
".",
"coll",
"(",
")",
"\n",
"defer",
"closeColl",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"coll",
".",
"UpsertId",
"(",
"name",
",",
"autocertCacheDoc",
"{",
"Name",
":",
"name",
",",
"Data",
":",
"data",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Put implements autocert.Cache.Put. | [
"Put",
"implements",
"autocert",
".",
"Cache",
".",
"Put",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/autocertcache.go#L32-L43 |
154,909 | juju/juju | state/autocertcache.go | Get | func (cache autocertCache) Get(ctx context.Context, name string) ([]byte, error) {
coll, closeColl := cache.coll()
defer closeColl()
var doc autocertCacheDoc
err := coll.FindId(name).One(&doc)
if err == nil {
return doc.Data, nil
}
if errors.Cause(err) == mgo.ErrNotFound {
return nil, autocert.ErrCacheMiss
}
return nil, errors.Annotatef(err, "cannot get autocert key %q", name)
} | go | func (cache autocertCache) Get(ctx context.Context, name string) ([]byte, error) {
coll, closeColl := cache.coll()
defer closeColl()
var doc autocertCacheDoc
err := coll.FindId(name).One(&doc)
if err == nil {
return doc.Data, nil
}
if errors.Cause(err) == mgo.ErrNotFound {
return nil, autocert.ErrCacheMiss
}
return nil, errors.Annotatef(err, "cannot get autocert key %q", name)
} | [
"func",
"(",
"cache",
"autocertCache",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"coll",
",",
"closeColl",
":=",
"cache",
".",
"coll",
"(",
")",
"\n",
"defer",
"closeColl",
"(",
")",
"\n",
"var",
"doc",
"autocertCacheDoc",
"\n",
"err",
":=",
"coll",
".",
"FindId",
"(",
"name",
")",
".",
"One",
"(",
"&",
"doc",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"doc",
".",
"Data",
",",
"nil",
"\n",
"}",
"\n",
"if",
"errors",
".",
"Cause",
"(",
"err",
")",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"nil",
",",
"autocert",
".",
"ErrCacheMiss",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"name",
")",
"\n",
"}"
] | // Get implements autocert.Cache.Get. | [
"Get",
"implements",
"autocert",
".",
"Cache",
".",
"Get",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/autocertcache.go#L46-L58 |
154,910 | juju/juju | state/autocertcache.go | Delete | func (cache autocertCache) Delete(ctx context.Context, name string) error {
coll, closeColl := cache.coll()
defer closeColl()
err := coll.RemoveId(name)
if err == nil || errors.Cause(err) == mgo.ErrNotFound {
return nil
}
return errors.Annotatef(err, "cannot delete autocert key %q", name)
} | go | func (cache autocertCache) Delete(ctx context.Context, name string) error {
coll, closeColl := cache.coll()
defer closeColl()
err := coll.RemoveId(name)
if err == nil || errors.Cause(err) == mgo.ErrNotFound {
return nil
}
return errors.Annotatef(err, "cannot delete autocert key %q", name)
} | [
"func",
"(",
"cache",
"autocertCache",
")",
"Delete",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
")",
"error",
"{",
"coll",
",",
"closeColl",
":=",
"cache",
".",
"coll",
"(",
")",
"\n",
"defer",
"closeColl",
"(",
")",
"\n",
"err",
":=",
"coll",
".",
"RemoveId",
"(",
"name",
")",
"\n",
"if",
"err",
"==",
"nil",
"||",
"errors",
".",
"Cause",
"(",
"err",
")",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"name",
")",
"\n",
"}"
] | // Delete implements autocert.Cache.Delete. | [
"Delete",
"implements",
"autocert",
".",
"Cache",
".",
"Delete",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/autocertcache.go#L61-L69 |
154,911 | juju/juju | worker/upgrader/upgrader.go | AllowedTargetVersion | func AllowedTargetVersion(
origAgentVersion version.Number,
curVersion version.Number,
upgradeStepsRunning bool,
targetVersion version.Number,
) bool {
if upgradeStepsRunning && targetVersion == origAgentVersion {
return true
}
if targetVersion.Major < curVersion.Major {
return false
}
if targetVersion.Major == curVersion.Major && targetVersion.Minor < curVersion.Minor {
return false
}
return true
} | go | func AllowedTargetVersion(
origAgentVersion version.Number,
curVersion version.Number,
upgradeStepsRunning bool,
targetVersion version.Number,
) bool {
if upgradeStepsRunning && targetVersion == origAgentVersion {
return true
}
if targetVersion.Major < curVersion.Major {
return false
}
if targetVersion.Major == curVersion.Major && targetVersion.Minor < curVersion.Minor {
return false
}
return true
} | [
"func",
"AllowedTargetVersion",
"(",
"origAgentVersion",
"version",
".",
"Number",
",",
"curVersion",
"version",
".",
"Number",
",",
"upgradeStepsRunning",
"bool",
",",
"targetVersion",
"version",
".",
"Number",
",",
")",
"bool",
"{",
"if",
"upgradeStepsRunning",
"&&",
"targetVersion",
"==",
"origAgentVersion",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"targetVersion",
".",
"Major",
"<",
"curVersion",
".",
"Major",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"targetVersion",
".",
"Major",
"==",
"curVersion",
".",
"Major",
"&&",
"targetVersion",
".",
"Minor",
"<",
"curVersion",
".",
"Minor",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // AllowedTargetVersion checks if targetVersion is too different from
// curVersion to allow a downgrade. | [
"AllowedTargetVersion",
"checks",
"if",
"targetVersion",
"is",
"too",
"different",
"from",
"curVersion",
"to",
"allow",
"a",
"downgrade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgrader/upgrader.go#L115-L131 |
154,912 | juju/juju | worker/common/cleanup.go | NewCleanupWorker | func NewCleanupWorker(w worker.Worker, cleanup func()) worker.Worker {
return &CleanupWorker{
Worker: w,
cleanup: cleanup,
}
} | go | func NewCleanupWorker(w worker.Worker, cleanup func()) worker.Worker {
return &CleanupWorker{
Worker: w,
cleanup: cleanup,
}
} | [
"func",
"NewCleanupWorker",
"(",
"w",
"worker",
".",
"Worker",
",",
"cleanup",
"func",
"(",
")",
")",
"worker",
".",
"Worker",
"{",
"return",
"&",
"CleanupWorker",
"{",
"Worker",
":",
"w",
",",
"cleanup",
":",
"cleanup",
",",
"}",
"\n",
"}"
] | // NewCleanupWorker returns a worker that ensures a cleanup function
// is run after the underlying worker is finished. | [
"NewCleanupWorker",
"returns",
"a",
"worker",
"that",
"ensures",
"a",
"cleanup",
"function",
"is",
"run",
"after",
"the",
"underlying",
"worker",
"is",
"finished",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/common/cleanup.go#L14-L19 |
154,913 | juju/juju | worker/common/cleanup.go | Wait | func (w *CleanupWorker) Wait() error {
err := w.Worker.Wait()
w.cleanupOnce.Do(w.cleanup)
return err
} | go | func (w *CleanupWorker) Wait() error {
err := w.Worker.Wait()
w.cleanupOnce.Do(w.cleanup)
return err
} | [
"func",
"(",
"w",
"*",
"CleanupWorker",
")",
"Wait",
"(",
")",
"error",
"{",
"err",
":=",
"w",
".",
"Worker",
".",
"Wait",
"(",
")",
"\n",
"w",
".",
"cleanupOnce",
".",
"Do",
"(",
"w",
".",
"cleanup",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Wait ensures the cleanup func is run after the worker finishes. | [
"Wait",
"ensures",
"the",
"cleanup",
"func",
"is",
"run",
"after",
"the",
"worker",
"finishes",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/common/cleanup.go#L31-L35 |
154,914 | juju/juju | apiserver/observer/request_notifier.go | NewRequestObserver | func NewRequestObserver(ctx RequestObserverContext) *RequestObserver {
// Ideally we should have a logging context so we can log into the correct
// model rather than the api server for everything.
module := ctx.Logger.Name()
return &RequestObserver{
clock: ctx.Clock,
hub: ctx.Hub,
logger: ctx.Logger,
connLogger: loggo.GetLogger(module + ".connection"),
pingLogger: loggo.GetLogger(module + ".ping"),
}
} | go | func NewRequestObserver(ctx RequestObserverContext) *RequestObserver {
// Ideally we should have a logging context so we can log into the correct
// model rather than the api server for everything.
module := ctx.Logger.Name()
return &RequestObserver{
clock: ctx.Clock,
hub: ctx.Hub,
logger: ctx.Logger,
connLogger: loggo.GetLogger(module + ".connection"),
pingLogger: loggo.GetLogger(module + ".ping"),
}
} | [
"func",
"NewRequestObserver",
"(",
"ctx",
"RequestObserverContext",
")",
"*",
"RequestObserver",
"{",
"// Ideally we should have a logging context so we can log into the correct",
"// model rather than the api server for everything.",
"module",
":=",
"ctx",
".",
"Logger",
".",
"Name",
"(",
")",
"\n",
"return",
"&",
"RequestObserver",
"{",
"clock",
":",
"ctx",
".",
"Clock",
",",
"hub",
":",
"ctx",
".",
"Hub",
",",
"logger",
":",
"ctx",
".",
"Logger",
",",
"connLogger",
":",
"loggo",
".",
"GetLogger",
"(",
"module",
"+",
"\"",
"\"",
")",
",",
"pingLogger",
":",
"loggo",
".",
"GetLogger",
"(",
"module",
"+",
"\"",
"\"",
")",
",",
"}",
"\n",
"}"
] | // NewRequestObserver returns a new RPCObserver. | [
"NewRequestObserver",
"returns",
"a",
"new",
"RPCObserver",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/request_notifier.go#L65-L76 |
154,915 | juju/juju | apiserver/observer/request_notifier.go | Leave | func (n *RequestObserver) Leave() {
if n.state.agent {
// Don't log disconnections from the controller to the model.
if !n.state.fromController {
n.connLogger.Infof("agent disconnected: %s for %s", n.state.tag, n.state.model)
}
n.hub.Publish(apiserver.DisconnectTopic, apiserver.APIConnection{
AgentTag: n.state.tag,
ControllerAgent: n.state.fromController,
ModelUUID: n.state.model,
ConnectionID: n.state.id,
})
}
n.logger.Debugf(
"[%X] %s API connection terminated after %v",
n.state.id,
n.state.tag,
time.Since(n.state.websocketConnected),
)
} | go | func (n *RequestObserver) Leave() {
if n.state.agent {
// Don't log disconnections from the controller to the model.
if !n.state.fromController {
n.connLogger.Infof("agent disconnected: %s for %s", n.state.tag, n.state.model)
}
n.hub.Publish(apiserver.DisconnectTopic, apiserver.APIConnection{
AgentTag: n.state.tag,
ControllerAgent: n.state.fromController,
ModelUUID: n.state.model,
ConnectionID: n.state.id,
})
}
n.logger.Debugf(
"[%X] %s API connection terminated after %v",
n.state.id,
n.state.tag,
time.Since(n.state.websocketConnected),
)
} | [
"func",
"(",
"n",
"*",
"RequestObserver",
")",
"Leave",
"(",
")",
"{",
"if",
"n",
".",
"state",
".",
"agent",
"{",
"// Don't log disconnections from the controller to the model.",
"if",
"!",
"n",
".",
"state",
".",
"fromController",
"{",
"n",
".",
"connLogger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"n",
".",
"state",
".",
"tag",
",",
"n",
".",
"state",
".",
"model",
")",
"\n",
"}",
"\n",
"n",
".",
"hub",
".",
"Publish",
"(",
"apiserver",
".",
"DisconnectTopic",
",",
"apiserver",
".",
"APIConnection",
"{",
"AgentTag",
":",
"n",
".",
"state",
".",
"tag",
",",
"ControllerAgent",
":",
"n",
".",
"state",
".",
"fromController",
",",
"ModelUUID",
":",
"n",
".",
"state",
".",
"model",
",",
"ConnectionID",
":",
"n",
".",
"state",
".",
"id",
",",
"}",
")",
"\n",
"}",
"\n",
"n",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"n",
".",
"state",
".",
"id",
",",
"n",
".",
"state",
".",
"tag",
",",
"time",
".",
"Since",
"(",
"n",
".",
"state",
".",
"websocketConnected",
")",
",",
")",
"\n",
"}"
] | // Leave implements Observer. | [
"Leave",
"implements",
"Observer",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/request_notifier.go#L121-L140 |
154,916 | juju/juju | apiserver/observer/request_notifier.go | ServerRequest | func (n *rpcObserver) ServerRequest(hdr *rpc.Header, body interface{}) {
n.requestStart = n.clock.Now()
if hdr.Request.Type == "Pinger" && hdr.Request.Action == "Ping" {
n.logRequestTrace(n.pingLogger, hdr, body)
return
}
// TODO(rog) 2013-10-11 remove secrets from some requests.
// Until secrets are removed, we only log the body of the requests at trace level
// which is below the default level of debug.
if n.logger.IsTraceEnabled() {
n.logRequestTrace(n.logger, hdr, body)
} else {
n.logger.Debugf("<- [%X] %s %s", n.id, n.tag, jsoncodec.DumpRequest(hdr, "'params redacted'"))
}
} | go | func (n *rpcObserver) ServerRequest(hdr *rpc.Header, body interface{}) {
n.requestStart = n.clock.Now()
if hdr.Request.Type == "Pinger" && hdr.Request.Action == "Ping" {
n.logRequestTrace(n.pingLogger, hdr, body)
return
}
// TODO(rog) 2013-10-11 remove secrets from some requests.
// Until secrets are removed, we only log the body of the requests at trace level
// which is below the default level of debug.
if n.logger.IsTraceEnabled() {
n.logRequestTrace(n.logger, hdr, body)
} else {
n.logger.Debugf("<- [%X] %s %s", n.id, n.tag, jsoncodec.DumpRequest(hdr, "'params redacted'"))
}
} | [
"func",
"(",
"n",
"*",
"rpcObserver",
")",
"ServerRequest",
"(",
"hdr",
"*",
"rpc",
".",
"Header",
",",
"body",
"interface",
"{",
"}",
")",
"{",
"n",
".",
"requestStart",
"=",
"n",
".",
"clock",
".",
"Now",
"(",
")",
"\n\n",
"if",
"hdr",
".",
"Request",
".",
"Type",
"==",
"\"",
"\"",
"&&",
"hdr",
".",
"Request",
".",
"Action",
"==",
"\"",
"\"",
"{",
"n",
".",
"logRequestTrace",
"(",
"n",
".",
"pingLogger",
",",
"hdr",
",",
"body",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// TODO(rog) 2013-10-11 remove secrets from some requests.",
"// Until secrets are removed, we only log the body of the requests at trace level",
"// which is below the default level of debug.",
"if",
"n",
".",
"logger",
".",
"IsTraceEnabled",
"(",
")",
"{",
"n",
".",
"logRequestTrace",
"(",
"n",
".",
"logger",
",",
"hdr",
",",
"body",
")",
"\n",
"}",
"else",
"{",
"n",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"n",
".",
"id",
",",
"n",
".",
"tag",
",",
"jsoncodec",
".",
"DumpRequest",
"(",
"hdr",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"}"
] | // ServerRequest implements rpc.Observer. | [
"ServerRequest",
"implements",
"rpc",
".",
"Observer",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/request_notifier.go#L164-L180 |
154,917 | juju/juju | apiserver/observer/request_notifier.go | ServerReply | func (n *rpcObserver) ServerReply(req rpc.Request, hdr *rpc.Header, body interface{}) {
if req.Type == "Pinger" && req.Action == "Ping" {
n.logReplyTrace(n.pingLogger, hdr, body)
return
}
// TODO(rog) 2013-10-11 remove secrets from some responses.
// Until secrets are removed, we only log the body of the requests at trace level
// which is below the default level of debug.
if n.logger.IsTraceEnabled() {
n.logReplyTrace(n.logger, hdr, body)
} else {
n.logger.Debugf(
"-> [%X] %s %s %s %s[%q].%s",
n.id,
n.tag,
time.Since(n.requestStart),
jsoncodec.DumpRequest(hdr, "'body redacted'"),
req.Type,
req.Id,
req.Action,
)
}
} | go | func (n *rpcObserver) ServerReply(req rpc.Request, hdr *rpc.Header, body interface{}) {
if req.Type == "Pinger" && req.Action == "Ping" {
n.logReplyTrace(n.pingLogger, hdr, body)
return
}
// TODO(rog) 2013-10-11 remove secrets from some responses.
// Until secrets are removed, we only log the body of the requests at trace level
// which is below the default level of debug.
if n.logger.IsTraceEnabled() {
n.logReplyTrace(n.logger, hdr, body)
} else {
n.logger.Debugf(
"-> [%X] %s %s %s %s[%q].%s",
n.id,
n.tag,
time.Since(n.requestStart),
jsoncodec.DumpRequest(hdr, "'body redacted'"),
req.Type,
req.Id,
req.Action,
)
}
} | [
"func",
"(",
"n",
"*",
"rpcObserver",
")",
"ServerReply",
"(",
"req",
"rpc",
".",
"Request",
",",
"hdr",
"*",
"rpc",
".",
"Header",
",",
"body",
"interface",
"{",
"}",
")",
"{",
"if",
"req",
".",
"Type",
"==",
"\"",
"\"",
"&&",
"req",
".",
"Action",
"==",
"\"",
"\"",
"{",
"n",
".",
"logReplyTrace",
"(",
"n",
".",
"pingLogger",
",",
"hdr",
",",
"body",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// TODO(rog) 2013-10-11 remove secrets from some responses.",
"// Until secrets are removed, we only log the body of the requests at trace level",
"// which is below the default level of debug.",
"if",
"n",
".",
"logger",
".",
"IsTraceEnabled",
"(",
")",
"{",
"n",
".",
"logReplyTrace",
"(",
"n",
".",
"logger",
",",
"hdr",
",",
"body",
")",
"\n",
"}",
"else",
"{",
"n",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"n",
".",
"id",
",",
"n",
".",
"tag",
",",
"time",
".",
"Since",
"(",
"n",
".",
"requestStart",
")",
",",
"jsoncodec",
".",
"DumpRequest",
"(",
"hdr",
",",
"\"",
"\"",
")",
",",
"req",
".",
"Type",
",",
"req",
".",
"Id",
",",
"req",
".",
"Action",
",",
")",
"\n",
"}",
"\n",
"}"
] | // ServerReply implements rpc.Observer. | [
"ServerReply",
"implements",
"rpc",
".",
"Observer",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/request_notifier.go#L183-L206 |
154,918 | juju/juju | worker/certupdater/certupdater.go | NewCertificateUpdater | func NewCertificateUpdater(config Config) worker.Worker {
return legacy.NewNotifyWorker(&CertificateUpdater{
addressWatcher: config.AddressWatcher,
configGetter: config.ControllerConfigGetter,
hostPortsGetter: config.APIHostPortsGetter,
getter: config.StateServingInfoGetter,
setter: config.StateServingInfoSetter,
})
} | go | func NewCertificateUpdater(config Config) worker.Worker {
return legacy.NewNotifyWorker(&CertificateUpdater{
addressWatcher: config.AddressWatcher,
configGetter: config.ControllerConfigGetter,
hostPortsGetter: config.APIHostPortsGetter,
getter: config.StateServingInfoGetter,
setter: config.StateServingInfoSetter,
})
} | [
"func",
"NewCertificateUpdater",
"(",
"config",
"Config",
")",
"worker",
".",
"Worker",
"{",
"return",
"legacy",
".",
"NewNotifyWorker",
"(",
"&",
"CertificateUpdater",
"{",
"addressWatcher",
":",
"config",
".",
"AddressWatcher",
",",
"configGetter",
":",
"config",
".",
"ControllerConfigGetter",
",",
"hostPortsGetter",
":",
"config",
".",
"APIHostPortsGetter",
",",
"getter",
":",
"config",
".",
"StateServingInfoGetter",
",",
"setter",
":",
"config",
".",
"StateServingInfoSetter",
",",
"}",
")",
"\n",
"}"
] | // NewCertificateUpdater returns a worker.Worker that watches for changes to
// machine addresses and then generates a new controller certificate with those
// addresses in the certificate's SAN value. | [
"NewCertificateUpdater",
"returns",
"a",
"worker",
".",
"Worker",
"that",
"watches",
"for",
"changes",
"to",
"machine",
"addresses",
"and",
"then",
"generates",
"a",
"new",
"controller",
"certificate",
"with",
"those",
"addresses",
"in",
"the",
"certificate",
"s",
"SAN",
"value",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/certupdater/certupdater.go#L79-L87 |
154,919 | juju/juju | worker/certupdater/certupdater.go | SetUp | func (c *CertificateUpdater) SetUp() (state.NotifyWatcher, error) {
// Populate certificate SAN with any addresses we know about now.
apiHostPorts, err := c.hostPortsGetter.APIHostPortsForClients()
if err != nil {
return nil, errors.Annotate(err, "retrieving initial server addresses")
}
var initialSANAddresses []network.Address
for _, server := range apiHostPorts {
for _, nhp := range server {
if nhp.Scope != network.ScopeCloudLocal {
continue
}
initialSANAddresses = append(initialSANAddresses, nhp.Address)
}
}
if err := c.updateCertificate(initialSANAddresses); err != nil {
return nil, errors.Annotate(err, "setting initial certificate SAN list")
}
return c.addressWatcher.WatchAddresses(), nil
} | go | func (c *CertificateUpdater) SetUp() (state.NotifyWatcher, error) {
// Populate certificate SAN with any addresses we know about now.
apiHostPorts, err := c.hostPortsGetter.APIHostPortsForClients()
if err != nil {
return nil, errors.Annotate(err, "retrieving initial server addresses")
}
var initialSANAddresses []network.Address
for _, server := range apiHostPorts {
for _, nhp := range server {
if nhp.Scope != network.ScopeCloudLocal {
continue
}
initialSANAddresses = append(initialSANAddresses, nhp.Address)
}
}
if err := c.updateCertificate(initialSANAddresses); err != nil {
return nil, errors.Annotate(err, "setting initial certificate SAN list")
}
return c.addressWatcher.WatchAddresses(), nil
} | [
"func",
"(",
"c",
"*",
"CertificateUpdater",
")",
"SetUp",
"(",
")",
"(",
"state",
".",
"NotifyWatcher",
",",
"error",
")",
"{",
"// Populate certificate SAN with any addresses we know about now.",
"apiHostPorts",
",",
"err",
":=",
"c",
".",
"hostPortsGetter",
".",
"APIHostPortsForClients",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"var",
"initialSANAddresses",
"[",
"]",
"network",
".",
"Address",
"\n",
"for",
"_",
",",
"server",
":=",
"range",
"apiHostPorts",
"{",
"for",
"_",
",",
"nhp",
":=",
"range",
"server",
"{",
"if",
"nhp",
".",
"Scope",
"!=",
"network",
".",
"ScopeCloudLocal",
"{",
"continue",
"\n",
"}",
"\n",
"initialSANAddresses",
"=",
"append",
"(",
"initialSANAddresses",
",",
"nhp",
".",
"Address",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"updateCertificate",
"(",
"initialSANAddresses",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"c",
".",
"addressWatcher",
".",
"WatchAddresses",
"(",
")",
",",
"nil",
"\n",
"}"
] | // SetUp is defined on the NotifyWatchHandler interface. | [
"SetUp",
"is",
"defined",
"on",
"the",
"NotifyWatchHandler",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/certupdater/certupdater.go#L90-L109 |
154,920 | juju/juju | worker/certupdater/certupdater.go | Handle | func (c *CertificateUpdater) Handle(done <-chan struct{}) error {
addresses := c.addressWatcher.Addresses()
if reflect.DeepEqual(addresses, c.addresses) {
// Sometimes the watcher will tell us things have changed, when they
// haven't as far as we can tell.
logger.Debugf("addresses haven't really changed since last updated cert")
return nil
}
return c.updateCertificate(addresses)
} | go | func (c *CertificateUpdater) Handle(done <-chan struct{}) error {
addresses := c.addressWatcher.Addresses()
if reflect.DeepEqual(addresses, c.addresses) {
// Sometimes the watcher will tell us things have changed, when they
// haven't as far as we can tell.
logger.Debugf("addresses haven't really changed since last updated cert")
return nil
}
return c.updateCertificate(addresses)
} | [
"func",
"(",
"c",
"*",
"CertificateUpdater",
")",
"Handle",
"(",
"done",
"<-",
"chan",
"struct",
"{",
"}",
")",
"error",
"{",
"addresses",
":=",
"c",
".",
"addressWatcher",
".",
"Addresses",
"(",
")",
"\n",
"if",
"reflect",
".",
"DeepEqual",
"(",
"addresses",
",",
"c",
".",
"addresses",
")",
"{",
"// Sometimes the watcher will tell us things have changed, when they",
"// haven't as far as we can tell.",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"c",
".",
"updateCertificate",
"(",
"addresses",
")",
"\n",
"}"
] | // Handle is defined on the NotifyWatchHandler interface. | [
"Handle",
"is",
"defined",
"on",
"the",
"NotifyWatchHandler",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/certupdater/certupdater.go#L112-L121 |
154,921 | juju/juju | worker/certupdater/certupdater.go | updateRequired | func updateRequired(serverCert string, newAddrs []string) ([]string, bool, error) {
x509Cert, err := cert.ParseCert(serverCert)
if err != nil {
return nil, false, errors.Annotate(err, "cannot parse existing TLS certificate")
}
existingAddr := set.NewStrings()
for _, ip := range x509Cert.IPAddresses {
existingAddr.Add(ip.String())
}
logger.Debugf("existing cert addresses %v", existingAddr)
logger.Debugf("new addresses %v", newAddrs)
// Does newAddr contain any that are not already in existingAddr?
newAddrSet := set.NewStrings(newAddrs...)
update := newAddrSet.Difference(existingAddr).Size() > 0
newAddrSet = newAddrSet.Union(existingAddr)
return newAddrSet.SortedValues(), update, nil
} | go | func updateRequired(serverCert string, newAddrs []string) ([]string, bool, error) {
x509Cert, err := cert.ParseCert(serverCert)
if err != nil {
return nil, false, errors.Annotate(err, "cannot parse existing TLS certificate")
}
existingAddr := set.NewStrings()
for _, ip := range x509Cert.IPAddresses {
existingAddr.Add(ip.String())
}
logger.Debugf("existing cert addresses %v", existingAddr)
logger.Debugf("new addresses %v", newAddrs)
// Does newAddr contain any that are not already in existingAddr?
newAddrSet := set.NewStrings(newAddrs...)
update := newAddrSet.Difference(existingAddr).Size() > 0
newAddrSet = newAddrSet.Union(existingAddr)
return newAddrSet.SortedValues(), update, nil
} | [
"func",
"updateRequired",
"(",
"serverCert",
"string",
",",
"newAddrs",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"string",
",",
"bool",
",",
"error",
")",
"{",
"x509Cert",
",",
"err",
":=",
"cert",
".",
"ParseCert",
"(",
"serverCert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"existingAddr",
":=",
"set",
".",
"NewStrings",
"(",
")",
"\n",
"for",
"_",
",",
"ip",
":=",
"range",
"x509Cert",
".",
"IPAddresses",
"{",
"existingAddr",
".",
"Add",
"(",
"ip",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"existingAddr",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"newAddrs",
")",
"\n",
"// Does newAddr contain any that are not already in existingAddr?",
"newAddrSet",
":=",
"set",
".",
"NewStrings",
"(",
"newAddrs",
"...",
")",
"\n",
"update",
":=",
"newAddrSet",
".",
"Difference",
"(",
"existingAddr",
")",
".",
"Size",
"(",
")",
">",
"0",
"\n",
"newAddrSet",
"=",
"newAddrSet",
".",
"Union",
"(",
"existingAddr",
")",
"\n",
"return",
"newAddrSet",
".",
"SortedValues",
"(",
")",
",",
"update",
",",
"nil",
"\n",
"}"
] | // updateRequired returns true and a list of merged addresses if any of the
// new addresses are not yet contained in the server cert SAN list. | [
"updateRequired",
"returns",
"true",
"and",
"a",
"list",
"of",
"merged",
"addresses",
"if",
"any",
"of",
"the",
"new",
"addresses",
"are",
"not",
"yet",
"contained",
"in",
"the",
"server",
"cert",
"SAN",
"list",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/certupdater/certupdater.go#L186-L202 |
154,922 | juju/juju | worker/remoterelations/remoteapplicationworker.go | startUnitsWorkers | func (w *remoteApplicationWorker) startUnitsWorkers(
relationTag names.RelationTag,
applicationToken, relationToken, remoteAppToken string,
applicationName string,
mac *macaroon.Macaroon,
) (*relationUnitsWorker, *relationUnitsWorker, error) {
// Start a watcher to track changes to the units in the relation in the local model.
localRelationUnitsWatcher, err := w.localModelFacade.WatchLocalRelationUnits(relationTag.Id())
if err != nil {
return nil, nil, errors.Annotatef(err, "watching local side of relation %v", relationTag.Id())
}
// localUnitSettingsFunc converts relations units watcher results from the local model
// into settings params using an api call to the local model.
localUnitSettingsFunc := func(changedUnitNames []string) ([]params.SettingsResult, error) {
relationUnits := make([]params.RelationUnit, len(changedUnitNames))
for i, changedName := range changedUnitNames {
relationUnits[i] = params.RelationUnit{
Relation: relationTag.String(),
Unit: names.NewUnitTag(changedName).String(),
}
}
return w.localModelFacade.RelationUnitSettings(relationUnits)
}
localUnitsWorker, err := newRelationUnitsWorker(
relationTag,
applicationToken,
mac,
relationToken,
localRelationUnitsWatcher,
w.localRelationChanges,
localUnitSettingsFunc,
)
if err != nil {
return nil, nil, errors.Trace(err)
}
if err := w.catacomb.Add(localUnitsWorker); err != nil {
return nil, nil, errors.Trace(err)
}
// Start a watcher to track changes to the units in the relation in the remote model.
remoteRelationUnitsWatcher, err := w.remoteModelFacade.WatchRelationUnits(params.RemoteEntityArg{
Token: relationToken,
Macaroons: macaroon.Slice{mac},
})
if err != nil {
w.checkOfferPermissionDenied(err, remoteAppToken, relationToken)
return nil, nil, errors.Annotatef(
err, "watching remote side of application %v and relation %v",
applicationName, relationTag.Id())
}
// remoteUnitSettingsFunc converts relations units watcher results from the remote model
// into settings params using an api call to the remote model.
remoteUnitSettingsFunc := func(changedUnitNames []string) ([]params.SettingsResult, error) {
relationUnits := make([]params.RemoteRelationUnit, len(changedUnitNames))
for i, changedName := range changedUnitNames {
relationUnits[i] = params.RemoteRelationUnit{
RelationToken: relationToken,
Unit: names.NewUnitTag(changedName).String(),
Macaroons: macaroon.Slice{mac},
}
}
return w.remoteModelFacade.RelationUnitSettings(relationUnits)
}
remoteUnitsWorker, err := newRelationUnitsWorker(
relationTag,
remoteAppToken,
mac,
relationToken,
remoteRelationUnitsWatcher,
w.remoteRelationChanges,
remoteUnitSettingsFunc,
)
if err != nil {
return nil, nil, errors.Trace(err)
}
if err := w.catacomb.Add(remoteUnitsWorker); err != nil {
return nil, nil, errors.Trace(err)
}
return localUnitsWorker, remoteUnitsWorker, nil
} | go | func (w *remoteApplicationWorker) startUnitsWorkers(
relationTag names.RelationTag,
applicationToken, relationToken, remoteAppToken string,
applicationName string,
mac *macaroon.Macaroon,
) (*relationUnitsWorker, *relationUnitsWorker, error) {
// Start a watcher to track changes to the units in the relation in the local model.
localRelationUnitsWatcher, err := w.localModelFacade.WatchLocalRelationUnits(relationTag.Id())
if err != nil {
return nil, nil, errors.Annotatef(err, "watching local side of relation %v", relationTag.Id())
}
// localUnitSettingsFunc converts relations units watcher results from the local model
// into settings params using an api call to the local model.
localUnitSettingsFunc := func(changedUnitNames []string) ([]params.SettingsResult, error) {
relationUnits := make([]params.RelationUnit, len(changedUnitNames))
for i, changedName := range changedUnitNames {
relationUnits[i] = params.RelationUnit{
Relation: relationTag.String(),
Unit: names.NewUnitTag(changedName).String(),
}
}
return w.localModelFacade.RelationUnitSettings(relationUnits)
}
localUnitsWorker, err := newRelationUnitsWorker(
relationTag,
applicationToken,
mac,
relationToken,
localRelationUnitsWatcher,
w.localRelationChanges,
localUnitSettingsFunc,
)
if err != nil {
return nil, nil, errors.Trace(err)
}
if err := w.catacomb.Add(localUnitsWorker); err != nil {
return nil, nil, errors.Trace(err)
}
// Start a watcher to track changes to the units in the relation in the remote model.
remoteRelationUnitsWatcher, err := w.remoteModelFacade.WatchRelationUnits(params.RemoteEntityArg{
Token: relationToken,
Macaroons: macaroon.Slice{mac},
})
if err != nil {
w.checkOfferPermissionDenied(err, remoteAppToken, relationToken)
return nil, nil, errors.Annotatef(
err, "watching remote side of application %v and relation %v",
applicationName, relationTag.Id())
}
// remoteUnitSettingsFunc converts relations units watcher results from the remote model
// into settings params using an api call to the remote model.
remoteUnitSettingsFunc := func(changedUnitNames []string) ([]params.SettingsResult, error) {
relationUnits := make([]params.RemoteRelationUnit, len(changedUnitNames))
for i, changedName := range changedUnitNames {
relationUnits[i] = params.RemoteRelationUnit{
RelationToken: relationToken,
Unit: names.NewUnitTag(changedName).String(),
Macaroons: macaroon.Slice{mac},
}
}
return w.remoteModelFacade.RelationUnitSettings(relationUnits)
}
remoteUnitsWorker, err := newRelationUnitsWorker(
relationTag,
remoteAppToken,
mac,
relationToken,
remoteRelationUnitsWatcher,
w.remoteRelationChanges,
remoteUnitSettingsFunc,
)
if err != nil {
return nil, nil, errors.Trace(err)
}
if err := w.catacomb.Add(remoteUnitsWorker); err != nil {
return nil, nil, errors.Trace(err)
}
return localUnitsWorker, remoteUnitsWorker, nil
} | [
"func",
"(",
"w",
"*",
"remoteApplicationWorker",
")",
"startUnitsWorkers",
"(",
"relationTag",
"names",
".",
"RelationTag",
",",
"applicationToken",
",",
"relationToken",
",",
"remoteAppToken",
"string",
",",
"applicationName",
"string",
",",
"mac",
"*",
"macaroon",
".",
"Macaroon",
",",
")",
"(",
"*",
"relationUnitsWorker",
",",
"*",
"relationUnitsWorker",
",",
"error",
")",
"{",
"// Start a watcher to track changes to the units in the relation in the local model.",
"localRelationUnitsWatcher",
",",
"err",
":=",
"w",
".",
"localModelFacade",
".",
"WatchLocalRelationUnits",
"(",
"relationTag",
".",
"Id",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"relationTag",
".",
"Id",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// localUnitSettingsFunc converts relations units watcher results from the local model",
"// into settings params using an api call to the local model.",
"localUnitSettingsFunc",
":=",
"func",
"(",
"changedUnitNames",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"params",
".",
"SettingsResult",
",",
"error",
")",
"{",
"relationUnits",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"RelationUnit",
",",
"len",
"(",
"changedUnitNames",
")",
")",
"\n",
"for",
"i",
",",
"changedName",
":=",
"range",
"changedUnitNames",
"{",
"relationUnits",
"[",
"i",
"]",
"=",
"params",
".",
"RelationUnit",
"{",
"Relation",
":",
"relationTag",
".",
"String",
"(",
")",
",",
"Unit",
":",
"names",
".",
"NewUnitTag",
"(",
"changedName",
")",
".",
"String",
"(",
")",
",",
"}",
"\n",
"}",
"\n",
"return",
"w",
".",
"localModelFacade",
".",
"RelationUnitSettings",
"(",
"relationUnits",
")",
"\n",
"}",
"\n",
"localUnitsWorker",
",",
"err",
":=",
"newRelationUnitsWorker",
"(",
"relationTag",
",",
"applicationToken",
",",
"mac",
",",
"relationToken",
",",
"localRelationUnitsWatcher",
",",
"w",
".",
"localRelationChanges",
",",
"localUnitSettingsFunc",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"w",
".",
"catacomb",
".",
"Add",
"(",
"localUnitsWorker",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Start a watcher to track changes to the units in the relation in the remote model.",
"remoteRelationUnitsWatcher",
",",
"err",
":=",
"w",
".",
"remoteModelFacade",
".",
"WatchRelationUnits",
"(",
"params",
".",
"RemoteEntityArg",
"{",
"Token",
":",
"relationToken",
",",
"Macaroons",
":",
"macaroon",
".",
"Slice",
"{",
"mac",
"}",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"checkOfferPermissionDenied",
"(",
"err",
",",
"remoteAppToken",
",",
"relationToken",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"applicationName",
",",
"relationTag",
".",
"Id",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// remoteUnitSettingsFunc converts relations units watcher results from the remote model",
"// into settings params using an api call to the remote model.",
"remoteUnitSettingsFunc",
":=",
"func",
"(",
"changedUnitNames",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"params",
".",
"SettingsResult",
",",
"error",
")",
"{",
"relationUnits",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"RemoteRelationUnit",
",",
"len",
"(",
"changedUnitNames",
")",
")",
"\n",
"for",
"i",
",",
"changedName",
":=",
"range",
"changedUnitNames",
"{",
"relationUnits",
"[",
"i",
"]",
"=",
"params",
".",
"RemoteRelationUnit",
"{",
"RelationToken",
":",
"relationToken",
",",
"Unit",
":",
"names",
".",
"NewUnitTag",
"(",
"changedName",
")",
".",
"String",
"(",
")",
",",
"Macaroons",
":",
"macaroon",
".",
"Slice",
"{",
"mac",
"}",
",",
"}",
"\n",
"}",
"\n",
"return",
"w",
".",
"remoteModelFacade",
".",
"RelationUnitSettings",
"(",
"relationUnits",
")",
"\n",
"}",
"\n",
"remoteUnitsWorker",
",",
"err",
":=",
"newRelationUnitsWorker",
"(",
"relationTag",
",",
"remoteAppToken",
",",
"mac",
",",
"relationToken",
",",
"remoteRelationUnitsWatcher",
",",
"w",
".",
"remoteRelationChanges",
",",
"remoteUnitSettingsFunc",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"w",
".",
"catacomb",
".",
"Add",
"(",
"remoteUnitsWorker",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"localUnitsWorker",
",",
"remoteUnitsWorker",
",",
"nil",
"\n",
"}"
] | // startUnitsWorkers starts 2 workers to watch for unit settings or departed changes;
// one worker is for the local model, the other for the remote model. | [
"startUnitsWorkers",
"starts",
"2",
"workers",
"to",
"watch",
"for",
"unit",
"settings",
"or",
"departed",
"changes",
";",
"one",
"worker",
"is",
"for",
"the",
"local",
"model",
"the",
"other",
"for",
"the",
"remote",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/remoterelations/remoteapplicationworker.go#L331-L412 |
154,923 | juju/juju | worker/remoterelations/remoteapplicationworker.go | processConsumingRelation | func (w *remoteApplicationWorker) processConsumingRelation(
key string,
relations map[string]*relation,
remoteRelation *params.RemoteRelation,
) error {
// We have not seen the relation before, make
// sure it is registered on the offering side.
// Or relation was suspended and is now resumed so re-register.
applicationTag := names.NewApplicationTag(remoteRelation.ApplicationName)
relationTag := names.NewRelationTag(key)
applicationToken, remoteAppToken, relationToken, mac, err := w.registerRemoteRelation(
applicationTag, relationTag, w.offerUUID,
remoteRelation.Endpoint, remoteRelation.RemoteEndpointName)
if err != nil {
w.checkOfferPermissionDenied(err, "", "")
return errors.Annotatef(err, "registering application %v and relation %v", remoteRelation.ApplicationName, relationTag.Id())
}
// Have we seen the relation before.
r, relationKnown := relations[key]
if !relationKnown {
// Totally new so start the lifecycle watcher.
remoteRelationsWatcher, err := w.remoteModelFacade.WatchRelationSuspendedStatus(params.RemoteEntityArg{
Token: relationToken,
Macaroons: macaroon.Slice{mac},
})
if err != nil {
w.checkOfferPermissionDenied(err, remoteAppToken, relationToken)
return errors.Annotatef(err, "watching remote side of relation %v", remoteRelation.Key)
}
remoteRelationsWorker, err := newRemoteRelationsWorker(
relationTag,
remoteAppToken,
relationToken,
remoteRelationsWatcher,
w.remoteRelationChanges,
)
if err != nil {
return errors.Trace(err)
}
if err := w.catacomb.Add(remoteRelationsWorker); err != nil {
return errors.Trace(err)
}
r = &relation{
relationId: remoteRelation.Id,
suspended: remoteRelation.Suspended,
remoteRrw: remoteRelationsWorker,
macaroon: mac,
localEndpoint: remoteRelation.Endpoint,
remoteEndpointName: remoteRelation.RemoteEndpointName,
applicationToken: applicationToken,
relationToken: relationToken,
}
relations[key] = r
}
if r.localRuw == nil && !remoteRelation.Suspended {
// Also start the units watchers (local and remote).
localUnitsWorker, remoteUnitsWorker, err := w.startUnitsWorkers(
relationTag, applicationToken, relationToken, remoteAppToken, remoteRelation.ApplicationName, mac)
if err != nil {
return errors.Annotate(err, "starting relation units workers")
}
r.localRuw = localUnitsWorker
r.remoteRuw = remoteUnitsWorker
}
// If the relation is dying, stop the watcher.
if remoteRelation.Life != params.Alive {
return w.processRelationDying(key, r, !relationKnown)
}
return nil
} | go | func (w *remoteApplicationWorker) processConsumingRelation(
key string,
relations map[string]*relation,
remoteRelation *params.RemoteRelation,
) error {
// We have not seen the relation before, make
// sure it is registered on the offering side.
// Or relation was suspended and is now resumed so re-register.
applicationTag := names.NewApplicationTag(remoteRelation.ApplicationName)
relationTag := names.NewRelationTag(key)
applicationToken, remoteAppToken, relationToken, mac, err := w.registerRemoteRelation(
applicationTag, relationTag, w.offerUUID,
remoteRelation.Endpoint, remoteRelation.RemoteEndpointName)
if err != nil {
w.checkOfferPermissionDenied(err, "", "")
return errors.Annotatef(err, "registering application %v and relation %v", remoteRelation.ApplicationName, relationTag.Id())
}
// Have we seen the relation before.
r, relationKnown := relations[key]
if !relationKnown {
// Totally new so start the lifecycle watcher.
remoteRelationsWatcher, err := w.remoteModelFacade.WatchRelationSuspendedStatus(params.RemoteEntityArg{
Token: relationToken,
Macaroons: macaroon.Slice{mac},
})
if err != nil {
w.checkOfferPermissionDenied(err, remoteAppToken, relationToken)
return errors.Annotatef(err, "watching remote side of relation %v", remoteRelation.Key)
}
remoteRelationsWorker, err := newRemoteRelationsWorker(
relationTag,
remoteAppToken,
relationToken,
remoteRelationsWatcher,
w.remoteRelationChanges,
)
if err != nil {
return errors.Trace(err)
}
if err := w.catacomb.Add(remoteRelationsWorker); err != nil {
return errors.Trace(err)
}
r = &relation{
relationId: remoteRelation.Id,
suspended: remoteRelation.Suspended,
remoteRrw: remoteRelationsWorker,
macaroon: mac,
localEndpoint: remoteRelation.Endpoint,
remoteEndpointName: remoteRelation.RemoteEndpointName,
applicationToken: applicationToken,
relationToken: relationToken,
}
relations[key] = r
}
if r.localRuw == nil && !remoteRelation.Suspended {
// Also start the units watchers (local and remote).
localUnitsWorker, remoteUnitsWorker, err := w.startUnitsWorkers(
relationTag, applicationToken, relationToken, remoteAppToken, remoteRelation.ApplicationName, mac)
if err != nil {
return errors.Annotate(err, "starting relation units workers")
}
r.localRuw = localUnitsWorker
r.remoteRuw = remoteUnitsWorker
}
// If the relation is dying, stop the watcher.
if remoteRelation.Life != params.Alive {
return w.processRelationDying(key, r, !relationKnown)
}
return nil
} | [
"func",
"(",
"w",
"*",
"remoteApplicationWorker",
")",
"processConsumingRelation",
"(",
"key",
"string",
",",
"relations",
"map",
"[",
"string",
"]",
"*",
"relation",
",",
"remoteRelation",
"*",
"params",
".",
"RemoteRelation",
",",
")",
"error",
"{",
"// We have not seen the relation before, make",
"// sure it is registered on the offering side.",
"// Or relation was suspended and is now resumed so re-register.",
"applicationTag",
":=",
"names",
".",
"NewApplicationTag",
"(",
"remoteRelation",
".",
"ApplicationName",
")",
"\n",
"relationTag",
":=",
"names",
".",
"NewRelationTag",
"(",
"key",
")",
"\n",
"applicationToken",
",",
"remoteAppToken",
",",
"relationToken",
",",
"mac",
",",
"err",
":=",
"w",
".",
"registerRemoteRelation",
"(",
"applicationTag",
",",
"relationTag",
",",
"w",
".",
"offerUUID",
",",
"remoteRelation",
".",
"Endpoint",
",",
"remoteRelation",
".",
"RemoteEndpointName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"checkOfferPermissionDenied",
"(",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"remoteRelation",
".",
"ApplicationName",
",",
"relationTag",
".",
"Id",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// Have we seen the relation before.",
"r",
",",
"relationKnown",
":=",
"relations",
"[",
"key",
"]",
"\n",
"if",
"!",
"relationKnown",
"{",
"// Totally new so start the lifecycle watcher.",
"remoteRelationsWatcher",
",",
"err",
":=",
"w",
".",
"remoteModelFacade",
".",
"WatchRelationSuspendedStatus",
"(",
"params",
".",
"RemoteEntityArg",
"{",
"Token",
":",
"relationToken",
",",
"Macaroons",
":",
"macaroon",
".",
"Slice",
"{",
"mac",
"}",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"checkOfferPermissionDenied",
"(",
"err",
",",
"remoteAppToken",
",",
"relationToken",
")",
"\n",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"remoteRelation",
".",
"Key",
")",
"\n",
"}",
"\n\n",
"remoteRelationsWorker",
",",
"err",
":=",
"newRemoteRelationsWorker",
"(",
"relationTag",
",",
"remoteAppToken",
",",
"relationToken",
",",
"remoteRelationsWatcher",
",",
"w",
".",
"remoteRelationChanges",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"w",
".",
"catacomb",
".",
"Add",
"(",
"remoteRelationsWorker",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"r",
"=",
"&",
"relation",
"{",
"relationId",
":",
"remoteRelation",
".",
"Id",
",",
"suspended",
":",
"remoteRelation",
".",
"Suspended",
",",
"remoteRrw",
":",
"remoteRelationsWorker",
",",
"macaroon",
":",
"mac",
",",
"localEndpoint",
":",
"remoteRelation",
".",
"Endpoint",
",",
"remoteEndpointName",
":",
"remoteRelation",
".",
"RemoteEndpointName",
",",
"applicationToken",
":",
"applicationToken",
",",
"relationToken",
":",
"relationToken",
",",
"}",
"\n",
"relations",
"[",
"key",
"]",
"=",
"r",
"\n",
"}",
"\n\n",
"if",
"r",
".",
"localRuw",
"==",
"nil",
"&&",
"!",
"remoteRelation",
".",
"Suspended",
"{",
"// Also start the units watchers (local and remote).",
"localUnitsWorker",
",",
"remoteUnitsWorker",
",",
"err",
":=",
"w",
".",
"startUnitsWorkers",
"(",
"relationTag",
",",
"applicationToken",
",",
"relationToken",
",",
"remoteAppToken",
",",
"remoteRelation",
".",
"ApplicationName",
",",
"mac",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"r",
".",
"localRuw",
"=",
"localUnitsWorker",
"\n",
"r",
".",
"remoteRuw",
"=",
"remoteUnitsWorker",
"\n",
"}",
"\n\n",
"// If the relation is dying, stop the watcher.",
"if",
"remoteRelation",
".",
"Life",
"!=",
"params",
".",
"Alive",
"{",
"return",
"w",
".",
"processRelationDying",
"(",
"key",
",",
"r",
",",
"!",
"relationKnown",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // processConsumingRelation starts the sub-workers necessary to listen and publish
// local unit settings changes, and watch and consume remote unit settings changes.
// Ths will be called when a new relation is created or when a relation resumes
// after being suspended. | [
"processConsumingRelation",
"starts",
"the",
"sub",
"-",
"workers",
"necessary",
"to",
"listen",
"and",
"publish",
"local",
"unit",
"settings",
"changes",
"and",
"watch",
"and",
"consume",
"remote",
"unit",
"settings",
"changes",
".",
"Ths",
"will",
"be",
"called",
"when",
"a",
"new",
"relation",
"is",
"created",
"or",
"when",
"a",
"relation",
"resumes",
"after",
"being",
"suspended",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/remoterelations/remoteapplicationworker.go#L418-L493 |
154,924 | juju/juju | caas/kubernetes/provider/errors.go | MaskError | func MaskError(err error) bool {
_, ok := errors.Cause(err).(*k8serrors.StatusError)
return ok
} | go | func MaskError(err error) bool {
_, ok := errors.Cause(err).(*k8serrors.StatusError)
return ok
} | [
"func",
"MaskError",
"(",
"err",
"error",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
".",
"(",
"*",
"k8serrors",
".",
"StatusError",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // MaskError is used to signify that an error
// should not be reported back to the caller. | [
"MaskError",
"is",
"used",
"to",
"signify",
"that",
"an",
"error",
"should",
"not",
"be",
"reported",
"back",
"to",
"the",
"caller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/errors.go#L64-L67 |
154,925 | juju/juju | cmd/juju/crossmodel/show.go | NewShowOfferedEndpointCommand | func NewShowOfferedEndpointCommand() cmd.Command {
showCmd := &showCommand{}
showCmd.newAPIFunc = func(controllerName string) (ShowAPI, error) {
return showCmd.NewRemoteEndpointsAPI(controllerName)
}
return modelcmd.WrapController(showCmd)
} | go | func NewShowOfferedEndpointCommand() cmd.Command {
showCmd := &showCommand{}
showCmd.newAPIFunc = func(controllerName string) (ShowAPI, error) {
return showCmd.NewRemoteEndpointsAPI(controllerName)
}
return modelcmd.WrapController(showCmd)
} | [
"func",
"NewShowOfferedEndpointCommand",
"(",
")",
"cmd",
".",
"Command",
"{",
"showCmd",
":=",
"&",
"showCommand",
"{",
"}",
"\n",
"showCmd",
".",
"newAPIFunc",
"=",
"func",
"(",
"controllerName",
"string",
")",
"(",
"ShowAPI",
",",
"error",
")",
"{",
"return",
"showCmd",
".",
"NewRemoteEndpointsAPI",
"(",
"controllerName",
")",
"\n",
"}",
"\n",
"return",
"modelcmd",
".",
"WrapController",
"(",
"showCmd",
")",
"\n",
"}"
] | // NewShowOfferedEndpointCommand constructs command that
// allows to show details of offered application's endpoint. | [
"NewShowOfferedEndpointCommand",
"constructs",
"command",
"that",
"allows",
"to",
"show",
"details",
"of",
"offered",
"application",
"s",
"endpoint",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/show.go#L55-L61 |
154,926 | juju/juju | cmd/juju/crossmodel/show.go | convertOffers | func convertOffers(
store string, loggedInUser names.UserTag, offers ...*crossmodel.ApplicationOfferDetails,
) (map[string]ShowOfferedApplication, error) {
if len(offers) == 0 {
return nil, nil
}
output := make(map[string]ShowOfferedApplication, len(offers))
for _, one := range offers {
access := accessForUser(loggedInUser, one.Users)
app := ShowOfferedApplication{
Access: access,
Endpoints: convertRemoteEndpoints(one.Endpoints...),
Users: convertUsers(one.Users...),
}
if one.ApplicationDescription != "" {
app.Description = one.ApplicationDescription
}
url, err := crossmodel.ParseOfferURL(one.OfferURL)
if err != nil {
return nil, err
}
if url.Source == "" {
url.Source = store
}
output[url.String()] = app
}
return output, nil
} | go | func convertOffers(
store string, loggedInUser names.UserTag, offers ...*crossmodel.ApplicationOfferDetails,
) (map[string]ShowOfferedApplication, error) {
if len(offers) == 0 {
return nil, nil
}
output := make(map[string]ShowOfferedApplication, len(offers))
for _, one := range offers {
access := accessForUser(loggedInUser, one.Users)
app := ShowOfferedApplication{
Access: access,
Endpoints: convertRemoteEndpoints(one.Endpoints...),
Users: convertUsers(one.Users...),
}
if one.ApplicationDescription != "" {
app.Description = one.ApplicationDescription
}
url, err := crossmodel.ParseOfferURL(one.OfferURL)
if err != nil {
return nil, err
}
if url.Source == "" {
url.Source = store
}
output[url.String()] = app
}
return output, nil
} | [
"func",
"convertOffers",
"(",
"store",
"string",
",",
"loggedInUser",
"names",
".",
"UserTag",
",",
"offers",
"...",
"*",
"crossmodel",
".",
"ApplicationOfferDetails",
",",
")",
"(",
"map",
"[",
"string",
"]",
"ShowOfferedApplication",
",",
"error",
")",
"{",
"if",
"len",
"(",
"offers",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"output",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"ShowOfferedApplication",
",",
"len",
"(",
"offers",
")",
")",
"\n",
"for",
"_",
",",
"one",
":=",
"range",
"offers",
"{",
"access",
":=",
"accessForUser",
"(",
"loggedInUser",
",",
"one",
".",
"Users",
")",
"\n",
"app",
":=",
"ShowOfferedApplication",
"{",
"Access",
":",
"access",
",",
"Endpoints",
":",
"convertRemoteEndpoints",
"(",
"one",
".",
"Endpoints",
"...",
")",
",",
"Users",
":",
"convertUsers",
"(",
"one",
".",
"Users",
"...",
")",
",",
"}",
"\n",
"if",
"one",
".",
"ApplicationDescription",
"!=",
"\"",
"\"",
"{",
"app",
".",
"Description",
"=",
"one",
".",
"ApplicationDescription",
"\n",
"}",
"\n",
"url",
",",
"err",
":=",
"crossmodel",
".",
"ParseOfferURL",
"(",
"one",
".",
"OfferURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"url",
".",
"Source",
"==",
"\"",
"\"",
"{",
"url",
".",
"Source",
"=",
"store",
"\n",
"}",
"\n",
"output",
"[",
"url",
".",
"String",
"(",
")",
"]",
"=",
"app",
"\n",
"}",
"\n",
"return",
"output",
",",
"nil",
"\n",
"}"
] | // convertOffers takes any number of api-formatted remote applications and
// creates a collection of ui-formatted offers. | [
"convertOffers",
"takes",
"any",
"number",
"of",
"api",
"-",
"formatted",
"remote",
"applications",
"and",
"creates",
"a",
"collection",
"of",
"ui",
"-",
"formatted",
"offers",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/show.go#L168-L195 |
154,927 | juju/juju | provider/maas/util.go | getSystemIdValues | func getSystemIdValues(key string, instanceIds []instance.Id) url.Values {
values := url.Values{}
for _, instanceId := range instanceIds {
values.Add(key, extractSystemId(instanceId))
}
return values
} | go | func getSystemIdValues(key string, instanceIds []instance.Id) url.Values {
values := url.Values{}
for _, instanceId := range instanceIds {
values.Add(key, extractSystemId(instanceId))
}
return values
} | [
"func",
"getSystemIdValues",
"(",
"key",
"string",
",",
"instanceIds",
"[",
"]",
"instance",
".",
"Id",
")",
"url",
".",
"Values",
"{",
"values",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"for",
"_",
",",
"instanceId",
":=",
"range",
"instanceIds",
"{",
"values",
".",
"Add",
"(",
"key",
",",
"extractSystemId",
"(",
"instanceId",
")",
")",
"\n",
"}",
"\n",
"return",
"values",
"\n",
"}"
] | // getSystemIdValues returns a url.Values object with all the 'system_ids'
// from the given instanceIds stored under the specified key. This is used
// to filter out instances when listing the nodes objects. | [
"getSystemIdValues",
"returns",
"a",
"url",
".",
"Values",
"object",
"with",
"all",
"the",
"system_ids",
"from",
"the",
"given",
"instanceIds",
"stored",
"under",
"the",
"specified",
"key",
".",
"This",
"is",
"used",
"to",
"filter",
"out",
"instances",
"when",
"listing",
"the",
"nodes",
"objects",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/util.go#L32-L38 |
154,928 | juju/juju | provider/maas/util.go | cloudinitRunCmd | func (info *machineInfo) cloudinitRunCmd(cloudcfg cloudinit.CloudConfig) (string, error) {
dataDir, err := paths.DataDir(cloudcfg.GetSeries())
if err != nil {
return "", errors.Trace(err)
}
yaml, err := goyaml.Marshal(info)
if err != nil {
return "", errors.Trace(err)
}
renderer := cloudcfg.ShellRenderer()
fileName := renderer.Join(renderer.FromSlash(dataDir), "MAASmachine.txt")
script := renderer.MkdirAll(dataDir)
contents := renderer.Quote(string(yaml))
script = append(script, renderer.WriteFile(fileName, []byte(contents))...)
script = append(script, renderer.Chmod(fileName, 0755)...)
return strings.Join(script, "\n"), nil
} | go | func (info *machineInfo) cloudinitRunCmd(cloudcfg cloudinit.CloudConfig) (string, error) {
dataDir, err := paths.DataDir(cloudcfg.GetSeries())
if err != nil {
return "", errors.Trace(err)
}
yaml, err := goyaml.Marshal(info)
if err != nil {
return "", errors.Trace(err)
}
renderer := cloudcfg.ShellRenderer()
fileName := renderer.Join(renderer.FromSlash(dataDir), "MAASmachine.txt")
script := renderer.MkdirAll(dataDir)
contents := renderer.Quote(string(yaml))
script = append(script, renderer.WriteFile(fileName, []byte(contents))...)
script = append(script, renderer.Chmod(fileName, 0755)...)
return strings.Join(script, "\n"), nil
} | [
"func",
"(",
"info",
"*",
"machineInfo",
")",
"cloudinitRunCmd",
"(",
"cloudcfg",
"cloudinit",
".",
"CloudConfig",
")",
"(",
"string",
",",
"error",
")",
"{",
"dataDir",
",",
"err",
":=",
"paths",
".",
"DataDir",
"(",
"cloudcfg",
".",
"GetSeries",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"yaml",
",",
"err",
":=",
"goyaml",
".",
"Marshal",
"(",
"info",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"renderer",
":=",
"cloudcfg",
".",
"ShellRenderer",
"(",
")",
"\n",
"fileName",
":=",
"renderer",
".",
"Join",
"(",
"renderer",
".",
"FromSlash",
"(",
"dataDir",
")",
",",
"\"",
"\"",
")",
"\n",
"script",
":=",
"renderer",
".",
"MkdirAll",
"(",
"dataDir",
")",
"\n",
"contents",
":=",
"renderer",
".",
"Quote",
"(",
"string",
"(",
"yaml",
")",
")",
"\n",
"script",
"=",
"append",
"(",
"script",
",",
"renderer",
".",
"WriteFile",
"(",
"fileName",
",",
"[",
"]",
"byte",
"(",
"contents",
")",
")",
"...",
")",
"\n",
"script",
"=",
"append",
"(",
"script",
",",
"renderer",
".",
"Chmod",
"(",
"fileName",
",",
"0755",
")",
"...",
")",
"\n",
"return",
"strings",
".",
"Join",
"(",
"script",
",",
"\"",
"\\n",
"\"",
")",
",",
"nil",
"\n",
"}"
] | // cloudinitRunCmd returns the shell command that, when run, will create the
// "machine info" file containing the hostname of a machine.
// That command is destined to be used by cloudinit. | [
"cloudinitRunCmd",
"returns",
"the",
"shell",
"command",
"that",
"when",
"run",
"will",
"create",
"the",
"machine",
"info",
"file",
"containing",
"the",
"hostname",
"of",
"a",
"machine",
".",
"That",
"command",
"is",
"destined",
"to",
"be",
"used",
"by",
"cloudinit",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/util.go#L57-L73 |
154,929 | juju/juju | apiserver/facades/controller/machineundertaker/backend.go | Machine | func (b *backendShim) Machine(id string) (Machine, error) {
return b.State.Machine(id)
} | go | func (b *backendShim) Machine(id string) (Machine, error) {
return b.State.Machine(id)
} | [
"func",
"(",
"b",
"*",
"backendShim",
")",
"Machine",
"(",
"id",
"string",
")",
"(",
"Machine",
",",
"error",
")",
"{",
"return",
"b",
".",
"State",
".",
"Machine",
"(",
"id",
")",
"\n",
"}"
] | // Machine implements Machine. | [
"Machine",
"implements",
"Machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/machineundertaker/backend.go#L43-L45 |
154,930 | juju/juju | cloudconfig/providerinit/renderers/common.go | ToBase64 | func ToBase64(data []byte) []byte {
buf := make([]byte, base64.StdEncoding.EncodedLen(len(data)))
base64.StdEncoding.Encode(buf, data)
return buf
} | go | func ToBase64(data []byte) []byte {
buf := make([]byte, base64.StdEncoding.EncodedLen(len(data)))
base64.StdEncoding.Encode(buf, data)
return buf
} | [
"func",
"ToBase64",
"(",
"data",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"base64",
".",
"StdEncoding",
".",
"EncodedLen",
"(",
"len",
"(",
"data",
")",
")",
")",
"\n",
"base64",
".",
"StdEncoding",
".",
"Encode",
"(",
"buf",
",",
"data",
")",
"\n",
"return",
"buf",
"\n",
"}"
] | // ToBase64 just transforms whatever userdata it gets to base64 format | [
"ToBase64",
"just",
"transforms",
"whatever",
"userdata",
"it",
"gets",
"to",
"base64",
"format"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/providerinit/renderers/common.go#L18-L22 |
154,931 | juju/juju | cloudconfig/providerinit/renderers/common.go | RenderScript | func RenderScript(cfg cloudinit.RenderConfig, ds ...Decorator) ([]byte, error) {
out, err := cfg.RenderScript()
if err != nil {
return nil, err
}
return applyDecorators([]byte(out), ds), nil
} | go | func RenderScript(cfg cloudinit.RenderConfig, ds ...Decorator) ([]byte, error) {
out, err := cfg.RenderScript()
if err != nil {
return nil, err
}
return applyDecorators([]byte(out), ds), nil
} | [
"func",
"RenderScript",
"(",
"cfg",
"cloudinit",
".",
"RenderConfig",
",",
"ds",
"...",
"Decorator",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"out",
",",
"err",
":=",
"cfg",
".",
"RenderScript",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"applyDecorators",
"(",
"[",
"]",
"byte",
"(",
"out",
")",
",",
"ds",
")",
",",
"nil",
"\n",
"}"
] | // RenderScript renders the given cloud-config as a script, and then passes the
// script through the given decorators. | [
"RenderScript",
"renders",
"the",
"given",
"cloud",
"-",
"config",
"as",
"a",
"script",
"and",
"then",
"passes",
"the",
"script",
"through",
"the",
"given",
"decorators",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/providerinit/renderers/common.go#L54-L60 |
154,932 | juju/juju | resource/context/internal/content.go | Verify | func (c Content) Verify(size int64, fp charmresource.Fingerprint) error {
if size != c.Size {
return errors.Errorf("resource size does not match expected (%d != %d)", size, c.Size)
}
// Only verify a finger print if it's set (i.e not for docker image details).
if c.Fingerprint.IsZero() {
return nil
}
if !bytes.Equal(fp.Bytes(), c.Fingerprint.Bytes()) {
return errors.Errorf("resource fingerprint does not match expected (%q != %q)", fp, c.Fingerprint)
}
return nil
} | go | func (c Content) Verify(size int64, fp charmresource.Fingerprint) error {
if size != c.Size {
return errors.Errorf("resource size does not match expected (%d != %d)", size, c.Size)
}
// Only verify a finger print if it's set (i.e not for docker image details).
if c.Fingerprint.IsZero() {
return nil
}
if !bytes.Equal(fp.Bytes(), c.Fingerprint.Bytes()) {
return errors.Errorf("resource fingerprint does not match expected (%q != %q)", fp, c.Fingerprint)
}
return nil
} | [
"func",
"(",
"c",
"Content",
")",
"Verify",
"(",
"size",
"int64",
",",
"fp",
"charmresource",
".",
"Fingerprint",
")",
"error",
"{",
"if",
"size",
"!=",
"c",
".",
"Size",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"size",
",",
"c",
".",
"Size",
")",
"\n",
"}",
"\n",
"// Only verify a finger print if it's set (i.e not for docker image details).",
"if",
"c",
".",
"Fingerprint",
".",
"IsZero",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"fp",
".",
"Bytes",
"(",
")",
",",
"c",
".",
"Fingerprint",
".",
"Bytes",
"(",
")",
")",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fp",
",",
"c",
".",
"Fingerprint",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Verify ensures that the actual resource content details match
// the expected ones. | [
"Verify",
"ensures",
"that",
"the",
"actual",
"resource",
"content",
"details",
"match",
"the",
"expected",
"ones",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/content.go#L34-L46 |
154,933 | juju/juju | resource/context/internal/content.go | NewContentChecker | func NewContentChecker(content Content, sizeTracker SizeTracker, checksumWriter ChecksumWriter) *Checker {
return &Checker{
Content: content,
SizeTracker: sizeTracker,
ChecksumWriter: checksumWriter,
}
} | go | func NewContentChecker(content Content, sizeTracker SizeTracker, checksumWriter ChecksumWriter) *Checker {
return &Checker{
Content: content,
SizeTracker: sizeTracker,
ChecksumWriter: checksumWriter,
}
} | [
"func",
"NewContentChecker",
"(",
"content",
"Content",
",",
"sizeTracker",
"SizeTracker",
",",
"checksumWriter",
"ChecksumWriter",
")",
"*",
"Checker",
"{",
"return",
"&",
"Checker",
"{",
"Content",
":",
"content",
",",
"SizeTracker",
":",
"sizeTracker",
",",
"ChecksumWriter",
":",
"checksumWriter",
",",
"}",
"\n",
"}"
] | // NewContentChecker returns a Checker for the provided data. | [
"NewContentChecker",
"returns",
"a",
"Checker",
"for",
"the",
"provided",
"data",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/content.go#L111-L117 |
154,934 | juju/juju | resource/context/internal/content.go | WrapReader | func (c Checker) WrapReader(reader io.Reader) io.Reader {
hashingReader := io.TeeReader(reader, c.ChecksumWriter)
return io.TeeReader(hashingReader, c.SizeTracker)
} | go | func (c Checker) WrapReader(reader io.Reader) io.Reader {
hashingReader := io.TeeReader(reader, c.ChecksumWriter)
return io.TeeReader(hashingReader, c.SizeTracker)
} | [
"func",
"(",
"c",
"Checker",
")",
"WrapReader",
"(",
"reader",
"io",
".",
"Reader",
")",
"io",
".",
"Reader",
"{",
"hashingReader",
":=",
"io",
".",
"TeeReader",
"(",
"reader",
",",
"c",
".",
"ChecksumWriter",
")",
"\n",
"return",
"io",
".",
"TeeReader",
"(",
"hashingReader",
",",
"c",
".",
"SizeTracker",
")",
"\n",
"}"
] | // WrapReader implements ContentChecker. | [
"WrapReader",
"implements",
"ContentChecker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/content.go#L120-L123 |
154,935 | juju/juju | resource/context/internal/content.go | Verify | func (c Checker) Verify() error {
size := c.SizeTracker.Size()
fp := c.ChecksumWriter.Fingerprint()
if err := c.Content.Verify(size, fp); err != nil {
return errors.Trace(err)
}
return nil
} | go | func (c Checker) Verify() error {
size := c.SizeTracker.Size()
fp := c.ChecksumWriter.Fingerprint()
if err := c.Content.Verify(size, fp); err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"(",
"c",
"Checker",
")",
"Verify",
"(",
")",
"error",
"{",
"size",
":=",
"c",
".",
"SizeTracker",
".",
"Size",
"(",
")",
"\n",
"fp",
":=",
"c",
".",
"ChecksumWriter",
".",
"Fingerprint",
"(",
")",
"\n",
"if",
"err",
":=",
"c",
".",
"Content",
".",
"Verify",
"(",
"size",
",",
"fp",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Verify implements ContentChecker. | [
"Verify",
"implements",
"ContentChecker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/content.go#L126-L133 |
154,936 | juju/juju | apiserver/logsink/mocks/metrics_mock.go | NewMockCounter | func NewMockCounter(ctrl *gomock.Controller) *MockCounter {
mock := &MockCounter{ctrl: ctrl}
mock.recorder = &MockCounterMockRecorder{mock}
return mock
} | go | func NewMockCounter(ctrl *gomock.Controller) *MockCounter {
mock := &MockCounter{ctrl: ctrl}
mock.recorder = &MockCounterMockRecorder{mock}
return mock
} | [
"func",
"NewMockCounter",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockCounter",
"{",
"mock",
":=",
"&",
"MockCounter",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockCounterMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockCounter creates a new mock instance | [
"NewMockCounter",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/logsink/mocks/metrics_mock.go#L26-L30 |
154,937 | juju/juju | apiserver/logsink/mocks/metrics_mock.go | Describe | func (mr *MockCounterMockRecorder) Describe(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Describe", reflect.TypeOf((*MockCounter)(nil).Describe), arg0)
} | go | func (mr *MockCounterMockRecorder) Describe(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Describe", reflect.TypeOf((*MockCounter)(nil).Describe), arg0)
} | [
"func",
"(",
"mr",
"*",
"MockCounterMockRecorder",
")",
"Describe",
"(",
"arg0",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockCounter",
")",
"(",
"nil",
")",
".",
"Describe",
")",
",",
"arg0",
")",
"\n",
"}"
] | // Describe indicates an expected call of Describe | [
"Describe",
"indicates",
"an",
"expected",
"call",
"of",
"Describe"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/logsink/mocks/metrics_mock.go#L75-L77 |
154,938 | juju/juju | apiserver/logsink/mocks/metrics_mock.go | NewMockGauge | func NewMockGauge(ctrl *gomock.Controller) *MockGauge {
mock := &MockGauge{ctrl: ctrl}
mock.recorder = &MockGaugeMockRecorder{mock}
return mock
} | go | func NewMockGauge(ctrl *gomock.Controller) *MockGauge {
mock := &MockGauge{ctrl: ctrl}
mock.recorder = &MockGaugeMockRecorder{mock}
return mock
} | [
"func",
"NewMockGauge",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockGauge",
"{",
"mock",
":=",
"&",
"MockGauge",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockGaugeMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockGauge creates a new mock instance | [
"NewMockGauge",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/logsink/mocks/metrics_mock.go#L113-L117 |
154,939 | juju/juju | apiserver/logsink/mocks/metrics_mock.go | Desc | func (m *MockGauge) Desc() *prometheus.Desc {
ret := m.ctrl.Call(m, "Desc")
ret0, _ := ret[0].(*prometheus.Desc)
return ret0
} | go | func (m *MockGauge) Desc() *prometheus.Desc {
ret := m.ctrl.Call(m, "Desc")
ret0, _ := ret[0].(*prometheus.Desc)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockGauge",
")",
"Desc",
"(",
")",
"*",
"prometheus",
".",
"Desc",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"*",
"prometheus",
".",
"Desc",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // Desc mocks base method | [
"Desc",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/logsink/mocks/metrics_mock.go#L155-L159 |
154,940 | juju/juju | apiserver/logsink/mocks/metrics_mock.go | Sub | func (m *MockGauge) Sub(arg0 float64) {
m.ctrl.Call(m, "Sub", arg0)
} | go | func (m *MockGauge) Sub(arg0 float64) {
m.ctrl.Call(m, "Sub", arg0)
} | [
"func",
"(",
"m",
"*",
"MockGauge",
")",
"Sub",
"(",
"arg0",
"float64",
")",
"{",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"}"
] | // Sub mocks base method | [
"Sub",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/logsink/mocks/metrics_mock.go#L207-L209 |
154,941 | juju/juju | apiserver/logsink/mocks/metrics_mock.go | Sub | func (mr *MockGaugeMockRecorder) Sub(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sub", reflect.TypeOf((*MockGauge)(nil).Sub), arg0)
} | go | func (mr *MockGaugeMockRecorder) Sub(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sub", reflect.TypeOf((*MockGauge)(nil).Sub), arg0)
} | [
"func",
"(",
"mr",
"*",
"MockGaugeMockRecorder",
")",
"Sub",
"(",
"arg0",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockGauge",
")",
"(",
"nil",
")",
".",
"Sub",
")",
",",
"arg0",
")",
"\n",
"}"
] | // Sub indicates an expected call of Sub | [
"Sub",
"indicates",
"an",
"expected",
"call",
"of",
"Sub"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/logsink/mocks/metrics_mock.go#L212-L214 |
154,942 | juju/juju | core/cache/resident.go | new | func (m *residentManager) new() *Resident {
id := m.residentCount.next()
r := &Resident{
id: id,
deregister: func() { m.deregister(id) },
nextResourceId: func() uint64 { return m.resourceCount.next() },
workers: make(map[uint64]worker.Worker),
}
m.mu.Lock()
m.residents[r.id] = r
m.mu.Unlock()
return r
} | go | func (m *residentManager) new() *Resident {
id := m.residentCount.next()
r := &Resident{
id: id,
deregister: func() { m.deregister(id) },
nextResourceId: func() uint64 { return m.resourceCount.next() },
workers: make(map[uint64]worker.Worker),
}
m.mu.Lock()
m.residents[r.id] = r
m.mu.Unlock()
return r
} | [
"func",
"(",
"m",
"*",
"residentManager",
")",
"new",
"(",
")",
"*",
"Resident",
"{",
"id",
":=",
"m",
".",
"residentCount",
".",
"next",
"(",
")",
"\n\n",
"r",
":=",
"&",
"Resident",
"{",
"id",
":",
"id",
",",
"deregister",
":",
"func",
"(",
")",
"{",
"m",
".",
"deregister",
"(",
"id",
")",
"}",
",",
"nextResourceId",
":",
"func",
"(",
")",
"uint64",
"{",
"return",
"m",
".",
"resourceCount",
".",
"next",
"(",
")",
"}",
",",
"workers",
":",
"make",
"(",
"map",
"[",
"uint64",
"]",
"worker",
".",
"Worker",
")",
",",
"}",
"\n\n",
"m",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"m",
".",
"residents",
"[",
"r",
".",
"id",
"]",
"=",
"r",
"\n",
"m",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"r",
"\n",
"}"
] | // new creates a uniquely identified type-agnostic cache resident,
// registers it in the internal map, then returns it. | [
"new",
"creates",
"a",
"uniquely",
"identified",
"type",
"-",
"agnostic",
"cache",
"resident",
"registers",
"it",
"in",
"the",
"internal",
"map",
"then",
"returns",
"it",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/resident.go#L85-L100 |
154,943 | juju/juju | core/cache/resident.go | mark | func (m *residentManager) mark() {
m.mu.Lock()
for _, r := range m.residents {
r.setStale(true)
}
m.marked = len(m.residents) > 0
m.mu.Unlock()
} | go | func (m *residentManager) mark() {
m.mu.Lock()
for _, r := range m.residents {
r.setStale(true)
}
m.marked = len(m.residents) > 0
m.mu.Unlock()
} | [
"func",
"(",
"m",
"*",
"residentManager",
")",
"mark",
"(",
")",
"{",
"m",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"m",
".",
"residents",
"{",
"r",
".",
"setStale",
"(",
"true",
")",
"\n",
"}",
"\n",
"m",
".",
"marked",
"=",
"len",
"(",
"m",
".",
"residents",
")",
">",
"0",
"\n",
"m",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // mark sets all of the manager's residents to be stale.
// If there were residents to mark, we set "marked" to be true. | [
"mark",
"sets",
"all",
"of",
"the",
"manager",
"s",
"residents",
"to",
"be",
"stale",
".",
"If",
"there",
"were",
"residents",
"to",
"mark",
"we",
"set",
"marked",
"to",
"be",
"true",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/resident.go#L104-L111 |
154,944 | juju/juju | core/cache/resident.go | sweep | func (m *residentManager) sweep() <-chan struct{} {
finished := make(chan struct{})
// If we are not marked, there is no work to do.
if !m.isMarked() {
close(finished)
return finished
}
removalIds, removalMessages := m.evictions()
go func() {
defer close(finished)
for _, id := range removalIds {
select {
case m.removals <- removalMessages[id]:
case <-m.dying:
logger.Debugf("aborting cache sweep")
return
}
}
}()
m.setMarked(false)
return finished
} | go | func (m *residentManager) sweep() <-chan struct{} {
finished := make(chan struct{})
// If we are not marked, there is no work to do.
if !m.isMarked() {
close(finished)
return finished
}
removalIds, removalMessages := m.evictions()
go func() {
defer close(finished)
for _, id := range removalIds {
select {
case m.removals <- removalMessages[id]:
case <-m.dying:
logger.Debugf("aborting cache sweep")
return
}
}
}()
m.setMarked(false)
return finished
} | [
"func",
"(",
"m",
"*",
"residentManager",
")",
"sweep",
"(",
")",
"<-",
"chan",
"struct",
"{",
"}",
"{",
"finished",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n\n",
"// If we are not marked, there is no work to do.",
"if",
"!",
"m",
".",
"isMarked",
"(",
")",
"{",
"close",
"(",
"finished",
")",
"\n",
"return",
"finished",
"\n",
"}",
"\n\n",
"removalIds",
",",
"removalMessages",
":=",
"m",
".",
"evictions",
"(",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"defer",
"close",
"(",
"finished",
")",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"removalIds",
"{",
"select",
"{",
"case",
"m",
".",
"removals",
"<-",
"removalMessages",
"[",
"id",
"]",
":",
"case",
"<-",
"m",
".",
"dying",
":",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"m",
".",
"setMarked",
"(",
"false",
")",
"\n",
"return",
"finished",
"\n",
"}"
] | // sweep removes stale cache residents in descending order of ID.
// Lock protection of the resident map is done in "evictions" and in the
// the ultimate "evict" invocations. | [
"sweep",
"removes",
"stale",
"cache",
"residents",
"in",
"descending",
"order",
"of",
"ID",
".",
"Lock",
"protection",
"of",
"the",
"resident",
"map",
"is",
"done",
"in",
"evictions",
"and",
"in",
"the",
"the",
"ultimate",
"evict",
"invocations",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/resident.go#L116-L141 |
154,945 | juju/juju | core/cache/resident.go | evictions | func (m *residentManager) evictions() ([]uint64, map[uint64]interface{}) {
m.mu.Lock()
defer m.mu.Unlock()
// Create a descending order slice of stale IDs,
// and a map of resident removal messages.
var removalIds []uint64
removalMessages := make(map[uint64]interface{})
for id, r := range m.residents {
if r.isStale() {
if r.removalMessage == nil {
logger.Warningf("cache resident %d has no removal message; skipping eviction", id)
continue
}
removalIds = append(removalIds, id)
removalMessages[id] = r.removalMessage
}
}
sort.Sort(uint64Reverse(removalIds))
return removalIds, removalMessages
} | go | func (m *residentManager) evictions() ([]uint64, map[uint64]interface{}) {
m.mu.Lock()
defer m.mu.Unlock()
// Create a descending order slice of stale IDs,
// and a map of resident removal messages.
var removalIds []uint64
removalMessages := make(map[uint64]interface{})
for id, r := range m.residents {
if r.isStale() {
if r.removalMessage == nil {
logger.Warningf("cache resident %d has no removal message; skipping eviction", id)
continue
}
removalIds = append(removalIds, id)
removalMessages[id] = r.removalMessage
}
}
sort.Sort(uint64Reverse(removalIds))
return removalIds, removalMessages
} | [
"func",
"(",
"m",
"*",
"residentManager",
")",
"evictions",
"(",
")",
"(",
"[",
"]",
"uint64",
",",
"map",
"[",
"uint64",
"]",
"interface",
"{",
"}",
")",
"{",
"m",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Create a descending order slice of stale IDs,",
"// and a map of resident removal messages.",
"var",
"removalIds",
"[",
"]",
"uint64",
"\n",
"removalMessages",
":=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"id",
",",
"r",
":=",
"range",
"m",
".",
"residents",
"{",
"if",
"r",
".",
"isStale",
"(",
")",
"{",
"if",
"r",
".",
"removalMessage",
"==",
"nil",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"removalIds",
"=",
"append",
"(",
"removalIds",
",",
"id",
")",
"\n",
"removalMessages",
"[",
"id",
"]",
"=",
"r",
".",
"removalMessage",
"\n",
"}",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"uint64Reverse",
"(",
"removalIds",
")",
")",
"\n\n",
"return",
"removalIds",
",",
"removalMessages",
"\n",
"}"
] | // evictions iterates over the cache residents and generates a map of
// eviction messages and a slice for determining order of eviction.
// Because the IDs are supplied in increasing order,
// this ensures we never remove a resident's model before the resident itself. | [
"evictions",
"iterates",
"over",
"the",
"cache",
"residents",
"and",
"generates",
"a",
"map",
"of",
"eviction",
"messages",
"and",
"a",
"slice",
"for",
"determining",
"order",
"of",
"eviction",
".",
"Because",
"the",
"IDs",
"are",
"supplied",
"in",
"increasing",
"order",
"this",
"ensures",
"we",
"never",
"remove",
"a",
"resident",
"s",
"model",
"before",
"the",
"resident",
"itself",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/resident.go#L147-L169 |
154,946 | juju/juju | core/cache/resident.go | evict | func (r *Resident) evict() error {
if err := r.cleanup(); err != nil {
return errors.Trace(err)
}
r.deregister()
return nil
} | go | func (r *Resident) evict() error {
if err := r.cleanup(); err != nil {
return errors.Trace(err)
}
r.deregister()
return nil
} | [
"func",
"(",
"r",
"*",
"Resident",
")",
"evict",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"r",
".",
"cleanup",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"r",
".",
"deregister",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // evict cleans up any resources created by this resident,
// then deregisters it. | [
"evict",
"cleans",
"up",
"any",
"resources",
"created",
"by",
"this",
"resident",
"then",
"deregisters",
"it",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/resident.go#L238-L244 |
154,947 | juju/juju | core/cache/resident.go | cleanup | func (r *Resident) cleanup() error {
return errors.Annotatef(r.cleanupWorkers(), "cleaning up cache resident %d:", r.id)
} | go | func (r *Resident) cleanup() error {
return errors.Annotatef(r.cleanupWorkers(), "cleaning up cache resident %d:", r.id)
} | [
"func",
"(",
"r",
"*",
"Resident",
")",
"cleanup",
"(",
")",
"error",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"r",
".",
"cleanupWorkers",
"(",
")",
",",
"\"",
"\"",
",",
"r",
".",
"id",
")",
"\n",
"}"
] | // cleanup performs all resource maintenance associated with a resident
// being evicted from the cache.
// Note that this method does not deregister the resident from the manager. | [
"cleanup",
"performs",
"all",
"resource",
"maintenance",
"associated",
"with",
"a",
"resident",
"being",
"evicted",
"from",
"the",
"cache",
".",
"Note",
"that",
"this",
"method",
"does",
"not",
"deregister",
"the",
"resident",
"from",
"the",
"manager",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/resident.go#L249-L251 |
154,948 | juju/juju | core/cache/resident.go | cleanupWorkers | func (r *Resident) cleanupWorkers() error {
var errs []string
for id, w := range r.workers {
if err := worker.Stop(w); err != nil {
errs = append(errs, errors.Annotatef(err, "worker %d", id).Error())
}
}
if len(errs) != 0 {
return errors.Errorf("worker cleanup errors:\n\t%s", strings.Join(errs, "\n\t"))
}
return nil
} | go | func (r *Resident) cleanupWorkers() error {
var errs []string
for id, w := range r.workers {
if err := worker.Stop(w); err != nil {
errs = append(errs, errors.Annotatef(err, "worker %d", id).Error())
}
}
if len(errs) != 0 {
return errors.Errorf("worker cleanup errors:\n\t%s", strings.Join(errs, "\n\t"))
}
return nil
} | [
"func",
"(",
"r",
"*",
"Resident",
")",
"cleanupWorkers",
"(",
")",
"error",
"{",
"var",
"errs",
"[",
"]",
"string",
"\n",
"for",
"id",
",",
"w",
":=",
"range",
"r",
".",
"workers",
"{",
"if",
"err",
":=",
"worker",
".",
"Stop",
"(",
"w",
")",
";",
"err",
"!=",
"nil",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"id",
")",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"errs",
")",
"!=",
"0",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\\n",
"\\t",
"\"",
",",
"strings",
".",
"Join",
"(",
"errs",
",",
"\"",
"\\n",
"\\t",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // cleanupWorkers calls "Stop" on all registered workers.
// Note that the deregistration method should have been added the the worker's
// tomb cleanup method - stopping the worker cleanly is enough to deregister. | [
"cleanupWorkers",
"calls",
"Stop",
"on",
"all",
"registered",
"workers",
".",
"Note",
"that",
"the",
"deregistration",
"method",
"should",
"have",
"been",
"added",
"the",
"the",
"worker",
"s",
"tomb",
"cleanup",
"method",
"-",
"stopping",
"the",
"worker",
"cleanly",
"is",
"enough",
"to",
"deregister",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/resident.go#L256-L268 |
154,949 | juju/juju | core/cache/resident.go | deregisterWorker | func (r *Resident) deregisterWorker(id uint64) {
r.mu.Lock()
delete(r.workers, id)
r.mu.Unlock()
} | go | func (r *Resident) deregisterWorker(id uint64) {
r.mu.Lock()
delete(r.workers, id)
r.mu.Unlock()
} | [
"func",
"(",
"r",
"*",
"Resident",
")",
"deregisterWorker",
"(",
"id",
"uint64",
")",
"{",
"r",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"r",
".",
"workers",
",",
"id",
")",
"\n",
"r",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // deregisterWorker informs the resident that we no longer care about this
// worker. We expect this call to come from workers stopped by other actors
// other than the resident, so we ensure Goroutine safety. | [
"deregisterWorker",
"informs",
"the",
"resident",
"that",
"we",
"no",
"longer",
"care",
"about",
"this",
"worker",
".",
"We",
"expect",
"this",
"call",
"to",
"come",
"from",
"workers",
"stopped",
"by",
"other",
"actors",
"other",
"than",
"the",
"resident",
"so",
"we",
"ensure",
"Goroutine",
"safety",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/resident.go#L273-L277 |
154,950 | juju/juju | cmd/juju/common/format.go | UserFriendlyDuration | func UserFriendlyDuration(when, now time.Time) string {
since := now.Sub(when)
// if over 24 hours ago, just say the date.
if since.Hours() >= 24 {
return when.Format("2006-01-02")
}
if since.Hours() >= 1 {
unit := "hours"
if int(since.Hours()) == 1 {
unit = "hour"
}
return fmt.Sprintf("%d %s ago", int(since.Hours()), unit)
}
if since.Minutes() >= 1 {
unit := "minutes"
if int(since.Minutes()) == 1 {
unit = "minute"
}
return fmt.Sprintf("%d %s ago", int(since.Minutes()), unit)
}
if since.Seconds() >= 2 {
return fmt.Sprintf("%d seconds ago", int(since.Seconds()))
}
return "just now"
} | go | func UserFriendlyDuration(when, now time.Time) string {
since := now.Sub(when)
// if over 24 hours ago, just say the date.
if since.Hours() >= 24 {
return when.Format("2006-01-02")
}
if since.Hours() >= 1 {
unit := "hours"
if int(since.Hours()) == 1 {
unit = "hour"
}
return fmt.Sprintf("%d %s ago", int(since.Hours()), unit)
}
if since.Minutes() >= 1 {
unit := "minutes"
if int(since.Minutes()) == 1 {
unit = "minute"
}
return fmt.Sprintf("%d %s ago", int(since.Minutes()), unit)
}
if since.Seconds() >= 2 {
return fmt.Sprintf("%d seconds ago", int(since.Seconds()))
}
return "just now"
} | [
"func",
"UserFriendlyDuration",
"(",
"when",
",",
"now",
"time",
".",
"Time",
")",
"string",
"{",
"since",
":=",
"now",
".",
"Sub",
"(",
"when",
")",
"\n",
"// if over 24 hours ago, just say the date.",
"if",
"since",
".",
"Hours",
"(",
")",
">=",
"24",
"{",
"return",
"when",
".",
"Format",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"since",
".",
"Hours",
"(",
")",
">=",
"1",
"{",
"unit",
":=",
"\"",
"\"",
"\n",
"if",
"int",
"(",
"since",
".",
"Hours",
"(",
")",
")",
"==",
"1",
"{",
"unit",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"int",
"(",
"since",
".",
"Hours",
"(",
")",
")",
",",
"unit",
")",
"\n",
"}",
"\n",
"if",
"since",
".",
"Minutes",
"(",
")",
">=",
"1",
"{",
"unit",
":=",
"\"",
"\"",
"\n",
"if",
"int",
"(",
"since",
".",
"Minutes",
"(",
")",
")",
"==",
"1",
"{",
"unit",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"int",
"(",
"since",
".",
"Minutes",
"(",
")",
")",
",",
"unit",
")",
"\n",
"}",
"\n",
"if",
"since",
".",
"Seconds",
"(",
")",
">=",
"2",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"int",
"(",
"since",
".",
"Seconds",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // UserFriendlyDuration translates a time in the past into a user
// friendly string representation relative to the "now" time argument. | [
"UserFriendlyDuration",
"translates",
"a",
"time",
"in",
"the",
"past",
"into",
"a",
"user",
"friendly",
"string",
"representation",
"relative",
"to",
"the",
"now",
"time",
"argument",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/common/format.go#L28-L52 |
154,951 | juju/juju | cmd/juju/common/format.go | FormatTime | func FormatTime(t *time.Time, formatISO bool) string {
if formatISO {
// If requested, use ISO time format.
// The format we use is RFC3339 without the "T". From the spec:
// NOTE: ISO 8601 defines date and time separated by "T".
// Applications using this syntax may choose, for the sake of
// readability, to specify a full-date and full-time separated by
// (say) a space character.
return t.UTC().Format("2006-01-02 15:04:05Z")
}
// Otherwise use local time.
return t.Local().Format("02 Jan 2006 15:04:05Z07:00")
} | go | func FormatTime(t *time.Time, formatISO bool) string {
if formatISO {
// If requested, use ISO time format.
// The format we use is RFC3339 without the "T". From the spec:
// NOTE: ISO 8601 defines date and time separated by "T".
// Applications using this syntax may choose, for the sake of
// readability, to specify a full-date and full-time separated by
// (say) a space character.
return t.UTC().Format("2006-01-02 15:04:05Z")
}
// Otherwise use local time.
return t.Local().Format("02 Jan 2006 15:04:05Z07:00")
} | [
"func",
"FormatTime",
"(",
"t",
"*",
"time",
".",
"Time",
",",
"formatISO",
"bool",
")",
"string",
"{",
"if",
"formatISO",
"{",
"// If requested, use ISO time format.",
"// The format we use is RFC3339 without the \"T\". From the spec:",
"// NOTE: ISO 8601 defines date and time separated by \"T\".",
"// Applications using this syntax may choose, for the sake of",
"// readability, to specify a full-date and full-time separated by",
"// (say) a space character.",
"return",
"t",
".",
"UTC",
"(",
")",
".",
"Format",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Otherwise use local time.",
"return",
"t",
".",
"Local",
"(",
")",
".",
"Format",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // FormatTime returns a string with the local time formatted
// in an arbitrary format used for status or and localized tz
// or in UTC timezone and format RFC3339 if u is specified. | [
"FormatTime",
"returns",
"a",
"string",
"with",
"the",
"local",
"time",
"formatted",
"in",
"an",
"arbitrary",
"format",
"used",
"for",
"status",
"or",
"and",
"localized",
"tz",
"or",
"in",
"UTC",
"timezone",
"and",
"format",
"RFC3339",
"if",
"u",
"is",
"specified",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/common/format.go#L57-L69 |
154,952 | juju/juju | api/imagemetadatamanager/client.go | List | func (c *Client) List(
stream, region string,
series, arches []string,
virtType, rootStorageType string,
) ([]params.CloudImageMetadata, error) {
in := params.ImageMetadataFilter{
Region: region,
Series: series,
Arches: arches,
Stream: stream,
VirtType: virtType,
RootStorageType: rootStorageType,
}
out := params.ListCloudImageMetadataResult{}
err := c.facade.FacadeCall("List", in, &out)
return out.Result, err
} | go | func (c *Client) List(
stream, region string,
series, arches []string,
virtType, rootStorageType string,
) ([]params.CloudImageMetadata, error) {
in := params.ImageMetadataFilter{
Region: region,
Series: series,
Arches: arches,
Stream: stream,
VirtType: virtType,
RootStorageType: rootStorageType,
}
out := params.ListCloudImageMetadataResult{}
err := c.facade.FacadeCall("List", in, &out)
return out.Result, err
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"List",
"(",
"stream",
",",
"region",
"string",
",",
"series",
",",
"arches",
"[",
"]",
"string",
",",
"virtType",
",",
"rootStorageType",
"string",
",",
")",
"(",
"[",
"]",
"params",
".",
"CloudImageMetadata",
",",
"error",
")",
"{",
"in",
":=",
"params",
".",
"ImageMetadataFilter",
"{",
"Region",
":",
"region",
",",
"Series",
":",
"series",
",",
"Arches",
":",
"arches",
",",
"Stream",
":",
"stream",
",",
"VirtType",
":",
"virtType",
",",
"RootStorageType",
":",
"rootStorageType",
",",
"}",
"\n",
"out",
":=",
"params",
".",
"ListCloudImageMetadataResult",
"{",
"}",
"\n",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"in",
",",
"&",
"out",
")",
"\n",
"return",
"out",
".",
"Result",
",",
"err",
"\n",
"}"
] | // List returns image metadata that matches filter.
// Empty filter will return all image metadata. | [
"List",
"returns",
"image",
"metadata",
"that",
"matches",
"filter",
".",
"Empty",
"filter",
"will",
"return",
"all",
"image",
"metadata",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/imagemetadatamanager/client.go#L28-L44 |
154,953 | juju/juju | api/imagemetadatamanager/client.go | Save | func (c *Client) Save(metadata []params.CloudImageMetadata) error {
in := params.MetadataSaveParams{
Metadata: []params.CloudImageMetadataList{{metadata}},
}
out := params.ErrorResults{}
err := c.facade.FacadeCall("Save", in, &out)
if err != nil {
return errors.Trace(err)
}
if len(out.Results) != 1 {
return errors.Errorf("exected 1 result, got %d", len(out.Results))
}
if out.Results[0].Error != nil {
return errors.Trace(out.Results[0].Error)
}
return nil
} | go | func (c *Client) Save(metadata []params.CloudImageMetadata) error {
in := params.MetadataSaveParams{
Metadata: []params.CloudImageMetadataList{{metadata}},
}
out := params.ErrorResults{}
err := c.facade.FacadeCall("Save", in, &out)
if err != nil {
return errors.Trace(err)
}
if len(out.Results) != 1 {
return errors.Errorf("exected 1 result, got %d", len(out.Results))
}
if out.Results[0].Error != nil {
return errors.Trace(out.Results[0].Error)
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Save",
"(",
"metadata",
"[",
"]",
"params",
".",
"CloudImageMetadata",
")",
"error",
"{",
"in",
":=",
"params",
".",
"MetadataSaveParams",
"{",
"Metadata",
":",
"[",
"]",
"params",
".",
"CloudImageMetadataList",
"{",
"{",
"metadata",
"}",
"}",
",",
"}",
"\n",
"out",
":=",
"params",
".",
"ErrorResults",
"{",
"}",
"\n",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"in",
",",
"&",
"out",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"out",
".",
"Results",
")",
"!=",
"1",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"out",
".",
"Results",
")",
")",
"\n",
"}",
"\n",
"if",
"out",
".",
"Results",
"[",
"0",
"]",
".",
"Error",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"out",
".",
"Results",
"[",
"0",
"]",
".",
"Error",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Save saves specified image metadata.
// Supports bulk saves for scenarios like cloud image metadata caching at bootstrap. | [
"Save",
"saves",
"specified",
"image",
"metadata",
".",
"Supports",
"bulk",
"saves",
"for",
"scenarios",
"like",
"cloud",
"image",
"metadata",
"caching",
"at",
"bootstrap",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/imagemetadatamanager/client.go#L48-L64 |
154,954 | juju/juju | api/imagemetadatamanager/client.go | Delete | func (c *Client) Delete(imageId string) error {
in := params.MetadataImageIds{[]string{imageId}}
out := params.ErrorResults{}
err := c.facade.FacadeCall("Delete", in, &out)
if err != nil {
return errors.Trace(err)
}
result := out.Results
if len(result) != 1 {
return errors.Errorf("expected to find one result for image id %q but found %d", imageId, len(result))
}
theOne := result[0]
if theOne.Error != nil {
return errors.Trace(theOne.Error)
}
return nil
} | go | func (c *Client) Delete(imageId string) error {
in := params.MetadataImageIds{[]string{imageId}}
out := params.ErrorResults{}
err := c.facade.FacadeCall("Delete", in, &out)
if err != nil {
return errors.Trace(err)
}
result := out.Results
if len(result) != 1 {
return errors.Errorf("expected to find one result for image id %q but found %d", imageId, len(result))
}
theOne := result[0]
if theOne.Error != nil {
return errors.Trace(theOne.Error)
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Delete",
"(",
"imageId",
"string",
")",
"error",
"{",
"in",
":=",
"params",
".",
"MetadataImageIds",
"{",
"[",
"]",
"string",
"{",
"imageId",
"}",
"}",
"\n",
"out",
":=",
"params",
".",
"ErrorResults",
"{",
"}",
"\n",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"in",
",",
"&",
"out",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"result",
":=",
"out",
".",
"Results",
"\n",
"if",
"len",
"(",
"result",
")",
"!=",
"1",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"imageId",
",",
"len",
"(",
"result",
")",
")",
"\n",
"}",
"\n\n",
"theOne",
":=",
"result",
"[",
"0",
"]",
"\n",
"if",
"theOne",
".",
"Error",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"theOne",
".",
"Error",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Delete removes image metadata for given image id from stored metadata. | [
"Delete",
"removes",
"image",
"metadata",
"for",
"given",
"image",
"id",
"from",
"stored",
"metadata",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/imagemetadatamanager/client.go#L67-L85 |
154,955 | juju/juju | environs/tools/tools.go | FindExactTools | func FindExactTools(env environs.Environ, vers version.Number, series string, arch string) (_ *coretools.Tools, err error) {
logger.Debugf("finding exact version %s", vers)
// Construct a tools filter.
// Discard all that are known to be irrelevant.
filter := coretools.Filter{
Number: vers,
Series: series,
Arch: arch,
}
streams := PreferredStreams(&vers, env.Config().Development(), env.Config().AgentStream())
logger.Debugf("looking for agent binaries in streams %v", streams)
availableTools, err := FindTools(env, vers.Major, vers.Minor, streams, filter)
if err != nil {
return nil, err
}
if len(availableTools) != 1 {
return nil, fmt.Errorf("expected one agent binary, got %d agent binaries", len(availableTools))
}
return availableTools[0], nil
} | go | func FindExactTools(env environs.Environ, vers version.Number, series string, arch string) (_ *coretools.Tools, err error) {
logger.Debugf("finding exact version %s", vers)
// Construct a tools filter.
// Discard all that are known to be irrelevant.
filter := coretools.Filter{
Number: vers,
Series: series,
Arch: arch,
}
streams := PreferredStreams(&vers, env.Config().Development(), env.Config().AgentStream())
logger.Debugf("looking for agent binaries in streams %v", streams)
availableTools, err := FindTools(env, vers.Major, vers.Minor, streams, filter)
if err != nil {
return nil, err
}
if len(availableTools) != 1 {
return nil, fmt.Errorf("expected one agent binary, got %d agent binaries", len(availableTools))
}
return availableTools[0], nil
} | [
"func",
"FindExactTools",
"(",
"env",
"environs",
".",
"Environ",
",",
"vers",
"version",
".",
"Number",
",",
"series",
"string",
",",
"arch",
"string",
")",
"(",
"_",
"*",
"coretools",
".",
"Tools",
",",
"err",
"error",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"vers",
")",
"\n",
"// Construct a tools filter.",
"// Discard all that are known to be irrelevant.",
"filter",
":=",
"coretools",
".",
"Filter",
"{",
"Number",
":",
"vers",
",",
"Series",
":",
"series",
",",
"Arch",
":",
"arch",
",",
"}",
"\n",
"streams",
":=",
"PreferredStreams",
"(",
"&",
"vers",
",",
"env",
".",
"Config",
"(",
")",
".",
"Development",
"(",
")",
",",
"env",
".",
"Config",
"(",
")",
".",
"AgentStream",
"(",
")",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"streams",
")",
"\n",
"availableTools",
",",
"err",
":=",
"FindTools",
"(",
"env",
",",
"vers",
".",
"Major",
",",
"vers",
".",
"Minor",
",",
"streams",
",",
"filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"availableTools",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"availableTools",
")",
")",
"\n",
"}",
"\n",
"return",
"availableTools",
"[",
"0",
"]",
",",
"nil",
"\n",
"}"
] | // FindExactTools returns only the tools that match the supplied version. | [
"FindExactTools",
"returns",
"only",
"the",
"tools",
"that",
"match",
"the",
"supplied",
"version",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/tools.go#L184-L203 |
154,956 | juju/juju | environs/tools/tools.go | checkToolsSeries | func checkToolsSeries(toolsList coretools.List, series string) error {
toolsSeries := toolsList.AllSeries()
if len(toolsSeries) != 1 {
return fmt.Errorf("expected single series, got %v", toolsSeries)
}
if toolsSeries[0] != series {
return fmt.Errorf("agent binary mismatch: expected series %v, got %v", series, toolsSeries[0])
}
return nil
} | go | func checkToolsSeries(toolsList coretools.List, series string) error {
toolsSeries := toolsList.AllSeries()
if len(toolsSeries) != 1 {
return fmt.Errorf("expected single series, got %v", toolsSeries)
}
if toolsSeries[0] != series {
return fmt.Errorf("agent binary mismatch: expected series %v, got %v", series, toolsSeries[0])
}
return nil
} | [
"func",
"checkToolsSeries",
"(",
"toolsList",
"coretools",
".",
"List",
",",
"series",
"string",
")",
"error",
"{",
"toolsSeries",
":=",
"toolsList",
".",
"AllSeries",
"(",
")",
"\n",
"if",
"len",
"(",
"toolsSeries",
")",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"toolsSeries",
")",
"\n",
"}",
"\n",
"if",
"toolsSeries",
"[",
"0",
"]",
"!=",
"series",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"series",
",",
"toolsSeries",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // checkToolsSeries verifies that all the given possible tools are for the
// given OS series. | [
"checkToolsSeries",
"verifies",
"that",
"all",
"the",
"given",
"possible",
"tools",
"are",
"for",
"the",
"given",
"OS",
"series",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/tools.go#L207-L216 |
154,957 | juju/juju | environs/tools/tools.go | PreferredStreams | func PreferredStreams(vers *version.Number, forceDevel bool, stream string) []string {
// If the use has already nominated a specific stream, we'll use that.
if stream != "" && stream != ReleasedStream {
if fallbacks, ok := streamFallbacks[stream]; ok {
return copyStrings(fallbacks)
}
return []string{stream}
}
// If we're not upgrading from a known version, we use the
// currently running version.
if vers == nil {
vers = &jujuversion.Current
}
// Devel versions are alpha or beta etc as defined by the version tag.
// The user can also force the use of devel streams via config.
if forceDevel || jujuversion.IsDev(*vers) {
return copyStrings(streamFallbacks[DevelStream])
}
return copyStrings(streamFallbacks[ReleasedStream])
} | go | func PreferredStreams(vers *version.Number, forceDevel bool, stream string) []string {
// If the use has already nominated a specific stream, we'll use that.
if stream != "" && stream != ReleasedStream {
if fallbacks, ok := streamFallbacks[stream]; ok {
return copyStrings(fallbacks)
}
return []string{stream}
}
// If we're not upgrading from a known version, we use the
// currently running version.
if vers == nil {
vers = &jujuversion.Current
}
// Devel versions are alpha or beta etc as defined by the version tag.
// The user can also force the use of devel streams via config.
if forceDevel || jujuversion.IsDev(*vers) {
return copyStrings(streamFallbacks[DevelStream])
}
return copyStrings(streamFallbacks[ReleasedStream])
} | [
"func",
"PreferredStreams",
"(",
"vers",
"*",
"version",
".",
"Number",
",",
"forceDevel",
"bool",
",",
"stream",
"string",
")",
"[",
"]",
"string",
"{",
"// If the use has already nominated a specific stream, we'll use that.",
"if",
"stream",
"!=",
"\"",
"\"",
"&&",
"stream",
"!=",
"ReleasedStream",
"{",
"if",
"fallbacks",
",",
"ok",
":=",
"streamFallbacks",
"[",
"stream",
"]",
";",
"ok",
"{",
"return",
"copyStrings",
"(",
"fallbacks",
")",
"\n",
"}",
"\n",
"return",
"[",
"]",
"string",
"{",
"stream",
"}",
"\n",
"}",
"\n",
"// If we're not upgrading from a known version, we use the",
"// currently running version.",
"if",
"vers",
"==",
"nil",
"{",
"vers",
"=",
"&",
"jujuversion",
".",
"Current",
"\n",
"}",
"\n",
"// Devel versions are alpha or beta etc as defined by the version tag.",
"// The user can also force the use of devel streams via config.",
"if",
"forceDevel",
"||",
"jujuversion",
".",
"IsDev",
"(",
"*",
"vers",
")",
"{",
"return",
"copyStrings",
"(",
"streamFallbacks",
"[",
"DevelStream",
"]",
")",
"\n",
"}",
"\n",
"return",
"copyStrings",
"(",
"streamFallbacks",
"[",
"ReleasedStream",
"]",
")",
"\n",
"}"
] | // PreferredStreams returns the tools streams that should be searched
// for tools, based on the required version, whether devel mode is
// required, and any user specified stream. The streams are in
// fallback order - if there are no matching tools in one stream the
// next should be checked. | [
"PreferredStreams",
"returns",
"the",
"tools",
"streams",
"that",
"should",
"be",
"searched",
"for",
"tools",
"based",
"on",
"the",
"required",
"version",
"whether",
"devel",
"mode",
"is",
"required",
"and",
"any",
"user",
"specified",
"stream",
".",
"The",
"streams",
"are",
"in",
"fallback",
"order",
"-",
"if",
"there",
"are",
"no",
"matching",
"tools",
"in",
"one",
"stream",
"the",
"next",
"should",
"be",
"checked",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/tools.go#L244-L263 |
154,958 | juju/juju | state/payloads_ns.go | forUnitWithNames | func (nsPayloads_) forUnitWithNames(unit string, names []string) bson.D {
ids := make([]string, 0, len(names))
for _, name := range names {
ids = append(ids, nsPayloads.docID(unit, name))
}
return bson.D{{"_id", bson.D{{"$in", ids}}}}
} | go | func (nsPayloads_) forUnitWithNames(unit string, names []string) bson.D {
ids := make([]string, 0, len(names))
for _, name := range names {
ids = append(ids, nsPayloads.docID(unit, name))
}
return bson.D{{"_id", bson.D{{"$in", ids}}}}
} | [
"func",
"(",
"nsPayloads_",
")",
"forUnitWithNames",
"(",
"unit",
"string",
",",
"names",
"[",
"]",
"string",
")",
"bson",
".",
"D",
"{",
"ids",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"names",
")",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"ids",
"=",
"append",
"(",
"ids",
",",
"nsPayloads",
".",
"docID",
"(",
"unit",
",",
"name",
")",
")",
"\n",
"}",
"\n",
"return",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"ids",
"}",
"}",
"}",
"}",
"\n",
"}"
] | // forUnitWithNames returns a selector that matches any payloads for the
// supplied unit that have the supplied names. | [
"forUnitWithNames",
"returns",
"a",
"selector",
"that",
"matches",
"any",
"payloads",
"for",
"the",
"supplied",
"unit",
"that",
"have",
"the",
"supplied",
"names",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/payloads_ns.go#L77-L83 |
154,959 | juju/juju | state/payloads_ns.go | asDoc | func (nsPayloads_) asDoc(p payload.FullPayloadInfo) payloadDoc {
labels := make([]string, len(p.Labels))
copy(labels, p.Labels)
return payloadDoc{
UnitID: p.Unit,
Name: p.PayloadClass.Name,
MachineID: p.Machine,
Type: p.PayloadClass.Type,
RawID: p.ID,
State: p.Status,
Labels: labels,
}
} | go | func (nsPayloads_) asDoc(p payload.FullPayloadInfo) payloadDoc {
labels := make([]string, len(p.Labels))
copy(labels, p.Labels)
return payloadDoc{
UnitID: p.Unit,
Name: p.PayloadClass.Name,
MachineID: p.Machine,
Type: p.PayloadClass.Type,
RawID: p.ID,
State: p.Status,
Labels: labels,
}
} | [
"func",
"(",
"nsPayloads_",
")",
"asDoc",
"(",
"p",
"payload",
".",
"FullPayloadInfo",
")",
"payloadDoc",
"{",
"labels",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"p",
".",
"Labels",
")",
")",
"\n",
"copy",
"(",
"labels",
",",
"p",
".",
"Labels",
")",
"\n",
"return",
"payloadDoc",
"{",
"UnitID",
":",
"p",
".",
"Unit",
",",
"Name",
":",
"p",
".",
"PayloadClass",
".",
"Name",
",",
"MachineID",
":",
"p",
".",
"Machine",
",",
"Type",
":",
"p",
".",
"PayloadClass",
".",
"Type",
",",
"RawID",
":",
"p",
".",
"ID",
",",
"State",
":",
"p",
".",
"Status",
",",
"Labels",
":",
"labels",
",",
"}",
"\n",
"}"
] | // asDoc converts a FullPayloadInfo into an independent payloadDoc. | [
"asDoc",
"converts",
"a",
"FullPayloadInfo",
"into",
"an",
"independent",
"payloadDoc",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/payloads_ns.go#L86-L98 |
154,960 | juju/juju | state/payloads_ns.go | asPayload | func (nsPayloads_) asPayload(doc payloadDoc) payload.FullPayloadInfo {
labels := make([]string, len(doc.Labels))
copy(labels, doc.Labels)
p := payload.FullPayloadInfo{
Payload: payload.Payload{
PayloadClass: charm.PayloadClass{
Name: doc.Name,
Type: doc.Type,
},
ID: doc.RawID,
Status: doc.State,
Labels: labels,
Unit: doc.UnitID,
},
Machine: doc.MachineID,
}
return p
} | go | func (nsPayloads_) asPayload(doc payloadDoc) payload.FullPayloadInfo {
labels := make([]string, len(doc.Labels))
copy(labels, doc.Labels)
p := payload.FullPayloadInfo{
Payload: payload.Payload{
PayloadClass: charm.PayloadClass{
Name: doc.Name,
Type: doc.Type,
},
ID: doc.RawID,
Status: doc.State,
Labels: labels,
Unit: doc.UnitID,
},
Machine: doc.MachineID,
}
return p
} | [
"func",
"(",
"nsPayloads_",
")",
"asPayload",
"(",
"doc",
"payloadDoc",
")",
"payload",
".",
"FullPayloadInfo",
"{",
"labels",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"doc",
".",
"Labels",
")",
")",
"\n",
"copy",
"(",
"labels",
",",
"doc",
".",
"Labels",
")",
"\n",
"p",
":=",
"payload",
".",
"FullPayloadInfo",
"{",
"Payload",
":",
"payload",
".",
"Payload",
"{",
"PayloadClass",
":",
"charm",
".",
"PayloadClass",
"{",
"Name",
":",
"doc",
".",
"Name",
",",
"Type",
":",
"doc",
".",
"Type",
",",
"}",
",",
"ID",
":",
"doc",
".",
"RawID",
",",
"Status",
":",
"doc",
".",
"State",
",",
"Labels",
":",
"labels",
",",
"Unit",
":",
"doc",
".",
"UnitID",
",",
"}",
",",
"Machine",
":",
"doc",
".",
"MachineID",
",",
"}",
"\n",
"return",
"p",
"\n",
"}"
] | // asPayload converts a payloadDoc into an independent FullPayloadInfo. | [
"asPayload",
"converts",
"a",
"payloadDoc",
"into",
"an",
"independent",
"FullPayloadInfo",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/payloads_ns.go#L101-L118 |
154,961 | juju/juju | state/payloads_ns.go | asPayloads | func (nsPayloads_) asPayloads(docs []payloadDoc) []payload.FullPayloadInfo {
payloads := make([]payload.FullPayloadInfo, 0, len(docs))
for _, doc := range docs {
payloads = append(payloads, nsPayloads.asPayload(doc))
}
return payloads
} | go | func (nsPayloads_) asPayloads(docs []payloadDoc) []payload.FullPayloadInfo {
payloads := make([]payload.FullPayloadInfo, 0, len(docs))
for _, doc := range docs {
payloads = append(payloads, nsPayloads.asPayload(doc))
}
return payloads
} | [
"func",
"(",
"nsPayloads_",
")",
"asPayloads",
"(",
"docs",
"[",
"]",
"payloadDoc",
")",
"[",
"]",
"payload",
".",
"FullPayloadInfo",
"{",
"payloads",
":=",
"make",
"(",
"[",
"]",
"payload",
".",
"FullPayloadInfo",
",",
"0",
",",
"len",
"(",
"docs",
")",
")",
"\n",
"for",
"_",
",",
"doc",
":=",
"range",
"docs",
"{",
"payloads",
"=",
"append",
"(",
"payloads",
",",
"nsPayloads",
".",
"asPayload",
"(",
"doc",
")",
")",
"\n",
"}",
"\n",
"return",
"payloads",
"\n",
"}"
] | // asPayloads converts a slice of payloadDocs into a corresponding slice
// of independent FullPayloadInfos. | [
"asPayloads",
"converts",
"a",
"slice",
"of",
"payloadDocs",
"into",
"a",
"corresponding",
"slice",
"of",
"independent",
"FullPayloadInfos",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/payloads_ns.go#L122-L128 |
154,962 | juju/juju | state/payloads_ns.go | asResults | func (nsPayloads_) asResults(docs []payloadDoc) []payload.Result {
results := make([]payload.Result, 0, len(docs))
for _, doc := range docs {
full := nsPayloads.asPayload(doc)
results = append(results, payload.Result{
ID: doc.Name,
Payload: &full,
})
}
return results
} | go | func (nsPayloads_) asResults(docs []payloadDoc) []payload.Result {
results := make([]payload.Result, 0, len(docs))
for _, doc := range docs {
full := nsPayloads.asPayload(doc)
results = append(results, payload.Result{
ID: doc.Name,
Payload: &full,
})
}
return results
} | [
"func",
"(",
"nsPayloads_",
")",
"asResults",
"(",
"docs",
"[",
"]",
"payloadDoc",
")",
"[",
"]",
"payload",
".",
"Result",
"{",
"results",
":=",
"make",
"(",
"[",
"]",
"payload",
".",
"Result",
",",
"0",
",",
"len",
"(",
"docs",
")",
")",
"\n",
"for",
"_",
",",
"doc",
":=",
"range",
"docs",
"{",
"full",
":=",
"nsPayloads",
".",
"asPayload",
"(",
"doc",
")",
"\n",
"results",
"=",
"append",
"(",
"results",
",",
"payload",
".",
"Result",
"{",
"ID",
":",
"doc",
".",
"Name",
",",
"Payload",
":",
"&",
"full",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"results",
"\n",
"}"
] | // asResults converts a slice of payloadDocs into a corresponding slice
// of independent payload.Results. | [
"asResults",
"converts",
"a",
"slice",
"of",
"payloadDocs",
"into",
"a",
"corresponding",
"slice",
"of",
"independent",
"payload",
".",
"Results",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/payloads_ns.go#L132-L142 |
154,963 | juju/juju | state/payloads_ns.go | orderedResults | func (nsPayloads_) orderedResults(docs []payloadDoc, names []string) []payload.Result {
found := make(map[string]payloadDoc)
for _, doc := range docs {
found[doc.Name] = doc
}
results := make([]payload.Result, len(names))
for i, name := range names {
results[i].ID = name
if doc, ok := found[name]; ok {
full := nsPayloads.asPayload(doc)
results[i].Payload = &full
} else {
results[i].NotFound = true
results[i].Error = errors.NotFoundf(name)
}
}
return results
} | go | func (nsPayloads_) orderedResults(docs []payloadDoc, names []string) []payload.Result {
found := make(map[string]payloadDoc)
for _, doc := range docs {
found[doc.Name] = doc
}
results := make([]payload.Result, len(names))
for i, name := range names {
results[i].ID = name
if doc, ok := found[name]; ok {
full := nsPayloads.asPayload(doc)
results[i].Payload = &full
} else {
results[i].NotFound = true
results[i].Error = errors.NotFoundf(name)
}
}
return results
} | [
"func",
"(",
"nsPayloads_",
")",
"orderedResults",
"(",
"docs",
"[",
"]",
"payloadDoc",
",",
"names",
"[",
"]",
"string",
")",
"[",
"]",
"payload",
".",
"Result",
"{",
"found",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"payloadDoc",
")",
"\n",
"for",
"_",
",",
"doc",
":=",
"range",
"docs",
"{",
"found",
"[",
"doc",
".",
"Name",
"]",
"=",
"doc",
"\n",
"}",
"\n",
"results",
":=",
"make",
"(",
"[",
"]",
"payload",
".",
"Result",
",",
"len",
"(",
"names",
")",
")",
"\n",
"for",
"i",
",",
"name",
":=",
"range",
"names",
"{",
"results",
"[",
"i",
"]",
".",
"ID",
"=",
"name",
"\n",
"if",
"doc",
",",
"ok",
":=",
"found",
"[",
"name",
"]",
";",
"ok",
"{",
"full",
":=",
"nsPayloads",
".",
"asPayload",
"(",
"doc",
")",
"\n",
"results",
"[",
"i",
"]",
".",
"Payload",
"=",
"&",
"full",
"\n",
"}",
"else",
"{",
"results",
"[",
"i",
"]",
".",
"NotFound",
"=",
"true",
"\n",
"results",
"[",
"i",
"]",
".",
"Error",
"=",
"errors",
".",
"NotFoundf",
"(",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"results",
"\n",
"}"
] | // orderedResults converts payloadDocs into payload.Results, in the
// order defined by names, and represents missing names in the highly
// baroque fashion apparently designed into Results. | [
"orderedResults",
"converts",
"payloadDocs",
"into",
"payload",
".",
"Results",
"in",
"the",
"order",
"defined",
"by",
"names",
"and",
"represents",
"missing",
"names",
"in",
"the",
"highly",
"baroque",
"fashion",
"apparently",
"designed",
"into",
"Results",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/payloads_ns.go#L147-L164 |
154,964 | juju/juju | state/payloads_ns.go | trackOp | func (nsPayloads_) trackOp(payloads mongo.Collection, doc payloadDoc) (txn.Op, error) {
docID := nsPayloads.docID(doc.UnitID, doc.Name)
payloadOp := txn.Op{
C: payloads.Name(),
Id: docID,
}
count, err := payloads.FindId(docID).Count()
if err != nil {
return txn.Op{}, errors.Trace(err)
} else if count == 0 {
payloadOp.Assert = txn.DocMissing
payloadOp.Insert = doc
} else {
payloadOp.Assert = txn.DocExists
payloadOp.Update = bson.D{{"$set", doc}}
}
return payloadOp, nil
} | go | func (nsPayloads_) trackOp(payloads mongo.Collection, doc payloadDoc) (txn.Op, error) {
docID := nsPayloads.docID(doc.UnitID, doc.Name)
payloadOp := txn.Op{
C: payloads.Name(),
Id: docID,
}
count, err := payloads.FindId(docID).Count()
if err != nil {
return txn.Op{}, errors.Trace(err)
} else if count == 0 {
payloadOp.Assert = txn.DocMissing
payloadOp.Insert = doc
} else {
payloadOp.Assert = txn.DocExists
payloadOp.Update = bson.D{{"$set", doc}}
}
return payloadOp, nil
} | [
"func",
"(",
"nsPayloads_",
")",
"trackOp",
"(",
"payloads",
"mongo",
".",
"Collection",
",",
"doc",
"payloadDoc",
")",
"(",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"docID",
":=",
"nsPayloads",
".",
"docID",
"(",
"doc",
".",
"UnitID",
",",
"doc",
".",
"Name",
")",
"\n",
"payloadOp",
":=",
"txn",
".",
"Op",
"{",
"C",
":",
"payloads",
".",
"Name",
"(",
")",
",",
"Id",
":",
"docID",
",",
"}",
"\n",
"count",
",",
"err",
":=",
"payloads",
".",
"FindId",
"(",
"docID",
")",
".",
"Count",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"txn",
".",
"Op",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"count",
"==",
"0",
"{",
"payloadOp",
".",
"Assert",
"=",
"txn",
".",
"DocMissing",
"\n",
"payloadOp",
".",
"Insert",
"=",
"doc",
"\n",
"}",
"else",
"{",
"payloadOp",
".",
"Assert",
"=",
"txn",
".",
"DocExists",
"\n",
"payloadOp",
".",
"Update",
"=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"doc",
"}",
"}",
"\n",
"}",
"\n",
"return",
"payloadOp",
",",
"nil",
"\n",
"}"
] | // trackOp returns a txn.Op that will either insert or update the
// supplied payload, and fail if the observed precondition changes. | [
"trackOp",
"returns",
"a",
"txn",
".",
"Op",
"that",
"will",
"either",
"insert",
"or",
"update",
"the",
"supplied",
"payload",
"and",
"fail",
"if",
"the",
"observed",
"precondition",
"changes",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/payloads_ns.go#L168-L185 |
154,965 | juju/juju | state/payloads_ns.go | untrackOp | func (nsPayloads_) untrackOp(payloads mongo.Collection, docID string) (txn.Op, error) {
count, err := payloads.FindId(docID).Count()
if err != nil {
return txn.Op{}, errors.Trace(err)
} else if count == 0 {
return txn.Op{}, errAlreadyRemoved
}
return txn.Op{
C: payloads.Name(),
Id: docID,
Assert: txn.DocExists,
Remove: true,
}, nil
} | go | func (nsPayloads_) untrackOp(payloads mongo.Collection, docID string) (txn.Op, error) {
count, err := payloads.FindId(docID).Count()
if err != nil {
return txn.Op{}, errors.Trace(err)
} else if count == 0 {
return txn.Op{}, errAlreadyRemoved
}
return txn.Op{
C: payloads.Name(),
Id: docID,
Assert: txn.DocExists,
Remove: true,
}, nil
} | [
"func",
"(",
"nsPayloads_",
")",
"untrackOp",
"(",
"payloads",
"mongo",
".",
"Collection",
",",
"docID",
"string",
")",
"(",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"count",
",",
"err",
":=",
"payloads",
".",
"FindId",
"(",
"docID",
")",
".",
"Count",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"txn",
".",
"Op",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"count",
"==",
"0",
"{",
"return",
"txn",
".",
"Op",
"{",
"}",
",",
"errAlreadyRemoved",
"\n",
"}",
"\n",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"payloads",
".",
"Name",
"(",
")",
",",
"Id",
":",
"docID",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Remove",
":",
"true",
",",
"}",
",",
"nil",
"\n",
"}"
] | // untrackOp returns a txn.Op that will unconditionally remove the
// identified document. If the payload doesn't exist, it returns
// errAlreadyRemoved. | [
"untrackOp",
"returns",
"a",
"txn",
".",
"Op",
"that",
"will",
"unconditionally",
"remove",
"the",
"identified",
"document",
".",
"If",
"the",
"payload",
"doesn",
"t",
"exist",
"it",
"returns",
"errAlreadyRemoved",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/payloads_ns.go#L190-L203 |
154,966 | juju/juju | state/payloads_ns.go | setStatusOp | func (nsPayloads_) setStatusOp(payloads mongo.Collection, docID string, status string) (txn.Op, error) {
count, err := payloads.FindId(docID).Count()
if err != nil {
return txn.Op{}, errors.Trace(err)
} else if count == 0 {
return txn.Op{}, errAlreadyRemoved
}
return txn.Op{
C: payloads.Name(),
Id: docID,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"state", status}}}},
}, nil
} | go | func (nsPayloads_) setStatusOp(payloads mongo.Collection, docID string, status string) (txn.Op, error) {
count, err := payloads.FindId(docID).Count()
if err != nil {
return txn.Op{}, errors.Trace(err)
} else if count == 0 {
return txn.Op{}, errAlreadyRemoved
}
return txn.Op{
C: payloads.Name(),
Id: docID,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"state", status}}}},
}, nil
} | [
"func",
"(",
"nsPayloads_",
")",
"setStatusOp",
"(",
"payloads",
"mongo",
".",
"Collection",
",",
"docID",
"string",
",",
"status",
"string",
")",
"(",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"count",
",",
"err",
":=",
"payloads",
".",
"FindId",
"(",
"docID",
")",
".",
"Count",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"txn",
".",
"Op",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"count",
"==",
"0",
"{",
"return",
"txn",
".",
"Op",
"{",
"}",
",",
"errAlreadyRemoved",
"\n",
"}",
"\n",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"payloads",
".",
"Name",
"(",
")",
",",
"Id",
":",
"docID",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"status",
"}",
"}",
"}",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // setStatusOp returns a txn.Op that updates the status of the
// identified payload. If the payload doesn't exist, it returns
// errAlreadyRemoved. | [
"setStatusOp",
"returns",
"a",
"txn",
".",
"Op",
"that",
"updates",
"the",
"status",
"of",
"the",
"identified",
"payload",
".",
"If",
"the",
"payload",
"doesn",
"t",
"exist",
"it",
"returns",
"errAlreadyRemoved",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/payloads_ns.go#L208-L221 |
154,967 | juju/juju | worker/uniter/timer.go | NewUpdateStatusTimer | func NewUpdateStatusTimer() remotestate.UpdateStatusTimerFunc {
r := rand.New(rand.NewSource(time.Now().Unix()))
return func(wait time.Duration) remotestate.Waiter {
// Actual time to wait is randomised to be +/-20%
// of the nominal value.
lower := 0.8 * float64(wait)
window := 0.4 * float64(wait)
offset := float64(r.Int63n(int64(window)))
wait = time.Duration(lower + offset)
return waitDuration(wait)
}
} | go | func NewUpdateStatusTimer() remotestate.UpdateStatusTimerFunc {
r := rand.New(rand.NewSource(time.Now().Unix()))
return func(wait time.Duration) remotestate.Waiter {
// Actual time to wait is randomised to be +/-20%
// of the nominal value.
lower := 0.8 * float64(wait)
window := 0.4 * float64(wait)
offset := float64(r.Int63n(int64(window)))
wait = time.Duration(lower + offset)
return waitDuration(wait)
}
} | [
"func",
"NewUpdateStatusTimer",
"(",
")",
"remotestate",
".",
"UpdateStatusTimerFunc",
"{",
"r",
":=",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
")",
")",
"\n",
"return",
"func",
"(",
"wait",
"time",
".",
"Duration",
")",
"remotestate",
".",
"Waiter",
"{",
"// Actual time to wait is randomised to be +/-20%",
"// of the nominal value.",
"lower",
":=",
"0.8",
"*",
"float64",
"(",
"wait",
")",
"\n",
"window",
":=",
"0.4",
"*",
"float64",
"(",
"wait",
")",
"\n",
"offset",
":=",
"float64",
"(",
"r",
".",
"Int63n",
"(",
"int64",
"(",
"window",
")",
")",
")",
"\n",
"wait",
"=",
"time",
".",
"Duration",
"(",
"lower",
"+",
"offset",
")",
"\n\n",
"return",
"waitDuration",
"(",
"wait",
")",
"\n",
"}",
"\n",
"}"
] | // NewUpdateStatusTimer returns a func returning timed signal suitable for update-status hook. | [
"NewUpdateStatusTimer",
"returns",
"a",
"func",
"returning",
"timed",
"signal",
"suitable",
"for",
"update",
"-",
"status",
"hook",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/timer.go#L21-L33 |
154,968 | juju/juju | cmd/juju/user/login.go | NewLoginCommand | func NewLoginCommand() cmd.Command {
var c loginCommand
c.SetClientStore(loginClientStore)
c.CanClearCurrentModel = true
return modelcmd.WrapController(&c, modelcmd.WrapControllerSkipControllerFlags)
} | go | func NewLoginCommand() cmd.Command {
var c loginCommand
c.SetClientStore(loginClientStore)
c.CanClearCurrentModel = true
return modelcmd.WrapController(&c, modelcmd.WrapControllerSkipControllerFlags)
} | [
"func",
"NewLoginCommand",
"(",
")",
"cmd",
".",
"Command",
"{",
"var",
"c",
"loginCommand",
"\n",
"c",
".",
"SetClientStore",
"(",
"loginClientStore",
")",
"\n",
"c",
".",
"CanClearCurrentModel",
"=",
"true",
"\n",
"return",
"modelcmd",
".",
"WrapController",
"(",
"&",
"c",
",",
"modelcmd",
".",
"WrapControllerSkipControllerFlags",
")",
"\n",
"}"
] | // NewLoginCommand returns a new cmd.Command to handle "juju login". | [
"NewLoginCommand",
"returns",
"a",
"new",
"cmd",
".",
"Command",
"to",
"handle",
"juju",
"login",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/user/login.go#L94-L99 |
154,969 | juju/juju | cmd/juju/user/login.go | publicControllerLogin | func (c *loginCommand) publicControllerLogin(
ctx *cmd.Context,
host string,
controllerName string,
currentAccountDetails *jujuclient.AccountDetails,
) (api.Connection, *jujuclient.ControllerDetails, *jujuclient.AccountDetails, error) {
fail := func(err error) (api.Connection, *jujuclient.ControllerDetails, *jujuclient.AccountDetails, error) {
return nil, nil, nil, err
}
if !strings.ContainsAny(host, ".:") {
host1, err := c.getKnownControllerDomain(host, controllerName)
if errors.IsNotFound(err) {
return fail(errors.Errorf("%q is not a known public controller", host))
}
if err != nil {
return fail(errors.Annotatef(err, "could not determine controller host name"))
}
host = host1
} else if !strings.Contains(host, ":") {
host += ":443"
}
ctrlDetails := &jujuclient.ControllerDetails{
APIEndpoints: []string{host},
}
// Make a direct API connection because we don't yet know the
// controller UUID so can't store the thus-incomplete controller
// details to make a conventional connection.
//
// Unfortunately this means we'll connect twice to the controller
// but it's probably best to go through the conventional path the
// second time.
bclient, err := c.CommandBase.BakeryClient(c.ClientStore(), controllerName)
if err != nil {
return fail(errors.Trace(err))
}
dialOpts := api.DefaultDialOpts()
dialOpts.BakeryClient = bclient
dialOpts.VerifyCA = c.promptUserToTrustCA(ctx, ctrlDetails)
// Keep track of existing visitors as the dial callback will create
// a new visitor each time it gets invoked.
existingVisitor := bclient.WebPageVisitor
dial := func(d *jujuclient.AccountDetails) (api.Connection, error) {
// Attach a web visitor for "juju_userpass" which will be
// invoked if we attempt to login without a password and the
// remote controller does not support an external identity
// provider.
var tag names.Tag
if d.User != "" {
tag = names.NewUserTag(d.User)
}
dialOpts.BakeryClient.WebPageVisitor = httpbakery.NewMultiVisitor(
authentication.NewVisitor(d.User, func(string) (string, error) {
// The visitor from the authentication package
// passes the username to the password getter
// func. As other password getters may rely on
// this we just provide a wrapper that calls
// pollster with the correct label.
return c.pollster.EnterPassword("password")
}),
existingVisitor,
)
return apiOpen(&c.CommandBase, &api.Info{
Tag: tag,
Password: d.Password,
Addrs: []string{host},
}, dialOpts)
}
conn, accountDetails, err := c.login(ctx, currentAccountDetails, dial)
if err != nil {
return fail(errors.Trace(err))
}
// If we get to here, then we have a cached macaroon for the registered
// user. If we encounter an error after here, we need to clear it.
c.onRunError = func() {
if err := c.ClearControllerMacaroons(c.ClientStore(), controllerName); err != nil {
logger.Errorf("failed to clear macaroon: %v", err)
}
}
ctrlDetails.ControllerUUID = conn.ControllerTag().Id()
return conn, ctrlDetails, accountDetails, nil
} | go | func (c *loginCommand) publicControllerLogin(
ctx *cmd.Context,
host string,
controllerName string,
currentAccountDetails *jujuclient.AccountDetails,
) (api.Connection, *jujuclient.ControllerDetails, *jujuclient.AccountDetails, error) {
fail := func(err error) (api.Connection, *jujuclient.ControllerDetails, *jujuclient.AccountDetails, error) {
return nil, nil, nil, err
}
if !strings.ContainsAny(host, ".:") {
host1, err := c.getKnownControllerDomain(host, controllerName)
if errors.IsNotFound(err) {
return fail(errors.Errorf("%q is not a known public controller", host))
}
if err != nil {
return fail(errors.Annotatef(err, "could not determine controller host name"))
}
host = host1
} else if !strings.Contains(host, ":") {
host += ":443"
}
ctrlDetails := &jujuclient.ControllerDetails{
APIEndpoints: []string{host},
}
// Make a direct API connection because we don't yet know the
// controller UUID so can't store the thus-incomplete controller
// details to make a conventional connection.
//
// Unfortunately this means we'll connect twice to the controller
// but it's probably best to go through the conventional path the
// second time.
bclient, err := c.CommandBase.BakeryClient(c.ClientStore(), controllerName)
if err != nil {
return fail(errors.Trace(err))
}
dialOpts := api.DefaultDialOpts()
dialOpts.BakeryClient = bclient
dialOpts.VerifyCA = c.promptUserToTrustCA(ctx, ctrlDetails)
// Keep track of existing visitors as the dial callback will create
// a new visitor each time it gets invoked.
existingVisitor := bclient.WebPageVisitor
dial := func(d *jujuclient.AccountDetails) (api.Connection, error) {
// Attach a web visitor for "juju_userpass" which will be
// invoked if we attempt to login without a password and the
// remote controller does not support an external identity
// provider.
var tag names.Tag
if d.User != "" {
tag = names.NewUserTag(d.User)
}
dialOpts.BakeryClient.WebPageVisitor = httpbakery.NewMultiVisitor(
authentication.NewVisitor(d.User, func(string) (string, error) {
// The visitor from the authentication package
// passes the username to the password getter
// func. As other password getters may rely on
// this we just provide a wrapper that calls
// pollster with the correct label.
return c.pollster.EnterPassword("password")
}),
existingVisitor,
)
return apiOpen(&c.CommandBase, &api.Info{
Tag: tag,
Password: d.Password,
Addrs: []string{host},
}, dialOpts)
}
conn, accountDetails, err := c.login(ctx, currentAccountDetails, dial)
if err != nil {
return fail(errors.Trace(err))
}
// If we get to here, then we have a cached macaroon for the registered
// user. If we encounter an error after here, we need to clear it.
c.onRunError = func() {
if err := c.ClearControllerMacaroons(c.ClientStore(), controllerName); err != nil {
logger.Errorf("failed to clear macaroon: %v", err)
}
}
ctrlDetails.ControllerUUID = conn.ControllerTag().Id()
return conn, ctrlDetails, accountDetails, nil
} | [
"func",
"(",
"c",
"*",
"loginCommand",
")",
"publicControllerLogin",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
",",
"host",
"string",
",",
"controllerName",
"string",
",",
"currentAccountDetails",
"*",
"jujuclient",
".",
"AccountDetails",
",",
")",
"(",
"api",
".",
"Connection",
",",
"*",
"jujuclient",
".",
"ControllerDetails",
",",
"*",
"jujuclient",
".",
"AccountDetails",
",",
"error",
")",
"{",
"fail",
":=",
"func",
"(",
"err",
"error",
")",
"(",
"api",
".",
"Connection",
",",
"*",
"jujuclient",
".",
"ControllerDetails",
",",
"*",
"jujuclient",
".",
"AccountDetails",
",",
"error",
")",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"ContainsAny",
"(",
"host",
",",
"\"",
"\"",
")",
"{",
"host1",
",",
"err",
":=",
"c",
".",
"getKnownControllerDomain",
"(",
"host",
",",
"controllerName",
")",
"\n",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"fail",
"(",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"host",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fail",
"(",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"host",
"=",
"host1",
"\n",
"}",
"else",
"if",
"!",
"strings",
".",
"Contains",
"(",
"host",
",",
"\"",
"\"",
")",
"{",
"host",
"+=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"ctrlDetails",
":=",
"&",
"jujuclient",
".",
"ControllerDetails",
"{",
"APIEndpoints",
":",
"[",
"]",
"string",
"{",
"host",
"}",
",",
"}",
"\n\n",
"// Make a direct API connection because we don't yet know the",
"// controller UUID so can't store the thus-incomplete controller",
"// details to make a conventional connection.",
"//",
"// Unfortunately this means we'll connect twice to the controller",
"// but it's probably best to go through the conventional path the",
"// second time.",
"bclient",
",",
"err",
":=",
"c",
".",
"CommandBase",
".",
"BakeryClient",
"(",
"c",
".",
"ClientStore",
"(",
")",
",",
"controllerName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fail",
"(",
"errors",
".",
"Trace",
"(",
"err",
")",
")",
"\n",
"}",
"\n",
"dialOpts",
":=",
"api",
".",
"DefaultDialOpts",
"(",
")",
"\n",
"dialOpts",
".",
"BakeryClient",
"=",
"bclient",
"\n",
"dialOpts",
".",
"VerifyCA",
"=",
"c",
".",
"promptUserToTrustCA",
"(",
"ctx",
",",
"ctrlDetails",
")",
"\n\n",
"// Keep track of existing visitors as the dial callback will create",
"// a new visitor each time it gets invoked.",
"existingVisitor",
":=",
"bclient",
".",
"WebPageVisitor",
"\n\n",
"dial",
":=",
"func",
"(",
"d",
"*",
"jujuclient",
".",
"AccountDetails",
")",
"(",
"api",
".",
"Connection",
",",
"error",
")",
"{",
"// Attach a web visitor for \"juju_userpass\" which will be",
"// invoked if we attempt to login without a password and the",
"// remote controller does not support an external identity",
"// provider.",
"var",
"tag",
"names",
".",
"Tag",
"\n",
"if",
"d",
".",
"User",
"!=",
"\"",
"\"",
"{",
"tag",
"=",
"names",
".",
"NewUserTag",
"(",
"d",
".",
"User",
")",
"\n",
"}",
"\n\n",
"dialOpts",
".",
"BakeryClient",
".",
"WebPageVisitor",
"=",
"httpbakery",
".",
"NewMultiVisitor",
"(",
"authentication",
".",
"NewVisitor",
"(",
"d",
".",
"User",
",",
"func",
"(",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"// The visitor from the authentication package",
"// passes the username to the password getter",
"// func. As other password getters may rely on",
"// this we just provide a wrapper that calls",
"// pollster with the correct label.",
"return",
"c",
".",
"pollster",
".",
"EnterPassword",
"(",
"\"",
"\"",
")",
"\n",
"}",
")",
",",
"existingVisitor",
",",
")",
"\n\n",
"return",
"apiOpen",
"(",
"&",
"c",
".",
"CommandBase",
",",
"&",
"api",
".",
"Info",
"{",
"Tag",
":",
"tag",
",",
"Password",
":",
"d",
".",
"Password",
",",
"Addrs",
":",
"[",
"]",
"string",
"{",
"host",
"}",
",",
"}",
",",
"dialOpts",
")",
"\n",
"}",
"\n",
"conn",
",",
"accountDetails",
",",
"err",
":=",
"c",
".",
"login",
"(",
"ctx",
",",
"currentAccountDetails",
",",
"dial",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fail",
"(",
"errors",
".",
"Trace",
"(",
"err",
")",
")",
"\n",
"}",
"\n",
"// If we get to here, then we have a cached macaroon for the registered",
"// user. If we encounter an error after here, we need to clear it.",
"c",
".",
"onRunError",
"=",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"c",
".",
"ClearControllerMacaroons",
"(",
"c",
".",
"ClientStore",
"(",
")",
",",
"controllerName",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"ctrlDetails",
".",
"ControllerUUID",
"=",
"conn",
".",
"ControllerTag",
"(",
")",
".",
"Id",
"(",
")",
"\n",
"return",
"conn",
",",
"ctrlDetails",
",",
"accountDetails",
",",
"nil",
"\n",
"}"
] | // publicControllerLogin logs into the public controller at the given
// host. The currentAccountDetails parameter holds existing account
// information about the controller account. | [
"publicControllerLogin",
"logs",
"into",
"the",
"public",
"controller",
"at",
"the",
"given",
"host",
".",
"The",
"currentAccountDetails",
"parameter",
"holds",
"existing",
"account",
"information",
"about",
"the",
"controller",
"account",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/user/login.go#L295-L382 |
154,970 | juju/juju | cmd/juju/user/login.go | login | func (c *loginCommand) login(
ctx *cmd.Context,
accountDetails *jujuclient.AccountDetails,
dial func(*jujuclient.AccountDetails) (api.Connection, error),
) (api.Connection, *jujuclient.AccountDetails, error) {
username := c.username
if c.username != "" && accountDetails != nil && accountDetails.User != c.username {
// The user has specified a different username than the
// user we've found in the controller's account details.
return nil, nil, errors.Errorf(`already logged in as %s.
Run "juju logout" first before attempting to log in as a different user.`,
accountDetails.User)
}
if accountDetails != nil && accountDetails.Password != "" {
// We've been provided some account details that
// contain a password, so try that first.
conn, err := dial(accountDetails)
if err == nil {
return conn, accountDetails, nil
}
if !errors.IsUnauthorized(err) {
return nil, nil, errors.Trace(err)
}
}
if c.username == "" {
// No username specified, so try external-user login first.
conn, err := dial(&jujuclient.AccountDetails{})
if err == nil {
user, ok := conn.AuthTag().(names.UserTag)
if !ok {
conn.Close()
return nil, nil, errors.Errorf("logged in as %v, not a user", conn.AuthTag())
}
return conn, &jujuclient.AccountDetails{
User: user.Id(),
}, nil
}
if !params.IsCodeNoCreds(err) {
return nil, nil, errors.Trace(err)
}
// CodeNoCreds was returned, which means that external users
// are not supported. Ask the user to type in their username
// and try a macaroon-based authentication; if that also fails
// the server will fall back to juju_userpass authentication
// and the web page visitor registered with httpbakery will
// prompt for the user's password.
if username, err = c.pollster.Enter("username"); err != nil {
return nil, nil, errors.Trace(err)
}
}
// Log in without specifying a password in the account details. This
// will trigger macaroon-based authentication, which will prompt the
// user for their password.
accountDetails = &jujuclient.AccountDetails{
User: username,
}
conn, err := dial(accountDetails)
return conn, accountDetails, errors.Trace(err)
} | go | func (c *loginCommand) login(
ctx *cmd.Context,
accountDetails *jujuclient.AccountDetails,
dial func(*jujuclient.AccountDetails) (api.Connection, error),
) (api.Connection, *jujuclient.AccountDetails, error) {
username := c.username
if c.username != "" && accountDetails != nil && accountDetails.User != c.username {
// The user has specified a different username than the
// user we've found in the controller's account details.
return nil, nil, errors.Errorf(`already logged in as %s.
Run "juju logout" first before attempting to log in as a different user.`,
accountDetails.User)
}
if accountDetails != nil && accountDetails.Password != "" {
// We've been provided some account details that
// contain a password, so try that first.
conn, err := dial(accountDetails)
if err == nil {
return conn, accountDetails, nil
}
if !errors.IsUnauthorized(err) {
return nil, nil, errors.Trace(err)
}
}
if c.username == "" {
// No username specified, so try external-user login first.
conn, err := dial(&jujuclient.AccountDetails{})
if err == nil {
user, ok := conn.AuthTag().(names.UserTag)
if !ok {
conn.Close()
return nil, nil, errors.Errorf("logged in as %v, not a user", conn.AuthTag())
}
return conn, &jujuclient.AccountDetails{
User: user.Id(),
}, nil
}
if !params.IsCodeNoCreds(err) {
return nil, nil, errors.Trace(err)
}
// CodeNoCreds was returned, which means that external users
// are not supported. Ask the user to type in their username
// and try a macaroon-based authentication; if that also fails
// the server will fall back to juju_userpass authentication
// and the web page visitor registered with httpbakery will
// prompt for the user's password.
if username, err = c.pollster.Enter("username"); err != nil {
return nil, nil, errors.Trace(err)
}
}
// Log in without specifying a password in the account details. This
// will trigger macaroon-based authentication, which will prompt the
// user for their password.
accountDetails = &jujuclient.AccountDetails{
User: username,
}
conn, err := dial(accountDetails)
return conn, accountDetails, errors.Trace(err)
} | [
"func",
"(",
"c",
"*",
"loginCommand",
")",
"login",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
",",
"accountDetails",
"*",
"jujuclient",
".",
"AccountDetails",
",",
"dial",
"func",
"(",
"*",
"jujuclient",
".",
"AccountDetails",
")",
"(",
"api",
".",
"Connection",
",",
"error",
")",
",",
")",
"(",
"api",
".",
"Connection",
",",
"*",
"jujuclient",
".",
"AccountDetails",
",",
"error",
")",
"{",
"username",
":=",
"c",
".",
"username",
"\n",
"if",
"c",
".",
"username",
"!=",
"\"",
"\"",
"&&",
"accountDetails",
"!=",
"nil",
"&&",
"accountDetails",
".",
"User",
"!=",
"c",
".",
"username",
"{",
"// The user has specified a different username than the",
"// user we've found in the controller's account details.",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"`already logged in as %s.\n\nRun \"juju logout\" first before attempting to log in as a different user.`",
",",
"accountDetails",
".",
"User",
")",
"\n",
"}",
"\n\n",
"if",
"accountDetails",
"!=",
"nil",
"&&",
"accountDetails",
".",
"Password",
"!=",
"\"",
"\"",
"{",
"// We've been provided some account details that",
"// contain a password, so try that first.",
"conn",
",",
"err",
":=",
"dial",
"(",
"accountDetails",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"conn",
",",
"accountDetails",
",",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"errors",
".",
"IsUnauthorized",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"c",
".",
"username",
"==",
"\"",
"\"",
"{",
"// No username specified, so try external-user login first.",
"conn",
",",
"err",
":=",
"dial",
"(",
"&",
"jujuclient",
".",
"AccountDetails",
"{",
"}",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"user",
",",
"ok",
":=",
"conn",
".",
"AuthTag",
"(",
")",
".",
"(",
"names",
".",
"UserTag",
")",
"\n",
"if",
"!",
"ok",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"conn",
".",
"AuthTag",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"conn",
",",
"&",
"jujuclient",
".",
"AccountDetails",
"{",
"User",
":",
"user",
".",
"Id",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"params",
".",
"IsCodeNoCreds",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// CodeNoCreds was returned, which means that external users",
"// are not supported. Ask the user to type in their username",
"// and try a macaroon-based authentication; if that also fails",
"// the server will fall back to juju_userpass authentication",
"// and the web page visitor registered with httpbakery will",
"// prompt for the user's password.",
"if",
"username",
",",
"err",
"=",
"c",
".",
"pollster",
".",
"Enter",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Log in without specifying a password in the account details. This",
"// will trigger macaroon-based authentication, which will prompt the",
"// user for their password.",
"accountDetails",
"=",
"&",
"jujuclient",
".",
"AccountDetails",
"{",
"User",
":",
"username",
",",
"}",
"\n",
"conn",
",",
"err",
":=",
"dial",
"(",
"accountDetails",
")",
"\n",
"return",
"conn",
",",
"accountDetails",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // login logs into a controller using the given account details by
// default, but falling back to prompting for a username and password if
// necessary. The details of making an API connection are abstracted out
// into the dial function because we need to dial differently depending
// on whether we have some existing local controller information or not.
//
// The dial function should make API connection using the account
// details that it is passed. | [
"login",
"logs",
"into",
"a",
"controller",
"using",
"the",
"given",
"account",
"details",
"by",
"default",
"but",
"falling",
"back",
"to",
"prompting",
"for",
"a",
"username",
"and",
"password",
"if",
"necessary",
".",
"The",
"details",
"of",
"making",
"an",
"API",
"connection",
"are",
"abstracted",
"out",
"into",
"the",
"dial",
"function",
"because",
"we",
"need",
"to",
"dial",
"differently",
"depending",
"on",
"whether",
"we",
"have",
"some",
"existing",
"local",
"controller",
"information",
"or",
"not",
".",
"The",
"dial",
"function",
"should",
"make",
"API",
"connection",
"using",
"the",
"account",
"details",
"that",
"it",
"is",
"passed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/user/login.go#L392-L454 |
154,971 | juju/juju | cmd/juju/user/login.go | getKnownControllerDomain | func (c *loginCommand) getKnownControllerDomain(name, controllerName string) (string, error) {
if strings.Contains(name, ".") || strings.Contains(name, ":") {
return "", errors.NotFoundf("controller %q", name)
}
baseURL := defaultJujuDirectory
if u := os.Getenv("JUJU_DIRECTORY"); u != "" {
baseURL = u
}
client, err := c.CommandBase.BakeryClient(c.ClientStore(), controllerName)
if err != nil {
return "", errors.Trace(err)
}
req, err := http.NewRequest("GET", baseURL+"/v1/controller/"+name, nil)
if err != nil {
return "", errors.Trace(err)
}
httpResp, err := client.Do(req)
if err != nil {
return "", errors.Trace(err)
}
defer httpResp.Body.Close()
if httpResp.StatusCode != http.StatusOK {
if httpResp.StatusCode == http.StatusNotFound {
return "", errors.NotFoundf("controller %q", name)
}
return "", errors.Errorf("unexpected HTTP response %q", httpResp.Status)
}
var resp controllerDomainResponse
if err := httprequest.UnmarshalJSONResponse(httpResp, &resp); err != nil {
return "", errors.Trace(err)
}
if resp.Host == "" {
return "", errors.Errorf("no host field found in response")
}
return resp.Host, nil
} | go | func (c *loginCommand) getKnownControllerDomain(name, controllerName string) (string, error) {
if strings.Contains(name, ".") || strings.Contains(name, ":") {
return "", errors.NotFoundf("controller %q", name)
}
baseURL := defaultJujuDirectory
if u := os.Getenv("JUJU_DIRECTORY"); u != "" {
baseURL = u
}
client, err := c.CommandBase.BakeryClient(c.ClientStore(), controllerName)
if err != nil {
return "", errors.Trace(err)
}
req, err := http.NewRequest("GET", baseURL+"/v1/controller/"+name, nil)
if err != nil {
return "", errors.Trace(err)
}
httpResp, err := client.Do(req)
if err != nil {
return "", errors.Trace(err)
}
defer httpResp.Body.Close()
if httpResp.StatusCode != http.StatusOK {
if httpResp.StatusCode == http.StatusNotFound {
return "", errors.NotFoundf("controller %q", name)
}
return "", errors.Errorf("unexpected HTTP response %q", httpResp.Status)
}
var resp controllerDomainResponse
if err := httprequest.UnmarshalJSONResponse(httpResp, &resp); err != nil {
return "", errors.Trace(err)
}
if resp.Host == "" {
return "", errors.Errorf("no host field found in response")
}
return resp.Host, nil
} | [
"func",
"(",
"c",
"*",
"loginCommand",
")",
"getKnownControllerDomain",
"(",
"name",
",",
"controllerName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"strings",
".",
"Contains",
"(",
"name",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"Contains",
"(",
"name",
",",
"\"",
"\"",
")",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"baseURL",
":=",
"defaultJujuDirectory",
"\n",
"if",
"u",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
";",
"u",
"!=",
"\"",
"\"",
"{",
"baseURL",
"=",
"u",
"\n",
"}",
"\n",
"client",
",",
"err",
":=",
"c",
".",
"CommandBase",
".",
"BakeryClient",
"(",
"c",
".",
"ClientStore",
"(",
")",
",",
"controllerName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"baseURL",
"+",
"\"",
"\"",
"+",
"name",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"httpResp",
",",
"err",
":=",
"client",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"httpResp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"httpResp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"if",
"httpResp",
".",
"StatusCode",
"==",
"http",
".",
"StatusNotFound",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"httpResp",
".",
"Status",
")",
"\n",
"}",
"\n",
"var",
"resp",
"controllerDomainResponse",
"\n",
"if",
"err",
":=",
"httprequest",
".",
"UnmarshalJSONResponse",
"(",
"httpResp",
",",
"&",
"resp",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"resp",
".",
"Host",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"resp",
".",
"Host",
",",
"nil",
"\n",
"}"
] | // getKnownControllerDomain returns the list of known
// controller domain aliases. | [
"getKnownControllerDomain",
"returns",
"the",
"list",
"of",
"known",
"controller",
"domain",
"aliases",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/user/login.go#L515-L550 |
154,972 | juju/juju | cmd/juju/user/login.go | ensureNotKnownEndpoint | func ensureNotKnownEndpoint(store jujuclient.ClientStore, endpoint string) error {
existingDetails, existingName, err := store.ControllerByAPIEndpoints(endpoint)
if err != nil && !errors.IsNotFound(err) {
return errors.Trace(err)
}
if existingDetails == nil {
return nil
}
// Check if we know the username for this controller
accountDetails, err := store.AccountDetails(existingName)
if err != nil && !errors.IsNotFound(err) {
return errors.Trace(err)
}
if accountDetails != nil {
return errors.Errorf(`This controller has already been registered on this client as %q
To login as user %q run 'juju login -u %s -c %s'.`, existingName, accountDetails.User, accountDetails.User, existingName)
}
return errors.Errorf(`This controller has already been registered on this client as %q
To login run 'juju login -c %s'.`, existingName, existingName)
} | go | func ensureNotKnownEndpoint(store jujuclient.ClientStore, endpoint string) error {
existingDetails, existingName, err := store.ControllerByAPIEndpoints(endpoint)
if err != nil && !errors.IsNotFound(err) {
return errors.Trace(err)
}
if existingDetails == nil {
return nil
}
// Check if we know the username for this controller
accountDetails, err := store.AccountDetails(existingName)
if err != nil && !errors.IsNotFound(err) {
return errors.Trace(err)
}
if accountDetails != nil {
return errors.Errorf(`This controller has already been registered on this client as %q
To login as user %q run 'juju login -u %s -c %s'.`, existingName, accountDetails.User, accountDetails.User, existingName)
}
return errors.Errorf(`This controller has already been registered on this client as %q
To login run 'juju login -c %s'.`, existingName, existingName)
} | [
"func",
"ensureNotKnownEndpoint",
"(",
"store",
"jujuclient",
".",
"ClientStore",
",",
"endpoint",
"string",
")",
"error",
"{",
"existingDetails",
",",
"existingName",
",",
"err",
":=",
"store",
".",
"ControllerByAPIEndpoints",
"(",
"endpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"existingDetails",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Check if we know the username for this controller",
"accountDetails",
",",
"err",
":=",
"store",
".",
"AccountDetails",
"(",
"existingName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"accountDetails",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"`This controller has already been registered on this client as %q\nTo login as user %q run 'juju login -u %s -c %s'.`",
",",
"existingName",
",",
"accountDetails",
".",
"User",
",",
"accountDetails",
".",
"User",
",",
"existingName",
")",
"\n",
"}",
"\n\n",
"return",
"errors",
".",
"Errorf",
"(",
"`This controller has already been registered on this client as %q\nTo login run 'juju login -c %s'.`",
",",
"existingName",
",",
"existingName",
")",
"\n",
"}"
] | // ensureNotKnownEndpoint checks whether any controllers in the local client
// cache contain the provided endpoint and returns an error if that is the
// case. | [
"ensureNotKnownEndpoint",
"checks",
"whether",
"any",
"controllers",
"in",
"the",
"local",
"client",
"cache",
"contain",
"the",
"provided",
"endpoint",
"and",
"returns",
"an",
"error",
"if",
"that",
"is",
"the",
"case",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/user/login.go#L604-L627 |
154,973 | juju/juju | apiserver/common/firewall/egressaddresswatcher.go | NewEgressAddressWatcher | func NewEgressAddressWatcher(backend State, rel Relation, appName string) (*EgressAddressWatcher, error) {
w := &EgressAddressWatcher{
backend: backend,
appName: appName,
rel: rel,
known: make(map[string]string),
out: make(chan []string),
addressChanges: make(chan string),
machines: make(map[string]*machineData),
unitToMachine: make(map[string]string),
knownModelEgress: set.NewStrings(),
}
err := catacomb.Invoke(catacomb.Plan{
Site: &w.catacomb,
Work: w.loop,
})
return w, err
} | go | func NewEgressAddressWatcher(backend State, rel Relation, appName string) (*EgressAddressWatcher, error) {
w := &EgressAddressWatcher{
backend: backend,
appName: appName,
rel: rel,
known: make(map[string]string),
out: make(chan []string),
addressChanges: make(chan string),
machines: make(map[string]*machineData),
unitToMachine: make(map[string]string),
knownModelEgress: set.NewStrings(),
}
err := catacomb.Invoke(catacomb.Plan{
Site: &w.catacomb,
Work: w.loop,
})
return w, err
} | [
"func",
"NewEgressAddressWatcher",
"(",
"backend",
"State",
",",
"rel",
"Relation",
",",
"appName",
"string",
")",
"(",
"*",
"EgressAddressWatcher",
",",
"error",
")",
"{",
"w",
":=",
"&",
"EgressAddressWatcher",
"{",
"backend",
":",
"backend",
",",
"appName",
":",
"appName",
",",
"rel",
":",
"rel",
",",
"known",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"out",
":",
"make",
"(",
"chan",
"[",
"]",
"string",
")",
",",
"addressChanges",
":",
"make",
"(",
"chan",
"string",
")",
",",
"machines",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"machineData",
")",
",",
"unitToMachine",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"knownModelEgress",
":",
"set",
".",
"NewStrings",
"(",
")",
",",
"}",
"\n",
"err",
":=",
"catacomb",
".",
"Invoke",
"(",
"catacomb",
".",
"Plan",
"{",
"Site",
":",
"&",
"w",
".",
"catacomb",
",",
"Work",
":",
"w",
".",
"loop",
",",
"}",
")",
"\n",
"return",
"w",
",",
"err",
"\n",
"}"
] | // NewEgressAddressWatcher creates an EgressAddressWatcher. | [
"NewEgressAddressWatcher",
"creates",
"an",
"EgressAddressWatcher",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/firewall/egressaddresswatcher.go#L58-L75 |
154,974 | juju/juju | worker/modelupgrader/manifold.go | Manifold | func Manifold(config ManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{
config.APICallerName,
config.EnvironName,
config.GateName,
},
Start: config.start,
Filter: bounceErrChanged,
}
} | go | func Manifold(config ManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{
config.APICallerName,
config.EnvironName,
config.GateName,
},
Start: config.start,
Filter: bounceErrChanged,
}
} | [
"func",
"Manifold",
"(",
"config",
"ManifoldConfig",
")",
"dependency",
".",
"Manifold",
"{",
"return",
"dependency",
".",
"Manifold",
"{",
"Inputs",
":",
"[",
"]",
"string",
"{",
"config",
".",
"APICallerName",
",",
"config",
".",
"EnvironName",
",",
"config",
".",
"GateName",
",",
"}",
",",
"Start",
":",
"config",
".",
"start",
",",
"Filter",
":",
"bounceErrChanged",
",",
"}",
"\n",
"}"
] | // Manifold returns a dependency.Manifold that will run a Worker as
// configured. | [
"Manifold",
"returns",
"a",
"dependency",
".",
"Manifold",
"that",
"will",
"run",
"a",
"Worker",
"as",
"configured",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/modelupgrader/manifold.go#L81-L91 |
154,975 | juju/juju | worker/modelupgrader/manifold.go | bounceErrChanged | func bounceErrChanged(err error) error {
if errors.Cause(err) == ErrModelRemoved {
return dependency.ErrUninstall
}
return err
} | go | func bounceErrChanged(err error) error {
if errors.Cause(err) == ErrModelRemoved {
return dependency.ErrUninstall
}
return err
} | [
"func",
"bounceErrChanged",
"(",
"err",
"error",
")",
"error",
"{",
"if",
"errors",
".",
"Cause",
"(",
"err",
")",
"==",
"ErrModelRemoved",
"{",
"return",
"dependency",
".",
"ErrUninstall",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // bounceErrChanged converts ErrModelRemoved to dependency.ErrUninstall. | [
"bounceErrChanged",
"converts",
"ErrModelRemoved",
"to",
"dependency",
".",
"ErrUninstall",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/modelupgrader/manifold.go#L94-L99 |
154,976 | juju/juju | worker/certupdater/manifold.go | NewMachineAddressWatcher | func NewMachineAddressWatcher(st *state.State, machineId string) (AddressWatcher, error) {
return st.Machine(machineId)
} | go | func NewMachineAddressWatcher(st *state.State, machineId string) (AddressWatcher, error) {
return st.Machine(machineId)
} | [
"func",
"NewMachineAddressWatcher",
"(",
"st",
"*",
"state",
".",
"State",
",",
"machineId",
"string",
")",
"(",
"AddressWatcher",
",",
"error",
")",
"{",
"return",
"st",
".",
"Machine",
"(",
"machineId",
")",
"\n",
"}"
] | // NewMachineAddressWatcher is the function that non-test code should
// pass into ManifoldConfig.NewMachineAddressWatcher. | [
"NewMachineAddressWatcher",
"is",
"the",
"function",
"that",
"non",
"-",
"test",
"code",
"should",
"pass",
"into",
"ManifoldConfig",
".",
"NewMachineAddressWatcher",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/certupdater/manifold.go#L101-L103 |
154,977 | juju/juju | state/modelconfig.go | ModelConfig | func (m *Model) ModelConfig() (*config.Config, error) {
return getModelConfig(m.st.db(), m.UUID())
} | go | func (m *Model) ModelConfig() (*config.Config, error) {
return getModelConfig(m.st.db(), m.UUID())
} | [
"func",
"(",
"m",
"*",
"Model",
")",
"ModelConfig",
"(",
")",
"(",
"*",
"config",
".",
"Config",
",",
"error",
")",
"{",
"return",
"getModelConfig",
"(",
"m",
".",
"st",
".",
"db",
"(",
")",
",",
"m",
".",
"UUID",
"(",
")",
")",
"\n",
"}"
] | // ModelConfig returns the complete config for the model | [
"ModelConfig",
"returns",
"the",
"complete",
"config",
"for",
"the",
"model"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L24-L26 |
154,978 | juju/juju | state/modelconfig.go | AgentVersion | func (m *Model) AgentVersion() (version.Number, error) {
cfg, err := m.ModelConfig()
if err != nil {
return version.Number{}, errors.Trace(err)
}
ver, ok := cfg.AgentVersion()
if !ok {
return version.Number{}, errors.NotFoundf("agent version")
}
return ver, nil
} | go | func (m *Model) AgentVersion() (version.Number, error) {
cfg, err := m.ModelConfig()
if err != nil {
return version.Number{}, errors.Trace(err)
}
ver, ok := cfg.AgentVersion()
if !ok {
return version.Number{}, errors.NotFoundf("agent version")
}
return ver, nil
} | [
"func",
"(",
"m",
"*",
"Model",
")",
"AgentVersion",
"(",
")",
"(",
"version",
".",
"Number",
",",
"error",
")",
"{",
"cfg",
",",
"err",
":=",
"m",
".",
"ModelConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"version",
".",
"Number",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"ver",
",",
"ok",
":=",
"cfg",
".",
"AgentVersion",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"version",
".",
"Number",
"{",
"}",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"ver",
",",
"nil",
"\n",
"}"
] | // AgentVersion returns the agent version for the model config.
// If no agent version is found, it returns NotFound error. | [
"AgentVersion",
"returns",
"the",
"agent",
"version",
"for",
"the",
"model",
"config",
".",
"If",
"no",
"agent",
"version",
"is",
"found",
"it",
"returns",
"NotFound",
"error",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L30-L40 |
154,979 | juju/juju | state/modelconfig.go | checkModelConfig | func checkModelConfig(cfg *config.Config) error {
allAttrs := cfg.AllAttrs()
for _, attr := range disallowedModelConfigAttrs {
if _, ok := allAttrs[attr]; ok {
return errors.Errorf(attr + " should never be written to the state")
}
}
if _, ok := cfg.AgentVersion(); !ok {
return errors.Errorf("agent-version must always be set in state")
}
for attr := range allAttrs {
if controller.ControllerOnlyAttribute(attr) {
return errors.Errorf("cannot set controller attribute %q on a model", attr)
}
}
return nil
} | go | func checkModelConfig(cfg *config.Config) error {
allAttrs := cfg.AllAttrs()
for _, attr := range disallowedModelConfigAttrs {
if _, ok := allAttrs[attr]; ok {
return errors.Errorf(attr + " should never be written to the state")
}
}
if _, ok := cfg.AgentVersion(); !ok {
return errors.Errorf("agent-version must always be set in state")
}
for attr := range allAttrs {
if controller.ControllerOnlyAttribute(attr) {
return errors.Errorf("cannot set controller attribute %q on a model", attr)
}
}
return nil
} | [
"func",
"checkModelConfig",
"(",
"cfg",
"*",
"config",
".",
"Config",
")",
"error",
"{",
"allAttrs",
":=",
"cfg",
".",
"AllAttrs",
"(",
")",
"\n",
"for",
"_",
",",
"attr",
":=",
"range",
"disallowedModelConfigAttrs",
"{",
"if",
"_",
",",
"ok",
":=",
"allAttrs",
"[",
"attr",
"]",
";",
"ok",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"attr",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"cfg",
".",
"AgentVersion",
"(",
")",
";",
"!",
"ok",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"attr",
":=",
"range",
"allAttrs",
"{",
"if",
"controller",
".",
"ControllerOnlyAttribute",
"(",
"attr",
")",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"attr",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // checkModelConfig returns an error if the config is definitely invalid. | [
"checkModelConfig",
"returns",
"an",
"error",
"if",
"the",
"config",
"is",
"definitely",
"invalid",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L51-L67 |
154,980 | juju/juju | state/modelconfig.go | inheritedConfigAttributes | func (st *State) inheritedConfigAttributes() (map[string]interface{}, error) {
rspec, err := st.regionSpec()
if err != nil {
return nil, errors.Trace(err)
}
configSources := modelConfigSources(st, rspec)
values := make(attrValues)
for _, src := range configSources {
cfg, err := src.sourceFunc()
if errors.IsNotFound(err) {
continue
}
if err != nil {
return nil, errors.Annotatef(err, "reading %s settings", src.name)
}
for attrName, value := range cfg {
values[attrName] = value
}
}
return values, nil
} | go | func (st *State) inheritedConfigAttributes() (map[string]interface{}, error) {
rspec, err := st.regionSpec()
if err != nil {
return nil, errors.Trace(err)
}
configSources := modelConfigSources(st, rspec)
values := make(attrValues)
for _, src := range configSources {
cfg, err := src.sourceFunc()
if errors.IsNotFound(err) {
continue
}
if err != nil {
return nil, errors.Annotatef(err, "reading %s settings", src.name)
}
for attrName, value := range cfg {
values[attrName] = value
}
}
return values, nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"inheritedConfigAttributes",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"rspec",
",",
"err",
":=",
"st",
".",
"regionSpec",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"configSources",
":=",
"modelConfigSources",
"(",
"st",
",",
"rspec",
")",
"\n",
"values",
":=",
"make",
"(",
"attrValues",
")",
"\n",
"for",
"_",
",",
"src",
":=",
"range",
"configSources",
"{",
"cfg",
",",
"err",
":=",
"src",
".",
"sourceFunc",
"(",
")",
"\n",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"src",
".",
"name",
")",
"\n",
"}",
"\n",
"for",
"attrName",
",",
"value",
":=",
"range",
"cfg",
"{",
"values",
"[",
"attrName",
"]",
"=",
"value",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"values",
",",
"nil",
"\n",
"}"
] | // inheritedConfigAttributes returns the merged collection of inherited config
// values used as model defaults when adding models or unsetting values. | [
"inheritedConfigAttributes",
"returns",
"the",
"merged",
"collection",
"of",
"inherited",
"config",
"values",
"used",
"as",
"model",
"defaults",
"when",
"adding",
"models",
"or",
"unsetting",
"values",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L71-L91 |
154,981 | juju/juju | state/modelconfig.go | modelConfigValues | func (model *Model) modelConfigValues(modelCfg attrValues) (config.ConfigValues, error) {
resultValues := make(attrValues)
for k, v := range modelCfg {
resultValues[k] = v
}
// Read all of the current inherited config values so
// we can dynamically reflect the origin of the model config.
rspec, err := model.st.regionSpec()
if err != nil {
return nil, errors.Trace(err)
}
configSources := modelConfigSources(model.st, rspec)
sourceNames := make([]string, 0, len(configSources))
sourceAttrs := make([]attrValues, 0, len(configSources))
for _, src := range configSources {
sourceNames = append(sourceNames, src.name)
cfg, err := src.sourceFunc()
if errors.IsNotFound(err) {
continue
}
if err != nil {
return nil, errors.Annotatef(err, "reading %s settings", src.name)
}
sourceAttrs = append(sourceAttrs, cfg)
// If no modelCfg was passed in, we'll accumulate data
// for the inherited values instead.
if len(modelCfg) == 0 {
for k, v := range cfg {
resultValues[k] = v
}
}
}
// Figure out the source of each config attribute based
// on the current model values and the inherited values.
result := make(config.ConfigValues)
for attr, val := range resultValues {
// Find the source of config for which the model
// value matches. If there's a match, the last match
// in the search order will be the source of config.
// If there's no match, the source is the model.
source := config.JujuModelConfigSource
n := len(sourceAttrs)
for i := range sourceAttrs {
if sourceAttrs[n-i-1][attr] == val {
source = sourceNames[n-i-1]
break
}
}
result[attr] = config.ConfigValue{
Value: val,
Source: source,
}
}
return result, nil
} | go | func (model *Model) modelConfigValues(modelCfg attrValues) (config.ConfigValues, error) {
resultValues := make(attrValues)
for k, v := range modelCfg {
resultValues[k] = v
}
// Read all of the current inherited config values so
// we can dynamically reflect the origin of the model config.
rspec, err := model.st.regionSpec()
if err != nil {
return nil, errors.Trace(err)
}
configSources := modelConfigSources(model.st, rspec)
sourceNames := make([]string, 0, len(configSources))
sourceAttrs := make([]attrValues, 0, len(configSources))
for _, src := range configSources {
sourceNames = append(sourceNames, src.name)
cfg, err := src.sourceFunc()
if errors.IsNotFound(err) {
continue
}
if err != nil {
return nil, errors.Annotatef(err, "reading %s settings", src.name)
}
sourceAttrs = append(sourceAttrs, cfg)
// If no modelCfg was passed in, we'll accumulate data
// for the inherited values instead.
if len(modelCfg) == 0 {
for k, v := range cfg {
resultValues[k] = v
}
}
}
// Figure out the source of each config attribute based
// on the current model values and the inherited values.
result := make(config.ConfigValues)
for attr, val := range resultValues {
// Find the source of config for which the model
// value matches. If there's a match, the last match
// in the search order will be the source of config.
// If there's no match, the source is the model.
source := config.JujuModelConfigSource
n := len(sourceAttrs)
for i := range sourceAttrs {
if sourceAttrs[n-i-1][attr] == val {
source = sourceNames[n-i-1]
break
}
}
result[attr] = config.ConfigValue{
Value: val,
Source: source,
}
}
return result, nil
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"modelConfigValues",
"(",
"modelCfg",
"attrValues",
")",
"(",
"config",
".",
"ConfigValues",
",",
"error",
")",
"{",
"resultValues",
":=",
"make",
"(",
"attrValues",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"modelCfg",
"{",
"resultValues",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"// Read all of the current inherited config values so",
"// we can dynamically reflect the origin of the model config.",
"rspec",
",",
"err",
":=",
"model",
".",
"st",
".",
"regionSpec",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"configSources",
":=",
"modelConfigSources",
"(",
"model",
".",
"st",
",",
"rspec",
")",
"\n",
"sourceNames",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"configSources",
")",
")",
"\n",
"sourceAttrs",
":=",
"make",
"(",
"[",
"]",
"attrValues",
",",
"0",
",",
"len",
"(",
"configSources",
")",
")",
"\n",
"for",
"_",
",",
"src",
":=",
"range",
"configSources",
"{",
"sourceNames",
"=",
"append",
"(",
"sourceNames",
",",
"src",
".",
"name",
")",
"\n",
"cfg",
",",
"err",
":=",
"src",
".",
"sourceFunc",
"(",
")",
"\n",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"src",
".",
"name",
")",
"\n",
"}",
"\n",
"sourceAttrs",
"=",
"append",
"(",
"sourceAttrs",
",",
"cfg",
")",
"\n\n",
"// If no modelCfg was passed in, we'll accumulate data",
"// for the inherited values instead.",
"if",
"len",
"(",
"modelCfg",
")",
"==",
"0",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"cfg",
"{",
"resultValues",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Figure out the source of each config attribute based",
"// on the current model values and the inherited values.",
"result",
":=",
"make",
"(",
"config",
".",
"ConfigValues",
")",
"\n",
"for",
"attr",
",",
"val",
":=",
"range",
"resultValues",
"{",
"// Find the source of config for which the model",
"// value matches. If there's a match, the last match",
"// in the search order will be the source of config.",
"// If there's no match, the source is the model.",
"source",
":=",
"config",
".",
"JujuModelConfigSource",
"\n",
"n",
":=",
"len",
"(",
"sourceAttrs",
")",
"\n",
"for",
"i",
":=",
"range",
"sourceAttrs",
"{",
"if",
"sourceAttrs",
"[",
"n",
"-",
"i",
"-",
"1",
"]",
"[",
"attr",
"]",
"==",
"val",
"{",
"source",
"=",
"sourceNames",
"[",
"n",
"-",
"i",
"-",
"1",
"]",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"result",
"[",
"attr",
"]",
"=",
"config",
".",
"ConfigValue",
"{",
"Value",
":",
"val",
",",
"Source",
":",
"source",
",",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // modelConfigValues returns the values and source for the supplied model config
// when combined with controller and Juju defaults. | [
"modelConfigValues",
"returns",
"the",
"values",
"and",
"source",
"for",
"the",
"supplied",
"model",
"config",
"when",
"combined",
"with",
"controller",
"and",
"Juju",
"defaults",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L95-L152 |
154,982 | juju/juju | state/modelconfig.go | UpdateModelConfigDefaultValues | func (st *State) UpdateModelConfigDefaultValues(attrs map[string]interface{}, removed []string, regionSpec *environs.CloudRegionSpec) error {
var key string
if regionSpec != nil {
if regionSpec.Region == "" {
key = cloudGlobalKey(regionSpec.Cloud)
} else {
key = regionSettingsGlobalKey(regionSpec.Cloud, regionSpec.Region)
}
} else {
// For backwards compatibility default to the model's cloud.
model, err := st.Model()
if err != nil {
return errors.Trace(err)
}
key = cloudGlobalKey(model.Cloud())
}
settings, err := readSettings(st.db(), globalSettingsC, key)
if err != nil {
if !errors.IsNotFound(err) {
return errors.Annotatef(err, "model %q", st.ModelUUID())
}
// We haven't created settings for this region yet.
_, err := createSettings(st.db(), globalSettingsC, key, attrs)
if err != nil {
return errors.Annotatef(err, "model %q", st.ModelUUID())
}
return nil
}
// TODO(axw) 2013-12-6 #1167616
// Ensure that the settings on disk have not changed
// underneath us. The settings changes are actually
// applied as a delta to what's on disk; if there has
// been a concurrent update, the change may not be what
// the user asked for.
settings.Update(attrs)
for _, r := range removed {
settings.Delete(r)
}
_, err = settings.Write()
return err
} | go | func (st *State) UpdateModelConfigDefaultValues(attrs map[string]interface{}, removed []string, regionSpec *environs.CloudRegionSpec) error {
var key string
if regionSpec != nil {
if regionSpec.Region == "" {
key = cloudGlobalKey(regionSpec.Cloud)
} else {
key = regionSettingsGlobalKey(regionSpec.Cloud, regionSpec.Region)
}
} else {
// For backwards compatibility default to the model's cloud.
model, err := st.Model()
if err != nil {
return errors.Trace(err)
}
key = cloudGlobalKey(model.Cloud())
}
settings, err := readSettings(st.db(), globalSettingsC, key)
if err != nil {
if !errors.IsNotFound(err) {
return errors.Annotatef(err, "model %q", st.ModelUUID())
}
// We haven't created settings for this region yet.
_, err := createSettings(st.db(), globalSettingsC, key, attrs)
if err != nil {
return errors.Annotatef(err, "model %q", st.ModelUUID())
}
return nil
}
// TODO(axw) 2013-12-6 #1167616
// Ensure that the settings on disk have not changed
// underneath us. The settings changes are actually
// applied as a delta to what's on disk; if there has
// been a concurrent update, the change may not be what
// the user asked for.
settings.Update(attrs)
for _, r := range removed {
settings.Delete(r)
}
_, err = settings.Write()
return err
} | [
"func",
"(",
"st",
"*",
"State",
")",
"UpdateModelConfigDefaultValues",
"(",
"attrs",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"removed",
"[",
"]",
"string",
",",
"regionSpec",
"*",
"environs",
".",
"CloudRegionSpec",
")",
"error",
"{",
"var",
"key",
"string",
"\n\n",
"if",
"regionSpec",
"!=",
"nil",
"{",
"if",
"regionSpec",
".",
"Region",
"==",
"\"",
"\"",
"{",
"key",
"=",
"cloudGlobalKey",
"(",
"regionSpec",
".",
"Cloud",
")",
"\n",
"}",
"else",
"{",
"key",
"=",
"regionSettingsGlobalKey",
"(",
"regionSpec",
".",
"Cloud",
",",
"regionSpec",
".",
"Region",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// For backwards compatibility default to the model's cloud.",
"model",
",",
"err",
":=",
"st",
".",
"Model",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"key",
"=",
"cloudGlobalKey",
"(",
"model",
".",
"Cloud",
"(",
")",
")",
"\n",
"}",
"\n",
"settings",
",",
"err",
":=",
"readSettings",
"(",
"st",
".",
"db",
"(",
")",
",",
"globalSettingsC",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"st",
".",
"ModelUUID",
"(",
")",
")",
"\n",
"}",
"\n",
"// We haven't created settings for this region yet.",
"_",
",",
"err",
":=",
"createSettings",
"(",
"st",
".",
"db",
"(",
")",
",",
"globalSettingsC",
",",
"key",
",",
"attrs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"st",
".",
"ModelUUID",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// TODO(axw) 2013-12-6 #1167616",
"// Ensure that the settings on disk have not changed",
"// underneath us. The settings changes are actually",
"// applied as a delta to what's on disk; if there has",
"// been a concurrent update, the change may not be what",
"// the user asked for.",
"settings",
".",
"Update",
"(",
"attrs",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"removed",
"{",
"settings",
".",
"Delete",
"(",
"r",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"settings",
".",
"Write",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // UpdateModelConfigDefaultValues updates the inherited settings used when creating a new model. | [
"UpdateModelConfigDefaultValues",
"updates",
"the",
"inherited",
"settings",
"used",
"when",
"creating",
"a",
"new",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L155-L197 |
154,983 | juju/juju | state/modelconfig.go | ModelConfigValues | func (model *Model) ModelConfigValues() (config.ConfigValues, error) {
cfg, err := model.ModelConfig()
if err != nil {
return nil, errors.Trace(err)
}
return model.modelConfigValues(cfg.AllAttrs())
} | go | func (model *Model) ModelConfigValues() (config.ConfigValues, error) {
cfg, err := model.ModelConfig()
if err != nil {
return nil, errors.Trace(err)
}
return model.modelConfigValues(cfg.AllAttrs())
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"ModelConfigValues",
"(",
")",
"(",
"config",
".",
"ConfigValues",
",",
"error",
")",
"{",
"cfg",
",",
"err",
":=",
"model",
".",
"ModelConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"model",
".",
"modelConfigValues",
"(",
"cfg",
".",
"AllAttrs",
"(",
")",
")",
"\n",
"}"
] | // ModelConfigValues returns the config values for the model represented
// by this state. | [
"ModelConfigValues",
"returns",
"the",
"config",
"values",
"for",
"the",
"model",
"represented",
"by",
"this",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L201-L207 |
154,984 | juju/juju | state/modelconfig.go | ModelConfigDefaultValues | func (st *State) ModelConfigDefaultValues(cloudName string) (config.ModelDefaultAttributes, error) {
cloud, err := st.Cloud(cloudName)
if err != nil {
return nil, errors.Trace(err)
}
result := make(config.ModelDefaultAttributes)
// Juju defaults
defaultAttrs, err := st.defaultInheritedConfig(cloudName)()
if err != nil {
return nil, errors.Trace(err)
}
for k, v := range defaultAttrs {
result[k] = config.AttributeDefaultValues{Default: v}
}
// Controller config
ciCfg, err := st.controllerInheritedConfig(cloudName)()
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
for k, v := range ciCfg {
if ds, ok := result[k]; ok {
ds.Controller = v
result[k] = ds
} else {
result[k] = config.AttributeDefaultValues{Controller: v}
}
}
// Region config
for _, region := range cloud.Regions {
rspec := &environs.CloudRegionSpec{Cloud: cloudName, Region: region.Name}
riCfg, err := st.regionInheritedConfig(rspec)()
if err != nil {
if errors.IsNotFound(err) {
continue
}
return nil, errors.Trace(err)
}
for k, v := range riCfg {
regCfg := config.RegionDefaultValue{Name: region.Name, Value: v}
if ds, ok := result[k]; ok {
ds.Regions = append(result[k].Regions, regCfg)
result[k] = ds
} else {
result[k] = config.AttributeDefaultValues{Regions: []config.RegionDefaultValue{regCfg}}
}
}
}
return result, nil
} | go | func (st *State) ModelConfigDefaultValues(cloudName string) (config.ModelDefaultAttributes, error) {
cloud, err := st.Cloud(cloudName)
if err != nil {
return nil, errors.Trace(err)
}
result := make(config.ModelDefaultAttributes)
// Juju defaults
defaultAttrs, err := st.defaultInheritedConfig(cloudName)()
if err != nil {
return nil, errors.Trace(err)
}
for k, v := range defaultAttrs {
result[k] = config.AttributeDefaultValues{Default: v}
}
// Controller config
ciCfg, err := st.controllerInheritedConfig(cloudName)()
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
for k, v := range ciCfg {
if ds, ok := result[k]; ok {
ds.Controller = v
result[k] = ds
} else {
result[k] = config.AttributeDefaultValues{Controller: v}
}
}
// Region config
for _, region := range cloud.Regions {
rspec := &environs.CloudRegionSpec{Cloud: cloudName, Region: region.Name}
riCfg, err := st.regionInheritedConfig(rspec)()
if err != nil {
if errors.IsNotFound(err) {
continue
}
return nil, errors.Trace(err)
}
for k, v := range riCfg {
regCfg := config.RegionDefaultValue{Name: region.Name, Value: v}
if ds, ok := result[k]; ok {
ds.Regions = append(result[k].Regions, regCfg)
result[k] = ds
} else {
result[k] = config.AttributeDefaultValues{Regions: []config.RegionDefaultValue{regCfg}}
}
}
}
return result, nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"ModelConfigDefaultValues",
"(",
"cloudName",
"string",
")",
"(",
"config",
".",
"ModelDefaultAttributes",
",",
"error",
")",
"{",
"cloud",
",",
"err",
":=",
"st",
".",
"Cloud",
"(",
"cloudName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"result",
":=",
"make",
"(",
"config",
".",
"ModelDefaultAttributes",
")",
"\n",
"// Juju defaults",
"defaultAttrs",
",",
"err",
":=",
"st",
".",
"defaultInheritedConfig",
"(",
"cloudName",
")",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"defaultAttrs",
"{",
"result",
"[",
"k",
"]",
"=",
"config",
".",
"AttributeDefaultValues",
"{",
"Default",
":",
"v",
"}",
"\n",
"}",
"\n",
"// Controller config",
"ciCfg",
",",
"err",
":=",
"st",
".",
"controllerInheritedConfig",
"(",
"cloudName",
")",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"ciCfg",
"{",
"if",
"ds",
",",
"ok",
":=",
"result",
"[",
"k",
"]",
";",
"ok",
"{",
"ds",
".",
"Controller",
"=",
"v",
"\n",
"result",
"[",
"k",
"]",
"=",
"ds",
"\n",
"}",
"else",
"{",
"result",
"[",
"k",
"]",
"=",
"config",
".",
"AttributeDefaultValues",
"{",
"Controller",
":",
"v",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// Region config",
"for",
"_",
",",
"region",
":=",
"range",
"cloud",
".",
"Regions",
"{",
"rspec",
":=",
"&",
"environs",
".",
"CloudRegionSpec",
"{",
"Cloud",
":",
"cloudName",
",",
"Region",
":",
"region",
".",
"Name",
"}",
"\n",
"riCfg",
",",
"err",
":=",
"st",
".",
"regionInheritedConfig",
"(",
"rspec",
")",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"riCfg",
"{",
"regCfg",
":=",
"config",
".",
"RegionDefaultValue",
"{",
"Name",
":",
"region",
".",
"Name",
",",
"Value",
":",
"v",
"}",
"\n",
"if",
"ds",
",",
"ok",
":=",
"result",
"[",
"k",
"]",
";",
"ok",
"{",
"ds",
".",
"Regions",
"=",
"append",
"(",
"result",
"[",
"k",
"]",
".",
"Regions",
",",
"regCfg",
")",
"\n",
"result",
"[",
"k",
"]",
"=",
"ds",
"\n",
"}",
"else",
"{",
"result",
"[",
"k",
"]",
"=",
"config",
".",
"AttributeDefaultValues",
"{",
"Regions",
":",
"[",
"]",
"config",
".",
"RegionDefaultValue",
"{",
"regCfg",
"}",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // ModelConfigDefaultValues returns the default config values to be used
// when creating a new model, and the origin of those values. | [
"ModelConfigDefaultValues",
"returns",
"the",
"default",
"config",
"values",
"to",
"be",
"used",
"when",
"creating",
"a",
"new",
"model",
"and",
"the",
"origin",
"of",
"those",
"values",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L211-L261 |
154,985 | juju/juju | state/modelconfig.go | checkControllerInheritedConfig | func checkControllerInheritedConfig(attrs attrValues) error {
disallowedCloudConfigAttrs := append(disallowedModelConfigAttrs[:], config.AgentVersionKey)
for _, attr := range disallowedCloudConfigAttrs {
if _, ok := attrs[attr]; ok {
return errors.Errorf("local cloud config cannot contain " + attr)
}
}
for attrName := range attrs {
if controller.ControllerOnlyAttribute(attrName) {
return errors.Errorf("local cloud config cannot contain controller attribute %q", attrName)
}
}
return nil
} | go | func checkControllerInheritedConfig(attrs attrValues) error {
disallowedCloudConfigAttrs := append(disallowedModelConfigAttrs[:], config.AgentVersionKey)
for _, attr := range disallowedCloudConfigAttrs {
if _, ok := attrs[attr]; ok {
return errors.Errorf("local cloud config cannot contain " + attr)
}
}
for attrName := range attrs {
if controller.ControllerOnlyAttribute(attrName) {
return errors.Errorf("local cloud config cannot contain controller attribute %q", attrName)
}
}
return nil
} | [
"func",
"checkControllerInheritedConfig",
"(",
"attrs",
"attrValues",
")",
"error",
"{",
"disallowedCloudConfigAttrs",
":=",
"append",
"(",
"disallowedModelConfigAttrs",
"[",
":",
"]",
",",
"config",
".",
"AgentVersionKey",
")",
"\n",
"for",
"_",
",",
"attr",
":=",
"range",
"disallowedCloudConfigAttrs",
"{",
"if",
"_",
",",
"ok",
":=",
"attrs",
"[",
"attr",
"]",
";",
"ok",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"attr",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"attrName",
":=",
"range",
"attrs",
"{",
"if",
"controller",
".",
"ControllerOnlyAttribute",
"(",
"attrName",
")",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"attrName",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // checkControllerInheritedConfig returns an error if the shared local cloud config is definitely invalid. | [
"checkControllerInheritedConfig",
"returns",
"an",
"error",
"if",
"the",
"shared",
"local",
"cloud",
"config",
"is",
"definitely",
"invalid",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L264-L277 |
154,986 | juju/juju | state/modelconfig.go | UpdateModelConfig | func (m *Model) UpdateModelConfig(updateAttrs map[string]interface{}, removeAttrs []string, additionalValidation ...ValidateConfigFunc) error {
if len(updateAttrs)+len(removeAttrs) == 0 {
return nil
}
st := m.State()
if len(removeAttrs) > 0 {
var removed []string
if updateAttrs == nil {
updateAttrs = make(map[string]interface{})
}
// For each removed attribute, pick up any inherited value
// and if there's one, use that.
inherited, err := st.inheritedConfigAttributes()
if err != nil {
return errors.Trace(err)
}
for _, attr := range removeAttrs {
// We we are updating an attribute, that takes
// precedence over removing.
if _, ok := updateAttrs[attr]; ok {
continue
}
if val, ok := inherited[attr]; ok {
updateAttrs[attr] = val
} else {
removed = append(removed, attr)
}
}
removeAttrs = removed
}
// TODO(axw) 2013-12-6 #1167616
// Ensure that the settings on disk have not changed
// underneath us. The settings changes are actually
// applied as a delta to what's on disk; if there has
// been a concurrent update, the change may not be what
// the user asked for.
modelSettings, err := readSettings(st.db(), settingsC, modelGlobalKey)
if err != nil {
return errors.Annotatef(err, "model %q", m.UUID())
}
oldConfig, err := m.ModelConfig()
if err != nil {
return errors.Trace(err)
}
for _, additionalValidationFunc := range additionalValidation {
err = additionalValidationFunc(updateAttrs, removeAttrs, oldConfig)
if err != nil {
return errors.Trace(err)
}
}
validCfg, err := st.buildAndValidateModelConfig(updateAttrs, removeAttrs, oldConfig)
if err != nil {
return errors.Trace(err)
}
validAttrs := validCfg.AllAttrs()
for k := range oldConfig.AllAttrs() {
if _, ok := validAttrs[k]; !ok {
modelSettings.Delete(k)
}
}
// Some values require marshalling before storage.
validAttrs = config.CoerceForStorage(validAttrs)
modelSettings.Update(validAttrs)
_, ops := modelSettings.settingsUpdateOps()
return modelSettings.write(ops)
} | go | func (m *Model) UpdateModelConfig(updateAttrs map[string]interface{}, removeAttrs []string, additionalValidation ...ValidateConfigFunc) error {
if len(updateAttrs)+len(removeAttrs) == 0 {
return nil
}
st := m.State()
if len(removeAttrs) > 0 {
var removed []string
if updateAttrs == nil {
updateAttrs = make(map[string]interface{})
}
// For each removed attribute, pick up any inherited value
// and if there's one, use that.
inherited, err := st.inheritedConfigAttributes()
if err != nil {
return errors.Trace(err)
}
for _, attr := range removeAttrs {
// We we are updating an attribute, that takes
// precedence over removing.
if _, ok := updateAttrs[attr]; ok {
continue
}
if val, ok := inherited[attr]; ok {
updateAttrs[attr] = val
} else {
removed = append(removed, attr)
}
}
removeAttrs = removed
}
// TODO(axw) 2013-12-6 #1167616
// Ensure that the settings on disk have not changed
// underneath us. The settings changes are actually
// applied as a delta to what's on disk; if there has
// been a concurrent update, the change may not be what
// the user asked for.
modelSettings, err := readSettings(st.db(), settingsC, modelGlobalKey)
if err != nil {
return errors.Annotatef(err, "model %q", m.UUID())
}
oldConfig, err := m.ModelConfig()
if err != nil {
return errors.Trace(err)
}
for _, additionalValidationFunc := range additionalValidation {
err = additionalValidationFunc(updateAttrs, removeAttrs, oldConfig)
if err != nil {
return errors.Trace(err)
}
}
validCfg, err := st.buildAndValidateModelConfig(updateAttrs, removeAttrs, oldConfig)
if err != nil {
return errors.Trace(err)
}
validAttrs := validCfg.AllAttrs()
for k := range oldConfig.AllAttrs() {
if _, ok := validAttrs[k]; !ok {
modelSettings.Delete(k)
}
}
// Some values require marshalling before storage.
validAttrs = config.CoerceForStorage(validAttrs)
modelSettings.Update(validAttrs)
_, ops := modelSettings.settingsUpdateOps()
return modelSettings.write(ops)
} | [
"func",
"(",
"m",
"*",
"Model",
")",
"UpdateModelConfig",
"(",
"updateAttrs",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"removeAttrs",
"[",
"]",
"string",
",",
"additionalValidation",
"...",
"ValidateConfigFunc",
")",
"error",
"{",
"if",
"len",
"(",
"updateAttrs",
")",
"+",
"len",
"(",
"removeAttrs",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"st",
":=",
"m",
".",
"State",
"(",
")",
"\n",
"if",
"len",
"(",
"removeAttrs",
")",
">",
"0",
"{",
"var",
"removed",
"[",
"]",
"string",
"\n",
"if",
"updateAttrs",
"==",
"nil",
"{",
"updateAttrs",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"}",
"\n",
"// For each removed attribute, pick up any inherited value",
"// and if there's one, use that.",
"inherited",
",",
"err",
":=",
"st",
".",
"inheritedConfigAttributes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"attr",
":=",
"range",
"removeAttrs",
"{",
"// We we are updating an attribute, that takes",
"// precedence over removing.",
"if",
"_",
",",
"ok",
":=",
"updateAttrs",
"[",
"attr",
"]",
";",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"val",
",",
"ok",
":=",
"inherited",
"[",
"attr",
"]",
";",
"ok",
"{",
"updateAttrs",
"[",
"attr",
"]",
"=",
"val",
"\n",
"}",
"else",
"{",
"removed",
"=",
"append",
"(",
"removed",
",",
"attr",
")",
"\n",
"}",
"\n",
"}",
"\n",
"removeAttrs",
"=",
"removed",
"\n",
"}",
"\n",
"// TODO(axw) 2013-12-6 #1167616",
"// Ensure that the settings on disk have not changed",
"// underneath us. The settings changes are actually",
"// applied as a delta to what's on disk; if there has",
"// been a concurrent update, the change may not be what",
"// the user asked for.",
"modelSettings",
",",
"err",
":=",
"readSettings",
"(",
"st",
".",
"db",
"(",
")",
",",
"settingsC",
",",
"modelGlobalKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"m",
".",
"UUID",
"(",
")",
")",
"\n",
"}",
"\n\n",
"oldConfig",
",",
"err",
":=",
"m",
".",
"ModelConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"additionalValidationFunc",
":=",
"range",
"additionalValidation",
"{",
"err",
"=",
"additionalValidationFunc",
"(",
"updateAttrs",
",",
"removeAttrs",
",",
"oldConfig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"validCfg",
",",
"err",
":=",
"st",
".",
"buildAndValidateModelConfig",
"(",
"updateAttrs",
",",
"removeAttrs",
",",
"oldConfig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"validAttrs",
":=",
"validCfg",
".",
"AllAttrs",
"(",
")",
"\n",
"for",
"k",
":=",
"range",
"oldConfig",
".",
"AllAttrs",
"(",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"validAttrs",
"[",
"k",
"]",
";",
"!",
"ok",
"{",
"modelSettings",
".",
"Delete",
"(",
"k",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Some values require marshalling before storage.",
"validAttrs",
"=",
"config",
".",
"CoerceForStorage",
"(",
"validAttrs",
")",
"\n\n",
"modelSettings",
".",
"Update",
"(",
"validAttrs",
")",
"\n",
"_",
",",
"ops",
":=",
"modelSettings",
".",
"settingsUpdateOps",
"(",
")",
"\n",
"return",
"modelSettings",
".",
"write",
"(",
"ops",
")",
"\n",
"}"
] | // UpdateModelConfig adds, updates or removes attributes in the current
// configuration of the model with the provided updateAttrs and
// removeAttrs. | [
"UpdateModelConfig",
"adds",
"updates",
"or",
"removes",
"attributes",
"in",
"the",
"current",
"configuration",
"of",
"the",
"model",
"with",
"the",
"provided",
"updateAttrs",
"and",
"removeAttrs",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L301-L371 |
154,987 | juju/juju | state/modelconfig.go | modelConfigSources | func modelConfigSources(st *State, regionSpec *environs.CloudRegionSpec) []modelConfigSource {
return []modelConfigSource{
{config.JujuDefaultSource, st.defaultInheritedConfig(regionSpec.Cloud)},
{config.JujuControllerSource, st.controllerInheritedConfig(regionSpec.Cloud)},
{config.JujuRegionSource, st.regionInheritedConfig(regionSpec)},
}
} | go | func modelConfigSources(st *State, regionSpec *environs.CloudRegionSpec) []modelConfigSource {
return []modelConfigSource{
{config.JujuDefaultSource, st.defaultInheritedConfig(regionSpec.Cloud)},
{config.JujuControllerSource, st.controllerInheritedConfig(regionSpec.Cloud)},
{config.JujuRegionSource, st.regionInheritedConfig(regionSpec)},
}
} | [
"func",
"modelConfigSources",
"(",
"st",
"*",
"State",
",",
"regionSpec",
"*",
"environs",
".",
"CloudRegionSpec",
")",
"[",
"]",
"modelConfigSource",
"{",
"return",
"[",
"]",
"modelConfigSource",
"{",
"{",
"config",
".",
"JujuDefaultSource",
",",
"st",
".",
"defaultInheritedConfig",
"(",
"regionSpec",
".",
"Cloud",
")",
"}",
",",
"{",
"config",
".",
"JujuControllerSource",
",",
"st",
".",
"controllerInheritedConfig",
"(",
"regionSpec",
".",
"Cloud",
")",
"}",
",",
"{",
"config",
".",
"JujuRegionSource",
",",
"st",
".",
"regionInheritedConfig",
"(",
"regionSpec",
")",
"}",
",",
"}",
"\n",
"}"
] | // modelConfigSources returns a slice of named model config
// sources, in hierarchical order. Starting from the first source,
// config is retrieved and each subsequent source adds to the
// overall config values, later values override earlier ones. | [
"modelConfigSources",
"returns",
"a",
"slice",
"of",
"named",
"model",
"config",
"sources",
"in",
"hierarchical",
"order",
".",
"Starting",
"from",
"the",
"first",
"source",
"config",
"is",
"retrieved",
"and",
"each",
"subsequent",
"source",
"adds",
"to",
"the",
"overall",
"config",
"values",
"later",
"values",
"override",
"earlier",
"ones",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L384-L390 |
154,988 | juju/juju | state/modelconfig.go | defaultInheritedConfig | func (st *State) defaultInheritedConfig(cloudName string) func() (attrValues, error) {
return func() (attrValues, error) {
var defaults = make(map[string]interface{})
for k, v := range config.ConfigDefaults() {
defaults[k] = v
}
providerDefaults, err := st.environsProviderConfigSchemaSource(cloudName)
if errors.IsNotImplemented(err) {
return defaults, nil
} else if err != nil {
return nil, errors.Trace(err)
}
fields := schema.FieldMap(providerDefaults.ConfigSchema(), providerDefaults.ConfigDefaults())
if coercedAttrs, err := fields.Coerce(defaults, nil); err != nil {
return nil, errors.Trace(err)
} else {
for k, v := range coercedAttrs.(map[string]interface{}) {
defaults[k] = v
}
}
return defaults, nil
}
} | go | func (st *State) defaultInheritedConfig(cloudName string) func() (attrValues, error) {
return func() (attrValues, error) {
var defaults = make(map[string]interface{})
for k, v := range config.ConfigDefaults() {
defaults[k] = v
}
providerDefaults, err := st.environsProviderConfigSchemaSource(cloudName)
if errors.IsNotImplemented(err) {
return defaults, nil
} else if err != nil {
return nil, errors.Trace(err)
}
fields := schema.FieldMap(providerDefaults.ConfigSchema(), providerDefaults.ConfigDefaults())
if coercedAttrs, err := fields.Coerce(defaults, nil); err != nil {
return nil, errors.Trace(err)
} else {
for k, v := range coercedAttrs.(map[string]interface{}) {
defaults[k] = v
}
}
return defaults, nil
}
} | [
"func",
"(",
"st",
"*",
"State",
")",
"defaultInheritedConfig",
"(",
"cloudName",
"string",
")",
"func",
"(",
")",
"(",
"attrValues",
",",
"error",
")",
"{",
"return",
"func",
"(",
")",
"(",
"attrValues",
",",
"error",
")",
"{",
"var",
"defaults",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"config",
".",
"ConfigDefaults",
"(",
")",
"{",
"defaults",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"providerDefaults",
",",
"err",
":=",
"st",
".",
"environsProviderConfigSchemaSource",
"(",
"cloudName",
")",
"\n",
"if",
"errors",
".",
"IsNotImplemented",
"(",
"err",
")",
"{",
"return",
"defaults",
",",
"nil",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"fields",
":=",
"schema",
".",
"FieldMap",
"(",
"providerDefaults",
".",
"ConfigSchema",
"(",
")",
",",
"providerDefaults",
".",
"ConfigDefaults",
"(",
")",
")",
"\n",
"if",
"coercedAttrs",
",",
"err",
":=",
"fields",
".",
"Coerce",
"(",
"defaults",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"else",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"coercedAttrs",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"defaults",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"defaults",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // defaultInheritedConfig returns config values which are defined
// as defaults in either Juju or the cloud's environ provider. | [
"defaultInheritedConfig",
"returns",
"config",
"values",
"which",
"are",
"defined",
"as",
"defaults",
"in",
"either",
"Juju",
"or",
"the",
"cloud",
"s",
"environ",
"provider",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L394-L416 |
154,989 | juju/juju | state/modelconfig.go | controllerInheritedConfig | func (st *State) controllerInheritedConfig(cloudName string) func() (attrValues, error) {
return func() (attrValues, error) {
settings, err := readSettings(st.db(), globalSettingsC, cloudGlobalKey(cloudName))
if err != nil {
return nil, errors.Annotatef(err, "controller %q", st.ControllerUUID())
}
return settings.Map(), nil
}
} | go | func (st *State) controllerInheritedConfig(cloudName string) func() (attrValues, error) {
return func() (attrValues, error) {
settings, err := readSettings(st.db(), globalSettingsC, cloudGlobalKey(cloudName))
if err != nil {
return nil, errors.Annotatef(err, "controller %q", st.ControllerUUID())
}
return settings.Map(), nil
}
} | [
"func",
"(",
"st",
"*",
"State",
")",
"controllerInheritedConfig",
"(",
"cloudName",
"string",
")",
"func",
"(",
")",
"(",
"attrValues",
",",
"error",
")",
"{",
"return",
"func",
"(",
")",
"(",
"attrValues",
",",
"error",
")",
"{",
"settings",
",",
"err",
":=",
"readSettings",
"(",
"st",
".",
"db",
"(",
")",
",",
"globalSettingsC",
",",
"cloudGlobalKey",
"(",
"cloudName",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"st",
".",
"ControllerUUID",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"settings",
".",
"Map",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // controllerInheritedConfig returns the inherited config values
// sourced from the local cloud config. | [
"controllerInheritedConfig",
"returns",
"the",
"inherited",
"config",
"values",
"sourced",
"from",
"the",
"local",
"cloud",
"config",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L420-L428 |
154,990 | juju/juju | state/modelconfig.go | regionInheritedConfig | func (st *State) regionInheritedConfig(regionSpec *environs.CloudRegionSpec) func() (attrValues, error) {
if regionSpec == nil {
return func() (attrValues, error) {
return nil, errors.New(
"no environs.CloudRegionSpec provided")
}
}
if regionSpec.Region == "" {
// It is expected that not all clouds have regions. So return not found
// if there is not a region here.
return func() (attrValues, error) {
return nil, errors.NotFoundf("region")
}
}
return func() (attrValues, error) {
settings, err := readSettings(st.db(),
globalSettingsC,
regionSettingsGlobalKey(regionSpec.Cloud, regionSpec.Region),
)
if err != nil {
return nil, errors.Annotatef(err, "region %q on %q cloud", regionSpec.Region, regionSpec.Cloud)
}
return settings.Map(), nil
}
} | go | func (st *State) regionInheritedConfig(regionSpec *environs.CloudRegionSpec) func() (attrValues, error) {
if regionSpec == nil {
return func() (attrValues, error) {
return nil, errors.New(
"no environs.CloudRegionSpec provided")
}
}
if regionSpec.Region == "" {
// It is expected that not all clouds have regions. So return not found
// if there is not a region here.
return func() (attrValues, error) {
return nil, errors.NotFoundf("region")
}
}
return func() (attrValues, error) {
settings, err := readSettings(st.db(),
globalSettingsC,
regionSettingsGlobalKey(regionSpec.Cloud, regionSpec.Region),
)
if err != nil {
return nil, errors.Annotatef(err, "region %q on %q cloud", regionSpec.Region, regionSpec.Cloud)
}
return settings.Map(), nil
}
} | [
"func",
"(",
"st",
"*",
"State",
")",
"regionInheritedConfig",
"(",
"regionSpec",
"*",
"environs",
".",
"CloudRegionSpec",
")",
"func",
"(",
")",
"(",
"attrValues",
",",
"error",
")",
"{",
"if",
"regionSpec",
"==",
"nil",
"{",
"return",
"func",
"(",
")",
"(",
"attrValues",
",",
"error",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"regionSpec",
".",
"Region",
"==",
"\"",
"\"",
"{",
"// It is expected that not all clouds have regions. So return not found",
"// if there is not a region here.",
"return",
"func",
"(",
")",
"(",
"attrValues",
",",
"error",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"func",
"(",
")",
"(",
"attrValues",
",",
"error",
")",
"{",
"settings",
",",
"err",
":=",
"readSettings",
"(",
"st",
".",
"db",
"(",
")",
",",
"globalSettingsC",
",",
"regionSettingsGlobalKey",
"(",
"regionSpec",
".",
"Cloud",
",",
"regionSpec",
".",
"Region",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"regionSpec",
".",
"Region",
",",
"regionSpec",
".",
"Cloud",
")",
"\n",
"}",
"\n",
"return",
"settings",
".",
"Map",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // regionInheritedConfig returns the configuration attributes for the region in
// the cloud where the model is targeted. | [
"regionInheritedConfig",
"returns",
"the",
"configuration",
"attributes",
"for",
"the",
"region",
"in",
"the",
"cloud",
"where",
"the",
"model",
"is",
"targeted",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L432-L456 |
154,991 | juju/juju | state/modelconfig.go | regionSpec | func (st *State) regionSpec() (*environs.CloudRegionSpec, error) {
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
rspec := &environs.CloudRegionSpec{
Cloud: model.Cloud(),
Region: model.CloudRegion(),
}
return rspec, nil
} | go | func (st *State) regionSpec() (*environs.CloudRegionSpec, error) {
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
rspec := &environs.CloudRegionSpec{
Cloud: model.Cloud(),
Region: model.CloudRegion(),
}
return rspec, nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"regionSpec",
"(",
")",
"(",
"*",
"environs",
".",
"CloudRegionSpec",
",",
"error",
")",
"{",
"model",
",",
"err",
":=",
"st",
".",
"Model",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"rspec",
":=",
"&",
"environs",
".",
"CloudRegionSpec",
"{",
"Cloud",
":",
"model",
".",
"Cloud",
"(",
")",
",",
"Region",
":",
"model",
".",
"CloudRegion",
"(",
")",
",",
"}",
"\n",
"return",
"rspec",
",",
"nil",
"\n",
"}"
] | // regionSpec returns a suitable environs.CloudRegionSpec for use in
// regionInheritedConfig. | [
"regionSpec",
"returns",
"a",
"suitable",
"environs",
".",
"CloudRegionSpec",
"for",
"use",
"in",
"regionInheritedConfig",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L460-L470 |
154,992 | juju/juju | state/modelconfig.go | composeModelConfigAttributes | func composeModelConfigAttributes(
modelAttr attrValues, configSources ...modelConfigSource,
) (attrValues, error) {
resultAttrs := make(attrValues)
// Compose default settings from all known sources.
for _, source := range configSources {
newSettings, err := source.sourceFunc()
if errors.IsNotFound(err) {
continue
}
if err != nil {
return nil, errors.Annotatef(err, "reading %s settings", source.name)
}
for name, val := range newSettings {
resultAttrs[name] = val
}
}
// Merge in model specific settings.
for attr, val := range modelAttr {
resultAttrs[attr] = val
}
return resultAttrs, nil
} | go | func composeModelConfigAttributes(
modelAttr attrValues, configSources ...modelConfigSource,
) (attrValues, error) {
resultAttrs := make(attrValues)
// Compose default settings from all known sources.
for _, source := range configSources {
newSettings, err := source.sourceFunc()
if errors.IsNotFound(err) {
continue
}
if err != nil {
return nil, errors.Annotatef(err, "reading %s settings", source.name)
}
for name, val := range newSettings {
resultAttrs[name] = val
}
}
// Merge in model specific settings.
for attr, val := range modelAttr {
resultAttrs[attr] = val
}
return resultAttrs, nil
} | [
"func",
"composeModelConfigAttributes",
"(",
"modelAttr",
"attrValues",
",",
"configSources",
"...",
"modelConfigSource",
",",
")",
"(",
"attrValues",
",",
"error",
")",
"{",
"resultAttrs",
":=",
"make",
"(",
"attrValues",
")",
"\n\n",
"// Compose default settings from all known sources.",
"for",
"_",
",",
"source",
":=",
"range",
"configSources",
"{",
"newSettings",
",",
"err",
":=",
"source",
".",
"sourceFunc",
"(",
")",
"\n",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"source",
".",
"name",
")",
"\n",
"}",
"\n",
"for",
"name",
",",
"val",
":=",
"range",
"newSettings",
"{",
"resultAttrs",
"[",
"name",
"]",
"=",
"val",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Merge in model specific settings.",
"for",
"attr",
",",
"val",
":=",
"range",
"modelAttr",
"{",
"resultAttrs",
"[",
"attr",
"]",
"=",
"val",
"\n",
"}",
"\n\n",
"return",
"resultAttrs",
",",
"nil",
"\n",
"}"
] | // composeModelConfigAttributes returns a set of model config settings composed from known
// sources of default values overridden by model specific attributes. | [
"composeModelConfigAttributes",
"returns",
"a",
"set",
"of",
"model",
"config",
"settings",
"composed",
"from",
"known",
"sources",
"of",
"default",
"values",
"overridden",
"by",
"model",
"specific",
"attributes",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L474-L499 |
154,993 | juju/juju | state/modelconfig.go | ComposeNewModelConfig | func (st *State) ComposeNewModelConfig(modelAttr map[string]interface{}, regionSpec *environs.CloudRegionSpec) (map[string]interface{}, error) {
configSources := modelConfigSources(st, regionSpec)
return composeModelConfigAttributes(modelAttr, configSources...)
} | go | func (st *State) ComposeNewModelConfig(modelAttr map[string]interface{}, regionSpec *environs.CloudRegionSpec) (map[string]interface{}, error) {
configSources := modelConfigSources(st, regionSpec)
return composeModelConfigAttributes(modelAttr, configSources...)
} | [
"func",
"(",
"st",
"*",
"State",
")",
"ComposeNewModelConfig",
"(",
"modelAttr",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"regionSpec",
"*",
"environs",
".",
"CloudRegionSpec",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"configSources",
":=",
"modelConfigSources",
"(",
"st",
",",
"regionSpec",
")",
"\n",
"return",
"composeModelConfigAttributes",
"(",
"modelAttr",
",",
"configSources",
"...",
")",
"\n",
"}"
] | // ComposeNewModelConfig returns a complete map of config attributes suitable for
// creating a new model, by combining user specified values with system defaults. | [
"ComposeNewModelConfig",
"returns",
"a",
"complete",
"map",
"of",
"config",
"attributes",
"suitable",
"for",
"creating",
"a",
"new",
"model",
"by",
"combining",
"user",
"specified",
"values",
"with",
"system",
"defaults",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelconfig.go#L503-L506 |
154,994 | juju/juju | cloudconfig/userdatacfg_win.go | ConfigureBasic | func (w *windowsConfigure) ConfigureBasic() error {
tmpDir, err := paths.TempDir(w.icfg.Series)
if err != nil {
return err
}
renderer := w.conf.ShellRenderer()
dataDir := renderer.FromSlash(w.icfg.DataDir)
baseDir := renderer.FromSlash(filepath.Dir(tmpDir))
binDir := renderer.Join(baseDir, "bin")
w.conf.AddScripts(windowsPowershellHelpers)
// The jujud user only gets created on non-nano versions for now.
if !series.IsWindowsNano(w.icfg.Series) {
w.conf.AddScripts(addJujuUser)
}
w.conf.AddScripts(
// Some providers create a baseDir before this step, but we need to
// make sure it exists before applying icacls
fmt.Sprintf(`mkdir -Force "%s"`, renderer.FromSlash(baseDir)),
fmt.Sprintf(`mkdir %s`, renderer.FromSlash(tmpDir)),
fmt.Sprintf(`mkdir "%s"`, binDir),
fmt.Sprintf(`mkdir "%s\locks"`, renderer.FromSlash(dataDir)),
`setx /m PATH "$env:PATH;C:\Juju\bin\"`,
// This is necessary for setACLs to work
`$adminsGroup = (New-Object System.Security.Principal.SecurityIdentifier("S-1-5-32-544")).Translate([System.Security.Principal.NTAccount])`,
fmt.Sprintf(`icacls "%s" /inheritance:r /grant "${adminsGroup}:(OI)(CI)(F)" /t`, renderer.FromSlash(baseDir)),
)
// TODO(bogdanteleaga): This, together with the call above, should be using setACLs, once it starts working across all windows versions properly.
// Until then, if we change permissions, both this and setACLs should be changed to do the same thing.
if !series.IsWindowsNano(w.icfg.Series) {
w.conf.AddScripts(fmt.Sprintf(`icacls "%s" /inheritance:r /grant "jujud:(OI)(CI)(F)" /t`, renderer.FromSlash(baseDir)))
}
noncefile := renderer.Join(dataDir, NonceFile)
w.conf.AddScripts(
fmt.Sprintf(`Set-Content "%s" "%s"`, noncefile, shquote(w.icfg.MachineNonce)),
)
return nil
} | go | func (w *windowsConfigure) ConfigureBasic() error {
tmpDir, err := paths.TempDir(w.icfg.Series)
if err != nil {
return err
}
renderer := w.conf.ShellRenderer()
dataDir := renderer.FromSlash(w.icfg.DataDir)
baseDir := renderer.FromSlash(filepath.Dir(tmpDir))
binDir := renderer.Join(baseDir, "bin")
w.conf.AddScripts(windowsPowershellHelpers)
// The jujud user only gets created on non-nano versions for now.
if !series.IsWindowsNano(w.icfg.Series) {
w.conf.AddScripts(addJujuUser)
}
w.conf.AddScripts(
// Some providers create a baseDir before this step, but we need to
// make sure it exists before applying icacls
fmt.Sprintf(`mkdir -Force "%s"`, renderer.FromSlash(baseDir)),
fmt.Sprintf(`mkdir %s`, renderer.FromSlash(tmpDir)),
fmt.Sprintf(`mkdir "%s"`, binDir),
fmt.Sprintf(`mkdir "%s\locks"`, renderer.FromSlash(dataDir)),
`setx /m PATH "$env:PATH;C:\Juju\bin\"`,
// This is necessary for setACLs to work
`$adminsGroup = (New-Object System.Security.Principal.SecurityIdentifier("S-1-5-32-544")).Translate([System.Security.Principal.NTAccount])`,
fmt.Sprintf(`icacls "%s" /inheritance:r /grant "${adminsGroup}:(OI)(CI)(F)" /t`, renderer.FromSlash(baseDir)),
)
// TODO(bogdanteleaga): This, together with the call above, should be using setACLs, once it starts working across all windows versions properly.
// Until then, if we change permissions, both this and setACLs should be changed to do the same thing.
if !series.IsWindowsNano(w.icfg.Series) {
w.conf.AddScripts(fmt.Sprintf(`icacls "%s" /inheritance:r /grant "jujud:(OI)(CI)(F)" /t`, renderer.FromSlash(baseDir)))
}
noncefile := renderer.Join(dataDir, NonceFile)
w.conf.AddScripts(
fmt.Sprintf(`Set-Content "%s" "%s"`, noncefile, shquote(w.icfg.MachineNonce)),
)
return nil
} | [
"func",
"(",
"w",
"*",
"windowsConfigure",
")",
"ConfigureBasic",
"(",
")",
"error",
"{",
"tmpDir",
",",
"err",
":=",
"paths",
".",
"TempDir",
"(",
"w",
".",
"icfg",
".",
"Series",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"renderer",
":=",
"w",
".",
"conf",
".",
"ShellRenderer",
"(",
")",
"\n",
"dataDir",
":=",
"renderer",
".",
"FromSlash",
"(",
"w",
".",
"icfg",
".",
"DataDir",
")",
"\n",
"baseDir",
":=",
"renderer",
".",
"FromSlash",
"(",
"filepath",
".",
"Dir",
"(",
"tmpDir",
")",
")",
"\n",
"binDir",
":=",
"renderer",
".",
"Join",
"(",
"baseDir",
",",
"\"",
"\"",
")",
"\n\n",
"w",
".",
"conf",
".",
"AddScripts",
"(",
"windowsPowershellHelpers",
")",
"\n\n",
"// The jujud user only gets created on non-nano versions for now.",
"if",
"!",
"series",
".",
"IsWindowsNano",
"(",
"w",
".",
"icfg",
".",
"Series",
")",
"{",
"w",
".",
"conf",
".",
"AddScripts",
"(",
"addJujuUser",
")",
"\n",
"}",
"\n\n",
"w",
".",
"conf",
".",
"AddScripts",
"(",
"// Some providers create a baseDir before this step, but we need to",
"// make sure it exists before applying icacls",
"fmt",
".",
"Sprintf",
"(",
"`mkdir -Force \"%s\"`",
",",
"renderer",
".",
"FromSlash",
"(",
"baseDir",
")",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"`mkdir %s`",
",",
"renderer",
".",
"FromSlash",
"(",
"tmpDir",
")",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"`mkdir \"%s\"`",
",",
"binDir",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"`mkdir \"%s\\locks\"`",
",",
"renderer",
".",
"FromSlash",
"(",
"dataDir",
")",
")",
",",
"`setx /m PATH \"$env:PATH;C:\\Juju\\bin\\\"`",
",",
"// This is necessary for setACLs to work",
"`$adminsGroup = (New-Object System.Security.Principal.SecurityIdentifier(\"S-1-5-32-544\")).Translate([System.Security.Principal.NTAccount])`",
",",
"fmt",
".",
"Sprintf",
"(",
"`icacls \"%s\" /inheritance:r /grant \"${adminsGroup}:(OI)(CI)(F)\" /t`",
",",
"renderer",
".",
"FromSlash",
"(",
"baseDir",
")",
")",
",",
")",
"\n\n",
"// TODO(bogdanteleaga): This, together with the call above, should be using setACLs, once it starts working across all windows versions properly.",
"// Until then, if we change permissions, both this and setACLs should be changed to do the same thing.",
"if",
"!",
"series",
".",
"IsWindowsNano",
"(",
"w",
".",
"icfg",
".",
"Series",
")",
"{",
"w",
".",
"conf",
".",
"AddScripts",
"(",
"fmt",
".",
"Sprintf",
"(",
"`icacls \"%s\" /inheritance:r /grant \"jujud:(OI)(CI)(F)\" /t`",
",",
"renderer",
".",
"FromSlash",
"(",
"baseDir",
")",
")",
")",
"\n",
"}",
"\n\n",
"noncefile",
":=",
"renderer",
".",
"Join",
"(",
"dataDir",
",",
"NonceFile",
")",
"\n",
"w",
".",
"conf",
".",
"AddScripts",
"(",
"fmt",
".",
"Sprintf",
"(",
"`Set-Content \"%s\" \"%s\"`",
",",
"noncefile",
",",
"shquote",
"(",
"w",
".",
"icfg",
".",
"MachineNonce",
")",
")",
",",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // ConfigureBasic implements UserdataConfig.ConfigureBasic | [
"ConfigureBasic",
"implements",
"UserdataConfig",
".",
"ConfigureBasic"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/userdatacfg_win.go#L52-L95 |
154,995 | juju/juju | cloudconfig/userdatacfg_win.go | ConfigureJuju | func (w *windowsConfigure) ConfigureJuju() error {
if err := w.icfg.VerifyConfig(); err != nil {
return errors.Trace(err)
}
if w.icfg.Controller != nil {
return errors.Errorf("controllers not supported on windows")
}
tools := w.icfg.ToolsList()[0]
toolsJson, err := json.Marshal(tools)
if err != nil {
return errors.Annotate(err, "while serializing the agent binaries")
}
renderer := w.conf.ShellRenderer()
w.conf.AddScripts(
fmt.Sprintf(`$binDir="%s"`, renderer.FromSlash(w.icfg.JujuTools())),
fmt.Sprintf(`mkdir '%s'`, renderer.FromSlash(w.icfg.LogDir)),
`mkdir $binDir`,
)
toolsDownloadCmds, err := addDownloadToolsCmds(
w.icfg.Series, w.icfg.APIInfo.CACert, w.icfg.ToolsList(),
)
if err != nil {
return errors.Trace(err)
}
w.conf.AddScripts(toolsDownloadCmds...)
w.conf.AddScripts(
`$dToolsHash = Get-FileSHA256 -FilePath "$binDir\tools.tar.gz"`,
fmt.Sprintf(`$dToolsHash > "$binDir\juju%s.sha256"`, tools.Version),
fmt.Sprintf(`if ($dToolsHash.ToLower() -ne "%s"){ Throw "Tools checksum mismatch"}`,
tools.SHA256),
fmt.Sprintf(`GUnZip-File -infile $binDir\tools.tar.gz -outdir $binDir`),
`rm "$binDir\tools.tar*"`,
fmt.Sprintf(`Set-Content $binDir\downloaded-tools.txt '%s'`, string(toolsJson)),
)
for _, cmd := range createJujuRegistryKeyCmds(w.icfg.Series) {
w.conf.AddRunCmd(cmd)
}
machineTag := names.NewMachineTag(w.icfg.MachineId)
_, err = w.addAgentInfo(machineTag)
if err != nil {
return errors.Trace(err)
}
return w.addMachineAgentToBoot()
} | go | func (w *windowsConfigure) ConfigureJuju() error {
if err := w.icfg.VerifyConfig(); err != nil {
return errors.Trace(err)
}
if w.icfg.Controller != nil {
return errors.Errorf("controllers not supported on windows")
}
tools := w.icfg.ToolsList()[0]
toolsJson, err := json.Marshal(tools)
if err != nil {
return errors.Annotate(err, "while serializing the agent binaries")
}
renderer := w.conf.ShellRenderer()
w.conf.AddScripts(
fmt.Sprintf(`$binDir="%s"`, renderer.FromSlash(w.icfg.JujuTools())),
fmt.Sprintf(`mkdir '%s'`, renderer.FromSlash(w.icfg.LogDir)),
`mkdir $binDir`,
)
toolsDownloadCmds, err := addDownloadToolsCmds(
w.icfg.Series, w.icfg.APIInfo.CACert, w.icfg.ToolsList(),
)
if err != nil {
return errors.Trace(err)
}
w.conf.AddScripts(toolsDownloadCmds...)
w.conf.AddScripts(
`$dToolsHash = Get-FileSHA256 -FilePath "$binDir\tools.tar.gz"`,
fmt.Sprintf(`$dToolsHash > "$binDir\juju%s.sha256"`, tools.Version),
fmt.Sprintf(`if ($dToolsHash.ToLower() -ne "%s"){ Throw "Tools checksum mismatch"}`,
tools.SHA256),
fmt.Sprintf(`GUnZip-File -infile $binDir\tools.tar.gz -outdir $binDir`),
`rm "$binDir\tools.tar*"`,
fmt.Sprintf(`Set-Content $binDir\downloaded-tools.txt '%s'`, string(toolsJson)),
)
for _, cmd := range createJujuRegistryKeyCmds(w.icfg.Series) {
w.conf.AddRunCmd(cmd)
}
machineTag := names.NewMachineTag(w.icfg.MachineId)
_, err = w.addAgentInfo(machineTag)
if err != nil {
return errors.Trace(err)
}
return w.addMachineAgentToBoot()
} | [
"func",
"(",
"w",
"*",
"windowsConfigure",
")",
"ConfigureJuju",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"w",
".",
"icfg",
".",
"VerifyConfig",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"w",
".",
"icfg",
".",
"Controller",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"tools",
":=",
"w",
".",
"icfg",
".",
"ToolsList",
"(",
")",
"[",
"0",
"]",
"\n",
"toolsJson",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"tools",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"renderer",
":=",
"w",
".",
"conf",
".",
"ShellRenderer",
"(",
")",
"\n",
"w",
".",
"conf",
".",
"AddScripts",
"(",
"fmt",
".",
"Sprintf",
"(",
"`$binDir=\"%s\"`",
",",
"renderer",
".",
"FromSlash",
"(",
"w",
".",
"icfg",
".",
"JujuTools",
"(",
")",
")",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"`mkdir '%s'`",
",",
"renderer",
".",
"FromSlash",
"(",
"w",
".",
"icfg",
".",
"LogDir",
")",
")",
",",
"`mkdir $binDir`",
",",
")",
"\n\n",
"toolsDownloadCmds",
",",
"err",
":=",
"addDownloadToolsCmds",
"(",
"w",
".",
"icfg",
".",
"Series",
",",
"w",
".",
"icfg",
".",
"APIInfo",
".",
"CACert",
",",
"w",
".",
"icfg",
".",
"ToolsList",
"(",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"w",
".",
"conf",
".",
"AddScripts",
"(",
"toolsDownloadCmds",
"...",
")",
"\n\n",
"w",
".",
"conf",
".",
"AddScripts",
"(",
"`$dToolsHash = Get-FileSHA256 -FilePath \"$binDir\\tools.tar.gz\"`",
",",
"fmt",
".",
"Sprintf",
"(",
"`$dToolsHash > \"$binDir\\juju%s.sha256\"`",
",",
"tools",
".",
"Version",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"`if ($dToolsHash.ToLower() -ne \"%s\"){ Throw \"Tools checksum mismatch\"}`",
",",
"tools",
".",
"SHA256",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"`GUnZip-File -infile $binDir\\tools.tar.gz -outdir $binDir`",
")",
",",
"`rm \"$binDir\\tools.tar*\"`",
",",
"fmt",
".",
"Sprintf",
"(",
"`Set-Content $binDir\\downloaded-tools.txt '%s'`",
",",
"string",
"(",
"toolsJson",
")",
")",
",",
")",
"\n\n",
"for",
"_",
",",
"cmd",
":=",
"range",
"createJujuRegistryKeyCmds",
"(",
"w",
".",
"icfg",
".",
"Series",
")",
"{",
"w",
".",
"conf",
".",
"AddRunCmd",
"(",
"cmd",
")",
"\n",
"}",
"\n\n",
"machineTag",
":=",
"names",
".",
"NewMachineTag",
"(",
"w",
".",
"icfg",
".",
"MachineId",
")",
"\n",
"_",
",",
"err",
"=",
"w",
".",
"addAgentInfo",
"(",
"machineTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"w",
".",
"addMachineAgentToBoot",
"(",
")",
"\n",
"}"
] | // ConfigureJuju implements UserdataConfig.ConfigureJuju | [
"ConfigureJuju",
"implements",
"UserdataConfig",
".",
"ConfigureJuju"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/userdatacfg_win.go#L98-L147 |
154,996 | juju/juju | cloudconfig/userdatacfg_win.go | createJujuRegistryKeyCmds | func createJujuRegistryKeyCmds(series string) []string {
aclCmds := setACLs(osenv.JujuRegistryKey, registryEntry, series)
regCmds := []string{
// Create a registry key for storing juju related information
fmt.Sprintf(`New-Item -Path '%s'`, osenv.JujuRegistryKey),
// Create a JUJU_DEV_FEATURE_FLAGS entry which may or may not be empty.
fmt.Sprintf(`New-ItemProperty -Path '%s' -Name '%s'`,
osenv.JujuRegistryKey,
osenv.JujuFeatureFlagEnvKey),
fmt.Sprintf(`Set-ItemProperty -Path '%s' -Name '%s' -Value '%s'`,
osenv.JujuRegistryKey,
osenv.JujuFeatureFlagEnvKey,
featureflag.AsEnvironmentValue()),
}
return append(regCmds[:1], append(aclCmds, regCmds[1:]...)...)
} | go | func createJujuRegistryKeyCmds(series string) []string {
aclCmds := setACLs(osenv.JujuRegistryKey, registryEntry, series)
regCmds := []string{
// Create a registry key for storing juju related information
fmt.Sprintf(`New-Item -Path '%s'`, osenv.JujuRegistryKey),
// Create a JUJU_DEV_FEATURE_FLAGS entry which may or may not be empty.
fmt.Sprintf(`New-ItemProperty -Path '%s' -Name '%s'`,
osenv.JujuRegistryKey,
osenv.JujuFeatureFlagEnvKey),
fmt.Sprintf(`Set-ItemProperty -Path '%s' -Name '%s' -Value '%s'`,
osenv.JujuRegistryKey,
osenv.JujuFeatureFlagEnvKey,
featureflag.AsEnvironmentValue()),
}
return append(regCmds[:1], append(aclCmds, regCmds[1:]...)...)
} | [
"func",
"createJujuRegistryKeyCmds",
"(",
"series",
"string",
")",
"[",
"]",
"string",
"{",
"aclCmds",
":=",
"setACLs",
"(",
"osenv",
".",
"JujuRegistryKey",
",",
"registryEntry",
",",
"series",
")",
"\n",
"regCmds",
":=",
"[",
"]",
"string",
"{",
"// Create a registry key for storing juju related information",
"fmt",
".",
"Sprintf",
"(",
"`New-Item -Path '%s'`",
",",
"osenv",
".",
"JujuRegistryKey",
")",
",",
"// Create a JUJU_DEV_FEATURE_FLAGS entry which may or may not be empty.",
"fmt",
".",
"Sprintf",
"(",
"`New-ItemProperty -Path '%s' -Name '%s'`",
",",
"osenv",
".",
"JujuRegistryKey",
",",
"osenv",
".",
"JujuFeatureFlagEnvKey",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"`Set-ItemProperty -Path '%s' -Name '%s' -Value '%s'`",
",",
"osenv",
".",
"JujuRegistryKey",
",",
"osenv",
".",
"JujuFeatureFlagEnvKey",
",",
"featureflag",
".",
"AsEnvironmentValue",
"(",
")",
")",
",",
"}",
"\n",
"return",
"append",
"(",
"regCmds",
"[",
":",
"1",
"]",
",",
"append",
"(",
"aclCmds",
",",
"regCmds",
"[",
"1",
":",
"]",
"...",
")",
"...",
")",
"\n",
"}"
] | // createJujuRegistryKeyCmds is going to create a juju registry key and set
// permissions on it such that it's only accessible to administrators | [
"createJujuRegistryKeyCmds",
"is",
"going",
"to",
"create",
"a",
"juju",
"registry",
"key",
"and",
"set",
"permissions",
"on",
"it",
"such",
"that",
"it",
"s",
"only",
"accessible",
"to",
"administrators"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/userdatacfg_win.go#L158-L175 |
154,997 | juju/juju | apiserver/common/crossmodel/state.go | GetBackend | func GetBackend(st *state.State) stateShim {
model, err := st.Model()
if err != nil {
logger.Errorf("called GetBackend on a State with no Model.")
return stateShim{}
}
return stateShim{State: st, Model: model}
} | go | func GetBackend(st *state.State) stateShim {
model, err := st.Model()
if err != nil {
logger.Errorf("called GetBackend on a State with no Model.")
return stateShim{}
}
return stateShim{State: st, Model: model}
} | [
"func",
"GetBackend",
"(",
"st",
"*",
"state",
".",
"State",
")",
"stateShim",
"{",
"model",
",",
"err",
":=",
"st",
".",
"Model",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"stateShim",
"{",
"}",
"\n",
"}",
"\n",
"return",
"stateShim",
"{",
"State",
":",
"st",
",",
"Model",
":",
"model",
"}",
"\n",
"}"
] | // GetBackend wraps a State to provide a Backend interface implementation. | [
"GetBackend",
"wraps",
"a",
"State",
"to",
"provide",
"a",
"Backend",
"interface",
"implementation",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/crossmodel/state.go#L45-L52 |
154,998 | juju/juju | provider/vsphere/environ.go | Bootstrap | func (env *environ) Bootstrap(
ctx environs.BootstrapContext,
callCtx callcontext.ProviderCallContext,
args environs.BootstrapParams,
) (result *environs.BootstrapResult, err error) {
// NOTE(axw) we must not pass a sessionEnviron to common.Bootstrap,
// as the Environ will be used during instance finalization after
// the Bootstrap method returns, and the session will be invalid.
if err := env.withSession(callCtx, func(env *sessionEnviron) error {
return env.ensureVMFolder(args.ControllerConfig.ControllerUUID(), callCtx)
}); err != nil {
return nil, errors.Trace(err)
}
return Bootstrap(ctx, env, callCtx, args)
} | go | func (env *environ) Bootstrap(
ctx environs.BootstrapContext,
callCtx callcontext.ProviderCallContext,
args environs.BootstrapParams,
) (result *environs.BootstrapResult, err error) {
// NOTE(axw) we must not pass a sessionEnviron to common.Bootstrap,
// as the Environ will be used during instance finalization after
// the Bootstrap method returns, and the session will be invalid.
if err := env.withSession(callCtx, func(env *sessionEnviron) error {
return env.ensureVMFolder(args.ControllerConfig.ControllerUUID(), callCtx)
}); err != nil {
return nil, errors.Trace(err)
}
return Bootstrap(ctx, env, callCtx, args)
} | [
"func",
"(",
"env",
"*",
"environ",
")",
"Bootstrap",
"(",
"ctx",
"environs",
".",
"BootstrapContext",
",",
"callCtx",
"callcontext",
".",
"ProviderCallContext",
",",
"args",
"environs",
".",
"BootstrapParams",
",",
")",
"(",
"result",
"*",
"environs",
".",
"BootstrapResult",
",",
"err",
"error",
")",
"{",
"// NOTE(axw) we must not pass a sessionEnviron to common.Bootstrap,",
"// as the Environ will be used during instance finalization after",
"// the Bootstrap method returns, and the session will be invalid.",
"if",
"err",
":=",
"env",
".",
"withSession",
"(",
"callCtx",
",",
"func",
"(",
"env",
"*",
"sessionEnviron",
")",
"error",
"{",
"return",
"env",
".",
"ensureVMFolder",
"(",
"args",
".",
"ControllerConfig",
".",
"ControllerUUID",
"(",
")",
",",
"callCtx",
")",
"\n",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"Bootstrap",
"(",
"ctx",
",",
"env",
",",
"callCtx",
",",
"args",
")",
"\n",
"}"
] | // Bootstrap is part of the environs.Environ interface. | [
"Bootstrap",
"is",
"part",
"of",
"the",
"environs",
".",
"Environ",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/environ.go#L130-L144 |
154,999 | juju/juju | worker/uniter/op_callbacks.go | PrepareHook | func (opc *operationCallbacks) PrepareHook(hi hook.Info) (string, error) {
name := string(hi.Kind)
switch {
case hi.Kind.IsRelation():
var err error
name, err = opc.u.relations.PrepareHook(hi)
if err != nil {
return "", err
}
case hi.Kind.IsStorage():
if err := opc.u.storage.ValidateHook(hi); err != nil {
return "", err
}
storageName, err := names.StorageName(hi.StorageId)
if err != nil {
return "", err
}
name = fmt.Sprintf("%s-%s", storageName, hi.Kind)
// TODO(axw) if the agent is not installed yet,
// set the status to "preparing storage".
case hi.Kind == hooks.ConfigChanged:
// TODO(axw)
//opc.u.f.DiscardConfigEvent()
case hi.Kind == hooks.LeaderSettingsChanged:
// TODO(axw)
//opc.u.f.DiscardLeaderSettingsEvent()
}
return name, nil
} | go | func (opc *operationCallbacks) PrepareHook(hi hook.Info) (string, error) {
name := string(hi.Kind)
switch {
case hi.Kind.IsRelation():
var err error
name, err = opc.u.relations.PrepareHook(hi)
if err != nil {
return "", err
}
case hi.Kind.IsStorage():
if err := opc.u.storage.ValidateHook(hi); err != nil {
return "", err
}
storageName, err := names.StorageName(hi.StorageId)
if err != nil {
return "", err
}
name = fmt.Sprintf("%s-%s", storageName, hi.Kind)
// TODO(axw) if the agent is not installed yet,
// set the status to "preparing storage".
case hi.Kind == hooks.ConfigChanged:
// TODO(axw)
//opc.u.f.DiscardConfigEvent()
case hi.Kind == hooks.LeaderSettingsChanged:
// TODO(axw)
//opc.u.f.DiscardLeaderSettingsEvent()
}
return name, nil
} | [
"func",
"(",
"opc",
"*",
"operationCallbacks",
")",
"PrepareHook",
"(",
"hi",
"hook",
".",
"Info",
")",
"(",
"string",
",",
"error",
")",
"{",
"name",
":=",
"string",
"(",
"hi",
".",
"Kind",
")",
"\n",
"switch",
"{",
"case",
"hi",
".",
"Kind",
".",
"IsRelation",
"(",
")",
":",
"var",
"err",
"error",
"\n",
"name",
",",
"err",
"=",
"opc",
".",
"u",
".",
"relations",
".",
"PrepareHook",
"(",
"hi",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"case",
"hi",
".",
"Kind",
".",
"IsStorage",
"(",
")",
":",
"if",
"err",
":=",
"opc",
".",
"u",
".",
"storage",
".",
"ValidateHook",
"(",
"hi",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"storageName",
",",
"err",
":=",
"names",
".",
"StorageName",
"(",
"hi",
".",
"StorageId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"name",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"storageName",
",",
"hi",
".",
"Kind",
")",
"\n",
"// TODO(axw) if the agent is not installed yet,",
"// set the status to \"preparing storage\".",
"case",
"hi",
".",
"Kind",
"==",
"hooks",
".",
"ConfigChanged",
":",
"// TODO(axw)",
"//opc.u.f.DiscardConfigEvent()",
"case",
"hi",
".",
"Kind",
"==",
"hooks",
".",
"LeaderSettingsChanged",
":",
"// TODO(axw)",
"//opc.u.f.DiscardLeaderSettingsEvent()",
"}",
"\n",
"return",
"name",
",",
"nil",
"\n",
"}"
] | // PrepareHook is part of the operation.Callbacks interface. | [
"PrepareHook",
"is",
"part",
"of",
"the",
"operation",
".",
"Callbacks",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/op_callbacks.go#L29-L57 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.