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
4,300
juju/juju
container/kvm/wrappedcmds.go
DestroyMachine
func DestroyMachine(c *kvmContainer) error { if c.runCmd == nil { c.runCmd = run } if c.pathfinder == nil { c.pathfinder = paths.DataDir } // We don't return errors for virsh commands because it is possible that we // didn't succeed in creating the domain. Additionally, we want all the // commands to run. If any fail it is certainly because the thing we're // trying to remove wasn't created. However, we still want to try removing // all the parts. The exception here is getting the guestBase, if that // fails we return the error because we cannot continue without it. _, err := c.runCmd("", virsh, "destroy", c.Name()) if err != nil { logger.Infof("`%s destroy %s` failed: %q", virsh, c.Name(), err) } // The nvram flag here removes the pflash drive for us. There is also a // `remove-all-storage` flag, but it is unclear if that would also remove // the backing store which we don't want to do. So we remove those manually // after undefining. _, err = c.runCmd("", virsh, "undefine", "--nvram", c.Name()) if err != nil { logger.Infof("`%s undefine --nvram %s` failed: %q", virsh, c.Name(), err) } guestBase, err := guestPath(c.pathfinder) if err != nil { return errors.Trace(err) } err = os.Remove(filepath.Join(guestBase, fmt.Sprintf("%s.qcow", c.Name()))) if err != nil { logger.Errorf("failed to remove system disk for %q: %s", c.Name(), err) } err = os.Remove(filepath.Join(guestBase, fmt.Sprintf("%s-ds.iso", c.Name()))) if err != nil { logger.Errorf("failed to remove cloud-init data disk for %q: %s", c.Name(), err) } return nil }
go
func DestroyMachine(c *kvmContainer) error { if c.runCmd == nil { c.runCmd = run } if c.pathfinder == nil { c.pathfinder = paths.DataDir } // We don't return errors for virsh commands because it is possible that we // didn't succeed in creating the domain. Additionally, we want all the // commands to run. If any fail it is certainly because the thing we're // trying to remove wasn't created. However, we still want to try removing // all the parts. The exception here is getting the guestBase, if that // fails we return the error because we cannot continue without it. _, err := c.runCmd("", virsh, "destroy", c.Name()) if err != nil { logger.Infof("`%s destroy %s` failed: %q", virsh, c.Name(), err) } // The nvram flag here removes the pflash drive for us. There is also a // `remove-all-storage` flag, but it is unclear if that would also remove // the backing store which we don't want to do. So we remove those manually // after undefining. _, err = c.runCmd("", virsh, "undefine", "--nvram", c.Name()) if err != nil { logger.Infof("`%s undefine --nvram %s` failed: %q", virsh, c.Name(), err) } guestBase, err := guestPath(c.pathfinder) if err != nil { return errors.Trace(err) } err = os.Remove(filepath.Join(guestBase, fmt.Sprintf("%s.qcow", c.Name()))) if err != nil { logger.Errorf("failed to remove system disk for %q: %s", c.Name(), err) } err = os.Remove(filepath.Join(guestBase, fmt.Sprintf("%s-ds.iso", c.Name()))) if err != nil { logger.Errorf("failed to remove cloud-init data disk for %q: %s", c.Name(), err) } return nil }
[ "func", "DestroyMachine", "(", "c", "*", "kvmContainer", ")", "error", "{", "if", "c", ".", "runCmd", "==", "nil", "{", "c", ".", "runCmd", "=", "run", "\n", "}", "\n", "if", "c", ".", "pathfinder", "==", "nil", "{", "c", ".", "pathfinder", "=", "paths", ".", "DataDir", "\n", "}", "\n\n", "// We don't return errors for virsh commands because it is possible that we", "// didn't succeed in creating the domain. Additionally, we want all the", "// commands to run. If any fail it is certainly because the thing we're", "// trying to remove wasn't created. However, we still want to try removing", "// all the parts. The exception here is getting the guestBase, if that", "// fails we return the error because we cannot continue without it.", "_", ",", "err", ":=", "c", ".", "runCmd", "(", "\"", "\"", ",", "virsh", ",", "\"", "\"", ",", "c", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "virsh", ",", "c", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n\n", "// The nvram flag here removes the pflash drive for us. There is also a", "// `remove-all-storage` flag, but it is unclear if that would also remove", "// the backing store which we don't want to do. So we remove those manually", "// after undefining.", "_", ",", "err", "=", "c", ".", "runCmd", "(", "\"", "\"", ",", "virsh", ",", "\"", "\"", ",", "\"", "\"", ",", "c", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "virsh", ",", "c", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "guestBase", ",", "err", ":=", "guestPath", "(", "c", ".", "pathfinder", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "err", "=", "os", ".", "Remove", "(", "filepath", ".", "Join", "(", "guestBase", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "Name", "(", ")", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "err", "=", "os", ".", "Remove", "(", "filepath", ".", "Join", "(", "guestBase", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "Name", "(", ")", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// DestroyMachine destroys the virtual machine represented by the kvmContainer.
[ "DestroyMachine", "destroys", "the", "virtual", "machine", "represented", "by", "the", "kvmContainer", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L230-L272
4,301
juju/juju
container/kvm/wrappedcmds.go
AutostartMachine
func AutostartMachine(c *kvmContainer) error { if c.runCmd == nil { c.runCmd = run } _, err := c.runCmd("", virsh, "autostart", c.Name()) return errors.Annotatef(err, "failed to autostart domain %q", c.Name()) }
go
func AutostartMachine(c *kvmContainer) error { if c.runCmd == nil { c.runCmd = run } _, err := c.runCmd("", virsh, "autostart", c.Name()) return errors.Annotatef(err, "failed to autostart domain %q", c.Name()) }
[ "func", "AutostartMachine", "(", "c", "*", "kvmContainer", ")", "error", "{", "if", "c", ".", "runCmd", "==", "nil", "{", "c", ".", "runCmd", "=", "run", "\n", "}", "\n", "_", ",", "err", ":=", "c", ".", "runCmd", "(", "\"", "\"", ",", "virsh", ",", "\"", "\"", ",", "c", ".", "Name", "(", ")", ")", "\n", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "c", ".", "Name", "(", ")", ")", "\n", "}" ]
// AutostartMachine indicates that the virtual machines should automatically // restart when the host restarts.
[ "AutostartMachine", "indicates", "that", "the", "virtual", "machines", "should", "automatically", "restart", "when", "the", "host", "restarts", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L276-L282
4,302
juju/juju
container/kvm/wrappedcmds.go
guestPath
func guestPath(pathfinder func(string) (string, error)) (string, error) { baseDir, err := pathfinder(series.MustHostSeries()) if err != nil { return "", errors.Trace(err) } return filepath.Join(baseDir, kvm, guestDir), nil }
go
func guestPath(pathfinder func(string) (string, error)) (string, error) { baseDir, err := pathfinder(series.MustHostSeries()) if err != nil { return "", errors.Trace(err) } return filepath.Join(baseDir, kvm, guestDir), nil }
[ "func", "guestPath", "(", "pathfinder", "func", "(", "string", ")", "(", "string", ",", "error", ")", ")", "(", "string", ",", "error", ")", "{", "baseDir", ",", "err", ":=", "pathfinder", "(", "series", ".", "MustHostSeries", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "filepath", ".", "Join", "(", "baseDir", ",", "kvm", ",", "guestDir", ")", ",", "nil", "\n", "}" ]
// guestPath returns the path to the guest directory from the given // pathfinder.
[ "guestPath", "returns", "the", "path", "to", "the", "guest", "directory", "from", "the", "given", "pathfinder", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L310-L316
4,303
juju/juju
container/kvm/wrappedcmds.go
writeDataSourceVolume
func writeDataSourceVolume(params CreateMachineParams) (string, error) { templateDir := filepath.Dir(params.UserDataFile) if err := writeMetadata(templateDir); err != nil { return "", errors.Trace(err) } if err := writeNetworkConfig(params, templateDir); err != nil { return "", errors.Trace(err) } // Creating a working DS volume was a bit troublesome for me. I finally // found the details in the docs. // http://cloudinit.readthedocs.io/en/latest/topics/datasources/nocloud.html // // The arguments passed to create the DS volume for NoCloud must be // `user-data` and `meta-data`. So the `cloud-init` file we generate won't // work. Also, they must be exactly `user-data` and `meta-data` with no // path beforehand, so `$JUJUDIR/containers/juju-someid-0/user-data` also // fails. // // Furthermore, symlinks aren't followed by NoCloud. So we rename our // cloud-init file to user-data. We could change the output name in // juju/cloudconfig/containerinit/container_userdata.go:WriteUserData but // who knows what that will break. userDataPath := filepath.Join(templateDir, userdata) if err := os.Rename(params.UserDataFile, userDataPath); err != nil { return "", errors.Trace(err) } // Create data the source volume outputting the iso image to the guests // (AKA libvirt storage pool) directory. guestBase, err := guestPath(params.findPath) if err != nil { return "", errors.Trace(err) } dsPath := filepath.Join(guestBase, fmt.Sprintf("%s-ds.iso", params.Host())) // Use the template path as the working directory. // This allows us to run the command with user-data and meta-data as // relative paths to appease the NoCloud script. out, err := params.runCmd( templateDir, "genisoimage", "-output", dsPath, "-volid", "cidata", "-joliet", "-rock", userdata, metadata, networkconfig) if err != nil { return "", errors.Trace(err) } logger.Debugf("create ds image: %s", out) return dsPath, nil }
go
func writeDataSourceVolume(params CreateMachineParams) (string, error) { templateDir := filepath.Dir(params.UserDataFile) if err := writeMetadata(templateDir); err != nil { return "", errors.Trace(err) } if err := writeNetworkConfig(params, templateDir); err != nil { return "", errors.Trace(err) } // Creating a working DS volume was a bit troublesome for me. I finally // found the details in the docs. // http://cloudinit.readthedocs.io/en/latest/topics/datasources/nocloud.html // // The arguments passed to create the DS volume for NoCloud must be // `user-data` and `meta-data`. So the `cloud-init` file we generate won't // work. Also, they must be exactly `user-data` and `meta-data` with no // path beforehand, so `$JUJUDIR/containers/juju-someid-0/user-data` also // fails. // // Furthermore, symlinks aren't followed by NoCloud. So we rename our // cloud-init file to user-data. We could change the output name in // juju/cloudconfig/containerinit/container_userdata.go:WriteUserData but // who knows what that will break. userDataPath := filepath.Join(templateDir, userdata) if err := os.Rename(params.UserDataFile, userDataPath); err != nil { return "", errors.Trace(err) } // Create data the source volume outputting the iso image to the guests // (AKA libvirt storage pool) directory. guestBase, err := guestPath(params.findPath) if err != nil { return "", errors.Trace(err) } dsPath := filepath.Join(guestBase, fmt.Sprintf("%s-ds.iso", params.Host())) // Use the template path as the working directory. // This allows us to run the command with user-data and meta-data as // relative paths to appease the NoCloud script. out, err := params.runCmd( templateDir, "genisoimage", "-output", dsPath, "-volid", "cidata", "-joliet", "-rock", userdata, metadata, networkconfig) if err != nil { return "", errors.Trace(err) } logger.Debugf("create ds image: %s", out) return dsPath, nil }
[ "func", "writeDataSourceVolume", "(", "params", "CreateMachineParams", ")", "(", "string", ",", "error", ")", "{", "templateDir", ":=", "filepath", ".", "Dir", "(", "params", ".", "UserDataFile", ")", "\n\n", "if", "err", ":=", "writeMetadata", "(", "templateDir", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "writeNetworkConfig", "(", "params", ",", "templateDir", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Creating a working DS volume was a bit troublesome for me. I finally", "// found the details in the docs.", "// http://cloudinit.readthedocs.io/en/latest/topics/datasources/nocloud.html", "//", "// The arguments passed to create the DS volume for NoCloud must be", "// `user-data` and `meta-data`. So the `cloud-init` file we generate won't", "// work. Also, they must be exactly `user-data` and `meta-data` with no", "// path beforehand, so `$JUJUDIR/containers/juju-someid-0/user-data` also", "// fails.", "//", "// Furthermore, symlinks aren't followed by NoCloud. So we rename our", "// cloud-init file to user-data. We could change the output name in", "// juju/cloudconfig/containerinit/container_userdata.go:WriteUserData but", "// who knows what that will break.", "userDataPath", ":=", "filepath", ".", "Join", "(", "templateDir", ",", "userdata", ")", "\n", "if", "err", ":=", "os", ".", "Rename", "(", "params", ".", "UserDataFile", ",", "userDataPath", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Create data the source volume outputting the iso image to the guests", "// (AKA libvirt storage pool) directory.", "guestBase", ",", "err", ":=", "guestPath", "(", "params", ".", "findPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "dsPath", ":=", "filepath", ".", "Join", "(", "guestBase", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "params", ".", "Host", "(", ")", ")", ")", "\n\n", "// Use the template path as the working directory.", "// This allows us to run the command with user-data and meta-data as", "// relative paths to appease the NoCloud script.", "out", ",", "err", ":=", "params", ".", "runCmd", "(", "templateDir", ",", "\"", "\"", ",", "\"", "\"", ",", "dsPath", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "userdata", ",", "metadata", ",", "networkconfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "out", ")", "\n\n", "return", "dsPath", ",", "nil", "\n", "}" ]
// writeDataSourceVolume creates a data source image for cloud init.
[ "writeDataSourceVolume", "creates", "a", "data", "source", "image", "for", "cloud", "init", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L319-L375
4,304
juju/juju
container/kvm/wrappedcmds.go
writeDomainXML
func writeDomainXML(templateDir string, p CreateMachineParams) (string, error) { domainPath := filepath.Join(templateDir, fmt.Sprintf("%s.xml", p.Host())) dom, err := libvirt.NewDomain(p) if err != nil { return "", errors.Trace(err) } ml, err := xml.MarshalIndent(&dom, "", " ") if err != nil { return "", errors.Trace(err) } f, err := os.Create(domainPath) if err != nil { return "", errors.Trace(err) } defer func() { err = f.Close() if err != nil { logger.Debugf("failed defer %q", errors.Trace(err)) } }() _, err = f.Write(ml) if err != nil { return "", errors.Trace(err) } return domainPath, nil }
go
func writeDomainXML(templateDir string, p CreateMachineParams) (string, error) { domainPath := filepath.Join(templateDir, fmt.Sprintf("%s.xml", p.Host())) dom, err := libvirt.NewDomain(p) if err != nil { return "", errors.Trace(err) } ml, err := xml.MarshalIndent(&dom, "", " ") if err != nil { return "", errors.Trace(err) } f, err := os.Create(domainPath) if err != nil { return "", errors.Trace(err) } defer func() { err = f.Close() if err != nil { logger.Debugf("failed defer %q", errors.Trace(err)) } }() _, err = f.Write(ml) if err != nil { return "", errors.Trace(err) } return domainPath, nil }
[ "func", "writeDomainXML", "(", "templateDir", "string", ",", "p", "CreateMachineParams", ")", "(", "string", ",", "error", ")", "{", "domainPath", ":=", "filepath", ".", "Join", "(", "templateDir", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "Host", "(", ")", ")", ")", "\n", "dom", ",", "err", ":=", "libvirt", ".", "NewDomain", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "ml", ",", "err", ":=", "xml", ".", "MarshalIndent", "(", "&", "dom", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "f", ",", "err", ":=", "os", ".", "Create", "(", "domainPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "err", "=", "f", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "_", ",", "err", "=", "f", ".", "Write", "(", "ml", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "domainPath", ",", "nil", "\n", "}" ]
// writeDomainXML writes out the configuration required to create a new guest // domain.
[ "writeDomainXML", "writes", "out", "the", "configuration", "required", "to", "create", "a", "new", "guest", "domain", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L379-L408
4,305
juju/juju
apiserver/facades/client/subnets/subnets.go
NewAPI
func NewAPI(st *state.State, res facade.Resources, auth facade.Authorizer) (SubnetsAPI, error) { stateshim, err := networkingcommon.NewStateShim(st) if err != nil { return nil, errors.Trace(err) } return newAPIWithBacking(stateshim, state.CallContext(st), res, auth) }
go
func NewAPI(st *state.State, res facade.Resources, auth facade.Authorizer) (SubnetsAPI, error) { stateshim, err := networkingcommon.NewStateShim(st) if err != nil { return nil, errors.Trace(err) } return newAPIWithBacking(stateshim, state.CallContext(st), res, auth) }
[ "func", "NewAPI", "(", "st", "*", "state", ".", "State", ",", "res", "facade", ".", "Resources", ",", "auth", "facade", ".", "Authorizer", ")", "(", "SubnetsAPI", ",", "error", ")", "{", "stateshim", ",", "err", ":=", "networkingcommon", ".", "NewStateShim", "(", "st", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "newAPIWithBacking", "(", "stateshim", ",", "state", ".", "CallContext", "(", "st", ")", ",", "res", ",", "auth", ")", "\n", "}" ]
// NewAPI creates a new Subnets API server-side facade with a // state.State backing.
[ "NewAPI", "creates", "a", "new", "Subnets", "API", "server", "-", "side", "facade", "with", "a", "state", ".", "State", "backing", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/subnets/subnets.go#L47-L53
4,306
juju/juju
apiserver/facades/client/subnets/subnets.go
AllSpaces
func (api *subnetsAPI) AllSpaces() (params.SpaceResults, error) { if err := api.checkCanRead(); err != nil { return params.SpaceResults{}, err } var results params.SpaceResults spaces, err := api.backing.AllSpaces() if err != nil { return results, errors.Trace(err) } results.Results = make([]params.SpaceResult, len(spaces)) for i, space := range spaces { // TODO(dimitern): Add a Tag() a method and use it here. Too // early to do it now as it will just complicate the tests. tag := names.NewSpaceTag(space.Name()) results.Results[i].Tag = tag.String() } return results, nil }
go
func (api *subnetsAPI) AllSpaces() (params.SpaceResults, error) { if err := api.checkCanRead(); err != nil { return params.SpaceResults{}, err } var results params.SpaceResults spaces, err := api.backing.AllSpaces() if err != nil { return results, errors.Trace(err) } results.Results = make([]params.SpaceResult, len(spaces)) for i, space := range spaces { // TODO(dimitern): Add a Tag() a method and use it here. Too // early to do it now as it will just complicate the tests. tag := names.NewSpaceTag(space.Name()) results.Results[i].Tag = tag.String() } return results, nil }
[ "func", "(", "api", "*", "subnetsAPI", ")", "AllSpaces", "(", ")", "(", "params", ".", "SpaceResults", ",", "error", ")", "{", "if", "err", ":=", "api", ".", "checkCanRead", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "SpaceResults", "{", "}", ",", "err", "\n", "}", "\n\n", "var", "results", "params", ".", "SpaceResults", "\n\n", "spaces", ",", "err", ":=", "api", ".", "backing", ".", "AllSpaces", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "results", ".", "Results", "=", "make", "(", "[", "]", "params", ".", "SpaceResult", ",", "len", "(", "spaces", ")", ")", "\n", "for", "i", ",", "space", ":=", "range", "spaces", "{", "// TODO(dimitern): Add a Tag() a method and use it here. Too", "// early to do it now as it will just complicate the tests.", "tag", ":=", "names", ".", "NewSpaceTag", "(", "space", ".", "Name", "(", ")", ")", "\n", "results", ".", "Results", "[", "i", "]", ".", "Tag", "=", "tag", ".", "String", "(", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// AllSpaces is defined on the API interface.
[ "AllSpaces", "is", "defined", "on", "the", "API", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/subnets/subnets.go#L101-L121
4,307
juju/juju
apiserver/facades/client/subnets/subnets.go
AddSubnets
func (api *subnetsAPI) AddSubnets(args params.AddSubnetsParams) (params.ErrorResults, error) { if err := api.checkCanWrite(); err != nil { return params.ErrorResults{}, err } return networkingcommon.AddSubnets(api.context, api.backing, args) }
go
func (api *subnetsAPI) AddSubnets(args params.AddSubnetsParams) (params.ErrorResults, error) { if err := api.checkCanWrite(); err != nil { return params.ErrorResults{}, err } return networkingcommon.AddSubnets(api.context, api.backing, args) }
[ "func", "(", "api", "*", "subnetsAPI", ")", "AddSubnets", "(", "args", "params", ".", "AddSubnetsParams", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "if", "err", ":=", "api", ".", "checkCanWrite", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "err", "\n", "}", "\n", "return", "networkingcommon", ".", "AddSubnets", "(", "api", ".", "context", ",", "api", ".", "backing", ",", "args", ")", "\n", "}" ]
// AddSubnets is defined on the API interface.
[ "AddSubnets", "is", "defined", "on", "the", "API", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/subnets/subnets.go#L124-L129
4,308
juju/juju
worker/uniter/runner/jujuc/leader-get.go
NewLeaderGetCommand
func NewLeaderGetCommand(ctx Context) (cmd.Command, error) { return &leaderGetCommand{ctx: ctx}, nil }
go
func NewLeaderGetCommand(ctx Context) (cmd.Command, error) { return &leaderGetCommand{ctx: ctx}, nil }
[ "func", "NewLeaderGetCommand", "(", "ctx", "Context", ")", "(", "cmd", ".", "Command", ",", "error", ")", "{", "return", "&", "leaderGetCommand", "{", "ctx", ":", "ctx", "}", ",", "nil", "\n", "}" ]
// NewLeaderGetCommand returns a new leaderGetCommand with the given context.
[ "NewLeaderGetCommand", "returns", "a", "new", "leaderGetCommand", "with", "the", "given", "context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/leader-get.go#L25-L27
4,309
juju/juju
cloud/personalclouds.go
PersonalCloudMetadata
func PersonalCloudMetadata() (map[string]Cloud, error) { clouds, err := ParseCloudMetadataFile(JujuPersonalCloudsPath()) if err != nil && os.IsNotExist(err) { return nil, nil } return clouds, err }
go
func PersonalCloudMetadata() (map[string]Cloud, error) { clouds, err := ParseCloudMetadataFile(JujuPersonalCloudsPath()) if err != nil && os.IsNotExist(err) { return nil, nil } return clouds, err }
[ "func", "PersonalCloudMetadata", "(", ")", "(", "map", "[", "string", "]", "Cloud", ",", "error", ")", "{", "clouds", ",", "err", ":=", "ParseCloudMetadataFile", "(", "JujuPersonalCloudsPath", "(", ")", ")", "\n", "if", "err", "!=", "nil", "&&", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "clouds", ",", "err", "\n", "}" ]
// PersonalCloudMetadata loads any personal cloud metadata defined // in the Juju Home directory. If not cloud metadata is found, // that is not an error; nil is returned.
[ "PersonalCloudMetadata", "loads", "any", "personal", "cloud", "metadata", "defined", "in", "the", "Juju", "Home", "directory", ".", "If", "not", "cloud", "metadata", "is", "found", "that", "is", "not", "an", "error", ";", "nil", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloud/personalclouds.go#L27-L33
4,310
juju/juju
cloud/personalclouds.go
ParseCloudMetadataFile
func ParseCloudMetadataFile(file string) (map[string]Cloud, error) { data, err := ioutil.ReadFile(file) if err != nil { return nil, err } clouds, err := ParseCloudMetadata(data) if err != nil { return nil, err } return clouds, err }
go
func ParseCloudMetadataFile(file string) (map[string]Cloud, error) { data, err := ioutil.ReadFile(file) if err != nil { return nil, err } clouds, err := ParseCloudMetadata(data) if err != nil { return nil, err } return clouds, err }
[ "func", "ParseCloudMetadataFile", "(", "file", "string", ")", "(", "map", "[", "string", "]", "Cloud", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "clouds", ",", "err", ":=", "ParseCloudMetadata", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "clouds", ",", "err", "\n", "}" ]
// ParseCloudMetadataFile loads any cloud metadata defined // in the specified file.
[ "ParseCloudMetadataFile", "loads", "any", "cloud", "metadata", "defined", "in", "the", "specified", "file", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloud/personalclouds.go#L37-L47
4,311
juju/juju
cloud/personalclouds.go
WritePersonalCloudMetadata
func WritePersonalCloudMetadata(cloudsMap map[string]Cloud) error { data, err := marshalCloudMetadata(cloudsMap) if err != nil { return errors.Trace(err) } return ioutil.WriteFile(JujuPersonalCloudsPath(), data, os.FileMode(0600)) }
go
func WritePersonalCloudMetadata(cloudsMap map[string]Cloud) error { data, err := marshalCloudMetadata(cloudsMap) if err != nil { return errors.Trace(err) } return ioutil.WriteFile(JujuPersonalCloudsPath(), data, os.FileMode(0600)) }
[ "func", "WritePersonalCloudMetadata", "(", "cloudsMap", "map", "[", "string", "]", "Cloud", ")", "error", "{", "data", ",", "err", ":=", "marshalCloudMetadata", "(", "cloudsMap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "ioutil", ".", "WriteFile", "(", "JujuPersonalCloudsPath", "(", ")", ",", "data", ",", "os", ".", "FileMode", "(", "0600", ")", ")", "\n", "}" ]
// WritePersonalCloudMetadata marshals to YAML and writes the cloud metadata // to the personal cloud file.
[ "WritePersonalCloudMetadata", "marshals", "to", "YAML", "and", "writes", "the", "cloud", "metadata", "to", "the", "personal", "cloud", "file", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloud/personalclouds.go#L51-L57
4,312
juju/juju
network/containerizer/bridgepolicy.go
inferContainerSpaces
func (p *BridgePolicy) inferContainerSpaces(m Machine, containerId, defaultSpaceName string) (set.Strings, error) { if p.ContainerNetworkingMethod == "local" { return set.NewStrings(""), nil } hostSpaces, err := m.AllSpaces() if err != nil { return nil, errors.Trace(err) } logger.Debugf("container %q not qualified to a space, host machine %q is using spaces %s", containerId, m.Id(), network.QuoteSpaceSet(hostSpaces)) if len(hostSpaces) == 1 { return hostSpaces, nil } if defaultSpaceName != "" && hostSpaces.Contains(defaultSpaceName) { return set.NewStrings(defaultSpaceName), nil } if len(hostSpaces) == 0 { logger.Debugf("container has no desired spaces, " + "and host has no known spaces, triggering fallback " + "to bridge all devices") return set.NewStrings(""), nil } return nil, errors.Errorf("no obvious space for container %q, host machine has spaces: %s", containerId, network.QuoteSpaceSet(hostSpaces)) }
go
func (p *BridgePolicy) inferContainerSpaces(m Machine, containerId, defaultSpaceName string) (set.Strings, error) { if p.ContainerNetworkingMethod == "local" { return set.NewStrings(""), nil } hostSpaces, err := m.AllSpaces() if err != nil { return nil, errors.Trace(err) } logger.Debugf("container %q not qualified to a space, host machine %q is using spaces %s", containerId, m.Id(), network.QuoteSpaceSet(hostSpaces)) if len(hostSpaces) == 1 { return hostSpaces, nil } if defaultSpaceName != "" && hostSpaces.Contains(defaultSpaceName) { return set.NewStrings(defaultSpaceName), nil } if len(hostSpaces) == 0 { logger.Debugf("container has no desired spaces, " + "and host has no known spaces, triggering fallback " + "to bridge all devices") return set.NewStrings(""), nil } return nil, errors.Errorf("no obvious space for container %q, host machine has spaces: %s", containerId, network.QuoteSpaceSet(hostSpaces)) }
[ "func", "(", "p", "*", "BridgePolicy", ")", "inferContainerSpaces", "(", "m", "Machine", ",", "containerId", ",", "defaultSpaceName", "string", ")", "(", "set", ".", "Strings", ",", "error", ")", "{", "if", "p", ".", "ContainerNetworkingMethod", "==", "\"", "\"", "{", "return", "set", ".", "NewStrings", "(", "\"", "\"", ")", ",", "nil", "\n", "}", "\n", "hostSpaces", ",", "err", ":=", "m", ".", "AllSpaces", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "containerId", ",", "m", ".", "Id", "(", ")", ",", "network", ".", "QuoteSpaceSet", "(", "hostSpaces", ")", ")", "\n", "if", "len", "(", "hostSpaces", ")", "==", "1", "{", "return", "hostSpaces", ",", "nil", "\n", "}", "\n", "if", "defaultSpaceName", "!=", "\"", "\"", "&&", "hostSpaces", ".", "Contains", "(", "defaultSpaceName", ")", "{", "return", "set", ".", "NewStrings", "(", "defaultSpaceName", ")", ",", "nil", "\n", "}", "\n", "if", "len", "(", "hostSpaces", ")", "==", "0", "{", "logger", ".", "Debugf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ")", "\n", "return", "set", ".", "NewStrings", "(", "\"", "\"", ")", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "containerId", ",", "network", ".", "QuoteSpaceSet", "(", "hostSpaces", ")", ")", "\n", "}" ]
// inferContainerSpaces tries to find a valid space for the container to be // on. This should only be used when the container itself doesn't have any // valid constraints on what spaces it should be in. // If ContainerNetworkingMethod is 'local' we fall back to "" and use lxdbr0. // If this machine is in a single space, then that space is used. Else, if // the machine has the default space, then that space is used. // If neither of those conditions is true, then we return an error.
[ "inferContainerSpaces", "tries", "to", "find", "a", "valid", "space", "for", "the", "container", "to", "be", "on", ".", "This", "should", "only", "be", "used", "when", "the", "container", "itself", "doesn", "t", "have", "any", "valid", "constraints", "on", "what", "spaces", "it", "should", "be", "in", ".", "If", "ContainerNetworkingMethod", "is", "local", "we", "fall", "back", "to", "and", "use", "lxdbr0", ".", "If", "this", "machine", "is", "in", "a", "single", "space", "then", "that", "space", "is", "used", ".", "Else", "if", "the", "machine", "has", "the", "default", "space", "then", "that", "space", "is", "used", ".", "If", "neither", "of", "those", "conditions", "is", "true", "then", "we", "return", "an", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/containerizer/bridgepolicy.go#L50-L74
4,313
juju/juju
network/containerizer/bridgepolicy.go
determineContainerSpaces
func (p *BridgePolicy) determineContainerSpaces(m Machine, containerMachine Container, defaultSpaceName string) (set.Strings, error) { containerSpaces, err := containerMachine.DesiredSpaces() if err != nil { return nil, errors.Trace(err) } logger.Debugf("for container %q, found desired spaces: %s", containerMachine.Id(), network.QuoteSpaceSet(containerSpaces)) if len(containerSpaces) == 0 { // We have determined that the container doesn't have any useful // constraints set on it. So lets see if we can come up with // something useful. containerSpaces, err = p.inferContainerSpaces(m, containerMachine.Id(), defaultSpaceName) if err != nil { return nil, errors.Trace(err) } } return containerSpaces, nil }
go
func (p *BridgePolicy) determineContainerSpaces(m Machine, containerMachine Container, defaultSpaceName string) (set.Strings, error) { containerSpaces, err := containerMachine.DesiredSpaces() if err != nil { return nil, errors.Trace(err) } logger.Debugf("for container %q, found desired spaces: %s", containerMachine.Id(), network.QuoteSpaceSet(containerSpaces)) if len(containerSpaces) == 0 { // We have determined that the container doesn't have any useful // constraints set on it. So lets see if we can come up with // something useful. containerSpaces, err = p.inferContainerSpaces(m, containerMachine.Id(), defaultSpaceName) if err != nil { return nil, errors.Trace(err) } } return containerSpaces, nil }
[ "func", "(", "p", "*", "BridgePolicy", ")", "determineContainerSpaces", "(", "m", "Machine", ",", "containerMachine", "Container", ",", "defaultSpaceName", "string", ")", "(", "set", ".", "Strings", ",", "error", ")", "{", "containerSpaces", ",", "err", ":=", "containerMachine", ".", "DesiredSpaces", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "containerMachine", ".", "Id", "(", ")", ",", "network", ".", "QuoteSpaceSet", "(", "containerSpaces", ")", ")", "\n", "if", "len", "(", "containerSpaces", ")", "==", "0", "{", "// We have determined that the container doesn't have any useful", "// constraints set on it. So lets see if we can come up with", "// something useful.", "containerSpaces", ",", "err", "=", "p", ".", "inferContainerSpaces", "(", "m", ",", "containerMachine", ".", "Id", "(", ")", ",", "defaultSpaceName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "containerSpaces", ",", "nil", "\n", "}" ]
// determineContainerSpaces tries to use the direct information about a // container to find what spaces it should be in, and then falls back to what // we know about the host machine.
[ "determineContainerSpaces", "tries", "to", "use", "the", "direct", "information", "about", "a", "container", "to", "find", "what", "spaces", "it", "should", "be", "in", "and", "then", "falls", "back", "to", "what", "we", "know", "about", "the", "host", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/containerizer/bridgepolicy.go#L79-L96
4,314
juju/juju
network/containerizer/bridgepolicy.go
findSpacesAndDevicesForContainer
func (p *BridgePolicy) findSpacesAndDevicesForContainer(m Machine, containerMachine Container) (set.Strings, map[string][]LinkLayerDevice, error) { containerSpaces, err := p.determineContainerSpaces(m, containerMachine, "") if err != nil { return nil, nil, errors.Trace(err) } devicesPerSpace, err := m.LinkLayerDevicesForSpaces(containerSpaces.Values()) if err != nil { logger.Errorf("findSpacesAndDevicesForContainer(%q) got error looking for host spaces: %v", containerMachine.Id(), err) return nil, nil, errors.Trace(err) } return containerSpaces, devicesPerSpace, nil }
go
func (p *BridgePolicy) findSpacesAndDevicesForContainer(m Machine, containerMachine Container) (set.Strings, map[string][]LinkLayerDevice, error) { containerSpaces, err := p.determineContainerSpaces(m, containerMachine, "") if err != nil { return nil, nil, errors.Trace(err) } devicesPerSpace, err := m.LinkLayerDevicesForSpaces(containerSpaces.Values()) if err != nil { logger.Errorf("findSpacesAndDevicesForContainer(%q) got error looking for host spaces: %v", containerMachine.Id(), err) return nil, nil, errors.Trace(err) } return containerSpaces, devicesPerSpace, nil }
[ "func", "(", "p", "*", "BridgePolicy", ")", "findSpacesAndDevicesForContainer", "(", "m", "Machine", ",", "containerMachine", "Container", ")", "(", "set", ".", "Strings", ",", "map", "[", "string", "]", "[", "]", "LinkLayerDevice", ",", "error", ")", "{", "containerSpaces", ",", "err", ":=", "p", ".", "determineContainerSpaces", "(", "m", ",", "containerMachine", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "devicesPerSpace", ",", "err", ":=", "m", ".", "LinkLayerDevicesForSpaces", "(", "containerSpaces", ".", "Values", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "containerMachine", ".", "Id", "(", ")", ",", "err", ")", "\n", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "containerSpaces", ",", "devicesPerSpace", ",", "nil", "\n", "}" ]
// findSpacesAndDevicesForContainer looks up what spaces the container wants // to be in, and what spaces the host machine is already in, and tries to // find the devices on the host that are useful for the container.
[ "findSpacesAndDevicesForContainer", "looks", "up", "what", "spaces", "the", "container", "wants", "to", "be", "in", "and", "what", "spaces", "the", "host", "machine", "is", "already", "in", "and", "tries", "to", "find", "the", "devices", "on", "the", "host", "that", "are", "useful", "for", "the", "container", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/containerizer/bridgepolicy.go#L101-L113
4,315
juju/juju
worker/agentconfigupdater/manifold.go
Manifold
func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{ config.AgentName, config.APICallerName, config.CentralHubName, }, Start: func(context dependency.Context) (worker.Worker, error) { // Get the agent. var agent coreagent.Agent if err := context.Get(config.AgentName, &agent); err != nil { return nil, err } // Grab the tag and ensure that it's for a machine. currentConfig := agent.CurrentConfig() tag, ok := currentConfig.Tag().(names.MachineTag) if !ok { return nil, errors.New("agent's tag is not a machine tag") } // Get API connection. var apiCaller base.APICaller if err := context.Get(config.APICallerName, &apiCaller); err != nil { return nil, err } apiState, err := apiagent.NewState(apiCaller) if err != nil { return nil, errors.Trace(err) } // If the machine needs State, grab the state serving info // over the API and write it to the agent configuration. if controller, err := isController(apiState, tag); err != nil { return nil, errors.Annotate(err, "checking controller status") } else if !controller { // Not a controller, nothing to do. return nil, dependency.ErrUninstall } // Do the initial state serving info and mongo profile checks // before attempting to get the central hub. The central hub is only // running when the agent is a controller. If the agent isn't a controller // but should be, the agent config will not have any state serving info // but the database will think that we should be. In those situations // we need to update the local config and restart. controllerConfig, err := apiState.ControllerConfig() if err != nil { return nil, errors.Annotate(err, "getting controller config") } // If the mongo memory profile from the controller config // is different from the one in the agent config we need to // restart the agent to apply the memory profile to the mongo // service. logger := config.Logger agentsMongoMemoryProfile := currentConfig.MongoMemoryProfile() configMongoMemoryProfile := mongo.MemoryProfile(controllerConfig.MongoMemoryProfile()) mongoProfileChanged := agentsMongoMemoryProfile != configMongoMemoryProfile info, err := apiState.StateServingInfo() if err != nil { return nil, errors.Annotate(err, "getting state serving info") } err = agent.ChangeConfig(func(config coreagent.ConfigSetter) error { existing, hasInfo := config.StateServingInfo() if hasInfo { // Use the existing cert and key as they appear to // have been already updated by the cert updater // worker to have this machine's IP address as // part of the cert. This changed cert is never // put back into the database, so it isn't // reflected in the copy we have got from // apiState. info.Cert = existing.Cert info.PrivateKey = existing.PrivateKey } config.SetStateServingInfo(info) if mongoProfileChanged { logger.Debugf("setting agent config mongo memory profile: %q => %q", agentsMongoMemoryProfile, configMongoMemoryProfile) config.SetMongoMemoryProfile(configMongoMemoryProfile) } return nil }) if err != nil { return nil, errors.Trace(err) } // If we need a restart, return the fatal error. if mongoProfileChanged { logger.Infof("restarting agent for new mongo memory profile") return nil, jworker.ErrRestartAgent } // Only get the hub if we are a controller and we haven't updated // the memory profile. var hub *pubsub.StructuredHub if err := context.Get(config.CentralHubName, &hub); err != nil { logger.Tracef("hub dependency not available") return nil, err } return NewWorker(WorkerConfig{ Agent: agent, Hub: hub, MongoProfile: configMongoMemoryProfile, Logger: config.Logger, }) }, } }
go
func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{ config.AgentName, config.APICallerName, config.CentralHubName, }, Start: func(context dependency.Context) (worker.Worker, error) { // Get the agent. var agent coreagent.Agent if err := context.Get(config.AgentName, &agent); err != nil { return nil, err } // Grab the tag and ensure that it's for a machine. currentConfig := agent.CurrentConfig() tag, ok := currentConfig.Tag().(names.MachineTag) if !ok { return nil, errors.New("agent's tag is not a machine tag") } // Get API connection. var apiCaller base.APICaller if err := context.Get(config.APICallerName, &apiCaller); err != nil { return nil, err } apiState, err := apiagent.NewState(apiCaller) if err != nil { return nil, errors.Trace(err) } // If the machine needs State, grab the state serving info // over the API and write it to the agent configuration. if controller, err := isController(apiState, tag); err != nil { return nil, errors.Annotate(err, "checking controller status") } else if !controller { // Not a controller, nothing to do. return nil, dependency.ErrUninstall } // Do the initial state serving info and mongo profile checks // before attempting to get the central hub. The central hub is only // running when the agent is a controller. If the agent isn't a controller // but should be, the agent config will not have any state serving info // but the database will think that we should be. In those situations // we need to update the local config and restart. controllerConfig, err := apiState.ControllerConfig() if err != nil { return nil, errors.Annotate(err, "getting controller config") } // If the mongo memory profile from the controller config // is different from the one in the agent config we need to // restart the agent to apply the memory profile to the mongo // service. logger := config.Logger agentsMongoMemoryProfile := currentConfig.MongoMemoryProfile() configMongoMemoryProfile := mongo.MemoryProfile(controllerConfig.MongoMemoryProfile()) mongoProfileChanged := agentsMongoMemoryProfile != configMongoMemoryProfile info, err := apiState.StateServingInfo() if err != nil { return nil, errors.Annotate(err, "getting state serving info") } err = agent.ChangeConfig(func(config coreagent.ConfigSetter) error { existing, hasInfo := config.StateServingInfo() if hasInfo { // Use the existing cert and key as they appear to // have been already updated by the cert updater // worker to have this machine's IP address as // part of the cert. This changed cert is never // put back into the database, so it isn't // reflected in the copy we have got from // apiState. info.Cert = existing.Cert info.PrivateKey = existing.PrivateKey } config.SetStateServingInfo(info) if mongoProfileChanged { logger.Debugf("setting agent config mongo memory profile: %q => %q", agentsMongoMemoryProfile, configMongoMemoryProfile) config.SetMongoMemoryProfile(configMongoMemoryProfile) } return nil }) if err != nil { return nil, errors.Trace(err) } // If we need a restart, return the fatal error. if mongoProfileChanged { logger.Infof("restarting agent for new mongo memory profile") return nil, jworker.ErrRestartAgent } // Only get the hub if we are a controller and we haven't updated // the memory profile. var hub *pubsub.StructuredHub if err := context.Get(config.CentralHubName, &hub); err != nil { logger.Tracef("hub dependency not available") return nil, err } return NewWorker(WorkerConfig{ Agent: agent, Hub: hub, MongoProfile: configMongoMemoryProfile, Logger: config.Logger, }) }, } }
[ "func", "Manifold", "(", "config", "ManifoldConfig", ")", "dependency", ".", "Manifold", "{", "return", "dependency", ".", "Manifold", "{", "Inputs", ":", "[", "]", "string", "{", "config", ".", "AgentName", ",", "config", ".", "APICallerName", ",", "config", ".", "CentralHubName", ",", "}", ",", "Start", ":", "func", "(", "context", "dependency", ".", "Context", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "// Get the agent.", "var", "agent", "coreagent", ".", "Agent", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "AgentName", ",", "&", "agent", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Grab the tag and ensure that it's for a machine.", "currentConfig", ":=", "agent", ".", "CurrentConfig", "(", ")", "\n", "tag", ",", "ok", ":=", "currentConfig", ".", "Tag", "(", ")", ".", "(", "names", ".", "MachineTag", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Get API connection.", "var", "apiCaller", "base", ".", "APICaller", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "APICallerName", ",", "&", "apiCaller", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "apiState", ",", "err", ":=", "apiagent", ".", "NewState", "(", "apiCaller", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// If the machine needs State, grab the state serving info", "// over the API and write it to the agent configuration.", "if", "controller", ",", "err", ":=", "isController", "(", "apiState", ",", "tag", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "else", "if", "!", "controller", "{", "// Not a controller, nothing to do.", "return", "nil", ",", "dependency", ".", "ErrUninstall", "\n", "}", "\n\n", "// Do the initial state serving info and mongo profile checks", "// before attempting to get the central hub. The central hub is only", "// running when the agent is a controller. If the agent isn't a controller", "// but should be, the agent config will not have any state serving info", "// but the database will think that we should be. In those situations", "// we need to update the local config and restart.", "controllerConfig", ",", "err", ":=", "apiState", ".", "ControllerConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "// If the mongo memory profile from the controller config", "// is different from the one in the agent config we need to", "// restart the agent to apply the memory profile to the mongo", "// service.", "logger", ":=", "config", ".", "Logger", "\n", "agentsMongoMemoryProfile", ":=", "currentConfig", ".", "MongoMemoryProfile", "(", ")", "\n", "configMongoMemoryProfile", ":=", "mongo", ".", "MemoryProfile", "(", "controllerConfig", ".", "MongoMemoryProfile", "(", ")", ")", "\n", "mongoProfileChanged", ":=", "agentsMongoMemoryProfile", "!=", "configMongoMemoryProfile", "\n\n", "info", ",", "err", ":=", "apiState", ".", "StateServingInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "err", "=", "agent", ".", "ChangeConfig", "(", "func", "(", "config", "coreagent", ".", "ConfigSetter", ")", "error", "{", "existing", ",", "hasInfo", ":=", "config", ".", "StateServingInfo", "(", ")", "\n", "if", "hasInfo", "{", "// Use the existing cert and key as they appear to", "// have been already updated by the cert updater", "// worker to have this machine's IP address as", "// part of the cert. This changed cert is never", "// put back into the database, so it isn't", "// reflected in the copy we have got from", "// apiState.", "info", ".", "Cert", "=", "existing", ".", "Cert", "\n", "info", ".", "PrivateKey", "=", "existing", ".", "PrivateKey", "\n", "}", "\n", "config", ".", "SetStateServingInfo", "(", "info", ")", "\n", "if", "mongoProfileChanged", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "agentsMongoMemoryProfile", ",", "configMongoMemoryProfile", ")", "\n", "config", ".", "SetMongoMemoryProfile", "(", "configMongoMemoryProfile", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// If we need a restart, return the fatal error.", "if", "mongoProfileChanged", "{", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "jworker", ".", "ErrRestartAgent", "\n", "}", "\n\n", "// Only get the hub if we are a controller and we haven't updated", "// the memory profile.", "var", "hub", "*", "pubsub", ".", "StructuredHub", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "CentralHubName", ",", "&", "hub", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Tracef", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "NewWorker", "(", "WorkerConfig", "{", "Agent", ":", "agent", ",", "Hub", ":", "hub", ",", "MongoProfile", ":", "configMongoMemoryProfile", ",", "Logger", ":", "config", ".", "Logger", ",", "}", ")", "\n", "}", ",", "}", "\n", "}" ]
// Manifold defines a simple start function which // runs after the API connection has come up. If the machine agent is // a controller, it grabs the state serving info over the API and // records it to agent configuration, and then stops.
[ "Manifold", "defines", "a", "simple", "start", "function", "which", "runs", "after", "the", "API", "connection", "has", "come", "up", ".", "If", "the", "machine", "agent", "is", "a", "controller", "it", "grabs", "the", "state", "serving", "info", "over", "the", "API", "and", "records", "it", "to", "agent", "configuration", "and", "then", "stops", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/agentconfigupdater/manifold.go#L42-L150
4,316
juju/juju
cmd/juju/storage/poollistformatters.go
formatPoolListTabular
func formatPoolListTabular(writer io.Writer, value interface{}) error { pools, ok := value.(map[string]PoolInfo) if !ok { return errors.Errorf("expected value of type %T, got %T", pools, value) } formatPoolsTabular(writer, pools) return nil }
go
func formatPoolListTabular(writer io.Writer, value interface{}) error { pools, ok := value.(map[string]PoolInfo) if !ok { return errors.Errorf("expected value of type %T, got %T", pools, value) } formatPoolsTabular(writer, pools) return nil }
[ "func", "formatPoolListTabular", "(", "writer", "io", ".", "Writer", ",", "value", "interface", "{", "}", ")", "error", "{", "pools", ",", "ok", ":=", "value", ".", "(", "map", "[", "string", "]", "PoolInfo", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "pools", ",", "value", ")", "\n", "}", "\n", "formatPoolsTabular", "(", "writer", ",", "pools", ")", "\n", "return", "nil", "\n", "}" ]
// formatPoolListTabular returns a tabular summary of pool instances or // errors out if parameter is not a map of PoolInfo.
[ "formatPoolListTabular", "returns", "a", "tabular", "summary", "of", "pool", "instances", "or", "errors", "out", "if", "parameter", "is", "not", "a", "map", "of", "PoolInfo", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/storage/poollistformatters.go#L19-L26
4,317
juju/juju
cmd/juju/storage/poollistformatters.go
formatPoolsTabular
func formatPoolsTabular(writer io.Writer, pools map[string]PoolInfo) { tw := output.TabWriter(writer) print := func(values ...string) { fmt.Fprintln(tw, strings.Join(values, "\t")) } print("Name", "Provider", "Attrs") poolNames := make([]string, 0, len(pools)) for name := range pools { poolNames = append(poolNames, name) } sort.Strings(poolNames) for _, name := range poolNames { pool := pools[name] // order by key for deterministic return keys := make([]string, 0, len(pool.Attrs)) for key := range pool.Attrs { keys = append(keys, key) } sort.Strings(keys) attrs := make([]string, len(pool.Attrs)) for i, key := range keys { attrs[i] = fmt.Sprintf("%v=%v", key, pool.Attrs[key]) } print(name, pool.Provider, strings.Join(attrs, " ")) } tw.Flush() }
go
func formatPoolsTabular(writer io.Writer, pools map[string]PoolInfo) { tw := output.TabWriter(writer) print := func(values ...string) { fmt.Fprintln(tw, strings.Join(values, "\t")) } print("Name", "Provider", "Attrs") poolNames := make([]string, 0, len(pools)) for name := range pools { poolNames = append(poolNames, name) } sort.Strings(poolNames) for _, name := range poolNames { pool := pools[name] // order by key for deterministic return keys := make([]string, 0, len(pool.Attrs)) for key := range pool.Attrs { keys = append(keys, key) } sort.Strings(keys) attrs := make([]string, len(pool.Attrs)) for i, key := range keys { attrs[i] = fmt.Sprintf("%v=%v", key, pool.Attrs[key]) } print(name, pool.Provider, strings.Join(attrs, " ")) } tw.Flush() }
[ "func", "formatPoolsTabular", "(", "writer", "io", ".", "Writer", ",", "pools", "map", "[", "string", "]", "PoolInfo", ")", "{", "tw", ":=", "output", ".", "TabWriter", "(", "writer", ")", "\n", "print", ":=", "func", "(", "values", "...", "string", ")", "{", "fmt", ".", "Fprintln", "(", "tw", ",", "strings", ".", "Join", "(", "values", ",", "\"", "\\t", "\"", ")", ")", "\n", "}", "\n\n", "print", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "poolNames", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "pools", ")", ")", "\n", "for", "name", ":=", "range", "pools", "{", "poolNames", "=", "append", "(", "poolNames", ",", "name", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "poolNames", ")", "\n", "for", "_", ",", "name", ":=", "range", "poolNames", "{", "pool", ":=", "pools", "[", "name", "]", "\n", "// order by key for deterministic return", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "pool", ".", "Attrs", ")", ")", "\n", "for", "key", ":=", "range", "pool", ".", "Attrs", "{", "keys", "=", "append", "(", "keys", ",", "key", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n", "attrs", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "pool", ".", "Attrs", ")", ")", "\n", "for", "i", ",", "key", ":=", "range", "keys", "{", "attrs", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ",", "pool", ".", "Attrs", "[", "key", "]", ")", "\n", "}", "\n", "print", "(", "name", ",", "pool", ".", "Provider", ",", "strings", ".", "Join", "(", "attrs", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "tw", ".", "Flush", "(", ")", "\n", "}" ]
// formatPoolsTabular returns a tabular summary of pool instances.
[ "formatPoolsTabular", "returns", "a", "tabular", "summary", "of", "pool", "instances", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/storage/poollistformatters.go#L29-L57
4,318
juju/juju
provider/vsphere/errors.go
IsAuthorisationFailure
func IsAuthorisationFailure(err error) bool { baseErr := errors.Cause(err) if !soap.IsSoapFault(baseErr) { return false } fault := soap.ToSoapFault(baseErr) if fault.Code != serverFaultCode { return false } _, isPermissionError := fault.Detail.Fault.(types.NoPermission) if isPermissionError { return true } // Otherwise it could be a login error. return strings.Contains(fault.String, loginErrorFragment) }
go
func IsAuthorisationFailure(err error) bool { baseErr := errors.Cause(err) if !soap.IsSoapFault(baseErr) { return false } fault := soap.ToSoapFault(baseErr) if fault.Code != serverFaultCode { return false } _, isPermissionError := fault.Detail.Fault.(types.NoPermission) if isPermissionError { return true } // Otherwise it could be a login error. return strings.Contains(fault.String, loginErrorFragment) }
[ "func", "IsAuthorisationFailure", "(", "err", "error", ")", "bool", "{", "baseErr", ":=", "errors", ".", "Cause", "(", "err", ")", "\n", "if", "!", "soap", ".", "IsSoapFault", "(", "baseErr", ")", "{", "return", "false", "\n", "}", "\n", "fault", ":=", "soap", ".", "ToSoapFault", "(", "baseErr", ")", "\n", "if", "fault", ".", "Code", "!=", "serverFaultCode", "{", "return", "false", "\n", "}", "\n", "_", ",", "isPermissionError", ":=", "fault", ".", "Detail", ".", "Fault", ".", "(", "types", ".", "NoPermission", ")", "\n", "if", "isPermissionError", "{", "return", "true", "\n", "}", "\n", "// Otherwise it could be a login error.", "return", "strings", ".", "Contains", "(", "fault", ".", "String", ",", "loginErrorFragment", ")", "\n", "}" ]
// IsAuthorisationFailure determines whether the given error indicates // that the vsphere credential used is bad.
[ "IsAuthorisationFailure", "determines", "whether", "the", "given", "error", "indicates", "that", "the", "vsphere", "credential", "used", "is", "bad", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/errors.go#L31-L46
4,319
juju/juju
state/undertaker.go
ProcessDyingModel
func (st *State) ProcessDyingModel() (err error) { model, err := st.Model() if err != nil { return errors.Trace(err) } if model.Life() != Dying { return errors.Trace(ErrModelNotDying) } if st.IsController() { // We should not mark the controller model as Dead until // all hosted models have been removed, otherwise the // hosted model environs may not have been destroyed. modelUUIDs, err := st.AllModelUUIDsIncludingDead() if err != nil { return errors.Trace(err) } if n := len(modelUUIDs) - 1; n > 0 { return errors.Trace(hasHostedModelsError(n)) } } modelEntityRefsDoc, err := model.getEntityRefs() if err != nil { return errors.Trace(err) } if _, err := checkModelEntityRefsEmpty(modelEntityRefsDoc); err != nil { return errors.Trace(err) } return nil }
go
func (st *State) ProcessDyingModel() (err error) { model, err := st.Model() if err != nil { return errors.Trace(err) } if model.Life() != Dying { return errors.Trace(ErrModelNotDying) } if st.IsController() { // We should not mark the controller model as Dead until // all hosted models have been removed, otherwise the // hosted model environs may not have been destroyed. modelUUIDs, err := st.AllModelUUIDsIncludingDead() if err != nil { return errors.Trace(err) } if n := len(modelUUIDs) - 1; n > 0 { return errors.Trace(hasHostedModelsError(n)) } } modelEntityRefsDoc, err := model.getEntityRefs() if err != nil { return errors.Trace(err) } if _, err := checkModelEntityRefsEmpty(modelEntityRefsDoc); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "st", "*", "State", ")", "ProcessDyingModel", "(", ")", "(", "err", "error", ")", "{", "model", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "model", ".", "Life", "(", ")", "!=", "Dying", "{", "return", "errors", ".", "Trace", "(", "ErrModelNotDying", ")", "\n", "}", "\n\n", "if", "st", ".", "IsController", "(", ")", "{", "// We should not mark the controller model as Dead until", "// all hosted models have been removed, otherwise the", "// hosted model environs may not have been destroyed.", "modelUUIDs", ",", "err", ":=", "st", ".", "AllModelUUIDsIncludingDead", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "n", ":=", "len", "(", "modelUUIDs", ")", "-", "1", ";", "n", ">", "0", "{", "return", "errors", ".", "Trace", "(", "hasHostedModelsError", "(", "n", ")", ")", "\n", "}", "\n", "}", "\n\n", "modelEntityRefsDoc", ",", "err", ":=", "model", ".", "getEntityRefs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "checkModelEntityRefsEmpty", "(", "modelEntityRefsDoc", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ProcessDyingModel checks if the model is Dying and empty, and if so, // transitions the model to Dead. // // If the model is non-empty because it is the controller model and still // contains hosted models, an error satisfying IsHasHostedModelsError will // be returned. If the model is otherwise non-empty, an error satisfying // IsNonEmptyModelError will be returned.
[ "ProcessDyingModel", "checks", "if", "the", "model", "is", "Dying", "and", "empty", "and", "if", "so", "transitions", "the", "model", "to", "Dead", ".", "If", "the", "model", "is", "non", "-", "empty", "because", "it", "is", "the", "controller", "model", "and", "still", "contains", "hosted", "models", "an", "error", "satisfying", "IsHasHostedModelsError", "will", "be", "returned", ".", "If", "the", "model", "is", "otherwise", "non", "-", "empty", "an", "error", "satisfying", "IsNonEmptyModelError", "will", "be", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/undertaker.go#L19-L51
4,320
juju/juju
apiserver/facades/client/metricsdebug/metricsdebug.go
NewMetricsDebugAPI
func NewMetricsDebugAPI( st *state.State, resources facade.Resources, authorizer facade.Authorizer, ) (*MetricsDebugAPI, error) { if !authorizer.AuthClient() { return nil, common.ErrPerm } return &MetricsDebugAPI{ state: st, }, nil }
go
func NewMetricsDebugAPI( st *state.State, resources facade.Resources, authorizer facade.Authorizer, ) (*MetricsDebugAPI, error) { if !authorizer.AuthClient() { return nil, common.ErrPerm } return &MetricsDebugAPI{ state: st, }, nil }
[ "func", "NewMetricsDebugAPI", "(", "st", "*", "state", ".", "State", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ",", ")", "(", "*", "MetricsDebugAPI", ",", "error", ")", "{", "if", "!", "authorizer", ".", "AuthClient", "(", ")", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n\n", "return", "&", "MetricsDebugAPI", "{", "state", ":", "st", ",", "}", ",", "nil", "\n", "}" ]
// NewMetricsDebugAPI creates a new API endpoint for calling metrics debug functions.
[ "NewMetricsDebugAPI", "creates", "a", "new", "API", "endpoint", "for", "calling", "metrics", "debug", "functions", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/metricsdebug/metricsdebug.go#L57-L69
4,321
juju/juju
apiserver/facades/client/metricsdebug/metricsdebug.go
GetMetrics
func (api *MetricsDebugAPI) GetMetrics(args params.Entities) (params.MetricResults, error) { results := params.MetricResults{ Results: make([]params.EntityMetrics, len(args.Entities)), } if len(args.Entities) == 0 { batches, err := api.state.MetricBatchesForModel() if err != nil { return results, errors.Annotate(err, "failed to get metrics") } return params.MetricResults{ Results: []params.EntityMetrics{{ Metrics: api.filterLastValuePerKeyPerUnit(batches), }}, }, nil } for i, arg := range args.Entities { tag, err := names.ParseTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } var batches []state.MetricBatch switch tag.Kind() { case names.UnitTagKind: batches, err = api.state.MetricBatchesForUnit(tag.Id()) if err != nil { err = errors.Annotate(err, "failed to get metrics") results.Results[i].Error = common.ServerError(err) continue } case names.ApplicationTagKind: batches, err = api.state.MetricBatchesForApplication(tag.Id()) if err != nil { err = errors.Annotate(err, "failed to get metrics") results.Results[i].Error = common.ServerError(err) continue } default: err := errors.Errorf("invalid tag %v", arg.Tag) results.Results[i].Error = common.ServerError(err) } results.Results[i].Metrics = api.filterLastValuePerKeyPerUnit(batches) } return results, nil }
go
func (api *MetricsDebugAPI) GetMetrics(args params.Entities) (params.MetricResults, error) { results := params.MetricResults{ Results: make([]params.EntityMetrics, len(args.Entities)), } if len(args.Entities) == 0 { batches, err := api.state.MetricBatchesForModel() if err != nil { return results, errors.Annotate(err, "failed to get metrics") } return params.MetricResults{ Results: []params.EntityMetrics{{ Metrics: api.filterLastValuePerKeyPerUnit(batches), }}, }, nil } for i, arg := range args.Entities { tag, err := names.ParseTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } var batches []state.MetricBatch switch tag.Kind() { case names.UnitTagKind: batches, err = api.state.MetricBatchesForUnit(tag.Id()) if err != nil { err = errors.Annotate(err, "failed to get metrics") results.Results[i].Error = common.ServerError(err) continue } case names.ApplicationTagKind: batches, err = api.state.MetricBatchesForApplication(tag.Id()) if err != nil { err = errors.Annotate(err, "failed to get metrics") results.Results[i].Error = common.ServerError(err) continue } default: err := errors.Errorf("invalid tag %v", arg.Tag) results.Results[i].Error = common.ServerError(err) } results.Results[i].Metrics = api.filterLastValuePerKeyPerUnit(batches) } return results, nil }
[ "func", "(", "api", "*", "MetricsDebugAPI", ")", "GetMetrics", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "MetricResults", ",", "error", ")", "{", "results", ":=", "params", ".", "MetricResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "EntityMetrics", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "if", "len", "(", "args", ".", "Entities", ")", "==", "0", "{", "batches", ",", "err", ":=", "api", ".", "state", ".", "MetricBatchesForModel", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "params", ".", "MetricResults", "{", "Results", ":", "[", "]", "params", ".", "EntityMetrics", "{", "{", "Metrics", ":", "api", ".", "filterLastValuePerKeyPerUnit", "(", "batches", ")", ",", "}", "}", ",", "}", ",", "nil", "\n", "}", "\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "arg", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "var", "batches", "[", "]", "state", ".", "MetricBatch", "\n", "switch", "tag", ".", "Kind", "(", ")", "{", "case", "names", ".", "UnitTagKind", ":", "batches", ",", "err", "=", "api", ".", "state", ".", "MetricBatchesForUnit", "(", "tag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "case", "names", ".", "ApplicationTagKind", ":", "batches", ",", "err", "=", "api", ".", "state", ".", "MetricBatchesForApplication", "(", "tag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "default", ":", "err", ":=", "errors", ".", "Errorf", "(", "\"", "\"", ",", "arg", ".", "Tag", ")", "\n", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "Metrics", "=", "api", ".", "filterLastValuePerKeyPerUnit", "(", "batches", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// GetMetrics returns all metrics stored by the state server.
[ "GetMetrics", "returns", "all", "metrics", "stored", "by", "the", "state", "server", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/metricsdebug/metricsdebug.go#L72-L116
4,322
juju/juju
apiserver/facades/client/metricsdebug/metricsdebug.go
SetMeterStatus
func (api *MetricsDebugAPI) SetMeterStatus(args params.MeterStatusParams) (params.ErrorResults, error) { results := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Statuses)), } for i, arg := range args.Statuses { tag, err := names.ParseTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } err = api.setEntityMeterStatus(tag, state.MeterStatus{ Code: state.MeterStatusFromString(arg.Code), Info: arg.Info, }) if err != nil { results.Results[i].Error = common.ServerError(err) continue } } return results, nil }
go
func (api *MetricsDebugAPI) SetMeterStatus(args params.MeterStatusParams) (params.ErrorResults, error) { results := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Statuses)), } for i, arg := range args.Statuses { tag, err := names.ParseTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } err = api.setEntityMeterStatus(tag, state.MeterStatus{ Code: state.MeterStatusFromString(arg.Code), Info: arg.Info, }) if err != nil { results.Results[i].Error = common.ServerError(err) continue } } return results, nil }
[ "func", "(", "api", "*", "MetricsDebugAPI", ")", "SetMeterStatus", "(", "args", "params", ".", "MeterStatusParams", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "results", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Statuses", ")", ")", ",", "}", "\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Statuses", "{", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "arg", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "err", "=", "api", ".", "setEntityMeterStatus", "(", "tag", ",", "state", ".", "MeterStatus", "{", "Code", ":", "state", ".", "MeterStatusFromString", "(", "arg", ".", "Code", ")", ",", "Info", ":", "arg", ".", "Info", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// SetMeterStatus sets meter statuses for entities.
[ "SetMeterStatus", "sets", "meter", "statuses", "for", "entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/metricsdebug/metricsdebug.go#L170-L190
4,323
juju/juju
apiserver/common/password.go
NewPasswordChanger
func NewPasswordChanger(st state.EntityFinder, getCanChange GetAuthFunc) *PasswordChanger { return &PasswordChanger{ st: st, getCanChange: getCanChange, } }
go
func NewPasswordChanger(st state.EntityFinder, getCanChange GetAuthFunc) *PasswordChanger { return &PasswordChanger{ st: st, getCanChange: getCanChange, } }
[ "func", "NewPasswordChanger", "(", "st", "state", ".", "EntityFinder", ",", "getCanChange", "GetAuthFunc", ")", "*", "PasswordChanger", "{", "return", "&", "PasswordChanger", "{", "st", ":", "st", ",", "getCanChange", ":", "getCanChange", ",", "}", "\n", "}" ]
// NewPasswordChanger returns a new PasswordChanger. The GetAuthFunc will be // used on each invocation of SetPasswords to determine current permissions.
[ "NewPasswordChanger", "returns", "a", "new", "PasswordChanger", ".", "The", "GetAuthFunc", "will", "be", "used", "on", "each", "invocation", "of", "SetPasswords", "to", "determine", "current", "permissions", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/password.go#L26-L31
4,324
juju/juju
apiserver/common/password.go
SetPasswords
func (pc *PasswordChanger) SetPasswords(args params.EntityPasswords) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Changes)), } if len(args.Changes) == 0 { return result, nil } canChange, err := pc.getCanChange() if err != nil { return params.ErrorResults{}, errors.Trace(err) } for i, param := range args.Changes { tag, err := names.ParseTag(param.Tag) if err != nil { result.Results[i].Error = ServerError(ErrPerm) continue } if !canChange(tag) { result.Results[i].Error = ServerError(ErrPerm) continue } if err := pc.setPassword(tag, param.Password); err != nil { result.Results[i].Error = ServerError(err) } } return result, nil }
go
func (pc *PasswordChanger) SetPasswords(args params.EntityPasswords) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Changes)), } if len(args.Changes) == 0 { return result, nil } canChange, err := pc.getCanChange() if err != nil { return params.ErrorResults{}, errors.Trace(err) } for i, param := range args.Changes { tag, err := names.ParseTag(param.Tag) if err != nil { result.Results[i].Error = ServerError(ErrPerm) continue } if !canChange(tag) { result.Results[i].Error = ServerError(ErrPerm) continue } if err := pc.setPassword(tag, param.Password); err != nil { result.Results[i].Error = ServerError(err) } } return result, nil }
[ "func", "(", "pc", "*", "PasswordChanger", ")", "SetPasswords", "(", "args", "params", ".", "EntityPasswords", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "result", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Changes", ")", ")", ",", "}", "\n", "if", "len", "(", "args", ".", "Changes", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n", "canChange", ",", "err", ":=", "pc", ".", "getCanChange", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "i", ",", "param", ":=", "range", "args", ".", "Changes", "{", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "param", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "ServerError", "(", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "canChange", "(", "tag", ")", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "ServerError", "(", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "if", "err", ":=", "pc", ".", "setPassword", "(", "tag", ",", "param", ".", "Password", ")", ";", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "ServerError", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// SetPasswords sets the given password for each supplied entity, if possible.
[ "SetPasswords", "sets", "the", "given", "password", "for", "each", "supplied", "entity", "if", "possible", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/password.go#L34-L60
4,325
juju/juju
cmd/juju/caas/add.go
NewAddCAASCommand
func NewAddCAASCommand(cloudMetadataStore CloudMetadataStore) cmd.Command { store := jujuclient.NewFileClientStore() cmd := &AddCAASCommand{ OptionalControllerCommand: modelcmd.OptionalControllerCommand{Store: store}, cloudMetadataStore: cloudMetadataStore, store: store, newClientConfigReader: func(caasType string) (clientconfig.ClientConfigFunc, error) { return clientconfig.NewClientConfigReader(caasType) }, } cmd.addCloudAPIFunc = func() (AddCloudAPI, error) { root, err := cmd.NewAPIRoot(cmd.store, cmd.controllerName, "") if err != nil { return nil, errors.Trace(err) } return cloudapi.NewClient(root), nil } cmd.brokerGetter = cmd.newK8sClusterBroker cmd.getAllCloudDetails = jujucmdcloud.GetAllCloudDetails return modelcmd.WrapBase(cmd) }
go
func NewAddCAASCommand(cloudMetadataStore CloudMetadataStore) cmd.Command { store := jujuclient.NewFileClientStore() cmd := &AddCAASCommand{ OptionalControllerCommand: modelcmd.OptionalControllerCommand{Store: store}, cloudMetadataStore: cloudMetadataStore, store: store, newClientConfigReader: func(caasType string) (clientconfig.ClientConfigFunc, error) { return clientconfig.NewClientConfigReader(caasType) }, } cmd.addCloudAPIFunc = func() (AddCloudAPI, error) { root, err := cmd.NewAPIRoot(cmd.store, cmd.controllerName, "") if err != nil { return nil, errors.Trace(err) } return cloudapi.NewClient(root), nil } cmd.brokerGetter = cmd.newK8sClusterBroker cmd.getAllCloudDetails = jujucmdcloud.GetAllCloudDetails return modelcmd.WrapBase(cmd) }
[ "func", "NewAddCAASCommand", "(", "cloudMetadataStore", "CloudMetadataStore", ")", "cmd", ".", "Command", "{", "store", ":=", "jujuclient", ".", "NewFileClientStore", "(", ")", "\n", "cmd", ":=", "&", "AddCAASCommand", "{", "OptionalControllerCommand", ":", "modelcmd", ".", "OptionalControllerCommand", "{", "Store", ":", "store", "}", ",", "cloudMetadataStore", ":", "cloudMetadataStore", ",", "store", ":", "store", ",", "newClientConfigReader", ":", "func", "(", "caasType", "string", ")", "(", "clientconfig", ".", "ClientConfigFunc", ",", "error", ")", "{", "return", "clientconfig", ".", "NewClientConfigReader", "(", "caasType", ")", "\n", "}", ",", "}", "\n", "cmd", ".", "addCloudAPIFunc", "=", "func", "(", ")", "(", "AddCloudAPI", ",", "error", ")", "{", "root", ",", "err", ":=", "cmd", ".", "NewAPIRoot", "(", "cmd", ".", "store", ",", "cmd", ".", "controllerName", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "cloudapi", ".", "NewClient", "(", "root", ")", ",", "nil", "\n", "}", "\n\n", "cmd", ".", "brokerGetter", "=", "cmd", ".", "newK8sClusterBroker", "\n", "cmd", ".", "getAllCloudDetails", "=", "jujucmdcloud", ".", "GetAllCloudDetails", "\n", "return", "modelcmd", ".", "WrapBase", "(", "cmd", ")", "\n", "}" ]
// NewAddCAASCommand returns a command to add caas information.
[ "NewAddCAASCommand", "returns", "a", "command", "to", "add", "caas", "information", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/caas/add.go#L156-L177
4,326
juju/juju
cmd/juju/caas/add.go
getStdinPipe
func getStdinPipe(ctx *cmd.Context) (io.Reader, error) { if stdIn, ok := ctx.Stdin.(*os.File); ok && !terminal.IsTerminal(int(stdIn.Fd())) { // stdIn from pipe but not terminal stat, err := stdIn.Stat() if err != nil { return nil, err } content, err := ioutil.ReadAll(stdIn) if err != nil { return nil, err } if (stat.Mode()&os.ModeCharDevice) == 0 && len(content) > 0 { // workaround to get piped stdIn size because stat.Size() always == 0 return bytes.NewReader(content), nil } } return nil, nil }
go
func getStdinPipe(ctx *cmd.Context) (io.Reader, error) { if stdIn, ok := ctx.Stdin.(*os.File); ok && !terminal.IsTerminal(int(stdIn.Fd())) { // stdIn from pipe but not terminal stat, err := stdIn.Stat() if err != nil { return nil, err } content, err := ioutil.ReadAll(stdIn) if err != nil { return nil, err } if (stat.Mode()&os.ModeCharDevice) == 0 && len(content) > 0 { // workaround to get piped stdIn size because stat.Size() always == 0 return bytes.NewReader(content), nil } } return nil, nil }
[ "func", "getStdinPipe", "(", "ctx", "*", "cmd", ".", "Context", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "if", "stdIn", ",", "ok", ":=", "ctx", ".", "Stdin", ".", "(", "*", "os", ".", "File", ")", ";", "ok", "&&", "!", "terminal", ".", "IsTerminal", "(", "int", "(", "stdIn", ".", "Fd", "(", ")", ")", ")", "{", "// stdIn from pipe but not terminal", "stat", ",", "err", ":=", "stdIn", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "content", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "stdIn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "(", "stat", ".", "Mode", "(", ")", "&", "os", ".", "ModeCharDevice", ")", "==", "0", "&&", "len", "(", "content", ")", ">", "0", "{", "// workaround to get piped stdIn size because stat.Size() always == 0", "return", "bytes", ".", "NewReader", "(", "content", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// getStdinPipe returns nil if the context's stdin is not a pipe.
[ "getStdinPipe", "returns", "nil", "if", "the", "context", "s", "stdin", "is", "not", "a", "pipe", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/caas/add.go#L255-L272
4,327
juju/juju
apiserver/common/unitswatcher.go
NewUnitsWatcher
func NewUnitsWatcher(st state.EntityFinder, resources facade.Resources, getCanWatch GetAuthFunc) *UnitsWatcher { return &UnitsWatcher{ st: st, resources: resources, getCanWatch: getCanWatch, } }
go
func NewUnitsWatcher(st state.EntityFinder, resources facade.Resources, getCanWatch GetAuthFunc) *UnitsWatcher { return &UnitsWatcher{ st: st, resources: resources, getCanWatch: getCanWatch, } }
[ "func", "NewUnitsWatcher", "(", "st", "state", ".", "EntityFinder", ",", "resources", "facade", ".", "Resources", ",", "getCanWatch", "GetAuthFunc", ")", "*", "UnitsWatcher", "{", "return", "&", "UnitsWatcher", "{", "st", ":", "st", ",", "resources", ":", "resources", ",", "getCanWatch", ":", "getCanWatch", ",", "}", "\n", "}" ]
// NewUnitsWatcher returns a new UnitsWatcher. The GetAuthFunc will be // used on each invocation of WatchUnits to determine current // permissions.
[ "NewUnitsWatcher", "returns", "a", "new", "UnitsWatcher", ".", "The", "GetAuthFunc", "will", "be", "used", "on", "each", "invocation", "of", "WatchUnits", "to", "determine", "current", "permissions", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/unitswatcher.go#L27-L33
4,328
juju/juju
upgrades/preupgradesteps.go
PreUpgradeSteps
func PreUpgradeSteps(_ *state.StatePool, agentConf agent.Config, isController, isMaster, isCaas bool) error { if isCaas { logger.Debugf("skipping disk space checks for k8s controllers") return nil } if err := CheckFreeDiskSpace(agentConf.DataDir(), MinDiskSpaceMib); err != nil { return errors.Trace(err) } if isController { // Update distro info in case the new Juju controller version // is aware of new supported series. We'll keep going if this // fails, and the user can manually update it if they need to. logger.Infof("updating distro-info") err := updateDistroInfo() return errors.Annotate(err, "failed to update distro-info") } return nil }
go
func PreUpgradeSteps(_ *state.StatePool, agentConf agent.Config, isController, isMaster, isCaas bool) error { if isCaas { logger.Debugf("skipping disk space checks for k8s controllers") return nil } if err := CheckFreeDiskSpace(agentConf.DataDir(), MinDiskSpaceMib); err != nil { return errors.Trace(err) } if isController { // Update distro info in case the new Juju controller version // is aware of new supported series. We'll keep going if this // fails, and the user can manually update it if they need to. logger.Infof("updating distro-info") err := updateDistroInfo() return errors.Annotate(err, "failed to update distro-info") } return nil }
[ "func", "PreUpgradeSteps", "(", "_", "*", "state", ".", "StatePool", ",", "agentConf", "agent", ".", "Config", ",", "isController", ",", "isMaster", ",", "isCaas", "bool", ")", "error", "{", "if", "isCaas", "{", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n", "if", "err", ":=", "CheckFreeDiskSpace", "(", "agentConf", ".", "DataDir", "(", ")", ",", "MinDiskSpaceMib", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "isController", "{", "// Update distro info in case the new Juju controller version", "// is aware of new supported series. We'll keep going if this", "// fails, and the user can manually update it if they need to.", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "err", ":=", "updateDistroInfo", "(", ")", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// PreUpgradeSteps runs various checks and prepares for performing an upgrade. // If any check fails, an error is returned which aborts the upgrade.
[ "PreUpgradeSteps", "runs", "various", "checks", "and", "prepares", "for", "performing", "an", "upgrade", ".", "If", "any", "check", "fails", "an", "error", "is", "returned", "which", "aborts", "the", "upgrade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/preupgradesteps.go#L24-L41
4,329
juju/juju
upgrades/preupgradesteps.go
CheckFreeDiskSpace
func CheckFreeDiskSpace(dir string, thresholdMib uint64) error { usage := du.NewDiskUsage(dir) available := usage.Available() if available < thresholdMib*humanize.MiByte { return errors.Errorf("not enough free disk space on %q for upgrade: %s available, require %dMiB", dir, humanize.IBytes(available), thresholdMib) } return nil }
go
func CheckFreeDiskSpace(dir string, thresholdMib uint64) error { usage := du.NewDiskUsage(dir) available := usage.Available() if available < thresholdMib*humanize.MiByte { return errors.Errorf("not enough free disk space on %q for upgrade: %s available, require %dMiB", dir, humanize.IBytes(available), thresholdMib) } return nil }
[ "func", "CheckFreeDiskSpace", "(", "dir", "string", ",", "thresholdMib", "uint64", ")", "error", "{", "usage", ":=", "du", ".", "NewDiskUsage", "(", "dir", ")", "\n", "available", ":=", "usage", ".", "Available", "(", ")", "\n", "if", "available", "<", "thresholdMib", "*", "humanize", ".", "MiByte", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "dir", ",", "humanize", ".", "IBytes", "(", "available", ")", ",", "thresholdMib", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckFreeDiskSpace returns a helpful error if there isn't at // least thresholdMib MiB of free space available on the volume // containing dir.
[ "CheckFreeDiskSpace", "returns", "a", "helpful", "error", "if", "there", "isn", "t", "at", "least", "thresholdMib", "MiB", "of", "free", "space", "available", "on", "the", "volume", "containing", "dir", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/preupgradesteps.go#L50-L58
4,330
juju/juju
payload/status.go
ValidateState
func ValidateState(state string) error { if !okayStates.Contains(state) { supported := okayStates.Values() sort.Strings(supported) states := strings.Join(supported, `", "`) msg := fmt.Sprintf(`status %q not supported; expected one of ["%s"]`, state, states) return errors.NewNotValid(nil, msg) } return nil }
go
func ValidateState(state string) error { if !okayStates.Contains(state) { supported := okayStates.Values() sort.Strings(supported) states := strings.Join(supported, `", "`) msg := fmt.Sprintf(`status %q not supported; expected one of ["%s"]`, state, states) return errors.NewNotValid(nil, msg) } return nil }
[ "func", "ValidateState", "(", "state", "string", ")", "error", "{", "if", "!", "okayStates", ".", "Contains", "(", "state", ")", "{", "supported", ":=", "okayStates", ".", "Values", "(", ")", "\n", "sort", ".", "Strings", "(", "supported", ")", "\n", "states", ":=", "strings", ".", "Join", "(", "supported", ",", "`\", \"`", ")", "\n", "msg", ":=", "fmt", ".", "Sprintf", "(", "`status %q not supported; expected one of [\"%s\"]`", ",", "state", ",", "states", ")", "\n", "return", "errors", ".", "NewNotValid", "(", "nil", ",", "msg", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateState verifies the state passed in is a valid okayState.
[ "ValidateState", "verifies", "the", "state", "passed", "in", "is", "a", "valid", "okayState", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/status.go#L34-L43
4,331
juju/juju
apiserver/facades/client/backups/backups.go
NewAPI
func NewAPI(backend Backend, resources facade.Resources, authorizer facade.Authorizer) (*API, error) { isControllerAdmin, err := authorizer.HasPermission(permission.SuperuserAccess, backend.ControllerTag()) if err != nil && !errors.IsNotFound(err) { return nil, errors.Trace(err) } if !authorizer.AuthClient() || !isControllerAdmin { return nil, common.ErrPerm } // For now, backup operations are only permitted on the controller model. if !backend.IsController() { return nil, errors.New("backups are only supported from the controller model\nUse juju switch to select the controller model") } if backend.ModelType() == state.ModelTypeCAAS { return nil, errors.NotSupportedf("backups on kubernetes controllers") } // Get the backup paths. dataDir, err := extractResourceValue(resources, "dataDir") if err != nil { return nil, errors.Trace(err) } logsDir, err := extractResourceValue(resources, "logDir") if err != nil { return nil, errors.Trace(err) } config, err := backend.ModelConfig() if err != nil { return nil, errors.Trace(err) } backupDir := config.BackupDir() paths := backups.Paths{ BackupDir: backupDir, DataDir: dataDir, LogsDir: logsDir, } // Build the API. machineID, err := extractResourceValue(resources, "machineID") if err != nil { return nil, errors.Trace(err) } b := API{ backend: backend, paths: &paths, machineID: machineID, } return &b, nil }
go
func NewAPI(backend Backend, resources facade.Resources, authorizer facade.Authorizer) (*API, error) { isControllerAdmin, err := authorizer.HasPermission(permission.SuperuserAccess, backend.ControllerTag()) if err != nil && !errors.IsNotFound(err) { return nil, errors.Trace(err) } if !authorizer.AuthClient() || !isControllerAdmin { return nil, common.ErrPerm } // For now, backup operations are only permitted on the controller model. if !backend.IsController() { return nil, errors.New("backups are only supported from the controller model\nUse juju switch to select the controller model") } if backend.ModelType() == state.ModelTypeCAAS { return nil, errors.NotSupportedf("backups on kubernetes controllers") } // Get the backup paths. dataDir, err := extractResourceValue(resources, "dataDir") if err != nil { return nil, errors.Trace(err) } logsDir, err := extractResourceValue(resources, "logDir") if err != nil { return nil, errors.Trace(err) } config, err := backend.ModelConfig() if err != nil { return nil, errors.Trace(err) } backupDir := config.BackupDir() paths := backups.Paths{ BackupDir: backupDir, DataDir: dataDir, LogsDir: logsDir, } // Build the API. machineID, err := extractResourceValue(resources, "machineID") if err != nil { return nil, errors.Trace(err) } b := API{ backend: backend, paths: &paths, machineID: machineID, } return &b, nil }
[ "func", "NewAPI", "(", "backend", "Backend", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ")", "(", "*", "API", ",", "error", ")", "{", "isControllerAdmin", ",", "err", ":=", "authorizer", ".", "HasPermission", "(", "permission", ".", "SuperuserAccess", ",", "backend", ".", "ControllerTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "!", "authorizer", ".", "AuthClient", "(", ")", "||", "!", "isControllerAdmin", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n\n", "// For now, backup operations are only permitted on the controller model.", "if", "!", "backend", ".", "IsController", "(", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n\n", "if", "backend", ".", "ModelType", "(", ")", "==", "state", ".", "ModelTypeCAAS", "{", "return", "nil", ",", "errors", ".", "NotSupportedf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Get the backup paths.", "dataDir", ",", "err", ":=", "extractResourceValue", "(", "resources", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logsDir", ",", "err", ":=", "extractResourceValue", "(", "resources", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "config", ",", "err", ":=", "backend", ".", "ModelConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "backupDir", ":=", "config", ".", "BackupDir", "(", ")", "\n\n", "paths", ":=", "backups", ".", "Paths", "{", "BackupDir", ":", "backupDir", ",", "DataDir", ":", "dataDir", ",", "LogsDir", ":", "logsDir", ",", "}", "\n\n", "// Build the API.", "machineID", ",", "err", ":=", "extractResourceValue", "(", "resources", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "b", ":=", "API", "{", "backend", ":", "backend", ",", "paths", ":", "&", "paths", ",", "machineID", ":", "machineID", ",", "}", "\n", "return", "&", "b", ",", "nil", "\n", "}" ]
// NewAPI creates a new instance of the Backups API facade.
[ "NewAPI", "creates", "a", "new", "instance", "of", "the", "Backups", "API", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/backups/backups.go#L65-L117
4,332
juju/juju
apiserver/facades/client/backups/backups.go
CreateResult
func CreateResult(meta *backups.Metadata, filename string) params.BackupsMetadataResult { var result params.BackupsMetadataResult result.ID = meta.ID() result.Checksum = meta.Checksum() result.ChecksumFormat = meta.ChecksumFormat() result.Size = meta.Size() if meta.Stored() != nil { result.Stored = *(meta.Stored()) } result.Started = meta.Started if meta.Finished != nil { result.Finished = *meta.Finished } result.Notes = meta.Notes result.Model = meta.Origin.Model result.Machine = meta.Origin.Machine result.Hostname = meta.Origin.Hostname result.Version = meta.Origin.Version result.Series = meta.Origin.Series // TODO(wallyworld) - remove these ASAP // These are only used by the restore CLI when re-bootstrapping. // We will use a better solution but the way restore currently // works, we need them and they are no longer available via // bootstrap config. We will need to fix how re-bootstrap deals // with these keys to address the issue. result.CACert = meta.CACert result.CAPrivateKey = meta.CAPrivateKey result.Filename = filename return result }
go
func CreateResult(meta *backups.Metadata, filename string) params.BackupsMetadataResult { var result params.BackupsMetadataResult result.ID = meta.ID() result.Checksum = meta.Checksum() result.ChecksumFormat = meta.ChecksumFormat() result.Size = meta.Size() if meta.Stored() != nil { result.Stored = *(meta.Stored()) } result.Started = meta.Started if meta.Finished != nil { result.Finished = *meta.Finished } result.Notes = meta.Notes result.Model = meta.Origin.Model result.Machine = meta.Origin.Machine result.Hostname = meta.Origin.Hostname result.Version = meta.Origin.Version result.Series = meta.Origin.Series // TODO(wallyworld) - remove these ASAP // These are only used by the restore CLI when re-bootstrapping. // We will use a better solution but the way restore currently // works, we need them and they are no longer available via // bootstrap config. We will need to fix how re-bootstrap deals // with these keys to address the issue. result.CACert = meta.CACert result.CAPrivateKey = meta.CAPrivateKey result.Filename = filename return result }
[ "func", "CreateResult", "(", "meta", "*", "backups", ".", "Metadata", ",", "filename", "string", ")", "params", ".", "BackupsMetadataResult", "{", "var", "result", "params", ".", "BackupsMetadataResult", "\n\n", "result", ".", "ID", "=", "meta", ".", "ID", "(", ")", "\n\n", "result", ".", "Checksum", "=", "meta", ".", "Checksum", "(", ")", "\n", "result", ".", "ChecksumFormat", "=", "meta", ".", "ChecksumFormat", "(", ")", "\n", "result", ".", "Size", "=", "meta", ".", "Size", "(", ")", "\n", "if", "meta", ".", "Stored", "(", ")", "!=", "nil", "{", "result", ".", "Stored", "=", "*", "(", "meta", ".", "Stored", "(", ")", ")", "\n", "}", "\n\n", "result", ".", "Started", "=", "meta", ".", "Started", "\n", "if", "meta", ".", "Finished", "!=", "nil", "{", "result", ".", "Finished", "=", "*", "meta", ".", "Finished", "\n", "}", "\n", "result", ".", "Notes", "=", "meta", ".", "Notes", "\n\n", "result", ".", "Model", "=", "meta", ".", "Origin", ".", "Model", "\n", "result", ".", "Machine", "=", "meta", ".", "Origin", ".", "Machine", "\n", "result", ".", "Hostname", "=", "meta", ".", "Origin", ".", "Hostname", "\n", "result", ".", "Version", "=", "meta", ".", "Origin", ".", "Version", "\n", "result", ".", "Series", "=", "meta", ".", "Origin", ".", "Series", "\n\n", "// TODO(wallyworld) - remove these ASAP", "// These are only used by the restore CLI when re-bootstrapping.", "// We will use a better solution but the way restore currently", "// works, we need them and they are no longer available via", "// bootstrap config. We will need to fix how re-bootstrap deals", "// with these keys to address the issue.", "result", ".", "CACert", "=", "meta", ".", "CACert", "\n", "result", ".", "CAPrivateKey", "=", "meta", ".", "CAPrivateKey", "\n", "result", ".", "Filename", "=", "filename", "\n\n", "return", "result", "\n", "}" ]
// CreateResult updates the result with the information in the // metadata value.
[ "CreateResult", "updates", "the", "result", "with", "the", "information", "in", "the", "metadata", "value", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/backups/backups.go#L139-L174
4,333
juju/juju
apiserver/facades/agent/instancemutater/instancemutater.go
NewInstanceMutaterAPI
func NewInstanceMutaterAPI(st InstanceMutaterState, model ModelCache, resources facade.Resources, authorizer facade.Authorizer, ) (*InstanceMutaterAPI, error) { if !authorizer.AuthMachineAgent() && !authorizer.AuthController() { return nil, common.ErrPerm } getAuthFunc := common.AuthFuncForMachineAgent(authorizer) return &InstanceMutaterAPI{ LifeGetter: common.NewLifeGetter(st, getAuthFunc), st: st, model: model, resources: resources, authorizer: authorizer, getAuthFunc: getAuthFunc, }, nil }
go
func NewInstanceMutaterAPI(st InstanceMutaterState, model ModelCache, resources facade.Resources, authorizer facade.Authorizer, ) (*InstanceMutaterAPI, error) { if !authorizer.AuthMachineAgent() && !authorizer.AuthController() { return nil, common.ErrPerm } getAuthFunc := common.AuthFuncForMachineAgent(authorizer) return &InstanceMutaterAPI{ LifeGetter: common.NewLifeGetter(st, getAuthFunc), st: st, model: model, resources: resources, authorizer: authorizer, getAuthFunc: getAuthFunc, }, nil }
[ "func", "NewInstanceMutaterAPI", "(", "st", "InstanceMutaterState", ",", "model", "ModelCache", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ",", ")", "(", "*", "InstanceMutaterAPI", ",", "error", ")", "{", "if", "!", "authorizer", ".", "AuthMachineAgent", "(", ")", "&&", "!", "authorizer", ".", "AuthController", "(", ")", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n\n", "getAuthFunc", ":=", "common", ".", "AuthFuncForMachineAgent", "(", "authorizer", ")", "\n", "return", "&", "InstanceMutaterAPI", "{", "LifeGetter", ":", "common", ".", "NewLifeGetter", "(", "st", ",", "getAuthFunc", ")", ",", "st", ":", "st", ",", "model", ":", "model", ",", "resources", ":", "resources", ",", "authorizer", ":", "authorizer", ",", "getAuthFunc", ":", "getAuthFunc", ",", "}", ",", "nil", "\n", "}" ]
// NewInstanceMutaterAPI creates a new API server endpoint for managing // charm profiles on juju lxd machines and containers.
[ "NewInstanceMutaterAPI", "creates", "a", "new", "API", "server", "endpoint", "for", "managing", "charm", "profiles", "on", "juju", "lxd", "machines", "and", "containers", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/instancemutater.go#L68-L86
4,334
juju/juju
apiserver/facades/agent/instancemutater/instancemutater.go
CharmProfilingInfo
func (api *InstanceMutaterAPI) CharmProfilingInfo(arg params.Entity) (params.CharmProfilingInfoResult, error) { result := params.CharmProfilingInfoResult{ ProfileChanges: make([]params.ProfileInfoResult, 0), } canAccess, err := api.getAuthFunc() if err != nil { return params.CharmProfilingInfoResult{}, errors.Trace(err) } tag, err := names.ParseMachineTag(arg.Tag) if err != nil { result.Error = common.ServerError(common.ErrPerm) return result, nil } m, err := api.getCacheMachine(canAccess, tag) if err != nil { result.Error = common.ServerError(err) return result, nil } lxdProfileInfo, err := api.machineLXDProfileInfo(m) if err != nil { result.Error = common.ServerError(errors.Annotatef(err, "%s", tag)) } // use the results from the machineLXDProfileInfo and apply them to the // result result.InstanceId = lxdProfileInfo.InstanceId result.ModelName = lxdProfileInfo.ModelName result.CurrentProfiles = lxdProfileInfo.MachineProfiles result.ProfileChanges = lxdProfileInfo.ProfileUnits return result, nil }
go
func (api *InstanceMutaterAPI) CharmProfilingInfo(arg params.Entity) (params.CharmProfilingInfoResult, error) { result := params.CharmProfilingInfoResult{ ProfileChanges: make([]params.ProfileInfoResult, 0), } canAccess, err := api.getAuthFunc() if err != nil { return params.CharmProfilingInfoResult{}, errors.Trace(err) } tag, err := names.ParseMachineTag(arg.Tag) if err != nil { result.Error = common.ServerError(common.ErrPerm) return result, nil } m, err := api.getCacheMachine(canAccess, tag) if err != nil { result.Error = common.ServerError(err) return result, nil } lxdProfileInfo, err := api.machineLXDProfileInfo(m) if err != nil { result.Error = common.ServerError(errors.Annotatef(err, "%s", tag)) } // use the results from the machineLXDProfileInfo and apply them to the // result result.InstanceId = lxdProfileInfo.InstanceId result.ModelName = lxdProfileInfo.ModelName result.CurrentProfiles = lxdProfileInfo.MachineProfiles result.ProfileChanges = lxdProfileInfo.ProfileUnits return result, nil }
[ "func", "(", "api", "*", "InstanceMutaterAPI", ")", "CharmProfilingInfo", "(", "arg", "params", ".", "Entity", ")", "(", "params", ".", "CharmProfilingInfoResult", ",", "error", ")", "{", "result", ":=", "params", ".", "CharmProfilingInfoResult", "{", "ProfileChanges", ":", "make", "(", "[", "]", "params", ".", "ProfileInfoResult", ",", "0", ")", ",", "}", "\n", "canAccess", ",", "err", ":=", "api", ".", "getAuthFunc", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "CharmProfilingInfoResult", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "tag", ",", "err", ":=", "names", ".", "ParseMachineTag", "(", "arg", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "return", "result", ",", "nil", "\n", "}", "\n", "m", ",", "err", ":=", "api", ".", "getCacheMachine", "(", "canAccess", ",", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "return", "result", ",", "nil", "\n", "}", "\n", "lxdProfileInfo", ",", "err", ":=", "api", ".", "machineLXDProfileInfo", "(", "m", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Error", "=", "common", ".", "ServerError", "(", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "tag", ")", ")", "\n", "}", "\n\n", "// use the results from the machineLXDProfileInfo and apply them to the", "// result", "result", ".", "InstanceId", "=", "lxdProfileInfo", ".", "InstanceId", "\n", "result", ".", "ModelName", "=", "lxdProfileInfo", ".", "ModelName", "\n", "result", ".", "CurrentProfiles", "=", "lxdProfileInfo", ".", "MachineProfiles", "\n", "result", ".", "ProfileChanges", "=", "lxdProfileInfo", ".", "ProfileUnits", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// CharmProfilingInfo returns info to update lxd profiles on the machine. If // the machine is not provisioned, no profile change info will be returned, // nor will an error.
[ "CharmProfilingInfo", "returns", "info", "to", "update", "lxd", "profiles", "on", "the", "machine", ".", "If", "the", "machine", "is", "not", "provisioned", "no", "profile", "change", "info", "will", "be", "returned", "nor", "will", "an", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/instancemutater.go#L91-L122
4,335
juju/juju
apiserver/facades/agent/instancemutater/instancemutater.go
SetCharmProfiles
func (api *InstanceMutaterAPI) SetCharmProfiles(args params.SetProfileArgs) (params.ErrorResults, error) { results := make([]params.ErrorResult, len(args.Args)) canAccess, err := api.getAuthFunc() if err != nil { return params.ErrorResults{}, errors.Trace(err) } for i, a := range args.Args { err := api.setOneMachineCharmProfiles(a.Entity.Tag, a.Profiles, canAccess) results[i].Error = common.ServerError(err) } return params.ErrorResults{Results: results}, nil }
go
func (api *InstanceMutaterAPI) SetCharmProfiles(args params.SetProfileArgs) (params.ErrorResults, error) { results := make([]params.ErrorResult, len(args.Args)) canAccess, err := api.getAuthFunc() if err != nil { return params.ErrorResults{}, errors.Trace(err) } for i, a := range args.Args { err := api.setOneMachineCharmProfiles(a.Entity.Tag, a.Profiles, canAccess) results[i].Error = common.ServerError(err) } return params.ErrorResults{Results: results}, nil }
[ "func", "(", "api", "*", "InstanceMutaterAPI", ")", "SetCharmProfiles", "(", "args", "params", ".", "SetProfileArgs", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "results", ":=", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Args", ")", ")", "\n", "canAccess", ",", "err", ":=", "api", ".", "getAuthFunc", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "i", ",", "a", ":=", "range", "args", ".", "Args", "{", "err", ":=", "api", ".", "setOneMachineCharmProfiles", "(", "a", ".", "Entity", ".", "Tag", ",", "a", ".", "Profiles", ",", "canAccess", ")", "\n", "results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "params", ".", "ErrorResults", "{", "Results", ":", "results", "}", ",", "nil", "\n", "}" ]
// SetCharmProfiles records the given slice of charm profile names.
[ "SetCharmProfiles", "records", "the", "given", "slice", "of", "charm", "profile", "names", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/instancemutater.go#L148-L159
4,336
juju/juju
apiserver/facades/agent/instancemutater/instancemutater.go
WatchMachines
func (api *InstanceMutaterAPI) WatchMachines() (params.StringsWatchResult, error) { result := params.StringsWatchResult{} if !api.authorizer.AuthController() { return result, common.ErrPerm } watch, err := api.model.WatchMachines() if err != nil { return result, err } if changes, ok := <-watch.Changes(); ok { result.StringsWatcherId = api.resources.Register(watch) result.Changes = changes } else { return result, errors.Errorf("cannot obtain initial model machines") } return result, nil }
go
func (api *InstanceMutaterAPI) WatchMachines() (params.StringsWatchResult, error) { result := params.StringsWatchResult{} if !api.authorizer.AuthController() { return result, common.ErrPerm } watch, err := api.model.WatchMachines() if err != nil { return result, err } if changes, ok := <-watch.Changes(); ok { result.StringsWatcherId = api.resources.Register(watch) result.Changes = changes } else { return result, errors.Errorf("cannot obtain initial model machines") } return result, nil }
[ "func", "(", "api", "*", "InstanceMutaterAPI", ")", "WatchMachines", "(", ")", "(", "params", ".", "StringsWatchResult", ",", "error", ")", "{", "result", ":=", "params", ".", "StringsWatchResult", "{", "}", "\n", "if", "!", "api", ".", "authorizer", ".", "AuthController", "(", ")", "{", "return", "result", ",", "common", ".", "ErrPerm", "\n", "}", "\n\n", "watch", ",", "err", ":=", "api", ".", "model", ".", "WatchMachines", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n", "if", "changes", ",", "ok", ":=", "<-", "watch", ".", "Changes", "(", ")", ";", "ok", "{", "result", ".", "StringsWatcherId", "=", "api", ".", "resources", ".", "Register", "(", "watch", ")", "\n", "result", ".", "Changes", "=", "changes", "\n", "}", "else", "{", "return", "result", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// WatchMachines starts a watcher to track machines. // WatchMachines does not consume the initial event of the watch response, as // that returns the initial set of machines that are currently available.
[ "WatchMachines", "starts", "a", "watcher", "to", "track", "machines", ".", "WatchMachines", "does", "not", "consume", "the", "initial", "event", "of", "the", "watch", "response", "as", "that", "returns", "the", "initial", "set", "of", "machines", "that", "are", "currently", "available", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/instancemutater.go#L164-L181
4,337
juju/juju
apiserver/facades/agent/instancemutater/instancemutater.go
WatchContainers
func (api *InstanceMutaterAPI) WatchContainers(arg params.Entity) (params.StringsWatchResult, error) { result := params.StringsWatchResult{} canAccess, err := api.getAuthFunc() if err != nil { return result, errors.Trace(err) } tag, err := names.ParseMachineTag(arg.Tag) if err != nil { return result, errors.Trace(err) } machine, err := api.getCacheMachine(canAccess, tag) if err != nil { return result, err } watch, err := machine.WatchContainers() if err != nil { return result, err } if changes, ok := <-watch.Changes(); ok { result.StringsWatcherId = api.resources.Register(watch) result.Changes = changes } else { return result, errors.Errorf("cannot obtain initial machine containers") } return result, nil }
go
func (api *InstanceMutaterAPI) WatchContainers(arg params.Entity) (params.StringsWatchResult, error) { result := params.StringsWatchResult{} canAccess, err := api.getAuthFunc() if err != nil { return result, errors.Trace(err) } tag, err := names.ParseMachineTag(arg.Tag) if err != nil { return result, errors.Trace(err) } machine, err := api.getCacheMachine(canAccess, tag) if err != nil { return result, err } watch, err := machine.WatchContainers() if err != nil { return result, err } if changes, ok := <-watch.Changes(); ok { result.StringsWatcherId = api.resources.Register(watch) result.Changes = changes } else { return result, errors.Errorf("cannot obtain initial machine containers") } return result, nil }
[ "func", "(", "api", "*", "InstanceMutaterAPI", ")", "WatchContainers", "(", "arg", "params", ".", "Entity", ")", "(", "params", ".", "StringsWatchResult", ",", "error", ")", "{", "result", ":=", "params", ".", "StringsWatchResult", "{", "}", "\n", "canAccess", ",", "err", ":=", "api", ".", "getAuthFunc", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "tag", ",", "err", ":=", "names", ".", "ParseMachineTag", "(", "arg", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "machine", ",", "err", ":=", "api", ".", "getCacheMachine", "(", "canAccess", ",", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n", "watch", ",", "err", ":=", "machine", ".", "WatchContainers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n", "if", "changes", ",", "ok", ":=", "<-", "watch", ".", "Changes", "(", ")", ";", "ok", "{", "result", ".", "StringsWatcherId", "=", "api", ".", "resources", ".", "Register", "(", "watch", ")", "\n", "result", ".", "Changes", "=", "changes", "\n", "}", "else", "{", "return", "result", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// WatchContainers starts a watcher to track Containers on a given // machine.
[ "WatchContainers", "starts", "a", "watcher", "to", "track", "Containers", "on", "a", "given", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/instancemutater.go#L185-L210
4,338
juju/juju
apiserver/facades/agent/instancemutater/instancemutater.go
WatchLXDProfileVerificationNeeded
func (api *InstanceMutaterAPI) WatchLXDProfileVerificationNeeded(args params.Entities) (params.NotifyWatchResults, error) { result := params.NotifyWatchResults{ Results: make([]params.NotifyWatchResult, len(args.Entities)), } if len(args.Entities) == 0 { return result, nil } canAccess, err := api.getAuthFunc() if err != nil { return result, errors.Trace(err) } for i, entity := range args.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } entityResult, err := api.watchOneEntityApplication(canAccess, tag) result.Results[i] = entityResult result.Results[i].Error = common.ServerError(err) } return result, nil }
go
func (api *InstanceMutaterAPI) WatchLXDProfileVerificationNeeded(args params.Entities) (params.NotifyWatchResults, error) { result := params.NotifyWatchResults{ Results: make([]params.NotifyWatchResult, len(args.Entities)), } if len(args.Entities) == 0 { return result, nil } canAccess, err := api.getAuthFunc() if err != nil { return result, errors.Trace(err) } for i, entity := range args.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } entityResult, err := api.watchOneEntityApplication(canAccess, tag) result.Results[i] = entityResult result.Results[i].Error = common.ServerError(err) } return result, nil }
[ "func", "(", "api", "*", "InstanceMutaterAPI", ")", "WatchLXDProfileVerificationNeeded", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "NotifyWatchResults", ",", "error", ")", "{", "result", ":=", "params", ".", "NotifyWatchResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "NotifyWatchResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "if", "len", "(", "args", ".", "Entities", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n", "canAccess", ",", "err", ":=", "api", ".", "getAuthFunc", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseMachineTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "entityResult", ",", "err", ":=", "api", ".", "watchOneEntityApplication", "(", "canAccess", ",", "tag", ")", "\n", "result", ".", "Results", "[", "i", "]", "=", "entityResult", "\n", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// WatchLXDProfileVerificationNeeded starts a watcher to track Applications with // LXD Profiles.
[ "WatchLXDProfileVerificationNeeded", "starts", "a", "watcher", "to", "track", "Applications", "with", "LXD", "Profiles", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/instancemutater.go#L214-L236
4,339
juju/juju
cmd/juju/controller/killstatus.go
newTimedStatusUpdater
func newTimedStatusUpdater(ctx *cmd.Context, api destroyControllerAPI, controllerModelUUID string, clock clock.Clock) func(time.Duration) environmentStatus { return func(wait time.Duration) environmentStatus { if wait > 0 { <-clock.After(wait) } // If we hit an error, status.HostedModelCount will be 0, the polling // loop will stop and we'll go directly to destroying the model. ctrStatus, modelsStatus, err := newData(api, controllerModelUUID) if err != nil { ctx.Infof("Unable to get the controller summary from the API: %s.", err) } return environmentStatus{ controller: ctrStatus, models: modelsStatus, } } }
go
func newTimedStatusUpdater(ctx *cmd.Context, api destroyControllerAPI, controllerModelUUID string, clock clock.Clock) func(time.Duration) environmentStatus { return func(wait time.Duration) environmentStatus { if wait > 0 { <-clock.After(wait) } // If we hit an error, status.HostedModelCount will be 0, the polling // loop will stop and we'll go directly to destroying the model. ctrStatus, modelsStatus, err := newData(api, controllerModelUUID) if err != nil { ctx.Infof("Unable to get the controller summary from the API: %s.", err) } return environmentStatus{ controller: ctrStatus, models: modelsStatus, } } }
[ "func", "newTimedStatusUpdater", "(", "ctx", "*", "cmd", ".", "Context", ",", "api", "destroyControllerAPI", ",", "controllerModelUUID", "string", ",", "clock", "clock", ".", "Clock", ")", "func", "(", "time", ".", "Duration", ")", "environmentStatus", "{", "return", "func", "(", "wait", "time", ".", "Duration", ")", "environmentStatus", "{", "if", "wait", ">", "0", "{", "<-", "clock", ".", "After", "(", "wait", ")", "\n", "}", "\n\n", "// If we hit an error, status.HostedModelCount will be 0, the polling", "// loop will stop and we'll go directly to destroying the model.", "ctrStatus", ",", "modelsStatus", ",", "err", ":=", "newData", "(", "api", ",", "controllerModelUUID", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "environmentStatus", "{", "controller", ":", "ctrStatus", ",", "models", ":", "modelsStatus", ",", "}", "\n", "}", "\n", "}" ]
// newTimedStatusUpdater returns a function which waits a given period of time // before querying the apiserver for updated data.
[ "newTimedStatusUpdater", "returns", "a", "function", "which", "waits", "a", "given", "period", "of", "time", "before", "querying", "the", "apiserver", "for", "updated", "data", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/killstatus.go#L53-L71
4,340
juju/juju
apiserver/common/cloudspec/statehelpers.go
MakeCloudSpecGetter
func MakeCloudSpecGetter(pool Pool) func(names.ModelTag) (environs.CloudSpec, error) { return func(tag names.ModelTag) (environs.CloudSpec, error) { st, err := pool.Get(tag.Id()) if err != nil { return environs.CloudSpec{}, errors.Trace(err) } defer st.Release() m, err := st.Model() if err != nil { return environs.CloudSpec{}, errors.Trace(err) } // TODO - CAAS(externalreality): Once cloud methods are migrated // to model EnvironConfigGetter will no longer need to contain // both state and model but only model. // TODO (manadart 2018-02-15): This potentially frees the state from // the pool. Release is called, but the state reference survives. return stateenvirons.EnvironConfigGetter{State: st.State, Model: m}.CloudSpec() } }
go
func MakeCloudSpecGetter(pool Pool) func(names.ModelTag) (environs.CloudSpec, error) { return func(tag names.ModelTag) (environs.CloudSpec, error) { st, err := pool.Get(tag.Id()) if err != nil { return environs.CloudSpec{}, errors.Trace(err) } defer st.Release() m, err := st.Model() if err != nil { return environs.CloudSpec{}, errors.Trace(err) } // TODO - CAAS(externalreality): Once cloud methods are migrated // to model EnvironConfigGetter will no longer need to contain // both state and model but only model. // TODO (manadart 2018-02-15): This potentially frees the state from // the pool. Release is called, but the state reference survives. return stateenvirons.EnvironConfigGetter{State: st.State, Model: m}.CloudSpec() } }
[ "func", "MakeCloudSpecGetter", "(", "pool", "Pool", ")", "func", "(", "names", ".", "ModelTag", ")", "(", "environs", ".", "CloudSpec", ",", "error", ")", "{", "return", "func", "(", "tag", "names", ".", "ModelTag", ")", "(", "environs", ".", "CloudSpec", ",", "error", ")", "{", "st", ",", "err", ":=", "pool", ".", "Get", "(", "tag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "environs", ".", "CloudSpec", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "st", ".", "Release", "(", ")", "\n\n", "m", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "environs", ".", "CloudSpec", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// TODO - CAAS(externalreality): Once cloud methods are migrated", "// to model EnvironConfigGetter will no longer need to contain", "// both state and model but only model.", "// TODO (manadart 2018-02-15): This potentially frees the state from", "// the pool. Release is called, but the state reference survives.", "return", "stateenvirons", ".", "EnvironConfigGetter", "{", "State", ":", "st", ".", "State", ",", "Model", ":", "m", "}", ".", "CloudSpec", "(", ")", "\n", "}", "\n", "}" ]
// MakeCloudSpecGetter returns a function which returns a CloudSpec // for a given model, using the given Pool.
[ "MakeCloudSpecGetter", "returns", "a", "function", "which", "returns", "a", "CloudSpec", "for", "a", "given", "model", "using", "the", "given", "Pool", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/cloudspec/statehelpers.go#L23-L42
4,341
juju/juju
apiserver/common/cloudspec/statehelpers.go
MakeCloudSpecGetterForModel
func MakeCloudSpecGetterForModel(st *state.State) func(names.ModelTag) (environs.CloudSpec, error) { return func(tag names.ModelTag) (environs.CloudSpec, error) { m, err := st.Model() if err != nil { return environs.CloudSpec{}, errors.Trace(err) } configGetter := stateenvirons.EnvironConfigGetter{State: st, Model: m} if tag.Id() != st.ModelUUID() { return environs.CloudSpec{}, errors.New("cannot get cloud spec for this model") } return configGetter.CloudSpec() } }
go
func MakeCloudSpecGetterForModel(st *state.State) func(names.ModelTag) (environs.CloudSpec, error) { return func(tag names.ModelTag) (environs.CloudSpec, error) { m, err := st.Model() if err != nil { return environs.CloudSpec{}, errors.Trace(err) } configGetter := stateenvirons.EnvironConfigGetter{State: st, Model: m} if tag.Id() != st.ModelUUID() { return environs.CloudSpec{}, errors.New("cannot get cloud spec for this model") } return configGetter.CloudSpec() } }
[ "func", "MakeCloudSpecGetterForModel", "(", "st", "*", "state", ".", "State", ")", "func", "(", "names", ".", "ModelTag", ")", "(", "environs", ".", "CloudSpec", ",", "error", ")", "{", "return", "func", "(", "tag", "names", ".", "ModelTag", ")", "(", "environs", ".", "CloudSpec", ",", "error", ")", "{", "m", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "environs", ".", "CloudSpec", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "configGetter", ":=", "stateenvirons", ".", "EnvironConfigGetter", "{", "State", ":", "st", ",", "Model", ":", "m", "}", "\n\n", "if", "tag", ".", "Id", "(", ")", "!=", "st", ".", "ModelUUID", "(", ")", "{", "return", "environs", ".", "CloudSpec", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "configGetter", ".", "CloudSpec", "(", ")", "\n", "}", "\n", "}" ]
// MakeCloudSpecGetterForModel returns a function which returns a // CloudSpec for a single model. Attempts to request a CloudSpec for // any other model other than the one associated with the given // state.State results in an error.
[ "MakeCloudSpecGetterForModel", "returns", "a", "function", "which", "returns", "a", "CloudSpec", "for", "a", "single", "model", ".", "Attempts", "to", "request", "a", "CloudSpec", "for", "any", "other", "model", "other", "than", "the", "one", "associated", "with", "the", "given", "state", ".", "State", "results", "in", "an", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/cloudspec/statehelpers.go#L48-L61
4,342
juju/juju
apiserver/common/cloudspec/statehelpers.go
MakeCloudSpecWatcherForModel
func MakeCloudSpecWatcherForModel(st *state.State) func(names.ModelTag) (state.NotifyWatcher, error) { return func(tag names.ModelTag) (state.NotifyWatcher, error) { m, err := st.Model() if err != nil { return nil, errors.Trace(err) } if tag.Id() != st.ModelUUID() { return nil, errors.New("cannot get cloud spec for this model") } return m.WatchCloudSpecChanges(), nil } }
go
func MakeCloudSpecWatcherForModel(st *state.State) func(names.ModelTag) (state.NotifyWatcher, error) { return func(tag names.ModelTag) (state.NotifyWatcher, error) { m, err := st.Model() if err != nil { return nil, errors.Trace(err) } if tag.Id() != st.ModelUUID() { return nil, errors.New("cannot get cloud spec for this model") } return m.WatchCloudSpecChanges(), nil } }
[ "func", "MakeCloudSpecWatcherForModel", "(", "st", "*", "state", ".", "State", ")", "func", "(", "names", ".", "ModelTag", ")", "(", "state", ".", "NotifyWatcher", ",", "error", ")", "{", "return", "func", "(", "tag", "names", ".", "ModelTag", ")", "(", "state", ".", "NotifyWatcher", ",", "error", ")", "{", "m", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "tag", ".", "Id", "(", ")", "!=", "st", ".", "ModelUUID", "(", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "m", ".", "WatchCloudSpecChanges", "(", ")", ",", "nil", "\n", "}", "\n", "}" ]
// MakeCloudSpecWatcherForModel returns a function which returns a // NotifyWatcher for cloud spec changes for a single model. // Attempts to request a watcher for any other model other than the // one associated with the given state.State results in an error.
[ "MakeCloudSpecWatcherForModel", "returns", "a", "function", "which", "returns", "a", "NotifyWatcher", "for", "cloud", "spec", "changes", "for", "a", "single", "model", ".", "Attempts", "to", "request", "a", "watcher", "for", "any", "other", "model", "other", "than", "the", "one", "associated", "with", "the", "given", "state", ".", "State", "results", "in", "an", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/cloudspec/statehelpers.go#L67-L78
4,343
juju/juju
core/model/upgradeseries.go
ValidateUpgradeSeriesStatus
func ValidateUpgradeSeriesStatus(status UpgradeSeriesStatus) (UpgradeSeriesStatus, error) { if _, ok := UpgradeSeriesStatusOrder[status]; !ok { return UpgradeSeriesNotStarted, errors.NotValidf("upgrade series status of %q is", status) } return status, nil }
go
func ValidateUpgradeSeriesStatus(status UpgradeSeriesStatus) (UpgradeSeriesStatus, error) { if _, ok := UpgradeSeriesStatusOrder[status]; !ok { return UpgradeSeriesNotStarted, errors.NotValidf("upgrade series status of %q is", status) } return status, nil }
[ "func", "ValidateUpgradeSeriesStatus", "(", "status", "UpgradeSeriesStatus", ")", "(", "UpgradeSeriesStatus", ",", "error", ")", "{", "if", "_", ",", "ok", ":=", "UpgradeSeriesStatusOrder", "[", "status", "]", ";", "!", "ok", "{", "return", "UpgradeSeriesNotStarted", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "status", ")", "\n", "}", "\n", "return", "status", ",", "nil", "\n", "}" ]
// ValidateUpgradeSeriesStatus validates a the input status as valid for a // unit, returning the valid status or an error.
[ "ValidateUpgradeSeriesStatus", "validates", "a", "the", "input", "status", "as", "valid", "for", "a", "unit", "returning", "the", "valid", "status", "or", "an", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/model/upgradeseries.go#L37-L42
4,344
juju/juju
core/model/upgradeseries.go
CompareUpgradeSeriesStatus
func CompareUpgradeSeriesStatus(status1 UpgradeSeriesStatus, status2 UpgradeSeriesStatus) (int, error) { var err error st1, err := ValidateUpgradeSeriesStatus(status1) st2, err := ValidateUpgradeSeriesStatus(status2) if err != nil { return 0, err } if UpgradeSeriesStatusOrder[st1] == UpgradeSeriesStatusOrder[st2] { return 0, nil } if UpgradeSeriesStatusOrder[st1] < UpgradeSeriesStatusOrder[st2] { return -1, nil } return 1, nil }
go
func CompareUpgradeSeriesStatus(status1 UpgradeSeriesStatus, status2 UpgradeSeriesStatus) (int, error) { var err error st1, err := ValidateUpgradeSeriesStatus(status1) st2, err := ValidateUpgradeSeriesStatus(status2) if err != nil { return 0, err } if UpgradeSeriesStatusOrder[st1] == UpgradeSeriesStatusOrder[st2] { return 0, nil } if UpgradeSeriesStatusOrder[st1] < UpgradeSeriesStatusOrder[st2] { return -1, nil } return 1, nil }
[ "func", "CompareUpgradeSeriesStatus", "(", "status1", "UpgradeSeriesStatus", ",", "status2", "UpgradeSeriesStatus", ")", "(", "int", ",", "error", ")", "{", "var", "err", "error", "\n", "st1", ",", "err", ":=", "ValidateUpgradeSeriesStatus", "(", "status1", ")", "\n", "st2", ",", "err", ":=", "ValidateUpgradeSeriesStatus", "(", "status2", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "if", "UpgradeSeriesStatusOrder", "[", "st1", "]", "==", "UpgradeSeriesStatusOrder", "[", "st2", "]", "{", "return", "0", ",", "nil", "\n", "}", "\n", "if", "UpgradeSeriesStatusOrder", "[", "st1", "]", "<", "UpgradeSeriesStatusOrder", "[", "st2", "]", "{", "return", "-", "1", ",", "nil", "\n", "}", "\n", "return", "1", ",", "nil", "\n", "}" ]
// CompareUpgradeSeriesStatus compares two upgrade series statuses and returns // an integer; if the first argument equals the second then 0 is returned; if // the second is greater -1 is returned; 1 is returned otherwise. An error is // returned if either argument is an invalid status.
[ "CompareUpgradeSeriesStatus", "compares", "two", "upgrade", "series", "statuses", "and", "returns", "an", "integer", ";", "if", "the", "first", "argument", "equals", "the", "second", "then", "0", "is", "returned", ";", "if", "the", "second", "is", "greater", "-", "1", "is", "returned", ";", "1", "is", "returned", "otherwise", ".", "An", "error", "is", "returned", "if", "either", "argument", "is", "an", "invalid", "status", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/model/upgradeseries.go#L48-L63
4,345
juju/juju
apiserver/stateauthenticator/auth.go
NewAuthenticator
func NewAuthenticator(statePool *state.StatePool, clock clock.Clock) (*Authenticator, error) { authContext, err := newAuthContext(statePool.SystemState(), clock) if err != nil { return nil, errors.Trace(err) } return &Authenticator{ statePool: statePool, authContext: authContext, }, nil }
go
func NewAuthenticator(statePool *state.StatePool, clock clock.Clock) (*Authenticator, error) { authContext, err := newAuthContext(statePool.SystemState(), clock) if err != nil { return nil, errors.Trace(err) } return &Authenticator{ statePool: statePool, authContext: authContext, }, nil }
[ "func", "NewAuthenticator", "(", "statePool", "*", "state", ".", "StatePool", ",", "clock", "clock", ".", "Clock", ")", "(", "*", "Authenticator", ",", "error", ")", "{", "authContext", ",", "err", ":=", "newAuthContext", "(", "statePool", ".", "SystemState", "(", ")", ",", "clock", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "Authenticator", "{", "statePool", ":", "statePool", ",", "authContext", ":", "authContext", ",", "}", ",", "nil", "\n", "}" ]
// NewAuthenticator returns a new Authenticator using the given StatePool.
[ "NewAuthenticator", "returns", "a", "new", "Authenticator", "using", "the", "given", "StatePool", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/stateauthenticator/auth.go#L37-L46
4,346
juju/juju
apiserver/stateauthenticator/auth.go
Maintain
func (a *Authenticator) Maintain(done <-chan struct{}) { for { select { case <-done: return case <-a.authContext.clock.After(authentication.LocalLoginInteractionTimeout): now := a.authContext.clock.Now() a.authContext.localUserInteractions.Expire(now) } } }
go
func (a *Authenticator) Maintain(done <-chan struct{}) { for { select { case <-done: return case <-a.authContext.clock.After(authentication.LocalLoginInteractionTimeout): now := a.authContext.clock.Now() a.authContext.localUserInteractions.Expire(now) } } }
[ "func", "(", "a", "*", "Authenticator", ")", "Maintain", "(", "done", "<-", "chan", "struct", "{", "}", ")", "{", "for", "{", "select", "{", "case", "<-", "done", ":", "return", "\n", "case", "<-", "a", ".", "authContext", ".", "clock", ".", "After", "(", "authentication", ".", "LocalLoginInteractionTimeout", ")", ":", "now", ":=", "a", ".", "authContext", ".", "clock", ".", "Now", "(", ")", "\n", "a", ".", "authContext", ".", "localUserInteractions", ".", "Expire", "(", "now", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Maintain periodically expires local login interactions.
[ "Maintain", "periodically", "expires", "local", "login", "interactions", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/stateauthenticator/auth.go#L49-L59
4,347
juju/juju
apiserver/stateauthenticator/auth.go
CreateLocalLoginMacaroon
func (a *Authenticator) CreateLocalLoginMacaroon(tag names.UserTag) (*macaroon.Macaroon, error) { return a.authContext.CreateLocalLoginMacaroon(tag) }
go
func (a *Authenticator) CreateLocalLoginMacaroon(tag names.UserTag) (*macaroon.Macaroon, error) { return a.authContext.CreateLocalLoginMacaroon(tag) }
[ "func", "(", "a", "*", "Authenticator", ")", "CreateLocalLoginMacaroon", "(", "tag", "names", ".", "UserTag", ")", "(", "*", "macaroon", ".", "Macaroon", ",", "error", ")", "{", "return", "a", ".", "authContext", ".", "CreateLocalLoginMacaroon", "(", "tag", ")", "\n", "}" ]
// CreateLocalLoginMacaroon is part of the // httpcontext.LocalMacaroonAuthenticator interface.
[ "CreateLocalLoginMacaroon", "is", "part", "of", "the", "httpcontext", ".", "LocalMacaroonAuthenticator", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/stateauthenticator/auth.go#L63-L65
4,348
juju/juju
apiserver/stateauthenticator/auth.go
AddHandlers
func (a *Authenticator) AddHandlers(mux *apiserverhttp.Mux) { h := &localLoginHandlers{ authCtxt: a.authContext, finder: a.statePool.SystemState(), } h.AddHandlers(mux) }
go
func (a *Authenticator) AddHandlers(mux *apiserverhttp.Mux) { h := &localLoginHandlers{ authCtxt: a.authContext, finder: a.statePool.SystemState(), } h.AddHandlers(mux) }
[ "func", "(", "a", "*", "Authenticator", ")", "AddHandlers", "(", "mux", "*", "apiserverhttp", ".", "Mux", ")", "{", "h", ":=", "&", "localLoginHandlers", "{", "authCtxt", ":", "a", ".", "authContext", ",", "finder", ":", "a", ".", "statePool", ".", "SystemState", "(", ")", ",", "}", "\n", "h", ".", "AddHandlers", "(", "mux", ")", "\n", "}" ]
// AddHandlers adds the handlers to the given mux for handling local // macaroon logins.
[ "AddHandlers", "adds", "the", "handlers", "to", "the", "given", "mux", "for", "handling", "local", "macaroon", "logins", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/stateauthenticator/auth.go#L69-L75
4,349
juju/juju
apiserver/stateauthenticator/auth.go
Authenticate
func (a *Authenticator) Authenticate(req *http.Request) (httpcontext.AuthInfo, error) { modelUUID := httpcontext.RequestModelUUID(req) if modelUUID == "" { return httpcontext.AuthInfo{}, errors.New("model UUID not found") } loginRequest, err := LoginRequest(req) if err != nil { return httpcontext.AuthInfo{}, errors.Trace(err) } return a.AuthenticateLoginRequest(req.Host, modelUUID, loginRequest) }
go
func (a *Authenticator) Authenticate(req *http.Request) (httpcontext.AuthInfo, error) { modelUUID := httpcontext.RequestModelUUID(req) if modelUUID == "" { return httpcontext.AuthInfo{}, errors.New("model UUID not found") } loginRequest, err := LoginRequest(req) if err != nil { return httpcontext.AuthInfo{}, errors.Trace(err) } return a.AuthenticateLoginRequest(req.Host, modelUUID, loginRequest) }
[ "func", "(", "a", "*", "Authenticator", ")", "Authenticate", "(", "req", "*", "http", ".", "Request", ")", "(", "httpcontext", ".", "AuthInfo", ",", "error", ")", "{", "modelUUID", ":=", "httpcontext", ".", "RequestModelUUID", "(", "req", ")", "\n", "if", "modelUUID", "==", "\"", "\"", "{", "return", "httpcontext", ".", "AuthInfo", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "loginRequest", ",", "err", ":=", "LoginRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "httpcontext", ".", "AuthInfo", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "a", ".", "AuthenticateLoginRequest", "(", "req", ".", "Host", ",", "modelUUID", ",", "loginRequest", ")", "\n", "}" ]
// Authenticate is part of the httpcontext.Authenticator interface.
[ "Authenticate", "is", "part", "of", "the", "httpcontext", ".", "Authenticator", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/stateauthenticator/auth.go#L78-L88
4,350
juju/juju
provider/maas/volumes.go
mibToGb
func mibToGb(m uint64) uint64 { return common.MiBToGiB(m) * (humanize.GiByte / humanize.GByte) }
go
func mibToGb(m uint64) uint64 { return common.MiBToGiB(m) * (humanize.GiByte / humanize.GByte) }
[ "func", "mibToGb", "(", "m", "uint64", ")", "uint64", "{", "return", "common", ".", "MiBToGiB", "(", "m", ")", "*", "(", "humanize", ".", "GiByte", "/", "humanize", ".", "GByte", ")", "\n", "}" ]
// mibToGB converts the value in MiB to GB. // Juju works in MiB, MAAS expects GB.
[ "mibToGB", "converts", "the", "value", "in", "MiB", "to", "GB", ".", "Juju", "works", "in", "MiB", "MAAS", "expects", "GB", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/volumes.go#L147-L149
4,351
juju/juju
provider/maas/volumes.go
buildMAASVolumeParameters
func buildMAASVolumeParameters(args []storage.VolumeParams, cons constraints.Value) ([]volumeInfo, error) { if len(args) == 0 && cons.RootDisk == nil { return nil, nil } volumes := make([]volumeInfo, len(args)+1) rootVolume := volumeInfo{name: rootDiskLabel} if cons.RootDisk != nil { rootVolume.sizeInGB = mibToGb(*cons.RootDisk) } volumes[0] = rootVolume for i, v := range args { cfg, err := newStorageConfig(v.Attributes) if err != nil { return nil, errors.Trace(err) } info := volumeInfo{ name: v.Tag.Id(), sizeInGB: mibToGb(v.Size), tags: cfg.tags, } volumes[i+1] = info } return volumes, nil }
go
func buildMAASVolumeParameters(args []storage.VolumeParams, cons constraints.Value) ([]volumeInfo, error) { if len(args) == 0 && cons.RootDisk == nil { return nil, nil } volumes := make([]volumeInfo, len(args)+1) rootVolume := volumeInfo{name: rootDiskLabel} if cons.RootDisk != nil { rootVolume.sizeInGB = mibToGb(*cons.RootDisk) } volumes[0] = rootVolume for i, v := range args { cfg, err := newStorageConfig(v.Attributes) if err != nil { return nil, errors.Trace(err) } info := volumeInfo{ name: v.Tag.Id(), sizeInGB: mibToGb(v.Size), tags: cfg.tags, } volumes[i+1] = info } return volumes, nil }
[ "func", "buildMAASVolumeParameters", "(", "args", "[", "]", "storage", ".", "VolumeParams", ",", "cons", "constraints", ".", "Value", ")", "(", "[", "]", "volumeInfo", ",", "error", ")", "{", "if", "len", "(", "args", ")", "==", "0", "&&", "cons", ".", "RootDisk", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "volumes", ":=", "make", "(", "[", "]", "volumeInfo", ",", "len", "(", "args", ")", "+", "1", ")", "\n", "rootVolume", ":=", "volumeInfo", "{", "name", ":", "rootDiskLabel", "}", "\n", "if", "cons", ".", "RootDisk", "!=", "nil", "{", "rootVolume", ".", "sizeInGB", "=", "mibToGb", "(", "*", "cons", ".", "RootDisk", ")", "\n", "}", "\n", "volumes", "[", "0", "]", "=", "rootVolume", "\n", "for", "i", ",", "v", ":=", "range", "args", "{", "cfg", ",", "err", ":=", "newStorageConfig", "(", "v", ".", "Attributes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "info", ":=", "volumeInfo", "{", "name", ":", "v", ".", "Tag", ".", "Id", "(", ")", ",", "sizeInGB", ":", "mibToGb", "(", "v", ".", "Size", ")", ",", "tags", ":", "cfg", ".", "tags", ",", "}", "\n", "volumes", "[", "i", "+", "1", "]", "=", "info", "\n", "}", "\n", "return", "volumes", ",", "nil", "\n", "}" ]
// buildMAASVolumeParameters creates the MAAS volume information to include // in a request to acquire a MAAS node, based on the supplied storage parameters.
[ "buildMAASVolumeParameters", "creates", "the", "MAAS", "volume", "information", "to", "include", "in", "a", "request", "to", "acquire", "a", "MAAS", "node", "based", "on", "the", "supplied", "storage", "parameters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/volumes.go#L153-L176
4,352
juju/juju
state/persistence.go
One
func (sp statePersistence) One(collName, id string, doc interface{}) error { coll, closeColl := sp.st.db().GetCollection(collName) defer closeColl() err := coll.FindId(id).One(doc) if err == mgo.ErrNotFound { return errors.NotFoundf(id) } if err != nil { return errors.Trace(err) } return nil }
go
func (sp statePersistence) One(collName, id string, doc interface{}) error { coll, closeColl := sp.st.db().GetCollection(collName) defer closeColl() err := coll.FindId(id).One(doc) if err == mgo.ErrNotFound { return errors.NotFoundf(id) } if err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "sp", "statePersistence", ")", "One", "(", "collName", ",", "id", "string", ",", "doc", "interface", "{", "}", ")", "error", "{", "coll", ",", "closeColl", ":=", "sp", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "collName", ")", "\n", "defer", "closeColl", "(", ")", "\n\n", "err", ":=", "coll", ".", "FindId", "(", "id", ")", ".", "One", "(", "doc", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "errors", ".", "NotFoundf", "(", "id", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// One gets the identified document from the collection.
[ "One", "gets", "the", "identified", "document", "from", "the", "collection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/persistence.go#L51-L63
4,353
juju/juju
state/persistence.go
All
func (sp statePersistence) All(collName string, query, docs interface{}) error { coll, closeColl := sp.st.db().GetCollection(collName) defer closeColl() if err := coll.Find(query).All(docs); err != nil { return errors.Trace(err) } return nil }
go
func (sp statePersistence) All(collName string, query, docs interface{}) error { coll, closeColl := sp.st.db().GetCollection(collName) defer closeColl() if err := coll.Find(query).All(docs); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "sp", "statePersistence", ")", "All", "(", "collName", "string", ",", "query", ",", "docs", "interface", "{", "}", ")", "error", "{", "coll", ",", "closeColl", ":=", "sp", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "collName", ")", "\n", "defer", "closeColl", "(", ")", "\n\n", "if", "err", ":=", "coll", ".", "Find", "(", "query", ")", ".", "All", "(", "docs", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// All gets all documents from the collection matching the query.
[ "All", "gets", "all", "documents", "from", "the", "collection", "matching", "the", "query", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/persistence.go#L66-L74
4,354
juju/juju
state/persistence.go
Run
func (sp statePersistence) Run(transactions jujutxn.TransactionSource) error { if err := sp.st.db().Run(transactions); err != nil { return errors.Trace(err) } return nil }
go
func (sp statePersistence) Run(transactions jujutxn.TransactionSource) error { if err := sp.st.db().Run(transactions); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "sp", "statePersistence", ")", "Run", "(", "transactions", "jujutxn", ".", "TransactionSource", ")", "error", "{", "if", "err", ":=", "sp", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "transactions", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Run runs the transaction produced by the provided factory function.
[ "Run", "runs", "the", "transaction", "produced", "by", "the", "provided", "factory", "function", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/persistence.go#L77-L82
4,355
juju/juju
state/persistence.go
NewStorage
func (sp *statePersistence) NewStorage() storage.Storage { modelUUID := sp.st.ModelUUID() // TODO(ericsnow) Copy the session? session := sp.st.session store := storage.NewStorage(modelUUID, session) return store }
go
func (sp *statePersistence) NewStorage() storage.Storage { modelUUID := sp.st.ModelUUID() // TODO(ericsnow) Copy the session? session := sp.st.session store := storage.NewStorage(modelUUID, session) return store }
[ "func", "(", "sp", "*", "statePersistence", ")", "NewStorage", "(", ")", "storage", ".", "Storage", "{", "modelUUID", ":=", "sp", ".", "st", ".", "ModelUUID", "(", ")", "\n", "// TODO(ericsnow) Copy the session?", "session", ":=", "sp", ".", "st", ".", "session", "\n", "store", ":=", "storage", ".", "NewStorage", "(", "modelUUID", ",", "session", ")", "\n", "return", "store", "\n", "}" ]
// NewStorage returns a new blob storage for the model.
[ "NewStorage", "returns", "a", "new", "blob", "storage", "for", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/persistence.go#L85-L91
4,356
juju/juju
state/persistence.go
ApplicationExistsOps
func (sp *statePersistence) ApplicationExistsOps(applicationID string) []txn.Op { return []txn.Op{{ C: applicationsC, Id: applicationID, Assert: isAliveDoc, }} }
go
func (sp *statePersistence) ApplicationExistsOps(applicationID string) []txn.Op { return []txn.Op{{ C: applicationsC, Id: applicationID, Assert: isAliveDoc, }} }
[ "func", "(", "sp", "*", "statePersistence", ")", "ApplicationExistsOps", "(", "applicationID", "string", ")", "[", "]", "txn", ".", "Op", "{", "return", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "applicationsC", ",", "Id", ":", "applicationID", ",", "Assert", ":", "isAliveDoc", ",", "}", "}", "\n", "}" ]
// ApplicationExistsOps returns the operations that verify that the // identified application exists.
[ "ApplicationExistsOps", "returns", "the", "operations", "that", "verify", "that", "the", "identified", "application", "exists", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/persistence.go#L95-L101
4,357
juju/juju
cmd/modelcmd/modelcommand.go
ClientStore
func (c *ModelCommandBase) ClientStore() jujuclient.ClientStore { // c.store is set in maybeInitModel() below. if c.store == nil && !c.runStarted { panic("inappropriate method called before init finished") } return c.store }
go
func (c *ModelCommandBase) ClientStore() jujuclient.ClientStore { // c.store is set in maybeInitModel() below. if c.store == nil && !c.runStarted { panic("inappropriate method called before init finished") } return c.store }
[ "func", "(", "c", "*", "ModelCommandBase", ")", "ClientStore", "(", ")", "jujuclient", ".", "ClientStore", "{", "// c.store is set in maybeInitModel() below.", "if", "c", ".", "store", "==", "nil", "&&", "!", "c", ".", "runStarted", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "c", ".", "store", "\n", "}" ]
// ClientStore implements the ModelCommand interface.
[ "ClientStore", "implements", "the", "ModelCommand", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L122-L128
4,358
juju/juju
cmd/modelcmd/modelcommand.go
SetModelName
func (c *ModelCommandBase) SetModelName(modelName string, allowDefault bool) error { c._modelName = modelName c.allowDefaultModel = allowDefault // After setting the model name, we may need to ensure we have access to the // other model details if not already done. if err := c.maybeInitModel(); err != nil { return errors.Trace(err) } return nil }
go
func (c *ModelCommandBase) SetModelName(modelName string, allowDefault bool) error { c._modelName = modelName c.allowDefaultModel = allowDefault // After setting the model name, we may need to ensure we have access to the // other model details if not already done. if err := c.maybeInitModel(); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "c", "*", "ModelCommandBase", ")", "SetModelName", "(", "modelName", "string", ",", "allowDefault", "bool", ")", "error", "{", "c", ".", "_modelName", "=", "modelName", "\n", "c", ".", "allowDefaultModel", "=", "allowDefault", "\n\n", "// After setting the model name, we may need to ensure we have access to the", "// other model details if not already done.", "if", "err", ":=", "c", ".", "maybeInitModel", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetModelName implements the ModelCommand interface.
[ "SetModelName", "implements", "the", "ModelCommand", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L194-L204
4,359
juju/juju
cmd/modelcmd/modelcommand.go
ModelName
func (c *ModelCommandBase) ModelName() (string, error) { c.assertRunStarted() if err := c.maybeInitModel(); err != nil { return "", errors.Trace(err) } return c._modelName, nil }
go
func (c *ModelCommandBase) ModelName() (string, error) { c.assertRunStarted() if err := c.maybeInitModel(); err != nil { return "", errors.Trace(err) } return c._modelName, nil }
[ "func", "(", "c", "*", "ModelCommandBase", ")", "ModelName", "(", ")", "(", "string", ",", "error", ")", "{", "c", ".", "assertRunStarted", "(", ")", "\n", "if", "err", ":=", "c", ".", "maybeInitModel", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "c", ".", "_modelName", ",", "nil", "\n", "}" ]
// ModelName implements the ModelCommand interface.
[ "ModelName", "implements", "the", "ModelCommand", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L207-L213
4,360
juju/juju
cmd/modelcmd/modelcommand.go
ModelType
func (c *ModelCommandBase) ModelType() (model.ModelType, error) { if c._modelType != "" { return c._modelType, nil } // If we need to look up the model type, we need to ensure we // have access to the model details. if err := c.maybeInitModel(); err != nil { return "", errors.Trace(err) } details, err := c.store.ModelByName(c._controllerName, c._modelName) if err != nil { if !c.runStarted { return "", errors.Trace(err) } details, err = c.modelDetails(c._controllerName, c._modelName) if err != nil { return "", errors.Trace(err) } } c._modelType = details.ModelType return c._modelType, nil }
go
func (c *ModelCommandBase) ModelType() (model.ModelType, error) { if c._modelType != "" { return c._modelType, nil } // If we need to look up the model type, we need to ensure we // have access to the model details. if err := c.maybeInitModel(); err != nil { return "", errors.Trace(err) } details, err := c.store.ModelByName(c._controllerName, c._modelName) if err != nil { if !c.runStarted { return "", errors.Trace(err) } details, err = c.modelDetails(c._controllerName, c._modelName) if err != nil { return "", errors.Trace(err) } } c._modelType = details.ModelType return c._modelType, nil }
[ "func", "(", "c", "*", "ModelCommandBase", ")", "ModelType", "(", ")", "(", "model", ".", "ModelType", ",", "error", ")", "{", "if", "c", ".", "_modelType", "!=", "\"", "\"", "{", "return", "c", ".", "_modelType", ",", "nil", "\n", "}", "\n", "// If we need to look up the model type, we need to ensure we", "// have access to the model details.", "if", "err", ":=", "c", ".", "maybeInitModel", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "details", ",", "err", ":=", "c", ".", "store", ".", "ModelByName", "(", "c", ".", "_controllerName", ",", "c", ".", "_modelName", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "c", ".", "runStarted", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "details", ",", "err", "=", "c", ".", "modelDetails", "(", "c", ".", "_controllerName", ",", "c", ".", "_modelName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "c", ".", "_modelType", "=", "details", ".", "ModelType", "\n", "return", "c", ".", "_modelType", ",", "nil", "\n", "}" ]
// ModelType implements the ModelCommand interface.
[ "ModelType", "implements", "the", "ModelCommand", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L216-L237
4,361
juju/juju
cmd/modelcmd/modelcommand.go
SetActiveBranch
func (c *ModelCommandBase) SetActiveBranch(branchName string) error { _, modelDetails, err := c.ModelDetails() if err != nil { return errors.Annotate(err, "getting model details") } modelDetails.ActiveBranch = branchName if err = c.store.UpdateModel(c._controllerName, c._modelName, *modelDetails); err != nil { return err } c._activeBranch = branchName return nil }
go
func (c *ModelCommandBase) SetActiveBranch(branchName string) error { _, modelDetails, err := c.ModelDetails() if err != nil { return errors.Annotate(err, "getting model details") } modelDetails.ActiveBranch = branchName if err = c.store.UpdateModel(c._controllerName, c._modelName, *modelDetails); err != nil { return err } c._activeBranch = branchName return nil }
[ "func", "(", "c", "*", "ModelCommandBase", ")", "SetActiveBranch", "(", "branchName", "string", ")", "error", "{", "_", ",", "modelDetails", ",", "err", ":=", "c", ".", "ModelDetails", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "modelDetails", ".", "ActiveBranch", "=", "branchName", "\n", "if", "err", "=", "c", ".", "store", ".", "UpdateModel", "(", "c", ".", "_controllerName", ",", "c", ".", "_modelName", ",", "*", "modelDetails", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "_activeBranch", "=", "branchName", "\n", "return", "nil", "\n", "}" ]
// SetModelGeneration implements the ModelCommand interface.
[ "SetModelGeneration", "implements", "the", "ModelCommand", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L240-L251
4,362
juju/juju
cmd/modelcmd/modelcommand.go
ActiveBranch
func (c *ModelCommandBase) ActiveBranch() (string, error) { if c._activeBranch != "" { return c._activeBranch, nil } // If we need to look up the model generation, we need to ensure we // have access to the model details. if err := c.maybeInitModel(); err != nil { return "", errors.Trace(err) } details, err := c.store.ModelByName(c._controllerName, c._modelName) if err != nil { if !c.runStarted { return "", errors.Trace(err) } details, err = c.modelDetails(c._controllerName, c._modelName) if err != nil { return "", errors.Trace(err) } } c._activeBranch = details.ActiveBranch return c._activeBranch, nil }
go
func (c *ModelCommandBase) ActiveBranch() (string, error) { if c._activeBranch != "" { return c._activeBranch, nil } // If we need to look up the model generation, we need to ensure we // have access to the model details. if err := c.maybeInitModel(); err != nil { return "", errors.Trace(err) } details, err := c.store.ModelByName(c._controllerName, c._modelName) if err != nil { if !c.runStarted { return "", errors.Trace(err) } details, err = c.modelDetails(c._controllerName, c._modelName) if err != nil { return "", errors.Trace(err) } } c._activeBranch = details.ActiveBranch return c._activeBranch, nil }
[ "func", "(", "c", "*", "ModelCommandBase", ")", "ActiveBranch", "(", ")", "(", "string", ",", "error", ")", "{", "if", "c", ".", "_activeBranch", "!=", "\"", "\"", "{", "return", "c", ".", "_activeBranch", ",", "nil", "\n", "}", "\n", "// If we need to look up the model generation, we need to ensure we", "// have access to the model details.", "if", "err", ":=", "c", ".", "maybeInitModel", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "details", ",", "err", ":=", "c", ".", "store", ".", "ModelByName", "(", "c", ".", "_controllerName", ",", "c", ".", "_modelName", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "c", ".", "runStarted", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "details", ",", "err", "=", "c", ".", "modelDetails", "(", "c", ".", "_controllerName", ",", "c", ".", "_modelName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "c", ".", "_activeBranch", "=", "details", ".", "ActiveBranch", "\n", "return", "c", ".", "_activeBranch", ",", "nil", "\n", "}" ]
// ActiveBranch implements the ModelCommand interface.
[ "ActiveBranch", "implements", "the", "ModelCommand", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L254-L275
4,363
juju/juju
cmd/modelcmd/modelcommand.go
ControllerName
func (c *ModelCommandBase) ControllerName() (string, error) { c.assertRunStarted() if err := c.maybeInitModel(); err != nil { return "", errors.Trace(err) } return c._controllerName, nil }
go
func (c *ModelCommandBase) ControllerName() (string, error) { c.assertRunStarted() if err := c.maybeInitModel(); err != nil { return "", errors.Trace(err) } return c._controllerName, nil }
[ "func", "(", "c", "*", "ModelCommandBase", ")", "ControllerName", "(", ")", "(", "string", ",", "error", ")", "{", "c", ".", "assertRunStarted", "(", ")", "\n", "if", "err", ":=", "c", ".", "maybeInitModel", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "c", ".", "_controllerName", ",", "nil", "\n", "}" ]
// ControllerName implements the ModelCommand interface.
[ "ControllerName", "implements", "the", "ModelCommand", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L278-L284
4,364
juju/juju
cmd/modelcmd/modelcommand.go
NewAPIRoot
func (c *ModelCommandBase) NewAPIRoot() (api.Connection, error) { // We need to call ModelDetails() here and not just ModelName() to force // a refresh of the internal model details if those are not yet stored locally. modelName, _, err := c.ModelDetails() if err != nil { return nil, errors.Trace(err) } return c.newAPIRoot(modelName) }
go
func (c *ModelCommandBase) NewAPIRoot() (api.Connection, error) { // We need to call ModelDetails() here and not just ModelName() to force // a refresh of the internal model details if those are not yet stored locally. modelName, _, err := c.ModelDetails() if err != nil { return nil, errors.Trace(err) } return c.newAPIRoot(modelName) }
[ "func", "(", "c", "*", "ModelCommandBase", ")", "NewAPIRoot", "(", ")", "(", "api", ".", "Connection", ",", "error", ")", "{", "// We need to call ModelDetails() here and not just ModelName() to force", "// a refresh of the internal model details if those are not yet stored locally.", "modelName", ",", "_", ",", "err", ":=", "c", ".", "ModelDetails", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "c", ".", "newAPIRoot", "(", "modelName", ")", "\n", "}" ]
// NewAPIRoot returns a new connection to the API server for the environment // directed to the model specified on the command line.
[ "NewAPIRoot", "returns", "a", "new", "connection", "to", "the", "API", "server", "for", "the", "environment", "directed", "to", "the", "model", "specified", "on", "the", "command", "line", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L345-L353
4,365
juju/juju
cmd/modelcmd/modelcommand.go
newAPIRoot
func (c *ModelCommandBase) newAPIRoot(modelName string) (api.Connection, error) { controllerName, err := c.ControllerName() if err != nil { return nil, errors.Trace(err) } return c.CommandBase.NewAPIRoot(c.store, controllerName, modelName) }
go
func (c *ModelCommandBase) newAPIRoot(modelName string) (api.Connection, error) { controllerName, err := c.ControllerName() if err != nil { return nil, errors.Trace(err) } return c.CommandBase.NewAPIRoot(c.store, controllerName, modelName) }
[ "func", "(", "c", "*", "ModelCommandBase", ")", "newAPIRoot", "(", "modelName", "string", ")", "(", "api", ".", "Connection", ",", "error", ")", "{", "controllerName", ",", "err", ":=", "c", ".", "ControllerName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "c", ".", "CommandBase", ".", "NewAPIRoot", "(", "c", ".", "store", ",", "controllerName", ",", "modelName", ")", "\n", "}" ]
// newAPIRoot is the internal implementation of NewAPIRoot and NewControllerAPIRoot; // if modelName is empty, it makes a controller-only connection.
[ "newAPIRoot", "is", "the", "internal", "implementation", "of", "NewAPIRoot", "and", "NewControllerAPIRoot", ";", "if", "modelName", "is", "empty", "it", "makes", "a", "controller", "-", "only", "connection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L365-L371
4,366
juju/juju
cmd/modelcmd/modelcommand.go
Wrap
func Wrap(c ModelCommand, options ...WrapOption) ModelCommand { wrapper := &modelCommandWrapper{ ModelCommand: c, skipModelFlags: false, useDefaultModel: true, } for _, option := range options { option(wrapper) } // Define a new type so that we can embed the ModelCommand // interface one level deeper than cmd.Command, so that // we'll get the Command methods from WrapBase // and all the ModelCommand methods not in cmd.Command // from modelCommandWrapper. type embed struct { *modelCommandWrapper } return struct { embed cmd.Command }{ Command: WrapBase(wrapper), embed: embed{wrapper}, } }
go
func Wrap(c ModelCommand, options ...WrapOption) ModelCommand { wrapper := &modelCommandWrapper{ ModelCommand: c, skipModelFlags: false, useDefaultModel: true, } for _, option := range options { option(wrapper) } // Define a new type so that we can embed the ModelCommand // interface one level deeper than cmd.Command, so that // we'll get the Command methods from WrapBase // and all the ModelCommand methods not in cmd.Command // from modelCommandWrapper. type embed struct { *modelCommandWrapper } return struct { embed cmd.Command }{ Command: WrapBase(wrapper), embed: embed{wrapper}, } }
[ "func", "Wrap", "(", "c", "ModelCommand", ",", "options", "...", "WrapOption", ")", "ModelCommand", "{", "wrapper", ":=", "&", "modelCommandWrapper", "{", "ModelCommand", ":", "c", ",", "skipModelFlags", ":", "false", ",", "useDefaultModel", ":", "true", ",", "}", "\n", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "wrapper", ")", "\n", "}", "\n", "// Define a new type so that we can embed the ModelCommand", "// interface one level deeper than cmd.Command, so that", "// we'll get the Command methods from WrapBase", "// and all the ModelCommand methods not in cmd.Command", "// from modelCommandWrapper.", "type", "embed", "struct", "{", "*", "modelCommandWrapper", "\n", "}", "\n", "return", "struct", "{", "embed", "\n", "cmd", ".", "Command", "\n", "}", "{", "Command", ":", "WrapBase", "(", "wrapper", ")", ",", "embed", ":", "embed", "{", "wrapper", "}", ",", "}", "\n", "}" ]
// Wrap wraps the specified ModelCommand, returning a ModelCommand // that proxies to each of the ModelCommand methods. // Any provided options are applied to the wrapped command // before it is returned.
[ "Wrap", "wraps", "the", "specified", "ModelCommand", "returning", "a", "ModelCommand", "that", "proxies", "to", "each", "of", "the", "ModelCommand", "methods", ".", "Any", "provided", "options", "are", "applied", "to", "the", "wrapped", "command", "before", "it", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L428-L452
4,367
juju/juju
cmd/modelcmd/modelcommand.go
validateCommandForModelType
func (w *modelCommandWrapper) validateCommandForModelType(runStarted bool) error { _, iaasOnly := w.inner().(IAASOnlyCommand) _, caasOnly := w.inner().(CAASOnlyCommand) if !caasOnly && !iaasOnly { return nil } modelType, err := w.ModelCommand.ModelType() if err != nil { err = errors.Cause(err) // We need to error if Run() has been invoked the model is known and there was // some other error. If the model is not yet known, we'll grab the details // during the Run() API call later. if runStarted || (err != ErrNoModelSpecified && !errors.IsNotFound(err)) { return errors.Trace(err) } return nil } if modelType == model.CAAS && iaasOnly { err = errors.Errorf("Juju command %q not supported on kubernetes models", w.Info().Name) } if modelType == model.IAAS && caasOnly { err = errors.Errorf("Juju command %q not supported on non-container models", w.Info().Name) } if c, ok := w.inner().(modelSpecificCommand); ok { return c.IncompatibleModel(err) } return err }
go
func (w *modelCommandWrapper) validateCommandForModelType(runStarted bool) error { _, iaasOnly := w.inner().(IAASOnlyCommand) _, caasOnly := w.inner().(CAASOnlyCommand) if !caasOnly && !iaasOnly { return nil } modelType, err := w.ModelCommand.ModelType() if err != nil { err = errors.Cause(err) // We need to error if Run() has been invoked the model is known and there was // some other error. If the model is not yet known, we'll grab the details // during the Run() API call later. if runStarted || (err != ErrNoModelSpecified && !errors.IsNotFound(err)) { return errors.Trace(err) } return nil } if modelType == model.CAAS && iaasOnly { err = errors.Errorf("Juju command %q not supported on kubernetes models", w.Info().Name) } if modelType == model.IAAS && caasOnly { err = errors.Errorf("Juju command %q not supported on non-container models", w.Info().Name) } if c, ok := w.inner().(modelSpecificCommand); ok { return c.IncompatibleModel(err) } return err }
[ "func", "(", "w", "*", "modelCommandWrapper", ")", "validateCommandForModelType", "(", "runStarted", "bool", ")", "error", "{", "_", ",", "iaasOnly", ":=", "w", ".", "inner", "(", ")", ".", "(", "IAASOnlyCommand", ")", "\n", "_", ",", "caasOnly", ":=", "w", ".", "inner", "(", ")", ".", "(", "CAASOnlyCommand", ")", "\n", "if", "!", "caasOnly", "&&", "!", "iaasOnly", "{", "return", "nil", "\n", "}", "\n\n", "modelType", ",", "err", ":=", "w", ".", "ModelCommand", ".", "ModelType", "(", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "errors", ".", "Cause", "(", "err", ")", "\n", "// We need to error if Run() has been invoked the model is known and there was", "// some other error. If the model is not yet known, we'll grab the details", "// during the Run() API call later.", "if", "runStarted", "||", "(", "err", "!=", "ErrNoModelSpecified", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", ")", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "if", "modelType", "==", "model", ".", "CAAS", "&&", "iaasOnly", "{", "err", "=", "errors", ".", "Errorf", "(", "\"", "\"", ",", "w", ".", "Info", "(", ")", ".", "Name", ")", "\n", "}", "\n", "if", "modelType", "==", "model", ".", "IAAS", "&&", "caasOnly", "{", "err", "=", "errors", ".", "Errorf", "(", "\"", "\"", ",", "w", ".", "Info", "(", ")", ".", "Name", ")", "\n", "}", "\n\n", "if", "c", ",", "ok", ":=", "w", ".", "inner", "(", ")", ".", "(", "modelSpecificCommand", ")", ";", "ok", "{", "return", "c", ".", "IncompatibleModel", "(", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// validateCommandForModelType returns an error if an IAAS-only command // is run on a CAAS model.
[ "validateCommandForModelType", "returns", "an", "error", "if", "an", "IAAS", "-", "only", "command", "is", "run", "on", "a", "CAAS", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L486-L515
4,368
juju/juju
cmd/modelcmd/modelcommand.go
BootstrapContext
func BootstrapContext(cmdContext *cmd.Context) environs.BootstrapContext { return &bootstrapContext{ Context: cmdContext, verifyCredentials: true, } }
go
func BootstrapContext(cmdContext *cmd.Context) environs.BootstrapContext { return &bootstrapContext{ Context: cmdContext, verifyCredentials: true, } }
[ "func", "BootstrapContext", "(", "cmdContext", "*", "cmd", ".", "Context", ")", "environs", ".", "BootstrapContext", "{", "return", "&", "bootstrapContext", "{", "Context", ":", "cmdContext", ",", "verifyCredentials", ":", "true", ",", "}", "\n", "}" ]
// BootstrapContext returns a new BootstrapContext constructed from a command Context.
[ "BootstrapContext", "returns", "a", "new", "BootstrapContext", "constructed", "from", "a", "command", "Context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L573-L578
4,369
juju/juju
cmd/modelcmd/modelcommand.go
BootstrapContextNoVerify
func BootstrapContextNoVerify(cmdContext *cmd.Context) environs.BootstrapContext { return &bootstrapContext{ Context: cmdContext, verifyCredentials: false, } }
go
func BootstrapContextNoVerify(cmdContext *cmd.Context) environs.BootstrapContext { return &bootstrapContext{ Context: cmdContext, verifyCredentials: false, } }
[ "func", "BootstrapContextNoVerify", "(", "cmdContext", "*", "cmd", ".", "Context", ")", "environs", ".", "BootstrapContext", "{", "return", "&", "bootstrapContext", "{", "Context", ":", "cmdContext", ",", "verifyCredentials", ":", "false", ",", "}", "\n", "}" ]
// BootstrapContextNoVerify returns a new BootstrapContext constructed from a command Context // where the validation of credentials is false.
[ "BootstrapContextNoVerify", "returns", "a", "new", "BootstrapContext", "constructed", "from", "a", "command", "Context", "where", "the", "validation", "of", "credentials", "is", "false", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L582-L587
4,370
juju/juju
cmd/modelcmd/modelcommand.go
SplitModelName
func SplitModelName(name string) (controller, model string) { if i := strings.IndexRune(name, ':'); i >= 0 { return name[:i], name[i+1:] } return "", name }
go
func SplitModelName(name string) (controller, model string) { if i := strings.IndexRune(name, ':'); i >= 0 { return name[:i], name[i+1:] } return "", name }
[ "func", "SplitModelName", "(", "name", "string", ")", "(", "controller", ",", "model", "string", ")", "{", "if", "i", ":=", "strings", ".", "IndexRune", "(", "name", ",", "':'", ")", ";", "i", ">=", "0", "{", "return", "name", "[", ":", "i", "]", ",", "name", "[", "i", "+", "1", ":", "]", "\n", "}", "\n", "return", "\"", "\"", ",", "name", "\n", "}" ]
// SplitModelName splits a model name into its controller // and model parts. If the model is unqualified, then the // returned controller string will be empty, and the returned // model string will be identical to the input.
[ "SplitModelName", "splits", "a", "model", "name", "into", "its", "controller", "and", "model", "parts", ".", "If", "the", "model", "is", "unqualified", "then", "the", "returned", "controller", "string", "will", "be", "empty", "and", "the", "returned", "model", "string", "will", "be", "identical", "to", "the", "input", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/modelcommand.go#L593-L598
4,371
juju/juju
provider/azure/vmextension.go
vmExtensionProperties
func vmExtensionProperties(os jujuos.OSType) (*compute.VirtualMachineExtensionProperties, error) { var commandToExecute, extensionPublisher, extensionType, extensionVersion string switch os { case jujuos.Windows: commandToExecute = windowsExecuteCustomScriptCommand extensionPublisher = windowsCustomScriptPublisher extensionType = windowsCustomScriptType extensionVersion = windowsCustomScriptVersion case jujuos.CentOS: commandToExecute = linuxExecuteCustomScriptCommand extensionPublisher = linuxCustomScriptPublisher extensionType = linuxCustomScriptType extensionVersion = linuxCustomScriptVersion default: // Ubuntu renders CustomData as cloud-config, and interprets // it with cloud-init. Windows and CentOS do not use cloud-init // on Azure. return nil, errors.NotSupportedf("CustomScript extension for OS %q", os) } extensionSettings := map[string]interface{}{ "commandToExecute": commandToExecute, } return &compute.VirtualMachineExtensionProperties{ Publisher: to.StringPtr(extensionPublisher), Type: to.StringPtr(extensionType), TypeHandlerVersion: to.StringPtr(extensionVersion), AutoUpgradeMinorVersion: to.BoolPtr(true), Settings: &extensionSettings, }, nil }
go
func vmExtensionProperties(os jujuos.OSType) (*compute.VirtualMachineExtensionProperties, error) { var commandToExecute, extensionPublisher, extensionType, extensionVersion string switch os { case jujuos.Windows: commandToExecute = windowsExecuteCustomScriptCommand extensionPublisher = windowsCustomScriptPublisher extensionType = windowsCustomScriptType extensionVersion = windowsCustomScriptVersion case jujuos.CentOS: commandToExecute = linuxExecuteCustomScriptCommand extensionPublisher = linuxCustomScriptPublisher extensionType = linuxCustomScriptType extensionVersion = linuxCustomScriptVersion default: // Ubuntu renders CustomData as cloud-config, and interprets // it with cloud-init. Windows and CentOS do not use cloud-init // on Azure. return nil, errors.NotSupportedf("CustomScript extension for OS %q", os) } extensionSettings := map[string]interface{}{ "commandToExecute": commandToExecute, } return &compute.VirtualMachineExtensionProperties{ Publisher: to.StringPtr(extensionPublisher), Type: to.StringPtr(extensionType), TypeHandlerVersion: to.StringPtr(extensionVersion), AutoUpgradeMinorVersion: to.BoolPtr(true), Settings: &extensionSettings, }, nil }
[ "func", "vmExtensionProperties", "(", "os", "jujuos", ".", "OSType", ")", "(", "*", "compute", ".", "VirtualMachineExtensionProperties", ",", "error", ")", "{", "var", "commandToExecute", ",", "extensionPublisher", ",", "extensionType", ",", "extensionVersion", "string", "\n\n", "switch", "os", "{", "case", "jujuos", ".", "Windows", ":", "commandToExecute", "=", "windowsExecuteCustomScriptCommand", "\n", "extensionPublisher", "=", "windowsCustomScriptPublisher", "\n", "extensionType", "=", "windowsCustomScriptType", "\n", "extensionVersion", "=", "windowsCustomScriptVersion", "\n", "case", "jujuos", ".", "CentOS", ":", "commandToExecute", "=", "linuxExecuteCustomScriptCommand", "\n", "extensionPublisher", "=", "linuxCustomScriptPublisher", "\n", "extensionType", "=", "linuxCustomScriptType", "\n", "extensionVersion", "=", "linuxCustomScriptVersion", "\n", "default", ":", "// Ubuntu renders CustomData as cloud-config, and interprets", "// it with cloud-init. Windows and CentOS do not use cloud-init", "// on Azure.", "return", "nil", ",", "errors", ".", "NotSupportedf", "(", "\"", "\"", ",", "os", ")", "\n", "}", "\n\n", "extensionSettings", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "commandToExecute", ",", "}", "\n", "return", "&", "compute", ".", "VirtualMachineExtensionProperties", "{", "Publisher", ":", "to", ".", "StringPtr", "(", "extensionPublisher", ")", ",", "Type", ":", "to", ".", "StringPtr", "(", "extensionType", ")", ",", "TypeHandlerVersion", ":", "to", ".", "StringPtr", "(", "extensionVersion", ")", ",", "AutoUpgradeMinorVersion", ":", "to", ".", "BoolPtr", "(", "true", ")", ",", "Settings", ":", "&", "extensionSettings", ",", "}", ",", "nil", "\n", "}" ]
// vmExtension creates a CustomScript VM extension for the given VM // which will execute the CustomData on the machine as a script.
[ "vmExtension", "creates", "a", "CustomScript", "VM", "extension", "for", "the", "given", "VM", "which", "will", "execute", "the", "CustomData", "on", "the", "machine", "as", "a", "script", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/vmextension.go#L36-L67
4,372
juju/juju
cmd/juju/application/upgradecharm.go
NewUpgradeCharmCommand
func NewUpgradeCharmCommand() cmd.Command { cmd := &upgradeCharmCommand{ DeployResources: resourceadapters.DeployResources, ResolveCharm: resolveCharm, NewCharmAdder: newCharmAdder, NewCharmClient: func(conn base.APICallCloser) CharmClient { return charms.NewClient(conn) }, NewCharmUpgradeClient: func(conn base.APICallCloser) CharmAPIClient { return application.NewClient(conn) }, NewModelConfigGetter: func(conn base.APICallCloser) ModelConfigGetter { return modelconfig.NewClient(conn) }, NewResourceLister: func(conn base.APICallCloser) (ResourceLister, error) { resclient, err := resourceadapters.NewAPIClient(conn) if err != nil { return nil, err } return resclient, nil }, CharmStoreURLGetter: getCharmStoreAPIURL, } return modelcmd.Wrap(cmd) }
go
func NewUpgradeCharmCommand() cmd.Command { cmd := &upgradeCharmCommand{ DeployResources: resourceadapters.DeployResources, ResolveCharm: resolveCharm, NewCharmAdder: newCharmAdder, NewCharmClient: func(conn base.APICallCloser) CharmClient { return charms.NewClient(conn) }, NewCharmUpgradeClient: func(conn base.APICallCloser) CharmAPIClient { return application.NewClient(conn) }, NewModelConfigGetter: func(conn base.APICallCloser) ModelConfigGetter { return modelconfig.NewClient(conn) }, NewResourceLister: func(conn base.APICallCloser) (ResourceLister, error) { resclient, err := resourceadapters.NewAPIClient(conn) if err != nil { return nil, err } return resclient, nil }, CharmStoreURLGetter: getCharmStoreAPIURL, } return modelcmd.Wrap(cmd) }
[ "func", "NewUpgradeCharmCommand", "(", ")", "cmd", ".", "Command", "{", "cmd", ":=", "&", "upgradeCharmCommand", "{", "DeployResources", ":", "resourceadapters", ".", "DeployResources", ",", "ResolveCharm", ":", "resolveCharm", ",", "NewCharmAdder", ":", "newCharmAdder", ",", "NewCharmClient", ":", "func", "(", "conn", "base", ".", "APICallCloser", ")", "CharmClient", "{", "return", "charms", ".", "NewClient", "(", "conn", ")", "\n", "}", ",", "NewCharmUpgradeClient", ":", "func", "(", "conn", "base", ".", "APICallCloser", ")", "CharmAPIClient", "{", "return", "application", ".", "NewClient", "(", "conn", ")", "\n", "}", ",", "NewModelConfigGetter", ":", "func", "(", "conn", "base", ".", "APICallCloser", ")", "ModelConfigGetter", "{", "return", "modelconfig", ".", "NewClient", "(", "conn", ")", "\n", "}", ",", "NewResourceLister", ":", "func", "(", "conn", "base", ".", "APICallCloser", ")", "(", "ResourceLister", ",", "error", ")", "{", "resclient", ",", "err", ":=", "resourceadapters", ".", "NewAPIClient", "(", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "resclient", ",", "nil", "\n", "}", ",", "CharmStoreURLGetter", ":", "getCharmStoreAPIURL", ",", "}", "\n", "return", "modelcmd", ".", "Wrap", "(", "cmd", ")", "\n", "}" ]
// NewUpgradeCharmCommand returns a command which upgrades application's charm.
[ "NewUpgradeCharmCommand", "returns", "a", "command", "which", "upgrades", "application", "s", "charm", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/upgradecharm.go#L41-L65
4,373
juju/juju
cmd/juju/application/upgradecharm.go
addCharm
func (c *upgradeCharmCommand) addCharm( charmAdder CharmAdder, charmRepo *charmrepo.CharmStore, config *config.Config, oldURL *charm.URL, charmRef string, deployedSeries string, force bool, ) (charmstore.CharmID, *macaroon.Macaroon, error) { var id charmstore.CharmID // Charm may have been supplied via a path reference. If so, build a // local charm URL from the deployed series. ch, newURL, err := charmrepo.NewCharmAtPathForceSeries(charmRef, deployedSeries, c.ForceSeries) if err == nil { newName := ch.Meta().Name if newName != oldURL.Name { return id, nil, errors.Errorf("cannot upgrade %q to %q", oldURL.Name, newName) } addedURL, err := charmAdder.AddLocalCharm(newURL, ch, force) id.URL = addedURL return id, nil, err } if _, ok := err.(*charmrepo.NotFoundError); ok { return id, nil, errors.Errorf("no charm found at %q", charmRef) } // If we get a "not exists" or invalid path error then we attempt to interpret // the supplied charm reference as a URL below, otherwise we return the error. if err != os.ErrNotExist && !charmrepo.IsInvalidPathError(err) { return id, nil, err } refURL, err := charm.ParseURL(charmRef) if err != nil { return id, nil, errors.Trace(err) } // Charm has been supplied as a URL so we resolve and deploy using the store. newURL, channel, supportedSeries, err := c.ResolveCharm(charmRepo.ResolveWithChannel, refURL) if err != nil { return id, nil, errors.Trace(err) } id.Channel = channel _, seriesSupportedErr := charm.SeriesForCharm(deployedSeries, supportedSeries) if !c.ForceSeries && deployedSeries != "" && newURL.Series == "" && seriesSupportedErr != nil { series := []string{"no series"} if len(supportedSeries) > 0 { series = supportedSeries } return id, nil, errors.Errorf( "cannot upgrade from single series %q charm to a charm supporting %q. Use --force-series to override.", deployedSeries, series, ) } // If no explicit revision was set with either SwitchURL // or Revision flags, discover the latest. if *newURL == *oldURL { if refURL.Revision != -1 { return id, nil, errors.Errorf("already running specified charm %q", newURL) } // No point in trying to upgrade a charm store charm when // we just determined that's the latest revision // available. return id, nil, errors.Errorf("already running latest charm %q", newURL) } curl, csMac, err := addCharmFromURL(charmAdder, newURL, channel, force) if err != nil { return id, nil, errors.Trace(err) } id.URL = curl return id, csMac, nil }
go
func (c *upgradeCharmCommand) addCharm( charmAdder CharmAdder, charmRepo *charmrepo.CharmStore, config *config.Config, oldURL *charm.URL, charmRef string, deployedSeries string, force bool, ) (charmstore.CharmID, *macaroon.Macaroon, error) { var id charmstore.CharmID // Charm may have been supplied via a path reference. If so, build a // local charm URL from the deployed series. ch, newURL, err := charmrepo.NewCharmAtPathForceSeries(charmRef, deployedSeries, c.ForceSeries) if err == nil { newName := ch.Meta().Name if newName != oldURL.Name { return id, nil, errors.Errorf("cannot upgrade %q to %q", oldURL.Name, newName) } addedURL, err := charmAdder.AddLocalCharm(newURL, ch, force) id.URL = addedURL return id, nil, err } if _, ok := err.(*charmrepo.NotFoundError); ok { return id, nil, errors.Errorf("no charm found at %q", charmRef) } // If we get a "not exists" or invalid path error then we attempt to interpret // the supplied charm reference as a URL below, otherwise we return the error. if err != os.ErrNotExist && !charmrepo.IsInvalidPathError(err) { return id, nil, err } refURL, err := charm.ParseURL(charmRef) if err != nil { return id, nil, errors.Trace(err) } // Charm has been supplied as a URL so we resolve and deploy using the store. newURL, channel, supportedSeries, err := c.ResolveCharm(charmRepo.ResolveWithChannel, refURL) if err != nil { return id, nil, errors.Trace(err) } id.Channel = channel _, seriesSupportedErr := charm.SeriesForCharm(deployedSeries, supportedSeries) if !c.ForceSeries && deployedSeries != "" && newURL.Series == "" && seriesSupportedErr != nil { series := []string{"no series"} if len(supportedSeries) > 0 { series = supportedSeries } return id, nil, errors.Errorf( "cannot upgrade from single series %q charm to a charm supporting %q. Use --force-series to override.", deployedSeries, series, ) } // If no explicit revision was set with either SwitchURL // or Revision flags, discover the latest. if *newURL == *oldURL { if refURL.Revision != -1 { return id, nil, errors.Errorf("already running specified charm %q", newURL) } // No point in trying to upgrade a charm store charm when // we just determined that's the latest revision // available. return id, nil, errors.Errorf("already running latest charm %q", newURL) } curl, csMac, err := addCharmFromURL(charmAdder, newURL, channel, force) if err != nil { return id, nil, errors.Trace(err) } id.URL = curl return id, csMac, nil }
[ "func", "(", "c", "*", "upgradeCharmCommand", ")", "addCharm", "(", "charmAdder", "CharmAdder", ",", "charmRepo", "*", "charmrepo", ".", "CharmStore", ",", "config", "*", "config", ".", "Config", ",", "oldURL", "*", "charm", ".", "URL", ",", "charmRef", "string", ",", "deployedSeries", "string", ",", "force", "bool", ",", ")", "(", "charmstore", ".", "CharmID", ",", "*", "macaroon", ".", "Macaroon", ",", "error", ")", "{", "var", "id", "charmstore", ".", "CharmID", "\n", "// Charm may have been supplied via a path reference. If so, build a", "// local charm URL from the deployed series.", "ch", ",", "newURL", ",", "err", ":=", "charmrepo", ".", "NewCharmAtPathForceSeries", "(", "charmRef", ",", "deployedSeries", ",", "c", ".", "ForceSeries", ")", "\n", "if", "err", "==", "nil", "{", "newName", ":=", "ch", ".", "Meta", "(", ")", ".", "Name", "\n", "if", "newName", "!=", "oldURL", ".", "Name", "{", "return", "id", ",", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "oldURL", ".", "Name", ",", "newName", ")", "\n", "}", "\n", "addedURL", ",", "err", ":=", "charmAdder", ".", "AddLocalCharm", "(", "newURL", ",", "ch", ",", "force", ")", "\n", "id", ".", "URL", "=", "addedURL", "\n", "return", "id", ",", "nil", ",", "err", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "charmrepo", ".", "NotFoundError", ")", ";", "ok", "{", "return", "id", ",", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "charmRef", ")", "\n", "}", "\n", "// If we get a \"not exists\" or invalid path error then we attempt to interpret", "// the supplied charm reference as a URL below, otherwise we return the error.", "if", "err", "!=", "os", ".", "ErrNotExist", "&&", "!", "charmrepo", ".", "IsInvalidPathError", "(", "err", ")", "{", "return", "id", ",", "nil", ",", "err", "\n", "}", "\n\n", "refURL", ",", "err", ":=", "charm", ".", "ParseURL", "(", "charmRef", ")", "\n", "if", "err", "!=", "nil", "{", "return", "id", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Charm has been supplied as a URL so we resolve and deploy using the store.", "newURL", ",", "channel", ",", "supportedSeries", ",", "err", ":=", "c", ".", "ResolveCharm", "(", "charmRepo", ".", "ResolveWithChannel", ",", "refURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "id", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "id", ".", "Channel", "=", "channel", "\n", "_", ",", "seriesSupportedErr", ":=", "charm", ".", "SeriesForCharm", "(", "deployedSeries", ",", "supportedSeries", ")", "\n", "if", "!", "c", ".", "ForceSeries", "&&", "deployedSeries", "!=", "\"", "\"", "&&", "newURL", ".", "Series", "==", "\"", "\"", "&&", "seriesSupportedErr", "!=", "nil", "{", "series", ":=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "if", "len", "(", "supportedSeries", ")", ">", "0", "{", "series", "=", "supportedSeries", "\n", "}", "\n", "return", "id", ",", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "deployedSeries", ",", "series", ",", ")", "\n", "}", "\n", "// If no explicit revision was set with either SwitchURL", "// or Revision flags, discover the latest.", "if", "*", "newURL", "==", "*", "oldURL", "{", "if", "refURL", ".", "Revision", "!=", "-", "1", "{", "return", "id", ",", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "newURL", ")", "\n", "}", "\n", "// No point in trying to upgrade a charm store charm when", "// we just determined that's the latest revision", "// available.", "return", "id", ",", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "newURL", ")", "\n", "}", "\n\n", "curl", ",", "csMac", ",", "err", ":=", "addCharmFromURL", "(", "charmAdder", ",", "newURL", ",", "channel", ",", "force", ")", "\n", "if", "err", "!=", "nil", "{", "return", "id", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "id", ".", "URL", "=", "curl", "\n", "return", "id", ",", "csMac", ",", "nil", "\n", "}" ]
// addCharm interprets the new charmRef and adds the specified charm if // the new charm is different to what's already deployed as specified by // oldURL.
[ "addCharm", "interprets", "the", "new", "charmRef", "and", "adds", "the", "specified", "charm", "if", "the", "new", "charm", "is", "different", "to", "what", "s", "already", "deployed", "as", "specified", "by", "oldURL", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/upgradecharm.go#L549-L620
4,374
juju/juju
cmd/juju/status/output_oneline.go
FormatOneline
func FormatOneline(writer io.Writer, value interface{}) error { return formatOneline(writer, value, func(out io.Writer, format, uName string, u unitStatus, level int) { status := fmt.Sprintf( "agent:%s, workload:%s", u.JujuStatusInfo.Current, u.WorkloadStatusInfo.Current, ) fmt.Fprintf(out, format, uName, u.PublicAddress, status, ) }) }
go
func FormatOneline(writer io.Writer, value interface{}) error { return formatOneline(writer, value, func(out io.Writer, format, uName string, u unitStatus, level int) { status := fmt.Sprintf( "agent:%s, workload:%s", u.JujuStatusInfo.Current, u.WorkloadStatusInfo.Current, ) fmt.Fprintf(out, format, uName, u.PublicAddress, status, ) }) }
[ "func", "FormatOneline", "(", "writer", "io", ".", "Writer", ",", "value", "interface", "{", "}", ")", "error", "{", "return", "formatOneline", "(", "writer", ",", "value", ",", "func", "(", "out", "io", ".", "Writer", ",", "format", ",", "uName", "string", ",", "u", "unitStatus", ",", "level", "int", ")", "{", "status", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "u", ".", "JujuStatusInfo", ".", "Current", ",", "u", ".", "WorkloadStatusInfo", ".", "Current", ",", ")", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "format", ",", "uName", ",", "u", ".", "PublicAddress", ",", "status", ",", ")", "\n", "}", ")", "\n", "}" ]
// FormatOneline writes a brief list of units and their subordinates. // Subordinates will be indented 2 spaces and listed under their // superiors. This format works with version 2 of the CLI.
[ "FormatOneline", "writes", "a", "brief", "list", "of", "units", "and", "their", "subordinates", ".", "Subordinates", "will", "be", "indented", "2", "spaces", "and", "listed", "under", "their", "superiors", ".", "This", "format", "works", "with", "version", "2", "of", "the", "CLI", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/status/output_oneline.go#L18-L31
4,375
juju/juju
container/kvm/container.go
EnsureCachedImage
func (c *kvmContainer) EnsureCachedImage(params StartParams) error { var srcFunc func() simplestreams.DataSource if params.ImageDownloadURL != "" { srcFunc = func() simplestreams.DataSource { return imagedownloads.NewDataSource(params.ImageDownloadURL) } } var fType = BIOSFType if params.Arch == arch.ARM64 { fType = UEFIFType } sp := syncParams{ arch: params.Arch, series: params.Series, stream: params.Stream, fType: fType, srcFunc: srcFunc, } logger.Debugf("synchronise images for %s %s %s %s", sp.arch, sp.series, sp.stream, params.ImageDownloadURL) var callback ProgressCallback if params.StatusCallback != nil { callback = func(msg string) { _ = params.StatusCallback(status.Provisioning, msg, nil) } } if err := Sync(sp, nil, callback); err != nil { if !errors.IsAlreadyExists(err) { return errors.Trace(err) } logger.Debugf("image already cached %s", err) } return nil }
go
func (c *kvmContainer) EnsureCachedImage(params StartParams) error { var srcFunc func() simplestreams.DataSource if params.ImageDownloadURL != "" { srcFunc = func() simplestreams.DataSource { return imagedownloads.NewDataSource(params.ImageDownloadURL) } } var fType = BIOSFType if params.Arch == arch.ARM64 { fType = UEFIFType } sp := syncParams{ arch: params.Arch, series: params.Series, stream: params.Stream, fType: fType, srcFunc: srcFunc, } logger.Debugf("synchronise images for %s %s %s %s", sp.arch, sp.series, sp.stream, params.ImageDownloadURL) var callback ProgressCallback if params.StatusCallback != nil { callback = func(msg string) { _ = params.StatusCallback(status.Provisioning, msg, nil) } } if err := Sync(sp, nil, callback); err != nil { if !errors.IsAlreadyExists(err) { return errors.Trace(err) } logger.Debugf("image already cached %s", err) } return nil }
[ "func", "(", "c", "*", "kvmContainer", ")", "EnsureCachedImage", "(", "params", "StartParams", ")", "error", "{", "var", "srcFunc", "func", "(", ")", "simplestreams", ".", "DataSource", "\n", "if", "params", ".", "ImageDownloadURL", "!=", "\"", "\"", "{", "srcFunc", "=", "func", "(", ")", "simplestreams", ".", "DataSource", "{", "return", "imagedownloads", ".", "NewDataSource", "(", "params", ".", "ImageDownloadURL", ")", "\n", "}", "\n", "}", "\n", "var", "fType", "=", "BIOSFType", "\n", "if", "params", ".", "Arch", "==", "arch", ".", "ARM64", "{", "fType", "=", "UEFIFType", "\n", "}", "\n\n", "sp", ":=", "syncParams", "{", "arch", ":", "params", ".", "Arch", ",", "series", ":", "params", ".", "Series", ",", "stream", ":", "params", ".", "Stream", ",", "fType", ":", "fType", ",", "srcFunc", ":", "srcFunc", ",", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "sp", ".", "arch", ",", "sp", ".", "series", ",", "sp", ".", "stream", ",", "params", ".", "ImageDownloadURL", ")", "\n", "var", "callback", "ProgressCallback", "\n", "if", "params", ".", "StatusCallback", "!=", "nil", "{", "callback", "=", "func", "(", "msg", "string", ")", "{", "_", "=", "params", ".", "StatusCallback", "(", "status", ".", "Provisioning", ",", "msg", ",", "nil", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "Sync", "(", "sp", ",", "nil", ",", "callback", ")", ";", "err", "!=", "nil", "{", "if", "!", "errors", ".", "IsAlreadyExists", "(", "err", ")", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// EnsureCachedImage ensures that a container image suitable for satisfying // the input start parameters has been cached on disk.
[ "EnsureCachedImage", "ensures", "that", "a", "container", "image", "suitable", "for", "satisfying", "the", "input", "start", "parameters", "has", "been", "cached", "on", "disk", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/container.go#L40-L73
4,376
juju/juju
container/kvm/container.go
Start
func (c *kvmContainer) Start(params StartParams) error { var bridge string var interfaces []libvirt.InterfaceInfo if params.Network != nil { if params.Network.NetworkType == container.BridgeNetwork { bridge = params.Network.Device for _, iface := range params.Network.Interfaces { interfaces = append(interfaces, interfaceInfo{config: iface}) } } else { err := errors.New("Non-bridge network devices not yet supported") logger.Infof(err.Error()) return err } } logger.Debugf("create the machine %s", c.name) if params.StatusCallback != nil { _ = params.StatusCallback(status.Provisioning, "Creating instance", nil) } if err := CreateMachine(CreateMachineParams{ Hostname: c.name, Series: params.Series, UserDataFile: params.UserDataFile, NetworkConfigData: params.NetworkConfigData, NetworkBridge: bridge, Memory: params.Memory, CpuCores: params.CpuCores, RootDisk: params.RootDisk, Interfaces: interfaces, }); err != nil { return err } logger.Debugf("Set machine %s to autostart", c.name) if params.StatusCallback != nil { _ = params.StatusCallback(status.Provisioning, "Starting instance", nil) } return AutostartMachine(c) }
go
func (c *kvmContainer) Start(params StartParams) error { var bridge string var interfaces []libvirt.InterfaceInfo if params.Network != nil { if params.Network.NetworkType == container.BridgeNetwork { bridge = params.Network.Device for _, iface := range params.Network.Interfaces { interfaces = append(interfaces, interfaceInfo{config: iface}) } } else { err := errors.New("Non-bridge network devices not yet supported") logger.Infof(err.Error()) return err } } logger.Debugf("create the machine %s", c.name) if params.StatusCallback != nil { _ = params.StatusCallback(status.Provisioning, "Creating instance", nil) } if err := CreateMachine(CreateMachineParams{ Hostname: c.name, Series: params.Series, UserDataFile: params.UserDataFile, NetworkConfigData: params.NetworkConfigData, NetworkBridge: bridge, Memory: params.Memory, CpuCores: params.CpuCores, RootDisk: params.RootDisk, Interfaces: interfaces, }); err != nil { return err } logger.Debugf("Set machine %s to autostart", c.name) if params.StatusCallback != nil { _ = params.StatusCallback(status.Provisioning, "Starting instance", nil) } return AutostartMachine(c) }
[ "func", "(", "c", "*", "kvmContainer", ")", "Start", "(", "params", "StartParams", ")", "error", "{", "var", "bridge", "string", "\n", "var", "interfaces", "[", "]", "libvirt", ".", "InterfaceInfo", "\n", "if", "params", ".", "Network", "!=", "nil", "{", "if", "params", ".", "Network", ".", "NetworkType", "==", "container", ".", "BridgeNetwork", "{", "bridge", "=", "params", ".", "Network", ".", "Device", "\n", "for", "_", ",", "iface", ":=", "range", "params", ".", "Network", ".", "Interfaces", "{", "interfaces", "=", "append", "(", "interfaces", ",", "interfaceInfo", "{", "config", ":", "iface", "}", ")", "\n", "}", "\n", "}", "else", "{", "err", ":=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "logger", ".", "Infof", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "c", ".", "name", ")", "\n", "if", "params", ".", "StatusCallback", "!=", "nil", "{", "_", "=", "params", ".", "StatusCallback", "(", "status", ".", "Provisioning", ",", "\"", "\"", ",", "nil", ")", "\n", "}", "\n", "if", "err", ":=", "CreateMachine", "(", "CreateMachineParams", "{", "Hostname", ":", "c", ".", "name", ",", "Series", ":", "params", ".", "Series", ",", "UserDataFile", ":", "params", ".", "UserDataFile", ",", "NetworkConfigData", ":", "params", ".", "NetworkConfigData", ",", "NetworkBridge", ":", "bridge", ",", "Memory", ":", "params", ".", "Memory", ",", "CpuCores", ":", "params", ".", "CpuCores", ",", "RootDisk", ":", "params", ".", "RootDisk", ",", "Interfaces", ":", "interfaces", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "c", ".", "name", ")", "\n", "if", "params", ".", "StatusCallback", "!=", "nil", "{", "_", "=", "params", ".", "StatusCallback", "(", "status", ".", "Provisioning", ",", "\"", "\"", ",", "nil", ")", "\n", "}", "\n", "return", "AutostartMachine", "(", "c", ")", "\n", "}" ]
// Start creates and starts a new container. // It assumes that the backing image is already cached on disk.
[ "Start", "creates", "and", "starts", "a", "new", "container", ".", "It", "assumes", "that", "the", "backing", "image", "is", "already", "cached", "on", "disk", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/container.go#L77-L115
4,377
juju/juju
provider/oracle/environ.go
InstanceAvailabilityZoneNames
func (o *OracleEnviron) InstanceAvailabilityZoneNames(ctx context.ProviderCallContext, ids []instance.Id) ([]string, error) { instances, err := o.Instances(ctx, ids) if err != nil && err != environs.ErrPartialInstances { return nil, err } zones := make([]string, len(instances)) for idx := range instances { zones[idx] = "default" } return zones, nil }
go
func (o *OracleEnviron) InstanceAvailabilityZoneNames(ctx context.ProviderCallContext, ids []instance.Id) ([]string, error) { instances, err := o.Instances(ctx, ids) if err != nil && err != environs.ErrPartialInstances { return nil, err } zones := make([]string, len(instances)) for idx := range instances { zones[idx] = "default" } return zones, nil }
[ "func", "(", "o", "*", "OracleEnviron", ")", "InstanceAvailabilityZoneNames", "(", "ctx", "context", ".", "ProviderCallContext", ",", "ids", "[", "]", "instance", ".", "Id", ")", "(", "[", "]", "string", ",", "error", ")", "{", "instances", ",", "err", ":=", "o", ".", "Instances", "(", "ctx", ",", "ids", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "environs", ".", "ErrPartialInstances", "{", "return", "nil", ",", "err", "\n", "}", "\n", "zones", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "instances", ")", ")", "\n", "for", "idx", ":=", "range", "instances", "{", "zones", "[", "idx", "]", "=", "\"", "\"", "\n", "}", "\n", "return", "zones", ",", "nil", "\n", "}" ]
// InstanceAvailabilityzoneNames is defined in the common.ZonedEnviron interface
[ "InstanceAvailabilityzoneNames", "is", "defined", "in", "the", "common", ".", "ZonedEnviron", "interface" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/environ.go#L91-L101
4,378
juju/juju
provider/oracle/environ.go
NewOracleEnviron
func NewOracleEnviron(p *EnvironProvider, args environs.OpenParams, client EnvironAPI, c clock.Clock) (env *OracleEnviron, err error) { if client == nil { return nil, errors.NotFoundf("oracle client") } if p == nil { return nil, errors.NotFoundf("environ proivder") } env = &OracleEnviron{ p: p, spec: args.Cloud, cfg: args.Config, mutex: &sync.Mutex{}, client: client, clock: c, } env.namespace, err = instance.NewNamespace(env.cfg.UUID()) if err != nil { return nil, errors.Trace(err) } env.Firewaller = oraclenet.NewFirewall(env, client, c) env.Networking = oraclenet.NewEnviron(client, env) source := rand.NewSource(env.clock.Now().UTC().UnixNano()) r := rand.New(source) env.rand = r return env, nil }
go
func NewOracleEnviron(p *EnvironProvider, args environs.OpenParams, client EnvironAPI, c clock.Clock) (env *OracleEnviron, err error) { if client == nil { return nil, errors.NotFoundf("oracle client") } if p == nil { return nil, errors.NotFoundf("environ proivder") } env = &OracleEnviron{ p: p, spec: args.Cloud, cfg: args.Config, mutex: &sync.Mutex{}, client: client, clock: c, } env.namespace, err = instance.NewNamespace(env.cfg.UUID()) if err != nil { return nil, errors.Trace(err) } env.Firewaller = oraclenet.NewFirewall(env, client, c) env.Networking = oraclenet.NewEnviron(client, env) source := rand.NewSource(env.clock.Now().UTC().UnixNano()) r := rand.New(source) env.rand = r return env, nil }
[ "func", "NewOracleEnviron", "(", "p", "*", "EnvironProvider", ",", "args", "environs", ".", "OpenParams", ",", "client", "EnvironAPI", ",", "c", "clock", ".", "Clock", ")", "(", "env", "*", "OracleEnviron", ",", "err", "error", ")", "{", "if", "client", "==", "nil", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "p", "==", "nil", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}", "\n", "env", "=", "&", "OracleEnviron", "{", "p", ":", "p", ",", "spec", ":", "args", ".", "Cloud", ",", "cfg", ":", "args", ".", "Config", ",", "mutex", ":", "&", "sync", ".", "Mutex", "{", "}", ",", "client", ":", "client", ",", "clock", ":", "c", ",", "}", "\n", "env", ".", "namespace", ",", "err", "=", "instance", ".", "NewNamespace", "(", "env", ".", "cfg", ".", "UUID", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "env", ".", "Firewaller", "=", "oraclenet", ".", "NewFirewall", "(", "env", ",", "client", ",", "c", ")", "\n", "env", ".", "Networking", "=", "oraclenet", ".", "NewEnviron", "(", "client", ",", "env", ")", "\n\n", "source", ":=", "rand", ".", "NewSource", "(", "env", ".", "clock", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "r", ":=", "rand", ".", "New", "(", "source", ")", "\n", "env", ".", "rand", "=", "r", "\n\n", "return", "env", ",", "nil", "\n", "}" ]
// NewOracleEnviron returns a new OracleEnviron
[ "NewOracleEnviron", "returns", "a", "new", "OracleEnviron" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/environ.go#L104-L131
4,379
juju/juju
provider/oracle/environ.go
buildSpacesMap
func (e *OracleEnviron) buildSpacesMap(ctx context.ProviderCallContext) (map[string]network.SpaceInfo, map[string]string, error) { empty := set.Strings{} providerIdMap := map[string]string{} // NOTE (gsamfira): This seems brittle to me, and I would much rather get this // from state, as that information should already be there from the discovered spaces // and that is the information that gets presented to the user when running: // juju spaces // However I have not found a clean way to access that info from the provider, // without creating a facade. Someone with more knowledge on this might be able to chip in. spaces, err := e.Spaces(ctx) if err != nil { return nil, providerIdMap, errors.Trace(err) } spaceMap := make(map[string]network.SpaceInfo) for _, space := range spaces { jujuName := network.ConvertSpaceName(space.Name, empty) spaceMap[jujuName] = space empty.Add(jujuName) providerIdMap[string(space.ProviderId)] = space.Name } return spaceMap, providerIdMap, nil }
go
func (e *OracleEnviron) buildSpacesMap(ctx context.ProviderCallContext) (map[string]network.SpaceInfo, map[string]string, error) { empty := set.Strings{} providerIdMap := map[string]string{} // NOTE (gsamfira): This seems brittle to me, and I would much rather get this // from state, as that information should already be there from the discovered spaces // and that is the information that gets presented to the user when running: // juju spaces // However I have not found a clean way to access that info from the provider, // without creating a facade. Someone with more knowledge on this might be able to chip in. spaces, err := e.Spaces(ctx) if err != nil { return nil, providerIdMap, errors.Trace(err) } spaceMap := make(map[string]network.SpaceInfo) for _, space := range spaces { jujuName := network.ConvertSpaceName(space.Name, empty) spaceMap[jujuName] = space empty.Add(jujuName) providerIdMap[string(space.ProviderId)] = space.Name } return spaceMap, providerIdMap, nil }
[ "func", "(", "e", "*", "OracleEnviron", ")", "buildSpacesMap", "(", "ctx", "context", ".", "ProviderCallContext", ")", "(", "map", "[", "string", "]", "network", ".", "SpaceInfo", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "empty", ":=", "set", ".", "Strings", "{", "}", "\n", "providerIdMap", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "// NOTE (gsamfira): This seems brittle to me, and I would much rather get this", "// from state, as that information should already be there from the discovered spaces", "// and that is the information that gets presented to the user when running:", "// juju spaces", "// However I have not found a clean way to access that info from the provider,", "// without creating a facade. Someone with more knowledge on this might be able to chip in.", "spaces", ",", "err", ":=", "e", ".", "Spaces", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "providerIdMap", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "spaceMap", ":=", "make", "(", "map", "[", "string", "]", "network", ".", "SpaceInfo", ")", "\n", "for", "_", ",", "space", ":=", "range", "spaces", "{", "jujuName", ":=", "network", ".", "ConvertSpaceName", "(", "space", ".", "Name", ",", "empty", ")", "\n", "spaceMap", "[", "jujuName", "]", "=", "space", "\n", "empty", ".", "Add", "(", "jujuName", ")", "\n", "providerIdMap", "[", "string", "(", "space", ".", "ProviderId", ")", "]", "=", "space", ".", "Name", "\n", "}", "\n", "return", "spaceMap", ",", "providerIdMap", ",", "nil", "\n\n", "}" ]
// buildSpacesMap builds a map with juju converted names from provider space names // // shamelessly copied from the MAAS provider
[ "buildSpacesMap", "builds", "a", "map", "with", "juju", "converted", "names", "from", "provider", "space", "names", "shamelessly", "copied", "from", "the", "MAAS", "provider" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/environ.go#L211-L233
4,380
juju/juju
provider/oracle/environ.go
StopInstances
func (o *OracleEnviron) StopInstances(ctx context.ProviderCallContext, ids ...instance.Id) error { oracleInstances, err := o.getOracleInstances(ids...) if err == environs.ErrNoInstances { return nil } else if err != nil { return err } logger.Debugf("terminating instances %v", ids) if err := o.terminateInstances(oracleInstances...); err != nil { return err } return nil }
go
func (o *OracleEnviron) StopInstances(ctx context.ProviderCallContext, ids ...instance.Id) error { oracleInstances, err := o.getOracleInstances(ids...) if err == environs.ErrNoInstances { return nil } else if err != nil { return err } logger.Debugf("terminating instances %v", ids) if err := o.terminateInstances(oracleInstances...); err != nil { return err } return nil }
[ "func", "(", "o", "*", "OracleEnviron", ")", "StopInstances", "(", "ctx", "context", ".", "ProviderCallContext", ",", "ids", "...", "instance", ".", "Id", ")", "error", "{", "oracleInstances", ",", "err", ":=", "o", ".", "getOracleInstances", "(", "ids", "...", ")", "\n", "if", "err", "==", "environs", ".", "ErrNoInstances", "{", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "ids", ")", "\n", "if", "err", ":=", "o", ".", "terminateInstances", "(", "oracleInstances", "...", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// StopInstances is part of the InstanceBroker interface.
[ "StopInstances", "is", "part", "of", "the", "InstanceBroker", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/environ.go#L487-L501
4,381
juju/juju
provider/oracle/environ.go
getOracleInstances
func (o *OracleEnviron) getOracleInstances(ids ...instance.Id) ([]*oracleInstance, error) { ret := make([]*oracleInstance, 0, len(ids)) resp, err := o.client.AllInstances(nil) if err != nil { return nil, errors.Trace(err) } if len(resp.Result) == 0 { return nil, environs.ErrNoInstances } for _, val := range resp.Result { for _, id := range ids { oInst, err := newInstance(val, o) if err != nil { return nil, errors.Trace(err) } if oInst.Id() == id { ret = append(ret, oInst) break } } } if len(ret) < len(ids) { return ret, environs.ErrPartialInstances } return ret, nil }
go
func (o *OracleEnviron) getOracleInstances(ids ...instance.Id) ([]*oracleInstance, error) { ret := make([]*oracleInstance, 0, len(ids)) resp, err := o.client.AllInstances(nil) if err != nil { return nil, errors.Trace(err) } if len(resp.Result) == 0 { return nil, environs.ErrNoInstances } for _, val := range resp.Result { for _, id := range ids { oInst, err := newInstance(val, o) if err != nil { return nil, errors.Trace(err) } if oInst.Id() == id { ret = append(ret, oInst) break } } } if len(ret) < len(ids) { return ret, environs.ErrPartialInstances } return ret, nil }
[ "func", "(", "o", "*", "OracleEnviron", ")", "getOracleInstances", "(", "ids", "...", "instance", ".", "Id", ")", "(", "[", "]", "*", "oracleInstance", ",", "error", ")", "{", "ret", ":=", "make", "(", "[", "]", "*", "oracleInstance", ",", "0", ",", "len", "(", "ids", ")", ")", "\n", "resp", ",", "err", ":=", "o", ".", "client", ".", "AllInstances", "(", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "len", "(", "resp", ".", "Result", ")", "==", "0", "{", "return", "nil", ",", "environs", ".", "ErrNoInstances", "\n", "}", "\n\n", "for", "_", ",", "val", ":=", "range", "resp", ".", "Result", "{", "for", "_", ",", "id", ":=", "range", "ids", "{", "oInst", ",", "err", ":=", "newInstance", "(", "val", ",", "o", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "oInst", ".", "Id", "(", ")", "==", "id", "{", "ret", "=", "append", "(", "ret", ",", "oInst", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "len", "(", "ret", ")", "<", "len", "(", "ids", ")", "{", "return", "ret", ",", "environs", ".", "ErrPartialInstances", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// getOracleInstances attempts to fetch information from the oracle API for the // specified IDs.
[ "getOracleInstances", "attempts", "to", "fetch", "information", "from", "the", "oracle", "API", "for", "the", "specified", "IDs", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/environ.go#L553-L580
4,382
juju/juju
provider/oracle/environ.go
AllInstances
func (o *OracleEnviron) AllInstances(ctx context.ProviderCallContext) ([]envinstance.Instance, error) { tagFilter := tagValue{tags.JujuModel, o.Config().UUID()} all, err := o.allInstances(tagFilter) if err != nil { return nil, err } ret := make([]envinstance.Instance, len(all)) for i, val := range all { ret[i] = val } return ret, nil }
go
func (o *OracleEnviron) AllInstances(ctx context.ProviderCallContext) ([]envinstance.Instance, error) { tagFilter := tagValue{tags.JujuModel, o.Config().UUID()} all, err := o.allInstances(tagFilter) if err != nil { return nil, err } ret := make([]envinstance.Instance, len(all)) for i, val := range all { ret[i] = val } return ret, nil }
[ "func", "(", "o", "*", "OracleEnviron", ")", "AllInstances", "(", "ctx", "context", ".", "ProviderCallContext", ")", "(", "[", "]", "envinstance", ".", "Instance", ",", "error", ")", "{", "tagFilter", ":=", "tagValue", "{", "tags", ".", "JujuModel", ",", "o", ".", "Config", "(", ")", ".", "UUID", "(", ")", "}", "\n", "all", ",", "err", ":=", "o", ".", "allInstances", "(", "tagFilter", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ret", ":=", "make", "(", "[", "]", "envinstance", ".", "Instance", ",", "len", "(", "all", ")", ")", "\n", "for", "i", ",", "val", ":=", "range", "all", "{", "ret", "[", "i", "]", "=", "val", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// AllInstances is part of the InstanceBroker interface.
[ "AllInstances", "is", "part", "of", "the", "InstanceBroker", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/environ.go#L595-L607
4,383
juju/juju
provider/oracle/environ.go
MaintainInstance
func (o *OracleEnviron) MaintainInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) error { return nil }
go
func (o *OracleEnviron) MaintainInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) error { return nil }
[ "func", "(", "o", "*", "OracleEnviron", ")", "MaintainInstance", "(", "ctx", "context", ".", "ProviderCallContext", ",", "args", "environs", ".", "StartInstanceParams", ")", "error", "{", "return", "nil", "\n", "}" ]
// MaintainInstance is part of the InstanceBroker interface.
[ "MaintainInstance", "is", "part", "of", "the", "InstanceBroker", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/environ.go#L636-L638
4,384
juju/juju
provider/oracle/environ.go
Config
func (o *OracleEnviron) Config() *config.Config { o.mutex.Lock() defer o.mutex.Unlock() return o.cfg }
go
func (o *OracleEnviron) Config() *config.Config { o.mutex.Lock() defer o.mutex.Unlock() return o.cfg }
[ "func", "(", "o", "*", "OracleEnviron", ")", "Config", "(", ")", "*", "config", ".", "Config", "{", "o", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "o", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "o", ".", "cfg", "\n", "}" ]
// Config is part of the Environ interface.
[ "Config", "is", "part", "of", "the", "Environ", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/environ.go#L641-L645
4,385
juju/juju
provider/oracle/environ.go
ConstraintsValidator
func (o *OracleEnviron) ConstraintsValidator(ctx context.ProviderCallContext) (constraints.Validator, error) { // list of unsupported oracle provider constraints unsupportedConstraints := []string{ constraints.Container, constraints.CpuPower, constraints.RootDisk, constraints.VirtType, } // we choose to use the default validator implementation validator := constraints.NewValidator() // we must feed the validator that the oracle cloud // provider does not support these constraints validator.RegisterUnsupported(unsupportedConstraints) validator.RegisterVocabulary(constraints.Arch, []string{arch.I386, arch.AMD64}) logger.Infof("Returning constraints validator: %v", validator) return validator, nil }
go
func (o *OracleEnviron) ConstraintsValidator(ctx context.ProviderCallContext) (constraints.Validator, error) { // list of unsupported oracle provider constraints unsupportedConstraints := []string{ constraints.Container, constraints.CpuPower, constraints.RootDisk, constraints.VirtType, } // we choose to use the default validator implementation validator := constraints.NewValidator() // we must feed the validator that the oracle cloud // provider does not support these constraints validator.RegisterUnsupported(unsupportedConstraints) validator.RegisterVocabulary(constraints.Arch, []string{arch.I386, arch.AMD64}) logger.Infof("Returning constraints validator: %v", validator) return validator, nil }
[ "func", "(", "o", "*", "OracleEnviron", ")", "ConstraintsValidator", "(", "ctx", "context", ".", "ProviderCallContext", ")", "(", "constraints", ".", "Validator", ",", "error", ")", "{", "// list of unsupported oracle provider constraints", "unsupportedConstraints", ":=", "[", "]", "string", "{", "constraints", ".", "Container", ",", "constraints", ".", "CpuPower", ",", "constraints", ".", "RootDisk", ",", "constraints", ".", "VirtType", ",", "}", "\n\n", "// we choose to use the default validator implementation", "validator", ":=", "constraints", ".", "NewValidator", "(", ")", "\n", "// we must feed the validator that the oracle cloud", "// provider does not support these constraints", "validator", ".", "RegisterUnsupported", "(", "unsupportedConstraints", ")", "\n", "validator", ".", "RegisterVocabulary", "(", "constraints", ".", "Arch", ",", "[", "]", "string", "{", "arch", ".", "I386", ",", "arch", ".", "AMD64", "}", ")", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "validator", ")", "\n", "return", "validator", ",", "nil", "\n", "}" ]
// ConstraintsValidator is part of the environs.Environ interface.
[ "ConstraintsValidator", "is", "part", "of", "the", "environs", ".", "Environ", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/environ.go#L648-L665
4,386
juju/juju
provider/oracle/environ.go
DestroyController
func (o *OracleEnviron) DestroyController(ctx context.ProviderCallContext, controllerUUID string) error { err := o.Destroy(ctx) if err != nil { logger.Errorf("Failed to destroy environment through controller: %s", errors.Trace(err)) } instances, err := o.allControllerManagedInstances(controllerUUID) if err != nil { if err == environs.ErrNoInstances { return nil } return errors.Trace(err) } ids := make([]instance.Id, len(instances)) for i, val := range instances { ids[i] = val.Id() } return o.StopInstances(ctx, ids...) }
go
func (o *OracleEnviron) DestroyController(ctx context.ProviderCallContext, controllerUUID string) error { err := o.Destroy(ctx) if err != nil { logger.Errorf("Failed to destroy environment through controller: %s", errors.Trace(err)) } instances, err := o.allControllerManagedInstances(controllerUUID) if err != nil { if err == environs.ErrNoInstances { return nil } return errors.Trace(err) } ids := make([]instance.Id, len(instances)) for i, val := range instances { ids[i] = val.Id() } return o.StopInstances(ctx, ids...) }
[ "func", "(", "o", "*", "OracleEnviron", ")", "DestroyController", "(", "ctx", "context", ".", "ProviderCallContext", ",", "controllerUUID", "string", ")", "error", "{", "err", ":=", "o", ".", "Destroy", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", ")", "\n", "}", "\n", "instances", ",", "err", ":=", "o", ".", "allControllerManagedInstances", "(", "controllerUUID", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "environs", ".", "ErrNoInstances", "{", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ids", ":=", "make", "(", "[", "]", "instance", ".", "Id", ",", "len", "(", "instances", ")", ")", "\n", "for", "i", ",", "val", ":=", "range", "instances", "{", "ids", "[", "i", "]", "=", "val", ".", "Id", "(", ")", "\n", "}", "\n", "return", "o", ".", "StopInstances", "(", "ctx", ",", "ids", "...", ")", "\n", "}" ]
// DestroyController is part of the environs.Environ interface.
[ "DestroyController", "is", "part", "of", "the", "environs", ".", "Environ", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/environ.go#L745-L762
4,387
juju/juju
provider/oracle/environ.go
InstanceTypes
func (o *OracleEnviron) InstanceTypes(context.ProviderCallContext, constraints.Value) (envinstance.InstanceTypesWithCostMetadata, error) { var i envinstance.InstanceTypesWithCostMetadata return i, nil }
go
func (o *OracleEnviron) InstanceTypes(context.ProviderCallContext, constraints.Value) (envinstance.InstanceTypesWithCostMetadata, error) { var i envinstance.InstanceTypesWithCostMetadata return i, nil }
[ "func", "(", "o", "*", "OracleEnviron", ")", "InstanceTypes", "(", "context", ".", "ProviderCallContext", ",", "constraints", ".", "Value", ")", "(", "envinstance", ".", "InstanceTypesWithCostMetadata", ",", "error", ")", "{", "var", "i", "envinstance", ".", "InstanceTypesWithCostMetadata", "\n", "return", "i", ",", "nil", "\n", "}" ]
// InstanceTypes is part of the environs.InstanceTypesFetcher interface.
[ "InstanceTypes", "is", "part", "of", "the", "environs", ".", "InstanceTypesFetcher", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/environ.go#L775-L778
4,388
juju/juju
provider/oracle/environ.go
createInstance
func (e *OracleEnviron) createInstance(params oci.InstanceParams) (*oracleInstance, error) { if len(params.Instances) > 1 { return nil, errors.NotSupportedf("launching multiple instances") } logger.Debugf("running createInstance") resp, err := e.client.CreateInstance(params) if err != nil { return nil, errors.Trace(err) } instance, err := newInstance(resp.Instances[0], e) if err != nil { return nil, errors.Trace(err) } return instance, nil }
go
func (e *OracleEnviron) createInstance(params oci.InstanceParams) (*oracleInstance, error) { if len(params.Instances) > 1 { return nil, errors.NotSupportedf("launching multiple instances") } logger.Debugf("running createInstance") resp, err := e.client.CreateInstance(params) if err != nil { return nil, errors.Trace(err) } instance, err := newInstance(resp.Instances[0], e) if err != nil { return nil, errors.Trace(err) } return instance, nil }
[ "func", "(", "e", "*", "OracleEnviron", ")", "createInstance", "(", "params", "oci", ".", "InstanceParams", ")", "(", "*", "oracleInstance", ",", "error", ")", "{", "if", "len", "(", "params", ".", "Instances", ")", ">", "1", "{", "return", "nil", ",", "errors", ".", "NotSupportedf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "resp", ",", "err", ":=", "e", ".", "client", ".", "CreateInstance", "(", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "instance", ",", "err", ":=", "newInstance", "(", "resp", ".", "Instances", "[", "0", "]", ",", "e", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "instance", ",", "nil", "\n", "}" ]
// createInstance creates a new instance inside the oracle infrastructure
[ "createInstance", "creates", "a", "new", "instance", "inside", "the", "oracle", "infrastructure" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/environ.go#L781-L798
4,389
juju/juju
environs/errors.go
IsAvailabilityZoneIndependent
func IsAvailabilityZoneIndependent(err error) bool { if err, ok := errors.Cause(err).(AvailabilityZoneError); ok { return err.AvailabilityZoneIndependent() } return false }
go
func IsAvailabilityZoneIndependent(err error) bool { if err, ok := errors.Cause(err).(AvailabilityZoneError); ok { return err.AvailabilityZoneIndependent() } return false }
[ "func", "IsAvailabilityZoneIndependent", "(", "err", "error", ")", "bool", "{", "if", "err", ",", "ok", ":=", "errors", ".", "Cause", "(", "err", ")", ".", "(", "AvailabilityZoneError", ")", ";", "ok", "{", "return", "err", ".", "AvailabilityZoneIndependent", "(", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsAvailabilityZoneIndependent reports whether or not the given error, // or its cause, is independent of any particular availability zone. // Juju uses this to decide whether or not to attempt the failed operation // in another availability zone; zone-independent failures will not be // reattempted. // // If the error implements AvailabilityZoneError, then the result of // calling its AvailabilityZoneIndependent method will be returned; // otherwise this function returns false. That is, errors are assumed // to be specific to an availability zone by default, so that they can // be retried in another availability zone.
[ "IsAvailabilityZoneIndependent", "reports", "whether", "or", "not", "the", "given", "error", "or", "its", "cause", "is", "independent", "of", "any", "particular", "availability", "zone", ".", "Juju", "uses", "this", "to", "decide", "whether", "or", "not", "to", "attempt", "the", "failed", "operation", "in", "another", "availability", "zone", ";", "zone", "-", "independent", "failures", "will", "not", "be", "reattempted", ".", "If", "the", "error", "implements", "AvailabilityZoneError", "then", "the", "result", "of", "calling", "its", "AvailabilityZoneIndependent", "method", "will", "be", "returned", ";", "otherwise", "this", "function", "returns", "false", ".", "That", "is", "errors", "are", "assumed", "to", "be", "specific", "to", "an", "availability", "zone", "by", "default", "so", "that", "they", "can", "be", "retried", "in", "another", "availability", "zone", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/errors.go#L38-L43
4,390
juju/juju
worker/uniter/runner/context/env.go
OSDependentEnvVars
func OSDependentEnvVars(paths Paths) []string { switch jujuos.HostOS() { case jujuos.Windows: return windowsEnv(paths) case jujuos.Ubuntu: return ubuntuEnv(paths) case jujuos.CentOS: return centosEnv(paths) case jujuos.OpenSUSE: return opensuseEnv(paths) } return nil }
go
func OSDependentEnvVars(paths Paths) []string { switch jujuos.HostOS() { case jujuos.Windows: return windowsEnv(paths) case jujuos.Ubuntu: return ubuntuEnv(paths) case jujuos.CentOS: return centosEnv(paths) case jujuos.OpenSUSE: return opensuseEnv(paths) } return nil }
[ "func", "OSDependentEnvVars", "(", "paths", "Paths", ")", "[", "]", "string", "{", "switch", "jujuos", ".", "HostOS", "(", ")", "{", "case", "jujuos", ".", "Windows", ":", "return", "windowsEnv", "(", "paths", ")", "\n", "case", "jujuos", ".", "Ubuntu", ":", "return", "ubuntuEnv", "(", "paths", ")", "\n", "case", "jujuos", ".", "CentOS", ":", "return", "centosEnv", "(", "paths", ")", "\n", "case", "jujuos", ".", "OpenSUSE", ":", "return", "opensuseEnv", "(", "paths", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// OSDependentEnvVars returns the OS-dependent environment variables that // should be set for a hook context.
[ "OSDependentEnvVars", "returns", "the", "OS", "-", "dependent", "environment", "variables", "that", "should", "be", "set", "for", "a", "hook", "context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/context/env.go#L15-L27
4,391
juju/juju
worker/uniter/runner/context/env.go
windowsEnv
func windowsEnv(paths Paths) []string { charmDir := paths.GetCharmDir() charmModules := filepath.Join(charmDir, "lib", "Modules") return []string{ "Path=" + paths.GetToolsDir() + ";" + os.Getenv("Path"), "PSModulePath=" + os.Getenv("PSModulePath") + ";" + charmModules, } }
go
func windowsEnv(paths Paths) []string { charmDir := paths.GetCharmDir() charmModules := filepath.Join(charmDir, "lib", "Modules") return []string{ "Path=" + paths.GetToolsDir() + ";" + os.Getenv("Path"), "PSModulePath=" + os.Getenv("PSModulePath") + ";" + charmModules, } }
[ "func", "windowsEnv", "(", "paths", "Paths", ")", "[", "]", "string", "{", "charmDir", ":=", "paths", ".", "GetCharmDir", "(", ")", "\n", "charmModules", ":=", "filepath", ".", "Join", "(", "charmDir", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "[", "]", "string", "{", "\"", "\"", "+", "paths", ".", "GetToolsDir", "(", ")", "+", "\"", "\"", "+", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "\"", "\"", "+", "os", ".", "Getenv", "(", "\"", "\"", ")", "+", "\"", "\"", "+", "charmModules", ",", "}", "\n", "}" ]
// windowsEnv adds windows specific environment variables. PSModulePath // helps hooks use normal imports instead of dot sourcing modules // its a convenience variable. The PATH variable delimiter is // a semicolon instead of a colon
[ "windowsEnv", "adds", "windows", "specific", "environment", "variables", ".", "PSModulePath", "helps", "hooks", "use", "normal", "imports", "instead", "of", "dot", "sourcing", "modules", "its", "a", "convenience", "variable", ".", "The", "PATH", "variable", "delimiter", "is", "a", "semicolon", "instead", "of", "a", "colon" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/context/env.go#L57-L64
4,392
juju/juju
upgrades/steps_223.go
stateStepsFor223
func stateStepsFor223() []Step { return []Step{ &upgradeStep{ description: "add max-action-age and max-action-size config settings", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddActionPruneSettings() }, }, } }
go
func stateStepsFor223() []Step { return []Step{ &upgradeStep{ description: "add max-action-age and max-action-size config settings", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddActionPruneSettings() }, }, } }
[ "func", "stateStepsFor223", "(", ")", "[", "]", "Step", "{", "return", "[", "]", "Step", "{", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "context", ".", "State", "(", ")", ".", "AddActionPruneSettings", "(", ")", "\n", "}", ",", "}", ",", "}", "\n", "}" ]
// stateStepsFor223 returns upgrade steps for Juju 2.2.3 that manipulate state directly.
[ "stateStepsFor223", "returns", "upgrade", "steps", "for", "Juju", "2", ".", "2", ".", "3", "that", "manipulate", "state", "directly", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/steps_223.go#L7-L17
4,393
juju/juju
apiserver/facades/client/controller/destroy.go
DestroyController
func (c *ControllerAPIv3) DestroyController(args params.DestroyControllerArgs) error { if args.DestroyStorage != nil { return errors.New("destroy-storage unexpected on the v3 API") } destroyStorage := true args.DestroyStorage = &destroyStorage return destroyController(c.state, c.statePool, c.authorizer, args) }
go
func (c *ControllerAPIv3) DestroyController(args params.DestroyControllerArgs) error { if args.DestroyStorage != nil { return errors.New("destroy-storage unexpected on the v3 API") } destroyStorage := true args.DestroyStorage = &destroyStorage return destroyController(c.state, c.statePool, c.authorizer, args) }
[ "func", "(", "c", "*", "ControllerAPIv3", ")", "DestroyController", "(", "args", "params", ".", "DestroyControllerArgs", ")", "error", "{", "if", "args", ".", "DestroyStorage", "!=", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "destroyStorage", ":=", "true", "\n", "args", ".", "DestroyStorage", "=", "&", "destroyStorage", "\n", "return", "destroyController", "(", "c", ".", "state", ",", "c", ".", "statePool", ",", "c", ".", "authorizer", ",", "args", ")", "\n", "}" ]
// DestroyController destroys the controller. // // The v3 implementation of DestroyController ignores the DestroyStorage // field of the arguments, and unconditionally destroys all storage in // the controller. // // See ControllerAPIv4.DestroyController for more details.
[ "DestroyController", "destroys", "the", "controller", ".", "The", "v3", "implementation", "of", "DestroyController", "ignores", "the", "DestroyStorage", "field", "of", "the", "arguments", "and", "unconditionally", "destroys", "all", "storage", "in", "the", "controller", ".", "See", "ControllerAPIv4", ".", "DestroyController", "for", "more", "details", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/destroy.go#L23-L30
4,394
juju/juju
apiserver/facades/client/controller/destroy.go
DestroyController
func (c *ControllerAPI) DestroyController(args params.DestroyControllerArgs) error { return destroyController(c.state, c.statePool, c.authorizer, args) }
go
func (c *ControllerAPI) DestroyController(args params.DestroyControllerArgs) error { return destroyController(c.state, c.statePool, c.authorizer, args) }
[ "func", "(", "c", "*", "ControllerAPI", ")", "DestroyController", "(", "args", "params", ".", "DestroyControllerArgs", ")", "error", "{", "return", "destroyController", "(", "c", ".", "state", ",", "c", ".", "statePool", ",", "c", ".", "authorizer", ",", "args", ")", "\n", "}" ]
// DestroyController destroys the controller. // // If the args specify the destruction of the models, this method will // attempt to do so. Otherwise, if the controller has any non-empty, // non-Dead hosted models, then an error with the code // params.CodeHasHostedModels will be transmitted.
[ "DestroyController", "destroys", "the", "controller", ".", "If", "the", "args", "specify", "the", "destruction", "of", "the", "models", "this", "method", "will", "attempt", "to", "do", "so", ".", "Otherwise", "if", "the", "controller", "has", "any", "non", "-", "empty", "non", "-", "Dead", "hosted", "models", "then", "an", "error", "with", "the", "code", "params", ".", "CodeHasHostedModels", "will", "be", "transmitted", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/destroy.go#L38-L40
4,395
juju/juju
resource/api/helpers.go
Resource2API
func Resource2API(res resource.Resource) params.Resource { return params.Resource{ CharmResource: CharmResource2API(res.Resource), ID: res.ID, PendingID: res.PendingID, ApplicationID: res.ApplicationID, Username: res.Username, Timestamp: res.Timestamp, } }
go
func Resource2API(res resource.Resource) params.Resource { return params.Resource{ CharmResource: CharmResource2API(res.Resource), ID: res.ID, PendingID: res.PendingID, ApplicationID: res.ApplicationID, Username: res.Username, Timestamp: res.Timestamp, } }
[ "func", "Resource2API", "(", "res", "resource", ".", "Resource", ")", "params", ".", "Resource", "{", "return", "params", ".", "Resource", "{", "CharmResource", ":", "CharmResource2API", "(", "res", ".", "Resource", ")", ",", "ID", ":", "res", ".", "ID", ",", "PendingID", ":", "res", ".", "PendingID", ",", "ApplicationID", ":", "res", ".", "ApplicationID", ",", "Username", ":", "res", ".", "Username", ",", "Timestamp", ":", "res", ".", "Timestamp", ",", "}", "\n", "}" ]
// Resource2API converts a resource.Resource into // a Resource struct.
[ "Resource2API", "converts", "a", "resource", ".", "Resource", "into", "a", "Resource", "struct", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/helpers.go#L18-L27
4,396
juju/juju
resource/api/helpers.go
APIResult2ApplicationResources
func APIResult2ApplicationResources(apiResult params.ResourcesResult) (resource.ApplicationResources, error) { var result resource.ApplicationResources if apiResult.Error != nil { // TODO(ericsnow) Return the resources too? err := common.RestoreError(apiResult.Error) return resource.ApplicationResources{}, errors.Trace(err) } for _, apiRes := range apiResult.Resources { res, err := API2Resource(apiRes) if err != nil { // This could happen if the server is misbehaving // or non-conforming. // TODO(ericsnow) Aggregate errors? return resource.ApplicationResources{}, errors.Annotate(err, "got bad data from server") } result.Resources = append(result.Resources, res) } for _, unitRes := range apiResult.UnitResources { tag, err := names.ParseUnitTag(unitRes.Tag) if err != nil { return resource.ApplicationResources{}, errors.Annotate(err, "got bad data from server") } resNames := map[string]bool{} unitResources := resource.UnitResources{Tag: tag} for _, apiRes := range unitRes.Resources { res, err := API2Resource(apiRes) if err != nil { return resource.ApplicationResources{}, errors.Annotate(err, "got bad data from server") } resNames[res.Name] = true unitResources.Resources = append(unitResources.Resources, res) } if len(unitRes.DownloadProgress) > 0 { unitResources.DownloadProgress = make(map[string]int64) for resName, progress := range unitRes.DownloadProgress { if _, ok := resNames[resName]; !ok { err := errors.Errorf("got progress from unrecognized resource %q", resName) return resource.ApplicationResources{}, errors.Annotate(err, "got bad data from server") } unitResources.DownloadProgress[resName] = progress } } result.UnitResources = append(result.UnitResources, unitResources) } for _, chRes := range apiResult.CharmStoreResources { res, err := API2CharmResource(chRes) if err != nil { return resource.ApplicationResources{}, errors.Annotate(err, "got bad data from server") } result.CharmStoreResources = append(result.CharmStoreResources, res) } return result, nil }
go
func APIResult2ApplicationResources(apiResult params.ResourcesResult) (resource.ApplicationResources, error) { var result resource.ApplicationResources if apiResult.Error != nil { // TODO(ericsnow) Return the resources too? err := common.RestoreError(apiResult.Error) return resource.ApplicationResources{}, errors.Trace(err) } for _, apiRes := range apiResult.Resources { res, err := API2Resource(apiRes) if err != nil { // This could happen if the server is misbehaving // or non-conforming. // TODO(ericsnow) Aggregate errors? return resource.ApplicationResources{}, errors.Annotate(err, "got bad data from server") } result.Resources = append(result.Resources, res) } for _, unitRes := range apiResult.UnitResources { tag, err := names.ParseUnitTag(unitRes.Tag) if err != nil { return resource.ApplicationResources{}, errors.Annotate(err, "got bad data from server") } resNames := map[string]bool{} unitResources := resource.UnitResources{Tag: tag} for _, apiRes := range unitRes.Resources { res, err := API2Resource(apiRes) if err != nil { return resource.ApplicationResources{}, errors.Annotate(err, "got bad data from server") } resNames[res.Name] = true unitResources.Resources = append(unitResources.Resources, res) } if len(unitRes.DownloadProgress) > 0 { unitResources.DownloadProgress = make(map[string]int64) for resName, progress := range unitRes.DownloadProgress { if _, ok := resNames[resName]; !ok { err := errors.Errorf("got progress from unrecognized resource %q", resName) return resource.ApplicationResources{}, errors.Annotate(err, "got bad data from server") } unitResources.DownloadProgress[resName] = progress } } result.UnitResources = append(result.UnitResources, unitResources) } for _, chRes := range apiResult.CharmStoreResources { res, err := API2CharmResource(chRes) if err != nil { return resource.ApplicationResources{}, errors.Annotate(err, "got bad data from server") } result.CharmStoreResources = append(result.CharmStoreResources, res) } return result, nil }
[ "func", "APIResult2ApplicationResources", "(", "apiResult", "params", ".", "ResourcesResult", ")", "(", "resource", ".", "ApplicationResources", ",", "error", ")", "{", "var", "result", "resource", ".", "ApplicationResources", "\n\n", "if", "apiResult", ".", "Error", "!=", "nil", "{", "// TODO(ericsnow) Return the resources too?", "err", ":=", "common", ".", "RestoreError", "(", "apiResult", ".", "Error", ")", "\n", "return", "resource", ".", "ApplicationResources", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "apiRes", ":=", "range", "apiResult", ".", "Resources", "{", "res", ",", "err", ":=", "API2Resource", "(", "apiRes", ")", "\n", "if", "err", "!=", "nil", "{", "// This could happen if the server is misbehaving", "// or non-conforming.", "// TODO(ericsnow) Aggregate errors?", "return", "resource", ".", "ApplicationResources", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "result", ".", "Resources", "=", "append", "(", "result", ".", "Resources", ",", "res", ")", "\n", "}", "\n\n", "for", "_", ",", "unitRes", ":=", "range", "apiResult", ".", "UnitResources", "{", "tag", ",", "err", ":=", "names", ".", "ParseUnitTag", "(", "unitRes", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "resource", ".", "ApplicationResources", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "resNames", ":=", "map", "[", "string", "]", "bool", "{", "}", "\n", "unitResources", ":=", "resource", ".", "UnitResources", "{", "Tag", ":", "tag", "}", "\n", "for", "_", ",", "apiRes", ":=", "range", "unitRes", ".", "Resources", "{", "res", ",", "err", ":=", "API2Resource", "(", "apiRes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "resource", ".", "ApplicationResources", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "resNames", "[", "res", ".", "Name", "]", "=", "true", "\n", "unitResources", ".", "Resources", "=", "append", "(", "unitResources", ".", "Resources", ",", "res", ")", "\n", "}", "\n", "if", "len", "(", "unitRes", ".", "DownloadProgress", ")", ">", "0", "{", "unitResources", ".", "DownloadProgress", "=", "make", "(", "map", "[", "string", "]", "int64", ")", "\n", "for", "resName", ",", "progress", ":=", "range", "unitRes", ".", "DownloadProgress", "{", "if", "_", ",", "ok", ":=", "resNames", "[", "resName", "]", ";", "!", "ok", "{", "err", ":=", "errors", ".", "Errorf", "(", "\"", "\"", ",", "resName", ")", "\n", "return", "resource", ".", "ApplicationResources", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "unitResources", ".", "DownloadProgress", "[", "resName", "]", "=", "progress", "\n", "}", "\n", "}", "\n", "result", ".", "UnitResources", "=", "append", "(", "result", ".", "UnitResources", ",", "unitResources", ")", "\n", "}", "\n\n", "for", "_", ",", "chRes", ":=", "range", "apiResult", ".", "CharmStoreResources", "{", "res", ",", "err", ":=", "API2CharmResource", "(", "chRes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "resource", ".", "ApplicationResources", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "result", ".", "CharmStoreResources", "=", "append", "(", "result", ".", "CharmStoreResources", ",", "res", ")", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// APIResult2ApplicationResources converts a ResourcesResult into a resource.ApplicationResources.
[ "APIResult2ApplicationResources", "converts", "a", "ResourcesResult", "into", "a", "resource", ".", "ApplicationResources", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/helpers.go#L30-L87
4,397
juju/juju
resource/api/helpers.go
API2Resource
func API2Resource(apiRes params.Resource) (resource.Resource, error) { var res resource.Resource charmRes, err := API2CharmResource(apiRes.CharmResource) if err != nil { return res, errors.Trace(err) } res = resource.Resource{ Resource: charmRes, ID: apiRes.ID, PendingID: apiRes.PendingID, ApplicationID: apiRes.ApplicationID, Username: apiRes.Username, Timestamp: apiRes.Timestamp, } if err := res.Validate(); err != nil { return res, errors.Trace(err) } return res, nil }
go
func API2Resource(apiRes params.Resource) (resource.Resource, error) { var res resource.Resource charmRes, err := API2CharmResource(apiRes.CharmResource) if err != nil { return res, errors.Trace(err) } res = resource.Resource{ Resource: charmRes, ID: apiRes.ID, PendingID: apiRes.PendingID, ApplicationID: apiRes.ApplicationID, Username: apiRes.Username, Timestamp: apiRes.Timestamp, } if err := res.Validate(); err != nil { return res, errors.Trace(err) } return res, nil }
[ "func", "API2Resource", "(", "apiRes", "params", ".", "Resource", ")", "(", "resource", ".", "Resource", ",", "error", ")", "{", "var", "res", "resource", ".", "Resource", "\n\n", "charmRes", ",", "err", ":=", "API2CharmResource", "(", "apiRes", ".", "CharmResource", ")", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "res", "=", "resource", ".", "Resource", "{", "Resource", ":", "charmRes", ",", "ID", ":", "apiRes", ".", "ID", ",", "PendingID", ":", "apiRes", ".", "PendingID", ",", "ApplicationID", ":", "apiRes", ".", "ApplicationID", ",", "Username", ":", "apiRes", ".", "Username", ",", "Timestamp", ":", "apiRes", ".", "Timestamp", ",", "}", "\n\n", "if", "err", ":=", "res", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "res", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "res", ",", "nil", "\n", "}" ]
// API2Resource converts an API Resource struct into // a resource.Resource.
[ "API2Resource", "converts", "an", "API", "Resource", "struct", "into", "a", "resource", ".", "Resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/helpers.go#L121-L143
4,398
juju/juju
resource/api/helpers.go
CharmResource2API
func CharmResource2API(res charmresource.Resource) params.CharmResource { return params.CharmResource{ Name: res.Name, Type: res.Type.String(), Path: res.Path, Description: res.Description, Origin: res.Origin.String(), Revision: res.Revision, Fingerprint: res.Fingerprint.Bytes(), Size: res.Size, } }
go
func CharmResource2API(res charmresource.Resource) params.CharmResource { return params.CharmResource{ Name: res.Name, Type: res.Type.String(), Path: res.Path, Description: res.Description, Origin: res.Origin.String(), Revision: res.Revision, Fingerprint: res.Fingerprint.Bytes(), Size: res.Size, } }
[ "func", "CharmResource2API", "(", "res", "charmresource", ".", "Resource", ")", "params", ".", "CharmResource", "{", "return", "params", ".", "CharmResource", "{", "Name", ":", "res", ".", "Name", ",", "Type", ":", "res", ".", "Type", ".", "String", "(", ")", ",", "Path", ":", "res", ".", "Path", ",", "Description", ":", "res", ".", "Description", ",", "Origin", ":", "res", ".", "Origin", ".", "String", "(", ")", ",", "Revision", ":", "res", ".", "Revision", ",", "Fingerprint", ":", "res", ".", "Fingerprint", ".", "Bytes", "(", ")", ",", "Size", ":", "res", ".", "Size", ",", "}", "\n", "}" ]
// CharmResource2API converts a charm resource into // a CharmResource struct.
[ "CharmResource2API", "converts", "a", "charm", "resource", "into", "a", "CharmResource", "struct", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/helpers.go#L147-L158
4,399
juju/juju
resource/api/helpers.go
API2CharmResource
func API2CharmResource(apiInfo params.CharmResource) (charmresource.Resource, error) { var res charmresource.Resource rtype, err := charmresource.ParseType(apiInfo.Type) if err != nil { return res, errors.Trace(err) } origin, err := charmresource.ParseOrigin(apiInfo.Origin) if err != nil { return res, errors.Trace(err) } fp, err := resource.DeserializeFingerprint(apiInfo.Fingerprint) if err != nil { return res, errors.Trace(err) } res = charmresource.Resource{ Meta: charmresource.Meta{ Name: apiInfo.Name, Type: rtype, Path: apiInfo.Path, Description: apiInfo.Description, }, Origin: origin, Revision: apiInfo.Revision, Fingerprint: fp, Size: apiInfo.Size, } if err := res.Validate(); err != nil { return res, errors.Trace(err) } return res, nil }
go
func API2CharmResource(apiInfo params.CharmResource) (charmresource.Resource, error) { var res charmresource.Resource rtype, err := charmresource.ParseType(apiInfo.Type) if err != nil { return res, errors.Trace(err) } origin, err := charmresource.ParseOrigin(apiInfo.Origin) if err != nil { return res, errors.Trace(err) } fp, err := resource.DeserializeFingerprint(apiInfo.Fingerprint) if err != nil { return res, errors.Trace(err) } res = charmresource.Resource{ Meta: charmresource.Meta{ Name: apiInfo.Name, Type: rtype, Path: apiInfo.Path, Description: apiInfo.Description, }, Origin: origin, Revision: apiInfo.Revision, Fingerprint: fp, Size: apiInfo.Size, } if err := res.Validate(); err != nil { return res, errors.Trace(err) } return res, nil }
[ "func", "API2CharmResource", "(", "apiInfo", "params", ".", "CharmResource", ")", "(", "charmresource", ".", "Resource", ",", "error", ")", "{", "var", "res", "charmresource", ".", "Resource", "\n\n", "rtype", ",", "err", ":=", "charmresource", ".", "ParseType", "(", "apiInfo", ".", "Type", ")", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "origin", ",", "err", ":=", "charmresource", ".", "ParseOrigin", "(", "apiInfo", ".", "Origin", ")", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "fp", ",", "err", ":=", "resource", ".", "DeserializeFingerprint", "(", "apiInfo", ".", "Fingerprint", ")", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "res", "=", "charmresource", ".", "Resource", "{", "Meta", ":", "charmresource", ".", "Meta", "{", "Name", ":", "apiInfo", ".", "Name", ",", "Type", ":", "rtype", ",", "Path", ":", "apiInfo", ".", "Path", ",", "Description", ":", "apiInfo", ".", "Description", ",", "}", ",", "Origin", ":", "origin", ",", "Revision", ":", "apiInfo", ".", "Revision", ",", "Fingerprint", ":", "fp", ",", "Size", ":", "apiInfo", ".", "Size", ",", "}", "\n\n", "if", "err", ":=", "res", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "res", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// API2CharmResource converts an API CharmResource struct into // a charm resource.
[ "API2CharmResource", "converts", "an", "API", "CharmResource", "struct", "into", "a", "charm", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/helpers.go#L162-L197