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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
154,700
juju/juju
api/credentialvalidator/credentialvalidator.go
WatchCredential
func (c *Facade) WatchCredential(credentialID string) (watcher.NotifyWatcher, error) { if !names.IsValidCloudCredential(credentialID) { return nil, errors.NotValidf("cloud credential ID %q", credentialID) } in := names.NewCloudCredentialTag(credentialID).String() var result params.NotifyWatchResult err := c.facade.FacadeCall("WatchCredential", params.Entity{in}, &result) if err != nil { return nil, errors.Trace(err) } if err := result.Error; err != nil { return nil, errors.Trace(err) } w := apiwatcher.NewNotifyWatcher(c.facade.RawAPICaller(), result) return w, nil }
go
func (c *Facade) WatchCredential(credentialID string) (watcher.NotifyWatcher, error) { if !names.IsValidCloudCredential(credentialID) { return nil, errors.NotValidf("cloud credential ID %q", credentialID) } in := names.NewCloudCredentialTag(credentialID).String() var result params.NotifyWatchResult err := c.facade.FacadeCall("WatchCredential", params.Entity{in}, &result) if err != nil { return nil, errors.Trace(err) } if err := result.Error; err != nil { return nil, errors.Trace(err) } w := apiwatcher.NewNotifyWatcher(c.facade.RawAPICaller(), result) return w, nil }
[ "func", "(", "c", "*", "Facade", ")", "WatchCredential", "(", "credentialID", "string", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "if", "!", "names", ".", "IsValidCloudCredential", "(", "credentialID", ")", "{", "return", "nil", ",...
// WatchCredential provides a notify watcher that is responsive to changes // to a given cloud credential.
[ "WatchCredential", "provides", "a", "notify", "watcher", "that", "is", "responsive", "to", "changes", "to", "a", "given", "cloud", "credential", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/credentialvalidator/credentialvalidator.go#L61-L77
154,701
juju/juju
api/credentialvalidator/credentialvalidator.go
InvalidateModelCredential
func (c *Facade) InvalidateModelCredential(reason string) error { in := params.InvalidateCredentialArg{reason} var result params.ErrorResult err := c.facade.FacadeCall("InvalidateModelCredential", in, &result) if err != nil { return errors.Trace(err) } if result.Error != nil { return errors.Trace(result.Error) } return nil }
go
func (c *Facade) InvalidateModelCredential(reason string) error { in := params.InvalidateCredentialArg{reason} var result params.ErrorResult err := c.facade.FacadeCall("InvalidateModelCredential", in, &result) if err != nil { return errors.Trace(err) } if result.Error != nil { return errors.Trace(result.Error) } return nil }
[ "func", "(", "c", "*", "Facade", ")", "InvalidateModelCredential", "(", "reason", "string", ")", "error", "{", "in", ":=", "params", ".", "InvalidateCredentialArg", "{", "reason", "}", "\n", "var", "result", "params", ".", "ErrorResult", "\n", "err", ":=", ...
// InvalidateModelCredential invalidates cloud credential for the model that made a connection.
[ "InvalidateModelCredential", "invalidates", "cloud", "credential", "for", "the", "model", "that", "made", "a", "connection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/credentialvalidator/credentialvalidator.go#L80-L92
154,702
juju/juju
api/credentialvalidator/credentialvalidator.go
WatchModelCredential
func (c *Facade) WatchModelCredential() (watcher.NotifyWatcher, error) { if v := c.facade.BestAPIVersion(); v < 2 { return nil, errors.NotSupportedf("WatchModelCredential on CredentialValidator v%v", v) } var result params.NotifyWatchResult err := c.facade.FacadeCall("WatchModelCredential", nil, &result) if err != nil { return nil, errors.Trace(err) } if err := result.Error; err != nil { return nil, errors.Trace(err) } w := apiwatcher.NewNotifyWatcher(c.facade.RawAPICaller(), result) return w, nil }
go
func (c *Facade) WatchModelCredential() (watcher.NotifyWatcher, error) { if v := c.facade.BestAPIVersion(); v < 2 { return nil, errors.NotSupportedf("WatchModelCredential on CredentialValidator v%v", v) } var result params.NotifyWatchResult err := c.facade.FacadeCall("WatchModelCredential", nil, &result) if err != nil { return nil, errors.Trace(err) } if err := result.Error; err != nil { return nil, errors.Trace(err) } w := apiwatcher.NewNotifyWatcher(c.facade.RawAPICaller(), result) return w, nil }
[ "func", "(", "c", "*", "Facade", ")", "WatchModelCredential", "(", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "if", "v", ":=", "c", ".", "facade", ".", "BestAPIVersion", "(", ")", ";", "v", "<", "2", "{", "return", "nil", ",...
// WatchModelCredential provides a notify watcher that is responsive to changes // to a given cloud credential.
[ "WatchModelCredential", "provides", "a", "notify", "watcher", "that", "is", "responsive", "to", "changes", "to", "a", "given", "cloud", "credential", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/credentialvalidator/credentialvalidator.go#L96-L111
154,703
juju/juju
worker/uniter/operation/runaction.go
Prepare
func (ra *runAction) Prepare(state State) (*State, error) { rnr, err := ra.runnerFactory.NewActionRunner(ra.actionId) if cause := errors.Cause(err); charmrunner.IsBadActionError(cause) { if err := ra.callbacks.FailAction(ra.actionId, err.Error()); err != nil { return nil, err } return nil, ErrSkipExecute } else if cause == charmrunner.ErrActionNotAvailable { return nil, ErrSkipExecute } else if err != nil { return nil, errors.Annotatef(err, "cannot create runner for action %q", ra.actionId) } actionData, err := rnr.Context().ActionData() if err != nil { // this should *really* never happen, but let's not panic return nil, errors.Trace(err) } err = rnr.Context().Prepare() if err != nil { return nil, errors.Trace(err) } ra.name = actionData.Name ra.runner = rnr return stateChange{ Kind: RunAction, Step: Pending, ActionId: &ra.actionId, Hook: state.Hook, }.apply(state), nil }
go
func (ra *runAction) Prepare(state State) (*State, error) { rnr, err := ra.runnerFactory.NewActionRunner(ra.actionId) if cause := errors.Cause(err); charmrunner.IsBadActionError(cause) { if err := ra.callbacks.FailAction(ra.actionId, err.Error()); err != nil { return nil, err } return nil, ErrSkipExecute } else if cause == charmrunner.ErrActionNotAvailable { return nil, ErrSkipExecute } else if err != nil { return nil, errors.Annotatef(err, "cannot create runner for action %q", ra.actionId) } actionData, err := rnr.Context().ActionData() if err != nil { // this should *really* never happen, but let's not panic return nil, errors.Trace(err) } err = rnr.Context().Prepare() if err != nil { return nil, errors.Trace(err) } ra.name = actionData.Name ra.runner = rnr return stateChange{ Kind: RunAction, Step: Pending, ActionId: &ra.actionId, Hook: state.Hook, }.apply(state), nil }
[ "func", "(", "ra", "*", "runAction", ")", "Prepare", "(", "state", "State", ")", "(", "*", "State", ",", "error", ")", "{", "rnr", ",", "err", ":=", "ra", ".", "runnerFactory", ".", "NewActionRunner", "(", "ra", ".", "actionId", ")", "\n", "if", "c...
// Prepare ensures that the action is valid and can be executed. If not, it // will return ErrSkipExecute. It preserves any hook recorded in the supplied // state. // Prepare is part of the Operation interface.
[ "Prepare", "ensures", "that", "the", "action", "is", "valid", "and", "can", "be", "executed", ".", "If", "not", "it", "will", "return", "ErrSkipExecute", ".", "It", "preserves", "any", "hook", "recorded", "in", "the", "supplied", "state", ".", "Prepare", "...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/operation/runaction.go#L36-L65
154,704
juju/juju
worker/uniter/operation/runaction.go
Execute
func (ra *runAction) Execute(state State) (*State, error) { message := fmt.Sprintf("running action %s", ra.name) if err := ra.callbacks.SetExecutingStatus(message); err != nil { return nil, err } err := ra.runner.RunAction(ra.name) if err != nil { // This indicates an actual error -- an action merely failing should // be handled inside the Runner, and returned as nil. return nil, errors.Annotatef(err, "running action %q", ra.name) } return stateChange{ Kind: RunAction, Step: Done, ActionId: &ra.actionId, Hook: state.Hook, }.apply(state), nil }
go
func (ra *runAction) Execute(state State) (*State, error) { message := fmt.Sprintf("running action %s", ra.name) if err := ra.callbacks.SetExecutingStatus(message); err != nil { return nil, err } err := ra.runner.RunAction(ra.name) if err != nil { // This indicates an actual error -- an action merely failing should // be handled inside the Runner, and returned as nil. return nil, errors.Annotatef(err, "running action %q", ra.name) } return stateChange{ Kind: RunAction, Step: Done, ActionId: &ra.actionId, Hook: state.Hook, }.apply(state), nil }
[ "func", "(", "ra", "*", "runAction", ")", "Execute", "(", "state", "State", ")", "(", "*", "State", ",", "error", ")", "{", "message", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ra", ".", "name", ")", "\n\n", "if", "err", ":=", "ra", "...
// Execute runs the action, and preserves any hook recorded in the supplied state. // Execute is part of the Operation interface.
[ "Execute", "runs", "the", "action", "and", "preserves", "any", "hook", "recorded", "in", "the", "supplied", "state", ".", "Execute", "is", "part", "of", "the", "Operation", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/operation/runaction.go#L69-L88
154,705
juju/juju
cloudconfig/cloudinit/cloudinit_opensuse.go
addPackageProxyCmd
func (helper openSUSEHelper) addPackageProxyCmd(url string) string { return helper.paccmder.SetProxyCmds(proxy.Settings{ Http: url, })[0] }
go
func (helper openSUSEHelper) addPackageProxyCmd(url string) string { return helper.paccmder.SetProxyCmds(proxy.Settings{ Http: url, })[0] }
[ "func", "(", "helper", "openSUSEHelper", ")", "addPackageProxyCmd", "(", "url", "string", ")", "string", "{", "return", "helper", ".", "paccmder", ".", "SetProxyCmds", "(", "proxy", ".", "Settings", "{", "Http", ":", "url", ",", "}", ")", "[", "0", "]", ...
// addPackageProxyCmd is a helper method which returns the corresponding runcmd // to apply the package proxy settings for OpenSUSE
[ "addPackageProxyCmd", "is", "a", "helper", "method", "which", "returns", "the", "corresponding", "runcmd", "to", "apply", "the", "package", "proxy", "settings", "for", "OpenSUSE" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/cloudinit/cloudinit_opensuse.go#L30-L34
154,706
juju/juju
provider/vsphere/environ_broker.go
finishMachineConfig
func (env *sessionEnviron) finishMachineConfig(args environs.StartInstanceParams, img *OvaFileMetadata) error { envTools, err := args.Tools.Match(tools.Filter{Arch: img.Arch}) if err != nil { return err } if err := args.InstanceConfig.SetTools(envTools); err != nil { return errors.Trace(err) } return FinishInstanceConfig(args.InstanceConfig, env.Config()) }
go
func (env *sessionEnviron) finishMachineConfig(args environs.StartInstanceParams, img *OvaFileMetadata) error { envTools, err := args.Tools.Match(tools.Filter{Arch: img.Arch}) if err != nil { return err } if err := args.InstanceConfig.SetTools(envTools); err != nil { return errors.Trace(err) } return FinishInstanceConfig(args.InstanceConfig, env.Config()) }
[ "func", "(", "env", "*", "sessionEnviron", ")", "finishMachineConfig", "(", "args", "environs", ".", "StartInstanceParams", ",", "img", "*", "OvaFileMetadata", ")", "error", "{", "envTools", ",", "err", ":=", "args", ".", "Tools", ".", "Match", "(", "tools",...
// finishMachineConfig updates args.MachineConfig in place. Setting up // the API, StateServing, and SSHkeys information.
[ "finishMachineConfig", "updates", "args", ".", "MachineConfig", "in", "place", ".", "Setting", "up", "the", "API", "StateServing", "and", "SSHkeys", "information", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/environ_broker.go#L109-L118
154,707
juju/juju
resource/context/internal/resourcedir.go
NewDirectorySpec
func NewDirectorySpec(dataDir, name string, deps DirectorySpecDeps) *DirectorySpec { dirname := deps.Join(dataDir, name) spec := &DirectorySpec{ Name: name, Dirname: dirname, Deps: deps, } return spec }
go
func NewDirectorySpec(dataDir, name string, deps DirectorySpecDeps) *DirectorySpec { dirname := deps.Join(dataDir, name) spec := &DirectorySpec{ Name: name, Dirname: dirname, Deps: deps, } return spec }
[ "func", "NewDirectorySpec", "(", "dataDir", ",", "name", "string", ",", "deps", "DirectorySpecDeps", ")", "*", "DirectorySpec", "{", "dirname", ":=", "deps", ".", "Join", "(", "dataDir", ",", "name", ")", "\n\n", "spec", ":=", "&", "DirectorySpec", "{", "N...
// NewDirectorySpec returns a new directory spec for the given info.
[ "NewDirectorySpec", "returns", "a", "new", "directory", "spec", "for", "the", "given", "info", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/resourcedir.go#L29-L39
154,708
juju/juju
resource/context/internal/resourcedir.go
Resolve
func (spec DirectorySpec) Resolve(path ...string) string { return spec.Deps.Join(append([]string{spec.Dirname}, path...)...) }
go
func (spec DirectorySpec) Resolve(path ...string) string { return spec.Deps.Join(append([]string{spec.Dirname}, path...)...) }
[ "func", "(", "spec", "DirectorySpec", ")", "Resolve", "(", "path", "...", "string", ")", "string", "{", "return", "spec", ".", "Deps", ".", "Join", "(", "append", "(", "[", "]", "string", "{", "spec", ".", "Dirname", "}", ",", "path", "...", ")", "...
// Resolve returns the fully resolved file path, relative to the directory.
[ "Resolve", "returns", "the", "fully", "resolved", "file", "path", "relative", "to", "the", "directory", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/resourcedir.go#L42-L44
154,709
juju/juju
resource/context/internal/resourcedir.go
Initialize
func (spec DirectorySpec) Initialize() (*Directory, error) { if err := spec.Deps.MkdirAll(spec.Dirname); err != nil { return nil, errors.Annotate(err, "could not create resource dir") } return NewDirectory(&spec, spec.Deps), nil }
go
func (spec DirectorySpec) Initialize() (*Directory, error) { if err := spec.Deps.MkdirAll(spec.Dirname); err != nil { return nil, errors.Annotate(err, "could not create resource dir") } return NewDirectory(&spec, spec.Deps), nil }
[ "func", "(", "spec", "DirectorySpec", ")", "Initialize", "(", ")", "(", "*", "Directory", ",", "error", ")", "{", "if", "err", ":=", "spec", ".", "Deps", ".", "MkdirAll", "(", "spec", ".", "Dirname", ")", ";", "err", "!=", "nil", "{", "return", "ni...
// Initialize preps the spec'ed directory and returns it.
[ "Initialize", "preps", "the", "spec", "ed", "directory", "and", "returns", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/resourcedir.go#L56-L62
154,710
juju/juju
resource/context/internal/resourcedir.go
NewTempDirectorySpec
func NewTempDirectorySpec(name string, deps TempDirDeps) (*TempDirectorySpec, error) { tempDir, err := deps.NewTempDir() if err != nil { return nil, errors.Trace(err) } spec := &TempDirectorySpec{ DirectorySpec: NewDirectorySpec(tempDir, name, deps), CleanUp: func() error { return deps.RemoveDir(tempDir) }, } return spec, nil }
go
func NewTempDirectorySpec(name string, deps TempDirDeps) (*TempDirectorySpec, error) { tempDir, err := deps.NewTempDir() if err != nil { return nil, errors.Trace(err) } spec := &TempDirectorySpec{ DirectorySpec: NewDirectorySpec(tempDir, name, deps), CleanUp: func() error { return deps.RemoveDir(tempDir) }, } return spec, nil }
[ "func", "NewTempDirectorySpec", "(", "name", "string", ",", "deps", "TempDirDeps", ")", "(", "*", "TempDirectorySpec", ",", "error", ")", "{", "tempDir", ",", "err", ":=", "deps", ".", "NewTempDir", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return"...
// NewTempDirectorySpec creates a new temp directory spec // for the given resource.
[ "NewTempDirectorySpec", "creates", "a", "new", "temp", "directory", "spec", "for", "the", "given", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/resourcedir.go#L90-L103
154,711
juju/juju
resource/context/internal/resourcedir.go
NewDirectory
func NewDirectory(spec *DirectorySpec, deps DirectoryDeps) *Directory { dir := &Directory{ DirectorySpec: spec, Deps: deps, } return dir }
go
func NewDirectory(spec *DirectorySpec, deps DirectoryDeps) *Directory { dir := &Directory{ DirectorySpec: spec, Deps: deps, } return dir }
[ "func", "NewDirectory", "(", "spec", "*", "DirectorySpec", ",", "deps", "DirectoryDeps", ")", "*", "Directory", "{", "dir", ":=", "&", "Directory", "{", "DirectorySpec", ":", "spec", ",", "Deps", ":", "deps", ",", "}", "\n", "return", "dir", "\n", "}" ]
// NewDirectory returns a new directory for the provided spec.
[ "NewDirectory", "returns", "a", "new", "directory", "for", "the", "provided", "spec", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/resourcedir.go#L134-L140
154,712
juju/juju
resource/context/internal/resourcedir.go
Write
func (dir *Directory) Write(opened ContentSource) error { // TODO(ericsnow) Also write the info file... relPath := opened.Info().Path if err := dir.WriteContent(relPath, opened.Content()); err != nil { return errors.Trace(err) } return nil }
go
func (dir *Directory) Write(opened ContentSource) error { // TODO(ericsnow) Also write the info file... relPath := opened.Info().Path if err := dir.WriteContent(relPath, opened.Content()); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "dir", "*", "Directory", ")", "Write", "(", "opened", "ContentSource", ")", "error", "{", "// TODO(ericsnow) Also write the info file...", "relPath", ":=", "opened", ".", "Info", "(", ")", ".", "Path", "\n", "if", "err", ":=", "dir", ".", "Write...
// Write writes all relevant files from the given source // to the directory.
[ "Write", "writes", "all", "relevant", "files", "from", "the", "given", "source", "to", "the", "directory", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/resourcedir.go#L144-L153
154,713
juju/juju
resource/context/internal/resourcedir.go
WriteContent
func (dir *Directory) WriteContent(relPath string, content Content) error { if len(relPath) == 0 { // TODO(ericsnow) Use rd.readInfo().Path, like openResource() does? return errors.NotImplementedf("") } filename := dir.Resolve(relPath) target, err := dir.Deps.CreateWriter(filename) if err != nil { return errors.Annotate(err, "could not create new file for resource") } defer dir.Deps.CloseAndLog(target, filename) if err := dir.Deps.WriteContent(target, content); err != nil { return errors.Trace(err) } return nil }
go
func (dir *Directory) WriteContent(relPath string, content Content) error { if len(relPath) == 0 { // TODO(ericsnow) Use rd.readInfo().Path, like openResource() does? return errors.NotImplementedf("") } filename := dir.Resolve(relPath) target, err := dir.Deps.CreateWriter(filename) if err != nil { return errors.Annotate(err, "could not create new file for resource") } defer dir.Deps.CloseAndLog(target, filename) if err := dir.Deps.WriteContent(target, content); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "dir", "*", "Directory", ")", "WriteContent", "(", "relPath", "string", ",", "content", "Content", ")", "error", "{", "if", "len", "(", "relPath", ")", "==", "0", "{", "// TODO(ericsnow) Use rd.readInfo().Path, like openResource() does?", "return", "e...
// WriteContent writes the resource file to the given path // within the directory.
[ "WriteContent", "writes", "the", "resource", "file", "to", "the", "given", "path", "within", "the", "directory", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/internal/resourcedir.go#L157-L175
154,714
juju/juju
worker/meterstatus/connected.go
NewConnectedStatusWorker
func NewConnectedStatusWorker(cfg ConnectedConfig) (worker.Worker, error) { handler, err := NewConnectedStatusHandler(cfg) if err != nil { return nil, errors.Trace(err) } return watcher.NewNotifyWorker(watcher.NotifyConfig{ Handler: handler, }) }
go
func NewConnectedStatusWorker(cfg ConnectedConfig) (worker.Worker, error) { handler, err := NewConnectedStatusHandler(cfg) if err != nil { return nil, errors.Trace(err) } return watcher.NewNotifyWorker(watcher.NotifyConfig{ Handler: handler, }) }
[ "func", "NewConnectedStatusWorker", "(", "cfg", "ConnectedConfig", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "handler", ",", "err", ":=", "NewConnectedStatusHandler", "(", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "...
// NewConnectedStatusWorker creates a new worker that monitors the meter status of the // unit and runs the meter-status-changed hook appropriately.
[ "NewConnectedStatusWorker", "creates", "a", "new", "worker", "that", "monitors", "the", "meter", "status", "of", "the", "unit", "and", "runs", "the", "meter", "-", "status", "-", "changed", "hook", "appropriately", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/meterstatus/connected.go#L47-L55
154,715
juju/juju
worker/meterstatus/connected.go
NewConnectedStatusHandler
func NewConnectedStatusHandler(cfg ConnectedConfig) (watcher.NotifyHandler, error) { if err := cfg.Validate(); err != nil { return nil, errors.Trace(err) } w := &connectedStatusHandler{ config: cfg, } return w, nil }
go
func NewConnectedStatusHandler(cfg ConnectedConfig) (watcher.NotifyHandler, error) { if err := cfg.Validate(); err != nil { return nil, errors.Trace(err) } w := &connectedStatusHandler{ config: cfg, } return w, nil }
[ "func", "NewConnectedStatusHandler", "(", "cfg", "ConnectedConfig", ")", "(", "watcher", ".", "NotifyHandler", ",", "error", ")", "{", "if", "err", ":=", "cfg", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".",...
// NewConnectedStatusHandler creates a new meter status handler for handling meter status // changes as provided by the API.
[ "NewConnectedStatusHandler", "creates", "a", "new", "meter", "status", "handler", "for", "handling", "meter", "status", "changes", "as", "provided", "by", "the", "API", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/meterstatus/connected.go#L59-L68
154,716
juju/juju
worker/meterstatus/connected.go
SetUp
func (w *connectedStatusHandler) SetUp() (watcher.NotifyWatcher, error) { var err error w.code, w.info, _, err = w.config.StateFile.Read() if err != nil { return nil, errors.Trace(err) } return w.config.Status.WatchMeterStatus() }
go
func (w *connectedStatusHandler) SetUp() (watcher.NotifyWatcher, error) { var err error w.code, w.info, _, err = w.config.StateFile.Read() if err != nil { return nil, errors.Trace(err) } return w.config.Status.WatchMeterStatus() }
[ "func", "(", "w", "*", "connectedStatusHandler", ")", "SetUp", "(", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "var", "err", "error", "\n", "w", ".", "code", ",", "w", ".", "info", ",", "_", ",", "err", "=", "w", ".", "con...
// SetUp is part of the worker.NotifyWatchHandler interface.
[ "SetUp", "is", "part", "of", "the", "worker", ".", "NotifyWatchHandler", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/meterstatus/connected.go#L71-L79
154,717
juju/juju
worker/meterstatus/connected.go
Handle
func (w *connectedStatusHandler) Handle(abort <-chan struct{}) error { logger.Debugf("got meter status change signal from watcher") currentCode, currentInfo, err := w.config.Status.MeterStatus() if err != nil { return errors.Trace(err) } if currentCode == w.code && currentInfo == w.info { logger.Tracef("meter status (%q, %q) matches stored information (%q, %q), skipping", currentCode, currentInfo, w.code, w.info) return nil } w.applyStatus(currentCode, currentInfo, abort) w.code, w.info = currentCode, currentInfo err = w.config.StateFile.Write(w.code, w.info, nil) if err != nil { return errors.Annotate(err, "failed to record meter status worker state") } return nil }
go
func (w *connectedStatusHandler) Handle(abort <-chan struct{}) error { logger.Debugf("got meter status change signal from watcher") currentCode, currentInfo, err := w.config.Status.MeterStatus() if err != nil { return errors.Trace(err) } if currentCode == w.code && currentInfo == w.info { logger.Tracef("meter status (%q, %q) matches stored information (%q, %q), skipping", currentCode, currentInfo, w.code, w.info) return nil } w.applyStatus(currentCode, currentInfo, abort) w.code, w.info = currentCode, currentInfo err = w.config.StateFile.Write(w.code, w.info, nil) if err != nil { return errors.Annotate(err, "failed to record meter status worker state") } return nil }
[ "func", "(", "w", "*", "connectedStatusHandler", ")", "Handle", "(", "abort", "<-", "chan", "struct", "{", "}", ")", "error", "{", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "currentCode", ",", "currentInfo", ",", "err", ":=", "w", ".", "co...
// Handle is part of the worker.NotifyWatchHandler interface.
[ "Handle", "is", "part", "of", "the", "worker", ".", "NotifyWatchHandler", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/meterstatus/connected.go#L87-L104
154,718
juju/juju
state/resources_persistence.go
ListResources
func (p ResourcePersistence) ListResources(applicationID string) (resource.ApplicationResources, error) { logger.Tracef("listing all resources for application %q", applicationID) docs, err := p.resources(applicationID) if err != nil { return resource.ApplicationResources{}, errors.Trace(err) } store := map[string]charmresource.Resource{} units := map[names.UnitTag][]resource.Resource{} downloadProgress := make(map[names.UnitTag]map[string]int64) var results resource.ApplicationResources for _, doc := range docs { if doc.PendingID != "" { continue } res, err := doc2basicResource(doc) if err != nil { return resource.ApplicationResources{}, errors.Trace(err) } if !doc.LastPolled.IsZero() { store[res.Name] = res.Resource continue } if doc.UnitID == "" { results.Resources = append(results.Resources, res) continue } tag := names.NewUnitTag(doc.UnitID) if doc.PendingID == "" { units[tag] = append(units[tag], res) } if doc.DownloadProgress != nil { if downloadProgress[tag] == nil { downloadProgress[tag] = make(map[string]int64) } downloadProgress[tag][doc.Name] = *doc.DownloadProgress } } for _, res := range results.Resources { storeRes := store[res.Name] results.CharmStoreResources = append(results.CharmStoreResources, storeRes) } for tag, res := range units { results.UnitResources = append(results.UnitResources, resource.UnitResources{ Tag: tag, Resources: res, DownloadProgress: downloadProgress[tag], }) } return results, nil }
go
func (p ResourcePersistence) ListResources(applicationID string) (resource.ApplicationResources, error) { logger.Tracef("listing all resources for application %q", applicationID) docs, err := p.resources(applicationID) if err != nil { return resource.ApplicationResources{}, errors.Trace(err) } store := map[string]charmresource.Resource{} units := map[names.UnitTag][]resource.Resource{} downloadProgress := make(map[names.UnitTag]map[string]int64) var results resource.ApplicationResources for _, doc := range docs { if doc.PendingID != "" { continue } res, err := doc2basicResource(doc) if err != nil { return resource.ApplicationResources{}, errors.Trace(err) } if !doc.LastPolled.IsZero() { store[res.Name] = res.Resource continue } if doc.UnitID == "" { results.Resources = append(results.Resources, res) continue } tag := names.NewUnitTag(doc.UnitID) if doc.PendingID == "" { units[tag] = append(units[tag], res) } if doc.DownloadProgress != nil { if downloadProgress[tag] == nil { downloadProgress[tag] = make(map[string]int64) } downloadProgress[tag][doc.Name] = *doc.DownloadProgress } } for _, res := range results.Resources { storeRes := store[res.Name] results.CharmStoreResources = append(results.CharmStoreResources, storeRes) } for tag, res := range units { results.UnitResources = append(results.UnitResources, resource.UnitResources{ Tag: tag, Resources: res, DownloadProgress: downloadProgress[tag], }) } return results, nil }
[ "func", "(", "p", "ResourcePersistence", ")", "ListResources", "(", "applicationID", "string", ")", "(", "resource", ".", "ApplicationResources", ",", "error", ")", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "applicationID", ")", "\n\n", "docs", ","...
// ListResources returns the info for each non-pending resource of the // identified application.
[ "ListResources", "returns", "the", "info", "for", "each", "non", "-", "pending", "resource", "of", "the", "identified", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_persistence.go#L58-L111
154,719
juju/juju
state/resources_persistence.go
ListPendingResources
func (p ResourcePersistence) ListPendingResources(applicationID string) ([]resource.Resource, error) { docs, err := p.resources(applicationID) if err != nil { return nil, errors.Trace(err) } var resources []resource.Resource for _, doc := range docs { if doc.PendingID == "" { continue } // doc.UnitID will always be empty here. res, err := doc2basicResource(doc) if err != nil { return nil, errors.Trace(err) } resources = append(resources, res) } return resources, nil }
go
func (p ResourcePersistence) ListPendingResources(applicationID string) ([]resource.Resource, error) { docs, err := p.resources(applicationID) if err != nil { return nil, errors.Trace(err) } var resources []resource.Resource for _, doc := range docs { if doc.PendingID == "" { continue } // doc.UnitID will always be empty here. res, err := doc2basicResource(doc) if err != nil { return nil, errors.Trace(err) } resources = append(resources, res) } return resources, nil }
[ "func", "(", "p", "ResourcePersistence", ")", "ListPendingResources", "(", "applicationID", "string", ")", "(", "[", "]", "resource", ".", "Resource", ",", "error", ")", "{", "docs", ",", "err", ":=", "p", ".", "resources", "(", "applicationID", ")", "\n",...
// ListPendingResources returns the extended, model-related info for // each pending resource of the identifies application.
[ "ListPendingResources", "returns", "the", "extended", "model", "-", "related", "info", "for", "each", "pending", "resource", "of", "the", "identifies", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_persistence.go#L115-L135
154,720
juju/juju
state/resources_persistence.go
GetResource
func (p ResourcePersistence) GetResource(id string) (res resource.Resource, storagePath string, _ error) { doc, err := p.getOne(id) if err != nil { return res, "", errors.Trace(err) } stored, err := doc2resource(doc) if err != nil { return res, "", errors.Trace(err) } return stored.Resource, stored.storagePath, nil }
go
func (p ResourcePersistence) GetResource(id string) (res resource.Resource, storagePath string, _ error) { doc, err := p.getOne(id) if err != nil { return res, "", errors.Trace(err) } stored, err := doc2resource(doc) if err != nil { return res, "", errors.Trace(err) } return stored.Resource, stored.storagePath, nil }
[ "func", "(", "p", "ResourcePersistence", ")", "GetResource", "(", "id", "string", ")", "(", "res", "resource", ".", "Resource", ",", "storagePath", "string", ",", "_", "error", ")", "{", "doc", ",", "err", ":=", "p", ".", "getOne", "(", "id", ")", "\...
// GetResource returns the extended, model-related info for the non-pending // resource.
[ "GetResource", "returns", "the", "extended", "model", "-", "related", "info", "for", "the", "non", "-", "pending", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_persistence.go#L139-L151
154,721
juju/juju
state/resources_persistence.go
StageResource
func (p ResourcePersistence) StageResource(res resource.Resource, storagePath string) (*StagedResource, error) { if storagePath == "" { return nil, errors.Errorf("missing storage path") } if err := res.Validate(); err != nil { return nil, errors.Annotate(err, "bad resource") } stored := storedResource{ Resource: res, storagePath: storagePath, } staged := &StagedResource{ base: p.base, id: res.ID, stored: stored, } if err := staged.stage(); err != nil { return nil, errors.Trace(err) } return staged, nil }
go
func (p ResourcePersistence) StageResource(res resource.Resource, storagePath string) (*StagedResource, error) { if storagePath == "" { return nil, errors.Errorf("missing storage path") } if err := res.Validate(); err != nil { return nil, errors.Annotate(err, "bad resource") } stored := storedResource{ Resource: res, storagePath: storagePath, } staged := &StagedResource{ base: p.base, id: res.ID, stored: stored, } if err := staged.stage(); err != nil { return nil, errors.Trace(err) } return staged, nil }
[ "func", "(", "p", "ResourcePersistence", ")", "StageResource", "(", "res", "resource", ".", "Resource", ",", "storagePath", "string", ")", "(", "*", "StagedResource", ",", "error", ")", "{", "if", "storagePath", "==", "\"", "\"", "{", "return", "nil", ",",...
// StageResource adds the resource in a separate staging area // if the resource isn't already staged. If it is then // errors.AlreadyExists is returned. A wrapper around the staged // resource is returned which supports both finalizing and removing // the staged resource.
[ "StageResource", "adds", "the", "resource", "in", "a", "separate", "staging", "area", "if", "the", "resource", "isn", "t", "already", "staged", ".", "If", "it", "is", "then", "errors", ".", "AlreadyExists", "is", "returned", ".", "A", "wrapper", "around", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_persistence.go#L158-L180
154,722
juju/juju
state/resources_persistence.go
SetResource
func (p ResourcePersistence) SetResource(res resource.Resource) error { stored, err := p.getStored(res) if errors.IsNotFound(err) { stored = storedResource{Resource: res} } else if err != nil { return errors.Trace(err) } // TODO(ericsnow) Ensure that stored.Resource matches res? If we do // so then the following line is unnecessary. stored.Resource = res if err := res.Validate(); err != nil { return errors.Annotate(err, "bad resource") } buildTxn := func(attempt int) ([]txn.Op, error) { // This is an "upsert". var ops []txn.Op switch attempt { case 0: ops = newInsertResourceOps(stored) case 1: ops = newUpdateResourceOps(stored) default: // Either insert or update will work so we should not get here. return nil, errors.New("setting the resource failed") } if stored.PendingID == "" { // Only non-pending resources must have an existing application. ops = append(ops, p.base.ApplicationExistsOps(res.ApplicationID)...) } return ops, nil } if err := p.base.Run(buildTxn); err != nil { return errors.Trace(err) } return nil }
go
func (p ResourcePersistence) SetResource(res resource.Resource) error { stored, err := p.getStored(res) if errors.IsNotFound(err) { stored = storedResource{Resource: res} } else if err != nil { return errors.Trace(err) } // TODO(ericsnow) Ensure that stored.Resource matches res? If we do // so then the following line is unnecessary. stored.Resource = res if err := res.Validate(); err != nil { return errors.Annotate(err, "bad resource") } buildTxn := func(attempt int) ([]txn.Op, error) { // This is an "upsert". var ops []txn.Op switch attempt { case 0: ops = newInsertResourceOps(stored) case 1: ops = newUpdateResourceOps(stored) default: // Either insert or update will work so we should not get here. return nil, errors.New("setting the resource failed") } if stored.PendingID == "" { // Only non-pending resources must have an existing application. ops = append(ops, p.base.ApplicationExistsOps(res.ApplicationID)...) } return ops, nil } if err := p.base.Run(buildTxn); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "p", "ResourcePersistence", ")", "SetResource", "(", "res", "resource", ".", "Resource", ")", "error", "{", "stored", ",", "err", ":=", "p", ".", "getStored", "(", "res", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", ...
// SetResource sets the info for the resource.
[ "SetResource", "sets", "the", "info", "for", "the", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_persistence.go#L183-L220
154,723
juju/juju
state/resources_persistence.go
SetCharmStoreResource
func (p ResourcePersistence) SetCharmStoreResource(id, applicationID string, res charmresource.Resource, lastPolled time.Time) error { if err := res.Validate(); err != nil { return errors.Annotate(err, "bad resource") } csRes := charmStoreResource{ Resource: res, id: id, applicationID: applicationID, lastPolled: lastPolled, } buildTxn := func(attempt int) ([]txn.Op, error) { // This is an "upsert". var ops []txn.Op switch attempt { case 0: ops = newInsertCharmStoreResourceOps(csRes) case 1: ops = newUpdateCharmStoreResourceOps(csRes) default: // Either insert or update will work so we should not get here. return nil, errors.New("setting the resource failed") } // No pending resources so we always do this here. ops = append(ops, p.base.ApplicationExistsOps(applicationID)...) return ops, nil } if err := p.base.Run(buildTxn); err != nil { return errors.Trace(err) } return nil }
go
func (p ResourcePersistence) SetCharmStoreResource(id, applicationID string, res charmresource.Resource, lastPolled time.Time) error { if err := res.Validate(); err != nil { return errors.Annotate(err, "bad resource") } csRes := charmStoreResource{ Resource: res, id: id, applicationID: applicationID, lastPolled: lastPolled, } buildTxn := func(attempt int) ([]txn.Op, error) { // This is an "upsert". var ops []txn.Op switch attempt { case 0: ops = newInsertCharmStoreResourceOps(csRes) case 1: ops = newUpdateCharmStoreResourceOps(csRes) default: // Either insert or update will work so we should not get here. return nil, errors.New("setting the resource failed") } // No pending resources so we always do this here. ops = append(ops, p.base.ApplicationExistsOps(applicationID)...) return ops, nil } if err := p.base.Run(buildTxn); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "p", "ResourcePersistence", ")", "SetCharmStoreResource", "(", "id", ",", "applicationID", "string", ",", "res", "charmresource", ".", "Resource", ",", "lastPolled", "time", ".", "Time", ")", "error", "{", "if", "err", ":=", "res", ".", "Validat...
// SetCharmStoreResource stores the resource info that was retrieved // from the charm store.
[ "SetCharmStoreResource", "stores", "the", "resource", "info", "that", "was", "retrieved", "from", "the", "charm", "store", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_persistence.go#L224-L256
154,724
juju/juju
state/resources_persistence.go
SetUnitResource
func (p ResourcePersistence) SetUnitResource(unitID string, res resource.Resource) error { if res.PendingID != "" { return errors.Errorf("pending resources not allowed") } return p.setUnitResource(unitID, res, nil) }
go
func (p ResourcePersistence) SetUnitResource(unitID string, res resource.Resource) error { if res.PendingID != "" { return errors.Errorf("pending resources not allowed") } return p.setUnitResource(unitID, res, nil) }
[ "func", "(", "p", "ResourcePersistence", ")", "SetUnitResource", "(", "unitID", "string", ",", "res", "resource", ".", "Resource", ")", "error", "{", "if", "res", ".", "PendingID", "!=", "\"", "\"", "{", "return", "errors", ".", "Errorf", "(", "\"", "\""...
// SetUnitResource stores the resource info for a particular unit. The // resource must already be set for the application.
[ "SetUnitResource", "stores", "the", "resource", "info", "for", "a", "particular", "unit", ".", "The", "resource", "must", "already", "be", "set", "for", "the", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_persistence.go#L260-L265
154,725
juju/juju
state/resources_persistence.go
SetUnitResourceProgress
func (p ResourcePersistence) SetUnitResourceProgress(unitID string, res resource.Resource, progress int64) error { if res.PendingID == "" { return errors.Errorf("only pending resources may track progress") } return p.setUnitResource(unitID, res, &progress) }
go
func (p ResourcePersistence) SetUnitResourceProgress(unitID string, res resource.Resource, progress int64) error { if res.PendingID == "" { return errors.Errorf("only pending resources may track progress") } return p.setUnitResource(unitID, res, &progress) }
[ "func", "(", "p", "ResourcePersistence", ")", "SetUnitResourceProgress", "(", "unitID", "string", ",", "res", "resource", ".", "Resource", ",", "progress", "int64", ")", "error", "{", "if", "res", ".", "PendingID", "==", "\"", "\"", "{", "return", "errors", ...
// SetUnitResource stores the resource info for a particular unit. The // resource must already be set for the application. The provided progress // is stored in the DB.
[ "SetUnitResource", "stores", "the", "resource", "info", "for", "a", "particular", "unit", ".", "The", "resource", "must", "already", "be", "set", "for", "the", "application", ".", "The", "provided", "progress", "is", "stored", "in", "the", "DB", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_persistence.go#L270-L275
154,726
juju/juju
state/resources_persistence.go
NewRemoveUnitResourcesOps
func (p ResourcePersistence) NewRemoveUnitResourcesOps(unitID string) ([]txn.Op, error) { docs, err := p.unitResources(unitID) if err != nil { return nil, errors.Trace(err) } ops := newRemoveResourcesOps(docs) // We do not remove the resource from the blob store here. That is // an application-level matter. return ops, nil }
go
func (p ResourcePersistence) NewRemoveUnitResourcesOps(unitID string) ([]txn.Op, error) { docs, err := p.unitResources(unitID) if err != nil { return nil, errors.Trace(err) } ops := newRemoveResourcesOps(docs) // We do not remove the resource from the blob store here. That is // an application-level matter. return ops, nil }
[ "func", "(", "p", "ResourcePersistence", ")", "NewRemoveUnitResourcesOps", "(", "unitID", "string", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "docs", ",", "err", ":=", "p", ".", "unitResources", "(", "unitID", ")", "\n", "if", "err"...
// NewRemoveUnitResourcesOps returns mgo transaction operations // that remove resource information specific to the unit from state.
[ "NewRemoveUnitResourcesOps", "returns", "mgo", "transaction", "operations", "that", "remove", "resource", "information", "specific", "to", "the", "unit", "from", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_persistence.go#L375-L385
154,727
juju/juju
state/resources_persistence.go
NewRemoveResourcesOps
func (p ResourcePersistence) NewRemoveResourcesOps(applicationID string) ([]txn.Op, error) { docs, err := p.resources(applicationID) if err != nil { return nil, errors.Trace(err) } return removeResourcesAndStorageCleanupOps(docs), nil }
go
func (p ResourcePersistence) NewRemoveResourcesOps(applicationID string) ([]txn.Op, error) { docs, err := p.resources(applicationID) if err != nil { return nil, errors.Trace(err) } return removeResourcesAndStorageCleanupOps(docs), nil }
[ "func", "(", "p", "ResourcePersistence", ")", "NewRemoveResourcesOps", "(", "applicationID", "string", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "docs", ",", "err", ":=", "p", ".", "resources", "(", "applicationID", ")", "\n", "if", ...
// NewRemoveResourcesOps returns mgo transaction operations that // remove all the applications's resources from state.
[ "NewRemoveResourcesOps", "returns", "mgo", "transaction", "operations", "that", "remove", "all", "the", "applications", "s", "resources", "from", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_persistence.go#L389-L395
154,728
juju/juju
state/resources_persistence.go
NewRemovePendingAppResourcesOps
func (p ResourcePersistence) NewRemovePendingAppResourcesOps(applicationID string, pendingIDs map[string]string) ([]txn.Op, error) { docs, err := p.resources(applicationID) if err != nil { return nil, errors.Trace(err) } pending := make([]resourceDoc, 0, len(docs)) for _, doc := range docs { if doc.UnitID != "" || doc.PendingID == "" { continue } if pendingIDs[doc.Name] != doc.PendingID { // This is a pending resource for a different deployment // of an application with the same name. continue } pending = append(pending, doc) } return removeResourcesAndStorageCleanupOps(pending), nil }
go
func (p ResourcePersistence) NewRemovePendingAppResourcesOps(applicationID string, pendingIDs map[string]string) ([]txn.Op, error) { docs, err := p.resources(applicationID) if err != nil { return nil, errors.Trace(err) } pending := make([]resourceDoc, 0, len(docs)) for _, doc := range docs { if doc.UnitID != "" || doc.PendingID == "" { continue } if pendingIDs[doc.Name] != doc.PendingID { // This is a pending resource for a different deployment // of an application with the same name. continue } pending = append(pending, doc) } return removeResourcesAndStorageCleanupOps(pending), nil }
[ "func", "(", "p", "ResourcePersistence", ")", "NewRemovePendingAppResourcesOps", "(", "applicationID", "string", ",", "pendingIDs", "map", "[", "string", "]", "string", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "docs", ",", "err", ":=",...
// NewRemovePendingResourcesOps returns mgo transaction operations to // clean up pending resources for the application from state. We pass // in the pending IDs to avoid removing the wrong resources if there's // a race to deploy the same application.
[ "NewRemovePendingResourcesOps", "returns", "mgo", "transaction", "operations", "to", "clean", "up", "pending", "resources", "for", "the", "application", "from", "state", ".", "We", "pass", "in", "the", "pending", "IDs", "to", "avoid", "removing", "the", "wrong", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_persistence.go#L401-L419
154,729
juju/juju
api/metricsadder/client.go
NewClient
func NewClient(caller base.APICaller) *Client { return &Client{facade: base.NewFacadeCaller(caller, "MetricsAdder")} }
go
func NewClient(caller base.APICaller) *Client { return &Client{facade: base.NewFacadeCaller(caller, "MetricsAdder")} }
[ "func", "NewClient", "(", "caller", "base", ".", "APICaller", ")", "*", "Client", "{", "return", "&", "Client", "{", "facade", ":", "base", ".", "NewFacadeCaller", "(", "caller", ",", "\"", "\"", ")", "}", "\n", "}" ]
// NewClient creates a new client for accessing the metricsadder API.
[ "NewClient", "creates", "a", "new", "client", "for", "accessing", "the", "metricsadder", "API", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/metricsadder/client.go#L22-L24
154,730
juju/juju
api/metricsadder/client.go
AddMetricBatches
func (c *Client) AddMetricBatches(batches []params.MetricBatchParam) (map[string]error, error) { parameters := params.MetricBatchParams{ Batches: batches, } results := new(params.ErrorResults) err := c.facade.FacadeCall("AddMetricBatches", parameters, results) if err != nil { return nil, errors.Trace(err) } resultMap := make(map[string]error) for i, result := range results.Results { resultMap[batches[i].Batch.UUID] = result.Error } return resultMap, nil }
go
func (c *Client) AddMetricBatches(batches []params.MetricBatchParam) (map[string]error, error) { parameters := params.MetricBatchParams{ Batches: batches, } results := new(params.ErrorResults) err := c.facade.FacadeCall("AddMetricBatches", parameters, results) if err != nil { return nil, errors.Trace(err) } resultMap := make(map[string]error) for i, result := range results.Results { resultMap[batches[i].Batch.UUID] = result.Error } return resultMap, nil }
[ "func", "(", "c", "*", "Client", ")", "AddMetricBatches", "(", "batches", "[", "]", "params", ".", "MetricBatchParam", ")", "(", "map", "[", "string", "]", "error", ",", "error", ")", "{", "parameters", ":=", "params", ".", "MetricBatchParams", "{", "Bat...
// AddMetricBatches implements the MetricsAdderClient interface.
[ "AddMetricBatches", "implements", "the", "MetricsAdderClient", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/metricsadder/client.go#L34-L48
154,731
juju/juju
worker/txnpruner/txnpruner.go
New
func New(tp TransactionPruner, interval time.Duration, clock clock.Clock) worker.Worker { return jworker.NewSimpleWorker(func(stopCh <-chan struct{}) error { for { select { case <-clock.After(interval): err := tp.MaybePruneTransactions() if err != nil { return errors.Annotate(err, "pruning failed, txnpruner stopping") } case <-stopCh: return nil } } }) }
go
func New(tp TransactionPruner, interval time.Duration, clock clock.Clock) worker.Worker { return jworker.NewSimpleWorker(func(stopCh <-chan struct{}) error { for { select { case <-clock.After(interval): err := tp.MaybePruneTransactions() if err != nil { return errors.Annotate(err, "pruning failed, txnpruner stopping") } case <-stopCh: return nil } } }) }
[ "func", "New", "(", "tp", "TransactionPruner", ",", "interval", "time", ".", "Duration", ",", "clock", "clock", ".", "Clock", ")", "worker", ".", "Worker", "{", "return", "jworker", ".", "NewSimpleWorker", "(", "func", "(", "stopCh", "<-", "chan", "struct"...
// New returns a worker which periodically prunes the data for // completed transactions.
[ "New", "returns", "a", "worker", "which", "periodically", "prunes", "the", "data", "for", "completed", "transactions", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/txnpruner/txnpruner.go#L24-L38
154,732
juju/juju
cmd/juju/status/output_tabular.go
FormatTabular
func FormatTabular(writer io.Writer, forceColor bool, value interface{}) error { fs, valueConverted := value.(formattedStatus) if !valueConverted { return errors.Errorf("expected value of type %T, got %T", fs, value) } // To format things into columns. tw := output.TabWriter(writer) if forceColor { tw.SetColorCapable(forceColor) } cloudRegion := fs.Model.Cloud if fs.Model.CloudRegion != "" { cloudRegion += "/" + fs.Model.CloudRegion } // Default table output header := []interface{}{"Model", "Controller", "Cloud/Region", "Version"} values := []interface{}{fs.Model.Name, fs.Model.Controller, cloudRegion, fs.Model.Version} // Optional table output if values exist message := getModelMessage(fs.Model) if fs.Model.SLA != "" { header = append(header, "SLA") values = append(values, fs.Model.SLA) } if cs := fs.Controller; cs != nil && cs.Timestamp != "" { header = append(header, "Timestamp") values = append(values, cs.Timestamp) } if message != "" { header = append(header, "Notes") values = append(values, message) } // The first set of headers don't use outputHeaders because it adds the blank line. w := startSection(tw, true, header...) w.Println(values...) if len(fs.RemoteApplications) > 0 { printRemoteApplications(tw, fs.RemoteApplications) } if len(fs.Applications) > 0 { printApplications(tw, fs) } if fs.Model.Type != caasModelType && len(fs.Machines) > 0 { printMachines(tw, false, fs.Machines) } if err := printOffers(tw, fs.Offers); err != nil { w.Println(err.Error()) } if len(fs.Relations) > 0 { printRelations(tw, fs.Relations) } if fs.Storage != nil { storage.FormatStorageListForStatusTabular(tw, *fs.Storage) } endSection(tw) return nil }
go
func FormatTabular(writer io.Writer, forceColor bool, value interface{}) error { fs, valueConverted := value.(formattedStatus) if !valueConverted { return errors.Errorf("expected value of type %T, got %T", fs, value) } // To format things into columns. tw := output.TabWriter(writer) if forceColor { tw.SetColorCapable(forceColor) } cloudRegion := fs.Model.Cloud if fs.Model.CloudRegion != "" { cloudRegion += "/" + fs.Model.CloudRegion } // Default table output header := []interface{}{"Model", "Controller", "Cloud/Region", "Version"} values := []interface{}{fs.Model.Name, fs.Model.Controller, cloudRegion, fs.Model.Version} // Optional table output if values exist message := getModelMessage(fs.Model) if fs.Model.SLA != "" { header = append(header, "SLA") values = append(values, fs.Model.SLA) } if cs := fs.Controller; cs != nil && cs.Timestamp != "" { header = append(header, "Timestamp") values = append(values, cs.Timestamp) } if message != "" { header = append(header, "Notes") values = append(values, message) } // The first set of headers don't use outputHeaders because it adds the blank line. w := startSection(tw, true, header...) w.Println(values...) if len(fs.RemoteApplications) > 0 { printRemoteApplications(tw, fs.RemoteApplications) } if len(fs.Applications) > 0 { printApplications(tw, fs) } if fs.Model.Type != caasModelType && len(fs.Machines) > 0 { printMachines(tw, false, fs.Machines) } if err := printOffers(tw, fs.Offers); err != nil { w.Println(err.Error()) } if len(fs.Relations) > 0 { printRelations(tw, fs.Relations) } if fs.Storage != nil { storage.FormatStorageListForStatusTabular(tw, *fs.Storage) } endSection(tw) return nil }
[ "func", "FormatTabular", "(", "writer", "io", ".", "Writer", ",", "forceColor", "bool", ",", "value", "interface", "{", "}", ")", "error", "{", "fs", ",", "valueConverted", ":=", "value", ".", "(", "formattedStatus", ")", "\n", "if", "!", "valueConverted",...
// FormatTabular writes a tabular summary of machines, applications, and // units. Any subordinate items are indented by two spaces beneath // their superior.
[ "FormatTabular", "writes", "a", "tabular", "summary", "of", "machines", "applications", "and", "units", ".", "Any", "subordinate", "items", "are", "indented", "by", "two", "spaces", "beneath", "their", "superior", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/status/output_tabular.go#L38-L104
154,733
juju/juju
cmd/juju/status/output_tabular.go
printOffers
func printOffers(tw *ansiterm.TabWriter, offers map[string]offerStatus) error { if len(offers) == 0 { return nil } w := startSection(tw, false, "Offer", "Application", "Charm", "Rev", "Connected", "Endpoint", "Interface", "Role") for _, offerName := range naturalsort.Sort(stringKeysFromMap(offers)) { offer := offers[offerName] // Sort endpoints alphabetically. endpoints := []string{} for endpoint := range offer.Endpoints { endpoints = append(endpoints, endpoint) } sort.Strings(endpoints) for i, endpointName := range endpoints { endpoint := offer.Endpoints[endpointName] if i == 0 { // As there is some information about offer and its endpoints, // only display offer information once when the first endpoint is displayed. curl, err := charm.ParseURL(offer.CharmURL) if err != nil { return errors.Trace(err) } w.Println(offerName, offer.ApplicationName, curl.Name, fmt.Sprint(curl.Revision), fmt.Sprintf("%v/%v", offer.ActiveConnectedCount, offer.TotalConnectedCount), endpointName, endpoint.Interface, endpoint.Role) continue } // Subsequent lines only need to display endpoint information. // This will display less noise. w.Println("", "", "", "", endpointName, endpoint.Interface, endpoint.Role) } } endSection(tw) return nil }
go
func printOffers(tw *ansiterm.TabWriter, offers map[string]offerStatus) error { if len(offers) == 0 { return nil } w := startSection(tw, false, "Offer", "Application", "Charm", "Rev", "Connected", "Endpoint", "Interface", "Role") for _, offerName := range naturalsort.Sort(stringKeysFromMap(offers)) { offer := offers[offerName] // Sort endpoints alphabetically. endpoints := []string{} for endpoint := range offer.Endpoints { endpoints = append(endpoints, endpoint) } sort.Strings(endpoints) for i, endpointName := range endpoints { endpoint := offer.Endpoints[endpointName] if i == 0 { // As there is some information about offer and its endpoints, // only display offer information once when the first endpoint is displayed. curl, err := charm.ParseURL(offer.CharmURL) if err != nil { return errors.Trace(err) } w.Println(offerName, offer.ApplicationName, curl.Name, fmt.Sprint(curl.Revision), fmt.Sprintf("%v/%v", offer.ActiveConnectedCount, offer.TotalConnectedCount), endpointName, endpoint.Interface, endpoint.Role) continue } // Subsequent lines only need to display endpoint information. // This will display less noise. w.Println("", "", "", "", endpointName, endpoint.Interface, endpoint.Role) } } endSection(tw) return nil }
[ "func", "printOffers", "(", "tw", "*", "ansiterm", ".", "TabWriter", ",", "offers", "map", "[", "string", "]", "offerStatus", ")", "error", "{", "if", "len", "(", "offers", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "w", ":=", "startSecti...
// printOffers prints a tabular summary of the offers.
[ "printOffers", "prints", "a", "tabular", "summary", "of", "the", "offers", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/status/output_tabular.go#L313-L349
154,734
juju/juju
cmd/juju/status/output_tabular.go
FormatMachineTabular
func FormatMachineTabular(writer io.Writer, forceColor bool, value interface{}) error { fs, valueConverted := value.(formattedMachineStatus) if !valueConverted { return errors.Errorf("expected value of type %T, got %T", fs, value) } tw := output.TabWriter(writer) if forceColor { tw.SetColorCapable(forceColor) } printMachines(tw, true, fs.Machines) return nil }
go
func FormatMachineTabular(writer io.Writer, forceColor bool, value interface{}) error { fs, valueConverted := value.(formattedMachineStatus) if !valueConverted { return errors.Errorf("expected value of type %T, got %T", fs, value) } tw := output.TabWriter(writer) if forceColor { tw.SetColorCapable(forceColor) } printMachines(tw, true, fs.Machines) return nil }
[ "func", "FormatMachineTabular", "(", "writer", "io", ".", "Writer", ",", "forceColor", "bool", ",", "value", "interface", "{", "}", ")", "error", "{", "fs", ",", "valueConverted", ":=", "value", ".", "(", "formattedMachineStatus", ")", "\n", "if", "!", "va...
// FormatMachineTabular writes a tabular summary of machine
[ "FormatMachineTabular", "writes", "a", "tabular", "summary", "of", "machine" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/status/output_tabular.go#L421-L432
154,735
juju/juju
cmd/juju/status/output_tabular.go
agentDoing
func agentDoing(agentStatus statusInfoContents) string { if agentStatus.Current != status.Executing { return "" } // First see if we can determine a hook name. var hookNames []string for _, h := range hooks.UnitHooks() { hookNames = append(hookNames, string(h)) } for _, h := range hooks.RelationHooks() { hookNames = append(hookNames, string(h)) } hookExp := regexp.MustCompile(fmt.Sprintf(`running (?P<hook>%s?) hook`, strings.Join(hookNames, "|"))) match := hookExp.FindStringSubmatch(agentStatus.Message) if len(match) > 0 { return match[1] } // Now try for an action name. actionExp := regexp.MustCompile(`running action (?P<action>.*)`) match = actionExp.FindStringSubmatch(agentStatus.Message) if len(match) > 0 { return match[1] } return "" }
go
func agentDoing(agentStatus statusInfoContents) string { if agentStatus.Current != status.Executing { return "" } // First see if we can determine a hook name. var hookNames []string for _, h := range hooks.UnitHooks() { hookNames = append(hookNames, string(h)) } for _, h := range hooks.RelationHooks() { hookNames = append(hookNames, string(h)) } hookExp := regexp.MustCompile(fmt.Sprintf(`running (?P<hook>%s?) hook`, strings.Join(hookNames, "|"))) match := hookExp.FindStringSubmatch(agentStatus.Message) if len(match) > 0 { return match[1] } // Now try for an action name. actionExp := regexp.MustCompile(`running action (?P<action>.*)`) match = actionExp.FindStringSubmatch(agentStatus.Message) if len(match) > 0 { return match[1] } return "" }
[ "func", "agentDoing", "(", "agentStatus", "statusInfoContents", ")", "string", "{", "if", "agentStatus", ".", "Current", "!=", "status", ".", "Executing", "{", "return", "\"", "\"", "\n", "}", "\n", "// First see if we can determine a hook name.", "var", "hookNames"...
// agentDoing returns what hook or action, if any, // the agent is currently executing. // The hook name or action is extracted from the agent message.
[ "agentDoing", "returns", "what", "hook", "or", "action", "if", "any", "the", "agent", "is", "currently", "executing", ".", "The", "hook", "name", "or", "action", "is", "extracted", "from", "the", "agent", "message", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/status/output_tabular.go#L437-L461
154,736
juju/juju
provider/ec2/image.go
findInstanceSpec
func findInstanceSpec( controller bool, allImageMetadata []*imagemetadata.ImageMetadata, instanceTypes []instances.InstanceType, ic *instances.InstanceConstraint, ) (*instances.InstanceSpec, error) { logger.Debugf("received %d image(s)", len(allImageMetadata)) if !controller { ic.Constraints = withDefaultNonControllerConstraints(ic.Constraints) } suitableImages := filterImages(allImageMetadata, ic) logger.Debugf("found %d suitable image(s)", len(suitableImages)) images := instances.ImageMetadataToImages(suitableImages) return instances.FindInstanceSpec(images, ic, instanceTypes) }
go
func findInstanceSpec( controller bool, allImageMetadata []*imagemetadata.ImageMetadata, instanceTypes []instances.InstanceType, ic *instances.InstanceConstraint, ) (*instances.InstanceSpec, error) { logger.Debugf("received %d image(s)", len(allImageMetadata)) if !controller { ic.Constraints = withDefaultNonControllerConstraints(ic.Constraints) } suitableImages := filterImages(allImageMetadata, ic) logger.Debugf("found %d suitable image(s)", len(suitableImages)) images := instances.ImageMetadataToImages(suitableImages) return instances.FindInstanceSpec(images, ic, instanceTypes) }
[ "func", "findInstanceSpec", "(", "controller", "bool", ",", "allImageMetadata", "[", "]", "*", "imagemetadata", ".", "ImageMetadata", ",", "instanceTypes", "[", "]", "instances", ".", "InstanceType", ",", "ic", "*", "instances", ".", "InstanceConstraint", ",", "...
// findInstanceSpec returns an InstanceSpec satisfying the supplied instanceConstraint.
[ "findInstanceSpec", "returns", "an", "InstanceSpec", "satisfying", "the", "supplied", "instanceConstraint", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/image.go#L39-L53
154,737
juju/juju
resource/context/cmd/get.go
NewGetCmd
func NewGetCmd(c jujuc.ContextComponent) (*GetCmd, error) { return &GetCmd{ compContext: c, }, nil }
go
func NewGetCmd(c jujuc.ContextComponent) (*GetCmd, error) { return &GetCmd{ compContext: c, }, nil }
[ "func", "NewGetCmd", "(", "c", "jujuc", ".", "ContextComponent", ")", "(", "*", "GetCmd", ",", "error", ")", "{", "return", "&", "GetCmd", "{", "compContext", ":", "c", ",", "}", ",", "nil", "\n", "}" ]
// NewGetCmd creates a new GetCmd for the given hook context.
[ "NewGetCmd", "creates", "a", "new", "GetCmd", "for", "the", "given", "hook", "context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/cmd/get.go#L20-L24
154,738
juju/juju
cmd/juju/user/whoami.go
NewWhoAmICommand
func NewWhoAmICommand() cmd.Command { cmd := &whoAmICommand{ store: jujuclient.NewFileClientStore(), } return modelcmd.WrapBase(cmd) }
go
func NewWhoAmICommand() cmd.Command { cmd := &whoAmICommand{ store: jujuclient.NewFileClientStore(), } return modelcmd.WrapBase(cmd) }
[ "func", "NewWhoAmICommand", "(", ")", "cmd", ".", "Command", "{", "cmd", ":=", "&", "whoAmICommand", "{", "store", ":", "jujuclient", ".", "NewFileClientStore", "(", ")", ",", "}", "\n", "return", "modelcmd", ".", "WrapBase", "(", "cmd", ")", "\n", "}" ]
// NewWhoAmICommand returns a command to print login details.
[ "NewWhoAmICommand", "returns", "a", "command", "to", "print", "login", "details", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/user/whoami.go#L37-L42
154,739
juju/juju
cmd/helpers.go
IsUserAbortedError
func IsUserAbortedError(err error) bool { _, ok := errors.Cause(err).(userAbortedError) return ok }
go
func IsUserAbortedError(err error) bool { _, ok := errors.Cause(err).(userAbortedError) return ok }
[ "func", "IsUserAbortedError", "(", "err", "error", ")", "bool", "{", "_", ",", "ok", ":=", "errors", ".", "Cause", "(", "err", ")", ".", "(", "userAbortedError", ")", "\n", "return", "ok", "\n", "}" ]
// IsUserAbortedError returns true if err is of type userAbortedError.
[ "IsUserAbortedError", "returns", "true", "if", "err", "is", "of", "type", "userAbortedError", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/helpers.go#L25-L28
154,740
juju/juju
cmd/helpers.go
UserConfirmYes
func UserConfirmYes(ctx *cmd.Context) error { scanner := bufio.NewScanner(ctx.Stdin) scanner.Scan() err := scanner.Err() if err != nil && err != io.EOF { return errors.Trace(err) } answer := strings.ToLower(scanner.Text()) if answer != "y" && answer != "yes" { return errors.Trace(userAbortedError("aborted")) } return nil }
go
func UserConfirmYes(ctx *cmd.Context) error { scanner := bufio.NewScanner(ctx.Stdin) scanner.Scan() err := scanner.Err() if err != nil && err != io.EOF { return errors.Trace(err) } answer := strings.ToLower(scanner.Text()) if answer != "y" && answer != "yes" { return errors.Trace(userAbortedError("aborted")) } return nil }
[ "func", "UserConfirmYes", "(", "ctx", "*", "cmd", ".", "Context", ")", "error", "{", "scanner", ":=", "bufio", ".", "NewScanner", "(", "ctx", ".", "Stdin", ")", "\n", "scanner", ".", "Scan", "(", ")", "\n", "err", ":=", "scanner", ".", "Err", "(", ...
// UserConfirmYes returns an error if we do not read a "y" or "yes" from user // input.
[ "UserConfirmYes", "returns", "an", "error", "if", "we", "do", "not", "read", "a", "y", "or", "yes", "from", "user", "input", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/helpers.go#L32-L44
154,741
juju/juju
resource/api/client/client.go
NewClient
func NewClient(caller FacadeCaller, doer Doer, closer io.Closer) *Client { return &Client{ FacadeCaller: caller, Closer: closer, doer: doer, } }
go
func NewClient(caller FacadeCaller, doer Doer, closer io.Closer) *Client { return &Client{ FacadeCaller: caller, Closer: closer, doer: doer, } }
[ "func", "NewClient", "(", "caller", "FacadeCaller", ",", "doer", "Doer", ",", "closer", "io", ".", "Closer", ")", "*", "Client", "{", "return", "&", "Client", "{", "FacadeCaller", ":", "caller", ",", "Closer", ":", "closer", ",", "doer", ":", "doer", "...
// NewClient returns a new Client for the given raw API caller.
[ "NewClient", "returns", "a", "new", "Client", "for", "the", "given", "raw", "API", "caller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/client/client.go#L43-L49
154,742
juju/juju
resource/api/client/client.go
ListResources
func (c Client) ListResources(applications []string) ([]resource.ApplicationResources, error) { args, err := newListResourcesArgs(applications) if err != nil { return nil, errors.Trace(err) } var apiResults params.ResourcesResults if err := c.FacadeCall("ListResources", &args, &apiResults); err != nil { return nil, errors.Trace(err) } if len(apiResults.Results) != len(applications) { // We don't bother returning the results we *did* get since // something bad happened on the server. return nil, errors.Errorf("got invalid data from server (expected %d results, got %d)", len(applications), len(apiResults.Results)) } var errs []error results := make([]resource.ApplicationResources, len(applications)) for i := range applications { apiResult := apiResults.Results[i] result, err := api.APIResult2ApplicationResources(apiResult) if err != nil { errs = append(errs, errors.Trace(err)) } results[i] = result } if err := resolveErrors(errs); err != nil { return nil, errors.Trace(err) } return results, nil }
go
func (c Client) ListResources(applications []string) ([]resource.ApplicationResources, error) { args, err := newListResourcesArgs(applications) if err != nil { return nil, errors.Trace(err) } var apiResults params.ResourcesResults if err := c.FacadeCall("ListResources", &args, &apiResults); err != nil { return nil, errors.Trace(err) } if len(apiResults.Results) != len(applications) { // We don't bother returning the results we *did* get since // something bad happened on the server. return nil, errors.Errorf("got invalid data from server (expected %d results, got %d)", len(applications), len(apiResults.Results)) } var errs []error results := make([]resource.ApplicationResources, len(applications)) for i := range applications { apiResult := apiResults.Results[i] result, err := api.APIResult2ApplicationResources(apiResult) if err != nil { errs = append(errs, errors.Trace(err)) } results[i] = result } if err := resolveErrors(errs); err != nil { return nil, errors.Trace(err) } return results, nil }
[ "func", "(", "c", "Client", ")", "ListResources", "(", "applications", "[", "]", "string", ")", "(", "[", "]", "resource", ".", "ApplicationResources", ",", "error", ")", "{", "args", ",", "err", ":=", "newListResourcesArgs", "(", "applications", ")", "\n"...
// ListResources calls the ListResources API server method with // the given application names.
[ "ListResources", "calls", "the", "ListResources", "API", "server", "method", "with", "the", "given", "application", "names", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/client/client.go#L53-L86
154,743
juju/juju
resource/api/client/client.go
newListResourcesArgs
func newListResourcesArgs(applications []string) (params.ListResourcesArgs, error) { var args params.ListResourcesArgs var errs []error for _, application := range applications { if !names.IsValidApplication(application) { err := errors.Errorf("invalid application %q", application) errs = append(errs, err) continue } args.Entities = append(args.Entities, params.Entity{ Tag: names.NewApplicationTag(application).String(), }) } if err := resolveErrors(errs); err != nil { return args, errors.Trace(err) } return args, nil }
go
func newListResourcesArgs(applications []string) (params.ListResourcesArgs, error) { var args params.ListResourcesArgs var errs []error for _, application := range applications { if !names.IsValidApplication(application) { err := errors.Errorf("invalid application %q", application) errs = append(errs, err) continue } args.Entities = append(args.Entities, params.Entity{ Tag: names.NewApplicationTag(application).String(), }) } if err := resolveErrors(errs); err != nil { return args, errors.Trace(err) } return args, nil }
[ "func", "newListResourcesArgs", "(", "applications", "[", "]", "string", ")", "(", "params", ".", "ListResourcesArgs", ",", "error", ")", "{", "var", "args", "params", ".", "ListResourcesArgs", "\n", "var", "errs", "[", "]", "error", "\n", "for", "_", ",",...
// newListResourcesArgs returns the arguments for the ListResources endpoint.
[ "newListResourcesArgs", "returns", "the", "arguments", "for", "the", "ListResources", "endpoint", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/client/client.go#L89-L106
154,744
juju/juju
resource/api/client/client.go
Upload
func (c Client) Upload(application, name, filename string, reader io.ReadSeeker) error { uReq, err := api.NewUploadRequest(application, name, filename, reader) if err != nil { return errors.Trace(err) } req, err := uReq.HTTPRequest() if err != nil { return errors.Trace(err) } var response params.UploadResult // ignored if err := c.doer.Do(req, reader, &response); err != nil { return errors.Trace(err) } return nil }
go
func (c Client) Upload(application, name, filename string, reader io.ReadSeeker) error { uReq, err := api.NewUploadRequest(application, name, filename, reader) if err != nil { return errors.Trace(err) } req, err := uReq.HTTPRequest() if err != nil { return errors.Trace(err) } var response params.UploadResult // ignored if err := c.doer.Do(req, reader, &response); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "c", "Client", ")", "Upload", "(", "application", ",", "name", ",", "filename", "string", ",", "reader", "io", ".", "ReadSeeker", ")", "error", "{", "uReq", ",", "err", ":=", "api", ".", "NewUploadRequest", "(", "application", ",", "name", ...
// Upload sends the provided resource blob up to Juju.
[ "Upload", "sends", "the", "provided", "resource", "blob", "up", "to", "Juju", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/client/client.go#L109-L125
154,745
juju/juju
resource/api/client/client.go
AddPendingResources
func (c Client) AddPendingResources(args AddPendingResourcesArgs) (pendingIDs []string, err error) { apiArgs, err := newAddPendingResourcesArgs(args.ApplicationID, args.CharmID, args.CharmStoreMacaroon, args.Resources) if err != nil { return nil, errors.Trace(err) } var result params.AddPendingResourcesResult if err := c.FacadeCall("AddPendingResources", &apiArgs, &result); err != nil { return nil, errors.Trace(err) } if result.Error != nil { err := common.RestoreError(result.Error) return nil, errors.Trace(err) } if len(result.PendingIDs) != len(args.Resources) { return nil, errors.Errorf("bad data from server: expected %d IDs, got %d", len(args.Resources), len(result.PendingIDs)) } for i, id := range result.PendingIDs { if id == "" { return nil, errors.Errorf("bad data from server: got an empty ID for resource %q", args.Resources[i].Name) } // TODO(ericsnow) Do other validation? } return result.PendingIDs, nil }
go
func (c Client) AddPendingResources(args AddPendingResourcesArgs) (pendingIDs []string, err error) { apiArgs, err := newAddPendingResourcesArgs(args.ApplicationID, args.CharmID, args.CharmStoreMacaroon, args.Resources) if err != nil { return nil, errors.Trace(err) } var result params.AddPendingResourcesResult if err := c.FacadeCall("AddPendingResources", &apiArgs, &result); err != nil { return nil, errors.Trace(err) } if result.Error != nil { err := common.RestoreError(result.Error) return nil, errors.Trace(err) } if len(result.PendingIDs) != len(args.Resources) { return nil, errors.Errorf("bad data from server: expected %d IDs, got %d", len(args.Resources), len(result.PendingIDs)) } for i, id := range result.PendingIDs { if id == "" { return nil, errors.Errorf("bad data from server: got an empty ID for resource %q", args.Resources[i].Name) } // TODO(ericsnow) Do other validation? } return result.PendingIDs, nil }
[ "func", "(", "c", "Client", ")", "AddPendingResources", "(", "args", "AddPendingResourcesArgs", ")", "(", "pendingIDs", "[", "]", "string", ",", "err", "error", ")", "{", "apiArgs", ",", "err", ":=", "newAddPendingResourcesArgs", "(", "args", ".", "Application...
// AddPendingResources sends the provided resource info up to Juju // without making it available yet.
[ "AddPendingResources", "sends", "the", "provided", "resource", "info", "up", "to", "Juju", "without", "making", "it", "available", "yet", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/client/client.go#L146-L172
154,746
juju/juju
resource/api/client/client.go
newAddPendingResourcesArgs
func newAddPendingResourcesArgs(applicationID string, chID charmstore.CharmID, csMac *macaroon.Macaroon, resources []charmresource.Resource) (params.AddPendingResourcesArgs, error) { var args params.AddPendingResourcesArgs if !names.IsValidApplication(applicationID) { return args, errors.Errorf("invalid application %q", applicationID) } tag := names.NewApplicationTag(applicationID).String() var apiResources []params.CharmResource for _, res := range resources { if err := res.Validate(); err != nil { return args, errors.Trace(err) } apiRes := api.CharmResource2API(res) apiResources = append(apiResources, apiRes) } args.Tag = tag args.Resources = apiResources if chID.URL != nil { args.URL = chID.URL.String() args.Channel = string(chID.Channel) args.CharmStoreMacaroon = csMac } return args, nil }
go
func newAddPendingResourcesArgs(applicationID string, chID charmstore.CharmID, csMac *macaroon.Macaroon, resources []charmresource.Resource) (params.AddPendingResourcesArgs, error) { var args params.AddPendingResourcesArgs if !names.IsValidApplication(applicationID) { return args, errors.Errorf("invalid application %q", applicationID) } tag := names.NewApplicationTag(applicationID).String() var apiResources []params.CharmResource for _, res := range resources { if err := res.Validate(); err != nil { return args, errors.Trace(err) } apiRes := api.CharmResource2API(res) apiResources = append(apiResources, apiRes) } args.Tag = tag args.Resources = apiResources if chID.URL != nil { args.URL = chID.URL.String() args.Channel = string(chID.Channel) args.CharmStoreMacaroon = csMac } return args, nil }
[ "func", "newAddPendingResourcesArgs", "(", "applicationID", "string", ",", "chID", "charmstore", ".", "CharmID", ",", "csMac", "*", "macaroon", ".", "Macaroon", ",", "resources", "[", "]", "charmresource", ".", "Resource", ")", "(", "params", ".", "AddPendingRes...
// newAddPendingResourcesArgs returns the arguments for the // AddPendingResources API endpoint.
[ "newAddPendingResourcesArgs", "returns", "the", "arguments", "for", "the", "AddPendingResources", "API", "endpoint", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/client/client.go#L176-L200
154,747
juju/juju
resource/api/client/client.go
UploadPendingResource
func (c Client) UploadPendingResource(applicationID string, res charmresource.Resource, filename string, reader io.ReadSeeker) (pendingID string, err error) { ids, err := c.AddPendingResources(AddPendingResourcesArgs{ ApplicationID: applicationID, Resources: []charmresource.Resource{res}, }) if err != nil { return "", errors.Trace(err) } pendingID = ids[0] if reader != nil { uReq, err := api.NewUploadRequest(applicationID, res.Name, filename, reader) if err != nil { return "", errors.Trace(err) } uReq.PendingID = pendingID req, err := uReq.HTTPRequest() if err != nil { return "", errors.Trace(err) } var response params.UploadResult // ignored if err := c.doer.Do(req, reader, &response); err != nil { return "", errors.Trace(err) } } return pendingID, nil }
go
func (c Client) UploadPendingResource(applicationID string, res charmresource.Resource, filename string, reader io.ReadSeeker) (pendingID string, err error) { ids, err := c.AddPendingResources(AddPendingResourcesArgs{ ApplicationID: applicationID, Resources: []charmresource.Resource{res}, }) if err != nil { return "", errors.Trace(err) } pendingID = ids[0] if reader != nil { uReq, err := api.NewUploadRequest(applicationID, res.Name, filename, reader) if err != nil { return "", errors.Trace(err) } uReq.PendingID = pendingID req, err := uReq.HTTPRequest() if err != nil { return "", errors.Trace(err) } var response params.UploadResult // ignored if err := c.doer.Do(req, reader, &response); err != nil { return "", errors.Trace(err) } } return pendingID, nil }
[ "func", "(", "c", "Client", ")", "UploadPendingResource", "(", "applicationID", "string", ",", "res", "charmresource", ".", "Resource", ",", "filename", "string", ",", "reader", "io", ".", "ReadSeeker", ")", "(", "pendingID", "string", ",", "err", "error", "...
// UploadPendingResource sends the provided resource blob up to Juju // and makes it available.
[ "UploadPendingResource", "sends", "the", "provided", "resource", "blob", "up", "to", "Juju", "and", "makes", "it", "available", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/client/client.go#L204-L232
154,748
juju/juju
worker/instancemutater/mocks/machinemutater_mock.go
NewMockMutaterMachine
func NewMockMutaterMachine(ctrl *gomock.Controller) *MockMutaterMachine { mock := &MockMutaterMachine{ctrl: ctrl} mock.recorder = &MockMutaterMachineMockRecorder{mock} return mock }
go
func NewMockMutaterMachine(ctrl *gomock.Controller) *MockMutaterMachine { mock := &MockMutaterMachine{ctrl: ctrl} mock.recorder = &MockMutaterMachineMockRecorder{mock} return mock }
[ "func", "NewMockMutaterMachine", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockMutaterMachine", "{", "mock", ":=", "&", "MockMutaterMachine", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockMutaterMachineMockRecorder"...
// NewMockMutaterMachine creates a new mock instance
[ "NewMockMutaterMachine", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancemutater/mocks/machinemutater_mock.go#L29-L33
154,749
juju/juju
worker/instancemutater/mocks/machinemutater_mock.go
CharmProfilingInfo
func (m *MockMutaterMachine) CharmProfilingInfo() (*instancemutater.UnitProfileInfo, error) { ret := m.ctrl.Call(m, "CharmProfilingInfo") ret0, _ := ret[0].(*instancemutater.UnitProfileInfo) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockMutaterMachine) CharmProfilingInfo() (*instancemutater.UnitProfileInfo, error) { ret := m.ctrl.Call(m, "CharmProfilingInfo") ret0, _ := ret[0].(*instancemutater.UnitProfileInfo) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockMutaterMachine", ")", "CharmProfilingInfo", "(", ")", "(", "*", "instancemutater", ".", "UnitProfileInfo", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", "...
// CharmProfilingInfo mocks base method
[ "CharmProfilingInfo", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancemutater/mocks/machinemutater_mock.go#L41-L46
154,750
juju/juju
worker/instancemutater/mocks/machinemutater_mock.go
Refresh
func (m *MockMutaterMachine) Refresh() error { ret := m.ctrl.Call(m, "Refresh") ret0, _ := ret[0].(error) return ret0 }
go
func (m *MockMutaterMachine) Refresh() error { ret := m.ctrl.Call(m, "Refresh") ret0, _ := ret[0].(error) return ret0 }
[ "func", "(", "m", "*", "MockMutaterMachine", ")", "Refresh", "(", ")", "error", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "error", ")", "\n",...
// Refresh mocks base method
[ "Refresh", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancemutater/mocks/machinemutater_mock.go#L79-L83
154,751
juju/juju
worker/instancemutater/mocks/machinemutater_mock.go
SetCharmProfiles
func (mr *MockMutaterMachineMockRecorder) SetCharmProfiles(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCharmProfiles", reflect.TypeOf((*MockMutaterMachine)(nil).SetCharmProfiles), arg0) }
go
func (mr *MockMutaterMachineMockRecorder) SetCharmProfiles(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCharmProfiles", reflect.TypeOf((*MockMutaterMachine)(nil).SetCharmProfiles), arg0) }
[ "func", "(", "mr", "*", "MockMutaterMachineMockRecorder", ")", "SetCharmProfiles", "(", "arg0", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ...
// SetCharmProfiles indicates an expected call of SetCharmProfiles
[ "SetCharmProfiles", "indicates", "an", "expected", "call", "of", "SetCharmProfiles" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancemutater/mocks/machinemutater_mock.go#L98-L100
154,752
juju/juju
worker/instancemutater/mocks/machinemutater_mock.go
SetModificationStatus
func (mr *MockMutaterMachineMockRecorder) SetModificationStatus(arg0, arg1, arg2 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetModificationStatus", reflect.TypeOf((*MockMutaterMachine)(nil).SetModificationStatus), arg0, arg1, arg2) }
go
func (mr *MockMutaterMachineMockRecorder) SetModificationStatus(arg0, arg1, arg2 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetModificationStatus", reflect.TypeOf((*MockMutaterMachine)(nil).SetModificationStatus), arg0, arg1, arg2) }
[ "func", "(", "mr", "*", "MockMutaterMachineMockRecorder", ")", "SetModificationStatus", "(", "arg0", ",", "arg1", ",", "arg2", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodTy...
// SetModificationStatus indicates an expected call of SetModificationStatus
[ "SetModificationStatus", "indicates", "an", "expected", "call", "of", "SetModificationStatus" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancemutater/mocks/machinemutater_mock.go#L110-L112
154,753
juju/juju
api/caasunitprovisioner/client.go
WatchApplications
func (c *Client) WatchApplications() (watcher.StringsWatcher, error) { var result params.StringsWatchResult if err := c.facade.FacadeCall("WatchApplications", nil, &result); err != nil { return nil, err } if err := result.Error; err != nil { return nil, result.Error } w := apiwatcher.NewStringsWatcher(c.facade.RawAPICaller(), result) return w, nil }
go
func (c *Client) WatchApplications() (watcher.StringsWatcher, error) { var result params.StringsWatchResult if err := c.facade.FacadeCall("WatchApplications", nil, &result); err != nil { return nil, err } if err := result.Error; err != nil { return nil, result.Error } w := apiwatcher.NewStringsWatcher(c.facade.RawAPICaller(), result) return w, nil }
[ "func", "(", "c", "*", "Client", ")", "WatchApplications", "(", ")", "(", "watcher", ".", "StringsWatcher", ",", "error", ")", "{", "var", "result", "params", ".", "StringsWatchResult", "\n", "if", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(",...
// WatchApplications returns a StringsWatcher that notifies of // changes to the lifecycles of CAAS applications in the current model.
[ "WatchApplications", "returns", "a", "StringsWatcher", "that", "notifies", "of", "changes", "to", "the", "lifecycles", "of", "CAAS", "applications", "in", "the", "current", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasunitprovisioner/client.go#L54-L64
154,754
juju/juju
api/caasunitprovisioner/client.go
ApplicationConfig
func (c *Client) ApplicationConfig(applicationName string) (application.ConfigAttributes, error) { var results params.ApplicationGetConfigResults args := params.Entities{ Entities: []params.Entity{{Tag: names.NewApplicationTag(applicationName).String()}}, } err := c.facade.FacadeCall("ApplicationsConfig", args, &results) if err != nil { return nil, errors.Trace(err) } if len(results.Results) != len(args.Entities) { return nil, errors.Errorf("expected %d result(s), got %d", len(args.Entities), len(results.Results)) } return application.ConfigAttributes(results.Results[0].Config), nil }
go
func (c *Client) ApplicationConfig(applicationName string) (application.ConfigAttributes, error) { var results params.ApplicationGetConfigResults args := params.Entities{ Entities: []params.Entity{{Tag: names.NewApplicationTag(applicationName).String()}}, } err := c.facade.FacadeCall("ApplicationsConfig", args, &results) if err != nil { return nil, errors.Trace(err) } if len(results.Results) != len(args.Entities) { return nil, errors.Errorf("expected %d result(s), got %d", len(args.Entities), len(results.Results)) } return application.ConfigAttributes(results.Results[0].Config), nil }
[ "func", "(", "c", "*", "Client", ")", "ApplicationConfig", "(", "applicationName", "string", ")", "(", "application", ".", "ConfigAttributes", ",", "error", ")", "{", "var", "results", "params", ".", "ApplicationGetConfigResults", "\n", "args", ":=", "params", ...
// ApplicationConfig returns the config for the specified application.
[ "ApplicationConfig", "returns", "the", "config", "for", "the", "specified", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasunitprovisioner/client.go#L67-L80
154,755
juju/juju
api/caasunitprovisioner/client.go
WatchApplicationScale
func (c *Client) WatchApplicationScale(application string) (watcher.NotifyWatcher, error) { applicationTag, err := applicationTag(application) if err != nil { return nil, errors.Trace(err) } args := entities(applicationTag) var results params.NotifyWatchResults if err := c.facade.FacadeCall("WatchApplicationsScale", args, &results); err != nil { return nil, err } if n := len(results.Results); n != 1 { return nil, errors.Errorf("expected 1 result, got %d", n) } if err := results.Results[0].Error; err != nil { return nil, errors.Trace(err) } w := apiwatcher.NewNotifyWatcher(c.facade.RawAPICaller(), results.Results[0]) return w, nil }
go
func (c *Client) WatchApplicationScale(application string) (watcher.NotifyWatcher, error) { applicationTag, err := applicationTag(application) if err != nil { return nil, errors.Trace(err) } args := entities(applicationTag) var results params.NotifyWatchResults if err := c.facade.FacadeCall("WatchApplicationsScale", args, &results); err != nil { return nil, err } if n := len(results.Results); n != 1 { return nil, errors.Errorf("expected 1 result, got %d", n) } if err := results.Results[0].Error; err != nil { return nil, errors.Trace(err) } w := apiwatcher.NewNotifyWatcher(c.facade.RawAPICaller(), results.Results[0]) return w, nil }
[ "func", "(", "c", "*", "Client", ")", "WatchApplicationScale", "(", "application", "string", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "applicationTag", ",", "err", ":=", "applicationTag", "(", "application", ")", "\n", "if", "err", ...
// WatchApplicationScale returns a NotifyWatcher that notifies of // changes to the lifecycles of units of the specified // CAAS application in the current model.
[ "WatchApplicationScale", "returns", "a", "NotifyWatcher", "that", "notifies", "of", "changes", "to", "the", "lifecycles", "of", "units", "of", "the", "specified", "CAAS", "application", "in", "the", "current", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasunitprovisioner/client.go#L85-L104
154,756
juju/juju
api/caasunitprovisioner/client.go
ApplicationScale
func (c *Client) ApplicationScale(applicationName string) (int, error) { var results params.IntResults args := params.Entities{ Entities: []params.Entity{{Tag: names.NewApplicationTag(applicationName).String()}}, } err := c.facade.FacadeCall("ApplicationsScale", args, &results) if err != nil { return 0, errors.Trace(err) } if len(results.Results) != len(args.Entities) { return 0, errors.Errorf("expected %d result(s), got %d", len(args.Entities), len(results.Results)) } return results.Results[0].Result, nil }
go
func (c *Client) ApplicationScale(applicationName string) (int, error) { var results params.IntResults args := params.Entities{ Entities: []params.Entity{{Tag: names.NewApplicationTag(applicationName).String()}}, } err := c.facade.FacadeCall("ApplicationsScale", args, &results) if err != nil { return 0, errors.Trace(err) } if len(results.Results) != len(args.Entities) { return 0, errors.Errorf("expected %d result(s), got %d", len(args.Entities), len(results.Results)) } return results.Results[0].Result, nil }
[ "func", "(", "c", "*", "Client", ")", "ApplicationScale", "(", "applicationName", "string", ")", "(", "int", ",", "error", ")", "{", "var", "results", "params", ".", "IntResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", ...
// ApplicationScale returns the scale for the specified application.
[ "ApplicationScale", "returns", "the", "scale", "for", "the", "specified", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasunitprovisioner/client.go#L107-L120
154,757
juju/juju
api/caasunitprovisioner/client.go
ProvisioningInfo
func (c *Client) ProvisioningInfo(appName string) (*ProvisioningInfo, error) { appTag, err := applicationTag(appName) if err != nil { return nil, errors.Trace(err) } args := entities(appTag) var results params.KubernetesProvisioningInfoResults if err := c.facade.FacadeCall("ProvisioningInfo", args, &results); err != nil { return nil, err } if n := len(results.Results); n != 1 { return nil, errors.Errorf("expected 1 result, got %d", n) } if err := results.Results[0].Error; err != nil { return nil, maybeNotFound(err) } result := results.Results[0].Result info := &ProvisioningInfo{ PodSpec: result.PodSpec, Constraints: result.Constraints, Tags: result.Tags, } if result.DeploymentInfo != nil { info.DeploymentInfo = DeploymentInfo{ DeploymentType: result.DeploymentInfo.DeploymentType, ServiceType: result.DeploymentInfo.ServiceType, } } for _, fs := range result.Filesystems { fsInfo, err := filesystemFromParams(fs) if err != nil { return nil, errors.Trace(err) } info.Filesystems = append(info.Filesystems, *fsInfo) } var devs []devices.KubernetesDeviceParams for _, device := range result.Devices { devs = append(devs, devices.KubernetesDeviceParams{ Type: devices.DeviceType(device.Type), Count: device.Count, Attributes: device.Attributes, }) } info.Devices = devs return info, nil }
go
func (c *Client) ProvisioningInfo(appName string) (*ProvisioningInfo, error) { appTag, err := applicationTag(appName) if err != nil { return nil, errors.Trace(err) } args := entities(appTag) var results params.KubernetesProvisioningInfoResults if err := c.facade.FacadeCall("ProvisioningInfo", args, &results); err != nil { return nil, err } if n := len(results.Results); n != 1 { return nil, errors.Errorf("expected 1 result, got %d", n) } if err := results.Results[0].Error; err != nil { return nil, maybeNotFound(err) } result := results.Results[0].Result info := &ProvisioningInfo{ PodSpec: result.PodSpec, Constraints: result.Constraints, Tags: result.Tags, } if result.DeploymentInfo != nil { info.DeploymentInfo = DeploymentInfo{ DeploymentType: result.DeploymentInfo.DeploymentType, ServiceType: result.DeploymentInfo.ServiceType, } } for _, fs := range result.Filesystems { fsInfo, err := filesystemFromParams(fs) if err != nil { return nil, errors.Trace(err) } info.Filesystems = append(info.Filesystems, *fsInfo) } var devs []devices.KubernetesDeviceParams for _, device := range result.Devices { devs = append(devs, devices.KubernetesDeviceParams{ Type: devices.DeviceType(device.Type), Count: device.Count, Attributes: device.Attributes, }) } info.Devices = devs return info, nil }
[ "func", "(", "c", "*", "Client", ")", "ProvisioningInfo", "(", "appName", "string", ")", "(", "*", "ProvisioningInfo", ",", "error", ")", "{", "appTag", ",", "err", ":=", "applicationTag", "(", "appName", ")", "\n", "if", "err", "!=", "nil", "{", "retu...
// ProvisioningInfo returns the provisioning info for the specified CAAS // application in the current model.
[ "ProvisioningInfo", "returns", "the", "provisioning", "info", "for", "the", "specified", "CAAS", "application", "in", "the", "current", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasunitprovisioner/client.go#L164-L212
154,758
juju/juju
api/caasunitprovisioner/client.go
maybeNotFound
func maybeNotFound(err *params.Error) error { if err == nil || !params.IsCodeNotFound(err) { return err } return errors.NewNotFound(err, "") }
go
func maybeNotFound(err *params.Error) error { if err == nil || !params.IsCodeNotFound(err) { return err } return errors.NewNotFound(err, "") }
[ "func", "maybeNotFound", "(", "err", "*", "params", ".", "Error", ")", "error", "{", "if", "err", "==", "nil", "||", "!", "params", ".", "IsCodeNotFound", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "return", "errors", ".", "NewNotFound", ...
// maybeNotFound returns an error satisfying errors.IsNotFound // if the supplied error has a CodeNotFound error.
[ "maybeNotFound", "returns", "an", "error", "satisfying", "errors", ".", "IsNotFound", "if", "the", "supplied", "error", "has", "a", "CodeNotFound", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasunitprovisioner/client.go#L272-L277
154,759
juju/juju
api/caasunitprovisioner/client.go
UpdateUnits
func (c *Client) UpdateUnits(arg params.UpdateApplicationUnits) error { var result params.ErrorResults args := params.UpdateApplicationUnitArgs{Args: []params.UpdateApplicationUnits{arg}} err := c.facade.FacadeCall("UpdateApplicationsUnits", args, &result) if err != nil { return errors.Trace(err) } if len(result.Results) != len(args.Args) { return errors.Errorf("expected %d result(s), got %d", len(args.Args), len(result.Results)) } if result.Results[0].Error == nil { return nil } return maybeNotFound(result.Results[0].Error) }
go
func (c *Client) UpdateUnits(arg params.UpdateApplicationUnits) error { var result params.ErrorResults args := params.UpdateApplicationUnitArgs{Args: []params.UpdateApplicationUnits{arg}} err := c.facade.FacadeCall("UpdateApplicationsUnits", args, &result) if err != nil { return errors.Trace(err) } if len(result.Results) != len(args.Args) { return errors.Errorf("expected %d result(s), got %d", len(args.Args), len(result.Results)) } if result.Results[0].Error == nil { return nil } return maybeNotFound(result.Results[0].Error) }
[ "func", "(", "c", "*", "Client", ")", "UpdateUnits", "(", "arg", "params", ".", "UpdateApplicationUnits", ")", "error", "{", "var", "result", "params", ".", "ErrorResults", "\n", "args", ":=", "params", ".", "UpdateApplicationUnitArgs", "{", "Args", ":", "["...
// UpdateUnits updates the state model to reflect the state of the units // as reported by the cloud.
[ "UpdateUnits", "updates", "the", "state", "model", "to", "reflect", "the", "state", "of", "the", "units", "as", "reported", "by", "the", "cloud", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasunitprovisioner/client.go#L281-L295
154,760
juju/juju
api/caasunitprovisioner/client.go
UpdateApplicationService
func (c *Client) UpdateApplicationService(arg params.UpdateApplicationServiceArg) error { var result params.ErrorResults args := params.UpdateApplicationServiceArgs{Args: []params.UpdateApplicationServiceArg{arg}} if err := c.facade.FacadeCall("UpdateApplicationsService", args, &result); err != nil { return errors.Trace(err) } if len(result.Results) != len(args.Args) { return errors.Errorf("expected %d result(s), got %d", len(args.Args), len(result.Results)) } if result.Results[0].Error == nil { return nil } return maybeNotFound(result.Results[0].Error) }
go
func (c *Client) UpdateApplicationService(arg params.UpdateApplicationServiceArg) error { var result params.ErrorResults args := params.UpdateApplicationServiceArgs{Args: []params.UpdateApplicationServiceArg{arg}} if err := c.facade.FacadeCall("UpdateApplicationsService", args, &result); err != nil { return errors.Trace(err) } if len(result.Results) != len(args.Args) { return errors.Errorf("expected %d result(s), got %d", len(args.Args), len(result.Results)) } if result.Results[0].Error == nil { return nil } return maybeNotFound(result.Results[0].Error) }
[ "func", "(", "c", "*", "Client", ")", "UpdateApplicationService", "(", "arg", "params", ".", "UpdateApplicationServiceArg", ")", "error", "{", "var", "result", "params", ".", "ErrorResults", "\n", "args", ":=", "params", ".", "UpdateApplicationServiceArgs", "{", ...
// UpdateApplicationService updates the state model to reflect the state of the application's // service as reported by the cloud.
[ "UpdateApplicationService", "updates", "the", "state", "model", "to", "reflect", "the", "state", "of", "the", "application", "s", "service", "as", "reported", "by", "the", "cloud", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasunitprovisioner/client.go#L299-L312
154,761
juju/juju
api/caasunitprovisioner/client.go
SetOperatorStatus
func (c *Client) SetOperatorStatus(appName string, status status.Status, message string, data map[string]interface{}) error { var result params.ErrorResults args := params.SetStatus{Entities: []params.EntityStatusArgs{ {Tag: names.NewApplicationTag(appName).String(), Status: status.String(), Info: message, Data: data}, }} err := c.facade.FacadeCall("SetOperatorStatus", args, &result) if err != nil { return err } return result.OneError() }
go
func (c *Client) SetOperatorStatus(appName string, status status.Status, message string, data map[string]interface{}) error { var result params.ErrorResults args := params.SetStatus{Entities: []params.EntityStatusArgs{ {Tag: names.NewApplicationTag(appName).String(), Status: status.String(), Info: message, Data: data}, }} err := c.facade.FacadeCall("SetOperatorStatus", args, &result) if err != nil { return err } return result.OneError() }
[ "func", "(", "c", "*", "Client", ")", "SetOperatorStatus", "(", "appName", "string", ",", "status", "status", ".", "Status", ",", "message", "string", ",", "data", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "var", "result", "p...
// SetOperatorStatus updates the provisioning status of an operator.
[ "SetOperatorStatus", "updates", "the", "provisioning", "status", "of", "an", "operator", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasunitprovisioner/client.go#L315-L325
154,762
juju/juju
worker/peergrouper/worker.go
New
func New(config Config) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } w := &pgWorker{ config: config, machineChanges: make(chan struct{}), machineTrackers: make(map[string]*machineTracker), detailsRequests: make(chan string), } err := catacomb.Invoke(catacomb.Plan{ Site: &w.catacomb, Work: w.loop, }) if err != nil { return nil, errors.Trace(err) } return w, nil }
go
func New(config Config) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } w := &pgWorker{ config: config, machineChanges: make(chan struct{}), machineTrackers: make(map[string]*machineTracker), detailsRequests: make(chan string), } err := catacomb.Invoke(catacomb.Plan{ Site: &w.catacomb, Work: w.loop, }) if err != nil { return nil, errors.Trace(err) } return w, nil }
[ "func", "New", "(", "config", "Config", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")"...
// New returns a new worker that maintains the mongo replica set // with respect to the given state.
[ "New", "returns", "a", "new", "worker", "that", "maintains", "the", "mongo", "replica", "set", "with", "respect", "to", "the", "given", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/worker.go#L170-L189
154,763
juju/juju
worker/peergrouper/worker.go
watchForControllerChanges
func (w *pgWorker) watchForControllerChanges() (<-chan struct{}, error) { controllerInfoWatcher := w.config.State.WatchControllerInfo() if err := w.catacomb.Add(controllerInfoWatcher); err != nil { return nil, errors.Trace(err) } controllerStatusWatcher := w.config.State.WatchControllerStatusChanges() if err := w.catacomb.Add(controllerStatusWatcher); err != nil { return nil, errors.Trace(err) } out := make(chan struct{}) go func() { for { select { case <-w.catacomb.Dying(): return case <-controllerInfoWatcher.Changes(): out <- struct{}{} case <-controllerStatusWatcher.Changes(): out <- struct{}{} } } }() return out, nil }
go
func (w *pgWorker) watchForControllerChanges() (<-chan struct{}, error) { controllerInfoWatcher := w.config.State.WatchControllerInfo() if err := w.catacomb.Add(controllerInfoWatcher); err != nil { return nil, errors.Trace(err) } controllerStatusWatcher := w.config.State.WatchControllerStatusChanges() if err := w.catacomb.Add(controllerStatusWatcher); err != nil { return nil, errors.Trace(err) } out := make(chan struct{}) go func() { for { select { case <-w.catacomb.Dying(): return case <-controllerInfoWatcher.Changes(): out <- struct{}{} case <-controllerStatusWatcher.Changes(): out <- struct{}{} } } }() return out, nil }
[ "func", "(", "w", "*", "pgWorker", ")", "watchForControllerChanges", "(", ")", "(", "<-", "chan", "struct", "{", "}", ",", "error", ")", "{", "controllerInfoWatcher", ":=", "w", ".", "config", ".", "State", ".", "WatchControllerInfo", "(", ")", "\n", "if...
// watchForControllerChanges starts two watchers for changes to controller // info and status. // It returns a channel which will receive events if any of the watchers fires.
[ "watchForControllerChanges", "starts", "two", "watchers", "for", "changes", "to", "controller", "info", "and", "status", ".", "It", "returns", "a", "channel", "which", "will", "receive", "events", "if", "any", "of", "the", "watchers", "fires", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/worker.go#L317-L342
154,764
juju/juju
worker/peergrouper/worker.go
watchForConfigChanges
func (w *pgWorker) watchForConfigChanges() (<-chan struct{}, error) { controllerConfigWatcher := w.config.State.WatchControllerConfig() if err := w.catacomb.Add(controllerConfigWatcher); err != nil { return nil, errors.Trace(err) } return controllerConfigWatcher.Changes(), nil }
go
func (w *pgWorker) watchForConfigChanges() (<-chan struct{}, error) { controllerConfigWatcher := w.config.State.WatchControllerConfig() if err := w.catacomb.Add(controllerConfigWatcher); err != nil { return nil, errors.Trace(err) } return controllerConfigWatcher.Changes(), nil }
[ "func", "(", "w", "*", "pgWorker", ")", "watchForConfigChanges", "(", ")", "(", "<-", "chan", "struct", "{", "}", ",", "error", ")", "{", "controllerConfigWatcher", ":=", "w", ".", "config", ".", "State", ".", "WatchControllerConfig", "(", ")", "\n", "if...
// watchForConfigChanges starts a watcher for changes to controller config. // It returns a channel which will receive events if the watcher fires. // This is separate from watchForControllerChanges because of the worker loop // logic. If controller machines have not changed, then further processing // does not occur, whereas we want to re-publish API addresses and check // for replica-set changes if either the management or HA space configs have // changed.
[ "watchForConfigChanges", "starts", "a", "watcher", "for", "changes", "to", "controller", "config", ".", "It", "returns", "a", "channel", "which", "will", "receive", "events", "if", "the", "watcher", "fires", ".", "This", "is", "separate", "from", "watchForContro...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/worker.go#L351-L357
154,765
juju/juju
worker/peergrouper/worker.go
updateControllerMachines
func (w *pgWorker) updateControllerMachines() (bool, error) { info, err := w.config.State.ControllerInfo() if err != nil { return false, fmt.Errorf("cannot get controller info: %v", err) } logger.Debugf("controller machines in state: %#v", info.MachineIds) changed := false // Stop machine goroutines that no longer correspond to controller // machines. for _, m := range w.machineTrackers { if !inStrings(m.Id(), info.MachineIds) { worker.Stop(m) delete(w.machineTrackers, m.Id()) changed = true } } // Start machines with no watcher for _, id := range info.MachineIds { stm, err := w.config.State.Machine(id) if err != nil { if errors.IsNotFound(err) { // If the machine isn't found, it must have been // removed and will soon enough be removed // from the controller list. This will probably // never happen, but we'll code defensively anyway. logger.Warningf("machine %q from controller list not found", id) continue } return false, fmt.Errorf("cannot get machine %q: %v", id, err) } if _, ok := w.machineTrackers[id]; ok { continue } logger.Debugf("found new machine %q", id) // Don't add the machine unless it is "Started" machineStatus, err := stm.Status() if err != nil { return false, errors.Annotatef(err, "cannot get status for machine %q", id) } // A machine in status Error or Stopped might still be properly running the controller. We still want to treat // it as an active machine, even if we're trying to tear it down. if machineStatus.Status != status.Pending { logger.Debugf("machine %q has started, adding it to peergrouper list", id) tracker, err := newMachineTracker(stm, w.machineChanges) if err != nil { return false, errors.Trace(err) } if err := w.catacomb.Add(tracker); err != nil { return false, errors.Trace(err) } w.machineTrackers[id] = tracker changed = true } else { logger.Debugf("machine %q not ready: %v", id, machineStatus.Status) } } return changed, nil }
go
func (w *pgWorker) updateControllerMachines() (bool, error) { info, err := w.config.State.ControllerInfo() if err != nil { return false, fmt.Errorf("cannot get controller info: %v", err) } logger.Debugf("controller machines in state: %#v", info.MachineIds) changed := false // Stop machine goroutines that no longer correspond to controller // machines. for _, m := range w.machineTrackers { if !inStrings(m.Id(), info.MachineIds) { worker.Stop(m) delete(w.machineTrackers, m.Id()) changed = true } } // Start machines with no watcher for _, id := range info.MachineIds { stm, err := w.config.State.Machine(id) if err != nil { if errors.IsNotFound(err) { // If the machine isn't found, it must have been // removed and will soon enough be removed // from the controller list. This will probably // never happen, but we'll code defensively anyway. logger.Warningf("machine %q from controller list not found", id) continue } return false, fmt.Errorf("cannot get machine %q: %v", id, err) } if _, ok := w.machineTrackers[id]; ok { continue } logger.Debugf("found new machine %q", id) // Don't add the machine unless it is "Started" machineStatus, err := stm.Status() if err != nil { return false, errors.Annotatef(err, "cannot get status for machine %q", id) } // A machine in status Error or Stopped might still be properly running the controller. We still want to treat // it as an active machine, even if we're trying to tear it down. if machineStatus.Status != status.Pending { logger.Debugf("machine %q has started, adding it to peergrouper list", id) tracker, err := newMachineTracker(stm, w.machineChanges) if err != nil { return false, errors.Trace(err) } if err := w.catacomb.Add(tracker); err != nil { return false, errors.Trace(err) } w.machineTrackers[id] = tracker changed = true } else { logger.Debugf("machine %q not ready: %v", id, machineStatus.Status) } } return changed, nil }
[ "func", "(", "w", "*", "pgWorker", ")", "updateControllerMachines", "(", ")", "(", "bool", ",", "error", ")", "{", "info", ",", "err", ":=", "w", ".", "config", ".", "State", ".", "ControllerInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "re...
// updateControllerMachines updates the peergrouper's current list of // controller machines, as well as starting and stopping trackers for // them as they are added and removed.
[ "updateControllerMachines", "updates", "the", "peergrouper", "s", "current", "list", "of", "controller", "machines", "as", "well", "as", "starting", "and", "stopping", "trackers", "for", "them", "as", "they", "are", "added", "and", "removed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/worker.go#L362-L424
154,766
juju/juju
worker/peergrouper/worker.go
apiServerHostPorts
func (w *pgWorker) apiServerHostPorts() map[string][]network.HostPort { servers := make(map[string][]network.HostPort) for _, m := range w.machineTrackers { hostPorts := network.AddressesWithPort(m.Addresses(), w.config.APIPort) if len(hostPorts) == 0 { continue } servers[m.Id()] = hostPorts } return servers }
go
func (w *pgWorker) apiServerHostPorts() map[string][]network.HostPort { servers := make(map[string][]network.HostPort) for _, m := range w.machineTrackers { hostPorts := network.AddressesWithPort(m.Addresses(), w.config.APIPort) if len(hostPorts) == 0 { continue } servers[m.Id()] = hostPorts } return servers }
[ "func", "(", "w", "*", "pgWorker", ")", "apiServerHostPorts", "(", ")", "map", "[", "string", "]", "[", "]", "network", ".", "HostPort", "{", "servers", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "network", ".", "HostPort", ")", "\n", ...
// apiServerHostPorts returns the host-ports for each apiserver machine.
[ "apiServerHostPorts", "returns", "the", "host", "-", "ports", "for", "each", "apiserver", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/worker.go#L448-L458
154,767
juju/juju
worker/peergrouper/worker.go
peerGroupInfo
func (w *pgWorker) peerGroupInfo() (*peerGroupInfo, error) { sts, err := w.config.MongoSession.CurrentStatus() if err != nil { return nil, errors.Annotate(err, "cannot get replica set status") } members, err := w.config.MongoSession.CurrentMembers() if err != nil { return nil, errors.Annotate(err, "cannot get replica set members") } haSpace, err := w.getHASpaceFromConfig() if err != nil { return nil, err } logger.Tracef("read peer group info: %# v\n%# v", pretty.Formatter(sts), pretty.Formatter(members)) return newPeerGroupInfo(w.machineTrackers, sts.Members, members, w.config.MongoPort, haSpace) }
go
func (w *pgWorker) peerGroupInfo() (*peerGroupInfo, error) { sts, err := w.config.MongoSession.CurrentStatus() if err != nil { return nil, errors.Annotate(err, "cannot get replica set status") } members, err := w.config.MongoSession.CurrentMembers() if err != nil { return nil, errors.Annotate(err, "cannot get replica set members") } haSpace, err := w.getHASpaceFromConfig() if err != nil { return nil, err } logger.Tracef("read peer group info: %# v\n%# v", pretty.Formatter(sts), pretty.Formatter(members)) return newPeerGroupInfo(w.machineTrackers, sts.Members, members, w.config.MongoPort, haSpace) }
[ "func", "(", "w", "*", "pgWorker", ")", "peerGroupInfo", "(", ")", "(", "*", "peerGroupInfo", ",", "error", ")", "{", "sts", ",", "err", ":=", "w", ".", "config", ".", "MongoSession", ".", "CurrentStatus", "(", ")", "\n", "if", "err", "!=", "nil", ...
// peerGroupInfo collates current session information about the // mongo peer group with information from state machines.
[ "peerGroupInfo", "collates", "current", "session", "information", "about", "the", "mongo", "peer", "group", "with", "information", "from", "state", "machines", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/worker.go#L662-L680
154,768
juju/juju
worker/peergrouper/worker.go
setHasVote
func setHasVote(ms []*machineTracker, hasVote bool) error { if len(ms) == 0 { return nil } logger.Infof("setting HasVote=%v on machines %v", hasVote, ms) for _, m := range ms { if err := m.stm.SetHasVote(hasVote); err != nil { return fmt.Errorf("cannot set voting status of %q to %v: %v", m.Id(), hasVote, err) } } return nil }
go
func setHasVote(ms []*machineTracker, hasVote bool) error { if len(ms) == 0 { return nil } logger.Infof("setting HasVote=%v on machines %v", hasVote, ms) for _, m := range ms { if err := m.stm.SetHasVote(hasVote); err != nil { return fmt.Errorf("cannot set voting status of %q to %v: %v", m.Id(), hasVote, err) } } return nil }
[ "func", "setHasVote", "(", "ms", "[", "]", "*", "machineTracker", ",", "hasVote", "bool", ")", "error", "{", "if", "len", "(", "ms", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "hasVote", "...
// setHasVote sets the HasVote status of all the given machines to hasVote.
[ "setHasVote", "sets", "the", "HasVote", "status", "of", "all", "the", "given", "machines", "to", "hasVote", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/worker.go#L693-L704
154,769
juju/juju
cmd/juju/application/config.go
getAPI
func (c *configCommand) getAPI() (applicationAPI, error) { if c.api != nil { return c.api, nil } root, err := c.NewAPIRoot() if err != nil { return nil, errors.Trace(err) } client := application.NewClient(root) return client, nil }
go
func (c *configCommand) getAPI() (applicationAPI, error) { if c.api != nil { return c.api, nil } root, err := c.NewAPIRoot() if err != nil { return nil, errors.Trace(err) } client := application.NewClient(root) return client, nil }
[ "func", "(", "c", "*", "configCommand", ")", "getAPI", "(", ")", "(", "applicationAPI", ",", "error", ")", "{", "if", "c", ".", "api", "!=", "nil", "{", "return", "c", ".", "api", ",", "nil", "\n", "}", "\n", "root", ",", "err", ":=", "c", ".",...
// getAPI either uses the fake API set at test time or that is nil, gets a real // API and sets that as the API.
[ "getAPI", "either", "uses", "the", "fake", "API", "set", "at", "test", "time", "or", "that", "is", "nil", "gets", "a", "real", "API", "and", "sets", "that", "as", "the", "API", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/config.go#L136-L146
154,770
juju/juju
cmd/juju/application/config.go
resetConfig
func (c *configCommand) resetConfig(client applicationAPI, ctx *cmd.Context) error { var err error if client.BestAPIVersion() < 6 { err = client.Unset(c.applicationName, c.resetKeys) } else { err = client.UnsetApplicationConfig(c.branchName, c.applicationName, c.resetKeys) } return block.ProcessBlockedError(err, block.BlockChange) }
go
func (c *configCommand) resetConfig(client applicationAPI, ctx *cmd.Context) error { var err error if client.BestAPIVersion() < 6 { err = client.Unset(c.applicationName, c.resetKeys) } else { err = client.UnsetApplicationConfig(c.branchName, c.applicationName, c.resetKeys) } return block.ProcessBlockedError(err, block.BlockChange) }
[ "func", "(", "c", "*", "configCommand", ")", "resetConfig", "(", "client", "applicationAPI", ",", "ctx", "*", "cmd", ".", "Context", ")", "error", "{", "var", "err", "error", "\n", "if", "client", ".", "BestAPIVersion", "(", ")", "<", "6", "{", "err", ...
// resetConfig is the run action when we are resetting attributes.
[ "resetConfig", "is", "the", "run", "action", "when", "we", "are", "resetting", "attributes", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/config.go#L317-L325
154,771
juju/juju
cmd/juju/application/config.go
setConfig
func (c *configCommand) setConfig(client applicationAPI, ctx *cmd.Context) error { if c.useFile { return c.setConfigFromFile(client, ctx) } settings, err := c.validateValues(ctx) if err != nil { return errors.Trace(err) } result, err := client.Get(c.branchName, c.applicationName) if err != nil { return err } for k, v := range settings { configValue := result.CharmConfig[k] configValueMap, ok := configValue.(map[string]interface{}) if ok { // convert the value to string and compare if fmt.Sprintf("%v", configValueMap["value"]) == v { logger.Warningf("the configuration setting %q already has the value %q", k, v) } } } if client.BestAPIVersion() < 6 { err = client.Set(c.applicationName, settings) } else { err = client.SetApplicationConfig(c.branchName, c.applicationName, settings) } return block.ProcessBlockedError(err, block.BlockChange) }
go
func (c *configCommand) setConfig(client applicationAPI, ctx *cmd.Context) error { if c.useFile { return c.setConfigFromFile(client, ctx) } settings, err := c.validateValues(ctx) if err != nil { return errors.Trace(err) } result, err := client.Get(c.branchName, c.applicationName) if err != nil { return err } for k, v := range settings { configValue := result.CharmConfig[k] configValueMap, ok := configValue.(map[string]interface{}) if ok { // convert the value to string and compare if fmt.Sprintf("%v", configValueMap["value"]) == v { logger.Warningf("the configuration setting %q already has the value %q", k, v) } } } if client.BestAPIVersion() < 6 { err = client.Set(c.applicationName, settings) } else { err = client.SetApplicationConfig(c.branchName, c.applicationName, settings) } return block.ProcessBlockedError(err, block.BlockChange) }
[ "func", "(", "c", "*", "configCommand", ")", "setConfig", "(", "client", "applicationAPI", ",", "ctx", "*", "cmd", ".", "Context", ")", "error", "{", "if", "c", ".", "useFile", "{", "return", "c", ".", "setConfigFromFile", "(", "client", ",", "ctx", ")...
// setConfig is the run action when we are setting new attribute values as args // or as a file passed in.
[ "setConfig", "is", "the", "run", "action", "when", "we", "are", "setting", "new", "attribute", "values", "as", "args", "or", "as", "a", "file", "passed", "in", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/config.go#L329-L362
154,772
juju/juju
cmd/juju/application/config.go
setConfigFromFile
func (c *configCommand) setConfigFromFile(client applicationAPI, ctx *cmd.Context) error { var ( b []byte err error ) if c.configFile.Path == "-" { buf := bytes.Buffer{} if _, err := buf.ReadFrom(ctx.Stdin); err != nil { return errors.Trace(err) } b = buf.Bytes() } else { b, err = c.configFile.Read(ctx) if err != nil { return errors.Trace(err) } } return errors.Trace(block.ProcessBlockedError( client.Update( params.ApplicationUpdate{ ApplicationName: c.applicationName, SettingsYAML: string(b), Generation: c.branchName, }, ), block.BlockChange)) }
go
func (c *configCommand) setConfigFromFile(client applicationAPI, ctx *cmd.Context) error { var ( b []byte err error ) if c.configFile.Path == "-" { buf := bytes.Buffer{} if _, err := buf.ReadFrom(ctx.Stdin); err != nil { return errors.Trace(err) } b = buf.Bytes() } else { b, err = c.configFile.Read(ctx) if err != nil { return errors.Trace(err) } } return errors.Trace(block.ProcessBlockedError( client.Update( params.ApplicationUpdate{ ApplicationName: c.applicationName, SettingsYAML: string(b), Generation: c.branchName, }, ), block.BlockChange)) }
[ "func", "(", "c", "*", "configCommand", ")", "setConfigFromFile", "(", "client", "applicationAPI", ",", "ctx", "*", "cmd", ".", "Context", ")", "error", "{", "var", "(", "b", "[", "]", "byte", "\n", "err", "error", "\n", ")", "\n", "if", "c", ".", ...
// setConfigFromFile sets the application configuration from settings passed // in a YAML file.
[ "setConfigFromFile", "sets", "the", "application", "configuration", "from", "settings", "passed", "in", "a", "YAML", "file", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/config.go#L366-L391
154,773
juju/juju
cmd/juju/application/config.go
getConfig
func (c *configCommand) getConfig(client applicationAPI, ctx *cmd.Context) error { results, err := client.Get(c.branchName, c.applicationName) if err != nil { return err } if len(c.keys) == 1 { logger.Infof("format %v is ignored", c.out.Name()) key := c.keys[0] info, found := results.CharmConfig[key].(map[string]interface{}) if !found && len(results.ApplicationConfig) > 0 { info, found = results.ApplicationConfig[key].(map[string]interface{}) } if !found { return errors.Errorf("key %q not found in %q application config or charm settings.", key, c.applicationName) } v, ok := info["value"] if !ok || v == nil { // Note that unlike the output with a non-nil and non-empty value below, this // output should never have a newline. return nil } // TODO (anastasiamac 2018-08-29) We want to have a new line after here (fmt.Fprintln). // However, it will break all existing scripts and should be done as part of Juju 3.x work. _, err := fmt.Fprint(ctx.Stdout, v) return errors.Trace(err) } resultsMap := map[string]interface{}{ "application": results.Application, "charm": results.Charm, "settings": results.CharmConfig, } if len(results.ApplicationConfig) > 0 { resultsMap["application-config"] = results.ApplicationConfig } err = c.out.Write(ctx, resultsMap) if featureflag.Enabled(feature.Generations) && err == nil { var gen string gen, err = c.ActiveBranch() if err == nil { _, err = ctx.Stdout.Write([]byte(fmt.Sprintf("\nchanges will be targeted to generation: %s\n", gen))) } } return errors.Trace(err) }
go
func (c *configCommand) getConfig(client applicationAPI, ctx *cmd.Context) error { results, err := client.Get(c.branchName, c.applicationName) if err != nil { return err } if len(c.keys) == 1 { logger.Infof("format %v is ignored", c.out.Name()) key := c.keys[0] info, found := results.CharmConfig[key].(map[string]interface{}) if !found && len(results.ApplicationConfig) > 0 { info, found = results.ApplicationConfig[key].(map[string]interface{}) } if !found { return errors.Errorf("key %q not found in %q application config or charm settings.", key, c.applicationName) } v, ok := info["value"] if !ok || v == nil { // Note that unlike the output with a non-nil and non-empty value below, this // output should never have a newline. return nil } // TODO (anastasiamac 2018-08-29) We want to have a new line after here (fmt.Fprintln). // However, it will break all existing scripts and should be done as part of Juju 3.x work. _, err := fmt.Fprint(ctx.Stdout, v) return errors.Trace(err) } resultsMap := map[string]interface{}{ "application": results.Application, "charm": results.Charm, "settings": results.CharmConfig, } if len(results.ApplicationConfig) > 0 { resultsMap["application-config"] = results.ApplicationConfig } err = c.out.Write(ctx, resultsMap) if featureflag.Enabled(feature.Generations) && err == nil { var gen string gen, err = c.ActiveBranch() if err == nil { _, err = ctx.Stdout.Write([]byte(fmt.Sprintf("\nchanges will be targeted to generation: %s\n", gen))) } } return errors.Trace(err) }
[ "func", "(", "c", "*", "configCommand", ")", "getConfig", "(", "client", "applicationAPI", ",", "ctx", "*", "cmd", ".", "Context", ")", "error", "{", "results", ",", "err", ":=", "client", ".", "Get", "(", "c", ".", "branchName", ",", "c", ".", "appl...
// getConfig is the run action to return one or all configuration values.
[ "getConfig", "is", "the", "run", "action", "to", "return", "one", "or", "all", "configuration", "values", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/config.go#L394-L440
154,774
juju/juju
cmd/juju/application/config.go
validateValues
func (c *configCommand) validateValues(ctx *cmd.Context) (map[string]string, error) { settings := map[string]string{} for k, v := range c.values { //empty string is also valid as a setting value if v == "" { settings[k] = v continue } if v[0] != '@' { if !utf8.ValidString(v) { return nil, errors.Errorf("value for option %q contains non-UTF-8 sequences", k) } settings[k] = v continue } nv, err := readValue(ctx, v[1:]) if err != nil { return nil, errors.Trace(err) } if !utf8.ValidString(nv) { return nil, errors.Errorf("value for option %q contains non-UTF-8 sequences", k) } settings[k] = nv } return settings, nil }
go
func (c *configCommand) validateValues(ctx *cmd.Context) (map[string]string, error) { settings := map[string]string{} for k, v := range c.values { //empty string is also valid as a setting value if v == "" { settings[k] = v continue } if v[0] != '@' { if !utf8.ValidString(v) { return nil, errors.Errorf("value for option %q contains non-UTF-8 sequences", k) } settings[k] = v continue } nv, err := readValue(ctx, v[1:]) if err != nil { return nil, errors.Trace(err) } if !utf8.ValidString(nv) { return nil, errors.Errorf("value for option %q contains non-UTF-8 sequences", k) } settings[k] = nv } return settings, nil }
[ "func", "(", "c", "*", "configCommand", ")", "validateValues", "(", "ctx", "*", "cmd", ".", "Context", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "settings", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "fo...
// validateValues reads the values provided as args and validates that they are // valid UTF-8.
[ "validateValues", "reads", "the", "values", "provided", "as", "args", "and", "validates", "that", "they", "are", "valid", "UTF", "-", "8", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/config.go#L444-L470
154,775
juju/juju
cmd/juju/application/config.go
readValue
func readValue(ctx *cmd.Context, filename string) (string, error) { absFilename := ctx.AbsPath(filename) fi, err := os.Stat(absFilename) if err != nil { return "", errors.Errorf("cannot read option from file %q: %v", filename, err) } if fi.Size() > maxValueSize { return "", errors.Errorf("size of option file is larger than 5M") } content, err := ioutil.ReadFile(ctx.AbsPath(filename)) if err != nil { return "", errors.Errorf("cannot read option from file %q: %v", filename, err) } return string(content), nil }
go
func readValue(ctx *cmd.Context, filename string) (string, error) { absFilename := ctx.AbsPath(filename) fi, err := os.Stat(absFilename) if err != nil { return "", errors.Errorf("cannot read option from file %q: %v", filename, err) } if fi.Size() > maxValueSize { return "", errors.Errorf("size of option file is larger than 5M") } content, err := ioutil.ReadFile(ctx.AbsPath(filename)) if err != nil { return "", errors.Errorf("cannot read option from file %q: %v", filename, err) } return string(content), nil }
[ "func", "readValue", "(", "ctx", "*", "cmd", ".", "Context", ",", "filename", "string", ")", "(", "string", ",", "error", ")", "{", "absFilename", ":=", "ctx", ".", "AbsPath", "(", "filename", ")", "\n", "fi", ",", "err", ":=", "os", ".", "Stat", "...
// readValue reads the value of an option out of the named file. // An empty content is valid, like in parsing the options. The upper // size is 5M.
[ "readValue", "reads", "the", "value", "of", "an", "option", "out", "of", "the", "named", "file", ".", "An", "empty", "content", "is", "valid", "like", "in", "parsing", "the", "options", ".", "The", "upper", "size", "is", "5M", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/config.go#L475-L489
154,776
juju/juju
mongo/mongometrics/dialmetrics.go
NewDialCollector
func NewDialCollector() *DialCollector { return &DialCollector{ dialsTotal: prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: "juju", Name: "mongo_dials_total", Help: "Total number of MongoDB server dials.", }, dialLabels), dialDuration: prometheus.NewSummaryVec(prometheus.SummaryOpts{ Namespace: "juju", Name: "mongo_dial_duration_seconds", Help: "Time taken dialng MongoDB server.", }, dialLabels), } }
go
func NewDialCollector() *DialCollector { return &DialCollector{ dialsTotal: prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: "juju", Name: "mongo_dials_total", Help: "Total number of MongoDB server dials.", }, dialLabels), dialDuration: prometheus.NewSummaryVec(prometheus.SummaryOpts{ Namespace: "juju", Name: "mongo_dial_duration_seconds", Help: "Time taken dialng MongoDB server.", }, dialLabels), } }
[ "func", "NewDialCollector", "(", ")", "*", "DialCollector", "{", "return", "&", "DialCollector", "{", "dialsTotal", ":", "prometheus", ".", "NewCounterVec", "(", "prometheus", ".", "CounterOpts", "{", "Namespace", ":", "\"", "\"", ",", "Name", ":", "\"", "\"...
// NewDialCollector returns a new DialCollector.
[ "NewDialCollector", "returns", "a", "new", "DialCollector", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/mongometrics/dialmetrics.go#L28-L42
154,777
juju/juju
mongo/mongometrics/dialmetrics.go
PostDialServer
func (c *DialCollector) PostDialServer(server string, duration time.Duration, dialErr error) { var failedValue, timeoutValue string if dialErr != nil { // TODO(axw) attempt to distinguish more types of // errors, e.g. failure due to TLS handshake vs. net // dial. failedValue = "failed" if err, ok := dialErr.(*net.OpError); ok { failedValue = err.Op } if err, ok := dialErr.(net.Error); ok { if err.Timeout() { timeoutValue = "timed out" } } } labels := prometheus.Labels{ serverLabel: server, failedLabel: failedValue, timeoutLabel: timeoutValue, } c.dialsTotal.With(labels).Inc() c.dialDuration.With(labels).Observe(duration.Seconds()) }
go
func (c *DialCollector) PostDialServer(server string, duration time.Duration, dialErr error) { var failedValue, timeoutValue string if dialErr != nil { // TODO(axw) attempt to distinguish more types of // errors, e.g. failure due to TLS handshake vs. net // dial. failedValue = "failed" if err, ok := dialErr.(*net.OpError); ok { failedValue = err.Op } if err, ok := dialErr.(net.Error); ok { if err.Timeout() { timeoutValue = "timed out" } } } labels := prometheus.Labels{ serverLabel: server, failedLabel: failedValue, timeoutLabel: timeoutValue, } c.dialsTotal.With(labels).Inc() c.dialDuration.With(labels).Observe(duration.Seconds()) }
[ "func", "(", "c", "*", "DialCollector", ")", "PostDialServer", "(", "server", "string", ",", "duration", "time", ".", "Duration", ",", "dialErr", "error", ")", "{", "var", "failedValue", ",", "timeoutValue", "string", "\n", "if", "dialErr", "!=", "nil", "{...
// PostDialServer is a function that may be used in // mongo.DialOpts.PostDialServer, to update metrics.
[ "PostDialServer", "is", "a", "function", "that", "may", "be", "used", "in", "mongo", ".", "DialOpts", ".", "PostDialServer", "to", "update", "metrics", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/mongometrics/dialmetrics.go#L58-L81
154,778
juju/juju
worker/logsender/worker.go
New
func New(logs LogRecordCh, logSenderAPI *logsender.API) worker.Worker { loop := func(stop <-chan struct{}) error { // It has been observed that sometimes the logsender.API gets wedged // attempting to get the LogWriter while the agent is being torn down, // and the call to logSenderAPI.LogWriter() doesn't return. This stops // the logsender worker from shutting down, and causes the entire // agent to get wedged. To mitigate this, we get the LogWriter in a // different goroutine allowing the worker to interrupt this. sender := make(chan logsender.LogWriter) errChan := make(chan error) go func() { logWriter, err := logSenderAPI.LogWriter() if err != nil { select { case errChan <- err: case <-stop: } return } select { case sender <- logWriter: case <-stop: logWriter.Close() } return }() var logWriter logsender.LogWriter var err error select { case logWriter = <-sender: case err = <-errChan: return errors.Annotate(err, "logsender dial failed") case <-stop: return nil } defer logWriter.Close() for { select { case rec := <-logs: err := logWriter.WriteLog(&params.LogRecord{ Time: rec.Time, Module: rec.Module, Location: rec.Location, Level: rec.Level.String(), Message: rec.Message, }) if err != nil { return errors.Trace(err) } if rec.DroppedAfter > 0 { // If messages were dropped after this one, report // the count (the source of the log messages - // BufferedLogWriter - handles the actual dropping // and counting). // // Any logs indicated as dropped here are will // never end up in the logs DB in the JES // (although will still be in the local agent log // file). Message dropping by the // BufferedLogWriter is last resort protection // against memory exhaustion and should only // happen if API connectivity is lost for extended // periods. The maximum in-memory log buffer is // quite large (see the InstallBufferedLogWriter // call in jujuDMain). err := logWriter.WriteLog(&params.LogRecord{ Time: rec.Time, Module: loggerName, Level: loggo.WARNING.String(), Message: fmt.Sprintf("%d log messages dropped due to lack of API connectivity", rec.DroppedAfter), }) if err != nil { return errors.Trace(err) } } case <-stop: return nil } } } return jworker.NewSimpleWorker(loop) }
go
func New(logs LogRecordCh, logSenderAPI *logsender.API) worker.Worker { loop := func(stop <-chan struct{}) error { // It has been observed that sometimes the logsender.API gets wedged // attempting to get the LogWriter while the agent is being torn down, // and the call to logSenderAPI.LogWriter() doesn't return. This stops // the logsender worker from shutting down, and causes the entire // agent to get wedged. To mitigate this, we get the LogWriter in a // different goroutine allowing the worker to interrupt this. sender := make(chan logsender.LogWriter) errChan := make(chan error) go func() { logWriter, err := logSenderAPI.LogWriter() if err != nil { select { case errChan <- err: case <-stop: } return } select { case sender <- logWriter: case <-stop: logWriter.Close() } return }() var logWriter logsender.LogWriter var err error select { case logWriter = <-sender: case err = <-errChan: return errors.Annotate(err, "logsender dial failed") case <-stop: return nil } defer logWriter.Close() for { select { case rec := <-logs: err := logWriter.WriteLog(&params.LogRecord{ Time: rec.Time, Module: rec.Module, Location: rec.Location, Level: rec.Level.String(), Message: rec.Message, }) if err != nil { return errors.Trace(err) } if rec.DroppedAfter > 0 { // If messages were dropped after this one, report // the count (the source of the log messages - // BufferedLogWriter - handles the actual dropping // and counting). // // Any logs indicated as dropped here are will // never end up in the logs DB in the JES // (although will still be in the local agent log // file). Message dropping by the // BufferedLogWriter is last resort protection // against memory exhaustion and should only // happen if API connectivity is lost for extended // periods. The maximum in-memory log buffer is // quite large (see the InstallBufferedLogWriter // call in jujuDMain). err := logWriter.WriteLog(&params.LogRecord{ Time: rec.Time, Module: loggerName, Level: loggo.WARNING.String(), Message: fmt.Sprintf("%d log messages dropped due to lack of API connectivity", rec.DroppedAfter), }) if err != nil { return errors.Trace(err) } } case <-stop: return nil } } } return jworker.NewSimpleWorker(loop) }
[ "func", "New", "(", "logs", "LogRecordCh", ",", "logSenderAPI", "*", "logsender", ".", "API", ")", "worker", ".", "Worker", "{", "loop", ":=", "func", "(", "stop", "<-", "chan", "struct", "{", "}", ")", "error", "{", "// It has been observed that sometimes t...
// New starts a logsender worker which reads log message structs from // a channel and sends them to the JES via the logsink API.
[ "New", "starts", "a", "logsender", "worker", "which", "reads", "log", "message", "structs", "from", "a", "channel", "and", "sends", "them", "to", "the", "JES", "via", "the", "logsink", "API", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/logsender/worker.go#L22-L104
154,779
juju/juju
state/block.go
ToParams
func (t BlockType) ToParams() multiwatcher.BlockType { if jujuBlock, ok := typeNames[t]; ok { return jujuBlock } panic(fmt.Sprintf("unknown block type %d", int(t))) }
go
func (t BlockType) ToParams() multiwatcher.BlockType { if jujuBlock, ok := typeNames[t]; ok { return jujuBlock } panic(fmt.Sprintf("unknown block type %d", int(t))) }
[ "func", "(", "t", "BlockType", ")", "ToParams", "(", ")", "multiwatcher", ".", "BlockType", "{", "if", "jujuBlock", ",", "ok", ":=", "typeNames", "[", "t", "]", ";", "ok", "{", "return", "jujuBlock", "\n", "}", "\n", "panic", "(", "fmt", ".", "Sprint...
// ToParams returns the type as multiwatcher.BlockType.
[ "ToParams", "returns", "the", "type", "as", "multiwatcher", ".", "BlockType", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/block.go#L78-L83
154,780
juju/juju
state/block.go
MigrationValue
func (t BlockType) MigrationValue() string { if value, ok := blockMigrationValue[t]; ok { return value } return "unknown" }
go
func (t BlockType) MigrationValue() string { if value, ok := blockMigrationValue[t]; ok { return value } return "unknown" }
[ "func", "(", "t", "BlockType", ")", "MigrationValue", "(", ")", "string", "{", "if", "value", ",", "ok", ":=", "blockMigrationValue", "[", "t", "]", ";", "ok", "{", "return", "value", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// MigrationValue converts the block type value into a useful human readable // string for model migration.
[ "MigrationValue", "converts", "the", "block", "type", "value", "into", "a", "useful", "human", "readable", "string", "for", "model", "migration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/block.go#L92-L97
154,781
juju/juju
state/block.go
ParseBlockType
func ParseBlockType(str string) BlockType { for _, one := range AllTypes() { if one.String() == str { return one } } panic(fmt.Sprintf("unknown block type %v", str)) }
go
func ParseBlockType(str string) BlockType { for _, one := range AllTypes() { if one.String() == str { return one } } panic(fmt.Sprintf("unknown block type %v", str)) }
[ "func", "ParseBlockType", "(", "str", "string", ")", "BlockType", "{", "for", "_", ",", "one", ":=", "range", "AllTypes", "(", ")", "{", "if", "one", ".", "String", "(", ")", "==", "str", "{", "return", "one", "\n", "}", "\n", "}", "\n", "panic", ...
// ParseBlockType returns BlockType from humanly readable type representation.
[ "ParseBlockType", "returns", "BlockType", "from", "humanly", "readable", "type", "representation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/block.go#L100-L107
154,782
juju/juju
state/block.go
Tag
func (b *block) Tag() (names.Tag, error) { tag, err := names.ParseTag(b.doc.Tag) if err != nil { return nil, errors.Annotatef(err, "getting block information") } return tag, nil }
go
func (b *block) Tag() (names.Tag, error) { tag, err := names.ParseTag(b.doc.Tag) if err != nil { return nil, errors.Annotatef(err, "getting block information") } return tag, nil }
[ "func", "(", "b", "*", "block", ")", "Tag", "(", ")", "(", "names", ".", "Tag", ",", "error", ")", "{", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "b", ".", "doc", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", ...
// Tag is part of the state.Block interface.
[ "Tag", "is", "part", "of", "the", "state", ".", "Block", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/block.go#L147-L153
154,783
juju/juju
state/block.go
SwitchBlockOn
func (st *State) SwitchBlockOn(t BlockType, msg string) error { return setModelBlock(st, t, msg) }
go
func (st *State) SwitchBlockOn(t BlockType, msg string) error { return setModelBlock(st, t, msg) }
[ "func", "(", "st", "*", "State", ")", "SwitchBlockOn", "(", "t", "BlockType", ",", "msg", "string", ")", "error", "{", "return", "setModelBlock", "(", "st", ",", "t", ",", "msg", ")", "\n", "}" ]
// SwitchBlockOn enables block of specified type for the // current model.
[ "SwitchBlockOn", "enables", "block", "of", "specified", "type", "for", "the", "current", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/block.go#L162-L164
154,784
juju/juju
state/block.go
GetBlockForType
func (st *State) GetBlockForType(t BlockType) (Block, bool, error) { return getBlockForType(st, t) }
go
func (st *State) GetBlockForType(t BlockType) (Block, bool, error) { return getBlockForType(st, t) }
[ "func", "(", "st", "*", "State", ")", "GetBlockForType", "(", "t", "BlockType", ")", "(", "Block", ",", "bool", ",", "error", ")", "{", "return", "getBlockForType", "(", "st", ",", "t", ")", "\n", "}" ]
// GetBlockForType returns the Block of the specified type for the current model // where // not found -> nil, false, nil // found -> block, true, nil // error -> nil, false, err
[ "GetBlockForType", "returns", "the", "Block", "of", "the", "specified", "type", "for", "the", "current", "model", "where", "not", "found", "-", ">", "nil", "false", "nil", "found", "-", ">", "block", "true", "nil", "error", "-", ">", "nil", "false", "err...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/block.go#L177-L179
154,785
juju/juju
state/block.go
AllBlocks
func (st *State) AllBlocks() ([]Block, error) { blocksCollection, closer := st.db().GetCollection(blocksC) defer closer() var bdocs []blockDoc err := blocksCollection.Find(nil).All(&bdocs) if err != nil { return nil, errors.Annotatef(err, "cannot get all blocks") } blocks := make([]Block, len(bdocs)) for i, doc := range bdocs { blocks[i] = &block{doc} } return blocks, nil }
go
func (st *State) AllBlocks() ([]Block, error) { blocksCollection, closer := st.db().GetCollection(blocksC) defer closer() var bdocs []blockDoc err := blocksCollection.Find(nil).All(&bdocs) if err != nil { return nil, errors.Annotatef(err, "cannot get all blocks") } blocks := make([]Block, len(bdocs)) for i, doc := range bdocs { blocks[i] = &block{doc} } return blocks, nil }
[ "func", "(", "st", "*", "State", ")", "AllBlocks", "(", ")", "(", "[", "]", "Block", ",", "error", ")", "{", "blocksCollection", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "blocksC", ")", "\n", "defer", "closer", "("...
// AllBlocks returns all blocks in the model.
[ "AllBlocks", "returns", "all", "blocks", "in", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/block.go#L199-L213
154,786
juju/juju
state/block.go
AllBlocksForController
func (st *State) AllBlocksForController() ([]Block, error) { blocksCollection, closer := st.db().GetRawCollection(blocksC) defer closer() var bdocs []blockDoc err := blocksCollection.Find(nil).All(&bdocs) if err != nil { return nil, errors.Annotate(err, "cannot get all blocks") } blocks := make([]Block, len(bdocs)) for i, doc := range bdocs { blocks[i] = &block{doc} } return blocks, nil }
go
func (st *State) AllBlocksForController() ([]Block, error) { blocksCollection, closer := st.db().GetRawCollection(blocksC) defer closer() var bdocs []blockDoc err := blocksCollection.Find(nil).All(&bdocs) if err != nil { return nil, errors.Annotate(err, "cannot get all blocks") } blocks := make([]Block, len(bdocs)) for i, doc := range bdocs { blocks[i] = &block{doc} } return blocks, nil }
[ "func", "(", "st", "*", "State", ")", "AllBlocksForController", "(", ")", "(", "[", "]", "Block", ",", "error", ")", "{", "blocksCollection", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetRawCollection", "(", "blocksC", ")", "\n", "defer", ...
// AllBlocksForController returns all blocks in any models on // the controller.
[ "AllBlocksForController", "returns", "all", "blocks", "in", "any", "models", "on", "the", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/block.go#L217-L232
154,787
juju/juju
state/block.go
setModelBlock
func setModelBlock(mb modelBackend, t BlockType, msg string) error { buildTxn := func(attempt int) ([]txn.Op, error) { block, exists, err := getBlockForType(mb, t) if err != nil { return nil, errors.Trace(err) } // Cannot create blocks of the same type more than once per model. // Cannot update current blocks. if exists { return block.updateMessageOp(msg) } return createModelBlockOps(mb, t, msg) } return mb.db().Run(buildTxn) }
go
func setModelBlock(mb modelBackend, t BlockType, msg string) error { buildTxn := func(attempt int) ([]txn.Op, error) { block, exists, err := getBlockForType(mb, t) if err != nil { return nil, errors.Trace(err) } // Cannot create blocks of the same type more than once per model. // Cannot update current blocks. if exists { return block.updateMessageOp(msg) } return createModelBlockOps(mb, t, msg) } return mb.db().Run(buildTxn) }
[ "func", "setModelBlock", "(", "mb", "modelBackend", ",", "t", "BlockType", ",", "msg", "string", ")", "error", "{", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "block", ",", "exists",...
// setModelBlock updates the blocks collection with the // specified block. // Only one instance of each block type can exist in model.
[ "setModelBlock", "updates", "the", "blocks", "collection", "with", "the", "specified", "block", ".", "Only", "one", "instance", "of", "each", "block", "type", "can", "exist", "in", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/block.go#L260-L274
154,788
juju/juju
state/block.go
newBlockId
func newBlockId(mb modelBackend) (string, error) { seq, err := sequence(mb, "block") if err != nil { return "", errors.Trace(err) } return fmt.Sprint(seq), nil }
go
func newBlockId(mb modelBackend) (string, error) { seq, err := sequence(mb, "block") if err != nil { return "", errors.Trace(err) } return fmt.Sprint(seq), nil }
[ "func", "newBlockId", "(", "mb", "modelBackend", ")", "(", "string", ",", "error", ")", "{", "seq", ",", "err", ":=", "sequence", "(", "mb", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Tra...
// newBlockId returns a sequential block id for this model.
[ "newBlockId", "returns", "a", "sequential", "block", "id", "for", "this", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/block.go#L277-L283
154,789
juju/juju
state/bakerystorage/storage.go
MongoIndexes
func MongoIndexes() []mgo.Index { // Note: this second-guesses the underlying document format // used by bakery's mgostorage package. // TODO change things so that we can use EnsureIndex instead. return []mgo.Index{{ Key: []string{"-created"}, }, { Key: []string{"expires"}, ExpireAfter: time.Second, }} }
go
func MongoIndexes() []mgo.Index { // Note: this second-guesses the underlying document format // used by bakery's mgostorage package. // TODO change things so that we can use EnsureIndex instead. return []mgo.Index{{ Key: []string{"-created"}, }, { Key: []string{"expires"}, ExpireAfter: time.Second, }} }
[ "func", "MongoIndexes", "(", ")", "[", "]", "mgo", ".", "Index", "{", "// Note: this second-guesses the underlying document format", "// used by bakery's mgostorage package.", "// TODO change things so that we can use EnsureIndex instead.", "return", "[", "]", "mgo", ".", "Index"...
// MongoIndexes returns the indexes to apply to the MongoDB collection.
[ "MongoIndexes", "returns", "the", "indexes", "to", "apply", "to", "the", "MongoDB", "collection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/bakerystorage/storage.go#L17-L27
154,790
juju/juju
state/bakerystorage/storage.go
ExpireAfter
func (s *storage) ExpireAfter(expireAfter time.Duration) ExpirableStorage { newStorage := *s newStorage.expireAfter = expireAfter return &newStorage }
go
func (s *storage) ExpireAfter(expireAfter time.Duration) ExpirableStorage { newStorage := *s newStorage.expireAfter = expireAfter return &newStorage }
[ "func", "(", "s", "*", "storage", ")", "ExpireAfter", "(", "expireAfter", "time", ".", "Duration", ")", "ExpirableStorage", "{", "newStorage", ":=", "*", "s", "\n", "newStorage", ".", "expireAfter", "=", "expireAfter", "\n", "return", "&", "newStorage", "\n"...
// ExpireAfter implements ExpirableStorage.ExpireAfter.
[ "ExpireAfter", "implements", "ExpirableStorage", ".", "ExpireAfter", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/bakerystorage/storage.go#L46-L50
154,791
juju/juju
state/bakerystorage/storage.go
RootKey
func (s *storage) RootKey() ([]byte, []byte, error) { storage, closer := s.getStorage() defer closer() return storage.RootKey() }
go
func (s *storage) RootKey() ([]byte, []byte, error) { storage, closer := s.getStorage() defer closer() return storage.RootKey() }
[ "func", "(", "s", "*", "storage", ")", "RootKey", "(", ")", "(", "[", "]", "byte", ",", "[", "]", "byte", ",", "error", ")", "{", "storage", ",", "closer", ":=", "s", ".", "getStorage", "(", ")", "\n", "defer", "closer", "(", ")", "\n", "return...
// RootKey implements Storage.RootKey
[ "RootKey", "implements", "Storage", ".", "RootKey" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/bakerystorage/storage.go#L53-L57
154,792
juju/juju
state/bakerystorage/storage.go
legacyGet
func (s *storage) legacyGet(location []byte) ([]byte, error) { coll, closer := s.config.GetCollection() defer closer() var i storageDoc err := coll.FindId(string(location)).One(&i) if err != nil { if err == mgo.ErrNotFound { return nil, bakery.ErrNotFound } return nil, errors.Annotatef(err, "cannot get item for location %q", location) } var rootKey legacyRootKey err = json.Unmarshal([]byte(i.Item), &rootKey) if err != nil { return nil, errors.Annotate(err, "was unable to unmarshal found rootkey") } return rootKey.RootKey, nil }
go
func (s *storage) legacyGet(location []byte) ([]byte, error) { coll, closer := s.config.GetCollection() defer closer() var i storageDoc err := coll.FindId(string(location)).One(&i) if err != nil { if err == mgo.ErrNotFound { return nil, bakery.ErrNotFound } return nil, errors.Annotatef(err, "cannot get item for location %q", location) } var rootKey legacyRootKey err = json.Unmarshal([]byte(i.Item), &rootKey) if err != nil { return nil, errors.Annotate(err, "was unable to unmarshal found rootkey") } return rootKey.RootKey, nil }
[ "func", "(", "s", "*", "storage", ")", "legacyGet", "(", "location", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "coll", ",", "closer", ":=", "s", ".", "config", ".", "GetCollection", "(", ")", "\n", "defer", "closer", "...
// legacyGet is attempted as the id we're looking for was created in a previous // version of Juju while using v1 versions of the macaroon-bakery.
[ "legacyGet", "is", "attempted", "as", "the", "id", "we", "re", "looking", "for", "was", "created", "in", "a", "previous", "version", "of", "Juju", "while", "using", "v1", "versions", "of", "the", "macaroon", "-", "bakery", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/bakerystorage/storage.go#L80-L98
154,793
juju/juju
network/debinterfaces/format.go
FlattenStanzas
func FlattenStanzas(stanzas []Stanza) []Stanza { result := make([]Stanza, 0) for _, s := range stanzas { switch v := s.(type) { case SourceStanza: result = append(result, v.Stanzas...) case SourceDirectoryStanza: result = append(result, v.Stanzas...) default: result = append(result, v) } } return result }
go
func FlattenStanzas(stanzas []Stanza) []Stanza { result := make([]Stanza, 0) for _, s := range stanzas { switch v := s.(type) { case SourceStanza: result = append(result, v.Stanzas...) case SourceDirectoryStanza: result = append(result, v.Stanzas...) default: result = append(result, v) } } return result }
[ "func", "FlattenStanzas", "(", "stanzas", "[", "]", "Stanza", ")", "[", "]", "Stanza", "{", "result", ":=", "make", "(", "[", "]", "Stanza", ",", "0", ")", "\n\n", "for", "_", ",", "s", ":=", "range", "stanzas", "{", "switch", "v", ":=", "s", "."...
// FlattenStanzas flattens all stanzas, and recursively for all // 'source' and 'source-directory' stanzas, returning a single slice.
[ "FlattenStanzas", "flattens", "all", "stanzas", "and", "recursively", "for", "all", "source", "and", "source", "-", "directory", "stanzas", "returning", "a", "single", "slice", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/debinterfaces/format.go#L13-L28
154,794
juju/juju
network/debinterfaces/format.go
FormatStanzas
func FormatStanzas(stanzas []Stanza, count int) string { var buffer bytes.Buffer for i, s := range stanzas { buffer.WriteString(FormatDefinition(s.Definition(), count)) buffer.WriteString("\n") // If the current stanza is 'auto' and the next one is // 'iface' then don't add an additional blank line // between them. if _, ok := stanzas[i].(AutoStanza); ok { if i+1 < len(stanzas) { if _, ok := stanzas[i+1].(IfaceStanza); !ok { buffer.WriteString("\n") } } } else if i+1 < len(stanzas) { buffer.WriteString("\n") } } return strings.TrimSuffix(buffer.String(), "\n") }
go
func FormatStanzas(stanzas []Stanza, count int) string { var buffer bytes.Buffer for i, s := range stanzas { buffer.WriteString(FormatDefinition(s.Definition(), count)) buffer.WriteString("\n") // If the current stanza is 'auto' and the next one is // 'iface' then don't add an additional blank line // between them. if _, ok := stanzas[i].(AutoStanza); ok { if i+1 < len(stanzas) { if _, ok := stanzas[i+1].(IfaceStanza); !ok { buffer.WriteString("\n") } } } else if i+1 < len(stanzas) { buffer.WriteString("\n") } } return strings.TrimSuffix(buffer.String(), "\n") }
[ "func", "FormatStanzas", "(", "stanzas", "[", "]", "Stanza", ",", "count", "int", ")", "string", "{", "var", "buffer", "bytes", ".", "Buffer", "\n\n", "for", "i", ",", "s", ":=", "range", "stanzas", "{", "buffer", ".", "WriteString", "(", "FormatDefiniti...
// FormatStanzas returns a string representing all stanzas // definitions, recursively expanding stanzas found in both source and // source-directory definitions.
[ "FormatStanzas", "returns", "a", "string", "representing", "all", "stanzas", "definitions", "recursively", "expanding", "stanzas", "found", "in", "both", "source", "and", "source", "-", "directory", "definitions", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/debinterfaces/format.go#L33-L54
154,795
juju/juju
network/debinterfaces/format.go
FormatDefinition
func FormatDefinition(definition []string, count int) string { var buffer bytes.Buffer spacer := strings.Repeat(" ", count) for i, d := range definition { if i == 0 { buffer.WriteString(d) buffer.WriteString("\n") } else { buffer.WriteString(spacer) buffer.WriteString(d) buffer.WriteString("\n") } } return strings.TrimSuffix(buffer.String(), "\n") }
go
func FormatDefinition(definition []string, count int) string { var buffer bytes.Buffer spacer := strings.Repeat(" ", count) for i, d := range definition { if i == 0 { buffer.WriteString(d) buffer.WriteString("\n") } else { buffer.WriteString(spacer) buffer.WriteString(d) buffer.WriteString("\n") } } return strings.TrimSuffix(buffer.String(), "\n") }
[ "func", "FormatDefinition", "(", "definition", "[", "]", "string", ",", "count", "int", ")", "string", "{", "var", "buffer", "bytes", ".", "Buffer", "\n\n", "spacer", ":=", "strings", ".", "Repeat", "(", "\"", "\"", ",", "count", ")", "\n\n", "for", "i...
// FormatDefinition formats the complete stanza, indenting any options // with count leading spaces.
[ "FormatDefinition", "formats", "the", "complete", "stanza", "indenting", "any", "options", "with", "count", "leading", "spaces", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/debinterfaces/format.go#L58-L75
154,796
juju/juju
core/lxdprofile/validate.go
ValidateLXDProfile
func ValidateLXDProfile(profiler LXDProfiler) error { // if profiler is nil, there is no available profiler to call LXDProfile // then return out early if profiler == nil { return nil } // Profile from the api could be nil, so check that it isn't if profile := profiler.LXDProfile(); profile != nil { err := profile.ValidateConfigDevices() return errors.Trace(err) } return nil }
go
func ValidateLXDProfile(profiler LXDProfiler) error { // if profiler is nil, there is no available profiler to call LXDProfile // then return out early if profiler == nil { return nil } // Profile from the api could be nil, so check that it isn't if profile := profiler.LXDProfile(); profile != nil { err := profile.ValidateConfigDevices() return errors.Trace(err) } return nil }
[ "func", "ValidateLXDProfile", "(", "profiler", "LXDProfiler", ")", "error", "{", "// if profiler is nil, there is no available profiler to call LXDProfile", "// then return out early", "if", "profiler", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "// Profile from the ...
// ValidateLXDProfile will validate the profile to determin if the configuration // is valid or not before passing continuing on.
[ "ValidateLXDProfile", "will", "validate", "the", "profile", "to", "determin", "if", "the", "configuration", "is", "valid", "or", "not", "before", "passing", "continuing", "on", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/lxdprofile/validate.go#L43-L55
154,797
juju/juju
core/lxdprofile/validate.go
NotEmpty
func NotEmpty(profiler LXDProfiler) bool { if profile := profiler.LXDProfile(); profile != nil { return !profile.Empty() } return false }
go
func NotEmpty(profiler LXDProfiler) bool { if profile := profiler.LXDProfile(); profile != nil { return !profile.Empty() } return false }
[ "func", "NotEmpty", "(", "profiler", "LXDProfiler", ")", "bool", "{", "if", "profile", ":=", "profiler", ".", "LXDProfile", "(", ")", ";", "profile", "!=", "nil", "{", "return", "!", "profile", ".", "Empty", "(", ")", "\n", "}", "\n", "return", "false"...
// NotEmpty will return false if the profiler containers a profile, that is // empty. If the profile is empty, we'll return false. // If there is no valid profile in the profiler, it will return false
[ "NotEmpty", "will", "return", "false", "if", "the", "profiler", "containers", "a", "profile", "that", "is", "empty", ".", "If", "the", "profile", "is", "empty", "we", "ll", "return", "false", ".", "If", "there", "is", "no", "valid", "profile", "in", "the...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/lxdprofile/validate.go#L60-L65
154,798
juju/juju
payload/context/register.go
NewRegisterCmd
func NewRegisterCmd(ctx HookContext) (*RegisterCmd, error) { return &RegisterCmd{hookContextFunc: componentHookContext(ctx)}, nil }
go
func NewRegisterCmd(ctx HookContext) (*RegisterCmd, error) { return &RegisterCmd{hookContextFunc: componentHookContext(ctx)}, nil }
[ "func", "NewRegisterCmd", "(", "ctx", "HookContext", ")", "(", "*", "RegisterCmd", ",", "error", ")", "{", "return", "&", "RegisterCmd", "{", "hookContextFunc", ":", "componentHookContext", "(", "ctx", ")", "}", ",", "nil", "\n", "}" ]
// NewRegisterCmd returns a new RegisterCmd that wraps the given context.
[ "NewRegisterCmd", "returns", "a", "new", "RegisterCmd", "that", "wraps", "the", "given", "context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/context/register.go#L19-L21
154,799
juju/juju
apiserver/facades/client/machinemanager/machinemanager.go
NewFacade
func NewFacade(ctx facade.Context) (*MachineManagerAPI, error) { st := ctx.State() model, err := st.Model() if err != nil { return nil, errors.Trace(err) } backend := &stateShim{State: st} storageAccess, err := getStorageState(st) if err != nil { return nil, errors.Trace(err) } pool := &poolShim{ctx.StatePool()} return NewMachineManagerAPI(backend, storageAccess, pool, ctx.Auth(), model.ModelTag(), state.CallContext(st), ctx.Resources()) }
go
func NewFacade(ctx facade.Context) (*MachineManagerAPI, error) { st := ctx.State() model, err := st.Model() if err != nil { return nil, errors.Trace(err) } backend := &stateShim{State: st} storageAccess, err := getStorageState(st) if err != nil { return nil, errors.Trace(err) } pool := &poolShim{ctx.StatePool()} return NewMachineManagerAPI(backend, storageAccess, pool, ctx.Auth(), model.ModelTag(), state.CallContext(st), ctx.Resources()) }
[ "func", "NewFacade", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "MachineManagerAPI", ",", "error", ")", "{", "st", ":=", "ctx", ".", "State", "(", ")", "\n", "model", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!...
// NewFacade create a new server-side MachineManager API facade. This // is used for facade registration.
[ "NewFacade", "create", "a", "new", "server", "-", "side", "MachineManager", "API", "facade", ".", "This", "is", "used", "for", "facade", "registration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/machinemanager/machinemanager.go#L45-L58