id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
153,900
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", "[", "0", "]", ".", "(", "*", "httprequest", ".", "Client", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// HTTPClient mocks base method
[ "HTTPClient", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L104-L109
153,901
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", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// 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
153,902
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", ",", "arg1", ",", "arg2", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "error", ")", "\n", "return", "ret0", "\n", "}" ]
// FacadeCall mocks base method
[ "FacadeCall", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L165-L169
153,903
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", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockFacadeCaller", ")", "(", "nil", ")", ".", "FacadeCall", ")", ",", "arg0", ",", "arg1", ",", "arg2", ")", "\n", "}" ]
// 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
153,904
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", "]", ".", "(", "base", ".", "APICaller", ")", "\n", "return", "ret0", "\n", "}" ]
// RawAPICaller mocks base method
[ "RawAPICaller", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/mocks/caller_mock.go#L189-L193
153,905
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", "=", "&", "MockRestClientInterfaceMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// 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
153,906
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", "]", ".", "(", "schema", ".", "GroupVersion", ")", "\n", "return", "ret0", "\n", "}" ]
// 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
153,907
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", ".", "TypeOf", "(", "(", "*", "MockRestClientInterface", ")", "(", "nil", ")", ".", "APIVersion", ")", ")", "\n", "}" ]
// 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
153,908
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", "]", ".", "(", "flowcontrol", ".", "RateLimiter", ")", "\n", "return", "ret0", "\n", "}" ]
// 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
153,909
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", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "*", "rest", ".", "Request", ")", "\n", "return", "ret0", "\n", "}" ]
// 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
153,910
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", "(", ")", "}", ",", "}", ")", "\n", "}" ]
// 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
153,911
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", ".", "RegisteredProviders", ",", "cloudByNameFunc", ":", "jujucloud", ".", "CloudByName", ",", "}", "\n", "c", ".", "allCloudsFunc", "=", "func", "(", ")", "(", "map", "[", "string", "]", "jujucloud", ".", "Cloud", ",", "error", ")", "{", "return", "c", ".", "allClouds", "(", ")", "\n", "}", "\n", "return", "c", "\n", "}" ]
// 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
153,912
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", ",", ")", "(", "defaultCloud", ",", "defaultRegion", "string", ",", "isNew", "bool", ",", "_", "error", ")", "{", "isNew", "=", "true", "\n", "for", "_", ",", "cloudName", ":=", "range", "sortedCloudNames", "{", "cloud", ":=", "clouds", "[", "cloudName", "]", "\n", "if", "cloud", ".", "Type", "!=", "providerName", "{", "continue", "\n", "}", "\n", "credentials", ",", "err", ":=", "c", ".", "store", ".", "CredentialForCloud", "(", "cloudName", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "// None found.", "continue", "\n", "}", "\n", "existingCredNames", ":=", "set", ".", "NewStrings", "(", ")", "\n", "for", "name", ":=", "range", "credentials", ".", "AuthCredentials", "{", "existingCredNames", ".", "Add", "(", "name", ")", "\n", "}", "\n", "isNew", "=", "!", "existingCredNames", ".", "Contains", "(", "credName", ")", "\n", "if", "defaultRegion", "==", "\"", "\"", "&&", "credentials", ".", "DefaultRegion", "!=", "\"", "\"", "{", "defaultRegion", "=", "credentials", ".", "DefaultRegion", "\n", "}", "\n", "if", "defaultCloud", "==", "\"", "\"", "{", "defaultCloud", "=", "cloudName", "\n", "}", "\n", "}", "\n", "return", "defaultCloud", ",", "defaultRegion", ",", "isNew", ",", "nil", "\n", "}" ]
// 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", "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", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/cloud/detectcredentials.go#L249-L281
153,913
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", ".", "printCredentialOptions", "(", "ctxt", ",", "discovered", ")", "\n", "var", "input", "string", "\n", "for", "{", "var", "err", "error", "\n", "input", ",", "err", "=", "c", ".", "promptCredentialNumber", "(", "ctxt", ".", "Stderr", ",", "ctxt", ".", "Stdin", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "strings", ".", "ToLower", "(", "input", ")", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "if", "input", "!=", "\"", "\"", "{", "break", "\n", "}", "\n", "}", "\n\n", "// Check the entered number.", "num", ",", "err", ":=", "strconv", ".", "Atoi", "(", "input", ")", "\n", "if", "err", "!=", "nil", "||", "num", "<", "1", "||", "num", ">", "len", "(", "discovered", ")", "{", "fmt", ".", "Fprintf", "(", "ctxt", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "len", "(", "discovered", ")", ")", "\n", "continue", "\n", "}", "\n", "cred", ":=", "discovered", "[", "num", "-", "1", "]", "\n", "// Prompt for the cloud for which to save the credential.", "cloudName", ",", "err", ":=", "c", ".", "promptCloudName", "(", "ctxt", ".", "Stderr", ",", "ctxt", ".", "Stdin", ",", "cred", ".", "defaultCloudName", ",", "cred", ".", "cloudType", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "ctxt", ".", "Stderr", ",", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "if", "cloudName", "==", "\"", "\"", "{", "fmt", ".", "Fprintln", "(", "ctxt", ".", "Stderr", ",", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n\n", "// Reading existing info so we can apply updated values.", "existing", ",", "err", ":=", "c", ".", "store", ".", "CredentialForCloud", "(", "cloudName", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "fmt", ".", "Fprintf", "(", "ctxt", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "existing", "=", "&", "jujucloud", ".", "CloudCredential", "{", "AuthCredentials", ":", "make", "(", "map", "[", "string", "]", "jujucloud", ".", "Credential", ")", ",", "}", "\n", "}", "\n", "if", "cred", ".", "region", "!=", "\"", "\"", "{", "existing", ".", "DefaultRegion", "=", "cred", ".", "region", "\n", "}", "\n", "existing", ".", "AuthCredentials", "[", "cred", ".", "credentialName", "]", "=", "cred", ".", "credential", "\n", "if", "err", ":=", "c", ".", "store", ".", "UpdateCredential", "(", "cloudName", ",", "*", "existing", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "ctxt", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "else", "{", "// Update so we display correctly next time list is printed.", "cred", ".", "isNew", "=", "false", "\n", "discovered", "[", "num", "-", "1", "]", "=", "cred", "\n", "fmt", ".", "Fprintf", "(", "ctxt", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "cred", ".", "credential", ".", "Label", ",", "cloudName", ")", "\n", "}", "\n", "}", "\n", "}" ]
// 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
153,914
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", ".", "NewStorageAPI", "(", ")", "\n", "}", "\n", "return", "modelcmd", ".", "Wrap", "(", "cmd", ")", "\n", "}" ]
// 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
153,915
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", ".", "FilesystemAttachmentParams", ",", "0", ",", "len", "(", "ops", ")", ")", "\n", "for", "_", ",", "op", ":=", "range", "ops", "{", "args", ":=", "op", ".", "args", "\n", "if", "args", ".", "Path", "==", "\"", "\"", "{", "args", ".", "Path", "=", "filepath", ".", "Join", "(", "ctx", ".", "config", ".", "StorageDir", ",", "args", ".", "Filesystem", ".", "Id", "(", ")", ")", "\n", "}", "\n", "filesystemAttachmentParams", "=", "append", "(", "filesystemAttachmentParams", ",", "args", ")", "\n", "}", "\n", "paramsBySource", ",", "filesystemSources", ",", "err", ":=", "filesystemAttachmentParamsBySource", "(", "ctx", ".", "config", ".", "StorageDir", ",", "filesystemAttachmentParams", ",", "ctx", ".", "filesystems", ",", "ctx", ".", "managedFilesystemSource", ",", "ctx", ".", "config", ".", "Registry", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "reschedule", "[", "]", "scheduleOp", "\n", "var", "filesystemAttachments", "[", "]", "storage", ".", "FilesystemAttachment", "\n", "var", "statuses", "[", "]", "params", ".", "EntityStatusArgs", "\n", "for", "sourceName", ",", "filesystemAttachmentParams", ":=", "range", "paramsBySource", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "filesystemAttachmentParams", ")", "\n", "filesystemSource", ":=", "filesystemSources", "[", "sourceName", "]", "\n", "results", ",", "err", ":=", "filesystemSource", ".", "AttachFilesystems", "(", "ctx", ".", "config", ".", "CloudCallContext", ",", "filesystemAttachmentParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "sourceName", ")", "\n", "}", "\n", "for", "i", ",", "result", ":=", "range", "results", "{", "p", ":=", "filesystemAttachmentParams", "[", "i", "]", "\n", "statuses", "=", "append", "(", "statuses", ",", "params", ".", "EntityStatusArgs", "{", "Tag", ":", "p", ".", "Filesystem", ".", "String", "(", ")", ",", "Status", ":", "status", ".", "Attached", ".", "String", "(", ")", ",", "}", ")", "\n", "entityStatus", ":=", "&", "statuses", "[", "len", "(", "statuses", ")", "-", "1", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "// Reschedule the filesystem attachment.", "id", ":=", "params", ".", "MachineStorageId", "{", "MachineTag", ":", "p", ".", "Machine", ".", "String", "(", ")", ",", "AttachmentTag", ":", "p", ".", "Filesystem", ".", "String", "(", ")", ",", "}", "\n", "reschedule", "=", "append", "(", "reschedule", ",", "ops", "[", "id", "]", ")", "\n\n", "// 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", "(", ")", "\n", "entityStatus", ".", "Info", "=", "result", ".", "Error", ".", "Error", "(", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "names", ".", "ReadableString", "(", "p", ".", "Filesystem", ")", ",", "names", ".", "ReadableString", "(", "p", ".", "Machine", ")", ",", "result", ".", "Error", ",", ")", "\n", "continue", "\n", "}", "\n", "filesystemAttachments", "=", "append", "(", "filesystemAttachments", ",", "*", "result", ".", "FilesystemAttachment", ")", "\n", "}", "\n", "}", "\n", "scheduleOperations", "(", "ctx", ",", "reschedule", "...", ")", "\n", "setStatus", "(", "ctx", ",", "statuses", ")", "\n", "if", "err", ":=", "setFilesystemAttachmentInfo", "(", "ctx", ",", "filesystemAttachments", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
153,916
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", ".", "FilesystemAttachmentParams", ",", "0", ",", "len", "(", "ops", ")", ")", "\n", "for", "_", ",", "op", ":=", "range", "ops", "{", "filesystemAttachmentParams", "=", "append", "(", "filesystemAttachmentParams", ",", "op", ".", "args", ")", "\n", "}", "\n", "paramsBySource", ",", "filesystemSources", ",", "err", ":=", "filesystemAttachmentParamsBySource", "(", "ctx", ".", "config", ".", "StorageDir", ",", "filesystemAttachmentParams", ",", "ctx", ".", "filesystems", ",", "ctx", ".", "managedFilesystemSource", ",", "ctx", ".", "config", ".", "Registry", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "reschedule", "[", "]", "scheduleOp", "\n", "var", "statuses", "[", "]", "params", ".", "EntityStatusArgs", "\n", "var", "remove", "[", "]", "params", ".", "MachineStorageId", "\n", "for", "sourceName", ",", "filesystemAttachmentParams", ":=", "range", "paramsBySource", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "filesystemAttachmentParams", ")", "\n", "filesystemSource", ",", "ok", ":=", "filesystemSources", "[", "sourceName", "]", "\n", "if", "!", "ok", "&&", "ctx", ".", "isApplicationKind", "(", ")", "{", "continue", "\n", "}", "\n", "errs", ",", "err", ":=", "filesystemSource", ".", "DetachFilesystems", "(", "ctx", ".", "config", ".", "CloudCallContext", ",", "filesystemAttachmentParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "sourceName", ")", "\n", "}", "\n", "for", "i", ",", "err", ":=", "range", "errs", "{", "p", ":=", "filesystemAttachmentParams", "[", "i", "]", "\n", "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", "(", ")", ",", "}", ")", "\n", "id", ":=", "params", ".", "MachineStorageId", "{", "MachineTag", ":", "p", ".", "Machine", ".", "String", "(", ")", ",", "AttachmentTag", ":", "p", ".", "Filesystem", ".", "String", "(", ")", ",", "}", "\n", "entityStatus", ":=", "&", "statuses", "[", "len", "(", "statuses", ")", "-", "1", "]", "\n", "if", "err", "!=", "nil", "{", "reschedule", "=", "append", "(", "reschedule", ",", "ops", "[", "id", "]", ")", "\n", "entityStatus", ".", "Status", "=", "status", ".", "Detaching", ".", "String", "(", ")", "\n", "entityStatus", ".", "Info", "=", "err", ".", "Error", "(", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "names", ".", "ReadableString", "(", "p", ".", "Filesystem", ")", ",", "names", ".", "ReadableString", "(", "p", ".", "Machine", ")", ",", "err", ",", ")", "\n", "continue", "\n", "}", "\n", "remove", "=", "append", "(", "remove", ",", "id", ")", "\n", "}", "\n", "}", "\n", "scheduleOperations", "(", "ctx", ",", "reschedule", "...", ")", "\n", "setStatus", "(", "ctx", ",", "statuses", ")", "\n", "if", "err", ":=", "removeAttachments", "(", "ctx", ",", "remove", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "id", ":=", "range", "remove", "{", "delete", "(", "ctx", ".", "filesystemAttachments", ",", "id", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
153,917
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", ",", ")", "(", "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", ")", "\n", "for", "_", ",", "params", ":=", "range", "params", "{", "sourceName", ":=", "string", "(", "params", ".", "Provider", ")", "\n", "if", "_", ",", "ok", ":=", "filesystemSources", "[", "sourceName", "]", ";", "ok", "{", "continue", "\n", "}", "\n", "if", "params", ".", "Volume", "!=", "(", "names", ".", "VolumeTag", "{", "}", ")", "{", "filesystemSources", "[", "sourceName", "]", "=", "managedFilesystemSource", "\n", "continue", "\n", "}", "\n", "filesystemSource", ",", "err", ":=", "filesystemSource", "(", "baseStorageDir", ",", "sourceName", ",", "params", ".", "Provider", ",", "registry", ",", ")", "\n", "// 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", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "filesystemSources", "[", "sourceName", "]", "=", "filesystemSource", "\n", "}", "\n", "paramsBySource", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "storage", ".", "FilesystemParams", ")", "\n", "for", "_", ",", "param", ":=", "range", "params", "{", "sourceName", ":=", "string", "(", "param", ".", "Provider", ")", "\n", "filesystemSource", ":=", "filesystemSources", "[", "sourceName", "]", "\n", "if", "filesystemSource", "==", "nil", "{", "// Ignore nil filesystem sources; this means that the", "// filesystem should be created by the machine-provisioner.", "continue", "\n", "}", "\n", "paramsBySource", "[", "sourceName", "]", "=", "append", "(", "paramsBySource", "[", "sourceName", "]", ",", "param", ")", "\n", "}", "\n", "return", "paramsBySource", ",", "filesystemSources", ",", "nil", "\n", "}" ]
// 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
153,918
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", ")", "{", "valid", ":=", "make", "(", "[", "]", "storage", ".", "FilesystemParams", ",", "0", ",", "len", "(", "filesystemParams", ")", ")", "\n", "results", ":=", "make", "(", "[", "]", "error", ",", "len", "(", "filesystemParams", ")", ")", "\n", "for", "i", ",", "params", ":=", "range", "filesystemParams", "{", "err", ":=", "filesystemSource", ".", "ValidateFilesystemParams", "(", "params", ")", "\n", "if", "err", "==", "nil", "{", "valid", "=", "append", "(", "valid", ",", "params", ")", "\n", "}", "\n", "results", "[", "i", "]", "=", "err", "\n", "}", "\n", "return", "valid", ",", "results", "\n", "}" ]
// 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
153,919
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", ",", "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", ")", "\n", "paramsBySource", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "storage", ".", "FilesystemAttachmentParams", ")", "\n", "for", "_", ",", "params", ":=", "range", "filesystemAttachmentParams", "{", "sourceName", ":=", "string", "(", "params", ".", "Provider", ")", "\n", "paramsBySource", "[", "sourceName", "]", "=", "append", "(", "paramsBySource", "[", "sourceName", "]", ",", "params", ")", "\n", "if", "_", ",", "ok", ":=", "filesystemSources", "[", "sourceName", "]", ";", "ok", "{", "continue", "\n", "}", "\n", "filesystem", ",", "ok", ":=", "filesystems", "[", "params", ".", "Filesystem", "]", "\n", "if", "!", "ok", "||", "filesystem", ".", "Volume", "!=", "(", "names", ".", "VolumeTag", "{", "}", ")", "{", "filesystemSources", "[", "sourceName", "]", "=", "managedFilesystemSource", "\n", "continue", "\n", "}", "\n", "filesystemSource", ",", "err", ":=", "filesystemSource", "(", "baseStorageDir", ",", "sourceName", ",", "params", ".", "Provider", ",", "registry", ",", ")", "\n", "// 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", ",", "\"", "\"", ")", "\n", "}", "\n", "filesystemSources", "[", "sourceName", "]", "=", "filesystemSource", "\n", "}", "\n", "return", "paramsBySource", ",", "filesystemSources", ",", "nil", "\n", "}" ]
// 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
153,920
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 service.", "if", "!", "authorizer", ".", "AuthClient", "(", ")", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n", "m", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "KeyManagerAPI", "{", "state", ":", "st", ",", "model", ":", "m", ",", "resources", ":", "resources", ",", "authorizer", ":", "authorizer", ",", "apiUser", ":", "authorizer", ".", "GetAuthTag", "(", ")", ".", "(", "names", ".", "UserTag", ")", ",", "check", ":", "common", ".", "NewBlockChecker", "(", "st", ")", ",", "}", ",", "nil", "\n", "}" ]
// 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
153,921
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", ")", "\n", "cfg", ",", "err", ":=", "api", ".", "model", ".", "ModelConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "keys", "=", "ssh", ".", "SplitAuthorisedKeys", "(", "cfg", ".", "AuthorizedKeys", "(", ")", ")", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "fingerprint", ",", "_", ",", "err", ":=", "ssh", ".", "KeyFingerprint", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "key", ",", "err", ")", "\n", "}", "\n", "fingerprints", ".", "Add", "(", "fingerprint", ")", "\n", "}", "\n", "return", "keys", ",", "fingerprints", ",", "nil", "\n", "}" ]
// 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
153,922
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", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "result", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "arg", ".", "Keys", ")", ")", ",", "}", "\n", "if", "len", "(", "arg", ".", "Keys", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n\n", "if", "err", ":=", "api", ".", "checkCanWrite", "(", "arg", ".", "User", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n\n", "// For now, authorised keys are global, common to all users.", "sshKeys", ",", "currentFingerprints", ",", "err", ":=", "api", ".", "currentKeyDataForAdd", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "common", ".", "ServerError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n\n", "// Ensure we are not going to add invalid or duplicate keys.", "result", ".", "Results", "=", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "arg", ".", "Keys", ")", ")", "\n", "for", "i", ",", "key", ":=", "range", "arg", ".", "Keys", "{", "fingerprint", ",", "_", ",", "err", ":=", "ssh", ".", "KeyFingerprint", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", ")", "\n", "continue", "\n", "}", "\n", "if", "currentFingerprints", ".", "Contains", "(", "fingerprint", ")", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", ")", "\n", "continue", "\n", "}", "\n", "sshKeys", "=", "append", "(", "sshKeys", ",", "key", ")", "\n", "}", "\n", "err", "=", "api", ".", "writeSSHKeys", "(", "sshKeys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// 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
153,923
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", ")", ")", "\n", "for", "_", ",", "keyId", ":=", "range", "keyIds", "{", "keyInfo", ":=", "[", "]", "importedSSHKey", "{", "}", "\n", "output", ",", "err", ":=", "RunSSHImportId", "(", "keyId", ")", "\n", "if", "err", "!=", "nil", "{", "keyInfo", "=", "append", "(", "keyInfo", ",", "importedSSHKey", "{", "err", ":", "err", "}", ")", "\n", "continue", "\n", "}", "\n", "lines", ":=", "strings", ".", "Split", "(", "output", ",", "\"", "\\n", "\"", ")", "\n", "hasKey", ":=", "false", "\n", "for", "_", ",", "line", ":=", "range", "lines", "{", "if", "!", "strings", ".", "HasPrefix", "(", "line", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "hasKey", "=", "true", "\n", "// ignore key comment (e.g., user@host)", "fingerprint", ",", "_", ",", "err", ":=", "ssh", ".", "KeyFingerprint", "(", "line", ")", "\n", "keyInfo", "=", "append", "(", "keyInfo", ",", "importedSSHKey", "{", "key", ":", "line", ",", "fingerprint", ":", "fingerprint", ",", "err", ":", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "keyId", ")", ",", "}", ")", "\n", "}", "\n", "if", "!", "hasKey", "{", "keyInfo", "=", "append", "(", "keyInfo", ",", "importedSSHKey", "{", "err", ":", "errors", ".", "Errorf", "(", "\"", "\"", ",", "keyId", ")", ",", "}", ")", "\n", "}", "\n", "importResults", "[", "keyId", "]", "=", "keyInfo", "\n", "}", "\n", "return", "importResults", "\n", "}" ]
// 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
153,924
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", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "result", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "arg", ".", "Keys", ")", ")", ",", "}", "\n", "if", "len", "(", "arg", ".", "Keys", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n\n", "if", "err", ":=", "api", ".", "checkCanWrite", "(", "arg", ".", "User", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n\n", "// For now, authorised keys are global, common to all users.", "sshKeys", ",", "currentFingerprints", ",", "err", ":=", "api", ".", "currentKeyDataForAdd", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "common", ".", "ServerError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n\n", "importedKeyInfo", ":=", "runSSHKeyImport", "(", "arg", ".", "Keys", ")", "\n", "// Ensure we are not going to add invalid or duplicate keys.", "result", ".", "Results", "=", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "importedKeyInfo", ")", ")", "\n", "for", "i", ",", "key", ":=", "range", "arg", ".", "Keys", "{", "compoundErr", ":=", "\"", "\"", "\n", "for", "_", ",", "keyInfo", ":=", "range", "importedKeyInfo", "[", "key", "]", "{", "if", "keyInfo", ".", "err", "!=", "nil", "{", "compoundErr", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "keyInfo", ".", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "currentFingerprints", ".", "Contains", "(", "keyInfo", ".", "fingerprint", ")", "{", "compoundErr", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "keyInfo", ".", "key", ")", ")", "\n", "continue", "\n", "}", "\n", "sshKeys", "=", "append", "(", "sshKeys", ",", "keyInfo", ".", "key", ")", "\n", "}", "\n", "if", "compoundErr", "!=", "\"", "\"", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "errors", ".", "Errorf", "(", "strings", ".", "TrimSuffix", "(", "compoundErr", ",", "\"", "\\n", "\"", ")", ")", ")", "\n", "}", "\n\n", "}", "\n", "err", "=", "api", ".", "writeSSHKeys", "(", "sshKeys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// 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
153,925
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", ")", "{", "cfg", ",", "err", ":=", "api", ".", "model", ".", "ModelConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// For now, authorised keys are global, common to all users.", "currentKeys", "=", "ssh", ".", "SplitAuthorisedKeys", "(", "cfg", ".", "AuthorizedKeys", "(", ")", ")", "\n\n", "// 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", ")", "\n", "byComment", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "key", ":=", "range", "currentKeys", "{", "fingerprint", ",", "comment", ",", "err", ":=", "ssh", ".", "KeyFingerprint", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "key", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "byFingerprint", "[", "fingerprint", "]", "=", "key", "\n", "if", "comment", "!=", "\"", "\"", "{", "byComment", "[", "comment", "]", "=", "key", "\n", "}", "\n", "}", "\n", "return", "currentKeys", ",", "byFingerprint", ",", "byComment", ",", "nil", "\n", "}" ]
// 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
153,926
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", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "result", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "arg", ".", "Keys", ")", ")", ",", "}", "\n", "if", "len", "(", "arg", ".", "Keys", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n\n", "if", "err", ":=", "api", ".", "checkCanWrite", "(", "arg", ".", "User", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n\n", "allKeys", ",", "byFingerprint", ",", "byComment", ",", "err", ":=", "api", ".", "currentKeyDataForDelete", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "common", ".", "ServerError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n\n", "// Record the keys to be deleted in the second pass.", "keysToDelete", ":=", "make", "(", "set", ".", "Strings", ")", "\n\n", "// 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", "]", "\n", "if", "ok", "{", "keysToDelete", ".", "Add", "(", "key", ")", "\n", "continue", "\n", "}", "\n", "// Not a fingerprint, is it a comment?", "key", ",", "ok", "=", "byComment", "[", "keyId", "]", "\n", "if", "ok", "{", "if", "internalComments", ".", "Contains", "(", "keyId", ")", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyId", ")", ")", "\n", "continue", "\n", "}", "\n", "keysToDelete", ".", "Add", "(", "key", ")", "\n", "continue", "\n", "}", "\n", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyId", ")", ")", "\n", "}", "\n\n", "var", "keysToWrite", "[", "]", "string", "\n\n", "// Add back only the keys that are not deleted, preserving the order.", "for", "_", ",", "key", ":=", "range", "allKeys", "{", "if", "!", "keysToDelete", ".", "Contains", "(", "key", ")", "{", "keysToWrite", "=", "append", "(", "keysToWrite", ",", "key", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "keysToWrite", ")", "==", "0", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "common", ".", "ServerError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "err", "=", "api", ".", "writeSSHKeys", "(", "keysToWrite", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// 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
153,927
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", "}", "\n", "return", "&", "CloudAPIV2", "{", "v3", "}", ",", "nil", "\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
153,928
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", ")", "{", "if", "!", "authorizer", ".", "AuthClient", "(", ")", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n\n", "authUser", ",", "_", ":=", "authorizer", ".", "GetAuthTag", "(", ")", ".", "(", "names", ".", "UserTag", ")", "\n", "getUserAuthFunc", ":=", "func", "(", ")", "(", "common", ".", "AuthFunc", ",", "error", ")", "{", "isAdmin", ",", "err", ":=", "authorizer", ".", "HasPermission", "(", "permission", ".", "SuperuserAccess", ",", "backend", ".", "ControllerTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "func", "(", "tag", "names", ".", "Tag", ")", "bool", "{", "userTag", ",", "ok", ":=", "tag", ".", "(", "names", ".", "UserTag", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "return", "isAdmin", "||", "userTag", "==", "authUser", "\n", "}", ",", "nil", "\n", "}", "\n", "return", "&", "CloudAPI", "{", "backend", ":", "backend", ",", "ctlrBackend", ":", "ctlrBackend", ",", "authorizer", ":", "authorizer", ",", "getCredentialsAuthFunc", ":", "getUserAuthFunc", ",", "apiUser", ":", "authUser", ",", "callContext", ":", "callCtx", ",", "pool", ":", "pool", ",", "}", ",", "nil", "\n", "}" ]
// 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
153,929
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", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n", "isAdmin", ",", "err", ":=", "api", ".", "authorizer", ".", "HasPermission", "(", "permission", ".", "SuperuserAccess", ",", "api", ".", "ctlrBackend", ".", "ControllerTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "result", ".", "Clouds", "=", "make", "(", "map", "[", "string", "]", "params", ".", "Cloud", ")", "\n", "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", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n", "if", "!", "canAccess", "{", "continue", "\n", "}", "\n", "}", "\n", "paramsCloud", ":=", "common", ".", "CloudToParams", "(", "aCloud", ")", "\n", "result", ".", "Clouds", "[", "tag", ".", "String", "(", ")", "]", "=", "paramsCloud", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// 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
153,930
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 &paramsCloud, 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 &paramsCloud, 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", "(", "[", "]", "params", ".", "CloudResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "isAdmin", ",", "err", ":=", "api", ".", "authorizer", ".", "HasPermission", "(", "permission", ".", "SuperuserAccess", ",", "api", ".", "ctlrBackend", ".", "ControllerTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "results", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "one", ":=", "func", "(", "arg", "params", ".", "Entity", ")", "(", "*", "params", ".", "Cloud", ",", "error", ")", "{", "tag", ",", "err", ":=", "names", ".", "ParseCloudTag", "(", "arg", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Ensure user has permission to see the cloud.", "if", "!", "isAdmin", "{", "canAccess", ",", "err", ":=", "api", ".", "canAccessCloud", "(", "tag", ".", "Id", "(", ")", ",", "api", ".", "apiUser", ",", "permission", ".", "AddModelAccess", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "canAccess", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "tag", ".", "Id", "(", ")", ")", "\n", "}", "\n", "}", "\n", "aCloud", ",", "err", ":=", "api", ".", "backend", ".", "Cloud", "(", "tag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "paramsCloud", ":=", "common", ".", "CloudToParams", "(", "aCloud", ")", "\n", "return", "&", "paramsCloud", ",", "nil", "\n", "}", "\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Entities", "{", "aCloud", ",", "err", ":=", "one", "(", "arg", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "else", "{", "results", ".", "Results", "[", "i", "]", ".", "Cloud", "=", "aCloud", "\n", "}", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// 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
153,931
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", "(", "[", "]", "params", ".", "CloudInfoResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n\n", "oneCloudInfo", ":=", "func", "(", "arg", "params", ".", "Entity", ")", "(", "*", "params", ".", "CloudInfo", ",", "error", ")", "{", "tag", ",", "err", ":=", "names", ".", "ParseCloudTag", "(", "arg", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "api", ".", "getCloudInfo", "(", "tag", ")", "\n", "}", "\n\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Entities", "{", "cloudInfo", ",", "err", ":=", "oneCloudInfo", "(", "arg", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "Result", "=", "cloudInfo", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// 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
153,932
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", "{", "return", "params", ".", "StringResult", "{", "}", ",", "err", "\n", "}", "\n", "return", "params", ".", "StringResult", "{", "Result", ":", "names", ".", "NewCloudTag", "(", "controllerModel", ".", "Cloud", "(", ")", ")", ".", "String", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// 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
153,933
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", "(", "[", "]", "params", ".", "StringsResult", ",", "len", "(", "args", ".", "UserClouds", ")", ")", ",", "}", "\n", "authFunc", ",", "err", ":=", "api", ".", "getCredentialsAuthFunc", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", ",", "err", "\n", "}", "\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "UserClouds", "{", "userTag", ",", "err", ":=", "names", ".", "ParseUserTag", "(", "arg", ".", "UserTag", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "authFunc", "(", "userTag", ")", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "cloudTag", ",", "err", ":=", "names", ".", "ParseCloudTag", "(", "arg", ".", "CloudTag", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "cloudCredentials", ",", "err", ":=", "api", ".", "backend", ".", "CloudCredentials", "(", "userTag", ",", "cloudTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "out", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "cloudCredentials", ")", ")", "\n", "for", "tagId", ":=", "range", "cloudCredentials", "{", "if", "!", "names", ".", "IsValidCloudCredential", "(", "tagId", ")", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "tagId", ")", ")", "\n", "continue", "\n", "}", "\n", "out", "=", "append", "(", "out", ",", "names", ".", "NewCloudCredentialTag", "(", "tagId", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "Result", "=", "out", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// 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
153,934
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", ",", "false", ",", "args", ")", "\n", "}" ]
// 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", "models", "or", "their", "cloud", "instances", "are", "not", "going", "to", "be", "accessible", "with", "corresponding", "credential", "there", "will", "be", "detailed", "validation", "errors", "per", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L549-L551
153,935
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", ",", "args", ".", "Force", ",", "params", ".", "TaggedCredentials", "{", "args", ".", "Credentials", "}", ")", "\n", "}" ]
// 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", "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", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L559-L561
153,936
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 performed promised models checks and authorise use of force.", "results", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Credentials", ")", ")", ",", "}", "\n", "authFunc", ",", "err", ":=", "api", ".", "getCredentialsAuthFunc", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", ",", "err", "\n", "}", "\n\n", "opMessage", ":=", "func", "(", "force", "bool", ")", "string", "{", "if", "force", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "\"", "\"", "\n", "}", "\n\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Credentials", "{", "tag", ",", "err", ":=", "names", ".", "ParseCloudCredentialTag", "(", "arg", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "// 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", ")", "\n", "continue", "\n", "}", "\n\n", "models", ",", "err", ":=", "api", ".", "credentialModels", "(", "tag", ")", "\n", "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", ")", "\n", "continue", "\n", "}", "\n", "logger", ".", "Warningf", "(", "\"", "\"", ",", "tag", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "models", ")", "!=", "0", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "tag", ",", "opMessage", "(", "arg", ".", "Force", ")", ",", "modelsPretty", "(", "models", ")", ",", ")", "\n", "if", "!", "arg", ".", "Force", "{", "// Some models still use this credential - do not delete this credential...", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "errors", ".", "Errorf", "(", "\"", "\"", ",", "tag", ",", "len", "(", "models", ")", ",", "plural", "(", "len", "(", "models", ")", ")", ")", ")", "\n", "continue", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "api", ".", "backend", ".", "RemoveCloudCredential", "(", "tag", ")", ";", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// 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", "-", "use", "needs", "to", "be", "revoked", "nonetheless", "this", "method", "allows", "the", "use", "of", "force", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/cloud/cloud.go#L825-L882
153,937
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", ".", "ctlrBackend", ".", "ControllerTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "else", "if", "!", "isAdmin", "{", "return", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "}", "\n", "err", "=", "api", ".", "backend", ".", "AddCloud", "(", "common", ".", "CloudFromParams", "(", "cloudArgs", ".", "Name", ",", "cloudArgs", ".", "Cloud", ")", ",", "api", ".", "apiUser", ".", "Name", "(", ")", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// 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
153,938
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", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "cloudArgs", ".", "Clouds", ")", ")", ",", "}", "\n", "isAdmin", ",", "err", ":=", "api", ".", "authorizer", ".", "HasPermission", "(", "permission", ".", "SuperuserAccess", ",", "api", ".", "ctlrBackend", ".", "ControllerTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "results", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "else", "if", "!", "isAdmin", "{", "return", "results", ",", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "}", "\n", "for", "i", ",", "cloud", ":=", "range", "cloudArgs", ".", "Clouds", "{", "err", ":=", "api", ".", "backend", ".", "UpdateCloud", "(", "common", ".", "CloudFromParams", "(", "cloud", ".", "Name", ",", "cloud", ".", "Cloud", ")", ")", "\n", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// 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
153,939
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", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Changes", ")", ")", ",", "}", "\n", "if", "len", "(", "args", ".", "Changes", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Changes", "{", "cloudTag", ",", "err", ":=", "names", ".", "ParseCloudTag", "(", "arg", ".", "CloudTag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "_", ",", "err", "=", "c", ".", "backend", ".", "Cloud", "(", "cloudTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "c", ".", "apiUser", ".", "String", "(", ")", "==", "arg", ".", "UserTag", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "continue", "\n", "}", "\n\n", "isAdmin", ",", "err", ":=", "c", ".", "authorizer", ".", "HasPermission", "(", "permission", ".", "SuperuserAccess", ",", "c", ".", "backend", ".", "ControllerTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "isAdmin", "{", "callerAccess", ",", "err", ":=", "c", ".", "backend", ".", "GetCloudAccess", "(", "cloudTag", ".", "Id", "(", ")", ",", "c", ".", "apiUser", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "callerAccess", "!=", "permission", ".", "AdminAccess", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "}", "\n\n", "cloudAccess", ":=", "permission", ".", "Access", "(", "arg", ".", "Access", ")", "\n", "if", "err", ":=", "permission", ".", "ValidateCloudAccess", "(", "cloudAccess", ")", ";", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n\n", "targetUserTag", ",", "err", ":=", "names", ".", "ParseUserTag", "(", "arg", ".", "UserTag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ")", "\n", "continue", "\n", "}", "\n\n", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "ChangeCloudAccess", "(", "c", ".", "backend", ",", "cloudTag", ".", "Id", "(", ")", ",", "targetUserTag", ",", "arg", ".", "Action", ",", "cloudAccess", ")", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// 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
153,940
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", "{", "case", "params", ".", "GrantCloudAccess", ":", "err", ":=", "grantCloudAccess", "(", "backend", ",", "cloud", ",", "targetUserTag", ",", "access", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "case", "params", ".", "RevokeCloudAccess", ":", "return", "revokeCloudAccess", "(", "backend", ",", "cloud", ",", "targetUserTag", ",", "access", ")", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "action", ")", "\n", "}", "\n", "}" ]
// 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
153,941
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", ",", "}", ",", "Start", ":", "startFunc", "(", "config", ")", ",", "Output", ":", "outputFunc", ",", "}", "\n", "}" ]
// 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
153,942
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", "==", "nil", "{", "return", "nil", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "agent", "agent", ".", "Agent", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "AgentName", ",", "&", "agent", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "apiCaller", "base", ".", "APICaller", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "APICallerName", ",", "&", "apiCaller", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "NewManifoldWorker", "(", "agent", ",", "apiCaller", ",", "config", ".", "Clock", ",", "config", ".", "LeadershipGuarantee", ")", "\n", "}", "\n", "}" ]
// 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
153,943
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", "count", "int", "\n", "result", ":=", "map", "[", "interface", "{", "}", "]", "bool", "{", "}", "\n", "handle", ":=", "func", "(", "ch", "watcher", ".", "Change", ")", "{", "count", "++", "\n", "result", "[", "ch", ".", "Id", "]", "=", "ch", ".", "Revno", ">", "0", "\n", "}", "\n", "handle", "(", "one", ")", "\n", "// TODO(fwereade): 2016-03-17 lp:1558657", "timeout", ":=", "time", ".", "After", "(", "10", "*", "time", ".", "Millisecond", ")", "\n", "for", "done", ":=", "false", ";", "!", "done", ";", "{", "select", "{", "case", "<-", "stop", ":", "return", "nil", ",", "false", "\n", "case", "another", ":=", "<-", "more", ":", "handle", "(", "another", ")", "\n", "case", "<-", "timeout", ":", "done", "=", "true", "\n", "}", "\n", "}", "\n", "watchLogger", ".", "Tracef", "(", "\"", "\"", ",", "count", ",", "len", "(", "result", ")", ")", "\n", "return", "result", ",", "true", "\n", "}" ]
// 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", "observed", "to", "have", "changed", ".", "If", "a", "value", "is", "read", "from", "the", "supplied", "stop", "chan", "collect", "returns", "false", "immediately", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L140-L162
153,944
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", "observed", "to", "be", "Dead", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L220-L222
153,945
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
153,946
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
153,947
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
153,948
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", "to", "do", "extra", "initialization", "to", "the", "volume", "in", "cases", "such", "as", "iSCSI", "disks", "or", "other", "disks", "that", "have", "similar", "requirements" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L294-L296
153,949
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
153,950
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", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L355-L357
153,951
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", "scoped", "to", "the", "application", "s", "units", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L370-L372
153,952
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
153,953
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
153,954
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", "prefix", ":=", "unitGlobalKey", "(", "unit", ".", "Id", "(", ")", ")", "+", "\"", "\"", "\n", "filter", ":=", "func", "(", "id", "interface", "{", "}", ")", "bool", "{", "k", ",", "err", ":=", "sb", ".", "mb", ".", "strictLocalID", "(", "id", ".", "(", "string", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "strings", ".", "HasPrefix", "(", "k", ",", "prefix", ")", "\n", "}", "\n", "tr", ":=", "func", "(", "id", "string", ")", "string", "{", "// Transform storage attachment document ID to storage ID.", "return", "id", "[", "len", "(", "prefix", ")", ":", "]", "\n", "}", "\n", "return", "newLifecycleWatcher", "(", "sb", ".", "mb", ",", "storageAttachmentsC", ",", "members", ",", "filter", ",", "tr", ")", "\n", "}" ]
// 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
153,955
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", "+", "\"", "\"", "\n", "filter", ":=", "func", "(", "unitDocID", "interface", "{", "}", ")", "bool", "{", "unitName", ",", "err", ":=", "a", ".", "st", ".", "strictLocalID", "(", "unitDocID", ".", "(", "string", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "strings", ".", "HasPrefix", "(", "unitName", ",", "prefix", ")", "\n", "}", "\n", "return", "newLifecycleWatcher", "(", "a", ".", "st", ",", "unitsC", ",", "members", ",", "filter", ",", "nil", ")", "\n", "}" ]
// 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
153,956
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", ".", "strictLocalID", "(", "id", ".", "(", "string", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "if", "k", "!=", "a", ".", "doc", ".", "Name", "{", "return", "false", "\n", "}", "\n", "applications", ",", "closer", ":=", "a", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "applicationsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "var", "scaleField", "=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "1", "}", "}", "\n", "var", "doc", "*", "applicationDoc", "\n", "if", "err", ":=", "applications", ".", "FindId", "(", "k", ")", ".", "Select", "(", "scaleField", ")", ".", "One", "(", "&", "doc", ")", ";", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "match", ":=", "doc", ".", "DesiredScale", "!=", "currentScale", "\n", "currentScale", "=", "doc", ".", "DesiredScale", "\n", "return", "match", "\n", "}", "\n", "return", "newNotifyCollWatcher", "(", "a", ".", "st", ",", "applicationsC", ",", "filter", ")", "\n", "}" ]
// 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
153,957
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", ".", "NumberSnippet", ")", "\n", "return", "m", ".", "containersWatcher", "(", "isChild", ")", "\n", "}" ]
// 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
153,958
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", ".", "NumberSnippet", ")", "\n", "return", "m", ".", "containersWatcher", "(", "isChild", ")", "\n", "}" ]
// 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
153,959
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", "defer", "closer", "(", ")", "\n\n", "docs", ":=", "[", "]", "relationScopeDoc", "{", "}", "\n", "sel", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "\"", "\"", "+", "w", ".", "prefix", "}", "}", "}", ",", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "true", "}", "}", "}", ",", "}", "\n", "if", "err", "=", "relationScopes", ".", "Find", "(", "sel", ")", ".", "All", "(", "&", "docs", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "info", "=", "&", "scopeInfo", "{", "base", ":", "map", "[", "string", "]", "bool", "{", "}", ",", "diff", ":", "map", "[", "string", "]", "bool", "{", "}", ",", "}", "\n", "for", "_", ",", "doc", ":=", "range", "docs", "{", "if", "name", ":=", "doc", ".", "unitName", "(", ")", ";", "name", "!=", "w", ".", "ignore", "{", "info", ".", "add", "(", "name", ")", "\n", "}", "\n", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "w", ".", "prefix", ",", "pretty", ".", "Formatter", "(", "info", ")", ")", "\n", "return", "info", ",", "nil", "\n", "}" ]
// 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
153,960
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", "(", "relationScopesC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "var", "existIds", "[", "]", "string", "\n", "for", "id", ",", "exists", ":=", "range", "ids", "{", "switch", "id", ":=", "id", ".", "(", "type", ")", "{", "case", "string", ":", "if", "exists", "{", "existIds", "=", "append", "(", "existIds", ",", "id", ")", "\n", "}", "else", "{", "key", ",", "err", ":=", "w", ".", "backend", ".", "strictLocalID", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "info", ".", "remove", "(", "unitNameFromScopeKey", "(", "key", ")", ")", "\n", "}", "\n", "default", ":", "logger", ".", "Warningf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "}", "\n", "var", "docs", "[", "]", "relationScopeDoc", "\n", "sel", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "existIds", "}", "}", "}", "}", "\n", "if", "err", ":=", "relationScopes", ".", "Find", "(", "sel", ")", ".", "All", "(", "&", "docs", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "doc", ":=", "range", "docs", "{", "name", ":=", "doc", ".", "unitName", "(", ")", "\n", "if", "doc", ".", "Departing", "{", "info", ".", "remove", "(", "name", ")", "\n", "}", "else", "if", "name", "!=", "w", ".", "ignore", "{", "info", ".", "add", "(", "name", ")", "\n", "}", "\n", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "w", ".", "prefix", ",", "pretty", ".", "Formatter", "(", "info", ")", ",", "pretty", ".", "Formatter", "(", "ids", ")", ")", "\n", "return", "nil", "\n", "}" ]
// 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", "whether", "it", "s", "treated", "as", "added", "or", "removed", "depends", "on", "the", "value", "of", "the", "document", "s", "Departing", "field", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L924-L961
153,961
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", "is", "not", "globally", "scoped", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1024-L1026
153,962
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", "(", "c", ".", "Entered", ")", ")", "\n", "for", "i", ",", "name", ":=", "range", "c", ".", "Entered", "{", "key", ":=", "w", ".", "sw", ".", "prefix", "+", "name", "\n", "docID", ":=", "w", ".", "backend", ".", "docID", "(", "key", ")", "\n", "docIds", "[", "i", "]", "=", "docID", "\n", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "w", ".", "sw", ".", "prefix", ",", "c", ".", "Entered", ",", "c", ".", "Left", ")", "\n", "if", "err", ":=", "w", ".", "watcher", ".", "WatchMulti", "(", "settingsC", ",", "docIds", ",", "w", ".", "updates", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "docID", ":=", "range", "docIds", "{", "w", ".", "watching", ".", "Add", "(", "docID", ".", "(", "string", ")", ")", "\n", "}", "\n", "for", "_", ",", "name", ":=", "range", "c", ".", "Entered", "{", "key", ":=", "w", ".", "sw", ".", "prefix", "+", "name", "\n", "if", "err", ":=", "w", ".", "mergeSettings", "(", "changes", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "changes", ".", "Departed", "=", "remove", "(", "changes", ".", "Departed", ",", "name", ")", "\n", "}", "\n", "for", "_", ",", "name", ":=", "range", "c", ".", "Left", "{", "key", ":=", "w", ".", "sw", ".", "prefix", "+", "name", "\n", "docID", ":=", "w", ".", "backend", ".", "docID", "(", "key", ")", "\n", "changes", ".", "Departed", "=", "append", "(", "changes", ".", "Departed", ",", "name", ")", "\n", "if", "changes", ".", "Changed", "!=", "nil", "{", "delete", "(", "changes", ".", "Changed", ",", "name", ")", "\n", "}", "\n", "w", ".", "watcher", ".", "Unwatch", "(", "settingsC", ",", "docID", ",", "w", ".", "updates", ")", "\n", "w", ".", "watching", ".", "Remove", "(", "docID", ")", "\n", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "w", ".", "sw", ".", "prefix", ",", "changes", ")", "\n", "return", "nil", "\n", "}" ]
// 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", "RelationUnitsChange", "event", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1100-L1133
153,963
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", ")", "-", "1", "]", "\n", "return", "strs", "[", ":", "len", "(", "strs", ")", "-", "1", "]", "\n", "}", "\n", "}", "\n", "return", "strs", "\n", "}" ]
// 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
153,964
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", ".", "(", "string", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "k", "==", "r", ".", "Tag", "(", ")", ".", "Id", "(", ")", "\n", "}", "\n", "members", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "r", ".", "Id", "(", ")", "}", "}", "\n", "return", "newRelationLifeSuspendedWatcher", "(", "r", ".", "st", ",", "members", ",", "filter", ",", "nil", ")", "\n", "}" ]
// 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
153,965
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", ",", ")", "*", "relationLifeSuspendedWatcher", "{", "w", ":=", "&", "relationLifeSuspendedWatcher", "{", "commonWatcher", ":", "newCommonWatcher", "(", "backend", ")", ",", "out", ":", "make", "(", "chan", "[", "]", "string", ")", ",", "members", ":", "members", ",", "filter", ":", "filter", ",", "transform", ":", "transform", ",", "lifeSuspended", ":", "make", "(", "map", "[", "string", "]", "relationLifeSuspended", ")", ",", "}", "\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "defer", "close", "(", "w", ".", "out", ")", "\n", "return", "w", ".", "loop", "(", ")", "\n", "}", ")", "\n", "return", "w", "\n", "}" ]
// 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
153,966
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", ":=", "func", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "err", ":=", "u", ".", "Refresh", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "u", ".", "doc", ".", "Subordinates", ",", "nil", "\n", "}", "\n", "return", "newUnitsWatcher", "(", "u", ".", "st", ",", "u", ".", "Tag", "(", ")", ",", "getUnits", ",", "coll", ",", "u", ".", "doc", ".", "DocID", ")", "\n", "}" ]
// 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
153,967
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", ":=", "func", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "err", ":=", "m", ".", "Refresh", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "m", ".", "doc", ".", "Principals", ",", "nil", "\n", "}", "\n", "return", "newUnitsWatcher", "(", "m", ".", "st", ",", "m", ".", "Tag", "(", ")", ",", "getUnits", ",", "coll", ",", "m", ".", "doc", ".", "DocID", ")", "\n", "}" ]
// 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
153,968
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", "\n", "}", "\n", "return", "w", ".", "watchUnits", "(", "initialNames", ",", "nil", ")", "\n", "}" ]
// 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
153,969
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", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "unknown", "[", "]", "string", "\n", "for", "_", ",", "name", ":=", "range", "latest", "{", "if", "_", ",", "found", ":=", "w", ".", "life", "[", "name", "]", ";", "!", "found", "{", "unknown", "=", "append", "(", "unknown", ",", "name", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "unknown", ")", ">", "0", "{", "changes", ",", "err", "=", "w", ".", "watchUnits", "(", "unknown", ",", "changes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "for", "name", ":=", "range", "w", ".", "life", "{", "if", "hasString", "(", "latest", ",", "name", ")", "{", "continue", "\n", "}", "\n", "if", "!", "hasString", "(", "changes", ",", "name", ")", "{", "changes", "=", "append", "(", "changes", ",", "name", ")", "\n", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "unitsC", ",", "name", ")", "\n", "delete", "(", "w", ".", "life", ",", "name", ")", "\n", "w", ".", "watcher", ".", "Unwatch", "(", "unitsC", ",", "w", ".", "backend", ".", "docID", "(", "name", ")", ",", "w", ".", "in", ")", "\n", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "changes", ")", "\n", "return", "changes", ",", "nil", "\n", "}" ]
// 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
153,970
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", "var", "doc", "lifeWatchDoc", "\n", "units", ",", "closer", ":=", "w", ".", "db", ".", "GetCollection", "(", "unitsC", ")", "\n", "err", ":=", "units", ".", "FindId", "(", "name", ")", ".", "Select", "(", "lifeWatchFields", ")", ".", "One", "(", "&", "doc", ")", "\n", "closer", "(", ")", "\n", "gone", ":=", "false", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "gone", "=", "true", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "if", "doc", ".", "Life", "==", "Dead", "{", "gone", "=", "true", "\n", "}", "\n", "life", ":=", "w", ".", "life", "[", "name", "]", "\n", "switch", "{", "case", "gone", ":", "delete", "(", "w", ".", "life", ",", "name", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "unitsC", ",", "name", ")", "\n", "w", ".", "watcher", ".", "Unwatch", "(", "unitsC", ",", "w", ".", "backend", ".", "docID", "(", "name", ")", ",", "w", ".", "in", ")", "\n", "case", "life", "!=", "doc", ".", "Life", ":", "logger", ".", "Tracef", "(", "\"", "\"", ",", "unitsC", ",", "name", ",", "doc", ".", "Life", ")", "\n", "w", ".", "life", "[", "name", "]", "=", "doc", ".", "Life", "\n", "default", ":", "return", "changes", ",", "nil", "\n", "}", "\n", "if", "!", "hasString", "(", "changes", ",", "name", ")", "{", "changes", "=", "append", "(", "changes", ",", "name", ")", "\n", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "changes", ")", "\n", "return", "changes", ",", "nil", "\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
153,971
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
153,972
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
153,973
juju/juju
state/watcher.go
WatchLeaderSettings
func (a *Application) WatchLeaderSettings() NotifyWatcher { docId := a.st.docID(leadershipSettingsKey(a.Name())) return newEntityWatcher(a.st, settingsC, docId) }
go
func (a *Application) WatchLeaderSettings() NotifyWatcher { docId := a.st.docID(leadershipSettingsKey(a.Name())) return newEntityWatcher(a.st, settingsC, docId) }
[ "func", "(", "a", "*", "Application", ")", "WatchLeaderSettings", "(", ")", "NotifyWatcher", "{", "docId", ":=", "a", ".", "st", ".", "docID", "(", "leadershipSettingsKey", "(", "a", ".", "Name", "(", ")", ")", ")", "\n", "return", "newEntityWatcher", "(", "a", ".", "st", ",", "settingsC", ",", "docId", ")", "\n", "}" ]
// WatchLeaderSettings returns a watcher for observing changed to an application's // leader settings.
[ "WatchLeaderSettings", "returns", "a", "watcher", "for", "observing", "changed", "to", "an", "application", "s", "leader", "settings", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1669-L1672
153,974
juju/juju
state/watcher.go
Watch
func (u *Unit) Watch() NotifyWatcher { return newEntityWatcher(u.st, unitsC, u.doc.DocID) }
go
func (u *Unit) Watch() NotifyWatcher { return newEntityWatcher(u.st, unitsC, u.doc.DocID) }
[ "func", "(", "u", "*", "Unit", ")", "Watch", "(", ")", "NotifyWatcher", "{", "return", "newEntityWatcher", "(", "u", ".", "st", ",", "unitsC", ",", "u", ".", "doc", ".", "DocID", ")", "\n", "}" ]
// Watch returns a watcher for observing changes to a unit.
[ "Watch", "returns", "a", "watcher", "for", "observing", "changes", "to", "a", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1675-L1677
153,975
juju/juju
state/watcher.go
Watch
func (m *Model) Watch() NotifyWatcher { return newEntityWatcher(m.st, modelsC, m.doc.UUID) }
go
func (m *Model) Watch() NotifyWatcher { return newEntityWatcher(m.st, modelsC, m.doc.UUID) }
[ "func", "(", "m", "*", "Model", ")", "Watch", "(", ")", "NotifyWatcher", "{", "return", "newEntityWatcher", "(", "m", ".", "st", ",", "modelsC", ",", "m", ".", "doc", ".", "UUID", ")", "\n", "}" ]
// Watch returns a watcher for observing changes to a model.
[ "Watch", "returns", "a", "watcher", "for", "observing", "changes", "to", "a", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1680-L1682
153,976
juju/juju
state/watcher.go
WatchInstanceData
func (m *Machine) WatchInstanceData() NotifyWatcher { return newEntityWatcher(m.st, instanceDataC, m.doc.Id) }
go
func (m *Machine) WatchInstanceData() NotifyWatcher { return newEntityWatcher(m.st, instanceDataC, m.doc.Id) }
[ "func", "(", "m", "*", "Machine", ")", "WatchInstanceData", "(", ")", "NotifyWatcher", "{", "return", "newEntityWatcher", "(", "m", ".", "st", ",", "instanceDataC", ",", "m", ".", "doc", ".", "Id", ")", "\n", "}" ]
// WatchInstanceData returns a watcher for observing changes to a model.
[ "WatchInstanceData", "returns", "a", "watcher", "for", "observing", "changes", "to", "a", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1685-L1687
153,977
juju/juju
state/watcher.go
WatchForModelConfigChanges
func (model *Model) WatchForModelConfigChanges() NotifyWatcher { return newEntityWatcher(model.st, settingsC, model.st.docID(modelGlobalKey)) }
go
func (model *Model) WatchForModelConfigChanges() NotifyWatcher { return newEntityWatcher(model.st, settingsC, model.st.docID(modelGlobalKey)) }
[ "func", "(", "model", "*", "Model", ")", "WatchForModelConfigChanges", "(", ")", "NotifyWatcher", "{", "return", "newEntityWatcher", "(", "model", ".", "st", ",", "settingsC", ",", "model", ".", "st", ".", "docID", "(", "modelGlobalKey", ")", ")", "\n", "}" ]
// WatchForModelConfigChanges returns a NotifyWatcher waiting for the Model // Config to change.
[ "WatchForModelConfigChanges", "returns", "a", "NotifyWatcher", "waiting", "for", "the", "Model", "Config", "to", "change", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1703-L1705
153,978
juju/juju
state/watcher.go
WatchCloudSpecChanges
func (model *Model) WatchCloudSpecChanges() NotifyWatcher { return newEntityWatcher(model.st, cloudsC, model.Cloud()) }
go
func (model *Model) WatchCloudSpecChanges() NotifyWatcher { return newEntityWatcher(model.st, cloudsC, model.Cloud()) }
[ "func", "(", "model", "*", "Model", ")", "WatchCloudSpecChanges", "(", ")", "NotifyWatcher", "{", "return", "newEntityWatcher", "(", "model", ".", "st", ",", "cloudsC", ",", "model", ".", "Cloud", "(", ")", ")", "\n", "}" ]
// WatchCloudSpecChanges returns a NotifyWatcher waiting for the cloud // to change for the model.
[ "WatchCloudSpecChanges", "returns", "a", "NotifyWatcher", "waiting", "for", "the", "cloud", "to", "change", "for", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1709-L1711
153,979
juju/juju
state/watcher.go
WatchModelEntityReferences
func (st *State) WatchModelEntityReferences(mUUID string) NotifyWatcher { return newEntityWatcher(st, modelEntityRefsC, mUUID) }
go
func (st *State) WatchModelEntityReferences(mUUID string) NotifyWatcher { return newEntityWatcher(st, modelEntityRefsC, mUUID) }
[ "func", "(", "st", "*", "State", ")", "WatchModelEntityReferences", "(", "mUUID", "string", ")", "NotifyWatcher", "{", "return", "newEntityWatcher", "(", "st", ",", "modelEntityRefsC", ",", "mUUID", ")", "\n", "}" ]
// WatchModelEntityReferences returns a NotifyWatcher waiting for the Model // Entity references to change for specified model.
[ "WatchModelEntityReferences", "returns", "a", "NotifyWatcher", "waiting", "for", "the", "Model", "Entity", "references", "to", "change", "for", "specified", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1715-L1717
153,980
juju/juju
state/watcher.go
WatchStorageAttachment
func (sb *storageBackend) WatchStorageAttachment(s names.StorageTag, u names.UnitTag) NotifyWatcher { id := storageAttachmentId(u.Id(), s.Id()) return newEntityWatcher(sb.mb, storageAttachmentsC, sb.mb.docID(id)) }
go
func (sb *storageBackend) WatchStorageAttachment(s names.StorageTag, u names.UnitTag) NotifyWatcher { id := storageAttachmentId(u.Id(), s.Id()) return newEntityWatcher(sb.mb, storageAttachmentsC, sb.mb.docID(id)) }
[ "func", "(", "sb", "*", "storageBackend", ")", "WatchStorageAttachment", "(", "s", "names", ".", "StorageTag", ",", "u", "names", ".", "UnitTag", ")", "NotifyWatcher", "{", "id", ":=", "storageAttachmentId", "(", "u", ".", "Id", "(", ")", ",", "s", ".", "Id", "(", ")", ")", "\n", "return", "newEntityWatcher", "(", "sb", ".", "mb", ",", "storageAttachmentsC", ",", "sb", ".", "mb", ".", "docID", "(", "id", ")", ")", "\n", "}" ]
// WatchStorageAttachment returns a watcher for observing changes // to a storage attachment.
[ "WatchStorageAttachment", "returns", "a", "watcher", "for", "observing", "changes", "to", "a", "storage", "attachment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1739-L1742
153,981
juju/juju
state/watcher.go
WatchVolumeAttachment
func (sb *storageBackend) WatchVolumeAttachment(host names.Tag, v names.VolumeTag) NotifyWatcher { id := volumeAttachmentId(host.Id(), v.Id()) return newEntityWatcher(sb.mb, volumeAttachmentsC, sb.mb.docID(id)) }
go
func (sb *storageBackend) WatchVolumeAttachment(host names.Tag, v names.VolumeTag) NotifyWatcher { id := volumeAttachmentId(host.Id(), v.Id()) return newEntityWatcher(sb.mb, volumeAttachmentsC, sb.mb.docID(id)) }
[ "func", "(", "sb", "*", "storageBackend", ")", "WatchVolumeAttachment", "(", "host", "names", ".", "Tag", ",", "v", "names", ".", "VolumeTag", ")", "NotifyWatcher", "{", "id", ":=", "volumeAttachmentId", "(", "host", ".", "Id", "(", ")", ",", "v", ".", "Id", "(", ")", ")", "\n", "return", "newEntityWatcher", "(", "sb", ".", "mb", ",", "volumeAttachmentsC", ",", "sb", ".", "mb", ".", "docID", "(", "id", ")", ")", "\n", "}" ]
// WatchVolumeAttachment returns a watcher for observing changes // to a volume attachment.
[ "WatchVolumeAttachment", "returns", "a", "watcher", "for", "observing", "changes", "to", "a", "volume", "attachment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1746-L1749
153,982
juju/juju
state/watcher.go
WatchFilesystemAttachment
func (sb *storageBackend) WatchFilesystemAttachment(host names.Tag, f names.FilesystemTag) NotifyWatcher { id := filesystemAttachmentId(host.Id(), f.Id()) return newEntityWatcher(sb.mb, filesystemAttachmentsC, sb.mb.docID(id)) }
go
func (sb *storageBackend) WatchFilesystemAttachment(host names.Tag, f names.FilesystemTag) NotifyWatcher { id := filesystemAttachmentId(host.Id(), f.Id()) return newEntityWatcher(sb.mb, filesystemAttachmentsC, sb.mb.docID(id)) }
[ "func", "(", "sb", "*", "storageBackend", ")", "WatchFilesystemAttachment", "(", "host", "names", ".", "Tag", ",", "f", "names", ".", "FilesystemTag", ")", "NotifyWatcher", "{", "id", ":=", "filesystemAttachmentId", "(", "host", ".", "Id", "(", ")", ",", "f", ".", "Id", "(", ")", ")", "\n", "return", "newEntityWatcher", "(", "sb", ".", "mb", ",", "filesystemAttachmentsC", ",", "sb", ".", "mb", ".", "docID", "(", "id", ")", ")", "\n", "}" ]
// WatchFilesystemAttachment returns a watcher for observing changes // to a filesystem attachment.
[ "WatchFilesystemAttachment", "returns", "a", "watcher", "for", "observing", "changes", "to", "a", "filesystem", "attachment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1753-L1756
153,983
juju/juju
state/watcher.go
WatchCharmConfig
func (a *Application) WatchCharmConfig() (NotifyWatcher, error) { configKey := a.charmConfigKey() return newEntityWatcher(a.st, settingsC, a.st.docID(configKey)), nil }
go
func (a *Application) WatchCharmConfig() (NotifyWatcher, error) { configKey := a.charmConfigKey() return newEntityWatcher(a.st, settingsC, a.st.docID(configKey)), nil }
[ "func", "(", "a", "*", "Application", ")", "WatchCharmConfig", "(", ")", "(", "NotifyWatcher", ",", "error", ")", "{", "configKey", ":=", "a", ".", "charmConfigKey", "(", ")", "\n", "return", "newEntityWatcher", "(", "a", ".", "st", ",", "settingsC", ",", "a", ".", "st", ".", "docID", "(", "configKey", ")", ")", ",", "nil", "\n", "}" ]
// WatchCharmConfig returns a watcher for observing changes to the // application's charm configuration settings. The returned watcher will be // valid only while the application's charm URL is not changed.
[ "WatchCharmConfig", "returns", "a", "watcher", "for", "observing", "changes", "to", "the", "application", "s", "charm", "configuration", "settings", ".", "The", "returned", "watcher", "will", "be", "valid", "only", "while", "the", "application", "s", "charm", "URL", "is", "not", "changed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1761-L1764
153,984
juju/juju
state/watcher.go
WatchApplicationConfigSettings
func (u *Unit) WatchApplicationConfigSettings() (NotifyWatcher, error) { applicationConfigKey := applicationConfigKey(u.ApplicationName()) return newEntityWatcher(u.st, settingsC, u.st.docID(applicationConfigKey)), nil }
go
func (u *Unit) WatchApplicationConfigSettings() (NotifyWatcher, error) { applicationConfigKey := applicationConfigKey(u.ApplicationName()) return newEntityWatcher(u.st, settingsC, u.st.docID(applicationConfigKey)), nil }
[ "func", "(", "u", "*", "Unit", ")", "WatchApplicationConfigSettings", "(", ")", "(", "NotifyWatcher", ",", "error", ")", "{", "applicationConfigKey", ":=", "applicationConfigKey", "(", "u", ".", "ApplicationName", "(", ")", ")", "\n", "return", "newEntityWatcher", "(", "u", ".", "st", ",", "settingsC", ",", "u", ".", "st", ".", "docID", "(", "applicationConfigKey", ")", ")", ",", "nil", "\n", "}" ]
// WatchApplicationConfigSettings is the same as WatchConfigSettings but // notifies on changes to application configuration not charm configuration.
[ "WatchApplicationConfigSettings", "is", "the", "same", "as", "WatchConfigSettings", "but", "notifies", "on", "changes", "to", "application", "configuration", "not", "charm", "configuration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1782-L1785
153,985
juju/juju
state/watcher.go
WatchConfigSettingsHash
func (u *Unit) WatchConfigSettingsHash() (StringsWatcher, error) { if u.doc.CharmURL == nil { return nil, fmt.Errorf("unit charm not set") } charmConfigKey := applicationCharmConfigKey(u.doc.Application, u.doc.CharmURL) return newSettingsHashWatcher(u.st, charmConfigKey), nil }
go
func (u *Unit) WatchConfigSettingsHash() (StringsWatcher, error) { if u.doc.CharmURL == nil { return nil, fmt.Errorf("unit charm not set") } charmConfigKey := applicationCharmConfigKey(u.doc.Application, u.doc.CharmURL) return newSettingsHashWatcher(u.st, charmConfigKey), nil }
[ "func", "(", "u", "*", "Unit", ")", "WatchConfigSettingsHash", "(", ")", "(", "StringsWatcher", ",", "error", ")", "{", "if", "u", ".", "doc", ".", "CharmURL", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "charmConfigKey", ":=", "applicationCharmConfigKey", "(", "u", ".", "doc", ".", "Application", ",", "u", ".", "doc", ".", "CharmURL", ")", "\n", "return", "newSettingsHashWatcher", "(", "u", ".", "st", ",", "charmConfigKey", ")", ",", "nil", "\n", "}" ]
// WatchConfigSettingsHash returns a watcher that yields a hash of the // unit's charm config settings whenever they are changed. The // returned watcher will be valid only while the application's charm // URL is not changed.
[ "WatchConfigSettingsHash", "returns", "a", "watcher", "that", "yields", "a", "hash", "of", "the", "unit", "s", "charm", "config", "settings", "whenever", "they", "are", "changed", ".", "The", "returned", "watcher", "will", "be", "valid", "only", "while", "the", "application", "s", "charm", "URL", "is", "not", "changed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1791-L1797
153,986
juju/juju
state/watcher.go
WatchApplicationConfigSettingsHash
func (u *Unit) WatchApplicationConfigSettingsHash() (StringsWatcher, error) { applicationConfigKey := applicationConfigKey(u.ApplicationName()) return newSettingsHashWatcher(u.st, applicationConfigKey), nil }
go
func (u *Unit) WatchApplicationConfigSettingsHash() (StringsWatcher, error) { applicationConfigKey := applicationConfigKey(u.ApplicationName()) return newSettingsHashWatcher(u.st, applicationConfigKey), nil }
[ "func", "(", "u", "*", "Unit", ")", "WatchApplicationConfigSettingsHash", "(", ")", "(", "StringsWatcher", ",", "error", ")", "{", "applicationConfigKey", ":=", "applicationConfigKey", "(", "u", ".", "ApplicationName", "(", ")", ")", "\n", "return", "newSettingsHashWatcher", "(", "u", ".", "st", ",", "applicationConfigKey", ")", ",", "nil", "\n", "}" ]
// WatchApplicationConfigSettingsHash is the same as // WatchConfigSettingsHash but watches the application's config rather // than charm configuration. Yields a hash of the application config // with each change.
[ "WatchApplicationConfigSettingsHash", "is", "the", "same", "as", "WatchConfigSettingsHash", "but", "watches", "the", "application", "s", "config", "rather", "than", "charm", "configuration", ".", "Yields", "a", "hash", "of", "the", "application", "config", "with", "each", "change", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1803-L1806
153,987
juju/juju
state/watcher.go
WatchMeterStatus
func (u *Unit) WatchMeterStatus() NotifyWatcher { return newDocWatcher(u.st, []docKey{ { meterStatusC, u.st.docID(u.globalMeterStatusKey()), }, { meterStatusC, metricsManagerKey(u.st), }, }) }
go
func (u *Unit) WatchMeterStatus() NotifyWatcher { return newDocWatcher(u.st, []docKey{ { meterStatusC, u.st.docID(u.globalMeterStatusKey()), }, { meterStatusC, metricsManagerKey(u.st), }, }) }
[ "func", "(", "u", "*", "Unit", ")", "WatchMeterStatus", "(", ")", "NotifyWatcher", "{", "return", "newDocWatcher", "(", "u", ".", "st", ",", "[", "]", "docKey", "{", "{", "meterStatusC", ",", "u", ".", "st", ".", "docID", "(", "u", ".", "globalMeterStatusKey", "(", ")", ")", ",", "}", ",", "{", "meterStatusC", ",", "metricsManagerKey", "(", "u", ".", "st", ")", ",", "}", ",", "}", ")", "\n", "}" ]
// WatchMeterStatus returns a watcher observing changes that affect the meter status // of a unit.
[ "WatchMeterStatus", "returns", "a", "watcher", "observing", "changes", "that", "affect", "the", "meter", "status", "of", "a", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1810-L1820
153,988
juju/juju
state/watcher.go
WatchLXDProfileUpgradeNotifications
func (m *Machine) WatchLXDProfileUpgradeNotifications(applicationName string) (StringsWatcher, error) { app, err := m.st.Application(applicationName) if err != nil { return nil, errors.Trace(err) } watchDocId := app.doc.DocID return watchInstanceCharmProfileCompatibilityData(m.st, watchDocId), nil }
go
func (m *Machine) WatchLXDProfileUpgradeNotifications(applicationName string) (StringsWatcher, error) { app, err := m.st.Application(applicationName) if err != nil { return nil, errors.Trace(err) } watchDocId := app.doc.DocID return watchInstanceCharmProfileCompatibilityData(m.st, watchDocId), nil }
[ "func", "(", "m", "*", "Machine", ")", "WatchLXDProfileUpgradeNotifications", "(", "applicationName", "string", ")", "(", "StringsWatcher", ",", "error", ")", "{", "app", ",", "err", ":=", "m", ".", "st", ".", "Application", "(", "applicationName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "watchDocId", ":=", "app", ".", "doc", ".", "DocID", "\n", "return", "watchInstanceCharmProfileCompatibilityData", "(", "m", ".", "st", ",", "watchDocId", ")", ",", "nil", "\n", "}" ]
// WatchLXDProfileUpgradeNotifications returns a watcher that observes the status // of a lxd profile upgrade by monitoring changes on the unit machine's lxd profile // upgrade completed field that is specific to an application name. Used by // UniterAPI v9.
[ "WatchLXDProfileUpgradeNotifications", "returns", "a", "watcher", "that", "observes", "the", "status", "of", "a", "lxd", "profile", "upgrade", "by", "monitoring", "changes", "on", "the", "unit", "machine", "s", "lxd", "profile", "upgrade", "completed", "field", "that", "is", "specific", "to", "an", "application", "name", ".", "Used", "by", "UniterAPI", "v9", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1826-L1833
153,989
juju/juju
state/watcher.go
WatchLXDProfileUpgradeNotifications
func (u *Unit) WatchLXDProfileUpgradeNotifications() (StringsWatcher, error) { app, err := u.Application() if err != nil { return nil, errors.Trace(err) } watchDocId := app.doc.DocID return watchInstanceCharmProfileCompatibilityData(u.st, watchDocId), nil }
go
func (u *Unit) WatchLXDProfileUpgradeNotifications() (StringsWatcher, error) { app, err := u.Application() if err != nil { return nil, errors.Trace(err) } watchDocId := app.doc.DocID return watchInstanceCharmProfileCompatibilityData(u.st, watchDocId), nil }
[ "func", "(", "u", "*", "Unit", ")", "WatchLXDProfileUpgradeNotifications", "(", ")", "(", "StringsWatcher", ",", "error", ")", "{", "app", ",", "err", ":=", "u", ".", "Application", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "watchDocId", ":=", "app", ".", "doc", ".", "DocID", "\n", "return", "watchInstanceCharmProfileCompatibilityData", "(", "u", ".", "st", ",", "watchDocId", ")", ",", "nil", "\n", "}" ]
// WatchLXDProfileUpgradeNotifications returns a watcher that observes the status // of a lxd profile upgrade by monitoring changes on the unit machine's lxd profile // upgrade completed field that is specific to itself.
[ "WatchLXDProfileUpgradeNotifications", "returns", "a", "watcher", "that", "observes", "the", "status", "of", "a", "lxd", "profile", "upgrade", "by", "monitoring", "changes", "on", "the", "unit", "machine", "s", "lxd", "profile", "upgrade", "completed", "field", "that", "is", "specific", "to", "itself", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1838-L1845
153,990
juju/juju
state/watcher.go
WatchUpgradeSeriesNotifications
func (m *Machine) WatchUpgradeSeriesNotifications() (NotifyWatcher, error) { watch := newEntityWatcher(m.st, machineUpgradeSeriesLocksC, m.doc.DocID) if _, ok := <-watch.Changes(); ok { return watch, nil } return nil, watcher.EnsureErr(watch) }
go
func (m *Machine) WatchUpgradeSeriesNotifications() (NotifyWatcher, error) { watch := newEntityWatcher(m.st, machineUpgradeSeriesLocksC, m.doc.DocID) if _, ok := <-watch.Changes(); ok { return watch, nil } return nil, watcher.EnsureErr(watch) }
[ "func", "(", "m", "*", "Machine", ")", "WatchUpgradeSeriesNotifications", "(", ")", "(", "NotifyWatcher", ",", "error", ")", "{", "watch", ":=", "newEntityWatcher", "(", "m", ".", "st", ",", "machineUpgradeSeriesLocksC", ",", "m", ".", "doc", ".", "DocID", ")", "\n", "if", "_", ",", "ok", ":=", "<-", "watch", ".", "Changes", "(", ")", ";", "ok", "{", "return", "watch", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "watcher", ".", "EnsureErr", "(", "watch", ")", "\n", "}" ]
// WatchUpgradeSeriesNotifications returns a watcher that observes the status of // a series upgrade by monitoring changes to its parent machine's upgrade series // lock.
[ "WatchUpgradeSeriesNotifications", "returns", "a", "watcher", "that", "observes", "the", "status", "of", "a", "series", "upgrade", "by", "monitoring", "changes", "to", "its", "parent", "machine", "s", "upgrade", "series", "lock", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2023-L2030
153,991
juju/juju
state/watcher.go
getTxnRevno
func getTxnRevno(coll mongo.Collection, id interface{}) (int64, error) { doc := struct { TxnRevno int64 `bson:"txn-revno"` }{} fields := bson.D{{"txn-revno", 1}} if err := coll.FindId(id).Select(fields).One(&doc); err == mgo.ErrNotFound { return -1, nil } else if err != nil { return 0, err } return doc.TxnRevno, nil }
go
func getTxnRevno(coll mongo.Collection, id interface{}) (int64, error) { doc := struct { TxnRevno int64 `bson:"txn-revno"` }{} fields := bson.D{{"txn-revno", 1}} if err := coll.FindId(id).Select(fields).One(&doc); err == mgo.ErrNotFound { return -1, nil } else if err != nil { return 0, err } return doc.TxnRevno, nil }
[ "func", "getTxnRevno", "(", "coll", "mongo", ".", "Collection", ",", "id", "interface", "{", "}", ")", "(", "int64", ",", "error", ")", "{", "doc", ":=", "struct", "{", "TxnRevno", "int64", "`bson:\"txn-revno\"`", "\n", "}", "{", "}", "\n", "fields", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "1", "}", "}", "\n", "if", "err", ":=", "coll", ".", "FindId", "(", "id", ")", ".", "Select", "(", "fields", ")", ".", "One", "(", "&", "doc", ")", ";", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "-", "1", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "doc", ".", "TxnRevno", ",", "nil", "\n", "}" ]
// getTxnRevno returns the transaction revision number of the // given document id in the given collection. It is useful to enable // a watcher.Watcher to be primed with the correct revision // id.
[ "getTxnRevno", "returns", "the", "transaction", "revision", "number", "of", "the", "given", "document", "id", "in", "the", "given", "collection", ".", "It", "is", "useful", "to", "enable", "a", "watcher", ".", "Watcher", "to", "be", "primed", "with", "the", "correct", "revision", "id", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2076-L2087
153,992
juju/juju
state/watcher.go
watchNewUnits
func (w *machineUnitsWatcher) watchNewUnits(unitNames, pending []string, unitColl mongo.Collection) ([]string, error) { if len(unitNames) == 0 { return pending, nil } ids := make([]interface{}, len(unitNames)) for i := range unitNames { ids[i] = w.backend.docID(unitNames[i]) } logger.Tracef("for machine %q watching new units %q", w.machine.doc.DocID, unitNames) err := w.watcher.WatchMulti(unitsC, ids, w.in) if err != nil { return nil, errors.Trace(err) } if unitColl == nil { var closer SessionCloser unitColl, closer = w.db.GetCollection(unitsC) defer closer() } var doc unitDoc iter := unitColl.Find(bson.M{"_id": bson.M{"$in": unitNames}}).Iter() unknownSubs := set.NewStrings() notfound := set.NewStrings(unitNames...) for iter.Next(&doc) { notfound.Remove(doc.Name) w.known[doc.Name] = doc.Life pending = append(pending, doc.Name) // now load subordinates for _, subunitName := range doc.Subordinates { if _, subknown := w.known[subunitName]; !subknown { unknownSubs.Add(subunitName) } } } if err := iter.Close(); err != nil { return nil, errors.Trace(err) } for name := range notfound { logger.Debugf("unit %q referenced but not found", name) w.watcher.Unwatch(unitsC, w.backend.docID(name), w.in) } if !unknownSubs.IsEmpty() { pending, err = w.watchNewUnits(unknownSubs.Values(), pending, unitColl) if err != nil { return nil, errors.Trace(err) } } return pending, nil }
go
func (w *machineUnitsWatcher) watchNewUnits(unitNames, pending []string, unitColl mongo.Collection) ([]string, error) { if len(unitNames) == 0 { return pending, nil } ids := make([]interface{}, len(unitNames)) for i := range unitNames { ids[i] = w.backend.docID(unitNames[i]) } logger.Tracef("for machine %q watching new units %q", w.machine.doc.DocID, unitNames) err := w.watcher.WatchMulti(unitsC, ids, w.in) if err != nil { return nil, errors.Trace(err) } if unitColl == nil { var closer SessionCloser unitColl, closer = w.db.GetCollection(unitsC) defer closer() } var doc unitDoc iter := unitColl.Find(bson.M{"_id": bson.M{"$in": unitNames}}).Iter() unknownSubs := set.NewStrings() notfound := set.NewStrings(unitNames...) for iter.Next(&doc) { notfound.Remove(doc.Name) w.known[doc.Name] = doc.Life pending = append(pending, doc.Name) // now load subordinates for _, subunitName := range doc.Subordinates { if _, subknown := w.known[subunitName]; !subknown { unknownSubs.Add(subunitName) } } } if err := iter.Close(); err != nil { return nil, errors.Trace(err) } for name := range notfound { logger.Debugf("unit %q referenced but not found", name) w.watcher.Unwatch(unitsC, w.backend.docID(name), w.in) } if !unknownSubs.IsEmpty() { pending, err = w.watchNewUnits(unknownSubs.Values(), pending, unitColl) if err != nil { return nil, errors.Trace(err) } } return pending, nil }
[ "func", "(", "w", "*", "machineUnitsWatcher", ")", "watchNewUnits", "(", "unitNames", ",", "pending", "[", "]", "string", ",", "unitColl", "mongo", ".", "Collection", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "len", "(", "unitNames", ")", "==", "0", "{", "return", "pending", ",", "nil", "\n", "}", "\n", "ids", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "unitNames", ")", ")", "\n", "for", "i", ":=", "range", "unitNames", "{", "ids", "[", "i", "]", "=", "w", ".", "backend", ".", "docID", "(", "unitNames", "[", "i", "]", ")", "\n", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "w", ".", "machine", ".", "doc", ".", "DocID", ",", "unitNames", ")", "\n", "err", ":=", "w", ".", "watcher", ".", "WatchMulti", "(", "unitsC", ",", "ids", ",", "w", ".", "in", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "unitColl", "==", "nil", "{", "var", "closer", "SessionCloser", "\n", "unitColl", ",", "closer", "=", "w", ".", "db", ".", "GetCollection", "(", "unitsC", ")", "\n", "defer", "closer", "(", ")", "\n", "}", "\n", "var", "doc", "unitDoc", "\n", "iter", ":=", "unitColl", ".", "Find", "(", "bson", ".", "M", "{", "\"", "\"", ":", "bson", ".", "M", "{", "\"", "\"", ":", "unitNames", "}", "}", ")", ".", "Iter", "(", ")", "\n", "unknownSubs", ":=", "set", ".", "NewStrings", "(", ")", "\n", "notfound", ":=", "set", ".", "NewStrings", "(", "unitNames", "...", ")", "\n", "for", "iter", ".", "Next", "(", "&", "doc", ")", "{", "notfound", ".", "Remove", "(", "doc", ".", "Name", ")", "\n", "w", ".", "known", "[", "doc", ".", "Name", "]", "=", "doc", ".", "Life", "\n", "pending", "=", "append", "(", "pending", ",", "doc", ".", "Name", ")", "\n", "// now load subordinates", "for", "_", ",", "subunitName", ":=", "range", "doc", ".", "Subordinates", "{", "if", "_", ",", "subknown", ":=", "w", ".", "known", "[", "subunitName", "]", ";", "!", "subknown", "{", "unknownSubs", ".", "Add", "(", "subunitName", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "iter", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "name", ":=", "range", "notfound", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "name", ")", "\n", "w", ".", "watcher", ".", "Unwatch", "(", "unitsC", ",", "w", ".", "backend", ".", "docID", "(", "name", ")", ",", "w", ".", "in", ")", "\n", "}", "\n", "if", "!", "unknownSubs", ".", "IsEmpty", "(", ")", "{", "pending", ",", "err", "=", "w", ".", "watchNewUnits", "(", "unknownSubs", ".", "Values", "(", ")", ",", "pending", ",", "unitColl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "pending", ",", "nil", "\n", "}" ]
// watchNewUnits sets up a watcher for all of the named units and then updates pending changes. // There is an assumption that all unitNames being passed are unknown and do not have a watch active for them.
[ "watchNewUnits", "sets", "up", "a", "watcher", "for", "all", "of", "the", "named", "units", "and", "then", "updates", "pending", "changes", ".", "There", "is", "an", "assumption", "that", "all", "unitNames", "being", "passed", "are", "unknown", "and", "do", "not", "have", "a", "watch", "active", "for", "them", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2186-L2234
153,993
juju/juju
state/watcher.go
removeWatchedUnit
func (w *machineUnitsWatcher) removeWatchedUnit(unitName string, doc unitDoc, pending []string) ([]string, error) { logger.Tracef("machineUnitsWatcher removing unit %q for life %q", doc.Name, doc.Life) life, known := w.known[unitName] // Unit was removed or unassigned from w.machine if known { delete(w.known, unitName) docID := w.backend.docID(unitName) w.watcher.Unwatch(unitsC, docID, w.in) if life != Dead && !hasString(pending, unitName) { pending = append(pending, unitName) } for _, subunitName := range doc.Subordinates { if sublife, subknown := w.known[subunitName]; subknown { delete(w.known, subunitName) w.watcher.Unwatch(unitsC, w.backend.docID(subunitName), w.in) if sublife != Dead && !hasString(pending, subunitName) { pending = append(pending, subunitName) } } } } return pending, nil }
go
func (w *machineUnitsWatcher) removeWatchedUnit(unitName string, doc unitDoc, pending []string) ([]string, error) { logger.Tracef("machineUnitsWatcher removing unit %q for life %q", doc.Name, doc.Life) life, known := w.known[unitName] // Unit was removed or unassigned from w.machine if known { delete(w.known, unitName) docID := w.backend.docID(unitName) w.watcher.Unwatch(unitsC, docID, w.in) if life != Dead && !hasString(pending, unitName) { pending = append(pending, unitName) } for _, subunitName := range doc.Subordinates { if sublife, subknown := w.known[subunitName]; subknown { delete(w.known, subunitName) w.watcher.Unwatch(unitsC, w.backend.docID(subunitName), w.in) if sublife != Dead && !hasString(pending, subunitName) { pending = append(pending, subunitName) } } } } return pending, nil }
[ "func", "(", "w", "*", "machineUnitsWatcher", ")", "removeWatchedUnit", "(", "unitName", "string", ",", "doc", "unitDoc", ",", "pending", "[", "]", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "doc", ".", "Name", ",", "doc", ".", "Life", ")", "\n", "life", ",", "known", ":=", "w", ".", "known", "[", "unitName", "]", "\n", "// Unit was removed or unassigned from w.machine", "if", "known", "{", "delete", "(", "w", ".", "known", ",", "unitName", ")", "\n", "docID", ":=", "w", ".", "backend", ".", "docID", "(", "unitName", ")", "\n", "w", ".", "watcher", ".", "Unwatch", "(", "unitsC", ",", "docID", ",", "w", ".", "in", ")", "\n", "if", "life", "!=", "Dead", "&&", "!", "hasString", "(", "pending", ",", "unitName", ")", "{", "pending", "=", "append", "(", "pending", ",", "unitName", ")", "\n", "}", "\n", "for", "_", ",", "subunitName", ":=", "range", "doc", ".", "Subordinates", "{", "if", "sublife", ",", "subknown", ":=", "w", ".", "known", "[", "subunitName", "]", ";", "subknown", "{", "delete", "(", "w", ".", "known", ",", "subunitName", ")", "\n", "w", ".", "watcher", ".", "Unwatch", "(", "unitsC", ",", "w", ".", "backend", ".", "docID", "(", "subunitName", ")", ",", "w", ".", "in", ")", "\n", "if", "sublife", "!=", "Dead", "&&", "!", "hasString", "(", "pending", ",", "subunitName", ")", "{", "pending", "=", "append", "(", "pending", ",", "subunitName", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "pending", ",", "nil", "\n", "}" ]
// removeWatchedUnit stops watching the unit, and all subordinates for this unit
[ "removeWatchedUnit", "stops", "watching", "the", "unit", "and", "all", "subordinates", "for", "this", "unit" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2237-L2259
153,994
juju/juju
state/watcher.go
newActionStatusWatcher
func newActionStatusWatcher(backend modelBackend, receivers []ActionReceiver, statusSet ...ActionStatus) StringsWatcher { watchLogger.Debugf("newActionStatusWatcher receivers:'%+v', statuses'%+v'", receivers, statusSet) w := &actionStatusWatcher{ commonWatcher: newCommonWatcher(backend), source: make(chan watcher.Change), sink: make(chan []string), receiverFilter: actionReceiverInCollectionOp(receivers...), statusFilter: statusInCollectionOp(statusSet...), } w.tomb.Go(func() error { defer close(w.sink) return w.loop() }) return w }
go
func newActionStatusWatcher(backend modelBackend, receivers []ActionReceiver, statusSet ...ActionStatus) StringsWatcher { watchLogger.Debugf("newActionStatusWatcher receivers:'%+v', statuses'%+v'", receivers, statusSet) w := &actionStatusWatcher{ commonWatcher: newCommonWatcher(backend), source: make(chan watcher.Change), sink: make(chan []string), receiverFilter: actionReceiverInCollectionOp(receivers...), statusFilter: statusInCollectionOp(statusSet...), } w.tomb.Go(func() error { defer close(w.sink) return w.loop() }) return w }
[ "func", "newActionStatusWatcher", "(", "backend", "modelBackend", ",", "receivers", "[", "]", "ActionReceiver", ",", "statusSet", "...", "ActionStatus", ")", "StringsWatcher", "{", "watchLogger", ".", "Debugf", "(", "\"", "\"", ",", "receivers", ",", "statusSet", ")", "\n", "w", ":=", "&", "actionStatusWatcher", "{", "commonWatcher", ":", "newCommonWatcher", "(", "backend", ")", ",", "source", ":", "make", "(", "chan", "watcher", ".", "Change", ")", ",", "sink", ":", "make", "(", "chan", "[", "]", "string", ")", ",", "receiverFilter", ":", "actionReceiverInCollectionOp", "(", "receivers", "...", ")", ",", "statusFilter", ":", "statusInCollectionOp", "(", "statusSet", "...", ")", ",", "}", "\n\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "defer", "close", "(", "w", ".", "sink", ")", "\n", "return", "w", ".", "loop", "(", ")", "\n", "}", ")", "\n\n", "return", "w", "\n", "}" ]
// newActionStatusWatcher returns the StringsWatcher that will notify // on changes to Actions with the given ActionReceiver and ActionStatus // filters.
[ "newActionStatusWatcher", "returns", "the", "StringsWatcher", "that", "will", "notify", "on", "changes", "to", "Actions", "with", "the", "given", "ActionReceiver", "and", "ActionStatus", "filters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2432-L2448
153,995
juju/juju
state/watcher.go
matchingIds
func (w *actionStatusWatcher) matchingIds(ids ...string) ([]string, error) { watchLogger.Tracef("actionStatusWatcher matchingIds() ids:'%+v'", ids) coll, closer := w.db.GetCollection(actionsC) defer closer() idFilter := localIdInCollectionOp(w.backend, ids...) query := bson.D{{"$and", []bson.D{idFilter, w.receiverFilter, w.statusFilter}}} iter := coll.Find(query).Iter() var found []string var doc actionDoc for iter.Next(&doc) { found = append(found, w.backend.localID(doc.DocId)) } watchLogger.Debugf("actionStatusWatcher matchingIds() ids:'%+v', found:'%+v'", ids, found) return found, iter.Close() }
go
func (w *actionStatusWatcher) matchingIds(ids ...string) ([]string, error) { watchLogger.Tracef("actionStatusWatcher matchingIds() ids:'%+v'", ids) coll, closer := w.db.GetCollection(actionsC) defer closer() idFilter := localIdInCollectionOp(w.backend, ids...) query := bson.D{{"$and", []bson.D{idFilter, w.receiverFilter, w.statusFilter}}} iter := coll.Find(query).Iter() var found []string var doc actionDoc for iter.Next(&doc) { found = append(found, w.backend.localID(doc.DocId)) } watchLogger.Debugf("actionStatusWatcher matchingIds() ids:'%+v', found:'%+v'", ids, found) return found, iter.Close() }
[ "func", "(", "w", "*", "actionStatusWatcher", ")", "matchingIds", "(", "ids", "...", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "watchLogger", ".", "Tracef", "(", "\"", "\"", ",", "ids", ")", "\n\n", "coll", ",", "closer", ":=", "w", ".", "db", ".", "GetCollection", "(", "actionsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "idFilter", ":=", "localIdInCollectionOp", "(", "w", ".", "backend", ",", "ids", "...", ")", "\n", "query", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "[", "]", "bson", ".", "D", "{", "idFilter", ",", "w", ".", "receiverFilter", ",", "w", ".", "statusFilter", "}", "}", "}", "\n", "iter", ":=", "coll", ".", "Find", "(", "query", ")", ".", "Iter", "(", ")", "\n", "var", "found", "[", "]", "string", "\n", "var", "doc", "actionDoc", "\n", "for", "iter", ".", "Next", "(", "&", "doc", ")", "{", "found", "=", "append", "(", "found", ",", "w", ".", "backend", ".", "localID", "(", "doc", ".", "DocId", ")", ")", "\n", "}", "\n", "watchLogger", ".", "Debugf", "(", "\"", "\"", ",", "ids", ",", "found", ")", "\n", "return", "found", ",", "iter", ".", "Close", "(", ")", "\n", "}" ]
// matchingIds is a helper function that filters the actionsC collection // on the ActionReceivers and ActionStatus set defined on the watcher. // If ids are passed in the collection is further filtered to only // Actions that also have one of the supplied _id's.
[ "matchingIds", "is", "a", "helper", "function", "that", "filters", "the", "actionsC", "collection", "on", "the", "ActionReceivers", "and", "ActionStatus", "set", "defined", "on", "the", "watcher", ".", "If", "ids", "are", "passed", "in", "the", "collection", "is", "further", "filtered", "to", "only", "Actions", "that", "also", "have", "one", "of", "the", "supplied", "_id", "s", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2511-L2527
153,996
juju/juju
state/watcher.go
filterAndMergeIds
func (w *actionStatusWatcher) filterAndMergeIds(changes *[]string, updates map[interface{}]bool) error { watchLogger.Tracef("actionStatusWatcher filterAndMergeIds(changes:'%+v', updates:'%+v')", changes, updates) var adds []string for id, exists := range updates { switch id := id.(type) { case string: localId := w.backend.localID(id) chIx, idAlreadyInChangeset := indexOf(localId, *changes) if exists { if !idAlreadyInChangeset { adds = append(adds, localId) } } else { if idAlreadyInChangeset { // remove id from changes *changes = append((*changes)[:chIx], (*changes)[chIx+1:]...) } } default: return errors.Errorf("id is not of type string, got %T", id) } } if len(adds) > 0 { ids, err := w.matchingIds(adds...) if err != nil { return errors.Trace(err) } *changes = append(*changes, ids...) } return nil }
go
func (w *actionStatusWatcher) filterAndMergeIds(changes *[]string, updates map[interface{}]bool) error { watchLogger.Tracef("actionStatusWatcher filterAndMergeIds(changes:'%+v', updates:'%+v')", changes, updates) var adds []string for id, exists := range updates { switch id := id.(type) { case string: localId := w.backend.localID(id) chIx, idAlreadyInChangeset := indexOf(localId, *changes) if exists { if !idAlreadyInChangeset { adds = append(adds, localId) } } else { if idAlreadyInChangeset { // remove id from changes *changes = append((*changes)[:chIx], (*changes)[chIx+1:]...) } } default: return errors.Errorf("id is not of type string, got %T", id) } } if len(adds) > 0 { ids, err := w.matchingIds(adds...) if err != nil { return errors.Trace(err) } *changes = append(*changes, ids...) } return nil }
[ "func", "(", "w", "*", "actionStatusWatcher", ")", "filterAndMergeIds", "(", "changes", "*", "[", "]", "string", ",", "updates", "map", "[", "interface", "{", "}", "]", "bool", ")", "error", "{", "watchLogger", ".", "Tracef", "(", "\"", "\"", ",", "changes", ",", "updates", ")", "\n", "var", "adds", "[", "]", "string", "\n", "for", "id", ",", "exists", ":=", "range", "updates", "{", "switch", "id", ":=", "id", ".", "(", "type", ")", "{", "case", "string", ":", "localId", ":=", "w", ".", "backend", ".", "localID", "(", "id", ")", "\n", "chIx", ",", "idAlreadyInChangeset", ":=", "indexOf", "(", "localId", ",", "*", "changes", ")", "\n", "if", "exists", "{", "if", "!", "idAlreadyInChangeset", "{", "adds", "=", "append", "(", "adds", ",", "localId", ")", "\n", "}", "\n", "}", "else", "{", "if", "idAlreadyInChangeset", "{", "// remove id from changes", "*", "changes", "=", "append", "(", "(", "*", "changes", ")", "[", ":", "chIx", "]", ",", "(", "*", "changes", ")", "[", "chIx", "+", "1", ":", "]", "...", ")", "\n", "}", "\n", "}", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "adds", ")", ">", "0", "{", "ids", ",", "err", ":=", "w", ".", "matchingIds", "(", "adds", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "*", "changes", "=", "append", "(", "*", "changes", ",", "ids", "...", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// filterAndMergeIds combines existing pending changes along with // updates from the upstream watcher, and updates the changes set. // If the upstream changes do not match the ActionReceivers and // ActionStatus set filters defined on the watcher, they are silently // dropped.
[ "filterAndMergeIds", "combines", "existing", "pending", "changes", "along", "with", "updates", "from", "the", "upstream", "watcher", "and", "updates", "the", "changes", "set", ".", "If", "the", "upstream", "changes", "do", "not", "match", "the", "ActionReceivers", "and", "ActionStatus", "set", "filters", "defined", "on", "the", "watcher", "they", "are", "silently", "dropped", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2534-L2564
153,997
juju/juju
state/watcher.go
inCollectionOp
func inCollectionOp(key string, ids ...string) bson.D { ret := bson.D{} switch len(ids) { case 0: case 1: ret = append(ret, bson.DocElem{key, ids[0]}) default: ret = append(ret, bson.DocElem{key, bson.D{{"$in", ids}}}) } return ret }
go
func inCollectionOp(key string, ids ...string) bson.D { ret := bson.D{} switch len(ids) { case 0: case 1: ret = append(ret, bson.DocElem{key, ids[0]}) default: ret = append(ret, bson.DocElem{key, bson.D{{"$in", ids}}}) } return ret }
[ "func", "inCollectionOp", "(", "key", "string", ",", "ids", "...", "string", ")", "bson", ".", "D", "{", "ret", ":=", "bson", ".", "D", "{", "}", "\n", "switch", "len", "(", "ids", ")", "{", "case", "0", ":", "case", "1", ":", "ret", "=", "append", "(", "ret", ",", "bson", ".", "DocElem", "{", "key", ",", "ids", "[", "0", "]", "}", ")", "\n", "default", ":", "ret", "=", "append", "(", "ret", ",", "bson", ".", "DocElem", "{", "key", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "ids", "}", "}", "}", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// inCollectionOp takes a key name and a list of potential values and // returns a bson.D Op that will match on the supplied key and values.
[ "inCollectionOp", "takes", "a", "key", "name", "and", "a", "list", "of", "potential", "values", "and", "returns", "a", "bson", ".", "D", "Op", "that", "will", "match", "on", "the", "supplied", "key", "and", "values", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2568-L2578
153,998
juju/juju
state/watcher.go
localIdInCollectionOp
func localIdInCollectionOp(st modelBackend, localIds ...string) bson.D { ids := make([]string, len(localIds)) for i, id := range localIds { ids[i] = st.docID(id) } return inCollectionOp("_id", ids...) }
go
func localIdInCollectionOp(st modelBackend, localIds ...string) bson.D { ids := make([]string, len(localIds)) for i, id := range localIds { ids[i] = st.docID(id) } return inCollectionOp("_id", ids...) }
[ "func", "localIdInCollectionOp", "(", "st", "modelBackend", ",", "localIds", "...", "string", ")", "bson", ".", "D", "{", "ids", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "localIds", ")", ")", "\n", "for", "i", ",", "id", ":=", "range", "localIds", "{", "ids", "[", "i", "]", "=", "st", ".", "docID", "(", "id", ")", "\n", "}", "\n", "return", "inCollectionOp", "(", "\"", "\"", ",", "ids", "...", ")", "\n", "}" ]
// localIdInCollectionOp is a special form of inCollectionOp that just // converts id's to their model-uuid prefixed form.
[ "localIdInCollectionOp", "is", "a", "special", "form", "of", "inCollectionOp", "that", "just", "converts", "id", "s", "to", "their", "model", "-", "uuid", "prefixed", "form", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2582-L2588
153,999
juju/juju
state/watcher.go
newCollectionWatcher
func newCollectionWatcher(backend modelBackend, cfg colWCfg) StringsWatcher { if cfg.global { if cfg.filter == nil { cfg.filter = func(x interface{}) bool { return true } } } else { // Always ensure that there is at least filtering on the // model in place. backstop := isLocalID(backend) if cfg.filter == nil { cfg.filter = backstop } else { innerFilter := cfg.filter cfg.filter = func(id interface{}) bool { if !backstop(id) { return false } return innerFilter(id) } } } w := &collectionWatcher{ colWCfg: cfg, commonWatcher: newCommonWatcher(backend), source: make(chan watcher.Change), sink: make(chan []string), } w.tomb.Go(func() error { defer close(w.sink) defer close(w.source) return w.loop() }) return w }
go
func newCollectionWatcher(backend modelBackend, cfg colWCfg) StringsWatcher { if cfg.global { if cfg.filter == nil { cfg.filter = func(x interface{}) bool { return true } } } else { // Always ensure that there is at least filtering on the // model in place. backstop := isLocalID(backend) if cfg.filter == nil { cfg.filter = backstop } else { innerFilter := cfg.filter cfg.filter = func(id interface{}) bool { if !backstop(id) { return false } return innerFilter(id) } } } w := &collectionWatcher{ colWCfg: cfg, commonWatcher: newCommonWatcher(backend), source: make(chan watcher.Change), sink: make(chan []string), } w.tomb.Go(func() error { defer close(w.sink) defer close(w.source) return w.loop() }) return w }
[ "func", "newCollectionWatcher", "(", "backend", "modelBackend", ",", "cfg", "colWCfg", ")", "StringsWatcher", "{", "if", "cfg", ".", "global", "{", "if", "cfg", ".", "filter", "==", "nil", "{", "cfg", ".", "filter", "=", "func", "(", "x", "interface", "{", "}", ")", "bool", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "else", "{", "// Always ensure that there is at least filtering on the", "// model in place.", "backstop", ":=", "isLocalID", "(", "backend", ")", "\n", "if", "cfg", ".", "filter", "==", "nil", "{", "cfg", ".", "filter", "=", "backstop", "\n", "}", "else", "{", "innerFilter", ":=", "cfg", ".", "filter", "\n", "cfg", ".", "filter", "=", "func", "(", "id", "interface", "{", "}", ")", "bool", "{", "if", "!", "backstop", "(", "id", ")", "{", "return", "false", "\n", "}", "\n", "return", "innerFilter", "(", "id", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "w", ":=", "&", "collectionWatcher", "{", "colWCfg", ":", "cfg", ",", "commonWatcher", ":", "newCommonWatcher", "(", "backend", ")", ",", "source", ":", "make", "(", "chan", "watcher", ".", "Change", ")", ",", "sink", ":", "make", "(", "chan", "[", "]", "string", ")", ",", "}", "\n\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "defer", "close", "(", "w", ".", "sink", ")", "\n", "defer", "close", "(", "w", ".", "source", ")", "\n", "return", "w", ".", "loop", "(", ")", "\n", "}", ")", "\n\n", "return", "w", "\n", "}" ]
// newCollectionWatcher starts and returns a new StringsWatcher configured // with the given collection and filter function
[ "newCollectionWatcher", "starts", "and", "returns", "a", "new", "StringsWatcher", "configured", "with", "the", "given", "collection", "and", "filter", "function" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2632-L2670