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
|
---|---|---|---|---|---|---|---|---|---|---|---|
154,400 | juju/juju | api/migrationtarget/client.go | Import | func (c *Client) Import(bytes []byte) error {
serialized := params.SerializedModel{Bytes: bytes}
return c.caller.FacadeCall("Import", serialized, nil)
} | go | func (c *Client) Import(bytes []byte) error {
serialized := params.SerializedModel{Bytes: bytes}
return c.caller.FacadeCall("Import", serialized, nil)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Import",
"(",
"bytes",
"[",
"]",
"byte",
")",
"error",
"{",
"serialized",
":=",
"params",
".",
"SerializedModel",
"{",
"Bytes",
":",
"bytes",
"}",
"\n",
"return",
"c",
".",
"caller",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"serialized",
",",
"nil",
")",
"\n",
"}"
] | // Import takes a serialized model and imports it into the target
// controller. | [
"Import",
"takes",
"a",
"serialized",
"model",
"and",
"imports",
"it",
"into",
"the",
"target",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/migrationtarget/client.go#L58-L61 |
154,401 | juju/juju | api/migrationtarget/client.go | Abort | func (c *Client) Abort(modelUUID string) error {
args := params.ModelArgs{ModelTag: names.NewModelTag(modelUUID).String()}
return c.caller.FacadeCall("Abort", args, nil)
} | go | func (c *Client) Abort(modelUUID string) error {
args := params.ModelArgs{ModelTag: names.NewModelTag(modelUUID).String()}
return c.caller.FacadeCall("Abort", args, nil)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Abort",
"(",
"modelUUID",
"string",
")",
"error",
"{",
"args",
":=",
"params",
".",
"ModelArgs",
"{",
"ModelTag",
":",
"names",
".",
"NewModelTag",
"(",
"modelUUID",
")",
".",
"String",
"(",
")",
"}",
"\n",
"return",
"c",
".",
"caller",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"args",
",",
"nil",
")",
"\n",
"}"
] | // Abort removes all data relating to a previously imported model. | [
"Abort",
"removes",
"all",
"data",
"relating",
"to",
"a",
"previously",
"imported",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/migrationtarget/client.go#L64-L67 |
154,402 | juju/juju | api/migrationtarget/client.go | UploadTools | func (c *Client) UploadTools(modelUUID string, r io.ReadSeeker, vers version.Binary, additionalSeries ...string) (tools.List, error) {
endpoint := fmt.Sprintf("/migrate/tools?binaryVersion=%s&series=%s", vers, strings.Join(additionalSeries, ","))
contentType := "application/x-tar-gz"
var resp params.ToolsResult
if err := c.httpPost(modelUUID, r, endpoint, contentType, &resp); err != nil {
return nil, errors.Trace(err)
}
return resp.ToolsList, nil
} | go | func (c *Client) UploadTools(modelUUID string, r io.ReadSeeker, vers version.Binary, additionalSeries ...string) (tools.List, error) {
endpoint := fmt.Sprintf("/migrate/tools?binaryVersion=%s&series=%s", vers, strings.Join(additionalSeries, ","))
contentType := "application/x-tar-gz"
var resp params.ToolsResult
if err := c.httpPost(modelUUID, r, endpoint, contentType, &resp); err != nil {
return nil, errors.Trace(err)
}
return resp.ToolsList, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"UploadTools",
"(",
"modelUUID",
"string",
",",
"r",
"io",
".",
"ReadSeeker",
",",
"vers",
"version",
".",
"Binary",
",",
"additionalSeries",
"...",
"string",
")",
"(",
"tools",
".",
"List",
",",
"error",
")",
"{",
"endpoint",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"vers",
",",
"strings",
".",
"Join",
"(",
"additionalSeries",
",",
"\"",
"\"",
")",
")",
"\n",
"contentType",
":=",
"\"",
"\"",
"\n",
"var",
"resp",
"params",
".",
"ToolsResult",
"\n",
"if",
"err",
":=",
"c",
".",
"httpPost",
"(",
"modelUUID",
",",
"r",
",",
"endpoint",
",",
"contentType",
",",
"&",
"resp",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"resp",
".",
"ToolsList",
",",
"nil",
"\n",
"}"
] | // UploadTools uploads tools at the specified location to the API server over HTTPS
// for the specified model. | [
"UploadTools",
"uploads",
"tools",
"at",
"the",
"specified",
"location",
"to",
"the",
"API",
"server",
"over",
"HTTPS",
"for",
"the",
"specified",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/migrationtarget/client.go#L100-L108 |
154,403 | juju/juju | api/migrationtarget/client.go | UploadResource | func (c *Client) UploadResource(modelUUID string, res resource.Resource, r io.ReadSeeker) error {
args := makeResourceArgs(res)
args.Add("application", res.ApplicationID)
err := c.resourcePost(modelUUID, args, r)
return errors.Trace(err)
} | go | func (c *Client) UploadResource(modelUUID string, res resource.Resource, r io.ReadSeeker) error {
args := makeResourceArgs(res)
args.Add("application", res.ApplicationID)
err := c.resourcePost(modelUUID, args, r)
return errors.Trace(err)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"UploadResource",
"(",
"modelUUID",
"string",
",",
"res",
"resource",
".",
"Resource",
",",
"r",
"io",
".",
"ReadSeeker",
")",
"error",
"{",
"args",
":=",
"makeResourceArgs",
"(",
"res",
")",
"\n",
"args",
".",
"Add",
"(",
"\"",
"\"",
",",
"res",
".",
"ApplicationID",
")",
"\n",
"err",
":=",
"c",
".",
"resourcePost",
"(",
"modelUUID",
",",
"args",
",",
"r",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // UploadResource uploads a resource to the migration endpoint. | [
"UploadResource",
"uploads",
"a",
"resource",
"to",
"the",
"migration",
"endpoint",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/migrationtarget/client.go#L111-L116 |
154,404 | juju/juju | api/migrationtarget/client.go | SetUnitResource | func (c *Client) SetUnitResource(modelUUID, unit string, res resource.Resource) error {
args := makeResourceArgs(res)
args.Add("unit", unit)
err := c.resourcePost(modelUUID, args, nil)
return errors.Trace(err)
} | go | func (c *Client) SetUnitResource(modelUUID, unit string, res resource.Resource) error {
args := makeResourceArgs(res)
args.Add("unit", unit)
err := c.resourcePost(modelUUID, args, nil)
return errors.Trace(err)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SetUnitResource",
"(",
"modelUUID",
",",
"unit",
"string",
",",
"res",
"resource",
".",
"Resource",
")",
"error",
"{",
"args",
":=",
"makeResourceArgs",
"(",
"res",
")",
"\n",
"args",
".",
"Add",
"(",
"\"",
"\"",
",",
"unit",
")",
"\n",
"err",
":=",
"c",
".",
"resourcePost",
"(",
"modelUUID",
",",
"args",
",",
"nil",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // SetUnitResource sets the metadata for a particular unit resource. | [
"SetUnitResource",
"sets",
"the",
"metadata",
"for",
"a",
"particular",
"unit",
"resource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/migrationtarget/client.go#L127-L132 |
154,405 | juju/juju | api/migrationtarget/client.go | OpenLogTransferStream | func (c *Client) OpenLogTransferStream(modelUUID string) (base.Stream, error) {
attrs := url.Values{}
attrs.Set("jujuclientversion", jujuversion.Current.String())
headers := http.Header{}
headers.Set(params.MigrationModelHTTPHeader, modelUUID)
caller := c.caller.RawAPICaller()
stream, err := caller.ConnectControllerStream("/migrate/logtransfer", attrs, headers)
if err != nil {
return nil, errors.Trace(err)
}
return stream, nil
} | go | func (c *Client) OpenLogTransferStream(modelUUID string) (base.Stream, error) {
attrs := url.Values{}
attrs.Set("jujuclientversion", jujuversion.Current.String())
headers := http.Header{}
headers.Set(params.MigrationModelHTTPHeader, modelUUID)
caller := c.caller.RawAPICaller()
stream, err := caller.ConnectControllerStream("/migrate/logtransfer", attrs, headers)
if err != nil {
return nil, errors.Trace(err)
}
return stream, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OpenLogTransferStream",
"(",
"modelUUID",
"string",
")",
"(",
"base",
".",
"Stream",
",",
"error",
")",
"{",
"attrs",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"attrs",
".",
"Set",
"(",
"\"",
"\"",
",",
"jujuversion",
".",
"Current",
".",
"String",
"(",
")",
")",
"\n",
"headers",
":=",
"http",
".",
"Header",
"{",
"}",
"\n",
"headers",
".",
"Set",
"(",
"params",
".",
"MigrationModelHTTPHeader",
",",
"modelUUID",
")",
"\n",
"caller",
":=",
"c",
".",
"caller",
".",
"RawAPICaller",
"(",
")",
"\n",
"stream",
",",
"err",
":=",
"caller",
".",
"ConnectControllerStream",
"(",
"\"",
"\"",
",",
"attrs",
",",
"headers",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"stream",
",",
"nil",
"\n",
"}"
] | // OpenLogTransferStream connects to the migration logtransfer
// endpoint on the target controller and returns a stream that JSON
// logs records can be fed into. The objects written should be params.LogRecords. | [
"OpenLogTransferStream",
"connects",
"to",
"the",
"migration",
"logtransfer",
"endpoint",
"on",
"the",
"target",
"controller",
"and",
"returns",
"a",
"stream",
"that",
"JSON",
"logs",
"records",
"can",
"be",
"fed",
"into",
".",
"The",
"objects",
"written",
"should",
"be",
"params",
".",
"LogRecords",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/migrationtarget/client.go#L186-L197 |
154,406 | juju/juju | api/migrationtarget/client.go | CACert | func (c *Client) CACert() (string, error) {
var result params.BytesResult
err := c.caller.FacadeCall("CACert", nil, &result)
if err != nil {
return "", err
}
return string(result.Result), nil
} | go | func (c *Client) CACert() (string, error) {
var result params.BytesResult
err := c.caller.FacadeCall("CACert", nil, &result)
if err != nil {
return "", err
}
return string(result.Result), nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CACert",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"result",
"params",
".",
"BytesResult",
"\n",
"err",
":=",
"c",
".",
"caller",
".",
"FacadeCall",
"(",
"\"",
"\"",
",",
"nil",
",",
"&",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"string",
"(",
"result",
".",
"Result",
")",
",",
"nil",
"\n",
"}"
] | // CACert returns the CA certificate associated with
// the connection. | [
"CACert",
"returns",
"the",
"CA",
"certificate",
"associated",
"with",
"the",
"connection",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/migrationtarget/client.go#L226-L233 |
154,407 | juju/juju | core/cache/unit.go | Name | func (u *Unit) Name() string {
u.mu.Lock()
defer u.mu.Unlock()
return u.details.Name
} | go | func (u *Unit) Name() string {
u.mu.Lock()
defer u.mu.Unlock()
return u.details.Name
} | [
"func",
"(",
"u",
"*",
"Unit",
")",
"Name",
"(",
")",
"string",
"{",
"u",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"u",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"u",
".",
"details",
".",
"Name",
"\n",
"}"
] | // Name returns the name of this unit. | [
"Name",
"returns",
"the",
"name",
"of",
"this",
"unit",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/unit.go#L36-L40 |
154,408 | juju/juju | core/cache/unit.go | Application | func (u *Unit) Application() string {
u.mu.Lock()
defer u.mu.Unlock()
return u.details.Application
} | go | func (u *Unit) Application() string {
u.mu.Lock()
defer u.mu.Unlock()
return u.details.Application
} | [
"func",
"(",
"u",
"*",
"Unit",
")",
"Application",
"(",
")",
"string",
"{",
"u",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"u",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"u",
".",
"details",
".",
"Application",
"\n",
"}"
] | // Application returns the application name of this unit. | [
"Application",
"returns",
"the",
"application",
"name",
"of",
"this",
"unit",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/unit.go#L43-L47 |
154,409 | juju/juju | core/cache/unit.go | MachineId | func (u *Unit) MachineId() string {
u.mu.Lock()
defer u.mu.Unlock()
return u.details.MachineId
} | go | func (u *Unit) MachineId() string {
u.mu.Lock()
defer u.mu.Unlock()
return u.details.MachineId
} | [
"func",
"(",
"u",
"*",
"Unit",
")",
"MachineId",
"(",
")",
"string",
"{",
"u",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"u",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"u",
".",
"details",
".",
"MachineId",
"\n",
"}"
] | // MachineId returns the ID of the machine hosting this unit. | [
"MachineId",
"returns",
"the",
"ID",
"of",
"the",
"machine",
"hosting",
"this",
"unit",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/unit.go#L50-L54 |
154,410 | juju/juju | core/cache/unit.go | Subordinate | func (u *Unit) Subordinate() bool {
u.mu.Lock()
defer u.mu.Unlock()
return u.details.Subordinate
} | go | func (u *Unit) Subordinate() bool {
u.mu.Lock()
defer u.mu.Unlock()
return u.details.Subordinate
} | [
"func",
"(",
"u",
"*",
"Unit",
")",
"Subordinate",
"(",
")",
"bool",
"{",
"u",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"u",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"u",
".",
"details",
".",
"Subordinate",
"\n",
"}"
] | // Subordinate returns a bool indicating whether this unit is a subordinate. | [
"Subordinate",
"returns",
"a",
"bool",
"indicating",
"whether",
"this",
"unit",
"is",
"a",
"subordinate",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/unit.go#L57-L61 |
154,411 | juju/juju | core/cache/unit.go | Principal | func (u *Unit) Principal() string {
u.mu.Lock()
defer u.mu.Unlock()
return u.details.Principal
} | go | func (u *Unit) Principal() string {
u.mu.Lock()
defer u.mu.Unlock()
return u.details.Principal
} | [
"func",
"(",
"u",
"*",
"Unit",
")",
"Principal",
"(",
")",
"string",
"{",
"u",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"u",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"u",
".",
"details",
".",
"Principal",
"\n",
"}"
] | // Principal returns the name of the principal unit for the same application. | [
"Principal",
"returns",
"the",
"name",
"of",
"the",
"principal",
"unit",
"for",
"the",
"same",
"application",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/unit.go#L64-L68 |
154,412 | juju/juju | core/cache/unit.go | CharmURL | func (u *Unit) CharmURL() string {
u.mu.Lock()
defer u.mu.Unlock()
return u.details.CharmURL
} | go | func (u *Unit) CharmURL() string {
u.mu.Lock()
defer u.mu.Unlock()
return u.details.CharmURL
} | [
"func",
"(",
"u",
"*",
"Unit",
")",
"CharmURL",
"(",
")",
"string",
"{",
"u",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"u",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"u",
".",
"details",
".",
"CharmURL",
"\n",
"}"
] | // CharmURL returns the charm URL for this unit's application. | [
"CharmURL",
"returns",
"the",
"charm",
"URL",
"for",
"this",
"unit",
"s",
"application",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/unit.go#L71-L75 |
154,413 | juju/juju | apiserver/params/params.go | OneError | func (result ErrorResults) OneError() error {
if n := len(result.Results); n != 1 {
return fmt.Errorf("expected 1 result, got %d", n)
}
if err := result.Results[0].Error; err != nil {
return err
}
return nil
} | go | func (result ErrorResults) OneError() error {
if n := len(result.Results); n != 1 {
return fmt.Errorf("expected 1 result, got %d", n)
}
if err := result.Results[0].Error; err != nil {
return err
}
return nil
} | [
"func",
"(",
"result",
"ErrorResults",
")",
"OneError",
"(",
")",
"error",
"{",
"if",
"n",
":=",
"len",
"(",
"result",
".",
"Results",
")",
";",
"n",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"n",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"result",
".",
"Results",
"[",
"0",
"]",
".",
"Error",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // OneError returns the error from the result
// of a bulk operation on a single value. | [
"OneError",
"returns",
"the",
"error",
"from",
"the",
"result",
"of",
"a",
"bulk",
"operation",
"on",
"a",
"single",
"value",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/params.go#L84-L92 |
154,414 | juju/juju | apiserver/params/params.go | Combine | func (result ErrorResults) Combine() error {
var errorStrings []string
for _, r := range result.Results {
if r.Error != nil {
errorStrings = append(errorStrings, r.Error.Error())
}
}
if errorStrings != nil {
return errors.New(strings.Join(errorStrings, "\n"))
}
return nil
} | go | func (result ErrorResults) Combine() error {
var errorStrings []string
for _, r := range result.Results {
if r.Error != nil {
errorStrings = append(errorStrings, r.Error.Error())
}
}
if errorStrings != nil {
return errors.New(strings.Join(errorStrings, "\n"))
}
return nil
} | [
"func",
"(",
"result",
"ErrorResults",
")",
"Combine",
"(",
")",
"error",
"{",
"var",
"errorStrings",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"result",
".",
"Results",
"{",
"if",
"r",
".",
"Error",
"!=",
"nil",
"{",
"errorStrings",
"=",
"append",
"(",
"errorStrings",
",",
"r",
".",
"Error",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"errorStrings",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"strings",
".",
"Join",
"(",
"errorStrings",
",",
"\"",
"\\n",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Combine returns one error from the result which is an accumulation of the
// errors. If there are no errors in the result, the return value is nil.
// Otherwise the error values are combined with new-line characters. | [
"Combine",
"returns",
"one",
"error",
"from",
"the",
"result",
"which",
"is",
"an",
"accumulation",
"of",
"the",
"errors",
".",
"If",
"there",
"are",
"no",
"errors",
"in",
"the",
"result",
"the",
"return",
"value",
"is",
"nil",
".",
"Otherwise",
"the",
"error",
"values",
"are",
"combined",
"with",
"new",
"-",
"line",
"characters",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/params.go#L97-L108 |
154,415 | juju/juju | apiserver/facades/client/resources/facade.go | NewPublicFacade | func NewPublicFacade(st *state.State, _ facade.Resources, authorizer facade.Authorizer) (*Facade, error) {
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
rst, err := st.Resources()
if err != nil {
return nil, errors.Trace(err)
}
controllerCfg, err := st.ControllerConfig()
if err != nil {
return nil, errors.Trace(err)
}
newClient := func() (CharmStore, error) {
return charmstore.NewCachingClient(state.MacaroonCache{st}, controllerCfg.CharmStoreURL())
}
facade, err := NewFacade(rst, newClient)
if err != nil {
return nil, errors.Trace(err)
}
return facade, nil
} | go | func NewPublicFacade(st *state.State, _ facade.Resources, authorizer facade.Authorizer) (*Facade, error) {
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
rst, err := st.Resources()
if err != nil {
return nil, errors.Trace(err)
}
controllerCfg, err := st.ControllerConfig()
if err != nil {
return nil, errors.Trace(err)
}
newClient := func() (CharmStore, error) {
return charmstore.NewCachingClient(state.MacaroonCache{st}, controllerCfg.CharmStoreURL())
}
facade, err := NewFacade(rst, newClient)
if err != nil {
return nil, errors.Trace(err)
}
return facade, nil
} | [
"func",
"NewPublicFacade",
"(",
"st",
"*",
"state",
".",
"State",
",",
"_",
"facade",
".",
"Resources",
",",
"authorizer",
"facade",
".",
"Authorizer",
")",
"(",
"*",
"Facade",
",",
"error",
")",
"{",
"if",
"!",
"authorizer",
".",
"AuthClient",
"(",
")",
"{",
"return",
"nil",
",",
"common",
".",
"ErrPerm",
"\n",
"}",
"\n\n",
"rst",
",",
"err",
":=",
"st",
".",
"Resources",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"controllerCfg",
",",
"err",
":=",
"st",
".",
"ControllerConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"newClient",
":=",
"func",
"(",
")",
"(",
"CharmStore",
",",
"error",
")",
"{",
"return",
"charmstore",
".",
"NewCachingClient",
"(",
"state",
".",
"MacaroonCache",
"{",
"st",
"}",
",",
"controllerCfg",
".",
"CharmStoreURL",
"(",
")",
")",
"\n",
"}",
"\n",
"facade",
",",
"err",
":=",
"NewFacade",
"(",
"rst",
",",
"newClient",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"facade",
",",
"nil",
"\n",
"}"
] | // NewPublicFacade creates a public API facade for resources. It is
// used for API registration. | [
"NewPublicFacade",
"creates",
"a",
"public",
"API",
"facade",
"for",
"resources",
".",
"It",
"is",
"used",
"for",
"API",
"registration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/resources/facade.go#L60-L81 |
154,416 | juju/juju | apiserver/facades/client/resources/facade.go | NewFacade | func NewFacade(store Backend, newClient func() (CharmStore, error)) (*Facade, error) {
if store == nil {
return nil, errors.Errorf("missing data store")
}
if newClient == nil {
// Technically this only matters for one code path through
// AddPendingResources(). However, that functionality should be
// provided. So we indicate the problem here instead of later
// in the specific place where it actually matters.
return nil, errors.Errorf("missing factory for new charm store clients")
}
f := &Facade{
store: store,
newCharmstoreClient: newClient,
}
return f, nil
} | go | func NewFacade(store Backend, newClient func() (CharmStore, error)) (*Facade, error) {
if store == nil {
return nil, errors.Errorf("missing data store")
}
if newClient == nil {
// Technically this only matters for one code path through
// AddPendingResources(). However, that functionality should be
// provided. So we indicate the problem here instead of later
// in the specific place where it actually matters.
return nil, errors.Errorf("missing factory for new charm store clients")
}
f := &Facade{
store: store,
newCharmstoreClient: newClient,
}
return f, nil
} | [
"func",
"NewFacade",
"(",
"store",
"Backend",
",",
"newClient",
"func",
"(",
")",
"(",
"CharmStore",
",",
"error",
")",
")",
"(",
"*",
"Facade",
",",
"error",
")",
"{",
"if",
"store",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"newClient",
"==",
"nil",
"{",
"// Technically this only matters for one code path through",
"// AddPendingResources(). However, that functionality should be",
"// provided. So we indicate the problem here instead of later",
"// in the specific place where it actually matters.",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"f",
":=",
"&",
"Facade",
"{",
"store",
":",
"store",
",",
"newCharmstoreClient",
":",
"newClient",
",",
"}",
"\n",
"return",
"f",
",",
"nil",
"\n",
"}"
] | // NewFacade returns a new resoures API facade. | [
"NewFacade",
"returns",
"a",
"new",
"resoures",
"API",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/resources/facade.go#L84-L101 |
154,417 | juju/juju | apiserver/facades/client/resources/facade.go | ListResources | func (f Facade) ListResources(args params.ListResourcesArgs) (params.ResourcesResults, error) {
var r params.ResourcesResults
r.Results = make([]params.ResourcesResult, len(args.Entities))
for i, e := range args.Entities {
logger.Tracef("Listing resources for %q", e.Tag)
tag, apierr := parseApplicationTag(e.Tag)
if apierr != nil {
r.Results[i] = params.ResourcesResult{
ErrorResult: params.ErrorResult{
Error: apierr,
},
}
continue
}
svcRes, err := f.store.ListResources(tag.Id())
if err != nil {
r.Results[i] = errorResult(err)
continue
}
r.Results[i] = api.ApplicationResources2APIResult(svcRes)
}
return r, nil
} | go | func (f Facade) ListResources(args params.ListResourcesArgs) (params.ResourcesResults, error) {
var r params.ResourcesResults
r.Results = make([]params.ResourcesResult, len(args.Entities))
for i, e := range args.Entities {
logger.Tracef("Listing resources for %q", e.Tag)
tag, apierr := parseApplicationTag(e.Tag)
if apierr != nil {
r.Results[i] = params.ResourcesResult{
ErrorResult: params.ErrorResult{
Error: apierr,
},
}
continue
}
svcRes, err := f.store.ListResources(tag.Id())
if err != nil {
r.Results[i] = errorResult(err)
continue
}
r.Results[i] = api.ApplicationResources2APIResult(svcRes)
}
return r, nil
} | [
"func",
"(",
"f",
"Facade",
")",
"ListResources",
"(",
"args",
"params",
".",
"ListResourcesArgs",
")",
"(",
"params",
".",
"ResourcesResults",
",",
"error",
")",
"{",
"var",
"r",
"params",
".",
"ResourcesResults",
"\n",
"r",
".",
"Results",
"=",
"make",
"(",
"[",
"]",
"params",
".",
"ResourcesResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
"\n\n",
"for",
"i",
",",
"e",
":=",
"range",
"args",
".",
"Entities",
"{",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"e",
".",
"Tag",
")",
"\n",
"tag",
",",
"apierr",
":=",
"parseApplicationTag",
"(",
"e",
".",
"Tag",
")",
"\n",
"if",
"apierr",
"!=",
"nil",
"{",
"r",
".",
"Results",
"[",
"i",
"]",
"=",
"params",
".",
"ResourcesResult",
"{",
"ErrorResult",
":",
"params",
".",
"ErrorResult",
"{",
"Error",
":",
"apierr",
",",
"}",
",",
"}",
"\n",
"continue",
"\n",
"}",
"\n\n",
"svcRes",
",",
"err",
":=",
"f",
".",
"store",
".",
"ListResources",
"(",
"tag",
".",
"Id",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"r",
".",
"Results",
"[",
"i",
"]",
"=",
"errorResult",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"r",
".",
"Results",
"[",
"i",
"]",
"=",
"api",
".",
"ApplicationResources2APIResult",
"(",
"svcRes",
")",
"\n",
"}",
"\n",
"return",
"r",
",",
"nil",
"\n",
"}"
] | // ListResources returns the list of resources for the given application. | [
"ListResources",
"returns",
"the",
"list",
"of",
"resources",
"for",
"the",
"given",
"application",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/resources/facade.go#L104-L129 |
154,418 | juju/juju | apiserver/facades/client/resources/facade.go | resourcesFromCharmstore | func (f Facade) resourcesFromCharmstore(charms []charmstore.CharmID, client CharmStore) (map[string]charmresource.Resource, error) {
results, err := client.ListResources(charms)
if err != nil {
return nil, errors.Trace(err)
}
storeResources := make(map[string]charmresource.Resource)
if len(results) != 0 {
for _, res := range results[0] {
storeResources[res.Name] = res
}
}
return storeResources, nil
} | go | func (f Facade) resourcesFromCharmstore(charms []charmstore.CharmID, client CharmStore) (map[string]charmresource.Resource, error) {
results, err := client.ListResources(charms)
if err != nil {
return nil, errors.Trace(err)
}
storeResources := make(map[string]charmresource.Resource)
if len(results) != 0 {
for _, res := range results[0] {
storeResources[res.Name] = res
}
}
return storeResources, nil
} | [
"func",
"(",
"f",
"Facade",
")",
"resourcesFromCharmstore",
"(",
"charms",
"[",
"]",
"charmstore",
".",
"CharmID",
",",
"client",
"CharmStore",
")",
"(",
"map",
"[",
"string",
"]",
"charmresource",
".",
"Resource",
",",
"error",
")",
"{",
"results",
",",
"err",
":=",
"client",
".",
"ListResources",
"(",
"charms",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"storeResources",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"charmresource",
".",
"Resource",
")",
"\n",
"if",
"len",
"(",
"results",
")",
"!=",
"0",
"{",
"for",
"_",
",",
"res",
":=",
"range",
"results",
"[",
"0",
"]",
"{",
"storeResources",
"[",
"res",
".",
"Name",
"]",
"=",
"res",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"storeResources",
",",
"nil",
"\n",
"}"
] | // resourcesFromCharmstore gets the info for the charm's resources in
// the charm store. If the charm URL has a revision then that revision's
// resources are returned. Otherwise the latest info for each of the
// resources is returned. | [
"resourcesFromCharmstore",
"gets",
"the",
"info",
"for",
"the",
"charm",
"s",
"resources",
"in",
"the",
"charm",
"store",
".",
"If",
"the",
"charm",
"URL",
"has",
"a",
"revision",
"then",
"that",
"revision",
"s",
"resources",
"are",
"returned",
".",
"Otherwise",
"the",
"latest",
"info",
"for",
"each",
"of",
"the",
"resources",
"is",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/resources/facade.go#L238-L250 |
154,419 | juju/juju | apiserver/facades/client/resources/facade.go | resolveStoreResource | func resolveStoreResource(res charmresource.Resource, storeResources map[string]charmresource.Resource, id charmstore.CharmID, client CharmStore) (charmresource.Resource, error) {
storeRes, ok := storeResources[res.Name]
if !ok {
// This indicates that AddPendingResources() was called for
// a resource the charm store doesn't know about (for the
// relevant charm revision).
// TODO(ericsnow) Do the following once the charm store supports
// the necessary endpoints:
// return res, errors.NotFoundf("charm store resource %q", res.Name)
return res, nil
}
if res.Revision < 0 {
// The caller wants to use the charm store info.
return storeRes, nil
}
if res.Revision == storeRes.Revision {
// We don't worry about if they otherwise match. Only the
// revision is significant here. So we use the info from the
// charm store since it is authoritative.
return storeRes, nil
}
if res.Fingerprint.IsZero() {
// The caller wants resource info from the charm store, but with
// a different resource revision than the one associated with
// the charm in the store.
req := charmstore.ResourceRequest{
Charm: id.URL,
Channel: id.Channel,
Name: res.Name,
Revision: res.Revision,
}
storeRes, err := client.ResourceInfo(req)
if err != nil {
return storeRes, errors.Trace(err)
}
return storeRes, nil
}
// The caller fully-specified a resource with a different resource
// revision than the one associated with the charm in the store. So
// we use the provided info as-is.
return res, nil
} | go | func resolveStoreResource(res charmresource.Resource, storeResources map[string]charmresource.Resource, id charmstore.CharmID, client CharmStore) (charmresource.Resource, error) {
storeRes, ok := storeResources[res.Name]
if !ok {
// This indicates that AddPendingResources() was called for
// a resource the charm store doesn't know about (for the
// relevant charm revision).
// TODO(ericsnow) Do the following once the charm store supports
// the necessary endpoints:
// return res, errors.NotFoundf("charm store resource %q", res.Name)
return res, nil
}
if res.Revision < 0 {
// The caller wants to use the charm store info.
return storeRes, nil
}
if res.Revision == storeRes.Revision {
// We don't worry about if they otherwise match. Only the
// revision is significant here. So we use the info from the
// charm store since it is authoritative.
return storeRes, nil
}
if res.Fingerprint.IsZero() {
// The caller wants resource info from the charm store, but with
// a different resource revision than the one associated with
// the charm in the store.
req := charmstore.ResourceRequest{
Charm: id.URL,
Channel: id.Channel,
Name: res.Name,
Revision: res.Revision,
}
storeRes, err := client.ResourceInfo(req)
if err != nil {
return storeRes, errors.Trace(err)
}
return storeRes, nil
}
// The caller fully-specified a resource with a different resource
// revision than the one associated with the charm in the store. So
// we use the provided info as-is.
return res, nil
} | [
"func",
"resolveStoreResource",
"(",
"res",
"charmresource",
".",
"Resource",
",",
"storeResources",
"map",
"[",
"string",
"]",
"charmresource",
".",
"Resource",
",",
"id",
"charmstore",
".",
"CharmID",
",",
"client",
"CharmStore",
")",
"(",
"charmresource",
".",
"Resource",
",",
"error",
")",
"{",
"storeRes",
",",
"ok",
":=",
"storeResources",
"[",
"res",
".",
"Name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"// This indicates that AddPendingResources() was called for",
"// a resource the charm store doesn't know about (for the",
"// relevant charm revision).",
"// TODO(ericsnow) Do the following once the charm store supports",
"// the necessary endpoints:",
"// return res, errors.NotFoundf(\"charm store resource %q\", res.Name)",
"return",
"res",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"res",
".",
"Revision",
"<",
"0",
"{",
"// The caller wants to use the charm store info.",
"return",
"storeRes",
",",
"nil",
"\n",
"}",
"\n",
"if",
"res",
".",
"Revision",
"==",
"storeRes",
".",
"Revision",
"{",
"// We don't worry about if they otherwise match. Only the",
"// revision is significant here. So we use the info from the",
"// charm store since it is authoritative.",
"return",
"storeRes",
",",
"nil",
"\n",
"}",
"\n",
"if",
"res",
".",
"Fingerprint",
".",
"IsZero",
"(",
")",
"{",
"// The caller wants resource info from the charm store, but with",
"// a different resource revision than the one associated with",
"// the charm in the store.",
"req",
":=",
"charmstore",
".",
"ResourceRequest",
"{",
"Charm",
":",
"id",
".",
"URL",
",",
"Channel",
":",
"id",
".",
"Channel",
",",
"Name",
":",
"res",
".",
"Name",
",",
"Revision",
":",
"res",
".",
"Revision",
",",
"}",
"\n",
"storeRes",
",",
"err",
":=",
"client",
".",
"ResourceInfo",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"storeRes",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"storeRes",
",",
"nil",
"\n",
"}",
"\n",
"// The caller fully-specified a resource with a different resource",
"// revision than the one associated with the charm in the store. So",
"// we use the provided info as-is.",
"return",
"res",
",",
"nil",
"\n",
"}"
] | // resolveStoreResource selects the resource info to use. It decides
// between the provided and latest info based on the revision. | [
"resolveStoreResource",
"selects",
"the",
"resource",
"info",
"to",
"use",
".",
"It",
"decides",
"between",
"the",
"provided",
"and",
"latest",
"info",
"based",
"on",
"the",
"revision",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/resources/facade.go#L277-L319 |
154,420 | juju/juju | provider/maas/environ.go | ecfg | func (env *maasEnviron) ecfg() *maasModelConfig {
env.ecfgMutex.Lock()
cfg := *env.ecfgUnlocked
env.ecfgMutex.Unlock()
return &cfg
} | go | func (env *maasEnviron) ecfg() *maasModelConfig {
env.ecfgMutex.Lock()
cfg := *env.ecfgUnlocked
env.ecfgMutex.Unlock()
return &cfg
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"ecfg",
"(",
")",
"*",
"maasModelConfig",
"{",
"env",
".",
"ecfgMutex",
".",
"Lock",
"(",
")",
"\n",
"cfg",
":=",
"*",
"env",
".",
"ecfgUnlocked",
"\n",
"env",
".",
"ecfgMutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"&",
"cfg",
"\n",
"}"
] | // ecfg returns the environment's maasModelConfig, and protects it with a
// mutex. | [
"ecfg",
"returns",
"the",
"environment",
"s",
"maasModelConfig",
"and",
"protects",
"it",
"with",
"a",
"mutex",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L236-L241 |
154,421 | juju/juju | provider/maas/environ.go | allArchitectures2 | func (env *maasEnviron) allArchitectures2(ctx context.ProviderCallContext) ([]string, error) {
resources, err := env.maasController.BootResources()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
architectures := set.NewStrings()
for _, resource := range resources {
architectures.Add(strings.Split(resource.Architecture(), "/")[0])
}
return architectures.SortedValues(), nil
} | go | func (env *maasEnviron) allArchitectures2(ctx context.ProviderCallContext) ([]string, error) {
resources, err := env.maasController.BootResources()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
architectures := set.NewStrings()
for _, resource := range resources {
architectures.Add(strings.Split(resource.Architecture(), "/")[0])
}
return architectures.SortedValues(), nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"allArchitectures2",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"resources",
",",
"err",
":=",
"env",
".",
"maasController",
".",
"BootResources",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"architectures",
":=",
"set",
".",
"NewStrings",
"(",
")",
"\n",
"for",
"_",
",",
"resource",
":=",
"range",
"resources",
"{",
"architectures",
".",
"Add",
"(",
"strings",
".",
"Split",
"(",
"resource",
".",
"Architecture",
"(",
")",
",",
"\"",
"\"",
")",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"return",
"architectures",
".",
"SortedValues",
"(",
")",
",",
"nil",
"\n",
"}"
] | // allArchitectures2 uses the MAAS2 controller to get architectures from boot
// resources. | [
"allArchitectures2",
"uses",
"the",
"MAAS2",
"controller",
"to",
"get",
"architectures",
"from",
"boot",
"resources",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L351-L362 |
154,422 | juju/juju | provider/maas/environ.go | allArchitecturesWithFallback | func (env *maasEnviron) allArchitecturesWithFallback(ctx context.ProviderCallContext) ([]string, error) {
architectures, err := env.allArchitectures(ctx)
if err != nil || len(architectures) == 0 {
logger.Debugf("error querying boot-images: %v", err)
logger.Debugf("falling back to listing nodes")
architectures, err := env.nodeArchitectures(ctx)
if err != nil {
return nil, errors.Trace(err)
}
return architectures, nil
} else {
return architectures, nil
}
} | go | func (env *maasEnviron) allArchitecturesWithFallback(ctx context.ProviderCallContext) ([]string, error) {
architectures, err := env.allArchitectures(ctx)
if err != nil || len(architectures) == 0 {
logger.Debugf("error querying boot-images: %v", err)
logger.Debugf("falling back to listing nodes")
architectures, err := env.nodeArchitectures(ctx)
if err != nil {
return nil, errors.Trace(err)
}
return architectures, nil
} else {
return architectures, nil
}
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"allArchitecturesWithFallback",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"architectures",
",",
"err",
":=",
"env",
".",
"allArchitectures",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"len",
"(",
"architectures",
")",
"==",
"0",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"architectures",
",",
"err",
":=",
"env",
".",
"nodeArchitectures",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"architectures",
",",
"nil",
"\n",
"}",
"else",
"{",
"return",
"architectures",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // allArchitectureWithFallback queries MAAS for all of the boot-images
// across all registered nodegroups and collapses them down to unique
// architectures. | [
"allArchitectureWithFallback",
"queries",
"MAAS",
"for",
"all",
"of",
"the",
"boot",
"-",
"images",
"across",
"all",
"registered",
"nodegroups",
"and",
"collapses",
"them",
"down",
"to",
"unique",
"architectures",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L367-L380 |
154,423 | juju/juju | provider/maas/environ.go | getNodegroups | func (env *maasEnviron) getNodegroups(ctx context.ProviderCallContext) ([]string, error) {
nodegroupsListing := env.getMAASClient().GetSubObject("nodegroups")
nodegroupsResult, err := nodegroupsListing.CallGet("list", nil)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
list, err := nodegroupsResult.GetArray()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
nodegroups := make([]string, len(list))
for i, obj := range list {
nodegroup, err := obj.GetMap()
if err != nil {
return nil, err
}
uuid, err := nodegroup["uuid"].GetString()
if err != nil {
return nil, err
}
nodegroups[i] = uuid
}
return nodegroups, nil
} | go | func (env *maasEnviron) getNodegroups(ctx context.ProviderCallContext) ([]string, error) {
nodegroupsListing := env.getMAASClient().GetSubObject("nodegroups")
nodegroupsResult, err := nodegroupsListing.CallGet("list", nil)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
list, err := nodegroupsResult.GetArray()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
nodegroups := make([]string, len(list))
for i, obj := range list {
nodegroup, err := obj.GetMap()
if err != nil {
return nil, err
}
uuid, err := nodegroup["uuid"].GetString()
if err != nil {
return nil, err
}
nodegroups[i] = uuid
}
return nodegroups, nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"getNodegroups",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"nodegroupsListing",
":=",
"env",
".",
"getMAASClient",
"(",
")",
".",
"GetSubObject",
"(",
"\"",
"\"",
")",
"\n",
"nodegroupsResult",
",",
"err",
":=",
"nodegroupsListing",
".",
"CallGet",
"(",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"list",
",",
"err",
":=",
"nodegroupsResult",
".",
"GetArray",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"nodegroups",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"list",
")",
")",
"\n",
"for",
"i",
",",
"obj",
":=",
"range",
"list",
"{",
"nodegroup",
",",
"err",
":=",
"obj",
".",
"GetMap",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"uuid",
",",
"err",
":=",
"nodegroup",
"[",
"\"",
"\"",
"]",
".",
"GetString",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"nodegroups",
"[",
"i",
"]",
"=",
"uuid",
"\n",
"}",
"\n",
"return",
"nodegroups",
",",
"nil",
"\n",
"}"
] | // getNodegroups returns the UUID corresponding to each nodegroup
// in the MAAS installation. | [
"getNodegroups",
"returns",
"the",
"UUID",
"corresponding",
"to",
"each",
"nodegroup",
"in",
"the",
"MAAS",
"installation",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L402-L427 |
154,424 | juju/juju | provider/maas/environ.go | nodegroupBootImages | func (env *maasEnviron) nodegroupBootImages(ctx context.ProviderCallContext, nodegroupUUID string) ([]bootImage, error) {
nodegroupObject := env.getMAASClient().GetSubObject("nodegroups").GetSubObject(nodegroupUUID)
bootImagesObject := nodegroupObject.GetSubObject("boot-images/")
result, err := bootImagesObject.CallGet("", nil)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
list, err := result.GetArray()
if err != nil {
return nil, err
}
var bootImages []bootImage
for _, obj := range list {
bootimage, err := obj.GetMap()
if err != nil {
return nil, err
}
arch, err := bootimage["architecture"].GetString()
if err != nil {
return nil, err
}
release, err := bootimage["release"].GetString()
if err != nil {
return nil, err
}
bootImages = append(bootImages, bootImage{
architecture: arch,
release: release,
})
}
return bootImages, nil
} | go | func (env *maasEnviron) nodegroupBootImages(ctx context.ProviderCallContext, nodegroupUUID string) ([]bootImage, error) {
nodegroupObject := env.getMAASClient().GetSubObject("nodegroups").GetSubObject(nodegroupUUID)
bootImagesObject := nodegroupObject.GetSubObject("boot-images/")
result, err := bootImagesObject.CallGet("", nil)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
list, err := result.GetArray()
if err != nil {
return nil, err
}
var bootImages []bootImage
for _, obj := range list {
bootimage, err := obj.GetMap()
if err != nil {
return nil, err
}
arch, err := bootimage["architecture"].GetString()
if err != nil {
return nil, err
}
release, err := bootimage["release"].GetString()
if err != nil {
return nil, err
}
bootImages = append(bootImages, bootImage{
architecture: arch,
release: release,
})
}
return bootImages, nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"nodegroupBootImages",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"nodegroupUUID",
"string",
")",
"(",
"[",
"]",
"bootImage",
",",
"error",
")",
"{",
"nodegroupObject",
":=",
"env",
".",
"getMAASClient",
"(",
")",
".",
"GetSubObject",
"(",
"\"",
"\"",
")",
".",
"GetSubObject",
"(",
"nodegroupUUID",
")",
"\n",
"bootImagesObject",
":=",
"nodegroupObject",
".",
"GetSubObject",
"(",
"\"",
"\"",
")",
"\n",
"result",
",",
"err",
":=",
"bootImagesObject",
".",
"CallGet",
"(",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"list",
",",
"err",
":=",
"result",
".",
"GetArray",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"bootImages",
"[",
"]",
"bootImage",
"\n",
"for",
"_",
",",
"obj",
":=",
"range",
"list",
"{",
"bootimage",
",",
"err",
":=",
"obj",
".",
"GetMap",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"arch",
",",
"err",
":=",
"bootimage",
"[",
"\"",
"\"",
"]",
".",
"GetString",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"release",
",",
"err",
":=",
"bootimage",
"[",
"\"",
"\"",
"]",
".",
"GetString",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"bootImages",
"=",
"append",
"(",
"bootImages",
",",
"bootImage",
"{",
"architecture",
":",
"arch",
",",
"release",
":",
"release",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"bootImages",
",",
"nil",
"\n",
"}"
] | // nodegroupBootImages returns the set of boot-images for the specified nodegroup. | [
"nodegroupBootImages",
"returns",
"the",
"set",
"of",
"boot",
"-",
"images",
"for",
"the",
"specified",
"nodegroup",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L435-L467 |
154,425 | juju/juju | provider/maas/environ.go | getCapabilities | func getCapabilities(client *gomaasapi.MAASObject, serverURL string) (set.Strings, error) {
caps := make(set.Strings)
var result gomaasapi.JSONObject
var err error
for a := shortAttempt.Start(); a.Next(); {
version := client.GetSubObject("version/")
result, err = version.CallGet("", nil)
if err == nil {
break
}
if err, ok := errors.Cause(err).(gomaasapi.ServerError); ok && err.StatusCode == 404 {
logger.Debugf("Failed attempting to get capabilities from maas endpoint %q: %v", serverURL, err)
message := "could not connect to MAAS controller - check the endpoint is correct"
trimmedURL := strings.TrimRight(serverURL, "/")
if !strings.HasSuffix(trimmedURL, "/MAAS") {
message += " (it normally ends with /MAAS)"
}
return caps, errors.NewNotSupported(nil, message)
}
}
if err != nil {
logger.Debugf("Can't connect to maas server at endpoint %q: %v", serverURL, err)
return caps, err
}
info, err := result.GetMap()
if err != nil {
logger.Debugf("Invalid data returned from maas endpoint %q: %v", serverURL, err)
// invalid data of some sort, probably not a MAAS server.
return caps, errors.New("failed to get expected data from server")
}
capsObj, ok := info["capabilities"]
if !ok {
return caps, fmt.Errorf("MAAS does not report capabilities")
}
items, err := capsObj.GetArray()
if err != nil {
logger.Debugf("Invalid data returned from maas endpoint %q: %v", serverURL, err)
return caps, errors.New("failed to get expected data from server")
}
for _, item := range items {
val, err := item.GetString()
if err != nil {
logger.Debugf("Invalid data returned from maas endpoint %q: %v", serverURL, err)
return set.NewStrings(), errors.New("failed to get expected data from server")
}
caps.Add(val)
}
return caps, nil
} | go | func getCapabilities(client *gomaasapi.MAASObject, serverURL string) (set.Strings, error) {
caps := make(set.Strings)
var result gomaasapi.JSONObject
var err error
for a := shortAttempt.Start(); a.Next(); {
version := client.GetSubObject("version/")
result, err = version.CallGet("", nil)
if err == nil {
break
}
if err, ok := errors.Cause(err).(gomaasapi.ServerError); ok && err.StatusCode == 404 {
logger.Debugf("Failed attempting to get capabilities from maas endpoint %q: %v", serverURL, err)
message := "could not connect to MAAS controller - check the endpoint is correct"
trimmedURL := strings.TrimRight(serverURL, "/")
if !strings.HasSuffix(trimmedURL, "/MAAS") {
message += " (it normally ends with /MAAS)"
}
return caps, errors.NewNotSupported(nil, message)
}
}
if err != nil {
logger.Debugf("Can't connect to maas server at endpoint %q: %v", serverURL, err)
return caps, err
}
info, err := result.GetMap()
if err != nil {
logger.Debugf("Invalid data returned from maas endpoint %q: %v", serverURL, err)
// invalid data of some sort, probably not a MAAS server.
return caps, errors.New("failed to get expected data from server")
}
capsObj, ok := info["capabilities"]
if !ok {
return caps, fmt.Errorf("MAAS does not report capabilities")
}
items, err := capsObj.GetArray()
if err != nil {
logger.Debugf("Invalid data returned from maas endpoint %q: %v", serverURL, err)
return caps, errors.New("failed to get expected data from server")
}
for _, item := range items {
val, err := item.GetString()
if err != nil {
logger.Debugf("Invalid data returned from maas endpoint %q: %v", serverURL, err)
return set.NewStrings(), errors.New("failed to get expected data from server")
}
caps.Add(val)
}
return caps, nil
} | [
"func",
"getCapabilities",
"(",
"client",
"*",
"gomaasapi",
".",
"MAASObject",
",",
"serverURL",
"string",
")",
"(",
"set",
".",
"Strings",
",",
"error",
")",
"{",
"caps",
":=",
"make",
"(",
"set",
".",
"Strings",
")",
"\n",
"var",
"result",
"gomaasapi",
".",
"JSONObject",
"\n",
"var",
"err",
"error",
"\n\n",
"for",
"a",
":=",
"shortAttempt",
".",
"Start",
"(",
")",
";",
"a",
".",
"Next",
"(",
")",
";",
"{",
"version",
":=",
"client",
".",
"GetSubObject",
"(",
"\"",
"\"",
")",
"\n",
"result",
",",
"err",
"=",
"version",
".",
"CallGet",
"(",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"if",
"err",
",",
"ok",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
".",
"(",
"gomaasapi",
".",
"ServerError",
")",
";",
"ok",
"&&",
"err",
".",
"StatusCode",
"==",
"404",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"serverURL",
",",
"err",
")",
"\n\n",
"message",
":=",
"\"",
"\"",
"\n",
"trimmedURL",
":=",
"strings",
".",
"TrimRight",
"(",
"serverURL",
",",
"\"",
"\"",
")",
"\n",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"trimmedURL",
",",
"\"",
"\"",
")",
"{",
"message",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"caps",
",",
"errors",
".",
"NewNotSupported",
"(",
"nil",
",",
"message",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"serverURL",
",",
"err",
")",
"\n",
"return",
"caps",
",",
"err",
"\n",
"}",
"\n",
"info",
",",
"err",
":=",
"result",
".",
"GetMap",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"serverURL",
",",
"err",
")",
"\n",
"// invalid data of some sort, probably not a MAAS server.",
"return",
"caps",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"capsObj",
",",
"ok",
":=",
"info",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"caps",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"items",
",",
"err",
":=",
"capsObj",
".",
"GetArray",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"serverURL",
",",
"err",
")",
"\n",
"return",
"caps",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"item",
":=",
"range",
"items",
"{",
"val",
",",
"err",
":=",
"item",
".",
"GetString",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"serverURL",
",",
"err",
")",
"\n",
"return",
"set",
".",
"NewStrings",
"(",
")",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"caps",
".",
"Add",
"(",
"val",
")",
"\n",
"}",
"\n",
"return",
"caps",
",",
"nil",
"\n",
"}"
] | // getCapabilities asks the MAAS server for its capabilities, if
// supported by the server. | [
"getCapabilities",
"asks",
"the",
"MAAS",
"server",
"for",
"its",
"capabilities",
"if",
"supported",
"by",
"the",
"server",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L658-L708 |
154,426 | juju/juju | provider/maas/environ.go | getMAASClient | func (env *maasEnviron) getMAASClient() *gomaasapi.MAASObject {
env.ecfgMutex.Lock()
defer env.ecfgMutex.Unlock()
return env.maasClientUnlocked
} | go | func (env *maasEnviron) getMAASClient() *gomaasapi.MAASObject {
env.ecfgMutex.Lock()
defer env.ecfgMutex.Unlock()
return env.maasClientUnlocked
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"getMAASClient",
"(",
")",
"*",
"gomaasapi",
".",
"MAASObject",
"{",
"env",
".",
"ecfgMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"env",
".",
"ecfgMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"env",
".",
"maasClientUnlocked",
"\n",
"}"
] | // getMAASClient returns a MAAS client object to use for a request, in a
// lock-protected fashion. | [
"getMAASClient",
"returns",
"a",
"MAAS",
"client",
"object",
"to",
"use",
"for",
"a",
"request",
"in",
"a",
"lock",
"-",
"protected",
"fashion",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L712-L717 |
154,427 | juju/juju | provider/maas/environ.go | acquireNode2 | func (env *maasEnviron) acquireNode2(
ctx context.ProviderCallContext,
nodeName, zoneName, systemId string,
cons constraints.Value,
interfaces []interfaceBinding,
volumes []volumeInfo,
) (maasInstance, error) {
acquireParams := convertConstraints2(cons)
positiveSpaceNames, negativeSpaceNames := convertSpacesFromConstraints(cons.Spaces)
positiveSpaces, negativeSpaces, err := env.spaceNamesToSpaceInfo(ctx, positiveSpaceNames, negativeSpaceNames)
// If spaces aren't supported the constraints should be empty anyway.
if err != nil && !errors.IsNotSupported(err) {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
err = addInterfaces2(&acquireParams, interfaces, positiveSpaces, negativeSpaces)
if err != nil {
return nil, errors.Trace(err)
}
addStorage2(&acquireParams, volumes)
acquireParams.AgentName = env.uuid
if zoneName != "" {
acquireParams.Zone = zoneName
}
if nodeName != "" {
acquireParams.Hostname = nodeName
}
if systemId != "" {
acquireParams.SystemId = systemId
}
machine, constraintMatches, err := env.maasController.AllocateMachine(acquireParams)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
return &maas2Instance{
machine: machine,
constraintMatches: constraintMatches,
environ: env,
}, nil
} | go | func (env *maasEnviron) acquireNode2(
ctx context.ProviderCallContext,
nodeName, zoneName, systemId string,
cons constraints.Value,
interfaces []interfaceBinding,
volumes []volumeInfo,
) (maasInstance, error) {
acquireParams := convertConstraints2(cons)
positiveSpaceNames, negativeSpaceNames := convertSpacesFromConstraints(cons.Spaces)
positiveSpaces, negativeSpaces, err := env.spaceNamesToSpaceInfo(ctx, positiveSpaceNames, negativeSpaceNames)
// If spaces aren't supported the constraints should be empty anyway.
if err != nil && !errors.IsNotSupported(err) {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
err = addInterfaces2(&acquireParams, interfaces, positiveSpaces, negativeSpaces)
if err != nil {
return nil, errors.Trace(err)
}
addStorage2(&acquireParams, volumes)
acquireParams.AgentName = env.uuid
if zoneName != "" {
acquireParams.Zone = zoneName
}
if nodeName != "" {
acquireParams.Hostname = nodeName
}
if systemId != "" {
acquireParams.SystemId = systemId
}
machine, constraintMatches, err := env.maasController.AllocateMachine(acquireParams)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
return &maas2Instance{
machine: machine,
constraintMatches: constraintMatches,
environ: env,
}, nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"acquireNode2",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"nodeName",
",",
"zoneName",
",",
"systemId",
"string",
",",
"cons",
"constraints",
".",
"Value",
",",
"interfaces",
"[",
"]",
"interfaceBinding",
",",
"volumes",
"[",
"]",
"volumeInfo",
",",
")",
"(",
"maasInstance",
",",
"error",
")",
"{",
"acquireParams",
":=",
"convertConstraints2",
"(",
"cons",
")",
"\n",
"positiveSpaceNames",
",",
"negativeSpaceNames",
":=",
"convertSpacesFromConstraints",
"(",
"cons",
".",
"Spaces",
")",
"\n",
"positiveSpaces",
",",
"negativeSpaces",
",",
"err",
":=",
"env",
".",
"spaceNamesToSpaceInfo",
"(",
"ctx",
",",
"positiveSpaceNames",
",",
"negativeSpaceNames",
")",
"\n",
"// If spaces aren't supported the constraints should be empty anyway.",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotSupported",
"(",
"err",
")",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"addInterfaces2",
"(",
"&",
"acquireParams",
",",
"interfaces",
",",
"positiveSpaces",
",",
"negativeSpaces",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"addStorage2",
"(",
"&",
"acquireParams",
",",
"volumes",
")",
"\n",
"acquireParams",
".",
"AgentName",
"=",
"env",
".",
"uuid",
"\n",
"if",
"zoneName",
"!=",
"\"",
"\"",
"{",
"acquireParams",
".",
"Zone",
"=",
"zoneName",
"\n",
"}",
"\n",
"if",
"nodeName",
"!=",
"\"",
"\"",
"{",
"acquireParams",
".",
"Hostname",
"=",
"nodeName",
"\n",
"}",
"\n",
"if",
"systemId",
"!=",
"\"",
"\"",
"{",
"acquireParams",
".",
"SystemId",
"=",
"systemId",
"\n",
"}",
"\n",
"machine",
",",
"constraintMatches",
",",
"err",
":=",
"env",
".",
"maasController",
".",
"AllocateMachine",
"(",
"acquireParams",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"maas2Instance",
"{",
"machine",
":",
"machine",
",",
"constraintMatches",
":",
"constraintMatches",
",",
"environ",
":",
"env",
",",
"}",
",",
"nil",
"\n",
"}"
] | // acquireNode2 allocates a machine from MAAS2. | [
"acquireNode2",
"allocates",
"a",
"machine",
"from",
"MAAS2",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L774-L815 |
154,428 | juju/juju | provider/maas/environ.go | acquireNode | func (env *maasEnviron) acquireNode(
ctx context.ProviderCallContext,
nodeName, zoneName, systemId string,
cons constraints.Value,
interfaces []interfaceBinding,
volumes []volumeInfo,
) (gomaasapi.MAASObject, error) {
// TODO(axw) 2014-08-18 #1358219
// We should be requesting preferred architectures if unspecified,
// like in the other providers.
//
// This is slightly complicated in MAAS as there are a finite
// number of each architecture; preference may also conflict with
// other constraints, such as tags. Thus, a preference becomes a
// demand (which may fail) if not handled properly.
acquireParams := convertConstraints(cons)
positiveSpaceNames, negativeSpaceNames := convertSpacesFromConstraints(cons.Spaces)
positiveSpaces, negativeSpaces, err := env.spaceNamesToSpaceInfo(ctx, positiveSpaceNames, negativeSpaceNames)
// If spaces aren't supported the constraints should be empty anyway.
if err != nil && !errors.IsNotSupported(err) {
return gomaasapi.MAASObject{}, errors.Trace(err)
}
err = addInterfaces(acquireParams, interfaces, positiveSpaces, negativeSpaces)
if err != nil {
return gomaasapi.MAASObject{}, errors.Trace(err)
}
addStorage(acquireParams, volumes)
acquireParams.Add("agent_name", env.uuid)
if zoneName != "" {
acquireParams.Add("zone", zoneName)
}
if nodeName != "" {
acquireParams.Add("name", nodeName)
}
if systemId != "" {
acquireParams.Add("system_id", systemId)
}
var result gomaasapi.JSONObject
for a := shortAttempt.Start(); a.Next(); {
client := env.getMAASClient().GetSubObject("nodes/")
logger.Tracef("calling acquire with params: %+v", acquireParams)
result, err = client.CallPost("acquire", acquireParams)
if err == nil {
break
}
}
if err != nil {
return gomaasapi.MAASObject{}, err
}
node, err := result.GetMAASObject()
if err != nil {
err := errors.Annotate(err, "unexpected result from 'acquire' on MAAS API")
return gomaasapi.MAASObject{}, err
}
return node, nil
} | go | func (env *maasEnviron) acquireNode(
ctx context.ProviderCallContext,
nodeName, zoneName, systemId string,
cons constraints.Value,
interfaces []interfaceBinding,
volumes []volumeInfo,
) (gomaasapi.MAASObject, error) {
// TODO(axw) 2014-08-18 #1358219
// We should be requesting preferred architectures if unspecified,
// like in the other providers.
//
// This is slightly complicated in MAAS as there are a finite
// number of each architecture; preference may also conflict with
// other constraints, such as tags. Thus, a preference becomes a
// demand (which may fail) if not handled properly.
acquireParams := convertConstraints(cons)
positiveSpaceNames, negativeSpaceNames := convertSpacesFromConstraints(cons.Spaces)
positiveSpaces, negativeSpaces, err := env.spaceNamesToSpaceInfo(ctx, positiveSpaceNames, negativeSpaceNames)
// If spaces aren't supported the constraints should be empty anyway.
if err != nil && !errors.IsNotSupported(err) {
return gomaasapi.MAASObject{}, errors.Trace(err)
}
err = addInterfaces(acquireParams, interfaces, positiveSpaces, negativeSpaces)
if err != nil {
return gomaasapi.MAASObject{}, errors.Trace(err)
}
addStorage(acquireParams, volumes)
acquireParams.Add("agent_name", env.uuid)
if zoneName != "" {
acquireParams.Add("zone", zoneName)
}
if nodeName != "" {
acquireParams.Add("name", nodeName)
}
if systemId != "" {
acquireParams.Add("system_id", systemId)
}
var result gomaasapi.JSONObject
for a := shortAttempt.Start(); a.Next(); {
client := env.getMAASClient().GetSubObject("nodes/")
logger.Tracef("calling acquire with params: %+v", acquireParams)
result, err = client.CallPost("acquire", acquireParams)
if err == nil {
break
}
}
if err != nil {
return gomaasapi.MAASObject{}, err
}
node, err := result.GetMAASObject()
if err != nil {
err := errors.Annotate(err, "unexpected result from 'acquire' on MAAS API")
return gomaasapi.MAASObject{}, err
}
return node, nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"acquireNode",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"nodeName",
",",
"zoneName",
",",
"systemId",
"string",
",",
"cons",
"constraints",
".",
"Value",
",",
"interfaces",
"[",
"]",
"interfaceBinding",
",",
"volumes",
"[",
"]",
"volumeInfo",
",",
")",
"(",
"gomaasapi",
".",
"MAASObject",
",",
"error",
")",
"{",
"// TODO(axw) 2014-08-18 #1358219",
"// We should be requesting preferred architectures if unspecified,",
"// like in the other providers.",
"//",
"// This is slightly complicated in MAAS as there are a finite",
"// number of each architecture; preference may also conflict with",
"// other constraints, such as tags. Thus, a preference becomes a",
"// demand (which may fail) if not handled properly.",
"acquireParams",
":=",
"convertConstraints",
"(",
"cons",
")",
"\n",
"positiveSpaceNames",
",",
"negativeSpaceNames",
":=",
"convertSpacesFromConstraints",
"(",
"cons",
".",
"Spaces",
")",
"\n",
"positiveSpaces",
",",
"negativeSpaces",
",",
"err",
":=",
"env",
".",
"spaceNamesToSpaceInfo",
"(",
"ctx",
",",
"positiveSpaceNames",
",",
"negativeSpaceNames",
")",
"\n",
"// If spaces aren't supported the constraints should be empty anyway.",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotSupported",
"(",
"err",
")",
"{",
"return",
"gomaasapi",
".",
"MAASObject",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"addInterfaces",
"(",
"acquireParams",
",",
"interfaces",
",",
"positiveSpaces",
",",
"negativeSpaces",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"gomaasapi",
".",
"MAASObject",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"addStorage",
"(",
"acquireParams",
",",
"volumes",
")",
"\n",
"acquireParams",
".",
"Add",
"(",
"\"",
"\"",
",",
"env",
".",
"uuid",
")",
"\n",
"if",
"zoneName",
"!=",
"\"",
"\"",
"{",
"acquireParams",
".",
"Add",
"(",
"\"",
"\"",
",",
"zoneName",
")",
"\n",
"}",
"\n",
"if",
"nodeName",
"!=",
"\"",
"\"",
"{",
"acquireParams",
".",
"Add",
"(",
"\"",
"\"",
",",
"nodeName",
")",
"\n",
"}",
"\n",
"if",
"systemId",
"!=",
"\"",
"\"",
"{",
"acquireParams",
".",
"Add",
"(",
"\"",
"\"",
",",
"systemId",
")",
"\n",
"}",
"\n\n",
"var",
"result",
"gomaasapi",
".",
"JSONObject",
"\n",
"for",
"a",
":=",
"shortAttempt",
".",
"Start",
"(",
")",
";",
"a",
".",
"Next",
"(",
")",
";",
"{",
"client",
":=",
"env",
".",
"getMAASClient",
"(",
")",
".",
"GetSubObject",
"(",
"\"",
"\"",
")",
"\n",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"acquireParams",
")",
"\n",
"result",
",",
"err",
"=",
"client",
".",
"CallPost",
"(",
"\"",
"\"",
",",
"acquireParams",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"gomaasapi",
".",
"MAASObject",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"node",
",",
"err",
":=",
"result",
".",
"GetMAASObject",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
":=",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"return",
"gomaasapi",
".",
"MAASObject",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"node",
",",
"nil",
"\n",
"}"
] | // acquireNode allocates a node from the MAAS. | [
"acquireNode",
"allocates",
"a",
"node",
"from",
"the",
"MAAS",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L818-L876 |
154,429 | juju/juju | provider/maas/environ.go | startNode | func (env *maasEnviron) startNode(node gomaasapi.MAASObject, series string, userdata []byte) (*gomaasapi.MAASObject, error) {
params := url.Values{
"distro_series": {series},
"user_data": {string(userdata)},
}
// Initialize err to a non-nil value as a sentinel for the following
// loop.
err := fmt.Errorf("(no error)")
var result gomaasapi.JSONObject
for a := shortAttempt.Start(); a.Next() && err != nil; {
result, err = node.CallPost("start", params)
if err == nil {
break
}
}
if err == nil {
var startedNode gomaasapi.MAASObject
startedNode, err = result.GetMAASObject()
if err != nil {
logger.Errorf("cannot process API response after successfully starting node: %v", err)
return nil, err
}
return &startedNode, nil
}
return nil, err
} | go | func (env *maasEnviron) startNode(node gomaasapi.MAASObject, series string, userdata []byte) (*gomaasapi.MAASObject, error) {
params := url.Values{
"distro_series": {series},
"user_data": {string(userdata)},
}
// Initialize err to a non-nil value as a sentinel for the following
// loop.
err := fmt.Errorf("(no error)")
var result gomaasapi.JSONObject
for a := shortAttempt.Start(); a.Next() && err != nil; {
result, err = node.CallPost("start", params)
if err == nil {
break
}
}
if err == nil {
var startedNode gomaasapi.MAASObject
startedNode, err = result.GetMAASObject()
if err != nil {
logger.Errorf("cannot process API response after successfully starting node: %v", err)
return nil, err
}
return &startedNode, nil
}
return nil, err
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"startNode",
"(",
"node",
"gomaasapi",
".",
"MAASObject",
",",
"series",
"string",
",",
"userdata",
"[",
"]",
"byte",
")",
"(",
"*",
"gomaasapi",
".",
"MAASObject",
",",
"error",
")",
"{",
"params",
":=",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"series",
"}",
",",
"\"",
"\"",
":",
"{",
"string",
"(",
"userdata",
")",
"}",
",",
"}",
"\n",
"// Initialize err to a non-nil value as a sentinel for the following",
"// loop.",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"var",
"result",
"gomaasapi",
".",
"JSONObject",
"\n",
"for",
"a",
":=",
"shortAttempt",
".",
"Start",
"(",
")",
";",
"a",
".",
"Next",
"(",
")",
"&&",
"err",
"!=",
"nil",
";",
"{",
"result",
",",
"err",
"=",
"node",
".",
"CallPost",
"(",
"\"",
"\"",
",",
"params",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
"==",
"nil",
"{",
"var",
"startedNode",
"gomaasapi",
".",
"MAASObject",
"\n",
"startedNode",
",",
"err",
"=",
"result",
".",
"GetMAASObject",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"startedNode",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}"
] | // startNode installs and boots a node. | [
"startNode",
"installs",
"and",
"boots",
"a",
"node",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L879-L905 |
154,430 | juju/juju | provider/maas/environ.go | newCloudinitConfig | func (env *maasEnviron) newCloudinitConfig(hostname, forSeries string) (cloudinit.CloudConfig, error) {
cloudcfg, err := cloudinit.New(forSeries)
if err != nil {
return nil, err
}
info := machineInfo{hostname}
runCmd, err := info.cloudinitRunCmd(cloudcfg)
if err != nil {
return nil, errors.Trace(err)
}
operatingSystem, err := series.GetOSFromSeries(forSeries)
if err != nil {
return nil, errors.Trace(err)
}
switch operatingSystem {
case os.Windows:
cloudcfg.AddScripts(runCmd)
case os.Ubuntu:
cloudcfg.SetSystemUpdate(true)
cloudcfg.AddScripts("set -xe", runCmd)
// DisableNetworkManagement can still disable the bridge(s) creation.
if on, set := env.Config().DisableNetworkManagement(); on && set {
logger.Infof(
"network management disabled - not using %q bridge for containers",
instancecfg.DefaultBridgeName,
)
break
}
cloudcfg.AddPackage("bridge-utils")
}
return cloudcfg, nil
} | go | func (env *maasEnviron) newCloudinitConfig(hostname, forSeries string) (cloudinit.CloudConfig, error) {
cloudcfg, err := cloudinit.New(forSeries)
if err != nil {
return nil, err
}
info := machineInfo{hostname}
runCmd, err := info.cloudinitRunCmd(cloudcfg)
if err != nil {
return nil, errors.Trace(err)
}
operatingSystem, err := series.GetOSFromSeries(forSeries)
if err != nil {
return nil, errors.Trace(err)
}
switch operatingSystem {
case os.Windows:
cloudcfg.AddScripts(runCmd)
case os.Ubuntu:
cloudcfg.SetSystemUpdate(true)
cloudcfg.AddScripts("set -xe", runCmd)
// DisableNetworkManagement can still disable the bridge(s) creation.
if on, set := env.Config().DisableNetworkManagement(); on && set {
logger.Infof(
"network management disabled - not using %q bridge for containers",
instancecfg.DefaultBridgeName,
)
break
}
cloudcfg.AddPackage("bridge-utils")
}
return cloudcfg, nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"newCloudinitConfig",
"(",
"hostname",
",",
"forSeries",
"string",
")",
"(",
"cloudinit",
".",
"CloudConfig",
",",
"error",
")",
"{",
"cloudcfg",
",",
"err",
":=",
"cloudinit",
".",
"New",
"(",
"forSeries",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"info",
":=",
"machineInfo",
"{",
"hostname",
"}",
"\n",
"runCmd",
",",
"err",
":=",
"info",
".",
"cloudinitRunCmd",
"(",
"cloudcfg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"operatingSystem",
",",
"err",
":=",
"series",
".",
"GetOSFromSeries",
"(",
"forSeries",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"switch",
"operatingSystem",
"{",
"case",
"os",
".",
"Windows",
":",
"cloudcfg",
".",
"AddScripts",
"(",
"runCmd",
")",
"\n",
"case",
"os",
".",
"Ubuntu",
":",
"cloudcfg",
".",
"SetSystemUpdate",
"(",
"true",
")",
"\n",
"cloudcfg",
".",
"AddScripts",
"(",
"\"",
"\"",
",",
"runCmd",
")",
"\n",
"// DisableNetworkManagement can still disable the bridge(s) creation.",
"if",
"on",
",",
"set",
":=",
"env",
".",
"Config",
"(",
")",
".",
"DisableNetworkManagement",
"(",
")",
";",
"on",
"&&",
"set",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"instancecfg",
".",
"DefaultBridgeName",
",",
")",
"\n",
"break",
"\n",
"}",
"\n",
"cloudcfg",
".",
"AddPackage",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"cloudcfg",
",",
"nil",
"\n",
"}"
] | // newCloudinitConfig creates a cloudinit.Config structure suitable as a base
// for initialising a MAAS node. | [
"newCloudinitConfig",
"creates",
"a",
"cloudinit",
".",
"Config",
"structure",
"suitable",
"as",
"a",
"base",
"for",
"initialising",
"a",
"MAAS",
"node",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L1395-L1428 |
154,431 | juju/juju | provider/maas/environ.go | Instances | func (env *maasEnviron) Instances(ctx context.ProviderCallContext, ids []instance.Id) ([]instances.Instance, error) {
if len(ids) == 0 {
// This would be treated as "return all instances" below, so
// treat it as a special case.
// The interface requires us to return this particular error
// if no instances were found.
return nil, environs.ErrNoInstances
}
acquired, err := env.acquiredInstances(ctx, ids)
if err != nil {
return nil, errors.Trace(err)
}
if len(acquired) == 0 {
return nil, environs.ErrNoInstances
}
idMap := make(map[instance.Id]instances.Instance)
for _, instance := range acquired {
idMap[instance.Id()] = instance
}
missing := false
result := make([]instances.Instance, len(ids))
for index, id := range ids {
val, ok := idMap[id]
if !ok {
missing = true
continue
}
result[index] = val
}
if missing {
return result, environs.ErrPartialInstances
}
return result, nil
} | go | func (env *maasEnviron) Instances(ctx context.ProviderCallContext, ids []instance.Id) ([]instances.Instance, error) {
if len(ids) == 0 {
// This would be treated as "return all instances" below, so
// treat it as a special case.
// The interface requires us to return this particular error
// if no instances were found.
return nil, environs.ErrNoInstances
}
acquired, err := env.acquiredInstances(ctx, ids)
if err != nil {
return nil, errors.Trace(err)
}
if len(acquired) == 0 {
return nil, environs.ErrNoInstances
}
idMap := make(map[instance.Id]instances.Instance)
for _, instance := range acquired {
idMap[instance.Id()] = instance
}
missing := false
result := make([]instances.Instance, len(ids))
for index, id := range ids {
val, ok := idMap[id]
if !ok {
missing = true
continue
}
result[index] = val
}
if missing {
return result, environs.ErrPartialInstances
}
return result, nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"Instances",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"ids",
"[",
"]",
"instance",
".",
"Id",
")",
"(",
"[",
"]",
"instances",
".",
"Instance",
",",
"error",
")",
"{",
"if",
"len",
"(",
"ids",
")",
"==",
"0",
"{",
"// This would be treated as \"return all instances\" below, so",
"// treat it as a special case.",
"// The interface requires us to return this particular error",
"// if no instances were found.",
"return",
"nil",
",",
"environs",
".",
"ErrNoInstances",
"\n",
"}",
"\n",
"acquired",
",",
"err",
":=",
"env",
".",
"acquiredInstances",
"(",
"ctx",
",",
"ids",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"acquired",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"environs",
".",
"ErrNoInstances",
"\n",
"}",
"\n\n",
"idMap",
":=",
"make",
"(",
"map",
"[",
"instance",
".",
"Id",
"]",
"instances",
".",
"Instance",
")",
"\n",
"for",
"_",
",",
"instance",
":=",
"range",
"acquired",
"{",
"idMap",
"[",
"instance",
".",
"Id",
"(",
")",
"]",
"=",
"instance",
"\n",
"}",
"\n\n",
"missing",
":=",
"false",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"instances",
".",
"Instance",
",",
"len",
"(",
"ids",
")",
")",
"\n",
"for",
"index",
",",
"id",
":=",
"range",
"ids",
"{",
"val",
",",
"ok",
":=",
"idMap",
"[",
"id",
"]",
"\n",
"if",
"!",
"ok",
"{",
"missing",
"=",
"true",
"\n",
"continue",
"\n",
"}",
"\n",
"result",
"[",
"index",
"]",
"=",
"val",
"\n",
"}",
"\n\n",
"if",
"missing",
"{",
"return",
"result",
",",
"environs",
".",
"ErrPartialInstances",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // Instances returns the instances.Instance objects corresponding to the given
// slice of instance.Id. The error is ErrNoInstances if no instances
// were found. | [
"Instances",
"returns",
"the",
"instances",
".",
"Instance",
"objects",
"corresponding",
"to",
"the",
"given",
"slice",
"of",
"instance",
".",
"Id",
".",
"The",
"error",
"is",
"ErrNoInstances",
"if",
"no",
"instances",
"were",
"found",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L1568-L1604 |
154,432 | juju/juju | provider/maas/environ.go | instances1 | func (env *maasEnviron) instances1(ctx context.ProviderCallContext, filter url.Values) ([]instances.Instance, error) {
nodeListing := env.getMAASClient().GetSubObject("nodes")
listNodeObjects, err := nodeListing.CallGet("list", filter)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
listNodes, err := listNodeObjects.GetArray()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
instances := make([]instances.Instance, len(listNodes))
for index, nodeObj := range listNodes {
node, err := nodeObj.GetMAASObject()
if err != nil {
return nil, err
}
instances[index] = &maas1Instance{
maasObject: &node,
environ: env,
statusGetter: env.deploymentStatusOne,
}
}
return instances, nil
} | go | func (env *maasEnviron) instances1(ctx context.ProviderCallContext, filter url.Values) ([]instances.Instance, error) {
nodeListing := env.getMAASClient().GetSubObject("nodes")
listNodeObjects, err := nodeListing.CallGet("list", filter)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
listNodes, err := listNodeObjects.GetArray()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, err
}
instances := make([]instances.Instance, len(listNodes))
for index, nodeObj := range listNodes {
node, err := nodeObj.GetMAASObject()
if err != nil {
return nil, err
}
instances[index] = &maas1Instance{
maasObject: &node,
environ: env,
statusGetter: env.deploymentStatusOne,
}
}
return instances, nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"instances1",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"filter",
"url",
".",
"Values",
")",
"(",
"[",
"]",
"instances",
".",
"Instance",
",",
"error",
")",
"{",
"nodeListing",
":=",
"env",
".",
"getMAASClient",
"(",
")",
".",
"GetSubObject",
"(",
"\"",
"\"",
")",
"\n",
"listNodeObjects",
",",
"err",
":=",
"nodeListing",
".",
"CallGet",
"(",
"\"",
"\"",
",",
"filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"listNodes",
",",
"err",
":=",
"listNodeObjects",
".",
"GetArray",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"instances",
":=",
"make",
"(",
"[",
"]",
"instances",
".",
"Instance",
",",
"len",
"(",
"listNodes",
")",
")",
"\n",
"for",
"index",
",",
"nodeObj",
":=",
"range",
"listNodes",
"{",
"node",
",",
"err",
":=",
"nodeObj",
".",
"GetMAASObject",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"instances",
"[",
"index",
"]",
"=",
"&",
"maas1Instance",
"{",
"maasObject",
":",
"&",
"node",
",",
"environ",
":",
"env",
",",
"statusGetter",
":",
"env",
".",
"deploymentStatusOne",
",",
"}",
"\n",
"}",
"\n",
"return",
"instances",
",",
"nil",
"\n",
"}"
] | // instances calls the MAAS API to list nodes matching the given filter. | [
"instances",
"calls",
"the",
"MAAS",
"API",
"to",
"list",
"nodes",
"matching",
"the",
"given",
"filter",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L1625-L1650 |
154,433 | juju/juju | provider/maas/environ.go | subnetsFromNode | func (env *maasEnviron) subnetsFromNode(ctx context.ProviderCallContext, nodeId string) ([]gomaasapi.JSONObject, error) {
client := env.getMAASClient().GetSubObject("nodes").GetSubObject(nodeId)
json, err := client.CallGet("", nil)
if err != nil {
if maasErr, ok := errors.Cause(err).(gomaasapi.ServerError); ok && maasErr.StatusCode == http.StatusNotFound {
return nil, errors.NotFoundf("intance %q", nodeId)
}
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
nodeMap, err := json.GetMap()
if err != nil {
return nil, errors.Trace(err)
}
interfacesArray, err := nodeMap["interface_set"].GetArray()
if err != nil {
return nil, errors.Trace(err)
}
var subnets []gomaasapi.JSONObject
for _, iface := range interfacesArray {
ifaceMap, err := iface.GetMap()
if err != nil {
return nil, errors.Trace(err)
}
linksArray, err := ifaceMap["links"].GetArray()
if err != nil {
return nil, errors.Trace(err)
}
for _, link := range linksArray {
linkMap, err := link.GetMap()
if err != nil {
return nil, errors.Trace(err)
}
subnet, ok := linkMap["subnet"]
if !ok {
return nil, errors.New("subnet not found")
}
subnets = append(subnets, subnet)
}
}
return subnets, nil
} | go | func (env *maasEnviron) subnetsFromNode(ctx context.ProviderCallContext, nodeId string) ([]gomaasapi.JSONObject, error) {
client := env.getMAASClient().GetSubObject("nodes").GetSubObject(nodeId)
json, err := client.CallGet("", nil)
if err != nil {
if maasErr, ok := errors.Cause(err).(gomaasapi.ServerError); ok && maasErr.StatusCode == http.StatusNotFound {
return nil, errors.NotFoundf("intance %q", nodeId)
}
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
nodeMap, err := json.GetMap()
if err != nil {
return nil, errors.Trace(err)
}
interfacesArray, err := nodeMap["interface_set"].GetArray()
if err != nil {
return nil, errors.Trace(err)
}
var subnets []gomaasapi.JSONObject
for _, iface := range interfacesArray {
ifaceMap, err := iface.GetMap()
if err != nil {
return nil, errors.Trace(err)
}
linksArray, err := ifaceMap["links"].GetArray()
if err != nil {
return nil, errors.Trace(err)
}
for _, link := range linksArray {
linkMap, err := link.GetMap()
if err != nil {
return nil, errors.Trace(err)
}
subnet, ok := linkMap["subnet"]
if !ok {
return nil, errors.New("subnet not found")
}
subnets = append(subnets, subnet)
}
}
return subnets, nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"subnetsFromNode",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"nodeId",
"string",
")",
"(",
"[",
"]",
"gomaasapi",
".",
"JSONObject",
",",
"error",
")",
"{",
"client",
":=",
"env",
".",
"getMAASClient",
"(",
")",
".",
"GetSubObject",
"(",
"\"",
"\"",
")",
".",
"GetSubObject",
"(",
"nodeId",
")",
"\n",
"json",
",",
"err",
":=",
"client",
".",
"CallGet",
"(",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"maasErr",
",",
"ok",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
".",
"(",
"gomaasapi",
".",
"ServerError",
")",
";",
"ok",
"&&",
"maasErr",
".",
"StatusCode",
"==",
"http",
".",
"StatusNotFound",
"{",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"nodeId",
")",
"\n",
"}",
"\n",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"nodeMap",
",",
"err",
":=",
"json",
".",
"GetMap",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"interfacesArray",
",",
"err",
":=",
"nodeMap",
"[",
"\"",
"\"",
"]",
".",
"GetArray",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"var",
"subnets",
"[",
"]",
"gomaasapi",
".",
"JSONObject",
"\n",
"for",
"_",
",",
"iface",
":=",
"range",
"interfacesArray",
"{",
"ifaceMap",
",",
"err",
":=",
"iface",
".",
"GetMap",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"linksArray",
",",
"err",
":=",
"ifaceMap",
"[",
"\"",
"\"",
"]",
".",
"GetArray",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"link",
":=",
"range",
"linksArray",
"{",
"linkMap",
",",
"err",
":=",
"link",
".",
"GetMap",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"subnet",
",",
"ok",
":=",
"linkMap",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"subnets",
"=",
"append",
"(",
"subnets",
",",
"subnet",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"subnets",
",",
"nil",
"\n",
"}"
] | // subnetsFromNode fetches all the subnets for a specific node. | [
"subnetsFromNode",
"fetches",
"all",
"the",
"subnets",
"for",
"a",
"specific",
"node",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L1666-L1707 |
154,434 | juju/juju | provider/maas/environ.go | subnetFromJson | func (env *maasEnviron) subnetFromJson(subnet gomaasapi.JSONObject, spaceId network.Id) (network.SubnetInfo, error) {
var subnetInfo network.SubnetInfo
fields, err := subnet.GetMap()
if err != nil {
return subnetInfo, errors.Trace(err)
}
subnetIdFloat, err := fields["id"].GetFloat64()
if err != nil {
return subnetInfo, errors.Annotatef(err, "cannot get subnet Id")
}
subnetId := strconv.Itoa(int(subnetIdFloat))
cidr, err := fields["cidr"].GetString()
if err != nil {
return subnetInfo, errors.Annotatef(err, "cannot get cidr")
}
vid := 0
vidField, ok := fields["vid"]
if ok && !vidField.IsNil() {
// vid is optional, so assume it's 0 when missing or nil.
vidFloat, err := vidField.GetFloat64()
if err != nil {
return subnetInfo, errors.Errorf("cannot get vlan tag: %v", err)
}
vid = int(vidFloat)
}
subnetInfo = network.SubnetInfo{
ProviderId: network.Id(subnetId),
VLANTag: vid,
CIDR: cidr,
SpaceProviderId: spaceId,
}
return subnetInfo, nil
} | go | func (env *maasEnviron) subnetFromJson(subnet gomaasapi.JSONObject, spaceId network.Id) (network.SubnetInfo, error) {
var subnetInfo network.SubnetInfo
fields, err := subnet.GetMap()
if err != nil {
return subnetInfo, errors.Trace(err)
}
subnetIdFloat, err := fields["id"].GetFloat64()
if err != nil {
return subnetInfo, errors.Annotatef(err, "cannot get subnet Id")
}
subnetId := strconv.Itoa(int(subnetIdFloat))
cidr, err := fields["cidr"].GetString()
if err != nil {
return subnetInfo, errors.Annotatef(err, "cannot get cidr")
}
vid := 0
vidField, ok := fields["vid"]
if ok && !vidField.IsNil() {
// vid is optional, so assume it's 0 when missing or nil.
vidFloat, err := vidField.GetFloat64()
if err != nil {
return subnetInfo, errors.Errorf("cannot get vlan tag: %v", err)
}
vid = int(vidFloat)
}
subnetInfo = network.SubnetInfo{
ProviderId: network.Id(subnetId),
VLANTag: vid,
CIDR: cidr,
SpaceProviderId: spaceId,
}
return subnetInfo, nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"subnetFromJson",
"(",
"subnet",
"gomaasapi",
".",
"JSONObject",
",",
"spaceId",
"network",
".",
"Id",
")",
"(",
"network",
".",
"SubnetInfo",
",",
"error",
")",
"{",
"var",
"subnetInfo",
"network",
".",
"SubnetInfo",
"\n",
"fields",
",",
"err",
":=",
"subnet",
".",
"GetMap",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"subnetInfo",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"subnetIdFloat",
",",
"err",
":=",
"fields",
"[",
"\"",
"\"",
"]",
".",
"GetFloat64",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"subnetInfo",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"subnetId",
":=",
"strconv",
".",
"Itoa",
"(",
"int",
"(",
"subnetIdFloat",
")",
")",
"\n",
"cidr",
",",
"err",
":=",
"fields",
"[",
"\"",
"\"",
"]",
".",
"GetString",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"subnetInfo",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"vid",
":=",
"0",
"\n",
"vidField",
",",
"ok",
":=",
"fields",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"&&",
"!",
"vidField",
".",
"IsNil",
"(",
")",
"{",
"// vid is optional, so assume it's 0 when missing or nil.",
"vidFloat",
",",
"err",
":=",
"vidField",
".",
"GetFloat64",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"subnetInfo",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"vid",
"=",
"int",
"(",
"vidFloat",
")",
"\n",
"}",
"\n\n",
"subnetInfo",
"=",
"network",
".",
"SubnetInfo",
"{",
"ProviderId",
":",
"network",
".",
"Id",
"(",
"subnetId",
")",
",",
"VLANTag",
":",
"vid",
",",
"CIDR",
":",
"cidr",
",",
"SpaceProviderId",
":",
"spaceId",
",",
"}",
"\n",
"return",
"subnetInfo",
",",
"nil",
"\n",
"}"
] | // subnetFromJson populates a network.SubnetInfo from a gomaasapi.JSONObject
// representing a single subnet. This can come from either the subnets api
// endpoint or the node endpoint. | [
"subnetFromJson",
"populates",
"a",
"network",
".",
"SubnetInfo",
"from",
"a",
"gomaasapi",
".",
"JSONObject",
"representing",
"a",
"single",
"subnet",
".",
"This",
"can",
"come",
"from",
"either",
"the",
"subnets",
"api",
"endpoint",
"or",
"the",
"node",
"endpoint",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L1712-L1745 |
154,435 | juju/juju | provider/maas/environ.go | fetchAllSubnets | func (env *maasEnviron) fetchAllSubnets(ctx context.ProviderCallContext) ([]gomaasapi.JSONObject, error) {
client := env.getMAASClient().GetSubObject("subnets")
json, err := client.CallGet("", nil)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
return json.GetArray()
} | go | func (env *maasEnviron) fetchAllSubnets(ctx context.ProviderCallContext) ([]gomaasapi.JSONObject, error) {
client := env.getMAASClient().GetSubObject("subnets")
json, err := client.CallGet("", nil)
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
return json.GetArray()
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"fetchAllSubnets",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
")",
"(",
"[",
"]",
"gomaasapi",
".",
"JSONObject",
",",
"error",
")",
"{",
"client",
":=",
"env",
".",
"getMAASClient",
"(",
")",
".",
"GetSubObject",
"(",
"\"",
"\"",
")",
"\n\n",
"json",
",",
"err",
":=",
"client",
".",
"CallGet",
"(",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"json",
".",
"GetArray",
"(",
")",
"\n",
"}"
] | // fetchAllSubnets calls the MAAS subnets API to get all subnets and returns the
// JSON response or an error. If capNetworkDeploymentUbuntu is not available, an
// error satisfying errors.IsNotSupported will be returned. | [
"fetchAllSubnets",
"calls",
"the",
"MAAS",
"subnets",
"API",
"to",
"get",
"all",
"subnets",
"and",
"returns",
"the",
"JSON",
"response",
"or",
"an",
"error",
".",
"If",
"capNetworkDeploymentUbuntu",
"is",
"not",
"available",
"an",
"error",
"satisfying",
"errors",
".",
"IsNotSupported",
"will",
"be",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L1837-L1846 |
154,436 | juju/juju | provider/maas/environ.go | subnetToSpaceIds | func (env *maasEnviron) subnetToSpaceIds(ctx context.ProviderCallContext) (map[string]network.Id, error) {
subnetsMap := make(map[string]network.Id)
spaces, err := env.Spaces(ctx)
if err != nil {
return subnetsMap, errors.Trace(err)
}
for _, space := range spaces {
for _, subnet := range space.Subnets {
subnetsMap[subnet.CIDR] = space.ProviderId
}
}
return subnetsMap, nil
} | go | func (env *maasEnviron) subnetToSpaceIds(ctx context.ProviderCallContext) (map[string]network.Id, error) {
subnetsMap := make(map[string]network.Id)
spaces, err := env.Spaces(ctx)
if err != nil {
return subnetsMap, errors.Trace(err)
}
for _, space := range spaces {
for _, subnet := range space.Subnets {
subnetsMap[subnet.CIDR] = space.ProviderId
}
}
return subnetsMap, nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"subnetToSpaceIds",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
")",
"(",
"map",
"[",
"string",
"]",
"network",
".",
"Id",
",",
"error",
")",
"{",
"subnetsMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"network",
".",
"Id",
")",
"\n",
"spaces",
",",
"err",
":=",
"env",
".",
"Spaces",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"subnetsMap",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"space",
":=",
"range",
"spaces",
"{",
"for",
"_",
",",
"subnet",
":=",
"range",
"space",
".",
"Subnets",
"{",
"subnetsMap",
"[",
"subnet",
".",
"CIDR",
"]",
"=",
"space",
".",
"ProviderId",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"subnetsMap",
",",
"nil",
"\n",
"}"
] | // subnetToSpaceIds fetches the spaces from MAAS and builds a map of subnets to
// space ids. | [
"subnetToSpaceIds",
"fetches",
"the",
"spaces",
"from",
"MAAS",
"and",
"builds",
"a",
"map",
"of",
"subnets",
"to",
"space",
"ids",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L1850-L1862 |
154,437 | juju/juju | provider/maas/environ.go | Spaces | func (env *maasEnviron) Spaces(ctx context.ProviderCallContext) ([]network.SpaceInfo, error) {
if !env.usingMAAS2() {
return env.spaces1(ctx)
}
return env.spaces2(ctx)
} | go | func (env *maasEnviron) Spaces(ctx context.ProviderCallContext) ([]network.SpaceInfo, error) {
if !env.usingMAAS2() {
return env.spaces1(ctx)
}
return env.spaces2(ctx)
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"Spaces",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
")",
"(",
"[",
"]",
"network",
".",
"SpaceInfo",
",",
"error",
")",
"{",
"if",
"!",
"env",
".",
"usingMAAS2",
"(",
")",
"{",
"return",
"env",
".",
"spaces1",
"(",
"ctx",
")",
"\n",
"}",
"\n",
"return",
"env",
".",
"spaces2",
"(",
"ctx",
")",
"\n",
"}"
] | // Spaces returns all the spaces, that have subnets, known to the provider.
// Space name is not filled in as the provider doesn't know the juju name for
// the space. | [
"Spaces",
"returns",
"all",
"the",
"spaces",
"that",
"have",
"subnets",
"known",
"to",
"the",
"provider",
".",
"Space",
"name",
"is",
"not",
"filled",
"in",
"as",
"the",
"provider",
"doesn",
"t",
"know",
"the",
"juju",
"name",
"for",
"the",
"space",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L1867-L1872 |
154,438 | juju/juju | provider/maas/environ.go | Subnets | func (env *maasEnviron) Subnets(ctx context.ProviderCallContext, instId instance.Id, subnetIds []network.Id) ([]network.SubnetInfo, error) {
if env.usingMAAS2() {
return env.subnets2(ctx, instId, subnetIds)
}
return env.subnets1(ctx, instId, subnetIds)
} | go | func (env *maasEnviron) Subnets(ctx context.ProviderCallContext, instId instance.Id, subnetIds []network.Id) ([]network.SubnetInfo, error) {
if env.usingMAAS2() {
return env.subnets2(ctx, instId, subnetIds)
}
return env.subnets1(ctx, instId, subnetIds)
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"Subnets",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"instId",
"instance",
".",
"Id",
",",
"subnetIds",
"[",
"]",
"network",
".",
"Id",
")",
"(",
"[",
"]",
"network",
".",
"SubnetInfo",
",",
"error",
")",
"{",
"if",
"env",
".",
"usingMAAS2",
"(",
")",
"{",
"return",
"env",
".",
"subnets2",
"(",
"ctx",
",",
"instId",
",",
"subnetIds",
")",
"\n",
"}",
"\n",
"return",
"env",
".",
"subnets1",
"(",
"ctx",
",",
"instId",
",",
"subnetIds",
")",
"\n",
"}"
] | // Subnets returns basic information about the specified subnets known
// by the provider for the specified instance. subnetIds must not be
// empty. Implements NetworkingEnviron.Subnets. | [
"Subnets",
"returns",
"basic",
"information",
"about",
"the",
"specified",
"subnets",
"known",
"by",
"the",
"provider",
"for",
"the",
"specified",
"instance",
".",
"subnetIds",
"must",
"not",
"be",
"empty",
".",
"Implements",
"NetworkingEnviron",
".",
"Subnets",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L1954-L1959 |
154,439 | juju/juju | provider/maas/environ.go | AllInstances | func (env *maasEnviron) AllInstances(ctx context.ProviderCallContext) ([]instances.Instance, error) {
return env.acquiredInstances(ctx, nil)
} | go | func (env *maasEnviron) AllInstances(ctx context.ProviderCallContext) ([]instances.Instance, error) {
return env.acquiredInstances(ctx, nil)
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"AllInstances",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
")",
"(",
"[",
"]",
"instances",
".",
"Instance",
",",
"error",
")",
"{",
"return",
"env",
".",
"acquiredInstances",
"(",
"ctx",
",",
"nil",
")",
"\n",
"}"
] | // AllInstances returns all the instances.Instance in this provider. | [
"AllInstances",
"returns",
"all",
"the",
"instances",
".",
"Instance",
"in",
"this",
"provider",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L2080-L2082 |
154,440 | juju/juju | provider/maas/environ.go | Storage | func (env *maasEnviron) Storage() storage.Storage {
env.ecfgMutex.Lock()
defer env.ecfgMutex.Unlock()
return env.storageUnlocked
} | go | func (env *maasEnviron) Storage() storage.Storage {
env.ecfgMutex.Lock()
defer env.ecfgMutex.Unlock()
return env.storageUnlocked
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"Storage",
"(",
")",
"storage",
".",
"Storage",
"{",
"env",
".",
"ecfgMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"env",
".",
"ecfgMutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"env",
".",
"storageUnlocked",
"\n",
"}"
] | // Storage is defined by the Environ interface. | [
"Storage",
"is",
"defined",
"by",
"the",
"Environ",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L2085-L2089 |
154,441 | juju/juju | provider/maas/environ.go | AdoptResources | func (env *maasEnviron) AdoptResources(ctx context.ProviderCallContext, controllerUUID string, fromVersion version.Number) error {
if !env.usingMAAS2() {
// We don't track instance -> controller for MAAS1.
return nil
}
instances, err := env.AllInstances(ctx)
if err != nil {
return errors.Trace(err)
}
var failed []instance.Id
for _, inst := range instances {
maas2Instance, ok := inst.(*maas2Instance)
if !ok {
// This should never happen.
return errors.Errorf("instance %q wasn't a maas2Instance", inst.Id())
}
// From the MAAS docs: "[SetOwnerData] will not remove any
// previous keys unless explicitly passed with an empty
// string." So not passing all of the keys here is fine.
// https://maas.ubuntu.com/docs2.0/api.html#machine
err := maas2Instance.machine.SetOwnerData(map[string]string{tags.JujuController: controllerUUID})
if err != nil {
logger.Errorf("error setting controller uuid tag for %q: %v", inst.Id(), err)
failed = append(failed, inst.Id())
}
}
if failed != nil {
return errors.Errorf("failed to update controller for some instances: %v", failed)
}
return nil
} | go | func (env *maasEnviron) AdoptResources(ctx context.ProviderCallContext, controllerUUID string, fromVersion version.Number) error {
if !env.usingMAAS2() {
// We don't track instance -> controller for MAAS1.
return nil
}
instances, err := env.AllInstances(ctx)
if err != nil {
return errors.Trace(err)
}
var failed []instance.Id
for _, inst := range instances {
maas2Instance, ok := inst.(*maas2Instance)
if !ok {
// This should never happen.
return errors.Errorf("instance %q wasn't a maas2Instance", inst.Id())
}
// From the MAAS docs: "[SetOwnerData] will not remove any
// previous keys unless explicitly passed with an empty
// string." So not passing all of the keys here is fine.
// https://maas.ubuntu.com/docs2.0/api.html#machine
err := maas2Instance.machine.SetOwnerData(map[string]string{tags.JujuController: controllerUUID})
if err != nil {
logger.Errorf("error setting controller uuid tag for %q: %v", inst.Id(), err)
failed = append(failed, inst.Id())
}
}
if failed != nil {
return errors.Errorf("failed to update controller for some instances: %v", failed)
}
return nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"AdoptResources",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"controllerUUID",
"string",
",",
"fromVersion",
"version",
".",
"Number",
")",
"error",
"{",
"if",
"!",
"env",
".",
"usingMAAS2",
"(",
")",
"{",
"// We don't track instance -> controller for MAAS1.",
"return",
"nil",
"\n",
"}",
"\n\n",
"instances",
",",
"err",
":=",
"env",
".",
"AllInstances",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"var",
"failed",
"[",
"]",
"instance",
".",
"Id",
"\n",
"for",
"_",
",",
"inst",
":=",
"range",
"instances",
"{",
"maas2Instance",
",",
"ok",
":=",
"inst",
".",
"(",
"*",
"maas2Instance",
")",
"\n",
"if",
"!",
"ok",
"{",
"// This should never happen.",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"inst",
".",
"Id",
"(",
")",
")",
"\n",
"}",
"\n",
"// From the MAAS docs: \"[SetOwnerData] will not remove any",
"// previous keys unless explicitly passed with an empty",
"// string.\" So not passing all of the keys here is fine.",
"// https://maas.ubuntu.com/docs2.0/api.html#machine",
"err",
":=",
"maas2Instance",
".",
"machine",
".",
"SetOwnerData",
"(",
"map",
"[",
"string",
"]",
"string",
"{",
"tags",
".",
"JujuController",
":",
"controllerUUID",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"inst",
".",
"Id",
"(",
")",
",",
"err",
")",
"\n",
"failed",
"=",
"append",
"(",
"failed",
",",
"inst",
".",
"Id",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"failed",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"failed",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // AdoptResources updates all the instances to indicate they
// are now associated with the specified controller. | [
"AdoptResources",
"updates",
"all",
"the",
"instances",
"to",
"indicate",
"they",
"are",
"now",
"associated",
"with",
"the",
"specified",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L2368-L2400 |
154,442 | juju/juju | provider/maas/environ.go | AreSpacesRoutable | func (*maasEnviron) AreSpacesRoutable(ctx context.ProviderCallContext, space1, space2 *environs.ProviderSpaceInfo) (bool, error) {
return false, nil
} | go | func (*maasEnviron) AreSpacesRoutable(ctx context.ProviderCallContext, space1, space2 *environs.ProviderSpaceInfo) (bool, error) {
return false, nil
} | [
"func",
"(",
"*",
"maasEnviron",
")",
"AreSpacesRoutable",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"space1",
",",
"space2",
"*",
"environs",
".",
"ProviderSpaceInfo",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // AreSpacesRoutable implements environs.NetworkingEnviron. | [
"AreSpacesRoutable",
"implements",
"environs",
".",
"NetworkingEnviron",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L2408-L2410 |
154,443 | juju/juju | provider/maas/environ.go | Domains | func (env *maasEnviron) Domains(ctx context.ProviderCallContext) ([]string, error) {
maasDomains, err := env.maasController.Domains()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
result := []string{}
for _, domain := range maasDomains {
result = append(result, domain.Name())
}
return result, nil
} | go | func (env *maasEnviron) Domains(ctx context.ProviderCallContext) ([]string, error) {
maasDomains, err := env.maasController.Domains()
if err != nil {
common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
return nil, errors.Trace(err)
}
result := []string{}
for _, domain := range maasDomains {
result = append(result, domain.Name())
}
return result, nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"Domains",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"maasDomains",
",",
"err",
":=",
"env",
".",
"maasController",
".",
"Domains",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCredentialError",
"(",
"IsAuthorisationFailure",
",",
"err",
",",
"ctx",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"result",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"domain",
":=",
"range",
"maasDomains",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"domain",
".",
"Name",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // Get the domains managed by MAAS. Currently we only need the name of the domain. If more information is needed
// This function can be updated to parse and return a structure. Client code would need to be updated. | [
"Get",
"the",
"domains",
"managed",
"by",
"MAAS",
".",
"Currently",
"we",
"only",
"need",
"the",
"name",
"of",
"the",
"domain",
".",
"If",
"more",
"information",
"is",
"needed",
"This",
"function",
"can",
"be",
"updated",
"to",
"parse",
"and",
"return",
"a",
"structure",
".",
"Client",
"code",
"would",
"need",
"to",
"be",
"updated",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/environ.go#L2424-L2435 |
154,444 | juju/juju | environs/imagemetadata.go | RegisterUserImageDataSourceFunc | func RegisterUserImageDataSourceFunc(id string, f ImageDataSourceFunc) {
datasourceFuncsMu.Lock()
defer datasourceFuncsMu.Unlock()
for i := range datasourceFuncs {
if datasourceFuncs[i].id == id {
datasourceFuncs[i].f = f
return
}
}
logger.Debugf("new user image datasource registered: %v", id)
datasourceFuncs = append([]datasourceFuncId{{id, f}}, datasourceFuncs...)
} | go | func RegisterUserImageDataSourceFunc(id string, f ImageDataSourceFunc) {
datasourceFuncsMu.Lock()
defer datasourceFuncsMu.Unlock()
for i := range datasourceFuncs {
if datasourceFuncs[i].id == id {
datasourceFuncs[i].f = f
return
}
}
logger.Debugf("new user image datasource registered: %v", id)
datasourceFuncs = append([]datasourceFuncId{{id, f}}, datasourceFuncs...)
} | [
"func",
"RegisterUserImageDataSourceFunc",
"(",
"id",
"string",
",",
"f",
"ImageDataSourceFunc",
")",
"{",
"datasourceFuncsMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"datasourceFuncsMu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"i",
":=",
"range",
"datasourceFuncs",
"{",
"if",
"datasourceFuncs",
"[",
"i",
"]",
".",
"id",
"==",
"id",
"{",
"datasourceFuncs",
"[",
"i",
"]",
".",
"f",
"=",
"f",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"datasourceFuncs",
"=",
"append",
"(",
"[",
"]",
"datasourceFuncId",
"{",
"{",
"id",
",",
"f",
"}",
"}",
",",
"datasourceFuncs",
"...",
")",
"\n",
"}"
] | // RegisterUserImageDataSourceFunc registers an ImageDataSourceFunc
// with the specified id at the start of the search path, overwriting
// any function previously registered with the same id. | [
"RegisterUserImageDataSourceFunc",
"registers",
"an",
"ImageDataSourceFunc",
"with",
"the",
"specified",
"id",
"at",
"the",
"start",
"of",
"the",
"search",
"path",
"overwriting",
"any",
"function",
"previously",
"registered",
"with",
"the",
"same",
"id",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata.go#L37-L48 |
154,445 | juju/juju | environs/imagemetadata.go | UnregisterImageDataSourceFunc | func UnregisterImageDataSourceFunc(id string) {
datasourceFuncsMu.Lock()
defer datasourceFuncsMu.Unlock()
for i, f := range datasourceFuncs {
if f.id == id {
head := datasourceFuncs[:i]
tail := datasourceFuncs[i+1:]
datasourceFuncs = append(head, tail...)
return
}
}
} | go | func UnregisterImageDataSourceFunc(id string) {
datasourceFuncsMu.Lock()
defer datasourceFuncsMu.Unlock()
for i, f := range datasourceFuncs {
if f.id == id {
head := datasourceFuncs[:i]
tail := datasourceFuncs[i+1:]
datasourceFuncs = append(head, tail...)
return
}
}
} | [
"func",
"UnregisterImageDataSourceFunc",
"(",
"id",
"string",
")",
"{",
"datasourceFuncsMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"datasourceFuncsMu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"i",
",",
"f",
":=",
"range",
"datasourceFuncs",
"{",
"if",
"f",
".",
"id",
"==",
"id",
"{",
"head",
":=",
"datasourceFuncs",
"[",
":",
"i",
"]",
"\n",
"tail",
":=",
"datasourceFuncs",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"datasourceFuncs",
"=",
"append",
"(",
"head",
",",
"tail",
"...",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // UnregisterImageDataSourceFunc unregisters an ImageDataSourceFunc
// with the specified id. | [
"UnregisterImageDataSourceFunc",
"unregisters",
"an",
"ImageDataSourceFunc",
"with",
"the",
"specified",
"id",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata.go#L68-L79 |
154,446 | juju/juju | environs/imagemetadata.go | ImageMetadataSources | func ImageMetadataSources(env BootstrapEnviron) ([]simplestreams.DataSource, error) {
config := env.Config()
// Add configured and environment-specific datasources.
var sources []simplestreams.DataSource
if userURL, ok := config.ImageMetadataURL(); ok {
verify := utils.VerifySSLHostnames
if !config.SSLHostnameVerification() {
verify = utils.NoVerifySSLHostnames
}
publicKey, _ := simplestreams.UserPublicSigningKey()
sources = append(sources, simplestreams.NewURLSignedDataSource("image-metadata-url", userURL, publicKey, verify, simplestreams.SPECIFIC_CLOUD_DATA, false))
}
envDataSources, err := environmentDataSources(env)
if err != nil {
return nil, err
}
sources = append(sources, envDataSources...)
// Add the official image metadata datasources.
officialDataSources, err := imagemetadata.OfficialDataSources(config.ImageStream())
if err != nil {
return nil, err
}
for _, source := range officialDataSources {
sources = append(sources, source)
}
for _, ds := range sources {
logger.Debugf("obtained image datasource %q", ds.Description())
}
return sources, nil
} | go | func ImageMetadataSources(env BootstrapEnviron) ([]simplestreams.DataSource, error) {
config := env.Config()
// Add configured and environment-specific datasources.
var sources []simplestreams.DataSource
if userURL, ok := config.ImageMetadataURL(); ok {
verify := utils.VerifySSLHostnames
if !config.SSLHostnameVerification() {
verify = utils.NoVerifySSLHostnames
}
publicKey, _ := simplestreams.UserPublicSigningKey()
sources = append(sources, simplestreams.NewURLSignedDataSource("image-metadata-url", userURL, publicKey, verify, simplestreams.SPECIFIC_CLOUD_DATA, false))
}
envDataSources, err := environmentDataSources(env)
if err != nil {
return nil, err
}
sources = append(sources, envDataSources...)
// Add the official image metadata datasources.
officialDataSources, err := imagemetadata.OfficialDataSources(config.ImageStream())
if err != nil {
return nil, err
}
for _, source := range officialDataSources {
sources = append(sources, source)
}
for _, ds := range sources {
logger.Debugf("obtained image datasource %q", ds.Description())
}
return sources, nil
} | [
"func",
"ImageMetadataSources",
"(",
"env",
"BootstrapEnviron",
")",
"(",
"[",
"]",
"simplestreams",
".",
"DataSource",
",",
"error",
")",
"{",
"config",
":=",
"env",
".",
"Config",
"(",
")",
"\n\n",
"// Add configured and environment-specific datasources.",
"var",
"sources",
"[",
"]",
"simplestreams",
".",
"DataSource",
"\n",
"if",
"userURL",
",",
"ok",
":=",
"config",
".",
"ImageMetadataURL",
"(",
")",
";",
"ok",
"{",
"verify",
":=",
"utils",
".",
"VerifySSLHostnames",
"\n",
"if",
"!",
"config",
".",
"SSLHostnameVerification",
"(",
")",
"{",
"verify",
"=",
"utils",
".",
"NoVerifySSLHostnames",
"\n",
"}",
"\n",
"publicKey",
",",
"_",
":=",
"simplestreams",
".",
"UserPublicSigningKey",
"(",
")",
"\n",
"sources",
"=",
"append",
"(",
"sources",
",",
"simplestreams",
".",
"NewURLSignedDataSource",
"(",
"\"",
"\"",
",",
"userURL",
",",
"publicKey",
",",
"verify",
",",
"simplestreams",
".",
"SPECIFIC_CLOUD_DATA",
",",
"false",
")",
")",
"\n",
"}",
"\n\n",
"envDataSources",
",",
"err",
":=",
"environmentDataSources",
"(",
"env",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"sources",
"=",
"append",
"(",
"sources",
",",
"envDataSources",
"...",
")",
"\n\n",
"// Add the official image metadata datasources.",
"officialDataSources",
",",
"err",
":=",
"imagemetadata",
".",
"OfficialDataSources",
"(",
"config",
".",
"ImageStream",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"source",
":=",
"range",
"officialDataSources",
"{",
"sources",
"=",
"append",
"(",
"sources",
",",
"source",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"ds",
":=",
"range",
"sources",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"ds",
".",
"Description",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"sources",
",",
"nil",
"\n",
"}"
] | // ImageMetadataSources returns the sources to use when looking for
// simplestreams image id metadata for the given stream. | [
"ImageMetadataSources",
"returns",
"the",
"sources",
"to",
"use",
"when",
"looking",
"for",
"simplestreams",
"image",
"id",
"metadata",
"for",
"the",
"given",
"stream",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata.go#L83-L115 |
154,447 | juju/juju | environs/imagemetadata.go | environmentDataSources | func environmentDataSources(bootstrapEnviron BootstrapEnviron) ([]simplestreams.DataSource, error) {
datasourceFuncsMu.RLock()
defer datasourceFuncsMu.RUnlock()
var datasources []simplestreams.DataSource
env, ok := bootstrapEnviron.(Environ)
if !ok {
logger.Debugf("environmentDataSources is supported for IAAS, environ %#v is not Environ", bootstrapEnviron)
// ignore for CAAS
return datasources, nil
}
for _, f := range datasourceFuncs {
datasource, err := f.f(env)
if err != nil {
if errors.IsNotSupported(err) {
continue
}
return nil, err
}
datasources = append(datasources, datasource)
}
return datasources, nil
} | go | func environmentDataSources(bootstrapEnviron BootstrapEnviron) ([]simplestreams.DataSource, error) {
datasourceFuncsMu.RLock()
defer datasourceFuncsMu.RUnlock()
var datasources []simplestreams.DataSource
env, ok := bootstrapEnviron.(Environ)
if !ok {
logger.Debugf("environmentDataSources is supported for IAAS, environ %#v is not Environ", bootstrapEnviron)
// ignore for CAAS
return datasources, nil
}
for _, f := range datasourceFuncs {
datasource, err := f.f(env)
if err != nil {
if errors.IsNotSupported(err) {
continue
}
return nil, err
}
datasources = append(datasources, datasource)
}
return datasources, nil
} | [
"func",
"environmentDataSources",
"(",
"bootstrapEnviron",
"BootstrapEnviron",
")",
"(",
"[",
"]",
"simplestreams",
".",
"DataSource",
",",
"error",
")",
"{",
"datasourceFuncsMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"datasourceFuncsMu",
".",
"RUnlock",
"(",
")",
"\n",
"var",
"datasources",
"[",
"]",
"simplestreams",
".",
"DataSource",
"\n",
"env",
",",
"ok",
":=",
"bootstrapEnviron",
".",
"(",
"Environ",
")",
"\n",
"if",
"!",
"ok",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"bootstrapEnviron",
")",
"\n",
"// ignore for CAAS",
"return",
"datasources",
",",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"datasourceFuncs",
"{",
"datasource",
",",
"err",
":=",
"f",
".",
"f",
"(",
"env",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"errors",
".",
"IsNotSupported",
"(",
"err",
")",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"datasources",
"=",
"append",
"(",
"datasources",
",",
"datasource",
")",
"\n",
"}",
"\n",
"return",
"datasources",
",",
"nil",
"\n",
"}"
] | // environmentDataSources returns simplestreams datasources for the environment
// by calling the functions registered in RegisterImageDataSourceFunc.
// The datasources returned will be in the same order the functions were registered. | [
"environmentDataSources",
"returns",
"simplestreams",
"datasources",
"for",
"the",
"environment",
"by",
"calling",
"the",
"functions",
"registered",
"in",
"RegisterImageDataSourceFunc",
".",
"The",
"datasources",
"returned",
"will",
"be",
"in",
"the",
"same",
"order",
"the",
"functions",
"were",
"registered",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata.go#L120-L141 |
154,448 | juju/juju | environs/config.go | UnregisterProvider | func (r *globalProviderRegistry) UnregisterProvider(providerType string) {
delete(r.providers, providerType)
for a, p := range r.aliases {
if p == providerType {
delete(r.aliases, a)
}
}
} | go | func (r *globalProviderRegistry) UnregisterProvider(providerType string) {
delete(r.providers, providerType)
for a, p := range r.aliases {
if p == providerType {
delete(r.aliases, a)
}
}
} | [
"func",
"(",
"r",
"*",
"globalProviderRegistry",
")",
"UnregisterProvider",
"(",
"providerType",
"string",
")",
"{",
"delete",
"(",
"r",
".",
"providers",
",",
"providerType",
")",
"\n",
"for",
"a",
",",
"p",
":=",
"range",
"r",
".",
"aliases",
"{",
"if",
"p",
"==",
"providerType",
"{",
"delete",
"(",
"r",
".",
"aliases",
",",
"a",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // UnregisterProvider removes the named provider from the list of available providers. | [
"UnregisterProvider",
"removes",
"the",
"named",
"provider",
"from",
"the",
"list",
"of",
"available",
"providers",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/config.go#L67-L74 |
154,449 | juju/juju | environs/config.go | RegisterProvider | func RegisterProvider(name string, p CloudEnvironProvider, alias ...string) (unregister func()) {
if err := GlobalProviderRegistry().RegisterProvider(p, name, alias...); err != nil {
panic(fmt.Errorf("juju: %v", err))
}
return func() {
GlobalProviderRegistry().UnregisterProvider(name)
}
} | go | func RegisterProvider(name string, p CloudEnvironProvider, alias ...string) (unregister func()) {
if err := GlobalProviderRegistry().RegisterProvider(p, name, alias...); err != nil {
panic(fmt.Errorf("juju: %v", err))
}
return func() {
GlobalProviderRegistry().UnregisterProvider(name)
}
} | [
"func",
"RegisterProvider",
"(",
"name",
"string",
",",
"p",
"CloudEnvironProvider",
",",
"alias",
"...",
"string",
")",
"(",
"unregister",
"func",
"(",
")",
")",
"{",
"if",
"err",
":=",
"GlobalProviderRegistry",
"(",
")",
".",
"RegisterProvider",
"(",
"p",
",",
"name",
",",
"alias",
"...",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"func",
"(",
")",
"{",
"GlobalProviderRegistry",
"(",
")",
".",
"UnregisterProvider",
"(",
"name",
")",
"\n",
"}",
"\n",
"}"
] | // RegisterProvider registers a new environment provider. Name gives the name
// of the provider, and p the interface to that provider.
//
// RegisterProvider will panic if the provider name or any of the aliases
// are registered more than once.
// The return function can be used to unregister the provider and is used by tests. | [
"RegisterProvider",
"registers",
"a",
"new",
"environment",
"provider",
".",
"Name",
"gives",
"the",
"name",
"of",
"the",
"provider",
"and",
"p",
"the",
"interface",
"to",
"that",
"provider",
".",
"RegisterProvider",
"will",
"panic",
"if",
"the",
"provider",
"name",
"or",
"any",
"of",
"the",
"aliases",
"are",
"registered",
"more",
"than",
"once",
".",
"The",
"return",
"function",
"can",
"be",
"used",
"to",
"unregister",
"the",
"provider",
"and",
"is",
"used",
"by",
"tests",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/config.go#L103-L110 |
154,450 | juju/juju | logfwd/syslog/client.go | Open | func Open(cfg RawConfig) (*Client, error) {
client, err := OpenForSender(cfg, &senderOpener{})
return client, errors.Trace(err)
} | go | func Open(cfg RawConfig) (*Client, error) {
client, err := OpenForSender(cfg, &senderOpener{})
return client, errors.Trace(err)
} | [
"func",
"Open",
"(",
"cfg",
"RawConfig",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"client",
",",
"err",
":=",
"OpenForSender",
"(",
"cfg",
",",
"&",
"senderOpener",
"{",
"}",
")",
"\n",
"return",
"client",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // Open connects to a remote syslog host and wraps that connection
// in a new client. | [
"Open",
"connects",
"to",
"a",
"remote",
"syslog",
"host",
"and",
"wraps",
"that",
"connection",
"in",
"a",
"new",
"client",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/logfwd/syslog/client.go#L55-L58 |
154,451 | juju/juju | logfwd/syslog/client.go | OpenForSender | func OpenForSender(cfg RawConfig, opener SenderOpener) (*Client, error) {
if err := cfg.Validate(); err != nil {
return nil, errors.Trace(err)
}
sender, err := open(cfg, opener)
if err != nil {
return nil, errors.Trace(err)
}
client := &Client{
Sender: sender,
}
return client, nil
} | go | func OpenForSender(cfg RawConfig, opener SenderOpener) (*Client, error) {
if err := cfg.Validate(); err != nil {
return nil, errors.Trace(err)
}
sender, err := open(cfg, opener)
if err != nil {
return nil, errors.Trace(err)
}
client := &Client{
Sender: sender,
}
return client, nil
} | [
"func",
"OpenForSender",
"(",
"cfg",
"RawConfig",
",",
"opener",
"SenderOpener",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"if",
"err",
":=",
"cfg",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"sender",
",",
"err",
":=",
"open",
"(",
"cfg",
",",
"opener",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"client",
":=",
"&",
"Client",
"{",
"Sender",
":",
"sender",
",",
"}",
"\n",
"return",
"client",
",",
"nil",
"\n",
"}"
] | // OpenForSender connects to a remote syslog host and wraps that
// connection in a new client. | [
"OpenForSender",
"connects",
"to",
"a",
"remote",
"syslog",
"host",
"and",
"wraps",
"that",
"connection",
"in",
"a",
"new",
"client",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/logfwd/syslog/client.go#L62-L76 |
154,452 | juju/juju | logfwd/syslog/client.go | Close | func (client Client) Close() error {
err := client.Sender.Close()
return errors.Trace(err)
} | go | func (client Client) Close() error {
err := client.Sender.Close()
return errors.Trace(err)
} | [
"func",
"(",
"client",
"Client",
")",
"Close",
"(",
")",
"error",
"{",
"err",
":=",
"client",
".",
"Sender",
".",
"Close",
"(",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // Close closes the client's connection. | [
"Close",
"closes",
"the",
"client",
"s",
"connection",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/logfwd/syslog/client.go#L96-L99 |
154,453 | juju/juju | logfwd/syslog/client.go | Send | func (client Client) Send(records []logfwd.Record) error {
for _, rec := range records {
msg, err := messageFromRecord(rec)
if err != nil {
return errors.Trace(err)
}
if err := client.Sender.Send(msg); err != nil {
return errors.Trace(err)
}
}
return nil
} | go | func (client Client) Send(records []logfwd.Record) error {
for _, rec := range records {
msg, err := messageFromRecord(rec)
if err != nil {
return errors.Trace(err)
}
if err := client.Sender.Send(msg); err != nil {
return errors.Trace(err)
}
}
return nil
} | [
"func",
"(",
"client",
"Client",
")",
"Send",
"(",
"records",
"[",
"]",
"logfwd",
".",
"Record",
")",
"error",
"{",
"for",
"_",
",",
"rec",
":=",
"range",
"records",
"{",
"msg",
",",
"err",
":=",
"messageFromRecord",
"(",
"rec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"client",
".",
"Sender",
".",
"Send",
"(",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Send sends the record to the remote syslog host. | [
"Send",
"sends",
"the",
"record",
"to",
"the",
"remote",
"syslog",
"host",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/logfwd/syslog/client.go#L102-L113 |
154,454 | juju/juju | mongo/collections.go | CollectionFromName | func CollectionFromName(db *mgo.Database, coll string) (Collection, func()) {
session := db.Session.Copy()
newColl := db.C(coll).With(session)
return WrapCollection(newColl), session.Close
} | go | func CollectionFromName(db *mgo.Database, coll string) (Collection, func()) {
session := db.Session.Copy()
newColl := db.C(coll).With(session)
return WrapCollection(newColl), session.Close
} | [
"func",
"CollectionFromName",
"(",
"db",
"*",
"mgo",
".",
"Database",
",",
"coll",
"string",
")",
"(",
"Collection",
",",
"func",
"(",
")",
")",
"{",
"session",
":=",
"db",
".",
"Session",
".",
"Copy",
"(",
")",
"\n",
"newColl",
":=",
"db",
".",
"C",
"(",
"coll",
")",
".",
"With",
"(",
"session",
")",
"\n",
"return",
"WrapCollection",
"(",
"newColl",
")",
",",
"session",
".",
"Close",
"\n",
"}"
] | // CollectionFromName returns a named collection on the specified database,
// initialised with a new session. Also returned is a close function which
// must be called when the collection is no longer required. | [
"CollectionFromName",
"returns",
"a",
"named",
"collection",
"on",
"the",
"specified",
"database",
"initialised",
"with",
"a",
"new",
"session",
".",
"Also",
"returned",
"is",
"a",
"close",
"function",
"which",
"must",
"be",
"called",
"when",
"the",
"collection",
"is",
"no",
"longer",
"required",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/collections.go#L15-L19 |
154,455 | juju/juju | mongo/collections.go | Find | func (cw collectionWrapper) Find(query interface{}) Query {
return queryWrapper{cw.Collection.Find(query)}
} | go | func (cw collectionWrapper) Find(query interface{}) Query {
return queryWrapper{cw.Collection.Find(query)}
} | [
"func",
"(",
"cw",
"collectionWrapper",
")",
"Find",
"(",
"query",
"interface",
"{",
"}",
")",
"Query",
"{",
"return",
"queryWrapper",
"{",
"cw",
".",
"Collection",
".",
"Find",
"(",
"query",
")",
"}",
"\n",
"}"
] | // Find is part of the Collection interface. | [
"Find",
"is",
"part",
"of",
"the",
"Collection",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/collections.go#L112-L114 |
154,456 | juju/juju | mongo/collections.go | Pipe | func (cw collectionWrapper) Pipe(pipeline interface{}) *mgo.Pipe {
return cw.Collection.Pipe(pipeline)
} | go | func (cw collectionWrapper) Pipe(pipeline interface{}) *mgo.Pipe {
return cw.Collection.Pipe(pipeline)
} | [
"func",
"(",
"cw",
"collectionWrapper",
")",
"Pipe",
"(",
"pipeline",
"interface",
"{",
"}",
")",
"*",
"mgo",
".",
"Pipe",
"{",
"return",
"cw",
".",
"Collection",
".",
"Pipe",
"(",
"pipeline",
")",
"\n",
"}"
] | // Pipe is part of the Collection interface | [
"Pipe",
"is",
"part",
"of",
"the",
"Collection",
"interface"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/collections.go#L117-L119 |
154,457 | juju/juju | mongo/collections.go | FindId | func (cw collectionWrapper) FindId(id interface{}) Query {
return queryWrapper{cw.Collection.FindId(id)}
} | go | func (cw collectionWrapper) FindId(id interface{}) Query {
return queryWrapper{cw.Collection.FindId(id)}
} | [
"func",
"(",
"cw",
"collectionWrapper",
")",
"FindId",
"(",
"id",
"interface",
"{",
"}",
")",
"Query",
"{",
"return",
"queryWrapper",
"{",
"cw",
".",
"Collection",
".",
"FindId",
"(",
"id",
")",
"}",
"\n",
"}"
] | // FindId is part of the Collection interface. | [
"FindId",
"is",
"part",
"of",
"the",
"Collection",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/collections.go#L122-L124 |
154,458 | juju/juju | cmd/juju/cloud/listcredentials.go | NewListCredentialsCommand | func NewListCredentialsCommand() cmd.Command {
return &listCredentialsCommand{
store: jujuclient.NewFileCredentialStore(),
cloudByNameFunc: jujucloud.CloudByName,
}
} | go | func NewListCredentialsCommand() cmd.Command {
return &listCredentialsCommand{
store: jujuclient.NewFileCredentialStore(),
cloudByNameFunc: jujucloud.CloudByName,
}
} | [
"func",
"NewListCredentialsCommand",
"(",
")",
"cmd",
".",
"Command",
"{",
"return",
"&",
"listCredentialsCommand",
"{",
"store",
":",
"jujuclient",
".",
"NewFileCredentialStore",
"(",
")",
",",
"cloudByNameFunc",
":",
"jujucloud",
".",
"CloudByName",
",",
"}",
"\n",
"}"
] | // NewListCredentialsCommand returns a command to list cloud credentials. | [
"NewListCredentialsCommand",
"returns",
"a",
"command",
"to",
"list",
"cloud",
"credentials",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/cloud/listcredentials.go#L116-L121 |
154,459 | juju/juju | cmd/juju/cloud/listcredentials.go | formatCredentialsTabular | func formatCredentialsTabular(writer io.Writer, value interface{}) error {
credentials, ok := value.(credentialsMap)
if !ok {
return errors.Errorf("expected value of type %T, got %T", credentials, value)
}
if len(credentials.Credentials) == 0 {
fmt.Fprintln(writer, "No locally stored credentials to display.")
return nil
}
// For tabular we'll sort alphabetically by cloud, and then by credential name.
var cloudNames []string
for name := range credentials.Credentials {
cloudNames = append(cloudNames, name)
}
sort.Strings(cloudNames)
tw := output.TabWriter(writer)
w := output.Wrapper{tw}
w.Println("Cloud", "Credentials")
for _, cloudName := range cloudNames {
var haveDefault bool
var credentialNames []string
credentials := credentials.Credentials[cloudName]
for credentialName := range credentials.Credentials {
if credentialName == credentials.DefaultCredential {
credentialNames = append([]string{credentialName + "*"}, credentialNames...)
haveDefault = true
} else {
credentialNames = append(credentialNames, credentialName)
}
}
if haveDefault {
sort.Strings(credentialNames[1:])
} else {
sort.Strings(credentialNames)
}
w.Println(cloudName, strings.Join(credentialNames, ", "))
}
tw.Flush()
return nil
} | go | func formatCredentialsTabular(writer io.Writer, value interface{}) error {
credentials, ok := value.(credentialsMap)
if !ok {
return errors.Errorf("expected value of type %T, got %T", credentials, value)
}
if len(credentials.Credentials) == 0 {
fmt.Fprintln(writer, "No locally stored credentials to display.")
return nil
}
// For tabular we'll sort alphabetically by cloud, and then by credential name.
var cloudNames []string
for name := range credentials.Credentials {
cloudNames = append(cloudNames, name)
}
sort.Strings(cloudNames)
tw := output.TabWriter(writer)
w := output.Wrapper{tw}
w.Println("Cloud", "Credentials")
for _, cloudName := range cloudNames {
var haveDefault bool
var credentialNames []string
credentials := credentials.Credentials[cloudName]
for credentialName := range credentials.Credentials {
if credentialName == credentials.DefaultCredential {
credentialNames = append([]string{credentialName + "*"}, credentialNames...)
haveDefault = true
} else {
credentialNames = append(credentialNames, credentialName)
}
}
if haveDefault {
sort.Strings(credentialNames[1:])
} else {
sort.Strings(credentialNames)
}
w.Println(cloudName, strings.Join(credentialNames, ", "))
}
tw.Flush()
return nil
} | [
"func",
"formatCredentialsTabular",
"(",
"writer",
"io",
".",
"Writer",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"credentials",
",",
"ok",
":=",
"value",
".",
"(",
"credentialsMap",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"credentials",
",",
"value",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"credentials",
".",
"Credentials",
")",
"==",
"0",
"{",
"fmt",
".",
"Fprintln",
"(",
"writer",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// For tabular we'll sort alphabetically by cloud, and then by credential name.",
"var",
"cloudNames",
"[",
"]",
"string",
"\n",
"for",
"name",
":=",
"range",
"credentials",
".",
"Credentials",
"{",
"cloudNames",
"=",
"append",
"(",
"cloudNames",
",",
"name",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"cloudNames",
")",
"\n\n",
"tw",
":=",
"output",
".",
"TabWriter",
"(",
"writer",
")",
"\n",
"w",
":=",
"output",
".",
"Wrapper",
"{",
"tw",
"}",
"\n",
"w",
".",
"Println",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"cloudName",
":=",
"range",
"cloudNames",
"{",
"var",
"haveDefault",
"bool",
"\n",
"var",
"credentialNames",
"[",
"]",
"string",
"\n",
"credentials",
":=",
"credentials",
".",
"Credentials",
"[",
"cloudName",
"]",
"\n",
"for",
"credentialName",
":=",
"range",
"credentials",
".",
"Credentials",
"{",
"if",
"credentialName",
"==",
"credentials",
".",
"DefaultCredential",
"{",
"credentialNames",
"=",
"append",
"(",
"[",
"]",
"string",
"{",
"credentialName",
"+",
"\"",
"\"",
"}",
",",
"credentialNames",
"...",
")",
"\n",
"haveDefault",
"=",
"true",
"\n",
"}",
"else",
"{",
"credentialNames",
"=",
"append",
"(",
"credentialNames",
",",
"credentialName",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"haveDefault",
"{",
"sort",
".",
"Strings",
"(",
"credentialNames",
"[",
"1",
":",
"]",
")",
"\n",
"}",
"else",
"{",
"sort",
".",
"Strings",
"(",
"credentialNames",
")",
"\n",
"}",
"\n",
"w",
".",
"Println",
"(",
"cloudName",
",",
"strings",
".",
"Join",
"(",
"credentialNames",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"tw",
".",
"Flush",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // formatCredentialsTabular writes a tabular summary of cloud information. | [
"formatCredentialsTabular",
"writes",
"a",
"tabular",
"summary",
"of",
"cloud",
"information",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/cloud/listcredentials.go#L240-L283 |
154,460 | juju/juju | apiserver/facades/controller/instancepoller/instancepoller.go | NewFacade | func NewFacade(
st *state.State,
resources facade.Resources,
authorizer facade.Authorizer,
) (*InstancePollerAPI, error) {
m, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
return NewInstancePollerAPI(st, m, resources, authorizer, clock.WallClock)
} | go | func NewFacade(
st *state.State,
resources facade.Resources,
authorizer facade.Authorizer,
) (*InstancePollerAPI, error) {
m, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
return NewInstancePollerAPI(st, m, resources, authorizer, clock.WallClock)
} | [
"func",
"NewFacade",
"(",
"st",
"*",
"state",
".",
"State",
",",
"resources",
"facade",
".",
"Resources",
",",
"authorizer",
"facade",
".",
"Authorizer",
",",
")",
"(",
"*",
"InstancePollerAPI",
",",
"error",
")",
"{",
"m",
",",
"err",
":=",
"st",
".",
"Model",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"NewInstancePollerAPI",
"(",
"st",
",",
"m",
",",
"resources",
",",
"authorizer",
",",
"clock",
".",
"WallClock",
")",
"\n",
"}"
] | // NewFacade wraps NewInstancePollerAPI for facade registration. | [
"NewFacade",
"wraps",
"NewInstancePollerAPI",
"for",
"facade",
"registration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/instancepoller/instancepoller.go#L36-L46 |
154,461 | juju/juju | apiserver/facades/controller/instancepoller/instancepoller.go | NewInstancePollerAPI | func NewInstancePollerAPI(
st *state.State,
m *state.Model,
resources facade.Resources,
authorizer facade.Authorizer,
clock clock.Clock,
) (*InstancePollerAPI, error) {
if !authorizer.AuthController() {
// InstancePoller must run as a controller.
return nil, common.ErrPerm
}
accessMachine := common.AuthFuncForTagKind(names.MachineTagKind)
sti := getState(st, m)
// Life() is supported for machines.
lifeGetter := common.NewLifeGetter(
sti,
accessMachine,
)
// ModelConfig() and WatchForModelConfigChanges() are allowed
// with unrestricted access.
modelWatcher := common.NewModelWatcher(
sti,
resources,
authorizer,
)
// WatchModelMachines() is allowed with unrestricted access.
machinesWatcher := common.NewModelMachinesWatcher(
sti,
resources,
authorizer,
)
// InstanceId() is supported for machines.
instanceIdGetter := common.NewInstanceIdGetter(
sti,
accessMachine,
)
// Status() is supported for machines.
statusGetter := common.NewStatusGetter(
sti,
accessMachine,
)
return &InstancePollerAPI{
LifeGetter: lifeGetter,
ModelWatcher: modelWatcher,
ModelMachinesWatcher: machinesWatcher,
InstanceIdGetter: instanceIdGetter,
StatusGetter: statusGetter,
st: sti,
resources: resources,
authorizer: authorizer,
accessMachine: accessMachine,
clock: clock,
}, nil
} | go | func NewInstancePollerAPI(
st *state.State,
m *state.Model,
resources facade.Resources,
authorizer facade.Authorizer,
clock clock.Clock,
) (*InstancePollerAPI, error) {
if !authorizer.AuthController() {
// InstancePoller must run as a controller.
return nil, common.ErrPerm
}
accessMachine := common.AuthFuncForTagKind(names.MachineTagKind)
sti := getState(st, m)
// Life() is supported for machines.
lifeGetter := common.NewLifeGetter(
sti,
accessMachine,
)
// ModelConfig() and WatchForModelConfigChanges() are allowed
// with unrestricted access.
modelWatcher := common.NewModelWatcher(
sti,
resources,
authorizer,
)
// WatchModelMachines() is allowed with unrestricted access.
machinesWatcher := common.NewModelMachinesWatcher(
sti,
resources,
authorizer,
)
// InstanceId() is supported for machines.
instanceIdGetter := common.NewInstanceIdGetter(
sti,
accessMachine,
)
// Status() is supported for machines.
statusGetter := common.NewStatusGetter(
sti,
accessMachine,
)
return &InstancePollerAPI{
LifeGetter: lifeGetter,
ModelWatcher: modelWatcher,
ModelMachinesWatcher: machinesWatcher,
InstanceIdGetter: instanceIdGetter,
StatusGetter: statusGetter,
st: sti,
resources: resources,
authorizer: authorizer,
accessMachine: accessMachine,
clock: clock,
}, nil
} | [
"func",
"NewInstancePollerAPI",
"(",
"st",
"*",
"state",
".",
"State",
",",
"m",
"*",
"state",
".",
"Model",
",",
"resources",
"facade",
".",
"Resources",
",",
"authorizer",
"facade",
".",
"Authorizer",
",",
"clock",
"clock",
".",
"Clock",
",",
")",
"(",
"*",
"InstancePollerAPI",
",",
"error",
")",
"{",
"if",
"!",
"authorizer",
".",
"AuthController",
"(",
")",
"{",
"// InstancePoller must run as a controller.",
"return",
"nil",
",",
"common",
".",
"ErrPerm",
"\n",
"}",
"\n",
"accessMachine",
":=",
"common",
".",
"AuthFuncForTagKind",
"(",
"names",
".",
"MachineTagKind",
")",
"\n",
"sti",
":=",
"getState",
"(",
"st",
",",
"m",
")",
"\n\n",
"// Life() is supported for machines.",
"lifeGetter",
":=",
"common",
".",
"NewLifeGetter",
"(",
"sti",
",",
"accessMachine",
",",
")",
"\n",
"// ModelConfig() and WatchForModelConfigChanges() are allowed",
"// with unrestricted access.",
"modelWatcher",
":=",
"common",
".",
"NewModelWatcher",
"(",
"sti",
",",
"resources",
",",
"authorizer",
",",
")",
"\n",
"// WatchModelMachines() is allowed with unrestricted access.",
"machinesWatcher",
":=",
"common",
".",
"NewModelMachinesWatcher",
"(",
"sti",
",",
"resources",
",",
"authorizer",
",",
")",
"\n",
"// InstanceId() is supported for machines.",
"instanceIdGetter",
":=",
"common",
".",
"NewInstanceIdGetter",
"(",
"sti",
",",
"accessMachine",
",",
")",
"\n",
"// Status() is supported for machines.",
"statusGetter",
":=",
"common",
".",
"NewStatusGetter",
"(",
"sti",
",",
"accessMachine",
",",
")",
"\n\n",
"return",
"&",
"InstancePollerAPI",
"{",
"LifeGetter",
":",
"lifeGetter",
",",
"ModelWatcher",
":",
"modelWatcher",
",",
"ModelMachinesWatcher",
":",
"machinesWatcher",
",",
"InstanceIdGetter",
":",
"instanceIdGetter",
",",
"StatusGetter",
":",
"statusGetter",
",",
"st",
":",
"sti",
",",
"resources",
":",
"resources",
",",
"authorizer",
":",
"authorizer",
",",
"accessMachine",
":",
"accessMachine",
",",
"clock",
":",
"clock",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewInstancePollerAPI creates a new server-side InstancePoller API
// facade. | [
"NewInstancePollerAPI",
"creates",
"a",
"new",
"server",
"-",
"side",
"InstancePoller",
"API",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/instancepoller/instancepoller.go#L50-L106 |
154,462 | juju/juju | apiserver/facades/controller/instancepoller/instancepoller.go | ProviderAddresses | func (a *InstancePollerAPI) ProviderAddresses(args params.Entities) (params.MachineAddressesResults, error) {
result := params.MachineAddressesResults{
Results: make([]params.MachineAddressesResult, len(args.Entities)),
}
canAccess, err := a.accessMachine()
if err != nil {
return result, err
}
for i, arg := range args.Entities {
machine, err := a.getOneMachine(arg.Tag, canAccess)
if err == nil {
addrs := machine.ProviderAddresses()
result.Results[i].Addresses = params.FromNetworkAddresses(addrs...)
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
} | go | func (a *InstancePollerAPI) ProviderAddresses(args params.Entities) (params.MachineAddressesResults, error) {
result := params.MachineAddressesResults{
Results: make([]params.MachineAddressesResult, len(args.Entities)),
}
canAccess, err := a.accessMachine()
if err != nil {
return result, err
}
for i, arg := range args.Entities {
machine, err := a.getOneMachine(arg.Tag, canAccess)
if err == nil {
addrs := machine.ProviderAddresses()
result.Results[i].Addresses = params.FromNetworkAddresses(addrs...)
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
} | [
"func",
"(",
"a",
"*",
"InstancePollerAPI",
")",
"ProviderAddresses",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"MachineAddressesResults",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"MachineAddressesResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"MachineAddressesResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"canAccess",
",",
"err",
":=",
"a",
".",
"accessMachine",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"err",
"\n",
"}",
"\n",
"for",
"i",
",",
"arg",
":=",
"range",
"args",
".",
"Entities",
"{",
"machine",
",",
"err",
":=",
"a",
".",
"getOneMachine",
"(",
"arg",
".",
"Tag",
",",
"canAccess",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"addrs",
":=",
"machine",
".",
"ProviderAddresses",
"(",
")",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Addresses",
"=",
"params",
".",
"FromNetworkAddresses",
"(",
"addrs",
"...",
")",
"\n",
"}",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // ProviderAddresses returns the list of all known provider addresses
// for each given entity. Only machine tags are accepted. | [
"ProviderAddresses",
"returns",
"the",
"list",
"of",
"all",
"known",
"provider",
"addresses",
"for",
"each",
"given",
"entity",
".",
"Only",
"machine",
"tags",
"are",
"accepted",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/instancepoller/instancepoller.go#L131-L148 |
154,463 | juju/juju | apiserver/facades/controller/instancepoller/instancepoller.go | SetProviderAddresses | func (a *InstancePollerAPI) SetProviderAddresses(args params.SetMachinesAddresses) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.MachineAddresses)),
}
canAccess, err := a.accessMachine()
if err != nil {
return result, err
}
for i, arg := range args.MachineAddresses {
machine, err := a.getOneMachine(arg.Tag, canAccess)
if err == nil {
addrsToSet := params.NetworkAddresses(arg.Addresses...)
err = machine.SetProviderAddresses(addrsToSet...)
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
} | go | func (a *InstancePollerAPI) SetProviderAddresses(args params.SetMachinesAddresses) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.MachineAddresses)),
}
canAccess, err := a.accessMachine()
if err != nil {
return result, err
}
for i, arg := range args.MachineAddresses {
machine, err := a.getOneMachine(arg.Tag, canAccess)
if err == nil {
addrsToSet := params.NetworkAddresses(arg.Addresses...)
err = machine.SetProviderAddresses(addrsToSet...)
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
} | [
"func",
"(",
"a",
"*",
"InstancePollerAPI",
")",
"SetProviderAddresses",
"(",
"args",
"params",
".",
"SetMachinesAddresses",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"ErrorResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"ErrorResult",
",",
"len",
"(",
"args",
".",
"MachineAddresses",
")",
")",
",",
"}",
"\n",
"canAccess",
",",
"err",
":=",
"a",
".",
"accessMachine",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"err",
"\n",
"}",
"\n",
"for",
"i",
",",
"arg",
":=",
"range",
"args",
".",
"MachineAddresses",
"{",
"machine",
",",
"err",
":=",
"a",
".",
"getOneMachine",
"(",
"arg",
".",
"Tag",
",",
"canAccess",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"addrsToSet",
":=",
"params",
".",
"NetworkAddresses",
"(",
"arg",
".",
"Addresses",
"...",
")",
"\n",
"err",
"=",
"machine",
".",
"SetProviderAddresses",
"(",
"addrsToSet",
"...",
")",
"\n",
"}",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // SetProviderAddresses updates the list of known provider addresses
// for each given entity. Only machine tags are accepted. | [
"SetProviderAddresses",
"updates",
"the",
"list",
"of",
"known",
"provider",
"addresses",
"for",
"each",
"given",
"entity",
".",
"Only",
"machine",
"tags",
"are",
"accepted",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/instancepoller/instancepoller.go#L152-L169 |
154,464 | juju/juju | apiserver/facades/controller/instancepoller/instancepoller.go | SetInstanceStatus | func (a *InstancePollerAPI) SetInstanceStatus(args params.SetStatus) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
canAccess, err := a.accessMachine()
if err != nil {
return result, err
}
for i, arg := range args.Entities {
machine, err := a.getOneMachine(arg.Tag, canAccess)
if err == nil {
now := a.clock.Now()
s := status.StatusInfo{
Status: status.Status(arg.Status),
Message: arg.Info,
Data: arg.Data,
Since: &now,
}
err = machine.SetInstanceStatus(s)
if status.Status(arg.Status) == status.ProvisioningError {
s.Status = status.Error
if err == nil {
err = machine.SetStatus(s)
}
}
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
} | go | func (a *InstancePollerAPI) SetInstanceStatus(args params.SetStatus) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
canAccess, err := a.accessMachine()
if err != nil {
return result, err
}
for i, arg := range args.Entities {
machine, err := a.getOneMachine(arg.Tag, canAccess)
if err == nil {
now := a.clock.Now()
s := status.StatusInfo{
Status: status.Status(arg.Status),
Message: arg.Info,
Data: arg.Data,
Since: &now,
}
err = machine.SetInstanceStatus(s)
if status.Status(arg.Status) == status.ProvisioningError {
s.Status = status.Error
if err == nil {
err = machine.SetStatus(s)
}
}
}
result.Results[i].Error = common.ServerError(err)
}
return result, nil
} | [
"func",
"(",
"a",
"*",
"InstancePollerAPI",
")",
"SetInstanceStatus",
"(",
"args",
"params",
".",
"SetStatus",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"ErrorResults",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"params",
".",
"ErrorResult",
",",
"len",
"(",
"args",
".",
"Entities",
")",
")",
",",
"}",
"\n",
"canAccess",
",",
"err",
":=",
"a",
".",
"accessMachine",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"err",
"\n",
"}",
"\n",
"for",
"i",
",",
"arg",
":=",
"range",
"args",
".",
"Entities",
"{",
"machine",
",",
"err",
":=",
"a",
".",
"getOneMachine",
"(",
"arg",
".",
"Tag",
",",
"canAccess",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"now",
":=",
"a",
".",
"clock",
".",
"Now",
"(",
")",
"\n",
"s",
":=",
"status",
".",
"StatusInfo",
"{",
"Status",
":",
"status",
".",
"Status",
"(",
"arg",
".",
"Status",
")",
",",
"Message",
":",
"arg",
".",
"Info",
",",
"Data",
":",
"arg",
".",
"Data",
",",
"Since",
":",
"&",
"now",
",",
"}",
"\n",
"err",
"=",
"machine",
".",
"SetInstanceStatus",
"(",
"s",
")",
"\n",
"if",
"status",
".",
"Status",
"(",
"arg",
".",
"Status",
")",
"==",
"status",
".",
"ProvisioningError",
"{",
"s",
".",
"Status",
"=",
"status",
".",
"Error",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"machine",
".",
"SetStatus",
"(",
"s",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"result",
".",
"Results",
"[",
"i",
"]",
".",
"Error",
"=",
"common",
".",
"ServerError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // SetInstanceStatus updates the instance status for each given
// entity. Only machine tags are accepted. | [
"SetInstanceStatus",
"updates",
"the",
"instance",
"status",
"for",
"each",
"given",
"entity",
".",
"Only",
"machine",
"tags",
"are",
"accepted",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/instancepoller/instancepoller.go#L198-L227 |
154,465 | juju/juju | apiserver/allfacades.go | AdminFacadeDetails | func AdminFacadeDetails() []facade.Details {
var fs []facade.Details
for v, f := range adminAPIFactories {
api := f(nil, nil, nil)
t := reflect.TypeOf(api)
fs = append(fs, facade.Details{
Name: "Admin",
Version: v,
Type: t,
})
}
return fs
} | go | func AdminFacadeDetails() []facade.Details {
var fs []facade.Details
for v, f := range adminAPIFactories {
api := f(nil, nil, nil)
t := reflect.TypeOf(api)
fs = append(fs, facade.Details{
Name: "Admin",
Version: v,
Type: t,
})
}
return fs
} | [
"func",
"AdminFacadeDetails",
"(",
")",
"[",
"]",
"facade",
".",
"Details",
"{",
"var",
"fs",
"[",
"]",
"facade",
".",
"Details",
"\n",
"for",
"v",
",",
"f",
":=",
"range",
"adminAPIFactories",
"{",
"api",
":=",
"f",
"(",
"nil",
",",
"nil",
",",
"nil",
")",
"\n",
"t",
":=",
"reflect",
".",
"TypeOf",
"(",
"api",
")",
"\n",
"fs",
"=",
"append",
"(",
"fs",
",",
"facade",
".",
"Details",
"{",
"Name",
":",
"\"",
"\"",
",",
"Version",
":",
"v",
",",
"Type",
":",
"t",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"fs",
"\n",
"}"
] | // AdminFacadeDetails returns information on the Admin facade provided
// at login time. The Facade field of the returned slice elements will
// be nil. | [
"AdminFacadeDetails",
"returns",
"information",
"on",
"the",
"Admin",
"facade",
"provided",
"at",
"login",
"time",
".",
"The",
"Facade",
"field",
"of",
"the",
"returned",
"slice",
"elements",
"will",
"be",
"nil",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/allfacades.go#L342-L354 |
154,466 | juju/juju | provider/azure/config.go | isKnownStorageAccountType | func isKnownStorageAccountType(t string) bool {
for _, knownStorageAccountType := range knownStorageAccountTypes {
if t == knownStorageAccountType {
return true
}
}
return false
} | go | func isKnownStorageAccountType(t string) bool {
for _, knownStorageAccountType := range knownStorageAccountTypes {
if t == knownStorageAccountType {
return true
}
}
return false
} | [
"func",
"isKnownStorageAccountType",
"(",
"t",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"knownStorageAccountType",
":=",
"range",
"knownStorageAccountTypes",
"{",
"if",
"t",
"==",
"knownStorageAccountType",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // isKnownStorageAccountType reports whether or not the given string identifies
// a known storage account type. | [
"isKnownStorageAccountType",
"reports",
"whether",
"or",
"not",
"the",
"given",
"string",
"identifies",
"a",
"known",
"storage",
"account",
"type",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/config.go#L130-L137 |
154,467 | juju/juju | provider/azure/config.go | canonicalLocation | func canonicalLocation(s string) string {
s = strings.Replace(s, " ", "", -1)
return strings.ToLower(s)
} | go | func canonicalLocation(s string) string {
s = strings.Replace(s, " ", "", -1)
return strings.ToLower(s)
} | [
"func",
"canonicalLocation",
"(",
"s",
"string",
")",
"string",
"{",
"s",
"=",
"strings",
".",
"Replace",
"(",
"s",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"return",
"strings",
".",
"ToLower",
"(",
"s",
")",
"\n",
"}"
] | // canonicalLocation returns the canonicalized location string. This involves
// stripping whitespace, and lowercasing. The ARM APIs do not support embedded
// whitespace, whereas the old Service Management APIs used to; we allow the
// user to provide either, and canonicalize them to one form that ARM allows. | [
"canonicalLocation",
"returns",
"the",
"canonicalized",
"location",
"string",
".",
"This",
"involves",
"stripping",
"whitespace",
"and",
"lowercasing",
".",
"The",
"ARM",
"APIs",
"do",
"not",
"support",
"embedded",
"whitespace",
"whereas",
"the",
"old",
"Service",
"Management",
"APIs",
"used",
"to",
";",
"we",
"allow",
"the",
"user",
"to",
"provide",
"either",
"and",
"canonicalize",
"them",
"to",
"one",
"form",
"that",
"ARM",
"allows",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/config.go#L143-L146 |
154,468 | juju/juju | network/firewall.go | NewIngressRule | func NewIngressRule(protocol string, from, to int, sourceCIDRs ...string) (IngressRule, error) {
rule := IngressRule{
PortRange: network.PortRange{
Protocol: protocol,
FromPort: from,
ToPort: to,
},
}
for _, cidr := range sourceCIDRs {
if _, _, err := net.ParseCIDR(cidr); err != nil {
return IngressRule{}, errors.Trace(err)
}
}
if len(sourceCIDRs) > 0 {
rule.SourceCIDRs = sourceCIDRs
}
return rule, nil
} | go | func NewIngressRule(protocol string, from, to int, sourceCIDRs ...string) (IngressRule, error) {
rule := IngressRule{
PortRange: network.PortRange{
Protocol: protocol,
FromPort: from,
ToPort: to,
},
}
for _, cidr := range sourceCIDRs {
if _, _, err := net.ParseCIDR(cidr); err != nil {
return IngressRule{}, errors.Trace(err)
}
}
if len(sourceCIDRs) > 0 {
rule.SourceCIDRs = sourceCIDRs
}
return rule, nil
} | [
"func",
"NewIngressRule",
"(",
"protocol",
"string",
",",
"from",
",",
"to",
"int",
",",
"sourceCIDRs",
"...",
"string",
")",
"(",
"IngressRule",
",",
"error",
")",
"{",
"rule",
":=",
"IngressRule",
"{",
"PortRange",
":",
"network",
".",
"PortRange",
"{",
"Protocol",
":",
"protocol",
",",
"FromPort",
":",
"from",
",",
"ToPort",
":",
"to",
",",
"}",
",",
"}",
"\n",
"for",
"_",
",",
"cidr",
":=",
"range",
"sourceCIDRs",
"{",
"if",
"_",
",",
"_",
",",
"err",
":=",
"net",
".",
"ParseCIDR",
"(",
"cidr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"IngressRule",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"sourceCIDRs",
")",
">",
"0",
"{",
"rule",
".",
"SourceCIDRs",
"=",
"sourceCIDRs",
"\n",
"}",
"\n",
"return",
"rule",
",",
"nil",
"\n",
"}"
] | // NewIngressRule returns an IngressRule for the specified port
// range. If no explicit source ranges are specified, there is no
// restriction from where incoming traffic originates. | [
"NewIngressRule",
"returns",
"an",
"IngressRule",
"for",
"the",
"specified",
"port",
"range",
".",
"If",
"no",
"explicit",
"source",
"ranges",
"are",
"specified",
"there",
"is",
"no",
"restriction",
"from",
"where",
"incoming",
"traffic",
"originates",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/firewall.go#L31-L48 |
154,469 | juju/juju | network/firewall.go | MustNewIngressRule | func MustNewIngressRule(protocol string, from, to int, sourceCIDRs ...string) IngressRule {
rule, err := NewIngressRule(protocol, from, to, sourceCIDRs...)
if err != nil {
panic(err)
}
return rule
} | go | func MustNewIngressRule(protocol string, from, to int, sourceCIDRs ...string) IngressRule {
rule, err := NewIngressRule(protocol, from, to, sourceCIDRs...)
if err != nil {
panic(err)
}
return rule
} | [
"func",
"MustNewIngressRule",
"(",
"protocol",
"string",
",",
"from",
",",
"to",
"int",
",",
"sourceCIDRs",
"...",
"string",
")",
"IngressRule",
"{",
"rule",
",",
"err",
":=",
"NewIngressRule",
"(",
"protocol",
",",
"from",
",",
"to",
",",
"sourceCIDRs",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"rule",
"\n",
"}"
] | // MustNewIngressRule returns an IngressRule for the specified port
// range. If no explicit source ranges are specified, there is no
// restriction from where incoming traffic originates.
// The method will panic if there is an error. | [
"MustNewIngressRule",
"returns",
"an",
"IngressRule",
"for",
"the",
"specified",
"port",
"range",
".",
"If",
"no",
"explicit",
"source",
"ranges",
"are",
"specified",
"there",
"is",
"no",
"restriction",
"from",
"where",
"incoming",
"traffic",
"originates",
".",
"The",
"method",
"will",
"panic",
"if",
"there",
"is",
"an",
"error",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/firewall.go#L54-L60 |
154,470 | juju/juju | network/firewall.go | NewOpenIngressRule | func NewOpenIngressRule(protocol string, from, to int) IngressRule {
rule, _ := NewIngressRule(protocol, from, to)
return rule
} | go | func NewOpenIngressRule(protocol string, from, to int) IngressRule {
rule, _ := NewIngressRule(protocol, from, to)
return rule
} | [
"func",
"NewOpenIngressRule",
"(",
"protocol",
"string",
",",
"from",
",",
"to",
"int",
")",
"IngressRule",
"{",
"rule",
",",
"_",
":=",
"NewIngressRule",
"(",
"protocol",
",",
"from",
",",
"to",
")",
"\n",
"return",
"rule",
"\n",
"}"
] | // NewOpenIngressRule returns an IngressRule for the specified port
// range. There is no restriction from where incoming traffic originates. | [
"NewOpenIngressRule",
"returns",
"an",
"IngressRule",
"for",
"the",
"specified",
"port",
"range",
".",
"There",
"is",
"no",
"restriction",
"from",
"where",
"incoming",
"traffic",
"originates",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/firewall.go#L64-L67 |
154,471 | juju/juju | network/firewall.go | String | func (r IngressRule) String() string {
source := ""
from := strings.Join(r.SourceCIDRs, ",")
if from != "" && from != "0.0.0.0/0" {
source = " from " + from
}
if r.FromPort == r.ToPort {
return fmt.Sprintf("%d/%s%s", r.FromPort, strings.ToLower(r.Protocol), source)
}
return fmt.Sprintf("%d-%d/%s%s", r.FromPort, r.ToPort, strings.ToLower(r.Protocol), source)
} | go | func (r IngressRule) String() string {
source := ""
from := strings.Join(r.SourceCIDRs, ",")
if from != "" && from != "0.0.0.0/0" {
source = " from " + from
}
if r.FromPort == r.ToPort {
return fmt.Sprintf("%d/%s%s", r.FromPort, strings.ToLower(r.Protocol), source)
}
return fmt.Sprintf("%d-%d/%s%s", r.FromPort, r.ToPort, strings.ToLower(r.Protocol), source)
} | [
"func",
"(",
"r",
"IngressRule",
")",
"String",
"(",
")",
"string",
"{",
"source",
":=",
"\"",
"\"",
"\n",
"from",
":=",
"strings",
".",
"Join",
"(",
"r",
".",
"SourceCIDRs",
",",
"\"",
"\"",
")",
"\n",
"if",
"from",
"!=",
"\"",
"\"",
"&&",
"from",
"!=",
"\"",
"\"",
"{",
"source",
"=",
"\"",
"\"",
"+",
"from",
"\n",
"}",
"\n",
"if",
"r",
".",
"FromPort",
"==",
"r",
".",
"ToPort",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"r",
".",
"FromPort",
",",
"strings",
".",
"ToLower",
"(",
"r",
".",
"Protocol",
")",
",",
"source",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"r",
".",
"FromPort",
",",
"r",
".",
"ToPort",
",",
"strings",
".",
"ToLower",
"(",
"r",
".",
"Protocol",
")",
",",
"source",
")",
"\n",
"}"
] | // String is the string representation of IngressRule. | [
"String",
"is",
"the",
"string",
"representation",
"of",
"IngressRule",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/firewall.go#L70-L80 |
154,472 | juju/juju | state/container.go | removeContainerRefOps | func removeContainerRefOps(mb modelBackend, machineId string) []txn.Op {
removeRefOp := txn.Op{
C: containerRefsC,
Id: mb.docID(machineId),
Assert: txn.DocExists,
Remove: true,
}
// If the machine is a container, figure out its parent host.
parentId := ParentId(machineId)
if parentId == "" {
return []txn.Op{removeRefOp}
}
removeParentRefOp := txn.Op{
C: containerRefsC,
Id: mb.docID(parentId),
Assert: txn.DocExists,
Update: bson.D{{"$pull", bson.D{{"children", machineId}}}},
}
return []txn.Op{removeRefOp, removeParentRefOp}
} | go | func removeContainerRefOps(mb modelBackend, machineId string) []txn.Op {
removeRefOp := txn.Op{
C: containerRefsC,
Id: mb.docID(machineId),
Assert: txn.DocExists,
Remove: true,
}
// If the machine is a container, figure out its parent host.
parentId := ParentId(machineId)
if parentId == "" {
return []txn.Op{removeRefOp}
}
removeParentRefOp := txn.Op{
C: containerRefsC,
Id: mb.docID(parentId),
Assert: txn.DocExists,
Update: bson.D{{"$pull", bson.D{{"children", machineId}}}},
}
return []txn.Op{removeRefOp, removeParentRefOp}
} | [
"func",
"removeContainerRefOps",
"(",
"mb",
"modelBackend",
",",
"machineId",
"string",
")",
"[",
"]",
"txn",
".",
"Op",
"{",
"removeRefOp",
":=",
"txn",
".",
"Op",
"{",
"C",
":",
"containerRefsC",
",",
"Id",
":",
"mb",
".",
"docID",
"(",
"machineId",
")",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Remove",
":",
"true",
",",
"}",
"\n",
"// If the machine is a container, figure out its parent host.",
"parentId",
":=",
"ParentId",
"(",
"machineId",
")",
"\n",
"if",
"parentId",
"==",
"\"",
"\"",
"{",
"return",
"[",
"]",
"txn",
".",
"Op",
"{",
"removeRefOp",
"}",
"\n",
"}",
"\n",
"removeParentRefOp",
":=",
"txn",
".",
"Op",
"{",
"C",
":",
"containerRefsC",
",",
"Id",
":",
"mb",
".",
"docID",
"(",
"parentId",
")",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"machineId",
"}",
"}",
"}",
"}",
",",
"}",
"\n",
"return",
"[",
"]",
"txn",
".",
"Op",
"{",
"removeRefOp",
",",
"removeParentRefOp",
"}",
"\n",
"}"
] | // removeContainerRefOps returns the txn.Op's necessary to remove a machine container record.
// These include removing the record itself and updating the host machine's children property. | [
"removeContainerRefOps",
"returns",
"the",
"txn",
".",
"Op",
"s",
"necessary",
"to",
"remove",
"a",
"machine",
"container",
"record",
".",
"These",
"include",
"removing",
"the",
"record",
"itself",
"and",
"updating",
"the",
"host",
"machine",
"s",
"children",
"property",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/container.go#L47-L66 |
154,473 | juju/juju | state/container.go | ParentId | func ParentId(machineId string) string {
idParts := strings.Split(machineId, "/")
if len(idParts) < 3 {
return ""
}
return strings.Join(idParts[:len(idParts)-2], "/")
} | go | func ParentId(machineId string) string {
idParts := strings.Split(machineId, "/")
if len(idParts) < 3 {
return ""
}
return strings.Join(idParts[:len(idParts)-2], "/")
} | [
"func",
"ParentId",
"(",
"machineId",
"string",
")",
"string",
"{",
"idParts",
":=",
"strings",
".",
"Split",
"(",
"machineId",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"idParts",
")",
"<",
"3",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"idParts",
"[",
":",
"len",
"(",
"idParts",
")",
"-",
"2",
"]",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // ParentId returns the id of the host machine if machineId a container id, or ""
// if machineId is not for a container. | [
"ParentId",
"returns",
"the",
"id",
"of",
"the",
"host",
"machine",
"if",
"machineId",
"a",
"container",
"id",
"or",
"if",
"machineId",
"is",
"not",
"for",
"a",
"container",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/container.go#L70-L76 |
154,474 | juju/juju | state/container.go | ContainerTypeFromId | func ContainerTypeFromId(machineId string) instance.ContainerType {
idParts := strings.Split(machineId, "/")
if len(idParts) < 3 {
return instance.ContainerType("")
}
return instance.ContainerType(idParts[len(idParts)-2])
} | go | func ContainerTypeFromId(machineId string) instance.ContainerType {
idParts := strings.Split(machineId, "/")
if len(idParts) < 3 {
return instance.ContainerType("")
}
return instance.ContainerType(idParts[len(idParts)-2])
} | [
"func",
"ContainerTypeFromId",
"(",
"machineId",
"string",
")",
"instance",
".",
"ContainerType",
"{",
"idParts",
":=",
"strings",
".",
"Split",
"(",
"machineId",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"idParts",
")",
"<",
"3",
"{",
"return",
"instance",
".",
"ContainerType",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"instance",
".",
"ContainerType",
"(",
"idParts",
"[",
"len",
"(",
"idParts",
")",
"-",
"2",
"]",
")",
"\n",
"}"
] | // ContainerTypeFromId returns the container type if machineId is a container id, or ""
// if machineId is not for a container. | [
"ContainerTypeFromId",
"returns",
"the",
"container",
"type",
"if",
"machineId",
"is",
"a",
"container",
"id",
"or",
"if",
"machineId",
"is",
"not",
"for",
"a",
"container",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/container.go#L80-L86 |
154,475 | juju/juju | state/container.go | NestingLevel | func NestingLevel(machineId string) int {
idParts := strings.Split(machineId, "/")
return (len(idParts) - 1) / 2
} | go | func NestingLevel(machineId string) int {
idParts := strings.Split(machineId, "/")
return (len(idParts) - 1) / 2
} | [
"func",
"NestingLevel",
"(",
"machineId",
"string",
")",
"int",
"{",
"idParts",
":=",
"strings",
".",
"Split",
"(",
"machineId",
",",
"\"",
"\"",
")",
"\n",
"return",
"(",
"len",
"(",
"idParts",
")",
"-",
"1",
")",
"/",
"2",
"\n",
"}"
] | // NestingLevel returns how many levels of nesting exist for a machine id. | [
"NestingLevel",
"returns",
"how",
"many",
"levels",
"of",
"nesting",
"exist",
"for",
"a",
"machine",
"id",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/container.go#L89-L92 |
154,476 | juju/juju | state/endpoint_bindings.go | createEndpointBindingsOp | func createEndpointBindingsOp(st *State, key string, givenMap map[string]string, meta *charm.Meta) (txn.Op, error) {
// No existing map to merge, just use the defaults.
initialMap, _, err := mergeBindings(givenMap, nil, meta)
if err != nil {
return txn.Op{}, errors.Trace(err)
}
// Validate the bindings before inserting.
if err := validateEndpointBindingsForCharm(st, initialMap, meta); err != nil {
return txn.Op{}, errors.Trace(err)
}
return txn.Op{
C: endpointBindingsC,
Id: key,
Assert: txn.DocMissing,
Insert: endpointBindingsDoc{
Bindings: initialMap,
},
}, nil
} | go | func createEndpointBindingsOp(st *State, key string, givenMap map[string]string, meta *charm.Meta) (txn.Op, error) {
// No existing map to merge, just use the defaults.
initialMap, _, err := mergeBindings(givenMap, nil, meta)
if err != nil {
return txn.Op{}, errors.Trace(err)
}
// Validate the bindings before inserting.
if err := validateEndpointBindingsForCharm(st, initialMap, meta); err != nil {
return txn.Op{}, errors.Trace(err)
}
return txn.Op{
C: endpointBindingsC,
Id: key,
Assert: txn.DocMissing,
Insert: endpointBindingsDoc{
Bindings: initialMap,
},
}, nil
} | [
"func",
"createEndpointBindingsOp",
"(",
"st",
"*",
"State",
",",
"key",
"string",
",",
"givenMap",
"map",
"[",
"string",
"]",
"string",
",",
"meta",
"*",
"charm",
".",
"Meta",
")",
"(",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"// No existing map to merge, just use the defaults.",
"initialMap",
",",
"_",
",",
"err",
":=",
"mergeBindings",
"(",
"givenMap",
",",
"nil",
",",
"meta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"txn",
".",
"Op",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Validate the bindings before inserting.",
"if",
"err",
":=",
"validateEndpointBindingsForCharm",
"(",
"st",
",",
"initialMap",
",",
"meta",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"txn",
".",
"Op",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"endpointBindingsC",
",",
"Id",
":",
"key",
",",
"Assert",
":",
"txn",
".",
"DocMissing",
",",
"Insert",
":",
"endpointBindingsDoc",
"{",
"Bindings",
":",
"initialMap",
",",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // createEndpointBindingsOp returns the op needed to create new endpoint
// bindings using the optional givenMap and the specified charm metadata to for
// determining defaults and to validate the effective bindings. | [
"createEndpointBindingsOp",
"returns",
"the",
"op",
"needed",
"to",
"create",
"new",
"endpoint",
"bindings",
"using",
"the",
"optional",
"givenMap",
"and",
"the",
"specified",
"charm",
"metadata",
"to",
"for",
"determining",
"defaults",
"and",
"to",
"validate",
"the",
"effective",
"bindings",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/endpoint_bindings.go#L147-L168 |
154,477 | juju/juju | state/endpoint_bindings.go | updateEndpointBindingsOp | func updateEndpointBindingsOp(st *State, key string, givenMap map[string]string, newMeta *charm.Meta) (txn.Op, error) {
// Fetch existing bindings.
existingMap, txnRevno, err := readEndpointBindings(st, key)
if err != nil && !errors.IsNotFound(err) {
return txn.Op{}, errors.Trace(err)
}
// Merge existing with given as needed.
updatedMap, isModified, err := mergeBindings(givenMap, existingMap, newMeta)
if err != nil {
return txn.Op{}, errors.Trace(err)
}
// Validate the bindings before updating.
if err := validateEndpointBindingsForCharm(st, updatedMap, newMeta); err != nil {
return txn.Op{}, errors.Trace(err)
}
if !isModified {
return txn.Op{}, jujutxn.ErrNoOperations
}
// Prepare the update operations.
escaped := make(bson.M, len(updatedMap))
for endpoint, space := range updatedMap {
escaped[utils.EscapeKey(endpoint)] = space
}
updateOp := txn.Op{
C: endpointBindingsC,
Id: key,
Update: bson.M{"$set": bson.M{"bindings": escaped}},
}
if existingMap != nil {
// Only assert existing haven't changed when they actually exist.
updateOp.Assert = bson.D{{"txn-revno", txnRevno}}
}
return updateOp, nil
} | go | func updateEndpointBindingsOp(st *State, key string, givenMap map[string]string, newMeta *charm.Meta) (txn.Op, error) {
// Fetch existing bindings.
existingMap, txnRevno, err := readEndpointBindings(st, key)
if err != nil && !errors.IsNotFound(err) {
return txn.Op{}, errors.Trace(err)
}
// Merge existing with given as needed.
updatedMap, isModified, err := mergeBindings(givenMap, existingMap, newMeta)
if err != nil {
return txn.Op{}, errors.Trace(err)
}
// Validate the bindings before updating.
if err := validateEndpointBindingsForCharm(st, updatedMap, newMeta); err != nil {
return txn.Op{}, errors.Trace(err)
}
if !isModified {
return txn.Op{}, jujutxn.ErrNoOperations
}
// Prepare the update operations.
escaped := make(bson.M, len(updatedMap))
for endpoint, space := range updatedMap {
escaped[utils.EscapeKey(endpoint)] = space
}
updateOp := txn.Op{
C: endpointBindingsC,
Id: key,
Update: bson.M{"$set": bson.M{"bindings": escaped}},
}
if existingMap != nil {
// Only assert existing haven't changed when they actually exist.
updateOp.Assert = bson.D{{"txn-revno", txnRevno}}
}
return updateOp, nil
} | [
"func",
"updateEndpointBindingsOp",
"(",
"st",
"*",
"State",
",",
"key",
"string",
",",
"givenMap",
"map",
"[",
"string",
"]",
"string",
",",
"newMeta",
"*",
"charm",
".",
"Meta",
")",
"(",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"// Fetch existing bindings.",
"existingMap",
",",
"txnRevno",
",",
"err",
":=",
"readEndpointBindings",
"(",
"st",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"txn",
".",
"Op",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Merge existing with given as needed.",
"updatedMap",
",",
"isModified",
",",
"err",
":=",
"mergeBindings",
"(",
"givenMap",
",",
"existingMap",
",",
"newMeta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"txn",
".",
"Op",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Validate the bindings before updating.",
"if",
"err",
":=",
"validateEndpointBindingsForCharm",
"(",
"st",
",",
"updatedMap",
",",
"newMeta",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"txn",
".",
"Op",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"isModified",
"{",
"return",
"txn",
".",
"Op",
"{",
"}",
",",
"jujutxn",
".",
"ErrNoOperations",
"\n",
"}",
"\n\n",
"// Prepare the update operations.",
"escaped",
":=",
"make",
"(",
"bson",
".",
"M",
",",
"len",
"(",
"updatedMap",
")",
")",
"\n",
"for",
"endpoint",
",",
"space",
":=",
"range",
"updatedMap",
"{",
"escaped",
"[",
"utils",
".",
"EscapeKey",
"(",
"endpoint",
")",
"]",
"=",
"space",
"\n",
"}",
"\n\n",
"updateOp",
":=",
"txn",
".",
"Op",
"{",
"C",
":",
"endpointBindingsC",
",",
"Id",
":",
"key",
",",
"Update",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"escaped",
"}",
"}",
",",
"}",
"\n",
"if",
"existingMap",
"!=",
"nil",
"{",
"// Only assert existing haven't changed when they actually exist.",
"updateOp",
".",
"Assert",
"=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"txnRevno",
"}",
"}",
"\n",
"}",
"\n",
"return",
"updateOp",
",",
"nil",
"\n",
"}"
] | // updateEndpointBindingsOp returns an op that merges the existing bindings with
// givenMap, using newMeta to validate the merged bindings, and asserting the
// existing ones haven't changed in the since we fetched them. | [
"updateEndpointBindingsOp",
"returns",
"an",
"op",
"that",
"merges",
"the",
"existing",
"bindings",
"with",
"givenMap",
"using",
"newMeta",
"to",
"validate",
"the",
"merged",
"bindings",
"and",
"asserting",
"the",
"existing",
"ones",
"haven",
"t",
"changed",
"in",
"the",
"since",
"we",
"fetched",
"them",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/endpoint_bindings.go#L173-L211 |
154,478 | juju/juju | state/endpoint_bindings.go | removeEndpointBindingsOp | func removeEndpointBindingsOp(key string) txn.Op {
return txn.Op{
C: endpointBindingsC,
Id: key,
Remove: true,
}
} | go | func removeEndpointBindingsOp(key string) txn.Op {
return txn.Op{
C: endpointBindingsC,
Id: key,
Remove: true,
}
} | [
"func",
"removeEndpointBindingsOp",
"(",
"key",
"string",
")",
"txn",
".",
"Op",
"{",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"endpointBindingsC",
",",
"Id",
":",
"key",
",",
"Remove",
":",
"true",
",",
"}",
"\n",
"}"
] | // removeEndpointBindingsOp returns an op removing the bindings for the given
// key, without asserting they exist in the first place. | [
"removeEndpointBindingsOp",
"returns",
"an",
"op",
"removing",
"the",
"bindings",
"for",
"the",
"given",
"key",
"without",
"asserting",
"they",
"exist",
"in",
"the",
"first",
"place",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/endpoint_bindings.go#L215-L221 |
154,479 | juju/juju | provider/openstack/networking.go | DefaultNetworks | func (n *switchingNetworking) DefaultNetworks() ([]nova.ServerNetworks, error) {
if err := n.initNetworking(); err != nil {
return nil, errors.Trace(err)
}
return n.networking.DefaultNetworks()
} | go | func (n *switchingNetworking) DefaultNetworks() ([]nova.ServerNetworks, error) {
if err := n.initNetworking(); err != nil {
return nil, errors.Trace(err)
}
return n.networking.DefaultNetworks()
} | [
"func",
"(",
"n",
"*",
"switchingNetworking",
")",
"DefaultNetworks",
"(",
")",
"(",
"[",
"]",
"nova",
".",
"ServerNetworks",
",",
"error",
")",
"{",
"if",
"err",
":=",
"n",
".",
"initNetworking",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"n",
".",
"networking",
".",
"DefaultNetworks",
"(",
")",
"\n",
"}"
] | // DefaultNetworks is part of the Networking interface. | [
"DefaultNetworks",
"is",
"part",
"of",
"the",
"Networking",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/networking.go#L100-L105 |
154,480 | juju/juju | provider/openstack/networking.go | NetworkInterfaces | func (n *switchingNetworking) NetworkInterfaces(instId instance.Id) ([]network.InterfaceInfo, error) {
if err := n.initNetworking(); err != nil {
return nil, errors.Trace(err)
}
return n.networking.NetworkInterfaces(instId)
} | go | func (n *switchingNetworking) NetworkInterfaces(instId instance.Id) ([]network.InterfaceInfo, error) {
if err := n.initNetworking(); err != nil {
return nil, errors.Trace(err)
}
return n.networking.NetworkInterfaces(instId)
} | [
"func",
"(",
"n",
"*",
"switchingNetworking",
")",
"NetworkInterfaces",
"(",
"instId",
"instance",
".",
"Id",
")",
"(",
"[",
"]",
"network",
".",
"InterfaceInfo",
",",
"error",
")",
"{",
"if",
"err",
":=",
"n",
".",
"initNetworking",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"n",
".",
"networking",
".",
"NetworkInterfaces",
"(",
"instId",
")",
"\n",
"}"
] | // NetworkInterfaces is part of the Networking interface | [
"NetworkInterfaces",
"is",
"part",
"of",
"the",
"Networking",
"interface"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/networking.go#L124-L129 |
154,481 | juju/juju | provider/openstack/networking.go | getExternalNeutronNetworksByAZ | func getExternalNeutronNetworksByAZ(e *Environ, azName string) ([]string, error) {
neutron := e.neutron()
// Find all external networks in availability zone
networks, err := neutron.ListNetworksV2(externalNetworkFilter())
if err != nil {
return nil, errors.Trace(err)
}
netIds := make([]string, 0)
for _, network := range networks {
for _, netAZ := range network.AvailabilityZones {
if azName == netAZ {
netIds = append(netIds, network.Id)
break
}
}
}
if len(netIds) == 0 {
return nil, errors.NewNotFound(nil, "No External networks found to allocate a Floating IP")
}
return netIds, nil
} | go | func getExternalNeutronNetworksByAZ(e *Environ, azName string) ([]string, error) {
neutron := e.neutron()
// Find all external networks in availability zone
networks, err := neutron.ListNetworksV2(externalNetworkFilter())
if err != nil {
return nil, errors.Trace(err)
}
netIds := make([]string, 0)
for _, network := range networks {
for _, netAZ := range network.AvailabilityZones {
if azName == netAZ {
netIds = append(netIds, network.Id)
break
}
}
}
if len(netIds) == 0 {
return nil, errors.NewNotFound(nil, "No External networks found to allocate a Floating IP")
}
return netIds, nil
} | [
"func",
"getExternalNeutronNetworksByAZ",
"(",
"e",
"*",
"Environ",
",",
"azName",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"neutron",
":=",
"e",
".",
"neutron",
"(",
")",
"\n",
"// Find all external networks in availability zone",
"networks",
",",
"err",
":=",
"neutron",
".",
"ListNetworksV2",
"(",
"externalNetworkFilter",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"netIds",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"for",
"_",
",",
"network",
":=",
"range",
"networks",
"{",
"for",
"_",
",",
"netAZ",
":=",
"range",
"network",
".",
"AvailabilityZones",
"{",
"if",
"azName",
"==",
"netAZ",
"{",
"netIds",
"=",
"append",
"(",
"netIds",
",",
"network",
".",
"Id",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"netIds",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"NewNotFound",
"(",
"nil",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"netIds",
",",
"nil",
"\n",
"}"
] | // getExternalNeutronNetworksByAZ returns all external networks within the
// given availability zone. If azName is empty, return all external networks. | [
"getExternalNeutronNetworksByAZ",
"returns",
"all",
"external",
"networks",
"within",
"the",
"given",
"availability",
"zone",
".",
"If",
"azName",
"is",
"empty",
"return",
"all",
"external",
"networks",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/networking.go#L246-L266 |
154,482 | juju/juju | provider/openstack/networking.go | Subnets | func (n *NeutronNetworking) Subnets(instId instance.Id, subnetIds []network.Id) ([]network.SubnetInfo, error) {
netIds := set.NewStrings()
neutron := n.env.neutron()
internalNet := n.env.ecfg().network()
netId, err := resolveNeutronNetwork(neutron, internalNet, false)
if err != nil {
// Note: (jam 2018-05-23) We don't treat this as fatal because we used to never pay attention to it anyway
if internalNet == "" {
logger.Warningf(noNetConfigMsg(err))
} else {
logger.Warningf("could not resolve internal network id for %q: %v", internalNet, err)
}
} else {
netIds.Add(netId)
// Note, there are cases where we will detect an external
// network without it being explicitly configured by the user.
// When we get to a point where we start detecting spaces for users
// on Openstack, we'll probably need to include better logic here.
externalNet := n.env.ecfg().externalNetwork()
if externalNet != "" {
netId, err := resolveNeutronNetwork(neutron, externalNet, true)
if err != nil {
logger.Warningf("could not resolve external network id for %q: %v", externalNet, err)
} else {
netIds.Add(netId)
}
}
}
logger.Debugf("finding subnets in networks: %s", strings.Join(netIds.Values(), ", "))
subIdSet := set.NewStrings()
for _, subId := range subnetIds {
subIdSet.Add(string(subId))
}
var results []network.SubnetInfo
if instId != instance.UnknownId {
// TODO(hml): 2017-03-20
// Implement Subnets() for case where instId is specified
return nil, errors.NotSupportedf("neutron subnets with instance Id")
} else {
// TODO(jam): 2018-05-23 It is likely that ListSubnetsV2 could
// take a Filter rather that doing the filtering client side.
subnets, err := neutron.ListSubnetsV2()
if err != nil {
return nil, errors.Annotatef(err, "failed to retrieve subnets")
}
if len(subnetIds) == 0 {
for _, subnet := range subnets {
// TODO (manadart 2018-07-17): If there was an error resolving
// an internal network ID, then no subnets will be discovered.
// The user will get an error attempting to add machines to
// this model and will have to update model config with a
// network name; but this does not re-discover the subnets.
// If subnets/spaces become important, we will have to address
// this somehow.
if !netIds.Contains(subnet.NetworkId) {
logger.Tracef("ignoring subnet %q, part of network %q", subnet.Id, subnet.NetworkId)
continue
}
subIdSet.Add(subnet.Id)
}
}
for _, subnet := range subnets {
if !subIdSet.Contains(subnet.Id) {
logger.Tracef("subnet %q not in %v, skipping", subnet.Id, subnetIds)
continue
}
subIdSet.Remove(subnet.Id)
if info, err := makeSubnetInfo(neutron, subnet); err == nil {
// Error will already have been logged.
results = append(results, info)
}
}
}
if !subIdSet.IsEmpty() {
return nil, errors.Errorf("failed to find the following subnet ids: %v", subIdSet.Values())
}
return results, nil
} | go | func (n *NeutronNetworking) Subnets(instId instance.Id, subnetIds []network.Id) ([]network.SubnetInfo, error) {
netIds := set.NewStrings()
neutron := n.env.neutron()
internalNet := n.env.ecfg().network()
netId, err := resolveNeutronNetwork(neutron, internalNet, false)
if err != nil {
// Note: (jam 2018-05-23) We don't treat this as fatal because we used to never pay attention to it anyway
if internalNet == "" {
logger.Warningf(noNetConfigMsg(err))
} else {
logger.Warningf("could not resolve internal network id for %q: %v", internalNet, err)
}
} else {
netIds.Add(netId)
// Note, there are cases where we will detect an external
// network without it being explicitly configured by the user.
// When we get to a point where we start detecting spaces for users
// on Openstack, we'll probably need to include better logic here.
externalNet := n.env.ecfg().externalNetwork()
if externalNet != "" {
netId, err := resolveNeutronNetwork(neutron, externalNet, true)
if err != nil {
logger.Warningf("could not resolve external network id for %q: %v", externalNet, err)
} else {
netIds.Add(netId)
}
}
}
logger.Debugf("finding subnets in networks: %s", strings.Join(netIds.Values(), ", "))
subIdSet := set.NewStrings()
for _, subId := range subnetIds {
subIdSet.Add(string(subId))
}
var results []network.SubnetInfo
if instId != instance.UnknownId {
// TODO(hml): 2017-03-20
// Implement Subnets() for case where instId is specified
return nil, errors.NotSupportedf("neutron subnets with instance Id")
} else {
// TODO(jam): 2018-05-23 It is likely that ListSubnetsV2 could
// take a Filter rather that doing the filtering client side.
subnets, err := neutron.ListSubnetsV2()
if err != nil {
return nil, errors.Annotatef(err, "failed to retrieve subnets")
}
if len(subnetIds) == 0 {
for _, subnet := range subnets {
// TODO (manadart 2018-07-17): If there was an error resolving
// an internal network ID, then no subnets will be discovered.
// The user will get an error attempting to add machines to
// this model and will have to update model config with a
// network name; but this does not re-discover the subnets.
// If subnets/spaces become important, we will have to address
// this somehow.
if !netIds.Contains(subnet.NetworkId) {
logger.Tracef("ignoring subnet %q, part of network %q", subnet.Id, subnet.NetworkId)
continue
}
subIdSet.Add(subnet.Id)
}
}
for _, subnet := range subnets {
if !subIdSet.Contains(subnet.Id) {
logger.Tracef("subnet %q not in %v, skipping", subnet.Id, subnetIds)
continue
}
subIdSet.Remove(subnet.Id)
if info, err := makeSubnetInfo(neutron, subnet); err == nil {
// Error will already have been logged.
results = append(results, info)
}
}
}
if !subIdSet.IsEmpty() {
return nil, errors.Errorf("failed to find the following subnet ids: %v", subIdSet.Values())
}
return results, nil
} | [
"func",
"(",
"n",
"*",
"NeutronNetworking",
")",
"Subnets",
"(",
"instId",
"instance",
".",
"Id",
",",
"subnetIds",
"[",
"]",
"network",
".",
"Id",
")",
"(",
"[",
"]",
"network",
".",
"SubnetInfo",
",",
"error",
")",
"{",
"netIds",
":=",
"set",
".",
"NewStrings",
"(",
")",
"\n",
"neutron",
":=",
"n",
".",
"env",
".",
"neutron",
"(",
")",
"\n",
"internalNet",
":=",
"n",
".",
"env",
".",
"ecfg",
"(",
")",
".",
"network",
"(",
")",
"\n",
"netId",
",",
"err",
":=",
"resolveNeutronNetwork",
"(",
"neutron",
",",
"internalNet",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Note: (jam 2018-05-23) We don't treat this as fatal because we used to never pay attention to it anyway",
"if",
"internalNet",
"==",
"\"",
"\"",
"{",
"logger",
".",
"Warningf",
"(",
"noNetConfigMsg",
"(",
"err",
")",
")",
"\n",
"}",
"else",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"internalNet",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"netIds",
".",
"Add",
"(",
"netId",
")",
"\n",
"// Note, there are cases where we will detect an external",
"// network without it being explicitly configured by the user.",
"// When we get to a point where we start detecting spaces for users",
"// on Openstack, we'll probably need to include better logic here.",
"externalNet",
":=",
"n",
".",
"env",
".",
"ecfg",
"(",
")",
".",
"externalNetwork",
"(",
")",
"\n",
"if",
"externalNet",
"!=",
"\"",
"\"",
"{",
"netId",
",",
"err",
":=",
"resolveNeutronNetwork",
"(",
"neutron",
",",
"externalNet",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"externalNet",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"netIds",
".",
"Add",
"(",
"netId",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"netIds",
".",
"Values",
"(",
")",
",",
"\"",
"\"",
")",
")",
"\n\n",
"subIdSet",
":=",
"set",
".",
"NewStrings",
"(",
")",
"\n",
"for",
"_",
",",
"subId",
":=",
"range",
"subnetIds",
"{",
"subIdSet",
".",
"Add",
"(",
"string",
"(",
"subId",
")",
")",
"\n",
"}",
"\n\n",
"var",
"results",
"[",
"]",
"network",
".",
"SubnetInfo",
"\n",
"if",
"instId",
"!=",
"instance",
".",
"UnknownId",
"{",
"// TODO(hml): 2017-03-20",
"// Implement Subnets() for case where instId is specified",
"return",
"nil",
",",
"errors",
".",
"NotSupportedf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"// TODO(jam): 2018-05-23 It is likely that ListSubnetsV2 could",
"// take a Filter rather that doing the filtering client side.",
"subnets",
",",
"err",
":=",
"neutron",
".",
"ListSubnetsV2",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"subnetIds",
")",
"==",
"0",
"{",
"for",
"_",
",",
"subnet",
":=",
"range",
"subnets",
"{",
"// TODO (manadart 2018-07-17): If there was an error resolving",
"// an internal network ID, then no subnets will be discovered.",
"// The user will get an error attempting to add machines to",
"// this model and will have to update model config with a",
"// network name; but this does not re-discover the subnets.",
"// If subnets/spaces become important, we will have to address",
"// this somehow.",
"if",
"!",
"netIds",
".",
"Contains",
"(",
"subnet",
".",
"NetworkId",
")",
"{",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"subnet",
".",
"Id",
",",
"subnet",
".",
"NetworkId",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"subIdSet",
".",
"Add",
"(",
"subnet",
".",
"Id",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"subnet",
":=",
"range",
"subnets",
"{",
"if",
"!",
"subIdSet",
".",
"Contains",
"(",
"subnet",
".",
"Id",
")",
"{",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"subnet",
".",
"Id",
",",
"subnetIds",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"subIdSet",
".",
"Remove",
"(",
"subnet",
".",
"Id",
")",
"\n",
"if",
"info",
",",
"err",
":=",
"makeSubnetInfo",
"(",
"neutron",
",",
"subnet",
")",
";",
"err",
"==",
"nil",
"{",
"// Error will already have been logged.",
"results",
"=",
"append",
"(",
"results",
",",
"info",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"subIdSet",
".",
"IsEmpty",
"(",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"subIdSet",
".",
"Values",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // Subnets returns basic information about the specified subnets known
// by the provider for the specified instance or list of ids. subnetIds can be
// empty, in which case all known are returned. | [
"Subnets",
"returns",
"basic",
"information",
"about",
"the",
"specified",
"subnets",
"known",
"by",
"the",
"provider",
"for",
"the",
"specified",
"instance",
"or",
"list",
"of",
"ids",
".",
"subnetIds",
"can",
"be",
"empty",
"in",
"which",
"case",
"all",
"known",
"are",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/openstack/networking.go#L329-L408 |
154,483 | juju/juju | container/lxd/cluster.go | UseTargetServer | func (s Server) UseTargetServer(name string) (*Server, error) {
logger.Debugf("creating LXD server for cluster node %q", name)
return NewServer(s.UseTarget(name))
} | go | func (s Server) UseTargetServer(name string) (*Server, error) {
logger.Debugf("creating LXD server for cluster node %q", name)
return NewServer(s.UseTarget(name))
} | [
"func",
"(",
"s",
"Server",
")",
"UseTargetServer",
"(",
"name",
"string",
")",
"(",
"*",
"Server",
",",
"error",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"return",
"NewServer",
"(",
"s",
".",
"UseTarget",
"(",
"name",
")",
")",
"\n",
"}"
] | // UseTargetServer returns a new Server based on the input target node name.
// It is intended for use when operations must target specific nodes in a
// cluster. | [
"UseTargetServer",
"returns",
"a",
"new",
"Server",
"based",
"on",
"the",
"input",
"target",
"node",
"name",
".",
"It",
"is",
"intended",
"for",
"use",
"when",
"operations",
"must",
"target",
"specific",
"nodes",
"in",
"a",
"cluster",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/cluster.go#L13-L16 |
154,484 | juju/juju | apiserver/facades/agent/instancemutater/mocks/state_mock.go | NewMockEntityFinder | func NewMockEntityFinder(ctrl *gomock.Controller) *MockEntityFinder {
mock := &MockEntityFinder{ctrl: ctrl}
mock.recorder = &MockEntityFinderMockRecorder{mock}
return mock
} | go | func NewMockEntityFinder(ctrl *gomock.Controller) *MockEntityFinder {
mock := &MockEntityFinder{ctrl: ctrl}
mock.recorder = &MockEntityFinderMockRecorder{mock}
return mock
} | [
"func",
"NewMockEntityFinder",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockEntityFinder",
"{",
"mock",
":=",
"&",
"MockEntityFinder",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockEntityFinderMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockEntityFinder creates a new mock instance | [
"NewMockEntityFinder",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/state_mock.go#L26-L30 |
154,485 | juju/juju | apiserver/facades/agent/instancemutater/mocks/state_mock.go | NewMockEntity | func NewMockEntity(ctrl *gomock.Controller) *MockEntity {
mock := &MockEntity{ctrl: ctrl}
mock.recorder = &MockEntityMockRecorder{mock}
return mock
} | go | func NewMockEntity(ctrl *gomock.Controller) *MockEntity {
mock := &MockEntity{ctrl: ctrl}
mock.recorder = &MockEntityMockRecorder{mock}
return mock
} | [
"func",
"NewMockEntity",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockEntity",
"{",
"mock",
":=",
"&",
"MockEntity",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockEntityMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockEntity creates a new mock instance | [
"NewMockEntity",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/state_mock.go#L62-L66 |
154,486 | juju/juju | apiserver/facades/agent/instancemutater/mocks/state_mock.go | Tag | func (mr *MockEntityMockRecorder) Tag() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Tag", reflect.TypeOf((*MockEntity)(nil).Tag))
} | go | func (mr *MockEntityMockRecorder) Tag() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Tag", reflect.TypeOf((*MockEntity)(nil).Tag))
} | [
"func",
"(",
"mr",
"*",
"MockEntityMockRecorder",
")",
"Tag",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockEntity",
")",
"(",
"nil",
")",
".",
"Tag",
")",
")",
"\n",
"}"
] | // Tag indicates an expected call of Tag | [
"Tag",
"indicates",
"an",
"expected",
"call",
"of",
"Tag"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/state_mock.go#L81-L83 |
154,487 | juju/juju | apiserver/facades/agent/instancemutater/mocks/state_mock.go | NewMockLifer | func NewMockLifer(ctrl *gomock.Controller) *MockLifer {
mock := &MockLifer{ctrl: ctrl}
mock.recorder = &MockLiferMockRecorder{mock}
return mock
} | go | func NewMockLifer(ctrl *gomock.Controller) *MockLifer {
mock := &MockLifer{ctrl: ctrl}
mock.recorder = &MockLiferMockRecorder{mock}
return mock
} | [
"func",
"NewMockLifer",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockLifer",
"{",
"mock",
":=",
"&",
"MockLifer",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockLiferMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockLifer creates a new mock instance | [
"NewMockLifer",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/state_mock.go#L97-L101 |
154,488 | juju/juju | provider/maas/devices.go | checkForExistingDevice | func (env *maasEnviron) checkForExistingDevice(params deviceCreatorParams) (gomaasapi.Device, error) {
devicesArgs := gomaasapi.DevicesArgs{
Hostname: []string{params.Name},
}
maybeDevices, err := params.Machine.Devices(devicesArgs)
if err != nil {
logger.Warningf("error while trying to lookup %q: %v", params.Name, err)
// not considered fatal, since we'll attempt to create the device if we didn't find it
return nil, nil
}
if len(maybeDevices) == 0 {
logger.Debugf("no existing MAAS devices for container %q, creating", params.Name)
return nil, nil
}
if len(maybeDevices) > 1 {
logger.Warningf("found more than 1 MAAS devices (%d) for container %q", len(maybeDevices),
params.Name)
return nil, errors.Errorf("found more than 1 MAAS device (%d) for container %q",
len(maybeDevices), params.Name)
}
device := maybeDevices[0]
// Now validate that this device has the right interfaces
matches, err := validateExistingDevice(params.DesiredInterfaceInfo, device)
if err != nil {
return nil, err
}
if matches {
logger.Debugf("found MAAS device for container %q using existing device", params.Name)
return device, nil
}
logger.Debugf("found existing MAAS device for container %q but interfaces did not match, removing device", params.Name)
// We found a device, but it doesn't match what we need. remove it and we'll create again.
device.Delete()
return nil, nil
} | go | func (env *maasEnviron) checkForExistingDevice(params deviceCreatorParams) (gomaasapi.Device, error) {
devicesArgs := gomaasapi.DevicesArgs{
Hostname: []string{params.Name},
}
maybeDevices, err := params.Machine.Devices(devicesArgs)
if err != nil {
logger.Warningf("error while trying to lookup %q: %v", params.Name, err)
// not considered fatal, since we'll attempt to create the device if we didn't find it
return nil, nil
}
if len(maybeDevices) == 0 {
logger.Debugf("no existing MAAS devices for container %q, creating", params.Name)
return nil, nil
}
if len(maybeDevices) > 1 {
logger.Warningf("found more than 1 MAAS devices (%d) for container %q", len(maybeDevices),
params.Name)
return nil, errors.Errorf("found more than 1 MAAS device (%d) for container %q",
len(maybeDevices), params.Name)
}
device := maybeDevices[0]
// Now validate that this device has the right interfaces
matches, err := validateExistingDevice(params.DesiredInterfaceInfo, device)
if err != nil {
return nil, err
}
if matches {
logger.Debugf("found MAAS device for container %q using existing device", params.Name)
return device, nil
}
logger.Debugf("found existing MAAS device for container %q but interfaces did not match, removing device", params.Name)
// We found a device, but it doesn't match what we need. remove it and we'll create again.
device.Delete()
return nil, nil
} | [
"func",
"(",
"env",
"*",
"maasEnviron",
")",
"checkForExistingDevice",
"(",
"params",
"deviceCreatorParams",
")",
"(",
"gomaasapi",
".",
"Device",
",",
"error",
")",
"{",
"devicesArgs",
":=",
"gomaasapi",
".",
"DevicesArgs",
"{",
"Hostname",
":",
"[",
"]",
"string",
"{",
"params",
".",
"Name",
"}",
",",
"}",
"\n",
"maybeDevices",
",",
"err",
":=",
"params",
".",
"Machine",
".",
"Devices",
"(",
"devicesArgs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"params",
".",
"Name",
",",
"err",
")",
"\n",
"// not considered fatal, since we'll attempt to create the device if we didn't find it",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"if",
"len",
"(",
"maybeDevices",
")",
"==",
"0",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"params",
".",
"Name",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"if",
"len",
"(",
"maybeDevices",
")",
">",
"1",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"len",
"(",
"maybeDevices",
")",
",",
"params",
".",
"Name",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"maybeDevices",
")",
",",
"params",
".",
"Name",
")",
"\n",
"}",
"\n",
"device",
":=",
"maybeDevices",
"[",
"0",
"]",
"\n",
"// Now validate that this device has the right interfaces",
"matches",
",",
"err",
":=",
"validateExistingDevice",
"(",
"params",
".",
"DesiredInterfaceInfo",
",",
"device",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"matches",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"params",
".",
"Name",
")",
"\n",
"return",
"device",
",",
"nil",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"params",
".",
"Name",
")",
"\n",
"// We found a device, but it doesn't match what we need. remove it and we'll create again.",
"device",
".",
"Delete",
"(",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // checkForExistingDevice checks to see if we've already registered a device
// with this name, and if its information is appropriately populated. If we
// have, then we just return the existing interface info. If we find it, but
// it doesn't match, then we ask MAAS to remove it, which should cause the
// calling code to create it again. | [
"checkForExistingDevice",
"checks",
"to",
"see",
"if",
"we",
"ve",
"already",
"registered",
"a",
"device",
"with",
"this",
"name",
"and",
"if",
"its",
"information",
"is",
"appropriately",
"populated",
".",
"If",
"we",
"have",
"then",
"we",
"just",
"return",
"the",
"existing",
"interface",
"info",
".",
"If",
"we",
"find",
"it",
"but",
"it",
"doesn",
"t",
"match",
"then",
"we",
"ask",
"MAAS",
"to",
"remove",
"it",
"which",
"should",
"cause",
"the",
"calling",
"code",
"to",
"create",
"it",
"again",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/maas/devices.go#L580-L614 |
154,489 | juju/juju | cmd/juju/crossmodel/showformatter.go | formatShowTabular | func formatShowTabular(writer io.Writer, value interface{}) error {
endpoints, ok := value.(map[string]ShowOfferedApplication)
if !ok {
return errors.Errorf("expected value of type %T, got %T", endpoints, value)
}
return formatOfferedEndpointsTabular(writer, endpoints)
} | go | func formatShowTabular(writer io.Writer, value interface{}) error {
endpoints, ok := value.(map[string]ShowOfferedApplication)
if !ok {
return errors.Errorf("expected value of type %T, got %T", endpoints, value)
}
return formatOfferedEndpointsTabular(writer, endpoints)
} | [
"func",
"formatShowTabular",
"(",
"writer",
"io",
".",
"Writer",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"endpoints",
",",
"ok",
":=",
"value",
".",
"(",
"map",
"[",
"string",
"]",
"ShowOfferedApplication",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"endpoints",
",",
"value",
")",
"\n",
"}",
"\n",
"return",
"formatOfferedEndpointsTabular",
"(",
"writer",
",",
"endpoints",
")",
"\n",
"}"
] | // formatShowTabular returns a tabular summary of remote applications or
// errors out if parameter is not of expected type. | [
"formatShowTabular",
"returns",
"a",
"tabular",
"summary",
"of",
"remote",
"applications",
"or",
"errors",
"out",
"if",
"parameter",
"is",
"not",
"of",
"expected",
"type",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/showformatter.go#L28-L34 |
154,490 | juju/juju | cmd/juju/crossmodel/showformatter.go | formatOfferedEndpointsTabular | func formatOfferedEndpointsTabular(writer io.Writer, all map[string]ShowOfferedApplication) error {
tw := output.TabWriter(writer)
w := output.Wrapper{tw}
w.Println("Store", "URL", "Access", "Description", "Endpoint", "Interface", "Role")
for urlStr, one := range all {
url, err := crossmodel.ParseOfferURL(urlStr)
if err != nil {
return err
}
store := url.Source
url.Source = ""
offerURL := url.String()
offerAccess := one.Access
offerDesc := one.Description
// truncate long description for now.
if len(offerDesc) > maxColumnLength {
offerDesc = fmt.Sprintf("%v%v", offerDesc[:maxFieldLength], truncatedSuffix)
}
descLines := breakLines(offerDesc)
// Find the maximum amount of iterations required:
// it will be either endpoints or description lines length
maxIterations := max(len(one.Endpoints), len(descLines))
names := []string{}
for name := range one.Endpoints {
names = append(names, name)
}
sort.Strings(names)
for i := 0; i < maxIterations; i++ {
descLine := descAt(descLines, i)
name, endpoint := endpointAt(one.Endpoints, names, i)
w.Println(store, offerURL, offerAccess, descLine, name, endpoint.Interface, endpoint.Role)
// Only print once.
store = ""
offerURL = ""
offerAccess = ""
}
}
tw.Flush()
return nil
} | go | func formatOfferedEndpointsTabular(writer io.Writer, all map[string]ShowOfferedApplication) error {
tw := output.TabWriter(writer)
w := output.Wrapper{tw}
w.Println("Store", "URL", "Access", "Description", "Endpoint", "Interface", "Role")
for urlStr, one := range all {
url, err := crossmodel.ParseOfferURL(urlStr)
if err != nil {
return err
}
store := url.Source
url.Source = ""
offerURL := url.String()
offerAccess := one.Access
offerDesc := one.Description
// truncate long description for now.
if len(offerDesc) > maxColumnLength {
offerDesc = fmt.Sprintf("%v%v", offerDesc[:maxFieldLength], truncatedSuffix)
}
descLines := breakLines(offerDesc)
// Find the maximum amount of iterations required:
// it will be either endpoints or description lines length
maxIterations := max(len(one.Endpoints), len(descLines))
names := []string{}
for name := range one.Endpoints {
names = append(names, name)
}
sort.Strings(names)
for i := 0; i < maxIterations; i++ {
descLine := descAt(descLines, i)
name, endpoint := endpointAt(one.Endpoints, names, i)
w.Println(store, offerURL, offerAccess, descLine, name, endpoint.Interface, endpoint.Role)
// Only print once.
store = ""
offerURL = ""
offerAccess = ""
}
}
tw.Flush()
return nil
} | [
"func",
"formatOfferedEndpointsTabular",
"(",
"writer",
"io",
".",
"Writer",
",",
"all",
"map",
"[",
"string",
"]",
"ShowOfferedApplication",
")",
"error",
"{",
"tw",
":=",
"output",
".",
"TabWriter",
"(",
"writer",
")",
"\n",
"w",
":=",
"output",
".",
"Wrapper",
"{",
"tw",
"}",
"\n\n",
"w",
".",
"Println",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"for",
"urlStr",
",",
"one",
":=",
"range",
"all",
"{",
"url",
",",
"err",
":=",
"crossmodel",
".",
"ParseOfferURL",
"(",
"urlStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"store",
":=",
"url",
".",
"Source",
"\n",
"url",
".",
"Source",
"=",
"\"",
"\"",
"\n",
"offerURL",
":=",
"url",
".",
"String",
"(",
")",
"\n",
"offerAccess",
":=",
"one",
".",
"Access",
"\n",
"offerDesc",
":=",
"one",
".",
"Description",
"\n\n",
"// truncate long description for now.",
"if",
"len",
"(",
"offerDesc",
")",
">",
"maxColumnLength",
"{",
"offerDesc",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"offerDesc",
"[",
":",
"maxFieldLength",
"]",
",",
"truncatedSuffix",
")",
"\n",
"}",
"\n",
"descLines",
":=",
"breakLines",
"(",
"offerDesc",
")",
"\n\n",
"// Find the maximum amount of iterations required:",
"// it will be either endpoints or description lines length",
"maxIterations",
":=",
"max",
"(",
"len",
"(",
"one",
".",
"Endpoints",
")",
",",
"len",
"(",
"descLines",
")",
")",
"\n\n",
"names",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"name",
":=",
"range",
"one",
".",
"Endpoints",
"{",
"names",
"=",
"append",
"(",
"names",
",",
"name",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"names",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"maxIterations",
";",
"i",
"++",
"{",
"descLine",
":=",
"descAt",
"(",
"descLines",
",",
"i",
")",
"\n",
"name",
",",
"endpoint",
":=",
"endpointAt",
"(",
"one",
".",
"Endpoints",
",",
"names",
",",
"i",
")",
"\n",
"w",
".",
"Println",
"(",
"store",
",",
"offerURL",
",",
"offerAccess",
",",
"descLine",
",",
"name",
",",
"endpoint",
".",
"Interface",
",",
"endpoint",
".",
"Role",
")",
"\n",
"// Only print once.",
"store",
"=",
"\"",
"\"",
"\n",
"offerURL",
"=",
"\"",
"\"",
"\n",
"offerAccess",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"tw",
".",
"Flush",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // formatOfferedEndpointsTabular returns a tabular summary of offered applications' endpoints. | [
"formatOfferedEndpointsTabular",
"returns",
"a",
"tabular",
"summary",
"of",
"offered",
"applications",
"endpoints",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/showformatter.go#L37-L82 |
154,491 | juju/juju | cmd/juju/commands/bootstrap_interactive.go | queryCloud | func queryCloud(clouds []string, defCloud string, scanner *bufio.Scanner, w io.Writer) (string, error) {
list := strings.Join(clouds, "\n")
if _, err := fmt.Fprint(w, "Clouds\n", list, "\n\n"); err != nil {
return "", errors.Trace(err)
}
// add support for a default (empty) selection.
clouds = append(clouds, "")
verify := interact.MatchOptions(clouds, "Invalid cloud.")
query := fmt.Sprintf("Select a cloud [%s]: ", defCloud)
cloud, err := interact.QueryVerify(query, scanner, w, w, verify)
if err != nil {
return "", errors.Trace(err)
}
if cloud == "" {
return defCloud, nil
}
if ok := names.IsValidCloud(cloud); !ok {
return "", errors.NotValidf("cloud name %q", cloud)
}
cloudName, ok := interact.FindMatch(cloud, clouds)
if !ok {
// should be impossible
return "", errors.Errorf("invalid cloud name chosen: %s", cloud)
}
return cloudName, nil
} | go | func queryCloud(clouds []string, defCloud string, scanner *bufio.Scanner, w io.Writer) (string, error) {
list := strings.Join(clouds, "\n")
if _, err := fmt.Fprint(w, "Clouds\n", list, "\n\n"); err != nil {
return "", errors.Trace(err)
}
// add support for a default (empty) selection.
clouds = append(clouds, "")
verify := interact.MatchOptions(clouds, "Invalid cloud.")
query := fmt.Sprintf("Select a cloud [%s]: ", defCloud)
cloud, err := interact.QueryVerify(query, scanner, w, w, verify)
if err != nil {
return "", errors.Trace(err)
}
if cloud == "" {
return defCloud, nil
}
if ok := names.IsValidCloud(cloud); !ok {
return "", errors.NotValidf("cloud name %q", cloud)
}
cloudName, ok := interact.FindMatch(cloud, clouds)
if !ok {
// should be impossible
return "", errors.Errorf("invalid cloud name chosen: %s", cloud)
}
return cloudName, nil
} | [
"func",
"queryCloud",
"(",
"clouds",
"[",
"]",
"string",
",",
"defCloud",
"string",
",",
"scanner",
"*",
"bufio",
".",
"Scanner",
",",
"w",
"io",
".",
"Writer",
")",
"(",
"string",
",",
"error",
")",
"{",
"list",
":=",
"strings",
".",
"Join",
"(",
"clouds",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"list",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// add support for a default (empty) selection.",
"clouds",
"=",
"append",
"(",
"clouds",
",",
"\"",
"\"",
")",
"\n\n",
"verify",
":=",
"interact",
".",
"MatchOptions",
"(",
"clouds",
",",
"\"",
"\"",
")",
"\n\n",
"query",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"defCloud",
")",
"\n",
"cloud",
",",
"err",
":=",
"interact",
".",
"QueryVerify",
"(",
"query",
",",
"scanner",
",",
"w",
",",
"w",
",",
"verify",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"cloud",
"==",
"\"",
"\"",
"{",
"return",
"defCloud",
",",
"nil",
"\n",
"}",
"\n",
"if",
"ok",
":=",
"names",
".",
"IsValidCloud",
"(",
"cloud",
")",
";",
"!",
"ok",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
",",
"cloud",
")",
"\n",
"}",
"\n\n",
"cloudName",
",",
"ok",
":=",
"interact",
".",
"FindMatch",
"(",
"cloud",
",",
"clouds",
")",
"\n",
"if",
"!",
"ok",
"{",
"// should be impossible",
"return",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cloud",
")",
"\n",
"}",
"\n\n",
"return",
"cloudName",
",",
"nil",
"\n",
"}"
] | // queryCloud asks the user to choose a cloud. | [
"queryCloud",
"asks",
"the",
"user",
"to",
"choose",
"a",
"cloud",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/bootstrap_interactive.go#L42-L72 |
154,492 | juju/juju | cmd/juju/commands/bootstrap_interactive.go | queryRegion | func queryRegion(cloud string, regions []jujucloud.Region, scanner *bufio.Scanner, w io.Writer) (string, error) {
fmt.Fprintf(w, "Regions in %s:\n", cloud)
names := jujucloud.RegionNames(regions)
// add an empty string to allow for a default value. Also gives us an extra
// line return after the list of names.
names = append(names, "")
if _, err := fmt.Fprintln(w, strings.Join(names, "\n")); err != nil {
return "", errors.Trace(err)
}
verify := interact.MatchOptions(names, "Invalid region.")
defaultRegion := regions[0].Name
query := fmt.Sprintf("Select a region in %s [%s]: ", cloud, defaultRegion)
region, err := interact.QueryVerify(query, scanner, w, w, verify)
if err != nil {
return "", errors.Trace(err)
}
if region == "" {
return defaultRegion, nil
}
regionName, ok := interact.FindMatch(region, names)
if !ok {
// should be impossible
return "", errors.Errorf("invalid region name chosen: %s", region)
}
return regionName, nil
} | go | func queryRegion(cloud string, regions []jujucloud.Region, scanner *bufio.Scanner, w io.Writer) (string, error) {
fmt.Fprintf(w, "Regions in %s:\n", cloud)
names := jujucloud.RegionNames(regions)
// add an empty string to allow for a default value. Also gives us an extra
// line return after the list of names.
names = append(names, "")
if _, err := fmt.Fprintln(w, strings.Join(names, "\n")); err != nil {
return "", errors.Trace(err)
}
verify := interact.MatchOptions(names, "Invalid region.")
defaultRegion := regions[0].Name
query := fmt.Sprintf("Select a region in %s [%s]: ", cloud, defaultRegion)
region, err := interact.QueryVerify(query, scanner, w, w, verify)
if err != nil {
return "", errors.Trace(err)
}
if region == "" {
return defaultRegion, nil
}
regionName, ok := interact.FindMatch(region, names)
if !ok {
// should be impossible
return "", errors.Errorf("invalid region name chosen: %s", region)
}
return regionName, nil
} | [
"func",
"queryRegion",
"(",
"cloud",
"string",
",",
"regions",
"[",
"]",
"jujucloud",
".",
"Region",
",",
"scanner",
"*",
"bufio",
".",
"Scanner",
",",
"w",
"io",
".",
"Writer",
")",
"(",
"string",
",",
"error",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"cloud",
")",
"\n",
"names",
":=",
"jujucloud",
".",
"RegionNames",
"(",
"regions",
")",
"\n",
"// add an empty string to allow for a default value. Also gives us an extra",
"// line return after the list of names.",
"names",
"=",
"append",
"(",
"names",
",",
"\"",
"\"",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"strings",
".",
"Join",
"(",
"names",
",",
"\"",
"\\n",
"\"",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"verify",
":=",
"interact",
".",
"MatchOptions",
"(",
"names",
",",
"\"",
"\"",
")",
"\n",
"defaultRegion",
":=",
"regions",
"[",
"0",
"]",
".",
"Name",
"\n",
"query",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"cloud",
",",
"defaultRegion",
")",
"\n",
"region",
",",
"err",
":=",
"interact",
".",
"QueryVerify",
"(",
"query",
",",
"scanner",
",",
"w",
",",
"w",
",",
"verify",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"region",
"==",
"\"",
"\"",
"{",
"return",
"defaultRegion",
",",
"nil",
"\n",
"}",
"\n",
"regionName",
",",
"ok",
":=",
"interact",
".",
"FindMatch",
"(",
"region",
",",
"names",
")",
"\n",
"if",
"!",
"ok",
"{",
"// should be impossible",
"return",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"region",
")",
"\n",
"}",
"\n\n",
"return",
"regionName",
",",
"nil",
"\n",
"}"
] | // queryRegion asks the user to pick a region of the ones passed in. The first
// region in the list will be the default. | [
"queryRegion",
"asks",
"the",
"user",
"to",
"pick",
"a",
"region",
"of",
"the",
"ones",
"passed",
"in",
".",
"The",
"first",
"region",
"in",
"the",
"list",
"will",
"be",
"the",
"default",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/bootstrap_interactive.go#L76-L102 |
154,493 | juju/juju | worker/uniter/relation/relations.go | NextOp | func (s *relationsResolver) NextOp(
localState resolver.LocalState,
remoteState remotestate.Snapshot,
opFactory operation.Factory,
) (operation.Operation, error) {
hook, err := s.relations.NextHook(localState, remoteState)
if err != nil {
return nil, errors.Trace(err)
}
return opFactory.NewRunHook(hook)
} | go | func (s *relationsResolver) NextOp(
localState resolver.LocalState,
remoteState remotestate.Snapshot,
opFactory operation.Factory,
) (operation.Operation, error) {
hook, err := s.relations.NextHook(localState, remoteState)
if err != nil {
return nil, errors.Trace(err)
}
return opFactory.NewRunHook(hook)
} | [
"func",
"(",
"s",
"*",
"relationsResolver",
")",
"NextOp",
"(",
"localState",
"resolver",
".",
"LocalState",
",",
"remoteState",
"remotestate",
".",
"Snapshot",
",",
"opFactory",
"operation",
".",
"Factory",
",",
")",
"(",
"operation",
".",
"Operation",
",",
"error",
")",
"{",
"hook",
",",
"err",
":=",
"s",
".",
"relations",
".",
"NextHook",
"(",
"localState",
",",
"remoteState",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"opFactory",
".",
"NewRunHook",
"(",
"hook",
")",
"\n",
"}"
] | // NextOp implements resolver.Resolver. | [
"NextOp",
"implements",
"resolver",
".",
"Resolver",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relations.go#L63-L73 |
154,494 | juju/juju | worker/uniter/relation/relations.go | NewRelations | func NewRelations(config RelationsConfig) (Relations, error) {
unit, err := config.State.Unit(config.UnitTag)
if err != nil {
return nil, errors.Trace(err)
}
principalName, subordinate, err := unit.PrincipalName()
if err != nil {
return nil, errors.Trace(err)
}
leadershipContext := config.NewLeadershipContext(
config.State.LeadershipSettings,
config.Tracker,
config.UnitTag.Id(),
)
r := &relations{
st: config.State,
unit: unit,
leaderCtx: leadershipContext,
subordinate: subordinate,
principalName: principalName,
charmDir: config.CharmDir,
relationsDir: config.RelationsDir,
relationers: make(map[int]*Relationer),
abort: config.Abort,
}
if err := r.init(); err != nil {
return nil, errors.Trace(err)
}
return r, nil
} | go | func NewRelations(config RelationsConfig) (Relations, error) {
unit, err := config.State.Unit(config.UnitTag)
if err != nil {
return nil, errors.Trace(err)
}
principalName, subordinate, err := unit.PrincipalName()
if err != nil {
return nil, errors.Trace(err)
}
leadershipContext := config.NewLeadershipContext(
config.State.LeadershipSettings,
config.Tracker,
config.UnitTag.Id(),
)
r := &relations{
st: config.State,
unit: unit,
leaderCtx: leadershipContext,
subordinate: subordinate,
principalName: principalName,
charmDir: config.CharmDir,
relationsDir: config.RelationsDir,
relationers: make(map[int]*Relationer),
abort: config.Abort,
}
if err := r.init(); err != nil {
return nil, errors.Trace(err)
}
return r, nil
} | [
"func",
"NewRelations",
"(",
"config",
"RelationsConfig",
")",
"(",
"Relations",
",",
"error",
")",
"{",
"unit",
",",
"err",
":=",
"config",
".",
"State",
".",
"Unit",
"(",
"config",
".",
"UnitTag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"principalName",
",",
"subordinate",
",",
"err",
":=",
"unit",
".",
"PrincipalName",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"leadershipContext",
":=",
"config",
".",
"NewLeadershipContext",
"(",
"config",
".",
"State",
".",
"LeadershipSettings",
",",
"config",
".",
"Tracker",
",",
"config",
".",
"UnitTag",
".",
"Id",
"(",
")",
",",
")",
"\n",
"r",
":=",
"&",
"relations",
"{",
"st",
":",
"config",
".",
"State",
",",
"unit",
":",
"unit",
",",
"leaderCtx",
":",
"leadershipContext",
",",
"subordinate",
":",
"subordinate",
",",
"principalName",
":",
"principalName",
",",
"charmDir",
":",
"config",
".",
"CharmDir",
",",
"relationsDir",
":",
"config",
".",
"RelationsDir",
",",
"relationers",
":",
"make",
"(",
"map",
"[",
"int",
"]",
"*",
"Relationer",
")",
",",
"abort",
":",
"config",
".",
"Abort",
",",
"}",
"\n",
"if",
"err",
":=",
"r",
".",
"init",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"r",
",",
"nil",
"\n",
"}"
] | // NewRelations returns a new Relations instance. | [
"NewRelations",
"returns",
"a",
"new",
"Relations",
"instance",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relations.go#L104-L133 |
154,495 | juju/juju | worker/uniter/relation/relations.go | NextHook | func (r *relations) NextHook(
localState resolver.LocalState,
remoteState remotestate.Snapshot,
) (hook.Info, error) {
if remoteState.Life == params.Dying {
// The unit is Dying, so make sure all subordinates are dying.
var destroyAllSubordinates bool
for relationId, relationSnapshot := range remoteState.Relations {
if relationSnapshot.Life != params.Alive {
continue
}
relationer, ok := r.relationers[relationId]
if !ok {
continue
}
if relationer.ru.Endpoint().Scope == corecharm.ScopeContainer {
relationSnapshot.Life = params.Dying
remoteState.Relations[relationId] = relationSnapshot
destroyAllSubordinates = true
}
}
if destroyAllSubordinates {
if err := r.unit.DestroyAllSubordinates(); err != nil {
return hook.Info{}, errors.Trace(err)
}
}
}
// Add/remove local relation state; enter and leave scope as necessary.
if err := r.update(remoteState.Relations); err != nil {
return hook.Info{}, errors.Trace(err)
}
if localState.Kind != operation.Continue {
return hook.Info{}, resolver.ErrNoOperation
}
// See if any of the relations have operations to perform.
for relationId, relationSnapshot := range remoteState.Relations {
relationer, ok := r.relationers[relationId]
if !ok || relationer.IsImplicit() {
continue
}
var remoteBroken bool
if remoteState.Life == params.Dying ||
relationSnapshot.Life == params.Dying || relationSnapshot.Suspended {
relationSnapshot = remotestate.RelationSnapshot{}
remoteBroken = true
// TODO(axw) if relation is implicit, leave scope & remove.
}
// If either the unit or the relation are Dying, or the relation becomes suspended,
// then the relation should be broken.
hook, err := nextRelationHook(relationer.dir, relationSnapshot, remoteBroken)
if err == resolver.ErrNoOperation {
continue
}
return hook, err
}
return hook.Info{}, resolver.ErrNoOperation
} | go | func (r *relations) NextHook(
localState resolver.LocalState,
remoteState remotestate.Snapshot,
) (hook.Info, error) {
if remoteState.Life == params.Dying {
// The unit is Dying, so make sure all subordinates are dying.
var destroyAllSubordinates bool
for relationId, relationSnapshot := range remoteState.Relations {
if relationSnapshot.Life != params.Alive {
continue
}
relationer, ok := r.relationers[relationId]
if !ok {
continue
}
if relationer.ru.Endpoint().Scope == corecharm.ScopeContainer {
relationSnapshot.Life = params.Dying
remoteState.Relations[relationId] = relationSnapshot
destroyAllSubordinates = true
}
}
if destroyAllSubordinates {
if err := r.unit.DestroyAllSubordinates(); err != nil {
return hook.Info{}, errors.Trace(err)
}
}
}
// Add/remove local relation state; enter and leave scope as necessary.
if err := r.update(remoteState.Relations); err != nil {
return hook.Info{}, errors.Trace(err)
}
if localState.Kind != operation.Continue {
return hook.Info{}, resolver.ErrNoOperation
}
// See if any of the relations have operations to perform.
for relationId, relationSnapshot := range remoteState.Relations {
relationer, ok := r.relationers[relationId]
if !ok || relationer.IsImplicit() {
continue
}
var remoteBroken bool
if remoteState.Life == params.Dying ||
relationSnapshot.Life == params.Dying || relationSnapshot.Suspended {
relationSnapshot = remotestate.RelationSnapshot{}
remoteBroken = true
// TODO(axw) if relation is implicit, leave scope & remove.
}
// If either the unit or the relation are Dying, or the relation becomes suspended,
// then the relation should be broken.
hook, err := nextRelationHook(relationer.dir, relationSnapshot, remoteBroken)
if err == resolver.ErrNoOperation {
continue
}
return hook, err
}
return hook.Info{}, resolver.ErrNoOperation
} | [
"func",
"(",
"r",
"*",
"relations",
")",
"NextHook",
"(",
"localState",
"resolver",
".",
"LocalState",
",",
"remoteState",
"remotestate",
".",
"Snapshot",
",",
")",
"(",
"hook",
".",
"Info",
",",
"error",
")",
"{",
"if",
"remoteState",
".",
"Life",
"==",
"params",
".",
"Dying",
"{",
"// The unit is Dying, so make sure all subordinates are dying.",
"var",
"destroyAllSubordinates",
"bool",
"\n",
"for",
"relationId",
",",
"relationSnapshot",
":=",
"range",
"remoteState",
".",
"Relations",
"{",
"if",
"relationSnapshot",
".",
"Life",
"!=",
"params",
".",
"Alive",
"{",
"continue",
"\n",
"}",
"\n",
"relationer",
",",
"ok",
":=",
"r",
".",
"relationers",
"[",
"relationId",
"]",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"relationer",
".",
"ru",
".",
"Endpoint",
"(",
")",
".",
"Scope",
"==",
"corecharm",
".",
"ScopeContainer",
"{",
"relationSnapshot",
".",
"Life",
"=",
"params",
".",
"Dying",
"\n",
"remoteState",
".",
"Relations",
"[",
"relationId",
"]",
"=",
"relationSnapshot",
"\n",
"destroyAllSubordinates",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"destroyAllSubordinates",
"{",
"if",
"err",
":=",
"r",
".",
"unit",
".",
"DestroyAllSubordinates",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"hook",
".",
"Info",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Add/remove local relation state; enter and leave scope as necessary.",
"if",
"err",
":=",
"r",
".",
"update",
"(",
"remoteState",
".",
"Relations",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"hook",
".",
"Info",
"{",
"}",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"localState",
".",
"Kind",
"!=",
"operation",
".",
"Continue",
"{",
"return",
"hook",
".",
"Info",
"{",
"}",
",",
"resolver",
".",
"ErrNoOperation",
"\n",
"}",
"\n\n",
"// See if any of the relations have operations to perform.",
"for",
"relationId",
",",
"relationSnapshot",
":=",
"range",
"remoteState",
".",
"Relations",
"{",
"relationer",
",",
"ok",
":=",
"r",
".",
"relationers",
"[",
"relationId",
"]",
"\n",
"if",
"!",
"ok",
"||",
"relationer",
".",
"IsImplicit",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"var",
"remoteBroken",
"bool",
"\n",
"if",
"remoteState",
".",
"Life",
"==",
"params",
".",
"Dying",
"||",
"relationSnapshot",
".",
"Life",
"==",
"params",
".",
"Dying",
"||",
"relationSnapshot",
".",
"Suspended",
"{",
"relationSnapshot",
"=",
"remotestate",
".",
"RelationSnapshot",
"{",
"}",
"\n",
"remoteBroken",
"=",
"true",
"\n",
"// TODO(axw) if relation is implicit, leave scope & remove.",
"}",
"\n",
"// If either the unit or the relation are Dying, or the relation becomes suspended,",
"// then the relation should be broken.",
"hook",
",",
"err",
":=",
"nextRelationHook",
"(",
"relationer",
".",
"dir",
",",
"relationSnapshot",
",",
"remoteBroken",
")",
"\n",
"if",
"err",
"==",
"resolver",
".",
"ErrNoOperation",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"hook",
",",
"err",
"\n",
"}",
"\n",
"return",
"hook",
".",
"Info",
"{",
"}",
",",
"resolver",
".",
"ErrNoOperation",
"\n",
"}"
] | // NextHook implements Relations. | [
"NextHook",
"implements",
"Relations",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relations.go#L196-L256 |
154,496 | juju/juju | worker/uniter/relation/relations.go | nextRelationHook | func nextRelationHook(
dir *StateDir,
remote remotestate.RelationSnapshot,
remoteBroken bool,
) (hook.Info, error) {
local := dir.State()
// If there's a guaranteed next hook, return that.
relationId := local.RelationId
if local.ChangedPending != "" {
unitName := local.ChangedPending
return hook.Info{
Kind: hooks.RelationChanged,
RelationId: relationId,
RemoteUnit: unitName,
ChangeVersion: remote.Members[unitName],
}, nil
}
// Get the union of all relevant units, and sort them, so we produce events
// in a consistent order (largely for the convenience of the tests).
allUnitNames := set.NewStrings()
for unitName := range local.Members {
allUnitNames.Add(unitName)
}
for unitName := range remote.Members {
allUnitNames.Add(unitName)
}
sortedUnitNames := allUnitNames.SortedValues()
// If there are any locally known units that are no longer reflected in
// remote state, depart them.
for _, unitName := range sortedUnitNames {
changeVersion, found := local.Members[unitName]
if !found {
continue
}
if _, found := remote.Members[unitName]; !found {
return hook.Info{
Kind: hooks.RelationDeparted,
RelationId: relationId,
RemoteUnit: unitName,
ChangeVersion: changeVersion,
}, nil
}
}
// If the relation's meant to be broken, break it.
if remoteBroken {
if !dir.Exists() {
// The relation may have been suspended and then removed, so we
// don't want to run the hook twice.
return hook.Info{}, resolver.ErrNoOperation
}
return hook.Info{
Kind: hooks.RelationBroken,
RelationId: relationId,
}, nil
}
// If there are any remote units not locally known, join them.
for _, unitName := range sortedUnitNames {
changeVersion, found := remote.Members[unitName]
if !found {
continue
}
if _, found := local.Members[unitName]; !found {
return hook.Info{
Kind: hooks.RelationJoined,
RelationId: relationId,
RemoteUnit: unitName,
ChangeVersion: changeVersion,
}, nil
}
}
// Finally scan for remote units whose latest version is not reflected
// in local state.
for _, unitName := range sortedUnitNames {
remoteChangeVersion, found := remote.Members[unitName]
if !found {
continue
}
localChangeVersion, found := local.Members[unitName]
if !found {
continue
}
// NOTE(axw) we use != and not > to cater due to the
// use of the relation settings document's txn-revno
// as the version. When model-uuid migration occurs, the
// document is recreated, resetting txn-revno.
if remoteChangeVersion != localChangeVersion {
return hook.Info{
Kind: hooks.RelationChanged,
RelationId: relationId,
RemoteUnit: unitName,
ChangeVersion: remoteChangeVersion,
}, nil
}
}
// Nothing left to do for this relation.
return hook.Info{}, resolver.ErrNoOperation
} | go | func nextRelationHook(
dir *StateDir,
remote remotestate.RelationSnapshot,
remoteBroken bool,
) (hook.Info, error) {
local := dir.State()
// If there's a guaranteed next hook, return that.
relationId := local.RelationId
if local.ChangedPending != "" {
unitName := local.ChangedPending
return hook.Info{
Kind: hooks.RelationChanged,
RelationId: relationId,
RemoteUnit: unitName,
ChangeVersion: remote.Members[unitName],
}, nil
}
// Get the union of all relevant units, and sort them, so we produce events
// in a consistent order (largely for the convenience of the tests).
allUnitNames := set.NewStrings()
for unitName := range local.Members {
allUnitNames.Add(unitName)
}
for unitName := range remote.Members {
allUnitNames.Add(unitName)
}
sortedUnitNames := allUnitNames.SortedValues()
// If there are any locally known units that are no longer reflected in
// remote state, depart them.
for _, unitName := range sortedUnitNames {
changeVersion, found := local.Members[unitName]
if !found {
continue
}
if _, found := remote.Members[unitName]; !found {
return hook.Info{
Kind: hooks.RelationDeparted,
RelationId: relationId,
RemoteUnit: unitName,
ChangeVersion: changeVersion,
}, nil
}
}
// If the relation's meant to be broken, break it.
if remoteBroken {
if !dir.Exists() {
// The relation may have been suspended and then removed, so we
// don't want to run the hook twice.
return hook.Info{}, resolver.ErrNoOperation
}
return hook.Info{
Kind: hooks.RelationBroken,
RelationId: relationId,
}, nil
}
// If there are any remote units not locally known, join them.
for _, unitName := range sortedUnitNames {
changeVersion, found := remote.Members[unitName]
if !found {
continue
}
if _, found := local.Members[unitName]; !found {
return hook.Info{
Kind: hooks.RelationJoined,
RelationId: relationId,
RemoteUnit: unitName,
ChangeVersion: changeVersion,
}, nil
}
}
// Finally scan for remote units whose latest version is not reflected
// in local state.
for _, unitName := range sortedUnitNames {
remoteChangeVersion, found := remote.Members[unitName]
if !found {
continue
}
localChangeVersion, found := local.Members[unitName]
if !found {
continue
}
// NOTE(axw) we use != and not > to cater due to the
// use of the relation settings document's txn-revno
// as the version. When model-uuid migration occurs, the
// document is recreated, resetting txn-revno.
if remoteChangeVersion != localChangeVersion {
return hook.Info{
Kind: hooks.RelationChanged,
RelationId: relationId,
RemoteUnit: unitName,
ChangeVersion: remoteChangeVersion,
}, nil
}
}
// Nothing left to do for this relation.
return hook.Info{}, resolver.ErrNoOperation
} | [
"func",
"nextRelationHook",
"(",
"dir",
"*",
"StateDir",
",",
"remote",
"remotestate",
".",
"RelationSnapshot",
",",
"remoteBroken",
"bool",
",",
")",
"(",
"hook",
".",
"Info",
",",
"error",
")",
"{",
"local",
":=",
"dir",
".",
"State",
"(",
")",
"\n",
"// If there's a guaranteed next hook, return that.",
"relationId",
":=",
"local",
".",
"RelationId",
"\n",
"if",
"local",
".",
"ChangedPending",
"!=",
"\"",
"\"",
"{",
"unitName",
":=",
"local",
".",
"ChangedPending",
"\n",
"return",
"hook",
".",
"Info",
"{",
"Kind",
":",
"hooks",
".",
"RelationChanged",
",",
"RelationId",
":",
"relationId",
",",
"RemoteUnit",
":",
"unitName",
",",
"ChangeVersion",
":",
"remote",
".",
"Members",
"[",
"unitName",
"]",
",",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"// Get the union of all relevant units, and sort them, so we produce events",
"// in a consistent order (largely for the convenience of the tests).",
"allUnitNames",
":=",
"set",
".",
"NewStrings",
"(",
")",
"\n",
"for",
"unitName",
":=",
"range",
"local",
".",
"Members",
"{",
"allUnitNames",
".",
"Add",
"(",
"unitName",
")",
"\n",
"}",
"\n",
"for",
"unitName",
":=",
"range",
"remote",
".",
"Members",
"{",
"allUnitNames",
".",
"Add",
"(",
"unitName",
")",
"\n",
"}",
"\n",
"sortedUnitNames",
":=",
"allUnitNames",
".",
"SortedValues",
"(",
")",
"\n\n",
"// If there are any locally known units that are no longer reflected in",
"// remote state, depart them.",
"for",
"_",
",",
"unitName",
":=",
"range",
"sortedUnitNames",
"{",
"changeVersion",
",",
"found",
":=",
"local",
".",
"Members",
"[",
"unitName",
"]",
"\n",
"if",
"!",
"found",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"_",
",",
"found",
":=",
"remote",
".",
"Members",
"[",
"unitName",
"]",
";",
"!",
"found",
"{",
"return",
"hook",
".",
"Info",
"{",
"Kind",
":",
"hooks",
".",
"RelationDeparted",
",",
"RelationId",
":",
"relationId",
",",
"RemoteUnit",
":",
"unitName",
",",
"ChangeVersion",
":",
"changeVersion",
",",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If the relation's meant to be broken, break it.",
"if",
"remoteBroken",
"{",
"if",
"!",
"dir",
".",
"Exists",
"(",
")",
"{",
"// The relation may have been suspended and then removed, so we",
"// don't want to run the hook twice.",
"return",
"hook",
".",
"Info",
"{",
"}",
",",
"resolver",
".",
"ErrNoOperation",
"\n",
"}",
"\n",
"return",
"hook",
".",
"Info",
"{",
"Kind",
":",
"hooks",
".",
"RelationBroken",
",",
"RelationId",
":",
"relationId",
",",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"// If there are any remote units not locally known, join them.",
"for",
"_",
",",
"unitName",
":=",
"range",
"sortedUnitNames",
"{",
"changeVersion",
",",
"found",
":=",
"remote",
".",
"Members",
"[",
"unitName",
"]",
"\n",
"if",
"!",
"found",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"_",
",",
"found",
":=",
"local",
".",
"Members",
"[",
"unitName",
"]",
";",
"!",
"found",
"{",
"return",
"hook",
".",
"Info",
"{",
"Kind",
":",
"hooks",
".",
"RelationJoined",
",",
"RelationId",
":",
"relationId",
",",
"RemoteUnit",
":",
"unitName",
",",
"ChangeVersion",
":",
"changeVersion",
",",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Finally scan for remote units whose latest version is not reflected",
"// in local state.",
"for",
"_",
",",
"unitName",
":=",
"range",
"sortedUnitNames",
"{",
"remoteChangeVersion",
",",
"found",
":=",
"remote",
".",
"Members",
"[",
"unitName",
"]",
"\n",
"if",
"!",
"found",
"{",
"continue",
"\n",
"}",
"\n",
"localChangeVersion",
",",
"found",
":=",
"local",
".",
"Members",
"[",
"unitName",
"]",
"\n",
"if",
"!",
"found",
"{",
"continue",
"\n",
"}",
"\n",
"// NOTE(axw) we use != and not > to cater due to the",
"// use of the relation settings document's txn-revno",
"// as the version. When model-uuid migration occurs, the",
"// document is recreated, resetting txn-revno.",
"if",
"remoteChangeVersion",
"!=",
"localChangeVersion",
"{",
"return",
"hook",
".",
"Info",
"{",
"Kind",
":",
"hooks",
".",
"RelationChanged",
",",
"RelationId",
":",
"relationId",
",",
"RemoteUnit",
":",
"unitName",
",",
"ChangeVersion",
":",
"remoteChangeVersion",
",",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Nothing left to do for this relation.",
"return",
"hook",
".",
"Info",
"{",
"}",
",",
"resolver",
".",
"ErrNoOperation",
"\n",
"}"
] | // nextRelationHook returns the next hook op that should be executed in the
// relation characterised by the supplied local and remote state; or an error
// if the states do not refer to the same relation; or ErrRelationUpToDate if
// no hooks need to be executed. | [
"nextRelationHook",
"returns",
"the",
"next",
"hook",
"op",
"that",
"should",
"be",
"executed",
"in",
"the",
"relation",
"characterised",
"by",
"the",
"supplied",
"local",
"and",
"remote",
"state",
";",
"or",
"an",
"error",
"if",
"the",
"states",
"do",
"not",
"refer",
"to",
"the",
"same",
"relation",
";",
"or",
"ErrRelationUpToDate",
"if",
"no",
"hooks",
"need",
"to",
"be",
"executed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relations.go#L262-L365 |
154,497 | juju/juju | worker/uniter/relation/relations.go | Name | func (r *relations) Name(id int) (string, error) {
relationer, found := r.relationers[id]
if !found {
return "", errors.Errorf("unknown relation: %d", id)
}
return relationer.ru.Endpoint().Name, nil
} | go | func (r *relations) Name(id int) (string, error) {
relationer, found := r.relationers[id]
if !found {
return "", errors.Errorf("unknown relation: %d", id)
}
return relationer.ru.Endpoint().Name, nil
} | [
"func",
"(",
"r",
"*",
"relations",
")",
"Name",
"(",
"id",
"int",
")",
"(",
"string",
",",
"error",
")",
"{",
"relationer",
",",
"found",
":=",
"r",
".",
"relationers",
"[",
"id",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"}",
"\n",
"return",
"relationer",
".",
"ru",
".",
"Endpoint",
"(",
")",
".",
"Name",
",",
"nil",
"\n",
"}"
] | // Name is part of the Relations interface. | [
"Name",
"is",
"part",
"of",
"the",
"Relations",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relations.go#L368-L374 |
154,498 | juju/juju | worker/uniter/relation/relations.go | PrepareHook | func (r *relations) PrepareHook(hookInfo hook.Info) (string, error) {
if !hookInfo.Kind.IsRelation() {
return "", errors.Errorf("not a relation hook: %#v", hookInfo)
}
relationer, found := r.relationers[hookInfo.RelationId]
if !found {
return "", errors.Errorf("unknown relation: %d", hookInfo.RelationId)
}
return relationer.PrepareHook(hookInfo)
} | go | func (r *relations) PrepareHook(hookInfo hook.Info) (string, error) {
if !hookInfo.Kind.IsRelation() {
return "", errors.Errorf("not a relation hook: %#v", hookInfo)
}
relationer, found := r.relationers[hookInfo.RelationId]
if !found {
return "", errors.Errorf("unknown relation: %d", hookInfo.RelationId)
}
return relationer.PrepareHook(hookInfo)
} | [
"func",
"(",
"r",
"*",
"relations",
")",
"PrepareHook",
"(",
"hookInfo",
"hook",
".",
"Info",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"!",
"hookInfo",
".",
"Kind",
".",
"IsRelation",
"(",
")",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hookInfo",
")",
"\n",
"}",
"\n",
"relationer",
",",
"found",
":=",
"r",
".",
"relationers",
"[",
"hookInfo",
".",
"RelationId",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hookInfo",
".",
"RelationId",
")",
"\n",
"}",
"\n",
"return",
"relationer",
".",
"PrepareHook",
"(",
"hookInfo",
")",
"\n",
"}"
] | // PrepareHook is part of the Relations interface. | [
"PrepareHook",
"is",
"part",
"of",
"the",
"Relations",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relations.go#L377-L386 |
154,499 | juju/juju | worker/uniter/relation/relations.go | CommitHook | func (r *relations) CommitHook(hookInfo hook.Info) (err error) {
defer func() {
if err == nil && hookInfo.Kind == hooks.RelationBroken {
delete(r.relationers, hookInfo.RelationId)
}
}()
if !hookInfo.Kind.IsRelation() {
return errors.Errorf("not a relation hook: %#v", hookInfo)
}
relationer, found := r.relationers[hookInfo.RelationId]
if !found {
return errors.Errorf("unknown relation: %d", hookInfo.RelationId)
}
return relationer.CommitHook(hookInfo)
} | go | func (r *relations) CommitHook(hookInfo hook.Info) (err error) {
defer func() {
if err == nil && hookInfo.Kind == hooks.RelationBroken {
delete(r.relationers, hookInfo.RelationId)
}
}()
if !hookInfo.Kind.IsRelation() {
return errors.Errorf("not a relation hook: %#v", hookInfo)
}
relationer, found := r.relationers[hookInfo.RelationId]
if !found {
return errors.Errorf("unknown relation: %d", hookInfo.RelationId)
}
return relationer.CommitHook(hookInfo)
} | [
"func",
"(",
"r",
"*",
"relations",
")",
"CommitHook",
"(",
"hookInfo",
"hook",
".",
"Info",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"==",
"nil",
"&&",
"hookInfo",
".",
"Kind",
"==",
"hooks",
".",
"RelationBroken",
"{",
"delete",
"(",
"r",
".",
"relationers",
",",
"hookInfo",
".",
"RelationId",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"if",
"!",
"hookInfo",
".",
"Kind",
".",
"IsRelation",
"(",
")",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hookInfo",
")",
"\n",
"}",
"\n",
"relationer",
",",
"found",
":=",
"r",
".",
"relationers",
"[",
"hookInfo",
".",
"RelationId",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hookInfo",
".",
"RelationId",
")",
"\n",
"}",
"\n",
"return",
"relationer",
".",
"CommitHook",
"(",
"hookInfo",
")",
"\n",
"}"
] | // CommitHook is part of the Relations interface. | [
"CommitHook",
"is",
"part",
"of",
"the",
"Relations",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/relation/relations.go#L389-L403 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.