id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
156,100 | juju/juju | worker/uniter/charm/manifest_deployer.go | startDeploy | func (d *manifestDeployer) startDeploy() error {
logger.Debugf("preparing to deploy charm %q", d.staged.url)
if err := os.MkdirAll(d.charmPath, 0755); err != nil {
return err
}
return WriteCharmURL(d.CharmPath(deployingURLPath), d.staged.url)
} | go | func (d *manifestDeployer) startDeploy() error {
logger.Debugf("preparing to deploy charm %q", d.staged.url)
if err := os.MkdirAll(d.charmPath, 0755); err != nil {
return err
}
return WriteCharmURL(d.CharmPath(deployingURLPath), d.staged.url)
} | [
"func",
"(",
"d",
"*",
"manifestDeployer",
")",
"startDeploy",
"(",
")",
"error",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"d",
".",
"staged",
".",
"url",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"d",
".",
"charmPath",
",",
"0755",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"WriteCharmURL",
"(",
"d",
".",
"CharmPath",
"(",
"deployingURLPath",
")",
",",
"d",
".",
"staged",
".",
"url",
")",
"\n",
"}"
] | // startDeploy persists the fact that we've started deploying the staged bundle. | [
"startDeploy",
"persists",
"the",
"fact",
"that",
"we",
"ve",
"started",
"deploying",
"the",
"staged",
"bundle",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/manifest_deployer.go#L112-L118 |
156,101 | juju/juju | worker/uniter/charm/manifest_deployer.go | removeDiff | func (d *manifestDeployer) removeDiff(oldManifest, newManifest set.Strings) error {
diff := oldManifest.Difference(newManifest)
for _, path := range diff.SortedValues() {
fullPath := filepath.Join(d.charmPath, filepath.FromSlash(path))
if err := os.RemoveAll(fullPath); err != nil {
return err
}
}
return nil
} | go | func (d *manifestDeployer) removeDiff(oldManifest, newManifest set.Strings) error {
diff := oldManifest.Difference(newManifest)
for _, path := range diff.SortedValues() {
fullPath := filepath.Join(d.charmPath, filepath.FromSlash(path))
if err := os.RemoveAll(fullPath); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"d",
"*",
"manifestDeployer",
")",
"removeDiff",
"(",
"oldManifest",
",",
"newManifest",
"set",
".",
"Strings",
")",
"error",
"{",
"diff",
":=",
"oldManifest",
".",
"Difference",
"(",
"newManifest",
")",
"\n",
"for",
"_",
",",
"path",
":=",
"range",
"diff",
".",
"SortedValues",
"(",
")",
"{",
"fullPath",
":=",
"filepath",
".",
"Join",
"(",
"d",
".",
"charmPath",
",",
"filepath",
".",
"FromSlash",
"(",
"path",
")",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"RemoveAll",
"(",
"fullPath",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // removeDiff removes every path in oldManifest that is not present in newManifest. | [
"removeDiff",
"removes",
"every",
"path",
"in",
"oldManifest",
"that",
"is",
"not",
"present",
"in",
"newManifest",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/manifest_deployer.go#L121-L130 |
156,102 | juju/juju | worker/uniter/charm/manifest_deployer.go | finishDeploy | func (d *manifestDeployer) finishDeploy() error {
logger.Debugf("finishing deploy of charm %q", d.staged.url)
oldPath := d.CharmPath(deployingURLPath)
newPath := d.CharmPath(CharmURLPath)
return utils.ReplaceFile(oldPath, newPath)
} | go | func (d *manifestDeployer) finishDeploy() error {
logger.Debugf("finishing deploy of charm %q", d.staged.url)
oldPath := d.CharmPath(deployingURLPath)
newPath := d.CharmPath(CharmURLPath)
return utils.ReplaceFile(oldPath, newPath)
} | [
"func",
"(",
"d",
"*",
"manifestDeployer",
")",
"finishDeploy",
"(",
")",
"error",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"d",
".",
"staged",
".",
"url",
")",
"\n",
"oldPath",
":=",
"d",
".",
"CharmPath",
"(",
"deployingURLPath",
")",
"\n",
"newPath",
":=",
"d",
".",
"CharmPath",
"(",
"CharmURLPath",
")",
"\n",
"return",
"utils",
".",
"ReplaceFile",
"(",
"oldPath",
",",
"newPath",
")",
"\n",
"}"
] | // finishDeploy persists the fact that we've finished deploying the staged bundle. | [
"finishDeploy",
"persists",
"the",
"fact",
"that",
"we",
"ve",
"finished",
"deploying",
"the",
"staged",
"bundle",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/manifest_deployer.go#L133-L138 |
156,103 | juju/juju | worker/uniter/charm/manifest_deployer.go | storeManifest | func (d *manifestDeployer) storeManifest(url *charm.URL, manifest set.Strings) error {
if err := os.MkdirAll(d.DataPath(manifestsDataPath), 0755); err != nil {
return err
}
name := charm.Quote(url.String())
path := filepath.Join(d.DataPath(manifestsDataPath), name)
return utils.WriteYaml(path, manifest.SortedValues())
} | go | func (d *manifestDeployer) storeManifest(url *charm.URL, manifest set.Strings) error {
if err := os.MkdirAll(d.DataPath(manifestsDataPath), 0755); err != nil {
return err
}
name := charm.Quote(url.String())
path := filepath.Join(d.DataPath(manifestsDataPath), name)
return utils.WriteYaml(path, manifest.SortedValues())
} | [
"func",
"(",
"d",
"*",
"manifestDeployer",
")",
"storeManifest",
"(",
"url",
"*",
"charm",
".",
"URL",
",",
"manifest",
"set",
".",
"Strings",
")",
"error",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"d",
".",
"DataPath",
"(",
"manifestsDataPath",
")",
",",
"0755",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"name",
":=",
"charm",
".",
"Quote",
"(",
"url",
".",
"String",
"(",
")",
")",
"\n",
"path",
":=",
"filepath",
".",
"Join",
"(",
"d",
".",
"DataPath",
"(",
"manifestsDataPath",
")",
",",
"name",
")",
"\n",
"return",
"utils",
".",
"WriteYaml",
"(",
"path",
",",
"manifest",
".",
"SortedValues",
"(",
")",
")",
"\n",
"}"
] | // storeManifest stores, into dataPath, the supplied manifest for the supplied charm. | [
"storeManifest",
"stores",
"into",
"dataPath",
"the",
"supplied",
"manifest",
"for",
"the",
"supplied",
"charm",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/manifest_deployer.go#L167-L174 |
156,104 | juju/juju | worker/uniter/charm/manifest_deployer.go | loadManifest | func (d *manifestDeployer) loadManifest(urlFilePath string) (*charm.URL, set.Strings, error) {
url, err := ReadCharmURL(d.CharmPath(urlFilePath))
if err != nil {
return nil, nil, err
}
name := charm.Quote(url.String())
path := filepath.Join(d.DataPath(manifestsDataPath), name)
manifest := []string{}
err = utils.ReadYaml(path, &manifest)
if os.IsNotExist(err) {
logger.Warningf("manifest not found at %q: files from charm %q may be left unremoved", path, url)
err = nil
}
return url, set.NewStrings(manifest...), err
} | go | func (d *manifestDeployer) loadManifest(urlFilePath string) (*charm.URL, set.Strings, error) {
url, err := ReadCharmURL(d.CharmPath(urlFilePath))
if err != nil {
return nil, nil, err
}
name := charm.Quote(url.String())
path := filepath.Join(d.DataPath(manifestsDataPath), name)
manifest := []string{}
err = utils.ReadYaml(path, &manifest)
if os.IsNotExist(err) {
logger.Warningf("manifest not found at %q: files from charm %q may be left unremoved", path, url)
err = nil
}
return url, set.NewStrings(manifest...), err
} | [
"func",
"(",
"d",
"*",
"manifestDeployer",
")",
"loadManifest",
"(",
"urlFilePath",
"string",
")",
"(",
"*",
"charm",
".",
"URL",
",",
"set",
".",
"Strings",
",",
"error",
")",
"{",
"url",
",",
"err",
":=",
"ReadCharmURL",
"(",
"d",
".",
"CharmPath",
"(",
"urlFilePath",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"name",
":=",
"charm",
".",
"Quote",
"(",
"url",
".",
"String",
"(",
")",
")",
"\n",
"path",
":=",
"filepath",
".",
"Join",
"(",
"d",
".",
"DataPath",
"(",
"manifestsDataPath",
")",
",",
"name",
")",
"\n",
"manifest",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"err",
"=",
"utils",
".",
"ReadYaml",
"(",
"path",
",",
"&",
"manifest",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"path",
",",
"url",
")",
"\n",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"url",
",",
"set",
".",
"NewStrings",
"(",
"manifest",
"...",
")",
",",
"err",
"\n",
"}"
] | // loadManifest loads, from dataPath, the manifest for the charm identified by the
// identity file at the supplied path within the charm directory. | [
"loadManifest",
"loads",
"from",
"dataPath",
"the",
"manifest",
"for",
"the",
"charm",
"identified",
"by",
"the",
"identity",
"file",
"at",
"the",
"supplied",
"path",
"within",
"the",
"charm",
"directory",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/manifest_deployer.go#L178-L192 |
156,105 | juju/juju | worker/uniter/charm/manifest_deployer.go | CharmPath | func (d *manifestDeployer) CharmPath(path string) string {
return filepath.Join(d.charmPath, path)
} | go | func (d *manifestDeployer) CharmPath(path string) string {
return filepath.Join(d.charmPath, path)
} | [
"func",
"(",
"d",
"*",
"manifestDeployer",
")",
"CharmPath",
"(",
"path",
"string",
")",
"string",
"{",
"return",
"filepath",
".",
"Join",
"(",
"d",
".",
"charmPath",
",",
"path",
")",
"\n",
"}"
] | // CharmPath returns the supplied path joined to the ManifestDeployer's charm directory. | [
"CharmPath",
"returns",
"the",
"supplied",
"path",
"joined",
"to",
"the",
"ManifestDeployer",
"s",
"charm",
"directory",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/manifest_deployer.go#L195-L197 |
156,106 | juju/juju | worker/uniter/charm/manifest_deployer.go | DataPath | func (d *manifestDeployer) DataPath(path string) string {
return filepath.Join(d.dataPath, path)
} | go | func (d *manifestDeployer) DataPath(path string) string {
return filepath.Join(d.dataPath, path)
} | [
"func",
"(",
"d",
"*",
"manifestDeployer",
")",
"DataPath",
"(",
"path",
"string",
")",
"string",
"{",
"return",
"filepath",
".",
"Join",
"(",
"d",
".",
"dataPath",
",",
"path",
")",
"\n",
"}"
] | // DataPath returns the supplied path joined to the ManifestDeployer's data directory. | [
"DataPath",
"returns",
"the",
"supplied",
"path",
"joined",
"to",
"the",
"ManifestDeployer",
"s",
"data",
"directory",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/manifest_deployer.go#L200-L202 |
156,107 | juju/juju | worker/uniter/charm/manifest_deployer.go | manifestDeployError | func manifestDeployError(err *error, upgrading bool) {
if *err != nil {
if upgrading {
// We now treat any failure to overwrite the charm -- or otherwise
// manipulate the charm directory -- as a conflict, because it's
// actually plausible for a user (or at least a charm author, who
// is the real audience for this case) to get in there and fix it.
logger.Errorf("cannot upgrade charm: %v", *err)
*err = ErrConflict
} else {
// ...but if we can't install at all, we just fail out as the old
// gitDeployer did, because I'm not willing to mess around with
// the uniter to enable ErrConflict handling on install. We've
// never heard of it actually happening, so this is probably not
// a big deal.
*err = fmt.Errorf("cannot install charm: %v", *err)
}
}
} | go | func manifestDeployError(err *error, upgrading bool) {
if *err != nil {
if upgrading {
// We now treat any failure to overwrite the charm -- or otherwise
// manipulate the charm directory -- as a conflict, because it's
// actually plausible for a user (or at least a charm author, who
// is the real audience for this case) to get in there and fix it.
logger.Errorf("cannot upgrade charm: %v", *err)
*err = ErrConflict
} else {
// ...but if we can't install at all, we just fail out as the old
// gitDeployer did, because I'm not willing to mess around with
// the uniter to enable ErrConflict handling on install. We've
// never heard of it actually happening, so this is probably not
// a big deal.
*err = fmt.Errorf("cannot install charm: %v", *err)
}
}
} | [
"func",
"manifestDeployError",
"(",
"err",
"*",
"error",
",",
"upgrading",
"bool",
")",
"{",
"if",
"*",
"err",
"!=",
"nil",
"{",
"if",
"upgrading",
"{",
"// We now treat any failure to overwrite the charm -- or otherwise",
"// manipulate the charm directory -- as a conflict, because it's",
"// actually plausible for a user (or at least a charm author, who",
"// is the real audience for this case) to get in there and fix it.",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"*",
"err",
")",
"\n",
"*",
"err",
"=",
"ErrConflict",
"\n",
"}",
"else",
"{",
"// ...but if we can't install at all, we just fail out as the old",
"// gitDeployer did, because I'm not willing to mess around with",
"// the uniter to enable ErrConflict handling on install. We've",
"// never heard of it actually happening, so this is probably not",
"// a big deal.",
"*",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"*",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // manifestDeployError annotates or replaces the supplied error according
// to whether or not an upgrade operation is in play. It was extracted from
// Deploy to aid that method's readability. | [
"manifestDeployError",
"annotates",
"or",
"replaces",
"the",
"supplied",
"error",
"according",
"to",
"whether",
"or",
"not",
"an",
"upgrade",
"operation",
"is",
"in",
"play",
".",
"It",
"was",
"extracted",
"from",
"Deploy",
"to",
"aid",
"that",
"method",
"s",
"readability",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/manifest_deployer.go#L207-L225 |
156,108 | juju/juju | cmd/juju/crossmodel/offer.go | NewOfferCommand | func NewOfferCommand() cmd.Command {
offerCmd := &offerCommand{}
offerCmd.newAPIFunc = func() (OfferAPI, error) {
return offerCmd.NewApplicationOffersAPI()
}
offerCmd.refreshModels = offerCmd.ControllerCommandBase.RefreshModels
return modelcmd.WrapController(offerCmd)
} | go | func NewOfferCommand() cmd.Command {
offerCmd := &offerCommand{}
offerCmd.newAPIFunc = func() (OfferAPI, error) {
return offerCmd.NewApplicationOffersAPI()
}
offerCmd.refreshModels = offerCmd.ControllerCommandBase.RefreshModels
return modelcmd.WrapController(offerCmd)
} | [
"func",
"NewOfferCommand",
"(",
")",
"cmd",
".",
"Command",
"{",
"offerCmd",
":=",
"&",
"offerCommand",
"{",
"}",
"\n",
"offerCmd",
".",
"newAPIFunc",
"=",
"func",
"(",
")",
"(",
"OfferAPI",
",",
"error",
")",
"{",
"return",
"offerCmd",
".",
"NewApplicationOffersAPI",
"(",
")",
"\n",
"}",
"\n",
"offerCmd",
".",
"refreshModels",
"=",
"offerCmd",
".",
"ControllerCommandBase",
".",
"RefreshModels",
"\n",
"return",
"modelcmd",
".",
"WrapController",
"(",
"offerCmd",
")",
"\n",
"}"
] | // NewOfferCommand constructs commands that enables endpoints for export. | [
"NewOfferCommand",
"constructs",
"commands",
"that",
"enables",
"endpoints",
"for",
"export",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/offer.go#L43-L50 |
156,109 | juju/juju | worker/uniter/operation/state.go | validate | func (st State) validate() (err error) {
defer errors.DeferredAnnotatef(&err, "invalid operation state")
hasHook := st.Hook != nil
hasActionId := st.ActionId != nil
hasCharm := st.CharmURL != nil
switch st.Kind {
case Install:
if st.Installed {
return errors.New("unexpected hook info with Kind Install")
}
fallthrough
case Upgrade:
switch {
case !hasCharm:
return errors.New("missing charm URL")
case hasActionId:
return errors.New("unexpected action id")
}
case RunAction:
switch {
case !hasActionId:
return errors.New("missing action id")
case hasCharm:
return errors.New("unexpected charm URL")
}
case RunHook:
switch {
case !hasHook:
return errors.New("missing hook info with Kind RunHook")
case hasCharm:
return errors.New("unexpected charm URL")
case hasActionId:
return errors.New("unexpected action id")
}
case Continue:
// TODO(jw4) LP-1438489
// ModeContinue should no longer have a Hook, but until the upgrade is
// fixed we can't fail the validation if it does.
if hasHook {
logger.Errorf("unexpected hook info with Kind Continue")
}
switch {
case hasCharm:
return errors.New("unexpected charm URL")
case hasActionId:
return errors.New("unexpected action id")
}
default:
return errors.Errorf("unknown operation %q", st.Kind)
}
switch st.Step {
case Queued, Pending, Done:
default:
return errors.Errorf("unknown operation step %q", st.Step)
}
if hasHook {
return st.Hook.Validate()
}
return nil
} | go | func (st State) validate() (err error) {
defer errors.DeferredAnnotatef(&err, "invalid operation state")
hasHook := st.Hook != nil
hasActionId := st.ActionId != nil
hasCharm := st.CharmURL != nil
switch st.Kind {
case Install:
if st.Installed {
return errors.New("unexpected hook info with Kind Install")
}
fallthrough
case Upgrade:
switch {
case !hasCharm:
return errors.New("missing charm URL")
case hasActionId:
return errors.New("unexpected action id")
}
case RunAction:
switch {
case !hasActionId:
return errors.New("missing action id")
case hasCharm:
return errors.New("unexpected charm URL")
}
case RunHook:
switch {
case !hasHook:
return errors.New("missing hook info with Kind RunHook")
case hasCharm:
return errors.New("unexpected charm URL")
case hasActionId:
return errors.New("unexpected action id")
}
case Continue:
// TODO(jw4) LP-1438489
// ModeContinue should no longer have a Hook, but until the upgrade is
// fixed we can't fail the validation if it does.
if hasHook {
logger.Errorf("unexpected hook info with Kind Continue")
}
switch {
case hasCharm:
return errors.New("unexpected charm URL")
case hasActionId:
return errors.New("unexpected action id")
}
default:
return errors.Errorf("unknown operation %q", st.Kind)
}
switch st.Step {
case Queued, Pending, Done:
default:
return errors.Errorf("unknown operation step %q", st.Step)
}
if hasHook {
return st.Hook.Validate()
}
return nil
} | [
"func",
"(",
"st",
"State",
")",
"validate",
"(",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"errors",
".",
"DeferredAnnotatef",
"(",
"&",
"err",
",",
"\"",
"\"",
")",
"\n",
"hasHook",
":=",
"st",
".",
"Hook",
"!=",
"nil",
"\n",
"hasActionId",
":=",
"st",
".",
"ActionId",
"!=",
"nil",
"\n",
"hasCharm",
":=",
"st",
".",
"CharmURL",
"!=",
"nil",
"\n",
"switch",
"st",
".",
"Kind",
"{",
"case",
"Install",
":",
"if",
"st",
".",
"Installed",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"fallthrough",
"\n",
"case",
"Upgrade",
":",
"switch",
"{",
"case",
"!",
"hasCharm",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"hasActionId",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"RunAction",
":",
"switch",
"{",
"case",
"!",
"hasActionId",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"hasCharm",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"RunHook",
":",
"switch",
"{",
"case",
"!",
"hasHook",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"hasCharm",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"hasActionId",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"Continue",
":",
"// TODO(jw4) LP-1438489",
"// ModeContinue should no longer have a Hook, but until the upgrade is",
"// fixed we can't fail the validation if it does.",
"if",
"hasHook",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"switch",
"{",
"case",
"hasCharm",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"hasActionId",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"default",
":",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"st",
".",
"Kind",
")",
"\n",
"}",
"\n",
"switch",
"st",
".",
"Step",
"{",
"case",
"Queued",
",",
"Pending",
",",
"Done",
":",
"default",
":",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"st",
".",
"Step",
")",
"\n",
"}",
"\n",
"if",
"hasHook",
"{",
"return",
"st",
".",
"Hook",
".",
"Validate",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // validate returns an error if the state violates expectations. | [
"validate",
"returns",
"an",
"error",
"if",
"the",
"state",
"violates",
"expectations",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/operation/state.go#L114-L173 |
156,110 | juju/juju | state/sshhostkeys.go | keysEqual | func keysEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
a = a[:]
b = b[:]
sort.Strings(a)
sort.Strings(b)
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
} | go | func keysEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
a = a[:]
b = b[:]
sort.Strings(a)
sort.Strings(b)
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
} | [
"func",
"keysEqual",
"(",
"a",
",",
"b",
"[",
"]",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"a",
"=",
"a",
"[",
":",
"]",
"\n",
"b",
"=",
"b",
"[",
":",
"]",
"\n",
"sort",
".",
"Strings",
"(",
"a",
")",
"\n",
"sort",
".",
"Strings",
"(",
"b",
")",
"\n",
"for",
"i",
":=",
"range",
"a",
"{",
"if",
"a",
"[",
"i",
"]",
"!=",
"b",
"[",
"i",
"]",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // keysEqual checks if the ssh host keys are the same between two sets.
// we shouldn't care about the order of the keys. | [
"keysEqual",
"checks",
"if",
"the",
"ssh",
"host",
"keys",
"are",
"the",
"same",
"between",
"two",
"sets",
".",
"we",
"shouldn",
"t",
"care",
"about",
"the",
"order",
"of",
"the",
"keys",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/sshhostkeys.go#L53-L67 |
156,111 | juju/juju | state/sshhostkeys.go | SetSSHHostKeys | func (st *State) SetSSHHostKeys(tag names.MachineTag, keys SSHHostKeys) error {
coll, closer := st.db().GetCollection(sshHostKeysC)
defer closer()
id := machineGlobalKey(tag.Id())
doc := sshHostKeysDoc{
Keys: keys,
}
var dbDoc sshHostKeysDoc
buildTxn := func(attempt int) ([]txn.Op, error) {
err := coll.FindId(id).One(&dbDoc)
if err != nil {
if err == mgo.ErrNotFound {
return []txn.Op{{
C: sshHostKeysC,
Id: id,
Insert: doc,
}}, nil
}
return nil, err
}
if keysEqual(dbDoc.Keys, keys) {
return nil, jujutxn.ErrNoOperations
}
return []txn.Op{{
C: sshHostKeysC,
Id: id,
Update: bson.M{"$set": doc},
}}, nil
}
if err := st.db().Run(buildTxn); err != nil {
return errors.Annotate(err, "SSH host key update failed")
}
return nil
} | go | func (st *State) SetSSHHostKeys(tag names.MachineTag, keys SSHHostKeys) error {
coll, closer := st.db().GetCollection(sshHostKeysC)
defer closer()
id := machineGlobalKey(tag.Id())
doc := sshHostKeysDoc{
Keys: keys,
}
var dbDoc sshHostKeysDoc
buildTxn := func(attempt int) ([]txn.Op, error) {
err := coll.FindId(id).One(&dbDoc)
if err != nil {
if err == mgo.ErrNotFound {
return []txn.Op{{
C: sshHostKeysC,
Id: id,
Insert: doc,
}}, nil
}
return nil, err
}
if keysEqual(dbDoc.Keys, keys) {
return nil, jujutxn.ErrNoOperations
}
return []txn.Op{{
C: sshHostKeysC,
Id: id,
Update: bson.M{"$set": doc},
}}, nil
}
if err := st.db().Run(buildTxn); err != nil {
return errors.Annotate(err, "SSH host key update failed")
}
return nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"SetSSHHostKeys",
"(",
"tag",
"names",
".",
"MachineTag",
",",
"keys",
"SSHHostKeys",
")",
"error",
"{",
"coll",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"sshHostKeysC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"id",
":=",
"machineGlobalKey",
"(",
"tag",
".",
"Id",
"(",
")",
")",
"\n",
"doc",
":=",
"sshHostKeysDoc",
"{",
"Keys",
":",
"keys",
",",
"}",
"\n",
"var",
"dbDoc",
"sshHostKeysDoc",
"\n",
"buildTxn",
":=",
"func",
"(",
"attempt",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"err",
":=",
"coll",
".",
"FindId",
"(",
"id",
")",
".",
"One",
"(",
"&",
"dbDoc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"[",
"]",
"txn",
".",
"Op",
"{",
"{",
"C",
":",
"sshHostKeysC",
",",
"Id",
":",
"id",
",",
"Insert",
":",
"doc",
",",
"}",
"}",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"keysEqual",
"(",
"dbDoc",
".",
"Keys",
",",
"keys",
")",
"{",
"return",
"nil",
",",
"jujutxn",
".",
"ErrNoOperations",
"\n",
"}",
"\n",
"return",
"[",
"]",
"txn",
".",
"Op",
"{",
"{",
"C",
":",
"sshHostKeysC",
",",
"Id",
":",
"id",
",",
"Update",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"doc",
"}",
",",
"}",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"st",
".",
"db",
"(",
")",
".",
"Run",
"(",
"buildTxn",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetSSHHostKeys updates the stored SSH host keys for an entity.
//
// See the note for GetSSHHostKeys regarding supported entities. | [
"SetSSHHostKeys",
"updates",
"the",
"stored",
"SSH",
"host",
"keys",
"for",
"an",
"entity",
".",
"See",
"the",
"note",
"for",
"GetSSHHostKeys",
"regarding",
"supported",
"entities",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/sshhostkeys.go#L72-L106 |
156,112 | juju/juju | state/sshhostkeys.go | removeSSHHostKeyOp | func removeSSHHostKeyOp(globalKey string) txn.Op {
return txn.Op{
C: sshHostKeysC,
Id: globalKey,
Remove: true,
}
} | go | func removeSSHHostKeyOp(globalKey string) txn.Op {
return txn.Op{
C: sshHostKeysC,
Id: globalKey,
Remove: true,
}
} | [
"func",
"removeSSHHostKeyOp",
"(",
"globalKey",
"string",
")",
"txn",
".",
"Op",
"{",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"sshHostKeysC",
",",
"Id",
":",
"globalKey",
",",
"Remove",
":",
"true",
",",
"}",
"\n",
"}"
] | // removeSSHHostKeyOp returns the operation needed to remove the SSH
// host key document associated with the given globalKey. | [
"removeSSHHostKeyOp",
"returns",
"the",
"operation",
"needed",
"to",
"remove",
"the",
"SSH",
"host",
"key",
"document",
"associated",
"with",
"the",
"given",
"globalKey",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/sshhostkeys.go#L110-L116 |
156,113 | juju/juju | apiserver/facades/controller/applicationscaler/facade.go | NewFacade | func NewFacade(backend Backend, res facade.Resources, auth facade.Authorizer) (*Facade, error) {
if !auth.AuthController() {
return nil, common.ErrPerm
}
return &Facade{
backend: backend,
resources: res,
}, nil
} | go | func NewFacade(backend Backend, res facade.Resources, auth facade.Authorizer) (*Facade, error) {
if !auth.AuthController() {
return nil, common.ErrPerm
}
return &Facade{
backend: backend,
resources: res,
}, nil
} | [
"func",
"NewFacade",
"(",
"backend",
"Backend",
",",
"res",
"facade",
".",
"Resources",
",",
"auth",
"facade",
".",
"Authorizer",
")",
"(",
"*",
"Facade",
",",
"error",
")",
"{",
"if",
"!",
"auth",
".",
"AuthController",
"(",
")",
"{",
"return",
"nil",
",",
"common",
".",
"ErrPerm",
"\n",
"}",
"\n",
"return",
"&",
"Facade",
"{",
"backend",
":",
"backend",
",",
"resources",
":",
"res",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewFacade creates a new authorized Facade. | [
"NewFacade",
"creates",
"a",
"new",
"authorized",
"Facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/applicationscaler/facade.go#L36-L44 |
156,114 | juju/juju | apiserver/facades/controller/applicationscaler/facade.go | Watch | func (facade *Facade) Watch() (params.StringsWatchResult, error) {
watch := facade.backend.WatchScaledServices()
if changes, ok := <-watch.Changes(); ok {
id := facade.resources.Register(watch)
return params.StringsWatchResult{
StringsWatcherId: id,
Changes: changes,
}, nil
}
return params.StringsWatchResult{}, watcher.EnsureErr(watch)
} | go | func (facade *Facade) Watch() (params.StringsWatchResult, error) {
watch := facade.backend.WatchScaledServices()
if changes, ok := <-watch.Changes(); ok {
id := facade.resources.Register(watch)
return params.StringsWatchResult{
StringsWatcherId: id,
Changes: changes,
}, nil
}
return params.StringsWatchResult{}, watcher.EnsureErr(watch)
} | [
"func",
"(",
"facade",
"*",
"Facade",
")",
"Watch",
"(",
")",
"(",
"params",
".",
"StringsWatchResult",
",",
"error",
")",
"{",
"watch",
":=",
"facade",
".",
"backend",
".",
"WatchScaledServices",
"(",
")",
"\n",
"if",
"changes",
",",
"ok",
":=",
"<-",
"watch",
".",
"Changes",
"(",
")",
";",
"ok",
"{",
"id",
":=",
"facade",
".",
"resources",
".",
"Register",
"(",
"watch",
")",
"\n",
"return",
"params",
".",
"StringsWatchResult",
"{",
"StringsWatcherId",
":",
"id",
",",
"Changes",
":",
"changes",
",",
"}",
",",
"nil",
"\n",
"}",
"\n",
"return",
"params",
".",
"StringsWatchResult",
"{",
"}",
",",
"watcher",
".",
"EnsureErr",
"(",
"watch",
")",
"\n",
"}"
] | // Watch returns a watcher that sends the names of services whose
// unit count may be below their configured minimum. | [
"Watch",
"returns",
"a",
"watcher",
"that",
"sends",
"the",
"names",
"of",
"services",
"whose",
"unit",
"count",
"may",
"be",
"below",
"their",
"configured",
"minimum",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/applicationscaler/facade.go#L48-L58 |
156,115 | juju/juju | apiserver/facades/controller/applicationscaler/facade.go | Rescale | func (facade *Facade) Rescale(args params.Entities) params.ErrorResults {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
for i, entity := range args.Entities {
err := facade.rescaleOne(entity.Tag)
result.Results[i].Error = common.ServerError(err)
}
return result
} | go | func (facade *Facade) Rescale(args params.Entities) params.ErrorResults {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
for i, entity := range args.Entities {
err := facade.rescaleOne(entity.Tag)
result.Results[i].Error = common.ServerError(err)
}
return result
} | [
"func",
"(",
"facade",
"*",
"Facade",
")",
"Rescale",
"(",
"args",
"params",
".",
"Entities",
")",
"params",
".",
"ErrorResults",
"{",
"result",
":=",
"params",
".",
"ErrorResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"ErrorResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"entity",
":=",
"range",
"args",
".",
"Entities",
"{",
"err",
":=",
"facade",
".",
"rescaleOne",
"(",
"entity",
".",
"Tag",
")",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // Rescale causes any supplied services to be scaled up to their
// minimum size. | [
"Rescale",
"causes",
"any",
"supplied",
"services",
"to",
"be",
"scaled",
"up",
"to",
"their",
"minimum",
"size",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/applicationscaler/facade.go#L62-L71 |
156,116 | juju/juju | apiserver/facades/controller/applicationscaler/facade.go | rescaleOne | func (facade *Facade) rescaleOne(tagString string) error {
tag, err := names.ParseTag(tagString)
if err != nil {
return errors.Trace(err)
}
ApplicationTag, ok := tag.(names.ApplicationTag)
if !ok {
return common.ErrPerm
}
return facade.backend.RescaleService(ApplicationTag.Id())
} | go | func (facade *Facade) rescaleOne(tagString string) error {
tag, err := names.ParseTag(tagString)
if err != nil {
return errors.Trace(err)
}
ApplicationTag, ok := tag.(names.ApplicationTag)
if !ok {
return common.ErrPerm
}
return facade.backend.RescaleService(ApplicationTag.Id())
} | [
"func",
"(",
"facade",
"*",
"Facade",
")",
"rescaleOne",
"(",
"tagString",
"string",
")",
"error",
"{",
"tag",
",",
"err",
":=",
"names",
".",
"ParseTag",
"(",
"tagString",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"ApplicationTag",
",",
"ok",
":=",
"tag",
".",
"(",
"names",
".",
"ApplicationTag",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"common",
".",
"ErrPerm",
"\n",
"}",
"\n",
"return",
"facade",
".",
"backend",
".",
"RescaleService",
"(",
"ApplicationTag",
".",
"Id",
"(",
")",
")",
"\n",
"}"
] | // rescaleOne scales up the supplied service, if necessary; or returns a
// suitable error. | [
"rescaleOne",
"scales",
"up",
"the",
"supplied",
"service",
"if",
"necessary",
";",
"or",
"returns",
"a",
"suitable",
"error",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/applicationscaler/facade.go#L75-L85 |
156,117 | juju/juju | worker/httpserver/tls.go | NewTLSConfig | func NewTLSConfig(st *state.State, getCertificate func() *tls.Certificate) (*tls.Config, error) {
controllerConfig, err := st.ControllerConfig()
if err != nil {
return nil, errors.Trace(err)
}
return newTLSConfig(
controllerConfig.AutocertDNSName(),
controllerConfig.AutocertURL(),
st.AutocertCache(),
getCertificate,
), nil
} | go | func NewTLSConfig(st *state.State, getCertificate func() *tls.Certificate) (*tls.Config, error) {
controllerConfig, err := st.ControllerConfig()
if err != nil {
return nil, errors.Trace(err)
}
return newTLSConfig(
controllerConfig.AutocertDNSName(),
controllerConfig.AutocertURL(),
st.AutocertCache(),
getCertificate,
), nil
} | [
"func",
"NewTLSConfig",
"(",
"st",
"*",
"state",
".",
"State",
",",
"getCertificate",
"func",
"(",
")",
"*",
"tls",
".",
"Certificate",
")",
"(",
"*",
"tls",
".",
"Config",
",",
"error",
")",
"{",
"controllerConfig",
",",
"err",
":=",
"st",
".",
"ControllerConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"newTLSConfig",
"(",
"controllerConfig",
".",
"AutocertDNSName",
"(",
")",
",",
"controllerConfig",
".",
"AutocertURL",
"(",
")",
",",
"st",
".",
"AutocertCache",
"(",
")",
",",
"getCertificate",
",",
")",
",",
"nil",
"\n",
"}"
] | // NewTLSConfig returns the TLS configuration for the HTTP server to use
// based on controller configuration stored in the state database. | [
"NewTLSConfig",
"returns",
"the",
"TLS",
"configuration",
"for",
"the",
"HTTP",
"server",
"to",
"use",
"based",
"on",
"controller",
"configuration",
"stored",
"in",
"the",
"state",
"database",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/httpserver/tls.go#L21-L32 |
156,118 | juju/juju | api/backups/create.go | Create | func (c *Client) Create(notes string, keepCopy, noDownload bool) (*params.BackupsMetadataResult, error) {
var result params.BackupsMetadataResult
args := params.BackupsCreateArgs{
Notes: notes,
KeepCopy: keepCopy,
NoDownload: noDownload,
}
if err := c.facade.FacadeCall("Create", args, &result); err != nil {
return nil, errors.Trace(err)
}
return &result, nil
} | go | func (c *Client) Create(notes string, keepCopy, noDownload bool) (*params.BackupsMetadataResult, error) {
var result params.BackupsMetadataResult
args := params.BackupsCreateArgs{
Notes: notes,
KeepCopy: keepCopy,
NoDownload: noDownload,
}
if err := c.facade.FacadeCall("Create", args, &result); err != nil {
return nil, errors.Trace(err)
}
return &result, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Create",
"(",
"notes",
"string",
",",
"keepCopy",
",",
"noDownload",
"bool",
")",
"(",
"*",
"params",
".",
"BackupsMetadataResult",
",",
"error",
")",
"{",
"var",
"result",
"params",
".",
"BackupsMetadataResult",
"\n",
"args",
":=",
"params",
".",
"BackupsCreateArgs",
"{",
"Notes",
":",
"notes",
",",
"KeepCopy",
":",
"keepCopy",
",",
"NoDownload",
":",
"noDownload",
",",
"}",
"\n\n",
"if",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"result",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"result",
",",
"nil",
"\n",
"}"
] | // Create sends a request to create a backup of juju's state. It
// returns the metadata associated with the resulting backup and a
// filename for download. | [
"Create",
"sends",
"a",
"request",
"to",
"create",
"a",
"backup",
"of",
"juju",
"s",
"state",
".",
"It",
"returns",
"the",
"metadata",
"associated",
"with",
"the",
"resulting",
"backup",
"and",
"a",
"filename",
"for",
"download",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/backups/create.go#L15-L28 |
156,119 | juju/juju | worker/uniter/charm/bundles.go | NewBundlesDir | func NewBundlesDir(path string, dlr Downloader) *BundlesDir {
if dlr == nil {
dlr = downloader.New(downloader.NewArgs{
HostnameVerification: utils.NoVerifySSLHostnames,
})
}
return &BundlesDir{
path: path,
downloader: dlr,
}
} | go | func NewBundlesDir(path string, dlr Downloader) *BundlesDir {
if dlr == nil {
dlr = downloader.New(downloader.NewArgs{
HostnameVerification: utils.NoVerifySSLHostnames,
})
}
return &BundlesDir{
path: path,
downloader: dlr,
}
} | [
"func",
"NewBundlesDir",
"(",
"path",
"string",
",",
"dlr",
"Downloader",
")",
"*",
"BundlesDir",
"{",
"if",
"dlr",
"==",
"nil",
"{",
"dlr",
"=",
"downloader",
".",
"New",
"(",
"downloader",
".",
"NewArgs",
"{",
"HostnameVerification",
":",
"utils",
".",
"NoVerifySSLHostnames",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"&",
"BundlesDir",
"{",
"path",
":",
"path",
",",
"downloader",
":",
"dlr",
",",
"}",
"\n",
"}"
] | // NewBundlesDir returns a new BundlesDir which uses path for storage. | [
"NewBundlesDir",
"returns",
"a",
"new",
"BundlesDir",
"which",
"uses",
"path",
"for",
"storage",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/bundles.go#L33-L43 |
156,120 | juju/juju | worker/uniter/charm/bundles.go | Read | func (d *BundlesDir) Read(info BundleInfo, abort <-chan struct{}) (Bundle, error) {
path := d.bundlePath(info)
if _, err := os.Stat(path); err != nil {
if !os.IsNotExist(err) {
return nil, err
}
if err := d.download(info, path, abort); err != nil {
return nil, err
}
}
return charm.ReadCharmArchive(path)
} | go | func (d *BundlesDir) Read(info BundleInfo, abort <-chan struct{}) (Bundle, error) {
path := d.bundlePath(info)
if _, err := os.Stat(path); err != nil {
if !os.IsNotExist(err) {
return nil, err
}
if err := d.download(info, path, abort); err != nil {
return nil, err
}
}
return charm.ReadCharmArchive(path)
} | [
"func",
"(",
"d",
"*",
"BundlesDir",
")",
"Read",
"(",
"info",
"BundleInfo",
",",
"abort",
"<-",
"chan",
"struct",
"{",
"}",
")",
"(",
"Bundle",
",",
"error",
")",
"{",
"path",
":=",
"d",
".",
"bundlePath",
"(",
"info",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"path",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"download",
"(",
"info",
",",
"path",
",",
"abort",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"charm",
".",
"ReadCharmArchive",
"(",
"path",
")",
"\n",
"}"
] | // Read returns a charm bundle from the directory. If no bundle exists yet,
// one will be downloaded and validated and copied into the directory before
// being returned. Downloads will be aborted if a value is received on abort. | [
"Read",
"returns",
"a",
"charm",
"bundle",
"from",
"the",
"directory",
".",
"If",
"no",
"bundle",
"exists",
"yet",
"one",
"will",
"be",
"downloaded",
"and",
"validated",
"and",
"copied",
"into",
"the",
"directory",
"before",
"being",
"returned",
".",
"Downloads",
"will",
"be",
"aborted",
"if",
"a",
"value",
"is",
"received",
"on",
"abort",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/bundles.go#L48-L59 |
156,121 | juju/juju | worker/uniter/charm/bundles.go | download | func (d *BundlesDir) download(info BundleInfo, target string, abort <-chan struct{}) (err error) {
// First download...
curl, err := url.Parse(info.URL().String())
if err != nil {
return errors.Annotate(err, "could not parse charm URL")
}
expectedSha256, err := info.ArchiveSha256()
req := downloader.Request{
URL: curl,
TargetDir: downloadsPath(d.path),
Verify: downloader.NewSha256Verifier(expectedSha256),
Abort: abort,
}
logger.Infof("downloading %s from API server", info.URL())
filename, err := d.downloader.Download(req)
if err != nil {
return errors.Annotatef(err, "failed to download charm %q from API server", info.URL())
}
defer errors.DeferredAnnotatef(&err, "downloaded but failed to copy charm to %q from %q", target, filename)
// ...then move the right location.
if err := os.MkdirAll(d.path, 0755); err != nil {
return errors.Trace(err)
}
if err := os.Rename(filename, target); err != nil {
return errors.Trace(err)
}
return nil
} | go | func (d *BundlesDir) download(info BundleInfo, target string, abort <-chan struct{}) (err error) {
// First download...
curl, err := url.Parse(info.URL().String())
if err != nil {
return errors.Annotate(err, "could not parse charm URL")
}
expectedSha256, err := info.ArchiveSha256()
req := downloader.Request{
URL: curl,
TargetDir: downloadsPath(d.path),
Verify: downloader.NewSha256Verifier(expectedSha256),
Abort: abort,
}
logger.Infof("downloading %s from API server", info.URL())
filename, err := d.downloader.Download(req)
if err != nil {
return errors.Annotatef(err, "failed to download charm %q from API server", info.URL())
}
defer errors.DeferredAnnotatef(&err, "downloaded but failed to copy charm to %q from %q", target, filename)
// ...then move the right location.
if err := os.MkdirAll(d.path, 0755); err != nil {
return errors.Trace(err)
}
if err := os.Rename(filename, target); err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"(",
"d",
"*",
"BundlesDir",
")",
"download",
"(",
"info",
"BundleInfo",
",",
"target",
"string",
",",
"abort",
"<-",
"chan",
"struct",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"// First download...",
"curl",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"info",
".",
"URL",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"expectedSha256",
",",
"err",
":=",
"info",
".",
"ArchiveSha256",
"(",
")",
"\n",
"req",
":=",
"downloader",
".",
"Request",
"{",
"URL",
":",
"curl",
",",
"TargetDir",
":",
"downloadsPath",
"(",
"d",
".",
"path",
")",
",",
"Verify",
":",
"downloader",
".",
"NewSha256Verifier",
"(",
"expectedSha256",
")",
",",
"Abort",
":",
"abort",
",",
"}",
"\n",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"info",
".",
"URL",
"(",
")",
")",
"\n",
"filename",
",",
"err",
":=",
"d",
".",
"downloader",
".",
"Download",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"info",
".",
"URL",
"(",
")",
")",
"\n",
"}",
"\n",
"defer",
"errors",
".",
"DeferredAnnotatef",
"(",
"&",
"err",
",",
"\"",
"\"",
",",
"target",
",",
"filename",
")",
"\n\n",
"// ...then move the right location.",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"d",
".",
"path",
",",
"0755",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"os",
".",
"Rename",
"(",
"filename",
",",
"target",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // download fetches the supplied charm and checks that it has the correct sha256
// hash, then copies it into the directory. If a value is received on abort, the
// download will be stopped. | [
"download",
"fetches",
"the",
"supplied",
"charm",
"and",
"checks",
"that",
"it",
"has",
"the",
"correct",
"sha256",
"hash",
"then",
"copies",
"it",
"into",
"the",
"directory",
".",
"If",
"a",
"value",
"is",
"received",
"on",
"abort",
"the",
"download",
"will",
"be",
"stopped",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/bundles.go#L64-L92 |
156,122 | juju/juju | worker/uniter/charm/bundles.go | bundlePath | func (d *BundlesDir) bundlePath(info BundleInfo) string {
return d.bundleURLPath(info.URL())
} | go | func (d *BundlesDir) bundlePath(info BundleInfo) string {
return d.bundleURLPath(info.URL())
} | [
"func",
"(",
"d",
"*",
"BundlesDir",
")",
"bundlePath",
"(",
"info",
"BundleInfo",
")",
"string",
"{",
"return",
"d",
".",
"bundleURLPath",
"(",
"info",
".",
"URL",
"(",
")",
")",
"\n",
"}"
] | // bundlePath returns the path to the location where the verified charm
// bundle identified by info will be, or has been, saved. | [
"bundlePath",
"returns",
"the",
"path",
"to",
"the",
"location",
"where",
"the",
"verified",
"charm",
"bundle",
"identified",
"by",
"info",
"will",
"be",
"or",
"has",
"been",
"saved",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/bundles.go#L96-L98 |
156,123 | juju/juju | worker/uniter/charm/bundles.go | bundleURLPath | func (d *BundlesDir) bundleURLPath(url *charm.URL) string {
return path.Join(d.path, charm.Quote(url.String()))
} | go | func (d *BundlesDir) bundleURLPath(url *charm.URL) string {
return path.Join(d.path, charm.Quote(url.String()))
} | [
"func",
"(",
"d",
"*",
"BundlesDir",
")",
"bundleURLPath",
"(",
"url",
"*",
"charm",
".",
"URL",
")",
"string",
"{",
"return",
"path",
".",
"Join",
"(",
"d",
".",
"path",
",",
"charm",
".",
"Quote",
"(",
"url",
".",
"String",
"(",
")",
")",
")",
"\n",
"}"
] | // bundleURLPath returns the path to the location where the verified charm
// bundle identified by url will be, or has been, saved. | [
"bundleURLPath",
"returns",
"the",
"path",
"to",
"the",
"location",
"where",
"the",
"verified",
"charm",
"bundle",
"identified",
"by",
"url",
"will",
"be",
"or",
"has",
"been",
"saved",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/bundles.go#L102-L104 |
156,124 | juju/juju | worker/uniter/charm/bundles.go | ClearDownloads | func ClearDownloads(bundlesDir string) error {
downloadDir := downloadsPath(bundlesDir)
err := os.RemoveAll(downloadDir)
return errors.Annotate(err, "unable to clear bundle downloads")
} | go | func ClearDownloads(bundlesDir string) error {
downloadDir := downloadsPath(bundlesDir)
err := os.RemoveAll(downloadDir)
return errors.Annotate(err, "unable to clear bundle downloads")
} | [
"func",
"ClearDownloads",
"(",
"bundlesDir",
"string",
")",
"error",
"{",
"downloadDir",
":=",
"downloadsPath",
"(",
"bundlesDir",
")",
"\n",
"err",
":=",
"os",
".",
"RemoveAll",
"(",
"downloadDir",
")",
"\n",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // ClearDownloads removes any entries in the temporary bundle download
// directory. It is intended to be called on uniter startup. | [
"ClearDownloads",
"removes",
"any",
"entries",
"in",
"the",
"temporary",
"bundle",
"download",
"directory",
".",
"It",
"is",
"intended",
"to",
"be",
"called",
"on",
"uniter",
"startup",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/bundles.go#L108-L112 |
156,125 | juju/juju | cmd/plugins/juju-metadata/listformatter.go | formatMetadataTabular | func formatMetadataTabular(writer io.Writer, metadata []MetadataInfo) {
tw := output.TabWriter(writer)
print := func(values ...string) {
fmt.Fprintln(tw, strings.Join(values, "\t"))
}
print("Source", "Series", "Arch", "Region", "Image id", "Stream", "Virt Type", "Storage Type")
for _, m := range metadata {
print(m.Source, m.Series, m.Arch, m.Region, m.ImageId, m.Stream, m.VirtType, m.RootStorageType)
}
tw.Flush()
} | go | func formatMetadataTabular(writer io.Writer, metadata []MetadataInfo) {
tw := output.TabWriter(writer)
print := func(values ...string) {
fmt.Fprintln(tw, strings.Join(values, "\t"))
}
print("Source", "Series", "Arch", "Region", "Image id", "Stream", "Virt Type", "Storage Type")
for _, m := range metadata {
print(m.Source, m.Series, m.Arch, m.Region, m.ImageId, m.Stream, m.VirtType, m.RootStorageType)
}
tw.Flush()
} | [
"func",
"formatMetadataTabular",
"(",
"writer",
"io",
".",
"Writer",
",",
"metadata",
"[",
"]",
"MetadataInfo",
")",
"{",
"tw",
":=",
"output",
".",
"TabWriter",
"(",
"writer",
")",
"\n",
"print",
":=",
"func",
"(",
"values",
"...",
"string",
")",
"{",
"fmt",
".",
"Fprintln",
"(",
"tw",
",",
"strings",
".",
"Join",
"(",
"values",
",",
"\"",
"\\t",
"\"",
")",
")",
"\n",
"}",
"\n",
"print",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"for",
"_",
",",
"m",
":=",
"range",
"metadata",
"{",
"print",
"(",
"m",
".",
"Source",
",",
"m",
".",
"Series",
",",
"m",
".",
"Arch",
",",
"m",
".",
"Region",
",",
"m",
".",
"ImageId",
",",
"m",
".",
"Stream",
",",
"m",
".",
"VirtType",
",",
"m",
".",
"RootStorageType",
")",
"\n",
"}",
"\n",
"tw",
".",
"Flush",
"(",
")",
"\n",
"}"
] | // formatMetadataTabular writes a tabular summary of cloud image metadata. | [
"formatMetadataTabular",
"writes",
"a",
"tabular",
"summary",
"of",
"cloud",
"image",
"metadata",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/plugins/juju-metadata/listformatter.go#L26-L37 |
156,126 | juju/juju | apiserver/facades/agent/agent/agent.go | NewAgentAPIV2 | func NewAgentAPIV2(st *state.State, resources facade.Resources, auth facade.Authorizer) (*AgentAPIV2, error) {
// Agents are defined to be any user that's not a client user.
if !auth.AuthMachineAgent() && !auth.AuthUnitAgent() {
return nil, common.ErrPerm
}
getCanChange := func() (common.AuthFunc, error) {
return auth.AuthOwner, nil
}
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
return &AgentAPIV2{
PasswordChanger: common.NewPasswordChanger(st, getCanChange),
RebootFlagClearer: common.NewRebootFlagClearer(st, getCanChange),
ModelWatcher: common.NewModelWatcher(model, resources, auth),
ControllerConfigAPI: common.NewStateControllerConfig(st),
CloudSpecAPI: cloudspec.NewCloudSpec(
resources,
cloudspec.MakeCloudSpecGetterForModel(st),
cloudspec.MakeCloudSpecWatcherForModel(st),
common.AuthFuncForTag(model.ModelTag()),
),
st: st,
auth: auth,
resources: resources,
}, nil
} | go | func NewAgentAPIV2(st *state.State, resources facade.Resources, auth facade.Authorizer) (*AgentAPIV2, error) {
// Agents are defined to be any user that's not a client user.
if !auth.AuthMachineAgent() && !auth.AuthUnitAgent() {
return nil, common.ErrPerm
}
getCanChange := func() (common.AuthFunc, error) {
return auth.AuthOwner, nil
}
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
return &AgentAPIV2{
PasswordChanger: common.NewPasswordChanger(st, getCanChange),
RebootFlagClearer: common.NewRebootFlagClearer(st, getCanChange),
ModelWatcher: common.NewModelWatcher(model, resources, auth),
ControllerConfigAPI: common.NewStateControllerConfig(st),
CloudSpecAPI: cloudspec.NewCloudSpec(
resources,
cloudspec.MakeCloudSpecGetterForModel(st),
cloudspec.MakeCloudSpecWatcherForModel(st),
common.AuthFuncForTag(model.ModelTag()),
),
st: st,
auth: auth,
resources: resources,
}, nil
} | [
"func",
"NewAgentAPIV2",
"(",
"st",
"*",
"state",
".",
"State",
",",
"resources",
"facade",
".",
"Resources",
",",
"auth",
"facade",
".",
"Authorizer",
")",
"(",
"*",
"AgentAPIV2",
",",
"error",
")",
"{",
"// Agents are defined to be any user that's not a client user.",
"if",
"!",
"auth",
".",
"AuthMachineAgent",
"(",
")",
"&&",
"!",
"auth",
".",
"AuthUnitAgent",
"(",
")",
"{",
"return",
"nil",
",",
"common",
".",
"ErrPerm",
"\n",
"}",
"\n",
"getCanChange",
":=",
"func",
"(",
")",
"(",
"common",
".",
"AuthFunc",
",",
"error",
")",
"{",
"return",
"auth",
".",
"AuthOwner",
",",
"nil",
"\n",
"}",
"\n\n",
"model",
",",
"err",
":=",
"st",
".",
"Model",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"AgentAPIV2",
"{",
"PasswordChanger",
":",
"common",
".",
"NewPasswordChanger",
"(",
"st",
",",
"getCanChange",
")",
",",
"RebootFlagClearer",
":",
"common",
".",
"NewRebootFlagClearer",
"(",
"st",
",",
"getCanChange",
")",
",",
"ModelWatcher",
":",
"common",
".",
"NewModelWatcher",
"(",
"model",
",",
"resources",
",",
"auth",
")",
",",
"ControllerConfigAPI",
":",
"common",
".",
"NewStateControllerConfig",
"(",
"st",
")",
",",
"CloudSpecAPI",
":",
"cloudspec",
".",
"NewCloudSpec",
"(",
"resources",
",",
"cloudspec",
".",
"MakeCloudSpecGetterForModel",
"(",
"st",
")",
",",
"cloudspec",
".",
"MakeCloudSpecWatcherForModel",
"(",
"st",
")",
",",
"common",
".",
"AuthFuncForTag",
"(",
"model",
".",
"ModelTag",
"(",
")",
")",
",",
")",
",",
"st",
":",
"st",
",",
"auth",
":",
"auth",
",",
"resources",
":",
"resources",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewAgentAPIV2 returns an object implementing version 2 of the Agent API
// with the given authorizer representing the currently logged in client. | [
"NewAgentAPIV2",
"returns",
"an",
"object",
"implementing",
"version",
"2",
"of",
"the",
"Agent",
"API",
"with",
"the",
"given",
"authorizer",
"representing",
"the",
"currently",
"logged",
"in",
"client",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/agent/agent.go#L38-L66 |
156,127 | juju/juju | apiserver/facades/agent/agent/agent.go | WatchCredentials | func (api *AgentAPIV2) WatchCredentials(args params.Entities) (params.NotifyWatchResults, error) {
if !api.auth.AuthController() {
return params.NotifyWatchResults{}, common.ErrPerm
}
results := params.NotifyWatchResults{
Results: make([]params.NotifyWatchResult, len(args.Entities)),
}
for i, entity := range args.Entities {
credentialTag, err := names.ParseCloudCredentialTag(entity.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
watch := api.st.WatchCredential(credentialTag)
// Consume the initial event. Technically, API calls to Watch
// 'transmit' the initial event in the Watch response. But
// NotifyWatchers have no state to transmit.
if _, ok := <-watch.Changes(); ok {
results.Results[i].NotifyWatcherId = api.resources.Register(watch)
} else {
err = watcher.EnsureErr(watch)
results.Results[i].Error = common.ServerError(err)
}
}
return results, nil
} | go | func (api *AgentAPIV2) WatchCredentials(args params.Entities) (params.NotifyWatchResults, error) {
if !api.auth.AuthController() {
return params.NotifyWatchResults{}, common.ErrPerm
}
results := params.NotifyWatchResults{
Results: make([]params.NotifyWatchResult, len(args.Entities)),
}
for i, entity := range args.Entities {
credentialTag, err := names.ParseCloudCredentialTag(entity.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
watch := api.st.WatchCredential(credentialTag)
// Consume the initial event. Technically, API calls to Watch
// 'transmit' the initial event in the Watch response. But
// NotifyWatchers have no state to transmit.
if _, ok := <-watch.Changes(); ok {
results.Results[i].NotifyWatcherId = api.resources.Register(watch)
} else {
err = watcher.EnsureErr(watch)
results.Results[i].Error = common.ServerError(err)
}
}
return results, nil
} | [
"func",
"(",
"api",
"*",
"AgentAPIV2",
")",
"WatchCredentials",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"NotifyWatchResults",
",",
"error",
")",
"{",
"if",
"!",
"api",
".",
"auth",
".",
"AuthController",
"(",
")",
"{",
"return",
"params",
".",
"NotifyWatchResults",
"{",
"}",
",",
"common",
".",
"ErrPerm",
"\n",
"}",
"\n\n",
"results",
":=",
"params",
".",
"NotifyWatchResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"NotifyWatchResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"entity",
":=",
"range",
"args",
".",
"Entities",
"{",
"credentialTag",
",",
"err",
":=",
"names",
".",
"ParseCloudCredentialTag",
"(",
"entity",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"watch",
":=",
"api",
".",
"st",
".",
"WatchCredential",
"(",
"credentialTag",
")",
"\n",
"// Consume the initial event. Technically, API calls to Watch",
"// 'transmit' the initial event in the Watch response. But",
"// NotifyWatchers have no state to transmit.",
"if",
"_",
",",
"ok",
":=",
"<-",
"watch",
".",
"Changes",
"(",
")",
";",
"ok",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"NotifyWatcherId",
"=",
"api",
".",
"resources",
".",
"Register",
"(",
"watch",
")",
"\n",
"}",
"else",
"{",
"err",
"=",
"watcher",
".",
"EnsureErr",
"(",
"watch",
")",
"\n",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // WatchCredentials watches for changes to the specified credentials. | [
"WatchCredentials",
"watches",
"for",
"changes",
"to",
"the",
"specified",
"credentials",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/agent/agent.go#L173-L199 |
156,128 | juju/juju | apiserver/observer/auditfilter.go | NewAuditLogFilter | func NewAuditLogFilter(log auditlog.AuditLog, filter func(auditlog.Request) bool) auditlog.AuditLog {
return &bufferedLog{
dest: log,
interesting: filter,
}
} | go | func NewAuditLogFilter(log auditlog.AuditLog, filter func(auditlog.Request) bool) auditlog.AuditLog {
return &bufferedLog{
dest: log,
interesting: filter,
}
} | [
"func",
"NewAuditLogFilter",
"(",
"log",
"auditlog",
".",
"AuditLog",
",",
"filter",
"func",
"(",
"auditlog",
".",
"Request",
")",
"bool",
")",
"auditlog",
".",
"AuditLog",
"{",
"return",
"&",
"bufferedLog",
"{",
"dest",
":",
"log",
",",
"interesting",
":",
"filter",
",",
"}",
"\n",
"}"
] | // NewAuditLogFilter returns an auditlog.AuditLog that will only log
// conversations to the underlying log passed in if they include a
// request that satisfies the filter function passed in. | [
"NewAuditLogFilter",
"returns",
"an",
"auditlog",
".",
"AuditLog",
"that",
"will",
"only",
"log",
"conversations",
"to",
"the",
"underlying",
"log",
"passed",
"in",
"if",
"they",
"include",
"a",
"request",
"that",
"satisfies",
"the",
"filter",
"function",
"passed",
"in",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/auditfilter.go#L30-L35 |
156,129 | juju/juju | apiserver/observer/auditfilter.go | AddConversation | func (l *bufferedLog) AddConversation(c auditlog.Conversation) error {
l.mu.Lock()
defer l.mu.Unlock()
// We always buffer the conversation, since we don't know whether
// it will have any interesting requests yet.
l.deferMessage(c)
return nil
} | go | func (l *bufferedLog) AddConversation(c auditlog.Conversation) error {
l.mu.Lock()
defer l.mu.Unlock()
// We always buffer the conversation, since we don't know whether
// it will have any interesting requests yet.
l.deferMessage(c)
return nil
} | [
"func",
"(",
"l",
"*",
"bufferedLog",
")",
"AddConversation",
"(",
"c",
"auditlog",
".",
"Conversation",
")",
"error",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"// We always buffer the conversation, since we don't know whether",
"// it will have any interesting requests yet.",
"l",
".",
"deferMessage",
"(",
"c",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddConversation implements auditlog.AuditLog. | [
"AddConversation",
"implements",
"auditlog",
".",
"AuditLog",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/auditfilter.go#L38-L45 |
156,130 | juju/juju | apiserver/observer/auditfilter.go | AddRequest | func (l *bufferedLog) AddRequest(r auditlog.Request) error {
l.mu.Lock()
if len(l.buffer) > 0 {
l.deferMessage(r)
var err error
if l.interesting(r) {
err = l.flush()
}
l.mu.Unlock()
return err
}
l.mu.Unlock()
// We've already flushed messages, forward this on
// immediately.
return l.dest.AddRequest(r)
} | go | func (l *bufferedLog) AddRequest(r auditlog.Request) error {
l.mu.Lock()
if len(l.buffer) > 0 {
l.deferMessage(r)
var err error
if l.interesting(r) {
err = l.flush()
}
l.mu.Unlock()
return err
}
l.mu.Unlock()
// We've already flushed messages, forward this on
// immediately.
return l.dest.AddRequest(r)
} | [
"func",
"(",
"l",
"*",
"bufferedLog",
")",
"AddRequest",
"(",
"r",
"auditlog",
".",
"Request",
")",
"error",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"len",
"(",
"l",
".",
"buffer",
")",
">",
"0",
"{",
"l",
".",
"deferMessage",
"(",
"r",
")",
"\n",
"var",
"err",
"error",
"\n",
"if",
"l",
".",
"interesting",
"(",
"r",
")",
"{",
"err",
"=",
"l",
".",
"flush",
"(",
")",
"\n",
"}",
"\n",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"// We've already flushed messages, forward this on",
"// immediately.",
"return",
"l",
".",
"dest",
".",
"AddRequest",
"(",
"r",
")",
"\n",
"}"
] | // AddRequest implements auditlog.AuditLog. | [
"AddRequest",
"implements",
"auditlog",
".",
"AuditLog",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/auditfilter.go#L48-L63 |
156,131 | juju/juju | apiserver/observer/auditfilter.go | AddResponse | func (l *bufferedLog) AddResponse(r auditlog.ResponseErrors) error {
l.mu.Lock()
if len(l.buffer) > 0 {
l.deferMessage(r)
l.mu.Unlock()
return nil
}
l.mu.Unlock()
// We've already flushed messages, forward this on
// immediately.
return l.dest.AddResponse(r)
} | go | func (l *bufferedLog) AddResponse(r auditlog.ResponseErrors) error {
l.mu.Lock()
if len(l.buffer) > 0 {
l.deferMessage(r)
l.mu.Unlock()
return nil
}
l.mu.Unlock()
// We've already flushed messages, forward this on
// immediately.
return l.dest.AddResponse(r)
} | [
"func",
"(",
"l",
"*",
"bufferedLog",
")",
"AddResponse",
"(",
"r",
"auditlog",
".",
"ResponseErrors",
")",
"error",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"len",
"(",
"l",
".",
"buffer",
")",
">",
"0",
"{",
"l",
".",
"deferMessage",
"(",
"r",
")",
"\n",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"// We've already flushed messages, forward this on",
"// immediately.",
"return",
"l",
".",
"dest",
".",
"AddResponse",
"(",
"r",
")",
"\n",
"}"
] | // AddResponse implements auditlog.AuditLog. | [
"AddResponse",
"implements",
"auditlog",
".",
"AuditLog",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/auditfilter.go#L66-L77 |
156,132 | juju/juju | state/linklayerdevices.go | IsValidLinkLayerDeviceType | func IsValidLinkLayerDeviceType(value string) bool {
switch LinkLayerDeviceType(value) {
case LoopbackDevice, EthernetDevice,
VLAN_8021QDevice,
BondDevice, BridgeDevice:
return true
}
return false
} | go | func IsValidLinkLayerDeviceType(value string) bool {
switch LinkLayerDeviceType(value) {
case LoopbackDevice, EthernetDevice,
VLAN_8021QDevice,
BondDevice, BridgeDevice:
return true
}
return false
} | [
"func",
"IsValidLinkLayerDeviceType",
"(",
"value",
"string",
")",
"bool",
"{",
"switch",
"LinkLayerDeviceType",
"(",
"value",
")",
"{",
"case",
"LoopbackDevice",
",",
"EthernetDevice",
",",
"VLAN_8021QDevice",
",",
"BondDevice",
",",
"BridgeDevice",
":",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsValidLinkLayerDeviceType returns whether the given value is a valid
// link-layer network device type. | [
"IsValidLinkLayerDeviceType",
"returns",
"whether",
"the",
"given",
"value",
"is",
"a",
"valid",
"link",
"-",
"layer",
"network",
"device",
"type",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L82-L90 |
156,133 | juju/juju | state/linklayerdevices.go | AllLinkLayerDevices | func (st *State) AllLinkLayerDevices() (devices []*LinkLayerDevice, err error) {
devicesCollection, closer := st.db().GetCollection(linkLayerDevicesC)
defer closer()
sdocs := []linkLayerDeviceDoc{}
err = devicesCollection.Find(nil).All(&sdocs)
if err != nil {
return nil, errors.Errorf("cannot get all link layer devices")
}
for _, d := range sdocs {
devices = append(devices, newLinkLayerDevice(st, d))
}
return devices, nil
} | go | func (st *State) AllLinkLayerDevices() (devices []*LinkLayerDevice, err error) {
devicesCollection, closer := st.db().GetCollection(linkLayerDevicesC)
defer closer()
sdocs := []linkLayerDeviceDoc{}
err = devicesCollection.Find(nil).All(&sdocs)
if err != nil {
return nil, errors.Errorf("cannot get all link layer devices")
}
for _, d := range sdocs {
devices = append(devices, newLinkLayerDevice(st, d))
}
return devices, nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"AllLinkLayerDevices",
"(",
")",
"(",
"devices",
"[",
"]",
"*",
"LinkLayerDevice",
",",
"err",
"error",
")",
"{",
"devicesCollection",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"linkLayerDevicesC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"sdocs",
":=",
"[",
"]",
"linkLayerDeviceDoc",
"{",
"}",
"\n",
"err",
"=",
"devicesCollection",
".",
"Find",
"(",
"nil",
")",
".",
"All",
"(",
"&",
"sdocs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"sdocs",
"{",
"devices",
"=",
"append",
"(",
"devices",
",",
"newLinkLayerDevice",
"(",
"st",
",",
"d",
")",
")",
"\n",
"}",
"\n",
"return",
"devices",
",",
"nil",
"\n",
"}"
] | // AllLinkLayerDevices returns all link layer devices in the model. | [
"AllLinkLayerDevices",
"returns",
"all",
"link",
"layer",
"devices",
"in",
"the",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L104-L117 |
156,134 | juju/juju | state/linklayerdevices.go | DocID | func (dev *LinkLayerDevice) DocID() string {
return dev.st.docID(dev.doc.DocID)
} | go | func (dev *LinkLayerDevice) DocID() string {
return dev.st.docID(dev.doc.DocID)
} | [
"func",
"(",
"dev",
"*",
"LinkLayerDevice",
")",
"DocID",
"(",
")",
"string",
"{",
"return",
"dev",
".",
"st",
".",
"docID",
"(",
"dev",
".",
"doc",
".",
"DocID",
")",
"\n",
"}"
] | // DocID returns the globally unique ID of the link-layer device, including the
// model UUID as prefix. | [
"DocID",
"returns",
"the",
"globally",
"unique",
"ID",
"of",
"the",
"link",
"-",
"layer",
"device",
"including",
"the",
"model",
"UUID",
"as",
"prefix",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L121-L123 |
156,135 | juju/juju | state/linklayerdevices.go | ProviderID | func (dev *LinkLayerDevice) ProviderID() network.Id {
return network.Id(dev.doc.ProviderID)
} | go | func (dev *LinkLayerDevice) ProviderID() network.Id {
return network.Id(dev.doc.ProviderID)
} | [
"func",
"(",
"dev",
"*",
"LinkLayerDevice",
")",
"ProviderID",
"(",
")",
"network",
".",
"Id",
"{",
"return",
"network",
".",
"Id",
"(",
"dev",
".",
"doc",
".",
"ProviderID",
")",
"\n",
"}"
] | // ProviderID returns the provider-specific device ID, if set. | [
"ProviderID",
"returns",
"the",
"provider",
"-",
"specific",
"device",
"ID",
"if",
"set",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L136-L138 |
156,136 | juju/juju | state/linklayerdevices.go | Machine | func (dev *LinkLayerDevice) Machine() (*Machine, error) {
return dev.st.Machine(dev.doc.MachineID)
} | go | func (dev *LinkLayerDevice) Machine() (*Machine, error) {
return dev.st.Machine(dev.doc.MachineID)
} | [
"func",
"(",
"dev",
"*",
"LinkLayerDevice",
")",
"Machine",
"(",
")",
"(",
"*",
"Machine",
",",
"error",
")",
"{",
"return",
"dev",
".",
"st",
".",
"Machine",
"(",
"dev",
".",
"doc",
".",
"MachineID",
")",
"\n",
"}"
] | // Machine returns the Machine this device belongs to. | [
"Machine",
"returns",
"the",
"Machine",
"this",
"device",
"belongs",
"to",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L146-L148 |
156,137 | juju/juju | state/linklayerdevices.go | ParentDevice | func (dev *LinkLayerDevice) ParentDevice() (*LinkLayerDevice, error) {
if dev.doc.ParentName == "" {
return nil, nil
}
parentDeviceName, parentMachineID := dev.parentDeviceNameAndMachineID()
return dev.machineProxy(parentMachineID).LinkLayerDevice(parentDeviceName)
} | go | func (dev *LinkLayerDevice) ParentDevice() (*LinkLayerDevice, error) {
if dev.doc.ParentName == "" {
return nil, nil
}
parentDeviceName, parentMachineID := dev.parentDeviceNameAndMachineID()
return dev.machineProxy(parentMachineID).LinkLayerDevice(parentDeviceName)
} | [
"func",
"(",
"dev",
"*",
"LinkLayerDevice",
")",
"ParentDevice",
"(",
")",
"(",
"*",
"LinkLayerDevice",
",",
"error",
")",
"{",
"if",
"dev",
".",
"doc",
".",
"ParentName",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"parentDeviceName",
",",
"parentMachineID",
":=",
"dev",
".",
"parentDeviceNameAndMachineID",
"(",
")",
"\n",
"return",
"dev",
".",
"machineProxy",
"(",
"parentMachineID",
")",
".",
"LinkLayerDevice",
"(",
"parentDeviceName",
")",
"\n",
"}"
] | // ParentDevice returns the LinkLayerDevice corresponding to the parent device
// of this device, if set. When no parent device name is set, it returns nil and
// no error. | [
"ParentDevice",
"returns",
"the",
"LinkLayerDevice",
"corresponding",
"to",
"the",
"parent",
"device",
"of",
"this",
"device",
"if",
"set",
".",
"When",
"no",
"parent",
"device",
"name",
"is",
"set",
"it",
"returns",
"nil",
"and",
"no",
"error",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L209-L216 |
156,138 | juju/juju | state/linklayerdevices.go | Remove | func (dev *LinkLayerDevice) Remove() (err error) {
defer errors.DeferredAnnotatef(&err, "cannot remove %s", dev)
buildTxn := func(attempt int) ([]txn.Op, error) {
if attempt > 0 {
if err = dev.errNoOperationsIfMissing(); err != nil {
return nil, err
}
}
ops, err := removeLinkLayerDeviceOps(dev.st, dev.DocID(), dev.parentDocID())
if err != nil {
return nil, err
}
if dev.ProviderID() != "" {
op := dev.st.networkEntityGlobalKeyRemoveOp("linklayerdevice", dev.ProviderID())
ops = append(ops, op)
}
return ops, nil
}
return dev.st.db().Run(buildTxn)
} | go | func (dev *LinkLayerDevice) Remove() (err error) {
defer errors.DeferredAnnotatef(&err, "cannot remove %s", dev)
buildTxn := func(attempt int) ([]txn.Op, error) {
if attempt > 0 {
if err = dev.errNoOperationsIfMissing(); err != nil {
return nil, err
}
}
ops, err := removeLinkLayerDeviceOps(dev.st, dev.DocID(), dev.parentDocID())
if err != nil {
return nil, err
}
if dev.ProviderID() != "" {
op := dev.st.networkEntityGlobalKeyRemoveOp("linklayerdevice", dev.ProviderID())
ops = append(ops, op)
}
return ops, nil
}
return dev.st.db().Run(buildTxn)
} | [
"func",
"(",
"dev",
"*",
"LinkLayerDevice",
")",
"Remove",
"(",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"errors",
".",
"DeferredAnnotatef",
"(",
"&",
"err",
",",
"\"",
"\"",
",",
"dev",
")",
"\n\n",
"buildTxn",
":=",
"func",
"(",
"attempt",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"if",
"attempt",
">",
"0",
"{",
"if",
"err",
"=",
"dev",
".",
"errNoOperationsIfMissing",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"ops",
",",
"err",
":=",
"removeLinkLayerDeviceOps",
"(",
"dev",
".",
"st",
",",
"dev",
".",
"DocID",
"(",
")",
",",
"dev",
".",
"parentDocID",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"dev",
".",
"ProviderID",
"(",
")",
"!=",
"\"",
"\"",
"{",
"op",
":=",
"dev",
".",
"st",
".",
"networkEntityGlobalKeyRemoveOp",
"(",
"\"",
"\"",
",",
"dev",
".",
"ProviderID",
"(",
")",
")",
"\n",
"ops",
"=",
"append",
"(",
"ops",
",",
"op",
")",
"\n",
"}",
"\n",
"return",
"ops",
",",
"nil",
"\n",
"}",
"\n",
"return",
"dev",
".",
"st",
".",
"db",
"(",
")",
".",
"Run",
"(",
"buildTxn",
")",
"\n",
"}"
] | // Remove removes the device, if it exists. No error is returned when the device
// was already removed. ErrParentDeviceHasChildren is returned if this device is
// a parent to one or more existing devices and therefore cannot be removed. | [
"Remove",
"removes",
"the",
"device",
"if",
"it",
"exists",
".",
"No",
"error",
"is",
"returned",
"when",
"the",
"device",
"was",
"already",
"removed",
".",
"ErrParentDeviceHasChildren",
"is",
"returned",
"if",
"this",
"device",
"is",
"a",
"parent",
"to",
"one",
"or",
"more",
"existing",
"devices",
"and",
"therefore",
"cannot",
"be",
"removed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L236-L256 |
156,139 | juju/juju | state/linklayerdevices.go | removeLinkLayerDeviceOps | func removeLinkLayerDeviceOps(st *State, linkLayerDeviceDocID, parentDeviceDocID string) ([]txn.Op, error) {
var numChildren int
if parentDeviceDocID == "" {
// If not a child, verify it has no children.
var err error
numChildren, err = getParentDeviceNumChildrenRefs(st, linkLayerDeviceDocID)
if err != nil {
return nil, errors.Trace(err)
}
}
// We know the DocID has a valid format for a global key, hence the last
// return below is ignored.
machineID, deviceName, canBeGlobalKey := parseLinkLayerDeviceGlobalKey(linkLayerDeviceDocID)
if !canBeGlobalKey {
return nil, errors.Errorf(
"link-layer device %q on machine %q has unexpected key format",
machineID, deviceName,
)
}
if numChildren > 0 {
return nil, newParentDeviceHasChildrenError(deviceName, numChildren)
}
var ops []txn.Op
if parentDeviceDocID != "" {
ops = append(ops, decrementDeviceNumChildrenOp(parentDeviceDocID))
}
addressesQuery := findAddressesQuery(machineID, deviceName)
if addressesOps, err := st.removeMatchingIPAddressesDocOps(addressesQuery); err == nil {
ops = append(ops, addressesOps...)
} else {
return nil, errors.Trace(err)
}
return append(ops,
removeLinkLayerDeviceDocOp(linkLayerDeviceDocID),
removeLinkLayerDevicesRefsOp(linkLayerDeviceDocID),
), nil
} | go | func removeLinkLayerDeviceOps(st *State, linkLayerDeviceDocID, parentDeviceDocID string) ([]txn.Op, error) {
var numChildren int
if parentDeviceDocID == "" {
// If not a child, verify it has no children.
var err error
numChildren, err = getParentDeviceNumChildrenRefs(st, linkLayerDeviceDocID)
if err != nil {
return nil, errors.Trace(err)
}
}
// We know the DocID has a valid format for a global key, hence the last
// return below is ignored.
machineID, deviceName, canBeGlobalKey := parseLinkLayerDeviceGlobalKey(linkLayerDeviceDocID)
if !canBeGlobalKey {
return nil, errors.Errorf(
"link-layer device %q on machine %q has unexpected key format",
machineID, deviceName,
)
}
if numChildren > 0 {
return nil, newParentDeviceHasChildrenError(deviceName, numChildren)
}
var ops []txn.Op
if parentDeviceDocID != "" {
ops = append(ops, decrementDeviceNumChildrenOp(parentDeviceDocID))
}
addressesQuery := findAddressesQuery(machineID, deviceName)
if addressesOps, err := st.removeMatchingIPAddressesDocOps(addressesQuery); err == nil {
ops = append(ops, addressesOps...)
} else {
return nil, errors.Trace(err)
}
return append(ops,
removeLinkLayerDeviceDocOp(linkLayerDeviceDocID),
removeLinkLayerDevicesRefsOp(linkLayerDeviceDocID),
), nil
} | [
"func",
"removeLinkLayerDeviceOps",
"(",
"st",
"*",
"State",
",",
"linkLayerDeviceDocID",
",",
"parentDeviceDocID",
"string",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"var",
"numChildren",
"int",
"\n",
"if",
"parentDeviceDocID",
"==",
"\"",
"\"",
"{",
"// If not a child, verify it has no children.",
"var",
"err",
"error",
"\n",
"numChildren",
",",
"err",
"=",
"getParentDeviceNumChildrenRefs",
"(",
"st",
",",
"linkLayerDeviceDocID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// We know the DocID has a valid format for a global key, hence the last",
"// return below is ignored.",
"machineID",
",",
"deviceName",
",",
"canBeGlobalKey",
":=",
"parseLinkLayerDeviceGlobalKey",
"(",
"linkLayerDeviceDocID",
")",
"\n",
"if",
"!",
"canBeGlobalKey",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"machineID",
",",
"deviceName",
",",
")",
"\n",
"}",
"\n",
"if",
"numChildren",
">",
"0",
"{",
"return",
"nil",
",",
"newParentDeviceHasChildrenError",
"(",
"deviceName",
",",
"numChildren",
")",
"\n",
"}",
"\n\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"if",
"parentDeviceDocID",
"!=",
"\"",
"\"",
"{",
"ops",
"=",
"append",
"(",
"ops",
",",
"decrementDeviceNumChildrenOp",
"(",
"parentDeviceDocID",
")",
")",
"\n",
"}",
"\n\n",
"addressesQuery",
":=",
"findAddressesQuery",
"(",
"machineID",
",",
"deviceName",
")",
"\n",
"if",
"addressesOps",
",",
"err",
":=",
"st",
".",
"removeMatchingIPAddressesDocOps",
"(",
"addressesQuery",
")",
";",
"err",
"==",
"nil",
"{",
"ops",
"=",
"append",
"(",
"ops",
",",
"addressesOps",
"...",
")",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"append",
"(",
"ops",
",",
"removeLinkLayerDeviceDocOp",
"(",
"linkLayerDeviceDocID",
")",
",",
"removeLinkLayerDevicesRefsOp",
"(",
"linkLayerDeviceDocID",
")",
",",
")",
",",
"nil",
"\n",
"}"
] | // removeLinkLayerDeviceOps returns the list of operations needed to remove the
// device with the given linkLayerDeviceDocID, asserting it still exists and has
// no children referring to it. If the device is a child, parentDeviceDocID will
// be non-empty and the operations includes decrementing the parent's
// NumChildren. | [
"removeLinkLayerDeviceOps",
"returns",
"the",
"list",
"of",
"operations",
"needed",
"to",
"remove",
"the",
"device",
"with",
"the",
"given",
"linkLayerDeviceDocID",
"asserting",
"it",
"still",
"exists",
"and",
"has",
"no",
"children",
"referring",
"to",
"it",
".",
"If",
"the",
"device",
"is",
"a",
"child",
"parentDeviceDocID",
"will",
"be",
"non",
"-",
"empty",
"and",
"the",
"operations",
"includes",
"decrementing",
"the",
"parent",
"s",
"NumChildren",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L273-L313 |
156,140 | juju/juju | state/linklayerdevices.go | removeLinkLayerDeviceDocOp | func removeLinkLayerDeviceDocOp(linkLayerDeviceDocID string) txn.Op {
return txn.Op{
C: linkLayerDevicesC,
Id: linkLayerDeviceDocID,
Assert: txn.DocExists,
Remove: true,
}
} | go | func removeLinkLayerDeviceDocOp(linkLayerDeviceDocID string) txn.Op {
return txn.Op{
C: linkLayerDevicesC,
Id: linkLayerDeviceDocID,
Assert: txn.DocExists,
Remove: true,
}
} | [
"func",
"removeLinkLayerDeviceDocOp",
"(",
"linkLayerDeviceDocID",
"string",
")",
"txn",
".",
"Op",
"{",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"linkLayerDevicesC",
",",
"Id",
":",
"linkLayerDeviceDocID",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Remove",
":",
"true",
",",
"}",
"\n",
"}"
] | // removeLinkLayerDeviceDocOp returns an operation to remove the
// linkLayerDeviceDoc matching the given linkLayerDeviceDocID, asserting it
// still exists. | [
"removeLinkLayerDeviceDocOp",
"returns",
"an",
"operation",
"to",
"remove",
"the",
"linkLayerDeviceDoc",
"matching",
"the",
"given",
"linkLayerDeviceDocID",
"asserting",
"it",
"still",
"exists",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L318-L325 |
156,141 | juju/juju | state/linklayerdevices.go | removeLinkLayerDeviceUnconditionallyOps | func removeLinkLayerDeviceUnconditionallyOps(linkLayerDeviceDocID string) []txn.Op {
// Reuse the regular remove ops, but drop their asserts.
removeDeviceDocOp := removeLinkLayerDeviceDocOp(linkLayerDeviceDocID)
removeDeviceDocOp.Assert = nil
removeRefsOp := removeLinkLayerDevicesRefsOp(linkLayerDeviceDocID)
removeRefsOp.Assert = nil
return []txn.Op{
removeDeviceDocOp,
removeRefsOp,
}
} | go | func removeLinkLayerDeviceUnconditionallyOps(linkLayerDeviceDocID string) []txn.Op {
// Reuse the regular remove ops, but drop their asserts.
removeDeviceDocOp := removeLinkLayerDeviceDocOp(linkLayerDeviceDocID)
removeDeviceDocOp.Assert = nil
removeRefsOp := removeLinkLayerDevicesRefsOp(linkLayerDeviceDocID)
removeRefsOp.Assert = nil
return []txn.Op{
removeDeviceDocOp,
removeRefsOp,
}
} | [
"func",
"removeLinkLayerDeviceUnconditionallyOps",
"(",
"linkLayerDeviceDocID",
"string",
")",
"[",
"]",
"txn",
".",
"Op",
"{",
"// Reuse the regular remove ops, but drop their asserts.",
"removeDeviceDocOp",
":=",
"removeLinkLayerDeviceDocOp",
"(",
"linkLayerDeviceDocID",
")",
"\n",
"removeDeviceDocOp",
".",
"Assert",
"=",
"nil",
"\n",
"removeRefsOp",
":=",
"removeLinkLayerDevicesRefsOp",
"(",
"linkLayerDeviceDocID",
")",
"\n",
"removeRefsOp",
".",
"Assert",
"=",
"nil",
"\n\n",
"return",
"[",
"]",
"txn",
".",
"Op",
"{",
"removeDeviceDocOp",
",",
"removeRefsOp",
",",
"}",
"\n",
"}"
] | // removeLinkLayerDeviceUnconditionallyOps returns the list of operations to
// unconditionally remove the device matching the given linkLayerDeviceDocID,
// along with its linkLayerDevicesRefsDoc. No asserts are included for the
// existence of both documents. | [
"removeLinkLayerDeviceUnconditionallyOps",
"returns",
"the",
"list",
"of",
"operations",
"to",
"unconditionally",
"remove",
"the",
"device",
"matching",
"the",
"given",
"linkLayerDeviceDocID",
"along",
"with",
"its",
"linkLayerDevicesRefsDoc",
".",
"No",
"asserts",
"are",
"included",
"for",
"the",
"existence",
"of",
"both",
"documents",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L331-L342 |
156,142 | juju/juju | state/linklayerdevices.go | insertLinkLayerDeviceDocOp | func insertLinkLayerDeviceDocOp(newDoc *linkLayerDeviceDoc) txn.Op {
return txn.Op{
C: linkLayerDevicesC,
Id: newDoc.DocID,
Assert: txn.DocMissing,
Insert: *newDoc,
}
} | go | func insertLinkLayerDeviceDocOp(newDoc *linkLayerDeviceDoc) txn.Op {
return txn.Op{
C: linkLayerDevicesC,
Id: newDoc.DocID,
Assert: txn.DocMissing,
Insert: *newDoc,
}
} | [
"func",
"insertLinkLayerDeviceDocOp",
"(",
"newDoc",
"*",
"linkLayerDeviceDoc",
")",
"txn",
".",
"Op",
"{",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"linkLayerDevicesC",
",",
"Id",
":",
"newDoc",
".",
"DocID",
",",
"Assert",
":",
"txn",
".",
"DocMissing",
",",
"Insert",
":",
"*",
"newDoc",
",",
"}",
"\n",
"}"
] | // insertLinkLayerDeviceDocOp returns an operation inserting the given newDoc,
// asserting it does not exist yet. | [
"insertLinkLayerDeviceDocOp",
"returns",
"an",
"operation",
"inserting",
"the",
"given",
"newDoc",
"asserting",
"it",
"does",
"not",
"exist",
"yet",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L346-L353 |
156,143 | juju/juju | state/linklayerdevices.go | updateLinkLayerDeviceDocOp | func updateLinkLayerDeviceDocOp(existingDoc, newDoc *linkLayerDeviceDoc) (txn.Op, bool) {
changes := make(bson.M)
if existingDoc.ProviderID == "" && newDoc.ProviderID != "" {
// Only allow changing the ProviderID if it was empty.
changes["providerid"] = newDoc.ProviderID
}
if existingDoc.Type != newDoc.Type {
changes["type"] = newDoc.Type
}
if existingDoc.MTU != newDoc.MTU {
changes["mtu"] = newDoc.MTU
}
if existingDoc.MACAddress != newDoc.MACAddress {
changes["mac-address"] = newDoc.MACAddress
}
if existingDoc.IsAutoStart != newDoc.IsAutoStart {
changes["is-auto-start"] = newDoc.IsAutoStart
}
if existingDoc.IsUp != newDoc.IsUp {
changes["is-up"] = newDoc.IsUp
}
if existingDoc.ParentName != newDoc.ParentName {
changes["parent-name"] = newDoc.ParentName
}
var updates bson.D
if len(changes) > 0 {
updates = append(updates, bson.DocElem{Name: "$set", Value: changes})
}
return txn.Op{
C: linkLayerDevicesC,
Id: existingDoc.DocID,
Assert: txn.DocExists,
Update: updates,
}, len(updates) > 0
} | go | func updateLinkLayerDeviceDocOp(existingDoc, newDoc *linkLayerDeviceDoc) (txn.Op, bool) {
changes := make(bson.M)
if existingDoc.ProviderID == "" && newDoc.ProviderID != "" {
// Only allow changing the ProviderID if it was empty.
changes["providerid"] = newDoc.ProviderID
}
if existingDoc.Type != newDoc.Type {
changes["type"] = newDoc.Type
}
if existingDoc.MTU != newDoc.MTU {
changes["mtu"] = newDoc.MTU
}
if existingDoc.MACAddress != newDoc.MACAddress {
changes["mac-address"] = newDoc.MACAddress
}
if existingDoc.IsAutoStart != newDoc.IsAutoStart {
changes["is-auto-start"] = newDoc.IsAutoStart
}
if existingDoc.IsUp != newDoc.IsUp {
changes["is-up"] = newDoc.IsUp
}
if existingDoc.ParentName != newDoc.ParentName {
changes["parent-name"] = newDoc.ParentName
}
var updates bson.D
if len(changes) > 0 {
updates = append(updates, bson.DocElem{Name: "$set", Value: changes})
}
return txn.Op{
C: linkLayerDevicesC,
Id: existingDoc.DocID,
Assert: txn.DocExists,
Update: updates,
}, len(updates) > 0
} | [
"func",
"updateLinkLayerDeviceDocOp",
"(",
"existingDoc",
",",
"newDoc",
"*",
"linkLayerDeviceDoc",
")",
"(",
"txn",
".",
"Op",
",",
"bool",
")",
"{",
"changes",
":=",
"make",
"(",
"bson",
".",
"M",
")",
"\n",
"if",
"existingDoc",
".",
"ProviderID",
"==",
"\"",
"\"",
"&&",
"newDoc",
".",
"ProviderID",
"!=",
"\"",
"\"",
"{",
"// Only allow changing the ProviderID if it was empty.",
"changes",
"[",
"\"",
"\"",
"]",
"=",
"newDoc",
".",
"ProviderID",
"\n",
"}",
"\n",
"if",
"existingDoc",
".",
"Type",
"!=",
"newDoc",
".",
"Type",
"{",
"changes",
"[",
"\"",
"\"",
"]",
"=",
"newDoc",
".",
"Type",
"\n",
"}",
"\n",
"if",
"existingDoc",
".",
"MTU",
"!=",
"newDoc",
".",
"MTU",
"{",
"changes",
"[",
"\"",
"\"",
"]",
"=",
"newDoc",
".",
"MTU",
"\n",
"}",
"\n",
"if",
"existingDoc",
".",
"MACAddress",
"!=",
"newDoc",
".",
"MACAddress",
"{",
"changes",
"[",
"\"",
"\"",
"]",
"=",
"newDoc",
".",
"MACAddress",
"\n",
"}",
"\n",
"if",
"existingDoc",
".",
"IsAutoStart",
"!=",
"newDoc",
".",
"IsAutoStart",
"{",
"changes",
"[",
"\"",
"\"",
"]",
"=",
"newDoc",
".",
"IsAutoStart",
"\n",
"}",
"\n",
"if",
"existingDoc",
".",
"IsUp",
"!=",
"newDoc",
".",
"IsUp",
"{",
"changes",
"[",
"\"",
"\"",
"]",
"=",
"newDoc",
".",
"IsUp",
"\n",
"}",
"\n",
"if",
"existingDoc",
".",
"ParentName",
"!=",
"newDoc",
".",
"ParentName",
"{",
"changes",
"[",
"\"",
"\"",
"]",
"=",
"newDoc",
".",
"ParentName",
"\n",
"}",
"\n\n",
"var",
"updates",
"bson",
".",
"D",
"\n",
"if",
"len",
"(",
"changes",
")",
">",
"0",
"{",
"updates",
"=",
"append",
"(",
"updates",
",",
"bson",
".",
"DocElem",
"{",
"Name",
":",
"\"",
"\"",
",",
"Value",
":",
"changes",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"linkLayerDevicesC",
",",
"Id",
":",
"existingDoc",
".",
"DocID",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"updates",
",",
"}",
",",
"len",
"(",
"updates",
")",
">",
"0",
"\n",
"}"
] | // updateLinkLayerDeviceDocOp returns an operation updating the fields of
// existingDoc with the respective values of those fields in newDoc. DocID,
// ModelUUID, MachineID, and Name cannot be changed. ProviderID cannot be
// changed once set. In all other cases newDoc values overwrites existingDoc
// values. | [
"updateLinkLayerDeviceDocOp",
"returns",
"an",
"operation",
"updating",
"the",
"fields",
"of",
"existingDoc",
"with",
"the",
"respective",
"values",
"of",
"those",
"fields",
"in",
"newDoc",
".",
"DocID",
"ModelUUID",
"MachineID",
"and",
"Name",
"cannot",
"be",
"changed",
".",
"ProviderID",
"cannot",
"be",
"changed",
"once",
"set",
".",
"In",
"all",
"other",
"cases",
"newDoc",
"values",
"overwrites",
"existingDoc",
"values",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L360-L396 |
156,144 | juju/juju | state/linklayerdevices.go | assertLinkLayerDeviceExistsOp | func assertLinkLayerDeviceExistsOp(linkLayerDeviceDocID string) txn.Op {
return txn.Op{
C: linkLayerDevicesC,
Id: linkLayerDeviceDocID,
Assert: txn.DocExists,
}
} | go | func assertLinkLayerDeviceExistsOp(linkLayerDeviceDocID string) txn.Op {
return txn.Op{
C: linkLayerDevicesC,
Id: linkLayerDeviceDocID,
Assert: txn.DocExists,
}
} | [
"func",
"assertLinkLayerDeviceExistsOp",
"(",
"linkLayerDeviceDocID",
"string",
")",
"txn",
".",
"Op",
"{",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"linkLayerDevicesC",
",",
"Id",
":",
"linkLayerDeviceDocID",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"}",
"\n",
"}"
] | // assertLinkLayerDeviceExistsOp returns an operation asserting the document
// matching linkLayerDeviceDocID exists. | [
"assertLinkLayerDeviceExistsOp",
"returns",
"an",
"operation",
"asserting",
"the",
"document",
"matching",
"linkLayerDeviceDocID",
"exists",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L400-L406 |
156,145 | juju/juju | state/linklayerdevices.go | String | func (dev *LinkLayerDevice) String() string {
return fmt.Sprintf("%s device %q on machine %q", dev.doc.Type, dev.doc.Name, dev.doc.MachineID)
} | go | func (dev *LinkLayerDevice) String() string {
return fmt.Sprintf("%s device %q on machine %q", dev.doc.Type, dev.doc.Name, dev.doc.MachineID)
} | [
"func",
"(",
"dev",
"*",
"LinkLayerDevice",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"dev",
".",
"doc",
".",
"Type",
",",
"dev",
".",
"doc",
".",
"Name",
",",
"dev",
".",
"doc",
".",
"MachineID",
")",
"\n",
"}"
] | // String returns a human-readable representation of the device. | [
"String",
"returns",
"a",
"human",
"-",
"readable",
"representation",
"of",
"the",
"device",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L409-L411 |
156,146 | juju/juju | state/linklayerdevices.go | IsValidLinkLayerDeviceName | func IsValidLinkLayerDeviceName(name string) bool {
if runtimeGOOS == "linux" {
return isValidLinuxDeviceName(name)
}
hasHash := strings.Contains(name, "#")
return !hasHash && stringLengthBetween(name, 1, 255)
} | go | func IsValidLinkLayerDeviceName(name string) bool {
if runtimeGOOS == "linux" {
return isValidLinuxDeviceName(name)
}
hasHash := strings.Contains(name, "#")
return !hasHash && stringLengthBetween(name, 1, 255)
} | [
"func",
"IsValidLinkLayerDeviceName",
"(",
"name",
"string",
")",
"bool",
"{",
"if",
"runtimeGOOS",
"==",
"\"",
"\"",
"{",
"return",
"isValidLinuxDeviceName",
"(",
"name",
")",
"\n",
"}",
"\n",
"hasHash",
":=",
"strings",
".",
"Contains",
"(",
"name",
",",
"\"",
"\"",
")",
"\n",
"return",
"!",
"hasHash",
"&&",
"stringLengthBetween",
"(",
"name",
",",
"1",
",",
"255",
")",
"\n",
"}"
] | // IsValidLinkLayerDeviceName returns whether the given name is a valid network
// link-layer device name, depending on the runtime.GOOS value. | [
"IsValidLinkLayerDeviceName",
"returns",
"whether",
"the",
"given",
"name",
"is",
"a",
"valid",
"network",
"link",
"-",
"layer",
"device",
"name",
"depending",
"on",
"the",
"runtime",
".",
"GOOS",
"value",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L440-L446 |
156,147 | juju/juju | state/linklayerdevices.go | Addresses | func (dev *LinkLayerDevice) Addresses() ([]*Address, error) {
var allAddresses []*Address
callbackFunc := func(resultDoc *ipAddressDoc) {
allAddresses = append(allAddresses, newIPAddress(dev.st, *resultDoc))
}
findQuery := findAddressesQuery(dev.doc.MachineID, dev.doc.Name)
if err := dev.st.forEachIPAddressDoc(findQuery, callbackFunc); err != nil {
return nil, errors.Trace(err)
}
return allAddresses, nil
} | go | func (dev *LinkLayerDevice) Addresses() ([]*Address, error) {
var allAddresses []*Address
callbackFunc := func(resultDoc *ipAddressDoc) {
allAddresses = append(allAddresses, newIPAddress(dev.st, *resultDoc))
}
findQuery := findAddressesQuery(dev.doc.MachineID, dev.doc.Name)
if err := dev.st.forEachIPAddressDoc(findQuery, callbackFunc); err != nil {
return nil, errors.Trace(err)
}
return allAddresses, nil
} | [
"func",
"(",
"dev",
"*",
"LinkLayerDevice",
")",
"Addresses",
"(",
")",
"(",
"[",
"]",
"*",
"Address",
",",
"error",
")",
"{",
"var",
"allAddresses",
"[",
"]",
"*",
"Address",
"\n",
"callbackFunc",
":=",
"func",
"(",
"resultDoc",
"*",
"ipAddressDoc",
")",
"{",
"allAddresses",
"=",
"append",
"(",
"allAddresses",
",",
"newIPAddress",
"(",
"dev",
".",
"st",
",",
"*",
"resultDoc",
")",
")",
"\n",
"}",
"\n\n",
"findQuery",
":=",
"findAddressesQuery",
"(",
"dev",
".",
"doc",
".",
"MachineID",
",",
"dev",
".",
"doc",
".",
"Name",
")",
"\n",
"if",
"err",
":=",
"dev",
".",
"st",
".",
"forEachIPAddressDoc",
"(",
"findQuery",
",",
"callbackFunc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"allAddresses",
",",
"nil",
"\n",
"}"
] | // Addresses returns all IP addresses assigned to the device. | [
"Addresses",
"returns",
"all",
"IP",
"addresses",
"assigned",
"to",
"the",
"device",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L481-L492 |
156,148 | juju/juju | state/linklayerdevices.go | RemoveAddresses | func (dev *LinkLayerDevice) RemoveAddresses() error {
findQuery := findAddressesQuery(dev.doc.MachineID, dev.doc.Name)
ops, err := dev.st.removeMatchingIPAddressesDocOps(findQuery)
if err != nil {
return errors.Trace(err)
}
return dev.st.db().RunTransaction(ops)
} | go | func (dev *LinkLayerDevice) RemoveAddresses() error {
findQuery := findAddressesQuery(dev.doc.MachineID, dev.doc.Name)
ops, err := dev.st.removeMatchingIPAddressesDocOps(findQuery)
if err != nil {
return errors.Trace(err)
}
return dev.st.db().RunTransaction(ops)
} | [
"func",
"(",
"dev",
"*",
"LinkLayerDevice",
")",
"RemoveAddresses",
"(",
")",
"error",
"{",
"findQuery",
":=",
"findAddressesQuery",
"(",
"dev",
".",
"doc",
".",
"MachineID",
",",
"dev",
".",
"doc",
".",
"Name",
")",
"\n",
"ops",
",",
"err",
":=",
"dev",
".",
"st",
".",
"removeMatchingIPAddressesDocOps",
"(",
"findQuery",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"dev",
".",
"st",
".",
"db",
"(",
")",
".",
"RunTransaction",
"(",
"ops",
")",
"\n",
"}"
] | // RemoveAddresses removes all IP addresses assigned to the device. | [
"RemoveAddresses",
"removes",
"all",
"IP",
"addresses",
"assigned",
"to",
"the",
"device",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L495-L503 |
156,149 | juju/juju | state/linklayerdevices.go | EthernetDeviceForBridge | func (dev *LinkLayerDevice) EthernetDeviceForBridge(name string) (LinkLayerDeviceArgs, error) {
if dev.Type() != BridgeDevice {
return LinkLayerDeviceArgs{}, errors.Errorf("device must be a Bridge Device, receiver has type %q", dev.Type())
}
return LinkLayerDeviceArgs{
Name: name,
Type: EthernetDevice,
MACAddress: network.GenerateVirtualMACAddress(),
MTU: dev.MTU(),
IsUp: true,
IsAutoStart: true,
ParentName: dev.globalKey(),
}, nil
} | go | func (dev *LinkLayerDevice) EthernetDeviceForBridge(name string) (LinkLayerDeviceArgs, error) {
if dev.Type() != BridgeDevice {
return LinkLayerDeviceArgs{}, errors.Errorf("device must be a Bridge Device, receiver has type %q", dev.Type())
}
return LinkLayerDeviceArgs{
Name: name,
Type: EthernetDevice,
MACAddress: network.GenerateVirtualMACAddress(),
MTU: dev.MTU(),
IsUp: true,
IsAutoStart: true,
ParentName: dev.globalKey(),
}, nil
} | [
"func",
"(",
"dev",
"*",
"LinkLayerDevice",
")",
"EthernetDeviceForBridge",
"(",
"name",
"string",
")",
"(",
"LinkLayerDeviceArgs",
",",
"error",
")",
"{",
"if",
"dev",
".",
"Type",
"(",
")",
"!=",
"BridgeDevice",
"{",
"return",
"LinkLayerDeviceArgs",
"{",
"}",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"dev",
".",
"Type",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"LinkLayerDeviceArgs",
"{",
"Name",
":",
"name",
",",
"Type",
":",
"EthernetDevice",
",",
"MACAddress",
":",
"network",
".",
"GenerateVirtualMACAddress",
"(",
")",
",",
"MTU",
":",
"dev",
".",
"MTU",
"(",
")",
",",
"IsUp",
":",
"true",
",",
"IsAutoStart",
":",
"true",
",",
"ParentName",
":",
"dev",
".",
"globalKey",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // EthernetDeviceForBridge returns LinkLayerDeviceArgs representing an ethernet
// device with the input name and this device as its parent.
// If the device is not a bridge, an error is returned. | [
"EthernetDeviceForBridge",
"returns",
"LinkLayerDeviceArgs",
"representing",
"an",
"ethernet",
"device",
"with",
"the",
"input",
"name",
"and",
"this",
"device",
"as",
"its",
"parent",
".",
"If",
"the",
"device",
"is",
"not",
"a",
"bridge",
"an",
"error",
"is",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices.go#L508-L521 |
156,150 | juju/juju | cmd/juju/user/remove.go | SetFlags | func (c *removeCommand) SetFlags(f *gnuflag.FlagSet) {
c.ControllerCommandBase.SetFlags(f)
f.BoolVar(&c.ConfirmDelete, "y", false, "Confirm deletion of the user")
f.BoolVar(&c.ConfirmDelete, "yes", false, "")
} | go | func (c *removeCommand) SetFlags(f *gnuflag.FlagSet) {
c.ControllerCommandBase.SetFlags(f)
f.BoolVar(&c.ConfirmDelete, "y", false, "Confirm deletion of the user")
f.BoolVar(&c.ConfirmDelete, "yes", false, "")
} | [
"func",
"(",
"c",
"*",
"removeCommand",
")",
"SetFlags",
"(",
"f",
"*",
"gnuflag",
".",
"FlagSet",
")",
"{",
"c",
".",
"ControllerCommandBase",
".",
"SetFlags",
"(",
"f",
")",
"\n",
"f",
".",
"BoolVar",
"(",
"&",
"c",
".",
"ConfirmDelete",
",",
"\"",
"\"",
",",
"false",
",",
"\"",
"\"",
")",
"\n",
"f",
".",
"BoolVar",
"(",
"&",
"c",
".",
"ConfirmDelete",
",",
"\"",
"\"",
",",
"false",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // SetFlags adds command specific flags and then returns the flagset. | [
"SetFlags",
"adds",
"command",
"specific",
"flags",
"and",
"then",
"returns",
"the",
"flagset",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/user/remove.go#L75-L79 |
156,151 | juju/juju | api/proxyupdater/proxyupdater.go | NewAPI | func NewAPI(caller base.APICaller, tag names.Tag) (*API, error) {
if caller == nil {
return nil, fmt.Errorf("caller is nil")
}
if tag == nil {
return nil, fmt.Errorf("tag is nil")
}
return &API{
facade: base.NewFacadeCaller(caller, proxyUpdaterFacade),
tag: tag,
}, nil
} | go | func NewAPI(caller base.APICaller, tag names.Tag) (*API, error) {
if caller == nil {
return nil, fmt.Errorf("caller is nil")
}
if tag == nil {
return nil, fmt.Errorf("tag is nil")
}
return &API{
facade: base.NewFacadeCaller(caller, proxyUpdaterFacade),
tag: tag,
}, nil
} | [
"func",
"NewAPI",
"(",
"caller",
"base",
".",
"APICaller",
",",
"tag",
"names",
".",
"Tag",
")",
"(",
"*",
"API",
",",
"error",
")",
"{",
"if",
"caller",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"tag",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"API",
"{",
"facade",
":",
"base",
".",
"NewFacadeCaller",
"(",
"caller",
",",
"proxyUpdaterFacade",
")",
",",
"tag",
":",
"tag",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewAPI returns a new api client facade instance. | [
"NewAPI",
"returns",
"a",
"new",
"api",
"client",
"facade",
"instance",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/proxyupdater/proxyupdater.go#L28-L41 |
156,152 | juju/juju | api/proxyupdater/proxyupdater.go | WatchForProxyConfigAndAPIHostPortChanges | func (api *API) WatchForProxyConfigAndAPIHostPortChanges() (watcher.NotifyWatcher, error) {
var results params.NotifyWatchResults
args := params.Entities{
Entities: []params.Entity{{Tag: api.tag.String()}},
}
err := api.facade.FacadeCall("WatchForProxyConfigAndAPIHostPortChanges", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
return newNotifyWatcher(api.facade.RawAPICaller(), result), nil
} | go | func (api *API) WatchForProxyConfigAndAPIHostPortChanges() (watcher.NotifyWatcher, error) {
var results params.NotifyWatchResults
args := params.Entities{
Entities: []params.Entity{{Tag: api.tag.String()}},
}
err := api.facade.FacadeCall("WatchForProxyConfigAndAPIHostPortChanges", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
return newNotifyWatcher(api.facade.RawAPICaller(), result), nil
} | [
"func",
"(",
"api",
"*",
"API",
")",
"WatchForProxyConfigAndAPIHostPortChanges",
"(",
")",
"(",
"watcher",
".",
"NotifyWatcher",
",",
"error",
")",
"{",
"var",
"results",
"params",
".",
"NotifyWatchResults",
"\n",
"args",
":=",
"params",
".",
"Entities",
"{",
"Entities",
":",
"[",
"]",
"params",
".",
"Entity",
"{",
"{",
"Tag",
":",
"api",
".",
"tag",
".",
"String",
"(",
")",
"}",
"}",
",",
"}",
"\n",
"err",
":=",
"api",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"results",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"results",
".",
"Results",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"results",
".",
"Results",
")",
")",
"\n",
"}",
"\n",
"result",
":=",
"results",
".",
"Results",
"[",
"0",
"]",
"\n",
"if",
"result",
".",
"Error",
"!=",
"nil",
"{",
"return",
"nil",
",",
"result",
".",
"Error",
"\n",
"}",
"\n\n",
"return",
"newNotifyWatcher",
"(",
"api",
".",
"facade",
".",
"RawAPICaller",
"(",
")",
",",
"result",
")",
",",
"nil",
"\n",
"}"
] | // WatchForProxyConfigAndAPIHostPortChanges returns a NotifyWatcher waiting for
// changes in the proxy configuration or API host ports | [
"WatchForProxyConfigAndAPIHostPortChanges",
"returns",
"a",
"NotifyWatcher",
"waiting",
"for",
"changes",
"in",
"the",
"proxy",
"configuration",
"or",
"API",
"host",
"ports"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/proxyupdater/proxyupdater.go#L45-L63 |
156,153 | juju/juju | apiserver/facades/controller/caasoperatorupgrader/upgrader.go | NewStateCAASOperatorUpgraderAPI | func NewStateCAASOperatorUpgraderAPI(ctx facade.Context) (*API, error) {
authorizer := ctx.Auth()
broker, err := stateenvirons.GetNewCAASBrokerFunc(caas.New)(ctx.State())
if err != nil {
return nil, errors.Annotate(err, "getting caas client")
}
return NewCAASOperatorUpgraderAPI(authorizer, broker)
} | go | func NewStateCAASOperatorUpgraderAPI(ctx facade.Context) (*API, error) {
authorizer := ctx.Auth()
broker, err := stateenvirons.GetNewCAASBrokerFunc(caas.New)(ctx.State())
if err != nil {
return nil, errors.Annotate(err, "getting caas client")
}
return NewCAASOperatorUpgraderAPI(authorizer, broker)
} | [
"func",
"NewStateCAASOperatorUpgraderAPI",
"(",
"ctx",
"facade",
".",
"Context",
")",
"(",
"*",
"API",
",",
"error",
")",
"{",
"authorizer",
":=",
"ctx",
".",
"Auth",
"(",
")",
"\n",
"broker",
",",
"err",
":=",
"stateenvirons",
".",
"GetNewCAASBrokerFunc",
"(",
"caas",
".",
"New",
")",
"(",
"ctx",
".",
"State",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"NewCAASOperatorUpgraderAPI",
"(",
"authorizer",
",",
"broker",
")",
"\n",
"}"
] | // NewStateCAASOperatorUpgraderAPI provides the signature required for facade registration. | [
"NewStateCAASOperatorUpgraderAPI",
"provides",
"the",
"signature",
"required",
"for",
"facade",
"registration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasoperatorupgrader/upgrader.go#L28-L35 |
156,154 | juju/juju | apiserver/facades/controller/caasoperatorupgrader/upgrader.go | NewCAASOperatorUpgraderAPI | func NewCAASOperatorUpgraderAPI(
authorizer facade.Authorizer,
broker caas.Upgrader,
) (*API, error) {
if !authorizer.AuthController() && !authorizer.AuthApplicationAgent() {
return nil, common.ErrPerm
}
return &API{
auth: authorizer,
broker: broker,
}, nil
} | go | func NewCAASOperatorUpgraderAPI(
authorizer facade.Authorizer,
broker caas.Upgrader,
) (*API, error) {
if !authorizer.AuthController() && !authorizer.AuthApplicationAgent() {
return nil, common.ErrPerm
}
return &API{
auth: authorizer,
broker: broker,
}, nil
} | [
"func",
"NewCAASOperatorUpgraderAPI",
"(",
"authorizer",
"facade",
".",
"Authorizer",
",",
"broker",
"caas",
".",
"Upgrader",
",",
")",
"(",
"*",
"API",
",",
"error",
")",
"{",
"if",
"!",
"authorizer",
".",
"AuthController",
"(",
")",
"&&",
"!",
"authorizer",
".",
"AuthApplicationAgent",
"(",
")",
"{",
"return",
"nil",
",",
"common",
".",
"ErrPerm",
"\n",
"}",
"\n",
"return",
"&",
"API",
"{",
"auth",
":",
"authorizer",
",",
"broker",
":",
"broker",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewCAASOperatorUpgraderAPI returns a new CAAS operator upgrader API facade. | [
"NewCAASOperatorUpgraderAPI",
"returns",
"a",
"new",
"CAAS",
"operator",
"upgrader",
"API",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasoperatorupgrader/upgrader.go#L38-L49 |
156,155 | juju/juju | apiserver/facades/controller/caasoperatorupgrader/upgrader.go | UpgradeOperator | func (api *API) UpgradeOperator(arg params.KubernetesUpgradeArg) (params.ErrorResult, error) {
serverErr := func(err error) params.ErrorResult {
return params.ErrorResult{common.ServerError(err)}
}
tag, err := names.ParseTag(arg.AgentTag)
if err != nil {
return serverErr(err), nil
}
if !api.auth.AuthOwner(tag) {
return serverErr(common.ErrPerm), nil
}
appName := tag.Id()
// Machines representing controllers really mean the controller operator.
if tag.Kind() == names.MachineTagKind {
appName = bootstrap.ControllerModelName
}
logger.Debugf("upgrading caas app %v", appName)
err = api.broker.Upgrade(appName, arg.Version)
if err != nil {
return serverErr(err), nil
}
return params.ErrorResult{}, nil
} | go | func (api *API) UpgradeOperator(arg params.KubernetesUpgradeArg) (params.ErrorResult, error) {
serverErr := func(err error) params.ErrorResult {
return params.ErrorResult{common.ServerError(err)}
}
tag, err := names.ParseTag(arg.AgentTag)
if err != nil {
return serverErr(err), nil
}
if !api.auth.AuthOwner(tag) {
return serverErr(common.ErrPerm), nil
}
appName := tag.Id()
// Machines representing controllers really mean the controller operator.
if tag.Kind() == names.MachineTagKind {
appName = bootstrap.ControllerModelName
}
logger.Debugf("upgrading caas app %v", appName)
err = api.broker.Upgrade(appName, arg.Version)
if err != nil {
return serverErr(err), nil
}
return params.ErrorResult{}, nil
} | [
"func",
"(",
"api",
"*",
"API",
")",
"UpgradeOperator",
"(",
"arg",
"params",
".",
"KubernetesUpgradeArg",
")",
"(",
"params",
".",
"ErrorResult",
",",
"error",
")",
"{",
"serverErr",
":=",
"func",
"(",
"err",
"error",
")",
"params",
".",
"ErrorResult",
"{",
"return",
"params",
".",
"ErrorResult",
"{",
"common",
".",
"ServerError",
"(",
"err",
")",
"}",
"\n",
"}",
"\n",
"tag",
",",
"err",
":=",
"names",
".",
"ParseTag",
"(",
"arg",
".",
"AgentTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"serverErr",
"(",
"err",
")",
",",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"api",
".",
"auth",
".",
"AuthOwner",
"(",
"tag",
")",
"{",
"return",
"serverErr",
"(",
"common",
".",
"ErrPerm",
")",
",",
"nil",
"\n",
"}",
"\n",
"appName",
":=",
"tag",
".",
"Id",
"(",
")",
"\n\n",
"// Machines representing controllers really mean the controller operator.",
"if",
"tag",
".",
"Kind",
"(",
")",
"==",
"names",
".",
"MachineTagKind",
"{",
"appName",
"=",
"bootstrap",
".",
"ControllerModelName",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"appName",
")",
"\n",
"err",
"=",
"api",
".",
"broker",
".",
"Upgrade",
"(",
"appName",
",",
"arg",
".",
"Version",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"serverErr",
"(",
"err",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"params",
".",
"ErrorResult",
"{",
"}",
",",
"nil",
"\n",
"}"
] | // UpgradeOperator upgrades the operator for the specified agents. | [
"UpgradeOperator",
"upgrades",
"the",
"operator",
"for",
"the",
"specified",
"agents",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasoperatorupgrader/upgrader.go#L52-L75 |
156,156 | juju/juju | cmd/juju/application/expose.go | Run | func (c *exposeCommand) Run(_ *cmd.Context) error {
client, err := c.getAPI()
if err != nil {
return err
}
defer client.Close()
return block.ProcessBlockedError(client.Expose(c.ApplicationName), block.BlockChange)
} | go | func (c *exposeCommand) Run(_ *cmd.Context) error {
client, err := c.getAPI()
if err != nil {
return err
}
defer client.Close()
return block.ProcessBlockedError(client.Expose(c.ApplicationName), block.BlockChange)
} | [
"func",
"(",
"c",
"*",
"exposeCommand",
")",
"Run",
"(",
"_",
"*",
"cmd",
".",
"Context",
")",
"error",
"{",
"client",
",",
"err",
":=",
"c",
".",
"getAPI",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"client",
".",
"Close",
"(",
")",
"\n",
"return",
"block",
".",
"ProcessBlockedError",
"(",
"client",
".",
"Expose",
"(",
"c",
".",
"ApplicationName",
")",
",",
"block",
".",
"BlockChange",
")",
"\n",
"}"
] | // Run changes the juju-managed firewall to expose any
// ports that were also explicitly marked by units as open. | [
"Run",
"changes",
"the",
"juju",
"-",
"managed",
"firewall",
"to",
"expose",
"any",
"ports",
"that",
"were",
"also",
"explicitly",
"marked",
"by",
"units",
"as",
"open",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/expose.go#L73-L80 |
156,157 | juju/juju | cmd/jujud/agent/engine/valueworker.go | NewValueWorker | func NewValueWorker(value interface{}) (worker.Worker, error) {
if value == nil {
return nil, errors.New("NewValueWorker expects a value")
}
w := &valueWorker{
value: value,
}
w.tomb.Go(func() error {
<-w.tomb.Dying()
return nil
})
return w, nil
} | go | func NewValueWorker(value interface{}) (worker.Worker, error) {
if value == nil {
return nil, errors.New("NewValueWorker expects a value")
}
w := &valueWorker{
value: value,
}
w.tomb.Go(func() error {
<-w.tomb.Dying()
return nil
})
return w, nil
} | [
"func",
"NewValueWorker",
"(",
"value",
"interface",
"{",
"}",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"if",
"value",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"w",
":=",
"&",
"valueWorker",
"{",
"value",
":",
"value",
",",
"}",
"\n",
"w",
".",
"tomb",
".",
"Go",
"(",
"func",
"(",
")",
"error",
"{",
"<-",
"w",
".",
"tomb",
".",
"Dying",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"w",
",",
"nil",
"\n",
"}"
] | // NewValueWorker returns a degenerate worker that exposes the supplied value
// when passed into ValueWorkerOutput. Please do not supply values that have
// their own dependency or lifecycle considerations; such values will subvert
// the operation of any containing dependency.Engine by insulating it from the
// failures and dependency changes of the contained value. | [
"NewValueWorker",
"returns",
"a",
"degenerate",
"worker",
"that",
"exposes",
"the",
"supplied",
"value",
"when",
"passed",
"into",
"ValueWorkerOutput",
".",
"Please",
"do",
"not",
"supply",
"values",
"that",
"have",
"their",
"own",
"dependency",
"or",
"lifecycle",
"considerations",
";",
"such",
"values",
"will",
"subvert",
"the",
"operation",
"of",
"any",
"containing",
"dependency",
".",
"Engine",
"by",
"insulating",
"it",
"from",
"the",
"failures",
"and",
"dependency",
"changes",
"of",
"the",
"contained",
"value",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/engine/valueworker.go#L19-L31 |
156,158 | juju/juju | cmd/jujud/agent/engine/valueworker.go | ValueWorkerOutput | func ValueWorkerOutput(in worker.Worker, out interface{}) error {
inWorker, _ := in.(*valueWorker)
if inWorker == nil {
return errors.Errorf("in should be a *valueWorker; is %#v", in)
}
outV := reflect.ValueOf(out)
if outV.Kind() != reflect.Ptr {
return errors.Errorf("out should be a pointer; is %#v", out)
}
outValV := outV.Elem()
outValT := outValV.Type()
inValV := reflect.ValueOf(inWorker.value)
inValT := inValV.Type()
if !inValT.ConvertibleTo(outValT) {
return errors.Errorf("cannot output into %T", out)
}
outValV.Set(inValV.Convert(outValT))
return nil
} | go | func ValueWorkerOutput(in worker.Worker, out interface{}) error {
inWorker, _ := in.(*valueWorker)
if inWorker == nil {
return errors.Errorf("in should be a *valueWorker; is %#v", in)
}
outV := reflect.ValueOf(out)
if outV.Kind() != reflect.Ptr {
return errors.Errorf("out should be a pointer; is %#v", out)
}
outValV := outV.Elem()
outValT := outValV.Type()
inValV := reflect.ValueOf(inWorker.value)
inValT := inValV.Type()
if !inValT.ConvertibleTo(outValT) {
return errors.Errorf("cannot output into %T", out)
}
outValV.Set(inValV.Convert(outValT))
return nil
} | [
"func",
"ValueWorkerOutput",
"(",
"in",
"worker",
".",
"Worker",
",",
"out",
"interface",
"{",
"}",
")",
"error",
"{",
"inWorker",
",",
"_",
":=",
"in",
".",
"(",
"*",
"valueWorker",
")",
"\n",
"if",
"inWorker",
"==",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"in",
")",
"\n",
"}",
"\n",
"outV",
":=",
"reflect",
".",
"ValueOf",
"(",
"out",
")",
"\n",
"if",
"outV",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"out",
")",
"\n",
"}",
"\n",
"outValV",
":=",
"outV",
".",
"Elem",
"(",
")",
"\n",
"outValT",
":=",
"outValV",
".",
"Type",
"(",
")",
"\n",
"inValV",
":=",
"reflect",
".",
"ValueOf",
"(",
"inWorker",
".",
"value",
")",
"\n",
"inValT",
":=",
"inValV",
".",
"Type",
"(",
")",
"\n",
"if",
"!",
"inValT",
".",
"ConvertibleTo",
"(",
"outValT",
")",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"out",
")",
"\n",
"}",
"\n",
"outValV",
".",
"Set",
"(",
"inValV",
".",
"Convert",
"(",
"outValT",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // ValueWorkerOutput sets the value wrapped by the supplied valueWorker into
// the out pointer, if type-compatible, or fails. | [
"ValueWorkerOutput",
"sets",
"the",
"value",
"wrapped",
"by",
"the",
"supplied",
"valueWorker",
"into",
"the",
"out",
"pointer",
"if",
"type",
"-",
"compatible",
"or",
"fails",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/engine/valueworker.go#L35-L53 |
156,159 | juju/juju | cloudconfig/cloudinit/cloudinit_win.go | RenderScript | func (cfg *windowsCloudConfig) RenderScript() (string, error) {
// NOTE: This shouldn't really be called on windows as it's used only for
// initialization via ssh.
script, err := cfg.renderWindows()
if err != nil {
return "", err
}
return string(script), err
} | go | func (cfg *windowsCloudConfig) RenderScript() (string, error) {
// NOTE: This shouldn't really be called on windows as it's used only for
// initialization via ssh.
script, err := cfg.renderWindows()
if err != nil {
return "", err
}
return string(script), err
} | [
"func",
"(",
"cfg",
"*",
"windowsCloudConfig",
")",
"RenderScript",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"// NOTE: This shouldn't really be called on windows as it's used only for",
"// initialization via ssh.",
"script",
",",
"err",
":=",
"cfg",
".",
"renderWindows",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"string",
"(",
"script",
")",
",",
"err",
"\n",
"}"
] | // RenderScript is defined on the RenderConfig interface. | [
"RenderScript",
"is",
"defined",
"on",
"the",
"RenderConfig",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/cloudinit/cloudinit_win.go#L72-L81 |
156,160 | juju/juju | cloudconfig/cloudinit/cloudinit_win.go | renderWindows | func (cfg *windowsCloudConfig) renderWindows() ([]byte, error) {
winCmds := cfg.RunCmds()
var script []byte
newline := "\r\n"
header := "#ps1_sysnative\r\n"
script = append(script, header...)
for _, cmd := range winCmds {
script = append(script, newline...)
script = append(script, cmd...)
}
return script, nil
} | go | func (cfg *windowsCloudConfig) renderWindows() ([]byte, error) {
winCmds := cfg.RunCmds()
var script []byte
newline := "\r\n"
header := "#ps1_sysnative\r\n"
script = append(script, header...)
for _, cmd := range winCmds {
script = append(script, newline...)
script = append(script, cmd...)
}
return script, nil
} | [
"func",
"(",
"cfg",
"*",
"windowsCloudConfig",
")",
"renderWindows",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"winCmds",
":=",
"cfg",
".",
"RunCmds",
"(",
")",
"\n",
"var",
"script",
"[",
"]",
"byte",
"\n",
"newline",
":=",
"\"",
"\\r",
"\\n",
"\"",
"\n",
"header",
":=",
"\"",
"\\r",
"\\n",
"\"",
"\n",
"script",
"=",
"append",
"(",
"script",
",",
"header",
"...",
")",
"\n",
"for",
"_",
",",
"cmd",
":=",
"range",
"winCmds",
"{",
"script",
"=",
"append",
"(",
"script",
",",
"newline",
"...",
")",
"\n",
"script",
"=",
"append",
"(",
"script",
",",
"cmd",
"...",
")",
"\n",
"}",
"\n",
"return",
"script",
",",
"nil",
"\n",
"}"
] | // renderWindows is a helper function which renders the runCmds of the Windows
// CloudConfig to a PowerShell script. | [
"renderWindows",
"is",
"a",
"helper",
"function",
"which",
"renders",
"the",
"runCmds",
"of",
"the",
"Windows",
"CloudConfig",
"to",
"a",
"PowerShell",
"script",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/cloudinit/cloudinit_win.go#L90-L101 |
156,161 | juju/juju | apiserver/facades/agent/retrystrategy/retrystrategy.go | NewRetryStrategyAPI | func NewRetryStrategyAPI(
st *state.State,
resources facade.Resources,
authorizer facade.Authorizer,
) (*RetryStrategyAPI, error) {
if !authorizer.AuthUnitAgent() && !authorizer.AuthApplicationAgent() {
return nil, common.ErrPerm
}
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
return &RetryStrategyAPI{
st: st,
model: model,
canAccess: func() (common.AuthFunc, error) {
return authorizer.AuthOwner, nil
},
resources: resources,
}, nil
} | go | func NewRetryStrategyAPI(
st *state.State,
resources facade.Resources,
authorizer facade.Authorizer,
) (*RetryStrategyAPI, error) {
if !authorizer.AuthUnitAgent() && !authorizer.AuthApplicationAgent() {
return nil, common.ErrPerm
}
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
return &RetryStrategyAPI{
st: st,
model: model,
canAccess: func() (common.AuthFunc, error) {
return authorizer.AuthOwner, nil
},
resources: resources,
}, nil
} | [
"func",
"NewRetryStrategyAPI",
"(",
"st",
"*",
"state",
".",
"State",
",",
"resources",
"facade",
".",
"Resources",
",",
"authorizer",
"facade",
".",
"Authorizer",
",",
")",
"(",
"*",
"RetryStrategyAPI",
",",
"error",
")",
"{",
"if",
"!",
"authorizer",
".",
"AuthUnitAgent",
"(",
")",
"&&",
"!",
"authorizer",
".",
"AuthApplicationAgent",
"(",
")",
"{",
"return",
"nil",
",",
"common",
".",
"ErrPerm",
"\n",
"}",
"\n\n",
"model",
",",
"err",
":=",
"st",
".",
"Model",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"RetryStrategyAPI",
"{",
"st",
":",
"st",
",",
"model",
":",
"model",
",",
"canAccess",
":",
"func",
"(",
")",
"(",
"common",
".",
"AuthFunc",
",",
"error",
")",
"{",
"return",
"authorizer",
".",
"AuthOwner",
",",
"nil",
"\n",
"}",
",",
"resources",
":",
"resources",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewRetryStrategyAPI creates a new API endpoint for getting retry strategies. | [
"NewRetryStrategyAPI",
"creates",
"a",
"new",
"API",
"endpoint",
"for",
"getting",
"retry",
"strategies",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/retrystrategy/retrystrategy.go#L46-L68 |
156,162 | juju/juju | apiserver/facades/agent/retrystrategy/retrystrategy.go | RetryStrategy | func (h *RetryStrategyAPI) RetryStrategy(args params.Entities) (params.RetryStrategyResults, error) {
results := params.RetryStrategyResults{
Results: make([]params.RetryStrategyResult, len(args.Entities)),
}
canAccess, err := h.canAccess()
if err != nil {
return params.RetryStrategyResults{}, errors.Trace(err)
}
config, err := h.model.ModelConfig()
if err != nil {
return params.RetryStrategyResults{}, errors.Trace(err)
}
for i, entity := range args.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
err = common.ErrPerm
if canAccess(tag) {
// Right now the only real configurable value is ShouldRetry,
// which is taken from the model.
// The rest are hardcoded.
results.Results[i].Result = ¶ms.RetryStrategy{
ShouldRetry: config.AutomaticallyRetryHooks(),
MinRetryTime: MinRetryTime,
MaxRetryTime: MaxRetryTime,
JitterRetryTime: JitterRetryTime,
RetryTimeFactor: RetryTimeFactor,
}
err = nil
}
results.Results[i].Error = common.ServerError(err)
}
return results, nil
} | go | func (h *RetryStrategyAPI) RetryStrategy(args params.Entities) (params.RetryStrategyResults, error) {
results := params.RetryStrategyResults{
Results: make([]params.RetryStrategyResult, len(args.Entities)),
}
canAccess, err := h.canAccess()
if err != nil {
return params.RetryStrategyResults{}, errors.Trace(err)
}
config, err := h.model.ModelConfig()
if err != nil {
return params.RetryStrategyResults{}, errors.Trace(err)
}
for i, entity := range args.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
err = common.ErrPerm
if canAccess(tag) {
// Right now the only real configurable value is ShouldRetry,
// which is taken from the model.
// The rest are hardcoded.
results.Results[i].Result = ¶ms.RetryStrategy{
ShouldRetry: config.AutomaticallyRetryHooks(),
MinRetryTime: MinRetryTime,
MaxRetryTime: MaxRetryTime,
JitterRetryTime: JitterRetryTime,
RetryTimeFactor: RetryTimeFactor,
}
err = nil
}
results.Results[i].Error = common.ServerError(err)
}
return results, nil
} | [
"func",
"(",
"h",
"*",
"RetryStrategyAPI",
")",
"RetryStrategy",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"RetryStrategyResults",
",",
"error",
")",
"{",
"results",
":=",
"params",
".",
"RetryStrategyResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"RetryStrategyResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"canAccess",
",",
"err",
":=",
"h",
".",
"canAccess",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"RetryStrategyResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"config",
",",
"err",
":=",
"h",
".",
"model",
".",
"ModelConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"RetryStrategyResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"entity",
":=",
"range",
"args",
".",
"Entities",
"{",
"tag",
",",
"err",
":=",
"names",
".",
"ParseTag",
"(",
"entity",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"err",
"=",
"common",
".",
"ErrPerm",
"\n",
"if",
"canAccess",
"(",
"tag",
")",
"{",
"// Right now the only real configurable value is ShouldRetry,",
"// which is taken from the model.",
"// The rest are hardcoded.",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Result",
"=",
"&",
"params",
".",
"RetryStrategy",
"{",
"ShouldRetry",
":",
"config",
".",
"AutomaticallyRetryHooks",
"(",
")",
",",
"MinRetryTime",
":",
"MinRetryTime",
",",
"MaxRetryTime",
":",
"MaxRetryTime",
",",
"JitterRetryTime",
":",
"JitterRetryTime",
",",
"RetryTimeFactor",
":",
"RetryTimeFactor",
",",
"}",
"\n",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // RetryStrategy returns RetryStrategyResults that can be used by any code that uses
// to configure the retry timer that's currently in juju utils. | [
"RetryStrategy",
"returns",
"RetryStrategyResults",
"that",
"can",
"be",
"used",
"by",
"any",
"code",
"that",
"uses",
"to",
"configure",
"the",
"retry",
"timer",
"that",
"s",
"currently",
"in",
"juju",
"utils",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/retrystrategy/retrystrategy.go#L72-L107 |
156,163 | juju/juju | apiserver/facades/agent/retrystrategy/retrystrategy.go | WatchRetryStrategy | func (h *RetryStrategyAPI) WatchRetryStrategy(args params.Entities) (params.NotifyWatchResults, error) {
results := params.NotifyWatchResults{
Results: make([]params.NotifyWatchResult, len(args.Entities)),
}
canAccess, err := h.canAccess()
if err != nil {
return params.NotifyWatchResults{}, errors.Trace(err)
}
for i, entity := range args.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
err = common.ErrPerm
if canAccess(tag) {
watch := h.model.WatchForModelConfigChanges()
// Consume the initial event. Technically, API calls to Watch
// 'transmit' the initial event in the Watch response. But
// NotifyWatchers have no state to transmit.
if _, ok := <-watch.Changes(); ok {
results.Results[i].NotifyWatcherId = h.resources.Register(watch)
err = nil
} else {
err = watcher.EnsureErr(watch)
}
}
results.Results[i].Error = common.ServerError(err)
}
return results, nil
} | go | func (h *RetryStrategyAPI) WatchRetryStrategy(args params.Entities) (params.NotifyWatchResults, error) {
results := params.NotifyWatchResults{
Results: make([]params.NotifyWatchResult, len(args.Entities)),
}
canAccess, err := h.canAccess()
if err != nil {
return params.NotifyWatchResults{}, errors.Trace(err)
}
for i, entity := range args.Entities {
tag, err := names.ParseTag(entity.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
err = common.ErrPerm
if canAccess(tag) {
watch := h.model.WatchForModelConfigChanges()
// Consume the initial event. Technically, API calls to Watch
// 'transmit' the initial event in the Watch response. But
// NotifyWatchers have no state to transmit.
if _, ok := <-watch.Changes(); ok {
results.Results[i].NotifyWatcherId = h.resources.Register(watch)
err = nil
} else {
err = watcher.EnsureErr(watch)
}
}
results.Results[i].Error = common.ServerError(err)
}
return results, nil
} | [
"func",
"(",
"h",
"*",
"RetryStrategyAPI",
")",
"WatchRetryStrategy",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"NotifyWatchResults",
",",
"error",
")",
"{",
"results",
":=",
"params",
".",
"NotifyWatchResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"NotifyWatchResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"canAccess",
",",
"err",
":=",
"h",
".",
"canAccess",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"NotifyWatchResults",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"entity",
":=",
"range",
"args",
".",
"Entities",
"{",
"tag",
",",
"err",
":=",
"names",
".",
"ParseTag",
"(",
"entity",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"err",
"=",
"common",
".",
"ErrPerm",
"\n",
"if",
"canAccess",
"(",
"tag",
")",
"{",
"watch",
":=",
"h",
".",
"model",
".",
"WatchForModelConfigChanges",
"(",
")",
"\n",
"// Consume the initial event. Technically, API calls to Watch",
"// 'transmit' the initial event in the Watch response. But",
"// NotifyWatchers have no state to transmit.",
"if",
"_",
",",
"ok",
":=",
"<-",
"watch",
".",
"Changes",
"(",
")",
";",
"ok",
"{",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"NotifyWatcherId",
"=",
"h",
".",
"resources",
".",
"Register",
"(",
"watch",
")",
"\n",
"err",
"=",
"nil",
"\n",
"}",
"else",
"{",
"err",
"=",
"watcher",
".",
"EnsureErr",
"(",
"watch",
")",
"\n",
"}",
"\n",
"}",
"\n",
"results",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // WatchRetryStrategy watches for changes to the model. Currently we only allow
// changes to the boolean that determines whether retries should be attempted or not. | [
"WatchRetryStrategy",
"watches",
"for",
"changes",
"to",
"the",
"model",
".",
"Currently",
"we",
"only",
"allow",
"changes",
"to",
"the",
"boolean",
"that",
"determines",
"whether",
"retries",
"should",
"be",
"attempted",
"or",
"not",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/retrystrategy/retrystrategy.go#L111-L141 |
156,164 | juju/juju | cmd/juju/common/gui.go | GUIDataSourceBaseURL | func GUIDataSourceBaseURL() string {
url := os.Getenv(guiBaseURLEnvVar)
if url != "" {
return url
}
return gui.DefaultBaseURL
} | go | func GUIDataSourceBaseURL() string {
url := os.Getenv(guiBaseURLEnvVar)
if url != "" {
return url
}
return gui.DefaultBaseURL
} | [
"func",
"GUIDataSourceBaseURL",
"(",
")",
"string",
"{",
"url",
":=",
"os",
".",
"Getenv",
"(",
"guiBaseURLEnvVar",
")",
"\n",
"if",
"url",
"!=",
"\"",
"\"",
"{",
"return",
"url",
"\n",
"}",
"\n",
"return",
"gui",
".",
"DefaultBaseURL",
"\n",
"}"
] | // GUIDataSourceBaseURL returns the default base URL to use for the Juju GUI
// simplestreams data source. The default value can be overridden by setting
// the JUJU_GUI_SIMPLESTREAMS_URL environment variable. | [
"GUIDataSourceBaseURL",
"returns",
"the",
"default",
"base",
"URL",
"to",
"use",
"for",
"the",
"Juju",
"GUI",
"simplestreams",
"data",
"source",
".",
"The",
"default",
"value",
"can",
"be",
"overridden",
"by",
"setting",
"the",
"JUJU_GUI_SIMPLESTREAMS_URL",
"environment",
"variable",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/common/gui.go#L17-L23 |
156,165 | juju/juju | core/watcher/multinotify.go | NewMultiNotifyWatcher | func NewMultiNotifyWatcher(w ...NotifyWatcher) *MultiNotifyWatcher {
m := &MultiNotifyWatcher{
watchers: w,
changes: make(chan struct{}),
}
var wg sync.WaitGroup
wg.Add(len(w))
staging := make(chan struct{})
for _, w := range w {
// Consume the first event of each watcher.
<-w.Changes()
go func(wCopy NotifyWatcher) {
defer wg.Done()
wCopy.Wait()
}(w)
// Copy events from the watcher to the staging channel.
go copyEvents(staging, w.Changes(), &m.tomb)
}
m.tomb.Go(func() error {
m.loop(staging)
wg.Wait()
return nil
})
return m
} | go | func NewMultiNotifyWatcher(w ...NotifyWatcher) *MultiNotifyWatcher {
m := &MultiNotifyWatcher{
watchers: w,
changes: make(chan struct{}),
}
var wg sync.WaitGroup
wg.Add(len(w))
staging := make(chan struct{})
for _, w := range w {
// Consume the first event of each watcher.
<-w.Changes()
go func(wCopy NotifyWatcher) {
defer wg.Done()
wCopy.Wait()
}(w)
// Copy events from the watcher to the staging channel.
go copyEvents(staging, w.Changes(), &m.tomb)
}
m.tomb.Go(func() error {
m.loop(staging)
wg.Wait()
return nil
})
return m
} | [
"func",
"NewMultiNotifyWatcher",
"(",
"w",
"...",
"NotifyWatcher",
")",
"*",
"MultiNotifyWatcher",
"{",
"m",
":=",
"&",
"MultiNotifyWatcher",
"{",
"watchers",
":",
"w",
",",
"changes",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"wg",
".",
"Add",
"(",
"len",
"(",
"w",
")",
")",
"\n",
"staging",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"w",
":=",
"range",
"w",
"{",
"// Consume the first event of each watcher.",
"<-",
"w",
".",
"Changes",
"(",
")",
"\n",
"go",
"func",
"(",
"wCopy",
"NotifyWatcher",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"wCopy",
".",
"Wait",
"(",
")",
"\n",
"}",
"(",
"w",
")",
"\n",
"// Copy events from the watcher to the staging channel.",
"go",
"copyEvents",
"(",
"staging",
",",
"w",
".",
"Changes",
"(",
")",
",",
"&",
"m",
".",
"tomb",
")",
"\n",
"}",
"\n",
"m",
".",
"tomb",
".",
"Go",
"(",
"func",
"(",
")",
"error",
"{",
"m",
".",
"loop",
"(",
"staging",
")",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"m",
"\n",
"}"
] | // NewMultiNotifyWatcher creates a NotifyWatcher that combines
// each of the NotifyWatchers passed in. Each watcher's initial
// event is consumed, and a single initial event is sent.
// Subsequent events are not coalesced. | [
"NewMultiNotifyWatcher",
"creates",
"a",
"NotifyWatcher",
"that",
"combines",
"each",
"of",
"the",
"NotifyWatchers",
"passed",
"in",
".",
"Each",
"watcher",
"s",
"initial",
"event",
"is",
"consumed",
"and",
"a",
"single",
"initial",
"event",
"is",
"sent",
".",
"Subsequent",
"events",
"are",
"not",
"coalesced",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/watcher/multinotify.go#L25-L49 |
156,166 | juju/juju | core/watcher/multinotify.go | loop | func (w *MultiNotifyWatcher) loop(in <-chan struct{}) {
defer close(w.changes)
// out is initialised to m.changes to send the initial event.
out := w.changes
var timer <-chan time.Time
for {
select {
case <-w.tomb.Dying():
return
case <-in:
if timer == nil {
// TODO(fwereade): 2016-03-17 lp:1558657
timer = time.After(10 * time.Millisecond)
}
case <-timer:
timer = nil
out = w.changes
case out <- struct{}{}:
out = nil
}
}
} | go | func (w *MultiNotifyWatcher) loop(in <-chan struct{}) {
defer close(w.changes)
// out is initialised to m.changes to send the initial event.
out := w.changes
var timer <-chan time.Time
for {
select {
case <-w.tomb.Dying():
return
case <-in:
if timer == nil {
// TODO(fwereade): 2016-03-17 lp:1558657
timer = time.After(10 * time.Millisecond)
}
case <-timer:
timer = nil
out = w.changes
case out <- struct{}{}:
out = nil
}
}
} | [
"func",
"(",
"w",
"*",
"MultiNotifyWatcher",
")",
"loop",
"(",
"in",
"<-",
"chan",
"struct",
"{",
"}",
")",
"{",
"defer",
"close",
"(",
"w",
".",
"changes",
")",
"\n",
"// out is initialised to m.changes to send the initial event.",
"out",
":=",
"w",
".",
"changes",
"\n",
"var",
"timer",
"<-",
"chan",
"time",
".",
"Time",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"w",
".",
"tomb",
".",
"Dying",
"(",
")",
":",
"return",
"\n",
"case",
"<-",
"in",
":",
"if",
"timer",
"==",
"nil",
"{",
"// TODO(fwereade): 2016-03-17 lp:1558657",
"timer",
"=",
"time",
".",
"After",
"(",
"10",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"}",
"\n",
"case",
"<-",
"timer",
":",
"timer",
"=",
"nil",
"\n",
"out",
"=",
"w",
".",
"changes",
"\n",
"case",
"out",
"<-",
"struct",
"{",
"}",
"{",
"}",
":",
"out",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // loop copies events from the input channel to the output channel,
// coalescing events by waiting a short time between receiving and
// sending. | [
"loop",
"copies",
"events",
"from",
"the",
"input",
"channel",
"to",
"the",
"output",
"channel",
"coalescing",
"events",
"by",
"waiting",
"a",
"short",
"time",
"between",
"receiving",
"and",
"sending",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/watcher/multinotify.go#L54-L75 |
156,167 | juju/juju | core/watcher/multinotify.go | copyEvents | func copyEvents(out chan<- struct{}, in <-chan struct{}, tomb *tomb.Tomb) {
var outC chan<- struct{}
for {
select {
case <-tomb.Dying():
return
case _, ok := <-in:
if !ok {
return
}
outC = out
case outC <- struct{}{}:
outC = nil
}
}
} | go | func copyEvents(out chan<- struct{}, in <-chan struct{}, tomb *tomb.Tomb) {
var outC chan<- struct{}
for {
select {
case <-tomb.Dying():
return
case _, ok := <-in:
if !ok {
return
}
outC = out
case outC <- struct{}{}:
outC = nil
}
}
} | [
"func",
"copyEvents",
"(",
"out",
"chan",
"<-",
"struct",
"{",
"}",
",",
"in",
"<-",
"chan",
"struct",
"{",
"}",
",",
"tomb",
"*",
"tomb",
".",
"Tomb",
")",
"{",
"var",
"outC",
"chan",
"<-",
"struct",
"{",
"}",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"tomb",
".",
"Dying",
"(",
")",
":",
"return",
"\n",
"case",
"_",
",",
"ok",
":=",
"<-",
"in",
":",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"outC",
"=",
"out",
"\n",
"case",
"outC",
"<-",
"struct",
"{",
"}",
"{",
"}",
":",
"outC",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // copyEvents copies channel events from "in" to "out", coalescing. | [
"copyEvents",
"copies",
"channel",
"events",
"from",
"in",
"to",
"out",
"coalescing",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/watcher/multinotify.go#L78-L93 |
156,168 | juju/juju | provider/openstack/firewaller.go | GetFirewaller | func (f *firewallerFactory) GetFirewaller(env environs.Environ) Firewaller {
return &switchingFirewaller{env: env.(*Environ)}
} | go | func (f *firewallerFactory) GetFirewaller(env environs.Environ) Firewaller {
return &switchingFirewaller{env: env.(*Environ)}
} | [
"func",
"(",
"f",
"*",
"firewallerFactory",
")",
"GetFirewaller",
"(",
"env",
"environs",
".",
"Environ",
")",
"Firewaller",
"{",
"return",
"&",
"switchingFirewaller",
"{",
"env",
":",
"env",
".",
"(",
"*",
"Environ",
")",
"}",
"\n",
"}"
] | // GetFirewaller implements FirewallerFactory | [
"GetFirewaller",
"implements",
"FirewallerFactory"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/firewaller.go#L94-L96 |
156,169 | juju/juju | provider/openstack/firewaller.go | GetSecurityGroups | func (c *firewallerBase) GetSecurityGroups(ctx context.ProviderCallContext, ids ...instance.Id) ([]string, error) {
var securityGroupNames []string
if c.environ.Config().FirewallMode() == config.FwInstance {
instances, err := c.environ.Instances(ctx, ids)
if err != nil {
return nil, errors.Trace(err)
}
novaClient := c.environ.nova()
securityGroupNames = make([]string, 0, len(ids))
for _, inst := range instances {
if inst == nil {
continue
}
serverId, err := instServerId(inst)
if err != nil {
return nil, errors.Trace(err)
}
groups, err := novaClient.GetServerSecurityGroups(string(inst.Id()))
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
for _, group := range groups {
// We only include the group specifically tied to the instance, not
// any group global to the model itself.
suffix := fmt.Sprintf("%s-%s", c.environ.Config().UUID(), serverId)
if strings.HasSuffix(group.Name, suffix) {
securityGroupNames = append(securityGroupNames, group.Name)
}
}
}
}
return securityGroupNames, nil
} | go | func (c *firewallerBase) GetSecurityGroups(ctx context.ProviderCallContext, ids ...instance.Id) ([]string, error) {
var securityGroupNames []string
if c.environ.Config().FirewallMode() == config.FwInstance {
instances, err := c.environ.Instances(ctx, ids)
if err != nil {
return nil, errors.Trace(err)
}
novaClient := c.environ.nova()
securityGroupNames = make([]string, 0, len(ids))
for _, inst := range instances {
if inst == nil {
continue
}
serverId, err := instServerId(inst)
if err != nil {
return nil, errors.Trace(err)
}
groups, err := novaClient.GetServerSecurityGroups(string(inst.Id()))
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
for _, group := range groups {
// We only include the group specifically tied to the instance, not
// any group global to the model itself.
suffix := fmt.Sprintf("%s-%s", c.environ.Config().UUID(), serverId)
if strings.HasSuffix(group.Name, suffix) {
securityGroupNames = append(securityGroupNames, group.Name)
}
}
}
}
return securityGroupNames, nil
} | [
"func",
"(",
"c",
"*",
"firewallerBase",
")",
"GetSecurityGroups",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"ids",
"...",
"instance",
".",
"Id",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"securityGroupNames",
"[",
"]",
"string",
"\n",
"if",
"c",
".",
"environ",
".",
"Config",
"(",
")",
".",
"FirewallMode",
"(",
")",
"==",
"config",
".",
"FwInstance",
"{",
"instances",
",",
"err",
":=",
"c",
".",
"environ",
".",
"Instances",
"(",
"ctx",
",",
"ids",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"novaClient",
":=",
"c",
".",
"environ",
".",
"nova",
"(",
")",
"\n",
"securityGroupNames",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"ids",
")",
")",
"\n",
"for",
"_",
",",
"inst",
":=",
"range",
"instances",
"{",
"if",
"inst",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"serverId",
",",
"err",
":=",
"instServerId",
"(",
"inst",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"groups",
",",
"err",
":=",
"novaClient",
".",
"GetServerSecurityGroups",
"(",
"string",
"(",
"inst",
".",
"Id",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"group",
":=",
"range",
"groups",
"{",
"// We only include the group specifically tied to the instance, not",
"// any group global to the model itself.",
"suffix",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"environ",
".",
"Config",
"(",
")",
".",
"UUID",
"(",
")",
",",
"serverId",
")",
"\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"group",
".",
"Name",
",",
"suffix",
")",
"{",
"securityGroupNames",
"=",
"append",
"(",
"securityGroupNames",
",",
"group",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"securityGroupNames",
",",
"nil",
"\n",
"}"
] | // GetSecurityGroups implements Firewaller interface. | [
"GetSecurityGroups",
"implements",
"Firewaller",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/firewaller.go#L218-L251 |
156,170 | juju/juju | provider/openstack/firewaller.go | deleteSecurityGroup | func deleteSecurityGroup(
ctx context.ProviderCallContext,
deleteSecurityGroupById func(string) error,
name, id string,
clock clock.Clock,
) {
logger.Debugf("deleting security group %q", name)
err := retry.Call(retry.CallArgs{
Func: func() error {
if err := deleteSecurityGroupById(id); err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return errors.Trace(err)
}
return nil
},
NotifyFunc: func(err error, attempt int) {
if attempt%4 == 0 {
message := fmt.Sprintf("waiting to delete security group %q", name)
if attempt != 4 {
message = "still " + message
}
logger.Debugf(message)
}
},
Attempts: 30,
Delay: time.Second,
Clock: clock,
})
if err != nil {
logger.Warningf("cannot delete security group %q. Used by another model?", name)
}
} | go | func deleteSecurityGroup(
ctx context.ProviderCallContext,
deleteSecurityGroupById func(string) error,
name, id string,
clock clock.Clock,
) {
logger.Debugf("deleting security group %q", name)
err := retry.Call(retry.CallArgs{
Func: func() error {
if err := deleteSecurityGroupById(id); err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return errors.Trace(err)
}
return nil
},
NotifyFunc: func(err error, attempt int) {
if attempt%4 == 0 {
message := fmt.Sprintf("waiting to delete security group %q", name)
if attempt != 4 {
message = "still " + message
}
logger.Debugf(message)
}
},
Attempts: 30,
Delay: time.Second,
Clock: clock,
})
if err != nil {
logger.Warningf("cannot delete security group %q. Used by another model?", name)
}
} | [
"func",
"deleteSecurityGroup",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"deleteSecurityGroupById",
"func",
"(",
"string",
")",
"error",
",",
"name",
",",
"id",
"string",
",",
"clock",
"clock",
".",
"Clock",
",",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"err",
":=",
"retry",
".",
"Call",
"(",
"retry",
".",
"CallArgs",
"{",
"Func",
":",
"func",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"deleteSecurityGroupById",
"(",
"id",
")",
";",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
",",
"NotifyFunc",
":",
"func",
"(",
"err",
"error",
",",
"attempt",
"int",
")",
"{",
"if",
"attempt",
"%",
"4",
"==",
"0",
"{",
"message",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"if",
"attempt",
"!=",
"4",
"{",
"message",
"=",
"\"",
"\"",
"+",
"message",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"message",
")",
"\n",
"}",
"\n",
"}",
",",
"Attempts",
":",
"30",
",",
"Delay",
":",
"time",
".",
"Second",
",",
"Clock",
":",
"clock",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"}"
] | // deleteSecurityGroup attempts to delete the security group. Should it fail,
// the deletion is retried due to timing issues in openstack. A security group
// cannot be deleted while it is in use. Theoretically we terminate all the
// instances before we attempt to delete the associated security groups, but
// in practice neutron hasn't always finished with the instance before it
// returns, so there is a race condition where we think the instance is
// terminated and hence attempt to delete the security groups but nova still
// has it around internally. To attempt to catch this timing issue, deletion
// of the groups is tried multiple times. | [
"deleteSecurityGroup",
"attempts",
"to",
"delete",
"the",
"security",
"group",
".",
"Should",
"it",
"fail",
"the",
"deletion",
"is",
"retried",
"due",
"to",
"timing",
"issues",
"in",
"openstack",
".",
"A",
"security",
"group",
"cannot",
"be",
"deleted",
"while",
"it",
"is",
"in",
"use",
".",
"Theoretically",
"we",
"terminate",
"all",
"the",
"instances",
"before",
"we",
"attempt",
"to",
"delete",
"the",
"associated",
"security",
"groups",
"but",
"in",
"practice",
"neutron",
"hasn",
"t",
"always",
"finished",
"with",
"the",
"instance",
"before",
"it",
"returns",
"so",
"there",
"is",
"a",
"race",
"condition",
"where",
"we",
"think",
"the",
"instance",
"is",
"terminated",
"and",
"hence",
"attempt",
"to",
"delete",
"the",
"security",
"groups",
"but",
"nova",
"still",
"has",
"it",
"around",
"internally",
".",
"To",
"attempt",
"to",
"catch",
"this",
"timing",
"issue",
"deletion",
"of",
"the",
"groups",
"is",
"tried",
"multiple",
"times",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/firewaller.go#L300-L331 |
156,171 | juju/juju | provider/openstack/firewaller.go | ensureGroup | func (c *neutronFirewaller) ensureGroup(name string, rules []neutron.RuleInfoV2) (neutron.SecurityGroupV2, error) {
neutronClient := c.environ.neutron()
var group neutron.SecurityGroupV2
// Due to parallelization of the provisioner, it's possible that we try
// to create the model security group a second time before the first time
// is complete causing failures.
c.ensureGroupMutex.Lock()
defer c.ensureGroupMutex.Unlock()
// First attempt to look up an existing group by name.
groupsFound, err := neutronClient.SecurityGroupByNameV2(name)
// a list is returned, but there should be only one
if err == nil && len(groupsFound) == 1 {
group = groupsFound[0]
} else if err != nil && strings.Contains(err.Error(), "failed to find security group") {
// TODO(hml): We should use a typed error here. SecurityGroupByNameV2
// doesn't currently return one for this case.
g, err := neutronClient.CreateSecurityGroupV2(name, "juju group")
if err != nil {
return zeroGroup, err
}
group = *g
} else if err == nil && len(groupsFound) > 1 {
// TODO(hml): Add unit test for this case
return zeroGroup, errors.New(fmt.Sprintf("More than one security group named %s was found", name))
} else {
return zeroGroup, err
}
have := newRuleInfoSetFromRules(group.Rules)
want := newRuleInfoSetFromRuleInfo(rules)
// Find rules we want to delete, that we have but don't want, and
// delete them.
remove := make(ruleInfoSet)
for k := range have {
// Neutron creates 2 egress rules with any new Security Group.
// Keep them.
if _, ok := want[k]; !ok && k.Direction != "egress" {
remove[k] = have[k]
}
}
for _, ruleId := range remove {
if err = neutronClient.DeleteSecurityGroupRuleV2(ruleId); err != nil {
return zeroGroup, err
}
}
// Find rules we want to add, that we want but don't have, and add
// them.
add := make(ruleInfoSet)
for k := range want {
if _, ok := have[k]; !ok {
add[k] = want[k]
}
}
for rule := range add {
rule.ParentGroupId = group.Id
// Neutron translates empty RemoteIPPrefix into
// 0.0.0.0/0 or ::/0 instead of ParentGroupId
// when EthernetType is set
if rule.RemoteIPPrefix == "" {
rule.RemoteGroupId = group.Id
}
if _, err := neutronClient.CreateSecurityGroupRuleV2(rule); err != nil {
return zeroGroup, err
}
}
// Since we may have done a few add or delete rules, get a new
// copy of the security group to return containing the end
// list of rules.
groupsFound, err = neutronClient.SecurityGroupByNameV2(name)
if err != nil {
return zeroGroup, err
} else if len(groupsFound) > 1 {
// TODO(hml): Add unit test for this case
return zeroGroup, errors.New(fmt.Sprintf("More than one security group named %s was found after group was ensured", name))
}
return groupsFound[0], nil
} | go | func (c *neutronFirewaller) ensureGroup(name string, rules []neutron.RuleInfoV2) (neutron.SecurityGroupV2, error) {
neutronClient := c.environ.neutron()
var group neutron.SecurityGroupV2
// Due to parallelization of the provisioner, it's possible that we try
// to create the model security group a second time before the first time
// is complete causing failures.
c.ensureGroupMutex.Lock()
defer c.ensureGroupMutex.Unlock()
// First attempt to look up an existing group by name.
groupsFound, err := neutronClient.SecurityGroupByNameV2(name)
// a list is returned, but there should be only one
if err == nil && len(groupsFound) == 1 {
group = groupsFound[0]
} else if err != nil && strings.Contains(err.Error(), "failed to find security group") {
// TODO(hml): We should use a typed error here. SecurityGroupByNameV2
// doesn't currently return one for this case.
g, err := neutronClient.CreateSecurityGroupV2(name, "juju group")
if err != nil {
return zeroGroup, err
}
group = *g
} else if err == nil && len(groupsFound) > 1 {
// TODO(hml): Add unit test for this case
return zeroGroup, errors.New(fmt.Sprintf("More than one security group named %s was found", name))
} else {
return zeroGroup, err
}
have := newRuleInfoSetFromRules(group.Rules)
want := newRuleInfoSetFromRuleInfo(rules)
// Find rules we want to delete, that we have but don't want, and
// delete them.
remove := make(ruleInfoSet)
for k := range have {
// Neutron creates 2 egress rules with any new Security Group.
// Keep them.
if _, ok := want[k]; !ok && k.Direction != "egress" {
remove[k] = have[k]
}
}
for _, ruleId := range remove {
if err = neutronClient.DeleteSecurityGroupRuleV2(ruleId); err != nil {
return zeroGroup, err
}
}
// Find rules we want to add, that we want but don't have, and add
// them.
add := make(ruleInfoSet)
for k := range want {
if _, ok := have[k]; !ok {
add[k] = want[k]
}
}
for rule := range add {
rule.ParentGroupId = group.Id
// Neutron translates empty RemoteIPPrefix into
// 0.0.0.0/0 or ::/0 instead of ParentGroupId
// when EthernetType is set
if rule.RemoteIPPrefix == "" {
rule.RemoteGroupId = group.Id
}
if _, err := neutronClient.CreateSecurityGroupRuleV2(rule); err != nil {
return zeroGroup, err
}
}
// Since we may have done a few add or delete rules, get a new
// copy of the security group to return containing the end
// list of rules.
groupsFound, err = neutronClient.SecurityGroupByNameV2(name)
if err != nil {
return zeroGroup, err
} else if len(groupsFound) > 1 {
// TODO(hml): Add unit test for this case
return zeroGroup, errors.New(fmt.Sprintf("More than one security group named %s was found after group was ensured", name))
}
return groupsFound[0], nil
} | [
"func",
"(",
"c",
"*",
"neutronFirewaller",
")",
"ensureGroup",
"(",
"name",
"string",
",",
"rules",
"[",
"]",
"neutron",
".",
"RuleInfoV2",
")",
"(",
"neutron",
".",
"SecurityGroupV2",
",",
"error",
")",
"{",
"neutronClient",
":=",
"c",
".",
"environ",
".",
"neutron",
"(",
")",
"\n",
"var",
"group",
"neutron",
".",
"SecurityGroupV2",
"\n\n",
"// Due to parallelization of the provisioner, it's possible that we try",
"// to create the model security group a second time before the first time",
"// is complete causing failures.",
"c",
".",
"ensureGroupMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"ensureGroupMutex",
".",
"Unlock",
"(",
")",
"\n",
"// First attempt to look up an existing group by name.",
"groupsFound",
",",
"err",
":=",
"neutronClient",
".",
"SecurityGroupByNameV2",
"(",
"name",
")",
"\n",
"// a list is returned, but there should be only one",
"if",
"err",
"==",
"nil",
"&&",
"len",
"(",
"groupsFound",
")",
"==",
"1",
"{",
"group",
"=",
"groupsFound",
"[",
"0",
"]",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"&&",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"// TODO(hml): We should use a typed error here. SecurityGroupByNameV2",
"// doesn't currently return one for this case.",
"g",
",",
"err",
":=",
"neutronClient",
".",
"CreateSecurityGroupV2",
"(",
"name",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"zeroGroup",
",",
"err",
"\n",
"}",
"\n",
"group",
"=",
"*",
"g",
"\n",
"}",
"else",
"if",
"err",
"==",
"nil",
"&&",
"len",
"(",
"groupsFound",
")",
">",
"1",
"{",
"// TODO(hml): Add unit test for this case",
"return",
"zeroGroup",
",",
"errors",
".",
"New",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
")",
"\n",
"}",
"else",
"{",
"return",
"zeroGroup",
",",
"err",
"\n",
"}",
"\n\n",
"have",
":=",
"newRuleInfoSetFromRules",
"(",
"group",
".",
"Rules",
")",
"\n",
"want",
":=",
"newRuleInfoSetFromRuleInfo",
"(",
"rules",
")",
"\n\n",
"// Find rules we want to delete, that we have but don't want, and",
"// delete them.",
"remove",
":=",
"make",
"(",
"ruleInfoSet",
")",
"\n",
"for",
"k",
":=",
"range",
"have",
"{",
"// Neutron creates 2 egress rules with any new Security Group.",
"// Keep them.",
"if",
"_",
",",
"ok",
":=",
"want",
"[",
"k",
"]",
";",
"!",
"ok",
"&&",
"k",
".",
"Direction",
"!=",
"\"",
"\"",
"{",
"remove",
"[",
"k",
"]",
"=",
"have",
"[",
"k",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"ruleId",
":=",
"range",
"remove",
"{",
"if",
"err",
"=",
"neutronClient",
".",
"DeleteSecurityGroupRuleV2",
"(",
"ruleId",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"zeroGroup",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Find rules we want to add, that we want but don't have, and add",
"// them.",
"add",
":=",
"make",
"(",
"ruleInfoSet",
")",
"\n",
"for",
"k",
":=",
"range",
"want",
"{",
"if",
"_",
",",
"ok",
":=",
"have",
"[",
"k",
"]",
";",
"!",
"ok",
"{",
"add",
"[",
"k",
"]",
"=",
"want",
"[",
"k",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"rule",
":=",
"range",
"add",
"{",
"rule",
".",
"ParentGroupId",
"=",
"group",
".",
"Id",
"\n",
"// Neutron translates empty RemoteIPPrefix into",
"// 0.0.0.0/0 or ::/0 instead of ParentGroupId",
"// when EthernetType is set",
"if",
"rule",
".",
"RemoteIPPrefix",
"==",
"\"",
"\"",
"{",
"rule",
".",
"RemoteGroupId",
"=",
"group",
".",
"Id",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"neutronClient",
".",
"CreateSecurityGroupRuleV2",
"(",
"rule",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"zeroGroup",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Since we may have done a few add or delete rules, get a new",
"// copy of the security group to return containing the end",
"// list of rules.",
"groupsFound",
",",
"err",
"=",
"neutronClient",
".",
"SecurityGroupByNameV2",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"zeroGroup",
",",
"err",
"\n",
"}",
"else",
"if",
"len",
"(",
"groupsFound",
")",
">",
"1",
"{",
"// TODO(hml): Add unit test for this case",
"return",
"zeroGroup",
",",
"errors",
".",
"New",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
")",
"\n",
"}",
"\n",
"return",
"groupsFound",
"[",
"0",
"]",
",",
"nil",
"\n",
"}"
] | // ensureGroup returns the security group with name and rules.
// If a group with name does not exist, one will be created.
// If it exists, its permissions are set to rules. | [
"ensureGroup",
"returns",
"the",
"security",
"group",
"with",
"name",
"and",
"rules",
".",
"If",
"a",
"group",
"with",
"name",
"does",
"not",
"exist",
"one",
"will",
"be",
"created",
".",
"If",
"it",
"exists",
"its",
"permissions",
"are",
"set",
"to",
"rules",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/firewaller.go#L563-L643 |
156,172 | juju/juju | provider/openstack/firewaller.go | newRuleInfoSetFromRules | func newRuleInfoSetFromRules(rules []neutron.SecurityGroupRuleV2) ruleInfoSet {
m := make(ruleInfoSet)
for _, r := range rules {
k := neutron.RuleInfoV2{
Direction: r.Direction,
EthernetType: r.EthernetType,
RemoteIPPrefix: r.RemoteIPPrefix,
}
if r.IPProtocol != nil {
k.IPProtocol = *r.IPProtocol
}
if r.PortRangeMax != nil {
k.PortRangeMax = *r.PortRangeMax
}
if r.PortRangeMin != nil {
k.PortRangeMin = *r.PortRangeMin
}
m[k] = r.Id
}
return m
} | go | func newRuleInfoSetFromRules(rules []neutron.SecurityGroupRuleV2) ruleInfoSet {
m := make(ruleInfoSet)
for _, r := range rules {
k := neutron.RuleInfoV2{
Direction: r.Direction,
EthernetType: r.EthernetType,
RemoteIPPrefix: r.RemoteIPPrefix,
}
if r.IPProtocol != nil {
k.IPProtocol = *r.IPProtocol
}
if r.PortRangeMax != nil {
k.PortRangeMax = *r.PortRangeMax
}
if r.PortRangeMin != nil {
k.PortRangeMin = *r.PortRangeMin
}
m[k] = r.Id
}
return m
} | [
"func",
"newRuleInfoSetFromRules",
"(",
"rules",
"[",
"]",
"neutron",
".",
"SecurityGroupRuleV2",
")",
"ruleInfoSet",
"{",
"m",
":=",
"make",
"(",
"ruleInfoSet",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"rules",
"{",
"k",
":=",
"neutron",
".",
"RuleInfoV2",
"{",
"Direction",
":",
"r",
".",
"Direction",
",",
"EthernetType",
":",
"r",
".",
"EthernetType",
",",
"RemoteIPPrefix",
":",
"r",
".",
"RemoteIPPrefix",
",",
"}",
"\n",
"if",
"r",
".",
"IPProtocol",
"!=",
"nil",
"{",
"k",
".",
"IPProtocol",
"=",
"*",
"r",
".",
"IPProtocol",
"\n",
"}",
"\n",
"if",
"r",
".",
"PortRangeMax",
"!=",
"nil",
"{",
"k",
".",
"PortRangeMax",
"=",
"*",
"r",
".",
"PortRangeMax",
"\n",
"}",
"\n",
"if",
"r",
".",
"PortRangeMin",
"!=",
"nil",
"{",
"k",
".",
"PortRangeMin",
"=",
"*",
"r",
".",
"PortRangeMin",
"\n",
"}",
"\n",
"m",
"[",
"k",
"]",
"=",
"r",
".",
"Id",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] | // newRuleSetForGroup returns a set of all of the permissions in a given
// slice of SecurityGroupRules. It ignores the group id, the
// remove group id, and tenant id. Keep the rule id to delete the rule if
// necessary. | [
"newRuleSetForGroup",
"returns",
"a",
"set",
"of",
"all",
"of",
"the",
"permissions",
"in",
"a",
"given",
"slice",
"of",
"SecurityGroupRules",
".",
"It",
"ignores",
"the",
"group",
"id",
"the",
"remove",
"group",
"id",
"and",
"tenant",
"id",
".",
"Keep",
"the",
"rule",
"id",
"to",
"delete",
"the",
"rule",
"if",
"necessary",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/firewaller.go#L654-L674 |
156,173 | juju/juju | provider/openstack/firewaller.go | newRuleInfoSetFromRuleInfo | func newRuleInfoSetFromRuleInfo(rules []neutron.RuleInfoV2) ruleInfoSet {
m := make(ruleInfoSet)
for _, r := range rules {
k := neutron.RuleInfoV2{
Direction: r.Direction,
IPProtocol: r.IPProtocol,
PortRangeMin: r.PortRangeMin,
PortRangeMax: r.PortRangeMax,
EthernetType: r.EthernetType,
RemoteIPPrefix: r.RemoteIPPrefix,
}
m[k] = ""
}
return m
} | go | func newRuleInfoSetFromRuleInfo(rules []neutron.RuleInfoV2) ruleInfoSet {
m := make(ruleInfoSet)
for _, r := range rules {
k := neutron.RuleInfoV2{
Direction: r.Direction,
IPProtocol: r.IPProtocol,
PortRangeMin: r.PortRangeMin,
PortRangeMax: r.PortRangeMax,
EthernetType: r.EthernetType,
RemoteIPPrefix: r.RemoteIPPrefix,
}
m[k] = ""
}
return m
} | [
"func",
"newRuleInfoSetFromRuleInfo",
"(",
"rules",
"[",
"]",
"neutron",
".",
"RuleInfoV2",
")",
"ruleInfoSet",
"{",
"m",
":=",
"make",
"(",
"ruleInfoSet",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"rules",
"{",
"k",
":=",
"neutron",
".",
"RuleInfoV2",
"{",
"Direction",
":",
"r",
".",
"Direction",
",",
"IPProtocol",
":",
"r",
".",
"IPProtocol",
",",
"PortRangeMin",
":",
"r",
".",
"PortRangeMin",
",",
"PortRangeMax",
":",
"r",
".",
"PortRangeMax",
",",
"EthernetType",
":",
"r",
".",
"EthernetType",
",",
"RemoteIPPrefix",
":",
"r",
".",
"RemoteIPPrefix",
",",
"}",
"\n",
"m",
"[",
"k",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] | // newRuleSetForGroup returns a set of all of the permissions in a given
// slice of RuleInfo. It ignores the rule id, the group id, the
// remove group id, and tenant id. | [
"newRuleSetForGroup",
"returns",
"a",
"set",
"of",
"all",
"of",
"the",
"permissions",
"in",
"a",
"given",
"slice",
"of",
"RuleInfo",
".",
"It",
"ignores",
"the",
"rule",
"id",
"the",
"group",
"id",
"the",
"remove",
"group",
"id",
"and",
"tenant",
"id",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/firewaller.go#L679-L693 |
156,174 | juju/juju | provider/openstack/firewaller.go | DeleteAllControllerGroups | func (c *neutronFirewaller) DeleteAllControllerGroups(ctx context.ProviderCallContext, controllerUUID string) error {
return deleteSecurityGroupsMatchingName(ctx, c.deleteSecurityGroups, c.jujuControllerGroupPrefix(controllerUUID))
} | go | func (c *neutronFirewaller) DeleteAllControllerGroups(ctx context.ProviderCallContext, controllerUUID string) error {
return deleteSecurityGroupsMatchingName(ctx, c.deleteSecurityGroups, c.jujuControllerGroupPrefix(controllerUUID))
} | [
"func",
"(",
"c",
"*",
"neutronFirewaller",
")",
"DeleteAllControllerGroups",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"controllerUUID",
"string",
")",
"error",
"{",
"return",
"deleteSecurityGroupsMatchingName",
"(",
"ctx",
",",
"c",
".",
"deleteSecurityGroups",
",",
"c",
".",
"jujuControllerGroupPrefix",
"(",
"controllerUUID",
")",
")",
"\n",
"}"
] | // DeleteAllControllerGroups implements Firewaller interface. | [
"DeleteAllControllerGroups",
"implements",
"Firewaller",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/firewaller.go#L722-L724 |
156,175 | juju/juju | provider/openstack/firewaller.go | matchingGroup | func (c *neutronFirewaller) matchingGroup(ctx context.ProviderCallContext, nameRegExp string) (neutron.SecurityGroupV2, error) {
re, err := regexp.Compile(nameRegExp)
if err != nil {
return neutron.SecurityGroupV2{}, err
}
neutronClient := c.environ.neutron()
allGroups, err := neutronClient.ListSecurityGroupsV2()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return neutron.SecurityGroupV2{}, err
}
var matchingGroups []neutron.SecurityGroupV2
for _, group := range allGroups {
if re.MatchString(group.Name) {
matchingGroups = append(matchingGroups, group)
}
}
numMatching := len(matchingGroups)
if numMatching == 0 {
return neutron.SecurityGroupV2{}, errors.NotFoundf("security groups matching %q", nameRegExp)
} else if numMatching > 1 {
return neutron.SecurityGroupV2{}, errors.New(fmt.Sprintf("%d security groups found matching %q, expected 1", numMatching, nameRegExp))
}
return matchingGroups[0], nil
} | go | func (c *neutronFirewaller) matchingGroup(ctx context.ProviderCallContext, nameRegExp string) (neutron.SecurityGroupV2, error) {
re, err := regexp.Compile(nameRegExp)
if err != nil {
return neutron.SecurityGroupV2{}, err
}
neutronClient := c.environ.neutron()
allGroups, err := neutronClient.ListSecurityGroupsV2()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return neutron.SecurityGroupV2{}, err
}
var matchingGroups []neutron.SecurityGroupV2
for _, group := range allGroups {
if re.MatchString(group.Name) {
matchingGroups = append(matchingGroups, group)
}
}
numMatching := len(matchingGroups)
if numMatching == 0 {
return neutron.SecurityGroupV2{}, errors.NotFoundf("security groups matching %q", nameRegExp)
} else if numMatching > 1 {
return neutron.SecurityGroupV2{}, errors.New(fmt.Sprintf("%d security groups found matching %q, expected 1", numMatching, nameRegExp))
}
return matchingGroups[0], nil
} | [
"func",
"(",
"c",
"*",
"neutronFirewaller",
")",
"matchingGroup",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"nameRegExp",
"string",
")",
"(",
"neutron",
".",
"SecurityGroupV2",
",",
"error",
")",
"{",
"re",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"nameRegExp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"neutron",
".",
"SecurityGroupV2",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"neutronClient",
":=",
"c",
".",
"environ",
".",
"neutron",
"(",
")",
"\n",
"allGroups",
",",
"err",
":=",
"neutronClient",
".",
"ListSecurityGroupsV2",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"neutron",
".",
"SecurityGroupV2",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"var",
"matchingGroups",
"[",
"]",
"neutron",
".",
"SecurityGroupV2",
"\n",
"for",
"_",
",",
"group",
":=",
"range",
"allGroups",
"{",
"if",
"re",
".",
"MatchString",
"(",
"group",
".",
"Name",
")",
"{",
"matchingGroups",
"=",
"append",
"(",
"matchingGroups",
",",
"group",
")",
"\n",
"}",
"\n",
"}",
"\n",
"numMatching",
":=",
"len",
"(",
"matchingGroups",
")",
"\n",
"if",
"numMatching",
"==",
"0",
"{",
"return",
"neutron",
".",
"SecurityGroupV2",
"{",
"}",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"nameRegExp",
")",
"\n",
"}",
"else",
"if",
"numMatching",
">",
"1",
"{",
"return",
"neutron",
".",
"SecurityGroupV2",
"{",
"}",
",",
"errors",
".",
"New",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"numMatching",
",",
"nameRegExp",
")",
")",
"\n",
"}",
"\n",
"return",
"matchingGroups",
"[",
"0",
"]",
",",
"nil",
"\n",
"}"
] | // Matching a security group by name only works if each name is unqiue. Neutron
// security groups are not required to have unique names. Juju constructs unique
// names, but there are frequently multiple matches to 'default' | [
"Matching",
"a",
"security",
"group",
"by",
"name",
"only",
"works",
"if",
"each",
"name",
"is",
"unqiue",
".",
"Neutron",
"security",
"groups",
"are",
"not",
"required",
"to",
"have",
"unique",
"names",
".",
"Juju",
"constructs",
"unique",
"names",
"but",
"there",
"are",
"frequently",
"multiple",
"matches",
"to",
"default"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/firewaller.go#L873-L897 |
156,176 | juju/juju | provider/openstack/firewaller.go | secGroupMatchesIngressRule | func secGroupMatchesIngressRule(secGroupRule neutron.SecurityGroupRuleV2, rule network.IngressRule) bool {
if secGroupRule.IPProtocol == nil ||
secGroupRule.PortRangeMax == nil || *secGroupRule.PortRangeMax == 0 ||
secGroupRule.PortRangeMin == nil || *secGroupRule.PortRangeMin == 0 {
return false
}
portsMatch := *secGroupRule.IPProtocol == rule.Protocol &&
*secGroupRule.PortRangeMin == rule.FromPort &&
*secGroupRule.PortRangeMax == rule.ToPort
if !portsMatch {
return false
}
// The ports match, so if the security group RemoteIPPrefix matches *any* of the
// rule's source ranges, then that's a match.
if len(rule.SourceCIDRs) == 0 {
return secGroupRule.RemoteIPPrefix == "" || secGroupRule.RemoteIPPrefix == "0.0.0.0/0"
}
for _, r := range rule.SourceCIDRs {
if r == secGroupRule.RemoteIPPrefix {
return true
}
}
return false
} | go | func secGroupMatchesIngressRule(secGroupRule neutron.SecurityGroupRuleV2, rule network.IngressRule) bool {
if secGroupRule.IPProtocol == nil ||
secGroupRule.PortRangeMax == nil || *secGroupRule.PortRangeMax == 0 ||
secGroupRule.PortRangeMin == nil || *secGroupRule.PortRangeMin == 0 {
return false
}
portsMatch := *secGroupRule.IPProtocol == rule.Protocol &&
*secGroupRule.PortRangeMin == rule.FromPort &&
*secGroupRule.PortRangeMax == rule.ToPort
if !portsMatch {
return false
}
// The ports match, so if the security group RemoteIPPrefix matches *any* of the
// rule's source ranges, then that's a match.
if len(rule.SourceCIDRs) == 0 {
return secGroupRule.RemoteIPPrefix == "" || secGroupRule.RemoteIPPrefix == "0.0.0.0/0"
}
for _, r := range rule.SourceCIDRs {
if r == secGroupRule.RemoteIPPrefix {
return true
}
}
return false
} | [
"func",
"secGroupMatchesIngressRule",
"(",
"secGroupRule",
"neutron",
".",
"SecurityGroupRuleV2",
",",
"rule",
"network",
".",
"IngressRule",
")",
"bool",
"{",
"if",
"secGroupRule",
".",
"IPProtocol",
"==",
"nil",
"||",
"secGroupRule",
".",
"PortRangeMax",
"==",
"nil",
"||",
"*",
"secGroupRule",
".",
"PortRangeMax",
"==",
"0",
"||",
"secGroupRule",
".",
"PortRangeMin",
"==",
"nil",
"||",
"*",
"secGroupRule",
".",
"PortRangeMin",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"portsMatch",
":=",
"*",
"secGroupRule",
".",
"IPProtocol",
"==",
"rule",
".",
"Protocol",
"&&",
"*",
"secGroupRule",
".",
"PortRangeMin",
"==",
"rule",
".",
"FromPort",
"&&",
"*",
"secGroupRule",
".",
"PortRangeMax",
"==",
"rule",
".",
"ToPort",
"\n",
"if",
"!",
"portsMatch",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// The ports match, so if the security group RemoteIPPrefix matches *any* of the",
"// rule's source ranges, then that's a match.",
"if",
"len",
"(",
"rule",
".",
"SourceCIDRs",
")",
"==",
"0",
"{",
"return",
"secGroupRule",
".",
"RemoteIPPrefix",
"==",
"\"",
"\"",
"||",
"secGroupRule",
".",
"RemoteIPPrefix",
"==",
"\"",
"\"",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"rule",
".",
"SourceCIDRs",
"{",
"if",
"r",
"==",
"secGroupRule",
".",
"RemoteIPPrefix",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // secGroupMatchesIngressRule checks if supplied nova security group rule matches the ingress rule | [
"secGroupMatchesIngressRule",
"checks",
"if",
"supplied",
"nova",
"security",
"group",
"rule",
"matches",
"the",
"ingress",
"rule"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/firewaller.go#L918-L941 |
156,177 | juju/juju | api/firewaller/machine.go | ActiveSubnets | func (m *Machine) ActiveSubnets() ([]names.SubnetTag, error) {
var results params.StringsResults
args := params.Entities{
Entities: []params.Entity{{Tag: m.tag.String()}},
}
err := m.st.facade.FacadeCall("GetMachineActiveSubnets", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
// Convert string tags to names.SubnetTag before returning.
tags := make([]names.SubnetTag, len(result.Result))
for i, tag := range result.Result {
var subnetTag names.SubnetTag
if tag != "" {
subnetTag, err = names.ParseSubnetTag(tag)
if err != nil {
return nil, err
}
}
tags[i] = subnetTag
}
return tags, nil
} | go | func (m *Machine) ActiveSubnets() ([]names.SubnetTag, error) {
var results params.StringsResults
args := params.Entities{
Entities: []params.Entity{{Tag: m.tag.String()}},
}
err := m.st.facade.FacadeCall("GetMachineActiveSubnets", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
// Convert string tags to names.SubnetTag before returning.
tags := make([]names.SubnetTag, len(result.Result))
for i, tag := range result.Result {
var subnetTag names.SubnetTag
if tag != "" {
subnetTag, err = names.ParseSubnetTag(tag)
if err != nil {
return nil, err
}
}
tags[i] = subnetTag
}
return tags, nil
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"ActiveSubnets",
"(",
")",
"(",
"[",
"]",
"names",
".",
"SubnetTag",
",",
"error",
")",
"{",
"var",
"results",
"params",
".",
"StringsResults",
"\n",
"args",
":=",
"params",
".",
"Entities",
"{",
"Entities",
":",
"[",
"]",
"params",
".",
"Entity",
"{",
"{",
"Tag",
":",
"m",
".",
"tag",
".",
"String",
"(",
")",
"}",
"}",
",",
"}",
"\n",
"err",
":=",
"m",
".",
"st",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"results",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"results",
".",
"Results",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"results",
".",
"Results",
")",
")",
"\n",
"}",
"\n",
"result",
":=",
"results",
".",
"Results",
"[",
"0",
"]",
"\n",
"if",
"result",
".",
"Error",
"!=",
"nil",
"{",
"return",
"nil",
",",
"result",
".",
"Error",
"\n",
"}",
"\n",
"// Convert string tags to names.SubnetTag before returning.",
"tags",
":=",
"make",
"(",
"[",
"]",
"names",
".",
"SubnetTag",
",",
"len",
"(",
"result",
".",
"Result",
")",
")",
"\n",
"for",
"i",
",",
"tag",
":=",
"range",
"result",
".",
"Result",
"{",
"var",
"subnetTag",
"names",
".",
"SubnetTag",
"\n",
"if",
"tag",
"!=",
"\"",
"\"",
"{",
"subnetTag",
",",
"err",
"=",
"names",
".",
"ParseSubnetTag",
"(",
"tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"tags",
"[",
"i",
"]",
"=",
"subnetTag",
"\n",
"}",
"\n",
"return",
"tags",
",",
"nil",
"\n",
"}"
] | // ActiveSubnets returns a list of subnet tags for which the machine has opened
// ports. | [
"ActiveSubnets",
"returns",
"a",
"list",
"of",
"subnet",
"tags",
"for",
"which",
"the",
"machine",
"has",
"opened",
"ports",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/firewaller/machine.go#L80-L109 |
156,178 | juju/juju | api/firewaller/machine.go | OpenedPorts | func (m *Machine) OpenedPorts(subnetTag names.SubnetTag) (map[network.PortRange]names.UnitTag, error) {
var results params.MachinePortsResults
var subnetTagAsString string
if subnetTag.Id() != "" {
subnetTagAsString = subnetTag.String()
}
args := params.MachinePortsParams{
Params: []params.MachinePorts{
{MachineTag: m.tag.String(), SubnetTag: subnetTagAsString},
},
}
err := m.st.facade.FacadeCall("GetMachinePorts", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
// Convert string tags to names.UnitTag before returning.
endResult := make(map[network.PortRange]names.UnitTag)
for _, ports := range result.Ports {
unitTag, err := names.ParseUnitTag(ports.UnitTag)
if err != nil {
return nil, err
}
endResult[ports.PortRange.NetworkPortRange()] = unitTag
}
return endResult, nil
} | go | func (m *Machine) OpenedPorts(subnetTag names.SubnetTag) (map[network.PortRange]names.UnitTag, error) {
var results params.MachinePortsResults
var subnetTagAsString string
if subnetTag.Id() != "" {
subnetTagAsString = subnetTag.String()
}
args := params.MachinePortsParams{
Params: []params.MachinePorts{
{MachineTag: m.tag.String(), SubnetTag: subnetTagAsString},
},
}
err := m.st.facade.FacadeCall("GetMachinePorts", args, &results)
if err != nil {
return nil, err
}
if len(results.Results) != 1 {
return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results))
}
result := results.Results[0]
if result.Error != nil {
return nil, result.Error
}
// Convert string tags to names.UnitTag before returning.
endResult := make(map[network.PortRange]names.UnitTag)
for _, ports := range result.Ports {
unitTag, err := names.ParseUnitTag(ports.UnitTag)
if err != nil {
return nil, err
}
endResult[ports.PortRange.NetworkPortRange()] = unitTag
}
return endResult, nil
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"OpenedPorts",
"(",
"subnetTag",
"names",
".",
"SubnetTag",
")",
"(",
"map",
"[",
"network",
".",
"PortRange",
"]",
"names",
".",
"UnitTag",
",",
"error",
")",
"{",
"var",
"results",
"params",
".",
"MachinePortsResults",
"\n",
"var",
"subnetTagAsString",
"string",
"\n",
"if",
"subnetTag",
".",
"Id",
"(",
")",
"!=",
"\"",
"\"",
"{",
"subnetTagAsString",
"=",
"subnetTag",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"args",
":=",
"params",
".",
"MachinePortsParams",
"{",
"Params",
":",
"[",
"]",
"params",
".",
"MachinePorts",
"{",
"{",
"MachineTag",
":",
"m",
".",
"tag",
".",
"String",
"(",
")",
",",
"SubnetTag",
":",
"subnetTagAsString",
"}",
",",
"}",
",",
"}",
"\n",
"err",
":=",
"m",
".",
"st",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"results",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"results",
".",
"Results",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"results",
".",
"Results",
")",
")",
"\n",
"}",
"\n",
"result",
":=",
"results",
".",
"Results",
"[",
"0",
"]",
"\n",
"if",
"result",
".",
"Error",
"!=",
"nil",
"{",
"return",
"nil",
",",
"result",
".",
"Error",
"\n",
"}",
"\n",
"// Convert string tags to names.UnitTag before returning.",
"endResult",
":=",
"make",
"(",
"map",
"[",
"network",
".",
"PortRange",
"]",
"names",
".",
"UnitTag",
")",
"\n",
"for",
"_",
",",
"ports",
":=",
"range",
"result",
".",
"Ports",
"{",
"unitTag",
",",
"err",
":=",
"names",
".",
"ParseUnitTag",
"(",
"ports",
".",
"UnitTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"endResult",
"[",
"ports",
".",
"PortRange",
".",
"NetworkPortRange",
"(",
")",
"]",
"=",
"unitTag",
"\n",
"}",
"\n",
"return",
"endResult",
",",
"nil",
"\n",
"}"
] | // OpenedPorts returns a map of network.PortRange to unit tag for all opened
// port ranges on the machine for the subnet matching given subnetTag. | [
"OpenedPorts",
"returns",
"a",
"map",
"of",
"network",
".",
"PortRange",
"to",
"unit",
"tag",
"for",
"all",
"opened",
"port",
"ranges",
"on",
"the",
"machine",
"for",
"the",
"subnet",
"matching",
"given",
"subnetTag",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/firewaller/machine.go#L113-L145 |
156,179 | juju/juju | state/txns.go | ResumeTransactions | func (st *State) ResumeTransactions() error {
runner, closer := st.database.TransactionRunner()
defer closer()
return runner.ResumeTransactions()
} | go | func (st *State) ResumeTransactions() error {
runner, closer := st.database.TransactionRunner()
defer closer()
return runner.ResumeTransactions()
} | [
"func",
"(",
"st",
"*",
"State",
")",
"ResumeTransactions",
"(",
")",
"error",
"{",
"runner",
",",
"closer",
":=",
"st",
".",
"database",
".",
"TransactionRunner",
"(",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"return",
"runner",
".",
"ResumeTransactions",
"(",
")",
"\n",
"}"
] | // ResumeTransactions resumes all pending transactions. | [
"ResumeTransactions",
"resumes",
"all",
"pending",
"transactions",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/txns.go#L33-L37 |
156,180 | juju/juju | state/txns.go | MaybePruneTransactions | func (st *State) MaybePruneTransactions() error {
runner, closer := st.database.TransactionRunner()
defer closer()
cfg, err := st.ControllerConfig()
if err != nil {
return errors.Trace(err)
}
// Prune txns when txn count has increased by 10% since last prune.
return runner.MaybePruneTransactions(jujutxn.PruneOptions{
PruneFactor: 1.1,
MinNewTransactions: 1000,
MaxNewTransactions: 100000,
MaxTime: time.Now().Add(-time.Hour),
MaxBatchTransactions: cfg.MaxPruneTxnBatchSize(),
MaxBatches: cfg.MaxPruneTxnPasses(),
SmallBatchTransactionCount: cfg.PruneTxnQueryCount(),
BatchTransactionSleepTime: cfg.PruneTxnSleepTime(),
})
} | go | func (st *State) MaybePruneTransactions() error {
runner, closer := st.database.TransactionRunner()
defer closer()
cfg, err := st.ControllerConfig()
if err != nil {
return errors.Trace(err)
}
// Prune txns when txn count has increased by 10% since last prune.
return runner.MaybePruneTransactions(jujutxn.PruneOptions{
PruneFactor: 1.1,
MinNewTransactions: 1000,
MaxNewTransactions: 100000,
MaxTime: time.Now().Add(-time.Hour),
MaxBatchTransactions: cfg.MaxPruneTxnBatchSize(),
MaxBatches: cfg.MaxPruneTxnPasses(),
SmallBatchTransactionCount: cfg.PruneTxnQueryCount(),
BatchTransactionSleepTime: cfg.PruneTxnSleepTime(),
})
} | [
"func",
"(",
"st",
"*",
"State",
")",
"MaybePruneTransactions",
"(",
")",
"error",
"{",
"runner",
",",
"closer",
":=",
"st",
".",
"database",
".",
"TransactionRunner",
"(",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"cfg",
",",
"err",
":=",
"st",
".",
"ControllerConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"// Prune txns when txn count has increased by 10% since last prune.",
"return",
"runner",
".",
"MaybePruneTransactions",
"(",
"jujutxn",
".",
"PruneOptions",
"{",
"PruneFactor",
":",
"1.1",
",",
"MinNewTransactions",
":",
"1000",
",",
"MaxNewTransactions",
":",
"100000",
",",
"MaxTime",
":",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"-",
"time",
".",
"Hour",
")",
",",
"MaxBatchTransactions",
":",
"cfg",
".",
"MaxPruneTxnBatchSize",
"(",
")",
",",
"MaxBatches",
":",
"cfg",
".",
"MaxPruneTxnPasses",
"(",
")",
",",
"SmallBatchTransactionCount",
":",
"cfg",
".",
"PruneTxnQueryCount",
"(",
")",
",",
"BatchTransactionSleepTime",
":",
"cfg",
".",
"PruneTxnSleepTime",
"(",
")",
",",
"}",
")",
"\n",
"}"
] | // MaybePruneTransactions removes data for completed transactions. | [
"MaybePruneTransactions",
"removes",
"data",
"for",
"completed",
"transactions",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/txns.go#L40-L58 |
156,181 | juju/juju | state/txns.go | RunTransaction | func (r *multiModelRunner) RunTransaction(tx *jujutxn.Transaction) error {
if len(tx.Ops) == 0 {
stack := shortStack()
// It is a warning that should be reported to us, but we definitely
// don't want to clutter up logs so we'll only write it once.
if !seenShortStacks[stack] {
seenShortStacks[stack] = true
logger.Warningf("Running no-op transaction - called by %s", stack)
}
}
newOps, err := r.updateOps(tx.Ops)
if err != nil {
return errors.Trace(err)
}
tx.Ops = newOps
return r.rawRunner.RunTransaction(tx)
} | go | func (r *multiModelRunner) RunTransaction(tx *jujutxn.Transaction) error {
if len(tx.Ops) == 0 {
stack := shortStack()
// It is a warning that should be reported to us, but we definitely
// don't want to clutter up logs so we'll only write it once.
if !seenShortStacks[stack] {
seenShortStacks[stack] = true
logger.Warningf("Running no-op transaction - called by %s", stack)
}
}
newOps, err := r.updateOps(tx.Ops)
if err != nil {
return errors.Trace(err)
}
tx.Ops = newOps
return r.rawRunner.RunTransaction(tx)
} | [
"func",
"(",
"r",
"*",
"multiModelRunner",
")",
"RunTransaction",
"(",
"tx",
"*",
"jujutxn",
".",
"Transaction",
")",
"error",
"{",
"if",
"len",
"(",
"tx",
".",
"Ops",
")",
"==",
"0",
"{",
"stack",
":=",
"shortStack",
"(",
")",
"\n",
"// It is a warning that should be reported to us, but we definitely",
"// don't want to clutter up logs so we'll only write it once.",
"if",
"!",
"seenShortStacks",
"[",
"stack",
"]",
"{",
"seenShortStacks",
"[",
"stack",
"]",
"=",
"true",
"\n",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"stack",
")",
"\n",
"}",
"\n",
"}",
"\n",
"newOps",
",",
"err",
":=",
"r",
".",
"updateOps",
"(",
"tx",
".",
"Ops",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"tx",
".",
"Ops",
"=",
"newOps",
"\n",
"return",
"r",
".",
"rawRunner",
".",
"RunTransaction",
"(",
"tx",
")",
"\n",
"}"
] | // RunTransaction is part of the jujutxn.Runner interface. Operations
// that affect multi-model collections will be modified to
// ensure correct interaction with these collections. | [
"RunTransaction",
"is",
"part",
"of",
"the",
"jujutxn",
".",
"Runner",
"interface",
".",
"Operations",
"that",
"affect",
"multi",
"-",
"model",
"collections",
"will",
"be",
"modified",
"to",
"ensure",
"correct",
"interaction",
"with",
"these",
"collections",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/txns.go#L82-L98 |
156,182 | juju/juju | state/txns.go | Run | func (r *multiModelRunner) Run(transactions jujutxn.TransactionSource) error {
return r.rawRunner.Run(func(attempt int) ([]txn.Op, error) {
ops, err := transactions(attempt)
if err != nil {
// Don't use Trace here as jujutxn doens't use juju/errors
// and won't deal correctly with some returned errors.
return nil, err
}
newOps, err := r.updateOps(ops)
if err != nil {
return nil, errors.Trace(err)
}
return newOps, nil
})
} | go | func (r *multiModelRunner) Run(transactions jujutxn.TransactionSource) error {
return r.rawRunner.Run(func(attempt int) ([]txn.Op, error) {
ops, err := transactions(attempt)
if err != nil {
// Don't use Trace here as jujutxn doens't use juju/errors
// and won't deal correctly with some returned errors.
return nil, err
}
newOps, err := r.updateOps(ops)
if err != nil {
return nil, errors.Trace(err)
}
return newOps, nil
})
} | [
"func",
"(",
"r",
"*",
"multiModelRunner",
")",
"Run",
"(",
"transactions",
"jujutxn",
".",
"TransactionSource",
")",
"error",
"{",
"return",
"r",
".",
"rawRunner",
".",
"Run",
"(",
"func",
"(",
"attempt",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"ops",
",",
"err",
":=",
"transactions",
"(",
"attempt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Don't use Trace here as jujutxn doens't use juju/errors",
"// and won't deal correctly with some returned errors.",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"newOps",
",",
"err",
":=",
"r",
".",
"updateOps",
"(",
"ops",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"newOps",
",",
"nil",
"\n",
"}",
")",
"\n",
"}"
] | // Run is part of the jujutxn.Runner interface. Operations returned by
// the given "transactions" function that affect multi-model
// collections will be modified to ensure correct interaction with
// these collections. | [
"Run",
"is",
"part",
"of",
"the",
"jujutxn",
".",
"Runner",
"interface",
".",
"Operations",
"returned",
"by",
"the",
"given",
"transactions",
"function",
"that",
"affect",
"multi",
"-",
"model",
"collections",
"will",
"be",
"modified",
"to",
"ensure",
"correct",
"interaction",
"with",
"these",
"collections",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/txns.go#L104-L118 |
156,183 | juju/juju | state/txns.go | MaybePruneTransactions | func (r *multiModelRunner) MaybePruneTransactions(opts jujutxn.PruneOptions) error {
return r.rawRunner.MaybePruneTransactions(opts)
} | go | func (r *multiModelRunner) MaybePruneTransactions(opts jujutxn.PruneOptions) error {
return r.rawRunner.MaybePruneTransactions(opts)
} | [
"func",
"(",
"r",
"*",
"multiModelRunner",
")",
"MaybePruneTransactions",
"(",
"opts",
"jujutxn",
".",
"PruneOptions",
")",
"error",
"{",
"return",
"r",
".",
"rawRunner",
".",
"MaybePruneTransactions",
"(",
"opts",
")",
"\n",
"}"
] | // MaybePruneTransactions is part of the jujutxn.Runner interface. | [
"MaybePruneTransactions",
"is",
"part",
"of",
"the",
"jujutxn",
".",
"Runner",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/txns.go#L126-L128 |
156,184 | juju/juju | state/txns.go | mungeUpdate | func (r *multiModelRunner) mungeUpdate(updateDoc interface{}) (interface{}, error) {
switch doc := updateDoc.(type) {
case bson.D:
return r.mungeBsonDUpdate(doc)
case bson.M:
return r.mungeBsonMUpdate(doc)
default:
return nil, errors.Errorf("don't know how to handle %T", updateDoc)
}
} | go | func (r *multiModelRunner) mungeUpdate(updateDoc interface{}) (interface{}, error) {
switch doc := updateDoc.(type) {
case bson.D:
return r.mungeBsonDUpdate(doc)
case bson.M:
return r.mungeBsonMUpdate(doc)
default:
return nil, errors.Errorf("don't know how to handle %T", updateDoc)
}
} | [
"func",
"(",
"r",
"*",
"multiModelRunner",
")",
"mungeUpdate",
"(",
"updateDoc",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"switch",
"doc",
":=",
"updateDoc",
".",
"(",
"type",
")",
"{",
"case",
"bson",
".",
"D",
":",
"return",
"r",
".",
"mungeBsonDUpdate",
"(",
"doc",
")",
"\n",
"case",
"bson",
".",
"M",
":",
"return",
"r",
".",
"mungeBsonMUpdate",
"(",
"doc",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"updateDoc",
")",
"\n",
"}",
"\n",
"}"
] | // mungeUpdate takes the value of an txn.Op Update field and modifies
// it to be multi-model safe, returning the modified document. | [
"mungeUpdate",
"takes",
"the",
"value",
"of",
"an",
"txn",
".",
"Op",
"Update",
"field",
"and",
"modifies",
"it",
"to",
"be",
"multi",
"-",
"model",
"safe",
"returning",
"the",
"modified",
"document",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/txns.go#L169-L178 |
156,185 | juju/juju | payload/context/status-set.go | NewStatusSetCmd | func NewStatusSetCmd(ctx HookContext) (*StatusSetCmd, error) {
return &StatusSetCmd{hookContextFunc: componentHookContext(ctx)}, nil
} | go | func NewStatusSetCmd(ctx HookContext) (*StatusSetCmd, error) {
return &StatusSetCmd{hookContextFunc: componentHookContext(ctx)}, nil
} | [
"func",
"NewStatusSetCmd",
"(",
"ctx",
"HookContext",
")",
"(",
"*",
"StatusSetCmd",
",",
"error",
")",
"{",
"return",
"&",
"StatusSetCmd",
"{",
"hookContextFunc",
":",
"componentHookContext",
"(",
"ctx",
")",
"}",
",",
"nil",
"\n",
"}"
] | // NewStatusSetCmd returns a new StatusSetCmd that wraps the given context. | [
"NewStatusSetCmd",
"returns",
"a",
"new",
"StatusSetCmd",
"that",
"wraps",
"the",
"given",
"context",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/context/status-set.go#L18-L20 |
156,186 | juju/juju | state/linklayerdevices_refs.go | insertLinkLayerDevicesRefsOp | func insertLinkLayerDevicesRefsOp(modelUUID, linkLayerDeviceDocID string) txn.Op {
refsDoc := &linkLayerDevicesRefsDoc{
DocID: linkLayerDeviceDocID,
ModelUUID: modelUUID,
NumChildren: 0,
}
return txn.Op{
C: linkLayerDevicesRefsC,
Id: linkLayerDeviceDocID,
Assert: txn.DocMissing,
Insert: refsDoc,
}
} | go | func insertLinkLayerDevicesRefsOp(modelUUID, linkLayerDeviceDocID string) txn.Op {
refsDoc := &linkLayerDevicesRefsDoc{
DocID: linkLayerDeviceDocID,
ModelUUID: modelUUID,
NumChildren: 0,
}
return txn.Op{
C: linkLayerDevicesRefsC,
Id: linkLayerDeviceDocID,
Assert: txn.DocMissing,
Insert: refsDoc,
}
} | [
"func",
"insertLinkLayerDevicesRefsOp",
"(",
"modelUUID",
",",
"linkLayerDeviceDocID",
"string",
")",
"txn",
".",
"Op",
"{",
"refsDoc",
":=",
"&",
"linkLayerDevicesRefsDoc",
"{",
"DocID",
":",
"linkLayerDeviceDocID",
",",
"ModelUUID",
":",
"modelUUID",
",",
"NumChildren",
":",
"0",
",",
"}",
"\n",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"linkLayerDevicesRefsC",
",",
"Id",
":",
"linkLayerDeviceDocID",
",",
"Assert",
":",
"txn",
".",
"DocMissing",
",",
"Insert",
":",
"refsDoc",
",",
"}",
"\n",
"}"
] | // insertLinkLayerDevicesRefsOp returns an operation to insert a new
// linkLayerDevicesRefsDoc for the given modelUUID and linkLayerDeviceDocID,
// with NumChildren=0. | [
"insertLinkLayerDevicesRefsOp",
"returns",
"an",
"operation",
"to",
"insert",
"a",
"new",
"linkLayerDevicesRefsDoc",
"for",
"the",
"given",
"modelUUID",
"and",
"linkLayerDeviceDocID",
"with",
"NumChildren",
"=",
"0",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_refs.go#L31-L43 |
156,187 | juju/juju | state/linklayerdevices_refs.go | removeLinkLayerDevicesRefsOp | func removeLinkLayerDevicesRefsOp(linkLayerDeviceDocID string) txn.Op {
hasNoChildren := bson.D{{"num-children", 0}}
return txn.Op{
C: linkLayerDevicesRefsC,
Id: linkLayerDeviceDocID,
Assert: hasNoChildren,
Remove: true,
}
} | go | func removeLinkLayerDevicesRefsOp(linkLayerDeviceDocID string) txn.Op {
hasNoChildren := bson.D{{"num-children", 0}}
return txn.Op{
C: linkLayerDevicesRefsC,
Id: linkLayerDeviceDocID,
Assert: hasNoChildren,
Remove: true,
}
} | [
"func",
"removeLinkLayerDevicesRefsOp",
"(",
"linkLayerDeviceDocID",
"string",
")",
"txn",
".",
"Op",
"{",
"hasNoChildren",
":=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"0",
"}",
"}",
"\n",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"linkLayerDevicesRefsC",
",",
"Id",
":",
"linkLayerDeviceDocID",
",",
"Assert",
":",
"hasNoChildren",
",",
"Remove",
":",
"true",
",",
"}",
"\n",
"}"
] | // removeLinkLayerDevicesRefsOp returns an operation to remove the
// linkLayerDevicesRefsDoc for the given linkLayerDeviceDocID, asserting the
// document has NumChildren == 0. | [
"removeLinkLayerDevicesRefsOp",
"returns",
"an",
"operation",
"to",
"remove",
"the",
"linkLayerDevicesRefsDoc",
"for",
"the",
"given",
"linkLayerDeviceDocID",
"asserting",
"the",
"document",
"has",
"NumChildren",
"==",
"0",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_refs.go#L48-L56 |
156,188 | juju/juju | state/linklayerdevices_refs.go | getParentDeviceNumChildrenRefs | func getParentDeviceNumChildrenRefs(st *State, linkLayerDeviceDocID string) (int, error) {
devicesRefs, closer := st.db().GetCollection(linkLayerDevicesRefsC)
defer closer()
var doc linkLayerDevicesRefsDoc
err := devicesRefs.FindId(linkLayerDeviceDocID).One(&doc)
if err == mgo.ErrNotFound {
return -1, nil
} else if err != nil {
return 0, errors.Trace(err)
}
return doc.NumChildren, nil
} | go | func getParentDeviceNumChildrenRefs(st *State, linkLayerDeviceDocID string) (int, error) {
devicesRefs, closer := st.db().GetCollection(linkLayerDevicesRefsC)
defer closer()
var doc linkLayerDevicesRefsDoc
err := devicesRefs.FindId(linkLayerDeviceDocID).One(&doc)
if err == mgo.ErrNotFound {
return -1, nil
} else if err != nil {
return 0, errors.Trace(err)
}
return doc.NumChildren, nil
} | [
"func",
"getParentDeviceNumChildrenRefs",
"(",
"st",
"*",
"State",
",",
"linkLayerDeviceDocID",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"devicesRefs",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"linkLayerDevicesRefsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"doc",
"linkLayerDevicesRefsDoc",
"\n",
"err",
":=",
"devicesRefs",
".",
"FindId",
"(",
"linkLayerDeviceDocID",
")",
".",
"One",
"(",
"&",
"doc",
")",
"\n",
"if",
"err",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"-",
"1",
",",
"nil",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"doc",
".",
"NumChildren",
",",
"nil",
"\n",
"}"
] | // getParentDeviceNumChildrenRefs returns the NumChildren value for the given
// linkLayerDeviceDocID. If the linkLayerDevicesRefsDoc is missing, no error and
// -1 children are returned. | [
"getParentDeviceNumChildrenRefs",
"returns",
"the",
"NumChildren",
"value",
"for",
"the",
"given",
"linkLayerDeviceDocID",
".",
"If",
"the",
"linkLayerDevicesRefsDoc",
"is",
"missing",
"no",
"error",
"and",
"-",
"1",
"children",
"are",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_refs.go#L61-L73 |
156,189 | juju/juju | state/linklayerdevices_refs.go | incrementDeviceNumChildrenOp | func incrementDeviceNumChildrenOp(linkLayerDeviceDocID string) txn.Op {
hasZeroOrMoreChildren := bson.D{{"num-children", bson.D{{"$gte", 0}}}}
return txn.Op{
C: linkLayerDevicesRefsC,
Id: linkLayerDeviceDocID,
Assert: hasZeroOrMoreChildren,
Update: bson.D{{"$inc", bson.D{{"num-children", 1}}}},
}
} | go | func incrementDeviceNumChildrenOp(linkLayerDeviceDocID string) txn.Op {
hasZeroOrMoreChildren := bson.D{{"num-children", bson.D{{"$gte", 0}}}}
return txn.Op{
C: linkLayerDevicesRefsC,
Id: linkLayerDeviceDocID,
Assert: hasZeroOrMoreChildren,
Update: bson.D{{"$inc", bson.D{{"num-children", 1}}}},
}
} | [
"func",
"incrementDeviceNumChildrenOp",
"(",
"linkLayerDeviceDocID",
"string",
")",
"txn",
".",
"Op",
"{",
"hasZeroOrMoreChildren",
":=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"0",
"}",
"}",
"}",
"}",
"\n",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"linkLayerDevicesRefsC",
",",
"Id",
":",
"linkLayerDeviceDocID",
",",
"Assert",
":",
"hasZeroOrMoreChildren",
",",
"Update",
":",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"1",
"}",
"}",
"}",
"}",
",",
"}",
"\n",
"}"
] | // incrementDeviceNumChildrenOp returns an operation that increments the
// NumChildren value of the linkLayerDevicesRefsDoc matching the given
// linkLayerDeviceDocID, and asserting the document has NumChildren >= 0. | [
"incrementDeviceNumChildrenOp",
"returns",
"an",
"operation",
"that",
"increments",
"the",
"NumChildren",
"value",
"of",
"the",
"linkLayerDevicesRefsDoc",
"matching",
"the",
"given",
"linkLayerDeviceDocID",
"and",
"asserting",
"the",
"document",
"has",
"NumChildren",
">",
"=",
"0",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_refs.go#L78-L86 |
156,190 | juju/juju | state/linklayerdevices_refs.go | decrementDeviceNumChildrenOp | func decrementDeviceNumChildrenOp(linkLayerDeviceDocID string) txn.Op {
hasAtLeastOneMoreChild := bson.D{{"num-children", bson.D{{"$gte", 1}}}}
return txn.Op{
C: linkLayerDevicesRefsC,
Id: linkLayerDeviceDocID,
Assert: hasAtLeastOneMoreChild,
Update: bson.D{{"$inc", bson.D{{"num-children", -1}}}},
}
} | go | func decrementDeviceNumChildrenOp(linkLayerDeviceDocID string) txn.Op {
hasAtLeastOneMoreChild := bson.D{{"num-children", bson.D{{"$gte", 1}}}}
return txn.Op{
C: linkLayerDevicesRefsC,
Id: linkLayerDeviceDocID,
Assert: hasAtLeastOneMoreChild,
Update: bson.D{{"$inc", bson.D{{"num-children", -1}}}},
}
} | [
"func",
"decrementDeviceNumChildrenOp",
"(",
"linkLayerDeviceDocID",
"string",
")",
"txn",
".",
"Op",
"{",
"hasAtLeastOneMoreChild",
":=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"1",
"}",
"}",
"}",
"}",
"\n",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"linkLayerDevicesRefsC",
",",
"Id",
":",
"linkLayerDeviceDocID",
",",
"Assert",
":",
"hasAtLeastOneMoreChild",
",",
"Update",
":",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"-",
"1",
"}",
"}",
"}",
"}",
",",
"}",
"\n",
"}"
] | // decrementDeviceNumChildrenOp returns an operation that decrements the
// NumChildren value of the linkLayerDevicesRefsDoc matching the given
// linkLayerDeviceDocID, and asserting the document has NumChildren >= 1. | [
"decrementDeviceNumChildrenOp",
"returns",
"an",
"operation",
"that",
"decrements",
"the",
"NumChildren",
"value",
"of",
"the",
"linkLayerDevicesRefsDoc",
"matching",
"the",
"given",
"linkLayerDeviceDocID",
"and",
"asserting",
"the",
"document",
"has",
"NumChildren",
">",
"=",
"1",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_refs.go#L91-L99 |
156,191 | juju/juju | api/applicationoffers/client.go | Offer | func (c *Client) Offer(modelUUID, application string, endpoints []string, offerName string, desc string) ([]params.ErrorResult, error) {
// TODO(wallyworld) - support endpoint aliases
ep := make(map[string]string)
for _, name := range endpoints {
ep[name] = name
}
offers := []params.AddApplicationOffer{
{
ModelTag: names.NewModelTag(modelUUID).String(),
ApplicationName: application,
ApplicationDescription: desc,
Endpoints: ep,
OfferName: offerName,
},
}
out := params.ErrorResults{}
if err := c.facade.FacadeCall("Offer", params.AddApplicationOffers{Offers: offers}, &out); err != nil {
return nil, errors.Trace(err)
}
return out.Results, nil
} | go | func (c *Client) Offer(modelUUID, application string, endpoints []string, offerName string, desc string) ([]params.ErrorResult, error) {
// TODO(wallyworld) - support endpoint aliases
ep := make(map[string]string)
for _, name := range endpoints {
ep[name] = name
}
offers := []params.AddApplicationOffer{
{
ModelTag: names.NewModelTag(modelUUID).String(),
ApplicationName: application,
ApplicationDescription: desc,
Endpoints: ep,
OfferName: offerName,
},
}
out := params.ErrorResults{}
if err := c.facade.FacadeCall("Offer", params.AddApplicationOffers{Offers: offers}, &out); err != nil {
return nil, errors.Trace(err)
}
return out.Results, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Offer",
"(",
"modelUUID",
",",
"application",
"string",
",",
"endpoints",
"[",
"]",
"string",
",",
"offerName",
"string",
",",
"desc",
"string",
")",
"(",
"[",
"]",
"params",
".",
"ErrorResult",
",",
"error",
")",
"{",
"// TODO(wallyworld) - support endpoint aliases",
"ep",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"endpoints",
"{",
"ep",
"[",
"name",
"]",
"=",
"name",
"\n",
"}",
"\n",
"offers",
":=",
"[",
"]",
"params",
".",
"AddApplicationOffer",
"{",
"{",
"ModelTag",
":",
"names",
".",
"NewModelTag",
"(",
"modelUUID",
")",
".",
"String",
"(",
")",
",",
"ApplicationName",
":",
"application",
",",
"ApplicationDescription",
":",
"desc",
",",
"Endpoints",
":",
"ep",
",",
"OfferName",
":",
"offerName",
",",
"}",
",",
"}",
"\n",
"out",
":=",
"params",
".",
"ErrorResults",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"params",
".",
"AddApplicationOffers",
"{",
"Offers",
":",
"offers",
"}",
",",
"&",
"out",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"out",
".",
"Results",
",",
"nil",
"\n",
"}"
] | // Offer prepares application's endpoints for consumption. | [
"Offer",
"prepares",
"application",
"s",
"endpoints",
"for",
"consumption",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/applicationoffers/client.go#L34-L54 |
156,192 | juju/juju | api/applicationoffers/client.go | ListOffers | func (c *Client) ListOffers(filters ...crossmodel.ApplicationOfferFilter) ([]*crossmodel.ApplicationOfferDetails, error) {
var paramsFilter params.OfferFilters
for _, f := range filters {
filterTerm := params.OfferFilter{
OwnerName: f.OwnerName,
ModelName: f.ModelName,
OfferName: f.OfferName,
ApplicationName: f.ApplicationName,
Endpoints: make([]params.EndpointFilterAttributes, len(f.Endpoints)),
AllowedConsumerTags: make([]string, len(f.AllowedConsumers)),
ConnectedUserTags: make([]string, len(f.ConnectedUsers)),
}
for i, ep := range f.Endpoints {
filterTerm.Endpoints[i].Name = ep.Name
filterTerm.Endpoints[i].Interface = ep.Interface
filterTerm.Endpoints[i].Role = ep.Role
}
for i, u := range f.AllowedConsumers {
filterTerm.AllowedConsumerTags[i] = names.NewUserTag(u).String()
}
for i, u := range f.ConnectedUsers {
filterTerm.ConnectedUserTags[i] = names.NewUserTag(u).String()
}
paramsFilter.Filters = append(paramsFilter.Filters, filterTerm)
}
offers := params.QueryApplicationOffersResults{}
err := c.facade.FacadeCall("ListApplicationOffers", paramsFilter, &offers)
if err != nil {
return nil, errors.Trace(err)
}
return convertOffersResultsToModel(offers.Results)
} | go | func (c *Client) ListOffers(filters ...crossmodel.ApplicationOfferFilter) ([]*crossmodel.ApplicationOfferDetails, error) {
var paramsFilter params.OfferFilters
for _, f := range filters {
filterTerm := params.OfferFilter{
OwnerName: f.OwnerName,
ModelName: f.ModelName,
OfferName: f.OfferName,
ApplicationName: f.ApplicationName,
Endpoints: make([]params.EndpointFilterAttributes, len(f.Endpoints)),
AllowedConsumerTags: make([]string, len(f.AllowedConsumers)),
ConnectedUserTags: make([]string, len(f.ConnectedUsers)),
}
for i, ep := range f.Endpoints {
filterTerm.Endpoints[i].Name = ep.Name
filterTerm.Endpoints[i].Interface = ep.Interface
filterTerm.Endpoints[i].Role = ep.Role
}
for i, u := range f.AllowedConsumers {
filterTerm.AllowedConsumerTags[i] = names.NewUserTag(u).String()
}
for i, u := range f.ConnectedUsers {
filterTerm.ConnectedUserTags[i] = names.NewUserTag(u).String()
}
paramsFilter.Filters = append(paramsFilter.Filters, filterTerm)
}
offers := params.QueryApplicationOffersResults{}
err := c.facade.FacadeCall("ListApplicationOffers", paramsFilter, &offers)
if err != nil {
return nil, errors.Trace(err)
}
return convertOffersResultsToModel(offers.Results)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ListOffers",
"(",
"filters",
"...",
"crossmodel",
".",
"ApplicationOfferFilter",
")",
"(",
"[",
"]",
"*",
"crossmodel",
".",
"ApplicationOfferDetails",
",",
"error",
")",
"{",
"var",
"paramsFilter",
"params",
".",
"OfferFilters",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"filters",
"{",
"filterTerm",
":=",
"params",
".",
"OfferFilter",
"{",
"OwnerName",
":",
"f",
".",
"OwnerName",
",",
"ModelName",
":",
"f",
".",
"ModelName",
",",
"OfferName",
":",
"f",
".",
"OfferName",
",",
"ApplicationName",
":",
"f",
".",
"ApplicationName",
",",
"Endpoints",
":",
"make",
"(",
"[",
"]",
"params",
".",
"EndpointFilterAttributes",
",",
"len",
"(",
"f",
".",
"Endpoints",
")",
")",
",",
"AllowedConsumerTags",
":",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"f",
".",
"AllowedConsumers",
")",
")",
",",
"ConnectedUserTags",
":",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"f",
".",
"ConnectedUsers",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"ep",
":=",
"range",
"f",
".",
"Endpoints",
"{",
"filterTerm",
".",
"Endpoints",
"[",
"i",
"]",
".",
"Name",
"=",
"ep",
".",
"Name",
"\n",
"filterTerm",
".",
"Endpoints",
"[",
"i",
"]",
".",
"Interface",
"=",
"ep",
".",
"Interface",
"\n",
"filterTerm",
".",
"Endpoints",
"[",
"i",
"]",
".",
"Role",
"=",
"ep",
".",
"Role",
"\n",
"}",
"\n",
"for",
"i",
",",
"u",
":=",
"range",
"f",
".",
"AllowedConsumers",
"{",
"filterTerm",
".",
"AllowedConsumerTags",
"[",
"i",
"]",
"=",
"names",
".",
"NewUserTag",
"(",
"u",
")",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"u",
":=",
"range",
"f",
".",
"ConnectedUsers",
"{",
"filterTerm",
".",
"ConnectedUserTags",
"[",
"i",
"]",
"=",
"names",
".",
"NewUserTag",
"(",
"u",
")",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"paramsFilter",
".",
"Filters",
"=",
"append",
"(",
"paramsFilter",
".",
"Filters",
",",
"filterTerm",
")",
"\n",
"}",
"\n\n",
"offers",
":=",
"params",
".",
"QueryApplicationOffersResults",
"{",
"}",
"\n",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"paramsFilter",
",",
"&",
"offers",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"convertOffersResultsToModel",
"(",
"offers",
".",
"Results",
")",
"\n",
"}"
] | // ListOffers gets all remote applications that have been offered from this Juju model.
// Each returned application satisfies at least one of the the specified filters. | [
"ListOffers",
"gets",
"all",
"remote",
"applications",
"that",
"have",
"been",
"offered",
"from",
"this",
"Juju",
"model",
".",
"Each",
"returned",
"application",
"satisfies",
"at",
"least",
"one",
"of",
"the",
"the",
"specified",
"filters",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/applicationoffers/client.go#L58-L90 |
156,193 | juju/juju | api/applicationoffers/client.go | GrantOffer | func (c *Client) GrantOffer(user, access string, offerURLs ...string) error {
return c.modifyOfferUser(params.GrantOfferAccess, user, access, offerURLs)
} | go | func (c *Client) GrantOffer(user, access string, offerURLs ...string) error {
return c.modifyOfferUser(params.GrantOfferAccess, user, access, offerURLs)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GrantOffer",
"(",
"user",
",",
"access",
"string",
",",
"offerURLs",
"...",
"string",
")",
"error",
"{",
"return",
"c",
".",
"modifyOfferUser",
"(",
"params",
".",
"GrantOfferAccess",
",",
"user",
",",
"access",
",",
"offerURLs",
")",
"\n",
"}"
] | // GrantOffer grants a user access to the specified offers. | [
"GrantOffer",
"grants",
"a",
"user",
"access",
"to",
"the",
"specified",
"offers",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/applicationoffers/client.go#L147-L149 |
156,194 | juju/juju | api/applicationoffers/client.go | RevokeOffer | func (c *Client) RevokeOffer(user, access string, offerURLs ...string) error {
return c.modifyOfferUser(params.RevokeOfferAccess, user, access, offerURLs)
} | go | func (c *Client) RevokeOffer(user, access string, offerURLs ...string) error {
return c.modifyOfferUser(params.RevokeOfferAccess, user, access, offerURLs)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"RevokeOffer",
"(",
"user",
",",
"access",
"string",
",",
"offerURLs",
"...",
"string",
")",
"error",
"{",
"return",
"c",
".",
"modifyOfferUser",
"(",
"params",
".",
"RevokeOfferAccess",
",",
"user",
",",
"access",
",",
"offerURLs",
")",
"\n",
"}"
] | // RevokeOffer revokes a user's access to the specified offers. | [
"RevokeOffer",
"revokes",
"a",
"user",
"s",
"access",
"to",
"the",
"specified",
"offers",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/applicationoffers/client.go#L152-L154 |
156,195 | juju/juju | api/applicationoffers/client.go | ApplicationOffer | func (c *Client) ApplicationOffer(urlStr string) (*crossmodel.ApplicationOfferDetails, error) {
url, err := crossmodel.ParseOfferURL(urlStr)
if err != nil {
return nil, errors.Trace(err)
}
if url.Source != "" {
return nil, errors.NotSupportedf("query for non-local application offers")
}
found := params.ApplicationOffersResults{}
err = c.facade.FacadeCall("ApplicationOffers", params.OfferURLs{[]string{urlStr}}, &found)
if err != nil {
return nil, errors.Trace(err)
}
result := found.Results
if len(result) != 1 {
return nil, errors.Errorf("expected to find one result for url %q but found %d", url, len(result))
}
theOne := result[0]
if theOne.Error != nil {
return nil, errors.Trace(theOne.Error)
}
return offerParamsToDetails(*theOne.Result)
} | go | func (c *Client) ApplicationOffer(urlStr string) (*crossmodel.ApplicationOfferDetails, error) {
url, err := crossmodel.ParseOfferURL(urlStr)
if err != nil {
return nil, errors.Trace(err)
}
if url.Source != "" {
return nil, errors.NotSupportedf("query for non-local application offers")
}
found := params.ApplicationOffersResults{}
err = c.facade.FacadeCall("ApplicationOffers", params.OfferURLs{[]string{urlStr}}, &found)
if err != nil {
return nil, errors.Trace(err)
}
result := found.Results
if len(result) != 1 {
return nil, errors.Errorf("expected to find one result for url %q but found %d", url, len(result))
}
theOne := result[0]
if theOne.Error != nil {
return nil, errors.Trace(theOne.Error)
}
return offerParamsToDetails(*theOne.Result)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ApplicationOffer",
"(",
"urlStr",
"string",
")",
"(",
"*",
"crossmodel",
".",
"ApplicationOfferDetails",
",",
"error",
")",
"{",
"url",
",",
"err",
":=",
"crossmodel",
".",
"ParseOfferURL",
"(",
"urlStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"url",
".",
"Source",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"NotSupportedf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"found",
":=",
"params",
".",
"ApplicationOffersResults",
"{",
"}",
"\n\n",
"err",
"=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"params",
".",
"OfferURLs",
"{",
"[",
"]",
"string",
"{",
"urlStr",
"}",
"}",
",",
"&",
"found",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"result",
":=",
"found",
".",
"Results",
"\n",
"if",
"len",
"(",
"result",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"url",
",",
"len",
"(",
"result",
")",
")",
"\n",
"}",
"\n\n",
"theOne",
":=",
"result",
"[",
"0",
"]",
"\n",
"if",
"theOne",
".",
"Error",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"theOne",
".",
"Error",
")",
"\n",
"}",
"\n",
"return",
"offerParamsToDetails",
"(",
"*",
"theOne",
".",
"Result",
")",
"\n",
"}"
] | // ApplicationOffer returns offered remote application details for a given URL. | [
"ApplicationOffer",
"returns",
"offered",
"remote",
"application",
"details",
"for",
"a",
"given",
"URL",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/applicationoffers/client.go#L196-L223 |
156,196 | juju/juju | api/applicationoffers/client.go | FindApplicationOffers | func (c *Client) FindApplicationOffers(filters ...crossmodel.ApplicationOfferFilter) ([]*crossmodel.ApplicationOfferDetails, error) {
// We need at least one filter. The default filter will list all local applications.
if len(filters) == 0 {
return nil, errors.New("at least one filter must be specified")
}
var paramsFilter params.OfferFilters
for _, f := range filters {
filterTerm := params.OfferFilter{
OfferName: f.OfferName,
ModelName: f.ModelName,
OwnerName: f.OwnerName,
}
filterTerm.Endpoints = make([]params.EndpointFilterAttributes, len(f.Endpoints))
for i, ep := range f.Endpoints {
filterTerm.Endpoints[i].Name = ep.Name
filterTerm.Endpoints[i].Interface = ep.Interface
filterTerm.Endpoints[i].Role = ep.Role
}
paramsFilter.Filters = append(paramsFilter.Filters, filterTerm)
}
offers := params.QueryApplicationOffersResults{}
err := c.facade.FacadeCall("FindApplicationOffers", paramsFilter, &offers)
if err != nil {
return nil, errors.Trace(err)
}
return convertOffersResultsToModel(offers.Results)
} | go | func (c *Client) FindApplicationOffers(filters ...crossmodel.ApplicationOfferFilter) ([]*crossmodel.ApplicationOfferDetails, error) {
// We need at least one filter. The default filter will list all local applications.
if len(filters) == 0 {
return nil, errors.New("at least one filter must be specified")
}
var paramsFilter params.OfferFilters
for _, f := range filters {
filterTerm := params.OfferFilter{
OfferName: f.OfferName,
ModelName: f.ModelName,
OwnerName: f.OwnerName,
}
filterTerm.Endpoints = make([]params.EndpointFilterAttributes, len(f.Endpoints))
for i, ep := range f.Endpoints {
filterTerm.Endpoints[i].Name = ep.Name
filterTerm.Endpoints[i].Interface = ep.Interface
filterTerm.Endpoints[i].Role = ep.Role
}
paramsFilter.Filters = append(paramsFilter.Filters, filterTerm)
}
offers := params.QueryApplicationOffersResults{}
err := c.facade.FacadeCall("FindApplicationOffers", paramsFilter, &offers)
if err != nil {
return nil, errors.Trace(err)
}
return convertOffersResultsToModel(offers.Results)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"FindApplicationOffers",
"(",
"filters",
"...",
"crossmodel",
".",
"ApplicationOfferFilter",
")",
"(",
"[",
"]",
"*",
"crossmodel",
".",
"ApplicationOfferDetails",
",",
"error",
")",
"{",
"// We need at least one filter. The default filter will list all local applications.",
"if",
"len",
"(",
"filters",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"var",
"paramsFilter",
"params",
".",
"OfferFilters",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"filters",
"{",
"filterTerm",
":=",
"params",
".",
"OfferFilter",
"{",
"OfferName",
":",
"f",
".",
"OfferName",
",",
"ModelName",
":",
"f",
".",
"ModelName",
",",
"OwnerName",
":",
"f",
".",
"OwnerName",
",",
"}",
"\n",
"filterTerm",
".",
"Endpoints",
"=",
"make",
"(",
"[",
"]",
"params",
".",
"EndpointFilterAttributes",
",",
"len",
"(",
"f",
".",
"Endpoints",
")",
")",
"\n",
"for",
"i",
",",
"ep",
":=",
"range",
"f",
".",
"Endpoints",
"{",
"filterTerm",
".",
"Endpoints",
"[",
"i",
"]",
".",
"Name",
"=",
"ep",
".",
"Name",
"\n",
"filterTerm",
".",
"Endpoints",
"[",
"i",
"]",
".",
"Interface",
"=",
"ep",
".",
"Interface",
"\n",
"filterTerm",
".",
"Endpoints",
"[",
"i",
"]",
".",
"Role",
"=",
"ep",
".",
"Role",
"\n",
"}",
"\n",
"paramsFilter",
".",
"Filters",
"=",
"append",
"(",
"paramsFilter",
".",
"Filters",
",",
"filterTerm",
")",
"\n",
"}",
"\n\n",
"offers",
":=",
"params",
".",
"QueryApplicationOffersResults",
"{",
"}",
"\n",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"paramsFilter",
",",
"&",
"offers",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"convertOffersResultsToModel",
"(",
"offers",
".",
"Results",
")",
"\n",
"}"
] | // FindApplicationOffers returns all application offers matching the supplied filter. | [
"FindApplicationOffers",
"returns",
"all",
"application",
"offers",
"matching",
"the",
"supplied",
"filter",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/applicationoffers/client.go#L226-L253 |
156,197 | juju/juju | api/applicationoffers/client.go | GetConsumeDetails | func (c *Client) GetConsumeDetails(urlStr string) (params.ConsumeOfferDetails, error) {
url, err := crossmodel.ParseOfferURL(urlStr)
if err != nil {
return params.ConsumeOfferDetails{}, errors.Trace(err)
}
if url.Source != "" {
return params.ConsumeOfferDetails{}, errors.NotSupportedf("query for application offers on another controller")
}
found := params.ConsumeOfferDetailsResults{}
err = c.facade.FacadeCall("GetConsumeDetails", params.OfferURLs{[]string{urlStr}}, &found)
if err != nil {
return params.ConsumeOfferDetails{}, errors.Trace(err)
}
result := found.Results
if len(result) != 1 {
return params.ConsumeOfferDetails{}, errors.Errorf("expected to find one result for url %q but found %d", url, len(result))
}
theOne := result[0]
if theOne.Error != nil {
return params.ConsumeOfferDetails{}, errors.Trace(theOne.Error)
}
return params.ConsumeOfferDetails{
Offer: theOne.Offer,
Macaroon: theOne.Macaroon,
ControllerInfo: theOne.ControllerInfo,
}, nil
} | go | func (c *Client) GetConsumeDetails(urlStr string) (params.ConsumeOfferDetails, error) {
url, err := crossmodel.ParseOfferURL(urlStr)
if err != nil {
return params.ConsumeOfferDetails{}, errors.Trace(err)
}
if url.Source != "" {
return params.ConsumeOfferDetails{}, errors.NotSupportedf("query for application offers on another controller")
}
found := params.ConsumeOfferDetailsResults{}
err = c.facade.FacadeCall("GetConsumeDetails", params.OfferURLs{[]string{urlStr}}, &found)
if err != nil {
return params.ConsumeOfferDetails{}, errors.Trace(err)
}
result := found.Results
if len(result) != 1 {
return params.ConsumeOfferDetails{}, errors.Errorf("expected to find one result for url %q but found %d", url, len(result))
}
theOne := result[0]
if theOne.Error != nil {
return params.ConsumeOfferDetails{}, errors.Trace(theOne.Error)
}
return params.ConsumeOfferDetails{
Offer: theOne.Offer,
Macaroon: theOne.Macaroon,
ControllerInfo: theOne.ControllerInfo,
}, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetConsumeDetails",
"(",
"urlStr",
"string",
")",
"(",
"params",
".",
"ConsumeOfferDetails",
",",
"error",
")",
"{",
"url",
",",
"err",
":=",
"crossmodel",
".",
"ParseOfferURL",
"(",
"urlStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ConsumeOfferDetails",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"url",
".",
"Source",
"!=",
"\"",
"\"",
"{",
"return",
"params",
".",
"ConsumeOfferDetails",
"{",
"}",
",",
"errors",
".",
"NotSupportedf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"found",
":=",
"params",
".",
"ConsumeOfferDetailsResults",
"{",
"}",
"\n\n",
"err",
"=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"params",
".",
"OfferURLs",
"{",
"[",
"]",
"string",
"{",
"urlStr",
"}",
"}",
",",
"&",
"found",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"params",
".",
"ConsumeOfferDetails",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"result",
":=",
"found",
".",
"Results",
"\n",
"if",
"len",
"(",
"result",
")",
"!=",
"1",
"{",
"return",
"params",
".",
"ConsumeOfferDetails",
"{",
"}",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"url",
",",
"len",
"(",
"result",
")",
")",
"\n",
"}",
"\n\n",
"theOne",
":=",
"result",
"[",
"0",
"]",
"\n",
"if",
"theOne",
".",
"Error",
"!=",
"nil",
"{",
"return",
"params",
".",
"ConsumeOfferDetails",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"theOne",
".",
"Error",
")",
"\n",
"}",
"\n",
"return",
"params",
".",
"ConsumeOfferDetails",
"{",
"Offer",
":",
"theOne",
".",
"Offer",
",",
"Macaroon",
":",
"theOne",
".",
"Macaroon",
",",
"ControllerInfo",
":",
"theOne",
".",
"ControllerInfo",
",",
"}",
",",
"nil",
"\n",
"}"
] | // GetConsumeDetails returns details necessary to consue an offer at a given URL. | [
"GetConsumeDetails",
"returns",
"details",
"necessary",
"to",
"consue",
"an",
"offer",
"at",
"a",
"given",
"URL",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/applicationoffers/client.go#L256-L287 |
156,198 | juju/juju | api/applicationoffers/client.go | DestroyOffers | func (c *Client) DestroyOffers(force bool, offerURLs ...string) error {
if len(offerURLs) == 0 {
return nil
}
if force {
if bestVer := c.BestAPIVersion(); bestVer < 2 {
return errors.NotImplementedf("DestroyOffers() with force (need v2+, have v%d)", bestVer)
}
}
args := params.DestroyApplicationOffers{
Force: force,
OfferURLs: make([]string, len(offerURLs)),
}
for i, url := range offerURLs {
if _, err := crossmodel.ParseOfferURL(url); err != nil {
return errors.Trace(err)
}
args.OfferURLs[i] = url
}
var result params.ErrorResults
err := c.facade.FacadeCall("DestroyOffers", args, &result)
if err != nil {
return errors.Trace(err)
}
if len(result.Results) != len(args.OfferURLs) {
return errors.Errorf("expected %d results, got %d", len(args.OfferURLs), len(result.Results))
}
return result.Combine()
} | go | func (c *Client) DestroyOffers(force bool, offerURLs ...string) error {
if len(offerURLs) == 0 {
return nil
}
if force {
if bestVer := c.BestAPIVersion(); bestVer < 2 {
return errors.NotImplementedf("DestroyOffers() with force (need v2+, have v%d)", bestVer)
}
}
args := params.DestroyApplicationOffers{
Force: force,
OfferURLs: make([]string, len(offerURLs)),
}
for i, url := range offerURLs {
if _, err := crossmodel.ParseOfferURL(url); err != nil {
return errors.Trace(err)
}
args.OfferURLs[i] = url
}
var result params.ErrorResults
err := c.facade.FacadeCall("DestroyOffers", args, &result)
if err != nil {
return errors.Trace(err)
}
if len(result.Results) != len(args.OfferURLs) {
return errors.Errorf("expected %d results, got %d", len(args.OfferURLs), len(result.Results))
}
return result.Combine()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"DestroyOffers",
"(",
"force",
"bool",
",",
"offerURLs",
"...",
"string",
")",
"error",
"{",
"if",
"len",
"(",
"offerURLs",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"force",
"{",
"if",
"bestVer",
":=",
"c",
".",
"BestAPIVersion",
"(",
")",
";",
"bestVer",
"<",
"2",
"{",
"return",
"errors",
".",
"NotImplementedf",
"(",
"\"",
"\"",
",",
"bestVer",
")",
"\n",
"}",
"\n",
"}",
"\n",
"args",
":=",
"params",
".",
"DestroyApplicationOffers",
"{",
"Force",
":",
"force",
",",
"OfferURLs",
":",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"offerURLs",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"url",
":=",
"range",
"offerURLs",
"{",
"if",
"_",
",",
"err",
":=",
"crossmodel",
".",
"ParseOfferURL",
"(",
"url",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"args",
".",
"OfferURLs",
"[",
"i",
"]",
"=",
"url",
"\n",
"}",
"\n\n",
"var",
"result",
"params",
".",
"ErrorResults",
"\n",
"err",
":=",
"c",
".",
"facade",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"&",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"result",
".",
"Results",
")",
"!=",
"len",
"(",
"args",
".",
"OfferURLs",
")",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"args",
".",
"OfferURLs",
")",
",",
"len",
"(",
"result",
".",
"Results",
")",
")",
"\n",
"}",
"\n",
"return",
"result",
".",
"Combine",
"(",
")",
"\n",
"}"
] | // DestroyOffers removes the specified application offers. | [
"DestroyOffers",
"removes",
"the",
"specified",
"application",
"offers",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/applicationoffers/client.go#L290-L319 |
156,199 | juju/juju | api/leadership/client.go | NewClient | func NewClient(caller base.APICaller) leadership.Claimer {
return &client{base.NewFacadeCaller(caller, "LeadershipService")}
} | go | func NewClient(caller base.APICaller) leadership.Claimer {
return &client{base.NewFacadeCaller(caller, "LeadershipService")}
} | [
"func",
"NewClient",
"(",
"caller",
"base",
".",
"APICaller",
")",
"leadership",
".",
"Claimer",
"{",
"return",
"&",
"client",
"{",
"base",
".",
"NewFacadeCaller",
"(",
"caller",
",",
"\"",
"\"",
")",
"}",
"\n",
"}"
] | // NewClient returns a new leadership.Claimer backed by the supplied api caller. | [
"NewClient",
"returns",
"a",
"new",
"leadership",
".",
"Claimer",
"backed",
"by",
"the",
"supplied",
"api",
"caller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/leadership/client.go#L26-L28 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.