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
157,100
juju/juju
apiserver/facades/client/highavailability/highavailability.go
ResumeHAReplicationAfterUpgrade
func (api *HighAvailabilityAPI) ResumeHAReplicationAfterUpgrade(args params.ResumeReplicationParams) error { return api.state.ResumeReplication(args.Members) }
go
func (api *HighAvailabilityAPI) ResumeHAReplicationAfterUpgrade(args params.ResumeReplicationParams) error { return api.state.ResumeReplication(args.Members) }
[ "func", "(", "api", "*", "HighAvailabilityAPI", ")", "ResumeHAReplicationAfterUpgrade", "(", "args", "params", ".", "ResumeReplicationParams", ")", "error", "{", "return", "api", ".", "state", ".", "ResumeReplication", "(", "args", ".", "Members", ")", "\n", "}" ]
// ResumeHAReplicationAfterUpgrade will add the upgraded members of HA // cluster to the upgraded master.
[ "ResumeHAReplicationAfterUpgrade", "will", "add", "the", "upgraded", "members", "of", "HA", "cluster", "to", "the", "upgraded", "master", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/highavailability/highavailability.go#L326-L328
157,101
juju/juju
environs/bootstrap/tools.go
validateUploadAllowed
func validateUploadAllowed(env environs.ConfigGetter, toolsArch, toolsSeries *string, validator constraints.Validator) error { // Now check that the architecture and series for which we are setting up an // environment matches that from which we are bootstrapping. hostArch := arch.HostArch() // We can't build tools for a different architecture if one is specified. if toolsArch != nil && *toolsArch != hostArch { return fmt.Errorf("cannot use agent built for %q using a machine running on %q", *toolsArch, hostArch) } hostOS := jujuos.HostOS() if toolsSeries != nil { toolsSeriesOS, err := series.GetOSFromSeries(*toolsSeries) if err != nil { return errors.Trace(err) } if !toolsSeriesOS.EquivalentTo(hostOS) { return errors.Errorf("cannot use agent built for %q using a machine running %q", *toolsSeries, hostOS) } } // If no architecture is specified, ensure the target provider supports instances matching our architecture. if _, err := validator.Validate(constraints.Value{Arch: &hostArch}); err != nil { return errors.Errorf( "model %q of type %s does not support instances running on %q", env.Config().Name(), env.Config().Type(), hostArch, ) } return nil }
go
func validateUploadAllowed(env environs.ConfigGetter, toolsArch, toolsSeries *string, validator constraints.Validator) error { // Now check that the architecture and series for which we are setting up an // environment matches that from which we are bootstrapping. hostArch := arch.HostArch() // We can't build tools for a different architecture if one is specified. if toolsArch != nil && *toolsArch != hostArch { return fmt.Errorf("cannot use agent built for %q using a machine running on %q", *toolsArch, hostArch) } hostOS := jujuos.HostOS() if toolsSeries != nil { toolsSeriesOS, err := series.GetOSFromSeries(*toolsSeries) if err != nil { return errors.Trace(err) } if !toolsSeriesOS.EquivalentTo(hostOS) { return errors.Errorf("cannot use agent built for %q using a machine running %q", *toolsSeries, hostOS) } } // If no architecture is specified, ensure the target provider supports instances matching our architecture. if _, err := validator.Validate(constraints.Value{Arch: &hostArch}); err != nil { return errors.Errorf( "model %q of type %s does not support instances running on %q", env.Config().Name(), env.Config().Type(), hostArch, ) } return nil }
[ "func", "validateUploadAllowed", "(", "env", "environs", ".", "ConfigGetter", ",", "toolsArch", ",", "toolsSeries", "*", "string", ",", "validator", "constraints", ".", "Validator", ")", "error", "{", "// Now check that the architecture and series for which we are setting up an", "// environment matches that from which we are bootstrapping.", "hostArch", ":=", "arch", ".", "HostArch", "(", ")", "\n", "// We can't build tools for a different architecture if one is specified.", "if", "toolsArch", "!=", "nil", "&&", "*", "toolsArch", "!=", "hostArch", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "*", "toolsArch", ",", "hostArch", ")", "\n", "}", "\n", "hostOS", ":=", "jujuos", ".", "HostOS", "(", ")", "\n", "if", "toolsSeries", "!=", "nil", "{", "toolsSeriesOS", ",", "err", ":=", "series", ".", "GetOSFromSeries", "(", "*", "toolsSeries", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "toolsSeriesOS", ".", "EquivalentTo", "(", "hostOS", ")", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "*", "toolsSeries", ",", "hostOS", ")", "\n", "}", "\n", "}", "\n", "// If no architecture is specified, ensure the target provider supports instances matching our architecture.", "if", "_", ",", "err", ":=", "validator", ".", "Validate", "(", "constraints", ".", "Value", "{", "Arch", ":", "&", "hostArch", "}", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "env", ".", "Config", "(", ")", ".", "Name", "(", ")", ",", "env", ".", "Config", "(", ")", ".", "Type", "(", ")", ",", "hostArch", ",", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateUploadAllowed returns an error if an attempt to upload tools should // not be allowed.
[ "validateUploadAllowed", "returns", "an", "error", "if", "an", "attempt", "to", "upload", "tools", "should", "not", "be", "allowed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/tools.go#L28-L54
157,102
juju/juju
environs/bootstrap/tools.go
findPackagedTools
func findPackagedTools( env environs.BootstrapEnviron, vers *version.Number, arch, series *string, ) (coretools.List, error) { // Look for tools in the environment's simplestreams search paths // for existing tools. // If the user hasn't asked for a specified tools version, see if // one is configured in the environment. if vers == nil { if agentVersion, ok := env.Config().AgentVersion(); ok { vers = &agentVersion } } logger.Infof("looking for bootstrap agent binaries: version=%v", vers) toolsList, findToolsErr := findBootstrapTools(env, vers, arch, series) logger.Infof("found %d packaged agent binaries", len(toolsList)) if findToolsErr != nil { return nil, findToolsErr } return toolsList, nil }
go
func findPackagedTools( env environs.BootstrapEnviron, vers *version.Number, arch, series *string, ) (coretools.List, error) { // Look for tools in the environment's simplestreams search paths // for existing tools. // If the user hasn't asked for a specified tools version, see if // one is configured in the environment. if vers == nil { if agentVersion, ok := env.Config().AgentVersion(); ok { vers = &agentVersion } } logger.Infof("looking for bootstrap agent binaries: version=%v", vers) toolsList, findToolsErr := findBootstrapTools(env, vers, arch, series) logger.Infof("found %d packaged agent binaries", len(toolsList)) if findToolsErr != nil { return nil, findToolsErr } return toolsList, nil }
[ "func", "findPackagedTools", "(", "env", "environs", ".", "BootstrapEnviron", ",", "vers", "*", "version", ".", "Number", ",", "arch", ",", "series", "*", "string", ",", ")", "(", "coretools", ".", "List", ",", "error", ")", "{", "// Look for tools in the environment's simplestreams search paths", "// for existing tools.", "// If the user hasn't asked for a specified tools version, see if", "// one is configured in the environment.", "if", "vers", "==", "nil", "{", "if", "agentVersion", ",", "ok", ":=", "env", ".", "Config", "(", ")", ".", "AgentVersion", "(", ")", ";", "ok", "{", "vers", "=", "&", "agentVersion", "\n", "}", "\n", "}", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "vers", ")", "\n", "toolsList", ",", "findToolsErr", ":=", "findBootstrapTools", "(", "env", ",", "vers", ",", "arch", ",", "series", ")", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "len", "(", "toolsList", ")", ")", "\n", "if", "findToolsErr", "!=", "nil", "{", "return", "nil", ",", "findToolsErr", "\n", "}", "\n", "return", "toolsList", ",", "nil", "\n", "}" ]
// findPackagedTools returns a list of tools for in simplestreams.
[ "findPackagedTools", "returns", "a", "list", "of", "tools", "for", "in", "simplestreams", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/tools.go#L57-L79
157,103
juju/juju
environs/bootstrap/tools.go
locallyBuildableTools
func locallyBuildableTools(toolsSeries *string) (buildable coretools.List, _ version.Number) { buildNumber := jujuversion.Current // Increment the build number so we know it's a custom build. buildNumber.Build++ for _, ser := range series.SupportedSeries() { if os, err := series.GetOSFromSeries(ser); err != nil || !os.EquivalentTo(jujuos.HostOS()) { continue } if toolsSeries != nil && ser != *toolsSeries { continue } binary := version.Binary{ Number: buildNumber, Series: ser, Arch: arch.HostArch(), } buildable = append(buildable, &coretools.Tools{Version: binary}) } return buildable, buildNumber }
go
func locallyBuildableTools(toolsSeries *string) (buildable coretools.List, _ version.Number) { buildNumber := jujuversion.Current // Increment the build number so we know it's a custom build. buildNumber.Build++ for _, ser := range series.SupportedSeries() { if os, err := series.GetOSFromSeries(ser); err != nil || !os.EquivalentTo(jujuos.HostOS()) { continue } if toolsSeries != nil && ser != *toolsSeries { continue } binary := version.Binary{ Number: buildNumber, Series: ser, Arch: arch.HostArch(), } buildable = append(buildable, &coretools.Tools{Version: binary}) } return buildable, buildNumber }
[ "func", "locallyBuildableTools", "(", "toolsSeries", "*", "string", ")", "(", "buildable", "coretools", ".", "List", ",", "_", "version", ".", "Number", ")", "{", "buildNumber", ":=", "jujuversion", ".", "Current", "\n", "// Increment the build number so we know it's a custom build.", "buildNumber", ".", "Build", "++", "\n", "for", "_", ",", "ser", ":=", "range", "series", ".", "SupportedSeries", "(", ")", "{", "if", "os", ",", "err", ":=", "series", ".", "GetOSFromSeries", "(", "ser", ")", ";", "err", "!=", "nil", "||", "!", "os", ".", "EquivalentTo", "(", "jujuos", ".", "HostOS", "(", ")", ")", "{", "continue", "\n", "}", "\n", "if", "toolsSeries", "!=", "nil", "&&", "ser", "!=", "*", "toolsSeries", "{", "continue", "\n", "}", "\n", "binary", ":=", "version", ".", "Binary", "{", "Number", ":", "buildNumber", ",", "Series", ":", "ser", ",", "Arch", ":", "arch", ".", "HostArch", "(", ")", ",", "}", "\n", "buildable", "=", "append", "(", "buildable", ",", "&", "coretools", ".", "Tools", "{", "Version", ":", "binary", "}", ")", "\n", "}", "\n", "return", "buildable", ",", "buildNumber", "\n", "}" ]
// locallyBuildableTools returns the list of tools that // can be built locally, for series of the same OS.
[ "locallyBuildableTools", "returns", "the", "list", "of", "tools", "that", "can", "be", "built", "locally", "for", "series", "of", "the", "same", "OS", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/tools.go#L83-L102
157,104
juju/juju
environs/bootstrap/tools.go
findBootstrapTools
func findBootstrapTools(env environs.BootstrapEnviron, vers *version.Number, arch, series *string) (list coretools.List, err error) { // Construct a tools filter. cliVersion := jujuversion.Current var filter coretools.Filter if arch != nil { filter.Arch = *arch } if series != nil { filter.Series = *series } if vers != nil { filter.Number = *vers } streams := envtools.PreferredStreams(vers, env.Config().Development(), env.Config().AgentStream()) return findTools(env, cliVersion.Major, cliVersion.Minor, streams, filter) }
go
func findBootstrapTools(env environs.BootstrapEnviron, vers *version.Number, arch, series *string) (list coretools.List, err error) { // Construct a tools filter. cliVersion := jujuversion.Current var filter coretools.Filter if arch != nil { filter.Arch = *arch } if series != nil { filter.Series = *series } if vers != nil { filter.Number = *vers } streams := envtools.PreferredStreams(vers, env.Config().Development(), env.Config().AgentStream()) return findTools(env, cliVersion.Major, cliVersion.Minor, streams, filter) }
[ "func", "findBootstrapTools", "(", "env", "environs", ".", "BootstrapEnviron", ",", "vers", "*", "version", ".", "Number", ",", "arch", ",", "series", "*", "string", ")", "(", "list", "coretools", ".", "List", ",", "err", "error", ")", "{", "// Construct a tools filter.", "cliVersion", ":=", "jujuversion", ".", "Current", "\n", "var", "filter", "coretools", ".", "Filter", "\n", "if", "arch", "!=", "nil", "{", "filter", ".", "Arch", "=", "*", "arch", "\n", "}", "\n", "if", "series", "!=", "nil", "{", "filter", ".", "Series", "=", "*", "series", "\n", "}", "\n", "if", "vers", "!=", "nil", "{", "filter", ".", "Number", "=", "*", "vers", "\n", "}", "\n", "streams", ":=", "envtools", ".", "PreferredStreams", "(", "vers", ",", "env", ".", "Config", "(", ")", ".", "Development", "(", ")", ",", "env", ".", "Config", "(", ")", ".", "AgentStream", "(", ")", ")", "\n", "return", "findTools", "(", "env", ",", "cliVersion", ".", "Major", ",", "cliVersion", ".", "Minor", ",", "streams", ",", "filter", ")", "\n", "}" ]
// findBootstrapTools returns a tools.List containing only those tools with // which it would be reasonable to launch an environment's first machine, // given the supplied constraints. If a specific agent version is not requested, // all tools matching the current major.minor version are chosen.
[ "findBootstrapTools", "returns", "a", "tools", ".", "List", "containing", "only", "those", "tools", "with", "which", "it", "would", "be", "reasonable", "to", "launch", "an", "environment", "s", "first", "machine", "given", "the", "supplied", "constraints", ".", "If", "a", "specific", "agent", "version", "is", "not", "requested", "all", "tools", "matching", "the", "current", "major", ".", "minor", "version", "are", "chosen", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/bootstrap/tools.go#L108-L123
157,105
juju/juju
cmd/juju/controller/destroy.go
NewDestroyCommand
func NewDestroyCommand() cmd.Command { cmd := destroyCommand{} cmd.controllerCredentialAPIFunc = cmd.credentialAPIForControllerModel cmd.environsDestroy = environs.Destroy // Even though this command is all about destroying a controller we end up // needing environment endpoints so we can fall back to the client destroy // environment method. This shouldn't really matter in practice as the // user trying to take down the controller will need to have access to the // controller environment anyway. return modelcmd.WrapController( &cmd, modelcmd.WrapControllerSkipControllerFlags, modelcmd.WrapControllerSkipDefaultController, ) }
go
func NewDestroyCommand() cmd.Command { cmd := destroyCommand{} cmd.controllerCredentialAPIFunc = cmd.credentialAPIForControllerModel cmd.environsDestroy = environs.Destroy // Even though this command is all about destroying a controller we end up // needing environment endpoints so we can fall back to the client destroy // environment method. This shouldn't really matter in practice as the // user trying to take down the controller will need to have access to the // controller environment anyway. return modelcmd.WrapController( &cmd, modelcmd.WrapControllerSkipControllerFlags, modelcmd.WrapControllerSkipDefaultController, ) }
[ "func", "NewDestroyCommand", "(", ")", "cmd", ".", "Command", "{", "cmd", ":=", "destroyCommand", "{", "}", "\n", "cmd", ".", "controllerCredentialAPIFunc", "=", "cmd", ".", "credentialAPIForControllerModel", "\n", "cmd", ".", "environsDestroy", "=", "environs", ".", "Destroy", "\n", "// Even though this command is all about destroying a controller we end up", "// needing environment endpoints so we can fall back to the client destroy", "// environment method. This shouldn't really matter in practice as the", "// user trying to take down the controller will need to have access to the", "// controller environment anyway.", "return", "modelcmd", ".", "WrapController", "(", "&", "cmd", ",", "modelcmd", ".", "WrapControllerSkipControllerFlags", ",", "modelcmd", ".", "WrapControllerSkipDefaultController", ",", ")", "\n", "}" ]
// NewDestroyCommand returns a command to destroy a controller.
[ "NewDestroyCommand", "returns", "a", "command", "to", "destroy", "a", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/destroy.go#L38-L52
157,106
juju/juju
cmd/juju/controller/destroy.go
checkNoAliveHostedModels
func (c *destroyCommand) checkNoAliveHostedModels(ctx *cmd.Context, models []modelData) error { if !hasAliveModels(models) { return nil } // The user did not specify --destroy-all-models, // and there are models still alive. var buf bytes.Buffer for _, model := range models { if model.Life != string(params.Alive) { continue } buf.WriteString(fmtModelStatus(model)) buf.WriteRune('\n') } controllerName, err := c.ControllerName() if err != nil { return errors.Trace(err) } return errors.Errorf(`cannot destroy controller %q The controller has live hosted models. If you want to destroy all hosted models in the controller, run this command again with the --destroy-all-models option. Models: %s`, controllerName, buf.String()) }
go
func (c *destroyCommand) checkNoAliveHostedModels(ctx *cmd.Context, models []modelData) error { if !hasAliveModels(models) { return nil } // The user did not specify --destroy-all-models, // and there are models still alive. var buf bytes.Buffer for _, model := range models { if model.Life != string(params.Alive) { continue } buf.WriteString(fmtModelStatus(model)) buf.WriteRune('\n') } controllerName, err := c.ControllerName() if err != nil { return errors.Trace(err) } return errors.Errorf(`cannot destroy controller %q The controller has live hosted models. If you want to destroy all hosted models in the controller, run this command again with the --destroy-all-models option. Models: %s`, controllerName, buf.String()) }
[ "func", "(", "c", "*", "destroyCommand", ")", "checkNoAliveHostedModels", "(", "ctx", "*", "cmd", ".", "Context", ",", "models", "[", "]", "modelData", ")", "error", "{", "if", "!", "hasAliveModels", "(", "models", ")", "{", "return", "nil", "\n", "}", "\n", "// The user did not specify --destroy-all-models,", "// and there are models still alive.", "var", "buf", "bytes", ".", "Buffer", "\n", "for", "_", ",", "model", ":=", "range", "models", "{", "if", "model", ".", "Life", "!=", "string", "(", "params", ".", "Alive", ")", "{", "continue", "\n", "}", "\n", "buf", ".", "WriteString", "(", "fmtModelStatus", "(", "model", ")", ")", "\n", "buf", ".", "WriteRune", "(", "'\\n'", ")", "\n", "}", "\n", "controllerName", ",", "err", ":=", "c", ".", "ControllerName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "errors", ".", "Errorf", "(", "`cannot destroy controller %q\n\nThe controller has live hosted models. If you want\nto destroy all hosted models in the controller,\nrun this command again with the --destroy-all-models\noption.\n\nModels:\n%s`", ",", "controllerName", ",", "buf", ".", "String", "(", ")", ")", "\n", "}" ]
// checkNoAliveHostedModels ensures that the given set of hosted models // contains none that are Alive. If there are, an message is printed // out to
[ "checkNoAliveHostedModels", "ensures", "that", "the", "given", "set", "of", "hosted", "models", "contains", "none", "that", "are", "Alive", ".", "If", "there", "are", "an", "message", "is", "printed", "out", "to" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/destroy.go#L316-L343
157,107
juju/juju
cmd/juju/controller/destroy.go
checkNoPersistentStorage
func (c *destroyCommand) checkNoPersistentStorage(ctx *cmd.Context, envStatus environmentStatus) error { models := append([]modelData{envStatus.controller.Model}, envStatus.models...) var modelsWithPersistentStorage int var persistentVolumesTotal int var persistentFilesystemsTotal int for _, m := range models { if m.PersistentVolumeCount+m.PersistentFilesystemCount == 0 { continue } modelsWithPersistentStorage++ persistentVolumesTotal += m.PersistentVolumeCount persistentFilesystemsTotal += m.PersistentFilesystemCount } var buf bytes.Buffer if n := persistentVolumesTotal; n > 0 { fmt.Fprintf(&buf, "%d volume", n) if n > 1 { buf.WriteRune('s') } if persistentFilesystemsTotal > 0 { buf.WriteString(" and ") } } if n := persistentFilesystemsTotal; n > 0 { fmt.Fprintf(&buf, "%d filesystem", n) if n > 1 { buf.WriteRune('s') } } buf.WriteRune(' ') if n := modelsWithPersistentStorage; n == 1 { buf.WriteString("in 1 model") } else { fmt.Fprintf(&buf, "across %d models", n) } controllerName, err := c.ControllerName() if err != nil { return errors.Trace(err) } return errors.Errorf(`cannot destroy controller %q The controller has persistent storage remaining: %s To destroy the storage, run the destroy-controller command again with the "--destroy-storage" option. To release the storage from Juju's management without destroying it, use the "--release-storage" option instead. The storage can then be imported into another Juju model. `, controllerName, buf.String()) }
go
func (c *destroyCommand) checkNoPersistentStorage(ctx *cmd.Context, envStatus environmentStatus) error { models := append([]modelData{envStatus.controller.Model}, envStatus.models...) var modelsWithPersistentStorage int var persistentVolumesTotal int var persistentFilesystemsTotal int for _, m := range models { if m.PersistentVolumeCount+m.PersistentFilesystemCount == 0 { continue } modelsWithPersistentStorage++ persistentVolumesTotal += m.PersistentVolumeCount persistentFilesystemsTotal += m.PersistentFilesystemCount } var buf bytes.Buffer if n := persistentVolumesTotal; n > 0 { fmt.Fprintf(&buf, "%d volume", n) if n > 1 { buf.WriteRune('s') } if persistentFilesystemsTotal > 0 { buf.WriteString(" and ") } } if n := persistentFilesystemsTotal; n > 0 { fmt.Fprintf(&buf, "%d filesystem", n) if n > 1 { buf.WriteRune('s') } } buf.WriteRune(' ') if n := modelsWithPersistentStorage; n == 1 { buf.WriteString("in 1 model") } else { fmt.Fprintf(&buf, "across %d models", n) } controllerName, err := c.ControllerName() if err != nil { return errors.Trace(err) } return errors.Errorf(`cannot destroy controller %q The controller has persistent storage remaining: %s To destroy the storage, run the destroy-controller command again with the "--destroy-storage" option. To release the storage from Juju's management without destroying it, use the "--release-storage" option instead. The storage can then be imported into another Juju model. `, controllerName, buf.String()) }
[ "func", "(", "c", "*", "destroyCommand", ")", "checkNoPersistentStorage", "(", "ctx", "*", "cmd", ".", "Context", ",", "envStatus", "environmentStatus", ")", "error", "{", "models", ":=", "append", "(", "[", "]", "modelData", "{", "envStatus", ".", "controller", ".", "Model", "}", ",", "envStatus", ".", "models", "...", ")", "\n\n", "var", "modelsWithPersistentStorage", "int", "\n", "var", "persistentVolumesTotal", "int", "\n", "var", "persistentFilesystemsTotal", "int", "\n", "for", "_", ",", "m", ":=", "range", "models", "{", "if", "m", ".", "PersistentVolumeCount", "+", "m", ".", "PersistentFilesystemCount", "==", "0", "{", "continue", "\n", "}", "\n", "modelsWithPersistentStorage", "++", "\n", "persistentVolumesTotal", "+=", "m", ".", "PersistentVolumeCount", "\n", "persistentFilesystemsTotal", "+=", "m", ".", "PersistentFilesystemCount", "\n", "}", "\n\n", "var", "buf", "bytes", ".", "Buffer", "\n", "if", "n", ":=", "persistentVolumesTotal", ";", "n", ">", "0", "{", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\"", ",", "n", ")", "\n", "if", "n", ">", "1", "{", "buf", ".", "WriteRune", "(", "'s'", ")", "\n", "}", "\n", "if", "persistentFilesystemsTotal", ">", "0", "{", "buf", ".", "WriteString", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "if", "n", ":=", "persistentFilesystemsTotal", ";", "n", ">", "0", "{", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\"", ",", "n", ")", "\n", "if", "n", ">", "1", "{", "buf", ".", "WriteRune", "(", "'s'", ")", "\n", "}", "\n", "}", "\n", "buf", ".", "WriteRune", "(", "' '", ")", "\n", "if", "n", ":=", "modelsWithPersistentStorage", ";", "n", "==", "1", "{", "buf", ".", "WriteString", "(", "\"", "\"", ")", "\n", "}", "else", "{", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\"", ",", "n", ")", "\n", "}", "\n\n", "controllerName", ",", "err", ":=", "c", ".", "ControllerName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "errors", ".", "Errorf", "(", "`cannot destroy controller %q\n\nThe controller has persistent storage remaining:\n\t%s\n\nTo destroy the storage, run the destroy-controller\ncommand again with the \"--destroy-storage\" option.\n\nTo release the storage from Juju's management\nwithout destroying it, use the \"--release-storage\"\noption instead. The storage can then be imported\ninto another Juju model.\n\n`", ",", "controllerName", ",", "buf", ".", "String", "(", ")", ")", "\n", "}" ]
// checkNoPersistentStorage ensures that the controller contains // no persistent storage. If there is any, a message is printed // out informing the user that they must choose to destroy or // release the storage.
[ "checkNoPersistentStorage", "ensures", "that", "the", "controller", "contains", "no", "persistent", "storage", ".", "If", "there", "is", "any", "a", "message", "is", "printed", "out", "informing", "the", "user", "that", "they", "must", "choose", "to", "destroy", "or", "release", "the", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/destroy.go#L349-L406
157,108
juju/juju
cmd/juju/controller/destroy.go
ensureUserFriendlyErrorLog
func (c *destroyCommand) ensureUserFriendlyErrorLog(destroyErr error, ctx *cmd.Context, api destroyControllerAPI) error { if destroyErr == nil { return nil } if params.IsCodeOperationBlocked(destroyErr) { logger.Errorf(destroyControllerBlockedMsg) if api != nil { models, err := api.ListBlockedModels() out := &bytes.Buffer{} if err == nil { var info interface{} info, err = block.FormatModelBlockInfo(models) if err != nil { return errors.Trace(err) } err = block.FormatTabularBlockedModels(out, info) } if err != nil { logger.Errorf("Unable to list models: %s", err) return cmd.ErrSilent } ctx.Infof(out.String()) } return cmd.ErrSilent } controllerName, err := c.ControllerName() if err != nil { return errors.Trace(err) } logger.Errorf(stdFailureMsg, controllerName) return destroyErr }
go
func (c *destroyCommand) ensureUserFriendlyErrorLog(destroyErr error, ctx *cmd.Context, api destroyControllerAPI) error { if destroyErr == nil { return nil } if params.IsCodeOperationBlocked(destroyErr) { logger.Errorf(destroyControllerBlockedMsg) if api != nil { models, err := api.ListBlockedModels() out := &bytes.Buffer{} if err == nil { var info interface{} info, err = block.FormatModelBlockInfo(models) if err != nil { return errors.Trace(err) } err = block.FormatTabularBlockedModels(out, info) } if err != nil { logger.Errorf("Unable to list models: %s", err) return cmd.ErrSilent } ctx.Infof(out.String()) } return cmd.ErrSilent } controllerName, err := c.ControllerName() if err != nil { return errors.Trace(err) } logger.Errorf(stdFailureMsg, controllerName) return destroyErr }
[ "func", "(", "c", "*", "destroyCommand", ")", "ensureUserFriendlyErrorLog", "(", "destroyErr", "error", ",", "ctx", "*", "cmd", ".", "Context", ",", "api", "destroyControllerAPI", ")", "error", "{", "if", "destroyErr", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "params", ".", "IsCodeOperationBlocked", "(", "destroyErr", ")", "{", "logger", ".", "Errorf", "(", "destroyControllerBlockedMsg", ")", "\n", "if", "api", "!=", "nil", "{", "models", ",", "err", ":=", "api", ".", "ListBlockedModels", "(", ")", "\n", "out", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", "==", "nil", "{", "var", "info", "interface", "{", "}", "\n", "info", ",", "err", "=", "block", ".", "FormatModelBlockInfo", "(", "models", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "err", "=", "block", ".", "FormatTabularBlockedModels", "(", "out", ",", "info", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "cmd", ".", "ErrSilent", "\n", "}", "\n", "ctx", ".", "Infof", "(", "out", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "cmd", ".", "ErrSilent", "\n", "}", "\n", "controllerName", ",", "err", ":=", "c", ".", "ControllerName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Errorf", "(", "stdFailureMsg", ",", "controllerName", ")", "\n", "return", "destroyErr", "\n", "}" ]
// ensureUserFriendlyErrorLog ensures that error will be logged and displayed // in a user-friendly manner with readable and digestable error message.
[ "ensureUserFriendlyErrorLog", "ensures", "that", "error", "will", "be", "logged", "and", "displayed", "in", "a", "user", "-", "friendly", "manner", "with", "readable", "and", "digestable", "error", "message", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/destroy.go#L410-L441
157,109
juju/juju
cmd/juju/controller/destroy.go
getControllerEnviron
func (c *destroyCommandBase) getControllerEnviron( ctx *cmd.Context, store jujuclient.ClientStore, controllerName string, sysAPI destroyControllerAPI, ) (environs.BootstrapEnviron, error) { // TODO: (hml) 2018-08-01 // We should try to destroy via the API first, from store is a // fall back position. env, err := c.getControllerEnvironFromStore(ctx, store, controllerName) if errors.IsNotFound(err) { return c.getControllerEnvironFromAPI(sysAPI, controllerName) } else if err != nil { return nil, errors.Annotate(err, "getting environ using bootstrap config from client store") } return env, nil }
go
func (c *destroyCommandBase) getControllerEnviron( ctx *cmd.Context, store jujuclient.ClientStore, controllerName string, sysAPI destroyControllerAPI, ) (environs.BootstrapEnviron, error) { // TODO: (hml) 2018-08-01 // We should try to destroy via the API first, from store is a // fall back position. env, err := c.getControllerEnvironFromStore(ctx, store, controllerName) if errors.IsNotFound(err) { return c.getControllerEnvironFromAPI(sysAPI, controllerName) } else if err != nil { return nil, errors.Annotate(err, "getting environ using bootstrap config from client store") } return env, nil }
[ "func", "(", "c", "*", "destroyCommandBase", ")", "getControllerEnviron", "(", "ctx", "*", "cmd", ".", "Context", ",", "store", "jujuclient", ".", "ClientStore", ",", "controllerName", "string", ",", "sysAPI", "destroyControllerAPI", ",", ")", "(", "environs", ".", "BootstrapEnviron", ",", "error", ")", "{", "// TODO: (hml) 2018-08-01", "// We should try to destroy via the API first, from store is a", "// fall back position.", "env", ",", "err", ":=", "c", ".", "getControllerEnvironFromStore", "(", "ctx", ",", "store", ",", "controllerName", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "c", ".", "getControllerEnvironFromAPI", "(", "sysAPI", ",", "controllerName", ")", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "env", ",", "nil", "\n", "}" ]
// getControllerEnviron returns the Environ for the controller model. // // getControllerEnviron gets the information required to get the // Environ by first checking the config store, then querying the // API if the information is not in the store.
[ "getControllerEnviron", "returns", "the", "Environ", "for", "the", "controller", "model", ".", "getControllerEnviron", "gets", "the", "information", "required", "to", "get", "the", "Environ", "by", "first", "checking", "the", "config", "store", "then", "querying", "the", "API", "if", "the", "information", "is", "not", "in", "the", "store", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/destroy.go#L533-L549
157,110
juju/juju
state/machine_upgradeseries.go
CreateUpgradeSeriesLock
func (m *Machine) CreateUpgradeSeriesLock(unitNames []string, toSeries string) error { buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := m.Refresh(); err != nil { return nil, errors.Trace(err) } } locked, err := m.IsLockedForSeriesUpgrade() if err != nil { return nil, errors.Trace(err) } if locked { return nil, errors.AlreadyExistsf("upgrade series lock for machine %q", m) } if err = m.isStillAlive(); err != nil { return nil, errors.Trace(err) } // Exit early if the Machine series doesn't need to change. fromSeries := m.Series() if fromSeries == toSeries { return nil, errors.Trace(errors.Errorf("machine %s already at series %s", m.Id(), toSeries)) } // If the units have changed, the verification is no longer valid. changed, err := m.unitsHaveChanged(unitNames) if err != nil { return nil, errors.Trace(err) } if changed { return nil, errors.Errorf("Units have changed, please retry (%v)", unitNames) } data := m.prepareUpgradeSeriesLock(unitNames, toSeries) return createUpgradeSeriesLockTxnOps(m.doc.Id, data), nil } err := m.st.db().Run(buildTxn) if err != nil { err = onAbort(err, ErrDead) logger.Errorf("cannot prepare series upgrade for machine %q: %v", m, err) return err } return errors.Trace(m.setUpgradeSeriesInstanceStatus(model.UpgradeSeriesPrepareStarted)) }
go
func (m *Machine) CreateUpgradeSeriesLock(unitNames []string, toSeries string) error { buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := m.Refresh(); err != nil { return nil, errors.Trace(err) } } locked, err := m.IsLockedForSeriesUpgrade() if err != nil { return nil, errors.Trace(err) } if locked { return nil, errors.AlreadyExistsf("upgrade series lock for machine %q", m) } if err = m.isStillAlive(); err != nil { return nil, errors.Trace(err) } // Exit early if the Machine series doesn't need to change. fromSeries := m.Series() if fromSeries == toSeries { return nil, errors.Trace(errors.Errorf("machine %s already at series %s", m.Id(), toSeries)) } // If the units have changed, the verification is no longer valid. changed, err := m.unitsHaveChanged(unitNames) if err != nil { return nil, errors.Trace(err) } if changed { return nil, errors.Errorf("Units have changed, please retry (%v)", unitNames) } data := m.prepareUpgradeSeriesLock(unitNames, toSeries) return createUpgradeSeriesLockTxnOps(m.doc.Id, data), nil } err := m.st.db().Run(buildTxn) if err != nil { err = onAbort(err, ErrDead) logger.Errorf("cannot prepare series upgrade for machine %q: %v", m, err) return err } return errors.Trace(m.setUpgradeSeriesInstanceStatus(model.UpgradeSeriesPrepareStarted)) }
[ "func", "(", "m", "*", "Machine", ")", "CreateUpgradeSeriesLock", "(", "unitNames", "[", "]", "string", ",", "toSeries", "string", ")", "error", "{", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "attempt", ">", "0", "{", "if", "err", ":=", "m", ".", "Refresh", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "locked", ",", "err", ":=", "m", ".", "IsLockedForSeriesUpgrade", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "locked", "{", "return", "nil", ",", "errors", ".", "AlreadyExistsf", "(", "\"", "\"", ",", "m", ")", "\n", "}", "\n", "if", "err", "=", "m", ".", "isStillAlive", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// Exit early if the Machine series doesn't need to change.", "fromSeries", ":=", "m", ".", "Series", "(", ")", "\n", "if", "fromSeries", "==", "toSeries", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "errors", ".", "Errorf", "(", "\"", "\"", ",", "m", ".", "Id", "(", ")", ",", "toSeries", ")", ")", "\n", "}", "\n", "// If the units have changed, the verification is no longer valid.", "changed", ",", "err", ":=", "m", ".", "unitsHaveChanged", "(", "unitNames", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "changed", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "unitNames", ")", "\n", "}", "\n", "data", ":=", "m", ".", "prepareUpgradeSeriesLock", "(", "unitNames", ",", "toSeries", ")", "\n", "return", "createUpgradeSeriesLockTxnOps", "(", "m", ".", "doc", ".", "Id", ",", "data", ")", ",", "nil", "\n", "}", "\n", "err", ":=", "m", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "onAbort", "(", "err", ",", "ErrDead", ")", "\n", "logger", ".", "Errorf", "(", "\"", "\"", ",", "m", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "return", "errors", ".", "Trace", "(", "m", ".", "setUpgradeSeriesInstanceStatus", "(", "model", ".", "UpgradeSeriesPrepareStarted", ")", ")", "\n", "}" ]
// CreateUpgradeSeriesLock create a prepare lock for series upgrade. If // this item exists in the database for a given machine it indicates that a // machine's operating system is being upgraded from one series to another; // for example, from xenial to bionic.
[ "CreateUpgradeSeriesLock", "create", "a", "prepare", "lock", "for", "series", "upgrade", ".", "If", "this", "item", "exists", "in", "the", "database", "for", "a", "given", "machine", "it", "indicates", "that", "a", "machine", "s", "operating", "system", "is", "being", "upgraded", "from", "one", "series", "to", "another", ";", "for", "example", "from", "xenial", "to", "bionic", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L62-L103
157,111
juju/juju
state/machine_upgradeseries.go
IsParentLockedForSeriesUpgrade
func (m *Machine) IsParentLockedForSeriesUpgrade() (bool, error) { parentId, isContainer := m.ParentId() if !isContainer { return false, nil } parent, err := m.st.Machine(parentId) if err != nil { return false, errors.Trace(err) } locked, err := parent.IsLockedForSeriesUpgrade() return locked, errors.Trace(err) }
go
func (m *Machine) IsParentLockedForSeriesUpgrade() (bool, error) { parentId, isContainer := m.ParentId() if !isContainer { return false, nil } parent, err := m.st.Machine(parentId) if err != nil { return false, errors.Trace(err) } locked, err := parent.IsLockedForSeriesUpgrade() return locked, errors.Trace(err) }
[ "func", "(", "m", "*", "Machine", ")", "IsParentLockedForSeriesUpgrade", "(", ")", "(", "bool", ",", "error", ")", "{", "parentId", ",", "isContainer", ":=", "m", ".", "ParentId", "(", ")", "\n", "if", "!", "isContainer", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "parent", ",", "err", ":=", "m", ".", "st", ".", "Machine", "(", "parentId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "locked", ",", "err", ":=", "parent", ".", "IsLockedForSeriesUpgrade", "(", ")", "\n", "return", "locked", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// IsParentLockedForSeriesUpgrade determines if a machine is a container who's // parent is locked for series upgrade.
[ "IsParentLockedForSeriesUpgrade", "determines", "if", "a", "machine", "is", "a", "container", "who", "s", "parent", "is", "locked", "for", "series", "upgrade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L107-L120
157,112
juju/juju
state/machine_upgradeseries.go
IsLockedForSeriesUpgrade
func (m *Machine) IsLockedForSeriesUpgrade() (bool, error) { _, err := m.getUpgradeSeriesLock() if err == nil { return true, nil } if errors.IsNotFound(err) { return false, nil } return false, errors.Trace(err) }
go
func (m *Machine) IsLockedForSeriesUpgrade() (bool, error) { _, err := m.getUpgradeSeriesLock() if err == nil { return true, nil } if errors.IsNotFound(err) { return false, nil } return false, errors.Trace(err) }
[ "func", "(", "m", "*", "Machine", ")", "IsLockedForSeriesUpgrade", "(", ")", "(", "bool", ",", "error", ")", "{", "_", ",", "err", ":=", "m", ".", "getUpgradeSeriesLock", "(", ")", "\n", "if", "err", "==", "nil", "{", "return", "true", ",", "nil", "\n", "}", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// IsLockedForSeriesUpgrade determines if a machine is locked for upgrade series.
[ "IsLockedForSeriesUpgrade", "determines", "if", "a", "machine", "is", "locked", "for", "upgrade", "series", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L123-L132
157,113
juju/juju
state/machine_upgradeseries.go
UpgradeSeriesTarget
func (m *Machine) UpgradeSeriesTarget() (string, error) { lock, err := m.getUpgradeSeriesLock() if err != nil { return "", errors.Trace(err) } return lock.ToSeries, nil }
go
func (m *Machine) UpgradeSeriesTarget() (string, error) { lock, err := m.getUpgradeSeriesLock() if err != nil { return "", errors.Trace(err) } return lock.ToSeries, nil }
[ "func", "(", "m", "*", "Machine", ")", "UpgradeSeriesTarget", "(", ")", "(", "string", ",", "error", ")", "{", "lock", ",", "err", ":=", "m", ".", "getUpgradeSeriesLock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "lock", ".", "ToSeries", ",", "nil", "\n", "}" ]
// UpgradeSeriesTarget returns the series // that the machine is being upgraded to.
[ "UpgradeSeriesTarget", "returns", "the", "series", "that", "the", "machine", "is", "being", "upgraded", "to", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L190-L196
157,114
juju/juju
state/machine_upgradeseries.go
StartUpgradeSeriesUnitCompletion
func (m *Machine) StartUpgradeSeriesUnitCompletion(message string) error { buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := m.Refresh(); err != nil { return nil, errors.Trace(err) } } if err := m.isStillAlive(); err != nil { return nil, errors.Trace(err) } lock, err := m.getUpgradeSeriesLock() if err != nil { return nil, err } if lock.MachineStatus != model.UpgradeSeriesCompleteStarted { return nil, fmt.Errorf("machine %q can not complete its unit, the machine has not yet been marked as completed", m.Id()) } timestamp := bson.Now() lock.Messages = append(lock.Messages, newUpgradeSeriesMessage(m.Tag().String(), message, timestamp)) lock.TimeStamp = timestamp changeCount := 0 for unitName, us := range lock.UnitStatuses { if us.Status == model.UpgradeSeriesCompleteStarted { continue } us.Status = model.UpgradeSeriesCompleteStarted us.Timestamp = timestamp lock.UnitStatuses[unitName] = us changeCount++ } if changeCount == 0 { return nil, jujutxn.ErrNoOperations } return startUpgradeSeriesUnitCompletionTxnOps(m.doc.Id, lock), nil } err := m.st.db().Run(buildTxn) if err != nil { err = onAbort(err, ErrDead) return err } return nil }
go
func (m *Machine) StartUpgradeSeriesUnitCompletion(message string) error { buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := m.Refresh(); err != nil { return nil, errors.Trace(err) } } if err := m.isStillAlive(); err != nil { return nil, errors.Trace(err) } lock, err := m.getUpgradeSeriesLock() if err != nil { return nil, err } if lock.MachineStatus != model.UpgradeSeriesCompleteStarted { return nil, fmt.Errorf("machine %q can not complete its unit, the machine has not yet been marked as completed", m.Id()) } timestamp := bson.Now() lock.Messages = append(lock.Messages, newUpgradeSeriesMessage(m.Tag().String(), message, timestamp)) lock.TimeStamp = timestamp changeCount := 0 for unitName, us := range lock.UnitStatuses { if us.Status == model.UpgradeSeriesCompleteStarted { continue } us.Status = model.UpgradeSeriesCompleteStarted us.Timestamp = timestamp lock.UnitStatuses[unitName] = us changeCount++ } if changeCount == 0 { return nil, jujutxn.ErrNoOperations } return startUpgradeSeriesUnitCompletionTxnOps(m.doc.Id, lock), nil } err := m.st.db().Run(buildTxn) if err != nil { err = onAbort(err, ErrDead) return err } return nil }
[ "func", "(", "m", "*", "Machine", ")", "StartUpgradeSeriesUnitCompletion", "(", "message", "string", ")", "error", "{", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "attempt", ">", "0", "{", "if", "err", ":=", "m", ".", "Refresh", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "m", ".", "isStillAlive", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "lock", ",", "err", ":=", "m", ".", "getUpgradeSeriesLock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "lock", ".", "MachineStatus", "!=", "model", ".", "UpgradeSeriesCompleteStarted", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "m", ".", "Id", "(", ")", ")", "\n", "}", "\n", "timestamp", ":=", "bson", ".", "Now", "(", ")", "\n", "lock", ".", "Messages", "=", "append", "(", "lock", ".", "Messages", ",", "newUpgradeSeriesMessage", "(", "m", ".", "Tag", "(", ")", ".", "String", "(", ")", ",", "message", ",", "timestamp", ")", ")", "\n", "lock", ".", "TimeStamp", "=", "timestamp", "\n", "changeCount", ":=", "0", "\n", "for", "unitName", ",", "us", ":=", "range", "lock", ".", "UnitStatuses", "{", "if", "us", ".", "Status", "==", "model", ".", "UpgradeSeriesCompleteStarted", "{", "continue", "\n", "}", "\n", "us", ".", "Status", "=", "model", ".", "UpgradeSeriesCompleteStarted", "\n", "us", ".", "Timestamp", "=", "timestamp", "\n", "lock", ".", "UnitStatuses", "[", "unitName", "]", "=", "us", "\n", "changeCount", "++", "\n", "}", "\n", "if", "changeCount", "==", "0", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "\n", "return", "startUpgradeSeriesUnitCompletionTxnOps", "(", "m", ".", "doc", ".", "Id", ",", "lock", ")", ",", "nil", "\n", "}", "\n", "err", ":=", "m", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "onAbort", "(", "err", ",", "ErrDead", ")", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// StartUpgradeSeriesUnitCompletion notifies units that an upgrade-series // workflow is ready for its "completion" phase.
[ "StartUpgradeSeriesUnitCompletion", "notifies", "units", "that", "an", "upgrade", "-", "series", "workflow", "is", "ready", "for", "its", "completion", "phase", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L200-L241
157,115
juju/juju
state/machine_upgradeseries.go
CompleteUpgradeSeries
func (m *Machine) CompleteUpgradeSeries() error { buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := m.Refresh(); err != nil { return nil, errors.Trace(err) } } if err := m.isStillAlive(); err != nil { return nil, errors.Trace(err) } readyForCompletion, err := m.isReadyForCompletion() if err != nil { return nil, errors.Trace(err) } if !readyForCompletion { return nil, fmt.Errorf("machine %q can not complete, it is either not prepared or already completed", m.Id()) } timestamp := bson.Now() message := newUpgradeSeriesMessage(m.Tag().String(), "complete phase started", timestamp) return completeUpgradeSeriesTxnOps(m.doc.Id, timestamp, message), nil } err := m.st.db().Run(buildTxn) if err != nil { err = onAbort(err, ErrDead) return err } return errors.Trace(m.setUpgradeSeriesInstanceStatus(model.UpgradeSeriesCompleteStarted)) }
go
func (m *Machine) CompleteUpgradeSeries() error { buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := m.Refresh(); err != nil { return nil, errors.Trace(err) } } if err := m.isStillAlive(); err != nil { return nil, errors.Trace(err) } readyForCompletion, err := m.isReadyForCompletion() if err != nil { return nil, errors.Trace(err) } if !readyForCompletion { return nil, fmt.Errorf("machine %q can not complete, it is either not prepared or already completed", m.Id()) } timestamp := bson.Now() message := newUpgradeSeriesMessage(m.Tag().String(), "complete phase started", timestamp) return completeUpgradeSeriesTxnOps(m.doc.Id, timestamp, message), nil } err := m.st.db().Run(buildTxn) if err != nil { err = onAbort(err, ErrDead) return err } return errors.Trace(m.setUpgradeSeriesInstanceStatus(model.UpgradeSeriesCompleteStarted)) }
[ "func", "(", "m", "*", "Machine", ")", "CompleteUpgradeSeries", "(", ")", "error", "{", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "attempt", ">", "0", "{", "if", "err", ":=", "m", ".", "Refresh", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "m", ".", "isStillAlive", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "readyForCompletion", ",", "err", ":=", "m", ".", "isReadyForCompletion", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "readyForCompletion", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "m", ".", "Id", "(", ")", ")", "\n", "}", "\n", "timestamp", ":=", "bson", ".", "Now", "(", ")", "\n", "message", ":=", "newUpgradeSeriesMessage", "(", "m", ".", "Tag", "(", ")", ".", "String", "(", ")", ",", "\"", "\"", ",", "timestamp", ")", "\n", "return", "completeUpgradeSeriesTxnOps", "(", "m", ".", "doc", ".", "Id", ",", "timestamp", ",", "message", ")", ",", "nil", "\n", "}", "\n", "err", ":=", "m", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "onAbort", "(", "err", ",", "ErrDead", ")", "\n", "return", "err", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "m", ".", "setUpgradeSeriesInstanceStatus", "(", "model", ".", "UpgradeSeriesCompleteStarted", ")", ")", "\n", "}" ]
// CompleteUpgradeSeries notifies units and machines that an upgrade series is // ready for its "completion" phase.
[ "CompleteUpgradeSeries", "notifies", "units", "and", "machines", "that", "an", "upgrade", "series", "is", "ready", "for", "its", "completion", "phase", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L265-L292
157,116
juju/juju
state/machine_upgradeseries.go
UpgradeSeriesUnitStatus
func (m *Machine) UpgradeSeriesUnitStatus(unitName string) (model.UpgradeSeriesStatus, error) { coll, closer := m.st.db().GetCollection(machineUpgradeSeriesLocksC) defer closer() var lock upgradeSeriesLockDoc err := coll.FindId(m.Id()).One(&lock) if err == mgo.ErrNotFound { return "", errors.NotFoundf("upgrade series lock for machine %q", m.Id()) } if err != nil { return "", errors.Trace(err) } if _, ok := lock.UnitStatuses[unitName]; !ok { return "", errors.NotFoundf("unit %q of machine %q", unitName, m.Id()) } return lock.UnitStatuses[unitName].Status, nil }
go
func (m *Machine) UpgradeSeriesUnitStatus(unitName string) (model.UpgradeSeriesStatus, error) { coll, closer := m.st.db().GetCollection(machineUpgradeSeriesLocksC) defer closer() var lock upgradeSeriesLockDoc err := coll.FindId(m.Id()).One(&lock) if err == mgo.ErrNotFound { return "", errors.NotFoundf("upgrade series lock for machine %q", m.Id()) } if err != nil { return "", errors.Trace(err) } if _, ok := lock.UnitStatuses[unitName]; !ok { return "", errors.NotFoundf("unit %q of machine %q", unitName, m.Id()) } return lock.UnitStatuses[unitName].Status, nil }
[ "func", "(", "m", "*", "Machine", ")", "UpgradeSeriesUnitStatus", "(", "unitName", "string", ")", "(", "model", ".", "UpgradeSeriesStatus", ",", "error", ")", "{", "coll", ",", "closer", ":=", "m", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "machineUpgradeSeriesLocksC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "var", "lock", "upgradeSeriesLockDoc", "\n", "err", ":=", "coll", ".", "FindId", "(", "m", ".", "Id", "(", ")", ")", ".", "One", "(", "&", "lock", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "\"", "\"", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "m", ".", "Id", "(", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "lock", ".", "UnitStatuses", "[", "unitName", "]", ";", "!", "ok", "{", "return", "\"", "\"", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "unitName", ",", "m", ".", "Id", "(", ")", ")", "\n", "}", "\n\n", "return", "lock", ".", "UnitStatuses", "[", "unitName", "]", ".", "Status", ",", "nil", "\n", "}" ]
// UnitStatus returns the series upgrade status for the input unit.
[ "UnitStatus", "returns", "the", "series", "upgrade", "status", "for", "the", "input", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L375-L392
157,117
juju/juju
state/machine_upgradeseries.go
UpgradeSeriesUnitStatuses
func (m *Machine) UpgradeSeriesUnitStatuses() (map[string]UpgradeSeriesUnitStatus, error) { lock, err := m.getUpgradeSeriesLock() if err != nil { return nil, errors.Trace(err) } return lock.UnitStatuses, nil }
go
func (m *Machine) UpgradeSeriesUnitStatuses() (map[string]UpgradeSeriesUnitStatus, error) { lock, err := m.getUpgradeSeriesLock() if err != nil { return nil, errors.Trace(err) } return lock.UnitStatuses, nil }
[ "func", "(", "m", "*", "Machine", ")", "UpgradeSeriesUnitStatuses", "(", ")", "(", "map", "[", "string", "]", "UpgradeSeriesUnitStatus", ",", "error", ")", "{", "lock", ",", "err", ":=", "m", ".", "getUpgradeSeriesLock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "lock", ".", "UnitStatuses", ",", "nil", "\n", "}" ]
// UnitStatus returns the unit statuses from the upgrade-series lock // for this machine.
[ "UnitStatus", "returns", "the", "unit", "statuses", "from", "the", "upgrade", "-", "series", "lock", "for", "this", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L396-L402
157,118
juju/juju
state/machine_upgradeseries.go
SetUpgradeSeriesUnitStatus
func (m *Machine) SetUpgradeSeriesUnitStatus(unitName string, status model.UpgradeSeriesStatus, message string) error { buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := m.Refresh(); err != nil { return nil, errors.Trace(err) } } if err := m.isStillAlive(); err != nil { return nil, errors.Trace(err) } canUpdate, err := m.verifyUnitUpgradeSeriesStatus(unitName, status) if err != nil { return nil, errors.Trace(err) } if !canUpdate { return nil, jujutxn.ErrNoOperations } timestamp := bson.Now() updateMessage := newUpgradeSeriesMessage(unitName, message, timestamp) return setUpgradeSeriesTxnOps(m.doc.Id, unitName, status, timestamp, updateMessage) } err := m.st.db().Run(buildTxn) if err != nil { err = onAbort(err, ErrDead) return err } return nil }
go
func (m *Machine) SetUpgradeSeriesUnitStatus(unitName string, status model.UpgradeSeriesStatus, message string) error { buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := m.Refresh(); err != nil { return nil, errors.Trace(err) } } if err := m.isStillAlive(); err != nil { return nil, errors.Trace(err) } canUpdate, err := m.verifyUnitUpgradeSeriesStatus(unitName, status) if err != nil { return nil, errors.Trace(err) } if !canUpdate { return nil, jujutxn.ErrNoOperations } timestamp := bson.Now() updateMessage := newUpgradeSeriesMessage(unitName, message, timestamp) return setUpgradeSeriesTxnOps(m.doc.Id, unitName, status, timestamp, updateMessage) } err := m.st.db().Run(buildTxn) if err != nil { err = onAbort(err, ErrDead) return err } return nil }
[ "func", "(", "m", "*", "Machine", ")", "SetUpgradeSeriesUnitStatus", "(", "unitName", "string", ",", "status", "model", ".", "UpgradeSeriesStatus", ",", "message", "string", ")", "error", "{", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "attempt", ">", "0", "{", "if", "err", ":=", "m", ".", "Refresh", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "m", ".", "isStillAlive", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "canUpdate", ",", "err", ":=", "m", ".", "verifyUnitUpgradeSeriesStatus", "(", "unitName", ",", "status", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "canUpdate", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "\n", "timestamp", ":=", "bson", ".", "Now", "(", ")", "\n", "updateMessage", ":=", "newUpgradeSeriesMessage", "(", "unitName", ",", "message", ",", "timestamp", ")", "\n", "return", "setUpgradeSeriesTxnOps", "(", "m", ".", "doc", ".", "Id", ",", "unitName", ",", "status", ",", "timestamp", ",", "updateMessage", ")", "\n", "}", "\n", "err", ":=", "m", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "onAbort", "(", "err", ",", "ErrDead", ")", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetUpgradeSeriesUnitStatus sets the status of a series upgrade for a unit.
[ "SetUpgradeSeriesUnitStatus", "sets", "the", "status", "of", "a", "series", "upgrade", "for", "a", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L405-L432
157,119
juju/juju
state/machine_upgradeseries.go
verifyUnitUpgradeSeriesStatus
func (m *Machine) verifyUnitUpgradeSeriesStatus(unitName string, status model.UpgradeSeriesStatus) (bool, error) { lock, err := m.getUpgradeSeriesLock() if err != nil { return false, err } us, ok := lock.UnitStatuses[unitName] if !ok { return false, errors.NotFoundf(unitName) } comp, err := model.CompareUpgradeSeriesStatus(us.Status, status) if err != nil { return false, err } return comp == -1, nil }
go
func (m *Machine) verifyUnitUpgradeSeriesStatus(unitName string, status model.UpgradeSeriesStatus) (bool, error) { lock, err := m.getUpgradeSeriesLock() if err != nil { return false, err } us, ok := lock.UnitStatuses[unitName] if !ok { return false, errors.NotFoundf(unitName) } comp, err := model.CompareUpgradeSeriesStatus(us.Status, status) if err != nil { return false, err } return comp == -1, nil }
[ "func", "(", "m", "*", "Machine", ")", "verifyUnitUpgradeSeriesStatus", "(", "unitName", "string", ",", "status", "model", ".", "UpgradeSeriesStatus", ")", "(", "bool", ",", "error", ")", "{", "lock", ",", "err", ":=", "m", ".", "getUpgradeSeriesLock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "us", ",", "ok", ":=", "lock", ".", "UnitStatuses", "[", "unitName", "]", "\n", "if", "!", "ok", "{", "return", "false", ",", "errors", ".", "NotFoundf", "(", "unitName", ")", "\n", "}", "\n\n", "comp", ",", "err", ":=", "model", ".", "CompareUpgradeSeriesStatus", "(", "us", ".", "Status", ",", "status", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "comp", "==", "-", "1", ",", "nil", "\n", "}" ]
// verifyUnitUpgradeSeriesStatus returns a boolean indicating whether or not it // is safe to update the UpgradeSeriesStatus of a lock.
[ "verifyUnitUpgradeSeriesStatus", "returns", "a", "boolean", "indicating", "whether", "or", "not", "it", "is", "safe", "to", "update", "the", "UpgradeSeriesStatus", "of", "a", "lock", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L436-L451
157,120
juju/juju
state/machine_upgradeseries.go
SetUpgradeSeriesStatus
func (m *Machine) SetUpgradeSeriesStatus(status model.UpgradeSeriesStatus, message string) error { buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := m.Refresh(); err != nil { return nil, errors.Trace(err) } } if err := m.isStillAlive(); err != nil { return nil, errors.Trace(err) } statusSet, err := m.isMachineUpgradeSeriesStatusSet(status) if err != nil { return nil, errors.Trace(err) } if statusSet { return nil, jujutxn.ErrNoOperations } timestamp := bson.Now() upgradeSeriesMessage := newUpgradeSeriesMessage(m.Tag().String(), message, timestamp) return setMachineUpgradeSeriesTxnOps(m.doc.Id, status, upgradeSeriesMessage, timestamp), nil } err := m.st.db().Run(buildTxn) if err != nil { err = onAbort(err, ErrDead) return err } return errors.Trace(m.setUpgradeSeriesInstanceStatus(status)) }
go
func (m *Machine) SetUpgradeSeriesStatus(status model.UpgradeSeriesStatus, message string) error { buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := m.Refresh(); err != nil { return nil, errors.Trace(err) } } if err := m.isStillAlive(); err != nil { return nil, errors.Trace(err) } statusSet, err := m.isMachineUpgradeSeriesStatusSet(status) if err != nil { return nil, errors.Trace(err) } if statusSet { return nil, jujutxn.ErrNoOperations } timestamp := bson.Now() upgradeSeriesMessage := newUpgradeSeriesMessage(m.Tag().String(), message, timestamp) return setMachineUpgradeSeriesTxnOps(m.doc.Id, status, upgradeSeriesMessage, timestamp), nil } err := m.st.db().Run(buildTxn) if err != nil { err = onAbort(err, ErrDead) return err } return errors.Trace(m.setUpgradeSeriesInstanceStatus(status)) }
[ "func", "(", "m", "*", "Machine", ")", "SetUpgradeSeriesStatus", "(", "status", "model", ".", "UpgradeSeriesStatus", ",", "message", "string", ")", "error", "{", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "attempt", ">", "0", "{", "if", "err", ":=", "m", ".", "Refresh", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "m", ".", "isStillAlive", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "statusSet", ",", "err", ":=", "m", ".", "isMachineUpgradeSeriesStatusSet", "(", "status", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "statusSet", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "\n", "timestamp", ":=", "bson", ".", "Now", "(", ")", "\n", "upgradeSeriesMessage", ":=", "newUpgradeSeriesMessage", "(", "m", ".", "Tag", "(", ")", ".", "String", "(", ")", ",", "message", ",", "timestamp", ")", "\n", "return", "setMachineUpgradeSeriesTxnOps", "(", "m", ".", "doc", ".", "Id", ",", "status", ",", "upgradeSeriesMessage", ",", "timestamp", ")", ",", "nil", "\n", "}", "\n", "err", ":=", "m", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "onAbort", "(", "err", ",", "ErrDead", ")", "\n", "return", "err", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "m", ".", "setUpgradeSeriesInstanceStatus", "(", "status", ")", ")", "\n", "}" ]
// SetUpgradeSeriesStatus sets the status of the machine in // the upgrade-series lock.
[ "SetUpgradeSeriesStatus", "sets", "the", "status", "of", "the", "machine", "in", "the", "upgrade", "-", "series", "lock", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L489-L516
157,121
juju/juju
state/machine_upgradeseries.go
GetUpgradeSeriesMessages
func (m *Machine) GetUpgradeSeriesMessages() ([]string, bool, error) { lock, err := m.getUpgradeSeriesLock() if errors.IsNotFound(err) { // If the lock is not found here then there are no more messages return nil, true, nil } if err != nil { return nil, false, errors.Trace(err) } // finished means that a subsequent call to this method, while the // Machine Lock is of a similar Machine Status, would return no // additional messages (notifications). Since the value of this variable // is returned, callers may choose to close streams or stop watchers // based on this information. finished := lock.MachineStatus == model.UpgradeSeriesCompleted || lock.MachineStatus == model.UpgradeSeriesPrepareCompleted // Filter seen messages unseenMessages := make([]UpgradeSeriesMessage, 0) for _, upgradeSeriesMessage := range lock.Messages { if !upgradeSeriesMessage.Seen { unseenMessages = append(unseenMessages, upgradeSeriesMessage) } } if len(unseenMessages) == 0 { return []string{}, finished, nil } sort.Slice(unseenMessages, func(i, j int) bool { return unseenMessages[i].Timestamp.Before(unseenMessages[j].Timestamp) }) messages := make([]string, 0) for _, unseenMessage := range unseenMessages { messages = append(messages, unseenMessage.Message) } err = m.SetUpgradeSeriesMessagesAsSeen(lock.Messages) if err != nil { return nil, false, errors.Trace(err) } return messages, finished, nil }
go
func (m *Machine) GetUpgradeSeriesMessages() ([]string, bool, error) { lock, err := m.getUpgradeSeriesLock() if errors.IsNotFound(err) { // If the lock is not found here then there are no more messages return nil, true, nil } if err != nil { return nil, false, errors.Trace(err) } // finished means that a subsequent call to this method, while the // Machine Lock is of a similar Machine Status, would return no // additional messages (notifications). Since the value of this variable // is returned, callers may choose to close streams or stop watchers // based on this information. finished := lock.MachineStatus == model.UpgradeSeriesCompleted || lock.MachineStatus == model.UpgradeSeriesPrepareCompleted // Filter seen messages unseenMessages := make([]UpgradeSeriesMessage, 0) for _, upgradeSeriesMessage := range lock.Messages { if !upgradeSeriesMessage.Seen { unseenMessages = append(unseenMessages, upgradeSeriesMessage) } } if len(unseenMessages) == 0 { return []string{}, finished, nil } sort.Slice(unseenMessages, func(i, j int) bool { return unseenMessages[i].Timestamp.Before(unseenMessages[j].Timestamp) }) messages := make([]string, 0) for _, unseenMessage := range unseenMessages { messages = append(messages, unseenMessage.Message) } err = m.SetUpgradeSeriesMessagesAsSeen(lock.Messages) if err != nil { return nil, false, errors.Trace(err) } return messages, finished, nil }
[ "func", "(", "m", "*", "Machine", ")", "GetUpgradeSeriesMessages", "(", ")", "(", "[", "]", "string", ",", "bool", ",", "error", ")", "{", "lock", ",", "err", ":=", "m", ".", "getUpgradeSeriesLock", "(", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "// If the lock is not found here then there are no more messages", "return", "nil", ",", "true", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// finished means that a subsequent call to this method, while the", "// Machine Lock is of a similar Machine Status, would return no", "// additional messages (notifications). Since the value of this variable", "// is returned, callers may choose to close streams or stop watchers", "// based on this information.", "finished", ":=", "lock", ".", "MachineStatus", "==", "model", ".", "UpgradeSeriesCompleted", "||", "lock", ".", "MachineStatus", "==", "model", ".", "UpgradeSeriesPrepareCompleted", "\n", "// Filter seen messages", "unseenMessages", ":=", "make", "(", "[", "]", "UpgradeSeriesMessage", ",", "0", ")", "\n", "for", "_", ",", "upgradeSeriesMessage", ":=", "range", "lock", ".", "Messages", "{", "if", "!", "upgradeSeriesMessage", ".", "Seen", "{", "unseenMessages", "=", "append", "(", "unseenMessages", ",", "upgradeSeriesMessage", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "unseenMessages", ")", "==", "0", "{", "return", "[", "]", "string", "{", "}", ",", "finished", ",", "nil", "\n", "}", "\n", "sort", ".", "Slice", "(", "unseenMessages", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "unseenMessages", "[", "i", "]", ".", "Timestamp", ".", "Before", "(", "unseenMessages", "[", "j", "]", ".", "Timestamp", ")", "\n", "}", ")", "\n", "messages", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "for", "_", ",", "unseenMessage", ":=", "range", "unseenMessages", "{", "messages", "=", "append", "(", "messages", ",", "unseenMessage", ".", "Message", ")", "\n", "}", "\n", "err", "=", "m", ".", "SetUpgradeSeriesMessagesAsSeen", "(", "lock", ".", "Messages", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "messages", ",", "finished", ",", "nil", "\n", "}" ]
// GetUpgradeSeriesMessages returns all 'unseen' upgrade series // notifications sorted by timestamp.
[ "GetUpgradeSeriesMessages", "returns", "all", "unseen", "upgrade", "series", "notifications", "sorted", "by", "timestamp", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L520-L558
157,122
juju/juju
state/machine_upgradeseries.go
SetUpgradeSeriesMessagesAsSeen
func (m *Machine) SetUpgradeSeriesMessagesAsSeen(messages []UpgradeSeriesMessage) error { buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := m.Refresh(); err != nil { return nil, errors.Trace(err) } } if len(messages) == 0 { return nil, jujutxn.ErrNoOperations } if err := m.isStillAlive(); err != nil { return nil, errors.Trace(err) } return setUpgradeSeriesMessageTxnOps(m.doc.Id, messages, true), nil } err := m.st.db().Run(buildTxn) if err != nil { err = onAbort(err, ErrDead) return err } return nil }
go
func (m *Machine) SetUpgradeSeriesMessagesAsSeen(messages []UpgradeSeriesMessage) error { buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := m.Refresh(); err != nil { return nil, errors.Trace(err) } } if len(messages) == 0 { return nil, jujutxn.ErrNoOperations } if err := m.isStillAlive(); err != nil { return nil, errors.Trace(err) } return setUpgradeSeriesMessageTxnOps(m.doc.Id, messages, true), nil } err := m.st.db().Run(buildTxn) if err != nil { err = onAbort(err, ErrDead) return err } return nil }
[ "func", "(", "m", "*", "Machine", ")", "SetUpgradeSeriesMessagesAsSeen", "(", "messages", "[", "]", "UpgradeSeriesMessage", ")", "error", "{", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "attempt", ">", "0", "{", "if", "err", ":=", "m", ".", "Refresh", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "messages", ")", "==", "0", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "\n", "if", "err", ":=", "m", ".", "isStillAlive", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "setUpgradeSeriesMessageTxnOps", "(", "m", ".", "doc", ".", "Id", ",", "messages", ",", "true", ")", ",", "nil", "\n", "}", "\n", "err", ":=", "m", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "onAbort", "(", "err", ",", "ErrDead", ")", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetUpgradeSeriesMessagesAsSeen marks a given upgrade series messages as // having been seen by a client of the API.
[ "SetUpgradeSeriesMessagesAsSeen", "marks", "a", "given", "upgrade", "series", "messages", "as", "having", "been", "seen", "by", "a", "client", "of", "the", "API", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L562-L583
157,123
juju/juju
state/machine_upgradeseries.go
setUpgradeSeriesInstanceStatus
func (m *Machine) setUpgradeSeriesInstanceStatus(usStatus model.UpgradeSeriesStatus) error { msg := "Running" if !noInstanceMessage.Contains(string(usStatus)) { msg = "Series upgrade: " + string(usStatus) } sInfo := status.StatusInfo{ Status: status.Running, Message: msg, } return errors.Trace(m.SetInstanceStatus(sInfo)) }
go
func (m *Machine) setUpgradeSeriesInstanceStatus(usStatus model.UpgradeSeriesStatus) error { msg := "Running" if !noInstanceMessage.Contains(string(usStatus)) { msg = "Series upgrade: " + string(usStatus) } sInfo := status.StatusInfo{ Status: status.Running, Message: msg, } return errors.Trace(m.SetInstanceStatus(sInfo)) }
[ "func", "(", "m", "*", "Machine", ")", "setUpgradeSeriesInstanceStatus", "(", "usStatus", "model", ".", "UpgradeSeriesStatus", ")", "error", "{", "msg", ":=", "\"", "\"", "\n", "if", "!", "noInstanceMessage", ".", "Contains", "(", "string", "(", "usStatus", ")", ")", "{", "msg", "=", "\"", "\"", "+", "string", "(", "usStatus", ")", "\n", "}", "\n\n", "sInfo", ":=", "status", ".", "StatusInfo", "{", "Status", ":", "status", ".", "Running", ",", "Message", ":", "msg", ",", "}", "\n", "return", "errors", ".", "Trace", "(", "m", ".", "SetInstanceStatus", "(", "sInfo", ")", ")", "\n", "}" ]
// setUpgradeSeriesInstanceStatus updates the instance status of a machine in // accordance with its progression through the upgrade-series workflow.
[ "setUpgradeSeriesInstanceStatus", "updates", "the", "instance", "status", "of", "a", "machine", "in", "accordance", "with", "its", "progression", "through", "the", "upgrade", "-", "series", "workflow", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L633-L644
157,124
juju/juju
state/machine_upgradeseries.go
upgradeSeriesMachineIds
func (st *State) upgradeSeriesMachineIds() ([]string, error) { coll, closer := st.db().GetCollection(machineUpgradeSeriesLocksC) defer closer() var locks []struct { Id string `bson:"machine-id"` } if err := coll.Find(nil).Select(bson.M{"machine-id": 1}).All(&locks); err != nil { return nil, errors.Trace(err) } ids := make([]string, len(locks)) for i, l := range locks { ids[i] = l.Id } return ids, nil }
go
func (st *State) upgradeSeriesMachineIds() ([]string, error) { coll, closer := st.db().GetCollection(machineUpgradeSeriesLocksC) defer closer() var locks []struct { Id string `bson:"machine-id"` } if err := coll.Find(nil).Select(bson.M{"machine-id": 1}).All(&locks); err != nil { return nil, errors.Trace(err) } ids := make([]string, len(locks)) for i, l := range locks { ids[i] = l.Id } return ids, nil }
[ "func", "(", "st", "*", "State", ")", "upgradeSeriesMachineIds", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "coll", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "machineUpgradeSeriesLocksC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "var", "locks", "[", "]", "struct", "{", "Id", "string", "`bson:\"machine-id\"`", "\n", "}", "\n", "if", "err", ":=", "coll", ".", "Find", "(", "nil", ")", ".", "Select", "(", "bson", ".", "M", "{", "\"", "\"", ":", "1", "}", ")", ".", "All", "(", "&", "locks", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "ids", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "locks", ")", ")", "\n", "for", "i", ",", "l", ":=", "range", "locks", "{", "ids", "[", "i", "]", "=", "l", ".", "Id", "\n", "}", "\n", "return", "ids", ",", "nil", "\n", "}" ]
// upgradeSeriesMachineIds returns the IDs of all machines // currently locked for series-upgrade.
[ "upgradeSeriesMachineIds", "returns", "the", "IDs", "of", "all", "machines", "currently", "locked", "for", "series", "-", "upgrade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine_upgradeseries.go#L670-L686
157,125
juju/juju
caas/kubernetes/provider/storage.go
ValidateStorageProvider
func ValidateStorageProvider(providerType storage.ProviderType, attributes map[string]interface{}) error { switch providerType { case K8s_ProviderType: case provider.RootfsProviderType: case provider.TmpfsProviderType: default: return errors.NotValidf("storage provider type %q", providerType) } if attributes == nil { return nil } if mediumValue, ok := attributes[storageMedium]; ok { medium := core.StorageMedium(fmt.Sprintf("%v", mediumValue)) if medium != core.StorageMediumMemory && medium != core.StorageMediumHugePages { return errors.NotValidf("storage medium %q", mediumValue) } } if providerType == K8s_ProviderType { if _, err := newStorageConfig(attributes); err != nil { return errors.Trace(err) } } return nil }
go
func ValidateStorageProvider(providerType storage.ProviderType, attributes map[string]interface{}) error { switch providerType { case K8s_ProviderType: case provider.RootfsProviderType: case provider.TmpfsProviderType: default: return errors.NotValidf("storage provider type %q", providerType) } if attributes == nil { return nil } if mediumValue, ok := attributes[storageMedium]; ok { medium := core.StorageMedium(fmt.Sprintf("%v", mediumValue)) if medium != core.StorageMediumMemory && medium != core.StorageMediumHugePages { return errors.NotValidf("storage medium %q", mediumValue) } } if providerType == K8s_ProviderType { if _, err := newStorageConfig(attributes); err != nil { return errors.Trace(err) } } return nil }
[ "func", "ValidateStorageProvider", "(", "providerType", "storage", ".", "ProviderType", ",", "attributes", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "switch", "providerType", "{", "case", "K8s_ProviderType", ":", "case", "provider", ".", "RootfsProviderType", ":", "case", "provider", ".", "TmpfsProviderType", ":", "default", ":", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "providerType", ")", "\n", "}", "\n", "if", "attributes", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "mediumValue", ",", "ok", ":=", "attributes", "[", "storageMedium", "]", ";", "ok", "{", "medium", ":=", "core", ".", "StorageMedium", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "mediumValue", ")", ")", "\n", "if", "medium", "!=", "core", ".", "StorageMediumMemory", "&&", "medium", "!=", "core", ".", "StorageMediumHugePages", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "mediumValue", ")", "\n", "}", "\n", "}", "\n", "if", "providerType", "==", "K8s_ProviderType", "{", "if", "_", ",", "err", ":=", "newStorageConfig", "(", "attributes", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
//ValidateStorageProvider returns an error if the storage type and config is not valid // for a Kubernetes deployment.
[ "ValidateStorageProvider", "returns", "an", "error", "if", "the", "storage", "type", "and", "config", "is", "not", "valid", "for", "a", "Kubernetes", "deployment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/storage.go#L37-L60
157,126
juju/juju
caas/kubernetes/provider/storage.go
StorageProviderTypes
func (k *kubernetesClient) StorageProviderTypes() ([]storage.ProviderType, error) { return []storage.ProviderType{K8s_ProviderType}, nil }
go
func (k *kubernetesClient) StorageProviderTypes() ([]storage.ProviderType, error) { return []storage.ProviderType{K8s_ProviderType}, nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "StorageProviderTypes", "(", ")", "(", "[", "]", "storage", ".", "ProviderType", ",", "error", ")", "{", "return", "[", "]", "storage", ".", "ProviderType", "{", "K8s_ProviderType", "}", ",", "nil", "\n", "}" ]
// StorageProviderTypes is defined on the storage.ProviderRegistry interface.
[ "StorageProviderTypes", "is", "defined", "on", "the", "storage", ".", "ProviderRegistry", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/storage.go#L63-L65
157,127
juju/juju
caas/kubernetes/provider/storage.go
StorageProvider
func (k *kubernetesClient) StorageProvider(t storage.ProviderType) (storage.Provider, error) { if t == K8s_ProviderType { return &storageProvider{k}, nil } return nil, errors.NotFoundf("storage provider %q", t) }
go
func (k *kubernetesClient) StorageProvider(t storage.ProviderType) (storage.Provider, error) { if t == K8s_ProviderType { return &storageProvider{k}, nil } return nil, errors.NotFoundf("storage provider %q", t) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "StorageProvider", "(", "t", "storage", ".", "ProviderType", ")", "(", "storage", ".", "Provider", ",", "error", ")", "{", "if", "t", "==", "K8s_ProviderType", "{", "return", "&", "storageProvider", "{", "k", "}", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "t", ")", "\n", "}" ]
// StorageProvider is defined on the storage.ProviderRegistry interface.
[ "StorageProvider", "is", "defined", "on", "the", "storage", ".", "ProviderRegistry", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/storage.go#L68-L73
157,128
juju/juju
caas/kubernetes/provider/storage.go
ValidateConfig
func (g *storageProvider) ValidateConfig(cfg *storage.Config) error { _, err := newStorageConfig(cfg.Attrs()) return errors.Trace(err) }
go
func (g *storageProvider) ValidateConfig(cfg *storage.Config) error { _, err := newStorageConfig(cfg.Attrs()) return errors.Trace(err) }
[ "func", "(", "g", "*", "storageProvider", ")", "ValidateConfig", "(", "cfg", "*", "storage", ".", "Config", ")", "error", "{", "_", ",", "err", ":=", "newStorageConfig", "(", "cfg", ".", "Attrs", "(", ")", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// ValidateConfig is defined on the storage.Provider interface.
[ "ValidateConfig", "is", "defined", "on", "the", "storage", ".", "Provider", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/storage.go#L141-L144
157,129
juju/juju
cmd/juju/crossmodel/find.go
NewFindEndpointsCommand
func NewFindEndpointsCommand() cmd.Command { findCmd := &findCommand{} findCmd.newAPIFunc = func(controllerName string) (FindAPI, error) { return findCmd.NewRemoteEndpointsAPI(controllerName) } return modelcmd.WrapController(findCmd) }
go
func NewFindEndpointsCommand() cmd.Command { findCmd := &findCommand{} findCmd.newAPIFunc = func(controllerName string) (FindAPI, error) { return findCmd.NewRemoteEndpointsAPI(controllerName) } return modelcmd.WrapController(findCmd) }
[ "func", "NewFindEndpointsCommand", "(", ")", "cmd", ".", "Command", "{", "findCmd", ":=", "&", "findCommand", "{", "}", "\n", "findCmd", ".", "newAPIFunc", "=", "func", "(", "controllerName", "string", ")", "(", "FindAPI", ",", "error", ")", "{", "return", "findCmd", ".", "NewRemoteEndpointsAPI", "(", "controllerName", ")", "\n", "}", "\n", "return", "modelcmd", ".", "WrapController", "(", "findCmd", ")", "\n", "}" ]
// NewFindEndpointsCommand constructs command that // allows to find offered application endpoints.
[ "NewFindEndpointsCommand", "constructs", "command", "that", "allows", "to", "find", "offered", "application", "endpoints", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/find.go#L50-L56
157,130
juju/juju
environs/imagemetadata/simplestreams.go
OfficialDataSources
func OfficialDataSources(stream string) ([]simplestreams.DataSource, error) { var result []simplestreams.DataSource // New images metadata for centos and windows and existing clouds. defaultJujuURL, err := ImageMetadataURL(DefaultJujuBaseURL, stream) if err != nil { return nil, err } if defaultJujuURL != "" { publicKey, err := simplestreams.UserPublicSigningKey() if err != nil { return nil, err } if publicKey == "" { publicKey = keys.JujuPublicKey } result = append( result, simplestreams.NewURLSignedDataSource("default cloud images", defaultJujuURL, publicKey, utils.VerifySSLHostnames, simplestreams.DEFAULT_CLOUD_DATA, true)) } // Fallback to image metadata for existing Ubuntu images. defaultUbuntuURL, err := ImageMetadataURL(DefaultUbuntuBaseURL, stream) if err != nil { return nil, err } if defaultUbuntuURL != "" { result = append( result, simplestreams.NewURLSignedDataSource("default ubuntu cloud images", defaultUbuntuURL, SimplestreamsImagesPublicKey, utils.VerifySSLHostnames, simplestreams.DEFAULT_CLOUD_DATA, true)) } return result, nil }
go
func OfficialDataSources(stream string) ([]simplestreams.DataSource, error) { var result []simplestreams.DataSource // New images metadata for centos and windows and existing clouds. defaultJujuURL, err := ImageMetadataURL(DefaultJujuBaseURL, stream) if err != nil { return nil, err } if defaultJujuURL != "" { publicKey, err := simplestreams.UserPublicSigningKey() if err != nil { return nil, err } if publicKey == "" { publicKey = keys.JujuPublicKey } result = append( result, simplestreams.NewURLSignedDataSource("default cloud images", defaultJujuURL, publicKey, utils.VerifySSLHostnames, simplestreams.DEFAULT_CLOUD_DATA, true)) } // Fallback to image metadata for existing Ubuntu images. defaultUbuntuURL, err := ImageMetadataURL(DefaultUbuntuBaseURL, stream) if err != nil { return nil, err } if defaultUbuntuURL != "" { result = append( result, simplestreams.NewURLSignedDataSource("default ubuntu cloud images", defaultUbuntuURL, SimplestreamsImagesPublicKey, utils.VerifySSLHostnames, simplestreams.DEFAULT_CLOUD_DATA, true)) } return result, nil }
[ "func", "OfficialDataSources", "(", "stream", "string", ")", "(", "[", "]", "simplestreams", ".", "DataSource", ",", "error", ")", "{", "var", "result", "[", "]", "simplestreams", ".", "DataSource", "\n\n", "// New images metadata for centos and windows and existing clouds.", "defaultJujuURL", ",", "err", ":=", "ImageMetadataURL", "(", "DefaultJujuBaseURL", ",", "stream", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "defaultJujuURL", "!=", "\"", "\"", "{", "publicKey", ",", "err", ":=", "simplestreams", ".", "UserPublicSigningKey", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "publicKey", "==", "\"", "\"", "{", "publicKey", "=", "keys", ".", "JujuPublicKey", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "simplestreams", ".", "NewURLSignedDataSource", "(", "\"", "\"", ",", "defaultJujuURL", ",", "publicKey", ",", "utils", ".", "VerifySSLHostnames", ",", "simplestreams", ".", "DEFAULT_CLOUD_DATA", ",", "true", ")", ")", "\n", "}", "\n\n", "// Fallback to image metadata for existing Ubuntu images.", "defaultUbuntuURL", ",", "err", ":=", "ImageMetadataURL", "(", "DefaultUbuntuBaseURL", ",", "stream", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "defaultUbuntuURL", "!=", "\"", "\"", "{", "result", "=", "append", "(", "result", ",", "simplestreams", ".", "NewURLSignedDataSource", "(", "\"", "\"", ",", "defaultUbuntuURL", ",", "SimplestreamsImagesPublicKey", ",", "utils", ".", "VerifySSLHostnames", ",", "simplestreams", ".", "DEFAULT_CLOUD_DATA", ",", "true", ")", ")", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// OfficialDataSources returns the simplestreams datasources where official // image metadata can be found.
[ "OfficialDataSources", "returns", "the", "simplestreams", "datasources", "where", "official", "image", "metadata", "can", "be", "found", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata/simplestreams.go#L119-L152
157,131
juju/juju
environs/imagemetadata/simplestreams.go
idStream
func idStream(stream string) string { idstream := "" if stream != "" && stream != ReleasedStream { idstream = "." + stream } return idstream }
go
func idStream(stream string) string { idstream := "" if stream != "" && stream != ReleasedStream { idstream = "." + stream } return idstream }
[ "func", "idStream", "(", "stream", "string", ")", "string", "{", "idstream", ":=", "\"", "\"", "\n", "if", "stream", "!=", "\"", "\"", "&&", "stream", "!=", "ReleasedStream", "{", "idstream", "=", "\"", "\"", "+", "stream", "\n", "}", "\n", "return", "idstream", "\n", "}" ]
// idStream returns the string to use in making a product id // for the given product stream.
[ "idStream", "returns", "the", "string", "to", "use", "in", "making", "a", "product", "id", "for", "the", "given", "product", "stream", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata/simplestreams.go#L176-L182
157,132
juju/juju
environs/imagemetadata/simplestreams.go
Fetch
func Fetch( sources []simplestreams.DataSource, cons *ImageConstraint, ) ([]*ImageMetadata, *simplestreams.ResolveInfo, error) { params := simplestreams.GetMetadataParams{ StreamsVersion: currentStreamsVersion, LookupConstraint: cons, ValueParams: simplestreams.ValueParams{ DataType: ImageIds, FilterFunc: appendMatchingImages, ValueTemplate: ImageMetadata{}, }, } items, resolveInfo, err := simplestreams.GetMetadata(sources, params) if err != nil { return nil, resolveInfo, err } metadata := make([]*ImageMetadata, len(items)) for i, md := range items { metadata[i] = md.(*ImageMetadata) } // Sorting the metadata is not strictly necessary, but it ensures consistent ordering for // all compilers, and it just makes it easier to look at the data. Sort(metadata) return metadata, resolveInfo, nil }
go
func Fetch( sources []simplestreams.DataSource, cons *ImageConstraint, ) ([]*ImageMetadata, *simplestreams.ResolveInfo, error) { params := simplestreams.GetMetadataParams{ StreamsVersion: currentStreamsVersion, LookupConstraint: cons, ValueParams: simplestreams.ValueParams{ DataType: ImageIds, FilterFunc: appendMatchingImages, ValueTemplate: ImageMetadata{}, }, } items, resolveInfo, err := simplestreams.GetMetadata(sources, params) if err != nil { return nil, resolveInfo, err } metadata := make([]*ImageMetadata, len(items)) for i, md := range items { metadata[i] = md.(*ImageMetadata) } // Sorting the metadata is not strictly necessary, but it ensures consistent ordering for // all compilers, and it just makes it easier to look at the data. Sort(metadata) return metadata, resolveInfo, nil }
[ "func", "Fetch", "(", "sources", "[", "]", "simplestreams", ".", "DataSource", ",", "cons", "*", "ImageConstraint", ",", ")", "(", "[", "]", "*", "ImageMetadata", ",", "*", "simplestreams", ".", "ResolveInfo", ",", "error", ")", "{", "params", ":=", "simplestreams", ".", "GetMetadataParams", "{", "StreamsVersion", ":", "currentStreamsVersion", ",", "LookupConstraint", ":", "cons", ",", "ValueParams", ":", "simplestreams", ".", "ValueParams", "{", "DataType", ":", "ImageIds", ",", "FilterFunc", ":", "appendMatchingImages", ",", "ValueTemplate", ":", "ImageMetadata", "{", "}", ",", "}", ",", "}", "\n", "items", ",", "resolveInfo", ",", "err", ":=", "simplestreams", ".", "GetMetadata", "(", "sources", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "resolveInfo", ",", "err", "\n", "}", "\n", "metadata", ":=", "make", "(", "[", "]", "*", "ImageMetadata", ",", "len", "(", "items", ")", ")", "\n", "for", "i", ",", "md", ":=", "range", "items", "{", "metadata", "[", "i", "]", "=", "md", ".", "(", "*", "ImageMetadata", ")", "\n", "}", "\n", "// Sorting the metadata is not strictly necessary, but it ensures consistent ordering for", "// all compilers, and it just makes it easier to look at the data.", "Sort", "(", "metadata", ")", "\n", "return", "metadata", ",", "resolveInfo", ",", "nil", "\n", "}" ]
// Fetch returns a list of images for the specified cloud matching the constraint. // The base URL locations are as specified - the first location which has a file is the one used. // Signed data is preferred, but if there is no signed data available and onlySigned is false, // then unsigned data is used.
[ "Fetch", "returns", "a", "list", "of", "images", "for", "the", "specified", "cloud", "matching", "the", "constraint", ".", "The", "base", "URL", "locations", "are", "as", "specified", "-", "the", "first", "location", "which", "has", "a", "file", "is", "the", "one", "used", ".", "Signed", "data", "is", "preferred", "but", "if", "there", "is", "no", "signed", "data", "available", "and", "onlySigned", "is", "false", "then", "unsigned", "data", "is", "used", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata/simplestreams.go#L234-L259
157,133
juju/juju
environs/imagemetadata/simplestreams.go
appendMatchingImages
func appendMatchingImages(source simplestreams.DataSource, matchingImages []interface{}, images map[string]interface{}, cons simplestreams.LookupConstraint) ([]interface{}, error) { imagesMap := make(map[imageKey]*ImageMetadata, len(matchingImages)) for _, val := range matchingImages { im := val.(*ImageMetadata) imagesMap[imageKey{im.VirtType, im.Arch, im.Version, im.RegionName, im.Storage}] = im } for _, val := range images { im := val.(*ImageMetadata) if cons != nil && cons.Params().Region != "" && cons.Params().Region != im.RegionName { continue } if _, ok := imagesMap[imageKey{im.VirtType, im.Arch, im.Version, im.RegionName, im.Storage}]; !ok { matchingImages = append(matchingImages, im) } } return matchingImages, nil }
go
func appendMatchingImages(source simplestreams.DataSource, matchingImages []interface{}, images map[string]interface{}, cons simplestreams.LookupConstraint) ([]interface{}, error) { imagesMap := make(map[imageKey]*ImageMetadata, len(matchingImages)) for _, val := range matchingImages { im := val.(*ImageMetadata) imagesMap[imageKey{im.VirtType, im.Arch, im.Version, im.RegionName, im.Storage}] = im } for _, val := range images { im := val.(*ImageMetadata) if cons != nil && cons.Params().Region != "" && cons.Params().Region != im.RegionName { continue } if _, ok := imagesMap[imageKey{im.VirtType, im.Arch, im.Version, im.RegionName, im.Storage}]; !ok { matchingImages = append(matchingImages, im) } } return matchingImages, nil }
[ "func", "appendMatchingImages", "(", "source", "simplestreams", ".", "DataSource", ",", "matchingImages", "[", "]", "interface", "{", "}", ",", "images", "map", "[", "string", "]", "interface", "{", "}", ",", "cons", "simplestreams", ".", "LookupConstraint", ")", "(", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "imagesMap", ":=", "make", "(", "map", "[", "imageKey", "]", "*", "ImageMetadata", ",", "len", "(", "matchingImages", ")", ")", "\n", "for", "_", ",", "val", ":=", "range", "matchingImages", "{", "im", ":=", "val", ".", "(", "*", "ImageMetadata", ")", "\n", "imagesMap", "[", "imageKey", "{", "im", ".", "VirtType", ",", "im", ".", "Arch", ",", "im", ".", "Version", ",", "im", ".", "RegionName", ",", "im", ".", "Storage", "}", "]", "=", "im", "\n", "}", "\n", "for", "_", ",", "val", ":=", "range", "images", "{", "im", ":=", "val", ".", "(", "*", "ImageMetadata", ")", "\n", "if", "cons", "!=", "nil", "&&", "cons", ".", "Params", "(", ")", ".", "Region", "!=", "\"", "\"", "&&", "cons", ".", "Params", "(", ")", ".", "Region", "!=", "im", ".", "RegionName", "{", "continue", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "imagesMap", "[", "imageKey", "{", "im", ".", "VirtType", ",", "im", ".", "Arch", ",", "im", ".", "Version", ",", "im", ".", "RegionName", ",", "im", ".", "Storage", "}", "]", ";", "!", "ok", "{", "matchingImages", "=", "append", "(", "matchingImages", ",", "im", ")", "\n", "}", "\n", "}", "\n", "return", "matchingImages", ",", "nil", "\n", "}" ]
// appendMatchingImages updates matchingImages with image metadata records from images which belong to the // specified region. If an image already exists in matchingImages, it is not overwritten.
[ "appendMatchingImages", "updates", "matchingImages", "with", "image", "metadata", "records", "from", "images", "which", "belong", "to", "the", "specified", "region", ".", "If", "an", "image", "already", "exists", "in", "matchingImages", "it", "is", "not", "overwritten", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata/simplestreams.go#L283-L301
157,134
juju/juju
apiserver/facades/client/backups/info.go
Info
func (a *API) Info(args params.BackupsInfoArgs) (params.BackupsMetadataResult, error) { backups, closer := newBackups(a.backend) defer closer.Close() meta, file, err := backups.Get(args.ID) if err != nil { return params.BackupsMetadataResult{}, errors.Trace(err) } if file != nil { // We don't use the archive file but need to close it // nonetheless or else we'll leak sockets. defer file.Close() } return CreateResult(meta, ""), nil }
go
func (a *API) Info(args params.BackupsInfoArgs) (params.BackupsMetadataResult, error) { backups, closer := newBackups(a.backend) defer closer.Close() meta, file, err := backups.Get(args.ID) if err != nil { return params.BackupsMetadataResult{}, errors.Trace(err) } if file != nil { // We don't use the archive file but need to close it // nonetheless or else we'll leak sockets. defer file.Close() } return CreateResult(meta, ""), nil }
[ "func", "(", "a", "*", "API", ")", "Info", "(", "args", "params", ".", "BackupsInfoArgs", ")", "(", "params", ".", "BackupsMetadataResult", ",", "error", ")", "{", "backups", ",", "closer", ":=", "newBackups", "(", "a", ".", "backend", ")", "\n", "defer", "closer", ".", "Close", "(", ")", "\n\n", "meta", ",", "file", ",", "err", ":=", "backups", ".", "Get", "(", "args", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "BackupsMetadataResult", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "file", "!=", "nil", "{", "// We don't use the archive file but need to close it", "// nonetheless or else we'll leak sockets.", "defer", "file", ".", "Close", "(", ")", "\n", "}", "\n\n", "return", "CreateResult", "(", "meta", ",", "\"", "\"", ")", ",", "nil", "\n", "}" ]
// Info provides the implementation of the API method.
[ "Info", "provides", "the", "implementation", "of", "the", "API", "method", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/backups/info.go#L13-L28
157,135
juju/juju
service/common/conf.go
Validate
func (c Conf) Validate(renderer shell.Renderer) error { if c.Desc == "" { return errors.New("missing Desc") } // Check the Exec* fields. if c.ExecStart == "" { return errors.New("missing ExecStart") } for field, cmd := range map[string]string{ "ExecStart": c.ExecStart, "ExecStopPost": c.ExecStopPost, } { if cmd == "" { continue } if err := c.checkExec(field, cmd, renderer); err != nil { return errors.Trace(err) } } for _, value := range c.Limit { switch value { case "unlimited", "infinity": default: _, err := strconv.Atoi(value) if err != nil { newErr := errors.NotValidf("limit must be \"infinity\", \"unlimited\", or an integer, %q", value) return errors.Wrap(err, newErr) } } } return nil }
go
func (c Conf) Validate(renderer shell.Renderer) error { if c.Desc == "" { return errors.New("missing Desc") } // Check the Exec* fields. if c.ExecStart == "" { return errors.New("missing ExecStart") } for field, cmd := range map[string]string{ "ExecStart": c.ExecStart, "ExecStopPost": c.ExecStopPost, } { if cmd == "" { continue } if err := c.checkExec(field, cmd, renderer); err != nil { return errors.Trace(err) } } for _, value := range c.Limit { switch value { case "unlimited", "infinity": default: _, err := strconv.Atoi(value) if err != nil { newErr := errors.NotValidf("limit must be \"infinity\", \"unlimited\", or an integer, %q", value) return errors.Wrap(err, newErr) } } } return nil }
[ "func", "(", "c", "Conf", ")", "Validate", "(", "renderer", "shell", ".", "Renderer", ")", "error", "{", "if", "c", ".", "Desc", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Check the Exec* fields.", "if", "c", ".", "ExecStart", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "field", ",", "cmd", ":=", "range", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "c", ".", "ExecStart", ",", "\"", "\"", ":", "c", ".", "ExecStopPost", ",", "}", "{", "if", "cmd", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "if", "err", ":=", "c", ".", "checkExec", "(", "field", ",", "cmd", ",", "renderer", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "value", ":=", "range", "c", ".", "Limit", "{", "switch", "value", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "default", ":", "_", ",", "err", ":=", "strconv", ".", "Atoi", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "newErr", ":=", "errors", ".", "NotValidf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "value", ")", "\n", "return", "errors", ".", "Wrap", "(", "err", ",", "newErr", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate checks the conf's values for correctness.
[ "Validate", "checks", "the", "conf", "s", "values", "for", "correctness", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/common/conf.go#L77-L112
157,136
juju/juju
service/common/conf.go
Unquote
func Unquote(str string) string { if len(str) < 2 { return str } for _, quote := range []string{`'`, `"`} { if str[0:1] == quote && str[len(str)-1:] == quote { return strings.Trim(str, quote) } } return str }
go
func Unquote(str string) string { if len(str) < 2 { return str } for _, quote := range []string{`'`, `"`} { if str[0:1] == quote && str[len(str)-1:] == quote { return strings.Trim(str, quote) } } return str }
[ "func", "Unquote", "(", "str", "string", ")", "string", "{", "if", "len", "(", "str", ")", "<", "2", "{", "return", "str", "\n", "}", "\n", "for", "_", ",", "quote", ":=", "range", "[", "]", "string", "{", "`'`", ",", "`\"`", "}", "{", "if", "str", "[", "0", ":", "1", "]", "==", "quote", "&&", "str", "[", "len", "(", "str", ")", "-", "1", ":", "]", "==", "quote", "{", "return", "strings", ".", "Trim", "(", "str", ",", "quote", ")", "\n", "}", "\n", "}", "\n", "return", "str", "\n", "}" ]
// Unquote returns the string embedded between matching quotation marks. // If there aren't any matching quotation marks then the string is // returned as-is.
[ "Unquote", "returns", "the", "string", "embedded", "between", "matching", "quotation", "marks", ".", "If", "there", "aren", "t", "any", "matching", "quotation", "marks", "then", "the", "string", "is", "returned", "as", "-", "is", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/common/conf.go#L126-L136
157,137
juju/juju
apiserver/common/imagecommon/imagemetadata.go
Save
func Save(st ImageMetadataInterface, metadata params.MetadataSaveParams) ([]params.ErrorResult, error) { all := make([]params.ErrorResult, len(metadata.Metadata)) if len(metadata.Metadata) == 0 { return nil, nil } modelCfg, err := st.ModelConfig() if err != nil { return nil, errors.Annotatef(err, "getting model config") } for i, one := range metadata.Metadata { md := ParseMetadataListFromParams(one, modelCfg) err := st.SaveMetadata(md) all[i] = params.ErrorResult{Error: common.ServerError(err)} } return all, nil }
go
func Save(st ImageMetadataInterface, metadata params.MetadataSaveParams) ([]params.ErrorResult, error) { all := make([]params.ErrorResult, len(metadata.Metadata)) if len(metadata.Metadata) == 0 { return nil, nil } modelCfg, err := st.ModelConfig() if err != nil { return nil, errors.Annotatef(err, "getting model config") } for i, one := range metadata.Metadata { md := ParseMetadataListFromParams(one, modelCfg) err := st.SaveMetadata(md) all[i] = params.ErrorResult{Error: common.ServerError(err)} } return all, nil }
[ "func", "Save", "(", "st", "ImageMetadataInterface", ",", "metadata", "params", ".", "MetadataSaveParams", ")", "(", "[", "]", "params", ".", "ErrorResult", ",", "error", ")", "{", "all", ":=", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "metadata", ".", "Metadata", ")", ")", "\n", "if", "len", "(", "metadata", ".", "Metadata", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "modelCfg", ",", "err", ":=", "st", ".", "ModelConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "i", ",", "one", ":=", "range", "metadata", ".", "Metadata", "{", "md", ":=", "ParseMetadataListFromParams", "(", "one", ",", "modelCfg", ")", "\n", "err", ":=", "st", ".", "SaveMetadata", "(", "md", ")", "\n", "all", "[", "i", "]", "=", "params", ".", "ErrorResult", "{", "Error", ":", "common", ".", "ServerError", "(", "err", ")", "}", "\n", "}", "\n", "return", "all", ",", "nil", "\n", "}" ]
// Save stores given cloud image metadata using given persistence interface.
[ "Save", "stores", "given", "cloud", "image", "metadata", "using", "given", "persistence", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/imagecommon/imagemetadata.go#L26-L41
157,138
juju/juju
apiserver/common/imagecommon/imagemetadata.go
ParseMetadataListFromParams
func ParseMetadataListFromParams(p params.CloudImageMetadataList, cfg *config.Config) []cloudimagemetadata.Metadata { results := make([]cloudimagemetadata.Metadata, len(p.Metadata)) for i, metadata := range p.Metadata { results[i] = cloudimagemetadata.Metadata{ MetadataAttributes: cloudimagemetadata.MetadataAttributes{ Stream: metadata.Stream, Region: metadata.Region, Version: metadata.Version, Series: metadata.Series, Arch: metadata.Arch, VirtType: metadata.VirtType, RootStorageType: metadata.RootStorageType, RootStorageSize: metadata.RootStorageSize, Source: metadata.Source, }, Priority: metadata.Priority, ImageId: metadata.ImageId, } // TODO (anastasiamac 2016-08-24) This is a band-aid solution. // Once correct value is read from simplestreams, this needs to go. // Bug# 1616295 if results[i].Stream == "" { results[i].Stream = cfg.ImageStream() } } return results }
go
func ParseMetadataListFromParams(p params.CloudImageMetadataList, cfg *config.Config) []cloudimagemetadata.Metadata { results := make([]cloudimagemetadata.Metadata, len(p.Metadata)) for i, metadata := range p.Metadata { results[i] = cloudimagemetadata.Metadata{ MetadataAttributes: cloudimagemetadata.MetadataAttributes{ Stream: metadata.Stream, Region: metadata.Region, Version: metadata.Version, Series: metadata.Series, Arch: metadata.Arch, VirtType: metadata.VirtType, RootStorageType: metadata.RootStorageType, RootStorageSize: metadata.RootStorageSize, Source: metadata.Source, }, Priority: metadata.Priority, ImageId: metadata.ImageId, } // TODO (anastasiamac 2016-08-24) This is a band-aid solution. // Once correct value is read from simplestreams, this needs to go. // Bug# 1616295 if results[i].Stream == "" { results[i].Stream = cfg.ImageStream() } } return results }
[ "func", "ParseMetadataListFromParams", "(", "p", "params", ".", "CloudImageMetadataList", ",", "cfg", "*", "config", ".", "Config", ")", "[", "]", "cloudimagemetadata", ".", "Metadata", "{", "results", ":=", "make", "(", "[", "]", "cloudimagemetadata", ".", "Metadata", ",", "len", "(", "p", ".", "Metadata", ")", ")", "\n", "for", "i", ",", "metadata", ":=", "range", "p", ".", "Metadata", "{", "results", "[", "i", "]", "=", "cloudimagemetadata", ".", "Metadata", "{", "MetadataAttributes", ":", "cloudimagemetadata", ".", "MetadataAttributes", "{", "Stream", ":", "metadata", ".", "Stream", ",", "Region", ":", "metadata", ".", "Region", ",", "Version", ":", "metadata", ".", "Version", ",", "Series", ":", "metadata", ".", "Series", ",", "Arch", ":", "metadata", ".", "Arch", ",", "VirtType", ":", "metadata", ".", "VirtType", ",", "RootStorageType", ":", "metadata", ".", "RootStorageType", ",", "RootStorageSize", ":", "metadata", ".", "RootStorageSize", ",", "Source", ":", "metadata", ".", "Source", ",", "}", ",", "Priority", ":", "metadata", ".", "Priority", ",", "ImageId", ":", "metadata", ".", "ImageId", ",", "}", "\n", "// TODO (anastasiamac 2016-08-24) This is a band-aid solution.", "// Once correct value is read from simplestreams, this needs to go.", "// Bug# 1616295", "if", "results", "[", "i", "]", ".", "Stream", "==", "\"", "\"", "{", "results", "[", "i", "]", ".", "Stream", "=", "cfg", ".", "ImageStream", "(", ")", "\n", "}", "\n", "}", "\n", "return", "results", "\n", "}" ]
// ParseMetadataListFromParams translates params.CloudImageMetadataList // into a collection of cloudimagemetadata.Metadata.
[ "ParseMetadataListFromParams", "translates", "params", ".", "CloudImageMetadataList", "into", "a", "collection", "of", "cloudimagemetadata", ".", "Metadata", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/imagecommon/imagemetadata.go#L45-L71
157,139
juju/juju
worker/uniter/storage/resolver.go
NewResolver
func NewResolver(storage *Attachments, modelType model.ModelType) resolver.Resolver { return &storageResolver{ storage: storage, modelType: modelType, life: make(map[names.StorageTag]params.Life), } }
go
func NewResolver(storage *Attachments, modelType model.ModelType) resolver.Resolver { return &storageResolver{ storage: storage, modelType: modelType, life: make(map[names.StorageTag]params.Life), } }
[ "func", "NewResolver", "(", "storage", "*", "Attachments", ",", "modelType", "model", ".", "ModelType", ")", "resolver", ".", "Resolver", "{", "return", "&", "storageResolver", "{", "storage", ":", "storage", ",", "modelType", ":", "modelType", ",", "life", ":", "make", "(", "map", "[", "names", ".", "StorageTag", "]", "params", ".", "Life", ")", ",", "}", "\n", "}" ]
// NewResolver returns a new storage resolver.
[ "NewResolver", "returns", "a", "new", "storage", "resolver", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/storage/resolver.go#L35-L41
157,140
juju/juju
worker/uniter/storage/resolver.go
maybeShortCircuitRemoval
func (s *storageResolver) maybeShortCircuitRemoval(remote map[names.StorageTag]remotestate.StorageSnapshot) error { for tag, snap := range remote { local, ok := s.storage.storageAttachments[tag] if (ok && local.attached) || snap.Life == params.Alive { continue } if err := s.storage.removeStorageAttachment(tag); err != nil { return errors.Trace(err) } delete(remote, tag) } return nil }
go
func (s *storageResolver) maybeShortCircuitRemoval(remote map[names.StorageTag]remotestate.StorageSnapshot) error { for tag, snap := range remote { local, ok := s.storage.storageAttachments[tag] if (ok && local.attached) || snap.Life == params.Alive { continue } if err := s.storage.removeStorageAttachment(tag); err != nil { return errors.Trace(err) } delete(remote, tag) } return nil }
[ "func", "(", "s", "*", "storageResolver", ")", "maybeShortCircuitRemoval", "(", "remote", "map", "[", "names", ".", "StorageTag", "]", "remotestate", ".", "StorageSnapshot", ")", "error", "{", "for", "tag", ",", "snap", ":=", "range", "remote", "{", "local", ",", "ok", ":=", "s", ".", "storage", ".", "storageAttachments", "[", "tag", "]", "\n", "if", "(", "ok", "&&", "local", ".", "attached", ")", "||", "snap", ".", "Life", "==", "params", ".", "Alive", "{", "continue", "\n", "}", "\n", "if", "err", ":=", "s", ".", "storage", ".", "removeStorageAttachment", "(", "tag", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "delete", "(", "remote", ",", "tag", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// maybeShortCircuitRemoval removes any storage that is not alive, // and has not had a storage-attached hook committed.
[ "maybeShortCircuitRemoval", "removes", "any", "storage", "that", "is", "not", "alive", "and", "has", "not", "had", "a", "storage", "-", "attached", "hook", "committed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/storage/resolver.go#L113-L125
157,141
juju/juju
provider/rackspace/networking.go
DecorateNetworking
func (d rackspaceNetworkingDecorator) DecorateNetworking(n openstack.Networking) (openstack.Networking, error) { return rackspaceNetworking{n}, nil }
go
func (d rackspaceNetworkingDecorator) DecorateNetworking(n openstack.Networking) (openstack.Networking, error) { return rackspaceNetworking{n}, nil }
[ "func", "(", "d", "rackspaceNetworkingDecorator", ")", "DecorateNetworking", "(", "n", "openstack", ".", "Networking", ")", "(", "openstack", ".", "Networking", ",", "error", ")", "{", "return", "rackspaceNetworking", "{", "n", "}", ",", "nil", "\n", "}" ]
// DecorateNetworking is part of the openstack.NetworkingDecorator interface.
[ "DecorateNetworking", "is", "part", "of", "the", "openstack", ".", "NetworkingDecorator", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/rackspace/networking.go#L15-L17
157,142
juju/juju
provider/rackspace/networking.go
DefaultNetworks
func (rackspaceNetworking) DefaultNetworks() ([]nova.ServerNetworks, error) { // These are the default rackspace networks, see: // http://docs.rackspace.com/servers/api/v2/cs-devguide/content/provision_server_with_networks.html return []nova.ServerNetworks{ {NetworkId: "00000000-0000-0000-0000-000000000000"}, //Racksapce PublicNet {NetworkId: "11111111-1111-1111-1111-111111111111"}, //Rackspace ServiceNet }, nil }
go
func (rackspaceNetworking) DefaultNetworks() ([]nova.ServerNetworks, error) { // These are the default rackspace networks, see: // http://docs.rackspace.com/servers/api/v2/cs-devguide/content/provision_server_with_networks.html return []nova.ServerNetworks{ {NetworkId: "00000000-0000-0000-0000-000000000000"}, //Racksapce PublicNet {NetworkId: "11111111-1111-1111-1111-111111111111"}, //Rackspace ServiceNet }, nil }
[ "func", "(", "rackspaceNetworking", ")", "DefaultNetworks", "(", ")", "(", "[", "]", "nova", ".", "ServerNetworks", ",", "error", ")", "{", "// These are the default rackspace networks, see:", "// http://docs.rackspace.com/servers/api/v2/cs-devguide/content/provision_server_with_networks.html", "return", "[", "]", "nova", ".", "ServerNetworks", "{", "{", "NetworkId", ":", "\"", "\"", "}", ",", "//Racksapce PublicNet", "{", "NetworkId", ":", "\"", "\"", "}", ",", "//Rackspace ServiceNet", "}", ",", "nil", "\n", "}" ]
// DefaultNetworks is part of the openstack.Networking interface.
[ "DefaultNetworks", "is", "part", "of", "the", "openstack", ".", "Networking", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/rackspace/networking.go#L24-L31
157,143
juju/juju
worker/provisioner/mocks/lxdprofileinstancebroker_mock.go
NewMockLXDProfileInstanceBroker
func NewMockLXDProfileInstanceBroker(ctrl *gomock.Controller) *MockLXDProfileInstanceBroker { mock := &MockLXDProfileInstanceBroker{ctrl: ctrl} mock.recorder = &MockLXDProfileInstanceBrokerMockRecorder{mock} return mock }
go
func NewMockLXDProfileInstanceBroker(ctrl *gomock.Controller) *MockLXDProfileInstanceBroker { mock := &MockLXDProfileInstanceBroker{ctrl: ctrl} mock.recorder = &MockLXDProfileInstanceBrokerMockRecorder{mock} return mock }
[ "func", "NewMockLXDProfileInstanceBroker", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockLXDProfileInstanceBroker", "{", "mock", ":=", "&", "MockLXDProfileInstanceBroker", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockLXDProfileInstanceBrokerMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockLXDProfileInstanceBroker creates a new mock instance
[ "NewMockLXDProfileInstanceBroker", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/mocks/lxdprofileinstancebroker_mock.go#L30-L34
157,144
juju/juju
worker/provisioner/mocks/lxdprofileinstancebroker_mock.go
AssignLXDProfiles
func (m *MockLXDProfileInstanceBroker) AssignLXDProfiles(arg0 string, arg1 []string, arg2 []lxdprofile.ProfilePost) ([]string, error) { ret := m.ctrl.Call(m, "AssignLXDProfiles", arg0, arg1, arg2) ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockLXDProfileInstanceBroker) AssignLXDProfiles(arg0 string, arg1 []string, arg2 []lxdprofile.ProfilePost) ([]string, error) { ret := m.ctrl.Call(m, "AssignLXDProfiles", arg0, arg1, arg2) ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockLXDProfileInstanceBroker", ")", "AssignLXDProfiles", "(", "arg0", "string", ",", "arg1", "[", "]", "string", ",", "arg2", "[", "]", "lxdprofile", ".", "ProfilePost", ")", "(", "[", "]", "string", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ",", "arg2", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "[", "]", "string", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// AssignLXDProfiles mocks base method
[ "AssignLXDProfiles", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/mocks/lxdprofileinstancebroker_mock.go#L55-L60
157,145
juju/juju
worker/provisioner/mocks/lxdprofileinstancebroker_mock.go
LXDProfileNames
func (m *MockLXDProfileInstanceBroker) LXDProfileNames(arg0 string) ([]string, error) { ret := m.ctrl.Call(m, "LXDProfileNames", arg0) ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockLXDProfileInstanceBroker) LXDProfileNames(arg0 string) ([]string, error) { ret := m.ctrl.Call(m, "LXDProfileNames", arg0) ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockLXDProfileInstanceBroker", ")", "LXDProfileNames", "(", "arg0", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "[", "]", "string", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// LXDProfileNames mocks base method
[ "LXDProfileNames", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/mocks/lxdprofileinstancebroker_mock.go#L68-L73
157,146
juju/juju
worker/provisioner/mocks/lxdprofileinstancebroker_mock.go
MaybeWriteLXDProfile
func (m *MockLXDProfileInstanceBroker) MaybeWriteLXDProfile(arg0 string, arg1 *charm_v6.LXDProfile) error { ret := m.ctrl.Call(m, "MaybeWriteLXDProfile", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
go
func (m *MockLXDProfileInstanceBroker) MaybeWriteLXDProfile(arg0 string, arg1 *charm_v6.LXDProfile) error { ret := m.ctrl.Call(m, "MaybeWriteLXDProfile", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
[ "func", "(", "m", "*", "MockLXDProfileInstanceBroker", ")", "MaybeWriteLXDProfile", "(", "arg0", "string", ",", "arg1", "*", "charm_v6", ".", "LXDProfile", ")", "error", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "error", ")", "\n", "return", "ret0", "\n", "}" ]
// MaybeWriteLXDProfile mocks base method
[ "MaybeWriteLXDProfile", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/mocks/lxdprofileinstancebroker_mock.go#L93-L97
157,147
juju/juju
worker/provisioner/mocks/lxdprofileinstancebroker_mock.go
ReplaceOrAddInstanceProfile
func (m *MockLXDProfileInstanceBroker) ReplaceOrAddInstanceProfile(arg0, arg1, arg2 string, arg3 *charm_v6.LXDProfile) ([]string, error) { ret := m.ctrl.Call(m, "ReplaceOrAddInstanceProfile", arg0, arg1, arg2, arg3) ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockLXDProfileInstanceBroker) ReplaceOrAddInstanceProfile(arg0, arg1, arg2 string, arg3 *charm_v6.LXDProfile) ([]string, error) { ret := m.ctrl.Call(m, "ReplaceOrAddInstanceProfile", arg0, arg1, arg2, arg3) ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockLXDProfileInstanceBroker", ")", "ReplaceOrAddInstanceProfile", "(", "arg0", ",", "arg1", ",", "arg2", "string", ",", "arg3", "*", "charm_v6", ".", "LXDProfile", ")", "(", "[", "]", "string", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ",", "arg2", ",", "arg3", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "[", "]", "string", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// ReplaceOrAddInstanceProfile mocks base method
[ "ReplaceOrAddInstanceProfile", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/mocks/lxdprofileinstancebroker_mock.go#L105-L110
157,148
juju/juju
worker/provisioner/mocks/lxdprofileinstancebroker_mock.go
StartInstance
func (m *MockLXDProfileInstanceBroker) StartInstance(arg0 context.ProviderCallContext, arg1 environs.StartInstanceParams) (*environs.StartInstanceResult, error) { ret := m.ctrl.Call(m, "StartInstance", arg0, arg1) ret0, _ := ret[0].(*environs.StartInstanceResult) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockLXDProfileInstanceBroker) StartInstance(arg0 context.ProviderCallContext, arg1 environs.StartInstanceParams) (*environs.StartInstanceResult, error) { ret := m.ctrl.Call(m, "StartInstance", arg0, arg1) ret0, _ := ret[0].(*environs.StartInstanceResult) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockLXDProfileInstanceBroker", ")", "StartInstance", "(", "arg0", "context", ".", "ProviderCallContext", ",", "arg1", "environs", ".", "StartInstanceParams", ")", "(", "*", "environs", ".", "StartInstanceResult", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "*", "environs", ".", "StartInstanceResult", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// StartInstance mocks base method
[ "StartInstance", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/mocks/lxdprofileinstancebroker_mock.go#L118-L123
157,149
juju/juju
api/uniter/storage.go
UnitStorageAttachments
func (sa *StorageAccessor) UnitStorageAttachments(unitTag names.UnitTag) ([]params.StorageAttachmentId, error) { if sa.facade.BestAPIVersion() < 2 { return nil, errors.NotImplementedf("UnitStorageAttachments() (need V2+)") } args := params.Entities{ Entities: []params.Entity{{Tag: unitTag.String()}}, } var results params.StorageAttachmentIdsResults err := sa.facade.FacadeCall("UnitStorageAttachments", args, &results) if err != nil { return nil, errors.Trace(err) } if len(results.Results) != 1 { return nil, errors.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, result.Error } return result.Result.Ids, nil }
go
func (sa *StorageAccessor) UnitStorageAttachments(unitTag names.UnitTag) ([]params.StorageAttachmentId, error) { if sa.facade.BestAPIVersion() < 2 { return nil, errors.NotImplementedf("UnitStorageAttachments() (need V2+)") } args := params.Entities{ Entities: []params.Entity{{Tag: unitTag.String()}}, } var results params.StorageAttachmentIdsResults err := sa.facade.FacadeCall("UnitStorageAttachments", args, &results) if err != nil { return nil, errors.Trace(err) } if len(results.Results) != 1 { return nil, errors.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, result.Error } return result.Result.Ids, nil }
[ "func", "(", "sa", "*", "StorageAccessor", ")", "UnitStorageAttachments", "(", "unitTag", "names", ".", "UnitTag", ")", "(", "[", "]", "params", ".", "StorageAttachmentId", ",", "error", ")", "{", "if", "sa", ".", "facade", ".", "BestAPIVersion", "(", ")", "<", "2", "{", "return", "nil", ",", "errors", ".", "NotImplementedf", "(", "\"", "\"", ")", "\n", "}", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "Tag", ":", "unitTag", ".", "String", "(", ")", "}", "}", ",", "}", "\n", "var", "results", "params", ".", "StorageAttachmentIdsResults", "\n", "err", ":=", "sa", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "result", ".", "Error", "\n", "}", "\n", "return", "result", ".", "Result", ".", "Ids", ",", "nil", "\n", "}" ]
// UnitStorageAttachments returns the IDs of a unit's storage attachments.
[ "UnitStorageAttachments", "returns", "the", "IDs", "of", "a", "unit", "s", "storage", "attachments", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/storage.go#L27-L47
157,150
juju/juju
api/uniter/storage.go
DestroyUnitStorageAttachments
func (sa *StorageAccessor) DestroyUnitStorageAttachments(unitTag names.UnitTag) error { if sa.facade.BestAPIVersion() < 2 { return errors.NotImplementedf("DestroyUnitStorageAttachments() (need V2+)") } args := params.Entities{ Entities: []params.Entity{{Tag: unitTag.String()}}, } var results params.ErrorResults err := sa.facade.FacadeCall("DestroyUnitStorageAttachments", args, &results) if err != nil { return errors.Trace(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 (sa *StorageAccessor) DestroyUnitStorageAttachments(unitTag names.UnitTag) error { if sa.facade.BestAPIVersion() < 2 { return errors.NotImplementedf("DestroyUnitStorageAttachments() (need V2+)") } args := params.Entities{ Entities: []params.Entity{{Tag: unitTag.String()}}, } var results params.ErrorResults err := sa.facade.FacadeCall("DestroyUnitStorageAttachments", args, &results) if err != nil { return errors.Trace(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", "(", "sa", "*", "StorageAccessor", ")", "DestroyUnitStorageAttachments", "(", "unitTag", "names", ".", "UnitTag", ")", "error", "{", "if", "sa", ".", "facade", ".", "BestAPIVersion", "(", ")", "<", "2", "{", "return", "errors", ".", "NotImplementedf", "(", "\"", "\"", ")", "\n", "}", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "Tag", ":", "unitTag", ".", "String", "(", ")", "}", "}", ",", "}", "\n", "var", "results", "params", ".", "ErrorResults", "\n", "err", ":=", "sa", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "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", "}" ]
// DestroyUnitStorageAttachments ensures that the specified unit's storage // attachments will be removed at some point in the future.
[ "DestroyUnitStorageAttachments", "ensures", "that", "the", "specified", "unit", "s", "storage", "attachments", "will", "be", "removed", "at", "some", "point", "in", "the", "future", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/storage.go#L51-L71
157,151
juju/juju
api/uniter/storage.go
WatchUnitStorageAttachments
func (sa *StorageAccessor) WatchUnitStorageAttachments(unitTag names.UnitTag) (watcher.StringsWatcher, error) { var results params.StringsWatchResults args := params.Entities{ Entities: []params.Entity{{Tag: unitTag.String()}}, } err := sa.facade.FacadeCall("WatchUnitStorageAttachments", args, &results) if err != nil { return nil, err } if len(results.Results) != 1 { return nil, errors.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, result.Error } w := apiwatcher.NewStringsWatcher(sa.facade.RawAPICaller(), result) return w, nil }
go
func (sa *StorageAccessor) WatchUnitStorageAttachments(unitTag names.UnitTag) (watcher.StringsWatcher, error) { var results params.StringsWatchResults args := params.Entities{ Entities: []params.Entity{{Tag: unitTag.String()}}, } err := sa.facade.FacadeCall("WatchUnitStorageAttachments", args, &results) if err != nil { return nil, err } if len(results.Results) != 1 { return nil, errors.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, result.Error } w := apiwatcher.NewStringsWatcher(sa.facade.RawAPICaller(), result) return w, nil }
[ "func", "(", "sa", "*", "StorageAccessor", ")", "WatchUnitStorageAttachments", "(", "unitTag", "names", ".", "UnitTag", ")", "(", "watcher", ".", "StringsWatcher", ",", "error", ")", "{", "var", "results", "params", ".", "StringsWatchResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "Tag", ":", "unitTag", ".", "String", "(", ")", "}", "}", ",", "}", "\n", "err", ":=", "sa", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "result", ".", "Error", "\n", "}", "\n", "w", ":=", "apiwatcher", ".", "NewStringsWatcher", "(", "sa", ".", "facade", ".", "RawAPICaller", "(", ")", ",", "result", ")", "\n", "return", "w", ",", "nil", "\n", "}" ]
// WatchUnitStorageAttachments starts a watcher for changes to storage // attachments related to the unit. The watcher will return the // IDs of the corresponding storage instances.
[ "WatchUnitStorageAttachments", "starts", "a", "watcher", "for", "changes", "to", "storage", "attachments", "related", "to", "the", "unit", ".", "The", "watcher", "will", "return", "the", "IDs", "of", "the", "corresponding", "storage", "instances", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/storage.go#L76-L94
157,152
juju/juju
api/uniter/storage.go
StorageAttachment
func (sa *StorageAccessor) StorageAttachment(storageTag names.StorageTag, unitTag names.UnitTag) (params.StorageAttachment, error) { if sa.facade.BestAPIVersion() < 2 { return params.StorageAttachment{}, errors.NotImplementedf("StorageAttachment() (need V2+)") } args := params.StorageAttachmentIds{ Ids: []params.StorageAttachmentId{{ StorageTag: storageTag.String(), UnitTag: unitTag.String(), }}, } var results params.StorageAttachmentResults err := sa.facade.FacadeCall("StorageAttachments", args, &results) if err != nil { return params.StorageAttachment{}, errors.Trace(err) } if len(results.Results) != 1 { return params.StorageAttachment{}, errors.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return params.StorageAttachment{}, result.Error } return result.Result, nil }
go
func (sa *StorageAccessor) StorageAttachment(storageTag names.StorageTag, unitTag names.UnitTag) (params.StorageAttachment, error) { if sa.facade.BestAPIVersion() < 2 { return params.StorageAttachment{}, errors.NotImplementedf("StorageAttachment() (need V2+)") } args := params.StorageAttachmentIds{ Ids: []params.StorageAttachmentId{{ StorageTag: storageTag.String(), UnitTag: unitTag.String(), }}, } var results params.StorageAttachmentResults err := sa.facade.FacadeCall("StorageAttachments", args, &results) if err != nil { return params.StorageAttachment{}, errors.Trace(err) } if len(results.Results) != 1 { return params.StorageAttachment{}, errors.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return params.StorageAttachment{}, result.Error } return result.Result, nil }
[ "func", "(", "sa", "*", "StorageAccessor", ")", "StorageAttachment", "(", "storageTag", "names", ".", "StorageTag", ",", "unitTag", "names", ".", "UnitTag", ")", "(", "params", ".", "StorageAttachment", ",", "error", ")", "{", "if", "sa", ".", "facade", ".", "BestAPIVersion", "(", ")", "<", "2", "{", "return", "params", ".", "StorageAttachment", "{", "}", ",", "errors", ".", "NotImplementedf", "(", "\"", "\"", ")", "\n", "}", "\n", "args", ":=", "params", ".", "StorageAttachmentIds", "{", "Ids", ":", "[", "]", "params", ".", "StorageAttachmentId", "{", "{", "StorageTag", ":", "storageTag", ".", "String", "(", ")", ",", "UnitTag", ":", "unitTag", ".", "String", "(", ")", ",", "}", "}", ",", "}", "\n", "var", "results", "params", ".", "StorageAttachmentResults", "\n", "err", ":=", "sa", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "StorageAttachment", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "params", ".", "StorageAttachment", "{", "}", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "params", ".", "StorageAttachment", "{", "}", ",", "result", ".", "Error", "\n", "}", "\n", "return", "result", ".", "Result", ",", "nil", "\n", "}" ]
// StorageAttachment returns the storage attachment with the specified // unit and storage tags.
[ "StorageAttachment", "returns", "the", "storage", "attachment", "with", "the", "specified", "unit", "and", "storage", "tags", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/storage.go#L98-L121
157,153
juju/juju
api/uniter/storage.go
StorageAttachmentLife
func (sa *StorageAccessor) StorageAttachmentLife(ids []params.StorageAttachmentId) ([]params.LifeResult, error) { if sa.facade.BestAPIVersion() < 2 { return nil, errors.NotImplementedf("StorageAttachmentLife() (need V2+)") } args := params.StorageAttachmentIds{ids} var results params.LifeResults err := sa.facade.FacadeCall("StorageAttachmentLife", args, &results) if err != nil { return nil, errors.Trace(err) } if len(results.Results) != len(ids) { return nil, errors.Errorf("expected %d results, got %d", len(ids), len(results.Results)) } return results.Results, nil }
go
func (sa *StorageAccessor) StorageAttachmentLife(ids []params.StorageAttachmentId) ([]params.LifeResult, error) { if sa.facade.BestAPIVersion() < 2 { return nil, errors.NotImplementedf("StorageAttachmentLife() (need V2+)") } args := params.StorageAttachmentIds{ids} var results params.LifeResults err := sa.facade.FacadeCall("StorageAttachmentLife", args, &results) if err != nil { return nil, errors.Trace(err) } if len(results.Results) != len(ids) { return nil, errors.Errorf("expected %d results, got %d", len(ids), len(results.Results)) } return results.Results, nil }
[ "func", "(", "sa", "*", "StorageAccessor", ")", "StorageAttachmentLife", "(", "ids", "[", "]", "params", ".", "StorageAttachmentId", ")", "(", "[", "]", "params", ".", "LifeResult", ",", "error", ")", "{", "if", "sa", ".", "facade", ".", "BestAPIVersion", "(", ")", "<", "2", "{", "return", "nil", ",", "errors", ".", "NotImplementedf", "(", "\"", "\"", ")", "\n", "}", "\n", "args", ":=", "params", ".", "StorageAttachmentIds", "{", "ids", "}", "\n", "var", "results", "params", ".", "LifeResults", "\n", "err", ":=", "sa", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "len", "(", "ids", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "ids", ")", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "return", "results", ".", "Results", ",", "nil", "\n", "}" ]
// StorageAttachmentLife returns the lifecycle state of the storage attachments // with the specified IDs.
[ "StorageAttachmentLife", "returns", "the", "lifecycle", "state", "of", "the", "storage", "attachments", "with", "the", "specified", "IDs", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/storage.go#L125-L139
157,154
juju/juju
api/uniter/storage.go
WatchStorageAttachment
func (sa *StorageAccessor) WatchStorageAttachment(storageTag names.StorageTag, unitTag names.UnitTag) (watcher.NotifyWatcher, error) { var results params.NotifyWatchResults args := params.StorageAttachmentIds{ Ids: []params.StorageAttachmentId{{ StorageTag: storageTag.String(), UnitTag: unitTag.String(), }}, } err := sa.facade.FacadeCall("WatchStorageAttachments", args, &results) if err != nil { return nil, err } if len(results.Results) != 1 { return nil, errors.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, result.Error } w := apiwatcher.NewNotifyWatcher(sa.facade.RawAPICaller(), result) return w, nil }
go
func (sa *StorageAccessor) WatchStorageAttachment(storageTag names.StorageTag, unitTag names.UnitTag) (watcher.NotifyWatcher, error) { var results params.NotifyWatchResults args := params.StorageAttachmentIds{ Ids: []params.StorageAttachmentId{{ StorageTag: storageTag.String(), UnitTag: unitTag.String(), }}, } err := sa.facade.FacadeCall("WatchStorageAttachments", args, &results) if err != nil { return nil, err } if len(results.Results) != 1 { return nil, errors.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, result.Error } w := apiwatcher.NewNotifyWatcher(sa.facade.RawAPICaller(), result) return w, nil }
[ "func", "(", "sa", "*", "StorageAccessor", ")", "WatchStorageAttachment", "(", "storageTag", "names", ".", "StorageTag", ",", "unitTag", "names", ".", "UnitTag", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "var", "results", "params", ".", "NotifyWatchResults", "\n", "args", ":=", "params", ".", "StorageAttachmentIds", "{", "Ids", ":", "[", "]", "params", ".", "StorageAttachmentId", "{", "{", "StorageTag", ":", "storageTag", ".", "String", "(", ")", ",", "UnitTag", ":", "unitTag", ".", "String", "(", ")", ",", "}", "}", ",", "}", "\n", "err", ":=", "sa", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "result", ".", "Error", "\n", "}", "\n", "w", ":=", "apiwatcher", ".", "NewNotifyWatcher", "(", "sa", ".", "facade", ".", "RawAPICaller", "(", ")", ",", "result", ")", "\n", "return", "w", ",", "nil", "\n", "}" ]
// WatchStorageAttachments starts a watcher for changes to the info // of the storage attachment with the specified unit and storage tags.
[ "WatchStorageAttachments", "starts", "a", "watcher", "for", "changes", "to", "the", "info", "of", "the", "storage", "attachment", "with", "the", "specified", "unit", "and", "storage", "tags", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/storage.go#L143-L164
157,155
juju/juju
api/uniter/storage.go
RemoveStorageAttachment
func (sa *StorageAccessor) RemoveStorageAttachment(storageTag names.StorageTag, unitTag names.UnitTag) error { var results params.ErrorResults args := params.StorageAttachmentIds{ Ids: []params.StorageAttachmentId{{ StorageTag: storageTag.String(), UnitTag: unitTag.String(), }}, } err := sa.facade.FacadeCall("RemoveStorageAttachments", 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 (sa *StorageAccessor) RemoveStorageAttachment(storageTag names.StorageTag, unitTag names.UnitTag) error { var results params.ErrorResults args := params.StorageAttachmentIds{ Ids: []params.StorageAttachmentId{{ StorageTag: storageTag.String(), UnitTag: unitTag.String(), }}, } err := sa.facade.FacadeCall("RemoveStorageAttachments", 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", "(", "sa", "*", "StorageAccessor", ")", "RemoveStorageAttachment", "(", "storageTag", "names", ".", "StorageTag", ",", "unitTag", "names", ".", "UnitTag", ")", "error", "{", "var", "results", "params", ".", "ErrorResults", "\n", "args", ":=", "params", ".", "StorageAttachmentIds", "{", "Ids", ":", "[", "]", "params", ".", "StorageAttachmentId", "{", "{", "StorageTag", ":", "storageTag", ".", "String", "(", ")", ",", "UnitTag", ":", "unitTag", ".", "String", "(", ")", ",", "}", "}", ",", "}", "\n", "err", ":=", "sa", ".", "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", "}" ]
// RemoveStorageAttachment removes the storage attachment with the // specified unit and storage tags from state. This method is only // expected to succeed if the storage attachment is Dead.
[ "RemoveStorageAttachment", "removes", "the", "storage", "attachment", "with", "the", "specified", "unit", "and", "storage", "tags", "from", "state", ".", "This", "method", "is", "only", "expected", "to", "succeed", "if", "the", "storage", "attachment", "is", "Dead", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/storage.go#L169-L189
157,156
juju/juju
cloudconfig/instancecfg/instancecfg.go
Marshal
func (p *StateInitializationParams) Marshal() ([]byte, error) { customImageMetadataJSON, err := json.Marshal(p.CustomImageMetadata) if err != nil { return nil, errors.Annotate(err, "marshalling custom image metadata") } controllerCloud, err := cloud.MarshalCloud(p.ControllerCloud) if err != nil { return nil, errors.Annotate(err, "marshalling cloud definition") } internal := stateInitializationParamsInternal{ p.ControllerConfig, p.ControllerModelConfig.AllAttrs(), p.ControllerModelEnvironVersion, p.ControllerInheritedConfig, p.RegionInheritedConfig, p.HostedModelConfig, p.BootstrapMachineInstanceId, p.BootstrapMachineConstraints, p.BootstrapMachineHardwareCharacteristics, p.ModelConstraints, string(customImageMetadataJSON), string(controllerCloud), p.ControllerCloudRegion, p.ControllerCloudCredentialName, p.ControllerCloudCredential, } return yaml.Marshal(&internal) }
go
func (p *StateInitializationParams) Marshal() ([]byte, error) { customImageMetadataJSON, err := json.Marshal(p.CustomImageMetadata) if err != nil { return nil, errors.Annotate(err, "marshalling custom image metadata") } controllerCloud, err := cloud.MarshalCloud(p.ControllerCloud) if err != nil { return nil, errors.Annotate(err, "marshalling cloud definition") } internal := stateInitializationParamsInternal{ p.ControllerConfig, p.ControllerModelConfig.AllAttrs(), p.ControllerModelEnvironVersion, p.ControllerInheritedConfig, p.RegionInheritedConfig, p.HostedModelConfig, p.BootstrapMachineInstanceId, p.BootstrapMachineConstraints, p.BootstrapMachineHardwareCharacteristics, p.ModelConstraints, string(customImageMetadataJSON), string(controllerCloud), p.ControllerCloudRegion, p.ControllerCloudCredentialName, p.ControllerCloudCredential, } return yaml.Marshal(&internal) }
[ "func", "(", "p", "*", "StateInitializationParams", ")", "Marshal", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "customImageMetadataJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "p", ".", "CustomImageMetadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "controllerCloud", ",", "err", ":=", "cloud", ".", "MarshalCloud", "(", "p", ".", "ControllerCloud", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "internal", ":=", "stateInitializationParamsInternal", "{", "p", ".", "ControllerConfig", ",", "p", ".", "ControllerModelConfig", ".", "AllAttrs", "(", ")", ",", "p", ".", "ControllerModelEnvironVersion", ",", "p", ".", "ControllerInheritedConfig", ",", "p", ".", "RegionInheritedConfig", ",", "p", ".", "HostedModelConfig", ",", "p", ".", "BootstrapMachineInstanceId", ",", "p", ".", "BootstrapMachineConstraints", ",", "p", ".", "BootstrapMachineHardwareCharacteristics", ",", "p", ".", "ModelConstraints", ",", "string", "(", "customImageMetadataJSON", ")", ",", "string", "(", "controllerCloud", ")", ",", "p", ".", "ControllerCloudRegion", ",", "p", ".", "ControllerCloudCredentialName", ",", "p", ".", "ControllerCloudCredential", ",", "}", "\n", "return", "yaml", ".", "Marshal", "(", "&", "internal", ")", "\n", "}" ]
// Marshal marshals StateInitializationParams to an opaque byte array.
[ "Marshal", "marshals", "StateInitializationParams", "to", "an", "opaque", "byte", "array", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/instancecfg/instancecfg.go#L331-L358
157,157
juju/juju
cloudconfig/instancecfg/instancecfg.go
Unmarshal
func (p *StateInitializationParams) Unmarshal(data []byte) error { var internal stateInitializationParamsInternal if err := yaml.Unmarshal(data, &internal); err != nil { return errors.Annotate(err, "unmarshalling state initialization params") } var imageMetadata []*imagemetadata.ImageMetadata if err := json.Unmarshal([]byte(internal.CustomImageMetadataJSON), &imageMetadata); err != nil { return errors.Trace(err) } cfg, err := config.New(config.NoDefaults, internal.ControllerModelConfig) if err != nil { return errors.Trace(err) } controllerCloud, err := cloud.UnmarshalCloud([]byte(internal.ControllerCloud)) if err != nil { return errors.Trace(err) } *p = StateInitializationParams{ ControllerConfig: internal.ControllerConfig, ControllerModelConfig: cfg, ControllerModelEnvironVersion: internal.ControllerModelEnvironVersion, ControllerInheritedConfig: internal.ControllerInheritedConfig, RegionInheritedConfig: internal.RegionInheritedConfig, HostedModelConfig: internal.HostedModelConfig, BootstrapMachineInstanceId: internal.BootstrapMachineInstanceId, BootstrapMachineConstraints: internal.BootstrapMachineConstraints, BootstrapMachineHardwareCharacteristics: internal.BootstrapMachineHardwareCharacteristics, ModelConstraints: internal.ModelConstraints, CustomImageMetadata: imageMetadata, ControllerCloud: controllerCloud, ControllerCloudRegion: internal.ControllerCloudRegion, ControllerCloudCredentialName: internal.ControllerCloudCredentialName, ControllerCloudCredential: internal.ControllerCloudCredential, } return nil }
go
func (p *StateInitializationParams) Unmarshal(data []byte) error { var internal stateInitializationParamsInternal if err := yaml.Unmarshal(data, &internal); err != nil { return errors.Annotate(err, "unmarshalling state initialization params") } var imageMetadata []*imagemetadata.ImageMetadata if err := json.Unmarshal([]byte(internal.CustomImageMetadataJSON), &imageMetadata); err != nil { return errors.Trace(err) } cfg, err := config.New(config.NoDefaults, internal.ControllerModelConfig) if err != nil { return errors.Trace(err) } controllerCloud, err := cloud.UnmarshalCloud([]byte(internal.ControllerCloud)) if err != nil { return errors.Trace(err) } *p = StateInitializationParams{ ControllerConfig: internal.ControllerConfig, ControllerModelConfig: cfg, ControllerModelEnvironVersion: internal.ControllerModelEnvironVersion, ControllerInheritedConfig: internal.ControllerInheritedConfig, RegionInheritedConfig: internal.RegionInheritedConfig, HostedModelConfig: internal.HostedModelConfig, BootstrapMachineInstanceId: internal.BootstrapMachineInstanceId, BootstrapMachineConstraints: internal.BootstrapMachineConstraints, BootstrapMachineHardwareCharacteristics: internal.BootstrapMachineHardwareCharacteristics, ModelConstraints: internal.ModelConstraints, CustomImageMetadata: imageMetadata, ControllerCloud: controllerCloud, ControllerCloudRegion: internal.ControllerCloudRegion, ControllerCloudCredentialName: internal.ControllerCloudCredentialName, ControllerCloudCredential: internal.ControllerCloudCredential, } return nil }
[ "func", "(", "p", "*", "StateInitializationParams", ")", "Unmarshal", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "internal", "stateInitializationParamsInternal", "\n", "if", "err", ":=", "yaml", ".", "Unmarshal", "(", "data", ",", "&", "internal", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "var", "imageMetadata", "[", "]", "*", "imagemetadata", ".", "ImageMetadata", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "internal", ".", "CustomImageMetadataJSON", ")", ",", "&", "imageMetadata", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "cfg", ",", "err", ":=", "config", ".", "New", "(", "config", ".", "NoDefaults", ",", "internal", ".", "ControllerModelConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "controllerCloud", ",", "err", ":=", "cloud", ".", "UnmarshalCloud", "(", "[", "]", "byte", "(", "internal", ".", "ControllerCloud", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "*", "p", "=", "StateInitializationParams", "{", "ControllerConfig", ":", "internal", ".", "ControllerConfig", ",", "ControllerModelConfig", ":", "cfg", ",", "ControllerModelEnvironVersion", ":", "internal", ".", "ControllerModelEnvironVersion", ",", "ControllerInheritedConfig", ":", "internal", ".", "ControllerInheritedConfig", ",", "RegionInheritedConfig", ":", "internal", ".", "RegionInheritedConfig", ",", "HostedModelConfig", ":", "internal", ".", "HostedModelConfig", ",", "BootstrapMachineInstanceId", ":", "internal", ".", "BootstrapMachineInstanceId", ",", "BootstrapMachineConstraints", ":", "internal", ".", "BootstrapMachineConstraints", ",", "BootstrapMachineHardwareCharacteristics", ":", "internal", ".", "BootstrapMachineHardwareCharacteristics", ",", "ModelConstraints", ":", "internal", ".", "ModelConstraints", ",", "CustomImageMetadata", ":", "imageMetadata", ",", "ControllerCloud", ":", "controllerCloud", ",", "ControllerCloudRegion", ":", "internal", ".", "ControllerCloudRegion", ",", "ControllerCloudCredentialName", ":", "internal", ".", "ControllerCloudCredentialName", ",", "ControllerCloudCredential", ":", "internal", ".", "ControllerCloudCredential", ",", "}", "\n", "return", "nil", "\n", "}" ]
// Unmarshal unmarshals StateInitializationParams from a byte array that // was generated with StateInitializationParams.Marshal.
[ "Unmarshal", "unmarshals", "StateInitializationParams", "from", "a", "byte", "array", "that", "was", "generated", "with", "StateInitializationParams", ".", "Marshal", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/instancecfg/instancecfg.go#L362-L397
157,158
juju/juju
cloudconfig/instancecfg/instancecfg.go
JujuTools
func (cfg *InstanceConfig) JujuTools() string { return agenttools.SharedToolsDir(cfg.DataDir, cfg.AgentVersion()) }
go
func (cfg *InstanceConfig) JujuTools() string { return agenttools.SharedToolsDir(cfg.DataDir, cfg.AgentVersion()) }
[ "func", "(", "cfg", "*", "InstanceConfig", ")", "JujuTools", "(", ")", "string", "{", "return", "agenttools", ".", "SharedToolsDir", "(", "cfg", ".", "DataDir", ",", "cfg", ".", "AgentVersion", "(", ")", ")", "\n", "}" ]
// JujuTools returns the directory where Juju tools are stored.
[ "JujuTools", "returns", "the", "directory", "where", "Juju", "tools", "are", "stored", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/instancecfg/instancecfg.go#L459-L461
157,159
juju/juju
cloudconfig/instancecfg/instancecfg.go
AgentVersion
func (cfg *InstanceConfig) AgentVersion() version.Binary { if len(cfg.tools) == 0 { return version.Binary{} } return cfg.tools[0].Version }
go
func (cfg *InstanceConfig) AgentVersion() version.Binary { if len(cfg.tools) == 0 { return version.Binary{} } return cfg.tools[0].Version }
[ "func", "(", "cfg", "*", "InstanceConfig", ")", "AgentVersion", "(", ")", "version", ".", "Binary", "{", "if", "len", "(", "cfg", ".", "tools", ")", "==", "0", "{", "return", "version", ".", "Binary", "{", "}", "\n", "}", "\n", "return", "cfg", ".", "tools", "[", "0", "]", ".", "Version", "\n", "}" ]
// AgentVersion returns the version of the Juju agent that will be configured // on the instance. The zero value will be returned if there are no tools set.
[ "AgentVersion", "returns", "the", "version", "of", "the", "Juju", "agent", "that", "will", "be", "configured", "on", "the", "instance", ".", "The", "zero", "value", "will", "be", "returned", "if", "there", "are", "no", "tools", "set", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/instancecfg/instancecfg.go#L519-L524
157,160
juju/juju
cloudconfig/instancecfg/instancecfg.go
ToolsList
func (cfg *InstanceConfig) ToolsList() coretools.List { if cfg.tools == nil { return nil } return copyToolsList(cfg.tools) }
go
func (cfg *InstanceConfig) ToolsList() coretools.List { if cfg.tools == nil { return nil } return copyToolsList(cfg.tools) }
[ "func", "(", "cfg", "*", "InstanceConfig", ")", "ToolsList", "(", ")", "coretools", ".", "List", "{", "if", "cfg", ".", "tools", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "copyToolsList", "(", "cfg", ".", "tools", ")", "\n", "}" ]
// ToolsList returns the list of tools in the order in which they will // be tried.
[ "ToolsList", "returns", "the", "list", "of", "tools", "in", "the", "order", "in", "which", "they", "will", "be", "tried", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/instancecfg/instancecfg.go#L528-L533
157,161
juju/juju
cloudconfig/instancecfg/instancecfg.go
SetSnapSource
func (cfg *InstanceConfig) SetSnapSource(snapPath string, snapAssertionsPath string) error { if snapPath == "" { return nil } _, err := os.Stat(snapPath) if err != nil { return errors.Annotatef(err, "unable set local snap (at %s)", snapPath) } _, err = os.Stat(snapAssertionsPath) if err != nil { return errors.Annotatef(err, "unable set local snap .assert (at %s)", snapAssertionsPath) } cfg.Bootstrap.JujuDbSnapPath = snapPath cfg.Bootstrap.JujuDbSnapAssertionsPath = snapAssertionsPath return nil }
go
func (cfg *InstanceConfig) SetSnapSource(snapPath string, snapAssertionsPath string) error { if snapPath == "" { return nil } _, err := os.Stat(snapPath) if err != nil { return errors.Annotatef(err, "unable set local snap (at %s)", snapPath) } _, err = os.Stat(snapAssertionsPath) if err != nil { return errors.Annotatef(err, "unable set local snap .assert (at %s)", snapAssertionsPath) } cfg.Bootstrap.JujuDbSnapPath = snapPath cfg.Bootstrap.JujuDbSnapAssertionsPath = snapAssertionsPath return nil }
[ "func", "(", "cfg", "*", "InstanceConfig", ")", "SetSnapSource", "(", "snapPath", "string", ",", "snapAssertionsPath", "string", ")", "error", "{", "if", "snapPath", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "_", ",", "err", ":=", "os", ".", "Stat", "(", "snapPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "snapPath", ")", "\n", "}", "\n\n", "_", ",", "err", "=", "os", ".", "Stat", "(", "snapAssertionsPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "snapAssertionsPath", ")", "\n", "}", "\n\n", "cfg", ".", "Bootstrap", ".", "JujuDbSnapPath", "=", "snapPath", "\n", "cfg", ".", "Bootstrap", ".", "JujuDbSnapAssertionsPath", "=", "snapAssertionsPath", "\n\n", "return", "nil", "\n", "}" ]
// SetSnapSource annotates the instance configuration // with the location of a local .snap to upload during // the instance's provisioning.
[ "SetSnapSource", "annotates", "the", "instance", "configuration", "with", "the", "location", "of", "a", "local", ".", "snap", "to", "upload", "during", "the", "instance", "s", "provisioning", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/instancecfg/instancecfg.go#L578-L597
157,162
juju/juju
cloudconfig/instancecfg/instancecfg.go
VerifyConfig
func (cfg *InstanceConfig) VerifyConfig() (err error) { defer errors.DeferredAnnotatef(&err, "invalid machine configuration") if !names.IsValidMachine(cfg.MachineId) { return errors.New("invalid machine id") } if cfg.DataDir == "" { return errors.New("missing var directory") } if cfg.LogDir == "" { return errors.New("missing log directory") } if cfg.MetricsSpoolDir == "" { return errors.New("missing metrics spool directory") } if len(cfg.Jobs) == 0 { return errors.New("missing machine jobs") } if cfg.CloudInitOutputLog == "" { return errors.New("missing cloud-init output log path") } if cfg.tools == nil { // SetTools() has never been called successfully. return errors.New("missing agent binaries") } // We don't need to check cfg.toolsURLs since SetTools() does. if cfg.APIInfo == nil { return errors.New("missing API info") } if cfg.APIInfo.ModelTag.Id() == "" { return errors.New("missing model tag") } if len(cfg.APIInfo.CACert) == 0 { return errors.New("missing API CA certificate") } if cfg.MachineAgentServiceName == "" { return errors.New("missing machine agent service name") } if cfg.MachineNonce == "" { return errors.New("missing machine nonce") } if cfg.Controller != nil { if err := cfg.verifyControllerConfig(); err != nil { return errors.Trace(err) } } if cfg.Bootstrap != nil { if err := cfg.verifyBootstrapConfig(); err != nil { return errors.Trace(err) } } else { if cfg.APIInfo.Tag != names.NewMachineTag(cfg.MachineId) { return errors.New("API entity tag must match started machine") } if len(cfg.APIInfo.Addrs) == 0 { return errors.New("missing API hosts") } } return nil }
go
func (cfg *InstanceConfig) VerifyConfig() (err error) { defer errors.DeferredAnnotatef(&err, "invalid machine configuration") if !names.IsValidMachine(cfg.MachineId) { return errors.New("invalid machine id") } if cfg.DataDir == "" { return errors.New("missing var directory") } if cfg.LogDir == "" { return errors.New("missing log directory") } if cfg.MetricsSpoolDir == "" { return errors.New("missing metrics spool directory") } if len(cfg.Jobs) == 0 { return errors.New("missing machine jobs") } if cfg.CloudInitOutputLog == "" { return errors.New("missing cloud-init output log path") } if cfg.tools == nil { // SetTools() has never been called successfully. return errors.New("missing agent binaries") } // We don't need to check cfg.toolsURLs since SetTools() does. if cfg.APIInfo == nil { return errors.New("missing API info") } if cfg.APIInfo.ModelTag.Id() == "" { return errors.New("missing model tag") } if len(cfg.APIInfo.CACert) == 0 { return errors.New("missing API CA certificate") } if cfg.MachineAgentServiceName == "" { return errors.New("missing machine agent service name") } if cfg.MachineNonce == "" { return errors.New("missing machine nonce") } if cfg.Controller != nil { if err := cfg.verifyControllerConfig(); err != nil { return errors.Trace(err) } } if cfg.Bootstrap != nil { if err := cfg.verifyBootstrapConfig(); err != nil { return errors.Trace(err) } } else { if cfg.APIInfo.Tag != names.NewMachineTag(cfg.MachineId) { return errors.New("API entity tag must match started machine") } if len(cfg.APIInfo.Addrs) == 0 { return errors.New("missing API hosts") } } return nil }
[ "func", "(", "cfg", "*", "InstanceConfig", ")", "VerifyConfig", "(", ")", "(", "err", "error", ")", "{", "defer", "errors", ".", "DeferredAnnotatef", "(", "&", "err", ",", "\"", "\"", ")", "\n", "if", "!", "names", ".", "IsValidMachine", "(", "cfg", ".", "MachineId", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "DataDir", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "LogDir", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "MetricsSpoolDir", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "Jobs", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "CloudInitOutputLog", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "tools", "==", "nil", "{", "// SetTools() has never been called successfully.", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "// We don't need to check cfg.toolsURLs since SetTools() does.", "if", "cfg", ".", "APIInfo", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "APIInfo", ".", "ModelTag", ".", "Id", "(", ")", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "APIInfo", ".", "CACert", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "MachineAgentServiceName", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "MachineNonce", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "Controller", "!=", "nil", "{", "if", "err", ":=", "cfg", ".", "verifyControllerConfig", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "cfg", ".", "Bootstrap", "!=", "nil", "{", "if", "err", ":=", "cfg", ".", "verifyBootstrapConfig", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "if", "cfg", ".", "APIInfo", ".", "Tag", "!=", "names", ".", "NewMachineTag", "(", "cfg", ".", "MachineId", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "APIInfo", ".", "Addrs", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// VerifyConfig verifies that the InstanceConfig is valid.
[ "VerifyConfig", "verifies", "that", "the", "InstanceConfig", "is", "valid", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/instancecfg/instancecfg.go#L606-L664
157,163
juju/juju
cloudconfig/instancecfg/instancecfg.go
VerifyConfig
func (cfg *BootstrapConfig) VerifyConfig() (err error) { if cfg.ControllerModelConfig == nil { return errors.New("missing model configuration") } if len(cfg.StateServingInfo.Cert) == 0 { return errors.New("missing controller certificate") } if len(cfg.StateServingInfo.PrivateKey) == 0 { return errors.New("missing controller private key") } if len(cfg.StateServingInfo.CAPrivateKey) == 0 { return errors.New("missing ca cert private key") } if cfg.StateServingInfo.StatePort == 0 { return errors.New("missing state port") } if cfg.StateServingInfo.APIPort == 0 { return errors.New("missing API port") } if cfg.BootstrapMachineInstanceId == "" { return errors.New("missing bootstrap machine instance ID") } if len(cfg.HostedModelConfig) == 0 { return errors.New("missing hosted model config") } return nil }
go
func (cfg *BootstrapConfig) VerifyConfig() (err error) { if cfg.ControllerModelConfig == nil { return errors.New("missing model configuration") } if len(cfg.StateServingInfo.Cert) == 0 { return errors.New("missing controller certificate") } if len(cfg.StateServingInfo.PrivateKey) == 0 { return errors.New("missing controller private key") } if len(cfg.StateServingInfo.CAPrivateKey) == 0 { return errors.New("missing ca cert private key") } if cfg.StateServingInfo.StatePort == 0 { return errors.New("missing state port") } if cfg.StateServingInfo.APIPort == 0 { return errors.New("missing API port") } if cfg.BootstrapMachineInstanceId == "" { return errors.New("missing bootstrap machine instance ID") } if len(cfg.HostedModelConfig) == 0 { return errors.New("missing hosted model config") } return nil }
[ "func", "(", "cfg", "*", "BootstrapConfig", ")", "VerifyConfig", "(", ")", "(", "err", "error", ")", "{", "if", "cfg", ".", "ControllerModelConfig", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "StateServingInfo", ".", "Cert", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "StateServingInfo", ".", "PrivateKey", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "StateServingInfo", ".", "CAPrivateKey", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "StateServingInfo", ".", "StatePort", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "StateServingInfo", ".", "APIPort", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "BootstrapMachineInstanceId", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "HostedModelConfig", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// VerifyConfig verifies that the BootstrapConfig is valid.
[ "VerifyConfig", "verifies", "that", "the", "BootstrapConfig", "is", "valid", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/instancecfg/instancecfg.go#L697-L723
157,164
juju/juju
cloudconfig/instancecfg/instancecfg.go
NewInstanceConfig
func NewInstanceConfig( controllerTag names.ControllerTag, machineID, machineNonce, imageStream, series string, apiInfo *api.Info, ) (*InstanceConfig, error) { dataDir, err := paths.DataDir(series) if err != nil { return nil, err } logDir, err := paths.LogDir(series) if err != nil { return nil, err } metricsSpoolDir, err := paths.MetricsSpoolDir(series) if err != nil { return nil, err } cloudInitOutputLog := path.Join(logDir, "cloud-init-output.log") icfg := &InstanceConfig{ // Fixed entries. DataDir: dataDir, LogDir: path.Join(logDir, "juju"), MetricsSpoolDir: metricsSpoolDir, Jobs: []multiwatcher.MachineJob{multiwatcher.JobHostUnits}, CloudInitOutputLog: cloudInitOutputLog, MachineAgentServiceName: "jujud-" + names.NewMachineTag(machineID).String(), Series: series, Tags: map[string]string{}, // Parameter entries. ControllerTag: controllerTag, MachineId: machineID, MachineNonce: machineNonce, APIInfo: apiInfo, ImageStream: imageStream, } return icfg, nil }
go
func NewInstanceConfig( controllerTag names.ControllerTag, machineID, machineNonce, imageStream, series string, apiInfo *api.Info, ) (*InstanceConfig, error) { dataDir, err := paths.DataDir(series) if err != nil { return nil, err } logDir, err := paths.LogDir(series) if err != nil { return nil, err } metricsSpoolDir, err := paths.MetricsSpoolDir(series) if err != nil { return nil, err } cloudInitOutputLog := path.Join(logDir, "cloud-init-output.log") icfg := &InstanceConfig{ // Fixed entries. DataDir: dataDir, LogDir: path.Join(logDir, "juju"), MetricsSpoolDir: metricsSpoolDir, Jobs: []multiwatcher.MachineJob{multiwatcher.JobHostUnits}, CloudInitOutputLog: cloudInitOutputLog, MachineAgentServiceName: "jujud-" + names.NewMachineTag(machineID).String(), Series: series, Tags: map[string]string{}, // Parameter entries. ControllerTag: controllerTag, MachineId: machineID, MachineNonce: machineNonce, APIInfo: apiInfo, ImageStream: imageStream, } return icfg, nil }
[ "func", "NewInstanceConfig", "(", "controllerTag", "names", ".", "ControllerTag", ",", "machineID", ",", "machineNonce", ",", "imageStream", ",", "series", "string", ",", "apiInfo", "*", "api", ".", "Info", ",", ")", "(", "*", "InstanceConfig", ",", "error", ")", "{", "dataDir", ",", "err", ":=", "paths", ".", "DataDir", "(", "series", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "logDir", ",", "err", ":=", "paths", ".", "LogDir", "(", "series", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "metricsSpoolDir", ",", "err", ":=", "paths", ".", "MetricsSpoolDir", "(", "series", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cloudInitOutputLog", ":=", "path", ".", "Join", "(", "logDir", ",", "\"", "\"", ")", "\n", "icfg", ":=", "&", "InstanceConfig", "{", "// Fixed entries.", "DataDir", ":", "dataDir", ",", "LogDir", ":", "path", ".", "Join", "(", "logDir", ",", "\"", "\"", ")", ",", "MetricsSpoolDir", ":", "metricsSpoolDir", ",", "Jobs", ":", "[", "]", "multiwatcher", ".", "MachineJob", "{", "multiwatcher", ".", "JobHostUnits", "}", ",", "CloudInitOutputLog", ":", "cloudInitOutputLog", ",", "MachineAgentServiceName", ":", "\"", "\"", "+", "names", ".", "NewMachineTag", "(", "machineID", ")", ".", "String", "(", ")", ",", "Series", ":", "series", ",", "Tags", ":", "map", "[", "string", "]", "string", "{", "}", ",", "// Parameter entries.", "ControllerTag", ":", "controllerTag", ",", "MachineId", ":", "machineID", ",", "MachineNonce", ":", "machineNonce", ",", "APIInfo", ":", "apiInfo", ",", "ImageStream", ":", "imageStream", ",", "}", "\n", "return", "icfg", ",", "nil", "\n", "}" ]
// NewInstanceConfig sets up a basic machine configuration, for a // non-bootstrap node. You'll still need to supply more information, // but this takes care of the fixed entries and the ones that are // always needed.
[ "NewInstanceConfig", "sets", "up", "a", "basic", "machine", "configuration", "for", "a", "non", "-", "bootstrap", "node", ".", "You", "ll", "still", "need", "to", "supply", "more", "information", "but", "this", "takes", "care", "of", "the", "fixed", "entries", "and", "the", "ones", "that", "are", "always", "needed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/instancecfg/instancecfg.go#L744-L784
157,165
juju/juju
cloudconfig/instancecfg/instancecfg.go
NewBootstrapInstanceConfig
func NewBootstrapInstanceConfig( config controller.Config, cons, modelCons constraints.Value, series, publicImageSigningKey string, ) (*InstanceConfig, error) { // For a bootstrap instance, the caller must provide the state.Info // and the api.Info. The machine id must *always* be "0". icfg, err := NewInstanceConfig(names.NewControllerTag(config.ControllerUUID()), "0", agent.BootstrapNonce, "", series, nil) if err != nil { return nil, err } icfg.Controller = &ControllerConfig{ PublicImageSigningKey: publicImageSigningKey, } icfg.Controller.Config = make(map[string]interface{}) for k, v := range config { icfg.Controller.Config[k] = v } icfg.Bootstrap = &BootstrapConfig{ StateInitializationParams: StateInitializationParams{ BootstrapMachineConstraints: cons, ModelConstraints: modelCons, }, } icfg.Jobs = []multiwatcher.MachineJob{ multiwatcher.JobManageModel, multiwatcher.JobHostUnits, } return icfg, nil }
go
func NewBootstrapInstanceConfig( config controller.Config, cons, modelCons constraints.Value, series, publicImageSigningKey string, ) (*InstanceConfig, error) { // For a bootstrap instance, the caller must provide the state.Info // and the api.Info. The machine id must *always* be "0". icfg, err := NewInstanceConfig(names.NewControllerTag(config.ControllerUUID()), "0", agent.BootstrapNonce, "", series, nil) if err != nil { return nil, err } icfg.Controller = &ControllerConfig{ PublicImageSigningKey: publicImageSigningKey, } icfg.Controller.Config = make(map[string]interface{}) for k, v := range config { icfg.Controller.Config[k] = v } icfg.Bootstrap = &BootstrapConfig{ StateInitializationParams: StateInitializationParams{ BootstrapMachineConstraints: cons, ModelConstraints: modelCons, }, } icfg.Jobs = []multiwatcher.MachineJob{ multiwatcher.JobManageModel, multiwatcher.JobHostUnits, } return icfg, nil }
[ "func", "NewBootstrapInstanceConfig", "(", "config", "controller", ".", "Config", ",", "cons", ",", "modelCons", "constraints", ".", "Value", ",", "series", ",", "publicImageSigningKey", "string", ",", ")", "(", "*", "InstanceConfig", ",", "error", ")", "{", "// For a bootstrap instance, the caller must provide the state.Info", "// and the api.Info. The machine id must *always* be \"0\".", "icfg", ",", "err", ":=", "NewInstanceConfig", "(", "names", ".", "NewControllerTag", "(", "config", ".", "ControllerUUID", "(", ")", ")", ",", "\"", "\"", ",", "agent", ".", "BootstrapNonce", ",", "\"", "\"", ",", "series", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "icfg", ".", "Controller", "=", "&", "ControllerConfig", "{", "PublicImageSigningKey", ":", "publicImageSigningKey", ",", "}", "\n", "icfg", ".", "Controller", ".", "Config", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "for", "k", ",", "v", ":=", "range", "config", "{", "icfg", ".", "Controller", ".", "Config", "[", "k", "]", "=", "v", "\n", "}", "\n", "icfg", ".", "Bootstrap", "=", "&", "BootstrapConfig", "{", "StateInitializationParams", ":", "StateInitializationParams", "{", "BootstrapMachineConstraints", ":", "cons", ",", "ModelConstraints", ":", "modelCons", ",", "}", ",", "}", "\n", "icfg", ".", "Jobs", "=", "[", "]", "multiwatcher", ".", "MachineJob", "{", "multiwatcher", ".", "JobManageModel", ",", "multiwatcher", ".", "JobHostUnits", ",", "}", "\n", "return", "icfg", ",", "nil", "\n", "}" ]
// NewBootstrapInstanceConfig sets up a basic machine configuration for a // bootstrap node. You'll still need to supply more information, but this // takes care of the fixed entries and the ones that are always needed.
[ "NewBootstrapInstanceConfig", "sets", "up", "a", "basic", "machine", "configuration", "for", "a", "bootstrap", "node", ".", "You", "ll", "still", "need", "to", "supply", "more", "information", "but", "this", "takes", "care", "of", "the", "fixed", "entries", "and", "the", "ones", "that", "are", "always", "needed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/instancecfg/instancecfg.go#L789-L818
157,166
juju/juju
cloudconfig/instancecfg/instancecfg.go
PopulateInstanceConfig
func PopulateInstanceConfig(icfg *InstanceConfig, providerType, authorizedKeys string, sslHostnameVerification bool, legacyProxySettings, jujuProxySettings, aptProxySettings proxy.Settings, aptMirror string, enableOSRefreshUpdates bool, enableOSUpgrade bool, cloudInitUserData map[string]interface{}, profiles []string, ) error { icfg.AuthorizedKeys = authorizedKeys if icfg.AgentEnvironment == nil { icfg.AgentEnvironment = make(map[string]string) } icfg.AgentEnvironment[agent.ProviderType] = providerType icfg.AgentEnvironment[agent.ContainerType] = string(icfg.MachineContainerType) icfg.DisableSSLHostnameVerification = !sslHostnameVerification icfg.LegacyProxySettings = legacyProxySettings icfg.LegacyProxySettings.AutoNoProxy = strings.Join(icfg.APIHosts(), ",") icfg.JujuProxySettings = jujuProxySettings // No AutoNoProxy needed as juju no proxy values are CIDR aware. icfg.AptProxySettings = aptProxySettings icfg.AptMirror = aptMirror icfg.EnableOSRefreshUpdate = enableOSRefreshUpdates icfg.EnableOSUpgrade = enableOSUpgrade icfg.CloudInitUserData = cloudInitUserData icfg.Profiles = profiles return nil }
go
func PopulateInstanceConfig(icfg *InstanceConfig, providerType, authorizedKeys string, sslHostnameVerification bool, legacyProxySettings, jujuProxySettings, aptProxySettings proxy.Settings, aptMirror string, enableOSRefreshUpdates bool, enableOSUpgrade bool, cloudInitUserData map[string]interface{}, profiles []string, ) error { icfg.AuthorizedKeys = authorizedKeys if icfg.AgentEnvironment == nil { icfg.AgentEnvironment = make(map[string]string) } icfg.AgentEnvironment[agent.ProviderType] = providerType icfg.AgentEnvironment[agent.ContainerType] = string(icfg.MachineContainerType) icfg.DisableSSLHostnameVerification = !sslHostnameVerification icfg.LegacyProxySettings = legacyProxySettings icfg.LegacyProxySettings.AutoNoProxy = strings.Join(icfg.APIHosts(), ",") icfg.JujuProxySettings = jujuProxySettings // No AutoNoProxy needed as juju no proxy values are CIDR aware. icfg.AptProxySettings = aptProxySettings icfg.AptMirror = aptMirror icfg.EnableOSRefreshUpdate = enableOSRefreshUpdates icfg.EnableOSUpgrade = enableOSUpgrade icfg.CloudInitUserData = cloudInitUserData icfg.Profiles = profiles return nil }
[ "func", "PopulateInstanceConfig", "(", "icfg", "*", "InstanceConfig", ",", "providerType", ",", "authorizedKeys", "string", ",", "sslHostnameVerification", "bool", ",", "legacyProxySettings", ",", "jujuProxySettings", ",", "aptProxySettings", "proxy", ".", "Settings", ",", "aptMirror", "string", ",", "enableOSRefreshUpdates", "bool", ",", "enableOSUpgrade", "bool", ",", "cloudInitUserData", "map", "[", "string", "]", "interface", "{", "}", ",", "profiles", "[", "]", "string", ",", ")", "error", "{", "icfg", ".", "AuthorizedKeys", "=", "authorizedKeys", "\n", "if", "icfg", ".", "AgentEnvironment", "==", "nil", "{", "icfg", ".", "AgentEnvironment", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "icfg", ".", "AgentEnvironment", "[", "agent", ".", "ProviderType", "]", "=", "providerType", "\n", "icfg", ".", "AgentEnvironment", "[", "agent", ".", "ContainerType", "]", "=", "string", "(", "icfg", ".", "MachineContainerType", ")", "\n", "icfg", ".", "DisableSSLHostnameVerification", "=", "!", "sslHostnameVerification", "\n", "icfg", ".", "LegacyProxySettings", "=", "legacyProxySettings", "\n", "icfg", ".", "LegacyProxySettings", ".", "AutoNoProxy", "=", "strings", ".", "Join", "(", "icfg", ".", "APIHosts", "(", ")", ",", "\"", "\"", ")", "\n", "icfg", ".", "JujuProxySettings", "=", "jujuProxySettings", "\n", "// No AutoNoProxy needed as juju no proxy values are CIDR aware.", "icfg", ".", "AptProxySettings", "=", "aptProxySettings", "\n", "icfg", ".", "AptMirror", "=", "aptMirror", "\n", "icfg", ".", "EnableOSRefreshUpdate", "=", "enableOSRefreshUpdates", "\n", "icfg", ".", "EnableOSUpgrade", "=", "enableOSUpgrade", "\n", "icfg", ".", "CloudInitUserData", "=", "cloudInitUserData", "\n", "icfg", ".", "Profiles", "=", "profiles", "\n", "return", "nil", "\n", "}" ]
// PopulateInstanceConfig is called both from the FinishInstanceConfig below, // which does have access to the environment config, and from the container // provisioners, which don't have access to the environment config. Everything // that is needed to provision a container needs to be returned to the // provisioner in the ContainerConfig structure. Those values are then used to // call this function.
[ "PopulateInstanceConfig", "is", "called", "both", "from", "the", "FinishInstanceConfig", "below", "which", "does", "have", "access", "to", "the", "environment", "config", "and", "from", "the", "container", "provisioners", "which", "don", "t", "have", "access", "to", "the", "environment", "config", ".", "Everything", "that", "is", "needed", "to", "provision", "a", "container", "needs", "to", "be", "returned", "to", "the", "provisioner", "in", "the", "ContainerConfig", "structure", ".", "Those", "values", "are", "then", "used", "to", "call", "this", "function", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/instancecfg/instancecfg.go#L826-L854
157,167
juju/juju
cloudconfig/instancecfg/instancecfg.go
InstanceTags
func InstanceTags(modelUUID, controllerUUID string, tagger tags.ResourceTagger, jobs []multiwatcher.MachineJob) map[string]string { instanceTags := tags.ResourceTags( names.NewModelTag(modelUUID), names.NewControllerTag(controllerUUID), tagger, ) if multiwatcher.AnyJobNeedsState(jobs...) { instanceTags[tags.JujuIsController] = "true" } return instanceTags }
go
func InstanceTags(modelUUID, controllerUUID string, tagger tags.ResourceTagger, jobs []multiwatcher.MachineJob) map[string]string { instanceTags := tags.ResourceTags( names.NewModelTag(modelUUID), names.NewControllerTag(controllerUUID), tagger, ) if multiwatcher.AnyJobNeedsState(jobs...) { instanceTags[tags.JujuIsController] = "true" } return instanceTags }
[ "func", "InstanceTags", "(", "modelUUID", ",", "controllerUUID", "string", ",", "tagger", "tags", ".", "ResourceTagger", ",", "jobs", "[", "]", "multiwatcher", ".", "MachineJob", ")", "map", "[", "string", "]", "string", "{", "instanceTags", ":=", "tags", ".", "ResourceTags", "(", "names", ".", "NewModelTag", "(", "modelUUID", ")", ",", "names", ".", "NewControllerTag", "(", "controllerUUID", ")", ",", "tagger", ",", ")", "\n", "if", "multiwatcher", ".", "AnyJobNeedsState", "(", "jobs", "...", ")", "{", "instanceTags", "[", "tags", ".", "JujuIsController", "]", "=", "\"", "\"", "\n", "}", "\n", "return", "instanceTags", "\n", "}" ]
// InstanceTags returns the minimum set of tags that should be set on a // machine instance, if the provider supports them.
[ "InstanceTags", "returns", "the", "minimum", "set", "of", "tags", "that", "should", "be", "set", "on", "a", "machine", "instance", "if", "the", "provider", "supports", "them", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/instancecfg/instancecfg.go#L896-L906
157,168
juju/juju
worker/metrics/sender/manifold.go
Manifold
func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{ config.AgentName, config.APICallerName, config.MetricSpoolName, }, Start: func(context dependency.Context) (worker.Worker, error) { var apicaller base.APICaller var factory spool.MetricFactory err := context.Get(config.APICallerName, &apicaller) if err != nil { return nil, errors.Trace(err) } err = context.Get(config.MetricSpoolName, &factory) if err != nil { return nil, errors.Trace(err) } var agent agent.Agent if err := context.Get(config.AgentName, &agent); err != nil { return nil, err } agentConfig := agent.CurrentConfig() tag := agentConfig.Tag() unitTag, ok := tag.(names.UnitTag) if !ok { return nil, errors.Errorf("expected a unit tag, got %v", tag) } paths := uniter.NewWorkerPaths(agentConfig.DataDir(), unitTag, "metrics-send") client := newMetricAdderClient(apicaller) s, err := newSender(client, factory, paths.State.BaseDir, unitTag.String()) if err != nil { return nil, errors.Trace(err) } return spool.NewPeriodicWorker(s.Do, period, jworker.NewTimer, s.stop), nil }, } }
go
func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{ config.AgentName, config.APICallerName, config.MetricSpoolName, }, Start: func(context dependency.Context) (worker.Worker, error) { var apicaller base.APICaller var factory spool.MetricFactory err := context.Get(config.APICallerName, &apicaller) if err != nil { return nil, errors.Trace(err) } err = context.Get(config.MetricSpoolName, &factory) if err != nil { return nil, errors.Trace(err) } var agent agent.Agent if err := context.Get(config.AgentName, &agent); err != nil { return nil, err } agentConfig := agent.CurrentConfig() tag := agentConfig.Tag() unitTag, ok := tag.(names.UnitTag) if !ok { return nil, errors.Errorf("expected a unit tag, got %v", tag) } paths := uniter.NewWorkerPaths(agentConfig.DataDir(), unitTag, "metrics-send") client := newMetricAdderClient(apicaller) s, err := newSender(client, factory, paths.State.BaseDir, unitTag.String()) if err != nil { return nil, errors.Trace(err) } return spool.NewPeriodicWorker(s.Do, period, jworker.NewTimer, s.stop), nil }, } }
[ "func", "Manifold", "(", "config", "ManifoldConfig", ")", "dependency", ".", "Manifold", "{", "return", "dependency", ".", "Manifold", "{", "Inputs", ":", "[", "]", "string", "{", "config", ".", "AgentName", ",", "config", ".", "APICallerName", ",", "config", ".", "MetricSpoolName", ",", "}", ",", "Start", ":", "func", "(", "context", "dependency", ".", "Context", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "var", "apicaller", "base", ".", "APICaller", "\n", "var", "factory", "spool", ".", "MetricFactory", "\n", "err", ":=", "context", ".", "Get", "(", "config", ".", "APICallerName", ",", "&", "apicaller", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "err", "=", "context", ".", "Get", "(", "config", ".", "MetricSpoolName", ",", "&", "factory", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "agent", "agent", ".", "Agent", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "AgentName", ",", "&", "agent", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "agentConfig", ":=", "agent", ".", "CurrentConfig", "(", ")", "\n", "tag", ":=", "agentConfig", ".", "Tag", "(", ")", "\n", "unitTag", ",", "ok", ":=", "tag", ".", "(", "names", ".", "UnitTag", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "tag", ")", "\n", "}", "\n", "paths", ":=", "uniter", ".", "NewWorkerPaths", "(", "agentConfig", ".", "DataDir", "(", ")", ",", "unitTag", ",", "\"", "\"", ")", "\n\n", "client", ":=", "newMetricAdderClient", "(", "apicaller", ")", "\n\n", "s", ",", "err", ":=", "newSender", "(", "client", ",", "factory", ",", "paths", ".", "State", ".", "BaseDir", ",", "unitTag", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "spool", ".", "NewPeriodicWorker", "(", "s", ".", "Do", ",", "period", ",", "jworker", ".", "NewTimer", ",", "s", ".", "stop", ")", ",", "nil", "\n", "}", ",", "}", "\n", "}" ]
// Manifold creates a metric sender manifold.
[ "Manifold", "creates", "a", "metric", "sender", "manifold", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/sender/manifold.go#L39-L78
157,169
juju/juju
cmd/juju/model/mocks/trackbranch_mock.go
NewMockTrackBranchCommandAPI
func NewMockTrackBranchCommandAPI(ctrl *gomock.Controller) *MockTrackBranchCommandAPI { mock := &MockTrackBranchCommandAPI{ctrl: ctrl} mock.recorder = &MockTrackBranchCommandAPIMockRecorder{mock} return mock }
go
func NewMockTrackBranchCommandAPI(ctrl *gomock.Controller) *MockTrackBranchCommandAPI { mock := &MockTrackBranchCommandAPI{ctrl: ctrl} mock.recorder = &MockTrackBranchCommandAPIMockRecorder{mock} return mock }
[ "func", "NewMockTrackBranchCommandAPI", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockTrackBranchCommandAPI", "{", "mock", ":=", "&", "MockTrackBranchCommandAPI", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockTrackBranchCommandAPIMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockTrackBranchCommandAPI creates a new mock instance
[ "NewMockTrackBranchCommandAPI", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/mocks/trackbranch_mock.go#L24-L28
157,170
juju/juju
cmd/juju/model/mocks/trackbranch_mock.go
TrackBranch
func (m *MockTrackBranchCommandAPI) TrackBranch(arg0 string, arg1 []string) error { ret := m.ctrl.Call(m, "TrackBranch", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
go
func (m *MockTrackBranchCommandAPI) TrackBranch(arg0 string, arg1 []string) error { ret := m.ctrl.Call(m, "TrackBranch", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
[ "func", "(", "m", "*", "MockTrackBranchCommandAPI", ")", "TrackBranch", "(", "arg0", "string", ",", "arg1", "[", "]", "string", ")", "error", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "error", ")", "\n", "return", "ret0", "\n", "}" ]
// TrackBranch mocks base method
[ "TrackBranch", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/mocks/trackbranch_mock.go#L48-L52
157,171
juju/juju
cmd/juju/model/mocks/trackbranch_mock.go
TrackBranch
func (mr *MockTrackBranchCommandAPIMockRecorder) TrackBranch(arg0, arg1 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TrackBranch", reflect.TypeOf((*MockTrackBranchCommandAPI)(nil).TrackBranch), arg0, arg1) }
go
func (mr *MockTrackBranchCommandAPIMockRecorder) TrackBranch(arg0, arg1 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TrackBranch", reflect.TypeOf((*MockTrackBranchCommandAPI)(nil).TrackBranch), arg0, arg1) }
[ "func", "(", "mr", "*", "MockTrackBranchCommandAPIMockRecorder", ")", "TrackBranch", "(", "arg0", ",", "arg1", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockTrackBranchCommandAPI", ")", "(", "nil", ")", ".", "TrackBranch", ")", ",", "arg0", ",", "arg1", ")", "\n", "}" ]
// TrackBranch indicates an expected call of TrackBranch
[ "TrackBranch", "indicates", "an", "expected", "call", "of", "TrackBranch" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/mocks/trackbranch_mock.go#L55-L57
157,172
juju/juju
worker/upgradeseries/manifold.go
newWorker
func (config ManifoldConfig) newWorker(a agent.Agent, apiCaller base.APICaller) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } // Ensure that we have a machine tag. agentCfg := a.CurrentConfig() tag, ok := agentCfg.Tag().(names.MachineTag) if !ok { return nil, errors.Errorf("expected a machine tag, got %v", tag) } // Partially apply the NewFacade method and pass it as a factory. // This is so the worker can use the API server in different contexts. // TODO (manadart 2018-08-30): This behaviour is vestigial. // We no longer need a factory and can pass a concrete facade. newFacade := func(t names.Tag) Facade { return config.NewFacade(apiCaller, t) } // Partially apply Upgrader factory function so we only need to request // using the getter for the target OS series. newUpgrader := func(targetSeries string) (Upgrader, error) { return NewUpgrader(targetSeries, service.NewServiceManagerWithDefaults(), config.Logger) } cfg := Config{ Tag: tag, Logger: config.Logger, FacadeFactory: newFacade, Service: &serviceAccess{}, UpgraderFactory: newUpgrader, } w, err := config.NewWorker(cfg) return w, errors.Annotate(err, "starting machine upgrade series worker") }
go
func (config ManifoldConfig) newWorker(a agent.Agent, apiCaller base.APICaller) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } // Ensure that we have a machine tag. agentCfg := a.CurrentConfig() tag, ok := agentCfg.Tag().(names.MachineTag) if !ok { return nil, errors.Errorf("expected a machine tag, got %v", tag) } // Partially apply the NewFacade method and pass it as a factory. // This is so the worker can use the API server in different contexts. // TODO (manadart 2018-08-30): This behaviour is vestigial. // We no longer need a factory and can pass a concrete facade. newFacade := func(t names.Tag) Facade { return config.NewFacade(apiCaller, t) } // Partially apply Upgrader factory function so we only need to request // using the getter for the target OS series. newUpgrader := func(targetSeries string) (Upgrader, error) { return NewUpgrader(targetSeries, service.NewServiceManagerWithDefaults(), config.Logger) } cfg := Config{ Tag: tag, Logger: config.Logger, FacadeFactory: newFacade, Service: &serviceAccess{}, UpgraderFactory: newUpgrader, } w, err := config.NewWorker(cfg) return w, errors.Annotate(err, "starting machine upgrade series worker") }
[ "func", "(", "config", "ManifoldConfig", ")", "newWorker", "(", "a", "agent", ".", "Agent", ",", "apiCaller", "base", ".", "APICaller", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Ensure that we have a machine tag.", "agentCfg", ":=", "a", ".", "CurrentConfig", "(", ")", "\n", "tag", ",", "ok", ":=", "agentCfg", ".", "Tag", "(", ")", ".", "(", "names", ".", "MachineTag", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "tag", ")", "\n", "}", "\n\n", "// Partially apply the NewFacade method and pass it as a factory.", "// This is so the worker can use the API server in different contexts.", "// TODO (manadart 2018-08-30): This behaviour is vestigial.", "// We no longer need a factory and can pass a concrete facade.", "newFacade", ":=", "func", "(", "t", "names", ".", "Tag", ")", "Facade", "{", "return", "config", ".", "NewFacade", "(", "apiCaller", ",", "t", ")", "\n", "}", "\n\n", "// Partially apply Upgrader factory function so we only need to request", "// using the getter for the target OS series.", "newUpgrader", ":=", "func", "(", "targetSeries", "string", ")", "(", "Upgrader", ",", "error", ")", "{", "return", "NewUpgrader", "(", "targetSeries", ",", "service", ".", "NewServiceManagerWithDefaults", "(", ")", ",", "config", ".", "Logger", ")", "\n", "}", "\n\n", "cfg", ":=", "Config", "{", "Tag", ":", "tag", ",", "Logger", ":", "config", ".", "Logger", ",", "FacadeFactory", ":", "newFacade", ",", "Service", ":", "&", "serviceAccess", "{", "}", ",", "UpgraderFactory", ":", "newUpgrader", ",", "}", "\n\n", "w", ",", "err", ":=", "config", ".", "NewWorker", "(", "cfg", ")", "\n", "return", "w", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// newWorker wraps NewWorker for use in a engine.AgentAPIManifold.
[ "newWorker", "wraps", "NewWorker", "for", "use", "in", "a", "engine", ".", "AgentAPIManifold", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/manifold.go#L54-L90
157,173
juju/juju
provider/gce/google/conn_network.go
OpenPorts
func (gce Connection) OpenPorts(target string, rules ...network.IngressRule) error { return errors.Trace(gce.OpenPortsWithNamer(target, RandomSuffixNamer, rules...)) }
go
func (gce Connection) OpenPorts(target string, rules ...network.IngressRule) error { return errors.Trace(gce.OpenPortsWithNamer(target, RandomSuffixNamer, rules...)) }
[ "func", "(", "gce", "Connection", ")", "OpenPorts", "(", "target", "string", ",", "rules", "...", "network", ".", "IngressRule", ")", "error", "{", "return", "errors", ".", "Trace", "(", "gce", ".", "OpenPortsWithNamer", "(", "target", ",", "RandomSuffixNamer", ",", "rules", "...", ")", ")", "\n", "}" ]
// OpenPorts adds or updates GCE firewall rules so that traffic to the // target ports is allowed from the source ranges specified by the // ingress rules. If a rule matching a set of source ranges doesn't // already exist, it will be created - the name will be made unique // using a random suffix.
[ "OpenPorts", "adds", "or", "updates", "GCE", "firewall", "rules", "so", "that", "traffic", "to", "the", "target", "ports", "is", "allowed", "from", "the", "source", "ranges", "specified", "by", "the", "ingress", "rules", ".", "If", "a", "rule", "matching", "a", "set", "of", "source", "ranges", "doesn", "t", "already", "exist", "it", "will", "be", "created", "-", "the", "name", "will", "be", "made", "unique", "using", "a", "random", "suffix", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/conn_network.go#L50-L52
157,174
juju/juju
provider/gce/google/conn_network.go
OpenPortsWithNamer
func (gce Connection) OpenPortsWithNamer(target string, namer FirewallNamer, rules ...network.IngressRule) error { if len(rules) == 0 { return nil } // First gather the current ingress rules. currentRuleSet, err := gce.firewallRules(target) if err != nil { return errors.Trace(err) } // From the input rules, compose the firewall specs we want to add. inputRuleSet := newRuleSetFromRules(rules...) // For each input rule, either create a new firewall or update // an existing one depending on what exists already. // The rules are keyed by a hash of the source CIDRs. var sortedKeys []string for key := range inputRuleSet { sortedKeys = append(sortedKeys, key) } sort.Strings(sortedKeys) allNames := currentRuleSet.allNames() // Get the rules by sorted key for deterministic testing. for _, key := range sortedKeys { inputFirewall := inputRuleSet[key] // First check to see if there's any existing firewall with the same ports as what we want. existingFirewall, ok := currentRuleSet.matchProtocolPorts(inputFirewall.AllowedPorts) if !ok { // If not, look for any existing firewall with the same source CIDRs. existingFirewall, ok = currentRuleSet.matchSourceCIDRs(inputFirewall.SourceCIDRs) } if !ok { // Create a new firewall. name, err := namer(inputFirewall, target, allNames) if err != nil { return errors.Trace(err) } allNames.Add(name) spec := firewallSpec(name, target, inputFirewall.SourceCIDRs, inputFirewall.AllowedPorts) if err := gce.raw.AddFirewall(gce.projectID, spec); err != nil { return errors.Annotatef(err, "opening port(s) %+v", rules) } continue } // An existing firewall exists with either same same ports or the same source // CIDRs as what we have been asked to open. Either way, we just need to update // the existing firewall. // Merge the ports. allowedPorts := existingFirewall.AllowedPorts.union(inputFirewall.AllowedPorts) // Merge the CIDRs cidrs := set.NewStrings(existingFirewall.SourceCIDRs...) combinedCIDRs := cidrs.Union(set.NewStrings(inputFirewall.SourceCIDRs...)).SortedValues() // Copy new firewall details into required firewall spec. spec := firewallSpec(existingFirewall.Name, target, combinedCIDRs, allowedPorts) if err := gce.raw.UpdateFirewall(gce.projectID, existingFirewall.Name, spec); err != nil { return errors.Annotatef(err, "opening port(s) %+v", rules) } } return nil }
go
func (gce Connection) OpenPortsWithNamer(target string, namer FirewallNamer, rules ...network.IngressRule) error { if len(rules) == 0 { return nil } // First gather the current ingress rules. currentRuleSet, err := gce.firewallRules(target) if err != nil { return errors.Trace(err) } // From the input rules, compose the firewall specs we want to add. inputRuleSet := newRuleSetFromRules(rules...) // For each input rule, either create a new firewall or update // an existing one depending on what exists already. // The rules are keyed by a hash of the source CIDRs. var sortedKeys []string for key := range inputRuleSet { sortedKeys = append(sortedKeys, key) } sort.Strings(sortedKeys) allNames := currentRuleSet.allNames() // Get the rules by sorted key for deterministic testing. for _, key := range sortedKeys { inputFirewall := inputRuleSet[key] // First check to see if there's any existing firewall with the same ports as what we want. existingFirewall, ok := currentRuleSet.matchProtocolPorts(inputFirewall.AllowedPorts) if !ok { // If not, look for any existing firewall with the same source CIDRs. existingFirewall, ok = currentRuleSet.matchSourceCIDRs(inputFirewall.SourceCIDRs) } if !ok { // Create a new firewall. name, err := namer(inputFirewall, target, allNames) if err != nil { return errors.Trace(err) } allNames.Add(name) spec := firewallSpec(name, target, inputFirewall.SourceCIDRs, inputFirewall.AllowedPorts) if err := gce.raw.AddFirewall(gce.projectID, spec); err != nil { return errors.Annotatef(err, "opening port(s) %+v", rules) } continue } // An existing firewall exists with either same same ports or the same source // CIDRs as what we have been asked to open. Either way, we just need to update // the existing firewall. // Merge the ports. allowedPorts := existingFirewall.AllowedPorts.union(inputFirewall.AllowedPorts) // Merge the CIDRs cidrs := set.NewStrings(existingFirewall.SourceCIDRs...) combinedCIDRs := cidrs.Union(set.NewStrings(inputFirewall.SourceCIDRs...)).SortedValues() // Copy new firewall details into required firewall spec. spec := firewallSpec(existingFirewall.Name, target, combinedCIDRs, allowedPorts) if err := gce.raw.UpdateFirewall(gce.projectID, existingFirewall.Name, spec); err != nil { return errors.Annotatef(err, "opening port(s) %+v", rules) } } return nil }
[ "func", "(", "gce", "Connection", ")", "OpenPortsWithNamer", "(", "target", "string", ",", "namer", "FirewallNamer", ",", "rules", "...", "network", ".", "IngressRule", ")", "error", "{", "if", "len", "(", "rules", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// First gather the current ingress rules.", "currentRuleSet", ",", "err", ":=", "gce", ".", "firewallRules", "(", "target", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// From the input rules, compose the firewall specs we want to add.", "inputRuleSet", ":=", "newRuleSetFromRules", "(", "rules", "...", ")", "\n\n", "// For each input rule, either create a new firewall or update", "// an existing one depending on what exists already.", "// The rules are keyed by a hash of the source CIDRs.", "var", "sortedKeys", "[", "]", "string", "\n", "for", "key", ":=", "range", "inputRuleSet", "{", "sortedKeys", "=", "append", "(", "sortedKeys", ",", "key", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "sortedKeys", ")", "\n\n", "allNames", ":=", "currentRuleSet", ".", "allNames", "(", ")", "\n\n", "// Get the rules by sorted key for deterministic testing.", "for", "_", ",", "key", ":=", "range", "sortedKeys", "{", "inputFirewall", ":=", "inputRuleSet", "[", "key", "]", "\n\n", "// First check to see if there's any existing firewall with the same ports as what we want.", "existingFirewall", ",", "ok", ":=", "currentRuleSet", ".", "matchProtocolPorts", "(", "inputFirewall", ".", "AllowedPorts", ")", "\n", "if", "!", "ok", "{", "// If not, look for any existing firewall with the same source CIDRs.", "existingFirewall", ",", "ok", "=", "currentRuleSet", ".", "matchSourceCIDRs", "(", "inputFirewall", ".", "SourceCIDRs", ")", "\n", "}", "\n\n", "if", "!", "ok", "{", "// Create a new firewall.", "name", ",", "err", ":=", "namer", "(", "inputFirewall", ",", "target", ",", "allNames", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "allNames", ".", "Add", "(", "name", ")", "\n", "spec", ":=", "firewallSpec", "(", "name", ",", "target", ",", "inputFirewall", ".", "SourceCIDRs", ",", "inputFirewall", ".", "AllowedPorts", ")", "\n", "if", "err", ":=", "gce", ".", "raw", ".", "AddFirewall", "(", "gce", ".", "projectID", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "rules", ")", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "// An existing firewall exists with either same same ports or the same source", "// CIDRs as what we have been asked to open. Either way, we just need to update", "// the existing firewall.", "// Merge the ports.", "allowedPorts", ":=", "existingFirewall", ".", "AllowedPorts", ".", "union", "(", "inputFirewall", ".", "AllowedPorts", ")", "\n\n", "// Merge the CIDRs", "cidrs", ":=", "set", ".", "NewStrings", "(", "existingFirewall", ".", "SourceCIDRs", "...", ")", "\n", "combinedCIDRs", ":=", "cidrs", ".", "Union", "(", "set", ".", "NewStrings", "(", "inputFirewall", ".", "SourceCIDRs", "...", ")", ")", ".", "SortedValues", "(", ")", "\n\n", "// Copy new firewall details into required firewall spec.", "spec", ":=", "firewallSpec", "(", "existingFirewall", ".", "Name", ",", "target", ",", "combinedCIDRs", ",", "allowedPorts", ")", "\n", "if", "err", ":=", "gce", ".", "raw", ".", "UpdateFirewall", "(", "gce", ".", "projectID", ",", "existingFirewall", ".", "Name", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "rules", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// OpenPortsWithNamer adds or creates firewall rules in the same way // as OpenPorts, but uses the FirewallNamer passed in to generate the // firewall name - this is mostly useful for getting predictable // results in tests.
[ "OpenPortsWithNamer", "adds", "or", "creates", "firewall", "rules", "in", "the", "same", "way", "as", "OpenPorts", "but", "uses", "the", "FirewallNamer", "passed", "in", "to", "generate", "the", "firewall", "name", "-", "this", "is", "mostly", "useful", "for", "getting", "predictable", "results", "in", "tests", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/conn_network.go#L62-L129
157,175
juju/juju
provider/gce/google/conn_network.go
RandomSuffixNamer
func RandomSuffixNamer(fw *firewall, prefix string, existingNames set.Strings) (string, error) { // For backwards compatibility, open rules for "0.0.0.0/0" // do not use any suffix in the name. if len(fw.SourceCIDRs) == 0 || len(fw.SourceCIDRs) == 1 && fw.SourceCIDRs[0] == "0.0.0.0/0" { return prefix, nil } data := make([]byte, 4) for i := 0; i < 10; i++ { _, err := rand.Read(data) if err != nil { return "", errors.Trace(err) } name := fmt.Sprintf("%s-%x", prefix, data) if !existingNames.Contains(name) { return name, nil } } return "", errors.New("couldn't pick unique name after 10 attempts") }
go
func RandomSuffixNamer(fw *firewall, prefix string, existingNames set.Strings) (string, error) { // For backwards compatibility, open rules for "0.0.0.0/0" // do not use any suffix in the name. if len(fw.SourceCIDRs) == 0 || len(fw.SourceCIDRs) == 1 && fw.SourceCIDRs[0] == "0.0.0.0/0" { return prefix, nil } data := make([]byte, 4) for i := 0; i < 10; i++ { _, err := rand.Read(data) if err != nil { return "", errors.Trace(err) } name := fmt.Sprintf("%s-%x", prefix, data) if !existingNames.Contains(name) { return name, nil } } return "", errors.New("couldn't pick unique name after 10 attempts") }
[ "func", "RandomSuffixNamer", "(", "fw", "*", "firewall", ",", "prefix", "string", ",", "existingNames", "set", ".", "Strings", ")", "(", "string", ",", "error", ")", "{", "// For backwards compatibility, open rules for \"0.0.0.0/0\"", "// do not use any suffix in the name.", "if", "len", "(", "fw", ".", "SourceCIDRs", ")", "==", "0", "||", "len", "(", "fw", ".", "SourceCIDRs", ")", "==", "1", "&&", "fw", ".", "SourceCIDRs", "[", "0", "]", "==", "\"", "\"", "{", "return", "prefix", ",", "nil", "\n", "}", "\n", "data", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "10", ";", "i", "++", "{", "_", ",", "err", ":=", "rand", ".", "Read", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "name", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "prefix", ",", "data", ")", "\n", "if", "!", "existingNames", ".", "Contains", "(", "name", ")", "{", "return", "name", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// RandomSuffixNamer tries to find a unique name for the firewall by // appending a random suffix.
[ "RandomSuffixNamer", "tries", "to", "find", "a", "unique", "name", "for", "the", "firewall", "by", "appending", "a", "random", "suffix", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/conn_network.go#L133-L151
157,176
juju/juju
provider/gce/google/conn_network.go
ClosePorts
func (gce Connection) ClosePorts(target string, rules ...network.IngressRule) error { // First gather the current ingress rules. currentRuleSet, err := gce.firewallRules(target) if err != nil { return errors.Trace(err) } // From the input rules, compose the firewall specs we want to add. inputRuleSet := newRuleSetFromRules(rules...) // For each input firewall, find an existing firewall including it // and update or remove it. for _, inputFirewall := range inputRuleSet { existingFirewall, allPortsMatch := currentRuleSet.matchProtocolPorts(inputFirewall.AllowedPorts) if allPortsMatch { // All the ports match so it may be that just a CIDR needs to be removed. cidrs := set.NewStrings(existingFirewall.SourceCIDRs...) remainingCidrs := cidrs.Difference(set.NewStrings(inputFirewall.SourceCIDRs...)).SortedValues() // If all CIDRs are also to be removed, we can delete the firewall. if len(remainingCidrs) == 0 { // Delete a firewall. // TODO(ericsnow) Handle case where firewall does not exist. if err := gce.raw.RemoveFirewall(gce.projectID, existingFirewall.Name); err != nil { return errors.Annotatef(err, "closing port(s) %+v", rules) } continue } // Update the existing firewall with the remaining CIDRs. spec := firewallSpec(existingFirewall.Name, target, remainingCidrs, existingFirewall.AllowedPorts) if err := gce.raw.UpdateFirewall(gce.projectID, existingFirewall.Name, spec); err != nil { return errors.Annotatef(err, "closing port(s) %+v", rules) } continue } existingFirewall, sourceCIDRMatch := currentRuleSet.matchSourceCIDRs(inputFirewall.SourceCIDRs) if !sourceCIDRMatch { // We already know ports don't match, so if CIDRs don't match either, we either // have a partial match or no match. // No matches are a no-op. Partial matches might require splitting firewall rules // which is not supported at the moment. We'll return an error as it's better to // be overly cautious than accidentally leave ports open. The issue shouldn't occur // in practice unless people have manually played with the firewall rules. return errors.NotSupportedf("closing port(s) %+v over non-matching rules", rules) } // Delete the ports to close. remainingPorts := existingFirewall.AllowedPorts.remove(inputFirewall.AllowedPorts) // Copy new firewall details into required firewall spec. spec := firewallSpec(existingFirewall.Name, target, existingFirewall.SourceCIDRs, remainingPorts) if err := gce.raw.UpdateFirewall(gce.projectID, existingFirewall.Name, spec); err != nil { return errors.Annotatef(err, "closing port(s) %+v", rules) } } return nil }
go
func (gce Connection) ClosePorts(target string, rules ...network.IngressRule) error { // First gather the current ingress rules. currentRuleSet, err := gce.firewallRules(target) if err != nil { return errors.Trace(err) } // From the input rules, compose the firewall specs we want to add. inputRuleSet := newRuleSetFromRules(rules...) // For each input firewall, find an existing firewall including it // and update or remove it. for _, inputFirewall := range inputRuleSet { existingFirewall, allPortsMatch := currentRuleSet.matchProtocolPorts(inputFirewall.AllowedPorts) if allPortsMatch { // All the ports match so it may be that just a CIDR needs to be removed. cidrs := set.NewStrings(existingFirewall.SourceCIDRs...) remainingCidrs := cidrs.Difference(set.NewStrings(inputFirewall.SourceCIDRs...)).SortedValues() // If all CIDRs are also to be removed, we can delete the firewall. if len(remainingCidrs) == 0 { // Delete a firewall. // TODO(ericsnow) Handle case where firewall does not exist. if err := gce.raw.RemoveFirewall(gce.projectID, existingFirewall.Name); err != nil { return errors.Annotatef(err, "closing port(s) %+v", rules) } continue } // Update the existing firewall with the remaining CIDRs. spec := firewallSpec(existingFirewall.Name, target, remainingCidrs, existingFirewall.AllowedPorts) if err := gce.raw.UpdateFirewall(gce.projectID, existingFirewall.Name, spec); err != nil { return errors.Annotatef(err, "closing port(s) %+v", rules) } continue } existingFirewall, sourceCIDRMatch := currentRuleSet.matchSourceCIDRs(inputFirewall.SourceCIDRs) if !sourceCIDRMatch { // We already know ports don't match, so if CIDRs don't match either, we either // have a partial match or no match. // No matches are a no-op. Partial matches might require splitting firewall rules // which is not supported at the moment. We'll return an error as it's better to // be overly cautious than accidentally leave ports open. The issue shouldn't occur // in practice unless people have manually played with the firewall rules. return errors.NotSupportedf("closing port(s) %+v over non-matching rules", rules) } // Delete the ports to close. remainingPorts := existingFirewall.AllowedPorts.remove(inputFirewall.AllowedPorts) // Copy new firewall details into required firewall spec. spec := firewallSpec(existingFirewall.Name, target, existingFirewall.SourceCIDRs, remainingPorts) if err := gce.raw.UpdateFirewall(gce.projectID, existingFirewall.Name, spec); err != nil { return errors.Annotatef(err, "closing port(s) %+v", rules) } } return nil }
[ "func", "(", "gce", "Connection", ")", "ClosePorts", "(", "target", "string", ",", "rules", "...", "network", ".", "IngressRule", ")", "error", "{", "// First gather the current ingress rules.", "currentRuleSet", ",", "err", ":=", "gce", ".", "firewallRules", "(", "target", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// From the input rules, compose the firewall specs we want to add.", "inputRuleSet", ":=", "newRuleSetFromRules", "(", "rules", "...", ")", "\n\n", "// For each input firewall, find an existing firewall including it", "// and update or remove it.", "for", "_", ",", "inputFirewall", ":=", "range", "inputRuleSet", "{", "existingFirewall", ",", "allPortsMatch", ":=", "currentRuleSet", ".", "matchProtocolPorts", "(", "inputFirewall", ".", "AllowedPorts", ")", "\n", "if", "allPortsMatch", "{", "// All the ports match so it may be that just a CIDR needs to be removed.", "cidrs", ":=", "set", ".", "NewStrings", "(", "existingFirewall", ".", "SourceCIDRs", "...", ")", "\n", "remainingCidrs", ":=", "cidrs", ".", "Difference", "(", "set", ".", "NewStrings", "(", "inputFirewall", ".", "SourceCIDRs", "...", ")", ")", ".", "SortedValues", "(", ")", "\n\n", "// If all CIDRs are also to be removed, we can delete the firewall.", "if", "len", "(", "remainingCidrs", ")", "==", "0", "{", "// Delete a firewall.", "// TODO(ericsnow) Handle case where firewall does not exist.", "if", "err", ":=", "gce", ".", "raw", ".", "RemoveFirewall", "(", "gce", ".", "projectID", ",", "existingFirewall", ".", "Name", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "rules", ")", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "// Update the existing firewall with the remaining CIDRs.", "spec", ":=", "firewallSpec", "(", "existingFirewall", ".", "Name", ",", "target", ",", "remainingCidrs", ",", "existingFirewall", ".", "AllowedPorts", ")", "\n", "if", "err", ":=", "gce", ".", "raw", ".", "UpdateFirewall", "(", "gce", ".", "projectID", ",", "existingFirewall", ".", "Name", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "rules", ")", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "existingFirewall", ",", "sourceCIDRMatch", ":=", "currentRuleSet", ".", "matchSourceCIDRs", "(", "inputFirewall", ".", "SourceCIDRs", ")", "\n", "if", "!", "sourceCIDRMatch", "{", "// We already know ports don't match, so if CIDRs don't match either, we either", "// have a partial match or no match.", "// No matches are a no-op. Partial matches might require splitting firewall rules", "// which is not supported at the moment. We'll return an error as it's better to", "// be overly cautious than accidentally leave ports open. The issue shouldn't occur", "// in practice unless people have manually played with the firewall rules.", "return", "errors", ".", "NotSupportedf", "(", "\"", "\"", ",", "rules", ")", "\n", "}", "\n\n", "// Delete the ports to close.", "remainingPorts", ":=", "existingFirewall", ".", "AllowedPorts", ".", "remove", "(", "inputFirewall", ".", "AllowedPorts", ")", "\n\n", "// Copy new firewall details into required firewall spec.", "spec", ":=", "firewallSpec", "(", "existingFirewall", ".", "Name", ",", "target", ",", "existingFirewall", ".", "SourceCIDRs", ",", "remainingPorts", ")", "\n", "if", "err", ":=", "gce", ".", "raw", ".", "UpdateFirewall", "(", "gce", ".", "projectID", ",", "existingFirewall", ".", "Name", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "rules", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ClosePorts sends a request to the GCE API to close the provided port // ranges on the named firewall. If the firewall does not exist nothing // happens. If the firewall is left with no ports then it is removed. // Otherwise it will be left with just the open ports it has that do not // match the provided port ranges. The call blocks until the ports are // closed or the request fails.
[ "ClosePorts", "sends", "a", "request", "to", "the", "GCE", "API", "to", "close", "the", "provided", "port", "ranges", "on", "the", "named", "firewall", ".", "If", "the", "firewall", "does", "not", "exist", "nothing", "happens", ".", "If", "the", "firewall", "is", "left", "with", "no", "ports", "then", "it", "is", "removed", ".", "Otherwise", "it", "will", "be", "left", "with", "just", "the", "open", "ports", "it", "has", "that", "do", "not", "match", "the", "provided", "port", "ranges", ".", "The", "call", "blocks", "until", "the", "ports", "are", "closed", "or", "the", "request", "fails", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/conn_network.go#L159-L217
157,177
juju/juju
provider/gce/google/conn_network.go
Subnetworks
func (gce Connection) Subnetworks(region string) ([]*compute.Subnetwork, error) { results, err := gce.raw.ListSubnetworks(gce.projectID, region) if err != nil { return nil, errors.Trace(err) } return results, nil }
go
func (gce Connection) Subnetworks(region string) ([]*compute.Subnetwork, error) { results, err := gce.raw.ListSubnetworks(gce.projectID, region) if err != nil { return nil, errors.Trace(err) } return results, nil }
[ "func", "(", "gce", "Connection", ")", "Subnetworks", "(", "region", "string", ")", "(", "[", "]", "*", "compute", ".", "Subnetwork", ",", "error", ")", "{", "results", ",", "err", ":=", "gce", ".", "raw", ".", "ListSubnetworks", "(", "gce", ".", "projectID", ",", "region", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// Subnetworks returns the subnets available in this region.
[ "Subnetworks", "returns", "the", "subnets", "available", "in", "this", "region", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/conn_network.go#L220-L226
157,178
juju/juju
provider/gce/google/conn_network.go
Networks
func (gce Connection) Networks() ([]*compute.Network, error) { results, err := gce.raw.ListNetworks(gce.projectID) if err != nil { return nil, errors.Trace(err) } return results, nil }
go
func (gce Connection) Networks() ([]*compute.Network, error) { results, err := gce.raw.ListNetworks(gce.projectID) if err != nil { return nil, errors.Trace(err) } return results, nil }
[ "func", "(", "gce", "Connection", ")", "Networks", "(", ")", "(", "[", "]", "*", "compute", ".", "Network", ",", "error", ")", "{", "results", ",", "err", ":=", "gce", ".", "raw", ".", "ListNetworks", "(", "gce", ".", "projectID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// Networks returns the networks available.
[ "Networks", "returns", "the", "networks", "available", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/conn_network.go#L229-L235
157,179
juju/juju
worker/fanconfigurer/fanconfigurer.go
processNewConfig
func (fc *FanConfigurer) processNewConfig() error { logger.Debugf("Processing new fan config") fc.mu.Lock() defer fc.mu.Unlock() fanConfig, err := fc.config.Facade.FanConfig() if err != nil { return err } if len(fanConfig) == 0 { logger.Debugf("Fan not enabled") // TODO(wpk) 2017-08-05 We have to clean this up! return nil } for i, fan := range fanConfig { logger.Debugf("Adding config for %d: %s %s", i, fan.Underlay, fan.Overlay) line := fmt.Sprintf("fanatic enable-fan -u %s -o %s", fan.Underlay, fan.Overlay) result, err := scriptrunner.RunCommand(line, os.Environ(), fc.clock, 5000*time.Millisecond) logger.Debugf("Launched %s - result %v %v %d", line, string(result.Stdout), string(result.Stderr), result.Code) if err != nil { return err } } // TODO(wpk) 2017-09-28 Although officially not needed we do fanctl up -a just to be sure - // fanatic sometimes fails to bring up interface because of some weird interactions with iptables. result, err := scriptrunner.RunCommand("fanctl up -a", os.Environ(), fc.clock, 5000*time.Millisecond) logger.Debugf("Launched fanctl up -a - result %v %v %d", string(result.Stdout), string(result.Stderr), result.Code) return err }
go
func (fc *FanConfigurer) processNewConfig() error { logger.Debugf("Processing new fan config") fc.mu.Lock() defer fc.mu.Unlock() fanConfig, err := fc.config.Facade.FanConfig() if err != nil { return err } if len(fanConfig) == 0 { logger.Debugf("Fan not enabled") // TODO(wpk) 2017-08-05 We have to clean this up! return nil } for i, fan := range fanConfig { logger.Debugf("Adding config for %d: %s %s", i, fan.Underlay, fan.Overlay) line := fmt.Sprintf("fanatic enable-fan -u %s -o %s", fan.Underlay, fan.Overlay) result, err := scriptrunner.RunCommand(line, os.Environ(), fc.clock, 5000*time.Millisecond) logger.Debugf("Launched %s - result %v %v %d", line, string(result.Stdout), string(result.Stderr), result.Code) if err != nil { return err } } // TODO(wpk) 2017-09-28 Although officially not needed we do fanctl up -a just to be sure - // fanatic sometimes fails to bring up interface because of some weird interactions with iptables. result, err := scriptrunner.RunCommand("fanctl up -a", os.Environ(), fc.clock, 5000*time.Millisecond) logger.Debugf("Launched fanctl up -a - result %v %v %d", string(result.Stdout), string(result.Stderr), result.Code) return err }
[ "func", "(", "fc", "*", "FanConfigurer", ")", "processNewConfig", "(", ")", "error", "{", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "fc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "fc", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "fanConfig", ",", "err", ":=", "fc", ".", "config", ".", "Facade", ".", "FanConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "fanConfig", ")", "==", "0", "{", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "// TODO(wpk) 2017-08-05 We have to clean this up!", "return", "nil", "\n", "}", "\n\n", "for", "i", ",", "fan", ":=", "range", "fanConfig", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "i", ",", "fan", ".", "Underlay", ",", "fan", ".", "Overlay", ")", "\n", "line", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "fan", ".", "Underlay", ",", "fan", ".", "Overlay", ")", "\n", "result", ",", "err", ":=", "scriptrunner", ".", "RunCommand", "(", "line", ",", "os", ".", "Environ", "(", ")", ",", "fc", ".", "clock", ",", "5000", "*", "time", ".", "Millisecond", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "line", ",", "string", "(", "result", ".", "Stdout", ")", ",", "string", "(", "result", ".", "Stderr", ")", ",", "result", ".", "Code", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "// TODO(wpk) 2017-09-28 Although officially not needed we do fanctl up -a just to be sure -", "// fanatic sometimes fails to bring up interface because of some weird interactions with iptables.", "result", ",", "err", ":=", "scriptrunner", ".", "RunCommand", "(", "\"", "\"", ",", "os", ".", "Environ", "(", ")", ",", "fc", ".", "clock", ",", "5000", "*", "time", ".", "Millisecond", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "string", "(", "result", ".", "Stdout", ")", ",", "string", "(", "result", ".", "Stderr", ")", ",", "result", ".", "Code", ")", "\n\n", "return", "err", "\n", "}" ]
// processNewConfig acts on a new fan config.
[ "processNewConfig", "acts", "on", "a", "new", "fan", "config", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/fanconfigurer/fanconfigurer.go#L42-L72
157,180
juju/juju
api/common/watch.go
Watch
func Watch(facade base.FacadeCaller, method string, tag names.Tag) (watcher.NotifyWatcher, error) { var results params.NotifyWatchResults args := params.Entities{ Entities: []params.Entity{{Tag: tag.String()}}, } err := facade.FacadeCall(method, 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(facade.RawAPICaller(), result), nil }
go
func Watch(facade base.FacadeCaller, method string, tag names.Tag) (watcher.NotifyWatcher, error) { var results params.NotifyWatchResults args := params.Entities{ Entities: []params.Entity{{Tag: tag.String()}}, } err := facade.FacadeCall(method, 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(facade.RawAPICaller(), result), nil }
[ "func", "Watch", "(", "facade", "base", ".", "FacadeCaller", ",", "method", "string", ",", "tag", "names", ".", "Tag", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "var", "results", "params", ".", "NotifyWatchResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "Tag", ":", "tag", ".", "String", "(", ")", "}", "}", ",", "}", "\n", "err", ":=", "facade", ".", "FacadeCall", "(", "method", ",", "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", "(", "facade", ".", "RawAPICaller", "(", ")", ",", "result", ")", ",", "nil", "\n", "}" ]
// Watch starts a NotifyWatcher for the entity with the specified tag.
[ "Watch", "starts", "a", "NotifyWatcher", "for", "the", "entity", "with", "the", "specified", "tag", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/common/watch.go#L18-L35
157,181
juju/juju
environs/config/authkeys.go
ConcatAuthKeys
func ConcatAuthKeys(a, b string) string { if a == "" { return b } if b == "" { return a } if a[len(a)-1] != '\n' { return a + "\n" + b } return a + b }
go
func ConcatAuthKeys(a, b string) string { if a == "" { return b } if b == "" { return a } if a[len(a)-1] != '\n' { return a + "\n" + b } return a + b }
[ "func", "ConcatAuthKeys", "(", "a", ",", "b", "string", ")", "string", "{", "if", "a", "==", "\"", "\"", "{", "return", "b", "\n", "}", "\n", "if", "b", "==", "\"", "\"", "{", "return", "a", "\n", "}", "\n", "if", "a", "[", "len", "(", "a", ")", "-", "1", "]", "!=", "'\\n'", "{", "return", "a", "+", "\"", "\\n", "\"", "+", "b", "\n", "}", "\n", "return", "a", "+", "b", "\n", "}" ]
// ConcatAuthKeys concatenates the two sets of authorised keys, interposing // a newline if necessary, because authorised keys are newline-separated.
[ "ConcatAuthKeys", "concatenates", "the", "two", "sets", "of", "authorised", "keys", "interposing", "a", "newline", "if", "necessary", "because", "authorised", "keys", "are", "newline", "-", "separated", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/config/authkeys.go#L13-L24
157,182
juju/juju
logfwd/record.go
Validate
func (rec Record) Validate() error { if err := rec.Origin.Validate(); err != nil { return errors.Annotate(err, "invalid Origin") } if rec.Timestamp.IsZero() { return errors.NewNotValid(nil, "empty Timestamp") } // rec.Level may be anything, so we don't check it. if err := rec.Location.Validate(); err != nil { return errors.Annotate(err, "invalid Location") } // rec.Message may be anything, so we don't check it. return nil }
go
func (rec Record) Validate() error { if err := rec.Origin.Validate(); err != nil { return errors.Annotate(err, "invalid Origin") } if rec.Timestamp.IsZero() { return errors.NewNotValid(nil, "empty Timestamp") } // rec.Level may be anything, so we don't check it. if err := rec.Location.Validate(); err != nil { return errors.Annotate(err, "invalid Location") } // rec.Message may be anything, so we don't check it. return nil }
[ "func", "(", "rec", "Record", ")", "Validate", "(", ")", "error", "{", "if", "err", ":=", "rec", ".", "Origin", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "rec", ".", "Timestamp", ".", "IsZero", "(", ")", "{", "return", "errors", ".", "NewNotValid", "(", "nil", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// rec.Level may be anything, so we don't check it.", "if", "err", ":=", "rec", ".", "Location", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// rec.Message may be anything, so we don't check it.", "return", "nil", "\n", "}" ]
// Validate ensures that the record is correct.
[ "Validate", "ensures", "that", "the", "record", "is", "correct", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/logfwd/record.go#L39-L57
157,183
juju/juju
logfwd/record.go
String
func (loc SourceLocation) String() string { if loc.Line < 0 { return loc.Filename } if loc.Line == 0 && loc.Filename == "" { return "" } return fmt.Sprintf("%s:%d", loc.Filename, loc.Line) }
go
func (loc SourceLocation) String() string { if loc.Line < 0 { return loc.Filename } if loc.Line == 0 && loc.Filename == "" { return "" } return fmt.Sprintf("%s:%d", loc.Filename, loc.Line) }
[ "func", "(", "loc", "SourceLocation", ")", "String", "(", ")", "string", "{", "if", "loc", ".", "Line", "<", "0", "{", "return", "loc", ".", "Filename", "\n", "}", "\n", "if", "loc", ".", "Line", "==", "0", "&&", "loc", ".", "Filename", "==", "\"", "\"", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "loc", ".", "Filename", ",", "loc", ".", "Line", ")", "\n", "}" ]
// String returns a string representation of the location.
[ "String", "returns", "a", "string", "representation", "of", "the", "location", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/logfwd/record.go#L120-L128
157,184
juju/juju
logfwd/record.go
Validate
func (loc SourceLocation) Validate() error { if loc == zero { return nil } // Module may be anything, so there's nothing to check there. // Filename may be set with no line number set, but not the other // way around. if loc.Line >= 0 && loc.Filename == "" { return errors.NewNotValid(nil, "Line set but Filename empty") } return nil }
go
func (loc SourceLocation) Validate() error { if loc == zero { return nil } // Module may be anything, so there's nothing to check there. // Filename may be set with no line number set, but not the other // way around. if loc.Line >= 0 && loc.Filename == "" { return errors.NewNotValid(nil, "Line set but Filename empty") } return nil }
[ "func", "(", "loc", "SourceLocation", ")", "Validate", "(", ")", "error", "{", "if", "loc", "==", "zero", "{", "return", "nil", "\n", "}", "\n\n", "// Module may be anything, so there's nothing to check there.", "// Filename may be set with no line number set, but not the other", "// way around.", "if", "loc", ".", "Line", ">=", "0", "&&", "loc", ".", "Filename", "==", "\"", "\"", "{", "return", "errors", ".", "NewNotValid", "(", "nil", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate ensures that the location is correct.
[ "Validate", "ensures", "that", "the", "location", "is", "correct", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/logfwd/record.go#L133-L147
157,185
juju/juju
api/upgradeseries/upgradeseries.go
NewClient
func NewClient(caller base.APICaller, authTag names.Tag) *Client { facadeCaller := base.NewFacadeCaller( caller, upgradeSeriesFacade, ) return &Client{ facade: facadeCaller, authTag: authTag, UpgradeSeriesAPI: common.NewUpgradeSeriesAPI(facadeCaller, authTag), LeadershipPinningAPI: common.NewLeadershipPinningAPIFromFacade(facadeCaller), } }
go
func NewClient(caller base.APICaller, authTag names.Tag) *Client { facadeCaller := base.NewFacadeCaller( caller, upgradeSeriesFacade, ) return &Client{ facade: facadeCaller, authTag: authTag, UpgradeSeriesAPI: common.NewUpgradeSeriesAPI(facadeCaller, authTag), LeadershipPinningAPI: common.NewLeadershipPinningAPIFromFacade(facadeCaller), } }
[ "func", "NewClient", "(", "caller", "base", ".", "APICaller", ",", "authTag", "names", ".", "Tag", ")", "*", "Client", "{", "facadeCaller", ":=", "base", ".", "NewFacadeCaller", "(", "caller", ",", "upgradeSeriesFacade", ",", ")", "\n", "return", "&", "Client", "{", "facade", ":", "facadeCaller", ",", "authTag", ":", "authTag", ",", "UpgradeSeriesAPI", ":", "common", ".", "NewUpgradeSeriesAPI", "(", "facadeCaller", ",", "authTag", ")", ",", "LeadershipPinningAPI", ":", "common", ".", "NewLeadershipPinningAPIFromFacade", "(", "facadeCaller", ")", ",", "}", "\n", "}" ]
// NewClient Constructs an API caller.
[ "NewClient", "Constructs", "an", "API", "caller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/upgradeseries/upgradeseries.go#L29-L40
157,186
juju/juju
api/upgradeseries/upgradeseries.go
MachineStatus
func (s *Client) MachineStatus() (model.UpgradeSeriesStatus, error) { var results params.UpgradeSeriesStatusResults args := params.Entities{ Entities: []params.Entity{{Tag: s.authTag.String()}}, } err := s.facade.FacadeCall("MachineStatus", args, &results) if err != nil { return "", errors.Trace(err) } if len(results.Results) != 1 { return "", errors.Errorf("expected 1 result, got %d", len(results.Results)) } r := results.Results[0] if r.Error == nil { return r.Status, nil } if params.IsCodeNotFound(r.Error) { return "", errors.NewNotFound(r.Error, "") } return "", errors.Trace(r.Error) }
go
func (s *Client) MachineStatus() (model.UpgradeSeriesStatus, error) { var results params.UpgradeSeriesStatusResults args := params.Entities{ Entities: []params.Entity{{Tag: s.authTag.String()}}, } err := s.facade.FacadeCall("MachineStatus", args, &results) if err != nil { return "", errors.Trace(err) } if len(results.Results) != 1 { return "", errors.Errorf("expected 1 result, got %d", len(results.Results)) } r := results.Results[0] if r.Error == nil { return r.Status, nil } if params.IsCodeNotFound(r.Error) { return "", errors.NewNotFound(r.Error, "") } return "", errors.Trace(r.Error) }
[ "func", "(", "s", "*", "Client", ")", "MachineStatus", "(", ")", "(", "model", ".", "UpgradeSeriesStatus", ",", "error", ")", "{", "var", "results", "params", ".", "UpgradeSeriesStatusResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "Tag", ":", "s", ".", "authTag", ".", "String", "(", ")", "}", "}", ",", "}", "\n\n", "err", ":=", "s", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n\n", "r", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "r", ".", "Error", "==", "nil", "{", "return", "r", ".", "Status", ",", "nil", "\n", "}", "\n\n", "if", "params", ".", "IsCodeNotFound", "(", "r", ".", "Error", ")", "{", "return", "\"", "\"", ",", "errors", ".", "NewNotFound", "(", "r", ".", "Error", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "r", ".", "Error", ")", "\n", "}" ]
// Machine status retrieves the machine status from remote state.
[ "Machine", "status", "retrieves", "the", "machine", "status", "from", "remote", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/upgradeseries/upgradeseries.go#L43-L66
157,187
juju/juju
api/upgradeseries/upgradeseries.go
SetMachineStatus
func (s *Client) SetMachineStatus(status model.UpgradeSeriesStatus, reason string) error { var results params.ErrorResults args := params.UpgradeSeriesStatusParams{ Params: []params.UpgradeSeriesStatusParam{{ Entity: params.Entity{Tag: s.authTag.String()}, Status: status, Message: reason, }}, } err := s.facade.FacadeCall("SetMachineStatus", 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 (s *Client) SetMachineStatus(status model.UpgradeSeriesStatus, reason string) error { var results params.ErrorResults args := params.UpgradeSeriesStatusParams{ Params: []params.UpgradeSeriesStatusParam{{ Entity: params.Entity{Tag: s.authTag.String()}, Status: status, Message: reason, }}, } err := s.facade.FacadeCall("SetMachineStatus", 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", "(", "s", "*", "Client", ")", "SetMachineStatus", "(", "status", "model", ".", "UpgradeSeriesStatus", ",", "reason", "string", ")", "error", "{", "var", "results", "params", ".", "ErrorResults", "\n", "args", ":=", "params", ".", "UpgradeSeriesStatusParams", "{", "Params", ":", "[", "]", "params", ".", "UpgradeSeriesStatusParam", "{", "{", "Entity", ":", "params", ".", "Entity", "{", "Tag", ":", "s", ".", "authTag", ".", "String", "(", ")", "}", ",", "Status", ":", "status", ",", "Message", ":", "reason", ",", "}", "}", ",", "}", "\n\n", "err", ":=", "s", ".", "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\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "result", ".", "Error", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetMachineStatus sets the machine status in remote state.
[ "SetMachineStatus", "sets", "the", "machine", "status", "in", "remote", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/upgradeseries/upgradeseries.go#L142-L165
157,188
juju/juju
api/upgradeseries/upgradeseries.go
StartUnitCompletion
func (s *Client) StartUnitCompletion(reason string) error { var results params.ErrorResults args := params.UpgradeSeriesStartUnitCompletionParam{ Entities: []params.Entity{{Tag: s.authTag.String()}}, Message: reason, } err := s.facade.FacadeCall("StartUnitCompletion", 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 (s *Client) StartUnitCompletion(reason string) error { var results params.ErrorResults args := params.UpgradeSeriesStartUnitCompletionParam{ Entities: []params.Entity{{Tag: s.authTag.String()}}, Message: reason, } err := s.facade.FacadeCall("StartUnitCompletion", 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", "(", "s", "*", "Client", ")", "StartUnitCompletion", "(", "reason", "string", ")", "error", "{", "var", "results", "params", ".", "ErrorResults", "\n", "args", ":=", "params", ".", "UpgradeSeriesStartUnitCompletionParam", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "Tag", ":", "s", ".", "authTag", ".", "String", "(", ")", "}", "}", ",", "Message", ":", "reason", ",", "}", "\n\n", "err", ":=", "s", ".", "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\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "result", ".", "Error", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// StartUnitCompletion starts the complete phase for all subordinate units.
[ "StartUnitCompletion", "starts", "the", "complete", "phase", "for", "all", "subordinate", "units", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/upgradeseries/upgradeseries.go#L168-L188
157,189
juju/juju
api/upgradeseries/upgradeseries.go
FinishUpgradeSeries
func (s *Client) FinishUpgradeSeries(hostSeries string) error { var results params.ErrorResults args := params.UpdateSeriesArgs{Args: []params.UpdateSeriesArg{{ Entity: params.Entity{Tag: s.authTag.String()}, Series: hostSeries, }}} err := s.facade.FacadeCall("FinishUpgradeSeries", 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 (s *Client) FinishUpgradeSeries(hostSeries string) error { var results params.ErrorResults args := params.UpdateSeriesArgs{Args: []params.UpdateSeriesArg{{ Entity: params.Entity{Tag: s.authTag.String()}, Series: hostSeries, }}} err := s.facade.FacadeCall("FinishUpgradeSeries", 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", "(", "s", "*", "Client", ")", "FinishUpgradeSeries", "(", "hostSeries", "string", ")", "error", "{", "var", "results", "params", ".", "ErrorResults", "\n", "args", ":=", "params", ".", "UpdateSeriesArgs", "{", "Args", ":", "[", "]", "params", ".", "UpdateSeriesArg", "{", "{", "Entity", ":", "params", ".", "Entity", "{", "Tag", ":", "s", ".", "authTag", ".", "String", "(", ")", "}", ",", "Series", ":", "hostSeries", ",", "}", "}", "}", "\n\n", "err", ":=", "s", ".", "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\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "result", ".", "Error", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FinishUpgradeSeries notifies the controller that the upgrade process is // completely finished, passing the current host OS series. // We use the name "Finish" to distinguish this method from the various // "Complete" phases.
[ "FinishUpgradeSeries", "notifies", "the", "controller", "that", "the", "upgrade", "process", "is", "completely", "finished", "passing", "the", "current", "host", "OS", "series", ".", "We", "use", "the", "name", "Finish", "to", "distinguish", "this", "method", "from", "the", "various", "Complete", "phases", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/upgradeseries/upgradeseries.go#L194-L214
157,190
juju/juju
api/singular/api.go
NewAPI
func NewAPI( apiCaller base.APICaller, claimant names.MachineTag, entity names.Tag, ) (*API, error) { if !names.IsValidMachine(claimant.Id()) { return nil, errors.NotValidf("claimant tag") } switch entity.(type) { case names.ModelTag: case names.ControllerTag: case nil: return nil, errors.New("nil entity supplied") default: return nil, errors.Errorf( "invalid entity kind %q for singular API", entity.Kind(), ) } facadeCaller := base.NewFacadeCaller(apiCaller, "Singular") return &API{ facadeCaller: facadeCaller, claimant: claimant, entity: entity, }, nil }
go
func NewAPI( apiCaller base.APICaller, claimant names.MachineTag, entity names.Tag, ) (*API, error) { if !names.IsValidMachine(claimant.Id()) { return nil, errors.NotValidf("claimant tag") } switch entity.(type) { case names.ModelTag: case names.ControllerTag: case nil: return nil, errors.New("nil entity supplied") default: return nil, errors.Errorf( "invalid entity kind %q for singular API", entity.Kind(), ) } facadeCaller := base.NewFacadeCaller(apiCaller, "Singular") return &API{ facadeCaller: facadeCaller, claimant: claimant, entity: entity, }, nil }
[ "func", "NewAPI", "(", "apiCaller", "base", ".", "APICaller", ",", "claimant", "names", ".", "MachineTag", ",", "entity", "names", ".", "Tag", ",", ")", "(", "*", "API", ",", "error", ")", "{", "if", "!", "names", ".", "IsValidMachine", "(", "claimant", ".", "Id", "(", ")", ")", "{", "return", "nil", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "switch", "entity", ".", "(", "type", ")", "{", "case", "names", ".", "ModelTag", ":", "case", "names", ".", "ControllerTag", ":", "case", "nil", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "entity", ".", "Kind", "(", ")", ",", ")", "\n", "}", "\n", "facadeCaller", ":=", "base", ".", "NewFacadeCaller", "(", "apiCaller", ",", "\"", "\"", ")", "\n", "return", "&", "API", "{", "facadeCaller", ":", "facadeCaller", ",", "claimant", ":", "claimant", ",", "entity", ":", "entity", ",", "}", ",", "nil", "\n", "}" ]
// NewAPI returns a new API client for the Singular facade. It exposes methods // for claiming and observing administration responsibility for the entity with // the supplied tag, on behalf of the authenticated agent.
[ "NewAPI", "returns", "a", "new", "API", "client", "for", "the", "Singular", "facade", ".", "It", "exposes", "methods", "for", "claiming", "and", "observing", "administration", "responsibility", "for", "the", "entity", "with", "the", "supplied", "tag", "on", "behalf", "of", "the", "authenticated", "agent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/singular/api.go#L20-L44
157,191
juju/juju
api/singular/api.go
Claim
func (api *API) Claim(duration time.Duration) error { args := params.SingularClaims{ Claims: []params.SingularClaim{{ EntityTag: api.entity.String(), ClaimantTag: api.claimant.String(), Duration: duration, }}, } var results params.ErrorResults err := api.facadeCaller.FacadeCall("Claim", args, &results) if err != nil { return errors.Trace(err) } err = results.OneError() if err != nil { if params.IsCodeLeaseClaimDenied(err) { return lease.ErrClaimDenied } return errors.Trace(err) } return nil }
go
func (api *API) Claim(duration time.Duration) error { args := params.SingularClaims{ Claims: []params.SingularClaim{{ EntityTag: api.entity.String(), ClaimantTag: api.claimant.String(), Duration: duration, }}, } var results params.ErrorResults err := api.facadeCaller.FacadeCall("Claim", args, &results) if err != nil { return errors.Trace(err) } err = results.OneError() if err != nil { if params.IsCodeLeaseClaimDenied(err) { return lease.ErrClaimDenied } return errors.Trace(err) } return nil }
[ "func", "(", "api", "*", "API", ")", "Claim", "(", "duration", "time", ".", "Duration", ")", "error", "{", "args", ":=", "params", ".", "SingularClaims", "{", "Claims", ":", "[", "]", "params", ".", "SingularClaim", "{", "{", "EntityTag", ":", "api", ".", "entity", ".", "String", "(", ")", ",", "ClaimantTag", ":", "api", ".", "claimant", ".", "String", "(", ")", ",", "Duration", ":", "duration", ",", "}", "}", ",", "}", "\n", "var", "results", "params", ".", "ErrorResults", "\n", "err", ":=", "api", ".", "facadeCaller", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "err", "=", "results", ".", "OneError", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "params", ".", "IsCodeLeaseClaimDenied", "(", "err", ")", "{", "return", "lease", ".", "ErrClaimDenied", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Claim attempts to claim responsibility for administration of the entity // for the supplied duration. If the claim is denied, it will return // lease.ErrClaimDenied.
[ "Claim", "attempts", "to", "claim", "responsibility", "for", "administration", "of", "the", "entity", "for", "the", "supplied", "duration", ".", "If", "the", "claim", "is", "denied", "it", "will", "return", "lease", ".", "ErrClaimDenied", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/singular/api.go#L57-L79
157,192
juju/juju
api/singular/api.go
Wait
func (api *API) Wait() error { args := params.Entities{ Entities: []params.Entity{{ Tag: api.entity.String(), }}, } var results params.ErrorResults err := api.facadeCaller.FacadeCall("Wait", args, &results) if err != nil { return errors.Trace(err) } return results.OneError() }
go
func (api *API) Wait() error { args := params.Entities{ Entities: []params.Entity{{ Tag: api.entity.String(), }}, } var results params.ErrorResults err := api.facadeCaller.FacadeCall("Wait", args, &results) if err != nil { return errors.Trace(err) } return results.OneError() }
[ "func", "(", "api", "*", "API", ")", "Wait", "(", ")", "error", "{", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "Tag", ":", "api", ".", "entity", ".", "String", "(", ")", ",", "}", "}", ",", "}", "\n", "var", "results", "params", ".", "ErrorResults", "\n", "err", ":=", "api", ".", "facadeCaller", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "results", ".", "OneError", "(", ")", "\n", "}" ]
// Wait blocks until nobody has responsibility for administration of the // entity. It should probably be doing something watchy rather than blocky, // but it's following the lease manager implementation underlying the original // leadership approach and it doesn't seem worth rewriting all that.
[ "Wait", "blocks", "until", "nobody", "has", "responsibility", "for", "administration", "of", "the", "entity", ".", "It", "should", "probably", "be", "doing", "something", "watchy", "rather", "than", "blocky", "but", "it", "s", "following", "the", "lease", "manager", "implementation", "underlying", "the", "original", "leadership", "approach", "and", "it", "doesn", "t", "seem", "worth", "rewriting", "all", "that", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/singular/api.go#L85-L97
157,193
juju/juju
worker/machineundertaker/undertaker.go
NewWorker
func NewWorker(api Facade, env environs.Environ, credentialAPI common.CredentialAPI) (worker.Worker, error) { envNetworking, _ := environs.SupportsNetworking(env) w, err := watcher.NewNotifyWorker(watcher.NotifyConfig{ Handler: &Undertaker{ API: api, Releaser: envNetworking, CallContext: common.NewCloudCallContext(credentialAPI, nil), }, }) if err != nil { return nil, errors.Trace(err) } return w, nil }
go
func NewWorker(api Facade, env environs.Environ, credentialAPI common.CredentialAPI) (worker.Worker, error) { envNetworking, _ := environs.SupportsNetworking(env) w, err := watcher.NewNotifyWorker(watcher.NotifyConfig{ Handler: &Undertaker{ API: api, Releaser: envNetworking, CallContext: common.NewCloudCallContext(credentialAPI, nil), }, }) if err != nil { return nil, errors.Trace(err) } return w, nil }
[ "func", "NewWorker", "(", "api", "Facade", ",", "env", "environs", ".", "Environ", ",", "credentialAPI", "common", ".", "CredentialAPI", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "envNetworking", ",", "_", ":=", "environs", ".", "SupportsNetworking", "(", "env", ")", "\n", "w", ",", "err", ":=", "watcher", ".", "NewNotifyWorker", "(", "watcher", ".", "NotifyConfig", "{", "Handler", ":", "&", "Undertaker", "{", "API", ":", "api", ",", "Releaser", ":", "envNetworking", ",", "CallContext", ":", "common", ".", "NewCloudCallContext", "(", "credentialAPI", ",", "nil", ")", ",", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "w", ",", "nil", "\n", "}" ]
// NewWorker returns a machine undertaker worker that will watch for // machines that need to be removed and remove them, cleaning up any // necessary provider-level resources first.
[ "NewWorker", "returns", "a", "machine", "undertaker", "worker", "that", "will", "watch", "for", "machines", "that", "need", "to", "be", "removed", "and", "remove", "them", "cleaning", "up", "any", "necessary", "provider", "-", "level", "resources", "first", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/machineundertaker/undertaker.go#L47-L60
157,194
juju/juju
mongo/mongodfinder.go
FindBest
func (m *MongodFinder) FindBest() (string, Version, error) { if featureflag.Enabled(feature.MongoDbSnap) { v, err := m.findVersion(JujuDbSnapMongodPath) if err != nil { return "", Version{}, errors.NotFoundf("%s snap not installed correctly. Executable %s", JujuDbSnap, JujuDbSnapMongodPath) } return JujuDbSnapMongodPath, v, nil } // In Bionic and beyond (and early trusty) we just use the system mongo. // We only use the system mongo if it is at least Mongo 3.4 if m.search.Exists(MongodSystemPath) { // We found Mongo in the system directory, check to see if the version is valid if v, err := m.findVersion(MongodSystemPath); err != nil { logger.Warningf("system mongo %q found, but ignoring error trying to get version: %v", MongodSystemPath, err) } else if v.NewerThan(minimumSystemMongoVersion) >= 0 { // We only support mongo 3.4 and newer from the system return MongodSystemPath, v, nil } } // the system mongo is either too old, or not valid, keep trying if m.search.Exists(JujuMongod32Path) { // juju-mongod32 is available, check its version as well. Mostly just as a reporting convenience // Do we want to use it even if we can't deal with --version? v, err := m.findVersion(JujuMongod32Path) if err != nil { logger.Warningf("juju-mongodb3.2 %q found, but ignoring error trying to get version: %v", JujuMongod32Path, err) v = Mongo32wt } return JujuMongod32Path, v, nil } if m.search.Exists(JujuMongod24Path) { // juju-mongod is available, check its version as well. Mostly just as a reporting convenience if v, err := m.findVersion(JujuMongod24Path); err != nil { logger.Warningf("juju-mongodb %q found, but ignoring error trying to get version: %v", JujuMongod24Path, err) } else { return JujuMongod24Path, v, nil } } return "", Version{}, errors.NotFoundf("could not find a viable 'mongod'") }
go
func (m *MongodFinder) FindBest() (string, Version, error) { if featureflag.Enabled(feature.MongoDbSnap) { v, err := m.findVersion(JujuDbSnapMongodPath) if err != nil { return "", Version{}, errors.NotFoundf("%s snap not installed correctly. Executable %s", JujuDbSnap, JujuDbSnapMongodPath) } return JujuDbSnapMongodPath, v, nil } // In Bionic and beyond (and early trusty) we just use the system mongo. // We only use the system mongo if it is at least Mongo 3.4 if m.search.Exists(MongodSystemPath) { // We found Mongo in the system directory, check to see if the version is valid if v, err := m.findVersion(MongodSystemPath); err != nil { logger.Warningf("system mongo %q found, but ignoring error trying to get version: %v", MongodSystemPath, err) } else if v.NewerThan(minimumSystemMongoVersion) >= 0 { // We only support mongo 3.4 and newer from the system return MongodSystemPath, v, nil } } // the system mongo is either too old, or not valid, keep trying if m.search.Exists(JujuMongod32Path) { // juju-mongod32 is available, check its version as well. Mostly just as a reporting convenience // Do we want to use it even if we can't deal with --version? v, err := m.findVersion(JujuMongod32Path) if err != nil { logger.Warningf("juju-mongodb3.2 %q found, but ignoring error trying to get version: %v", JujuMongod32Path, err) v = Mongo32wt } return JujuMongod32Path, v, nil } if m.search.Exists(JujuMongod24Path) { // juju-mongod is available, check its version as well. Mostly just as a reporting convenience if v, err := m.findVersion(JujuMongod24Path); err != nil { logger.Warningf("juju-mongodb %q found, but ignoring error trying to get version: %v", JujuMongod24Path, err) } else { return JujuMongod24Path, v, nil } } return "", Version{}, errors.NotFoundf("could not find a viable 'mongod'") }
[ "func", "(", "m", "*", "MongodFinder", ")", "FindBest", "(", ")", "(", "string", ",", "Version", ",", "error", ")", "{", "if", "featureflag", ".", "Enabled", "(", "feature", ".", "MongoDbSnap", ")", "{", "v", ",", "err", ":=", "m", ".", "findVersion", "(", "JujuDbSnapMongodPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "Version", "{", "}", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "JujuDbSnap", ",", "JujuDbSnapMongodPath", ")", "\n", "}", "\n", "return", "JujuDbSnapMongodPath", ",", "v", ",", "nil", "\n", "}", "\n\n", "// In Bionic and beyond (and early trusty) we just use the system mongo.", "// We only use the system mongo if it is at least Mongo 3.4", "if", "m", ".", "search", ".", "Exists", "(", "MongodSystemPath", ")", "{", "// We found Mongo in the system directory, check to see if the version is valid", "if", "v", ",", "err", ":=", "m", ".", "findVersion", "(", "MongodSystemPath", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "MongodSystemPath", ",", "err", ")", "\n", "}", "else", "if", "v", ".", "NewerThan", "(", "minimumSystemMongoVersion", ")", ">=", "0", "{", "// We only support mongo 3.4 and newer from the system", "return", "MongodSystemPath", ",", "v", ",", "nil", "\n", "}", "\n", "}", "\n", "// the system mongo is either too old, or not valid, keep trying", "if", "m", ".", "search", ".", "Exists", "(", "JujuMongod32Path", ")", "{", "// juju-mongod32 is available, check its version as well. Mostly just as a reporting convenience", "// Do we want to use it even if we can't deal with --version?", "v", ",", "err", ":=", "m", ".", "findVersion", "(", "JujuMongod32Path", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "JujuMongod32Path", ",", "err", ")", "\n", "v", "=", "Mongo32wt", "\n", "}", "\n", "return", "JujuMongod32Path", ",", "v", ",", "nil", "\n", "}", "\n", "if", "m", ".", "search", ".", "Exists", "(", "JujuMongod24Path", ")", "{", "// juju-mongod is available, check its version as well. Mostly just as a reporting convenience", "if", "v", ",", "err", ":=", "m", ".", "findVersion", "(", "JujuMongod24Path", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "JujuMongod24Path", ",", "err", ")", "\n", "}", "else", "{", "return", "JujuMongod24Path", ",", "v", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "Version", "{", "}", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}" ]
// FindBest tries to find the mongo version that best fits what we want to use.
[ "FindBest", "tries", "to", "find", "the", "mongo", "version", "that", "best", "fits", "what", "we", "want", "to", "use", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/mongodfinder.go#L42-L85
157,195
juju/juju
cloud/validations.go
collectTags
func collectTags(t reflect.Type, tag string, ignoreTypes []string, keys *map[string]struct{}) { switch t.Kind() { case reflect.Array, reflect.Slice, reflect.Map, reflect.Ptr: collectTags(t.Elem(), tag, ignoreTypes, keys) case reflect.Struct: for i := 0; i < t.NumField(); i++ { field := t.Field(i) fieldTag := field.Tag.Get(tag) var fieldTagKey string ignoredType := false for _, it := range ignoreTypes { if field.Type.String() == it { ignoredType = true break } } if fieldTag == "-" || ignoredType { continue } if len(fieldTag) > 0 { fieldTagKey = strings.Split(fieldTag, ",")[0] } else { fieldTagKey = strings.ToLower(field.Name) } (*keys)[fieldTagKey] = struct{}{} collectTags(field.Type, tag, ignoreTypes, keys) } } }
go
func collectTags(t reflect.Type, tag string, ignoreTypes []string, keys *map[string]struct{}) { switch t.Kind() { case reflect.Array, reflect.Slice, reflect.Map, reflect.Ptr: collectTags(t.Elem(), tag, ignoreTypes, keys) case reflect.Struct: for i := 0; i < t.NumField(); i++ { field := t.Field(i) fieldTag := field.Tag.Get(tag) var fieldTagKey string ignoredType := false for _, it := range ignoreTypes { if field.Type.String() == it { ignoredType = true break } } if fieldTag == "-" || ignoredType { continue } if len(fieldTag) > 0 { fieldTagKey = strings.Split(fieldTag, ",")[0] } else { fieldTagKey = strings.ToLower(field.Name) } (*keys)[fieldTagKey] = struct{}{} collectTags(field.Type, tag, ignoreTypes, keys) } } }
[ "func", "collectTags", "(", "t", "reflect", ".", "Type", ",", "tag", "string", ",", "ignoreTypes", "[", "]", "string", ",", "keys", "*", "map", "[", "string", "]", "struct", "{", "}", ")", "{", "switch", "t", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Array", ",", "reflect", ".", "Slice", ",", "reflect", ".", "Map", ",", "reflect", ".", "Ptr", ":", "collectTags", "(", "t", ".", "Elem", "(", ")", ",", "tag", ",", "ignoreTypes", ",", "keys", ")", "\n\n", "case", "reflect", ".", "Struct", ":", "for", "i", ":=", "0", ";", "i", "<", "t", ".", "NumField", "(", ")", ";", "i", "++", "{", "field", ":=", "t", ".", "Field", "(", "i", ")", "\n\n", "fieldTag", ":=", "field", ".", "Tag", ".", "Get", "(", "tag", ")", "\n", "var", "fieldTagKey", "string", "\n\n", "ignoredType", ":=", "false", "\n", "for", "_", ",", "it", ":=", "range", "ignoreTypes", "{", "if", "field", ".", "Type", ".", "String", "(", ")", "==", "it", "{", "ignoredType", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "fieldTag", "==", "\"", "\"", "||", "ignoredType", "{", "continue", "\n", "}", "\n\n", "if", "len", "(", "fieldTag", ")", ">", "0", "{", "fieldTagKey", "=", "strings", ".", "Split", "(", "fieldTag", ",", "\"", "\"", ")", "[", "0", "]", "\n", "}", "else", "{", "fieldTagKey", "=", "strings", ".", "ToLower", "(", "field", ".", "Name", ")", "\n", "}", "\n\n", "(", "*", "keys", ")", "[", "fieldTagKey", "]", "=", "struct", "{", "}", "{", "}", "\n", "collectTags", "(", "field", ".", "Type", ",", "tag", ",", "ignoreTypes", ",", "keys", ")", "\n", "}", "\n", "}", "\n", "}" ]
// collectTags returns a set of keys for a specified struct tag. If no tag is // specified for a particular field of the argument struct type, then the // all-lowercase field name is used as per Go tag conventions. If the tag // specified is not the name a conventionally formatted go struct tag, then the // results of this function are invalid. Values of invalid kinds result in no // processing.
[ "collectTags", "returns", "a", "set", "of", "keys", "for", "a", "specified", "struct", "tag", ".", "If", "no", "tag", "is", "specified", "for", "a", "particular", "field", "of", "the", "argument", "struct", "type", "then", "the", "all", "-", "lowercase", "field", "name", "is", "used", "as", "per", "Go", "tag", "conventions", ".", "If", "the", "tag", "specified", "is", "not", "the", "name", "a", "conventionally", "formatted", "go", "struct", "tag", "then", "the", "results", "of", "this", "function", "are", "invalid", ".", "Values", "of", "invalid", "kinds", "result", "in", "no", "processing", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloud/validations.go#L145-L180
157,196
juju/juju
mongo/service.go
RemoveService
func RemoveService() error { svc, err := discoverService(ServiceName) if err != nil { return errors.Trace(err) } if err := svc.Stop(); err != nil { return errors.Trace(err) } if err := svc.Remove(); err != nil { return errors.Trace(err) } return nil }
go
func RemoveService() error { svc, err := discoverService(ServiceName) if err != nil { return errors.Trace(err) } if err := svc.Stop(); err != nil { return errors.Trace(err) } if err := svc.Remove(); err != nil { return errors.Trace(err) } return nil }
[ "func", "RemoveService", "(", ")", "error", "{", "svc", ",", "err", ":=", "discoverService", "(", "ServiceName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "svc", ".", "Stop", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "svc", ".", "Remove", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RemoveService removes the mongoDB init service from this machine.
[ "RemoveService", "removes", "the", "mongoDB", "init", "service", "from", "this", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/service.go#L110-L122
157,197
juju/juju
mongo/service.go
StopService
func StopService() error { svc, err := discoverService(ServiceName) if err != nil { return errors.Trace(err) } return svc.Stop() }
go
func StopService() error { svc, err := discoverService(ServiceName) if err != nil { return errors.Trace(err) } return svc.Stop() }
[ "func", "StopService", "(", ")", "error", "{", "svc", ",", "err", ":=", "discoverService", "(", "ServiceName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "svc", ".", "Stop", "(", ")", "\n", "}" ]
// StopService will stop mongodb service.
[ "StopService", "will", "stop", "mongodb", "service", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/service.go#L125-L131
157,198
juju/juju
mongo/service.go
StartService
func StartService() error { svc, err := discoverService(ServiceName) if err != nil { return errors.Trace(err) } return svc.Start() }
go
func StartService() error { svc, err := discoverService(ServiceName) if err != nil { return errors.Trace(err) } return svc.Start() }
[ "func", "StartService", "(", ")", "error", "{", "svc", ",", "err", ":=", "discoverService", "(", "ServiceName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "svc", ".", "Start", "(", ")", "\n", "}" ]
// StartService will start mongodb service.
[ "StartService", "will", "start", "mongodb", "service", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/service.go#L134-L140
157,199
juju/juju
mongo/service.go
ReStartService
func ReStartService() error { // TODO(tsm): refactor to make use of service.RestartableService svc, err := discoverService(ServiceName) if err != nil { return errors.Trace(err) } return restartService(svc) }
go
func ReStartService() error { // TODO(tsm): refactor to make use of service.RestartableService svc, err := discoverService(ServiceName) if err != nil { return errors.Trace(err) } return restartService(svc) }
[ "func", "ReStartService", "(", ")", "error", "{", "// TODO(tsm): refactor to make use of service.RestartableService", "svc", ",", "err", ":=", "discoverService", "(", "ServiceName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "restartService", "(", "svc", ")", "\n", "}" ]
// ReStartService will stop and then start mongodb service.
[ "ReStartService", "will", "stop", "and", "then", "start", "mongodb", "service", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/service.go#L143-L150