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 list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
juju/juju | state/errors.go | IsProviderIDNotUniqueError | func IsProviderIDNotUniqueError(err interface{}) bool {
if err == nil {
return false
}
// In case of a wrapped error, check the cause first.
value := err
cause := errors.Cause(err.(error))
if cause != nil {
value = cause
}
_, ok := value.(*ErrProviderIDNotUnique)
return ok
} | go | func IsProviderIDNotUniqueError(err interface{}) bool {
if err == nil {
return false
}
// In case of a wrapped error, check the cause first.
value := err
cause := errors.Cause(err.(error))
if cause != nil {
value = cause
}
_, ok := value.(*ErrProviderIDNotUnique)
return ok
} | [
"func",
"IsProviderIDNotUniqueError",
"(",
"err",
"interface",
"{",
"}",
")",
"bool",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// In case of a wrapped error, check the cause first.",
"value",
":=",
"err",
"\n",
"cause",
":=",
"err... | // IsProviderIDNotUniqueError returns if the given error or its cause is
// ErrProviderIDNotUnique. | [
"IsProviderIDNotUniqueError",
"returns",
"if",
"the",
"given",
"error",
"or",
"its",
"cause",
"is",
"ErrProviderIDNotUnique",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/errors.go#L114-L126 | train |
juju/juju | state/errors.go | IsParentDeviceHasChildrenError | func IsParentDeviceHasChildrenError(err interface{}) bool {
if err == nil {
return false
}
// In case of a wrapped error, check the cause first.
value := err
cause := errors.Cause(err.(error))
if cause != nil {
value = cause
}
_, ok := value.(*ErrParentDeviceHasChildren)
return ok
} | go | func IsParentDeviceHasChildrenError(err interface{}) bool {
if err == nil {
return false
}
// In case of a wrapped error, check the cause first.
value := err
cause := errors.Cause(err.(error))
if cause != nil {
value = cause
}
_, ok := value.(*ErrParentDeviceHasChildren)
return ok
} | [
"func",
"IsParentDeviceHasChildrenError",
"(",
"err",
"interface",
"{",
"}",
")",
"bool",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// In case of a wrapped error, check the cause first.",
"value",
":=",
"err",
"\n",
"cause",
":=",
... | // IsParentDeviceHasChildrenError returns if the given error or its cause is
// ErrParentDeviceHasChildren. | [
"IsParentDeviceHasChildrenError",
"returns",
"if",
"the",
"given",
"error",
"or",
"its",
"cause",
"is",
"ErrParentDeviceHasChildren",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/errors.go#L149-L161 | train |
juju/juju | state/errors.go | IsIncompatibleSeriesError | func IsIncompatibleSeriesError(err interface{}) bool {
if err == nil {
return false
}
// In case of a wrapped error, check the cause first.
value := err
cause := errors.Cause(err.(error))
if cause != nil {
value = cause
}
_, ok := value.(*ErrIncompatibleSeries)
return ok
} | go | func IsIncompatibleSeriesError(err interface{}) bool {
if err == nil {
return false
}
// In case of a wrapped error, check the cause first.
value := err
cause := errors.Cause(err.(error))
if cause != nil {
value = cause
}
_, ok := value.(*ErrIncompatibleSeries)
return ok
} | [
"func",
"IsIncompatibleSeriesError",
"(",
"err",
"interface",
"{",
"}",
")",
"bool",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// In case of a wrapped error, check the cause first.",
"value",
":=",
"err",
"\n",
"cause",
":=",
"erro... | // IsIncompatibleSeriesError returns if the given error or its cause is
// ErrIncompatibleSeries. | [
"IsIncompatibleSeriesError",
"returns",
"if",
"the",
"given",
"error",
"or",
"its",
"cause",
"is",
"ErrIncompatibleSeries",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/errors.go#L178-L190 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go | NewMockInstanceMutaterState | func NewMockInstanceMutaterState(ctrl *gomock.Controller) *MockInstanceMutaterState {
mock := &MockInstanceMutaterState{ctrl: ctrl}
mock.recorder = &MockInstanceMutaterStateMockRecorder{mock}
return mock
} | go | func NewMockInstanceMutaterState(ctrl *gomock.Controller) *MockInstanceMutaterState {
mock := &MockInstanceMutaterState{ctrl: ctrl}
mock.recorder = &MockInstanceMutaterStateMockRecorder{mock}
return mock
} | [
"func",
"NewMockInstanceMutaterState",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockInstanceMutaterState",
"{",
"mock",
":=",
"&",
"MockInstanceMutaterState",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockInstanceM... | // NewMockInstanceMutaterState creates a new mock instance | [
"NewMockInstanceMutaterState",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go#L28-L32 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go | ControllerTimestamp | func (m *MockInstanceMutaterState) ControllerTimestamp() (*time.Time, error) {
ret := m.ctrl.Call(m, "ControllerTimestamp")
ret0, _ := ret[0].(*time.Time)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockInstanceMutaterState) ControllerTimestamp() (*time.Time, error) {
ret := m.ctrl.Call(m, "ControllerTimestamp")
ret0, _ := ret[0].(*time.Time)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockInstanceMutaterState",
")",
"ControllerTimestamp",
"(",
")",
"(",
"*",
"time",
".",
"Time",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":... | // ControllerTimestamp mocks base method | [
"ControllerTimestamp",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go#L40-L45 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go | ControllerTimestamp | func (mr *MockInstanceMutaterStateMockRecorder) ControllerTimestamp() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ControllerTimestamp", reflect.TypeOf((*MockInstanceMutaterState)(nil).ControllerTimestamp))
} | go | func (mr *MockInstanceMutaterStateMockRecorder) ControllerTimestamp() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ControllerTimestamp", reflect.TypeOf((*MockInstanceMutaterState)(nil).ControllerTimestamp))
} | [
"func",
"(",
"mr",
"*",
"MockInstanceMutaterStateMockRecorder",
")",
"ControllerTimestamp",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
... | // ControllerTimestamp indicates an expected call of ControllerTimestamp | [
"ControllerTimestamp",
"indicates",
"an",
"expected",
"call",
"of",
"ControllerTimestamp"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go#L48-L50 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go | FindEntity | func (m *MockInstanceMutaterState) FindEntity(arg0 names_v2.Tag) (state.Entity, error) {
ret := m.ctrl.Call(m, "FindEntity", arg0)
ret0, _ := ret[0].(state.Entity)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockInstanceMutaterState) FindEntity(arg0 names_v2.Tag) (state.Entity, error) {
ret := m.ctrl.Call(m, "FindEntity", arg0)
ret0, _ := ret[0].(state.Entity)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockInstanceMutaterState",
")",
"FindEntity",
"(",
"arg0",
"names_v2",
".",
"Tag",
")",
"(",
"state",
".",
"Entity",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",... | // FindEntity mocks base method | [
"FindEntity",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go#L53-L58 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go | NewMockMachine | func NewMockMachine(ctrl *gomock.Controller) *MockMachine {
mock := &MockMachine{ctrl: ctrl}
mock.recorder = &MockMachineMockRecorder{mock}
return mock
} | go | func NewMockMachine(ctrl *gomock.Controller) *MockMachine {
mock := &MockMachine{ctrl: ctrl}
mock.recorder = &MockMachineMockRecorder{mock}
return mock
} | [
"func",
"NewMockMachine",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockMachine",
"{",
"mock",
":=",
"&",
"MockMachine",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockMachineMockRecorder",
"{",
"mock",
"}",
... | // NewMockMachine creates a new mock instance | [
"NewMockMachine",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go#L77-L81 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go | SetModificationStatus | func (m *MockMachine) SetModificationStatus(arg0 status.StatusInfo) error {
ret := m.ctrl.Call(m, "SetModificationStatus", arg0)
ret0, _ := ret[0].(error)
return ret0
} | go | func (m *MockMachine) SetModificationStatus(arg0 status.StatusInfo) error {
ret := m.ctrl.Call(m, "SetModificationStatus", arg0)
ret0, _ := ret[0].(error)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockMachine",
")",
"SetModificationStatus",
"(",
"arg0",
"status",
".",
"StatusInfo",
")",
"error",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
... | // SetModificationStatus mocks base method | [
"SetModificationStatus",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go#L101-L105 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go | NewMockLXDProfile | func NewMockLXDProfile(ctrl *gomock.Controller) *MockLXDProfile {
mock := &MockLXDProfile{ctrl: ctrl}
mock.recorder = &MockLXDProfileMockRecorder{mock}
return mock
} | go | func NewMockLXDProfile(ctrl *gomock.Controller) *MockLXDProfile {
mock := &MockLXDProfile{ctrl: ctrl}
mock.recorder = &MockLXDProfileMockRecorder{mock}
return mock
} | [
"func",
"NewMockLXDProfile",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockLXDProfile",
"{",
"mock",
":=",
"&",
"MockLXDProfile",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockLXDProfileMockRecorder",
"{",
"mock... | // NewMockLXDProfile creates a new mock instance | [
"NewMockLXDProfile",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go#L124-L128 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go | Devices | func (m *MockLXDProfile) Devices() map[string]map[string]string {
ret := m.ctrl.Call(m, "Devices")
ret0, _ := ret[0].(map[string]map[string]string)
return ret0
} | go | func (m *MockLXDProfile) Devices() map[string]map[string]string {
ret := m.ctrl.Call(m, "Devices")
ret0, _ := ret[0].(map[string]map[string]string)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockLXDProfile",
")",
"Devices",
"(",
")",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"string",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
... | // Devices mocks base method | [
"Devices",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go#L160-L164 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go | Empty | func (m *MockLXDProfile) Empty() bool {
ret := m.ctrl.Call(m, "Empty")
ret0, _ := ret[0].(bool)
return ret0
} | go | func (m *MockLXDProfile) Empty() bool {
ret := m.ctrl.Call(m, "Empty")
ret0, _ := ret[0].(bool)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockLXDProfile",
")",
"Empty",
"(",
")",
"bool",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"bool",
")",
"\n",
"retu... | // Empty mocks base method | [
"Empty",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go#L172-L176 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go | ValidateConfigDevices | func (m *MockLXDProfile) ValidateConfigDevices() error {
ret := m.ctrl.Call(m, "ValidateConfigDevices")
ret0, _ := ret[0].(error)
return ret0
} | go | func (m *MockLXDProfile) ValidateConfigDevices() error {
ret := m.ctrl.Call(m, "ValidateConfigDevices")
ret0, _ := ret[0].(error)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockLXDProfile",
")",
"ValidateConfigDevices",
"(",
")",
"error",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"error",
")... | // ValidateConfigDevices mocks base method | [
"ValidateConfigDevices",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/instancemutater_mock.go#L184-L188 | train |
juju/juju | worker/retrystrategy/worker.go | NewRetryStrategyWorker | func NewRetryStrategyWorker(config WorkerConfig) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
w, err := watcher.NewNotifyWorker(watcher.NotifyConfig{
Handler: retryStrategyHandler{config},
})
if err != nil {
return nil, errors.Trace(err)
}
return &RetryStrategyWorker{w, config.RetryStrategy}, nil
} | go | func NewRetryStrategyWorker(config WorkerConfig) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
w, err := watcher.NewNotifyWorker(watcher.NotifyConfig{
Handler: retryStrategyHandler{config},
})
if err != nil {
return nil, errors.Trace(err)
}
return &RetryStrategyWorker{w, config.RetryStrategy}, nil
} | [
"func",
"NewRetryStrategyWorker",
"(",
"config",
"WorkerConfig",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"if",
"err",
":=",
"config",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trac... | // NewRetryStrategyWorker returns a worker.Worker that returns the current
// retry strategy and bounces when it changes. | [
"NewRetryStrategyWorker",
"returns",
"a",
"worker",
".",
"Worker",
"that",
"returns",
"the",
"current",
"retry",
"strategy",
"and",
"bounces",
"when",
"it",
"changes",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/retrystrategy/worker.go#L53-L64 | train |
juju/juju | worker/retrystrategy/worker.go | SetUp | func (h retryStrategyHandler) SetUp() (watcher.NotifyWatcher, error) {
return h.config.Facade.WatchRetryStrategy(h.config.AgentTag)
} | go | func (h retryStrategyHandler) SetUp() (watcher.NotifyWatcher, error) {
return h.config.Facade.WatchRetryStrategy(h.config.AgentTag)
} | [
"func",
"(",
"h",
"retryStrategyHandler",
")",
"SetUp",
"(",
")",
"(",
"watcher",
".",
"NotifyWatcher",
",",
"error",
")",
"{",
"return",
"h",
".",
"config",
".",
"Facade",
".",
"WatchRetryStrategy",
"(",
"h",
".",
"config",
".",
"AgentTag",
")",
"\n",
... | // SetUp is part of the watcher.NotifyHandler interface. | [
"SetUp",
"is",
"part",
"of",
"the",
"watcher",
".",
"NotifyHandler",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/retrystrategy/worker.go#L77-L79 | train |
juju/juju | worker/retrystrategy/worker.go | Handle | func (h retryStrategyHandler) Handle(_ <-chan struct{}) error {
newRetryStrategy, err := h.config.Facade.RetryStrategy(h.config.AgentTag)
if err != nil {
return errors.Trace(err)
}
if newRetryStrategy != h.config.RetryStrategy {
return errors.Errorf("bouncing retrystrategy worker to get new values")
}
return nil
} | go | func (h retryStrategyHandler) Handle(_ <-chan struct{}) error {
newRetryStrategy, err := h.config.Facade.RetryStrategy(h.config.AgentTag)
if err != nil {
return errors.Trace(err)
}
if newRetryStrategy != h.config.RetryStrategy {
return errors.Errorf("bouncing retrystrategy worker to get new values")
}
return nil
} | [
"func",
"(",
"h",
"retryStrategyHandler",
")",
"Handle",
"(",
"_",
"<-",
"chan",
"struct",
"{",
"}",
")",
"error",
"{",
"newRetryStrategy",
",",
"err",
":=",
"h",
".",
"config",
".",
"Facade",
".",
"RetryStrategy",
"(",
"h",
".",
"config",
".",
"AgentT... | // Handle is part of the watcher.NotifyHandler interface.
// Whenever a valid change is encountered the worker bounces,
// making the dependents bounce and get the new value | [
"Handle",
"is",
"part",
"of",
"the",
"watcher",
".",
"NotifyHandler",
"interface",
".",
"Whenever",
"a",
"valid",
"change",
"is",
"encountered",
"the",
"worker",
"bounces",
"making",
"the",
"dependents",
"bounce",
"and",
"get",
"the",
"new",
"value"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/retrystrategy/worker.go#L84-L93 | train |
juju/juju | cmd/juju/controller/kill.go | NewKillCommand | func NewKillCommand() modelcmd.Command {
cmd := killCommand{clock: clock.WallClock}
cmd.environsDestroy = environs.Destroy
return wrapKillCommand(&cmd)
} | go | func NewKillCommand() modelcmd.Command {
cmd := killCommand{clock: clock.WallClock}
cmd.environsDestroy = environs.Destroy
return wrapKillCommand(&cmd)
} | [
"func",
"NewKillCommand",
"(",
")",
"modelcmd",
".",
"Command",
"{",
"cmd",
":=",
"killCommand",
"{",
"clock",
":",
"clock",
".",
"WallClock",
"}",
"\n",
"cmd",
".",
"environsDestroy",
"=",
"environs",
".",
"Destroy",
"\n",
"return",
"wrapKillCommand",
"(",
... | // NewKillCommand returns a command to kill a controller. Killing is a
// forceful destroy. | [
"NewKillCommand",
"returns",
"a",
"command",
"to",
"kill",
"a",
"controller",
".",
"Killing",
"is",
"a",
"forceful",
"destroy",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/kill.go#L47-L51 | train |
juju/juju | cmd/juju/controller/kill.go | wrapKillCommand | func wrapKillCommand(kill *killCommand) modelcmd.Command {
return modelcmd.WrapController(
kill,
modelcmd.WrapControllerSkipControllerFlags,
modelcmd.WrapControllerSkipDefaultController,
)
} | go | func wrapKillCommand(kill *killCommand) modelcmd.Command {
return modelcmd.WrapController(
kill,
modelcmd.WrapControllerSkipControllerFlags,
modelcmd.WrapControllerSkipDefaultController,
)
} | [
"func",
"wrapKillCommand",
"(",
"kill",
"*",
"killCommand",
")",
"modelcmd",
".",
"Command",
"{",
"return",
"modelcmd",
".",
"WrapController",
"(",
"kill",
",",
"modelcmd",
".",
"WrapControllerSkipControllerFlags",
",",
"modelcmd",
".",
"WrapControllerSkipDefaultContr... | // wrapKillCommand provides the common wrapping used by tests and
// the default NewKillCommand above. | [
"wrapKillCommand",
"provides",
"the",
"common",
"wrapping",
"used",
"by",
"tests",
"and",
"the",
"default",
"NewKillCommand",
"above",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/kill.go#L55-L61 | train |
juju/juju | cmd/juju/controller/kill.go | DirectDestroyRemaining | func (c *killCommand) DirectDestroyRemaining(ctx *cmd.Context, api destroyControllerAPI) {
hasErrors := false
hostedConfig, err := api.HostedModelConfigs()
if err != nil {
hasErrors = true
logger.Errorf("unable to retrieve hosted model config: %v", err)
}
ctrlUUID := ""
// try to get controller UUID or just ignore.
if ctrlCfg, err := api.ControllerConfig(); err == nil {
ctrlUUID = ctrlCfg.ControllerUUID()
} else {
logger.Warningf("getting controller config from API: %v", err)
}
for _, model := range hostedConfig {
if model.Error != nil {
// We can only display model name here since
// the error coming from api can be anything
// including the parsing of the model owner tag.
// Only model name is guaranteed to be set in the result
// when an error is returned.
hasErrors = true
logger.Errorf("could not kill %s directly: %v", model.Name, model.Error)
continue
}
ctx.Infof("Killing %s/%s directly", model.Owner.Id(), model.Name)
cfg, err := config.New(config.NoDefaults, model.Config)
if err != nil {
logger.Errorf(err.Error())
hasErrors = true
continue
}
p, err := environs.Provider(model.CloudSpec.Type)
if err != nil {
logger.Errorf(err.Error())
hasErrors = true
continue
}
// TODO(caas) - only cloud providers support Destroy()
if cloudProvider, ok := p.(environs.CloudEnvironProvider); ok {
env, err := environs.Open(cloudProvider, environs.OpenParams{
ControllerUUID: ctrlUUID,
Cloud: model.CloudSpec,
Config: cfg,
})
if err != nil {
logger.Errorf(err.Error())
hasErrors = true
continue
}
cloudCallCtx := cloudCallContext(c.credentialAPIFunctionForModel(model.Name))
if err := env.Destroy(cloudCallCtx); err != nil {
logger.Errorf(err.Error())
hasErrors = true
continue
}
}
ctx.Infof(" done")
}
if hasErrors {
logger.Errorf("there were problems destroying some models, manual intervention may be necessary to ensure resources are released")
} else {
ctx.Infof("All hosted models destroyed, cleaning up controller machines")
}
} | go | func (c *killCommand) DirectDestroyRemaining(ctx *cmd.Context, api destroyControllerAPI) {
hasErrors := false
hostedConfig, err := api.HostedModelConfigs()
if err != nil {
hasErrors = true
logger.Errorf("unable to retrieve hosted model config: %v", err)
}
ctrlUUID := ""
// try to get controller UUID or just ignore.
if ctrlCfg, err := api.ControllerConfig(); err == nil {
ctrlUUID = ctrlCfg.ControllerUUID()
} else {
logger.Warningf("getting controller config from API: %v", err)
}
for _, model := range hostedConfig {
if model.Error != nil {
// We can only display model name here since
// the error coming from api can be anything
// including the parsing of the model owner tag.
// Only model name is guaranteed to be set in the result
// when an error is returned.
hasErrors = true
logger.Errorf("could not kill %s directly: %v", model.Name, model.Error)
continue
}
ctx.Infof("Killing %s/%s directly", model.Owner.Id(), model.Name)
cfg, err := config.New(config.NoDefaults, model.Config)
if err != nil {
logger.Errorf(err.Error())
hasErrors = true
continue
}
p, err := environs.Provider(model.CloudSpec.Type)
if err != nil {
logger.Errorf(err.Error())
hasErrors = true
continue
}
// TODO(caas) - only cloud providers support Destroy()
if cloudProvider, ok := p.(environs.CloudEnvironProvider); ok {
env, err := environs.Open(cloudProvider, environs.OpenParams{
ControllerUUID: ctrlUUID,
Cloud: model.CloudSpec,
Config: cfg,
})
if err != nil {
logger.Errorf(err.Error())
hasErrors = true
continue
}
cloudCallCtx := cloudCallContext(c.credentialAPIFunctionForModel(model.Name))
if err := env.Destroy(cloudCallCtx); err != nil {
logger.Errorf(err.Error())
hasErrors = true
continue
}
}
ctx.Infof(" done")
}
if hasErrors {
logger.Errorf("there were problems destroying some models, manual intervention may be necessary to ensure resources are released")
} else {
ctx.Infof("All hosted models destroyed, cleaning up controller machines")
}
} | [
"func",
"(",
"c",
"*",
"killCommand",
")",
"DirectDestroyRemaining",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
",",
"api",
"destroyControllerAPI",
")",
"{",
"hasErrors",
":=",
"false",
"\n",
"hostedConfig",
",",
"err",
":=",
"api",
".",
"HostedModelConfigs",
"... | // DirectDestroyRemaining will attempt to directly destroy any remaining
// models that have machines left. | [
"DirectDestroyRemaining",
"will",
"attempt",
"to",
"directly",
"destroy",
"any",
"remaining",
"models",
"that",
"have",
"machines",
"left",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/kill.go#L180-L244 | train |
juju/juju | cmd/juju/controller/kill.go | WaitForModels | func (c *killCommand) WaitForModels(ctx *cmd.Context, api destroyControllerAPI, uuid string) error {
thirtySeconds := (time.Second * 30)
updateStatus := newTimedStatusUpdater(ctx, api, uuid, c.clock)
envStatus := updateStatus(0)
lastStatus := envStatus.controller
lastChange := c.clock.Now().Truncate(time.Second)
deadline := lastChange.Add(c.timeout)
// Check for both undead models and live machines, as machines may be
// in the controller model.
for ; hasUnreclaimedResources(envStatus) && (deadline.After(c.clock.Now())); envStatus = updateStatus(5 * time.Second) {
now := c.clock.Now().Truncate(time.Second)
if envStatus.controller != lastStatus {
lastStatus = envStatus.controller
lastChange = now
deadline = lastChange.Add(c.timeout)
}
timeSinceLastChange := now.Sub(lastChange)
timeUntilDestruction := deadline.Sub(now)
warning := ""
// We want to show the warning if it has been more than 30 seconds since
// the last change, or we are within 30 seconds of our timeout.
if timeSinceLastChange > thirtySeconds || timeUntilDestruction < thirtySeconds {
warning = fmt.Sprintf(", will kill machines directly in %s", timeUntilDestruction)
}
ctx.Infof("%s%s", fmtCtrStatus(envStatus.controller), warning)
for _, modelStatus := range envStatus.models {
ctx.Verbosef(fmtModelStatus(modelStatus))
}
}
if hasUnreclaimedResources(envStatus) {
return errors.New("timed out")
} else {
ctx.Infof("All hosted models reclaimed, cleaning up controller machines")
}
return nil
} | go | func (c *killCommand) WaitForModels(ctx *cmd.Context, api destroyControllerAPI, uuid string) error {
thirtySeconds := (time.Second * 30)
updateStatus := newTimedStatusUpdater(ctx, api, uuid, c.clock)
envStatus := updateStatus(0)
lastStatus := envStatus.controller
lastChange := c.clock.Now().Truncate(time.Second)
deadline := lastChange.Add(c.timeout)
// Check for both undead models and live machines, as machines may be
// in the controller model.
for ; hasUnreclaimedResources(envStatus) && (deadline.After(c.clock.Now())); envStatus = updateStatus(5 * time.Second) {
now := c.clock.Now().Truncate(time.Second)
if envStatus.controller != lastStatus {
lastStatus = envStatus.controller
lastChange = now
deadline = lastChange.Add(c.timeout)
}
timeSinceLastChange := now.Sub(lastChange)
timeUntilDestruction := deadline.Sub(now)
warning := ""
// We want to show the warning if it has been more than 30 seconds since
// the last change, or we are within 30 seconds of our timeout.
if timeSinceLastChange > thirtySeconds || timeUntilDestruction < thirtySeconds {
warning = fmt.Sprintf(", will kill machines directly in %s", timeUntilDestruction)
}
ctx.Infof("%s%s", fmtCtrStatus(envStatus.controller), warning)
for _, modelStatus := range envStatus.models {
ctx.Verbosef(fmtModelStatus(modelStatus))
}
}
if hasUnreclaimedResources(envStatus) {
return errors.New("timed out")
} else {
ctx.Infof("All hosted models reclaimed, cleaning up controller machines")
}
return nil
} | [
"func",
"(",
"c",
"*",
"killCommand",
")",
"WaitForModels",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
",",
"api",
"destroyControllerAPI",
",",
"uuid",
"string",
")",
"error",
"{",
"thirtySeconds",
":=",
"(",
"time",
".",
"Second",
"*",
"30",
")",
"\n",
"... | // WaitForModels will wait for the models to bring themselves down nicely.
// It will return the UUIDs of any models that need to be removed forceably. | [
"WaitForModels",
"will",
"wait",
"for",
"the",
"models",
"to",
"bring",
"themselves",
"down",
"nicely",
".",
"It",
"will",
"return",
"the",
"UUIDs",
"of",
"any",
"models",
"that",
"need",
"to",
"be",
"removed",
"forceably",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/kill.go#L261-L297 | train |
juju/juju | resource/context/internal/context.go | ContextDownload | func ContextDownload(deps ContextDownloadDeps) (path string, err error) {
// TODO(katco): Potential race-condition: two commands running at
// once. Solve via collision using os.Mkdir() with a uniform
// temp dir name (e.g. "<datadir>/.<res name>.download")?
resDirSpec := deps.NewContextDirectorySpec()
remote, err := deps.OpenResource()
if err != nil {
return "", errors.Trace(err)
}
defer deps.CloseAndLog(remote, "remote resource")
path = resDirSpec.Resolve(remote.Info().Path)
isUpToDate, err := resDirSpec.IsUpToDate(remote.Content())
if err != nil {
return "", errors.Trace(err)
}
if isUpToDate {
// We're up to date already!
return path, nil
}
if err := deps.Download(resDirSpec, remote); err != nil {
return "", errors.Trace(err)
}
return path, nil
} | go | func ContextDownload(deps ContextDownloadDeps) (path string, err error) {
// TODO(katco): Potential race-condition: two commands running at
// once. Solve via collision using os.Mkdir() with a uniform
// temp dir name (e.g. "<datadir>/.<res name>.download")?
resDirSpec := deps.NewContextDirectorySpec()
remote, err := deps.OpenResource()
if err != nil {
return "", errors.Trace(err)
}
defer deps.CloseAndLog(remote, "remote resource")
path = resDirSpec.Resolve(remote.Info().Path)
isUpToDate, err := resDirSpec.IsUpToDate(remote.Content())
if err != nil {
return "", errors.Trace(err)
}
if isUpToDate {
// We're up to date already!
return path, nil
}
if err := deps.Download(resDirSpec, remote); err != nil {
return "", errors.Trace(err)
}
return path, nil
} | [
"func",
"ContextDownload",
"(",
"deps",
"ContextDownloadDeps",
")",
"(",
"path",
"string",
",",
"err",
"error",
")",
"{",
"// TODO(katco): Potential race-condition: two commands running at",
"// once. Solve via collision using os.Mkdir() with a uniform",
"// temp dir name (e.g. \"<da... | // ContextDownload downloads the named resource and returns the path
// to which it was downloaded. If the resource does not exist or has
// not been uploaded yet then errors.NotFound is returned.
//
// Note that the downloaded file is checked for correctness. | [
"ContextDownload",
"downloads",
"the",
"named",
"resource",
"and",
"returns",
"the",
"path",
"to",
"which",
"it",
"was",
"downloaded",
".",
"If",
"the",
"resource",
"does",
"not",
"exist",
"or",
"has",
"not",
"been",
"uploaded",
"yet",
"then",
"errors",
".",... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/context.go#L17-L45 | train |
juju/juju | resource/context/internal/context.go | NewContextDirectorySpec | func NewContextDirectorySpec(dataDir, name string, deps DirectorySpecDeps) ContextDirectorySpec {
return &contextDirectorySpec{
DirectorySpec: NewDirectorySpec(dataDir, name, deps),
}
} | go | func NewContextDirectorySpec(dataDir, name string, deps DirectorySpecDeps) ContextDirectorySpec {
return &contextDirectorySpec{
DirectorySpec: NewDirectorySpec(dataDir, name, deps),
}
} | [
"func",
"NewContextDirectorySpec",
"(",
"dataDir",
",",
"name",
"string",
",",
"deps",
"DirectorySpecDeps",
")",
"ContextDirectorySpec",
"{",
"return",
"&",
"contextDirectorySpec",
"{",
"DirectorySpec",
":",
"NewDirectorySpec",
"(",
"dataDir",
",",
"name",
",",
"dep... | // NewContextDirectorySpec returns a new directory spec for the context. | [
"NewContextDirectorySpec",
"returns",
"a",
"new",
"directory",
"spec",
"for",
"the",
"context",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/context.go#L80-L84 | train |
juju/juju | api/instancemutater/mocks/caller_mock.go | NewMockAPICaller | func NewMockAPICaller(ctrl *gomock.Controller) *MockAPICaller {
mock := &MockAPICaller{ctrl: ctrl}
mock.recorder = &MockAPICallerMockRecorder{mock}
return mock
} | go | func NewMockAPICaller(ctrl *gomock.Controller) *MockAPICaller {
mock := &MockAPICaller{ctrl: ctrl}
mock.recorder = &MockAPICallerMockRecorder{mock}
return mock
} | [
"func",
"NewMockAPICaller",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockAPICaller",
"{",
"mock",
":=",
"&",
"MockAPICaller",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockAPICallerMockRecorder",
"{",
"mock",
... | // NewMockAPICaller creates a new mock instance | [
"NewMockAPICaller",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L30-L34 | train |
juju/juju | api/instancemutater/mocks/caller_mock.go | BakeryClient | func (m *MockAPICaller) BakeryClient() *httpbakery.Client {
ret := m.ctrl.Call(m, "BakeryClient")
ret0, _ := ret[0].(*httpbakery.Client)
return ret0
} | go | func (m *MockAPICaller) BakeryClient() *httpbakery.Client {
ret := m.ctrl.Call(m, "BakeryClient")
ret0, _ := ret[0].(*httpbakery.Client)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockAPICaller",
")",
"BakeryClient",
"(",
")",
"*",
"httpbakery",
".",
"Client",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
... | // BakeryClient mocks base method | [
"BakeryClient",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L54-L58 | train |
juju/juju | api/instancemutater/mocks/caller_mock.go | BestFacadeVersion | func (mr *MockAPICallerMockRecorder) BestFacadeVersion(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BestFacadeVersion", reflect.TypeOf((*MockAPICaller)(nil).BestFacadeVersion), arg0)
} | go | func (mr *MockAPICallerMockRecorder) BestFacadeVersion(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BestFacadeVersion", reflect.TypeOf((*MockAPICaller)(nil).BestFacadeVersion), arg0)
} | [
"func",
"(",
"mr",
"*",
"MockAPICallerMockRecorder",
")",
"BestFacadeVersion",
"(",
"arg0",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",... | // BestFacadeVersion indicates an expected call of BestFacadeVersion | [
"BestFacadeVersion",
"indicates",
"an",
"expected",
"call",
"of",
"BestFacadeVersion"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L73-L75 | train |
juju/juju | api/instancemutater/mocks/caller_mock.go | ConnectControllerStream | func (m *MockAPICaller) ConnectControllerStream(arg0 string, arg1 url.Values, arg2 http.Header) (base.Stream, error) {
ret := m.ctrl.Call(m, "ConnectControllerStream", arg0, arg1, arg2)
ret0, _ := ret[0].(base.Stream)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockAPICaller) ConnectControllerStream(arg0 string, arg1 url.Values, arg2 http.Header) (base.Stream, error) {
ret := m.ctrl.Call(m, "ConnectControllerStream", arg0, arg1, arg2)
ret0, _ := ret[0].(base.Stream)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockAPICaller",
")",
"ConnectControllerStream",
"(",
"arg0",
"string",
",",
"arg1",
"url",
".",
"Values",
",",
"arg2",
"http",
".",
"Header",
")",
"(",
"base",
".",
"Stream",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctr... | // ConnectControllerStream mocks base method | [
"ConnectControllerStream",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L78-L83 | train |
juju/juju | api/instancemutater/mocks/caller_mock.go | ConnectStream | func (m *MockAPICaller) ConnectStream(arg0 string, arg1 url.Values) (base.Stream, error) {
ret := m.ctrl.Call(m, "ConnectStream", arg0, arg1)
ret0, _ := ret[0].(base.Stream)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockAPICaller) ConnectStream(arg0 string, arg1 url.Values) (base.Stream, error) {
ret := m.ctrl.Call(m, "ConnectStream", arg0, arg1)
ret0, _ := ret[0].(base.Stream)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockAPICaller",
")",
"ConnectStream",
"(",
"arg0",
"string",
",",
"arg1",
"url",
".",
"Values",
")",
"(",
"base",
".",
"Stream",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\""... | // ConnectStream mocks base method | [
"ConnectStream",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L91-L96 | train |
juju/juju | api/instancemutater/mocks/caller_mock.go | HTTPClient | func (m *MockAPICaller) HTTPClient() (*httprequest.Client, error) {
ret := m.ctrl.Call(m, "HTTPClient")
ret0, _ := ret[0].(*httprequest.Client)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockAPICaller) HTTPClient() (*httprequest.Client, error) {
ret := m.ctrl.Call(m, "HTTPClient")
ret0, _ := ret[0].(*httprequest.Client)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockAPICaller",
")",
"HTTPClient",
"(",
")",
"(",
"*",
"httprequest",
".",
"Client",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret"... | // HTTPClient mocks base method | [
"HTTPClient",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L104-L109 | train |
juju/juju | api/instancemutater/mocks/caller_mock.go | NewMockFacadeCaller | func NewMockFacadeCaller(ctrl *gomock.Controller) *MockFacadeCaller {
mock := &MockFacadeCaller{ctrl: ctrl}
mock.recorder = &MockFacadeCallerMockRecorder{mock}
return mock
} | go | func NewMockFacadeCaller(ctrl *gomock.Controller) *MockFacadeCaller {
mock := &MockFacadeCaller{ctrl: ctrl}
mock.recorder = &MockFacadeCallerMockRecorder{mock}
return mock
} | [
"func",
"NewMockFacadeCaller",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockFacadeCaller",
"{",
"mock",
":=",
"&",
"MockFacadeCaller",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockFacadeCallerMockRecorder",
"{",... | // NewMockFacadeCaller creates a new mock instance | [
"NewMockFacadeCaller",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L141-L145 | train |
juju/juju | api/instancemutater/mocks/caller_mock.go | FacadeCall | func (m *MockFacadeCaller) FacadeCall(arg0 string, arg1, arg2 interface{}) error {
ret := m.ctrl.Call(m, "FacadeCall", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
} | go | func (m *MockFacadeCaller) FacadeCall(arg0 string, arg1, arg2 interface{}) error {
ret := m.ctrl.Call(m, "FacadeCall", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockFacadeCaller",
")",
"FacadeCall",
"(",
"arg0",
"string",
",",
"arg1",
",",
"arg2",
"interface",
"{",
"}",
")",
"error",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
",",
"arg... | // FacadeCall mocks base method | [
"FacadeCall",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L165-L169 | train |
juju/juju | api/instancemutater/mocks/caller_mock.go | FacadeCall | func (mr *MockFacadeCallerMockRecorder) FacadeCall(arg0, arg1, arg2 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FacadeCall", reflect.TypeOf((*MockFacadeCaller)(nil).FacadeCall), arg0, arg1, arg2)
} | go | func (mr *MockFacadeCallerMockRecorder) FacadeCall(arg0, arg1, arg2 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FacadeCall", reflect.TypeOf((*MockFacadeCaller)(nil).FacadeCall), arg0, arg1, arg2)
} | [
"func",
"(",
"mr",
"*",
"MockFacadeCallerMockRecorder",
")",
"FacadeCall",
"(",
"arg0",
",",
"arg1",
",",
"arg2",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
... | // FacadeCall indicates an expected call of FacadeCall | [
"FacadeCall",
"indicates",
"an",
"expected",
"call",
"of",
"FacadeCall"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L172-L174 | train |
juju/juju | api/instancemutater/mocks/caller_mock.go | RawAPICaller | func (m *MockFacadeCaller) RawAPICaller() base.APICaller {
ret := m.ctrl.Call(m, "RawAPICaller")
ret0, _ := ret[0].(base.APICaller)
return ret0
} | go | func (m *MockFacadeCaller) RawAPICaller() base.APICaller {
ret := m.ctrl.Call(m, "RawAPICaller")
ret0, _ := ret[0].(base.APICaller)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockFacadeCaller",
")",
"RawAPICaller",
"(",
")",
"base",
".",
"APICaller",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
... | // RawAPICaller mocks base method | [
"RawAPICaller",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L189-L193 | train |
juju/juju | caas/kubernetes/provider/mocks/restclient_mock.go | NewMockRestClientInterface | func NewMockRestClientInterface(ctrl *gomock.Controller) *MockRestClientInterface {
mock := &MockRestClientInterface{ctrl: ctrl}
mock.recorder = &MockRestClientInterfaceMockRecorder{mock}
return mock
} | go | func NewMockRestClientInterface(ctrl *gomock.Controller) *MockRestClientInterface {
mock := &MockRestClientInterface{ctrl: ctrl}
mock.recorder = &MockRestClientInterfaceMockRecorder{mock}
return mock
} | [
"func",
"NewMockRestClientInterface",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockRestClientInterface",
"{",
"mock",
":=",
"&",
"MockRestClientInterface",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockRestClientIn... | // NewMockRestClientInterface creates a new mock instance | [
"NewMockRestClientInterface",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/restclient_mock.go#L29-L33 | train |
juju/juju | caas/kubernetes/provider/mocks/restclient_mock.go | APIVersion | func (m *MockRestClientInterface) APIVersion() schema.GroupVersion {
ret := m.ctrl.Call(m, "APIVersion")
ret0, _ := ret[0].(schema.GroupVersion)
return ret0
} | go | func (m *MockRestClientInterface) APIVersion() schema.GroupVersion {
ret := m.ctrl.Call(m, "APIVersion")
ret0, _ := ret[0].(schema.GroupVersion)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockRestClientInterface",
")",
"APIVersion",
"(",
")",
"schema",
".",
"GroupVersion",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
"."... | // APIVersion mocks base method | [
"APIVersion",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/restclient_mock.go#L41-L45 | train |
juju/juju | caas/kubernetes/provider/mocks/restclient_mock.go | APIVersion | func (mr *MockRestClientInterfaceMockRecorder) APIVersion() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "APIVersion", reflect.TypeOf((*MockRestClientInterface)(nil).APIVersion))
} | go | func (mr *MockRestClientInterfaceMockRecorder) APIVersion() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "APIVersion", reflect.TypeOf((*MockRestClientInterface)(nil).APIVersion))
} | [
"func",
"(",
"mr",
"*",
"MockRestClientInterfaceMockRecorder",
")",
"APIVersion",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",... | // APIVersion indicates an expected call of APIVersion | [
"APIVersion",
"indicates",
"an",
"expected",
"call",
"of",
"APIVersion"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/restclient_mock.go#L48-L50 | train |
juju/juju | caas/kubernetes/provider/mocks/restclient_mock.go | GetRateLimiter | func (m *MockRestClientInterface) GetRateLimiter() flowcontrol.RateLimiter {
ret := m.ctrl.Call(m, "GetRateLimiter")
ret0, _ := ret[0].(flowcontrol.RateLimiter)
return ret0
} | go | func (m *MockRestClientInterface) GetRateLimiter() flowcontrol.RateLimiter {
ret := m.ctrl.Call(m, "GetRateLimiter")
ret0, _ := ret[0].(flowcontrol.RateLimiter)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockRestClientInterface",
")",
"GetRateLimiter",
"(",
")",
"flowcontrol",
".",
"RateLimiter",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]... | // GetRateLimiter mocks base method | [
"GetRateLimiter",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/restclient_mock.go#L77-L81 | train |
juju/juju | caas/kubernetes/provider/mocks/restclient_mock.go | Verb | func (m *MockRestClientInterface) Verb(arg0 string) *rest.Request {
ret := m.ctrl.Call(m, "Verb", arg0)
ret0, _ := ret[0].(*rest.Request)
return ret0
} | go | func (m *MockRestClientInterface) Verb(arg0 string) *rest.Request {
ret := m.ctrl.Call(m, "Verb", arg0)
ret0, _ := ret[0].(*rest.Request)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockRestClientInterface",
")",
"Verb",
"(",
"arg0",
"string",
")",
"*",
"rest",
".",
"Request",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
... | // Verb mocks base method | [
"Verb",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/restclient_mock.go#L125-L129 | train |
juju/juju | cmd/juju/status/status.go | NewStatusCommand | func NewStatusCommand() cmd.Command {
return modelcmd.Wrap(&statusCommand{
checkProvidedIgnoredFlagF: func() set.Strings { return set.NewStrings() },
})
} | go | func NewStatusCommand() cmd.Command {
return modelcmd.Wrap(&statusCommand{
checkProvidedIgnoredFlagF: func() set.Strings { return set.NewStrings() },
})
} | [
"func",
"NewStatusCommand",
"(",
")",
"cmd",
".",
"Command",
"{",
"return",
"modelcmd",
".",
"Wrap",
"(",
"&",
"statusCommand",
"{",
"checkProvidedIgnoredFlagF",
":",
"func",
"(",
")",
"set",
".",
"Strings",
"{",
"return",
"set",
".",
"NewStrings",
"(",
")... | // NewStatusCommand returns a new command, which reports on the
// runtime state of various system entities. | [
"NewStatusCommand",
"returns",
"a",
"new",
"command",
"which",
"reports",
"on",
"the",
"runtime",
"state",
"of",
"various",
"system",
"entities",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/status/status.go#L38-L42 | train |
juju/juju | cmd/juju/cloud/detectcredentials.go | NewDetectCredentialsCommand | func NewDetectCredentialsCommand() cmd.Command {
c := &detectCredentialsCommand{
store: jujuclient.NewFileCredentialStore(),
registeredProvidersFunc: environs.RegisteredProviders,
cloudByNameFunc: jujucloud.CloudByName,
}
c.allCloudsFunc = func() (map[string]jujucloud.Cloud, error) {
return c.allClouds()
}
return c
} | go | func NewDetectCredentialsCommand() cmd.Command {
c := &detectCredentialsCommand{
store: jujuclient.NewFileCredentialStore(),
registeredProvidersFunc: environs.RegisteredProviders,
cloudByNameFunc: jujucloud.CloudByName,
}
c.allCloudsFunc = func() (map[string]jujucloud.Cloud, error) {
return c.allClouds()
}
return c
} | [
"func",
"NewDetectCredentialsCommand",
"(",
")",
"cmd",
".",
"Command",
"{",
"c",
":=",
"&",
"detectCredentialsCommand",
"{",
"store",
":",
"jujuclient",
".",
"NewFileCredentialStore",
"(",
")",
",",
"registeredProvidersFunc",
":",
"environs",
".",
"RegisteredProvid... | // NewDetectCredentialsCommand returns a command to add credential information to credentials.yaml. | [
"NewDetectCredentialsCommand",
"returns",
"a",
"command",
"to",
"add",
"credential",
"information",
"to",
"credentials",
".",
"yaml",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/cloud/detectcredentials.go#L87-L97 | train |
juju/juju | cmd/juju/cloud/detectcredentials.go | guessCloudInfo | func (c *detectCredentialsCommand) guessCloudInfo(
sortedCloudNames []string,
clouds map[string]jujucloud.Cloud,
providerName, credName string,
) (defaultCloud, defaultRegion string, isNew bool, _ error) {
isNew = true
for _, cloudName := range sortedCloudNames {
cloud := clouds[cloudName]
if cloud.Type != providerName {
continue
}
credentials, err := c.store.CredentialForCloud(cloudName)
if err != nil && !errors.IsNotFound(err) {
return "", "", false, errors.Trace(err)
}
if err != nil {
// None found.
continue
}
existingCredNames := set.NewStrings()
for name := range credentials.AuthCredentials {
existingCredNames.Add(name)
}
isNew = !existingCredNames.Contains(credName)
if defaultRegion == "" && credentials.DefaultRegion != "" {
defaultRegion = credentials.DefaultRegion
}
if defaultCloud == "" {
defaultCloud = cloudName
}
}
return defaultCloud, defaultRegion, isNew, nil
} | go | func (c *detectCredentialsCommand) guessCloudInfo(
sortedCloudNames []string,
clouds map[string]jujucloud.Cloud,
providerName, credName string,
) (defaultCloud, defaultRegion string, isNew bool, _ error) {
isNew = true
for _, cloudName := range sortedCloudNames {
cloud := clouds[cloudName]
if cloud.Type != providerName {
continue
}
credentials, err := c.store.CredentialForCloud(cloudName)
if err != nil && !errors.IsNotFound(err) {
return "", "", false, errors.Trace(err)
}
if err != nil {
// None found.
continue
}
existingCredNames := set.NewStrings()
for name := range credentials.AuthCredentials {
existingCredNames.Add(name)
}
isNew = !existingCredNames.Contains(credName)
if defaultRegion == "" && credentials.DefaultRegion != "" {
defaultRegion = credentials.DefaultRegion
}
if defaultCloud == "" {
defaultCloud = cloudName
}
}
return defaultCloud, defaultRegion, isNew, nil
} | [
"func",
"(",
"c",
"*",
"detectCredentialsCommand",
")",
"guessCloudInfo",
"(",
"sortedCloudNames",
"[",
"]",
"string",
",",
"clouds",
"map",
"[",
"string",
"]",
"jujucloud",
".",
"Cloud",
",",
"providerName",
",",
"credName",
"string",
",",
")",
"(",
"defaul... | // guessCloudInfo looks at all the compatible clouds for the provider name and
// looks to see whether the credential name exists already.
// The first match allows the default cloud and region to be set. The default
// cloud is used when prompting to save a credential. The sorted cloud names
// ensures that "aws" is preferred over "aws-china". | [
"guessCloudInfo",
"looks",
"at",
"all",
"the",
"compatible",
"clouds",
"for",
"the",
"provider",
"name",
"and",
"looks",
"to",
"see",
"whether",
"the",
"credential",
"name",
"exists",
"already",
".",
"The",
"first",
"match",
"allows",
"the",
"default",
"cloud"... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/cloud/detectcredentials.go#L249-L281 | train |
juju/juju | cmd/juju/cloud/detectcredentials.go | interactiveCredentialsUpdate | func (c *detectCredentialsCommand) interactiveCredentialsUpdate(ctxt *cmd.Context, discovered []discoveredCredential) error {
for {
// Prompt for a credential to save.
c.printCredentialOptions(ctxt, discovered)
var input string
for {
var err error
input, err = c.promptCredentialNumber(ctxt.Stderr, ctxt.Stdin)
if err != nil {
return errors.Trace(err)
}
if strings.ToLower(input) == "q" {
return nil
}
if input != "" {
break
}
}
// Check the entered number.
num, err := strconv.Atoi(input)
if err != nil || num < 1 || num > len(discovered) {
fmt.Fprintf(ctxt.Stderr, "Invalid choice, enter a number between 1 and %v\n", len(discovered))
continue
}
cred := discovered[num-1]
// Prompt for the cloud for which to save the credential.
cloudName, err := c.promptCloudName(ctxt.Stderr, ctxt.Stdin, cred.defaultCloudName, cred.cloudType)
if err != nil {
fmt.Fprintln(ctxt.Stderr, err.Error())
continue
}
if cloudName == "" {
fmt.Fprintln(ctxt.Stderr, "No cloud name entered.")
continue
}
// Reading existing info so we can apply updated values.
existing, err := c.store.CredentialForCloud(cloudName)
if err != nil && !errors.IsNotFound(err) {
fmt.Fprintf(ctxt.Stderr, "error reading credential file: %v\n", err)
continue
}
if errors.IsNotFound(err) {
existing = &jujucloud.CloudCredential{
AuthCredentials: make(map[string]jujucloud.Credential),
}
}
if cred.region != "" {
existing.DefaultRegion = cred.region
}
existing.AuthCredentials[cred.credentialName] = cred.credential
if err := c.store.UpdateCredential(cloudName, *existing); err != nil {
fmt.Fprintf(ctxt.Stderr, "error saving credential: %v\n", err)
} else {
// Update so we display correctly next time list is printed.
cred.isNew = false
discovered[num-1] = cred
fmt.Fprintf(ctxt.Stderr, "Saved %s to cloud %s\n", cred.credential.Label, cloudName)
}
}
} | go | func (c *detectCredentialsCommand) interactiveCredentialsUpdate(ctxt *cmd.Context, discovered []discoveredCredential) error {
for {
// Prompt for a credential to save.
c.printCredentialOptions(ctxt, discovered)
var input string
for {
var err error
input, err = c.promptCredentialNumber(ctxt.Stderr, ctxt.Stdin)
if err != nil {
return errors.Trace(err)
}
if strings.ToLower(input) == "q" {
return nil
}
if input != "" {
break
}
}
// Check the entered number.
num, err := strconv.Atoi(input)
if err != nil || num < 1 || num > len(discovered) {
fmt.Fprintf(ctxt.Stderr, "Invalid choice, enter a number between 1 and %v\n", len(discovered))
continue
}
cred := discovered[num-1]
// Prompt for the cloud for which to save the credential.
cloudName, err := c.promptCloudName(ctxt.Stderr, ctxt.Stdin, cred.defaultCloudName, cred.cloudType)
if err != nil {
fmt.Fprintln(ctxt.Stderr, err.Error())
continue
}
if cloudName == "" {
fmt.Fprintln(ctxt.Stderr, "No cloud name entered.")
continue
}
// Reading existing info so we can apply updated values.
existing, err := c.store.CredentialForCloud(cloudName)
if err != nil && !errors.IsNotFound(err) {
fmt.Fprintf(ctxt.Stderr, "error reading credential file: %v\n", err)
continue
}
if errors.IsNotFound(err) {
existing = &jujucloud.CloudCredential{
AuthCredentials: make(map[string]jujucloud.Credential),
}
}
if cred.region != "" {
existing.DefaultRegion = cred.region
}
existing.AuthCredentials[cred.credentialName] = cred.credential
if err := c.store.UpdateCredential(cloudName, *existing); err != nil {
fmt.Fprintf(ctxt.Stderr, "error saving credential: %v\n", err)
} else {
// Update so we display correctly next time list is printed.
cred.isNew = false
discovered[num-1] = cred
fmt.Fprintf(ctxt.Stderr, "Saved %s to cloud %s\n", cred.credential.Label, cloudName)
}
}
} | [
"func",
"(",
"c",
"*",
"detectCredentialsCommand",
")",
"interactiveCredentialsUpdate",
"(",
"ctxt",
"*",
"cmd",
".",
"Context",
",",
"discovered",
"[",
"]",
"discoveredCredential",
")",
"error",
"{",
"for",
"{",
"// Prompt for a credential to save.",
"c",
".",
"p... | // interactiveCredentialsUpdate prints a list of the discovered credentials
// and prompts the user to update their local credentials. | [
"interactiveCredentialsUpdate",
"prints",
"a",
"list",
"of",
"the",
"discovered",
"credentials",
"and",
"prompts",
"the",
"user",
"to",
"update",
"their",
"local",
"credentials",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/cloud/detectcredentials.go#L285-L346 | train |
juju/juju | cmd/juju/storage/poolupdate.go | NewPoolUpdateCommand | func NewPoolUpdateCommand() cmd.Command {
cmd := &poolUpdateCommand{}
cmd.newAPIFunc = func() (PoolUpdateAPI, error) {
return cmd.NewStorageAPI()
}
return modelcmd.Wrap(cmd)
} | go | func NewPoolUpdateCommand() cmd.Command {
cmd := &poolUpdateCommand{}
cmd.newAPIFunc = func() (PoolUpdateAPI, error) {
return cmd.NewStorageAPI()
}
return modelcmd.Wrap(cmd)
} | [
"func",
"NewPoolUpdateCommand",
"(",
")",
"cmd",
".",
"Command",
"{",
"cmd",
":=",
"&",
"poolUpdateCommand",
"{",
"}",
"\n",
"cmd",
".",
"newAPIFunc",
"=",
"func",
"(",
")",
"(",
"PoolUpdateAPI",
",",
"error",
")",
"{",
"return",
"cmd",
".",
"NewStorageA... | // NewPoolUpdateCommand returns a command that replaces the named storage pools' attributes. | [
"NewPoolUpdateCommand",
"returns",
"a",
"command",
"that",
"replaces",
"the",
"named",
"storage",
"pools",
"attributes",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/storage/poolupdate.go#L44-L50 | train |
juju/juju | worker/storageprovisioner/filesystem_ops.go | attachFilesystems | func attachFilesystems(ctx *context, ops map[params.MachineStorageId]*attachFilesystemOp) error {
filesystemAttachmentParams := make([]storage.FilesystemAttachmentParams, 0, len(ops))
for _, op := range ops {
args := op.args
if args.Path == "" {
args.Path = filepath.Join(ctx.config.StorageDir, args.Filesystem.Id())
}
filesystemAttachmentParams = append(filesystemAttachmentParams, args)
}
paramsBySource, filesystemSources, err := filesystemAttachmentParamsBySource(
ctx.config.StorageDir,
filesystemAttachmentParams,
ctx.filesystems,
ctx.managedFilesystemSource,
ctx.config.Registry,
)
if err != nil {
return errors.Trace(err)
}
var reschedule []scheduleOp
var filesystemAttachments []storage.FilesystemAttachment
var statuses []params.EntityStatusArgs
for sourceName, filesystemAttachmentParams := range paramsBySource {
logger.Debugf("attaching filesystems: %+v", filesystemAttachmentParams)
filesystemSource := filesystemSources[sourceName]
results, err := filesystemSource.AttachFilesystems(ctx.config.CloudCallContext, filesystemAttachmentParams)
if err != nil {
return errors.Annotatef(err, "attaching filesystems from source %q", sourceName)
}
for i, result := range results {
p := filesystemAttachmentParams[i]
statuses = append(statuses, params.EntityStatusArgs{
Tag: p.Filesystem.String(),
Status: status.Attached.String(),
})
entityStatus := &statuses[len(statuses)-1]
if result.Error != nil {
// Reschedule the filesystem attachment.
id := params.MachineStorageId{
MachineTag: p.Machine.String(),
AttachmentTag: p.Filesystem.String(),
}
reschedule = append(reschedule, ops[id])
// Note: we keep the status as "attaching" to
// indicate that we will retry. When we distinguish
// between transient and permanent errors, we will
// set the status to "error" for permanent errors.
entityStatus.Status = status.Attaching.String()
entityStatus.Info = result.Error.Error()
logger.Debugf(
"failed to attach %s to %s: %v",
names.ReadableString(p.Filesystem),
names.ReadableString(p.Machine),
result.Error,
)
continue
}
filesystemAttachments = append(filesystemAttachments, *result.FilesystemAttachment)
}
}
scheduleOperations(ctx, reschedule...)
setStatus(ctx, statuses)
if err := setFilesystemAttachmentInfo(ctx, filesystemAttachments); err != nil {
return errors.Trace(err)
}
return nil
} | go | func attachFilesystems(ctx *context, ops map[params.MachineStorageId]*attachFilesystemOp) error {
filesystemAttachmentParams := make([]storage.FilesystemAttachmentParams, 0, len(ops))
for _, op := range ops {
args := op.args
if args.Path == "" {
args.Path = filepath.Join(ctx.config.StorageDir, args.Filesystem.Id())
}
filesystemAttachmentParams = append(filesystemAttachmentParams, args)
}
paramsBySource, filesystemSources, err := filesystemAttachmentParamsBySource(
ctx.config.StorageDir,
filesystemAttachmentParams,
ctx.filesystems,
ctx.managedFilesystemSource,
ctx.config.Registry,
)
if err != nil {
return errors.Trace(err)
}
var reschedule []scheduleOp
var filesystemAttachments []storage.FilesystemAttachment
var statuses []params.EntityStatusArgs
for sourceName, filesystemAttachmentParams := range paramsBySource {
logger.Debugf("attaching filesystems: %+v", filesystemAttachmentParams)
filesystemSource := filesystemSources[sourceName]
results, err := filesystemSource.AttachFilesystems(ctx.config.CloudCallContext, filesystemAttachmentParams)
if err != nil {
return errors.Annotatef(err, "attaching filesystems from source %q", sourceName)
}
for i, result := range results {
p := filesystemAttachmentParams[i]
statuses = append(statuses, params.EntityStatusArgs{
Tag: p.Filesystem.String(),
Status: status.Attached.String(),
})
entityStatus := &statuses[len(statuses)-1]
if result.Error != nil {
// Reschedule the filesystem attachment.
id := params.MachineStorageId{
MachineTag: p.Machine.String(),
AttachmentTag: p.Filesystem.String(),
}
reschedule = append(reschedule, ops[id])
// Note: we keep the status as "attaching" to
// indicate that we will retry. When we distinguish
// between transient and permanent errors, we will
// set the status to "error" for permanent errors.
entityStatus.Status = status.Attaching.String()
entityStatus.Info = result.Error.Error()
logger.Debugf(
"failed to attach %s to %s: %v",
names.ReadableString(p.Filesystem),
names.ReadableString(p.Machine),
result.Error,
)
continue
}
filesystemAttachments = append(filesystemAttachments, *result.FilesystemAttachment)
}
}
scheduleOperations(ctx, reschedule...)
setStatus(ctx, statuses)
if err := setFilesystemAttachmentInfo(ctx, filesystemAttachments); err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"attachFilesystems",
"(",
"ctx",
"*",
"context",
",",
"ops",
"map",
"[",
"params",
".",
"MachineStorageId",
"]",
"*",
"attachFilesystemOp",
")",
"error",
"{",
"filesystemAttachmentParams",
":=",
"make",
"(",
"[",
"]",
"storage",
".",
"FilesystemAttachmen... | // attachFilesystems creates filesystem attachments with the specified parameters. | [
"attachFilesystems",
"creates",
"filesystem",
"attachments",
"with",
"the",
"specified",
"parameters",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/filesystem_ops.go#L119-L186 | train |
juju/juju | worker/storageprovisioner/filesystem_ops.go | detachFilesystems | func detachFilesystems(ctx *context, ops map[params.MachineStorageId]*detachFilesystemOp) error {
filesystemAttachmentParams := make([]storage.FilesystemAttachmentParams, 0, len(ops))
for _, op := range ops {
filesystemAttachmentParams = append(filesystemAttachmentParams, op.args)
}
paramsBySource, filesystemSources, err := filesystemAttachmentParamsBySource(
ctx.config.StorageDir,
filesystemAttachmentParams,
ctx.filesystems,
ctx.managedFilesystemSource,
ctx.config.Registry,
)
if err != nil {
return errors.Trace(err)
}
var reschedule []scheduleOp
var statuses []params.EntityStatusArgs
var remove []params.MachineStorageId
for sourceName, filesystemAttachmentParams := range paramsBySource {
logger.Debugf("detaching filesystems: %+v", filesystemAttachmentParams)
filesystemSource, ok := filesystemSources[sourceName]
if !ok && ctx.isApplicationKind() {
continue
}
errs, err := filesystemSource.DetachFilesystems(ctx.config.CloudCallContext, filesystemAttachmentParams)
if err != nil {
return errors.Annotatef(err, "detaching filesystems from source %q", sourceName)
}
for i, err := range errs {
p := filesystemAttachmentParams[i]
statuses = append(statuses, params.EntityStatusArgs{
Tag: p.Filesystem.String(),
// TODO(axw) when we support multiple
// attachment, we'll have to check if
// there are any other attachments
// before saying the status "detached".
Status: status.Detached.String(),
})
id := params.MachineStorageId{
MachineTag: p.Machine.String(),
AttachmentTag: p.Filesystem.String(),
}
entityStatus := &statuses[len(statuses)-1]
if err != nil {
reschedule = append(reschedule, ops[id])
entityStatus.Status = status.Detaching.String()
entityStatus.Info = err.Error()
logger.Debugf(
"failed to detach %s from %s: %v",
names.ReadableString(p.Filesystem),
names.ReadableString(p.Machine),
err,
)
continue
}
remove = append(remove, id)
}
}
scheduleOperations(ctx, reschedule...)
setStatus(ctx, statuses)
if err := removeAttachments(ctx, remove); err != nil {
return errors.Annotate(err, "removing attachments from state")
}
for _, id := range remove {
delete(ctx.filesystemAttachments, id)
}
return nil
} | go | func detachFilesystems(ctx *context, ops map[params.MachineStorageId]*detachFilesystemOp) error {
filesystemAttachmentParams := make([]storage.FilesystemAttachmentParams, 0, len(ops))
for _, op := range ops {
filesystemAttachmentParams = append(filesystemAttachmentParams, op.args)
}
paramsBySource, filesystemSources, err := filesystemAttachmentParamsBySource(
ctx.config.StorageDir,
filesystemAttachmentParams,
ctx.filesystems,
ctx.managedFilesystemSource,
ctx.config.Registry,
)
if err != nil {
return errors.Trace(err)
}
var reschedule []scheduleOp
var statuses []params.EntityStatusArgs
var remove []params.MachineStorageId
for sourceName, filesystemAttachmentParams := range paramsBySource {
logger.Debugf("detaching filesystems: %+v", filesystemAttachmentParams)
filesystemSource, ok := filesystemSources[sourceName]
if !ok && ctx.isApplicationKind() {
continue
}
errs, err := filesystemSource.DetachFilesystems(ctx.config.CloudCallContext, filesystemAttachmentParams)
if err != nil {
return errors.Annotatef(err, "detaching filesystems from source %q", sourceName)
}
for i, err := range errs {
p := filesystemAttachmentParams[i]
statuses = append(statuses, params.EntityStatusArgs{
Tag: p.Filesystem.String(),
// TODO(axw) when we support multiple
// attachment, we'll have to check if
// there are any other attachments
// before saying the status "detached".
Status: status.Detached.String(),
})
id := params.MachineStorageId{
MachineTag: p.Machine.String(),
AttachmentTag: p.Filesystem.String(),
}
entityStatus := &statuses[len(statuses)-1]
if err != nil {
reschedule = append(reschedule, ops[id])
entityStatus.Status = status.Detaching.String()
entityStatus.Info = err.Error()
logger.Debugf(
"failed to detach %s from %s: %v",
names.ReadableString(p.Filesystem),
names.ReadableString(p.Machine),
err,
)
continue
}
remove = append(remove, id)
}
}
scheduleOperations(ctx, reschedule...)
setStatus(ctx, statuses)
if err := removeAttachments(ctx, remove); err != nil {
return errors.Annotate(err, "removing attachments from state")
}
for _, id := range remove {
delete(ctx.filesystemAttachments, id)
}
return nil
} | [
"func",
"detachFilesystems",
"(",
"ctx",
"*",
"context",
",",
"ops",
"map",
"[",
"params",
".",
"MachineStorageId",
"]",
"*",
"detachFilesystemOp",
")",
"error",
"{",
"filesystemAttachmentParams",
":=",
"make",
"(",
"[",
"]",
"storage",
".",
"FilesystemAttachmen... | // detachFilesystems destroys filesystem attachments with the specified parameters. | [
"detachFilesystems",
"destroys",
"filesystem",
"attachments",
"with",
"the",
"specified",
"parameters",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/filesystem_ops.go#L290-L357 | train |
juju/juju | worker/storageprovisioner/filesystem_ops.go | filesystemParamsBySource | func filesystemParamsBySource(
baseStorageDir string,
params []storage.FilesystemParams,
managedFilesystemSource storage.FilesystemSource,
registry storage.ProviderRegistry,
) (map[string][]storage.FilesystemParams, map[string]storage.FilesystemSource, error) {
// TODO(axw) later we may have multiple instantiations (sources)
// for a storage provider, e.g. multiple Ceph installations. For
// now we assume a single source for each provider type, with no
// configuration.
filesystemSources := make(map[string]storage.FilesystemSource)
for _, params := range params {
sourceName := string(params.Provider)
if _, ok := filesystemSources[sourceName]; ok {
continue
}
if params.Volume != (names.VolumeTag{}) {
filesystemSources[sourceName] = managedFilesystemSource
continue
}
filesystemSource, err := filesystemSource(
baseStorageDir, sourceName, params.Provider, registry,
)
// For k8s models, there may be a not found error as there's only
// one (model) storage provisioner worker which reacts to all storage,
// even tmpfs or rootfs which is ostensibly handled by a machine storage
// provisioner worker. There's no such provisoner for k8s but we still
// process the detach/destroy so the state model can be updated.
if errors.Cause(err) == errNonDynamic || errors.IsNotFound(err) {
filesystemSource = nil
} else if err != nil {
return nil, nil, errors.Annotate(err, "getting filesystem source")
}
filesystemSources[sourceName] = filesystemSource
}
paramsBySource := make(map[string][]storage.FilesystemParams)
for _, param := range params {
sourceName := string(param.Provider)
filesystemSource := filesystemSources[sourceName]
if filesystemSource == nil {
// Ignore nil filesystem sources; this means that the
// filesystem should be created by the machine-provisioner.
continue
}
paramsBySource[sourceName] = append(paramsBySource[sourceName], param)
}
return paramsBySource, filesystemSources, nil
} | go | func filesystemParamsBySource(
baseStorageDir string,
params []storage.FilesystemParams,
managedFilesystemSource storage.FilesystemSource,
registry storage.ProviderRegistry,
) (map[string][]storage.FilesystemParams, map[string]storage.FilesystemSource, error) {
// TODO(axw) later we may have multiple instantiations (sources)
// for a storage provider, e.g. multiple Ceph installations. For
// now we assume a single source for each provider type, with no
// configuration.
filesystemSources := make(map[string]storage.FilesystemSource)
for _, params := range params {
sourceName := string(params.Provider)
if _, ok := filesystemSources[sourceName]; ok {
continue
}
if params.Volume != (names.VolumeTag{}) {
filesystemSources[sourceName] = managedFilesystemSource
continue
}
filesystemSource, err := filesystemSource(
baseStorageDir, sourceName, params.Provider, registry,
)
// For k8s models, there may be a not found error as there's only
// one (model) storage provisioner worker which reacts to all storage,
// even tmpfs or rootfs which is ostensibly handled by a machine storage
// provisioner worker. There's no such provisoner for k8s but we still
// process the detach/destroy so the state model can be updated.
if errors.Cause(err) == errNonDynamic || errors.IsNotFound(err) {
filesystemSource = nil
} else if err != nil {
return nil, nil, errors.Annotate(err, "getting filesystem source")
}
filesystemSources[sourceName] = filesystemSource
}
paramsBySource := make(map[string][]storage.FilesystemParams)
for _, param := range params {
sourceName := string(param.Provider)
filesystemSource := filesystemSources[sourceName]
if filesystemSource == nil {
// Ignore nil filesystem sources; this means that the
// filesystem should be created by the machine-provisioner.
continue
}
paramsBySource[sourceName] = append(paramsBySource[sourceName], param)
}
return paramsBySource, filesystemSources, nil
} | [
"func",
"filesystemParamsBySource",
"(",
"baseStorageDir",
"string",
",",
"params",
"[",
"]",
"storage",
".",
"FilesystemParams",
",",
"managedFilesystemSource",
"storage",
".",
"FilesystemSource",
",",
"registry",
"storage",
".",
"ProviderRegistry",
",",
")",
"(",
... | // filesystemParamsBySource separates the filesystem parameters by filesystem source. | [
"filesystemParamsBySource",
"separates",
"the",
"filesystem",
"parameters",
"by",
"filesystem",
"source",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/filesystem_ops.go#L360-L407 | train |
juju/juju | worker/storageprovisioner/filesystem_ops.go | validateFilesystemParams | func validateFilesystemParams(
filesystemSource storage.FilesystemSource,
filesystemParams []storage.FilesystemParams,
) ([]storage.FilesystemParams, []error) {
valid := make([]storage.FilesystemParams, 0, len(filesystemParams))
results := make([]error, len(filesystemParams))
for i, params := range filesystemParams {
err := filesystemSource.ValidateFilesystemParams(params)
if err == nil {
valid = append(valid, params)
}
results[i] = err
}
return valid, results
} | go | func validateFilesystemParams(
filesystemSource storage.FilesystemSource,
filesystemParams []storage.FilesystemParams,
) ([]storage.FilesystemParams, []error) {
valid := make([]storage.FilesystemParams, 0, len(filesystemParams))
results := make([]error, len(filesystemParams))
for i, params := range filesystemParams {
err := filesystemSource.ValidateFilesystemParams(params)
if err == nil {
valid = append(valid, params)
}
results[i] = err
}
return valid, results
} | [
"func",
"validateFilesystemParams",
"(",
"filesystemSource",
"storage",
".",
"FilesystemSource",
",",
"filesystemParams",
"[",
"]",
"storage",
".",
"FilesystemParams",
",",
")",
"(",
"[",
"]",
"storage",
".",
"FilesystemParams",
",",
"[",
"]",
"error",
")",
"{",... | // validateFilesystemParams validates a collection of filesystem parameters. | [
"validateFilesystemParams",
"validates",
"a",
"collection",
"of",
"filesystem",
"parameters",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/filesystem_ops.go#L410-L424 | train |
juju/juju | worker/storageprovisioner/filesystem_ops.go | filesystemAttachmentParamsBySource | func filesystemAttachmentParamsBySource(
baseStorageDir string,
filesystemAttachmentParams []storage.FilesystemAttachmentParams,
filesystems map[names.FilesystemTag]storage.Filesystem,
managedFilesystemSource storage.FilesystemSource,
registry storage.ProviderRegistry,
) (map[string][]storage.FilesystemAttachmentParams, map[string]storage.FilesystemSource, error) {
// TODO(axw) later we may have multiple instantiations (sources)
// for a storage provider, e.g. multiple Ceph installations. For
// now we assume a single source for each provider type, with no
// configuration.
filesystemSources := make(map[string]storage.FilesystemSource)
paramsBySource := make(map[string][]storage.FilesystemAttachmentParams)
for _, params := range filesystemAttachmentParams {
sourceName := string(params.Provider)
paramsBySource[sourceName] = append(paramsBySource[sourceName], params)
if _, ok := filesystemSources[sourceName]; ok {
continue
}
filesystem, ok := filesystems[params.Filesystem]
if !ok || filesystem.Volume != (names.VolumeTag{}) {
filesystemSources[sourceName] = managedFilesystemSource
continue
}
filesystemSource, err := filesystemSource(
baseStorageDir, sourceName, params.Provider, registry,
)
// For k8s models, there may be a not found error as there's only
// one (model) storage provisioner worker which reacts to all storage,
// even tmpfs or rootfs which is ostensibly handled by a machine storage
// provisioner worker. There's no such provisoner for k8s but we still
// process the detach/destroy so the state model can be updated.
if err != nil && !errors.IsNotFound(err) {
return nil, nil, errors.Annotate(err, "getting filesystem source")
}
filesystemSources[sourceName] = filesystemSource
}
return paramsBySource, filesystemSources, nil
} | go | func filesystemAttachmentParamsBySource(
baseStorageDir string,
filesystemAttachmentParams []storage.FilesystemAttachmentParams,
filesystems map[names.FilesystemTag]storage.Filesystem,
managedFilesystemSource storage.FilesystemSource,
registry storage.ProviderRegistry,
) (map[string][]storage.FilesystemAttachmentParams, map[string]storage.FilesystemSource, error) {
// TODO(axw) later we may have multiple instantiations (sources)
// for a storage provider, e.g. multiple Ceph installations. For
// now we assume a single source for each provider type, with no
// configuration.
filesystemSources := make(map[string]storage.FilesystemSource)
paramsBySource := make(map[string][]storage.FilesystemAttachmentParams)
for _, params := range filesystemAttachmentParams {
sourceName := string(params.Provider)
paramsBySource[sourceName] = append(paramsBySource[sourceName], params)
if _, ok := filesystemSources[sourceName]; ok {
continue
}
filesystem, ok := filesystems[params.Filesystem]
if !ok || filesystem.Volume != (names.VolumeTag{}) {
filesystemSources[sourceName] = managedFilesystemSource
continue
}
filesystemSource, err := filesystemSource(
baseStorageDir, sourceName, params.Provider, registry,
)
// For k8s models, there may be a not found error as there's only
// one (model) storage provisioner worker which reacts to all storage,
// even tmpfs or rootfs which is ostensibly handled by a machine storage
// provisioner worker. There's no such provisoner for k8s but we still
// process the detach/destroy so the state model can be updated.
if err != nil && !errors.IsNotFound(err) {
return nil, nil, errors.Annotate(err, "getting filesystem source")
}
filesystemSources[sourceName] = filesystemSource
}
return paramsBySource, filesystemSources, nil
} | [
"func",
"filesystemAttachmentParamsBySource",
"(",
"baseStorageDir",
"string",
",",
"filesystemAttachmentParams",
"[",
"]",
"storage",
".",
"FilesystemAttachmentParams",
",",
"filesystems",
"map",
"[",
"names",
".",
"FilesystemTag",
"]",
"storage",
".",
"Filesystem",
",... | // filesystemAttachmentParamsBySource separates the filesystem attachment parameters by filesystem source. | [
"filesystemAttachmentParamsBySource",
"separates",
"the",
"filesystem",
"attachment",
"parameters",
"by",
"filesystem",
"source",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/filesystem_ops.go#L427-L465 | train |
juju/juju | apiserver/facades/client/keymanager/keymanager.go | NewKeyManagerAPI | func NewKeyManagerAPI(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*KeyManagerAPI, error) {
// Only clients can access the key manager service.
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
m, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
return &KeyManagerAPI{
state: st,
model: m,
resources: resources,
authorizer: authorizer,
apiUser: authorizer.GetAuthTag().(names.UserTag),
check: common.NewBlockChecker(st),
}, nil
} | go | func NewKeyManagerAPI(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*KeyManagerAPI, error) {
// Only clients can access the key manager service.
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
m, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
return &KeyManagerAPI{
state: st,
model: m,
resources: resources,
authorizer: authorizer,
apiUser: authorizer.GetAuthTag().(names.UserTag),
check: common.NewBlockChecker(st),
}, nil
} | [
"func",
"NewKeyManagerAPI",
"(",
"st",
"*",
"state",
".",
"State",
",",
"resources",
"facade",
".",
"Resources",
",",
"authorizer",
"facade",
".",
"Authorizer",
")",
"(",
"*",
"KeyManagerAPI",
",",
"error",
")",
"{",
"// Only clients can access the key manager ser... | // NewKeyManagerAPI creates a new server-side keyupdater API end point. | [
"NewKeyManagerAPI",
"creates",
"a",
"new",
"server",
"-",
"side",
"keyupdater",
"API",
"end",
"point",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/keymanager/keymanager.go#L52-L69 | train |
juju/juju | apiserver/facades/client/keymanager/keymanager.go | currentKeyDataForAdd | func (api *KeyManagerAPI) currentKeyDataForAdd() (keys []string, fingerprints set.Strings, err error) {
fingerprints = make(set.Strings)
cfg, err := api.model.ModelConfig()
if err != nil {
return nil, nil, fmt.Errorf("reading current key data: %v", err)
}
keys = ssh.SplitAuthorisedKeys(cfg.AuthorizedKeys())
for _, key := range keys {
fingerprint, _, err := ssh.KeyFingerprint(key)
if err != nil {
logger.Warningf("ignoring invalid ssh key %q: %v", key, err)
}
fingerprints.Add(fingerprint)
}
return keys, fingerprints, nil
} | go | func (api *KeyManagerAPI) currentKeyDataForAdd() (keys []string, fingerprints set.Strings, err error) {
fingerprints = make(set.Strings)
cfg, err := api.model.ModelConfig()
if err != nil {
return nil, nil, fmt.Errorf("reading current key data: %v", err)
}
keys = ssh.SplitAuthorisedKeys(cfg.AuthorizedKeys())
for _, key := range keys {
fingerprint, _, err := ssh.KeyFingerprint(key)
if err != nil {
logger.Warningf("ignoring invalid ssh key %q: %v", key, err)
}
fingerprints.Add(fingerprint)
}
return keys, fingerprints, nil
} | [
"func",
"(",
"api",
"*",
"KeyManagerAPI",
")",
"currentKeyDataForAdd",
"(",
")",
"(",
"keys",
"[",
"]",
"string",
",",
"fingerprints",
"set",
".",
"Strings",
",",
"err",
"error",
")",
"{",
"fingerprints",
"=",
"make",
"(",
"set",
".",
"Strings",
")",
"... | // currentKeyDataForAdd gathers data used when adding ssh keys. | [
"currentKeyDataForAdd",
"gathers",
"data",
"used",
"when",
"adding",
"ssh",
"keys",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/keymanager/keymanager.go#L184-L199 | train |
juju/juju | apiserver/facades/client/keymanager/keymanager.go | AddKeys | func (api *KeyManagerAPI) AddKeys(arg params.ModifyUserSSHKeys) (params.ErrorResults, error) {
if err := api.check.ChangeAllowed(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(arg.Keys)),
}
if len(arg.Keys) == 0 {
return result, nil
}
if err := api.checkCanWrite(arg.User); err != nil {
return params.ErrorResults{}, common.ServerError(err)
}
// For now, authorised keys are global, common to all users.
sshKeys, currentFingerprints, err := api.currentKeyDataForAdd()
if err != nil {
return params.ErrorResults{}, common.ServerError(fmt.Errorf("reading current key data: %v", err))
}
// Ensure we are not going to add invalid or duplicate keys.
result.Results = make([]params.ErrorResult, len(arg.Keys))
for i, key := range arg.Keys {
fingerprint, _, err := ssh.KeyFingerprint(key)
if err != nil {
result.Results[i].Error = common.ServerError(fmt.Errorf("invalid ssh key: %s", key))
continue
}
if currentFingerprints.Contains(fingerprint) {
result.Results[i].Error = common.ServerError(fmt.Errorf("duplicate ssh key: %s", key))
continue
}
sshKeys = append(sshKeys, key)
}
err = api.writeSSHKeys(sshKeys)
if err != nil {
return params.ErrorResults{}, common.ServerError(err)
}
return result, nil
} | go | func (api *KeyManagerAPI) AddKeys(arg params.ModifyUserSSHKeys) (params.ErrorResults, error) {
if err := api.check.ChangeAllowed(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(arg.Keys)),
}
if len(arg.Keys) == 0 {
return result, nil
}
if err := api.checkCanWrite(arg.User); err != nil {
return params.ErrorResults{}, common.ServerError(err)
}
// For now, authorised keys are global, common to all users.
sshKeys, currentFingerprints, err := api.currentKeyDataForAdd()
if err != nil {
return params.ErrorResults{}, common.ServerError(fmt.Errorf("reading current key data: %v", err))
}
// Ensure we are not going to add invalid or duplicate keys.
result.Results = make([]params.ErrorResult, len(arg.Keys))
for i, key := range arg.Keys {
fingerprint, _, err := ssh.KeyFingerprint(key)
if err != nil {
result.Results[i].Error = common.ServerError(fmt.Errorf("invalid ssh key: %s", key))
continue
}
if currentFingerprints.Contains(fingerprint) {
result.Results[i].Error = common.ServerError(fmt.Errorf("duplicate ssh key: %s", key))
continue
}
sshKeys = append(sshKeys, key)
}
err = api.writeSSHKeys(sshKeys)
if err != nil {
return params.ErrorResults{}, common.ServerError(err)
}
return result, nil
} | [
"func",
"(",
"api",
"*",
"KeyManagerAPI",
")",
"AddKeys",
"(",
"arg",
"params",
".",
"ModifyUserSSHKeys",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"if",
"err",
":=",
"api",
".",
"check",
".",
"ChangeAllowed",
"(",
")",
";",
"err... | // AddKeys adds new authorised ssh keys for the specified user. | [
"AddKeys",
"adds",
"new",
"authorised",
"ssh",
"keys",
"for",
"the",
"specified",
"user",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/keymanager/keymanager.go#L202-L242 | train |
juju/juju | apiserver/facades/client/keymanager/keymanager.go | runSSHKeyImport | func runSSHKeyImport(keyIds []string) map[string][]importedSSHKey {
importResults := make(map[string][]importedSSHKey, len(keyIds))
for _, keyId := range keyIds {
keyInfo := []importedSSHKey{}
output, err := RunSSHImportId(keyId)
if err != nil {
keyInfo = append(keyInfo, importedSSHKey{err: err})
continue
}
lines := strings.Split(output, "\n")
hasKey := false
for _, line := range lines {
if !strings.HasPrefix(line, "ssh-") {
continue
}
hasKey = true
// ignore key comment (e.g., user@host)
fingerprint, _, err := ssh.KeyFingerprint(line)
keyInfo = append(keyInfo, importedSSHKey{
key: line,
fingerprint: fingerprint,
err: errors.Annotatef(err, "invalid ssh key for %s", keyId),
})
}
if !hasKey {
keyInfo = append(keyInfo, importedSSHKey{
err: errors.Errorf("invalid ssh key id: %s", keyId),
})
}
importResults[keyId] = keyInfo
}
return importResults
} | go | func runSSHKeyImport(keyIds []string) map[string][]importedSSHKey {
importResults := make(map[string][]importedSSHKey, len(keyIds))
for _, keyId := range keyIds {
keyInfo := []importedSSHKey{}
output, err := RunSSHImportId(keyId)
if err != nil {
keyInfo = append(keyInfo, importedSSHKey{err: err})
continue
}
lines := strings.Split(output, "\n")
hasKey := false
for _, line := range lines {
if !strings.HasPrefix(line, "ssh-") {
continue
}
hasKey = true
// ignore key comment (e.g., user@host)
fingerprint, _, err := ssh.KeyFingerprint(line)
keyInfo = append(keyInfo, importedSSHKey{
key: line,
fingerprint: fingerprint,
err: errors.Annotatef(err, "invalid ssh key for %s", keyId),
})
}
if !hasKey {
keyInfo = append(keyInfo, importedSSHKey{
err: errors.Errorf("invalid ssh key id: %s", keyId),
})
}
importResults[keyId] = keyInfo
}
return importResults
} | [
"func",
"runSSHKeyImport",
"(",
"keyIds",
"[",
"]",
"string",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"importedSSHKey",
"{",
"importResults",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"importedSSHKey",
",",
"len",
"(",
"keyIds",
")",
")... | // runSSHKeyImport uses ssh-import-id to find the ssh keys for the specified key ids. | [
"runSSHKeyImport",
"uses",
"ssh",
"-",
"import",
"-",
"id",
"to",
"find",
"the",
"ssh",
"keys",
"for",
"the",
"specified",
"key",
"ids",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/keymanager/keymanager.go#L258-L290 | train |
juju/juju | apiserver/facades/client/keymanager/keymanager.go | ImportKeys | func (api *KeyManagerAPI) ImportKeys(arg params.ModifyUserSSHKeys) (params.ErrorResults, error) {
if err := api.check.ChangeAllowed(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(arg.Keys)),
}
if len(arg.Keys) == 0 {
return result, nil
}
if err := api.checkCanWrite(arg.User); err != nil {
return params.ErrorResults{}, common.ServerError(err)
}
// For now, authorised keys are global, common to all users.
sshKeys, currentFingerprints, err := api.currentKeyDataForAdd()
if err != nil {
return params.ErrorResults{}, common.ServerError(fmt.Errorf("reading current key data: %v", err))
}
importedKeyInfo := runSSHKeyImport(arg.Keys)
// Ensure we are not going to add invalid or duplicate keys.
result.Results = make([]params.ErrorResult, len(importedKeyInfo))
for i, key := range arg.Keys {
compoundErr := ""
for _, keyInfo := range importedKeyInfo[key] {
if keyInfo.err != nil {
compoundErr += fmt.Sprintf("%v\n", keyInfo.err)
continue
}
if currentFingerprints.Contains(keyInfo.fingerprint) {
compoundErr += fmt.Sprintf("%v\n", errors.Errorf("duplicate ssh key: %s", keyInfo.key))
continue
}
sshKeys = append(sshKeys, keyInfo.key)
}
if compoundErr != "" {
result.Results[i].Error = common.ServerError(errors.Errorf(strings.TrimSuffix(compoundErr, "\n")))
}
}
err = api.writeSSHKeys(sshKeys)
if err != nil {
return params.ErrorResults{}, common.ServerError(err)
}
return result, nil
} | go | func (api *KeyManagerAPI) ImportKeys(arg params.ModifyUserSSHKeys) (params.ErrorResults, error) {
if err := api.check.ChangeAllowed(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(arg.Keys)),
}
if len(arg.Keys) == 0 {
return result, nil
}
if err := api.checkCanWrite(arg.User); err != nil {
return params.ErrorResults{}, common.ServerError(err)
}
// For now, authorised keys are global, common to all users.
sshKeys, currentFingerprints, err := api.currentKeyDataForAdd()
if err != nil {
return params.ErrorResults{}, common.ServerError(fmt.Errorf("reading current key data: %v", err))
}
importedKeyInfo := runSSHKeyImport(arg.Keys)
// Ensure we are not going to add invalid or duplicate keys.
result.Results = make([]params.ErrorResult, len(importedKeyInfo))
for i, key := range arg.Keys {
compoundErr := ""
for _, keyInfo := range importedKeyInfo[key] {
if keyInfo.err != nil {
compoundErr += fmt.Sprintf("%v\n", keyInfo.err)
continue
}
if currentFingerprints.Contains(keyInfo.fingerprint) {
compoundErr += fmt.Sprintf("%v\n", errors.Errorf("duplicate ssh key: %s", keyInfo.key))
continue
}
sshKeys = append(sshKeys, keyInfo.key)
}
if compoundErr != "" {
result.Results[i].Error = common.ServerError(errors.Errorf(strings.TrimSuffix(compoundErr, "\n")))
}
}
err = api.writeSSHKeys(sshKeys)
if err != nil {
return params.ErrorResults{}, common.ServerError(err)
}
return result, nil
} | [
"func",
"(",
"api",
"*",
"KeyManagerAPI",
")",
"ImportKeys",
"(",
"arg",
"params",
".",
"ModifyUserSSHKeys",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"if",
"err",
":=",
"api",
".",
"check",
".",
"ChangeAllowed",
"(",
")",
";",
"... | // ImportKeys imports new authorised ssh keys from the specified key ids for the specified user. | [
"ImportKeys",
"imports",
"new",
"authorised",
"ssh",
"keys",
"from",
"the",
"specified",
"key",
"ids",
"for",
"the",
"specified",
"user",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/keymanager/keymanager.go#L293-L340 | train |
juju/juju | apiserver/facades/client/keymanager/keymanager.go | currentKeyDataForDelete | func (api *KeyManagerAPI) currentKeyDataForDelete() (
currentKeys []string, byFingerprint map[string]string, byComment map[string]string, err error) {
cfg, err := api.model.ModelConfig()
if err != nil {
return nil, nil, nil, fmt.Errorf("reading current key data: %v", err)
}
// For now, authorised keys are global, common to all users.
currentKeys = ssh.SplitAuthorisedKeys(cfg.AuthorizedKeys())
// Make two maps that index keys by fingerprint and by comment for fast
// lookup of keys to delete which may be given as either.
byFingerprint = make(map[string]string)
byComment = make(map[string]string)
for _, key := range currentKeys {
fingerprint, comment, err := ssh.KeyFingerprint(key)
if err != nil {
logger.Debugf("keeping unrecognised existing ssh key %q: %v", key, err)
continue
}
byFingerprint[fingerprint] = key
if comment != "" {
byComment[comment] = key
}
}
return currentKeys, byFingerprint, byComment, nil
} | go | func (api *KeyManagerAPI) currentKeyDataForDelete() (
currentKeys []string, byFingerprint map[string]string, byComment map[string]string, err error) {
cfg, err := api.model.ModelConfig()
if err != nil {
return nil, nil, nil, fmt.Errorf("reading current key data: %v", err)
}
// For now, authorised keys are global, common to all users.
currentKeys = ssh.SplitAuthorisedKeys(cfg.AuthorizedKeys())
// Make two maps that index keys by fingerprint and by comment for fast
// lookup of keys to delete which may be given as either.
byFingerprint = make(map[string]string)
byComment = make(map[string]string)
for _, key := range currentKeys {
fingerprint, comment, err := ssh.KeyFingerprint(key)
if err != nil {
logger.Debugf("keeping unrecognised existing ssh key %q: %v", key, err)
continue
}
byFingerprint[fingerprint] = key
if comment != "" {
byComment[comment] = key
}
}
return currentKeys, byFingerprint, byComment, nil
} | [
"func",
"(",
"api",
"*",
"KeyManagerAPI",
")",
"currentKeyDataForDelete",
"(",
")",
"(",
"currentKeys",
"[",
"]",
"string",
",",
"byFingerprint",
"map",
"[",
"string",
"]",
"string",
",",
"byComment",
"map",
"[",
"string",
"]",
"string",
",",
"err",
"error... | // currentKeyDataForDelete gathers data used when deleting ssh keys. | [
"currentKeyDataForDelete",
"gathers",
"data",
"used",
"when",
"deleting",
"ssh",
"keys",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/keymanager/keymanager.go#L343-L369 | train |
juju/juju | apiserver/facades/client/keymanager/keymanager.go | DeleteKeys | func (api *KeyManagerAPI) DeleteKeys(arg params.ModifyUserSSHKeys) (params.ErrorResults, error) {
if err := api.check.ChangeAllowed(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(arg.Keys)),
}
if len(arg.Keys) == 0 {
return result, nil
}
if err := api.checkCanWrite(arg.User); err != nil {
return params.ErrorResults{}, common.ServerError(err)
}
allKeys, byFingerprint, byComment, err := api.currentKeyDataForDelete()
if err != nil {
return params.ErrorResults{}, common.ServerError(fmt.Errorf("reading current key data: %v", err))
}
// Record the keys to be deleted in the second pass.
keysToDelete := make(set.Strings)
// Find the keys corresponding to the specified key fingerprints or comments.
for i, keyId := range arg.Keys {
// Is given keyId a fingerprint?
key, ok := byFingerprint[keyId]
if ok {
keysToDelete.Add(key)
continue
}
// Not a fingerprint, is it a comment?
key, ok = byComment[keyId]
if ok {
if internalComments.Contains(keyId) {
result.Results[i].Error = common.ServerError(fmt.Errorf("may not delete internal key: %s", keyId))
continue
}
keysToDelete.Add(key)
continue
}
result.Results[i].Error = common.ServerError(fmt.Errorf("invalid ssh key: %s", keyId))
}
var keysToWrite []string
// Add back only the keys that are not deleted, preserving the order.
for _, key := range allKeys {
if !keysToDelete.Contains(key) {
keysToWrite = append(keysToWrite, key)
}
}
if len(keysToWrite) == 0 {
return params.ErrorResults{}, common.ServerError(fmt.Errorf("cannot delete all keys"))
}
err = api.writeSSHKeys(keysToWrite)
if err != nil {
return params.ErrorResults{}, common.ServerError(err)
}
return result, nil
} | go | func (api *KeyManagerAPI) DeleteKeys(arg params.ModifyUserSSHKeys) (params.ErrorResults, error) {
if err := api.check.ChangeAllowed(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(arg.Keys)),
}
if len(arg.Keys) == 0 {
return result, nil
}
if err := api.checkCanWrite(arg.User); err != nil {
return params.ErrorResults{}, common.ServerError(err)
}
allKeys, byFingerprint, byComment, err := api.currentKeyDataForDelete()
if err != nil {
return params.ErrorResults{}, common.ServerError(fmt.Errorf("reading current key data: %v", err))
}
// Record the keys to be deleted in the second pass.
keysToDelete := make(set.Strings)
// Find the keys corresponding to the specified key fingerprints or comments.
for i, keyId := range arg.Keys {
// Is given keyId a fingerprint?
key, ok := byFingerprint[keyId]
if ok {
keysToDelete.Add(key)
continue
}
// Not a fingerprint, is it a comment?
key, ok = byComment[keyId]
if ok {
if internalComments.Contains(keyId) {
result.Results[i].Error = common.ServerError(fmt.Errorf("may not delete internal key: %s", keyId))
continue
}
keysToDelete.Add(key)
continue
}
result.Results[i].Error = common.ServerError(fmt.Errorf("invalid ssh key: %s", keyId))
}
var keysToWrite []string
// Add back only the keys that are not deleted, preserving the order.
for _, key := range allKeys {
if !keysToDelete.Contains(key) {
keysToWrite = append(keysToWrite, key)
}
}
if len(keysToWrite) == 0 {
return params.ErrorResults{}, common.ServerError(fmt.Errorf("cannot delete all keys"))
}
err = api.writeSSHKeys(keysToWrite)
if err != nil {
return params.ErrorResults{}, common.ServerError(err)
}
return result, nil
} | [
"func",
"(",
"api",
"*",
"KeyManagerAPI",
")",
"DeleteKeys",
"(",
"arg",
"params",
".",
"ModifyUserSSHKeys",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"if",
"err",
":=",
"api",
".",
"check",
".",
"ChangeAllowed",
"(",
")",
";",
"... | // DeleteKeys deletes the authorised ssh keys for the specified user. | [
"DeleteKeys",
"deletes",
"the",
"authorised",
"ssh",
"keys",
"for",
"the",
"specified",
"user",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/keymanager/keymanager.go#L372-L434 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | NewFacadeV2 | func NewFacadeV2(context facade.Context) (*CloudAPIV2, error) {
v3, err := NewFacadeV3(context)
if err != nil {
return nil, err
}
return &CloudAPIV2{v3}, nil
} | go | func NewFacadeV2(context facade.Context) (*CloudAPIV2, error) {
v3, err := NewFacadeV3(context)
if err != nil {
return nil, err
}
return &CloudAPIV2{v3}, nil
} | [
"func",
"NewFacadeV2",
"(",
"context",
"facade",
".",
"Context",
")",
"(",
"*",
"CloudAPIV2",
",",
"error",
")",
"{",
"v3",
",",
"err",
":=",
"NewFacadeV3",
"(",
"context",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
... | // NewFacadeV2 is used for API registration. | [
"NewFacadeV2",
"is",
"used",
"for",
"API",
"registration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L177-L183 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | NewCloudAPI | func NewCloudAPI(backend, ctlrBackend Backend, pool ModelPoolBackend, authorizer facade.Authorizer, callCtx environscontext.ProviderCallContext) (*CloudAPI, error) {
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
authUser, _ := authorizer.GetAuthTag().(names.UserTag)
getUserAuthFunc := func() (common.AuthFunc, error) {
isAdmin, err := authorizer.HasPermission(permission.SuperuserAccess, backend.ControllerTag())
if err != nil && !errors.IsNotFound(err) {
return nil, err
}
return func(tag names.Tag) bool {
userTag, ok := tag.(names.UserTag)
if !ok {
return false
}
return isAdmin || userTag == authUser
}, nil
}
return &CloudAPI{
backend: backend,
ctlrBackend: ctlrBackend,
authorizer: authorizer,
getCredentialsAuthFunc: getUserAuthFunc,
apiUser: authUser,
callContext: callCtx,
pool: pool,
}, nil
} | go | func NewCloudAPI(backend, ctlrBackend Backend, pool ModelPoolBackend, authorizer facade.Authorizer, callCtx environscontext.ProviderCallContext) (*CloudAPI, error) {
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
authUser, _ := authorizer.GetAuthTag().(names.UserTag)
getUserAuthFunc := func() (common.AuthFunc, error) {
isAdmin, err := authorizer.HasPermission(permission.SuperuserAccess, backend.ControllerTag())
if err != nil && !errors.IsNotFound(err) {
return nil, err
}
return func(tag names.Tag) bool {
userTag, ok := tag.(names.UserTag)
if !ok {
return false
}
return isAdmin || userTag == authUser
}, nil
}
return &CloudAPI{
backend: backend,
ctlrBackend: ctlrBackend,
authorizer: authorizer,
getCredentialsAuthFunc: getUserAuthFunc,
apiUser: authUser,
callContext: callCtx,
pool: pool,
}, nil
} | [
"func",
"NewCloudAPI",
"(",
"backend",
",",
"ctlrBackend",
"Backend",
",",
"pool",
"ModelPoolBackend",
",",
"authorizer",
"facade",
".",
"Authorizer",
",",
"callCtx",
"environscontext",
".",
"ProviderCallContext",
")",
"(",
"*",
"CloudAPI",
",",
"error",
")",
"{... | // NewCloudAPI creates a new API server endpoint for managing the controller's
// cloud definition and cloud credentials. | [
"NewCloudAPI",
"creates",
"a",
"new",
"API",
"server",
"endpoint",
"for",
"managing",
"the",
"controller",
"s",
"cloud",
"definition",
"and",
"cloud",
"credentials",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L196-L224 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | Clouds | func (api *CloudAPI) Clouds() (params.CloudsResult, error) {
var result params.CloudsResult
clouds, err := api.backend.Clouds()
if err != nil {
return result, err
}
isAdmin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.ctlrBackend.ControllerTag())
if err != nil && !errors.IsNotFound(err) {
return result, errors.Trace(err)
}
result.Clouds = make(map[string]params.Cloud)
for tag, aCloud := range clouds {
// Ensure user has permission to see the cloud.
if !isAdmin {
canAccess, err := api.canAccessCloud(tag.Id(), api.apiUser, permission.AddModelAccess)
if err != nil {
return result, err
}
if !canAccess {
continue
}
}
paramsCloud := common.CloudToParams(aCloud)
result.Clouds[tag.String()] = paramsCloud
}
return result, nil
} | go | func (api *CloudAPI) Clouds() (params.CloudsResult, error) {
var result params.CloudsResult
clouds, err := api.backend.Clouds()
if err != nil {
return result, err
}
isAdmin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.ctlrBackend.ControllerTag())
if err != nil && !errors.IsNotFound(err) {
return result, errors.Trace(err)
}
result.Clouds = make(map[string]params.Cloud)
for tag, aCloud := range clouds {
// Ensure user has permission to see the cloud.
if !isAdmin {
canAccess, err := api.canAccessCloud(tag.Id(), api.apiUser, permission.AddModelAccess)
if err != nil {
return result, err
}
if !canAccess {
continue
}
}
paramsCloud := common.CloudToParams(aCloud)
result.Clouds[tag.String()] = paramsCloud
}
return result, nil
} | [
"func",
"(",
"api",
"*",
"CloudAPI",
")",
"Clouds",
"(",
")",
"(",
"params",
".",
"CloudsResult",
",",
"error",
")",
"{",
"var",
"result",
"params",
".",
"CloudsResult",
"\n",
"clouds",
",",
"err",
":=",
"api",
".",
"backend",
".",
"Clouds",
"(",
")"... | // Clouds returns the definitions of all clouds supported by the controller
// that the logged in user can see. | [
"Clouds",
"returns",
"the",
"definitions",
"of",
"all",
"clouds",
"supported",
"by",
"the",
"controller",
"that",
"the",
"logged",
"in",
"user",
"can",
"see",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L239-L265 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | Cloud | func (api *CloudAPI) Cloud(args params.Entities) (params.CloudResults, error) {
results := params.CloudResults{
Results: make([]params.CloudResult, len(args.Entities)),
}
isAdmin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.ctlrBackend.ControllerTag())
if err != nil && !errors.IsNotFound(err) {
return results, errors.Trace(err)
}
one := func(arg params.Entity) (*params.Cloud, error) {
tag, err := names.ParseCloudTag(arg.Tag)
if err != nil {
return nil, err
}
// Ensure user has permission to see the cloud.
if !isAdmin {
canAccess, err := api.canAccessCloud(tag.Id(), api.apiUser, permission.AddModelAccess)
if err != nil {
return nil, err
}
if !canAccess {
return nil, errors.NotFoundf("cloud %q", tag.Id())
}
}
aCloud, err := api.backend.Cloud(tag.Id())
if err != nil {
return nil, err
}
paramsCloud := common.CloudToParams(aCloud)
return ¶msCloud, nil
}
for i, arg := range args.Entities {
aCloud, err := one(arg)
if err != nil {
results.Results[i].Error = common.ServerError(err)
} else {
results.Results[i].Cloud = aCloud
}
}
return results, nil
} | go | func (api *CloudAPI) Cloud(args params.Entities) (params.CloudResults, error) {
results := params.CloudResults{
Results: make([]params.CloudResult, len(args.Entities)),
}
isAdmin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.ctlrBackend.ControllerTag())
if err != nil && !errors.IsNotFound(err) {
return results, errors.Trace(err)
}
one := func(arg params.Entity) (*params.Cloud, error) {
tag, err := names.ParseCloudTag(arg.Tag)
if err != nil {
return nil, err
}
// Ensure user has permission to see the cloud.
if !isAdmin {
canAccess, err := api.canAccessCloud(tag.Id(), api.apiUser, permission.AddModelAccess)
if err != nil {
return nil, err
}
if !canAccess {
return nil, errors.NotFoundf("cloud %q", tag.Id())
}
}
aCloud, err := api.backend.Cloud(tag.Id())
if err != nil {
return nil, err
}
paramsCloud := common.CloudToParams(aCloud)
return ¶msCloud, nil
}
for i, arg := range args.Entities {
aCloud, err := one(arg)
if err != nil {
results.Results[i].Error = common.ServerError(err)
} else {
results.Results[i].Cloud = aCloud
}
}
return results, nil
} | [
"func",
"(",
"api",
"*",
"CloudAPI",
")",
"Cloud",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"CloudResults",
",",
"error",
")",
"{",
"results",
":=",
"params",
".",
"CloudResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"p... | // Cloud returns the cloud definitions for the specified clouds. | [
"Cloud",
"returns",
"the",
"cloud",
"definitions",
"for",
"the",
"specified",
"clouds",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L268-L307 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | CloudInfo | func (api *CloudAPI) CloudInfo(args params.Entities) (params.CloudInfoResults, error) {
results := params.CloudInfoResults{
Results: make([]params.CloudInfoResult, len(args.Entities)),
}
oneCloudInfo := func(arg params.Entity) (*params.CloudInfo, error) {
tag, err := names.ParseCloudTag(arg.Tag)
if err != nil {
return nil, errors.Trace(err)
}
return api.getCloudInfo(tag)
}
for i, arg := range args.Entities {
cloudInfo, err := oneCloudInfo(arg)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = cloudInfo
}
return results, nil
} | go | func (api *CloudAPI) CloudInfo(args params.Entities) (params.CloudInfoResults, error) {
results := params.CloudInfoResults{
Results: make([]params.CloudInfoResult, len(args.Entities)),
}
oneCloudInfo := func(arg params.Entity) (*params.CloudInfo, error) {
tag, err := names.ParseCloudTag(arg.Tag)
if err != nil {
return nil, errors.Trace(err)
}
return api.getCloudInfo(tag)
}
for i, arg := range args.Entities {
cloudInfo, err := oneCloudInfo(arg)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = cloudInfo
}
return results, nil
} | [
"func",
"(",
"api",
"*",
"CloudAPI",
")",
"CloudInfo",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"CloudInfoResults",
",",
"error",
")",
"{",
"results",
":=",
"params",
".",
"CloudInfoResults",
"{",
"Results",
":",
"make",
"(",
"[",... | // CloudInfo returns information about the specified clouds. | [
"CloudInfo",
"returns",
"information",
"about",
"the",
"specified",
"clouds",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L310-L332 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | DefaultCloud | func (api *CloudAPIV4) DefaultCloud() (params.StringResult, error) {
controllerModel, err := api.ctlrBackend.Model()
if err != nil {
return params.StringResult{}, err
}
return params.StringResult{
Result: names.NewCloudTag(controllerModel.Cloud()).String(),
}, nil
} | go | func (api *CloudAPIV4) DefaultCloud() (params.StringResult, error) {
controllerModel, err := api.ctlrBackend.Model()
if err != nil {
return params.StringResult{}, err
}
return params.StringResult{
Result: names.NewCloudTag(controllerModel.Cloud()).String(),
}, nil
} | [
"func",
"(",
"api",
"*",
"CloudAPIV4",
")",
"DefaultCloud",
"(",
")",
"(",
"params",
".",
"StringResult",
",",
"error",
")",
"{",
"controllerModel",
",",
"err",
":=",
"api",
".",
"ctlrBackend",
".",
"Model",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
... | // DefaultCloud returns the tag of the cloud that models will be
// created in by default. | [
"DefaultCloud",
"returns",
"the",
"tag",
"of",
"the",
"cloud",
"that",
"models",
"will",
"be",
"created",
"in",
"by",
"default",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L454-L462 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | UserCredentials | func (api *CloudAPI) UserCredentials(args params.UserClouds) (params.StringsResults, error) {
results := params.StringsResults{
Results: make([]params.StringsResult, len(args.UserClouds)),
}
authFunc, err := api.getCredentialsAuthFunc()
if err != nil {
return results, err
}
for i, arg := range args.UserClouds {
userTag, err := names.ParseUserTag(arg.UserTag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
if !authFunc(userTag) {
results.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
cloudTag, err := names.ParseCloudTag(arg.CloudTag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
cloudCredentials, err := api.backend.CloudCredentials(userTag, cloudTag.Id())
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
out := make([]string, 0, len(cloudCredentials))
for tagId := range cloudCredentials {
if !names.IsValidCloudCredential(tagId) {
results.Results[i].Error = common.ServerError(errors.NotValidf("cloud credential ID %q", tagId))
continue
}
out = append(out, names.NewCloudCredentialTag(tagId).String())
}
results.Results[i].Result = out
}
return results, nil
} | go | func (api *CloudAPI) UserCredentials(args params.UserClouds) (params.StringsResults, error) {
results := params.StringsResults{
Results: make([]params.StringsResult, len(args.UserClouds)),
}
authFunc, err := api.getCredentialsAuthFunc()
if err != nil {
return results, err
}
for i, arg := range args.UserClouds {
userTag, err := names.ParseUserTag(arg.UserTag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
if !authFunc(userTag) {
results.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
cloudTag, err := names.ParseCloudTag(arg.CloudTag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
cloudCredentials, err := api.backend.CloudCredentials(userTag, cloudTag.Id())
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
out := make([]string, 0, len(cloudCredentials))
for tagId := range cloudCredentials {
if !names.IsValidCloudCredential(tagId) {
results.Results[i].Error = common.ServerError(errors.NotValidf("cloud credential ID %q", tagId))
continue
}
out = append(out, names.NewCloudCredentialTag(tagId).String())
}
results.Results[i].Result = out
}
return results, nil
} | [
"func",
"(",
"api",
"*",
"CloudAPI",
")",
"UserCredentials",
"(",
"args",
"params",
".",
"UserClouds",
")",
"(",
"params",
".",
"StringsResults",
",",
"error",
")",
"{",
"results",
":=",
"params",
".",
"StringsResults",
"{",
"Results",
":",
"make",
"(",
... | // UserCredentials returns the cloud credentials for a set of users. | [
"UserCredentials",
"returns",
"the",
"cloud",
"credentials",
"for",
"a",
"set",
"of",
"users",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L465-L504 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | CheckCredentialsModels | func (api *CloudAPI) CheckCredentialsModels(args params.TaggedCredentials) (params.UpdateCredentialResults, error) {
return api.commonUpdateCredentials(false, false, args)
} | go | func (api *CloudAPI) CheckCredentialsModels(args params.TaggedCredentials) (params.UpdateCredentialResults, error) {
return api.commonUpdateCredentials(false, false, args)
} | [
"func",
"(",
"api",
"*",
"CloudAPI",
")",
"CheckCredentialsModels",
"(",
"args",
"params",
".",
"TaggedCredentials",
")",
"(",
"params",
".",
"UpdateCredentialResults",
",",
"error",
")",
"{",
"return",
"api",
".",
"commonUpdateCredentials",
"(",
"false",
",",
... | // CheckCredentialsModels validates supplied cloud credentials' content against
// models that currently use these credentials.
// If there are any models that are using a credential and these models or their
// cloud instances are not going to be accessible with corresponding credential,
// there will be detailed validation errors per model. | [
"CheckCredentialsModels",
"validates",
"supplied",
"cloud",
"credentials",
"content",
"against",
"models",
"that",
"currently",
"use",
"these",
"credentials",
".",
"If",
"there",
"are",
"any",
"models",
"that",
"are",
"using",
"a",
"credential",
"and",
"these",
"m... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L549-L551 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | UpdateCredentialsCheckModels | func (api *CloudAPI) UpdateCredentialsCheckModels(args params.UpdateCredentialArgs) (params.UpdateCredentialResults, error) {
return api.commonUpdateCredentials(true, args.Force, params.TaggedCredentials{args.Credentials})
} | go | func (api *CloudAPI) UpdateCredentialsCheckModels(args params.UpdateCredentialArgs) (params.UpdateCredentialResults, error) {
return api.commonUpdateCredentials(true, args.Force, params.TaggedCredentials{args.Credentials})
} | [
"func",
"(",
"api",
"*",
"CloudAPI",
")",
"UpdateCredentialsCheckModels",
"(",
"args",
"params",
".",
"UpdateCredentialArgs",
")",
"(",
"params",
".",
"UpdateCredentialResults",
",",
"error",
")",
"{",
"return",
"api",
".",
"commonUpdateCredentials",
"(",
"true",
... | // UpdateCredentialsCheckModels updates a set of cloud credentials' content.
// If there are any models that are using a credential and these models
// are not going to be visible with updated credential content,
// there will be detailed validation errors per model.
// Controller admins can 'force' an update of the credential
// regardless of whether it is deemed valid or not. | [
"UpdateCredentialsCheckModels",
"updates",
"a",
"set",
"of",
"cloud",
"credentials",
"content",
".",
"If",
"there",
"are",
"any",
"models",
"that",
"are",
"using",
"a",
"credential",
"and",
"these",
"models",
"are",
"not",
"going",
"to",
"be",
"visible",
"with... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L559-L561 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | RevokeCredentialsCheckModels | func (api *CloudAPI) RevokeCredentialsCheckModels(args params.RevokeCredentialArgs) (params.ErrorResults, error) {
// TODO (anastasiamac 2018-11-13) the behavior here needs to be changed to performed promised models checks and authorise use of force.
results := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Credentials)),
}
authFunc, err := api.getCredentialsAuthFunc()
if err != nil {
return results, err
}
opMessage := func(force bool) string {
if force {
return "will be deleted but"
}
return "cannot be deleted as"
}
for i, arg := range args.Credentials {
tag, err := names.ParseCloudCredentialTag(arg.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
// NOTE(axw) if we add ACLs for cloud credentials, we'll need
// to change this auth check.
if !authFunc(tag.Owner()) {
results.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
models, err := api.credentialModels(tag)
if err != nil {
if !arg.Force {
// Could not determine if credential has models - do not continue updating this credential...
results.Results[i].Error = common.ServerError(err)
continue
}
logger.Warningf("could not get models that use credential %v: %v", tag, err)
}
if len(models) != 0 {
logger.Warningf("credential %v %v it is used by model%v",
tag,
opMessage(arg.Force),
modelsPretty(models),
)
if !arg.Force {
// Some models still use this credential - do not delete this credential...
results.Results[i].Error = common.ServerError(errors.Errorf("cannot delete credential %v: it is still used by %d model%v", tag, len(models), plural(len(models))))
continue
}
}
if err := api.backend.RemoveCloudCredential(tag); err != nil {
results.Results[i].Error = common.ServerError(err)
}
}
return results, nil
} | go | func (api *CloudAPI) RevokeCredentialsCheckModels(args params.RevokeCredentialArgs) (params.ErrorResults, error) {
// TODO (anastasiamac 2018-11-13) the behavior here needs to be changed to performed promised models checks and authorise use of force.
results := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Credentials)),
}
authFunc, err := api.getCredentialsAuthFunc()
if err != nil {
return results, err
}
opMessage := func(force bool) string {
if force {
return "will be deleted but"
}
return "cannot be deleted as"
}
for i, arg := range args.Credentials {
tag, err := names.ParseCloudCredentialTag(arg.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
// NOTE(axw) if we add ACLs for cloud credentials, we'll need
// to change this auth check.
if !authFunc(tag.Owner()) {
results.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
models, err := api.credentialModels(tag)
if err != nil {
if !arg.Force {
// Could not determine if credential has models - do not continue updating this credential...
results.Results[i].Error = common.ServerError(err)
continue
}
logger.Warningf("could not get models that use credential %v: %v", tag, err)
}
if len(models) != 0 {
logger.Warningf("credential %v %v it is used by model%v",
tag,
opMessage(arg.Force),
modelsPretty(models),
)
if !arg.Force {
// Some models still use this credential - do not delete this credential...
results.Results[i].Error = common.ServerError(errors.Errorf("cannot delete credential %v: it is still used by %d model%v", tag, len(models), plural(len(models))))
continue
}
}
if err := api.backend.RemoveCloudCredential(tag); err != nil {
results.Results[i].Error = common.ServerError(err)
}
}
return results, nil
} | [
"func",
"(",
"api",
"*",
"CloudAPI",
")",
"RevokeCredentialsCheckModels",
"(",
"args",
"params",
".",
"RevokeCredentialArgs",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"// TODO (anastasiamac 2018-11-13) the behavior here needs to be changed to perform... | // RevokeCredentialsCheckModels revokes a set of cloud credentials.
// If the credentials are used by any of the models, the credential deletion will be aborted.
// If credential-in-use needs to be revoked nonetheless, this method allows the use of force. | [
"RevokeCredentialsCheckModels",
"revokes",
"a",
"set",
"of",
"cloud",
"credentials",
".",
"If",
"the",
"credentials",
"are",
"used",
"by",
"any",
"of",
"the",
"models",
"the",
"credential",
"deletion",
"will",
"be",
"aborted",
".",
"If",
"credential",
"-",
"in... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L825-L882 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | AddCloud | func (api *CloudAPI) AddCloud(cloudArgs params.AddCloudArgs) error {
isAdmin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.ctlrBackend.ControllerTag())
if err != nil && !errors.IsNotFound(err) {
return errors.Trace(err)
} else if !isAdmin {
return common.ServerError(common.ErrPerm)
}
err = api.backend.AddCloud(common.CloudFromParams(cloudArgs.Name, cloudArgs.Cloud), api.apiUser.Name())
return errors.Trace(err)
} | go | func (api *CloudAPI) AddCloud(cloudArgs params.AddCloudArgs) error {
isAdmin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.ctlrBackend.ControllerTag())
if err != nil && !errors.IsNotFound(err) {
return errors.Trace(err)
} else if !isAdmin {
return common.ServerError(common.ErrPerm)
}
err = api.backend.AddCloud(common.CloudFromParams(cloudArgs.Name, cloudArgs.Cloud), api.apiUser.Name())
return errors.Trace(err)
} | [
"func",
"(",
"api",
"*",
"CloudAPI",
")",
"AddCloud",
"(",
"cloudArgs",
"params",
".",
"AddCloudArgs",
")",
"error",
"{",
"isAdmin",
",",
"err",
":=",
"api",
".",
"authorizer",
".",
"HasPermission",
"(",
"permission",
".",
"SuperuserAccess",
",",
"api",
".... | // AddCloud adds a new cloud, different from the one managed by the controller. | [
"AddCloud",
"adds",
"a",
"new",
"cloud",
"different",
"from",
"the",
"one",
"managed",
"by",
"the",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L963-L972 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | UpdateCloud | func (api *CloudAPI) UpdateCloud(cloudArgs params.UpdateCloudArgs) (params.ErrorResults, error) {
results := params.ErrorResults{
Results: make([]params.ErrorResult, len(cloudArgs.Clouds)),
}
isAdmin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.ctlrBackend.ControllerTag())
if err != nil && !errors.IsNotFound(err) {
return results, errors.Trace(err)
} else if !isAdmin {
return results, common.ServerError(common.ErrPerm)
}
for i, cloud := range cloudArgs.Clouds {
err := api.backend.UpdateCloud(common.CloudFromParams(cloud.Name, cloud.Cloud))
results.Results[i].Error = common.ServerError(err)
}
return results, nil
} | go | func (api *CloudAPI) UpdateCloud(cloudArgs params.UpdateCloudArgs) (params.ErrorResults, error) {
results := params.ErrorResults{
Results: make([]params.ErrorResult, len(cloudArgs.Clouds)),
}
isAdmin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.ctlrBackend.ControllerTag())
if err != nil && !errors.IsNotFound(err) {
return results, errors.Trace(err)
} else if !isAdmin {
return results, common.ServerError(common.ErrPerm)
}
for i, cloud := range cloudArgs.Clouds {
err := api.backend.UpdateCloud(common.CloudFromParams(cloud.Name, cloud.Cloud))
results.Results[i].Error = common.ServerError(err)
}
return results, nil
} | [
"func",
"(",
"api",
"*",
"CloudAPI",
")",
"UpdateCloud",
"(",
"cloudArgs",
"params",
".",
"UpdateCloudArgs",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"results",
":=",
"params",
".",
"ErrorResults",
"{",
"Results",
":",
"make",
"(",
... | // UpdateCloud updates an existing cloud that the controller knows about. | [
"UpdateCloud",
"updates",
"an",
"existing",
"cloud",
"that",
"the",
"controller",
"knows",
"about",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L975-L990 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | ModifyCloudAccess | func (c *CloudAPI) ModifyCloudAccess(args params.ModifyCloudAccessRequest) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Changes)),
}
if len(args.Changes) == 0 {
return result, nil
}
for i, arg := range args.Changes {
cloudTag, err := names.ParseCloudTag(arg.CloudTag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
_, err = c.backend.Cloud(cloudTag.Id())
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if c.apiUser.String() == arg.UserTag {
result.Results[i].Error = common.ServerError(errors.New("cannot change your own cloud access"))
continue
}
isAdmin, err := c.authorizer.HasPermission(permission.SuperuserAccess, c.backend.ControllerTag())
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if !isAdmin {
callerAccess, err := c.backend.GetCloudAccess(cloudTag.Id(), c.apiUser)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if callerAccess != permission.AdminAccess {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
}
cloudAccess := permission.Access(arg.Access)
if err := permission.ValidateCloudAccess(cloudAccess); err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
targetUserTag, err := names.ParseUserTag(arg.UserTag)
if err != nil {
result.Results[i].Error = common.ServerError(errors.Annotate(err, "could not modify cloud access"))
continue
}
result.Results[i].Error = common.ServerError(
ChangeCloudAccess(c.backend, cloudTag.Id(), targetUserTag, arg.Action, cloudAccess))
}
return result, nil
} | go | func (c *CloudAPI) ModifyCloudAccess(args params.ModifyCloudAccessRequest) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Changes)),
}
if len(args.Changes) == 0 {
return result, nil
}
for i, arg := range args.Changes {
cloudTag, err := names.ParseCloudTag(arg.CloudTag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
_, err = c.backend.Cloud(cloudTag.Id())
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if c.apiUser.String() == arg.UserTag {
result.Results[i].Error = common.ServerError(errors.New("cannot change your own cloud access"))
continue
}
isAdmin, err := c.authorizer.HasPermission(permission.SuperuserAccess, c.backend.ControllerTag())
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if !isAdmin {
callerAccess, err := c.backend.GetCloudAccess(cloudTag.Id(), c.apiUser)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if callerAccess != permission.AdminAccess {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
}
cloudAccess := permission.Access(arg.Access)
if err := permission.ValidateCloudAccess(cloudAccess); err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
targetUserTag, err := names.ParseUserTag(arg.UserTag)
if err != nil {
result.Results[i].Error = common.ServerError(errors.Annotate(err, "could not modify cloud access"))
continue
}
result.Results[i].Error = common.ServerError(
ChangeCloudAccess(c.backend, cloudTag.Id(), targetUserTag, arg.Action, cloudAccess))
}
return result, nil
} | [
"func",
"(",
"c",
"*",
"CloudAPI",
")",
"ModifyCloudAccess",
"(",
"args",
"params",
".",
"ModifyCloudAccessRequest",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"ErrorResults",
"{",
"Results",
":",
"make",
... | // ModifyCloudAccess changes the model access granted to users. | [
"ModifyCloudAccess",
"changes",
"the",
"model",
"access",
"granted",
"to",
"users",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L1146-L1203 | train |
juju/juju | apiserver/facades/client/cloud/cloud.go | ChangeCloudAccess | func ChangeCloudAccess(backend Backend, cloud string, targetUserTag names.UserTag, action params.CloudAction, access permission.Access) error {
switch action {
case params.GrantCloudAccess:
err := grantCloudAccess(backend, cloud, targetUserTag, access)
if err != nil {
return errors.Annotate(err, "could not grant cloud access")
}
return nil
case params.RevokeCloudAccess:
return revokeCloudAccess(backend, cloud, targetUserTag, access)
default:
return errors.Errorf("unknown action %q", action)
}
} | go | func ChangeCloudAccess(backend Backend, cloud string, targetUserTag names.UserTag, action params.CloudAction, access permission.Access) error {
switch action {
case params.GrantCloudAccess:
err := grantCloudAccess(backend, cloud, targetUserTag, access)
if err != nil {
return errors.Annotate(err, "could not grant cloud access")
}
return nil
case params.RevokeCloudAccess:
return revokeCloudAccess(backend, cloud, targetUserTag, access)
default:
return errors.Errorf("unknown action %q", action)
}
} | [
"func",
"ChangeCloudAccess",
"(",
"backend",
"Backend",
",",
"cloud",
"string",
",",
"targetUserTag",
"names",
".",
"UserTag",
",",
"action",
"params",
".",
"CloudAction",
",",
"access",
"permission",
".",
"Access",
")",
"error",
"{",
"switch",
"action",
"{",
... | // ChangeCloudAccess performs the requested access grant or revoke action for the
// specified user on the cloud. | [
"ChangeCloudAccess",
"performs",
"the",
"requested",
"access",
"grant",
"or",
"revoke",
"action",
"for",
"the",
"specified",
"user",
"on",
"the",
"cloud",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L1207-L1220 | train |
juju/juju | worker/leadership/manifold.go | Manifold | func Manifold(config ManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{
config.AgentName,
config.APICallerName,
},
Start: startFunc(config),
Output: outputFunc,
}
} | go | func Manifold(config ManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{
config.AgentName,
config.APICallerName,
},
Start: startFunc(config),
Output: outputFunc,
}
} | [
"func",
"Manifold",
"(",
"config",
"ManifoldConfig",
")",
"dependency",
".",
"Manifold",
"{",
"return",
"dependency",
".",
"Manifold",
"{",
"Inputs",
":",
"[",
"]",
"string",
"{",
"config",
".",
"AgentName",
",",
"config",
".",
"APICallerName",
",",
"}",
"... | // Manifold returns a manifold whose worker wraps a Tracker working on behalf of
// the dependency identified by AgentName. | [
"Manifold",
"returns",
"a",
"manifold",
"whose",
"worker",
"wraps",
"a",
"Tracker",
"working",
"on",
"behalf",
"of",
"the",
"dependency",
"identified",
"by",
"AgentName",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/leadership/manifold.go#L32-L41 | train |
juju/juju | worker/leadership/manifold.go | startFunc | func startFunc(config ManifoldConfig) dependency.StartFunc {
return func(context dependency.Context) (worker.Worker, error) {
if config.Clock == nil {
return nil, errors.NotValidf("missing Clock")
}
var agent agent.Agent
if err := context.Get(config.AgentName, &agent); err != nil {
return nil, err
}
var apiCaller base.APICaller
if err := context.Get(config.APICallerName, &apiCaller); err != nil {
return nil, err
}
return NewManifoldWorker(agent, apiCaller, config.Clock, config.LeadershipGuarantee)
}
} | go | func startFunc(config ManifoldConfig) dependency.StartFunc {
return func(context dependency.Context) (worker.Worker, error) {
if config.Clock == nil {
return nil, errors.NotValidf("missing Clock")
}
var agent agent.Agent
if err := context.Get(config.AgentName, &agent); err != nil {
return nil, err
}
var apiCaller base.APICaller
if err := context.Get(config.APICallerName, &apiCaller); err != nil {
return nil, err
}
return NewManifoldWorker(agent, apiCaller, config.Clock, config.LeadershipGuarantee)
}
} | [
"func",
"startFunc",
"(",
"config",
"ManifoldConfig",
")",
"dependency",
".",
"StartFunc",
"{",
"return",
"func",
"(",
"context",
"dependency",
".",
"Context",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"if",
"config",
".",
"Clock",
"==",
... | // startFunc returns a StartFunc that creates a worker based on the manifolds
// named in the supplied config. | [
"startFunc",
"returns",
"a",
"StartFunc",
"that",
"creates",
"a",
"worker",
"based",
"on",
"the",
"manifolds",
"named",
"in",
"the",
"supplied",
"config",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/leadership/manifold.go#L45-L60 | train |
juju/juju | state/watcher.go | collect | func collect(one watcher.Change, more <-chan watcher.Change, stop <-chan struct{}) (map[interface{}]bool, bool) {
var count int
result := map[interface{}]bool{}
handle := func(ch watcher.Change) {
count++
result[ch.Id] = ch.Revno > 0
}
handle(one)
// TODO(fwereade): 2016-03-17 lp:1558657
timeout := time.After(10 * time.Millisecond)
for done := false; !done; {
select {
case <-stop:
return nil, false
case another := <-more:
handle(another)
case <-timeout:
done = true
}
}
watchLogger.Tracef("read %d events for %d documents", count, len(result))
return result, true
} | go | func collect(one watcher.Change, more <-chan watcher.Change, stop <-chan struct{}) (map[interface{}]bool, bool) {
var count int
result := map[interface{}]bool{}
handle := func(ch watcher.Change) {
count++
result[ch.Id] = ch.Revno > 0
}
handle(one)
// TODO(fwereade): 2016-03-17 lp:1558657
timeout := time.After(10 * time.Millisecond)
for done := false; !done; {
select {
case <-stop:
return nil, false
case another := <-more:
handle(another)
case <-timeout:
done = true
}
}
watchLogger.Tracef("read %d events for %d documents", count, len(result))
return result, true
} | [
"func",
"collect",
"(",
"one",
"watcher",
".",
"Change",
",",
"more",
"<-",
"chan",
"watcher",
".",
"Change",
",",
"stop",
"<-",
"chan",
"struct",
"{",
"}",
")",
"(",
"map",
"[",
"interface",
"{",
"}",
"]",
"bool",
",",
"bool",
")",
"{",
"var",
"... | // collect combines the effects of the one change, and any further changes read
// from more in the next 10ms. The result map describes the existence, or not,
// of every id observed to have changed. If a value is read from the supplied
// stop chan, collect returns false immediately. | [
"collect",
"combines",
"the",
"effects",
"of",
"the",
"one",
"change",
"and",
"any",
"further",
"changes",
"read",
"from",
"more",
"in",
"the",
"next",
"10ms",
".",
"The",
"result",
"map",
"describes",
"the",
"existence",
"or",
"not",
"of",
"every",
"id",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L140-L162 | train |
juju/juju | state/watcher.go | WatchModelLives | func (st *State) WatchModelLives() StringsWatcher {
return newLifecycleWatcher(st, modelsC, nil, nil, nil)
} | go | func (st *State) WatchModelLives() StringsWatcher {
return newLifecycleWatcher(st, modelsC, nil, nil, nil)
} | [
"func",
"(",
"st",
"*",
"State",
")",
"WatchModelLives",
"(",
")",
"StringsWatcher",
"{",
"return",
"newLifecycleWatcher",
"(",
"st",
",",
"modelsC",
",",
"nil",
",",
"nil",
",",
"nil",
")",
"\n",
"}"
] | // WatchModelLives returns a StringsWatcher that notifies of changes
// to any model life values. The watcher will not send any more events
// for a model after it has been observed to be Dead. | [
"WatchModelLives",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"any",
"model",
"life",
"values",
".",
"The",
"watcher",
"will",
"not",
"send",
"any",
"more",
"events",
"for",
"a",
"model",
"after",
"it",
"has",
"been",
"obser... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L220-L222 | train |
juju/juju | state/watcher.go | WatchMachineVolumes | func (sb *storageBackend) WatchMachineVolumes(m names.MachineTag) StringsWatcher {
return sb.watchHostStorage(m, volumesC)
} | go | func (sb *storageBackend) WatchMachineVolumes(m names.MachineTag) StringsWatcher {
return sb.watchHostStorage(m, volumesC)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"WatchMachineVolumes",
"(",
"m",
"names",
".",
"MachineTag",
")",
"StringsWatcher",
"{",
"return",
"sb",
".",
"watchHostStorage",
"(",
"m",
",",
"volumesC",
")",
"\n",
"}"
] | // WatchMachineVolumes returns a StringsWatcher that notifies of changes to
// the lifecycles of all volumes scoped to the specified machine. | [
"WatchMachineVolumes",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"lifecycles",
"of",
"all",
"volumes",
"scoped",
"to",
"the",
"specified",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L254-L256 | train |
juju/juju | state/watcher.go | WatchMachineFilesystems | func (sb *storageBackend) WatchMachineFilesystems(m names.MachineTag) StringsWatcher {
return sb.watchHostStorage(m, filesystemsC)
} | go | func (sb *storageBackend) WatchMachineFilesystems(m names.MachineTag) StringsWatcher {
return sb.watchHostStorage(m, filesystemsC)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"WatchMachineFilesystems",
"(",
"m",
"names",
".",
"MachineTag",
")",
"StringsWatcher",
"{",
"return",
"sb",
".",
"watchHostStorage",
"(",
"m",
",",
"filesystemsC",
")",
"\n",
"}"
] | // WatchMachineFilesystems returns a StringsWatcher that notifies of changes
// to the lifecycles of all filesystems scoped to the specified machine. | [
"WatchMachineFilesystems",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"lifecycles",
"of",
"all",
"filesystems",
"scoped",
"to",
"the",
"specified",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L260-L262 | train |
juju/juju | state/watcher.go | WatchUnitFilesystems | func (sb *storageBackend) WatchUnitFilesystems(app names.ApplicationTag) StringsWatcher {
return sb.watchHostStorage(app, filesystemsC)
} | go | func (sb *storageBackend) WatchUnitFilesystems(app names.ApplicationTag) StringsWatcher {
return sb.watchHostStorage(app, filesystemsC)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"WatchUnitFilesystems",
"(",
"app",
"names",
".",
"ApplicationTag",
")",
"StringsWatcher",
"{",
"return",
"sb",
".",
"watchHostStorage",
"(",
"app",
",",
"filesystemsC",
")",
"\n",
"}"
] | // WatchUnitFilesystems returns a StringsWatcher that notifies of changes
// to the lifecycles of all filesystems scoped to units of the specified application. | [
"WatchUnitFilesystems",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"lifecycles",
"of",
"all",
"filesystems",
"scoped",
"to",
"units",
"of",
"the",
"specified",
"application",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L266-L268 | train |
juju/juju | state/watcher.go | WatchMachineAttachmentsPlans | func (sb *storageBackend) WatchMachineAttachmentsPlans(m names.MachineTag) StringsWatcher {
return sb.watchMachineVolumeAttachmentPlans(m)
} | go | func (sb *storageBackend) WatchMachineAttachmentsPlans(m names.MachineTag) StringsWatcher {
return sb.watchMachineVolumeAttachmentPlans(m)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"WatchMachineAttachmentsPlans",
"(",
"m",
"names",
".",
"MachineTag",
")",
"StringsWatcher",
"{",
"return",
"sb",
".",
"watchMachineVolumeAttachmentPlans",
"(",
"m",
")",
"\n",
"}"
] | // WatchMachineAttachmentsPlans returns a StringsWatcher that notifies machine agents
// that a volume has been attached to their instance by the environment provider.
// This allows machine agents to do extra initialization to the volume, in cases
// such as iSCSI disks, or other disks that have similar requirements | [
"WatchMachineAttachmentsPlans",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"machine",
"agents",
"that",
"a",
"volume",
"has",
"been",
"attached",
"to",
"their",
"instance",
"by",
"the",
"environment",
"provider",
".",
"This",
"allows",
"machine",
"agents"... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L294-L296 | train |
juju/juju | state/watcher.go | WatchMachineVolumeAttachments | func (sb *storageBackend) WatchMachineVolumeAttachments(m names.MachineTag) StringsWatcher {
return sb.watchHostStorageAttachments(m, volumeAttachmentsC)
} | go | func (sb *storageBackend) WatchMachineVolumeAttachments(m names.MachineTag) StringsWatcher {
return sb.watchHostStorageAttachments(m, volumeAttachmentsC)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"WatchMachineVolumeAttachments",
"(",
"m",
"names",
".",
"MachineTag",
")",
"StringsWatcher",
"{",
"return",
"sb",
".",
"watchHostStorageAttachments",
"(",
"m",
",",
"volumeAttachmentsC",
")",
"\n",
"}"
] | // WatchMachineVolumeAttachments returns a StringsWatcher that notifies of
// changes to the lifecycles of all volume attachments related to the specified
// machine, for volumes scoped to the machine. | [
"WatchMachineVolumeAttachments",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"lifecycles",
"of",
"all",
"volume",
"attachments",
"related",
"to",
"the",
"specified",
"machine",
"for",
"volumes",
"scoped",
"to",
"the",
"machine... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L348-L350 | train |
juju/juju | state/watcher.go | WatchMachineFilesystemAttachments | func (sb *storageBackend) WatchMachineFilesystemAttachments(m names.MachineTag) StringsWatcher {
return sb.watchHostStorageAttachments(m, filesystemAttachmentsC)
} | go | func (sb *storageBackend) WatchMachineFilesystemAttachments(m names.MachineTag) StringsWatcher {
return sb.watchHostStorageAttachments(m, filesystemAttachmentsC)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"WatchMachineFilesystemAttachments",
"(",
"m",
"names",
".",
"MachineTag",
")",
"StringsWatcher",
"{",
"return",
"sb",
".",
"watchHostStorageAttachments",
"(",
"m",
",",
"filesystemAttachmentsC",
")",
"\n",
"}"
] | // WatchMachineFilesystemAttachments returns a StringsWatcher that notifies of
// changes to the lifecycles of all filesystem attachments related to the specified
// machine, for filesystems scoped to the machine. | [
"WatchMachineFilesystemAttachments",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"lifecycles",
"of",
"all",
"filesystem",
"attachments",
"related",
"to",
"the",
"specified",
"machine",
"for",
"filesystems",
"scoped",
"to",
"the"... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L355-L357 | train |
juju/juju | state/watcher.go | WatchUnitFilesystemAttachments | func (sb *storageBackend) WatchUnitFilesystemAttachments(app names.ApplicationTag) StringsWatcher {
return sb.watchHostStorageAttachments(app, filesystemAttachmentsC)
} | go | func (sb *storageBackend) WatchUnitFilesystemAttachments(app names.ApplicationTag) StringsWatcher {
return sb.watchHostStorageAttachments(app, filesystemAttachmentsC)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"WatchUnitFilesystemAttachments",
"(",
"app",
"names",
".",
"ApplicationTag",
")",
"StringsWatcher",
"{",
"return",
"sb",
".",
"watchHostStorageAttachments",
"(",
"app",
",",
"filesystemAttachmentsC",
")",
"\n",
"}"
] | // WatchUnitFilesystemAttachments returns a StringsWatcher that notifies of
// changes to the lifecycles of all filesystem attachments related to the specified
// application's units, for filesystems scoped to the application's units. | [
"WatchUnitFilesystemAttachments",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"lifecycles",
"of",
"all",
"filesystem",
"attachments",
"related",
"to",
"the",
"specified",
"application",
"s",
"units",
"for",
"filesystems",
"scope... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L370-L372 | train |
juju/juju | state/watcher.go | WatchApplications | func (st *State) WatchApplications() StringsWatcher {
return newLifecycleWatcher(st, applicationsC, nil, isLocalID(st), nil)
} | go | func (st *State) WatchApplications() StringsWatcher {
return newLifecycleWatcher(st, applicationsC, nil, isLocalID(st), nil)
} | [
"func",
"(",
"st",
"*",
"State",
")",
"WatchApplications",
"(",
")",
"StringsWatcher",
"{",
"return",
"newLifecycleWatcher",
"(",
"st",
",",
"applicationsC",
",",
"nil",
",",
"isLocalID",
"(",
"st",
")",
",",
"nil",
")",
"\n",
"}"
] | // WatchApplications returns a StringsWatcher that notifies of changes to
// the lifecycles of the applications in the model. | [
"WatchApplications",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"lifecycles",
"of",
"the",
"applications",
"in",
"the",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L397-L399 | train |
juju/juju | state/watcher.go | WatchRemoteApplications | func (st *State) WatchRemoteApplications() StringsWatcher {
return newLifecycleWatcher(st, remoteApplicationsC, nil, isLocalID(st), nil)
} | go | func (st *State) WatchRemoteApplications() StringsWatcher {
return newLifecycleWatcher(st, remoteApplicationsC, nil, isLocalID(st), nil)
} | [
"func",
"(",
"st",
"*",
"State",
")",
"WatchRemoteApplications",
"(",
")",
"StringsWatcher",
"{",
"return",
"newLifecycleWatcher",
"(",
"st",
",",
"remoteApplicationsC",
",",
"nil",
",",
"isLocalID",
"(",
"st",
")",
",",
"nil",
")",
"\n",
"}"
] | // WatchRemoteApplications returns a StringsWatcher that notifies of changes to
// the lifecycles of the remote applications in the model. | [
"WatchRemoteApplications",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"lifecycles",
"of",
"the",
"remote",
"applications",
"in",
"the",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L403-L405 | train |
juju/juju | state/watcher.go | WatchStorageAttachments | func (sb *storageBackend) WatchStorageAttachments(unit names.UnitTag) StringsWatcher {
members := bson.D{{"unitid", unit.Id()}}
prefix := unitGlobalKey(unit.Id()) + "#"
filter := func(id interface{}) bool {
k, err := sb.mb.strictLocalID(id.(string))
if err != nil {
return false
}
return strings.HasPrefix(k, prefix)
}
tr := func(id string) string {
// Transform storage attachment document ID to storage ID.
return id[len(prefix):]
}
return newLifecycleWatcher(sb.mb, storageAttachmentsC, members, filter, tr)
} | go | func (sb *storageBackend) WatchStorageAttachments(unit names.UnitTag) StringsWatcher {
members := bson.D{{"unitid", unit.Id()}}
prefix := unitGlobalKey(unit.Id()) + "#"
filter := func(id interface{}) bool {
k, err := sb.mb.strictLocalID(id.(string))
if err != nil {
return false
}
return strings.HasPrefix(k, prefix)
}
tr := func(id string) string {
// Transform storage attachment document ID to storage ID.
return id[len(prefix):]
}
return newLifecycleWatcher(sb.mb, storageAttachmentsC, members, filter, tr)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"WatchStorageAttachments",
"(",
"unit",
"names",
".",
"UnitTag",
")",
"StringsWatcher",
"{",
"members",
":=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"unit",
".",
"Id",
"(",
")",
"}",
"}",
"\n",
"pr... | // WatchStorageAttachments returns a StringsWatcher that notifies of
// changes to the lifecycles of all storage instances attached to the
// specified unit. | [
"WatchStorageAttachments",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"lifecycles",
"of",
"all",
"storage",
"instances",
"attached",
"to",
"the",
"specified",
"unit",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L410-L425 | train |
juju/juju | state/watcher.go | WatchUnits | func (a *Application) WatchUnits() StringsWatcher {
members := bson.D{{"application", a.doc.Name}}
prefix := a.doc.Name + "/"
filter := func(unitDocID interface{}) bool {
unitName, err := a.st.strictLocalID(unitDocID.(string))
if err != nil {
return false
}
return strings.HasPrefix(unitName, prefix)
}
return newLifecycleWatcher(a.st, unitsC, members, filter, nil)
} | go | func (a *Application) WatchUnits() StringsWatcher {
members := bson.D{{"application", a.doc.Name}}
prefix := a.doc.Name + "/"
filter := func(unitDocID interface{}) bool {
unitName, err := a.st.strictLocalID(unitDocID.(string))
if err != nil {
return false
}
return strings.HasPrefix(unitName, prefix)
}
return newLifecycleWatcher(a.st, unitsC, members, filter, nil)
} | [
"func",
"(",
"a",
"*",
"Application",
")",
"WatchUnits",
"(",
")",
"StringsWatcher",
"{",
"members",
":=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"a",
".",
"doc",
".",
"Name",
"}",
"}",
"\n",
"prefix",
":=",
"a",
".",
"doc",
".",
"Name",
... | // WatchUnits returns a StringsWatcher that notifies of changes to the
// lifecycles of units of a. | [
"WatchUnits",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"lifecycles",
"of",
"units",
"of",
"a",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L429-L440 | train |
juju/juju | state/watcher.go | WatchScale | func (a *Application) WatchScale() NotifyWatcher {
currentScale := -1
filter := func(id interface{}) bool {
k, err := a.st.strictLocalID(id.(string))
if err != nil {
return false
}
if k != a.doc.Name {
return false
}
applications, closer := a.st.db().GetCollection(applicationsC)
defer closer()
var scaleField = bson.D{{"scale", 1}}
var doc *applicationDoc
if err := applications.FindId(k).Select(scaleField).One(&doc); err != nil {
return false
}
match := doc.DesiredScale != currentScale
currentScale = doc.DesiredScale
return match
}
return newNotifyCollWatcher(a.st, applicationsC, filter)
} | go | func (a *Application) WatchScale() NotifyWatcher {
currentScale := -1
filter := func(id interface{}) bool {
k, err := a.st.strictLocalID(id.(string))
if err != nil {
return false
}
if k != a.doc.Name {
return false
}
applications, closer := a.st.db().GetCollection(applicationsC)
defer closer()
var scaleField = bson.D{{"scale", 1}}
var doc *applicationDoc
if err := applications.FindId(k).Select(scaleField).One(&doc); err != nil {
return false
}
match := doc.DesiredScale != currentScale
currentScale = doc.DesiredScale
return match
}
return newNotifyCollWatcher(a.st, applicationsC, filter)
} | [
"func",
"(",
"a",
"*",
"Application",
")",
"WatchScale",
"(",
")",
"NotifyWatcher",
"{",
"currentScale",
":=",
"-",
"1",
"\n",
"filter",
":=",
"func",
"(",
"id",
"interface",
"{",
"}",
")",
"bool",
"{",
"k",
",",
"err",
":=",
"a",
".",
"st",
".",
... | // WatchScale returns a new NotifyWatcher watching for
// changes to the specified application's scale value. | [
"WatchScale",
"returns",
"a",
"new",
"NotifyWatcher",
"watching",
"for",
"changes",
"to",
"the",
"specified",
"application",
"s",
"scale",
"value",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L444-L467 | train |
juju/juju | state/watcher.go | WatchContainers | func (m *Machine) WatchContainers(ctype instance.ContainerType) StringsWatcher {
isChild := fmt.Sprintf("^%s/%s/%s$", m.doc.DocID, ctype, names.NumberSnippet)
return m.containersWatcher(isChild)
} | go | func (m *Machine) WatchContainers(ctype instance.ContainerType) StringsWatcher {
isChild := fmt.Sprintf("^%s/%s/%s$", m.doc.DocID, ctype, names.NumberSnippet)
return m.containersWatcher(isChild)
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"WatchContainers",
"(",
"ctype",
"instance",
".",
"ContainerType",
")",
"StringsWatcher",
"{",
"isChild",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"m",
".",
"doc",
".",
"DocID",
",",
"ctype",
",",
"names... | // WatchContainers returns a StringsWatcher that notifies of changes to the
// lifecycles of containers of the specified type on a machine. | [
"WatchContainers",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"lifecycles",
"of",
"containers",
"of",
"the",
"specified",
"type",
"on",
"a",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L514-L517 | train |
juju/juju | state/watcher.go | WatchAllContainers | func (m *Machine) WatchAllContainers() StringsWatcher {
isChild := fmt.Sprintf("^%s/%s/%s$", m.doc.DocID, names.ContainerTypeSnippet, names.NumberSnippet)
return m.containersWatcher(isChild)
} | go | func (m *Machine) WatchAllContainers() StringsWatcher {
isChild := fmt.Sprintf("^%s/%s/%s$", m.doc.DocID, names.ContainerTypeSnippet, names.NumberSnippet)
return m.containersWatcher(isChild)
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"WatchAllContainers",
"(",
")",
"StringsWatcher",
"{",
"isChild",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"m",
".",
"doc",
".",
"DocID",
",",
"names",
".",
"ContainerTypeSnippet",
",",
"names",
".",
"Nu... | // WatchAllContainers returns a StringsWatcher that notifies of changes to the
// lifecycles of all containers on a machine. | [
"WatchAllContainers",
"returns",
"a",
"StringsWatcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"lifecycles",
"of",
"all",
"containers",
"on",
"a",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L521-L524 | train |
juju/juju | state/watcher.go | initialInfo | func (w *RelationScopeWatcher) initialInfo() (info *scopeInfo, err error) {
relationScopes, closer := w.db.GetCollection(relationScopesC)
defer closer()
docs := []relationScopeDoc{}
sel := bson.D{
{"key", bson.D{{"$regex", "^" + w.prefix}}},
{"departing", bson.D{{"$ne", true}}},
}
if err = relationScopes.Find(sel).All(&docs); err != nil {
return nil, err
}
info = &scopeInfo{
base: map[string]bool{},
diff: map[string]bool{},
}
for _, doc := range docs {
if name := doc.unitName(); name != w.ignore {
info.add(name)
}
}
logger.Tracef("relationScopeWatcher prefix %q initializing with %# v",
w.prefix, pretty.Formatter(info))
return info, nil
} | go | func (w *RelationScopeWatcher) initialInfo() (info *scopeInfo, err error) {
relationScopes, closer := w.db.GetCollection(relationScopesC)
defer closer()
docs := []relationScopeDoc{}
sel := bson.D{
{"key", bson.D{{"$regex", "^" + w.prefix}}},
{"departing", bson.D{{"$ne", true}}},
}
if err = relationScopes.Find(sel).All(&docs); err != nil {
return nil, err
}
info = &scopeInfo{
base: map[string]bool{},
diff: map[string]bool{},
}
for _, doc := range docs {
if name := doc.unitName(); name != w.ignore {
info.add(name)
}
}
logger.Tracef("relationScopeWatcher prefix %q initializing with %# v",
w.prefix, pretty.Formatter(info))
return info, nil
} | [
"func",
"(",
"w",
"*",
"RelationScopeWatcher",
")",
"initialInfo",
"(",
")",
"(",
"info",
"*",
"scopeInfo",
",",
"err",
"error",
")",
"{",
"relationScopes",
",",
"closer",
":=",
"w",
".",
"db",
".",
"GetCollection",
"(",
"relationScopesC",
")",
"\n",
"de... | // initialInfo returns an uncommitted scopeInfo with the current set of units. | [
"initialInfo",
"returns",
"an",
"uncommitted",
"scopeInfo",
"with",
"the",
"current",
"set",
"of",
"units",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L894-L918 | train |
juju/juju | state/watcher.go | mergeChanges | func (w *RelationScopeWatcher) mergeChanges(info *scopeInfo, ids map[interface{}]bool) error {
relationScopes, closer := w.db.GetCollection(relationScopesC)
defer closer()
var existIds []string
for id, exists := range ids {
switch id := id.(type) {
case string:
if exists {
existIds = append(existIds, id)
} else {
key, err := w.backend.strictLocalID(id)
if err != nil {
return errors.Trace(err)
}
info.remove(unitNameFromScopeKey(key))
}
default:
logger.Warningf("ignoring bad relation scope id: %#v", id)
}
}
var docs []relationScopeDoc
sel := bson.D{{"_id", bson.D{{"$in", existIds}}}}
if err := relationScopes.Find(sel).All(&docs); err != nil {
return err
}
for _, doc := range docs {
name := doc.unitName()
if doc.Departing {
info.remove(name)
} else if name != w.ignore {
info.add(name)
}
}
logger.Tracef("RelationScopeWatcher prefix %q merge scope to %# v from ids: %# v",
w.prefix, pretty.Formatter(info), pretty.Formatter(ids))
return nil
} | go | func (w *RelationScopeWatcher) mergeChanges(info *scopeInfo, ids map[interface{}]bool) error {
relationScopes, closer := w.db.GetCollection(relationScopesC)
defer closer()
var existIds []string
for id, exists := range ids {
switch id := id.(type) {
case string:
if exists {
existIds = append(existIds, id)
} else {
key, err := w.backend.strictLocalID(id)
if err != nil {
return errors.Trace(err)
}
info.remove(unitNameFromScopeKey(key))
}
default:
logger.Warningf("ignoring bad relation scope id: %#v", id)
}
}
var docs []relationScopeDoc
sel := bson.D{{"_id", bson.D{{"$in", existIds}}}}
if err := relationScopes.Find(sel).All(&docs); err != nil {
return err
}
for _, doc := range docs {
name := doc.unitName()
if doc.Departing {
info.remove(name)
} else if name != w.ignore {
info.add(name)
}
}
logger.Tracef("RelationScopeWatcher prefix %q merge scope to %# v from ids: %# v",
w.prefix, pretty.Formatter(info), pretty.Formatter(ids))
return nil
} | [
"func",
"(",
"w",
"*",
"RelationScopeWatcher",
")",
"mergeChanges",
"(",
"info",
"*",
"scopeInfo",
",",
"ids",
"map",
"[",
"interface",
"{",
"}",
"]",
"bool",
")",
"error",
"{",
"relationScopes",
",",
"closer",
":=",
"w",
".",
"db",
".",
"GetCollection",... | // mergeChanges updates info with the contents of the changes in ids. False
// values are always treated as removed; true values cause the associated
// document to be read, and whether it's treated as added or removed depends
// on the value of the document's Departing field. | [
"mergeChanges",
"updates",
"info",
"with",
"the",
"contents",
"of",
"the",
"changes",
"in",
"ids",
".",
"False",
"values",
"are",
"always",
"treated",
"as",
"removed",
";",
"true",
"values",
"cause",
"the",
"associated",
"document",
"to",
"be",
"read",
"and"... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L924-L961 | train |
juju/juju | state/watcher.go | WatchUnits | func (r *Relation) WatchUnits(appName string) (RelationUnitsWatcher, error) {
return r.watchUnits(appName, false)
} | go | func (r *Relation) WatchUnits(appName string) (RelationUnitsWatcher, error) {
return r.watchUnits(appName, false)
} | [
"func",
"(",
"r",
"*",
"Relation",
")",
"WatchUnits",
"(",
"appName",
"string",
")",
"(",
"RelationUnitsWatcher",
",",
"error",
")",
"{",
"return",
"r",
".",
"watchUnits",
"(",
"appName",
",",
"false",
")",
"\n",
"}"
] | // WatchUnits returns a watcher that notifies of changes to the units of the
// specified application endpoint in the relation. This method will return an error
// if the endpoint is not globally scoped. | [
"WatchUnits",
"returns",
"a",
"watcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"units",
"of",
"the",
"specified",
"application",
"endpoint",
"in",
"the",
"relation",
".",
"This",
"method",
"will",
"return",
"an",
"error",
"if",
"the",
"endpoint",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1024-L1026 | train |
juju/juju | state/watcher.go | mergeScope | func (w *relationUnitsWatcher) mergeScope(changes *params.RelationUnitsChange, c *RelationScopeChange) error {
docIds := make([]interface{}, len(c.Entered))
for i, name := range c.Entered {
key := w.sw.prefix + name
docID := w.backend.docID(key)
docIds[i] = docID
}
logger.Tracef("relationUnitsWatcher %q watching newly entered: %v, and unwatching left %v", w.sw.prefix, c.Entered, c.Left)
if err := w.watcher.WatchMulti(settingsC, docIds, w.updates); err != nil {
return errors.Trace(err)
}
for _, docID := range docIds {
w.watching.Add(docID.(string))
}
for _, name := range c.Entered {
key := w.sw.prefix + name
if err := w.mergeSettings(changes, key); err != nil {
return errors.Annotatef(err, "while merging settings for %q entering relation scope", name)
}
changes.Departed = remove(changes.Departed, name)
}
for _, name := range c.Left {
key := w.sw.prefix + name
docID := w.backend.docID(key)
changes.Departed = append(changes.Departed, name)
if changes.Changed != nil {
delete(changes.Changed, name)
}
w.watcher.Unwatch(settingsC, docID, w.updates)
w.watching.Remove(docID)
}
logger.Tracef("relationUnitsWatcher %q Change updated to: %# v", w.sw.prefix, changes)
return nil
} | go | func (w *relationUnitsWatcher) mergeScope(changes *params.RelationUnitsChange, c *RelationScopeChange) error {
docIds := make([]interface{}, len(c.Entered))
for i, name := range c.Entered {
key := w.sw.prefix + name
docID := w.backend.docID(key)
docIds[i] = docID
}
logger.Tracef("relationUnitsWatcher %q watching newly entered: %v, and unwatching left %v", w.sw.prefix, c.Entered, c.Left)
if err := w.watcher.WatchMulti(settingsC, docIds, w.updates); err != nil {
return errors.Trace(err)
}
for _, docID := range docIds {
w.watching.Add(docID.(string))
}
for _, name := range c.Entered {
key := w.sw.prefix + name
if err := w.mergeSettings(changes, key); err != nil {
return errors.Annotatef(err, "while merging settings for %q entering relation scope", name)
}
changes.Departed = remove(changes.Departed, name)
}
for _, name := range c.Left {
key := w.sw.prefix + name
docID := w.backend.docID(key)
changes.Departed = append(changes.Departed, name)
if changes.Changed != nil {
delete(changes.Changed, name)
}
w.watcher.Unwatch(settingsC, docID, w.updates)
w.watching.Remove(docID)
}
logger.Tracef("relationUnitsWatcher %q Change updated to: %# v", w.sw.prefix, changes)
return nil
} | [
"func",
"(",
"w",
"*",
"relationUnitsWatcher",
")",
"mergeScope",
"(",
"changes",
"*",
"params",
".",
"RelationUnitsChange",
",",
"c",
"*",
"RelationScopeChange",
")",
"error",
"{",
"docIds",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
... | // mergeScope starts and stops settings watches on the units entering and
// leaving the scope in the supplied RelationScopeChange event, and applies
// the expressed changes to the supplied RelationUnitsChange event. | [
"mergeScope",
"starts",
"and",
"stops",
"settings",
"watches",
"on",
"the",
"units",
"entering",
"and",
"leaving",
"the",
"scope",
"in",
"the",
"supplied",
"RelationScopeChange",
"event",
"and",
"applies",
"the",
"expressed",
"changes",
"to",
"the",
"supplied",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1100-L1133 | train |
juju/juju | state/watcher.go | remove | func remove(strs []string, s string) []string {
for i, v := range strs {
if s == v {
strs[i] = strs[len(strs)-1]
return strs[:len(strs)-1]
}
}
return strs
} | go | func remove(strs []string, s string) []string {
for i, v := range strs {
if s == v {
strs[i] = strs[len(strs)-1]
return strs[:len(strs)-1]
}
}
return strs
} | [
"func",
"remove",
"(",
"strs",
"[",
"]",
"string",
",",
"s",
"string",
")",
"[",
"]",
"string",
"{",
"for",
"i",
",",
"v",
":=",
"range",
"strs",
"{",
"if",
"s",
"==",
"v",
"{",
"strs",
"[",
"i",
"]",
"=",
"strs",
"[",
"len",
"(",
"strs",
"... | // remove removes s from strs and returns the modified slice. | [
"remove",
"removes",
"s",
"from",
"strs",
"and",
"returns",
"the",
"modified",
"slice",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1136-L1144 | train |
juju/juju | state/watcher.go | WatchLifeSuspendedStatus | func (r *Relation) WatchLifeSuspendedStatus() StringsWatcher {
filter := func(id interface{}) bool {
k, err := r.st.strictLocalID(id.(string))
if err != nil {
return false
}
return k == r.Tag().Id()
}
members := bson.D{{"id", r.Id()}}
return newRelationLifeSuspendedWatcher(r.st, members, filter, nil)
} | go | func (r *Relation) WatchLifeSuspendedStatus() StringsWatcher {
filter := func(id interface{}) bool {
k, err := r.st.strictLocalID(id.(string))
if err != nil {
return false
}
return k == r.Tag().Id()
}
members := bson.D{{"id", r.Id()}}
return newRelationLifeSuspendedWatcher(r.st, members, filter, nil)
} | [
"func",
"(",
"r",
"*",
"Relation",
")",
"WatchLifeSuspendedStatus",
"(",
")",
"StringsWatcher",
"{",
"filter",
":=",
"func",
"(",
"id",
"interface",
"{",
"}",
")",
"bool",
"{",
"k",
",",
"err",
":=",
"r",
".",
"st",
".",
"strictLocalID",
"(",
"id",
"... | // WatchLifeSuspendedStatus returns a watcher that notifies of changes to the life
// or suspended status of the relation. | [
"WatchLifeSuspendedStatus",
"returns",
"a",
"watcher",
"that",
"notifies",
"of",
"changes",
"to",
"the",
"life",
"or",
"suspended",
"status",
"of",
"the",
"relation",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1200-L1210 | train |
juju/juju | state/watcher.go | newRelationLifeSuspendedWatcher | func newRelationLifeSuspendedWatcher(
backend modelBackend,
members bson.D,
filter func(key interface{}) bool,
transform func(id string) string,
) *relationLifeSuspendedWatcher {
w := &relationLifeSuspendedWatcher{
commonWatcher: newCommonWatcher(backend),
out: make(chan []string),
members: members,
filter: filter,
transform: transform,
lifeSuspended: make(map[string]relationLifeSuspended),
}
w.tomb.Go(func() error {
defer close(w.out)
return w.loop()
})
return w
} | go | func newRelationLifeSuspendedWatcher(
backend modelBackend,
members bson.D,
filter func(key interface{}) bool,
transform func(id string) string,
) *relationLifeSuspendedWatcher {
w := &relationLifeSuspendedWatcher{
commonWatcher: newCommonWatcher(backend),
out: make(chan []string),
members: members,
filter: filter,
transform: transform,
lifeSuspended: make(map[string]relationLifeSuspended),
}
w.tomb.Go(func() error {
defer close(w.out)
return w.loop()
})
return w
} | [
"func",
"newRelationLifeSuspendedWatcher",
"(",
"backend",
"modelBackend",
",",
"members",
"bson",
".",
"D",
",",
"filter",
"func",
"(",
"key",
"interface",
"{",
"}",
")",
"bool",
",",
"transform",
"func",
"(",
"id",
"string",
")",
"string",
",",
")",
"*",... | // newRelationLifeSuspendedWatcher creates a watcher that sends changes when the
// life or suspended status of specific relations change. | [
"newRelationLifeSuspendedWatcher",
"creates",
"a",
"watcher",
"that",
"sends",
"changes",
"when",
"the",
"life",
"or",
"suspended",
"status",
"of",
"specific",
"relations",
"change",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1231-L1250 | train |
juju/juju | state/watcher.go | WatchSubordinateUnits | func (u *Unit) WatchSubordinateUnits() StringsWatcher {
u = &Unit{st: u.st, doc: u.doc}
coll := unitsC
getUnits := func() ([]string, error) {
if err := u.Refresh(); err != nil {
return nil, err
}
return u.doc.Subordinates, nil
}
return newUnitsWatcher(u.st, u.Tag(), getUnits, coll, u.doc.DocID)
} | go | func (u *Unit) WatchSubordinateUnits() StringsWatcher {
u = &Unit{st: u.st, doc: u.doc}
coll := unitsC
getUnits := func() ([]string, error) {
if err := u.Refresh(); err != nil {
return nil, err
}
return u.doc.Subordinates, nil
}
return newUnitsWatcher(u.st, u.Tag(), getUnits, coll, u.doc.DocID)
} | [
"func",
"(",
"u",
"*",
"Unit",
")",
"WatchSubordinateUnits",
"(",
")",
"StringsWatcher",
"{",
"u",
"=",
"&",
"Unit",
"{",
"st",
":",
"u",
".",
"st",
",",
"doc",
":",
"u",
".",
"doc",
"}",
"\n",
"coll",
":=",
"unitsC",
"\n",
"getUnits",
":=",
"fun... | // WatchSubordinateUnits returns a StringsWatcher tracking the unit's subordinate units. | [
"WatchSubordinateUnits",
"returns",
"a",
"StringsWatcher",
"tracking",
"the",
"unit",
"s",
"subordinate",
"units",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1395-L1405 | train |
juju/juju | state/watcher.go | WatchPrincipalUnits | func (m *Machine) WatchPrincipalUnits() StringsWatcher {
m = &Machine{st: m.st, doc: m.doc}
coll := machinesC
getUnits := func() ([]string, error) {
if err := m.Refresh(); err != nil {
return nil, err
}
return m.doc.Principals, nil
}
return newUnitsWatcher(m.st, m.Tag(), getUnits, coll, m.doc.DocID)
} | go | func (m *Machine) WatchPrincipalUnits() StringsWatcher {
m = &Machine{st: m.st, doc: m.doc}
coll := machinesC
getUnits := func() ([]string, error) {
if err := m.Refresh(); err != nil {
return nil, err
}
return m.doc.Principals, nil
}
return newUnitsWatcher(m.st, m.Tag(), getUnits, coll, m.doc.DocID)
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"WatchPrincipalUnits",
"(",
")",
"StringsWatcher",
"{",
"m",
"=",
"&",
"Machine",
"{",
"st",
":",
"m",
".",
"st",
",",
"doc",
":",
"m",
".",
"doc",
"}",
"\n",
"coll",
":=",
"machinesC",
"\n",
"getUnits",
":=",... | // WatchPrincipalUnits returns a StringsWatcher tracking the machine's principal
// units. | [
"WatchPrincipalUnits",
"returns",
"a",
"StringsWatcher",
"tracking",
"the",
"machine",
"s",
"principal",
"units",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1409-L1419 | train |
juju/juju | state/watcher.go | initial | func (w *unitsWatcher) initial() ([]string, error) {
initialNames, err := w.getUnits()
if err != nil {
return nil, err
}
return w.watchUnits(initialNames, nil)
} | go | func (w *unitsWatcher) initial() ([]string, error) {
initialNames, err := w.getUnits()
if err != nil {
return nil, err
}
return w.watchUnits(initialNames, nil)
} | [
"func",
"(",
"w",
"*",
"unitsWatcher",
")",
"initial",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"initialNames",
",",
"err",
":=",
"w",
".",
"getUnits",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
... | // initial returns every member of the tracked set. | [
"initial",
"returns",
"every",
"member",
"of",
"the",
"tracked",
"set",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1459-L1465 | train |
juju/juju | state/watcher.go | update | func (w *unitsWatcher) update(changes []string) ([]string, error) {
latest, err := w.getUnits()
if err != nil {
return nil, err
}
var unknown []string
for _, name := range latest {
if _, found := w.life[name]; !found {
unknown = append(unknown, name)
}
}
if len(unknown) > 0 {
changes, err = w.watchUnits(unknown, changes)
if err != nil {
return nil, errors.Trace(err)
}
}
for name := range w.life {
if hasString(latest, name) {
continue
}
if !hasString(changes, name) {
changes = append(changes, name)
}
logger.Tracef("unit %q %q no longer in latest, removing watch", unitsC, name)
delete(w.life, name)
w.watcher.Unwatch(unitsC, w.backend.docID(name), w.in)
}
logger.Tracef("update reports changes: %q", changes)
return changes, nil
} | go | func (w *unitsWatcher) update(changes []string) ([]string, error) {
latest, err := w.getUnits()
if err != nil {
return nil, err
}
var unknown []string
for _, name := range latest {
if _, found := w.life[name]; !found {
unknown = append(unknown, name)
}
}
if len(unknown) > 0 {
changes, err = w.watchUnits(unknown, changes)
if err != nil {
return nil, errors.Trace(err)
}
}
for name := range w.life {
if hasString(latest, name) {
continue
}
if !hasString(changes, name) {
changes = append(changes, name)
}
logger.Tracef("unit %q %q no longer in latest, removing watch", unitsC, name)
delete(w.life, name)
w.watcher.Unwatch(unitsC, w.backend.docID(name), w.in)
}
logger.Tracef("update reports changes: %q", changes)
return changes, nil
} | [
"func",
"(",
"w",
"*",
"unitsWatcher",
")",
"update",
"(",
"changes",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"latest",
",",
"err",
":=",
"w",
".",
"getUnits",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"re... | // update adds to and returns changes, such that it contains the names of any
// non-Dead units to have entered or left the tracked set. | [
"update",
"adds",
"to",
"and",
"returns",
"changes",
"such",
"that",
"it",
"contains",
"the",
"names",
"of",
"any",
"non",
"-",
"Dead",
"units",
"to",
"have",
"entered",
"or",
"left",
"the",
"tracked",
"set",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1532-L1562 | train |
juju/juju | state/watcher.go | merge | func (w *unitsWatcher) merge(changes []string, name string) ([]string, error) {
logger.Tracef("merging change for %q %q", unitsC, name)
var doc lifeWatchDoc
units, closer := w.db.GetCollection(unitsC)
err := units.FindId(name).Select(lifeWatchFields).One(&doc)
closer()
gone := false
if err == mgo.ErrNotFound {
gone = true
} else if err != nil {
return nil, err
} else if doc.Life == Dead {
gone = true
}
life := w.life[name]
switch {
case gone:
delete(w.life, name)
logger.Tracef("document gone, unwatching %q %q", unitsC, name)
w.watcher.Unwatch(unitsC, w.backend.docID(name), w.in)
case life != doc.Life:
logger.Tracef("updating doc life %q %q to %q", unitsC, name, doc.Life)
w.life[name] = doc.Life
default:
return changes, nil
}
if !hasString(changes, name) {
changes = append(changes, name)
}
logger.Tracef("merge reporting changes: %q", changes)
return changes, nil
} | go | func (w *unitsWatcher) merge(changes []string, name string) ([]string, error) {
logger.Tracef("merging change for %q %q", unitsC, name)
var doc lifeWatchDoc
units, closer := w.db.GetCollection(unitsC)
err := units.FindId(name).Select(lifeWatchFields).One(&doc)
closer()
gone := false
if err == mgo.ErrNotFound {
gone = true
} else if err != nil {
return nil, err
} else if doc.Life == Dead {
gone = true
}
life := w.life[name]
switch {
case gone:
delete(w.life, name)
logger.Tracef("document gone, unwatching %q %q", unitsC, name)
w.watcher.Unwatch(unitsC, w.backend.docID(name), w.in)
case life != doc.Life:
logger.Tracef("updating doc life %q %q to %q", unitsC, name, doc.Life)
w.life[name] = doc.Life
default:
return changes, nil
}
if !hasString(changes, name) {
changes = append(changes, name)
}
logger.Tracef("merge reporting changes: %q", changes)
return changes, nil
} | [
"func",
"(",
"w",
"*",
"unitsWatcher",
")",
"merge",
"(",
"changes",
"[",
"]",
"string",
",",
"name",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"unitsC",
",",
"name",
")",
"\n",... | // merge adds to and returns changes, such that it contains the supplied unit
// name if that unit is unknown and non-Dead, or has changed lifecycle status. | [
"merge",
"adds",
"to",
"and",
"returns",
"changes",
"such",
"that",
"it",
"contains",
"the",
"supplied",
"unit",
"name",
"if",
"that",
"unit",
"is",
"unknown",
"and",
"non",
"-",
"Dead",
"or",
"has",
"changed",
"lifecycle",
"status",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1566-L1597 | train |
juju/juju | state/watcher.go | WatchHardwareCharacteristics | func (m *Machine) WatchHardwareCharacteristics() NotifyWatcher {
return newEntityWatcher(m.st, instanceDataC, m.doc.DocID)
} | go | func (m *Machine) WatchHardwareCharacteristics() NotifyWatcher {
return newEntityWatcher(m.st, instanceDataC, m.doc.DocID)
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"WatchHardwareCharacteristics",
"(",
")",
"NotifyWatcher",
"{",
"return",
"newEntityWatcher",
"(",
"m",
".",
"st",
",",
"instanceDataC",
",",
"m",
".",
"doc",
".",
"DocID",
")",
"\n",
"}"
] | // WatchHardwareCharacteristics returns a watcher for observing changes to a machine's hardware characteristics. | [
"WatchHardwareCharacteristics",
"returns",
"a",
"watcher",
"for",
"observing",
"changes",
"to",
"a",
"machine",
"s",
"hardware",
"characteristics",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1643-L1645 | train |
juju/juju | state/watcher.go | Watch | func (m *Machine) Watch() NotifyWatcher {
return newEntityWatcher(m.st, machinesC, m.doc.DocID)
} | go | func (m *Machine) Watch() NotifyWatcher {
return newEntityWatcher(m.st, machinesC, m.doc.DocID)
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"Watch",
"(",
")",
"NotifyWatcher",
"{",
"return",
"newEntityWatcher",
"(",
"m",
".",
"st",
",",
"machinesC",
",",
"m",
".",
"doc",
".",
"DocID",
")",
"\n",
"}"
] | // Watch returns a watcher for observing changes to a machine. | [
"Watch",
"returns",
"a",
"watcher",
"for",
"observing",
"changes",
"to",
"a",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1658-L1660 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.