id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
156,800
juju/juju
environs/sync/sync.go
selectSourceDatasource
func selectSourceDatasource(syncContext *SyncContext) (simplestreams.DataSource, error) { source := syncContext.Source if source == "" { source = envtools.DefaultBaseURL } sourceURL, err := envtools.ToolsURL(source) if err != nil { return nil, err } logger.Infof("source for sync of agent binaries: %v", sourceURL) return simplestreams.NewURLSignedDataSource("sync agent binaries source", sourceURL, keys.JujuPublicKey, utils.VerifySSLHostnames, simplestreams.CUSTOM_CLOUD_DATA, false), nil }
go
func selectSourceDatasource(syncContext *SyncContext) (simplestreams.DataSource, error) { source := syncContext.Source if source == "" { source = envtools.DefaultBaseURL } sourceURL, err := envtools.ToolsURL(source) if err != nil { return nil, err } logger.Infof("source for sync of agent binaries: %v", sourceURL) return simplestreams.NewURLSignedDataSource("sync agent binaries source", sourceURL, keys.JujuPublicKey, utils.VerifySSLHostnames, simplestreams.CUSTOM_CLOUD_DATA, false), nil }
[ "func", "selectSourceDatasource", "(", "syncContext", "*", "SyncContext", ")", "(", "simplestreams", ".", "DataSource", ",", "error", ")", "{", "source", ":=", "syncContext", ".", "Source", "\n", "if", "source", "==", "\"", "\"", "{", "source", "=", "envtools", ".", "DefaultBaseURL", "\n", "}", "\n", "sourceURL", ",", "err", ":=", "envtools", ".", "ToolsURL", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "sourceURL", ")", "\n", "return", "simplestreams", ".", "NewURLSignedDataSource", "(", "\"", "\"", ",", "sourceURL", ",", "keys", ".", "JujuPublicKey", ",", "utils", ".", "VerifySSLHostnames", ",", "simplestreams", ".", "CUSTOM_CLOUD_DATA", ",", "false", ")", ",", "nil", "\n", "}" ]
// selectSourceDatasource returns a storage reader based on the source setting.
[ "selectSourceDatasource", "returns", "a", "storage", "reader", "based", "on", "the", "source", "setting", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/sync/sync.go#L151-L162
156,801
juju/juju
environs/sync/sync.go
copyTools
func copyTools(toolsDir, stream string, tools []*coretools.Tools, u ToolsUploader) error { for _, tool := range tools { logger.Infof("copying %s from %s", tool.Version, tool.URL) if err := copyOneToolsPackage(toolsDir, stream, tool, u); err != nil { return err } } return nil }
go
func copyTools(toolsDir, stream string, tools []*coretools.Tools, u ToolsUploader) error { for _, tool := range tools { logger.Infof("copying %s from %s", tool.Version, tool.URL) if err := copyOneToolsPackage(toolsDir, stream, tool, u); err != nil { return err } } return nil }
[ "func", "copyTools", "(", "toolsDir", ",", "stream", "string", ",", "tools", "[", "]", "*", "coretools", ".", "Tools", ",", "u", "ToolsUploader", ")", "error", "{", "for", "_", ",", "tool", ":=", "range", "tools", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "tool", ".", "Version", ",", "tool", ".", "URL", ")", "\n", "if", "err", ":=", "copyOneToolsPackage", "(", "toolsDir", ",", "stream", ",", "tool", ",", "u", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// copyTools copies a set of tools from the source to the target.
[ "copyTools", "copies", "a", "set", "of", "tools", "from", "the", "source", "to", "the", "target", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/sync/sync.go#L165-L173
156,802
juju/juju
environs/sync/sync.go
copyOneToolsPackage
func copyOneToolsPackage(toolsDir, stream string, tools *coretools.Tools, u ToolsUploader) error { toolsName := envtools.StorageName(tools.Version, toolsDir) logger.Infof("downloading %q %v (%v)", stream, toolsName, tools.URL) resp, err := utils.GetValidatingHTTPClient().Get(tools.URL) if err != nil { return err } defer resp.Body.Close() // Verify SHA-256 hash. var buf bytes.Buffer sha256, size, err := utils.ReadSHA256(io.TeeReader(resp.Body, &buf)) if err != nil { return err } if tools.SHA256 == "" { logger.Errorf("no SHA-256 hash for %v", tools.SHA256) // TODO(dfc) can you spot the bug ? } else if sha256 != tools.SHA256 { return errors.Errorf("SHA-256 hash mismatch (%v/%v)", sha256, tools.SHA256) } sizeInKB := (size + 512) / 1024 logger.Infof("uploading %v (%dkB) to model", toolsName, sizeInKB) return u.UploadTools(toolsDir, stream, tools, buf.Bytes()) }
go
func copyOneToolsPackage(toolsDir, stream string, tools *coretools.Tools, u ToolsUploader) error { toolsName := envtools.StorageName(tools.Version, toolsDir) logger.Infof("downloading %q %v (%v)", stream, toolsName, tools.URL) resp, err := utils.GetValidatingHTTPClient().Get(tools.URL) if err != nil { return err } defer resp.Body.Close() // Verify SHA-256 hash. var buf bytes.Buffer sha256, size, err := utils.ReadSHA256(io.TeeReader(resp.Body, &buf)) if err != nil { return err } if tools.SHA256 == "" { logger.Errorf("no SHA-256 hash for %v", tools.SHA256) // TODO(dfc) can you spot the bug ? } else if sha256 != tools.SHA256 { return errors.Errorf("SHA-256 hash mismatch (%v/%v)", sha256, tools.SHA256) } sizeInKB := (size + 512) / 1024 logger.Infof("uploading %v (%dkB) to model", toolsName, sizeInKB) return u.UploadTools(toolsDir, stream, tools, buf.Bytes()) }
[ "func", "copyOneToolsPackage", "(", "toolsDir", ",", "stream", "string", ",", "tools", "*", "coretools", ".", "Tools", ",", "u", "ToolsUploader", ")", "error", "{", "toolsName", ":=", "envtools", ".", "StorageName", "(", "tools", ".", "Version", ",", "toolsDir", ")", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "stream", ",", "toolsName", ",", "tools", ".", "URL", ")", "\n", "resp", ",", "err", ":=", "utils", ".", "GetValidatingHTTPClient", "(", ")", ".", "Get", "(", "tools", ".", "URL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "// Verify SHA-256 hash.", "var", "buf", "bytes", ".", "Buffer", "\n", "sha256", ",", "size", ",", "err", ":=", "utils", ".", "ReadSHA256", "(", "io", ".", "TeeReader", "(", "resp", ".", "Body", ",", "&", "buf", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "tools", ".", "SHA256", "==", "\"", "\"", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "tools", ".", "SHA256", ")", "// TODO(dfc) can you spot the bug ?", "\n", "}", "else", "if", "sha256", "!=", "tools", ".", "SHA256", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "sha256", ",", "tools", ".", "SHA256", ")", "\n", "}", "\n", "sizeInKB", ":=", "(", "size", "+", "512", ")", "/", "1024", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "toolsName", ",", "sizeInKB", ")", "\n", "return", "u", ".", "UploadTools", "(", "toolsDir", ",", "stream", ",", "tools", ",", "buf", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// copyOneToolsPackage copies one tool from the source to the target.
[ "copyOneToolsPackage", "copies", "one", "tool", "from", "the", "source", "to", "the", "target", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/sync/sync.go#L176-L198
156,803
juju/juju
environs/sync/sync.go
cloneToolsForSeries
func cloneToolsForSeries(toolsInfo *BuiltAgent, stream string, series ...string) error { // Copy the tools to the target storage, recording a Tools struct for each one. var targetTools coretools.List targetTools = append(targetTools, &coretools.Tools{ Version: toolsInfo.Version, Size: toolsInfo.Size, SHA256: toolsInfo.Sha256Hash, }) putTools := func(vers version.Binary) (string, error) { name := envtools.StorageName(vers, stream) src := filepath.Join(toolsInfo.Dir, toolsInfo.StorageName) dest := filepath.Join(toolsInfo.Dir, name) destDir := filepath.Dir(dest) if err := os.MkdirAll(destDir, 0755); err != nil { return "", err } if err := utils.CopyFile(dest, src); err != nil { return "", err } // Append to targetTools the attributes required to write out tools metadata. targetTools = append(targetTools, &coretools.Tools{ Version: vers, Size: toolsInfo.Size, SHA256: toolsInfo.Sha256Hash, }) return name, nil } logger.Debugf("generating tarballs for %v", series) for _, series := range series { _, err := jujuseries.SeriesVersion(series) if err != nil { return err } if series != toolsInfo.Version.Series { fakeVersion := toolsInfo.Version fakeVersion.Series = series if _, err := putTools(fakeVersion); err != nil { return err } } } // The tools have been copied to a temp location from which they will be uploaded, // now write out the matching simplestreams metadata so that SyncTools can find them. metadataStore, err := filestorage.NewFileStorageWriter(toolsInfo.Dir) if err != nil { return err } logger.Debugf("generating agent metadata") return envtools.MergeAndWriteMetadata(metadataStore, stream, stream, targetTools, false) }
go
func cloneToolsForSeries(toolsInfo *BuiltAgent, stream string, series ...string) error { // Copy the tools to the target storage, recording a Tools struct for each one. var targetTools coretools.List targetTools = append(targetTools, &coretools.Tools{ Version: toolsInfo.Version, Size: toolsInfo.Size, SHA256: toolsInfo.Sha256Hash, }) putTools := func(vers version.Binary) (string, error) { name := envtools.StorageName(vers, stream) src := filepath.Join(toolsInfo.Dir, toolsInfo.StorageName) dest := filepath.Join(toolsInfo.Dir, name) destDir := filepath.Dir(dest) if err := os.MkdirAll(destDir, 0755); err != nil { return "", err } if err := utils.CopyFile(dest, src); err != nil { return "", err } // Append to targetTools the attributes required to write out tools metadata. targetTools = append(targetTools, &coretools.Tools{ Version: vers, Size: toolsInfo.Size, SHA256: toolsInfo.Sha256Hash, }) return name, nil } logger.Debugf("generating tarballs for %v", series) for _, series := range series { _, err := jujuseries.SeriesVersion(series) if err != nil { return err } if series != toolsInfo.Version.Series { fakeVersion := toolsInfo.Version fakeVersion.Series = series if _, err := putTools(fakeVersion); err != nil { return err } } } // The tools have been copied to a temp location from which they will be uploaded, // now write out the matching simplestreams metadata so that SyncTools can find them. metadataStore, err := filestorage.NewFileStorageWriter(toolsInfo.Dir) if err != nil { return err } logger.Debugf("generating agent metadata") return envtools.MergeAndWriteMetadata(metadataStore, stream, stream, targetTools, false) }
[ "func", "cloneToolsForSeries", "(", "toolsInfo", "*", "BuiltAgent", ",", "stream", "string", ",", "series", "...", "string", ")", "error", "{", "// Copy the tools to the target storage, recording a Tools struct for each one.", "var", "targetTools", "coretools", ".", "List", "\n", "targetTools", "=", "append", "(", "targetTools", ",", "&", "coretools", ".", "Tools", "{", "Version", ":", "toolsInfo", ".", "Version", ",", "Size", ":", "toolsInfo", ".", "Size", ",", "SHA256", ":", "toolsInfo", ".", "Sha256Hash", ",", "}", ")", "\n", "putTools", ":=", "func", "(", "vers", "version", ".", "Binary", ")", "(", "string", ",", "error", ")", "{", "name", ":=", "envtools", ".", "StorageName", "(", "vers", ",", "stream", ")", "\n", "src", ":=", "filepath", ".", "Join", "(", "toolsInfo", ".", "Dir", ",", "toolsInfo", ".", "StorageName", ")", "\n", "dest", ":=", "filepath", ".", "Join", "(", "toolsInfo", ".", "Dir", ",", "name", ")", "\n", "destDir", ":=", "filepath", ".", "Dir", "(", "dest", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "destDir", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "err", ":=", "utils", ".", "CopyFile", "(", "dest", ",", "src", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "// Append to targetTools the attributes required to write out tools metadata.", "targetTools", "=", "append", "(", "targetTools", ",", "&", "coretools", ".", "Tools", "{", "Version", ":", "vers", ",", "Size", ":", "toolsInfo", ".", "Size", ",", "SHA256", ":", "toolsInfo", ".", "Sha256Hash", ",", "}", ")", "\n", "return", "name", ",", "nil", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "series", ")", "\n", "for", "_", ",", "series", ":=", "range", "series", "{", "_", ",", "err", ":=", "jujuseries", ".", "SeriesVersion", "(", "series", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "series", "!=", "toolsInfo", ".", "Version", ".", "Series", "{", "fakeVersion", ":=", "toolsInfo", ".", "Version", "\n", "fakeVersion", ".", "Series", "=", "series", "\n", "if", "_", ",", "err", ":=", "putTools", "(", "fakeVersion", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "// The tools have been copied to a temp location from which they will be uploaded,", "// now write out the matching simplestreams metadata so that SyncTools can find them.", "metadataStore", ",", "err", ":=", "filestorage", ".", "NewFileStorageWriter", "(", "toolsInfo", ".", "Dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "envtools", ".", "MergeAndWriteMetadata", "(", "metadataStore", ",", "stream", ",", "stream", ",", "targetTools", ",", "false", ")", "\n", "}" ]
// cloneToolsForSeries copies the built tools tarball into a tarball for the specified // stream and series and generates corresponding metadata.
[ "cloneToolsForSeries", "copies", "the", "built", "tools", "tarball", "into", "a", "tarball", "for", "the", "specified", "stream", "and", "series", "and", "generates", "corresponding", "metadata", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/sync/sync.go#L227-L276
156,804
juju/juju
environs/sync/sync.go
buildAgentTarball
func buildAgentTarball(build bool, forceVersion *version.Number, stream string) (_ *BuiltAgent, err error) { // TODO(rog) find binaries from $PATH when not using a development // version of juju within a $GOPATH. logger.Debugf("Making agent binary tarball") // We create the entire archive before asking the environment to // start uploading so that we can be sure we have archived // correctly. f, err := ioutil.TempFile("", "juju-tgz") if err != nil { return nil, err } defer f.Close() defer os.Remove(f.Name()) toolsVersion, official, sha256Hash, err := envtools.BundleTools(build, f, forceVersion) if err != nil { return nil, err } // Built agent version needs to match the client used to bootstrap. builtVersion := toolsVersion builtVersion.Build = 0 clientVersion := jujuversion.Current clientVersion.Build = 0 if builtVersion.Number.Compare(clientVersion) != 0 { return nil, errors.Errorf("agent binary %v not compatible with bootstrap client %v", toolsVersion.Number, jujuversion.Current) } fileInfo, err := f.Stat() if err != nil { return nil, errors.Errorf("cannot stat newly made agent binary archive: %v", err) } size := fileInfo.Size() reportedVersion := toolsVersion if !official && forceVersion != nil { reportedVersion.Number = *forceVersion } if official { logger.Infof("using official agent binary %v (%dkB)", toolsVersion, (size+512)/1024) } else { logger.Infof("using agent binary %v aliased to %v (%dkB)", toolsVersion, reportedVersion, (size+512)/1024) } baseToolsDir, err := ioutil.TempDir("", "juju-tools") if err != nil { return nil, err } // If we exit with an error, clean up the built tools directory. defer func() { if err != nil { os.RemoveAll(baseToolsDir) } }() err = os.MkdirAll(filepath.Join(baseToolsDir, storage.BaseToolsPath, stream), 0755) if err != nil { return nil, err } storageName := envtools.StorageName(toolsVersion, stream) err = utils.CopyFile(filepath.Join(baseToolsDir, storageName), f.Name()) if err != nil { return nil, err } return &BuiltAgent{ Version: toolsVersion, Official: official, Dir: baseToolsDir, StorageName: storageName, Size: size, Sha256Hash: sha256Hash, }, nil }
go
func buildAgentTarball(build bool, forceVersion *version.Number, stream string) (_ *BuiltAgent, err error) { // TODO(rog) find binaries from $PATH when not using a development // version of juju within a $GOPATH. logger.Debugf("Making agent binary tarball") // We create the entire archive before asking the environment to // start uploading so that we can be sure we have archived // correctly. f, err := ioutil.TempFile("", "juju-tgz") if err != nil { return nil, err } defer f.Close() defer os.Remove(f.Name()) toolsVersion, official, sha256Hash, err := envtools.BundleTools(build, f, forceVersion) if err != nil { return nil, err } // Built agent version needs to match the client used to bootstrap. builtVersion := toolsVersion builtVersion.Build = 0 clientVersion := jujuversion.Current clientVersion.Build = 0 if builtVersion.Number.Compare(clientVersion) != 0 { return nil, errors.Errorf("agent binary %v not compatible with bootstrap client %v", toolsVersion.Number, jujuversion.Current) } fileInfo, err := f.Stat() if err != nil { return nil, errors.Errorf("cannot stat newly made agent binary archive: %v", err) } size := fileInfo.Size() reportedVersion := toolsVersion if !official && forceVersion != nil { reportedVersion.Number = *forceVersion } if official { logger.Infof("using official agent binary %v (%dkB)", toolsVersion, (size+512)/1024) } else { logger.Infof("using agent binary %v aliased to %v (%dkB)", toolsVersion, reportedVersion, (size+512)/1024) } baseToolsDir, err := ioutil.TempDir("", "juju-tools") if err != nil { return nil, err } // If we exit with an error, clean up the built tools directory. defer func() { if err != nil { os.RemoveAll(baseToolsDir) } }() err = os.MkdirAll(filepath.Join(baseToolsDir, storage.BaseToolsPath, stream), 0755) if err != nil { return nil, err } storageName := envtools.StorageName(toolsVersion, stream) err = utils.CopyFile(filepath.Join(baseToolsDir, storageName), f.Name()) if err != nil { return nil, err } return &BuiltAgent{ Version: toolsVersion, Official: official, Dir: baseToolsDir, StorageName: storageName, Size: size, Sha256Hash: sha256Hash, }, nil }
[ "func", "buildAgentTarball", "(", "build", "bool", ",", "forceVersion", "*", "version", ".", "Number", ",", "stream", "string", ")", "(", "_", "*", "BuiltAgent", ",", "err", "error", ")", "{", "// TODO(rog) find binaries from $PATH when not using a development", "// version of juju within a $GOPATH.", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "// We create the entire archive before asking the environment to", "// start uploading so that we can be sure we have archived", "// correctly.", "f", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "defer", "os", ".", "Remove", "(", "f", ".", "Name", "(", ")", ")", "\n", "toolsVersion", ",", "official", ",", "sha256Hash", ",", "err", ":=", "envtools", ".", "BundleTools", "(", "build", ",", "f", ",", "forceVersion", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Built agent version needs to match the client used to bootstrap.", "builtVersion", ":=", "toolsVersion", "\n", "builtVersion", ".", "Build", "=", "0", "\n", "clientVersion", ":=", "jujuversion", ".", "Current", "\n", "clientVersion", ".", "Build", "=", "0", "\n", "if", "builtVersion", ".", "Number", ".", "Compare", "(", "clientVersion", ")", "!=", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "toolsVersion", ".", "Number", ",", "jujuversion", ".", "Current", ")", "\n", "}", "\n", "fileInfo", ",", "err", ":=", "f", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "size", ":=", "fileInfo", ".", "Size", "(", ")", "\n", "reportedVersion", ":=", "toolsVersion", "\n", "if", "!", "official", "&&", "forceVersion", "!=", "nil", "{", "reportedVersion", ".", "Number", "=", "*", "forceVersion", "\n", "}", "\n", "if", "official", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "toolsVersion", ",", "(", "size", "+", "512", ")", "/", "1024", ")", "\n", "}", "else", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "toolsVersion", ",", "reportedVersion", ",", "(", "size", "+", "512", ")", "/", "1024", ")", "\n", "}", "\n", "baseToolsDir", ",", "err", ":=", "ioutil", ".", "TempDir", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// If we exit with an error, clean up the built tools directory.", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "os", ".", "RemoveAll", "(", "baseToolsDir", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "err", "=", "os", ".", "MkdirAll", "(", "filepath", ".", "Join", "(", "baseToolsDir", ",", "storage", ".", "BaseToolsPath", ",", "stream", ")", ",", "0755", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "storageName", ":=", "envtools", ".", "StorageName", "(", "toolsVersion", ",", "stream", ")", "\n", "err", "=", "utils", ".", "CopyFile", "(", "filepath", ".", "Join", "(", "baseToolsDir", ",", "storageName", ")", ",", "f", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "BuiltAgent", "{", "Version", ":", "toolsVersion", ",", "Official", ":", "official", ",", "Dir", ":", "baseToolsDir", ",", "StorageName", ":", "storageName", ",", "Size", ":", "size", ",", "Sha256Hash", ":", "sha256Hash", ",", "}", ",", "nil", "\n", "}" ]
// BuildAgentTarball bundles an agent tarball and places it in a temp directory in // the expected agent path.
[ "BuildAgentTarball", "bundles", "an", "agent", "tarball", "and", "places", "it", "in", "a", "temp", "directory", "in", "the", "expected", "agent", "path", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/sync/sync.go#L297-L366
156,805
juju/juju
environs/sync/sync.go
syncBuiltTools
func syncBuiltTools(stor storage.Storage, stream string, builtTools *BuiltAgent, fakeSeries ...string) (*coretools.Tools, error) { if err := cloneToolsForSeries(builtTools, stream, fakeSeries...); err != nil { return nil, err } syncContext := &SyncContext{ Source: builtTools.Dir, TargetToolsFinder: StorageToolsFinder{stor}, TargetToolsUploader: StorageToolsUploader{stor, false, false}, AllVersions: true, Stream: stream, MajorVersion: builtTools.Version.Major, MinorVersion: -1, } logger.Debugf("uploading agent binaries to cloud storage") err := SyncTools(syncContext) if err != nil { return nil, err } url, err := stor.URL(builtTools.StorageName) if err != nil { return nil, err } return &coretools.Tools{ Version: builtTools.Version, URL: url, Size: builtTools.Size, SHA256: builtTools.Sha256Hash, }, nil }
go
func syncBuiltTools(stor storage.Storage, stream string, builtTools *BuiltAgent, fakeSeries ...string) (*coretools.Tools, error) { if err := cloneToolsForSeries(builtTools, stream, fakeSeries...); err != nil { return nil, err } syncContext := &SyncContext{ Source: builtTools.Dir, TargetToolsFinder: StorageToolsFinder{stor}, TargetToolsUploader: StorageToolsUploader{stor, false, false}, AllVersions: true, Stream: stream, MajorVersion: builtTools.Version.Major, MinorVersion: -1, } logger.Debugf("uploading agent binaries to cloud storage") err := SyncTools(syncContext) if err != nil { return nil, err } url, err := stor.URL(builtTools.StorageName) if err != nil { return nil, err } return &coretools.Tools{ Version: builtTools.Version, URL: url, Size: builtTools.Size, SHA256: builtTools.Sha256Hash, }, nil }
[ "func", "syncBuiltTools", "(", "stor", "storage", ".", "Storage", ",", "stream", "string", ",", "builtTools", "*", "BuiltAgent", ",", "fakeSeries", "...", "string", ")", "(", "*", "coretools", ".", "Tools", ",", "error", ")", "{", "if", "err", ":=", "cloneToolsForSeries", "(", "builtTools", ",", "stream", ",", "fakeSeries", "...", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "syncContext", ":=", "&", "SyncContext", "{", "Source", ":", "builtTools", ".", "Dir", ",", "TargetToolsFinder", ":", "StorageToolsFinder", "{", "stor", "}", ",", "TargetToolsUploader", ":", "StorageToolsUploader", "{", "stor", ",", "false", ",", "false", "}", ",", "AllVersions", ":", "true", ",", "Stream", ":", "stream", ",", "MajorVersion", ":", "builtTools", ".", "Version", ".", "Major", ",", "MinorVersion", ":", "-", "1", ",", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "err", ":=", "SyncTools", "(", "syncContext", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "url", ",", "err", ":=", "stor", ".", "URL", "(", "builtTools", ".", "StorageName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "coretools", ".", "Tools", "{", "Version", ":", "builtTools", ".", "Version", ",", "URL", ":", "url", ",", "Size", ":", "builtTools", ".", "Size", ",", "SHA256", ":", "builtTools", ".", "Sha256Hash", ",", "}", ",", "nil", "\n", "}" ]
// syncBuiltTools copies to storage a tools tarball and cloned copies for each series.
[ "syncBuiltTools", "copies", "to", "storage", "a", "tools", "tarball", "and", "cloned", "copies", "for", "each", "series", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/sync/sync.go#L369-L397
156,806
juju/juju
apiserver/common/instanceidgetter.go
NewInstanceIdGetter
func NewInstanceIdGetter(st state.EntityFinder, getCanRead GetAuthFunc) *InstanceIdGetter { return &InstanceIdGetter{ st: st, getCanRead: getCanRead, } }
go
func NewInstanceIdGetter(st state.EntityFinder, getCanRead GetAuthFunc) *InstanceIdGetter { return &InstanceIdGetter{ st: st, getCanRead: getCanRead, } }
[ "func", "NewInstanceIdGetter", "(", "st", "state", ".", "EntityFinder", ",", "getCanRead", "GetAuthFunc", ")", "*", "InstanceIdGetter", "{", "return", "&", "InstanceIdGetter", "{", "st", ":", "st", ",", "getCanRead", ":", "getCanRead", ",", "}", "\n", "}" ]
// NewInstanceIdGetter returns a new InstanceIdGetter. The GetAuthFunc // will be used on each invocation of InstanceId to determine current // permissions.
[ "NewInstanceIdGetter", "returns", "a", "new", "InstanceIdGetter", ".", "The", "GetAuthFunc", "will", "be", "used", "on", "each", "invocation", "of", "InstanceId", "to", "determine", "current", "permissions", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/instanceidgetter.go#L24-L29
156,807
juju/juju
apiserver/common/instanceidgetter.go
InstanceId
func (ig *InstanceIdGetter) InstanceId(args params.Entities) (params.StringResults, error) { result := params.StringResults{ Results: make([]params.StringResult, len(args.Entities)), } canRead, err := ig.getCanRead() if err != nil { return result, err } for i, entity := range args.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { result.Results[i].Error = ServerError(ErrPerm) continue } err = ErrPerm if canRead(tag) { var instanceId instance.Id instanceId, err = ig.getInstanceId(tag) if err == nil { result.Results[i].Result = string(instanceId) } } result.Results[i].Error = ServerError(err) } return result, nil }
go
func (ig *InstanceIdGetter) InstanceId(args params.Entities) (params.StringResults, error) { result := params.StringResults{ Results: make([]params.StringResult, len(args.Entities)), } canRead, err := ig.getCanRead() if err != nil { return result, err } for i, entity := range args.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { result.Results[i].Error = ServerError(ErrPerm) continue } err = ErrPerm if canRead(tag) { var instanceId instance.Id instanceId, err = ig.getInstanceId(tag) if err == nil { result.Results[i].Result = string(instanceId) } } result.Results[i].Error = ServerError(err) } return result, nil }
[ "func", "(", "ig", "*", "InstanceIdGetter", ")", "InstanceId", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "StringResults", ",", "error", ")", "{", "result", ":=", "params", ".", "StringResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "StringResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "canRead", ",", "err", ":=", "ig", ".", "getCanRead", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "ServerError", "(", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "err", "=", "ErrPerm", "\n", "if", "canRead", "(", "tag", ")", "{", "var", "instanceId", "instance", ".", "Id", "\n", "instanceId", ",", "err", "=", "ig", ".", "getInstanceId", "(", "tag", ")", "\n", "if", "err", "==", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Result", "=", "string", "(", "instanceId", ")", "\n", "}", "\n", "}", "\n", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// InstanceId returns the provider specific instance id for each given // machine or an CodeNotProvisioned error, if not set.
[ "InstanceId", "returns", "the", "provider", "specific", "instance", "id", "for", "each", "given", "machine", "or", "an", "CodeNotProvisioned", "error", "if", "not", "set", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/instanceidgetter.go#L45-L70
156,808
juju/juju
api/backups/client.go
MakeClient
func MakeClient(frontend base.ClientFacade, backend base.FacadeCaller, client *httprequest.Client) *Client { return &Client{ ClientFacade: frontend, facade: backend, client: client, } }
go
func MakeClient(frontend base.ClientFacade, backend base.FacadeCaller, client *httprequest.Client) *Client { return &Client{ ClientFacade: frontend, facade: backend, client: client, } }
[ "func", "MakeClient", "(", "frontend", "base", ".", "ClientFacade", ",", "backend", "base", ".", "FacadeCaller", ",", "client", "*", "httprequest", ".", "Client", ")", "*", "Client", "{", "return", "&", "Client", "{", "ClientFacade", ":", "frontend", ",", "facade", ":", "backend", ",", "client", ":", "client", ",", "}", "\n", "}" ]
// MakeClient is a direct constructor function for a backups client.
[ "MakeClient", "is", "a", "direct", "constructor", "function", "for", "a", "backups", "client", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/backups/client.go#L24-L30
156,809
juju/juju
api/backups/client.go
NewClient
func NewClient(st base.APICallCloser) (*Client, error) { frontend, backend := base.NewClientFacade(st, "Backups") client, err := st.HTTPClient() if err != nil { return nil, errors.Trace(err) } return MakeClient(frontend, backend, client), nil }
go
func NewClient(st base.APICallCloser) (*Client, error) { frontend, backend := base.NewClientFacade(st, "Backups") client, err := st.HTTPClient() if err != nil { return nil, errors.Trace(err) } return MakeClient(frontend, backend, client), nil }
[ "func", "NewClient", "(", "st", "base", ".", "APICallCloser", ")", "(", "*", "Client", ",", "error", ")", "{", "frontend", ",", "backend", ":=", "base", ".", "NewClientFacade", "(", "st", ",", "\"", "\"", ")", "\n", "client", ",", "err", ":=", "st", ".", "HTTPClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "MakeClient", "(", "frontend", ",", "backend", ",", "client", ")", ",", "nil", "\n", "}" ]
// NewClient returns a new backups API client.
[ "NewClient", "returns", "a", "new", "backups", "API", "client", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/backups/client.go#L33-L40
156,810
juju/juju
api/instancemutater/machine.go
Refresh
func (m *Machine) Refresh() error { life, err := common.OneLife(m.facade, m.tag) if err != nil { return errors.Trace(err) } m.life = life return nil }
go
func (m *Machine) Refresh() error { life, err := common.OneLife(m.facade, m.tag) if err != nil { return errors.Trace(err) } m.life = life return nil }
[ "func", "(", "m", "*", "Machine", ")", "Refresh", "(", ")", "error", "{", "life", ",", "err", ":=", "common", ".", "OneLife", "(", "m", ".", "facade", ",", "m", ".", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "m", ".", "life", "=", "life", "\n", "return", "nil", "\n", "}" ]
// Refresh implements MutaterMachine.Refresh.
[ "Refresh", "implements", "MutaterMachine", ".", "Refresh", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/machine.go#L129-L136
156,811
juju/juju
api/instancemutater/machine.go
WatchUnits
func (m *Machine) WatchUnits() (watcher.StringsWatcher, error) { var results params.StringsWatchResults args := params.Entities{ Entities: []params.Entity{{Tag: m.tag.String()}}, } err := m.facade.FacadeCall("WatchUnits", args, &results) if err != nil { return nil, err } if len(results.Results) != 1 { return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, result.Error } w := apiwatcher.NewStringsWatcher(m.facade.RawAPICaller(), result) return w, nil }
go
func (m *Machine) WatchUnits() (watcher.StringsWatcher, error) { var results params.StringsWatchResults args := params.Entities{ Entities: []params.Entity{{Tag: m.tag.String()}}, } err := m.facade.FacadeCall("WatchUnits", args, &results) if err != nil { return nil, err } if len(results.Results) != 1 { return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, result.Error } w := apiwatcher.NewStringsWatcher(m.facade.RawAPICaller(), result) return w, nil }
[ "func", "(", "m", "*", "Machine", ")", "WatchUnits", "(", ")", "(", "watcher", ".", "StringsWatcher", ",", "error", ")", "{", "var", "results", "params", ".", "StringsWatchResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "Tag", ":", "m", ".", "tag", ".", "String", "(", ")", "}", "}", ",", "}", "\n", "err", ":=", "m", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "result", ".", "Error", "\n", "}", "\n", "w", ":=", "apiwatcher", ".", "NewStringsWatcher", "(", "m", ".", "facade", ".", "RawAPICaller", "(", ")", ",", "result", ")", "\n", "return", "w", ",", "nil", "\n", "}" ]
// WatchUnits implements MutaterMachine.WatchUnits.
[ "WatchUnits", "implements", "MutaterMachine", ".", "WatchUnits", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/machine.go#L139-L157
156,812
juju/juju
api/instancemutater/machine.go
WatchLXDProfileVerificationNeeded
func (m *Machine) WatchLXDProfileVerificationNeeded() (watcher.NotifyWatcher, error) { var results params.NotifyWatchResults args := params.Entities{ Entities: []params.Entity{{Tag: m.tag.String()}}, } err := m.facade.FacadeCall("WatchLXDProfileVerificationNeeded", args, &results) if err != nil { return nil, err } if len(results.Results) != 1 { return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, result.Error } return apiwatcher.NewNotifyWatcher(m.facade.RawAPICaller(), result), nil }
go
func (m *Machine) WatchLXDProfileVerificationNeeded() (watcher.NotifyWatcher, error) { var results params.NotifyWatchResults args := params.Entities{ Entities: []params.Entity{{Tag: m.tag.String()}}, } err := m.facade.FacadeCall("WatchLXDProfileVerificationNeeded", args, &results) if err != nil { return nil, err } if len(results.Results) != 1 { return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, result.Error } return apiwatcher.NewNotifyWatcher(m.facade.RawAPICaller(), result), nil }
[ "func", "(", "m", "*", "Machine", ")", "WatchLXDProfileVerificationNeeded", "(", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "var", "results", "params", ".", "NotifyWatchResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "Tag", ":", "m", ".", "tag", ".", "String", "(", ")", "}", "}", ",", "}", "\n", "err", ":=", "m", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "result", ".", "Error", "\n", "}", "\n", "return", "apiwatcher", ".", "NewNotifyWatcher", "(", "m", ".", "facade", ".", "RawAPICaller", "(", ")", ",", "result", ")", ",", "nil", "\n", "}" ]
// WatchLXDProfileVerificationNeeded implements MutaterMachine.WatchLXDProfileVerificationNeeded.
[ "WatchLXDProfileVerificationNeeded", "implements", "MutaterMachine", ".", "WatchLXDProfileVerificationNeeded", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/machine.go#L160-L177
156,813
juju/juju
api/instancemutater/machine.go
WatchContainers
func (m *Machine) WatchContainers() (watcher.StringsWatcher, error) { var result params.StringsWatchResult arg := params.Entity{Tag: m.tag.String()} err := m.facade.FacadeCall("WatchContainers", arg, &result) if err != nil { return nil, errors.Trace(err) } if result.Error != nil { return nil, result.Error } return apiwatcher.NewStringsWatcher(m.facade.RawAPICaller(), result), nil }
go
func (m *Machine) WatchContainers() (watcher.StringsWatcher, error) { var result params.StringsWatchResult arg := params.Entity{Tag: m.tag.String()} err := m.facade.FacadeCall("WatchContainers", arg, &result) if err != nil { return nil, errors.Trace(err) } if result.Error != nil { return nil, result.Error } return apiwatcher.NewStringsWatcher(m.facade.RawAPICaller(), result), nil }
[ "func", "(", "m", "*", "Machine", ")", "WatchContainers", "(", ")", "(", "watcher", ".", "StringsWatcher", ",", "error", ")", "{", "var", "result", "params", ".", "StringsWatchResult", "\n", "arg", ":=", "params", ".", "Entity", "{", "Tag", ":", "m", ".", "tag", ".", "String", "(", ")", "}", "\n", "err", ":=", "m", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "arg", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "result", ".", "Error", "\n", "}", "\n", "return", "apiwatcher", ".", "NewStringsWatcher", "(", "m", ".", "facade", ".", "RawAPICaller", "(", ")", ",", "result", ")", ",", "nil", "\n", "}" ]
// WatchContainers returns a StringsWatcher reporting changes to containers.
[ "WatchContainers", "returns", "a", "StringsWatcher", "reporting", "changes", "to", "containers", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/machine.go#L180-L191
156,814
juju/juju
api/instancemutater/machine.go
CharmProfilingInfo
func (m *Machine) CharmProfilingInfo() (*UnitProfileInfo, error) { var result params.CharmProfilingInfoResult args := params.Entity{Tag: m.tag.String()} err := m.facade.FacadeCall("CharmProfilingInfo", args, &result) if err != nil { return nil, err } if result.Error != nil { return nil, errors.Trace(result.Error) } returnResult := &UnitProfileInfo{ InstanceId: result.InstanceId, ModelName: result.ModelName, CurrentProfiles: result.CurrentProfiles, } profileChanges := make([]UnitProfileChanges, len(result.ProfileChanges)) for i, change := range result.ProfileChanges { var profile lxdprofile.Profile if change.Profile != nil { profile = lxdprofile.Profile{ Config: change.Profile.Config, Description: change.Profile.Description, Devices: change.Profile.Devices, } } profileChanges[i] = UnitProfileChanges{ ApplicationName: change.ApplicationName, Revision: change.Revision, Profile: profile, } if change.Error != nil { return nil, change.Error } } returnResult.ProfileChanges = profileChanges return returnResult, nil }
go
func (m *Machine) CharmProfilingInfo() (*UnitProfileInfo, error) { var result params.CharmProfilingInfoResult args := params.Entity{Tag: m.tag.String()} err := m.facade.FacadeCall("CharmProfilingInfo", args, &result) if err != nil { return nil, err } if result.Error != nil { return nil, errors.Trace(result.Error) } returnResult := &UnitProfileInfo{ InstanceId: result.InstanceId, ModelName: result.ModelName, CurrentProfiles: result.CurrentProfiles, } profileChanges := make([]UnitProfileChanges, len(result.ProfileChanges)) for i, change := range result.ProfileChanges { var profile lxdprofile.Profile if change.Profile != nil { profile = lxdprofile.Profile{ Config: change.Profile.Config, Description: change.Profile.Description, Devices: change.Profile.Devices, } } profileChanges[i] = UnitProfileChanges{ ApplicationName: change.ApplicationName, Revision: change.Revision, Profile: profile, } if change.Error != nil { return nil, change.Error } } returnResult.ProfileChanges = profileChanges return returnResult, nil }
[ "func", "(", "m", "*", "Machine", ")", "CharmProfilingInfo", "(", ")", "(", "*", "UnitProfileInfo", ",", "error", ")", "{", "var", "result", "params", ".", "CharmProfilingInfoResult", "\n", "args", ":=", "params", ".", "Entity", "{", "Tag", ":", "m", ".", "tag", ".", "String", "(", ")", "}", "\n", "err", ":=", "m", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "result", ".", "Error", ")", "\n", "}", "\n", "returnResult", ":=", "&", "UnitProfileInfo", "{", "InstanceId", ":", "result", ".", "InstanceId", ",", "ModelName", ":", "result", ".", "ModelName", ",", "CurrentProfiles", ":", "result", ".", "CurrentProfiles", ",", "}", "\n", "profileChanges", ":=", "make", "(", "[", "]", "UnitProfileChanges", ",", "len", "(", "result", ".", "ProfileChanges", ")", ")", "\n", "for", "i", ",", "change", ":=", "range", "result", ".", "ProfileChanges", "{", "var", "profile", "lxdprofile", ".", "Profile", "\n", "if", "change", ".", "Profile", "!=", "nil", "{", "profile", "=", "lxdprofile", ".", "Profile", "{", "Config", ":", "change", ".", "Profile", ".", "Config", ",", "Description", ":", "change", ".", "Profile", ".", "Description", ",", "Devices", ":", "change", ".", "Profile", ".", "Devices", ",", "}", "\n", "}", "\n", "profileChanges", "[", "i", "]", "=", "UnitProfileChanges", "{", "ApplicationName", ":", "change", ".", "ApplicationName", ",", "Revision", ":", "change", ".", "Revision", ",", "Profile", ":", "profile", ",", "}", "\n", "if", "change", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "change", ".", "Error", "\n", "}", "\n", "}", "\n", "returnResult", ".", "ProfileChanges", "=", "profileChanges", "\n", "return", "returnResult", ",", "nil", "\n", "}" ]
// CharmProfilingInfo implements MutaterMachine.CharmProfilingInfo.
[ "CharmProfilingInfo", "implements", "MutaterMachine", ".", "CharmProfilingInfo", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/instancemutater/machine.go#L207-L243
156,815
juju/juju
provider/dummy/leasestore.go
ExtendLease
func (s *leaseStore) ExtendLease(key lease.Key, req lease.Request, _ <-chan struct{}) error { s.mu.Lock() defer s.mu.Unlock() entry, found := s.entries[key] if !found { return lease.ErrInvalid } if entry.holder != req.Holder { return lease.ErrInvalid } now := s.clock.Now() expiry := now.Add(req.Duration) if !expiry.After(entry.start.Add(entry.duration)) { // No extension needed - the lease already expires after the // new time. return nil } // entry is a pointer back into the f.entries map, so this update // isn't lost. entry.start = now entry.duration = req.Duration return nil }
go
func (s *leaseStore) ExtendLease(key lease.Key, req lease.Request, _ <-chan struct{}) error { s.mu.Lock() defer s.mu.Unlock() entry, found := s.entries[key] if !found { return lease.ErrInvalid } if entry.holder != req.Holder { return lease.ErrInvalid } now := s.clock.Now() expiry := now.Add(req.Duration) if !expiry.After(entry.start.Add(entry.duration)) { // No extension needed - the lease already expires after the // new time. return nil } // entry is a pointer back into the f.entries map, so this update // isn't lost. entry.start = now entry.duration = req.Duration return nil }
[ "func", "(", "s", "*", "leaseStore", ")", "ExtendLease", "(", "key", "lease", ".", "Key", ",", "req", "lease", ".", "Request", ",", "_", "<-", "chan", "struct", "{", "}", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "entry", ",", "found", ":=", "s", ".", "entries", "[", "key", "]", "\n", "if", "!", "found", "{", "return", "lease", ".", "ErrInvalid", "\n", "}", "\n", "if", "entry", ".", "holder", "!=", "req", ".", "Holder", "{", "return", "lease", ".", "ErrInvalid", "\n", "}", "\n", "now", ":=", "s", ".", "clock", ".", "Now", "(", ")", "\n", "expiry", ":=", "now", ".", "Add", "(", "req", ".", "Duration", ")", "\n", "if", "!", "expiry", ".", "After", "(", "entry", ".", "start", ".", "Add", "(", "entry", ".", "duration", ")", ")", "{", "// No extension needed - the lease already expires after the", "// new time.", "return", "nil", "\n", "}", "\n", "// entry is a pointer back into the f.entries map, so this update", "// isn't lost.", "entry", ".", "start", "=", "now", "\n", "entry", ".", "duration", "=", "req", ".", "Duration", "\n", "return", "nil", "\n", "}" ]
// ExtendLease is part of lease.Store.
[ "ExtendLease", "is", "part", "of", "lease", ".", "Store", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/dummy/leasestore.go#L69-L91
156,816
juju/juju
provider/dummy/leasestore.go
ExpireLease
func (s *leaseStore) ExpireLease(key lease.Key) error { s.mu.Lock() defer s.mu.Unlock() entry, found := s.entries[key] if !found { return lease.ErrInvalid } expiry := entry.start.Add(entry.duration) if !s.clock.Now().After(expiry) { return lease.ErrInvalid } delete(s.entries, key) s.target.Expired(key) return nil }
go
func (s *leaseStore) ExpireLease(key lease.Key) error { s.mu.Lock() defer s.mu.Unlock() entry, found := s.entries[key] if !found { return lease.ErrInvalid } expiry := entry.start.Add(entry.duration) if !s.clock.Now().After(expiry) { return lease.ErrInvalid } delete(s.entries, key) s.target.Expired(key) return nil }
[ "func", "(", "s", "*", "leaseStore", ")", "ExpireLease", "(", "key", "lease", ".", "Key", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "entry", ",", "found", ":=", "s", ".", "entries", "[", "key", "]", "\n", "if", "!", "found", "{", "return", "lease", ".", "ErrInvalid", "\n", "}", "\n", "expiry", ":=", "entry", ".", "start", ".", "Add", "(", "entry", ".", "duration", ")", "\n", "if", "!", "s", ".", "clock", ".", "Now", "(", ")", ".", "After", "(", "expiry", ")", "{", "return", "lease", ".", "ErrInvalid", "\n", "}", "\n", "delete", "(", "s", ".", "entries", ",", "key", ")", "\n", "s", ".", "target", ".", "Expired", "(", "key", ")", "\n", "return", "nil", "\n", "}" ]
// Expire is part of lease.Store.
[ "Expire", "is", "part", "of", "lease", ".", "Store", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/dummy/leasestore.go#L94-L108
156,817
juju/juju
api/common/upgradeseries.go
NewUpgradeSeriesAPI
func NewUpgradeSeriesAPI(facade base.FacadeCaller, tag names.Tag) *UpgradeSeriesAPI { return &UpgradeSeriesAPI{facade: facade, tag: tag} }
go
func NewUpgradeSeriesAPI(facade base.FacadeCaller, tag names.Tag) *UpgradeSeriesAPI { return &UpgradeSeriesAPI{facade: facade, tag: tag} }
[ "func", "NewUpgradeSeriesAPI", "(", "facade", "base", ".", "FacadeCaller", ",", "tag", "names", ".", "Tag", ")", "*", "UpgradeSeriesAPI", "{", "return", "&", "UpgradeSeriesAPI", "{", "facade", ":", "facade", ",", "tag", ":", "tag", "}", "\n", "}" ]
// NewUpgradeSeriesAPI creates a UpgradeSeriesAPI on the specified facade, // and uses this name when calling through the caller.
[ "NewUpgradeSeriesAPI", "creates", "a", "UpgradeSeriesAPI", "on", "the", "specified", "facade", "and", "uses", "this", "name", "when", "calling", "through", "the", "caller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/common/upgradeseries.go#L26-L28
156,818
juju/juju
api/common/upgradeseries.go
UpgradeSeriesUnitStatus
func (u *UpgradeSeriesAPI) UpgradeSeriesUnitStatus() ([]model.UpgradeSeriesStatus, error) { var results params.UpgradeSeriesStatusResults args := params.Entities{ Entities: []params.Entity{{Tag: u.tag.String()}}, } err := u.facade.FacadeCall("UpgradeSeriesUnitStatus", args, &results) if err != nil { return nil, err } statuses := make([]model.UpgradeSeriesStatus, len(results.Results)) for i, res := range results.Results { if res.Error != nil { // TODO (externalreality) The code to convert api errors (with // error codes) back to normal Go errors is in bad spot and // causes import cycles which is why we don't use it here and may // be the reason why it has few uses despite being useful. if params.IsCodeNotFound(res.Error) { return nil, errors.NewNotFound(res.Error, "") } return nil, res.Error } statuses[i] = res.Status } return statuses, nil }
go
func (u *UpgradeSeriesAPI) UpgradeSeriesUnitStatus() ([]model.UpgradeSeriesStatus, error) { var results params.UpgradeSeriesStatusResults args := params.Entities{ Entities: []params.Entity{{Tag: u.tag.String()}}, } err := u.facade.FacadeCall("UpgradeSeriesUnitStatus", args, &results) if err != nil { return nil, err } statuses := make([]model.UpgradeSeriesStatus, len(results.Results)) for i, res := range results.Results { if res.Error != nil { // TODO (externalreality) The code to convert api errors (with // error codes) back to normal Go errors is in bad spot and // causes import cycles which is why we don't use it here and may // be the reason why it has few uses despite being useful. if params.IsCodeNotFound(res.Error) { return nil, errors.NewNotFound(res.Error, "") } return nil, res.Error } statuses[i] = res.Status } return statuses, nil }
[ "func", "(", "u", "*", "UpgradeSeriesAPI", ")", "UpgradeSeriesUnitStatus", "(", ")", "(", "[", "]", "model", ".", "UpgradeSeriesStatus", ",", "error", ")", "{", "var", "results", "params", ".", "UpgradeSeriesStatusResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "Tag", ":", "u", ".", "tag", ".", "String", "(", ")", "}", "}", ",", "}", "\n\n", "err", ":=", "u", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "statuses", ":=", "make", "(", "[", "]", "model", ".", "UpgradeSeriesStatus", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "for", "i", ",", "res", ":=", "range", "results", ".", "Results", "{", "if", "res", ".", "Error", "!=", "nil", "{", "// TODO (externalreality) The code to convert api errors (with", "// error codes) back to normal Go errors is in bad spot and", "// causes import cycles which is why we don't use it here and may", "// be the reason why it has few uses despite being useful.", "if", "params", ".", "IsCodeNotFound", "(", "res", ".", "Error", ")", "{", "return", "nil", ",", "errors", ".", "NewNotFound", "(", "res", ".", "Error", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", ",", "res", ".", "Error", "\n", "}", "\n", "statuses", "[", "i", "]", "=", "res", ".", "Status", "\n", "}", "\n", "return", "statuses", ",", "nil", "\n", "}" ]
// UpgradeSeriesUnitStatus returns the upgrade series status of a // unit from remote state.
[ "UpgradeSeriesUnitStatus", "returns", "the", "upgrade", "series", "status", "of", "a", "unit", "from", "remote", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/common/upgradeseries.go#L54-L80
156,819
juju/juju
api/common/upgradeseries.go
SetUpgradeSeriesUnitStatus
func (u *UpgradeSeriesAPI) SetUpgradeSeriesUnitStatus(status model.UpgradeSeriesStatus, reason string) error { var results params.ErrorResults args := params.UpgradeSeriesStatusParams{ Params: []params.UpgradeSeriesStatusParam{{ Entity: params.Entity{Tag: u.tag.String()}, Status: status, Message: reason, }}, } err := u.facade.FacadeCall("SetUpgradeSeriesUnitStatus", args, &results) if err != nil { return err } if len(results.Results) != 1 { return errors.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return result.Error } return nil }
go
func (u *UpgradeSeriesAPI) SetUpgradeSeriesUnitStatus(status model.UpgradeSeriesStatus, reason string) error { var results params.ErrorResults args := params.UpgradeSeriesStatusParams{ Params: []params.UpgradeSeriesStatusParam{{ Entity: params.Entity{Tag: u.tag.String()}, Status: status, Message: reason, }}, } err := u.facade.FacadeCall("SetUpgradeSeriesUnitStatus", args, &results) if err != nil { return err } if len(results.Results) != 1 { return errors.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return result.Error } return nil }
[ "func", "(", "u", "*", "UpgradeSeriesAPI", ")", "SetUpgradeSeriesUnitStatus", "(", "status", "model", ".", "UpgradeSeriesStatus", ",", "reason", "string", ")", "error", "{", "var", "results", "params", ".", "ErrorResults", "\n", "args", ":=", "params", ".", "UpgradeSeriesStatusParams", "{", "Params", ":", "[", "]", "params", ".", "UpgradeSeriesStatusParam", "{", "{", "Entity", ":", "params", ".", "Entity", "{", "Tag", ":", "u", ".", "tag", ".", "String", "(", ")", "}", ",", "Status", ":", "status", ",", "Message", ":", "reason", ",", "}", "}", ",", "}", "\n", "err", ":=", "u", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "result", ".", "Error", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetUpgradeSeriesUnitStatus sets the upgrade series status of the // unit in the remote state.
[ "SetUpgradeSeriesUnitStatus", "sets", "the", "upgrade", "series", "status", "of", "the", "unit", "in", "the", "remote", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/common/upgradeseries.go#L84-L105
156,820
juju/juju
worker/logforwarder/tracker.go
OpenTrackingSink
func OpenTrackingSink(args TrackingSinkArgs) (*LogSink, error) { sink, err := args.OpenSink(args.Config) if err != nil { return nil, errors.Trace(err) } return &LogSink{ &trackingSender{ SendCloser: sink, tracker: newLastSentTracker(args.Name, args.Caller), }, }, nil }
go
func OpenTrackingSink(args TrackingSinkArgs) (*LogSink, error) { sink, err := args.OpenSink(args.Config) if err != nil { return nil, errors.Trace(err) } return &LogSink{ &trackingSender{ SendCloser: sink, tracker: newLastSentTracker(args.Name, args.Caller), }, }, nil }
[ "func", "OpenTrackingSink", "(", "args", "TrackingSinkArgs", ")", "(", "*", "LogSink", ",", "error", ")", "{", "sink", ",", "err", ":=", "args", ".", "OpenSink", "(", "args", ".", "Config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "LogSink", "{", "&", "trackingSender", "{", "SendCloser", ":", "sink", ",", "tracker", ":", "newLastSentTracker", "(", "args", ".", "Name", ",", "args", ".", "Caller", ")", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// OpenTrackingSink opens a log record sender to use with a worker. // The sender also tracks records that were successfully sent.
[ "OpenTrackingSink", "opens", "a", "log", "record", "sender", "to", "use", "with", "a", "worker", ".", "The", "sender", "also", "tracks", "records", "that", "were", "successfully", "sent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/logforwarder/tracker.go#L34-L46
156,821
juju/juju
worker/logforwarder/tracker.go
Send
func (s *trackingSender) Send(records []logfwd.Record) error { if err := s.SendCloser.Send(records); err != nil { return errors.Trace(err) } if err := s.tracker.setLastSent(records); err != nil { return errors.Trace(err) } return nil }
go
func (s *trackingSender) Send(records []logfwd.Record) error { if err := s.SendCloser.Send(records); err != nil { return errors.Trace(err) } if err := s.tracker.setLastSent(records); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "s", "*", "trackingSender", ")", "Send", "(", "records", "[", "]", "logfwd", ".", "Record", ")", "error", "{", "if", "err", ":=", "s", ".", "SendCloser", ".", "Send", "(", "records", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "s", ".", "tracker", ".", "setLastSent", "(", "records", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Send implements Sender.
[ "Send", "implements", "Sender", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/logforwarder/tracker.go#L54-L62
156,822
juju/juju
environs/simplestreams/datasource.go
NewURLDataSource
func NewURLDataSource(description, baseURL string, hostnameVerification utils.SSLHostnameVerification, priority int, requireSigned bool) DataSource { return &urlDataSource{ description: description, baseURL: baseURL, hostnameVerification: hostnameVerification, priority: priority, requireSigned: requireSigned, } }
go
func NewURLDataSource(description, baseURL string, hostnameVerification utils.SSLHostnameVerification, priority int, requireSigned bool) DataSource { return &urlDataSource{ description: description, baseURL: baseURL, hostnameVerification: hostnameVerification, priority: priority, requireSigned: requireSigned, } }
[ "func", "NewURLDataSource", "(", "description", ",", "baseURL", "string", ",", "hostnameVerification", "utils", ".", "SSLHostnameVerification", ",", "priority", "int", ",", "requireSigned", "bool", ")", "DataSource", "{", "return", "&", "urlDataSource", "{", "description", ":", "description", ",", "baseURL", ":", "baseURL", ",", "hostnameVerification", ":", "hostnameVerification", ",", "priority", ":", "priority", ",", "requireSigned", ":", "requireSigned", ",", "}", "\n", "}" ]
// NewURLDataSource returns a new datasource reading from the specified baseURL.
[ "NewURLDataSource", "returns", "a", "new", "datasource", "reading", "from", "the", "specified", "baseURL", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/simplestreams/datasource.go#L77-L85
156,823
juju/juju
environs/simplestreams/datasource.go
NewURLSignedDataSource
func NewURLSignedDataSource(description, baseURL, publicKey string, hostnameVerification utils.SSLHostnameVerification, priority int, requireSigned bool) DataSource { return &urlDataSource{ description: description, baseURL: baseURL, publicSigningKey: publicKey, hostnameVerification: hostnameVerification, priority: priority, requireSigned: requireSigned, } }
go
func NewURLSignedDataSource(description, baseURL, publicKey string, hostnameVerification utils.SSLHostnameVerification, priority int, requireSigned bool) DataSource { return &urlDataSource{ description: description, baseURL: baseURL, publicSigningKey: publicKey, hostnameVerification: hostnameVerification, priority: priority, requireSigned: requireSigned, } }
[ "func", "NewURLSignedDataSource", "(", "description", ",", "baseURL", ",", "publicKey", "string", ",", "hostnameVerification", "utils", ".", "SSLHostnameVerification", ",", "priority", "int", ",", "requireSigned", "bool", ")", "DataSource", "{", "return", "&", "urlDataSource", "{", "description", ":", "description", ",", "baseURL", ":", "baseURL", ",", "publicSigningKey", ":", "publicKey", ",", "hostnameVerification", ":", "hostnameVerification", ",", "priority", ":", "priority", ",", "requireSigned", ":", "requireSigned", ",", "}", "\n", "}" ]
// NewURLSignedDataSource returns a new datasource for signed metadata reading from the specified baseURL.
[ "NewURLSignedDataSource", "returns", "a", "new", "datasource", "for", "signed", "metadata", "reading", "from", "the", "specified", "baseURL", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/simplestreams/datasource.go#L88-L97
156,824
juju/juju
apiserver/logsink/logsink.go
NewHTTPHandler
func NewHTTPHandler( newLogWriteCloser NewLogWriteCloserFunc, abort <-chan struct{}, ratelimit *RateLimitConfig, metrics MetricsCollector, modelUUID string, ) http.Handler { return &logSinkHandler{ newLogWriteCloser: newLogWriteCloser, abort: abort, ratelimit: ratelimit, newStopChannel: func() (chan struct{}, func()) { ch := make(chan struct{}) return ch, func() { close(ch) } }, metrics: metrics, modelUUID: modelUUID, } }
go
func NewHTTPHandler( newLogWriteCloser NewLogWriteCloserFunc, abort <-chan struct{}, ratelimit *RateLimitConfig, metrics MetricsCollector, modelUUID string, ) http.Handler { return &logSinkHandler{ newLogWriteCloser: newLogWriteCloser, abort: abort, ratelimit: ratelimit, newStopChannel: func() (chan struct{}, func()) { ch := make(chan struct{}) return ch, func() { close(ch) } }, metrics: metrics, modelUUID: modelUUID, } }
[ "func", "NewHTTPHandler", "(", "newLogWriteCloser", "NewLogWriteCloserFunc", ",", "abort", "<-", "chan", "struct", "{", "}", ",", "ratelimit", "*", "RateLimitConfig", ",", "metrics", "MetricsCollector", ",", "modelUUID", "string", ",", ")", "http", ".", "Handler", "{", "return", "&", "logSinkHandler", "{", "newLogWriteCloser", ":", "newLogWriteCloser", ",", "abort", ":", "abort", ",", "ratelimit", ":", "ratelimit", ",", "newStopChannel", ":", "func", "(", ")", "(", "chan", "struct", "{", "}", ",", "func", "(", ")", ")", "{", "ch", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "return", "ch", ",", "func", "(", ")", "{", "close", "(", "ch", ")", "}", "\n", "}", ",", "metrics", ":", "metrics", ",", "modelUUID", ":", "modelUUID", ",", "}", "\n", "}" ]
// NewHTTPHandler returns a new http.Handler for receiving log messages over a // websocket, using the given NewLogWriteCloserFunc to obtain a writer to which // the log messages will be written. // // ratelimit defines an optional rate-limit configuration. If nil, no rate- // limiting will be applied.
[ "NewHTTPHandler", "returns", "a", "new", "http", ".", "Handler", "for", "receiving", "log", "messages", "over", "a", "websocket", "using", "the", "given", "NewLogWriteCloserFunc", "to", "obtain", "a", "writer", "to", "which", "the", "log", "messages", "will", "be", "written", ".", "ratelimit", "defines", "an", "optional", "rate", "-", "limit", "configuration", ".", "If", "nil", "no", "rate", "-", "limiting", "will", "be", "applied", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/logsink/logsink.go#L119-L137
156,825
juju/juju
apiserver/logsink/logsink.go
sendError
func (h *logSinkHandler) sendError(ws *websocket.Conn, req *http.Request, err error) { // There is no need to log the error for normal operators as there is nothing // they can action. This is for developers. if err != nil && featureflag.Enabled(feature.DeveloperMode) { logger.Errorf("returning error from %s %s: %s", req.Method, req.URL.Path, errors.Details(err)) } h.mu.Lock() defer h.mu.Unlock() if sendErr := ws.SendInitialErrorV0(err); sendErr != nil { logger.Errorf("closing websocket, %v", err) ws.Close() } }
go
func (h *logSinkHandler) sendError(ws *websocket.Conn, req *http.Request, err error) { // There is no need to log the error for normal operators as there is nothing // they can action. This is for developers. if err != nil && featureflag.Enabled(feature.DeveloperMode) { logger.Errorf("returning error from %s %s: %s", req.Method, req.URL.Path, errors.Details(err)) } h.mu.Lock() defer h.mu.Unlock() if sendErr := ws.SendInitialErrorV0(err); sendErr != nil { logger.Errorf("closing websocket, %v", err) ws.Close() } }
[ "func", "(", "h", "*", "logSinkHandler", ")", "sendError", "(", "ws", "*", "websocket", ".", "Conn", ",", "req", "*", "http", ".", "Request", ",", "err", "error", ")", "{", "// There is no need to log the error for normal operators as there is nothing", "// they can action. This is for developers.", "if", "err", "!=", "nil", "&&", "featureflag", ".", "Enabled", "(", "feature", ".", "DeveloperMode", ")", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "req", ".", "Method", ",", "req", ".", "URL", ".", "Path", ",", "errors", ".", "Details", "(", "err", ")", ")", "\n", "}", "\n", "h", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "h", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "sendErr", ":=", "ws", ".", "SendInitialErrorV0", "(", "err", ")", ";", "sendErr", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "ws", ".", "Close", "(", ")", "\n", "}", "\n", "}" ]
// sendError sends a JSON-encoded error response.
[ "sendError", "sends", "a", "JSON", "-", "encoded", "error", "response", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/logsink/logsink.go#L363-L375
156,826
juju/juju
apiserver/logsink/logsink.go
JujuClientVersionFromRequest
func JujuClientVersionFromRequest(req *http.Request) (version.Number, error) { verStr := req.URL.Query().Get("jujuclientversion") if verStr == "" { return version.Zero, errors.New(`missing "jujuclientversion" in URL query`) } ver, err := version.Parse(verStr) if err != nil { return version.Zero, errors.Annotatef(err, "invalid jujuclientversion %q", verStr) } return ver, nil }
go
func JujuClientVersionFromRequest(req *http.Request) (version.Number, error) { verStr := req.URL.Query().Get("jujuclientversion") if verStr == "" { return version.Zero, errors.New(`missing "jujuclientversion" in URL query`) } ver, err := version.Parse(verStr) if err != nil { return version.Zero, errors.Annotatef(err, "invalid jujuclientversion %q", verStr) } return ver, nil }
[ "func", "JujuClientVersionFromRequest", "(", "req", "*", "http", ".", "Request", ")", "(", "version", ".", "Number", ",", "error", ")", "{", "verStr", ":=", "req", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "verStr", "==", "\"", "\"", "{", "return", "version", ".", "Zero", ",", "errors", ".", "New", "(", "`missing \"jujuclientversion\" in URL query`", ")", "\n", "}", "\n", "ver", ",", "err", ":=", "version", ".", "Parse", "(", "verStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "version", ".", "Zero", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "verStr", ")", "\n", "}", "\n", "return", "ver", ",", "nil", "\n", "}" ]
// JujuClientVersionFromRequest returns the Juju client version // number from the HTTP request.
[ "JujuClientVersionFromRequest", "returns", "the", "Juju", "client", "version", "number", "from", "the", "HTTP", "request", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/logsink/logsink.go#L379-L389
156,827
juju/juju
apiserver/logsink/logsink.go
Sleep
func (c ratelimitClock) Sleep(d time.Duration) { <-c.Clock.After(d) }
go
func (c ratelimitClock) Sleep(d time.Duration) { <-c.Clock.After(d) }
[ "func", "(", "c", "ratelimitClock", ")", "Sleep", "(", "d", "time", ".", "Duration", ")", "{", "<-", "c", ".", "Clock", ".", "After", "(", "d", ")", "\n", "}" ]
// Sleep is defined by the ratelimit.Clock interface.
[ "Sleep", "is", "defined", "by", "the", "ratelimit", ".", "Clock", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/logsink/logsink.go#L397-L399
156,828
juju/juju
worker/pruner/config.go
Validate
func (c *Config) Validate() error { if c.Facade == nil { return errors.New("missing Facade") } if c.Clock == nil { return errors.New("missing Clock") } return nil }
go
func (c *Config) Validate() error { if c.Facade == nil { return errors.New("missing Facade") } if c.Clock == nil { return errors.New("missing Clock") } return nil }
[ "func", "(", "c", "*", "Config", ")", "Validate", "(", ")", "error", "{", "if", "c", ".", "Facade", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "Clock", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate will err unless basic requirements for a valid // config are met.
[ "Validate", "will", "err", "unless", "basic", "requirements", "for", "a", "valid", "config", "are", "met", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/pruner/config.go#L22-L30
156,829
juju/juju
caas/containers.go
Validate
func (spec *PodSpec) Validate() error { for _, c := range spec.Containers { if err := c.Validate(); err != nil { return errors.Trace(err) } } for _, c := range spec.InitContainers { if err := c.Validate(); err != nil { return errors.Trace(err) } } if spec.ProviderPod != nil { return spec.ProviderPod.Validate() } return nil }
go
func (spec *PodSpec) Validate() error { for _, c := range spec.Containers { if err := c.Validate(); err != nil { return errors.Trace(err) } } for _, c := range spec.InitContainers { if err := c.Validate(); err != nil { return errors.Trace(err) } } if spec.ProviderPod != nil { return spec.ProviderPod.Validate() } return nil }
[ "func", "(", "spec", "*", "PodSpec", ")", "Validate", "(", ")", "error", "{", "for", "_", ",", "c", ":=", "range", "spec", ".", "Containers", "{", "if", "err", ":=", "c", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "spec", ".", "InitContainers", "{", "if", "err", ":=", "c", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "spec", ".", "ProviderPod", "!=", "nil", "{", "return", "spec", ".", "ProviderPod", ".", "Validate", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate returns an error if the spec is not valid.
[ "Validate", "returns", "an", "error", "if", "the", "spec", "is", "not", "valid", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/containers.go#L77-L92
156,830
juju/juju
caas/containers.go
Validate
func (spec *ContainerSpec) Validate() error { if spec.Name == "" { return errors.New("spec name is missing") } if spec.Image == "" && spec.ImageDetails.ImagePath == "" { return errors.New("spec image details is missing") } for _, fs := range spec.Files { if fs.Name == "" { return errors.New("file set name is missing") } if fs.MountPath == "" { return errors.Errorf("mount path is missing for file set %q", fs.Name) } } if spec.ProviderContainer != nil { return spec.ProviderContainer.Validate() } return nil }
go
func (spec *ContainerSpec) Validate() error { if spec.Name == "" { return errors.New("spec name is missing") } if spec.Image == "" && spec.ImageDetails.ImagePath == "" { return errors.New("spec image details is missing") } for _, fs := range spec.Files { if fs.Name == "" { return errors.New("file set name is missing") } if fs.MountPath == "" { return errors.Errorf("mount path is missing for file set %q", fs.Name) } } if spec.ProviderContainer != nil { return spec.ProviderContainer.Validate() } return nil }
[ "func", "(", "spec", "*", "ContainerSpec", ")", "Validate", "(", ")", "error", "{", "if", "spec", ".", "Name", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "spec", ".", "Image", "==", "\"", "\"", "&&", "spec", ".", "ImageDetails", ".", "ImagePath", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "fs", ":=", "range", "spec", ".", "Files", "{", "if", "fs", ".", "Name", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "fs", ".", "MountPath", "==", "\"", "\"", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "fs", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "if", "spec", ".", "ProviderContainer", "!=", "nil", "{", "return", "spec", ".", "ProviderContainer", ".", "Validate", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate is defined on ProviderContainer.
[ "Validate", "is", "defined", "on", "ProviderContainer", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/containers.go#L95-L114
156,831
juju/juju
storage/config.go
NewConfig
func NewConfig(name string, provider ProviderType, attrs map[string]interface{}) (*Config, error) { _, err := configChecker.Coerce(attrs, nil) if err != nil { return nil, errors.Annotate(err, "validating common storage config") } return &Config{ name: name, provider: provider, attrs: attrs, }, nil }
go
func NewConfig(name string, provider ProviderType, attrs map[string]interface{}) (*Config, error) { _, err := configChecker.Coerce(attrs, nil) if err != nil { return nil, errors.Annotate(err, "validating common storage config") } return &Config{ name: name, provider: provider, attrs: attrs, }, nil }
[ "func", "NewConfig", "(", "name", "string", ",", "provider", "ProviderType", ",", "attrs", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "*", "Config", ",", "error", ")", "{", "_", ",", "err", ":=", "configChecker", ".", "Coerce", "(", "attrs", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "Config", "{", "name", ":", "name", ",", "provider", ":", "provider", ",", "attrs", ":", "attrs", ",", "}", ",", "nil", "\n", "}" ]
// NewConfig creates a new Config for instantiating a storage source.
[ "NewConfig", "creates", "a", "new", "Config", "for", "instantiating", "a", "storage", "source", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/config.go#L39-L49
156,832
juju/juju
storage/config.go
Attrs
func (c *Config) Attrs() map[string]interface{} { if c.attrs == nil { return nil } attrs := make(map[string]interface{}) for k, v := range c.attrs { attrs[k] = v } return attrs }
go
func (c *Config) Attrs() map[string]interface{} { if c.attrs == nil { return nil } attrs := make(map[string]interface{}) for k, v := range c.attrs { attrs[k] = v } return attrs }
[ "func", "(", "c", "*", "Config", ")", "Attrs", "(", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "if", "c", ".", "attrs", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "attrs", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "for", "k", ",", "v", ":=", "range", "c", ".", "attrs", "{", "attrs", "[", "k", "]", "=", "v", "\n", "}", "\n", "return", "attrs", "\n", "}" ]
// Attrs returns the configuration attributes for a storage source.
[ "Attrs", "returns", "the", "configuration", "attributes", "for", "a", "storage", "source", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/config.go#L63-L72
156,833
juju/juju
storage/config.go
ValueString
func (c *Config) ValueString(name string) (string, bool) { v, ok := c.attrs[name].(string) return v, ok }
go
func (c *Config) ValueString(name string) (string, bool) { v, ok := c.attrs[name].(string) return v, ok }
[ "func", "(", "c", "*", "Config", ")", "ValueString", "(", "name", "string", ")", "(", "string", ",", "bool", ")", "{", "v", ",", "ok", ":=", "c", ".", "attrs", "[", "name", "]", ".", "(", "string", ")", "\n", "return", "v", ",", "ok", "\n", "}" ]
// ValueString returns the named config attribute as a string.
[ "ValueString", "returns", "the", "named", "config", "attribute", "as", "a", "string", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/config.go#L75-L78
156,834
juju/juju
apiserver/observer/recorder.go
NewRecorderFactory
func NewRecorderFactory( observerFactory rpc.ObserverFactory, recorder *auditlog.Recorder, captureArgs bool, ) rpc.RecorderFactory { return func() rpc.Recorder { return &combinedRecorder{ observer: observerFactory.RPCObserver(), recorder: recorder, captureArgs: captureArgs, } } }
go
func NewRecorderFactory( observerFactory rpc.ObserverFactory, recorder *auditlog.Recorder, captureArgs bool, ) rpc.RecorderFactory { return func() rpc.Recorder { return &combinedRecorder{ observer: observerFactory.RPCObserver(), recorder: recorder, captureArgs: captureArgs, } } }
[ "func", "NewRecorderFactory", "(", "observerFactory", "rpc", ".", "ObserverFactory", ",", "recorder", "*", "auditlog", ".", "Recorder", ",", "captureArgs", "bool", ",", ")", "rpc", ".", "RecorderFactory", "{", "return", "func", "(", ")", "rpc", ".", "Recorder", "{", "return", "&", "combinedRecorder", "{", "observer", ":", "observerFactory", ".", "RPCObserver", "(", ")", ",", "recorder", ":", "recorder", ",", "captureArgs", ":", "captureArgs", ",", "}", "\n", "}", "\n", "}" ]
// NewRecorderFactory makes a new rpc.RecorderFactory to make // recorders that that will update the observer and the auditlog // recorder when it records a request or reply. The auditlog recorder // can be nil.
[ "NewRecorderFactory", "makes", "a", "new", "rpc", ".", "RecorderFactory", "to", "make", "recorders", "that", "that", "will", "update", "the", "observer", "and", "the", "auditlog", "recorder", "when", "it", "records", "a", "request", "or", "reply", ".", "The", "auditlog", "recorder", "can", "be", "nil", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/recorder.go#L30-L42
156,835
juju/juju
apiserver/observer/recorder.go
HandleRequest
func (cr *combinedRecorder) HandleRequest(hdr *rpc.Header, body interface{}) error { cr.observer.ServerRequest(hdr, body) if cr.recorder == nil { return nil } var args string if cr.captureArgs { jsonArgs, err := json.Marshal(body) if err != nil { return errors.Trace(err) } args = string(jsonArgs) } return errors.Trace(cr.recorder.AddRequest(auditlog.RequestArgs{ RequestID: hdr.RequestId, Facade: hdr.Request.Type, Method: hdr.Request.Action, Version: hdr.Request.Version, Args: args, })) }
go
func (cr *combinedRecorder) HandleRequest(hdr *rpc.Header, body interface{}) error { cr.observer.ServerRequest(hdr, body) if cr.recorder == nil { return nil } var args string if cr.captureArgs { jsonArgs, err := json.Marshal(body) if err != nil { return errors.Trace(err) } args = string(jsonArgs) } return errors.Trace(cr.recorder.AddRequest(auditlog.RequestArgs{ RequestID: hdr.RequestId, Facade: hdr.Request.Type, Method: hdr.Request.Action, Version: hdr.Request.Version, Args: args, })) }
[ "func", "(", "cr", "*", "combinedRecorder", ")", "HandleRequest", "(", "hdr", "*", "rpc", ".", "Header", ",", "body", "interface", "{", "}", ")", "error", "{", "cr", ".", "observer", ".", "ServerRequest", "(", "hdr", ",", "body", ")", "\n", "if", "cr", ".", "recorder", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "var", "args", "string", "\n", "if", "cr", ".", "captureArgs", "{", "jsonArgs", ",", "err", ":=", "json", ".", "Marshal", "(", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "args", "=", "string", "(", "jsonArgs", ")", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "cr", ".", "recorder", ".", "AddRequest", "(", "auditlog", ".", "RequestArgs", "{", "RequestID", ":", "hdr", ".", "RequestId", ",", "Facade", ":", "hdr", ".", "Request", ".", "Type", ",", "Method", ":", "hdr", ".", "Request", ".", "Action", ",", "Version", ":", "hdr", ".", "Request", ".", "Version", ",", "Args", ":", "args", ",", "}", ")", ")", "\n", "}" ]
// HandleRequest implements rpc.Recorder.
[ "HandleRequest", "implements", "rpc", ".", "Recorder", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/recorder.go#L53-L73
156,836
juju/juju
apiserver/observer/recorder.go
HandleReply
func (cr *combinedRecorder) HandleReply(req rpc.Request, replyHdr *rpc.Header, body interface{}) error { cr.observer.ServerReply(req, replyHdr, body) if cr.recorder == nil { return nil } var responseErrors []*auditlog.Error if replyHdr.Error == "" { responseErrors = extractErrors(body) } else { responseErrors = []*auditlog.Error{{ Message: replyHdr.Error, Code: replyHdr.ErrorCode, }} } return errors.Trace(cr.recorder.AddResponse(auditlog.ResponseErrorsArgs{ RequestID: replyHdr.RequestId, Errors: responseErrors, })) }
go
func (cr *combinedRecorder) HandleReply(req rpc.Request, replyHdr *rpc.Header, body interface{}) error { cr.observer.ServerReply(req, replyHdr, body) if cr.recorder == nil { return nil } var responseErrors []*auditlog.Error if replyHdr.Error == "" { responseErrors = extractErrors(body) } else { responseErrors = []*auditlog.Error{{ Message: replyHdr.Error, Code: replyHdr.ErrorCode, }} } return errors.Trace(cr.recorder.AddResponse(auditlog.ResponseErrorsArgs{ RequestID: replyHdr.RequestId, Errors: responseErrors, })) }
[ "func", "(", "cr", "*", "combinedRecorder", ")", "HandleReply", "(", "req", "rpc", ".", "Request", ",", "replyHdr", "*", "rpc", ".", "Header", ",", "body", "interface", "{", "}", ")", "error", "{", "cr", ".", "observer", ".", "ServerReply", "(", "req", ",", "replyHdr", ",", "body", ")", "\n", "if", "cr", ".", "recorder", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "var", "responseErrors", "[", "]", "*", "auditlog", ".", "Error", "\n", "if", "replyHdr", ".", "Error", "==", "\"", "\"", "{", "responseErrors", "=", "extractErrors", "(", "body", ")", "\n", "}", "else", "{", "responseErrors", "=", "[", "]", "*", "auditlog", ".", "Error", "{", "{", "Message", ":", "replyHdr", ".", "Error", ",", "Code", ":", "replyHdr", ".", "ErrorCode", ",", "}", "}", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "cr", ".", "recorder", ".", "AddResponse", "(", "auditlog", ".", "ResponseErrorsArgs", "{", "RequestID", ":", "replyHdr", ".", "RequestId", ",", "Errors", ":", "responseErrors", ",", "}", ")", ")", "\n", "}" ]
// HandleReply implements rpc.Recorder.
[ "HandleReply", "implements", "rpc", ".", "Recorder", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/recorder.go#L76-L94
156,837
juju/juju
worker/storageprovisioner/volume_events.go
volumesChanged
func volumesChanged(ctx *context, changes []string) error { tags := make([]names.Tag, len(changes)) for i, change := range changes { tags[i] = names.NewVolumeTag(change) } alive, dying, dead, err := storageEntityLife(ctx, tags) if err != nil { return errors.Trace(err) } logger.Debugf("volumes alive: %v, dying: %v, dead: %v", alive, dying, dead) if err := processDyingVolumes(ctx, dying); err != nil { return errors.Annotate(err, "processing dying volumes") } if len(alive)+len(dead) == 0 { return nil } // Get volume information for alive and dead volumes, so // we can provision/deprovision. volumeTags := make([]names.VolumeTag, 0, len(alive)+len(dead)) for _, tag := range alive { volumeTags = append(volumeTags, tag.(names.VolumeTag)) } for _, tag := range dead { volumeTags = append(volumeTags, tag.(names.VolumeTag)) } volumeResults, err := ctx.config.Volumes.Volumes(volumeTags) if err != nil { return errors.Annotatef(err, "getting volume information") } if err := processDeadVolumes(ctx, volumeTags[len(alive):], volumeResults[len(alive):]); err != nil { return errors.Annotate(err, "deprovisioning volumes") } if err := processAliveVolumes(ctx, alive, volumeResults[:len(alive)]); err != nil { return errors.Annotate(err, "provisioning volumes") } return nil }
go
func volumesChanged(ctx *context, changes []string) error { tags := make([]names.Tag, len(changes)) for i, change := range changes { tags[i] = names.NewVolumeTag(change) } alive, dying, dead, err := storageEntityLife(ctx, tags) if err != nil { return errors.Trace(err) } logger.Debugf("volumes alive: %v, dying: %v, dead: %v", alive, dying, dead) if err := processDyingVolumes(ctx, dying); err != nil { return errors.Annotate(err, "processing dying volumes") } if len(alive)+len(dead) == 0 { return nil } // Get volume information for alive and dead volumes, so // we can provision/deprovision. volumeTags := make([]names.VolumeTag, 0, len(alive)+len(dead)) for _, tag := range alive { volumeTags = append(volumeTags, tag.(names.VolumeTag)) } for _, tag := range dead { volumeTags = append(volumeTags, tag.(names.VolumeTag)) } volumeResults, err := ctx.config.Volumes.Volumes(volumeTags) if err != nil { return errors.Annotatef(err, "getting volume information") } if err := processDeadVolumes(ctx, volumeTags[len(alive):], volumeResults[len(alive):]); err != nil { return errors.Annotate(err, "deprovisioning volumes") } if err := processAliveVolumes(ctx, alive, volumeResults[:len(alive)]); err != nil { return errors.Annotate(err, "provisioning volumes") } return nil }
[ "func", "volumesChanged", "(", "ctx", "*", "context", ",", "changes", "[", "]", "string", ")", "error", "{", "tags", ":=", "make", "(", "[", "]", "names", ".", "Tag", ",", "len", "(", "changes", ")", ")", "\n", "for", "i", ",", "change", ":=", "range", "changes", "{", "tags", "[", "i", "]", "=", "names", ".", "NewVolumeTag", "(", "change", ")", "\n", "}", "\n", "alive", ",", "dying", ",", "dead", ",", "err", ":=", "storageEntityLife", "(", "ctx", ",", "tags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "alive", ",", "dying", ",", "dead", ")", "\n", "if", "err", ":=", "processDyingVolumes", "(", "ctx", ",", "dying", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "alive", ")", "+", "len", "(", "dead", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// Get volume information for alive and dead volumes, so", "// we can provision/deprovision.", "volumeTags", ":=", "make", "(", "[", "]", "names", ".", "VolumeTag", ",", "0", ",", "len", "(", "alive", ")", "+", "len", "(", "dead", ")", ")", "\n", "for", "_", ",", "tag", ":=", "range", "alive", "{", "volumeTags", "=", "append", "(", "volumeTags", ",", "tag", ".", "(", "names", ".", "VolumeTag", ")", ")", "\n", "}", "\n", "for", "_", ",", "tag", ":=", "range", "dead", "{", "volumeTags", "=", "append", "(", "volumeTags", ",", "tag", ".", "(", "names", ".", "VolumeTag", ")", ")", "\n", "}", "\n", "volumeResults", ",", "err", ":=", "ctx", ".", "config", ".", "Volumes", ".", "Volumes", "(", "volumeTags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "processDeadVolumes", "(", "ctx", ",", "volumeTags", "[", "len", "(", "alive", ")", ":", "]", ",", "volumeResults", "[", "len", "(", "alive", ")", ":", "]", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "processAliveVolumes", "(", "ctx", ",", "alive", ",", "volumeResults", "[", ":", "len", "(", "alive", ")", "]", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// volumesChanged is called when the lifecycle states of the volumes // with the provided IDs have been seen to have changed.
[ "volumesChanged", "is", "called", "when", "the", "lifecycle", "states", "of", "the", "volumes", "with", "the", "provided", "IDs", "have", "been", "seen", "to", "have", "changed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L19-L56
156,838
juju/juju
worker/storageprovisioner/volume_events.go
volumeAttachmentsChanged
func volumeAttachmentsChanged(ctx *context, watcherIds []watcher.MachineStorageId) error { ids := copyMachineStorageIds(watcherIds) alive, dying, dead, err := attachmentLife(ctx, ids) if err != nil { return errors.Trace(err) } logger.Debugf("volume attachments alive: %v, dying: %v, dead: %v", alive, dying, dead) if len(dead) != 0 { // We should not see dead volume attachments; // attachments go directly from Dying to removed. logger.Warningf("unexpected dead volume attachments: %v", dead) } if len(alive)+len(dying) == 0 { return nil } // Get volume information for alive and dying volume attachments, so // we can attach/detach. ids = append(alive, dying...) volumeAttachmentResults, err := ctx.config.Volumes.VolumeAttachments(ids) if err != nil { return errors.Annotatef(err, "getting volume attachment information") } // Deprovision Dying volume attachments. dyingVolumeAttachmentResults := volumeAttachmentResults[len(alive):] if err := processDyingVolumeAttachments(ctx, dying, dyingVolumeAttachmentResults); err != nil { return errors.Annotate(err, "deprovisioning volume attachments") } // Provision Alive volume attachments. aliveVolumeAttachmentResults := volumeAttachmentResults[:len(alive)] if err := processAliveVolumeAttachments(ctx, alive, aliveVolumeAttachmentResults); err != nil { return errors.Annotate(err, "provisioning volumes") } return nil }
go
func volumeAttachmentsChanged(ctx *context, watcherIds []watcher.MachineStorageId) error { ids := copyMachineStorageIds(watcherIds) alive, dying, dead, err := attachmentLife(ctx, ids) if err != nil { return errors.Trace(err) } logger.Debugf("volume attachments alive: %v, dying: %v, dead: %v", alive, dying, dead) if len(dead) != 0 { // We should not see dead volume attachments; // attachments go directly from Dying to removed. logger.Warningf("unexpected dead volume attachments: %v", dead) } if len(alive)+len(dying) == 0 { return nil } // Get volume information for alive and dying volume attachments, so // we can attach/detach. ids = append(alive, dying...) volumeAttachmentResults, err := ctx.config.Volumes.VolumeAttachments(ids) if err != nil { return errors.Annotatef(err, "getting volume attachment information") } // Deprovision Dying volume attachments. dyingVolumeAttachmentResults := volumeAttachmentResults[len(alive):] if err := processDyingVolumeAttachments(ctx, dying, dyingVolumeAttachmentResults); err != nil { return errors.Annotate(err, "deprovisioning volume attachments") } // Provision Alive volume attachments. aliveVolumeAttachmentResults := volumeAttachmentResults[:len(alive)] if err := processAliveVolumeAttachments(ctx, alive, aliveVolumeAttachmentResults); err != nil { return errors.Annotate(err, "provisioning volumes") } return nil }
[ "func", "volumeAttachmentsChanged", "(", "ctx", "*", "context", ",", "watcherIds", "[", "]", "watcher", ".", "MachineStorageId", ")", "error", "{", "ids", ":=", "copyMachineStorageIds", "(", "watcherIds", ")", "\n", "alive", ",", "dying", ",", "dead", ",", "err", ":=", "attachmentLife", "(", "ctx", ",", "ids", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "alive", ",", "dying", ",", "dead", ")", "\n", "if", "len", "(", "dead", ")", "!=", "0", "{", "// We should not see dead volume attachments;", "// attachments go directly from Dying to removed.", "logger", ".", "Warningf", "(", "\"", "\"", ",", "dead", ")", "\n", "}", "\n", "if", "len", "(", "alive", ")", "+", "len", "(", "dying", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// Get volume information for alive and dying volume attachments, so", "// we can attach/detach.", "ids", "=", "append", "(", "alive", ",", "dying", "...", ")", "\n", "volumeAttachmentResults", ",", "err", ":=", "ctx", ".", "config", ".", "Volumes", ".", "VolumeAttachments", "(", "ids", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Deprovision Dying volume attachments.", "dyingVolumeAttachmentResults", ":=", "volumeAttachmentResults", "[", "len", "(", "alive", ")", ":", "]", "\n", "if", "err", ":=", "processDyingVolumeAttachments", "(", "ctx", ",", "dying", ",", "dyingVolumeAttachmentResults", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Provision Alive volume attachments.", "aliveVolumeAttachmentResults", ":=", "volumeAttachmentResults", "[", ":", "len", "(", "alive", ")", "]", "\n", "if", "err", ":=", "processAliveVolumeAttachments", "(", "ctx", ",", "alive", ",", "aliveVolumeAttachmentResults", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// volumeAttachmentsChanged is called when the lifecycle states of the volume // attachments with the provided IDs have been seen to have changed.
[ "volumeAttachmentsChanged", "is", "called", "when", "the", "lifecycle", "states", "of", "the", "volume", "attachments", "with", "the", "provided", "IDs", "have", "been", "seen", "to", "have", "changed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L175-L212
156,839
juju/juju
worker/storageprovisioner/volume_events.go
processDyingVolumes
func processDyingVolumes(ctx *context, tags []names.Tag) error { if ctx.isApplicationKind() { // only care dead for application. return nil } for _, tag := range tags { removePendingVolume(ctx, tag.(names.VolumeTag)) } return nil }
go
func processDyingVolumes(ctx *context, tags []names.Tag) error { if ctx.isApplicationKind() { // only care dead for application. return nil } for _, tag := range tags { removePendingVolume(ctx, tag.(names.VolumeTag)) } return nil }
[ "func", "processDyingVolumes", "(", "ctx", "*", "context", ",", "tags", "[", "]", "names", ".", "Tag", ")", "error", "{", "if", "ctx", ".", "isApplicationKind", "(", ")", "{", "// only care dead for application.", "return", "nil", "\n", "}", "\n", "for", "_", ",", "tag", ":=", "range", "tags", "{", "removePendingVolume", "(", "ctx", ",", "tag", ".", "(", "names", ".", "VolumeTag", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// processDyingVolumes processes the VolumeResults for Dying volumes, // removing them from provisioning-pending as necessary.
[ "processDyingVolumes", "processes", "the", "VolumeResults", "for", "Dying", "volumes", "removing", "them", "from", "provisioning", "-", "pending", "as", "necessary", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L216-L225
156,840
juju/juju
worker/storageprovisioner/volume_events.go
updateVolume
func updateVolume(ctx *context, info storage.Volume) { ctx.volumes[info.Tag] = info for id, params := range ctx.incompleteVolumeAttachmentParams { if params.VolumeId == "" && id.AttachmentTag == info.Tag.String() { params.VolumeId = info.VolumeId updatePendingVolumeAttachment(ctx, id, params) } } }
go
func updateVolume(ctx *context, info storage.Volume) { ctx.volumes[info.Tag] = info for id, params := range ctx.incompleteVolumeAttachmentParams { if params.VolumeId == "" && id.AttachmentTag == info.Tag.String() { params.VolumeId = info.VolumeId updatePendingVolumeAttachment(ctx, id, params) } } }
[ "func", "updateVolume", "(", "ctx", "*", "context", ",", "info", "storage", ".", "Volume", ")", "{", "ctx", ".", "volumes", "[", "info", ".", "Tag", "]", "=", "info", "\n", "for", "id", ",", "params", ":=", "range", "ctx", ".", "incompleteVolumeAttachmentParams", "{", "if", "params", ".", "VolumeId", "==", "\"", "\"", "&&", "id", ".", "AttachmentTag", "==", "info", ".", "Tag", ".", "String", "(", ")", "{", "params", ".", "VolumeId", "=", "info", ".", "VolumeId", "\n", "updatePendingVolumeAttachment", "(", "ctx", ",", "id", ",", "params", ")", "\n", "}", "\n", "}", "\n", "}" ]
// updateVolume updates the context with the given volume info.
[ "updateVolume", "updates", "the", "context", "with", "the", "given", "volume", "info", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L228-L236
156,841
juju/juju
worker/storageprovisioner/volume_events.go
updatePendingVolume
func updatePendingVolume(ctx *context, params storage.VolumeParams) { if params.Attachment == nil { // NOTE(axw) this would only happen if the model is // in an incoherent state; we should never have an // alive, unprovisioned, and unattached volume. logger.Warningf( "%s is in an incoherent state, ignoring", names.ReadableString(params.Tag), ) return } if params.Attachment.InstanceId == "" { watchMachine(ctx, params.Attachment.Machine.(names.MachineTag)) ctx.incompleteVolumeParams[params.Tag] = params } else { delete(ctx.incompleteVolumeParams, params.Tag) scheduleOperations(ctx, &createVolumeOp{args: params}) } }
go
func updatePendingVolume(ctx *context, params storage.VolumeParams) { if params.Attachment == nil { // NOTE(axw) this would only happen if the model is // in an incoherent state; we should never have an // alive, unprovisioned, and unattached volume. logger.Warningf( "%s is in an incoherent state, ignoring", names.ReadableString(params.Tag), ) return } if params.Attachment.InstanceId == "" { watchMachine(ctx, params.Attachment.Machine.(names.MachineTag)) ctx.incompleteVolumeParams[params.Tag] = params } else { delete(ctx.incompleteVolumeParams, params.Tag) scheduleOperations(ctx, &createVolumeOp{args: params}) } }
[ "func", "updatePendingVolume", "(", "ctx", "*", "context", ",", "params", "storage", ".", "VolumeParams", ")", "{", "if", "params", ".", "Attachment", "==", "nil", "{", "// NOTE(axw) this would only happen if the model is", "// in an incoherent state; we should never have an", "// alive, unprovisioned, and unattached volume.", "logger", ".", "Warningf", "(", "\"", "\"", ",", "names", ".", "ReadableString", "(", "params", ".", "Tag", ")", ",", ")", "\n", "return", "\n", "}", "\n", "if", "params", ".", "Attachment", ".", "InstanceId", "==", "\"", "\"", "{", "watchMachine", "(", "ctx", ",", "params", ".", "Attachment", ".", "Machine", ".", "(", "names", ".", "MachineTag", ")", ")", "\n", "ctx", ".", "incompleteVolumeParams", "[", "params", ".", "Tag", "]", "=", "params", "\n", "}", "else", "{", "delete", "(", "ctx", ".", "incompleteVolumeParams", ",", "params", ".", "Tag", ")", "\n", "scheduleOperations", "(", "ctx", ",", "&", "createVolumeOp", "{", "args", ":", "params", "}", ")", "\n", "}", "\n", "}" ]
// updatePendingVolume adds the given volume params to either the incomplete // set or the schedule. If the params are incomplete due to a missing instance // ID, updatePendingVolume will request that the machine be watched so its // instance ID can be learned.
[ "updatePendingVolume", "adds", "the", "given", "volume", "params", "to", "either", "the", "incomplete", "set", "or", "the", "schedule", ".", "If", "the", "params", "are", "incomplete", "due", "to", "a", "missing", "instance", "ID", "updatePendingVolume", "will", "request", "that", "the", "machine", "be", "watched", "so", "its", "instance", "ID", "can", "be", "learned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L242-L260
156,842
juju/juju
worker/storageprovisioner/volume_events.go
updatePendingVolumeAttachment
func updatePendingVolumeAttachment( ctx *context, id params.MachineStorageId, params storage.VolumeAttachmentParams, ) { if params.InstanceId == "" { watchMachine(ctx, params.Machine.(names.MachineTag)) } else if params.VolumeId != "" { delete(ctx.incompleteVolumeAttachmentParams, id) scheduleOperations(ctx, &attachVolumeOp{args: params}) return } ctx.incompleteVolumeAttachmentParams[id] = params }
go
func updatePendingVolumeAttachment( ctx *context, id params.MachineStorageId, params storage.VolumeAttachmentParams, ) { if params.InstanceId == "" { watchMachine(ctx, params.Machine.(names.MachineTag)) } else if params.VolumeId != "" { delete(ctx.incompleteVolumeAttachmentParams, id) scheduleOperations(ctx, &attachVolumeOp{args: params}) return } ctx.incompleteVolumeAttachmentParams[id] = params }
[ "func", "updatePendingVolumeAttachment", "(", "ctx", "*", "context", ",", "id", "params", ".", "MachineStorageId", ",", "params", "storage", ".", "VolumeAttachmentParams", ",", ")", "{", "if", "params", ".", "InstanceId", "==", "\"", "\"", "{", "watchMachine", "(", "ctx", ",", "params", ".", "Machine", ".", "(", "names", ".", "MachineTag", ")", ")", "\n", "}", "else", "if", "params", ".", "VolumeId", "!=", "\"", "\"", "{", "delete", "(", "ctx", ".", "incompleteVolumeAttachmentParams", ",", "id", ")", "\n", "scheduleOperations", "(", "ctx", ",", "&", "attachVolumeOp", "{", "args", ":", "params", "}", ")", "\n", "return", "\n", "}", "\n", "ctx", ".", "incompleteVolumeAttachmentParams", "[", "id", "]", "=", "params", "\n", "}" ]
// updatePendingVolumeAttachment adds the given volume attachment params to // either the incomplete set or the schedule. If the params are incomplete // due to a missing instance ID, updatePendingVolumeAttachment will request // that the machine be watched so its instance ID can be learned.
[ "updatePendingVolumeAttachment", "adds", "the", "given", "volume", "attachment", "params", "to", "either", "the", "incomplete", "set", "or", "the", "schedule", ".", "If", "the", "params", "are", "incomplete", "due", "to", "a", "missing", "instance", "ID", "updatePendingVolumeAttachment", "will", "request", "that", "the", "machine", "be", "watched", "so", "its", "instance", "ID", "can", "be", "learned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L273-L286
156,843
juju/juju
worker/storageprovisioner/volume_events.go
processDeadVolumes
func processDeadVolumes(ctx *context, tags []names.VolumeTag, volumeResults []params.VolumeResult) error { for _, tag := range tags { removePendingVolume(ctx, tag) } var destroy []names.VolumeTag var remove []names.Tag for i, result := range volumeResults { tag := tags[i] if result.Error == nil { logger.Debugf("volume %s is provisioned, queuing for deprovisioning", tag.Id()) volume, err := volumeFromParams(result.Result) if err != nil { return errors.Annotate(err, "getting volume info") } updateVolume(ctx, volume) destroy = append(destroy, tag) continue } if params.IsCodeNotProvisioned(result.Error) { logger.Debugf("volume %s is not provisioned, queuing for removal", tag.Id()) remove = append(remove, tag) continue } return errors.Annotatef(result.Error, "getting volume information for volume %s", tag.Id()) } if len(destroy) > 0 { ops := make([]scheduleOp, len(destroy)) for i, tag := range destroy { ops[i] = &removeVolumeOp{tag: tag} } scheduleOperations(ctx, ops...) } if err := removeEntities(ctx, remove); err != nil { return errors.Annotate(err, "removing volumes from state") } return nil }
go
func processDeadVolumes(ctx *context, tags []names.VolumeTag, volumeResults []params.VolumeResult) error { for _, tag := range tags { removePendingVolume(ctx, tag) } var destroy []names.VolumeTag var remove []names.Tag for i, result := range volumeResults { tag := tags[i] if result.Error == nil { logger.Debugf("volume %s is provisioned, queuing for deprovisioning", tag.Id()) volume, err := volumeFromParams(result.Result) if err != nil { return errors.Annotate(err, "getting volume info") } updateVolume(ctx, volume) destroy = append(destroy, tag) continue } if params.IsCodeNotProvisioned(result.Error) { logger.Debugf("volume %s is not provisioned, queuing for removal", tag.Id()) remove = append(remove, tag) continue } return errors.Annotatef(result.Error, "getting volume information for volume %s", tag.Id()) } if len(destroy) > 0 { ops := make([]scheduleOp, len(destroy)) for i, tag := range destroy { ops[i] = &removeVolumeOp{tag: tag} } scheduleOperations(ctx, ops...) } if err := removeEntities(ctx, remove); err != nil { return errors.Annotate(err, "removing volumes from state") } return nil }
[ "func", "processDeadVolumes", "(", "ctx", "*", "context", ",", "tags", "[", "]", "names", ".", "VolumeTag", ",", "volumeResults", "[", "]", "params", ".", "VolumeResult", ")", "error", "{", "for", "_", ",", "tag", ":=", "range", "tags", "{", "removePendingVolume", "(", "ctx", ",", "tag", ")", "\n", "}", "\n", "var", "destroy", "[", "]", "names", ".", "VolumeTag", "\n", "var", "remove", "[", "]", "names", ".", "Tag", "\n", "for", "i", ",", "result", ":=", "range", "volumeResults", "{", "tag", ":=", "tags", "[", "i", "]", "\n", "if", "result", ".", "Error", "==", "nil", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "tag", ".", "Id", "(", ")", ")", "\n", "volume", ",", "err", ":=", "volumeFromParams", "(", "result", ".", "Result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "updateVolume", "(", "ctx", ",", "volume", ")", "\n", "destroy", "=", "append", "(", "destroy", ",", "tag", ")", "\n", "continue", "\n", "}", "\n", "if", "params", ".", "IsCodeNotProvisioned", "(", "result", ".", "Error", ")", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "tag", ".", "Id", "(", ")", ")", "\n", "remove", "=", "append", "(", "remove", ",", "tag", ")", "\n", "continue", "\n", "}", "\n", "return", "errors", ".", "Annotatef", "(", "result", ".", "Error", ",", "\"", "\"", ",", "tag", ".", "Id", "(", ")", ")", "\n", "}", "\n", "if", "len", "(", "destroy", ")", ">", "0", "{", "ops", ":=", "make", "(", "[", "]", "scheduleOp", ",", "len", "(", "destroy", ")", ")", "\n", "for", "i", ",", "tag", ":=", "range", "destroy", "{", "ops", "[", "i", "]", "=", "&", "removeVolumeOp", "{", "tag", ":", "tag", "}", "\n", "}", "\n", "scheduleOperations", "(", "ctx", ",", "ops", "...", ")", "\n", "}", "\n", "if", "err", ":=", "removeEntities", "(", "ctx", ",", "remove", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// processDeadVolumes processes the VolumeResults for Dead volumes, // deprovisioning volumes and removing from state as necessary.
[ "processDeadVolumes", "processes", "the", "VolumeResults", "for", "Dead", "volumes", "deprovisioning", "volumes", "and", "removing", "from", "state", "as", "necessary", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L298-L334
156,844
juju/juju
worker/storageprovisioner/volume_events.go
processDyingVolumeAttachments
func processDyingVolumeAttachments( ctx *context, ids []params.MachineStorageId, volumeAttachmentResults []params.VolumeAttachmentResult, ) error { for _, id := range ids { removePendingVolumeAttachment(ctx, id) } detach := make([]params.MachineStorageId, 0, len(ids)) remove := make([]params.MachineStorageId, 0, len(ids)) for i, result := range volumeAttachmentResults { id := ids[i] if result.Error == nil { detach = append(detach, id) continue } if params.IsCodeNotProvisioned(result.Error) { remove = append(remove, id) continue } return errors.Annotatef(result.Error, "getting information for volume attachment %v", id) } if len(detach) > 0 { attachmentParams, err := volumeAttachmentParams(ctx, detach) if err != nil { return errors.Trace(err) } ops := make([]scheduleOp, len(attachmentParams)) for i, p := range attachmentParams { ops[i] = &detachVolumeOp{args: p} } scheduleOperations(ctx, ops...) } if err := removeAttachments(ctx, remove); err != nil { return errors.Annotate(err, "removing attachments from state") } for _, id := range remove { delete(ctx.volumeAttachments, id) } return nil }
go
func processDyingVolumeAttachments( ctx *context, ids []params.MachineStorageId, volumeAttachmentResults []params.VolumeAttachmentResult, ) error { for _, id := range ids { removePendingVolumeAttachment(ctx, id) } detach := make([]params.MachineStorageId, 0, len(ids)) remove := make([]params.MachineStorageId, 0, len(ids)) for i, result := range volumeAttachmentResults { id := ids[i] if result.Error == nil { detach = append(detach, id) continue } if params.IsCodeNotProvisioned(result.Error) { remove = append(remove, id) continue } return errors.Annotatef(result.Error, "getting information for volume attachment %v", id) } if len(detach) > 0 { attachmentParams, err := volumeAttachmentParams(ctx, detach) if err != nil { return errors.Trace(err) } ops := make([]scheduleOp, len(attachmentParams)) for i, p := range attachmentParams { ops[i] = &detachVolumeOp{args: p} } scheduleOperations(ctx, ops...) } if err := removeAttachments(ctx, remove); err != nil { return errors.Annotate(err, "removing attachments from state") } for _, id := range remove { delete(ctx.volumeAttachments, id) } return nil }
[ "func", "processDyingVolumeAttachments", "(", "ctx", "*", "context", ",", "ids", "[", "]", "params", ".", "MachineStorageId", ",", "volumeAttachmentResults", "[", "]", "params", ".", "VolumeAttachmentResult", ",", ")", "error", "{", "for", "_", ",", "id", ":=", "range", "ids", "{", "removePendingVolumeAttachment", "(", "ctx", ",", "id", ")", "\n", "}", "\n", "detach", ":=", "make", "(", "[", "]", "params", ".", "MachineStorageId", ",", "0", ",", "len", "(", "ids", ")", ")", "\n", "remove", ":=", "make", "(", "[", "]", "params", ".", "MachineStorageId", ",", "0", ",", "len", "(", "ids", ")", ")", "\n", "for", "i", ",", "result", ":=", "range", "volumeAttachmentResults", "{", "id", ":=", "ids", "[", "i", "]", "\n", "if", "result", ".", "Error", "==", "nil", "{", "detach", "=", "append", "(", "detach", ",", "id", ")", "\n", "continue", "\n", "}", "\n", "if", "params", ".", "IsCodeNotProvisioned", "(", "result", ".", "Error", ")", "{", "remove", "=", "append", "(", "remove", ",", "id", ")", "\n", "continue", "\n", "}", "\n", "return", "errors", ".", "Annotatef", "(", "result", ".", "Error", ",", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "if", "len", "(", "detach", ")", ">", "0", "{", "attachmentParams", ",", "err", ":=", "volumeAttachmentParams", "(", "ctx", ",", "detach", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ops", ":=", "make", "(", "[", "]", "scheduleOp", ",", "len", "(", "attachmentParams", ")", ")", "\n", "for", "i", ",", "p", ":=", "range", "attachmentParams", "{", "ops", "[", "i", "]", "=", "&", "detachVolumeOp", "{", "args", ":", "p", "}", "\n", "}", "\n", "scheduleOperations", "(", "ctx", ",", "ops", "...", ")", "\n", "}", "\n", "if", "err", ":=", "removeAttachments", "(", "ctx", ",", "remove", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "id", ":=", "range", "remove", "{", "delete", "(", "ctx", ".", "volumeAttachments", ",", "id", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// processDyingVolumeAttachments processes the VolumeAttachmentResults for // Dying volume attachments, detaching volumes and updating state as necessary.
[ "processDyingVolumeAttachments", "processes", "the", "VolumeAttachmentResults", "for", "Dying", "volume", "attachments", "detaching", "volumes", "and", "updating", "state", "as", "necessary", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L338-L378
156,845
juju/juju
worker/storageprovisioner/volume_events.go
processAliveVolumes
func processAliveVolumes(ctx *context, tags []names.Tag, volumeResults []params.VolumeResult) error { if ctx.isApplicationKind() { // only care dead for application kind. return nil } // Filter out the already-provisioned volumes. pending := make([]names.VolumeTag, 0, len(tags)) for i, result := range volumeResults { volumeTag := tags[i].(names.VolumeTag) if result.Error == nil { // Volume is already provisioned: skip. logger.Debugf("volume %q is already provisioned, nothing to do", tags[i].Id()) volume, err := volumeFromParams(result.Result) if err != nil { return errors.Annotate(err, "getting volume info") } updateVolume(ctx, volume) removePendingVolume(ctx, volumeTag) continue } if !params.IsCodeNotProvisioned(result.Error) { return errors.Annotatef( result.Error, "getting volume information for volume %q", tags[i].Id(), ) } // The volume has not yet been provisioned, so record its tag // to enquire about parameters below. pending = append(pending, volumeTag) } if len(pending) == 0 { return nil } volumeParams, err := volumeParams(ctx, pending) if err != nil { return errors.Annotate(err, "getting volume params") } for _, params := range volumeParams { if params.Attachment != nil && params.Attachment.Machine.Kind() != names.MachineTagKind { logger.Debugf("not queuing volume for non-machine %v", params.Attachment.Machine) continue } updatePendingVolume(ctx, params) } return nil }
go
func processAliveVolumes(ctx *context, tags []names.Tag, volumeResults []params.VolumeResult) error { if ctx.isApplicationKind() { // only care dead for application kind. return nil } // Filter out the already-provisioned volumes. pending := make([]names.VolumeTag, 0, len(tags)) for i, result := range volumeResults { volumeTag := tags[i].(names.VolumeTag) if result.Error == nil { // Volume is already provisioned: skip. logger.Debugf("volume %q is already provisioned, nothing to do", tags[i].Id()) volume, err := volumeFromParams(result.Result) if err != nil { return errors.Annotate(err, "getting volume info") } updateVolume(ctx, volume) removePendingVolume(ctx, volumeTag) continue } if !params.IsCodeNotProvisioned(result.Error) { return errors.Annotatef( result.Error, "getting volume information for volume %q", tags[i].Id(), ) } // The volume has not yet been provisioned, so record its tag // to enquire about parameters below. pending = append(pending, volumeTag) } if len(pending) == 0 { return nil } volumeParams, err := volumeParams(ctx, pending) if err != nil { return errors.Annotate(err, "getting volume params") } for _, params := range volumeParams { if params.Attachment != nil && params.Attachment.Machine.Kind() != names.MachineTagKind { logger.Debugf("not queuing volume for non-machine %v", params.Attachment.Machine) continue } updatePendingVolume(ctx, params) } return nil }
[ "func", "processAliveVolumes", "(", "ctx", "*", "context", ",", "tags", "[", "]", "names", ".", "Tag", ",", "volumeResults", "[", "]", "params", ".", "VolumeResult", ")", "error", "{", "if", "ctx", ".", "isApplicationKind", "(", ")", "{", "// only care dead for application kind.", "return", "nil", "\n", "}", "\n\n", "// Filter out the already-provisioned volumes.", "pending", ":=", "make", "(", "[", "]", "names", ".", "VolumeTag", ",", "0", ",", "len", "(", "tags", ")", ")", "\n", "for", "i", ",", "result", ":=", "range", "volumeResults", "{", "volumeTag", ":=", "tags", "[", "i", "]", ".", "(", "names", ".", "VolumeTag", ")", "\n", "if", "result", ".", "Error", "==", "nil", "{", "// Volume is already provisioned: skip.", "logger", ".", "Debugf", "(", "\"", "\"", ",", "tags", "[", "i", "]", ".", "Id", "(", ")", ")", "\n", "volume", ",", "err", ":=", "volumeFromParams", "(", "result", ".", "Result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "updateVolume", "(", "ctx", ",", "volume", ")", "\n", "removePendingVolume", "(", "ctx", ",", "volumeTag", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "params", ".", "IsCodeNotProvisioned", "(", "result", ".", "Error", ")", "{", "return", "errors", ".", "Annotatef", "(", "result", ".", "Error", ",", "\"", "\"", ",", "tags", "[", "i", "]", ".", "Id", "(", ")", ",", ")", "\n", "}", "\n", "// The volume has not yet been provisioned, so record its tag", "// to enquire about parameters below.", "pending", "=", "append", "(", "pending", ",", "volumeTag", ")", "\n", "}", "\n", "if", "len", "(", "pending", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "volumeParams", ",", "err", ":=", "volumeParams", "(", "ctx", ",", "pending", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "params", ":=", "range", "volumeParams", "{", "if", "params", ".", "Attachment", "!=", "nil", "&&", "params", ".", "Attachment", ".", "Machine", ".", "Kind", "(", ")", "!=", "names", ".", "MachineTagKind", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "params", ".", "Attachment", ".", "Machine", ")", "\n", "continue", "\n", "}", "\n", "updatePendingVolume", "(", "ctx", ",", "params", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// processAliveVolumes processes the VolumeResults for Alive volumes, // provisioning volumes and setting the info in state as necessary.
[ "processAliveVolumes", "processes", "the", "VolumeResults", "for", "Alive", "volumes", "provisioning", "volumes", "and", "setting", "the", "info", "in", "state", "as", "necessary", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L382-L427
156,846
juju/juju
worker/storageprovisioner/volume_events.go
processAliveVolumeAttachments
func processAliveVolumeAttachments( ctx *context, ids []params.MachineStorageId, volumeAttachmentResults []params.VolumeAttachmentResult, ) error { // Filter out the already-attached. pending := make([]params.MachineStorageId, 0, len(ids)) for i, result := range volumeAttachmentResults { if result.Error == nil { // Volume attachment is already provisioned: if we // didn't (re)attach in this session, then we must // do so now. action := "nothing to do" if _, ok := ctx.volumeAttachments[ids[i]]; !ok { // Not yet (re)attached in this session. pending = append(pending, ids[i]) action = "will reattach" } logger.Debugf( "%s is already attached to %s, %s", ids[i].AttachmentTag, ids[i].MachineTag, action, ) removePendingVolumeAttachment(ctx, ids[i]) continue } if !params.IsCodeNotProvisioned(result.Error) { return errors.Annotatef( result.Error, "getting information for attachment %v", ids[i], ) } // The volume has not yet been provisioned, so record its tag // to enquire about parameters below. pending = append(pending, ids[i]) } if len(pending) == 0 { return nil } params, err := volumeAttachmentParams(ctx, pending) if err != nil { return errors.Trace(err) } for i, params := range params { if params.Machine.Kind() != names.MachineTagKind { logger.Debugf("not queuing volume attachment for non-machine %v", params.Machine) continue } if volume, ok := ctx.volumes[params.Volume]; ok { params.VolumeId = volume.VolumeId } updatePendingVolumeAttachment(ctx, pending[i], params) } return nil }
go
func processAliveVolumeAttachments( ctx *context, ids []params.MachineStorageId, volumeAttachmentResults []params.VolumeAttachmentResult, ) error { // Filter out the already-attached. pending := make([]params.MachineStorageId, 0, len(ids)) for i, result := range volumeAttachmentResults { if result.Error == nil { // Volume attachment is already provisioned: if we // didn't (re)attach in this session, then we must // do so now. action := "nothing to do" if _, ok := ctx.volumeAttachments[ids[i]]; !ok { // Not yet (re)attached in this session. pending = append(pending, ids[i]) action = "will reattach" } logger.Debugf( "%s is already attached to %s, %s", ids[i].AttachmentTag, ids[i].MachineTag, action, ) removePendingVolumeAttachment(ctx, ids[i]) continue } if !params.IsCodeNotProvisioned(result.Error) { return errors.Annotatef( result.Error, "getting information for attachment %v", ids[i], ) } // The volume has not yet been provisioned, so record its tag // to enquire about parameters below. pending = append(pending, ids[i]) } if len(pending) == 0 { return nil } params, err := volumeAttachmentParams(ctx, pending) if err != nil { return errors.Trace(err) } for i, params := range params { if params.Machine.Kind() != names.MachineTagKind { logger.Debugf("not queuing volume attachment for non-machine %v", params.Machine) continue } if volume, ok := ctx.volumes[params.Volume]; ok { params.VolumeId = volume.VolumeId } updatePendingVolumeAttachment(ctx, pending[i], params) } return nil }
[ "func", "processAliveVolumeAttachments", "(", "ctx", "*", "context", ",", "ids", "[", "]", "params", ".", "MachineStorageId", ",", "volumeAttachmentResults", "[", "]", "params", ".", "VolumeAttachmentResult", ",", ")", "error", "{", "// Filter out the already-attached.", "pending", ":=", "make", "(", "[", "]", "params", ".", "MachineStorageId", ",", "0", ",", "len", "(", "ids", ")", ")", "\n", "for", "i", ",", "result", ":=", "range", "volumeAttachmentResults", "{", "if", "result", ".", "Error", "==", "nil", "{", "// Volume attachment is already provisioned: if we", "// didn't (re)attach in this session, then we must", "// do so now.", "action", ":=", "\"", "\"", "\n", "if", "_", ",", "ok", ":=", "ctx", ".", "volumeAttachments", "[", "ids", "[", "i", "]", "]", ";", "!", "ok", "{", "// Not yet (re)attached in this session.", "pending", "=", "append", "(", "pending", ",", "ids", "[", "i", "]", ")", "\n", "action", "=", "\"", "\"", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "ids", "[", "i", "]", ".", "AttachmentTag", ",", "ids", "[", "i", "]", ".", "MachineTag", ",", "action", ",", ")", "\n", "removePendingVolumeAttachment", "(", "ctx", ",", "ids", "[", "i", "]", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "params", ".", "IsCodeNotProvisioned", "(", "result", ".", "Error", ")", "{", "return", "errors", ".", "Annotatef", "(", "result", ".", "Error", ",", "\"", "\"", ",", "ids", "[", "i", "]", ",", ")", "\n", "}", "\n", "// The volume has not yet been provisioned, so record its tag", "// to enquire about parameters below.", "pending", "=", "append", "(", "pending", ",", "ids", "[", "i", "]", ")", "\n", "}", "\n", "if", "len", "(", "pending", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "params", ",", "err", ":=", "volumeAttachmentParams", "(", "ctx", ",", "pending", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "i", ",", "params", ":=", "range", "params", "{", "if", "params", ".", "Machine", ".", "Kind", "(", ")", "!=", "names", ".", "MachineTagKind", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "params", ".", "Machine", ")", "\n", "continue", "\n", "}", "\n", "if", "volume", ",", "ok", ":=", "ctx", ".", "volumes", "[", "params", ".", "Volume", "]", ";", "ok", "{", "params", ".", "VolumeId", "=", "volume", ".", "VolumeId", "\n", "}", "\n", "updatePendingVolumeAttachment", "(", "ctx", ",", "pending", "[", "i", "]", ",", "params", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// processAliveVolumeAttachments processes the VolumeAttachmentResults // for Alive volume attachments, attaching volumes and setting the info // in state as necessary.
[ "processAliveVolumeAttachments", "processes", "the", "VolumeAttachmentResults", "for", "Alive", "volume", "attachments", "attaching", "volumes", "and", "setting", "the", "info", "in", "state", "as", "necessary", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L432-L484
156,847
juju/juju
worker/storageprovisioner/volume_events.go
volumeAttachmentParams
func volumeAttachmentParams( ctx *context, ids []params.MachineStorageId, ) ([]storage.VolumeAttachmentParams, error) { paramsResults, err := ctx.config.Volumes.VolumeAttachmentParams(ids) if err != nil { return nil, errors.Annotate(err, "getting volume attachment params") } attachmentParams := make([]storage.VolumeAttachmentParams, len(ids)) for i, result := range paramsResults { if result.Error != nil { return nil, errors.Annotate(result.Error, "getting volume attachment parameters") } params, err := volumeAttachmentParamsFromParams(result.Result) if err != nil { return nil, errors.Annotate(err, "getting volume attachment parameters") } attachmentParams[i] = params } return attachmentParams, nil }
go
func volumeAttachmentParams( ctx *context, ids []params.MachineStorageId, ) ([]storage.VolumeAttachmentParams, error) { paramsResults, err := ctx.config.Volumes.VolumeAttachmentParams(ids) if err != nil { return nil, errors.Annotate(err, "getting volume attachment params") } attachmentParams := make([]storage.VolumeAttachmentParams, len(ids)) for i, result := range paramsResults { if result.Error != nil { return nil, errors.Annotate(result.Error, "getting volume attachment parameters") } params, err := volumeAttachmentParamsFromParams(result.Result) if err != nil { return nil, errors.Annotate(err, "getting volume attachment parameters") } attachmentParams[i] = params } return attachmentParams, nil }
[ "func", "volumeAttachmentParams", "(", "ctx", "*", "context", ",", "ids", "[", "]", "params", ".", "MachineStorageId", ",", ")", "(", "[", "]", "storage", ".", "VolumeAttachmentParams", ",", "error", ")", "{", "paramsResults", ",", "err", ":=", "ctx", ".", "config", ".", "Volumes", ".", "VolumeAttachmentParams", "(", "ids", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "attachmentParams", ":=", "make", "(", "[", "]", "storage", ".", "VolumeAttachmentParams", ",", "len", "(", "ids", ")", ")", "\n", "for", "i", ",", "result", ":=", "range", "paramsResults", "{", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "result", ".", "Error", ",", "\"", "\"", ")", "\n", "}", "\n", "params", ",", "err", ":=", "volumeAttachmentParamsFromParams", "(", "result", ".", "Result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "attachmentParams", "[", "i", "]", "=", "params", "\n", "}", "\n", "return", "attachmentParams", ",", "nil", "\n", "}" ]
// volumeAttachmentParams obtains the specified attachments' parameters.
[ "volumeAttachmentParams", "obtains", "the", "specified", "attachments", "parameters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L487-L506
156,848
juju/juju
worker/storageprovisioner/volume_events.go
volumeParams
func volumeParams(ctx *context, tags []names.VolumeTag) ([]storage.VolumeParams, error) { paramsResults, err := ctx.config.Volumes.VolumeParams(tags) if err != nil { return nil, errors.Annotate(err, "getting volume params") } allParams := make([]storage.VolumeParams, len(tags)) for i, result := range paramsResults { if result.Error != nil { return nil, errors.Annotate(result.Error, "getting volume parameters") } params, err := volumeParamsFromParams(result.Result) if err != nil { return nil, errors.Annotate(err, "getting volume parameters") } allParams[i] = params } return allParams, nil }
go
func volumeParams(ctx *context, tags []names.VolumeTag) ([]storage.VolumeParams, error) { paramsResults, err := ctx.config.Volumes.VolumeParams(tags) if err != nil { return nil, errors.Annotate(err, "getting volume params") } allParams := make([]storage.VolumeParams, len(tags)) for i, result := range paramsResults { if result.Error != nil { return nil, errors.Annotate(result.Error, "getting volume parameters") } params, err := volumeParamsFromParams(result.Result) if err != nil { return nil, errors.Annotate(err, "getting volume parameters") } allParams[i] = params } return allParams, nil }
[ "func", "volumeParams", "(", "ctx", "*", "context", ",", "tags", "[", "]", "names", ".", "VolumeTag", ")", "(", "[", "]", "storage", ".", "VolumeParams", ",", "error", ")", "{", "paramsResults", ",", "err", ":=", "ctx", ".", "config", ".", "Volumes", ".", "VolumeParams", "(", "tags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "allParams", ":=", "make", "(", "[", "]", "storage", ".", "VolumeParams", ",", "len", "(", "tags", ")", ")", "\n", "for", "i", ",", "result", ":=", "range", "paramsResults", "{", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "result", ".", "Error", ",", "\"", "\"", ")", "\n", "}", "\n", "params", ",", "err", ":=", "volumeParamsFromParams", "(", "result", ".", "Result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "allParams", "[", "i", "]", "=", "params", "\n", "}", "\n", "return", "allParams", ",", "nil", "\n", "}" ]
// volumeParams obtains the specified volumes' parameters.
[ "volumeParams", "obtains", "the", "specified", "volumes", "parameters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L509-L526
156,849
juju/juju
worker/storageprovisioner/volume_events.go
removeVolumeParams
func removeVolumeParams(ctx *context, tags []names.VolumeTag) ([]params.RemoveVolumeParams, error) { paramsResults, err := ctx.config.Volumes.RemoveVolumeParams(tags) if err != nil { return nil, errors.Annotate(err, "getting volume params") } allParams := make([]params.RemoveVolumeParams, len(tags)) for i, result := range paramsResults { if result.Error != nil { return nil, errors.Annotate(result.Error, "getting volume removal parameters") } allParams[i] = result.Result } return allParams, nil }
go
func removeVolumeParams(ctx *context, tags []names.VolumeTag) ([]params.RemoveVolumeParams, error) { paramsResults, err := ctx.config.Volumes.RemoveVolumeParams(tags) if err != nil { return nil, errors.Annotate(err, "getting volume params") } allParams := make([]params.RemoveVolumeParams, len(tags)) for i, result := range paramsResults { if result.Error != nil { return nil, errors.Annotate(result.Error, "getting volume removal parameters") } allParams[i] = result.Result } return allParams, nil }
[ "func", "removeVolumeParams", "(", "ctx", "*", "context", ",", "tags", "[", "]", "names", ".", "VolumeTag", ")", "(", "[", "]", "params", ".", "RemoveVolumeParams", ",", "error", ")", "{", "paramsResults", ",", "err", ":=", "ctx", ".", "config", ".", "Volumes", ".", "RemoveVolumeParams", "(", "tags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "allParams", ":=", "make", "(", "[", "]", "params", ".", "RemoveVolumeParams", ",", "len", "(", "tags", ")", ")", "\n", "for", "i", ",", "result", ":=", "range", "paramsResults", "{", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "result", ".", "Error", ",", "\"", "\"", ")", "\n", "}", "\n", "allParams", "[", "i", "]", "=", "result", ".", "Result", "\n", "}", "\n", "return", "allParams", ",", "nil", "\n", "}" ]
// removeVolumeParams obtains the specified volumes' destruction parameters.
[ "removeVolumeParams", "obtains", "the", "specified", "volumes", "destruction", "parameters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_events.go#L529-L542
156,850
juju/juju
provider/rackspace/environ.go
StartInstance
func (e environ) StartInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) (*environs.StartInstanceResult, error) { osString, err := series.GetOSFromSeries(args.Tools.OneSeries()) if err != nil { return nil, errors.Trace(err) } fwmode := e.Config().FirewallMode() if osString == jujuos.Windows && fwmode != config.FwNone { return nil, errors.Errorf("rackspace provider doesn't support firewalls for windows instances") } r, err := e.Environ.StartInstance(ctx, args) if err != nil { return nil, errors.Trace(err) } if fwmode != config.FwNone { interrupted := make(chan os.Signal, 1) timeout := environs.BootstrapDialOpts{ Timeout: time.Minute * 5, RetryDelay: time.Second * 5, AddressesDelay: time.Second * 20, } addr, err := waitSSH( ioutil.Discard, interrupted, ssh.DefaultClient, common.GetCheckNonceCommand(args.InstanceConfig), &common.RefreshableInstance{r.Instance, e}, ctx, timeout, common.DefaultHostSSHOptions, ) if err != nil { return nil, errors.Trace(err) } client := newInstanceConfigurator(addr) apiPort := 0 if args.InstanceConfig.Controller != nil { apiPort = args.InstanceConfig.Controller.Config.APIPort() } err = client.DropAllPorts([]int{apiPort, 22}, addr) if err != nil { common.HandleCredentialError(IsAuthorisationFailure, err, ctx) return nil, errors.Trace(err) } } return r, nil }
go
func (e environ) StartInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) (*environs.StartInstanceResult, error) { osString, err := series.GetOSFromSeries(args.Tools.OneSeries()) if err != nil { return nil, errors.Trace(err) } fwmode := e.Config().FirewallMode() if osString == jujuos.Windows && fwmode != config.FwNone { return nil, errors.Errorf("rackspace provider doesn't support firewalls for windows instances") } r, err := e.Environ.StartInstance(ctx, args) if err != nil { return nil, errors.Trace(err) } if fwmode != config.FwNone { interrupted := make(chan os.Signal, 1) timeout := environs.BootstrapDialOpts{ Timeout: time.Minute * 5, RetryDelay: time.Second * 5, AddressesDelay: time.Second * 20, } addr, err := waitSSH( ioutil.Discard, interrupted, ssh.DefaultClient, common.GetCheckNonceCommand(args.InstanceConfig), &common.RefreshableInstance{r.Instance, e}, ctx, timeout, common.DefaultHostSSHOptions, ) if err != nil { return nil, errors.Trace(err) } client := newInstanceConfigurator(addr) apiPort := 0 if args.InstanceConfig.Controller != nil { apiPort = args.InstanceConfig.Controller.Config.APIPort() } err = client.DropAllPorts([]int{apiPort, 22}, addr) if err != nil { common.HandleCredentialError(IsAuthorisationFailure, err, ctx) return nil, errors.Trace(err) } } return r, nil }
[ "func", "(", "e", "environ", ")", "StartInstance", "(", "ctx", "context", ".", "ProviderCallContext", ",", "args", "environs", ".", "StartInstanceParams", ")", "(", "*", "environs", ".", "StartInstanceResult", ",", "error", ")", "{", "osString", ",", "err", ":=", "series", ".", "GetOSFromSeries", "(", "args", ".", "Tools", ".", "OneSeries", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "fwmode", ":=", "e", ".", "Config", "(", ")", ".", "FirewallMode", "(", ")", "\n", "if", "osString", "==", "jujuos", ".", "Windows", "&&", "fwmode", "!=", "config", ".", "FwNone", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n\n", "}", "\n", "r", ",", "err", ":=", "e", ".", "Environ", ".", "StartInstance", "(", "ctx", ",", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "fwmode", "!=", "config", ".", "FwNone", "{", "interrupted", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "timeout", ":=", "environs", ".", "BootstrapDialOpts", "{", "Timeout", ":", "time", ".", "Minute", "*", "5", ",", "RetryDelay", ":", "time", ".", "Second", "*", "5", ",", "AddressesDelay", ":", "time", ".", "Second", "*", "20", ",", "}", "\n", "addr", ",", "err", ":=", "waitSSH", "(", "ioutil", ".", "Discard", ",", "interrupted", ",", "ssh", ".", "DefaultClient", ",", "common", ".", "GetCheckNonceCommand", "(", "args", ".", "InstanceConfig", ")", ",", "&", "common", ".", "RefreshableInstance", "{", "r", ".", "Instance", ",", "e", "}", ",", "ctx", ",", "timeout", ",", "common", ".", "DefaultHostSSHOptions", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "client", ":=", "newInstanceConfigurator", "(", "addr", ")", "\n", "apiPort", ":=", "0", "\n", "if", "args", ".", "InstanceConfig", ".", "Controller", "!=", "nil", "{", "apiPort", "=", "args", ".", "InstanceConfig", ".", "Controller", ".", "Config", ".", "APIPort", "(", ")", "\n", "}", "\n", "err", "=", "client", ".", "DropAllPorts", "(", "[", "]", "int", "{", "apiPort", ",", "22", "}", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "common", ".", "HandleCredentialError", "(", "IsAuthorisationFailure", ",", "err", ",", "ctx", ")", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "r", ",", "nil", "\n", "}" ]
// StartInstance implements environs.Environ.
[ "StartInstance", "implements", "environs", ".", "Environ", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/rackspace/environ.go#L37-L83
156,851
juju/juju
cmd/plugins/juju-metadata/listimages.go
convertDetailsToInfo
func convertDetailsToInfo(details []params.CloudImageMetadata) ([]MetadataInfo, []string) { if len(details) == 0 { return nil, nil } info := make([]MetadataInfo, len(details)) errs := []string{} for i, one := range details { info[i] = MetadataInfo{ Source: one.Source, Series: one.Series, Arch: one.Arch, Region: one.Region, ImageId: one.ImageId, Stream: one.Stream, VirtType: one.VirtType, RootStorageType: one.RootStorageType, } } return info, errs }
go
func convertDetailsToInfo(details []params.CloudImageMetadata) ([]MetadataInfo, []string) { if len(details) == 0 { return nil, nil } info := make([]MetadataInfo, len(details)) errs := []string{} for i, one := range details { info[i] = MetadataInfo{ Source: one.Source, Series: one.Series, Arch: one.Arch, Region: one.Region, ImageId: one.ImageId, Stream: one.Stream, VirtType: one.VirtType, RootStorageType: one.RootStorageType, } } return info, errs }
[ "func", "convertDetailsToInfo", "(", "details", "[", "]", "params", ".", "CloudImageMetadata", ")", "(", "[", "]", "MetadataInfo", ",", "[", "]", "string", ")", "{", "if", "len", "(", "details", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "info", ":=", "make", "(", "[", "]", "MetadataInfo", ",", "len", "(", "details", ")", ")", "\n", "errs", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ",", "one", ":=", "range", "details", "{", "info", "[", "i", "]", "=", "MetadataInfo", "{", "Source", ":", "one", ".", "Source", ",", "Series", ":", "one", ".", "Series", ",", "Arch", ":", "one", ".", "Arch", ",", "Region", ":", "one", ".", "Region", ",", "ImageId", ":", "one", ".", "ImageId", ",", "Stream", ":", "one", ".", "Stream", ",", "VirtType", ":", "one", ".", "VirtType", ",", "RootStorageType", ":", "one", ".", "RootStorageType", ",", "}", "\n", "}", "\n", "return", "info", ",", "errs", "\n", "}" ]
// convertDetailsToInfo converts cloud image metadata received from api to // structure native to CLI. // We also return a list of errors for versions we could not convert to series for user friendly read.
[ "convertDetailsToInfo", "converts", "cloud", "image", "metadata", "received", "from", "api", "to", "structure", "native", "to", "CLI", ".", "We", "also", "return", "a", "list", "of", "errors", "for", "versions", "we", "could", "not", "convert", "to", "series", "for", "user", "friendly", "read", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/plugins/juju-metadata/listimages.go#L164-L184
156,852
juju/juju
cmd/plugins/juju-metadata/listimages.go
Less
func (m metadataInfos) Less(i, j int) bool { if m[i].Source != m[j].Source { // Alphabetical order here is incidentally does what we want: // we want "custom" metadata to precede // "public" metadata. // This may need to b revisited if more meatadata sources will be discovered. return m[i].Source < m[j].Source } if m[i].Series != m[j].Series { // reverse order return m[i].Series > m[j].Series } if m[i].Arch != m[j].Arch { // alphabetical order return m[i].Arch < m[j].Arch } // alphabetical order return m[i].Region < m[j].Region }
go
func (m metadataInfos) Less(i, j int) bool { if m[i].Source != m[j].Source { // Alphabetical order here is incidentally does what we want: // we want "custom" metadata to precede // "public" metadata. // This may need to b revisited if more meatadata sources will be discovered. return m[i].Source < m[j].Source } if m[i].Series != m[j].Series { // reverse order return m[i].Series > m[j].Series } if m[i].Arch != m[j].Arch { // alphabetical order return m[i].Arch < m[j].Arch } // alphabetical order return m[i].Region < m[j].Region }
[ "func", "(", "m", "metadataInfos", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "if", "m", "[", "i", "]", ".", "Source", "!=", "m", "[", "j", "]", ".", "Source", "{", "// Alphabetical order here is incidentally does what we want:", "// we want \"custom\" metadata to precede", "// \"public\" metadata.", "// This may need to b revisited if more meatadata sources will be discovered.", "return", "m", "[", "i", "]", ".", "Source", "<", "m", "[", "j", "]", ".", "Source", "\n", "}", "\n", "if", "m", "[", "i", "]", ".", "Series", "!=", "m", "[", "j", "]", ".", "Series", "{", "// reverse order", "return", "m", "[", "i", "]", ".", "Series", ">", "m", "[", "j", "]", ".", "Series", "\n", "}", "\n", "if", "m", "[", "i", "]", ".", "Arch", "!=", "m", "[", "j", "]", ".", "Arch", "{", "// alphabetical order", "return", "m", "[", "i", "]", ".", "Arch", "<", "m", "[", "j", "]", ".", "Arch", "\n", "}", "\n", "// alphabetical order", "return", "m", "[", "i", "]", ".", "Region", "<", "m", "[", "j", "]", ".", "Region", "\n", "}" ]
// Implements sort.Interface and sort image metadata // by source, series, arch and region. // All properties are sorted in alphabetical order // except for series which is reversed - // latest series are at the beginning of the collection.
[ "Implements", "sort", ".", "Interface", "and", "sort", "image", "metadata", "by", "source", "series", "arch", "and", "region", ".", "All", "properties", "are", "sorted", "in", "alphabetical", "order", "except", "for", "series", "which", "is", "reversed", "-", "latest", "series", "are", "at", "the", "beginning", "of", "the", "collection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/plugins/juju-metadata/listimages.go#L200-L218
156,853
juju/juju
cmd/plugins/juju-metadata/listimages.go
groupMetadata
func groupMetadata(metadata []MetadataInfo) map[string]map[string]map[string]map[string][]minMetadataInfo { result := map[string]map[string]map[string]map[string][]minMetadataInfo{} for _, m := range metadata { sourceMap, ok := result[m.Source] if !ok { sourceMap = map[string]map[string]map[string][]minMetadataInfo{} result[m.Source] = sourceMap } seriesMap, ok := sourceMap[m.Series] if !ok { seriesMap = map[string]map[string][]minMetadataInfo{} sourceMap[m.Series] = seriesMap } archMap, ok := seriesMap[m.Arch] if !ok { archMap = map[string][]minMetadataInfo{} seriesMap[m.Arch] = archMap } archMap[m.Region] = append(archMap[m.Region], minMetadataInfo{m.ImageId, m.Stream, m.VirtType, m.RootStorageType}) } return result }
go
func groupMetadata(metadata []MetadataInfo) map[string]map[string]map[string]map[string][]minMetadataInfo { result := map[string]map[string]map[string]map[string][]minMetadataInfo{} for _, m := range metadata { sourceMap, ok := result[m.Source] if !ok { sourceMap = map[string]map[string]map[string][]minMetadataInfo{} result[m.Source] = sourceMap } seriesMap, ok := sourceMap[m.Series] if !ok { seriesMap = map[string]map[string][]minMetadataInfo{} sourceMap[m.Series] = seriesMap } archMap, ok := seriesMap[m.Arch] if !ok { archMap = map[string][]minMetadataInfo{} seriesMap[m.Arch] = archMap } archMap[m.Region] = append(archMap[m.Region], minMetadataInfo{m.ImageId, m.Stream, m.VirtType, m.RootStorageType}) } return result }
[ "func", "groupMetadata", "(", "metadata", "[", "]", "MetadataInfo", ")", "map", "[", "string", "]", "map", "[", "string", "]", "map", "[", "string", "]", "map", "[", "string", "]", "[", "]", "minMetadataInfo", "{", "result", ":=", "map", "[", "string", "]", "map", "[", "string", "]", "map", "[", "string", "]", "map", "[", "string", "]", "[", "]", "minMetadataInfo", "{", "}", "\n\n", "for", "_", ",", "m", ":=", "range", "metadata", "{", "sourceMap", ",", "ok", ":=", "result", "[", "m", ".", "Source", "]", "\n", "if", "!", "ok", "{", "sourceMap", "=", "map", "[", "string", "]", "map", "[", "string", "]", "map", "[", "string", "]", "[", "]", "minMetadataInfo", "{", "}", "\n", "result", "[", "m", ".", "Source", "]", "=", "sourceMap", "\n", "}", "\n\n", "seriesMap", ",", "ok", ":=", "sourceMap", "[", "m", ".", "Series", "]", "\n", "if", "!", "ok", "{", "seriesMap", "=", "map", "[", "string", "]", "map", "[", "string", "]", "[", "]", "minMetadataInfo", "{", "}", "\n", "sourceMap", "[", "m", ".", "Series", "]", "=", "seriesMap", "\n", "}", "\n\n", "archMap", ",", "ok", ":=", "seriesMap", "[", "m", ".", "Arch", "]", "\n", "if", "!", "ok", "{", "archMap", "=", "map", "[", "string", "]", "[", "]", "minMetadataInfo", "{", "}", "\n", "seriesMap", "[", "m", ".", "Arch", "]", "=", "archMap", "\n", "}", "\n\n", "archMap", "[", "m", ".", "Region", "]", "=", "append", "(", "archMap", "[", "m", ".", "Region", "]", ",", "minMetadataInfo", "{", "m", ".", "ImageId", ",", "m", ".", "Stream", ",", "m", ".", "VirtType", ",", "m", ".", "RootStorageType", "}", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// groupMetadata constructs map representation of metadata // grouping individual items by source, series, arch and region // to be served to Yaml and JSON output for readability.
[ "groupMetadata", "constructs", "map", "representation", "of", "metadata", "grouping", "individual", "items", "by", "source", "series", "arch", "and", "region", "to", "be", "served", "to", "Yaml", "and", "JSON", "output", "for", "readability", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/plugins/juju-metadata/listimages.go#L235-L261
156,854
juju/juju
apiserver/common/remove.go
NewRemover
func NewRemover(st state.EntityFinder, callEnsureDead bool, getCanModify GetAuthFunc) *Remover { return &Remover{ st: st, callEnsureDead: callEnsureDead, getCanModify: getCanModify, } }
go
func NewRemover(st state.EntityFinder, callEnsureDead bool, getCanModify GetAuthFunc) *Remover { return &Remover{ st: st, callEnsureDead: callEnsureDead, getCanModify: getCanModify, } }
[ "func", "NewRemover", "(", "st", "state", ".", "EntityFinder", ",", "callEnsureDead", "bool", ",", "getCanModify", "GetAuthFunc", ")", "*", "Remover", "{", "return", "&", "Remover", "{", "st", ":", "st", ",", "callEnsureDead", ":", "callEnsureDead", ",", "getCanModify", ":", "getCanModify", ",", "}", "\n", "}" ]
// NewRemover returns a new Remover. The callEnsureDead flag specifies // whether EnsureDead should be called on an entity before // removing. The GetAuthFunc will be used on each invocation of Remove // to determine current permissions.
[ "NewRemover", "returns", "a", "new", "Remover", ".", "The", "callEnsureDead", "flag", "specifies", "whether", "EnsureDead", "should", "be", "called", "on", "an", "entity", "before", "removing", ".", "The", "GetAuthFunc", "will", "be", "used", "on", "each", "invocation", "of", "Remove", "to", "determine", "current", "permissions", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/remove.go#L28-L34
156,855
juju/juju
apiserver/common/remove.go
Remove
func (r *Remover) Remove(args params.Entities) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Entities)), } if len(args.Entities) == 0 { return result, nil } canModify, err := r.getCanModify() if err != nil { return params.ErrorResults{}, errors.Trace(err) } for i, entity := range args.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { result.Results[i].Error = ServerError(ErrPerm) continue } err = ErrPerm if canModify(tag) { err = r.removeEntity(tag) } result.Results[i].Error = ServerError(err) } return result, nil }
go
func (r *Remover) Remove(args params.Entities) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Entities)), } if len(args.Entities) == 0 { return result, nil } canModify, err := r.getCanModify() if err != nil { return params.ErrorResults{}, errors.Trace(err) } for i, entity := range args.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { result.Results[i].Error = ServerError(ErrPerm) continue } err = ErrPerm if canModify(tag) { err = r.removeEntity(tag) } result.Results[i].Error = ServerError(err) } return result, nil }
[ "func", "(", "r", "*", "Remover", ")", "Remove", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "result", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "if", "len", "(", "args", ".", "Entities", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n", "canModify", ",", "err", ":=", "r", ".", "getCanModify", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "ServerError", "(", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "err", "=", "ErrPerm", "\n", "if", "canModify", "(", "tag", ")", "{", "err", "=", "r", ".", "removeEntity", "(", "tag", ")", "\n", "}", "\n", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Remove removes every given entity from state, calling EnsureDead // first, then Remove. It will fail if the entity is not present.
[ "Remove", "removes", "every", "given", "entity", "from", "state", "calling", "EnsureDead", "first", "then", "Remove", ".", "It", "will", "fail", "if", "the", "entity", "is", "not", "present", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/remove.go#L64-L88
156,856
juju/juju
apiserver/common/remove.go
MaxWait
func MaxWait(in *time.Duration) time.Duration { if in != nil { return *in } return 1 * time.Minute }
go
func MaxWait(in *time.Duration) time.Duration { if in != nil { return *in } return 1 * time.Minute }
[ "func", "MaxWait", "(", "in", "*", "time", ".", "Duration", ")", "time", ".", "Duration", "{", "if", "in", "!=", "nil", "{", "return", "*", "in", "\n", "}", "\n", "return", "1", "*", "time", ".", "Minute", "\n", "}" ]
// MaxWait is how far in the future the backstop force cleanup will be scheduled. // Default is 1min if no value is provided.
[ "MaxWait", "is", "how", "far", "in", "the", "future", "the", "backstop", "force", "cleanup", "will", "be", "scheduled", ".", "Default", "is", "1min", "if", "no", "value", "is", "provided", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/remove.go#L92-L97
156,857
juju/juju
worker/uniter/relation/relationer.go
NewRelationer
func NewRelationer(ru *apiuniter.RelationUnit, dir *StateDir) *Relationer { return &Relationer{ ru: ru, dir: dir, } }
go
func NewRelationer(ru *apiuniter.RelationUnit, dir *StateDir) *Relationer { return &Relationer{ ru: ru, dir: dir, } }
[ "func", "NewRelationer", "(", "ru", "*", "apiuniter", ".", "RelationUnit", ",", "dir", "*", "StateDir", ")", "*", "Relationer", "{", "return", "&", "Relationer", "{", "ru", ":", "ru", ",", "dir", ":", "dir", ",", "}", "\n", "}" ]
// NewRelationer creates a new Relationer. The unit will not join the // relation until explicitly requested.
[ "NewRelationer", "creates", "a", "new", "Relationer", ".", "The", "unit", "will", "not", "join", "the", "relation", "until", "explicitly", "requested", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relationer.go#L26-L31
156,858
juju/juju
worker/uniter/relation/relationer.go
ContextInfo
func (r *Relationer) ContextInfo() *context.RelationInfo { members := r.dir.State().Members memberNames := make([]string, 0, len(members)) for memberName := range members { memberNames = append(memberNames, memberName) } return &context.RelationInfo{r.ru, memberNames} }
go
func (r *Relationer) ContextInfo() *context.RelationInfo { members := r.dir.State().Members memberNames := make([]string, 0, len(members)) for memberName := range members { memberNames = append(memberNames, memberName) } return &context.RelationInfo{r.ru, memberNames} }
[ "func", "(", "r", "*", "Relationer", ")", "ContextInfo", "(", ")", "*", "context", ".", "RelationInfo", "{", "members", ":=", "r", ".", "dir", ".", "State", "(", ")", ".", "Members", "\n", "memberNames", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "members", ")", ")", "\n", "for", "memberName", ":=", "range", "members", "{", "memberNames", "=", "append", "(", "memberNames", ",", "memberName", ")", "\n", "}", "\n", "return", "&", "context", ".", "RelationInfo", "{", "r", ".", "ru", ",", "memberNames", "}", "\n", "}" ]
// ContextInfo returns a representation of the Relationer's current state.
[ "ContextInfo", "returns", "a", "representation", "of", "the", "Relationer", "s", "current", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relationer.go#L34-L41
156,859
juju/juju
worker/uniter/relation/relationer.go
Join
func (r *Relationer) Join() error { if r.dying { panic("dying relationer must not join!") } // We need to make sure the state directory exists before we join the // relation, lest a subsequent ReadAllStateDirs report local state that // doesn't include relations recorded in remote state. if err := r.dir.Ensure(); err != nil { return err } // uniter.RelationUnit.EnterScope() sets the unit's private address // internally automatically, so no need to set it here. return r.ru.EnterScope() }
go
func (r *Relationer) Join() error { if r.dying { panic("dying relationer must not join!") } // We need to make sure the state directory exists before we join the // relation, lest a subsequent ReadAllStateDirs report local state that // doesn't include relations recorded in remote state. if err := r.dir.Ensure(); err != nil { return err } // uniter.RelationUnit.EnterScope() sets the unit's private address // internally automatically, so no need to set it here. return r.ru.EnterScope() }
[ "func", "(", "r", "*", "Relationer", ")", "Join", "(", ")", "error", "{", "if", "r", ".", "dying", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "// We need to make sure the state directory exists before we join the", "// relation, lest a subsequent ReadAllStateDirs report local state that", "// doesn't include relations recorded in remote state.", "if", "err", ":=", "r", ".", "dir", ".", "Ensure", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// uniter.RelationUnit.EnterScope() sets the unit's private address", "// internally automatically, so no need to set it here.", "return", "r", ".", "ru", ".", "EnterScope", "(", ")", "\n", "}" ]
// Join initializes local state and causes the unit to enter its relation // scope, allowing its counterpart units to detect its presence and settings // changes. Local state directory is not created until needed.
[ "Join", "initializes", "local", "state", "and", "causes", "the", "unit", "to", "enter", "its", "relation", "scope", "allowing", "its", "counterpart", "units", "to", "detect", "its", "presence", "and", "settings", "changes", ".", "Local", "state", "directory", "is", "not", "created", "until", "needed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relationer.go#L52-L65
156,860
juju/juju
worker/uniter/relation/relationer.go
SetDying
func (r *Relationer) SetDying() error { if r.IsImplicit() { r.dying = true return r.die() } r.dying = true return nil }
go
func (r *Relationer) SetDying() error { if r.IsImplicit() { r.dying = true return r.die() } r.dying = true return nil }
[ "func", "(", "r", "*", "Relationer", ")", "SetDying", "(", ")", "error", "{", "if", "r", ".", "IsImplicit", "(", ")", "{", "r", ".", "dying", "=", "true", "\n", "return", "r", ".", "die", "(", ")", "\n", "}", "\n", "r", ".", "dying", "=", "true", "\n", "return", "nil", "\n", "}" ]
// SetDying informs the relationer that the unit is departing the relation, // and that the only hooks it should send henceforth are -departed hooks, // until the relation is empty, followed by a -broken hook.
[ "SetDying", "informs", "the", "relationer", "that", "the", "unit", "is", "departing", "the", "relation", "and", "that", "the", "only", "hooks", "it", "should", "send", "henceforth", "are", "-", "departed", "hooks", "until", "the", "relation", "is", "empty", "followed", "by", "a", "-", "broken", "hook", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relationer.go#L70-L77
156,861
juju/juju
worker/uniter/relation/relationer.go
die
func (r *Relationer) die() error { if err := r.ru.LeaveScope(); err != nil { return errors.Annotatef(err, "leaving scope of relation %q", r.ru.Relation()) } return r.dir.Remove() }
go
func (r *Relationer) die() error { if err := r.ru.LeaveScope(); err != nil { return errors.Annotatef(err, "leaving scope of relation %q", r.ru.Relation()) } return r.dir.Remove() }
[ "func", "(", "r", "*", "Relationer", ")", "die", "(", ")", "error", "{", "if", "err", ":=", "r", ".", "ru", ".", "LeaveScope", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "r", ".", "ru", ".", "Relation", "(", ")", ")", "\n", "}", "\n", "return", "r", ".", "dir", ".", "Remove", "(", ")", "\n", "}" ]
// die is run when the relationer has no further responsibilities; it leaves // relation scope, and removes the local relation state directory.
[ "die", "is", "run", "when", "the", "relationer", "has", "no", "further", "responsibilities", ";", "it", "leaves", "relation", "scope", "and", "removes", "the", "local", "relation", "state", "directory", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relationer.go#L81-L86
156,862
juju/juju
worker/uniter/relation/relationer.go
PrepareHook
func (r *Relationer) PrepareHook(hi hook.Info) (hookName string, err error) { if r.IsImplicit() { panic("implicit relations must not run hooks") } if err = r.dir.State().Validate(hi); err != nil { return } name := r.ru.Endpoint().Name return fmt.Sprintf("%s-%s", name, hi.Kind), nil }
go
func (r *Relationer) PrepareHook(hi hook.Info) (hookName string, err error) { if r.IsImplicit() { panic("implicit relations must not run hooks") } if err = r.dir.State().Validate(hi); err != nil { return } name := r.ru.Endpoint().Name return fmt.Sprintf("%s-%s", name, hi.Kind), nil }
[ "func", "(", "r", "*", "Relationer", ")", "PrepareHook", "(", "hi", "hook", ".", "Info", ")", "(", "hookName", "string", ",", "err", "error", ")", "{", "if", "r", ".", "IsImplicit", "(", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "=", "r", ".", "dir", ".", "State", "(", ")", ".", "Validate", "(", "hi", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "name", ":=", "r", ".", "ru", ".", "Endpoint", "(", ")", ".", "Name", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ",", "hi", ".", "Kind", ")", ",", "nil", "\n", "}" ]
// PrepareHook checks that the relation is in a state such that it makes // sense to execute the supplied hook, and ensures that the relation context // contains the latest relation state as communicated in the hook.Info. It // returns the name of the hook that must be run.
[ "PrepareHook", "checks", "that", "the", "relation", "is", "in", "a", "state", "such", "that", "it", "makes", "sense", "to", "execute", "the", "supplied", "hook", "and", "ensures", "that", "the", "relation", "context", "contains", "the", "latest", "relation", "state", "as", "communicated", "in", "the", "hook", ".", "Info", ".", "It", "returns", "the", "name", "of", "the", "hook", "that", "must", "be", "run", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relationer.go#L92-L101
156,863
juju/juju
worker/uniter/relation/relationer.go
CommitHook
func (r *Relationer) CommitHook(hi hook.Info) error { if r.IsImplicit() { panic("implicit relations must not run hooks") } if hi.Kind == hooks.RelationBroken { return r.die() } return r.dir.Write(hi) }
go
func (r *Relationer) CommitHook(hi hook.Info) error { if r.IsImplicit() { panic("implicit relations must not run hooks") } if hi.Kind == hooks.RelationBroken { return r.die() } return r.dir.Write(hi) }
[ "func", "(", "r", "*", "Relationer", ")", "CommitHook", "(", "hi", "hook", ".", "Info", ")", "error", "{", "if", "r", ".", "IsImplicit", "(", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "hi", ".", "Kind", "==", "hooks", ".", "RelationBroken", "{", "return", "r", ".", "die", "(", ")", "\n", "}", "\n", "return", "r", ".", "dir", ".", "Write", "(", "hi", ")", "\n", "}" ]
// CommitHook persists the fact of the supplied hook's completion.
[ "CommitHook", "persists", "the", "fact", "of", "the", "supplied", "hook", "s", "completion", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relationer.go#L104-L112
156,864
juju/juju
apiserver/facades/client/sshclient/facade.go
PublicAddress
func (facade *Facade) PublicAddress(args params.Entities) (params.SSHAddressResults, error) { if err := facade.checkIsModelAdmin(); err != nil { return params.SSHAddressResults{}, errors.Trace(err) } getter := func(m SSHMachine) (network.Address, error) { return m.PublicAddress() } return facade.getAddressPerEntity(args, getter) }
go
func (facade *Facade) PublicAddress(args params.Entities) (params.SSHAddressResults, error) { if err := facade.checkIsModelAdmin(); err != nil { return params.SSHAddressResults{}, errors.Trace(err) } getter := func(m SSHMachine) (network.Address, error) { return m.PublicAddress() } return facade.getAddressPerEntity(args, getter) }
[ "func", "(", "facade", "*", "Facade", ")", "PublicAddress", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "SSHAddressResults", ",", "error", ")", "{", "if", "err", ":=", "facade", ".", "checkIsModelAdmin", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "SSHAddressResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "getter", ":=", "func", "(", "m", "SSHMachine", ")", "(", "network", ".", "Address", ",", "error", ")", "{", "return", "m", ".", "PublicAddress", "(", ")", "}", "\n", "return", "facade", ".", "getAddressPerEntity", "(", "args", ",", "getter", ")", "\n", "}" ]
// PublicAddress reports the preferred public network address for one // or more entities. Machines and units are suppored.
[ "PublicAddress", "reports", "the", "preferred", "public", "network", "address", "for", "one", "or", "more", "entities", ".", "Machines", "and", "units", "are", "suppored", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/sshclient/facade.go#L63-L70
156,865
juju/juju
apiserver/facades/client/sshclient/facade.go
PublicKeys
func (facade *Facade) PublicKeys(args params.Entities) (params.SSHPublicKeysResults, error) { if err := facade.checkIsModelAdmin(); err != nil { return params.SSHPublicKeysResults{}, errors.Trace(err) } out := params.SSHPublicKeysResults{ Results: make([]params.SSHPublicKeysResult, len(args.Entities)), } for i, entity := range args.Entities { machine, err := facade.backend.GetMachineForEntity(entity.Tag) if err != nil { out.Results[i].Error = common.ServerError(err) } else { keys, err := facade.backend.GetSSHHostKeys(machine.MachineTag()) if err != nil { out.Results[i].Error = common.ServerError(err) } else { out.Results[i].PublicKeys = []string(keys) } } } return out, nil }
go
func (facade *Facade) PublicKeys(args params.Entities) (params.SSHPublicKeysResults, error) { if err := facade.checkIsModelAdmin(); err != nil { return params.SSHPublicKeysResults{}, errors.Trace(err) } out := params.SSHPublicKeysResults{ Results: make([]params.SSHPublicKeysResult, len(args.Entities)), } for i, entity := range args.Entities { machine, err := facade.backend.GetMachineForEntity(entity.Tag) if err != nil { out.Results[i].Error = common.ServerError(err) } else { keys, err := facade.backend.GetSSHHostKeys(machine.MachineTag()) if err != nil { out.Results[i].Error = common.ServerError(err) } else { out.Results[i].PublicKeys = []string(keys) } } } return out, nil }
[ "func", "(", "facade", "*", "Facade", ")", "PublicKeys", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "SSHPublicKeysResults", ",", "error", ")", "{", "if", "err", ":=", "facade", ".", "checkIsModelAdmin", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "SSHPublicKeysResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "out", ":=", "params", ".", "SSHPublicKeysResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "SSHPublicKeysResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "machine", ",", "err", ":=", "facade", ".", "backend", ".", "GetMachineForEntity", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "out", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "else", "{", "keys", ",", "err", ":=", "facade", ".", "backend", ".", "GetSSHHostKeys", "(", "machine", ".", "MachineTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "out", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "else", "{", "out", ".", "Results", "[", "i", "]", ".", "PublicKeys", "=", "[", "]", "string", "(", "keys", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// PublicKeys returns the public SSH hosts for one or more // entities. Machines and units are supported.
[ "PublicKeys", "returns", "the", "public", "SSH", "hosts", "for", "one", "or", "more", "entities", ".", "Machines", "and", "units", "are", "supported", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/sshclient/facade.go#L183-L205
156,866
juju/juju
apiserver/facades/client/sshclient/facade.go
Proxy
func (facade *Facade) Proxy() (params.SSHProxyResult, error) { if err := facade.checkIsModelAdmin(); err != nil { return params.SSHProxyResult{}, errors.Trace(err) } config, err := facade.backend.ModelConfig() if err != nil { return params.SSHProxyResult{}, err } return params.SSHProxyResult{UseProxy: config.ProxySSH()}, nil }
go
func (facade *Facade) Proxy() (params.SSHProxyResult, error) { if err := facade.checkIsModelAdmin(); err != nil { return params.SSHProxyResult{}, errors.Trace(err) } config, err := facade.backend.ModelConfig() if err != nil { return params.SSHProxyResult{}, err } return params.SSHProxyResult{UseProxy: config.ProxySSH()}, nil }
[ "func", "(", "facade", "*", "Facade", ")", "Proxy", "(", ")", "(", "params", ".", "SSHProxyResult", ",", "error", ")", "{", "if", "err", ":=", "facade", ".", "checkIsModelAdmin", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "SSHProxyResult", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "config", ",", "err", ":=", "facade", ".", "backend", ".", "ModelConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "SSHProxyResult", "{", "}", ",", "err", "\n", "}", "\n", "return", "params", ".", "SSHProxyResult", "{", "UseProxy", ":", "config", ".", "ProxySSH", "(", ")", "}", ",", "nil", "\n", "}" ]
// Proxy returns whether SSH connections should be proxied through the // controller hosts for the model associated with the API connection.
[ "Proxy", "returns", "whether", "SSH", "connections", "should", "be", "proxied", "through", "the", "controller", "hosts", "for", "the", "model", "associated", "with", "the", "API", "connection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/sshclient/facade.go#L209-L218
156,867
juju/juju
upgrades/contexts.go
NewContext
func NewContext( agentConfig agent.ConfigSetter, api api.Connection, st StateBackend, ) Context { return &upgradeContext{ agentConfig: agentConfig, api: api, st: st, } }
go
func NewContext( agentConfig agent.ConfigSetter, api api.Connection, st StateBackend, ) Context { return &upgradeContext{ agentConfig: agentConfig, api: api, st: st, } }
[ "func", "NewContext", "(", "agentConfig", "agent", ".", "ConfigSetter", ",", "api", "api", ".", "Connection", ",", "st", "StateBackend", ",", ")", "Context", "{", "return", "&", "upgradeContext", "{", "agentConfig", ":", "agentConfig", ",", "api", ":", "api", ",", "st", ":", "st", ",", "}", "\n", "}" ]
// NewContext returns a new upgrade context.
[ "NewContext", "returns", "a", "new", "upgrade", "context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/contexts.go#L39-L49
156,868
juju/juju
upgrades/contexts.go
APIState
func (c *upgradeContext) APIState() api.Connection { if c.api == nil { panic("API not available from this context") } return c.api }
go
func (c *upgradeContext) APIState() api.Connection { if c.api == nil { panic("API not available from this context") } return c.api }
[ "func", "(", "c", "*", "upgradeContext", ")", "APIState", "(", ")", "api", ".", "Connection", "{", "if", "c", ".", "api", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "c", ".", "api", "\n", "}" ]
// APIState is defined on the Context interface. // // This will panic if called on a Context returned by StateContext.
[ "APIState", "is", "defined", "on", "the", "Context", "interface", ".", "This", "will", "panic", "if", "called", "on", "a", "Context", "returned", "by", "StateContext", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/contexts.go#L61-L66
156,869
juju/juju
upgrades/contexts.go
State
func (c *upgradeContext) State() StateBackend { if c.st == nil { panic("State not available from this context") } return c.st }
go
func (c *upgradeContext) State() StateBackend { if c.st == nil { panic("State not available from this context") } return c.st }
[ "func", "(", "c", "*", "upgradeContext", ")", "State", "(", ")", "StateBackend", "{", "if", "c", ".", "st", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "c", ".", "st", "\n", "}" ]
// State is defined on the Context interface. // // This will panic if called on a Context returned by APIContext.
[ "State", "is", "defined", "on", "the", "Context", "interface", ".", "This", "will", "panic", "if", "called", "on", "a", "Context", "returned", "by", "APIContext", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/contexts.go#L71-L76
156,870
juju/juju
upgrades/contexts.go
StateContext
func (c *upgradeContext) StateContext() Context { return &upgradeContext{ agentConfig: c.agentConfig, st: c.st, } }
go
func (c *upgradeContext) StateContext() Context { return &upgradeContext{ agentConfig: c.agentConfig, st: c.st, } }
[ "func", "(", "c", "*", "upgradeContext", ")", "StateContext", "(", ")", "Context", "{", "return", "&", "upgradeContext", "{", "agentConfig", ":", "c", ".", "agentConfig", ",", "st", ":", "c", ".", "st", ",", "}", "\n", "}" ]
// StateContext is defined on the Context interface.
[ "StateContext", "is", "defined", "on", "the", "Context", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/contexts.go#L84-L89
156,871
juju/juju
upgrades/contexts.go
APIContext
func (c *upgradeContext) APIContext() Context { return &upgradeContext{ agentConfig: c.agentConfig, api: c.api, } }
go
func (c *upgradeContext) APIContext() Context { return &upgradeContext{ agentConfig: c.agentConfig, api: c.api, } }
[ "func", "(", "c", "*", "upgradeContext", ")", "APIContext", "(", ")", "Context", "{", "return", "&", "upgradeContext", "{", "agentConfig", ":", "c", ".", "agentConfig", ",", "api", ":", "c", ".", "api", ",", "}", "\n", "}" ]
// APIContext is defined on the Context interface.
[ "APIContext", "is", "defined", "on", "the", "Context", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/contexts.go#L92-L97
156,872
juju/juju
rpc/jsoncodec/codec.go
DumpRequest
func DumpRequest(hdr *rpc.Header, body interface{}) []byte { msg, err := response(hdr, body) if err != nil { return []byte(fmt.Sprintf("%q", err.Error())) } data, err := json.Marshal(msg) if err != nil { return []byte(fmt.Sprintf("%q", "marshal error: "+err.Error())) } return data }
go
func DumpRequest(hdr *rpc.Header, body interface{}) []byte { msg, err := response(hdr, body) if err != nil { return []byte(fmt.Sprintf("%q", err.Error())) } data, err := json.Marshal(msg) if err != nil { return []byte(fmt.Sprintf("%q", "marshal error: "+err.Error())) } return data }
[ "func", "DumpRequest", "(", "hdr", "*", "rpc", ".", "Header", ",", "body", "interface", "{", "}", ")", "[", "]", "byte", "{", "msg", ",", "err", ":=", "response", "(", "hdr", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "\n", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "\n", "return", "data", "\n", "}" ]
// DumpRequest returns JSON-formatted data representing // the RPC message with the given header and body, // as it would be written by Codec.WriteMessage. // If the body cannot be marshalled as JSON, the data // will hold a JSON string describing the error.
[ "DumpRequest", "returns", "JSON", "-", "formatted", "data", "representing", "the", "RPC", "message", "with", "the", "given", "header", "and", "body", "as", "it", "would", "be", "written", "by", "Codec", ".", "WriteMessage", ".", "If", "the", "body", "cannot", "be", "marshalled", "as", "JSON", "the", "data", "will", "hold", "a", "JSON", "string", "describing", "the", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/rpc/jsoncodec/codec.go#L205-L215
156,873
juju/juju
rpc/jsoncodec/codec.go
newOutMsgV0
func newOutMsgV0(hdr *rpc.Header, body interface{}) outMsgV0 { result := outMsgV0{ RequestId: hdr.RequestId, Type: hdr.Request.Type, Version: hdr.Request.Version, Id: hdr.Request.Id, Request: hdr.Request.Action, Error: hdr.Error, ErrorCode: hdr.ErrorCode, } if hdr.IsRequest() { result.Params = body } else { result.Response = body } return result }
go
func newOutMsgV0(hdr *rpc.Header, body interface{}) outMsgV0 { result := outMsgV0{ RequestId: hdr.RequestId, Type: hdr.Request.Type, Version: hdr.Request.Version, Id: hdr.Request.Id, Request: hdr.Request.Action, Error: hdr.Error, ErrorCode: hdr.ErrorCode, } if hdr.IsRequest() { result.Params = body } else { result.Response = body } return result }
[ "func", "newOutMsgV0", "(", "hdr", "*", "rpc", ".", "Header", ",", "body", "interface", "{", "}", ")", "outMsgV0", "{", "result", ":=", "outMsgV0", "{", "RequestId", ":", "hdr", ".", "RequestId", ",", "Type", ":", "hdr", ".", "Request", ".", "Type", ",", "Version", ":", "hdr", ".", "Request", ".", "Version", ",", "Id", ":", "hdr", ".", "Request", ".", "Id", ",", "Request", ":", "hdr", ".", "Request", ".", "Action", ",", "Error", ":", "hdr", ".", "Error", ",", "ErrorCode", ":", "hdr", ".", "ErrorCode", ",", "}", "\n", "if", "hdr", ".", "IsRequest", "(", ")", "{", "result", ".", "Params", "=", "body", "\n", "}", "else", "{", "result", ".", "Response", "=", "body", "\n", "}", "\n", "return", "result", "\n", "}" ]
// newOutMsgV0 fills out a outMsgV0 with information from the given // header and body.
[ "newOutMsgV0", "fills", "out", "a", "outMsgV0", "with", "information", "from", "the", "given", "header", "and", "body", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/rpc/jsoncodec/codec.go#L246-L262
156,874
juju/juju
rpc/jsoncodec/codec.go
newOutMsgV1
func newOutMsgV1(hdr *rpc.Header, body interface{}) outMsgV1 { result := outMsgV1{ RequestId: hdr.RequestId, Type: hdr.Request.Type, Version: hdr.Request.Version, Id: hdr.Request.Id, Request: hdr.Request.Action, Error: hdr.Error, ErrorCode: hdr.ErrorCode, ErrorInfo: hdr.ErrorInfo, } if hdr.IsRequest() { result.Params = body } else { result.Response = body } return result }
go
func newOutMsgV1(hdr *rpc.Header, body interface{}) outMsgV1 { result := outMsgV1{ RequestId: hdr.RequestId, Type: hdr.Request.Type, Version: hdr.Request.Version, Id: hdr.Request.Id, Request: hdr.Request.Action, Error: hdr.Error, ErrorCode: hdr.ErrorCode, ErrorInfo: hdr.ErrorInfo, } if hdr.IsRequest() { result.Params = body } else { result.Response = body } return result }
[ "func", "newOutMsgV1", "(", "hdr", "*", "rpc", ".", "Header", ",", "body", "interface", "{", "}", ")", "outMsgV1", "{", "result", ":=", "outMsgV1", "{", "RequestId", ":", "hdr", ".", "RequestId", ",", "Type", ":", "hdr", ".", "Request", ".", "Type", ",", "Version", ":", "hdr", ".", "Request", ".", "Version", ",", "Id", ":", "hdr", ".", "Request", ".", "Id", ",", "Request", ":", "hdr", ".", "Request", ".", "Action", ",", "Error", ":", "hdr", ".", "Error", ",", "ErrorCode", ":", "hdr", ".", "ErrorCode", ",", "ErrorInfo", ":", "hdr", ".", "ErrorInfo", ",", "}", "\n", "if", "hdr", ".", "IsRequest", "(", ")", "{", "result", ".", "Params", "=", "body", "\n", "}", "else", "{", "result", ".", "Response", "=", "body", "\n", "}", "\n", "return", "result", "\n", "}" ]
// newOutMsgV1 fills out a outMsgV1 with information from the given header and // body. This might look a lot like the v0 method, and that is because it is. // However, since Go determines structs to be sufficiently different if the // tags are different, we can't use the same code. Theoretically we could use // reflect, but no.
[ "newOutMsgV1", "fills", "out", "a", "outMsgV1", "with", "information", "from", "the", "given", "header", "and", "body", ".", "This", "might", "look", "a", "lot", "like", "the", "v0", "method", "and", "that", "is", "because", "it", "is", ".", "However", "since", "Go", "determines", "structs", "to", "be", "sufficiently", "different", "if", "the", "tags", "are", "different", "we", "can", "t", "use", "the", "same", "code", ".", "Theoretically", "we", "could", "use", "reflect", "but", "no", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/rpc/jsoncodec/codec.go#L269-L286
156,875
juju/juju
watcher/legacy/notifyworker.go
NewNotifyWorker
func NewNotifyWorker(handler NotifyWatchHandler) worker.Worker { nw := &notifyWorker{ handler: handler, } nw.tomb.Go(nw.loop) return nw }
go
func NewNotifyWorker(handler NotifyWatchHandler) worker.Worker { nw := &notifyWorker{ handler: handler, } nw.tomb.Go(nw.loop) return nw }
[ "func", "NewNotifyWorker", "(", "handler", "NotifyWatchHandler", ")", "worker", ".", "Worker", "{", "nw", ":=", "&", "notifyWorker", "{", "handler", ":", "handler", ",", "}", "\n\n", "nw", ".", "tomb", ".", "Go", "(", "nw", ".", "loop", ")", "\n", "return", "nw", "\n", "}" ]
// NewNotifyWorker starts a new worker running the business logic from // the handler. The worker loop is started in another goroutine as a // side effect of calling this.
[ "NewNotifyWorker", "starts", "a", "new", "worker", "running", "the", "business", "logic", "from", "the", "handler", ".", "The", "worker", "loop", "is", "started", "in", "another", "goroutine", "as", "a", "side", "effect", "of", "calling", "this", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/watcher/legacy/notifyworker.go#L48-L55
156,876
juju/juju
watcher/legacy/notifyworker.go
propagateTearDown
func propagateTearDown(handler tearDowner, t *tomb.Tomb) { if err := handler.TearDown(); err != nil { t.Kill(err) } }
go
func propagateTearDown(handler tearDowner, t *tomb.Tomb) { if err := handler.TearDown(); err != nil { t.Kill(err) } }
[ "func", "propagateTearDown", "(", "handler", "tearDowner", ",", "t", "*", "tomb", ".", "Tomb", ")", "{", "if", "err", ":=", "handler", ".", "TearDown", "(", ")", ";", "err", "!=", "nil", "{", "t", ".", "Kill", "(", "err", ")", "\n", "}", "\n", "}" ]
// propagateTearDown tears down the handler, but ensures any error is // propagated through the tomb's Kill method.
[ "propagateTearDown", "tears", "down", "the", "handler", "but", "ensures", "any", "error", "is", "propagated", "through", "the", "tomb", "s", "Kill", "method", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/watcher/legacy/notifyworker.go#L73-L77
156,877
juju/juju
worker/uniter/runner/jujuc/add-metric.go
NewAddMetricCommand
func NewAddMetricCommand(ctx Context) (cmd.Command, error) { return &AddMetricCommand{ctx: ctx}, nil }
go
func NewAddMetricCommand(ctx Context) (cmd.Command, error) { return &AddMetricCommand{ctx: ctx}, nil }
[ "func", "NewAddMetricCommand", "(", "ctx", "Context", ")", "(", "cmd", ".", "Command", ",", "error", ")", "{", "return", "&", "AddMetricCommand", "{", "ctx", ":", "ctx", "}", ",", "nil", "\n", "}" ]
// NewAddMetricCommand generates a new AddMetricCommand.
[ "NewAddMetricCommand", "generates", "a", "new", "AddMetricCommand", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/add-metric.go#L37-L39
156,878
juju/juju
worker/uniter/runner/jujuc/add-metric.go
Info
func (c *AddMetricCommand) Info() *cmd.Info { return jujucmd.Info(&cmd.Info{ Name: "add-metric", Args: "key1=value1 [key2=value2 ...]", Purpose: "add metrics", }) }
go
func (c *AddMetricCommand) Info() *cmd.Info { return jujucmd.Info(&cmd.Info{ Name: "add-metric", Args: "key1=value1 [key2=value2 ...]", Purpose: "add metrics", }) }
[ "func", "(", "c", "*", "AddMetricCommand", ")", "Info", "(", ")", "*", "cmd", ".", "Info", "{", "return", "jujucmd", ".", "Info", "(", "&", "cmd", ".", "Info", "{", "Name", ":", "\"", "\"", ",", "Args", ":", "\"", "\"", ",", "Purpose", ":", "\"", "\"", ",", "}", ")", "\n", "}" ]
// Info returns the command info structure for the add-metric command.
[ "Info", "returns", "the", "command", "info", "structure", "for", "the", "add", "-", "metric", "command", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/add-metric.go#L42-L48
156,879
juju/juju
worker/uniter/runner/jujuc/add-metric.go
Init
func (c *AddMetricCommand) Init(args []string) error { // TODO(fwereade): 2016-03-17 lp:1558657 now := time.Now() if len(args) == 0 { return fmt.Errorf("no metrics specified") } kvs, err := keyvalues.Parse(args, false) if err != nil { return errors.Annotate(err, "invalid metrics") } var labelArgs []string if c.Labels != "" { labelArgs = strings.Split(c.Labels, ",") } for key, value := range kvs { labels, err := keyvalues.Parse(labelArgs, false) if err != nil { return errors.Annotate(err, "invalid labels") } c.Metrics = append(c.Metrics, Metric{ Key: key, Value: value, Time: now, Labels: labels, }) } return nil }
go
func (c *AddMetricCommand) Init(args []string) error { // TODO(fwereade): 2016-03-17 lp:1558657 now := time.Now() if len(args) == 0 { return fmt.Errorf("no metrics specified") } kvs, err := keyvalues.Parse(args, false) if err != nil { return errors.Annotate(err, "invalid metrics") } var labelArgs []string if c.Labels != "" { labelArgs = strings.Split(c.Labels, ",") } for key, value := range kvs { labels, err := keyvalues.Parse(labelArgs, false) if err != nil { return errors.Annotate(err, "invalid labels") } c.Metrics = append(c.Metrics, Metric{ Key: key, Value: value, Time: now, Labels: labels, }) } return nil }
[ "func", "(", "c", "*", "AddMetricCommand", ")", "Init", "(", "args", "[", "]", "string", ")", "error", "{", "// TODO(fwereade): 2016-03-17 lp:1558657", "now", ":=", "time", ".", "Now", "(", ")", "\n", "if", "len", "(", "args", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "kvs", ",", "err", ":=", "keyvalues", ".", "Parse", "(", "args", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "var", "labelArgs", "[", "]", "string", "\n", "if", "c", ".", "Labels", "!=", "\"", "\"", "{", "labelArgs", "=", "strings", ".", "Split", "(", "c", ".", "Labels", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "key", ",", "value", ":=", "range", "kvs", "{", "labels", ",", "err", ":=", "keyvalues", ".", "Parse", "(", "labelArgs", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "c", ".", "Metrics", "=", "append", "(", "c", ".", "Metrics", ",", "Metric", "{", "Key", ":", "key", ",", "Value", ":", "value", ",", "Time", ":", "now", ",", "Labels", ":", "labels", ",", "}", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Init parses the command's parameters.
[ "Init", "parses", "the", "command", "s", "parameters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/add-metric.go#L57-L84
156,880
juju/juju
worker/uniter/runner/jujuc/add-metric.go
Run
func (c *AddMetricCommand) Run(ctx *cmd.Context) (err error) { for _, metric := range c.Metrics { if charm.IsBuiltinMetric(metric.Key) { return errors.Errorf("%v uses a reserved prefix", metric.Key) } if len(metric.Labels) > 0 { err := c.ctx.AddMetricLabels(metric.Key, metric.Value, metric.Time, metric.Labels) if err != nil { return errors.Annotate(err, "cannot record metric") } } else { err := c.ctx.AddMetric(metric.Key, metric.Value, metric.Time) if err != nil { return errors.Annotate(err, "cannot record metric") } } } return nil }
go
func (c *AddMetricCommand) Run(ctx *cmd.Context) (err error) { for _, metric := range c.Metrics { if charm.IsBuiltinMetric(metric.Key) { return errors.Errorf("%v uses a reserved prefix", metric.Key) } if len(metric.Labels) > 0 { err := c.ctx.AddMetricLabels(metric.Key, metric.Value, metric.Time, metric.Labels) if err != nil { return errors.Annotate(err, "cannot record metric") } } else { err := c.ctx.AddMetric(metric.Key, metric.Value, metric.Time) if err != nil { return errors.Annotate(err, "cannot record metric") } } } return nil }
[ "func", "(", "c", "*", "AddMetricCommand", ")", "Run", "(", "ctx", "*", "cmd", ".", "Context", ")", "(", "err", "error", ")", "{", "for", "_", ",", "metric", ":=", "range", "c", ".", "Metrics", "{", "if", "charm", ".", "IsBuiltinMetric", "(", "metric", ".", "Key", ")", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "metric", ".", "Key", ")", "\n", "}", "\n", "if", "len", "(", "metric", ".", "Labels", ")", ">", "0", "{", "err", ":=", "c", ".", "ctx", ".", "AddMetricLabels", "(", "metric", ".", "Key", ",", "metric", ".", "Value", ",", "metric", ".", "Time", ",", "metric", ".", "Labels", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "err", ":=", "c", ".", "ctx", ".", "AddMetric", "(", "metric", ".", "Key", ",", "metric", ".", "Value", ",", "metric", ".", "Time", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Run adds metrics to the hook context.
[ "Run", "adds", "metrics", "to", "the", "hook", "context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/add-metric.go#L87-L105
156,881
juju/juju
state/enableha.go
EnableHA
func (st *State) EnableHA( numControllers int, cons constraints.Value, series string, placement []string, ) (ControllersChanges, error) { if numControllers < 0 || (numControllers != 0 && numControllers%2 != 1) { return ControllersChanges{}, errors.New("number of controllers must be odd and non-negative") } if numControllers > replicaset.MaxPeers { return ControllersChanges{}, errors.Errorf("controller count is too large (allowed %d)", replicaset.MaxPeers) } var change ControllersChanges buildTxn := func(attempt int) ([]txn.Op, error) { currentInfo, err := st.ControllerInfo() if err != nil { return nil, errors.Trace(err) } desiredControllerCount := numControllers votingCount, err := st.getVotingMachineCount(currentInfo) if err != nil { return nil, errors.Trace(err) } if desiredControllerCount == 0 { // Make sure we go to add odd number of desired voters. Even if HA was currently at 2 desired voters desiredControllerCount = votingCount + (votingCount+1)%2 if desiredControllerCount <= 1 { desiredControllerCount = 3 } } if votingCount > desiredControllerCount { return nil, errors.New("cannot reduce controller count") } intent, err := st.enableHAIntentions(currentInfo, placement) if err != nil { return nil, err } voteCount := 0 for _, m := range intent.maintain { if m.WantsVote() { voteCount++ } } if voteCount == desiredControllerCount { return nil, jujutxn.ErrNoOperations } // Promote as many machines as we can to fulfil the shortfall. if n := desiredControllerCount - voteCount; n < len(intent.promote) { intent.promote = intent.promote[:n] } voteCount += len(intent.promote) if n := desiredControllerCount - voteCount; n < len(intent.convert) { intent.convert = intent.convert[:n] } voteCount += len(intent.convert) intent.newCount = desiredControllerCount - voteCount logger.Infof("%d new machines; promoting %v; converting %v", intent.newCount, intent.promote, intent.convert) var ops []txn.Op ops, change, err = st.enableHAIntentionOps(intent, currentInfo, cons, series) return ops, err } if err := st.db().Run(buildTxn); err != nil { err = errors.Annotate(err, "failed to create new controller machines") return ControllersChanges{}, err } return change, nil }
go
func (st *State) EnableHA( numControllers int, cons constraints.Value, series string, placement []string, ) (ControllersChanges, error) { if numControllers < 0 || (numControllers != 0 && numControllers%2 != 1) { return ControllersChanges{}, errors.New("number of controllers must be odd and non-negative") } if numControllers > replicaset.MaxPeers { return ControllersChanges{}, errors.Errorf("controller count is too large (allowed %d)", replicaset.MaxPeers) } var change ControllersChanges buildTxn := func(attempt int) ([]txn.Op, error) { currentInfo, err := st.ControllerInfo() if err != nil { return nil, errors.Trace(err) } desiredControllerCount := numControllers votingCount, err := st.getVotingMachineCount(currentInfo) if err != nil { return nil, errors.Trace(err) } if desiredControllerCount == 0 { // Make sure we go to add odd number of desired voters. Even if HA was currently at 2 desired voters desiredControllerCount = votingCount + (votingCount+1)%2 if desiredControllerCount <= 1 { desiredControllerCount = 3 } } if votingCount > desiredControllerCount { return nil, errors.New("cannot reduce controller count") } intent, err := st.enableHAIntentions(currentInfo, placement) if err != nil { return nil, err } voteCount := 0 for _, m := range intent.maintain { if m.WantsVote() { voteCount++ } } if voteCount == desiredControllerCount { return nil, jujutxn.ErrNoOperations } // Promote as many machines as we can to fulfil the shortfall. if n := desiredControllerCount - voteCount; n < len(intent.promote) { intent.promote = intent.promote[:n] } voteCount += len(intent.promote) if n := desiredControllerCount - voteCount; n < len(intent.convert) { intent.convert = intent.convert[:n] } voteCount += len(intent.convert) intent.newCount = desiredControllerCount - voteCount logger.Infof("%d new machines; promoting %v; converting %v", intent.newCount, intent.promote, intent.convert) var ops []txn.Op ops, change, err = st.enableHAIntentionOps(intent, currentInfo, cons, series) return ops, err } if err := st.db().Run(buildTxn); err != nil { err = errors.Annotate(err, "failed to create new controller machines") return ControllersChanges{}, err } return change, nil }
[ "func", "(", "st", "*", "State", ")", "EnableHA", "(", "numControllers", "int", ",", "cons", "constraints", ".", "Value", ",", "series", "string", ",", "placement", "[", "]", "string", ",", ")", "(", "ControllersChanges", ",", "error", ")", "{", "if", "numControllers", "<", "0", "||", "(", "numControllers", "!=", "0", "&&", "numControllers", "%", "2", "!=", "1", ")", "{", "return", "ControllersChanges", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "numControllers", ">", "replicaset", ".", "MaxPeers", "{", "return", "ControllersChanges", "{", "}", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "replicaset", ".", "MaxPeers", ")", "\n", "}", "\n", "var", "change", "ControllersChanges", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "currentInfo", ",", "err", ":=", "st", ".", "ControllerInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "desiredControllerCount", ":=", "numControllers", "\n", "votingCount", ",", "err", ":=", "st", ".", "getVotingMachineCount", "(", "currentInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "desiredControllerCount", "==", "0", "{", "// Make sure we go to add odd number of desired voters. Even if HA was currently at 2 desired voters", "desiredControllerCount", "=", "votingCount", "+", "(", "votingCount", "+", "1", ")", "%", "2", "\n", "if", "desiredControllerCount", "<=", "1", "{", "desiredControllerCount", "=", "3", "\n", "}", "\n", "}", "\n", "if", "votingCount", ">", "desiredControllerCount", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "intent", ",", "err", ":=", "st", ".", "enableHAIntentions", "(", "currentInfo", ",", "placement", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "voteCount", ":=", "0", "\n", "for", "_", ",", "m", ":=", "range", "intent", ".", "maintain", "{", "if", "m", ".", "WantsVote", "(", ")", "{", "voteCount", "++", "\n", "}", "\n", "}", "\n", "if", "voteCount", "==", "desiredControllerCount", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "\n", "// Promote as many machines as we can to fulfil the shortfall.", "if", "n", ":=", "desiredControllerCount", "-", "voteCount", ";", "n", "<", "len", "(", "intent", ".", "promote", ")", "{", "intent", ".", "promote", "=", "intent", ".", "promote", "[", ":", "n", "]", "\n", "}", "\n", "voteCount", "+=", "len", "(", "intent", ".", "promote", ")", "\n\n", "if", "n", ":=", "desiredControllerCount", "-", "voteCount", ";", "n", "<", "len", "(", "intent", ".", "convert", ")", "{", "intent", ".", "convert", "=", "intent", ".", "convert", "[", ":", "n", "]", "\n", "}", "\n", "voteCount", "+=", "len", "(", "intent", ".", "convert", ")", "\n\n", "intent", ".", "newCount", "=", "desiredControllerCount", "-", "voteCount", "\n\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "intent", ".", "newCount", ",", "intent", ".", "promote", ",", "intent", ".", "convert", ")", "\n\n", "var", "ops", "[", "]", "txn", ".", "Op", "\n", "ops", ",", "change", ",", "err", "=", "st", ".", "enableHAIntentionOps", "(", "intent", ",", "currentInfo", ",", "cons", ",", "series", ")", "\n", "return", "ops", ",", "err", "\n", "}", "\n", "if", "err", ":=", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", ";", "err", "!=", "nil", "{", "err", "=", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "return", "ControllersChanges", "{", "}", ",", "err", "\n", "}", "\n", "return", "change", ",", "nil", "\n", "}" ]
// EnableHA adds controller machines as necessary to make // the number of live controllers equal to numControllers. The given // constraints and series will be attached to any new machines. // If placement is not empty, any new machines which may be required are started // according to the specified placement directives until the placement list is // exhausted; thereafter any new machines are started according to the constraints and series. // MachineID is the id of the machine where the apiserver is running.
[ "EnableHA", "adds", "controller", "machines", "as", "necessary", "to", "make", "the", "number", "of", "live", "controllers", "equal", "to", "numControllers", ".", "The", "given", "constraints", "and", "series", "will", "be", "attached", "to", "any", "new", "machines", ".", "If", "placement", "is", "not", "empty", "any", "new", "machines", "which", "may", "be", "required", "are", "started", "according", "to", "the", "specified", "placement", "directives", "until", "the", "placement", "list", "is", "exhausted", ";", "thereafter", "any", "new", "machines", "are", "started", "according", "to", "the", "constraints", "and", "series", ".", "MachineID", "is", "the", "id", "of", "the", "machine", "where", "the", "apiserver", "is", "running", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/enableha.go#L97-L166
156,882
juju/juju
state/enableha.go
enableHAIntentionOps
func (st *State) enableHAIntentionOps( intent *enableHAIntent, currentInfo *ControllerInfo, cons constraints.Value, series string, ) ([]txn.Op, ControllersChanges, error) { var ops []txn.Op var change ControllersChanges for _, m := range intent.promote { ops = append(ops, promoteControllerOps(m)...) change.Promoted = append(change.Promoted, m.doc.Id) } for _, m := range intent.convert { ops = append(ops, convertControllerOps(m)...) change.Converted = append(change.Converted, m.doc.Id) } // Use any placement directives that have been provided // when adding new machines, until the directives have // been all used up. Ignore constraints for provided machines. // Set up a helper function to do the work required. placementCount := 0 getPlacementConstraints := func() (string, constraints.Value) { if placementCount >= len(intent.placement) { return "", cons } result := intent.placement[placementCount] placementCount++ return result, constraints.Value{} } mdocs := make([]*machineDoc, intent.newCount) for i := range mdocs { placement, cons := getPlacementConstraints() template := MachineTemplate{ Series: series, Jobs: []MachineJob{ JobHostUnits, JobManageModel, }, Constraints: cons, Placement: placement, } mdoc, addOps, err := st.addMachineOps(template) if err != nil { return nil, ControllersChanges{}, err } mdocs[i] = mdoc ops = append(ops, addOps...) change.Added = append(change.Added, mdoc.Id) } for _, m := range intent.maintain { tag, err := names.ParseTag(m.Tag().String()) if err != nil { return nil, ControllersChanges{}, errors.Annotate(err, "could not parse machine tag") } if tag.Kind() != names.MachineTagKind { return nil, ControllersChanges{}, errors.Errorf("expected machine tag kind, got %s", tag.Kind()) } change.Maintained = append(change.Maintained, tag.Id()) } ssOps, err := st.maintainControllersOps(mdocs, currentInfo) if err != nil { return nil, ControllersChanges{}, errors.Annotate(err, "cannot prepare machine add operations") } ops = append(ops, ssOps...) return ops, change, nil }
go
func (st *State) enableHAIntentionOps( intent *enableHAIntent, currentInfo *ControllerInfo, cons constraints.Value, series string, ) ([]txn.Op, ControllersChanges, error) { var ops []txn.Op var change ControllersChanges for _, m := range intent.promote { ops = append(ops, promoteControllerOps(m)...) change.Promoted = append(change.Promoted, m.doc.Id) } for _, m := range intent.convert { ops = append(ops, convertControllerOps(m)...) change.Converted = append(change.Converted, m.doc.Id) } // Use any placement directives that have been provided // when adding new machines, until the directives have // been all used up. Ignore constraints for provided machines. // Set up a helper function to do the work required. placementCount := 0 getPlacementConstraints := func() (string, constraints.Value) { if placementCount >= len(intent.placement) { return "", cons } result := intent.placement[placementCount] placementCount++ return result, constraints.Value{} } mdocs := make([]*machineDoc, intent.newCount) for i := range mdocs { placement, cons := getPlacementConstraints() template := MachineTemplate{ Series: series, Jobs: []MachineJob{ JobHostUnits, JobManageModel, }, Constraints: cons, Placement: placement, } mdoc, addOps, err := st.addMachineOps(template) if err != nil { return nil, ControllersChanges{}, err } mdocs[i] = mdoc ops = append(ops, addOps...) change.Added = append(change.Added, mdoc.Id) } for _, m := range intent.maintain { tag, err := names.ParseTag(m.Tag().String()) if err != nil { return nil, ControllersChanges{}, errors.Annotate(err, "could not parse machine tag") } if tag.Kind() != names.MachineTagKind { return nil, ControllersChanges{}, errors.Errorf("expected machine tag kind, got %s", tag.Kind()) } change.Maintained = append(change.Maintained, tag.Id()) } ssOps, err := st.maintainControllersOps(mdocs, currentInfo) if err != nil { return nil, ControllersChanges{}, errors.Annotate(err, "cannot prepare machine add operations") } ops = append(ops, ssOps...) return ops, change, nil }
[ "func", "(", "st", "*", "State", ")", "enableHAIntentionOps", "(", "intent", "*", "enableHAIntent", ",", "currentInfo", "*", "ControllerInfo", ",", "cons", "constraints", ".", "Value", ",", "series", "string", ",", ")", "(", "[", "]", "txn", ".", "Op", ",", "ControllersChanges", ",", "error", ")", "{", "var", "ops", "[", "]", "txn", ".", "Op", "\n", "var", "change", "ControllersChanges", "\n", "for", "_", ",", "m", ":=", "range", "intent", ".", "promote", "{", "ops", "=", "append", "(", "ops", ",", "promoteControllerOps", "(", "m", ")", "...", ")", "\n", "change", ".", "Promoted", "=", "append", "(", "change", ".", "Promoted", ",", "m", ".", "doc", ".", "Id", ")", "\n", "}", "\n", "for", "_", ",", "m", ":=", "range", "intent", ".", "convert", "{", "ops", "=", "append", "(", "ops", ",", "convertControllerOps", "(", "m", ")", "...", ")", "\n", "change", ".", "Converted", "=", "append", "(", "change", ".", "Converted", ",", "m", ".", "doc", ".", "Id", ")", "\n", "}", "\n", "// Use any placement directives that have been provided", "// when adding new machines, until the directives have", "// been all used up. Ignore constraints for provided machines.", "// Set up a helper function to do the work required.", "placementCount", ":=", "0", "\n", "getPlacementConstraints", ":=", "func", "(", ")", "(", "string", ",", "constraints", ".", "Value", ")", "{", "if", "placementCount", ">=", "len", "(", "intent", ".", "placement", ")", "{", "return", "\"", "\"", ",", "cons", "\n", "}", "\n", "result", ":=", "intent", ".", "placement", "[", "placementCount", "]", "\n", "placementCount", "++", "\n", "return", "result", ",", "constraints", ".", "Value", "{", "}", "\n", "}", "\n", "mdocs", ":=", "make", "(", "[", "]", "*", "machineDoc", ",", "intent", ".", "newCount", ")", "\n", "for", "i", ":=", "range", "mdocs", "{", "placement", ",", "cons", ":=", "getPlacementConstraints", "(", ")", "\n", "template", ":=", "MachineTemplate", "{", "Series", ":", "series", ",", "Jobs", ":", "[", "]", "MachineJob", "{", "JobHostUnits", ",", "JobManageModel", ",", "}", ",", "Constraints", ":", "cons", ",", "Placement", ":", "placement", ",", "}", "\n", "mdoc", ",", "addOps", ",", "err", ":=", "st", ".", "addMachineOps", "(", "template", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "ControllersChanges", "{", "}", ",", "err", "\n", "}", "\n", "mdocs", "[", "i", "]", "=", "mdoc", "\n", "ops", "=", "append", "(", "ops", ",", "addOps", "...", ")", "\n", "change", ".", "Added", "=", "append", "(", "change", ".", "Added", ",", "mdoc", ".", "Id", ")", "\n\n", "}", "\n", "for", "_", ",", "m", ":=", "range", "intent", ".", "maintain", "{", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "m", ".", "Tag", "(", ")", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "ControllersChanges", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "tag", ".", "Kind", "(", ")", "!=", "names", ".", "MachineTagKind", "{", "return", "nil", ",", "ControllersChanges", "{", "}", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "tag", ".", "Kind", "(", ")", ")", "\n", "}", "\n", "change", ".", "Maintained", "=", "append", "(", "change", ".", "Maintained", ",", "tag", ".", "Id", "(", ")", ")", "\n", "}", "\n", "ssOps", ",", "err", ":=", "st", ".", "maintainControllersOps", "(", "mdocs", ",", "currentInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "ControllersChanges", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "ssOps", "...", ")", "\n", "return", "ops", ",", "change", ",", "nil", "\n", "}" ]
// enableHAIntentionOps returns operations to fulfil the desired intent.
[ "enableHAIntentionOps", "returns", "operations", "to", "fulfil", "the", "desired", "intent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/enableha.go#L179-L245
156,883
juju/juju
state/enableha.go
RemoveControllerMachine
func (st *State) RemoveControllerMachine(m *Machine) error { logger.Infof("removing controller machine %q", m.doc.Id) buildTxn := func(attempt int) ([]txn.Op, error) { if attempt != 0 { // Something changed, make sure we're still up to date m.Refresh() } if m.WantsVote() { return nil, errors.Errorf("machine %s cannot be removed as a controller as it still wants to vote", m.Id()) } if m.HasVote() { return nil, errors.Errorf("machine %s cannot be removed as a controller as it still has a vote", m.Id()) } controllerInfo, err := st.ControllerInfo() if err != nil { return nil, errors.Trace(err) } if len(controllerInfo.MachineIds) <= 1 { return nil, errors.Errorf("machine %s cannot be removed as it is the last controller", m.Id()) } return removeControllerOps(m, controllerInfo), nil } if err := st.db().Run(buildTxn); err != nil { return errors.Trace(err) } return nil }
go
func (st *State) RemoveControllerMachine(m *Machine) error { logger.Infof("removing controller machine %q", m.doc.Id) buildTxn := func(attempt int) ([]txn.Op, error) { if attempt != 0 { // Something changed, make sure we're still up to date m.Refresh() } if m.WantsVote() { return nil, errors.Errorf("machine %s cannot be removed as a controller as it still wants to vote", m.Id()) } if m.HasVote() { return nil, errors.Errorf("machine %s cannot be removed as a controller as it still has a vote", m.Id()) } controllerInfo, err := st.ControllerInfo() if err != nil { return nil, errors.Trace(err) } if len(controllerInfo.MachineIds) <= 1 { return nil, errors.Errorf("machine %s cannot be removed as it is the last controller", m.Id()) } return removeControllerOps(m, controllerInfo), nil } if err := st.db().Run(buildTxn); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "st", "*", "State", ")", "RemoveControllerMachine", "(", "m", "*", "Machine", ")", "error", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "m", ".", "doc", ".", "Id", ")", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "attempt", "!=", "0", "{", "// Something changed, make sure we're still up to date", "m", ".", "Refresh", "(", ")", "\n", "}", "\n", "if", "m", ".", "WantsVote", "(", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "m", ".", "Id", "(", ")", ")", "\n", "}", "\n", "if", "m", ".", "HasVote", "(", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "m", ".", "Id", "(", ")", ")", "\n", "}", "\n", "controllerInfo", ",", "err", ":=", "st", ".", "ControllerInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "controllerInfo", ".", "MachineIds", ")", "<=", "1", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "m", ".", "Id", "(", ")", ")", "\n", "}", "\n", "return", "removeControllerOps", "(", "m", ",", "controllerInfo", ")", ",", "nil", "\n", "}", "\n", "if", "err", ":=", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RemoveControllerMachine will remove Machine from being part of the set of Controllers. // It must not have or want to vote, and it must not be the last controller.
[ "RemoveControllerMachine", "will", "remove", "Machine", "from", "being", "part", "of", "the", "set", "of", "Controllers", ".", "It", "must", "not", "have", "or", "want", "to", "vote", "and", "it", "must", "not", "be", "the", "last", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/enableha.go#L356-L382
156,884
juju/juju
rpc/rpcreflect/type.go
MethodNames
func (r *Type) MethodNames() []string { names := make([]string, 0, len(r.method)) for name := range r.method { names = append(names, name) } sort.Strings(names) return names }
go
func (r *Type) MethodNames() []string { names := make([]string, 0, len(r.method)) for name := range r.method { names = append(names, name) } sort.Strings(names) return names }
[ "func", "(", "r", "*", "Type", ")", "MethodNames", "(", ")", "[", "]", "string", "{", "names", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "r", ".", "method", ")", ")", "\n", "for", "name", ":=", "range", "r", ".", "method", "{", "names", "=", "append", "(", "names", ",", "name", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "names", ")", "\n", "return", "names", "\n", "}" ]
// MethodNames returns the names of all the root object // methods on the receiving object.
[ "MethodNames", "returns", "the", "names", "of", "all", "the", "root", "object", "methods", "on", "the", "receiving", "object", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/rpc/rpcreflect/type.go#L48-L55
156,885
juju/juju
rpc/rpcreflect/type.go
TypeOf
func TypeOf(goType reflect.Type) *Type { if goType == nil { return nil } typeMutex.RLock() t := typesByGoType[goType] typeMutex.RUnlock() if t != nil { return t } typeMutex.Lock() defer typeMutex.Unlock() t = typesByGoType[goType] if t != nil { return t } t = typeOf(goType) typesByGoType[goType] = t return t }
go
func TypeOf(goType reflect.Type) *Type { if goType == nil { return nil } typeMutex.RLock() t := typesByGoType[goType] typeMutex.RUnlock() if t != nil { return t } typeMutex.Lock() defer typeMutex.Unlock() t = typesByGoType[goType] if t != nil { return t } t = typeOf(goType) typesByGoType[goType] = t return t }
[ "func", "TypeOf", "(", "goType", "reflect", ".", "Type", ")", "*", "Type", "{", "if", "goType", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "typeMutex", ".", "RLock", "(", ")", "\n", "t", ":=", "typesByGoType", "[", "goType", "]", "\n", "typeMutex", ".", "RUnlock", "(", ")", "\n", "if", "t", "!=", "nil", "{", "return", "t", "\n", "}", "\n", "typeMutex", ".", "Lock", "(", ")", "\n", "defer", "typeMutex", ".", "Unlock", "(", ")", "\n", "t", "=", "typesByGoType", "[", "goType", "]", "\n", "if", "t", "!=", "nil", "{", "return", "t", "\n", "}", "\n", "t", "=", "typeOf", "(", "goType", ")", "\n", "typesByGoType", "[", "goType", "]", "=", "t", "\n", "return", "t", "\n", "}" ]
// TypeOf returns information on all root-level RPC methods // implemented by an object of the given Go type. // If goType is nil, it returns nil.
[ "TypeOf", "returns", "information", "on", "all", "root", "-", "level", "RPC", "methods", "implemented", "by", "an", "object", "of", "the", "given", "Go", "type", ".", "If", "goType", "is", "nil", "it", "returns", "nil", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/rpc/rpcreflect/type.go#L87-L106
156,886
juju/juju
rpc/rpcreflect/type.go
typeOf
func typeOf(goType reflect.Type) *Type { rm := &Type{ method: make(map[string]*RootMethod), } for i := 0; i < goType.NumMethod(); i++ { m := goType.Method(i) if m.PkgPath != "" || isKillMethod(m) { // The Kill method gets a special exception because // it fulfils the Killer interface which we're expecting, // so it's not really discarded as such. continue } if o := newRootMethod(m); o != nil { rm.method[m.Name] = o } else { rm.discarded = append(rm.discarded, m.Name) } } return rm }
go
func typeOf(goType reflect.Type) *Type { rm := &Type{ method: make(map[string]*RootMethod), } for i := 0; i < goType.NumMethod(); i++ { m := goType.Method(i) if m.PkgPath != "" || isKillMethod(m) { // The Kill method gets a special exception because // it fulfils the Killer interface which we're expecting, // so it's not really discarded as such. continue } if o := newRootMethod(m); o != nil { rm.method[m.Name] = o } else { rm.discarded = append(rm.discarded, m.Name) } } return rm }
[ "func", "typeOf", "(", "goType", "reflect", ".", "Type", ")", "*", "Type", "{", "rm", ":=", "&", "Type", "{", "method", ":", "make", "(", "map", "[", "string", "]", "*", "RootMethod", ")", ",", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "goType", ".", "NumMethod", "(", ")", ";", "i", "++", "{", "m", ":=", "goType", ".", "Method", "(", "i", ")", "\n", "if", "m", ".", "PkgPath", "!=", "\"", "\"", "||", "isKillMethod", "(", "m", ")", "{", "// The Kill method gets a special exception because", "// it fulfils the Killer interface which we're expecting,", "// so it's not really discarded as such.", "continue", "\n", "}", "\n", "if", "o", ":=", "newRootMethod", "(", "m", ")", ";", "o", "!=", "nil", "{", "rm", ".", "method", "[", "m", ".", "Name", "]", "=", "o", "\n", "}", "else", "{", "rm", ".", "discarded", "=", "append", "(", "rm", ".", "discarded", ",", "m", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "return", "rm", "\n", "}" ]
// typeOf is like TypeOf but without the cache - it // always allocates. Called with rootTypeMutex locked.
[ "typeOf", "is", "like", "TypeOf", "but", "without", "the", "cache", "-", "it", "always", "allocates", ".", "Called", "with", "rootTypeMutex", "locked", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/rpc/rpcreflect/type.go#L110-L129
156,887
juju/juju
rpc/rpcreflect/type.go
MethodNames
func (t *ObjType) MethodNames() []string { names := make([]string, 0, len(t.method)) for name := range t.method { names = append(names, name) } sort.Strings(names) return names }
go
func (t *ObjType) MethodNames() []string { names := make([]string, 0, len(t.method)) for name := range t.method { names = append(names, name) } sort.Strings(names) return names }
[ "func", "(", "t", "*", "ObjType", ")", "MethodNames", "(", ")", "[", "]", "string", "{", "names", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "t", ".", "method", ")", ")", "\n", "for", "name", ":=", "range", "t", ".", "method", "{", "names", "=", "append", "(", "names", ",", "name", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "names", ")", "\n", "return", "names", "\n", "}" ]
// MethodNames returns the names of all the RPC methods // defined on the type.
[ "MethodNames", "returns", "the", "names", "of", "all", "the", "RPC", "methods", "defined", "on", "the", "type", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/rpc/rpcreflect/type.go#L197-L204
156,888
juju/juju
rpc/rpcreflect/type.go
ObjTypeOf
func ObjTypeOf(objType reflect.Type) *ObjType { if objType == nil { return nil } objTypeMutex.RLock() methods := objTypesByGoType[objType] objTypeMutex.RUnlock() if methods != nil { return methods } objTypeMutex.Lock() defer objTypeMutex.Unlock() methods = objTypesByGoType[objType] if methods != nil { return methods } methods = objTypeOf(objType) objTypesByGoType[objType] = methods return methods }
go
func ObjTypeOf(objType reflect.Type) *ObjType { if objType == nil { return nil } objTypeMutex.RLock() methods := objTypesByGoType[objType] objTypeMutex.RUnlock() if methods != nil { return methods } objTypeMutex.Lock() defer objTypeMutex.Unlock() methods = objTypesByGoType[objType] if methods != nil { return methods } methods = objTypeOf(objType) objTypesByGoType[objType] = methods return methods }
[ "func", "ObjTypeOf", "(", "objType", "reflect", ".", "Type", ")", "*", "ObjType", "{", "if", "objType", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "objTypeMutex", ".", "RLock", "(", ")", "\n", "methods", ":=", "objTypesByGoType", "[", "objType", "]", "\n", "objTypeMutex", ".", "RUnlock", "(", ")", "\n", "if", "methods", "!=", "nil", "{", "return", "methods", "\n", "}", "\n", "objTypeMutex", ".", "Lock", "(", ")", "\n", "defer", "objTypeMutex", ".", "Unlock", "(", ")", "\n", "methods", "=", "objTypesByGoType", "[", "objType", "]", "\n", "if", "methods", "!=", "nil", "{", "return", "methods", "\n", "}", "\n", "methods", "=", "objTypeOf", "(", "objType", ")", "\n", "objTypesByGoType", "[", "objType", "]", "=", "methods", "\n", "return", "methods", "\n", "}" ]
// ObjTypeOf returns information on all RPC methods // implemented by an object of the given Go type, // as returned from a root-level method. // If objType is nil, it returns nil.
[ "ObjTypeOf", "returns", "information", "on", "all", "RPC", "methods", "implemented", "by", "an", "object", "of", "the", "given", "Go", "type", "as", "returned", "from", "a", "root", "-", "level", "method", ".", "If", "objType", "is", "nil", "it", "returns", "nil", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/rpc/rpcreflect/type.go#L229-L248
156,889
juju/juju
rpc/rpcreflect/type.go
objTypeOf
func objTypeOf(goType reflect.Type) *ObjType { objType := &ObjType{ method: make(map[string]*ObjMethod), goType: goType, } for i := 0; i < goType.NumMethod(); i++ { m := goType.Method(i) if m.PkgPath != "" { continue } if objm := newMethod(m, goType.Kind()); objm != nil { objType.method[m.Name] = objm } else { objType.discarded = append(objType.discarded, m.Name) } } return objType }
go
func objTypeOf(goType reflect.Type) *ObjType { objType := &ObjType{ method: make(map[string]*ObjMethod), goType: goType, } for i := 0; i < goType.NumMethod(); i++ { m := goType.Method(i) if m.PkgPath != "" { continue } if objm := newMethod(m, goType.Kind()); objm != nil { objType.method[m.Name] = objm } else { objType.discarded = append(objType.discarded, m.Name) } } return objType }
[ "func", "objTypeOf", "(", "goType", "reflect", ".", "Type", ")", "*", "ObjType", "{", "objType", ":=", "&", "ObjType", "{", "method", ":", "make", "(", "map", "[", "string", "]", "*", "ObjMethod", ")", ",", "goType", ":", "goType", ",", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "goType", ".", "NumMethod", "(", ")", ";", "i", "++", "{", "m", ":=", "goType", ".", "Method", "(", "i", ")", "\n", "if", "m", ".", "PkgPath", "!=", "\"", "\"", "{", "continue", "\n", "}", "\n", "if", "objm", ":=", "newMethod", "(", "m", ",", "goType", ".", "Kind", "(", ")", ")", ";", "objm", "!=", "nil", "{", "objType", ".", "method", "[", "m", ".", "Name", "]", "=", "objm", "\n", "}", "else", "{", "objType", ".", "discarded", "=", "append", "(", "objType", ".", "discarded", ",", "m", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "return", "objType", "\n", "}" ]
// objTypeOf is like ObjTypeOf but without the cache. // Called with objTypeMutex locked.
[ "objTypeOf", "is", "like", "ObjTypeOf", "but", "without", "the", "cache", ".", "Called", "with", "objTypeMutex", "locked", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/rpc/rpcreflect/type.go#L252-L269
156,890
juju/juju
state/cloudcontainer.go
Address
func (c *cloudContainer) Address() *network.Address { if c.doc.Address == nil { return nil } addr := c.doc.Address.networkAddress() return &addr }
go
func (c *cloudContainer) Address() *network.Address { if c.doc.Address == nil { return nil } addr := c.doc.Address.networkAddress() return &addr }
[ "func", "(", "c", "*", "cloudContainer", ")", "Address", "(", ")", "*", "network", ".", "Address", "{", "if", "c", ".", "doc", ".", "Address", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "addr", ":=", "c", ".", "doc", ".", "Address", ".", "networkAddress", "(", ")", "\n", "return", "&", "addr", "\n", "}" ]
// Address implements CloudContainer.
[ "Address", "implements", "CloudContainer", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudcontainer.go#L64-L70
156,891
juju/juju
state/cloudcontainer.go
Containers
func (m *CAASModel) Containers(providerIds ...string) ([]CloudContainer, error) { coll, closer := m.st.db().GetCollection(cloudContainersC) defer closer() var all []cloudContainerDoc err := coll.Find(bson.D{{"provider-id", bson.D{{"$in", providerIds}}}}).All(&all) if err != nil { return nil, errors.Trace(err) } var result []CloudContainer for _, doc := range all { unitKey := m.localID(doc.Id) // key is "u#<unitname>#charm" idx := len(unitKey) - len("#charm") result = append(result, &cloudContainer{doc: doc, unitName: unitKey[2:idx]}) } return result, nil }
go
func (m *CAASModel) Containers(providerIds ...string) ([]CloudContainer, error) { coll, closer := m.st.db().GetCollection(cloudContainersC) defer closer() var all []cloudContainerDoc err := coll.Find(bson.D{{"provider-id", bson.D{{"$in", providerIds}}}}).All(&all) if err != nil { return nil, errors.Trace(err) } var result []CloudContainer for _, doc := range all { unitKey := m.localID(doc.Id) // key is "u#<unitname>#charm" idx := len(unitKey) - len("#charm") result = append(result, &cloudContainer{doc: doc, unitName: unitKey[2:idx]}) } return result, nil }
[ "func", "(", "m", "*", "CAASModel", ")", "Containers", "(", "providerIds", "...", "string", ")", "(", "[", "]", "CloudContainer", ",", "error", ")", "{", "coll", ",", "closer", ":=", "m", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "cloudContainersC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "var", "all", "[", "]", "cloudContainerDoc", "\n", "err", ":=", "coll", ".", "Find", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "providerIds", "}", "}", "}", "}", ")", ".", "All", "(", "&", "all", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "result", "[", "]", "CloudContainer", "\n", "for", "_", ",", "doc", ":=", "range", "all", "{", "unitKey", ":=", "m", ".", "localID", "(", "doc", ".", "Id", ")", "\n", "// key is \"u#<unitname>#charm\"", "idx", ":=", "len", "(", "unitKey", ")", "-", "len", "(", "\"", "\"", ")", "\n", "result", "=", "append", "(", "result", ",", "&", "cloudContainer", "{", "doc", ":", "doc", ",", "unitName", ":", "unitKey", "[", "2", ":", "idx", "]", "}", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Containers returns the containers for the specified provider ids.
[ "Containers", "returns", "the", "containers", "for", "the", "specified", "provider", "ids", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudcontainer.go#L143-L160
156,892
juju/juju
cmd/juju/storage/poollist.go
NewPoolListCommand
func NewPoolListCommand() cmd.Command { cmd := &poolListCommand{} cmd.newAPIFunc = func() (PoolListAPI, error) { return cmd.NewStorageAPI() } return modelcmd.Wrap(cmd) }
go
func NewPoolListCommand() cmd.Command { cmd := &poolListCommand{} cmd.newAPIFunc = func() (PoolListAPI, error) { return cmd.NewStorageAPI() } return modelcmd.Wrap(cmd) }
[ "func", "NewPoolListCommand", "(", ")", "cmd", ".", "Command", "{", "cmd", ":=", "&", "poolListCommand", "{", "}", "\n", "cmd", ".", "newAPIFunc", "=", "func", "(", ")", "(", "PoolListAPI", ",", "error", ")", "{", "return", "cmd", ".", "NewStorageAPI", "(", ")", "\n", "}", "\n", "return", "modelcmd", ".", "Wrap", "(", "cmd", ")", "\n", "}" ]
// NewPoolListCommand returns a command that lists storage pools on a model
[ "NewPoolListCommand", "returns", "a", "command", "that", "lists", "storage", "pools", "on", "a", "model" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/storage/poollist.go#L51-L57
156,893
juju/juju
apiserver/httpcontext/model.go
RequestModelUUID
func RequestModelUUID(req *http.Request) string { if value := req.Context().Value(modelKey{}); value != nil { return value.(string) } return "" }
go
func RequestModelUUID(req *http.Request) string { if value := req.Context().Value(modelKey{}); value != nil { return value.(string) } return "" }
[ "func", "RequestModelUUID", "(", "req", "*", "http", ".", "Request", ")", "string", "{", "if", "value", ":=", "req", ".", "Context", "(", ")", ".", "Value", "(", "modelKey", "{", "}", ")", ";", "value", "!=", "nil", "{", "return", "value", ".", "(", "string", ")", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// RequestModelUUID returns the model UUID associated with this request // if there is one, or the empty string otherwise. No attempt is made // to validate the model UUID; QueryModelHandler does this, and // ImpliedModelHandler should always be supplied with a valid UUID.
[ "RequestModelUUID", "returns", "the", "model", "UUID", "associated", "with", "this", "request", "if", "there", "is", "one", "or", "the", "empty", "string", "otherwise", ".", "No", "attempt", "is", "made", "to", "validate", "the", "model", "UUID", ";", "QueryModelHandler", "does", "this", "and", "ImpliedModelHandler", "should", "always", "be", "supplied", "with", "a", "valid", "UUID", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/httpcontext/model.go#L61-L66
156,894
juju/juju
apiserver/facades/agent/storageprovisioner/shim.go
NewFacadeV4
func NewFacadeV4(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*StorageProvisionerAPIv4, error) { v3, err := NewFacadeV3(st, resources, authorizer) if err != nil { return nil, errors.Trace(err) } return NewStorageProvisionerAPIv4(v3), nil }
go
func NewFacadeV4(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*StorageProvisionerAPIv4, error) { v3, err := NewFacadeV3(st, resources, authorizer) if err != nil { return nil, errors.Trace(err) } return NewStorageProvisionerAPIv4(v3), nil }
[ "func", "NewFacadeV4", "(", "st", "*", "state", ".", "State", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ")", "(", "*", "StorageProvisionerAPIv4", ",", "error", ")", "{", "v3", ",", "err", ":=", "NewFacadeV3", "(", "st", ",", "resources", ",", "authorizer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "NewStorageProvisionerAPIv4", "(", "v3", ")", ",", "nil", "\n", "}" ]
// NewFacadeV4 provides the signature required for facade registration.
[ "NewFacadeV4", "provides", "the", "signature", "required", "for", "facade", "registration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/storageprovisioner/shim.go#L47-L53
156,895
juju/juju
state/unit.go
ContainerInfo
func (u *Unit) ContainerInfo() (CloudContainer, error) { doc, err := u.cloudContainer() if err != nil { return nil, errors.Trace(err) } return &cloudContainer{doc: *doc, unitName: u.Name()}, nil }
go
func (u *Unit) ContainerInfo() (CloudContainer, error) { doc, err := u.cloudContainer() if err != nil { return nil, errors.Trace(err) } return &cloudContainer{doc: *doc, unitName: u.Name()}, nil }
[ "func", "(", "u", "*", "Unit", ")", "ContainerInfo", "(", ")", "(", "CloudContainer", ",", "error", ")", "{", "doc", ",", "err", ":=", "u", ".", "cloudContainer", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "cloudContainer", "{", "doc", ":", "*", "doc", ",", "unitName", ":", "u", ".", "Name", "(", ")", "}", ",", "nil", "\n", "}" ]
// ContainerInfo returns information about the containing hosting this unit. // This is only used for CAAS models.
[ "ContainerInfo", "returns", "information", "about", "the", "containing", "hosting", "this", "unit", ".", "This", "is", "only", "used", "for", "CAAS", "models", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L122-L128
156,896
juju/juju
state/unit.go
SetWorkloadVersion
func (u *Unit) SetWorkloadVersion(version string) error { // Store in status rather than an attribute of the unit doc - we // want to avoid everything being an attr of the main docs to // stop a swarm of watchers being notified for irrelevant changes. now := u.st.clock().Now() return setStatus(u.st.db(), setStatusParams{ badge: "workload", globalKey: u.globalWorkloadVersionKey(), status: status.Active, message: version, updated: &now, }) }
go
func (u *Unit) SetWorkloadVersion(version string) error { // Store in status rather than an attribute of the unit doc - we // want to avoid everything being an attr of the main docs to // stop a swarm of watchers being notified for irrelevant changes. now := u.st.clock().Now() return setStatus(u.st.db(), setStatusParams{ badge: "workload", globalKey: u.globalWorkloadVersionKey(), status: status.Active, message: version, updated: &now, }) }
[ "func", "(", "u", "*", "Unit", ")", "SetWorkloadVersion", "(", "version", "string", ")", "error", "{", "// Store in status rather than an attribute of the unit doc - we", "// want to avoid everything being an attr of the main docs to", "// stop a swarm of watchers being notified for irrelevant changes.", "now", ":=", "u", ".", "st", ".", "clock", "(", ")", ".", "Now", "(", ")", "\n", "return", "setStatus", "(", "u", ".", "st", ".", "db", "(", ")", ",", "setStatusParams", "{", "badge", ":", "\"", "\"", ",", "globalKey", ":", "u", ".", "globalWorkloadVersionKey", "(", ")", ",", "status", ":", "status", ".", "Active", ",", "message", ":", "version", ",", "updated", ":", "&", "now", ",", "}", ")", "\n", "}" ]
// SetWorkloadVersion sets the version of the workload that the unit // is currently running.
[ "SetWorkloadVersion", "sets", "the", "version", "of", "the", "workload", "that", "the", "unit", "is", "currently", "running", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L236-L248
156,897
juju/juju
state/unit.go
WorkloadVersionHistory
func (u *Unit) WorkloadVersionHistory() *HistoryGetter { return &HistoryGetter{st: u.st, globalKey: u.globalWorkloadVersionKey()} }
go
func (u *Unit) WorkloadVersionHistory() *HistoryGetter { return &HistoryGetter{st: u.st, globalKey: u.globalWorkloadVersionKey()} }
[ "func", "(", "u", "*", "Unit", ")", "WorkloadVersionHistory", "(", ")", "*", "HistoryGetter", "{", "return", "&", "HistoryGetter", "{", "st", ":", "u", ".", "st", ",", "globalKey", ":", "u", ".", "globalWorkloadVersionKey", "(", ")", "}", "\n", "}" ]
// WorkloadVersionHistory returns a HistoryGetter which enables the // caller to request past workload version changes.
[ "WorkloadVersionHistory", "returns", "a", "HistoryGetter", "which", "enables", "the", "caller", "to", "request", "past", "workload", "version", "changes", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L252-L254
156,898
juju/juju
state/unit.go
AgentTools
func (u *Unit) AgentTools() (*tools.Tools, error) { if u.doc.Tools == nil { return nil, errors.NotFoundf("agent binaries for unit %q", u) } result := *u.doc.Tools return &result, nil }
go
func (u *Unit) AgentTools() (*tools.Tools, error) { if u.doc.Tools == nil { return nil, errors.NotFoundf("agent binaries for unit %q", u) } result := *u.doc.Tools return &result, nil }
[ "func", "(", "u", "*", "Unit", ")", "AgentTools", "(", ")", "(", "*", "tools", ".", "Tools", ",", "error", ")", "{", "if", "u", ".", "doc", ".", "Tools", "==", "nil", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "u", ")", "\n", "}", "\n", "result", ":=", "*", "u", ".", "doc", ".", "Tools", "\n", "return", "&", "result", ",", "nil", "\n", "}" ]
// AgentTools returns the tools that the agent is currently running. // It an error that satisfies errors.IsNotFound if the tools have not // yet been set.
[ "AgentTools", "returns", "the", "tools", "that", "the", "agent", "is", "currently", "running", ".", "It", "an", "error", "that", "satisfies", "errors", ".", "IsNotFound", "if", "the", "tools", "have", "not", "yet", "been", "set", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L259-L265
156,899
juju/juju
state/unit.go
PasswordValid
func (u *Unit) PasswordValid(password string) bool { agentHash := utils.AgentPasswordHash(password) if agentHash == u.doc.PasswordHash { return true } return false }
go
func (u *Unit) PasswordValid(password string) bool { agentHash := utils.AgentPasswordHash(password) if agentHash == u.doc.PasswordHash { return true } return false }
[ "func", "(", "u", "*", "Unit", ")", "PasswordValid", "(", "password", "string", ")", "bool", "{", "agentHash", ":=", "utils", ".", "AgentPasswordHash", "(", "password", ")", "\n", "if", "agentHash", "==", "u", ".", "doc", ".", "PasswordHash", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// PasswordValid returns whether the given password is valid // for the given unit.
[ "PasswordValid", "returns", "whether", "the", "given", "password", "is", "valid", "for", "the", "given", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L316-L322