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
|
---|---|---|---|---|---|---|---|---|---|---|---|
5,200 | juju/juju | container/lxd/certificate.go | NewCertificate | func NewCertificate(certPEM, keyPEM []byte) *Certificate {
return &Certificate{
CertPEM: certPEM,
KeyPEM: keyPEM,
}
} | go | func NewCertificate(certPEM, keyPEM []byte) *Certificate {
return &Certificate{
CertPEM: certPEM,
KeyPEM: keyPEM,
}
} | [
"func",
"NewCertificate",
"(",
"certPEM",
",",
"keyPEM",
"[",
"]",
"byte",
")",
"*",
"Certificate",
"{",
"return",
"&",
"Certificate",
"{",
"CertPEM",
":",
"certPEM",
",",
"KeyPEM",
":",
"keyPEM",
",",
"}",
"\n",
"}"
] | // NewCertificate creates a new Certificate for the given cert and key. | [
"NewCertificate",
"creates",
"a",
"new",
"Certificate",
"for",
"the",
"given",
"cert",
"and",
"key",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/certificate.go#L41-L46 |
5,201 | juju/juju | container/lxd/certificate.go | Validate | func (c *Certificate) Validate() error {
if len(c.CertPEM) == 0 {
return errors.NotValidf("missing cert PEM")
}
if len(c.KeyPEM) == 0 {
return errors.NotValidf("missing key PEM")
}
return nil
} | go | func (c *Certificate) Validate() error {
if len(c.CertPEM) == 0 {
return errors.NotValidf("missing cert PEM")
}
if len(c.KeyPEM) == 0 {
return errors.NotValidf("missing key PEM")
}
return nil
} | [
"func",
"(",
"c",
"*",
"Certificate",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"len",
"(",
"c",
".",
"CertPEM",
")",
"==",
"0",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"c",
".",
"KeyPEM",
")",
"==",
"0",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate ensures that the cert is valid. | [
"Validate",
"ensures",
"that",
"the",
"cert",
"is",
"valid",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/certificate.go#L49-L57 |
5,202 | juju/juju | container/lxd/certificate.go | WriteCertPEM | func (c *Certificate) WriteCertPEM(out io.Writer) error {
_, err := out.Write(c.CertPEM)
return errors.Trace(err)
} | go | func (c *Certificate) WriteCertPEM(out io.Writer) error {
_, err := out.Write(c.CertPEM)
return errors.Trace(err)
} | [
"func",
"(",
"c",
"*",
"Certificate",
")",
"WriteCertPEM",
"(",
"out",
"io",
".",
"Writer",
")",
"error",
"{",
"_",
",",
"err",
":=",
"out",
".",
"Write",
"(",
"c",
".",
"CertPEM",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // WriteCertPEM writes the cert's x.509 PEM data to the given writer. | [
"WriteCertPEM",
"writes",
"the",
"cert",
"s",
"x",
".",
"509",
"PEM",
"data",
"to",
"the",
"given",
"writer",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/certificate.go#L60-L63 |
5,203 | juju/juju | container/lxd/certificate.go | WriteKeyPEM | func (c *Certificate) WriteKeyPEM(out io.Writer) error {
_, err := out.Write(c.KeyPEM)
return errors.Trace(err)
} | go | func (c *Certificate) WriteKeyPEM(out io.Writer) error {
_, err := out.Write(c.KeyPEM)
return errors.Trace(err)
} | [
"func",
"(",
"c",
"*",
"Certificate",
")",
"WriteKeyPEM",
"(",
"out",
"io",
".",
"Writer",
")",
"error",
"{",
"_",
",",
"err",
":=",
"out",
".",
"Write",
"(",
"c",
".",
"KeyPEM",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // WriteKeyPEM writes the key's x.509 PEM data to the given writer. | [
"WriteKeyPEM",
"writes",
"the",
"key",
"s",
"x",
".",
"509",
"PEM",
"data",
"to",
"the",
"given",
"writer",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/certificate.go#L66-L69 |
5,204 | juju/juju | container/lxd/certificate.go | Fingerprint | func (c *Certificate) Fingerprint() (string, error) {
x509Cert, err := c.X509()
if err != nil {
return "", errors.Trace(err)
}
data := sha256.Sum256(x509Cert.Raw)
return fmt.Sprintf("%x", data), nil
} | go | func (c *Certificate) Fingerprint() (string, error) {
x509Cert, err := c.X509()
if err != nil {
return "", errors.Trace(err)
}
data := sha256.Sum256(x509Cert.Raw)
return fmt.Sprintf("%x", data), nil
} | [
"func",
"(",
"c",
"*",
"Certificate",
")",
"Fingerprint",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"x509Cert",
",",
"err",
":=",
"c",
".",
"X509",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"data",
":=",
"sha256",
".",
"Sum256",
"(",
"x509Cert",
".",
"Raw",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"data",
")",
",",
"nil",
"\n",
"}"
] | // Fingerprint returns the cert's LXD fingerprint. | [
"Fingerprint",
"returns",
"the",
"cert",
"s",
"LXD",
"fingerprint",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/certificate.go#L72-L79 |
5,205 | juju/juju | container/lxd/certificate.go | X509 | func (c *Certificate) X509() (*x509.Certificate, error) {
block, _ := pem.Decode(c.CertPEM)
if block == nil {
return nil, errors.Errorf("invalid cert PEM (%d bytes)", len(c.CertPEM))
}
x509Cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, errors.Trace(err)
}
return x509Cert, nil
} | go | func (c *Certificate) X509() (*x509.Certificate, error) {
block, _ := pem.Decode(c.CertPEM)
if block == nil {
return nil, errors.Errorf("invalid cert PEM (%d bytes)", len(c.CertPEM))
}
x509Cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, errors.Trace(err)
}
return x509Cert, nil
} | [
"func",
"(",
"c",
"*",
"Certificate",
")",
"X509",
"(",
")",
"(",
"*",
"x509",
".",
"Certificate",
",",
"error",
")",
"{",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"c",
".",
"CertPEM",
")",
"\n",
"if",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"c",
".",
"CertPEM",
")",
")",
"\n",
"}",
"\n\n",
"x509Cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"block",
".",
"Bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"x509Cert",
",",
"nil",
"\n",
"}"
] | // X509 returns the x.509 certificate. | [
"X509",
"returns",
"the",
"x",
".",
"509",
"certificate",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/certificate.go#L82-L93 |
5,206 | juju/juju | container/lxd/certificate.go | AsCreateRequest | func (c *Certificate) AsCreateRequest() (api.CertificatesPost, error) {
block, _ := pem.Decode(c.CertPEM)
if block == nil {
return api.CertificatesPost{}, errors.New("failed to decode certificate PEM")
}
return api.CertificatesPost{
Certificate: base64.StdEncoding.EncodeToString(block.Bytes),
CertificatePut: api.CertificatePut{
Name: c.Name,
Type: "client",
},
}, nil
} | go | func (c *Certificate) AsCreateRequest() (api.CertificatesPost, error) {
block, _ := pem.Decode(c.CertPEM)
if block == nil {
return api.CertificatesPost{}, errors.New("failed to decode certificate PEM")
}
return api.CertificatesPost{
Certificate: base64.StdEncoding.EncodeToString(block.Bytes),
CertificatePut: api.CertificatePut{
Name: c.Name,
Type: "client",
},
}, nil
} | [
"func",
"(",
"c",
"*",
"Certificate",
")",
"AsCreateRequest",
"(",
")",
"(",
"api",
".",
"CertificatesPost",
",",
"error",
")",
"{",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"c",
".",
"CertPEM",
")",
"\n",
"if",
"block",
"==",
"nil",
"{",
"return",
"api",
".",
"CertificatesPost",
"{",
"}",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"api",
".",
"CertificatesPost",
"{",
"Certificate",
":",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"block",
".",
"Bytes",
")",
",",
"CertificatePut",
":",
"api",
".",
"CertificatePut",
"{",
"Name",
":",
"c",
".",
"Name",
",",
"Type",
":",
"\"",
"\"",
",",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // AsCreateRequest creates a payload for the LXD API, suitable for posting the
// client certificate to an LXD server. | [
"AsCreateRequest",
"creates",
"a",
"payload",
"for",
"the",
"LXD",
"API",
"suitable",
"for",
"posting",
"the",
"client",
"certificate",
"to",
"an",
"LXD",
"server",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/certificate.go#L97-L110 |
5,207 | juju/juju | upgrades/steps_253.go | stateStepsFor253 | func stateStepsFor253() []Step {
return []Step{
&upgradeStep{
description: "update inherited controller config global key",
targets: []Target{DatabaseMaster},
run: func(context Context) error {
return context.State().UpdateInheritedControllerConfig()
},
},
}
} | go | func stateStepsFor253() []Step {
return []Step{
&upgradeStep{
description: "update inherited controller config global key",
targets: []Target{DatabaseMaster},
run: func(context Context) error {
return context.State().UpdateInheritedControllerConfig()
},
},
}
} | [
"func",
"stateStepsFor253",
"(",
")",
"[",
"]",
"Step",
"{",
"return",
"[",
"]",
"Step",
"{",
"&",
"upgradeStep",
"{",
"description",
":",
"\"",
"\"",
",",
"targets",
":",
"[",
"]",
"Target",
"{",
"DatabaseMaster",
"}",
",",
"run",
":",
"func",
"(",
"context",
"Context",
")",
"error",
"{",
"return",
"context",
".",
"State",
"(",
")",
".",
"UpdateInheritedControllerConfig",
"(",
")",
"\n",
"}",
",",
"}",
",",
"}",
"\n",
"}"
] | // stateStepsFor253 returns upgrade steps for Juju 2.5.3 that manipulate state directly. | [
"stateStepsFor253",
"returns",
"upgrade",
"steps",
"for",
"Juju",
"2",
".",
"5",
".",
"3",
"that",
"manipulate",
"state",
"directly",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/steps_253.go#L7-L17 |
5,208 | juju/juju | state/podspec.go | SetPodSpec | func (m *CAASModel) SetPodSpec(appTag names.ApplicationTag, spec string) error {
buildTxn := func(attempt int) ([]txn.Op, error) {
var prereqOps []txn.Op
app, err := m.State().Application(appTag.Id())
if err != nil {
return nil, errors.Trace(err)
}
if app.Life() != Alive {
return nil, errors.Errorf("application %s not alive", app.String())
}
prereqOps = append(prereqOps, txn.Op{
C: applicationsC,
Id: app.doc.DocID,
Assert: isAliveDoc,
})
op := txn.Op{
C: podSpecsC,
Id: applicationGlobalKey(appTag.Id()),
}
existing, err := m.PodSpec(appTag)
if err == nil {
if existing == spec {
return nil, jujutxn.ErrNoOperations
}
op.Assert = txn.DocExists
op.Update = bson.D{{"$set", bson.D{{"spec", spec}}}}
} else if errors.IsNotFound(err) {
op.Assert = txn.DocMissing
op.Insert = containerSpecDoc{Spec: spec}
} else {
return nil, err
}
return append(prereqOps, op), nil
}
return m.mb.db().Run(buildTxn)
} | go | func (m *CAASModel) SetPodSpec(appTag names.ApplicationTag, spec string) error {
buildTxn := func(attempt int) ([]txn.Op, error) {
var prereqOps []txn.Op
app, err := m.State().Application(appTag.Id())
if err != nil {
return nil, errors.Trace(err)
}
if app.Life() != Alive {
return nil, errors.Errorf("application %s not alive", app.String())
}
prereqOps = append(prereqOps, txn.Op{
C: applicationsC,
Id: app.doc.DocID,
Assert: isAliveDoc,
})
op := txn.Op{
C: podSpecsC,
Id: applicationGlobalKey(appTag.Id()),
}
existing, err := m.PodSpec(appTag)
if err == nil {
if existing == spec {
return nil, jujutxn.ErrNoOperations
}
op.Assert = txn.DocExists
op.Update = bson.D{{"$set", bson.D{{"spec", spec}}}}
} else if errors.IsNotFound(err) {
op.Assert = txn.DocMissing
op.Insert = containerSpecDoc{Spec: spec}
} else {
return nil, err
}
return append(prereqOps, op), nil
}
return m.mb.db().Run(buildTxn)
} | [
"func",
"(",
"m",
"*",
"CAASModel",
")",
"SetPodSpec",
"(",
"appTag",
"names",
".",
"ApplicationTag",
",",
"spec",
"string",
")",
"error",
"{",
"buildTxn",
":=",
"func",
"(",
"attempt",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"var",
"prereqOps",
"[",
"]",
"txn",
".",
"Op",
"\n",
"app",
",",
"err",
":=",
"m",
".",
"State",
"(",
")",
".",
"Application",
"(",
"appTag",
".",
"Id",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"app",
".",
"Life",
"(",
")",
"!=",
"Alive",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"app",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"prereqOps",
"=",
"append",
"(",
"prereqOps",
",",
"txn",
".",
"Op",
"{",
"C",
":",
"applicationsC",
",",
"Id",
":",
"app",
".",
"doc",
".",
"DocID",
",",
"Assert",
":",
"isAliveDoc",
",",
"}",
")",
"\n\n",
"op",
":=",
"txn",
".",
"Op",
"{",
"C",
":",
"podSpecsC",
",",
"Id",
":",
"applicationGlobalKey",
"(",
"appTag",
".",
"Id",
"(",
")",
")",
",",
"}",
"\n",
"existing",
",",
"err",
":=",
"m",
".",
"PodSpec",
"(",
"appTag",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"if",
"existing",
"==",
"spec",
"{",
"return",
"nil",
",",
"jujutxn",
".",
"ErrNoOperations",
"\n",
"}",
"\n",
"op",
".",
"Assert",
"=",
"txn",
".",
"DocExists",
"\n",
"op",
".",
"Update",
"=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"spec",
"}",
"}",
"}",
"}",
"\n",
"}",
"else",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"op",
".",
"Assert",
"=",
"txn",
".",
"DocMissing",
"\n",
"op",
".",
"Insert",
"=",
"containerSpecDoc",
"{",
"Spec",
":",
"spec",
"}",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"append",
"(",
"prereqOps",
",",
"op",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"m",
".",
"mb",
".",
"db",
"(",
")",
".",
"Run",
"(",
"buildTxn",
")",
"\n",
"}"
] | // SetPodSpec sets the pod spec for the given application tag.
// An error will be returned if the specified application is not alive. | [
"SetPodSpec",
"sets",
"the",
"pod",
"spec",
"for",
"the",
"given",
"application",
"tag",
".",
"An",
"error",
"will",
"be",
"returned",
"if",
"the",
"specified",
"application",
"is",
"not",
"alive",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/podspec.go#L26-L62 |
5,209 | juju/juju | state/podspec.go | PodSpec | func (m *CAASModel) PodSpec(appTag names.ApplicationTag) (string, error) {
coll, cleanup := m.mb.db().GetCollection(podSpecsC)
defer cleanup()
var doc containerSpecDoc
if err := coll.FindId(applicationGlobalKey(appTag.Id())).One(&doc); err != nil {
if err == mgo.ErrNotFound {
return "", errors.NotFoundf(
"pod spec for %s",
names.ReadableString(appTag),
)
}
return "", errors.Trace(err)
}
return doc.Spec, nil
} | go | func (m *CAASModel) PodSpec(appTag names.ApplicationTag) (string, error) {
coll, cleanup := m.mb.db().GetCollection(podSpecsC)
defer cleanup()
var doc containerSpecDoc
if err := coll.FindId(applicationGlobalKey(appTag.Id())).One(&doc); err != nil {
if err == mgo.ErrNotFound {
return "", errors.NotFoundf(
"pod spec for %s",
names.ReadableString(appTag),
)
}
return "", errors.Trace(err)
}
return doc.Spec, nil
} | [
"func",
"(",
"m",
"*",
"CAASModel",
")",
"PodSpec",
"(",
"appTag",
"names",
".",
"ApplicationTag",
")",
"(",
"string",
",",
"error",
")",
"{",
"coll",
",",
"cleanup",
":=",
"m",
".",
"mb",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"podSpecsC",
")",
"\n",
"defer",
"cleanup",
"(",
")",
"\n",
"var",
"doc",
"containerSpecDoc",
"\n",
"if",
"err",
":=",
"coll",
".",
"FindId",
"(",
"applicationGlobalKey",
"(",
"appTag",
".",
"Id",
"(",
")",
")",
")",
".",
"One",
"(",
"&",
"doc",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"names",
".",
"ReadableString",
"(",
"appTag",
")",
",",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"doc",
".",
"Spec",
",",
"nil",
"\n",
"}"
] | // PodSpec returns the pod spec for the given application tag. | [
"PodSpec",
"returns",
"the",
"pod",
"spec",
"for",
"the",
"given",
"application",
"tag",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/podspec.go#L65-L79 |
5,210 | juju/juju | provider/vsphere/internal/vsphereclient/createvm.go | addNetworkDevice | func (c *Client) addNetworkDevice(
ctx context.Context,
spec *types.VirtualMachineConfigSpec,
network *mo.Network,
mac string,
dvportgroupConfig map[types.ManagedObjectReference]types.DVPortgroupConfigInfo,
) (*types.VirtualVmxnet3, error) {
var networkBacking types.BaseVirtualDeviceBackingInfo
if dvportgroupConfig, ok := dvportgroupConfig[network.Reference()]; !ok {
// It's not a distributed virtual portgroup, so return
// a backing info for a plain old network interface.
networkBacking = &types.VirtualEthernetCardNetworkBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: network.Name,
},
}
} else {
// It's a distributed virtual portgroup, so retrieve the details of
// the distributed virtual switch, and return a backing info for
// connecting the VM to the portgroup.
var dvs mo.DistributedVirtualSwitch
if err := c.client.RetrieveOne(
ctx, *dvportgroupConfig.DistributedVirtualSwitch, nil, &dvs,
); err != nil {
return nil, errors.Annotate(err, "retrieving distributed vSwitch details")
}
networkBacking = &types.VirtualEthernetCardDistributedVirtualPortBackingInfo{
Port: types.DistributedVirtualSwitchPortConnection{
SwitchUuid: dvs.Uuid,
PortgroupKey: dvportgroupConfig.Key,
},
}
}
var networkDevice types.VirtualVmxnet3
wakeOnLan := true
networkDevice.WakeOnLanEnabled = &wakeOnLan
networkDevice.Backing = networkBacking
if mac != "" {
if !VerifyMAC(mac) {
return nil, fmt.Errorf("Invalid MAC address: %q", mac)
}
networkDevice.AddressType = "Manual"
networkDevice.MacAddress = mac
}
networkDevice.Connectable = &types.VirtualDeviceConnectInfo{
StartConnected: true,
AllowGuestControl: true,
}
spec.DeviceChange = append(spec.DeviceChange, &types.VirtualDeviceConfigSpec{
Operation: types.VirtualDeviceConfigSpecOperationAdd,
Device: &networkDevice,
})
return &networkDevice, nil
} | go | func (c *Client) addNetworkDevice(
ctx context.Context,
spec *types.VirtualMachineConfigSpec,
network *mo.Network,
mac string,
dvportgroupConfig map[types.ManagedObjectReference]types.DVPortgroupConfigInfo,
) (*types.VirtualVmxnet3, error) {
var networkBacking types.BaseVirtualDeviceBackingInfo
if dvportgroupConfig, ok := dvportgroupConfig[network.Reference()]; !ok {
// It's not a distributed virtual portgroup, so return
// a backing info for a plain old network interface.
networkBacking = &types.VirtualEthernetCardNetworkBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: network.Name,
},
}
} else {
// It's a distributed virtual portgroup, so retrieve the details of
// the distributed virtual switch, and return a backing info for
// connecting the VM to the portgroup.
var dvs mo.DistributedVirtualSwitch
if err := c.client.RetrieveOne(
ctx, *dvportgroupConfig.DistributedVirtualSwitch, nil, &dvs,
); err != nil {
return nil, errors.Annotate(err, "retrieving distributed vSwitch details")
}
networkBacking = &types.VirtualEthernetCardDistributedVirtualPortBackingInfo{
Port: types.DistributedVirtualSwitchPortConnection{
SwitchUuid: dvs.Uuid,
PortgroupKey: dvportgroupConfig.Key,
},
}
}
var networkDevice types.VirtualVmxnet3
wakeOnLan := true
networkDevice.WakeOnLanEnabled = &wakeOnLan
networkDevice.Backing = networkBacking
if mac != "" {
if !VerifyMAC(mac) {
return nil, fmt.Errorf("Invalid MAC address: %q", mac)
}
networkDevice.AddressType = "Manual"
networkDevice.MacAddress = mac
}
networkDevice.Connectable = &types.VirtualDeviceConnectInfo{
StartConnected: true,
AllowGuestControl: true,
}
spec.DeviceChange = append(spec.DeviceChange, &types.VirtualDeviceConfigSpec{
Operation: types.VirtualDeviceConfigSpecOperationAdd,
Device: &networkDevice,
})
return &networkDevice, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"addNetworkDevice",
"(",
"ctx",
"context",
".",
"Context",
",",
"spec",
"*",
"types",
".",
"VirtualMachineConfigSpec",
",",
"network",
"*",
"mo",
".",
"Network",
",",
"mac",
"string",
",",
"dvportgroupConfig",
"map",
"[",
"types",
".",
"ManagedObjectReference",
"]",
"types",
".",
"DVPortgroupConfigInfo",
",",
")",
"(",
"*",
"types",
".",
"VirtualVmxnet3",
",",
"error",
")",
"{",
"var",
"networkBacking",
"types",
".",
"BaseVirtualDeviceBackingInfo",
"\n",
"if",
"dvportgroupConfig",
",",
"ok",
":=",
"dvportgroupConfig",
"[",
"network",
".",
"Reference",
"(",
")",
"]",
";",
"!",
"ok",
"{",
"// It's not a distributed virtual portgroup, so return",
"// a backing info for a plain old network interface.",
"networkBacking",
"=",
"&",
"types",
".",
"VirtualEthernetCardNetworkBackingInfo",
"{",
"VirtualDeviceDeviceBackingInfo",
":",
"types",
".",
"VirtualDeviceDeviceBackingInfo",
"{",
"DeviceName",
":",
"network",
".",
"Name",
",",
"}",
",",
"}",
"\n",
"}",
"else",
"{",
"// It's a distributed virtual portgroup, so retrieve the details of",
"// the distributed virtual switch, and return a backing info for",
"// connecting the VM to the portgroup.",
"var",
"dvs",
"mo",
".",
"DistributedVirtualSwitch",
"\n",
"if",
"err",
":=",
"c",
".",
"client",
".",
"RetrieveOne",
"(",
"ctx",
",",
"*",
"dvportgroupConfig",
".",
"DistributedVirtualSwitch",
",",
"nil",
",",
"&",
"dvs",
",",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"networkBacking",
"=",
"&",
"types",
".",
"VirtualEthernetCardDistributedVirtualPortBackingInfo",
"{",
"Port",
":",
"types",
".",
"DistributedVirtualSwitchPortConnection",
"{",
"SwitchUuid",
":",
"dvs",
".",
"Uuid",
",",
"PortgroupKey",
":",
"dvportgroupConfig",
".",
"Key",
",",
"}",
",",
"}",
"\n",
"}",
"\n\n",
"var",
"networkDevice",
"types",
".",
"VirtualVmxnet3",
"\n",
"wakeOnLan",
":=",
"true",
"\n",
"networkDevice",
".",
"WakeOnLanEnabled",
"=",
"&",
"wakeOnLan",
"\n",
"networkDevice",
".",
"Backing",
"=",
"networkBacking",
"\n",
"if",
"mac",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"VerifyMAC",
"(",
"mac",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"mac",
")",
"\n",
"}",
"\n",
"networkDevice",
".",
"AddressType",
"=",
"\"",
"\"",
"\n",
"networkDevice",
".",
"MacAddress",
"=",
"mac",
"\n",
"}",
"\n",
"networkDevice",
".",
"Connectable",
"=",
"&",
"types",
".",
"VirtualDeviceConnectInfo",
"{",
"StartConnected",
":",
"true",
",",
"AllowGuestControl",
":",
"true",
",",
"}",
"\n",
"spec",
".",
"DeviceChange",
"=",
"append",
"(",
"spec",
".",
"DeviceChange",
",",
"&",
"types",
".",
"VirtualDeviceConfigSpec",
"{",
"Operation",
":",
"types",
".",
"VirtualDeviceConfigSpecOperationAdd",
",",
"Device",
":",
"&",
"networkDevice",
",",
"}",
")",
"\n",
"return",
"&",
"networkDevice",
",",
"nil",
"\n",
"}"
] | // addNetworkDevice adds an entry to the VirtualMachineConfigSpec's
// DeviceChange list, to create a NIC device connecting the machine
// to the specified network. | [
"addNetworkDevice",
"adds",
"an",
"entry",
"to",
"the",
"VirtualMachineConfigSpec",
"s",
"DeviceChange",
"list",
"to",
"create",
"a",
"NIC",
"device",
"connecting",
"the",
"machine",
"to",
"the",
"specified",
"network",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/createvm.go#L428-L482 |
5,211 | juju/juju | provider/vsphere/internal/vsphereclient/createvm.go | VerifyMAC | func VerifyMAC(mac string) bool {
parts := strings.Split(mac, ":")
if len(parts) != 6 {
return false
}
if parts[0] != "00" || parts[1] != "50" || parts[2] != "56" {
return false
}
for i, part := range parts[3:] {
v, err := strconv.ParseUint(part, 16, 8)
if err != nil {
return false
}
if i == 0 && v > 0x3f {
// 4th byte must be <= 0x3f
return false
}
}
return true
} | go | func VerifyMAC(mac string) bool {
parts := strings.Split(mac, ":")
if len(parts) != 6 {
return false
}
if parts[0] != "00" || parts[1] != "50" || parts[2] != "56" {
return false
}
for i, part := range parts[3:] {
v, err := strconv.ParseUint(part, 16, 8)
if err != nil {
return false
}
if i == 0 && v > 0x3f {
// 4th byte must be <= 0x3f
return false
}
}
return true
} | [
"func",
"VerifyMAC",
"(",
"mac",
"string",
")",
"bool",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"mac",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"6",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"parts",
"[",
"0",
"]",
"!=",
"\"",
"\"",
"||",
"parts",
"[",
"1",
"]",
"!=",
"\"",
"\"",
"||",
"parts",
"[",
"2",
"]",
"!=",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
",",
"part",
":=",
"range",
"parts",
"[",
"3",
":",
"]",
"{",
"v",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"part",
",",
"16",
",",
"8",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"i",
"==",
"0",
"&&",
"v",
">",
"0x3f",
"{",
"// 4th byte must be <= 0x3f",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // VerifyMAC verifies that the MAC is valid for VMWare. | [
"VerifyMAC",
"verifies",
"that",
"the",
"MAC",
"is",
"valid",
"for",
"VMWare",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/createvm.go#L497-L516 |
5,212 | juju/juju | provider/vsphere/internal/vsphereclient/createvm.go | computeResourceNetworks | func (c *Client) computeResourceNetworks(
ctx context.Context,
computeResource *mo.ComputeResource,
) ([]mo.Network, map[types.ManagedObjectReference]types.DVPortgroupConfigInfo, error) {
refsByType := make(map[string][]types.ManagedObjectReference)
for _, network := range computeResource.Network {
refsByType[network.Type] = append(refsByType[network.Type], network.Reference())
}
var networks []mo.Network
if refs := refsByType["Network"]; len(refs) > 0 {
if err := c.client.Retrieve(ctx, refs, nil, &networks); err != nil {
return nil, nil, errors.Annotate(err, "retrieving network details")
}
}
var opaqueNetworks []mo.OpaqueNetwork
if refs := refsByType["OpaqueNetwork"]; len(refs) > 0 {
if err := c.client.Retrieve(ctx, refs, nil, &opaqueNetworks); err != nil {
return nil, nil, errors.Annotate(err, "retrieving opaque network details")
}
for _, on := range opaqueNetworks {
networks = append(networks, on.Network)
}
}
var dvportgroups []mo.DistributedVirtualPortgroup
var dvportgroupConfig map[types.ManagedObjectReference]types.DVPortgroupConfigInfo
if refs := refsByType["DistributedVirtualPortgroup"]; len(refs) > 0 {
if err := c.client.Retrieve(ctx, refs, nil, &dvportgroups); err != nil {
return nil, nil, errors.Annotate(err, "retrieving distributed virtual portgroup details")
}
dvportgroupConfig = make(map[types.ManagedObjectReference]types.DVPortgroupConfigInfo)
allnetworks := make([]mo.Network, len(dvportgroups)+len(networks))
for i, d := range dvportgroups {
allnetworks[i] = d.Network
dvportgroupConfig[allnetworks[i].Reference()] = d.Config
}
copy(allnetworks[len(dvportgroups):], networks)
networks = allnetworks
}
return networks, dvportgroupConfig, nil
} | go | func (c *Client) computeResourceNetworks(
ctx context.Context,
computeResource *mo.ComputeResource,
) ([]mo.Network, map[types.ManagedObjectReference]types.DVPortgroupConfigInfo, error) {
refsByType := make(map[string][]types.ManagedObjectReference)
for _, network := range computeResource.Network {
refsByType[network.Type] = append(refsByType[network.Type], network.Reference())
}
var networks []mo.Network
if refs := refsByType["Network"]; len(refs) > 0 {
if err := c.client.Retrieve(ctx, refs, nil, &networks); err != nil {
return nil, nil, errors.Annotate(err, "retrieving network details")
}
}
var opaqueNetworks []mo.OpaqueNetwork
if refs := refsByType["OpaqueNetwork"]; len(refs) > 0 {
if err := c.client.Retrieve(ctx, refs, nil, &opaqueNetworks); err != nil {
return nil, nil, errors.Annotate(err, "retrieving opaque network details")
}
for _, on := range opaqueNetworks {
networks = append(networks, on.Network)
}
}
var dvportgroups []mo.DistributedVirtualPortgroup
var dvportgroupConfig map[types.ManagedObjectReference]types.DVPortgroupConfigInfo
if refs := refsByType["DistributedVirtualPortgroup"]; len(refs) > 0 {
if err := c.client.Retrieve(ctx, refs, nil, &dvportgroups); err != nil {
return nil, nil, errors.Annotate(err, "retrieving distributed virtual portgroup details")
}
dvportgroupConfig = make(map[types.ManagedObjectReference]types.DVPortgroupConfigInfo)
allnetworks := make([]mo.Network, len(dvportgroups)+len(networks))
for i, d := range dvportgroups {
allnetworks[i] = d.Network
dvportgroupConfig[allnetworks[i].Reference()] = d.Config
}
copy(allnetworks[len(dvportgroups):], networks)
networks = allnetworks
}
return networks, dvportgroupConfig, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"computeResourceNetworks",
"(",
"ctx",
"context",
".",
"Context",
",",
"computeResource",
"*",
"mo",
".",
"ComputeResource",
",",
")",
"(",
"[",
"]",
"mo",
".",
"Network",
",",
"map",
"[",
"types",
".",
"ManagedObjectReference",
"]",
"types",
".",
"DVPortgroupConfigInfo",
",",
"error",
")",
"{",
"refsByType",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"types",
".",
"ManagedObjectReference",
")",
"\n",
"for",
"_",
",",
"network",
":=",
"range",
"computeResource",
".",
"Network",
"{",
"refsByType",
"[",
"network",
".",
"Type",
"]",
"=",
"append",
"(",
"refsByType",
"[",
"network",
".",
"Type",
"]",
",",
"network",
".",
"Reference",
"(",
")",
")",
"\n",
"}",
"\n",
"var",
"networks",
"[",
"]",
"mo",
".",
"Network",
"\n",
"if",
"refs",
":=",
"refsByType",
"[",
"\"",
"\"",
"]",
";",
"len",
"(",
"refs",
")",
">",
"0",
"{",
"if",
"err",
":=",
"c",
".",
"client",
".",
"Retrieve",
"(",
"ctx",
",",
"refs",
",",
"nil",
",",
"&",
"networks",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"opaqueNetworks",
"[",
"]",
"mo",
".",
"OpaqueNetwork",
"\n",
"if",
"refs",
":=",
"refsByType",
"[",
"\"",
"\"",
"]",
";",
"len",
"(",
"refs",
")",
">",
"0",
"{",
"if",
"err",
":=",
"c",
".",
"client",
".",
"Retrieve",
"(",
"ctx",
",",
"refs",
",",
"nil",
",",
"&",
"opaqueNetworks",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"on",
":=",
"range",
"opaqueNetworks",
"{",
"networks",
"=",
"append",
"(",
"networks",
",",
"on",
".",
"Network",
")",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"dvportgroups",
"[",
"]",
"mo",
".",
"DistributedVirtualPortgroup",
"\n",
"var",
"dvportgroupConfig",
"map",
"[",
"types",
".",
"ManagedObjectReference",
"]",
"types",
".",
"DVPortgroupConfigInfo",
"\n",
"if",
"refs",
":=",
"refsByType",
"[",
"\"",
"\"",
"]",
";",
"len",
"(",
"refs",
")",
">",
"0",
"{",
"if",
"err",
":=",
"c",
".",
"client",
".",
"Retrieve",
"(",
"ctx",
",",
"refs",
",",
"nil",
",",
"&",
"dvportgroups",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"dvportgroupConfig",
"=",
"make",
"(",
"map",
"[",
"types",
".",
"ManagedObjectReference",
"]",
"types",
".",
"DVPortgroupConfigInfo",
")",
"\n",
"allnetworks",
":=",
"make",
"(",
"[",
"]",
"mo",
".",
"Network",
",",
"len",
"(",
"dvportgroups",
")",
"+",
"len",
"(",
"networks",
")",
")",
"\n",
"for",
"i",
",",
"d",
":=",
"range",
"dvportgroups",
"{",
"allnetworks",
"[",
"i",
"]",
"=",
"d",
".",
"Network",
"\n",
"dvportgroupConfig",
"[",
"allnetworks",
"[",
"i",
"]",
".",
"Reference",
"(",
")",
"]",
"=",
"d",
".",
"Config",
"\n",
"}",
"\n",
"copy",
"(",
"allnetworks",
"[",
"len",
"(",
"dvportgroups",
")",
":",
"]",
",",
"networks",
")",
"\n",
"networks",
"=",
"allnetworks",
"\n",
"}",
"\n",
"return",
"networks",
",",
"dvportgroupConfig",
",",
"nil",
"\n",
"}"
] | // computeResourceNetworks returns the networks available to the compute
// resource, and the config info for the distributed virtual portgroup
// networks. Networks are returned with the distributed virtual portgroups
// first, then standard switch networks, and then finally opaque networks. | [
"computeResourceNetworks",
"returns",
"the",
"networks",
"available",
"to",
"the",
"compute",
"resource",
"and",
"the",
"config",
"info",
"for",
"the",
"distributed",
"virtual",
"portgroup",
"networks",
".",
"Networks",
"are",
"returned",
"with",
"the",
"distributed",
"virtual",
"portgroups",
"first",
"then",
"standard",
"switch",
"networks",
"and",
"then",
"finally",
"opaque",
"networks",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/createvm.go#L531-L570 |
5,213 | juju/juju | cmd/juju/machine/show.go | Init | func (c *showMachineCommand) Init(args []string) error {
c.machineIds = args
return nil
} | go | func (c *showMachineCommand) Init(args []string) error {
c.machineIds = args
return nil
} | [
"func",
"(",
"c",
"*",
"showMachineCommand",
")",
"Init",
"(",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"c",
".",
"machineIds",
"=",
"args",
"\n",
"return",
"nil",
"\n",
"}"
] | // Init captures machineId's to show from CL args. | [
"Init",
"captures",
"machineId",
"s",
"to",
"show",
"from",
"CL",
"args",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/machine/show.go#L52-L55 |
5,214 | juju/juju | service/discovery.go | DiscoverService | func DiscoverService(name string, conf common.Conf) (Service, error) {
hostSeries := series.MustHostSeries()
initName, err := discoverInitSystem(hostSeries)
if err != nil {
return nil, errors.Trace(err)
}
service, err := newService(name, conf, initName, hostSeries)
if err != nil {
return nil, errors.Trace(err)
}
return service, nil
} | go | func DiscoverService(name string, conf common.Conf) (Service, error) {
hostSeries := series.MustHostSeries()
initName, err := discoverInitSystem(hostSeries)
if err != nil {
return nil, errors.Trace(err)
}
service, err := newService(name, conf, initName, hostSeries)
if err != nil {
return nil, errors.Trace(err)
}
return service, nil
} | [
"func",
"DiscoverService",
"(",
"name",
"string",
",",
"conf",
"common",
".",
"Conf",
")",
"(",
"Service",
",",
"error",
")",
"{",
"hostSeries",
":=",
"series",
".",
"MustHostSeries",
"(",
")",
"\n",
"initName",
",",
"err",
":=",
"discoverInitSystem",
"(",
"hostSeries",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"service",
",",
"err",
":=",
"newService",
"(",
"name",
",",
"conf",
",",
"initName",
",",
"hostSeries",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"service",
",",
"nil",
"\n",
"}"
] | // DiscoverService returns an interface to a service appropriate
// for the current system | [
"DiscoverService",
"returns",
"an",
"interface",
"to",
"a",
"service",
"appropriate",
"for",
"the",
"current",
"system"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/discovery.go#L25-L38 |
5,215 | juju/juju | service/discovery.go | VersionInitSystem | func VersionInitSystem(series string) (string, error) {
initName, err := versionInitSystem(series)
if err != nil {
return "", errors.Trace(err)
}
logger.Debugf("discovered init system %q from series %q", initName, series)
return initName, nil
} | go | func VersionInitSystem(series string) (string, error) {
initName, err := versionInitSystem(series)
if err != nil {
return "", errors.Trace(err)
}
logger.Debugf("discovered init system %q from series %q", initName, series)
return initName, nil
} | [
"func",
"VersionInitSystem",
"(",
"series",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"initName",
",",
"err",
":=",
"versionInitSystem",
"(",
"series",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"initName",
",",
"series",
")",
"\n",
"return",
"initName",
",",
"nil",
"\n",
"}"
] | // VersionInitSystem returns an init system name based on the provided
// series. If one cannot be identified a NotFound error is returned. | [
"VersionInitSystem",
"returns",
"an",
"init",
"system",
"name",
"based",
"on",
"the",
"provided",
"series",
".",
"If",
"one",
"cannot",
"be",
"identified",
"a",
"NotFound",
"error",
"is",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/discovery.go#L59-L66 |
5,216 | juju/juju | service/discovery.go | DiscoverInitSystemScript | func DiscoverInitSystemScript() string {
renderer := shell.BashRenderer{}
tests := []string{
discoverSystemd,
discoverUpstart,
"exit 1",
}
data := renderer.RenderScript(tests)
return string(data)
} | go | func DiscoverInitSystemScript() string {
renderer := shell.BashRenderer{}
tests := []string{
discoverSystemd,
discoverUpstart,
"exit 1",
}
data := renderer.RenderScript(tests)
return string(data)
} | [
"func",
"DiscoverInitSystemScript",
"(",
")",
"string",
"{",
"renderer",
":=",
"shell",
".",
"BashRenderer",
"{",
"}",
"\n",
"tests",
":=",
"[",
"]",
"string",
"{",
"discoverSystemd",
",",
"discoverUpstart",
",",
"\"",
"\"",
",",
"}",
"\n",
"data",
":=",
"renderer",
".",
"RenderScript",
"(",
"tests",
")",
"\n",
"return",
"string",
"(",
"data",
")",
"\n",
"}"
] | // DiscoverInitSystemScript returns the shell script to use when
// discovering the local init system. The script is quite specific to
// bash, so it includes an explicit bash shbang. | [
"DiscoverInitSystemScript",
"returns",
"the",
"shell",
"script",
"to",
"use",
"when",
"discovering",
"the",
"local",
"init",
"system",
".",
"The",
"script",
"is",
"quite",
"specific",
"to",
"bash",
"so",
"it",
"includes",
"an",
"explicit",
"bash",
"shbang",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/discovery.go#L131-L140 |
5,217 | juju/juju | service/discovery.go | newShellSelectCommand | func newShellSelectCommand(envVarName, defaultCase string, handler func(string) (string, bool)) string {
var cases []string
const shellCaseStatement = `
case "$%s" in
%s
*)
%s
;;
esac`
for _, initSystem := range linuxInitSystems {
cmd, ok := handler(initSystem)
if !ok {
continue
}
cases = append(cases, initSystem+")", " "+cmd, " ;;")
}
if len(cases) == 0 {
return ""
}
return fmt.Sprintf(shellCaseStatement[1:], envVarName, strings.Join(cases, "\n"), defaultCase)
} | go | func newShellSelectCommand(envVarName, defaultCase string, handler func(string) (string, bool)) string {
var cases []string
const shellCaseStatement = `
case "$%s" in
%s
*)
%s
;;
esac`
for _, initSystem := range linuxInitSystems {
cmd, ok := handler(initSystem)
if !ok {
continue
}
cases = append(cases, initSystem+")", " "+cmd, " ;;")
}
if len(cases) == 0 {
return ""
}
return fmt.Sprintf(shellCaseStatement[1:], envVarName, strings.Join(cases, "\n"), defaultCase)
} | [
"func",
"newShellSelectCommand",
"(",
"envVarName",
",",
"defaultCase",
"string",
",",
"handler",
"func",
"(",
"string",
")",
"(",
"string",
",",
"bool",
")",
")",
"string",
"{",
"var",
"cases",
"[",
"]",
"string",
"\n\n",
"const",
"shellCaseStatement",
"=",
"`\ncase \"$%s\" in\n%s\n*)\n %s\n ;;\nesac`",
"\n\n",
"for",
"_",
",",
"initSystem",
":=",
"range",
"linuxInitSystems",
"{",
"cmd",
",",
"ok",
":=",
"handler",
"(",
"initSystem",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"cases",
"=",
"append",
"(",
"cases",
",",
"initSystem",
"+",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"cmd",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"cases",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"shellCaseStatement",
"[",
"1",
":",
"]",
",",
"envVarName",
",",
"strings",
".",
"Join",
"(",
"cases",
",",
"\"",
"\\n",
"\"",
")",
",",
"defaultCase",
")",
"\n",
"}"
] | // newShellSelectCommand creates a bash case statement with clause for
// each of the linux init systems. The body of each clause comes from
// calling the provided handler with the init system name. If the
// handler does not support the args then it returns a false "ok" value. | [
"newShellSelectCommand",
"creates",
"a",
"bash",
"case",
"statement",
"with",
"clause",
"for",
"each",
"of",
"the",
"linux",
"init",
"systems",
".",
"The",
"body",
"of",
"each",
"clause",
"comes",
"from",
"calling",
"the",
"provided",
"handler",
"with",
"the",
"init",
"system",
"name",
".",
"If",
"the",
"handler",
"does",
"not",
"support",
"the",
"args",
"then",
"it",
"returns",
"a",
"false",
"ok",
"value",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/discovery.go#L146-L169 |
5,218 | juju/juju | worker/containerbroker/mocks/state_mock.go | ContainerManagerConfig | func (m *MockState) ContainerManagerConfig(arg0 params.ContainerManagerConfigParams) (params.ContainerManagerConfig, error) {
ret := m.ctrl.Call(m, "ContainerManagerConfig", arg0)
ret0, _ := ret[0].(params.ContainerManagerConfig)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockState) ContainerManagerConfig(arg0 params.ContainerManagerConfigParams) (params.ContainerManagerConfig, error) {
ret := m.ctrl.Call(m, "ContainerManagerConfig", arg0)
ret0, _ := ret[0].(params.ContainerManagerConfig)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockState",
")",
"ContainerManagerConfig",
"(",
"arg0",
"params",
".",
"ContainerManagerConfigParams",
")",
"(",
"params",
".",
"ContainerManagerConfig",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"params",
".",
"ContainerManagerConfig",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // ContainerManagerConfig mocks base method | [
"ContainerManagerConfig",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/containerbroker/mocks/state_mock.go#L53-L58 |
5,219 | juju/juju | worker/containerbroker/mocks/state_mock.go | HostChangesForContainer | func (mr *MockStateMockRecorder) HostChangesForContainer(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HostChangesForContainer", reflect.TypeOf((*MockState)(nil).HostChangesForContainer), arg0)
} | go | func (mr *MockStateMockRecorder) HostChangesForContainer(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HostChangesForContainer", reflect.TypeOf((*MockState)(nil).HostChangesForContainer), arg0)
} | [
"func",
"(",
"mr",
"*",
"MockStateMockRecorder",
")",
"HostChangesForContainer",
"(",
"arg0",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockState",
")",
"(",
"nil",
")",
".",
"HostChangesForContainer",
")",
",",
"arg0",
")",
"\n",
"}"
] | // HostChangesForContainer indicates an expected call of HostChangesForContainer | [
"HostChangesForContainer",
"indicates",
"an",
"expected",
"call",
"of",
"HostChangesForContainer"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/containerbroker/mocks/state_mock.go#L101-L103 |
5,220 | juju/juju | worker/containerbroker/mocks/state_mock.go | Machines | func (m *MockState) Machines(arg0 ...names_v2.MachineTag) ([]provisioner.MachineResult, error) {
varargs := []interface{}{}
for _, a := range arg0 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Machines", varargs...)
ret0, _ := ret[0].([]provisioner.MachineResult)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockState) Machines(arg0 ...names_v2.MachineTag) ([]provisioner.MachineResult, error) {
varargs := []interface{}{}
for _, a := range arg0 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Machines", varargs...)
ret0, _ := ret[0].([]provisioner.MachineResult)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockState",
")",
"Machines",
"(",
"arg0",
"...",
"names_v2",
".",
"MachineTag",
")",
"(",
"[",
"]",
"provisioner",
".",
"MachineResult",
",",
"error",
")",
"{",
"varargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"arg0",
"{",
"varargs",
"=",
"append",
"(",
"varargs",
",",
"a",
")",
"\n",
"}",
"\n",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"varargs",
"...",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"[",
"]",
"provisioner",
".",
"MachineResult",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // Machines mocks base method | [
"Machines",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/containerbroker/mocks/state_mock.go#L106-L115 |
5,221 | juju/juju | cmd/juju/backups/download.go | ResolveFilename | func (c *downloadCommand) ResolveFilename() string {
filename := c.Filename
if filename == "" {
filename = backups.FilenamePrefix + c.ID + ".tar.gz"
}
return filename
} | go | func (c *downloadCommand) ResolveFilename() string {
filename := c.Filename
if filename == "" {
filename = backups.FilenamePrefix + c.ID + ".tar.gz"
}
return filename
} | [
"func",
"(",
"c",
"*",
"downloadCommand",
")",
"ResolveFilename",
"(",
")",
"string",
"{",
"filename",
":=",
"c",
".",
"Filename",
"\n",
"if",
"filename",
"==",
"\"",
"\"",
"{",
"filename",
"=",
"backups",
".",
"FilenamePrefix",
"+",
"c",
".",
"ID",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"filename",
"\n",
"}"
] | // ResolveFilename returns the filename used by the command. | [
"ResolveFilename",
"returns",
"the",
"filename",
"used",
"by",
"the",
"command",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/backups/download.go#L113-L119 |
5,222 | juju/juju | state/backups/metadata.go | UnknownOrigin | func UnknownOrigin() Origin {
return Origin{
Model: UnknownString,
Machine: UnknownString,
Hostname: UnknownString,
Version: UnknownVersion,
}
} | go | func UnknownOrigin() Origin {
return Origin{
Model: UnknownString,
Machine: UnknownString,
Hostname: UnknownString,
Version: UnknownVersion,
}
} | [
"func",
"UnknownOrigin",
"(",
")",
"Origin",
"{",
"return",
"Origin",
"{",
"Model",
":",
"UnknownString",
",",
"Machine",
":",
"UnknownString",
",",
"Hostname",
":",
"UnknownString",
",",
"Version",
":",
"UnknownVersion",
",",
"}",
"\n",
"}"
] | // UnknownOrigin returns a new backups origin with unknown values. | [
"UnknownOrigin",
"returns",
"a",
"new",
"backups",
"origin",
"with",
"unknown",
"values",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/metadata.go#L46-L53 |
5,223 | juju/juju | state/backups/metadata.go | NewMetadata | func NewMetadata() *Metadata {
return &Metadata{
FileMetadata: filestorage.NewMetadata(),
// TODO(fwereade): 2016-03-17 lp:1558657
Started: time.Now().UTC(),
Origin: Origin{
Version: jujuversion.Current,
},
}
} | go | func NewMetadata() *Metadata {
return &Metadata{
FileMetadata: filestorage.NewMetadata(),
// TODO(fwereade): 2016-03-17 lp:1558657
Started: time.Now().UTC(),
Origin: Origin{
Version: jujuversion.Current,
},
}
} | [
"func",
"NewMetadata",
"(",
")",
"*",
"Metadata",
"{",
"return",
"&",
"Metadata",
"{",
"FileMetadata",
":",
"filestorage",
".",
"NewMetadata",
"(",
")",
",",
"// TODO(fwereade): 2016-03-17 lp:1558657",
"Started",
":",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
",",
"Origin",
":",
"Origin",
"{",
"Version",
":",
"jujuversion",
".",
"Current",
",",
"}",
",",
"}",
"\n",
"}"
] | // NewMetadata returns a new Metadata for a state backup archive. Only
// the start time and the version are set. | [
"NewMetadata",
"returns",
"a",
"new",
"Metadata",
"for",
"a",
"state",
"backup",
"archive",
".",
"Only",
"the",
"start",
"time",
"and",
"the",
"version",
"are",
"set",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/metadata.go#L87-L96 |
5,224 | juju/juju | state/backups/metadata.go | NewMetadataState | func NewMetadataState(db DB, machine, series string) (*Metadata, error) {
// hostname could be derived from the model...
hostname, err := os.Hostname()
if err != nil {
// If os.Hostname() is not working, something is woefully wrong.
// Run for the hills.
return nil, errors.Annotate(err, "could not get hostname (system unstable?)")
}
meta := NewMetadata()
meta.Origin.Model = db.ModelTag().Id()
meta.Origin.Machine = machine
meta.Origin.Hostname = hostname
meta.Origin.Series = series
si, err := db.StateServingInfo()
if err != nil {
return nil, errors.Annotate(err, "could not get server secrets")
}
controllerCfg, err := db.ControllerConfig()
if err != nil {
return nil, errors.Annotate(err, "could not get controller config")
}
meta.CACert, _ = controllerCfg.CACert()
meta.CAPrivateKey = si.CAPrivateKey
return meta, nil
} | go | func NewMetadataState(db DB, machine, series string) (*Metadata, error) {
// hostname could be derived from the model...
hostname, err := os.Hostname()
if err != nil {
// If os.Hostname() is not working, something is woefully wrong.
// Run for the hills.
return nil, errors.Annotate(err, "could not get hostname (system unstable?)")
}
meta := NewMetadata()
meta.Origin.Model = db.ModelTag().Id()
meta.Origin.Machine = machine
meta.Origin.Hostname = hostname
meta.Origin.Series = series
si, err := db.StateServingInfo()
if err != nil {
return nil, errors.Annotate(err, "could not get server secrets")
}
controllerCfg, err := db.ControllerConfig()
if err != nil {
return nil, errors.Annotate(err, "could not get controller config")
}
meta.CACert, _ = controllerCfg.CACert()
meta.CAPrivateKey = si.CAPrivateKey
return meta, nil
} | [
"func",
"NewMetadataState",
"(",
"db",
"DB",
",",
"machine",
",",
"series",
"string",
")",
"(",
"*",
"Metadata",
",",
"error",
")",
"{",
"// hostname could be derived from the model...",
"hostname",
",",
"err",
":=",
"os",
".",
"Hostname",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// If os.Hostname() is not working, something is woefully wrong.",
"// Run for the hills.",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"meta",
":=",
"NewMetadata",
"(",
")",
"\n",
"meta",
".",
"Origin",
".",
"Model",
"=",
"db",
".",
"ModelTag",
"(",
")",
".",
"Id",
"(",
")",
"\n",
"meta",
".",
"Origin",
".",
"Machine",
"=",
"machine",
"\n",
"meta",
".",
"Origin",
".",
"Hostname",
"=",
"hostname",
"\n",
"meta",
".",
"Origin",
".",
"Series",
"=",
"series",
"\n\n",
"si",
",",
"err",
":=",
"db",
".",
"StateServingInfo",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"controllerCfg",
",",
"err",
":=",
"db",
".",
"ControllerConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"meta",
".",
"CACert",
",",
"_",
"=",
"controllerCfg",
".",
"CACert",
"(",
")",
"\n",
"meta",
".",
"CAPrivateKey",
"=",
"si",
".",
"CAPrivateKey",
"\n",
"return",
"meta",
",",
"nil",
"\n",
"}"
] | // NewMetadataState composes a new backup metadata with its origin
// values set. The model UUID comes from state. The hostname is
// retrieved from the OS. | [
"NewMetadataState",
"composes",
"a",
"new",
"backup",
"metadata",
"with",
"its",
"origin",
"values",
"set",
".",
"The",
"model",
"UUID",
"comes",
"from",
"state",
".",
"The",
"hostname",
"is",
"retrieved",
"from",
"the",
"OS",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/metadata.go#L101-L127 |
5,225 | juju/juju | state/backups/metadata.go | MarkComplete | func (m *Metadata) MarkComplete(size int64, checksum string) error {
if size == 0 {
return errors.New("missing size")
}
if checksum == "" {
return errors.New("missing checksum")
}
format := checksumFormat
// TODO(fwereade): 2016-03-17 lp:1558657
finished := time.Now().UTC()
if err := m.SetFileInfo(size, checksum, format); err != nil {
return errors.Annotate(err, "unexpected failure")
}
m.Finished = &finished
return nil
} | go | func (m *Metadata) MarkComplete(size int64, checksum string) error {
if size == 0 {
return errors.New("missing size")
}
if checksum == "" {
return errors.New("missing checksum")
}
format := checksumFormat
// TODO(fwereade): 2016-03-17 lp:1558657
finished := time.Now().UTC()
if err := m.SetFileInfo(size, checksum, format); err != nil {
return errors.Annotate(err, "unexpected failure")
}
m.Finished = &finished
return nil
} | [
"func",
"(",
"m",
"*",
"Metadata",
")",
"MarkComplete",
"(",
"size",
"int64",
",",
"checksum",
"string",
")",
"error",
"{",
"if",
"size",
"==",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"checksum",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"format",
":=",
"checksumFormat",
"\n",
"// TODO(fwereade): 2016-03-17 lp:1558657",
"finished",
":=",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
"\n\n",
"if",
"err",
":=",
"m",
".",
"SetFileInfo",
"(",
"size",
",",
"checksum",
",",
"format",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"m",
".",
"Finished",
"=",
"&",
"finished",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // MarkComplete populates the remaining metadata values. The default
// checksum format is used. | [
"MarkComplete",
"populates",
"the",
"remaining",
"metadata",
"values",
".",
"The",
"default",
"checksum",
"format",
"is",
"used",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/metadata.go#L131-L148 |
5,226 | juju/juju | state/backups/metadata.go | NewMetadataJSONReader | func NewMetadataJSONReader(in io.Reader) (*Metadata, error) {
var flat flatMetadata
if err := json.NewDecoder(in).Decode(&flat); err != nil {
return nil, errors.Trace(err)
}
meta := NewMetadata()
meta.SetID(flat.ID)
err := meta.SetFileInfo(flat.Size, flat.Checksum, flat.ChecksumFormat)
if err != nil {
return nil, errors.Trace(err)
}
if !flat.Stored.IsZero() {
meta.SetStored(&flat.Stored)
}
meta.Started = flat.Started
if !flat.Finished.IsZero() {
meta.Finished = &flat.Finished
}
meta.Notes = flat.Notes
meta.Origin = Origin{
Model: flat.Environment,
Machine: flat.Machine,
Hostname: flat.Hostname,
Version: flat.Version,
Series: flat.Series,
}
// TODO(wallyworld) - put these in a separate file.
meta.CACert = flat.CACert
meta.CAPrivateKey = flat.CAPrivateKey
return meta, nil
} | go | func NewMetadataJSONReader(in io.Reader) (*Metadata, error) {
var flat flatMetadata
if err := json.NewDecoder(in).Decode(&flat); err != nil {
return nil, errors.Trace(err)
}
meta := NewMetadata()
meta.SetID(flat.ID)
err := meta.SetFileInfo(flat.Size, flat.Checksum, flat.ChecksumFormat)
if err != nil {
return nil, errors.Trace(err)
}
if !flat.Stored.IsZero() {
meta.SetStored(&flat.Stored)
}
meta.Started = flat.Started
if !flat.Finished.IsZero() {
meta.Finished = &flat.Finished
}
meta.Notes = flat.Notes
meta.Origin = Origin{
Model: flat.Environment,
Machine: flat.Machine,
Hostname: flat.Hostname,
Version: flat.Version,
Series: flat.Series,
}
// TODO(wallyworld) - put these in a separate file.
meta.CACert = flat.CACert
meta.CAPrivateKey = flat.CAPrivateKey
return meta, nil
} | [
"func",
"NewMetadataJSONReader",
"(",
"in",
"io",
".",
"Reader",
")",
"(",
"*",
"Metadata",
",",
"error",
")",
"{",
"var",
"flat",
"flatMetadata",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"in",
")",
".",
"Decode",
"(",
"&",
"flat",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"meta",
":=",
"NewMetadata",
"(",
")",
"\n",
"meta",
".",
"SetID",
"(",
"flat",
".",
"ID",
")",
"\n\n",
"err",
":=",
"meta",
".",
"SetFileInfo",
"(",
"flat",
".",
"Size",
",",
"flat",
".",
"Checksum",
",",
"flat",
".",
"ChecksumFormat",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"flat",
".",
"Stored",
".",
"IsZero",
"(",
")",
"{",
"meta",
".",
"SetStored",
"(",
"&",
"flat",
".",
"Stored",
")",
"\n",
"}",
"\n\n",
"meta",
".",
"Started",
"=",
"flat",
".",
"Started",
"\n",
"if",
"!",
"flat",
".",
"Finished",
".",
"IsZero",
"(",
")",
"{",
"meta",
".",
"Finished",
"=",
"&",
"flat",
".",
"Finished",
"\n",
"}",
"\n",
"meta",
".",
"Notes",
"=",
"flat",
".",
"Notes",
"\n",
"meta",
".",
"Origin",
"=",
"Origin",
"{",
"Model",
":",
"flat",
".",
"Environment",
",",
"Machine",
":",
"flat",
".",
"Machine",
",",
"Hostname",
":",
"flat",
".",
"Hostname",
",",
"Version",
":",
"flat",
".",
"Version",
",",
"Series",
":",
"flat",
".",
"Series",
",",
"}",
"\n\n",
"// TODO(wallyworld) - put these in a separate file.",
"meta",
".",
"CACert",
"=",
"flat",
".",
"CACert",
"\n",
"meta",
".",
"CAPrivateKey",
"=",
"flat",
".",
"CAPrivateKey",
"\n\n",
"return",
"meta",
",",
"nil",
"\n",
"}"
] | // NewMetadataJSONReader extracts a new metadata from the JSON file. | [
"NewMetadataJSONReader",
"extracts",
"a",
"new",
"metadata",
"from",
"the",
"JSON",
"file",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/metadata.go#L214-L250 |
5,227 | juju/juju | state/backups/metadata.go | BuildMetadata | func BuildMetadata(file *os.File) (*Metadata, error) {
// Extract the file size.
fi, err := file.Stat()
if err != nil {
return nil, errors.Trace(err)
}
size := fi.Size()
// Extract the timestamp.
timestamp := fileTimestamp(fi)
// Get the checksum.
hasher := sha1.New()
_, err = io.Copy(hasher, file)
if err != nil {
return nil, errors.Trace(err)
}
rawsum := hasher.Sum(nil)
checksum := base64.StdEncoding.EncodeToString(rawsum)
// Build the metadata.
meta := NewMetadata()
meta.Started = time.Time{}
meta.Origin = UnknownOrigin()
err = meta.MarkComplete(size, checksum)
if err != nil {
return nil, errors.Trace(err)
}
meta.Finished = ×tamp
return meta, nil
} | go | func BuildMetadata(file *os.File) (*Metadata, error) {
// Extract the file size.
fi, err := file.Stat()
if err != nil {
return nil, errors.Trace(err)
}
size := fi.Size()
// Extract the timestamp.
timestamp := fileTimestamp(fi)
// Get the checksum.
hasher := sha1.New()
_, err = io.Copy(hasher, file)
if err != nil {
return nil, errors.Trace(err)
}
rawsum := hasher.Sum(nil)
checksum := base64.StdEncoding.EncodeToString(rawsum)
// Build the metadata.
meta := NewMetadata()
meta.Started = time.Time{}
meta.Origin = UnknownOrigin()
err = meta.MarkComplete(size, checksum)
if err != nil {
return nil, errors.Trace(err)
}
meta.Finished = ×tamp
return meta, nil
} | [
"func",
"BuildMetadata",
"(",
"file",
"*",
"os",
".",
"File",
")",
"(",
"*",
"Metadata",
",",
"error",
")",
"{",
"// Extract the file size.",
"fi",
",",
"err",
":=",
"file",
".",
"Stat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"size",
":=",
"fi",
".",
"Size",
"(",
")",
"\n\n",
"// Extract the timestamp.",
"timestamp",
":=",
"fileTimestamp",
"(",
"fi",
")",
"\n\n",
"// Get the checksum.",
"hasher",
":=",
"sha1",
".",
"New",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"hasher",
",",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"rawsum",
":=",
"hasher",
".",
"Sum",
"(",
"nil",
")",
"\n",
"checksum",
":=",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"rawsum",
")",
"\n\n",
"// Build the metadata.",
"meta",
":=",
"NewMetadata",
"(",
")",
"\n",
"meta",
".",
"Started",
"=",
"time",
".",
"Time",
"{",
"}",
"\n",
"meta",
".",
"Origin",
"=",
"UnknownOrigin",
"(",
")",
"\n",
"err",
"=",
"meta",
".",
"MarkComplete",
"(",
"size",
",",
"checksum",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"meta",
".",
"Finished",
"=",
"&",
"timestamp",
"\n",
"return",
"meta",
",",
"nil",
"\n",
"}"
] | // BuildMetadata generates the metadata for a backup archive file. | [
"BuildMetadata",
"generates",
"the",
"metadata",
"for",
"a",
"backup",
"archive",
"file",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/metadata.go#L262-L293 |
5,228 | juju/juju | state/externalcontroller.go | ControllerInfo | func (rc *externalController) ControllerInfo() crossmodel.ControllerInfo {
return crossmodel.ControllerInfo{
ControllerTag: names.NewControllerTag(rc.doc.Id),
Alias: rc.doc.Alias,
Addrs: rc.doc.Addrs,
CACert: rc.doc.CACert,
}
} | go | func (rc *externalController) ControllerInfo() crossmodel.ControllerInfo {
return crossmodel.ControllerInfo{
ControllerTag: names.NewControllerTag(rc.doc.Id),
Alias: rc.doc.Alias,
Addrs: rc.doc.Addrs,
CACert: rc.doc.CACert,
}
} | [
"func",
"(",
"rc",
"*",
"externalController",
")",
"ControllerInfo",
"(",
")",
"crossmodel",
".",
"ControllerInfo",
"{",
"return",
"crossmodel",
".",
"ControllerInfo",
"{",
"ControllerTag",
":",
"names",
".",
"NewControllerTag",
"(",
"rc",
".",
"doc",
".",
"Id",
")",
",",
"Alias",
":",
"rc",
".",
"doc",
".",
"Alias",
",",
"Addrs",
":",
"rc",
".",
"doc",
".",
"Addrs",
",",
"CACert",
":",
"rc",
".",
"doc",
".",
"CACert",
",",
"}",
"\n",
"}"
] | // ControllerInfo implements ExternalController. | [
"ControllerInfo",
"implements",
"ExternalController",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/externalcontroller.go#L60-L67 |
5,229 | juju/juju | state/externalcontroller.go | Save | func (ec *externalControllers) Save(controller crossmodel.ControllerInfo, modelUUIDs ...string) (ExternalController, error) {
if err := controller.Validate(); err != nil {
return nil, errors.Trace(err)
}
doc := externalControllerDoc{
Id: controller.ControllerTag.Id(),
Alias: controller.Alias,
Addrs: controller.Addrs,
CACert: controller.CACert,
}
buildTxn := func(int) ([]txn.Op, error) {
model, err := ec.st.Model()
if err != nil {
return nil, errors.Annotate(err, "failed to load model")
}
if err := checkModelActive(ec.st); err != nil {
return nil, errors.Trace(err)
}
existing, err := ec.controller(controller.ControllerTag.Id())
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
var ops []txn.Op
if err == nil {
models := set.NewStrings(existing.Models...)
models = models.Union(set.NewStrings(modelUUIDs...))
ops = []txn.Op{{
C: externalControllersC,
Id: existing.Id,
Assert: txn.DocExists,
Update: bson.D{
{"$set",
bson.D{{"addresses", doc.Addrs},
{"alias", doc.Alias},
{"cacert", doc.CACert},
{"models", models.Values()}},
},
},
}, model.assertActiveOp()}
} else {
doc.Models = modelUUIDs
ops = []txn.Op{{
C: externalControllersC,
Id: doc.Id,
Assert: txn.DocMissing,
Insert: doc,
}, model.assertActiveOp()}
}
return ops, nil
}
if err := ec.st.db().Run(buildTxn); err != nil {
return nil, errors.Annotate(err, "failed to create external controllers")
}
return &externalController{
doc: doc,
}, nil
} | go | func (ec *externalControllers) Save(controller crossmodel.ControllerInfo, modelUUIDs ...string) (ExternalController, error) {
if err := controller.Validate(); err != nil {
return nil, errors.Trace(err)
}
doc := externalControllerDoc{
Id: controller.ControllerTag.Id(),
Alias: controller.Alias,
Addrs: controller.Addrs,
CACert: controller.CACert,
}
buildTxn := func(int) ([]txn.Op, error) {
model, err := ec.st.Model()
if err != nil {
return nil, errors.Annotate(err, "failed to load model")
}
if err := checkModelActive(ec.st); err != nil {
return nil, errors.Trace(err)
}
existing, err := ec.controller(controller.ControllerTag.Id())
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
var ops []txn.Op
if err == nil {
models := set.NewStrings(existing.Models...)
models = models.Union(set.NewStrings(modelUUIDs...))
ops = []txn.Op{{
C: externalControllersC,
Id: existing.Id,
Assert: txn.DocExists,
Update: bson.D{
{"$set",
bson.D{{"addresses", doc.Addrs},
{"alias", doc.Alias},
{"cacert", doc.CACert},
{"models", models.Values()}},
},
},
}, model.assertActiveOp()}
} else {
doc.Models = modelUUIDs
ops = []txn.Op{{
C: externalControllersC,
Id: doc.Id,
Assert: txn.DocMissing,
Insert: doc,
}, model.assertActiveOp()}
}
return ops, nil
}
if err := ec.st.db().Run(buildTxn); err != nil {
return nil, errors.Annotate(err, "failed to create external controllers")
}
return &externalController{
doc: doc,
}, nil
} | [
"func",
"(",
"ec",
"*",
"externalControllers",
")",
"Save",
"(",
"controller",
"crossmodel",
".",
"ControllerInfo",
",",
"modelUUIDs",
"...",
"string",
")",
"(",
"ExternalController",
",",
"error",
")",
"{",
"if",
"err",
":=",
"controller",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"doc",
":=",
"externalControllerDoc",
"{",
"Id",
":",
"controller",
".",
"ControllerTag",
".",
"Id",
"(",
")",
",",
"Alias",
":",
"controller",
".",
"Alias",
",",
"Addrs",
":",
"controller",
".",
"Addrs",
",",
"CACert",
":",
"controller",
".",
"CACert",
",",
"}",
"\n",
"buildTxn",
":=",
"func",
"(",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"model",
",",
"err",
":=",
"ec",
".",
"st",
".",
"Model",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"checkModelActive",
"(",
"ec",
".",
"st",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"existing",
",",
"err",
":=",
"ec",
".",
"controller",
"(",
"controller",
".",
"ControllerTag",
".",
"Id",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"var",
"ops",
"[",
"]",
"txn",
".",
"Op",
"\n",
"if",
"err",
"==",
"nil",
"{",
"models",
":=",
"set",
".",
"NewStrings",
"(",
"existing",
".",
"Models",
"...",
")",
"\n",
"models",
"=",
"models",
".",
"Union",
"(",
"set",
".",
"NewStrings",
"(",
"modelUUIDs",
"...",
")",
")",
"\n",
"ops",
"=",
"[",
"]",
"txn",
".",
"Op",
"{",
"{",
"C",
":",
"externalControllersC",
",",
"Id",
":",
"existing",
".",
"Id",
",",
"Assert",
":",
"txn",
".",
"DocExists",
",",
"Update",
":",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"doc",
".",
"Addrs",
"}",
",",
"{",
"\"",
"\"",
",",
"doc",
".",
"Alias",
"}",
",",
"{",
"\"",
"\"",
",",
"doc",
".",
"CACert",
"}",
",",
"{",
"\"",
"\"",
",",
"models",
".",
"Values",
"(",
")",
"}",
"}",
",",
"}",
",",
"}",
",",
"}",
",",
"model",
".",
"assertActiveOp",
"(",
")",
"}",
"\n",
"}",
"else",
"{",
"doc",
".",
"Models",
"=",
"modelUUIDs",
"\n",
"ops",
"=",
"[",
"]",
"txn",
".",
"Op",
"{",
"{",
"C",
":",
"externalControllersC",
",",
"Id",
":",
"doc",
".",
"Id",
",",
"Assert",
":",
"txn",
".",
"DocMissing",
",",
"Insert",
":",
"doc",
",",
"}",
",",
"model",
".",
"assertActiveOp",
"(",
")",
"}",
"\n",
"}",
"\n",
"return",
"ops",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"ec",
".",
"st",
".",
"db",
"(",
")",
".",
"Run",
"(",
"buildTxn",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"externalController",
"{",
"doc",
":",
"doc",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Add creates or updates an external controller record. | [
"Add",
"creates",
"or",
"updates",
"an",
"external",
"controller",
"record",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/externalcontroller.go#L89-L146 |
5,230 | juju/juju | state/externalcontroller.go | Remove | func (ec *externalControllers) Remove(controllerUUID string) error {
ops := []txn.Op{{
C: externalControllersC,
Id: controllerUUID,
Remove: true,
}}
err := ec.st.db().RunTransaction(ops)
return errors.Annotate(err, "failed to remove external controller")
} | go | func (ec *externalControllers) Remove(controllerUUID string) error {
ops := []txn.Op{{
C: externalControllersC,
Id: controllerUUID,
Remove: true,
}}
err := ec.st.db().RunTransaction(ops)
return errors.Annotate(err, "failed to remove external controller")
} | [
"func",
"(",
"ec",
"*",
"externalControllers",
")",
"Remove",
"(",
"controllerUUID",
"string",
")",
"error",
"{",
"ops",
":=",
"[",
"]",
"txn",
".",
"Op",
"{",
"{",
"C",
":",
"externalControllersC",
",",
"Id",
":",
"controllerUUID",
",",
"Remove",
":",
"true",
",",
"}",
"}",
"\n",
"err",
":=",
"ec",
".",
"st",
".",
"db",
"(",
")",
".",
"RunTransaction",
"(",
"ops",
")",
"\n",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // Remove removes an external controller record with the given controller UUID. | [
"Remove",
"removes",
"an",
"external",
"controller",
"record",
"with",
"the",
"given",
"controller",
"UUID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/externalcontroller.go#L149-L157 |
5,231 | juju/juju | state/externalcontroller.go | Controller | func (ec *externalControllers) Controller(controllerUUID string) (ExternalController, error) {
doc, err := ec.controller(controllerUUID)
if err != nil {
return nil, errors.Trace(err)
}
return &externalController{*doc}, nil
} | go | func (ec *externalControllers) Controller(controllerUUID string) (ExternalController, error) {
doc, err := ec.controller(controllerUUID)
if err != nil {
return nil, errors.Trace(err)
}
return &externalController{*doc}, nil
} | [
"func",
"(",
"ec",
"*",
"externalControllers",
")",
"Controller",
"(",
"controllerUUID",
"string",
")",
"(",
"ExternalController",
",",
"error",
")",
"{",
"doc",
",",
"err",
":=",
"ec",
".",
"controller",
"(",
"controllerUUID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"externalController",
"{",
"*",
"doc",
"}",
",",
"nil",
"\n",
"}"
] | // Controller retrieves an ExternalController with a given controller UUID. | [
"Controller",
"retrieves",
"an",
"ExternalController",
"with",
"a",
"given",
"controller",
"UUID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/externalcontroller.go#L160-L166 |
5,232 | juju/juju | state/externalcontroller.go | ControllerForModel | func (ec *externalControllers) ControllerForModel(modelUUID string) (ExternalController, error) {
coll, closer := ec.st.db().GetCollection(externalControllersC)
defer closer()
var doc []externalControllerDoc
err := coll.Find(bson.M{"models": bson.M{"$in": []string{modelUUID}}}).All(&doc)
if err != nil {
return nil, errors.Trace(err)
}
switch len(doc) {
case 0:
return nil, errors.NotFoundf("external controller with model %v", modelUUID)
case 1:
return &externalController{
doc: doc[0],
}, nil
}
return nil, errors.Errorf("expected 1 controller with model %v, got %d", modelUUID, len(doc))
} | go | func (ec *externalControllers) ControllerForModel(modelUUID string) (ExternalController, error) {
coll, closer := ec.st.db().GetCollection(externalControllersC)
defer closer()
var doc []externalControllerDoc
err := coll.Find(bson.M{"models": bson.M{"$in": []string{modelUUID}}}).All(&doc)
if err != nil {
return nil, errors.Trace(err)
}
switch len(doc) {
case 0:
return nil, errors.NotFoundf("external controller with model %v", modelUUID)
case 1:
return &externalController{
doc: doc[0],
}, nil
}
return nil, errors.Errorf("expected 1 controller with model %v, got %d", modelUUID, len(doc))
} | [
"func",
"(",
"ec",
"*",
"externalControllers",
")",
"ControllerForModel",
"(",
"modelUUID",
"string",
")",
"(",
"ExternalController",
",",
"error",
")",
"{",
"coll",
",",
"closer",
":=",
"ec",
".",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"externalControllersC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"var",
"doc",
"[",
"]",
"externalControllerDoc",
"\n",
"err",
":=",
"coll",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"[",
"]",
"string",
"{",
"modelUUID",
"}",
"}",
"}",
")",
".",
"All",
"(",
"&",
"doc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"switch",
"len",
"(",
"doc",
")",
"{",
"case",
"0",
":",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"modelUUID",
")",
"\n",
"case",
"1",
":",
"return",
"&",
"externalController",
"{",
"doc",
":",
"doc",
"[",
"0",
"]",
",",
"}",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"modelUUID",
",",
"len",
"(",
"doc",
")",
")",
"\n",
"}"
] | // ControllerForModel retrieves an ExternalController with a given model UUID. | [
"ControllerForModel",
"retrieves",
"an",
"ExternalController",
"with",
"a",
"given",
"model",
"UUID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/externalcontroller.go#L184-L202 |
5,233 | juju/juju | state/externalcontroller.go | WatchController | func (ec *externalControllers) WatchController(controllerUUID string) NotifyWatcher {
return newEntityWatcher(ec.st, externalControllersC, controllerUUID)
} | go | func (ec *externalControllers) WatchController(controllerUUID string) NotifyWatcher {
return newEntityWatcher(ec.st, externalControllersC, controllerUUID)
} | [
"func",
"(",
"ec",
"*",
"externalControllers",
")",
"WatchController",
"(",
"controllerUUID",
"string",
")",
"NotifyWatcher",
"{",
"return",
"newEntityWatcher",
"(",
"ec",
".",
"st",
",",
"externalControllersC",
",",
"controllerUUID",
")",
"\n",
"}"
] | // WatchController returns a notify watcher that watches for changes to the
// external controller with the specified controller UUID. | [
"WatchController",
"returns",
"a",
"notify",
"watcher",
"that",
"watches",
"for",
"changes",
"to",
"the",
"external",
"controller",
"with",
"the",
"specified",
"controller",
"UUID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/externalcontroller.go#L213-L215 |
5,234 | juju/juju | api/crossmodelrelations/macarooncache.go | NewMacaroonCache | func NewMacaroonCache(clock clock.Clock) *MacaroonCache {
c := &cacheInternal{clock: clock, macaroons: make(map[string]*macaroonEntry)}
cache := &MacaroonCache{c}
// The interval to run the expiry worker is somewhat arbitrary.
// Expired macaroons will be re-issued as needed; we just want to ensure
// that those which fall out of use are eventually cleaned up.
c.runExpiryWorker(10 * time.Minute)
runtime.SetFinalizer(cache, stopMacaroonCacheExpiryWorker)
return cache
} | go | func NewMacaroonCache(clock clock.Clock) *MacaroonCache {
c := &cacheInternal{clock: clock, macaroons: make(map[string]*macaroonEntry)}
cache := &MacaroonCache{c}
// The interval to run the expiry worker is somewhat arbitrary.
// Expired macaroons will be re-issued as needed; we just want to ensure
// that those which fall out of use are eventually cleaned up.
c.runExpiryWorker(10 * time.Minute)
runtime.SetFinalizer(cache, stopMacaroonCacheExpiryWorker)
return cache
} | [
"func",
"NewMacaroonCache",
"(",
"clock",
"clock",
".",
"Clock",
")",
"*",
"MacaroonCache",
"{",
"c",
":=",
"&",
"cacheInternal",
"{",
"clock",
":",
"clock",
",",
"macaroons",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"macaroonEntry",
")",
"}",
"\n",
"cache",
":=",
"&",
"MacaroonCache",
"{",
"c",
"}",
"\n",
"// The interval to run the expiry worker is somewhat arbitrary.",
"// Expired macaroons will be re-issued as needed; we just want to ensure",
"// that those which fall out of use are eventually cleaned up.",
"c",
".",
"runExpiryWorker",
"(",
"10",
"*",
"time",
".",
"Minute",
")",
"\n",
"runtime",
".",
"SetFinalizer",
"(",
"cache",
",",
"stopMacaroonCacheExpiryWorker",
")",
"\n",
"return",
"cache",
"\n",
"}"
] | // NewMacaroonCache returns a cache containing macaroons which are removed
// after the macaroons' expiry time. | [
"NewMacaroonCache",
"returns",
"a",
"cache",
"containing",
"macaroons",
"which",
"are",
"removed",
"after",
"the",
"macaroons",
"expiry",
"time",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/crossmodelrelations/macarooncache.go#L26-L35 |
5,235 | juju/juju | api/crossmodelrelations/macarooncache.go | Upsert | func (c *cacheInternal) Upsert(token string, ms macaroon.Slice) {
c.Lock()
defer c.Unlock()
var et *time.Time
if expiryTime, ok := checkers.MacaroonsExpiryTime(ms); ok {
et = &expiryTime
}
c.macaroons[token] = &macaroonEntry{
ms: ms,
expiryTime: et,
}
} | go | func (c *cacheInternal) Upsert(token string, ms macaroon.Slice) {
c.Lock()
defer c.Unlock()
var et *time.Time
if expiryTime, ok := checkers.MacaroonsExpiryTime(ms); ok {
et = &expiryTime
}
c.macaroons[token] = &macaroonEntry{
ms: ms,
expiryTime: et,
}
} | [
"func",
"(",
"c",
"*",
"cacheInternal",
")",
"Upsert",
"(",
"token",
"string",
",",
"ms",
"macaroon",
".",
"Slice",
")",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"et",
"*",
"time",
".",
"Time",
"\n",
"if",
"expiryTime",
",",
"ok",
":=",
"checkers",
".",
"MacaroonsExpiryTime",
"(",
"ms",
")",
";",
"ok",
"{",
"et",
"=",
"&",
"expiryTime",
"\n",
"}",
"\n",
"c",
".",
"macaroons",
"[",
"token",
"]",
"=",
"&",
"macaroonEntry",
"{",
"ms",
":",
"ms",
",",
"expiryTime",
":",
"et",
",",
"}",
"\n",
"}"
] | // Upsert inserts or updates a macaroon slice in the cache. | [
"Upsert",
"inserts",
"or",
"updates",
"a",
"macaroon",
"slice",
"in",
"the",
"cache",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/crossmodelrelations/macarooncache.go#L72-L84 |
5,236 | juju/juju | api/crossmodelrelations/macarooncache.go | Get | func (c *cacheInternal) Get(k string) (macaroon.Slice, bool) {
c.Lock()
defer c.Unlock()
entry, found := c.macaroons[k]
if !found {
return nil, false
}
if entry.expired(c.clock) {
delete(c.macaroons, k)
return nil, false
}
return entry.ms, true
} | go | func (c *cacheInternal) Get(k string) (macaroon.Slice, bool) {
c.Lock()
defer c.Unlock()
entry, found := c.macaroons[k]
if !found {
return nil, false
}
if entry.expired(c.clock) {
delete(c.macaroons, k)
return nil, false
}
return entry.ms, true
} | [
"func",
"(",
"c",
"*",
"cacheInternal",
")",
"Get",
"(",
"k",
"string",
")",
"(",
"macaroon",
".",
"Slice",
",",
"bool",
")",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n\n",
"entry",
",",
"found",
":=",
"c",
".",
"macaroons",
"[",
"k",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"if",
"entry",
".",
"expired",
"(",
"c",
".",
"clock",
")",
"{",
"delete",
"(",
"c",
".",
"macaroons",
",",
"k",
")",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"return",
"entry",
".",
"ms",
",",
"true",
"\n",
"}"
] | // Get returns a macaroon slice from the cache, and a bool indicating
// if the slice for the key was found. | [
"Get",
"returns",
"a",
"macaroon",
"slice",
"from",
"the",
"cache",
"and",
"a",
"bool",
"indicating",
"if",
"the",
"slice",
"for",
"the",
"key",
"was",
"found",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/crossmodelrelations/macarooncache.go#L88-L101 |
5,237 | juju/juju | cmd/plugins/juju-metadata/cloudimagemetadata.go | NewImageMetadataAPI | func (c *cloudImageMetadataCommandBase) NewImageMetadataAPI() (*imagemetadatamanager.Client, error) {
root, err := c.NewAPIRoot()
if err != nil {
return nil, err
}
return imagemetadatamanager.NewClient(root), nil
} | go | func (c *cloudImageMetadataCommandBase) NewImageMetadataAPI() (*imagemetadatamanager.Client, error) {
root, err := c.NewAPIRoot()
if err != nil {
return nil, err
}
return imagemetadatamanager.NewClient(root), nil
} | [
"func",
"(",
"c",
"*",
"cloudImageMetadataCommandBase",
")",
"NewImageMetadataAPI",
"(",
")",
"(",
"*",
"imagemetadatamanager",
".",
"Client",
",",
"error",
")",
"{",
"root",
",",
"err",
":=",
"c",
".",
"NewAPIRoot",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"imagemetadatamanager",
".",
"NewClient",
"(",
"root",
")",
",",
"nil",
"\n",
"}"
] | // NewImageMetadataAPI returns a image metadata api for the root api endpoint
// that the environment command returns. | [
"NewImageMetadataAPI",
"returns",
"a",
"image",
"metadata",
"api",
"for",
"the",
"root",
"api",
"endpoint",
"that",
"the",
"environment",
"command",
"returns",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/plugins/juju-metadata/cloudimagemetadata.go#L18-L24 |
5,238 | juju/juju | worker/upgradeseries/mocks/package_mock.go | NewMockFacade | func NewMockFacade(ctrl *gomock.Controller) *MockFacade {
mock := &MockFacade{ctrl: ctrl}
mock.recorder = &MockFacadeMockRecorder{mock}
return mock
} | go | func NewMockFacade(ctrl *gomock.Controller) *MockFacade {
mock := &MockFacade{ctrl: ctrl}
mock.recorder = &MockFacadeMockRecorder{mock}
return mock
} | [
"func",
"NewMockFacade",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockFacade",
"{",
"mock",
":=",
"&",
"MockFacade",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockFacadeMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockFacade creates a new mock instance | [
"NewMockFacade",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L29-L33 |
5,239 | juju/juju | worker/upgradeseries/mocks/package_mock.go | FinishUpgradeSeries | func (mr *MockFacadeMockRecorder) FinishUpgradeSeries(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FinishUpgradeSeries", reflect.TypeOf((*MockFacade)(nil).FinishUpgradeSeries), arg0)
} | go | func (mr *MockFacadeMockRecorder) FinishUpgradeSeries(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FinishUpgradeSeries", reflect.TypeOf((*MockFacade)(nil).FinishUpgradeSeries), arg0)
} | [
"func",
"(",
"mr",
"*",
"MockFacadeMockRecorder",
")",
"FinishUpgradeSeries",
"(",
"arg0",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockFacade",
")",
"(",
"nil",
")",
".",
"FinishUpgradeSeries",
")",
",",
"arg0",
")",
"\n",
"}"
] | // FinishUpgradeSeries indicates an expected call of FinishUpgradeSeries | [
"FinishUpgradeSeries",
"indicates",
"an",
"expected",
"call",
"of",
"FinishUpgradeSeries"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L48-L50 |
5,240 | juju/juju | worker/upgradeseries/mocks/package_mock.go | MachineStatus | func (m *MockFacade) MachineStatus() (model.UpgradeSeriesStatus, error) {
ret := m.ctrl.Call(m, "MachineStatus")
ret0, _ := ret[0].(model.UpgradeSeriesStatus)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockFacade) MachineStatus() (model.UpgradeSeriesStatus, error) {
ret := m.ctrl.Call(m, "MachineStatus")
ret0, _ := ret[0].(model.UpgradeSeriesStatus)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockFacade",
")",
"MachineStatus",
"(",
")",
"(",
"model",
".",
"UpgradeSeriesStatus",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"model",
".",
"UpgradeSeriesStatus",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // MachineStatus mocks base method | [
"MachineStatus",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L53-L58 |
5,241 | juju/juju | worker/upgradeseries/mocks/package_mock.go | SetMachineStatus | func (m *MockFacade) SetMachineStatus(arg0 model.UpgradeSeriesStatus, arg1 string) error {
ret := m.ctrl.Call(m, "SetMachineStatus", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
} | go | func (m *MockFacade) SetMachineStatus(arg0 model.UpgradeSeriesStatus, arg1 string) error {
ret := m.ctrl.Call(m, "SetMachineStatus", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockFacade",
")",
"SetMachineStatus",
"(",
"arg0",
"model",
".",
"UpgradeSeriesStatus",
",",
"arg1",
"string",
")",
"error",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
",",
"arg1",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // SetMachineStatus mocks base method | [
"SetMachineStatus",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L79-L83 |
5,242 | juju/juju | worker/upgradeseries/mocks/package_mock.go | StartUnitCompletion | func (m *MockFacade) StartUnitCompletion(arg0 string) error {
ret := m.ctrl.Call(m, "StartUnitCompletion", arg0)
ret0, _ := ret[0].(error)
return ret0
} | go | func (m *MockFacade) StartUnitCompletion(arg0 string) error {
ret := m.ctrl.Call(m, "StartUnitCompletion", arg0)
ret0, _ := ret[0].(error)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockFacade",
")",
"StartUnitCompletion",
"(",
"arg0",
"string",
")",
"error",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // StartUnitCompletion mocks base method | [
"StartUnitCompletion",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L91-L95 |
5,243 | juju/juju | worker/upgradeseries/mocks/package_mock.go | TargetSeries | func (m *MockFacade) TargetSeries() (string, error) {
ret := m.ctrl.Call(m, "TargetSeries")
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockFacade) TargetSeries() (string, error) {
ret := m.ctrl.Call(m, "TargetSeries")
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockFacade",
")",
"TargetSeries",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"string",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // TargetSeries mocks base method | [
"TargetSeries",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L103-L108 |
5,244 | juju/juju | worker/upgradeseries/mocks/package_mock.go | UnitsCompleted | func (m *MockFacade) UnitsCompleted() ([]names_v2.UnitTag, error) {
ret := m.ctrl.Call(m, "UnitsCompleted")
ret0, _ := ret[0].([]names_v2.UnitTag)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockFacade) UnitsCompleted() ([]names_v2.UnitTag, error) {
ret := m.ctrl.Call(m, "UnitsCompleted")
ret0, _ := ret[0].([]names_v2.UnitTag)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockFacade",
")",
"UnitsCompleted",
"(",
")",
"(",
"[",
"]",
"names_v2",
".",
"UnitTag",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"[",
"]",
"names_v2",
".",
"UnitTag",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // UnitsCompleted mocks base method | [
"UnitsCompleted",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L116-L121 |
5,245 | juju/juju | worker/upgradeseries/mocks/package_mock.go | UnpinMachineApplications | func (mr *MockFacadeMockRecorder) UnpinMachineApplications() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnpinMachineApplications", reflect.TypeOf((*MockFacade)(nil).UnpinMachineApplications))
} | go | func (mr *MockFacadeMockRecorder) UnpinMachineApplications() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnpinMachineApplications", reflect.TypeOf((*MockFacade)(nil).UnpinMachineApplications))
} | [
"func",
"(",
"mr",
"*",
"MockFacadeMockRecorder",
")",
"UnpinMachineApplications",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockFacade",
")",
"(",
"nil",
")",
".",
"UnpinMachineApplications",
")",
")",
"\n",
"}"
] | // UnpinMachineApplications indicates an expected call of UnpinMachineApplications | [
"UnpinMachineApplications",
"indicates",
"an",
"expected",
"call",
"of",
"UnpinMachineApplications"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L150-L152 |
5,246 | juju/juju | worker/upgradeseries/mocks/package_mock.go | Infof | func (m *MockLogger) Infof(arg0 string, arg1 ...interface{}) {
varargs := []interface{}{arg0}
for _, a := range arg1 {
varargs = append(varargs, a)
}
m.ctrl.Call(m, "Infof", varargs...)
} | go | func (m *MockLogger) Infof(arg0 string, arg1 ...interface{}) {
varargs := []interface{}{arg0}
for _, a := range arg1 {
varargs = append(varargs, a)
}
m.ctrl.Call(m, "Infof", varargs...)
} | [
"func",
"(",
"m",
"*",
"MockLogger",
")",
"Infof",
"(",
"arg0",
"string",
",",
"arg1",
"...",
"interface",
"{",
"}",
")",
"{",
"varargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"arg0",
"}",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"arg1",
"{",
"varargs",
"=",
"append",
"(",
"varargs",
",",
"a",
")",
"\n",
"}",
"\n",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"varargs",
"...",
")",
"\n",
"}"
] | // Infof mocks base method | [
"Infof",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L221-L227 |
5,247 | juju/juju | worker/upgradeseries/mocks/package_mock.go | Infof | func (mr *MockLoggerMockRecorder) Infof(arg0 interface{}, arg1 ...interface{}) *gomock.Call {
varargs := append([]interface{}{arg0}, arg1...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Infof", reflect.TypeOf((*MockLogger)(nil).Infof), varargs...)
} | go | func (mr *MockLoggerMockRecorder) Infof(arg0 interface{}, arg1 ...interface{}) *gomock.Call {
varargs := append([]interface{}{arg0}, arg1...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Infof", reflect.TypeOf((*MockLogger)(nil).Infof), varargs...)
} | [
"func",
"(",
"mr",
"*",
"MockLoggerMockRecorder",
")",
"Infof",
"(",
"arg0",
"interface",
"{",
"}",
",",
"arg1",
"...",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"varargs",
":=",
"append",
"(",
"[",
"]",
"interface",
"{",
"}",
"{",
"arg0",
"}",
",",
"arg1",
"...",
")",
"\n",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockLogger",
")",
"(",
"nil",
")",
".",
"Infof",
")",
",",
"varargs",
"...",
")",
"\n",
"}"
] | // Infof indicates an expected call of Infof | [
"Infof",
"indicates",
"an",
"expected",
"call",
"of",
"Infof"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L230-L233 |
5,248 | juju/juju | worker/upgradeseries/mocks/package_mock.go | NewMockAgentService | func NewMockAgentService(ctrl *gomock.Controller) *MockAgentService {
mock := &MockAgentService{ctrl: ctrl}
mock.recorder = &MockAgentServiceMockRecorder{mock}
return mock
} | go | func NewMockAgentService(ctrl *gomock.Controller) *MockAgentService {
mock := &MockAgentService{ctrl: ctrl}
mock.recorder = &MockAgentServiceMockRecorder{mock}
return mock
} | [
"func",
"NewMockAgentService",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockAgentService",
"{",
"mock",
":=",
"&",
"MockAgentService",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockAgentServiceMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockAgentService creates a new mock instance | [
"NewMockAgentService",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L262-L266 |
5,249 | juju/juju | worker/upgradeseries/mocks/package_mock.go | Running | func (m *MockAgentService) Running() (bool, error) {
ret := m.ctrl.Call(m, "Running")
ret0, _ := ret[0].(bool)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockAgentService) Running() (bool, error) {
ret := m.ctrl.Call(m, "Running")
ret0, _ := ret[0].(bool)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockAgentService",
")",
"Running",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"bool",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // Running mocks base method | [
"Running",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L274-L279 |
5,250 | juju/juju | worker/upgradeseries/mocks/package_mock.go | Running | func (mr *MockAgentServiceMockRecorder) Running() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Running", reflect.TypeOf((*MockAgentService)(nil).Running))
} | go | func (mr *MockAgentServiceMockRecorder) Running() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Running", reflect.TypeOf((*MockAgentService)(nil).Running))
} | [
"func",
"(",
"mr",
"*",
"MockAgentServiceMockRecorder",
")",
"Running",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockAgentService",
")",
"(",
"nil",
")",
".",
"Running",
")",
")",
"\n",
"}"
] | // Running indicates an expected call of Running | [
"Running",
"indicates",
"an",
"expected",
"call",
"of",
"Running"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L282-L284 |
5,251 | juju/juju | worker/upgradeseries/mocks/package_mock.go | NewMockServiceAccess | func NewMockServiceAccess(ctrl *gomock.Controller) *MockServiceAccess {
mock := &MockServiceAccess{ctrl: ctrl}
mock.recorder = &MockServiceAccessMockRecorder{mock}
return mock
} | go | func NewMockServiceAccess(ctrl *gomock.Controller) *MockServiceAccess {
mock := &MockServiceAccess{ctrl: ctrl}
mock.recorder = &MockServiceAccessMockRecorder{mock}
return mock
} | [
"func",
"NewMockServiceAccess",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockServiceAccess",
"{",
"mock",
":=",
"&",
"MockServiceAccess",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockServiceAccessMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockServiceAccess creates a new mock instance | [
"NewMockServiceAccess",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L322-L326 |
5,252 | juju/juju | worker/upgradeseries/mocks/package_mock.go | DiscoverService | func (m *MockServiceAccess) DiscoverService(arg0 string) (upgradeseries.AgentService, error) {
ret := m.ctrl.Call(m, "DiscoverService", arg0)
ret0, _ := ret[0].(upgradeseries.AgentService)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockServiceAccess) DiscoverService(arg0 string) (upgradeseries.AgentService, error) {
ret := m.ctrl.Call(m, "DiscoverService", arg0)
ret0, _ := ret[0].(upgradeseries.AgentService)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockServiceAccess",
")",
"DiscoverService",
"(",
"arg0",
"string",
")",
"(",
"upgradeseries",
".",
"AgentService",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"upgradeseries",
".",
"AgentService",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // DiscoverService mocks base method | [
"DiscoverService",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L334-L339 |
5,253 | juju/juju | worker/upgradeseries/mocks/package_mock.go | DiscoverService | func (mr *MockServiceAccessMockRecorder) DiscoverService(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DiscoverService", reflect.TypeOf((*MockServiceAccess)(nil).DiscoverService), arg0)
} | go | func (mr *MockServiceAccessMockRecorder) DiscoverService(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DiscoverService", reflect.TypeOf((*MockServiceAccess)(nil).DiscoverService), arg0)
} | [
"func",
"(",
"mr",
"*",
"MockServiceAccessMockRecorder",
")",
"DiscoverService",
"(",
"arg0",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockServiceAccess",
")",
"(",
"nil",
")",
".",
"DiscoverService",
")",
",",
"arg0",
")",
"\n",
"}"
] | // DiscoverService indicates an expected call of DiscoverService | [
"DiscoverService",
"indicates",
"an",
"expected",
"call",
"of",
"DiscoverService"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L342-L344 |
5,254 | juju/juju | worker/upgradeseries/mocks/package_mock.go | ListServices | func (m *MockServiceAccess) ListServices() ([]string, error) {
ret := m.ctrl.Call(m, "ListServices")
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockServiceAccess) ListServices() ([]string, error) {
ret := m.ctrl.Call(m, "ListServices")
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockServiceAccess",
")",
"ListServices",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"[",
"]",
"string",
")",
"\n",
"ret1",
",",
"_",
":=",
"ret",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
",",
"ret1",
"\n",
"}"
] | // ListServices mocks base method | [
"ListServices",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L347-L352 |
5,255 | juju/juju | worker/upgradeseries/mocks/package_mock.go | ListServices | func (mr *MockServiceAccessMockRecorder) ListServices() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListServices", reflect.TypeOf((*MockServiceAccess)(nil).ListServices))
} | go | func (mr *MockServiceAccessMockRecorder) ListServices() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListServices", reflect.TypeOf((*MockServiceAccess)(nil).ListServices))
} | [
"func",
"(",
"mr",
"*",
"MockServiceAccessMockRecorder",
")",
"ListServices",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockServiceAccess",
")",
"(",
"nil",
")",
".",
"ListServices",
")",
")",
"\n",
"}"
] | // ListServices indicates an expected call of ListServices | [
"ListServices",
"indicates",
"an",
"expected",
"call",
"of",
"ListServices"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L355-L357 |
5,256 | juju/juju | worker/upgradeseries/mocks/package_mock.go | NewMockUpgrader | func NewMockUpgrader(ctrl *gomock.Controller) *MockUpgrader {
mock := &MockUpgrader{ctrl: ctrl}
mock.recorder = &MockUpgraderMockRecorder{mock}
return mock
} | go | func NewMockUpgrader(ctrl *gomock.Controller) *MockUpgrader {
mock := &MockUpgrader{ctrl: ctrl}
mock.recorder = &MockUpgraderMockRecorder{mock}
return mock
} | [
"func",
"NewMockUpgrader",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockUpgrader",
"{",
"mock",
":=",
"&",
"MockUpgrader",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockUpgraderMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockUpgrader creates a new mock instance | [
"NewMockUpgrader",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L371-L375 |
5,257 | juju/juju | worker/upgradeseries/mocks/package_mock.go | PerformUpgrade | func (m *MockUpgrader) PerformUpgrade() error {
ret := m.ctrl.Call(m, "PerformUpgrade")
ret0, _ := ret[0].(error)
return ret0
} | go | func (m *MockUpgrader) PerformUpgrade() error {
ret := m.ctrl.Call(m, "PerformUpgrade")
ret0, _ := ret[0].(error)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockUpgrader",
")",
"PerformUpgrade",
"(",
")",
"error",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"error",
")",
"\n",
"return",
"ret0",
"\n",
"}"
] | // PerformUpgrade mocks base method | [
"PerformUpgrade",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L383-L387 |
5,258 | juju/juju | worker/upgradeseries/mocks/package_mock.go | PerformUpgrade | func (mr *MockUpgraderMockRecorder) PerformUpgrade() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PerformUpgrade", reflect.TypeOf((*MockUpgrader)(nil).PerformUpgrade))
} | go | func (mr *MockUpgraderMockRecorder) PerformUpgrade() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PerformUpgrade", reflect.TypeOf((*MockUpgrader)(nil).PerformUpgrade))
} | [
"func",
"(",
"mr",
"*",
"MockUpgraderMockRecorder",
")",
"PerformUpgrade",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockUpgrader",
")",
"(",
"nil",
")",
".",
"PerformUpgrade",
")",
")",
"\n",
"}"
] | // PerformUpgrade indicates an expected call of PerformUpgrade | [
"PerformUpgrade",
"indicates",
"an",
"expected",
"call",
"of",
"PerformUpgrade"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/mocks/package_mock.go#L390-L392 |
5,259 | juju/juju | resource/charmstore/cache.go | get | func (cfo cacheForOperations) get(name string) (resource.Resource, io.ReadCloser, error) {
if cfo.EntityCache == nil {
return resource.Resource{}, nil, errors.NotFoundf("resource %q", name)
}
res, reader, err := cfo.OpenResource(name)
if errors.IsNotFound(err) {
reader = nil
res, err = cfo.GetResource(name)
}
if err != nil {
return resource.Resource{}, nil, errors.Trace(err)
}
return res, reader, nil
} | go | func (cfo cacheForOperations) get(name string) (resource.Resource, io.ReadCloser, error) {
if cfo.EntityCache == nil {
return resource.Resource{}, nil, errors.NotFoundf("resource %q", name)
}
res, reader, err := cfo.OpenResource(name)
if errors.IsNotFound(err) {
reader = nil
res, err = cfo.GetResource(name)
}
if err != nil {
return resource.Resource{}, nil, errors.Trace(err)
}
return res, reader, nil
} | [
"func",
"(",
"cfo",
"cacheForOperations",
")",
"get",
"(",
"name",
"string",
")",
"(",
"resource",
".",
"Resource",
",",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"if",
"cfo",
".",
"EntityCache",
"==",
"nil",
"{",
"return",
"resource",
".",
"Resource",
"{",
"}",
",",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"res",
",",
"reader",
",",
"err",
":=",
"cfo",
".",
"OpenResource",
"(",
"name",
")",
"\n",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"reader",
"=",
"nil",
"\n",
"res",
",",
"err",
"=",
"cfo",
".",
"GetResource",
"(",
"name",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"resource",
".",
"Resource",
"{",
"}",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"res",
",",
"reader",
",",
"nil",
"\n",
"}"
] | // get retrieves the resource info and data from the cache. If only
// the info is found then the returned reader will be nil. If no cache
// is in use then errors.NotFound is returned. | [
"get",
"retrieves",
"the",
"resource",
"info",
"and",
"data",
"from",
"the",
"cache",
".",
"If",
"only",
"the",
"info",
"is",
"found",
"then",
"the",
"returned",
"reader",
"will",
"be",
"nil",
".",
"If",
"no",
"cache",
"is",
"in",
"use",
"then",
"errors",
".",
"NotFound",
"is",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/charmstore/cache.go#L38-L53 |
5,260 | juju/juju | resource/charmstore/cache.go | set | func (cfo cacheForOperations) set(chRes charmresource.Resource, reader io.ReadCloser) (resource.Resource, io.ReadCloser, error) {
if cfo.EntityCache == nil {
res := resource.Resource{
Resource: chRes,
}
return res, reader, nil // a no-op
}
defer reader.Close()
res, err := cfo.SetResource(chRes, reader)
if err != nil {
return resource.Resource{}, nil, errors.Trace(err)
}
// Make sure to use the potentially updated resource details.
res, reader, err = cfo.OpenResource(res.Name)
if err != nil {
return resource.Resource{}, nil, errors.Trace(err)
}
return res, reader, nil
} | go | func (cfo cacheForOperations) set(chRes charmresource.Resource, reader io.ReadCloser) (resource.Resource, io.ReadCloser, error) {
if cfo.EntityCache == nil {
res := resource.Resource{
Resource: chRes,
}
return res, reader, nil // a no-op
}
defer reader.Close()
res, err := cfo.SetResource(chRes, reader)
if err != nil {
return resource.Resource{}, nil, errors.Trace(err)
}
// Make sure to use the potentially updated resource details.
res, reader, err = cfo.OpenResource(res.Name)
if err != nil {
return resource.Resource{}, nil, errors.Trace(err)
}
return res, reader, nil
} | [
"func",
"(",
"cfo",
"cacheForOperations",
")",
"set",
"(",
"chRes",
"charmresource",
".",
"Resource",
",",
"reader",
"io",
".",
"ReadCloser",
")",
"(",
"resource",
".",
"Resource",
",",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"if",
"cfo",
".",
"EntityCache",
"==",
"nil",
"{",
"res",
":=",
"resource",
".",
"Resource",
"{",
"Resource",
":",
"chRes",
",",
"}",
"\n",
"return",
"res",
",",
"reader",
",",
"nil",
"// a no-op",
"\n",
"}",
"\n",
"defer",
"reader",
".",
"Close",
"(",
")",
"\n\n",
"res",
",",
"err",
":=",
"cfo",
".",
"SetResource",
"(",
"chRes",
",",
"reader",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"resource",
".",
"Resource",
"{",
"}",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Make sure to use the potentially updated resource details.",
"res",
",",
"reader",
",",
"err",
"=",
"cfo",
".",
"OpenResource",
"(",
"res",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"resource",
".",
"Resource",
"{",
"}",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"res",
",",
"reader",
",",
"nil",
"\n",
"}"
] | // set stores the resource info and data in the cache,
// if there is one. If no cache is in use then this is a no-op. Note
// that the returned reader may or may not be the same one that was
// passed in. | [
"set",
"stores",
"the",
"resource",
"info",
"and",
"data",
"in",
"the",
"cache",
"if",
"there",
"is",
"one",
".",
"If",
"no",
"cache",
"is",
"in",
"use",
"then",
"this",
"is",
"a",
"no",
"-",
"op",
".",
"Note",
"that",
"the",
"returned",
"reader",
"may",
"or",
"may",
"not",
"be",
"the",
"same",
"one",
"that",
"was",
"passed",
"in",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/charmstore/cache.go#L59-L80 |
5,261 | juju/juju | environs/tools/build.go | Archive | func Archive(w io.Writer, dir string) error {
entries, err := ioutil.ReadDir(dir)
if err != nil {
return err
}
gzw := gzip.NewWriter(w)
defer closeErrorCheck(&err, gzw)
tarw := tar.NewWriter(gzw)
defer closeErrorCheck(&err, tarw)
for _, ent := range entries {
h := tarHeader(ent)
logger.Debugf("adding entry: %#v", h)
// ignore local umask
if isExecutable(ent) {
h.Mode = 0755
} else {
h.Mode = 0644
}
err := tarw.WriteHeader(h)
if err != nil {
return err
}
fileName := filepath.Join(dir, ent.Name())
if err := copyFile(tarw, fileName); err != nil {
return err
}
}
return nil
} | go | func Archive(w io.Writer, dir string) error {
entries, err := ioutil.ReadDir(dir)
if err != nil {
return err
}
gzw := gzip.NewWriter(w)
defer closeErrorCheck(&err, gzw)
tarw := tar.NewWriter(gzw)
defer closeErrorCheck(&err, tarw)
for _, ent := range entries {
h := tarHeader(ent)
logger.Debugf("adding entry: %#v", h)
// ignore local umask
if isExecutable(ent) {
h.Mode = 0755
} else {
h.Mode = 0644
}
err := tarw.WriteHeader(h)
if err != nil {
return err
}
fileName := filepath.Join(dir, ent.Name())
if err := copyFile(tarw, fileName); err != nil {
return err
}
}
return nil
} | [
"func",
"Archive",
"(",
"w",
"io",
".",
"Writer",
",",
"dir",
"string",
")",
"error",
"{",
"entries",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"gzw",
":=",
"gzip",
".",
"NewWriter",
"(",
"w",
")",
"\n",
"defer",
"closeErrorCheck",
"(",
"&",
"err",
",",
"gzw",
")",
"\n\n",
"tarw",
":=",
"tar",
".",
"NewWriter",
"(",
"gzw",
")",
"\n",
"defer",
"closeErrorCheck",
"(",
"&",
"err",
",",
"tarw",
")",
"\n\n",
"for",
"_",
",",
"ent",
":=",
"range",
"entries",
"{",
"h",
":=",
"tarHeader",
"(",
"ent",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"h",
")",
"\n",
"// ignore local umask",
"if",
"isExecutable",
"(",
"ent",
")",
"{",
"h",
".",
"Mode",
"=",
"0755",
"\n",
"}",
"else",
"{",
"h",
".",
"Mode",
"=",
"0644",
"\n",
"}",
"\n",
"err",
":=",
"tarw",
".",
"WriteHeader",
"(",
"h",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"fileName",
":=",
"filepath",
".",
"Join",
"(",
"dir",
",",
"ent",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"err",
":=",
"copyFile",
"(",
"tarw",
",",
"fileName",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Archive writes the executable files found in the given directory in
// gzipped tar format to w. | [
"Archive",
"writes",
"the",
"executable",
"files",
"found",
"in",
"the",
"given",
"directory",
"in",
"gzipped",
"tar",
"format",
"to",
"w",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/build.go#L30-L61 |
5,262 | juju/juju | environs/tools/build.go | archiveAndSHA256 | func archiveAndSHA256(w io.Writer, dir string) (sha256hash string, err error) {
h := sha256.New()
if err := Archive(io.MultiWriter(h, w), dir); err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), err
} | go | func archiveAndSHA256(w io.Writer, dir string) (sha256hash string, err error) {
h := sha256.New()
if err := Archive(io.MultiWriter(h, w), dir); err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), err
} | [
"func",
"archiveAndSHA256",
"(",
"w",
"io",
".",
"Writer",
",",
"dir",
"string",
")",
"(",
"sha256hash",
"string",
",",
"err",
"error",
")",
"{",
"h",
":=",
"sha256",
".",
"New",
"(",
")",
"\n",
"if",
"err",
":=",
"Archive",
"(",
"io",
".",
"MultiWriter",
"(",
"h",
",",
"w",
")",
",",
"dir",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"h",
".",
"Sum",
"(",
"nil",
")",
")",
",",
"err",
"\n",
"}"
] | // archiveAndSHA256 calls Archive with the provided arguments,
// and returns a hex-encoded SHA256 hash of the resulting
// archive. | [
"archiveAndSHA256",
"calls",
"Archive",
"with",
"the",
"provided",
"arguments",
"and",
"returns",
"a",
"hex",
"-",
"encoded",
"SHA256",
"hash",
"of",
"the",
"resulting",
"archive",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/build.go#L66-L72 |
5,263 | juju/juju | environs/tools/build.go | copyFile | func copyFile(w io.Writer, file string) error {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(w, f)
return err
} | go | func copyFile(w io.Writer, file string) error {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(w, f)
return err
} | [
"func",
"copyFile",
"(",
"w",
"io",
".",
"Writer",
",",
"file",
"string",
")",
"error",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"w",
",",
"f",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // copyFile writes the contents of the given file to w. | [
"copyFile",
"writes",
"the",
"contents",
"of",
"the",
"given",
"file",
"to",
"w",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/build.go#L75-L83 |
5,264 | juju/juju | environs/tools/build.go | tarHeader | func tarHeader(i os.FileInfo) *tar.Header {
return &tar.Header{
Typeflag: tar.TypeReg,
Name: i.Name(),
Size: i.Size(),
Mode: int64(i.Mode() & 0777),
ModTime: i.ModTime(),
AccessTime: i.ModTime(),
ChangeTime: i.ModTime(),
Uname: "ubuntu",
Gname: "ubuntu",
}
} | go | func tarHeader(i os.FileInfo) *tar.Header {
return &tar.Header{
Typeflag: tar.TypeReg,
Name: i.Name(),
Size: i.Size(),
Mode: int64(i.Mode() & 0777),
ModTime: i.ModTime(),
AccessTime: i.ModTime(),
ChangeTime: i.ModTime(),
Uname: "ubuntu",
Gname: "ubuntu",
}
} | [
"func",
"tarHeader",
"(",
"i",
"os",
".",
"FileInfo",
")",
"*",
"tar",
".",
"Header",
"{",
"return",
"&",
"tar",
".",
"Header",
"{",
"Typeflag",
":",
"tar",
".",
"TypeReg",
",",
"Name",
":",
"i",
".",
"Name",
"(",
")",
",",
"Size",
":",
"i",
".",
"Size",
"(",
")",
",",
"Mode",
":",
"int64",
"(",
"i",
".",
"Mode",
"(",
")",
"&",
"0777",
")",
",",
"ModTime",
":",
"i",
".",
"ModTime",
"(",
")",
",",
"AccessTime",
":",
"i",
".",
"ModTime",
"(",
")",
",",
"ChangeTime",
":",
"i",
".",
"ModTime",
"(",
")",
",",
"Uname",
":",
"\"",
"\"",
",",
"Gname",
":",
"\"",
"\"",
",",
"}",
"\n",
"}"
] | // tarHeader returns a tar file header given the file's stat
// information. | [
"tarHeader",
"returns",
"a",
"tar",
"file",
"header",
"given",
"the",
"file",
"s",
"stat",
"information",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/build.go#L87-L99 |
5,265 | juju/juju | environs/tools/build.go | closeErrorCheck | func closeErrorCheck(errp *error, c io.Closer) {
err := c.Close()
if *errp == nil {
*errp = err
}
} | go | func closeErrorCheck(errp *error, c io.Closer) {
err := c.Close()
if *errp == nil {
*errp = err
}
} | [
"func",
"closeErrorCheck",
"(",
"errp",
"*",
"error",
",",
"c",
"io",
".",
"Closer",
")",
"{",
"err",
":=",
"c",
".",
"Close",
"(",
")",
"\n",
"if",
"*",
"errp",
"==",
"nil",
"{",
"*",
"errp",
"=",
"err",
"\n",
"}",
"\n",
"}"
] | // closeErrorCheck means that we can ensure that
// Close errors do not get lost even when we defer them, | [
"closeErrorCheck",
"means",
"that",
"we",
"can",
"ensure",
"that",
"Close",
"errors",
"do",
"not",
"get",
"lost",
"even",
"when",
"we",
"defer",
"them"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/build.go#L109-L114 |
5,266 | juju/juju | environs/tools/build.go | ExistingJujudLocation | func ExistingJujudLocation() (string, error) {
jujuLocation, err := findExecutable(os.Args[0])
if err != nil {
logger.Infof("%v", err)
return "", err
}
jujuDir := filepath.Dir(jujuLocation)
return jujuDir, nil
} | go | func ExistingJujudLocation() (string, error) {
jujuLocation, err := findExecutable(os.Args[0])
if err != nil {
logger.Infof("%v", err)
return "", err
}
jujuDir := filepath.Dir(jujuLocation)
return jujuDir, nil
} | [
"func",
"ExistingJujudLocation",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"jujuLocation",
",",
"err",
":=",
"findExecutable",
"(",
"os",
".",
"Args",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"jujuDir",
":=",
"filepath",
".",
"Dir",
"(",
"jujuLocation",
")",
"\n",
"return",
"jujuDir",
",",
"nil",
"\n",
"}"
] | // ExistingJujudLocation returns the directory to
// a jujud executable in the path. | [
"ExistingJujudLocation",
"returns",
"the",
"directory",
"to",
"a",
"jujud",
"executable",
"in",
"the",
"path",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/build.go#L170-L178 |
5,267 | juju/juju | environs/tools/build.go | bundleTools | func bundleTools(build bool, w io.Writer, forceVersion *version.Number) (_ version.Binary, official bool, sha256hash string, _ error) {
dir, err := ioutil.TempDir("", "juju-tools")
if err != nil {
return version.Binary{}, false, "", err
}
defer os.RemoveAll(dir)
if err := packageLocalTools(dir, build); err != nil {
return version.Binary{}, false, "", err
}
tvers, official, err := JujudVersion(dir)
if err != nil {
return version.Binary{}, false, "", errors.Trace(err)
}
if official {
logger.Debugf("using official version %s", tvers)
} else if forceVersion != nil {
logger.Debugf("forcing version to %s", forceVersion)
if err := ioutil.WriteFile(filepath.Join(dir, "FORCE-VERSION"), []byte(forceVersion.String()), 0666); err != nil {
return version.Binary{}, false, "", err
}
}
sha256hash, err = archiveAndSHA256(w, dir)
if err != nil {
return version.Binary{}, false, "", err
}
return tvers, official, sha256hash, err
} | go | func bundleTools(build bool, w io.Writer, forceVersion *version.Number) (_ version.Binary, official bool, sha256hash string, _ error) {
dir, err := ioutil.TempDir("", "juju-tools")
if err != nil {
return version.Binary{}, false, "", err
}
defer os.RemoveAll(dir)
if err := packageLocalTools(dir, build); err != nil {
return version.Binary{}, false, "", err
}
tvers, official, err := JujudVersion(dir)
if err != nil {
return version.Binary{}, false, "", errors.Trace(err)
}
if official {
logger.Debugf("using official version %s", tvers)
} else if forceVersion != nil {
logger.Debugf("forcing version to %s", forceVersion)
if err := ioutil.WriteFile(filepath.Join(dir, "FORCE-VERSION"), []byte(forceVersion.String()), 0666); err != nil {
return version.Binary{}, false, "", err
}
}
sha256hash, err = archiveAndSHA256(w, dir)
if err != nil {
return version.Binary{}, false, "", err
}
return tvers, official, sha256hash, err
} | [
"func",
"bundleTools",
"(",
"build",
"bool",
",",
"w",
"io",
".",
"Writer",
",",
"forceVersion",
"*",
"version",
".",
"Number",
")",
"(",
"_",
"version",
".",
"Binary",
",",
"official",
"bool",
",",
"sha256hash",
"string",
",",
"_",
"error",
")",
"{",
"dir",
",",
"err",
":=",
"ioutil",
".",
"TempDir",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"version",
".",
"Binary",
"{",
"}",
",",
"false",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"defer",
"os",
".",
"RemoveAll",
"(",
"dir",
")",
"\n",
"if",
"err",
":=",
"packageLocalTools",
"(",
"dir",
",",
"build",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"version",
".",
"Binary",
"{",
"}",
",",
"false",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"tvers",
",",
"official",
",",
"err",
":=",
"JujudVersion",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"version",
".",
"Binary",
"{",
"}",
",",
"false",
",",
"\"",
"\"",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"official",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"tvers",
")",
"\n",
"}",
"else",
"if",
"forceVersion",
"!=",
"nil",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"forceVersion",
")",
"\n",
"if",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"",
"\"",
")",
",",
"[",
"]",
"byte",
"(",
"forceVersion",
".",
"String",
"(",
")",
")",
",",
"0666",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"version",
".",
"Binary",
"{",
"}",
",",
"false",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"sha256hash",
",",
"err",
"=",
"archiveAndSHA256",
"(",
"w",
",",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"version",
".",
"Binary",
"{",
"}",
",",
"false",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"tvers",
",",
"official",
",",
"sha256hash",
",",
"err",
"\n",
"}"
] | // bundleTools bundles all the current juju tools in gzipped tar
// format to the given writer. If forceVersion is not nil and the
// file isn't an official build, a FORCE-VERSION file is included in
// the tools bundle so it will lie about its current version number. | [
"bundleTools",
"bundles",
"all",
"the",
"current",
"juju",
"tools",
"in",
"gzipped",
"tar",
"format",
"to",
"the",
"given",
"writer",
".",
"If",
"forceVersion",
"is",
"not",
"nil",
"and",
"the",
"file",
"isn",
"t",
"an",
"official",
"build",
"a",
"FORCE",
"-",
"VERSION",
"file",
"is",
"included",
"in",
"the",
"tools",
"bundle",
"so",
"it",
"will",
"lie",
"about",
"its",
"current",
"version",
"number",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/build.go#L268-L296 |
5,268 | juju/juju | environs/tools/build.go | JujudVersion | func JujudVersion(dir string) (version.Binary, bool, error) {
tvers, err := getVersionFromFile(dir)
official := err == nil
if err != nil && !errors.IsNotFound(err) && !isNoMatchingToolsChecksum(err) {
return version.Binary{}, false, errors.Trace(err)
}
if errors.IsNotFound(err) || isNoMatchingToolsChecksum(err) {
// No signature file found.
// Extract the version number that the jujud binary was built with.
// This is used to check compatibility with the version of the client
// being used to bootstrap.
tvers, err = getVersionFromJujud(dir)
if err != nil {
return version.Binary{}, false, errors.Trace(err)
}
}
return tvers, official, nil
} | go | func JujudVersion(dir string) (version.Binary, bool, error) {
tvers, err := getVersionFromFile(dir)
official := err == nil
if err != nil && !errors.IsNotFound(err) && !isNoMatchingToolsChecksum(err) {
return version.Binary{}, false, errors.Trace(err)
}
if errors.IsNotFound(err) || isNoMatchingToolsChecksum(err) {
// No signature file found.
// Extract the version number that the jujud binary was built with.
// This is used to check compatibility with the version of the client
// being used to bootstrap.
tvers, err = getVersionFromJujud(dir)
if err != nil {
return version.Binary{}, false, errors.Trace(err)
}
}
return tvers, official, nil
} | [
"func",
"JujudVersion",
"(",
"dir",
"string",
")",
"(",
"version",
".",
"Binary",
",",
"bool",
",",
"error",
")",
"{",
"tvers",
",",
"err",
":=",
"getVersionFromFile",
"(",
"dir",
")",
"\n",
"official",
":=",
"err",
"==",
"nil",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"&&",
"!",
"isNoMatchingToolsChecksum",
"(",
"err",
")",
"{",
"return",
"version",
".",
"Binary",
"{",
"}",
",",
"false",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"errors",
".",
"IsNotFound",
"(",
"err",
")",
"||",
"isNoMatchingToolsChecksum",
"(",
"err",
")",
"{",
"// No signature file found.",
"// Extract the version number that the jujud binary was built with.",
"// This is used to check compatibility with the version of the client",
"// being used to bootstrap.",
"tvers",
",",
"err",
"=",
"getVersionFromJujud",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"version",
".",
"Binary",
"{",
"}",
",",
"false",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"tvers",
",",
"official",
",",
"nil",
"\n",
"}"
] | // JujudVersion returns the Jujud version at the specified location,
// and whether it is an official binary. | [
"JujudVersion",
"returns",
"the",
"Jujud",
"version",
"at",
"the",
"specified",
"location",
"and",
"whether",
"it",
"is",
"an",
"official",
"binary",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/build.go#L320-L337 |
5,269 | juju/juju | service/agent.go | AgentConf | func AgentConf(info AgentInfo, renderer shell.Renderer) common.Conf {
conf := common.Conf{
Desc: fmt.Sprintf("juju agent for %s", info.name),
ExecStart: info.cmd(renderer),
Logfile: info.logFile(renderer),
Env: osenv.FeatureFlags(),
Timeout: agentServiceTimeout,
ServiceBinary: info.jujud(renderer),
ServiceArgs: info.execArgs(renderer),
}
switch info.Kind {
case AgentKindMachine:
conf.Limit = map[string]string{
"nofile": "64000",
}
case AgentKindUnit:
conf.Desc = "juju unit agent for " + info.ID
}
return conf
} | go | func AgentConf(info AgentInfo, renderer shell.Renderer) common.Conf {
conf := common.Conf{
Desc: fmt.Sprintf("juju agent for %s", info.name),
ExecStart: info.cmd(renderer),
Logfile: info.logFile(renderer),
Env: osenv.FeatureFlags(),
Timeout: agentServiceTimeout,
ServiceBinary: info.jujud(renderer),
ServiceArgs: info.execArgs(renderer),
}
switch info.Kind {
case AgentKindMachine:
conf.Limit = map[string]string{
"nofile": "64000",
}
case AgentKindUnit:
conf.Desc = "juju unit agent for " + info.ID
}
return conf
} | [
"func",
"AgentConf",
"(",
"info",
"AgentInfo",
",",
"renderer",
"shell",
".",
"Renderer",
")",
"common",
".",
"Conf",
"{",
"conf",
":=",
"common",
".",
"Conf",
"{",
"Desc",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"info",
".",
"name",
")",
",",
"ExecStart",
":",
"info",
".",
"cmd",
"(",
"renderer",
")",
",",
"Logfile",
":",
"info",
".",
"logFile",
"(",
"renderer",
")",
",",
"Env",
":",
"osenv",
".",
"FeatureFlags",
"(",
")",
",",
"Timeout",
":",
"agentServiceTimeout",
",",
"ServiceBinary",
":",
"info",
".",
"jujud",
"(",
"renderer",
")",
",",
"ServiceArgs",
":",
"info",
".",
"execArgs",
"(",
"renderer",
")",
",",
"}",
"\n\n",
"switch",
"info",
".",
"Kind",
"{",
"case",
"AgentKindMachine",
":",
"conf",
".",
"Limit",
"=",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"}",
"\n",
"case",
"AgentKindUnit",
":",
"conf",
".",
"Desc",
"=",
"\"",
"\"",
"+",
"info",
".",
"ID",
"\n",
"}",
"\n\n",
"return",
"conf",
"\n",
"}"
] | // AgentConf returns the data that defines an init service config
// for the identified agent. | [
"AgentConf",
"returns",
"the",
"data",
"that",
"defines",
"an",
"init",
"service",
"config",
"for",
"the",
"identified",
"agent",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/agent.go#L22-L43 |
5,270 | juju/juju | service/agent.go | ShutdownAfterConf | func ShutdownAfterConf(serviceName string) (common.Conf, error) {
if serviceName == "" {
return common.Conf{}, errors.New(`missing "after" service name`)
}
desc := "juju shutdown job"
return shutdownAfterConf(serviceName, desc), nil
} | go | func ShutdownAfterConf(serviceName string) (common.Conf, error) {
if serviceName == "" {
return common.Conf{}, errors.New(`missing "after" service name`)
}
desc := "juju shutdown job"
return shutdownAfterConf(serviceName, desc), nil
} | [
"func",
"ShutdownAfterConf",
"(",
"serviceName",
"string",
")",
"(",
"common",
".",
"Conf",
",",
"error",
")",
"{",
"if",
"serviceName",
"==",
"\"",
"\"",
"{",
"return",
"common",
".",
"Conf",
"{",
"}",
",",
"errors",
".",
"New",
"(",
"`missing \"after\" service name`",
")",
"\n",
"}",
"\n",
"desc",
":=",
"\"",
"\"",
"\n",
"return",
"shutdownAfterConf",
"(",
"serviceName",
",",
"desc",
")",
",",
"nil",
"\n",
"}"
] | // ShutdownAfterConf builds a service conf that will cause the host to
// shut down after the named service stops. | [
"ShutdownAfterConf",
"builds",
"a",
"service",
"conf",
"that",
"will",
"cause",
"the",
"host",
"to",
"shut",
"down",
"after",
"the",
"named",
"service",
"stops",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/agent.go#L68-L74 |
5,271 | juju/juju | worker/instancepoller/aggregate.go | instInfo | func (a *aggregator) instInfo(id instance.Id, inst instances.Instance) (instanceInfo, error) {
if inst == nil {
return instanceInfo{}, errors.NotFoundf("instance %v", id)
}
addr, err := inst.Addresses(a.callContext)
if err != nil {
return instanceInfo{}, err
}
return instanceInfo{
addr,
inst.Status(a.callContext),
}, nil
} | go | func (a *aggregator) instInfo(id instance.Id, inst instances.Instance) (instanceInfo, error) {
if inst == nil {
return instanceInfo{}, errors.NotFoundf("instance %v", id)
}
addr, err := inst.Addresses(a.callContext)
if err != nil {
return instanceInfo{}, err
}
return instanceInfo{
addr,
inst.Status(a.callContext),
}, nil
} | [
"func",
"(",
"a",
"*",
"aggregator",
")",
"instInfo",
"(",
"id",
"instance",
".",
"Id",
",",
"inst",
"instances",
".",
"Instance",
")",
"(",
"instanceInfo",
",",
"error",
")",
"{",
"if",
"inst",
"==",
"nil",
"{",
"return",
"instanceInfo",
"{",
"}",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"}",
"\n",
"addr",
",",
"err",
":=",
"inst",
".",
"Addresses",
"(",
"a",
".",
"callContext",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"instanceInfo",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"instanceInfo",
"{",
"addr",
",",
"inst",
".",
"Status",
"(",
"a",
".",
"callContext",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // instInfo returns the instance info for the given id
// and instance. If inst is nil, it returns a not-found error. | [
"instInfo",
"returns",
"the",
"instance",
"info",
"for",
"the",
"given",
"id",
"and",
"instance",
".",
"If",
"inst",
"is",
"nil",
"it",
"returns",
"a",
"not",
"-",
"found",
"error",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancepoller/aggregate.go#L160-L172 |
5,272 | juju/juju | worker/periodicworker.go | Reset | func (t *Timer) Reset(d time.Duration) bool {
return t.timer.Reset(d)
} | go | func (t *Timer) Reset(d time.Duration) bool {
return t.timer.Reset(d)
} | [
"func",
"(",
"t",
"*",
"Timer",
")",
"Reset",
"(",
"d",
"time",
".",
"Duration",
")",
"bool",
"{",
"return",
"t",
".",
"timer",
".",
"Reset",
"(",
"d",
")",
"\n",
"}"
] | // Reset implements PeriodicTimer. | [
"Reset",
"implements",
"PeriodicTimer",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/periodicworker.go#L66-L68 |
5,273 | juju/juju | worker/peergrouper/initiate.go | InitiateMongoServer | func InitiateMongoServer(p InitiateMongoParams) error {
logger.Debugf("Initiating mongo replicaset; dialInfo %#v; memberHostport %q; user %q; password %q", p.DialInfo, p.MemberHostPort, p.User, p.Password)
defer logger.Infof("finished InitiateMongoServer")
if len(p.DialInfo.Addrs) > 1 {
logger.Infof("more than one member; replica set must be already initiated")
return nil
}
p.DialInfo.Direct = true
// Initiate may fail while mongo is initialising, so we retry until
// we successfully populate the replicaset config.
var err error
for attempt := initiateAttemptStrategy.Start(); attempt.Next(); {
err = attemptInitiateMongoServer(p.DialInfo, p.MemberHostPort)
if err == nil {
logger.Infof("replica set initiated")
return err
}
if attempt.HasNext() {
logger.Debugf("replica set initiation failed, will retry: %v", err)
}
}
return errors.Annotatef(err, "cannot initiate replica set")
} | go | func InitiateMongoServer(p InitiateMongoParams) error {
logger.Debugf("Initiating mongo replicaset; dialInfo %#v; memberHostport %q; user %q; password %q", p.DialInfo, p.MemberHostPort, p.User, p.Password)
defer logger.Infof("finished InitiateMongoServer")
if len(p.DialInfo.Addrs) > 1 {
logger.Infof("more than one member; replica set must be already initiated")
return nil
}
p.DialInfo.Direct = true
// Initiate may fail while mongo is initialising, so we retry until
// we successfully populate the replicaset config.
var err error
for attempt := initiateAttemptStrategy.Start(); attempt.Next(); {
err = attemptInitiateMongoServer(p.DialInfo, p.MemberHostPort)
if err == nil {
logger.Infof("replica set initiated")
return err
}
if attempt.HasNext() {
logger.Debugf("replica set initiation failed, will retry: %v", err)
}
}
return errors.Annotatef(err, "cannot initiate replica set")
} | [
"func",
"InitiateMongoServer",
"(",
"p",
"InitiateMongoParams",
")",
"error",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"p",
".",
"DialInfo",
",",
"p",
".",
"MemberHostPort",
",",
"p",
".",
"User",
",",
"p",
".",
"Password",
")",
"\n",
"defer",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"len",
"(",
"p",
".",
"DialInfo",
".",
"Addrs",
")",
">",
"1",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"p",
".",
"DialInfo",
".",
"Direct",
"=",
"true",
"\n\n",
"// Initiate may fail while mongo is initialising, so we retry until",
"// we successfully populate the replicaset config.",
"var",
"err",
"error",
"\n",
"for",
"attempt",
":=",
"initiateAttemptStrategy",
".",
"Start",
"(",
")",
";",
"attempt",
".",
"Next",
"(",
")",
";",
"{",
"err",
"=",
"attemptInitiateMongoServer",
"(",
"p",
".",
"DialInfo",
",",
"p",
".",
"MemberHostPort",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"if",
"attempt",
".",
"HasNext",
"(",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // InitiateMongoServer checks for an existing mongo configuration.
// If no existing configuration is found one is created using Initiate. | [
"InitiateMongoServer",
"checks",
"for",
"an",
"existing",
"mongo",
"configuration",
".",
"If",
"no",
"existing",
"configuration",
"is",
"found",
"one",
"is",
"created",
"using",
"Initiate",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/initiate.go#L41-L65 |
5,274 | juju/juju | worker/peergrouper/initiate.go | attemptInitiateMongoServer | func attemptInitiateMongoServer(dialInfo *mgo.DialInfo, memberHostPort string) error {
session, err := mgo.DialWithInfo(dialInfo)
if err != nil {
return errors.Annotatef(err, "cannot dial mongo to initiate replicaset")
}
defer session.Close()
session.SetSocketTimeout(mongo.SocketTimeout)
return replicaset.Initiate(
session,
memberHostPort,
mongo.ReplicaSetName,
map[string]string{
jujuMachineKey: agent.BootstrapMachineId,
},
)
} | go | func attemptInitiateMongoServer(dialInfo *mgo.DialInfo, memberHostPort string) error {
session, err := mgo.DialWithInfo(dialInfo)
if err != nil {
return errors.Annotatef(err, "cannot dial mongo to initiate replicaset")
}
defer session.Close()
session.SetSocketTimeout(mongo.SocketTimeout)
return replicaset.Initiate(
session,
memberHostPort,
mongo.ReplicaSetName,
map[string]string{
jujuMachineKey: agent.BootstrapMachineId,
},
)
} | [
"func",
"attemptInitiateMongoServer",
"(",
"dialInfo",
"*",
"mgo",
".",
"DialInfo",
",",
"memberHostPort",
"string",
")",
"error",
"{",
"session",
",",
"err",
":=",
"mgo",
".",
"DialWithInfo",
"(",
"dialInfo",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"session",
".",
"Close",
"(",
")",
"\n",
"session",
".",
"SetSocketTimeout",
"(",
"mongo",
".",
"SocketTimeout",
")",
"\n\n",
"return",
"replicaset",
".",
"Initiate",
"(",
"session",
",",
"memberHostPort",
",",
"mongo",
".",
"ReplicaSetName",
",",
"map",
"[",
"string",
"]",
"string",
"{",
"jujuMachineKey",
":",
"agent",
".",
"BootstrapMachineId",
",",
"}",
",",
")",
"\n",
"}"
] | // attemptInitiateMongoServer attempts to initiate the replica set. | [
"attemptInitiateMongoServer",
"attempts",
"to",
"initiate",
"the",
"replica",
"set",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/initiate.go#L68-L84 |
5,275 | juju/juju | state/backups/restore.go | resetReplicaSet | func resetReplicaSet(dialInfo *mgo.DialInfo, memberHostPort string) error {
params := peergrouper.InitiateMongoParams{
DialInfo: dialInfo,
MemberHostPort: memberHostPort,
User: dialInfo.Username,
Password: dialInfo.Password,
}
return peergrouper.InitiateMongoServer(params)
} | go | func resetReplicaSet(dialInfo *mgo.DialInfo, memberHostPort string) error {
params := peergrouper.InitiateMongoParams{
DialInfo: dialInfo,
MemberHostPort: memberHostPort,
User: dialInfo.Username,
Password: dialInfo.Password,
}
return peergrouper.InitiateMongoServer(params)
} | [
"func",
"resetReplicaSet",
"(",
"dialInfo",
"*",
"mgo",
".",
"DialInfo",
",",
"memberHostPort",
"string",
")",
"error",
"{",
"params",
":=",
"peergrouper",
".",
"InitiateMongoParams",
"{",
"DialInfo",
":",
"dialInfo",
",",
"MemberHostPort",
":",
"memberHostPort",
",",
"User",
":",
"dialInfo",
".",
"Username",
",",
"Password",
":",
"dialInfo",
".",
"Password",
",",
"}",
"\n",
"return",
"peergrouper",
".",
"InitiateMongoServer",
"(",
"params",
")",
"\n",
"}"
] | // resetReplicaSet re-initiates replica-set using the new controller
// values, this is required after a mongo restore.
// In case of failure returns error. | [
"resetReplicaSet",
"re",
"-",
"initiates",
"replica",
"-",
"set",
"using",
"the",
"new",
"controller",
"values",
"this",
"is",
"required",
"after",
"a",
"mongo",
"restore",
".",
"In",
"case",
"of",
"failure",
"returns",
"error",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/restore.go#L37-L45 |
5,276 | juju/juju | state/backups/restore.go | tagUserCredentials | func tagUserCredentials(conf agent.Config) (string, string, error) {
username := conf.Tag().String()
var password string
// TODO(perrito) we might need an accessor for the actual state password
// just in case it ever changes from the same as api password.
apiInfo, ok := conf.APIInfo()
if ok {
password = apiInfo.Password
} else {
// There seems to be no way to reach this inconsistence other than making a
// backup on a machine where these fields are corrupted and even so I find
// no reasonable way to reach this state, yet since APIInfo has it as a
// possibility I prefer to handle it, we cannot recover from this since
// it would mean that the agent.conf is corrupted.
return "", "", errors.New("cannot obtain password to access the controller")
}
return username, password, nil
} | go | func tagUserCredentials(conf agent.Config) (string, string, error) {
username := conf.Tag().String()
var password string
// TODO(perrito) we might need an accessor for the actual state password
// just in case it ever changes from the same as api password.
apiInfo, ok := conf.APIInfo()
if ok {
password = apiInfo.Password
} else {
// There seems to be no way to reach this inconsistence other than making a
// backup on a machine where these fields are corrupted and even so I find
// no reasonable way to reach this state, yet since APIInfo has it as a
// possibility I prefer to handle it, we cannot recover from this since
// it would mean that the agent.conf is corrupted.
return "", "", errors.New("cannot obtain password to access the controller")
}
return username, password, nil
} | [
"func",
"tagUserCredentials",
"(",
"conf",
"agent",
".",
"Config",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"username",
":=",
"conf",
".",
"Tag",
"(",
")",
".",
"String",
"(",
")",
"\n",
"var",
"password",
"string",
"\n",
"// TODO(perrito) we might need an accessor for the actual state password",
"// just in case it ever changes from the same as api password.",
"apiInfo",
",",
"ok",
":=",
"conf",
".",
"APIInfo",
"(",
")",
"\n",
"if",
"ok",
"{",
"password",
"=",
"apiInfo",
".",
"Password",
"\n",
"}",
"else",
"{",
"// There seems to be no way to reach this inconsistence other than making a",
"// backup on a machine where these fields are corrupted and even so I find",
"// no reasonable way to reach this state, yet since APIInfo has it as a",
"// possibility I prefer to handle it, we cannot recover from this since",
"// it would mean that the agent.conf is corrupted.",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"username",
",",
"password",
",",
"nil",
"\n",
"}"
] | // tagUserCredentials is a convenience function that extracts the
// tag user and apipassword, required to access mongodb. | [
"tagUserCredentials",
"is",
"a",
"convenience",
"function",
"that",
"extracts",
"the",
"tag",
"user",
"and",
"apipassword",
"required",
"to",
"access",
"mongodb",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/restore.go#L55-L72 |
5,277 | juju/juju | state/backups/restore.go | newDialInfo | func newDialInfo(privateAddr string, conf agent.Config) (*mgo.DialInfo, error) {
dialOpts := mongo.DialOpts{Direct: true}
ssi, ok := conf.StateServingInfo()
if !ok {
return nil, errors.Errorf("cannot get state serving info to dial")
}
info := mongo.Info{
Addrs: []string{net.JoinHostPort(privateAddr, strconv.Itoa(ssi.StatePort))},
CACert: conf.CACert(),
}
dialInfo, err := mongo.DialInfo(info, dialOpts)
if err != nil {
return nil, errors.Annotate(err, "cannot produce a dial info")
}
oldPassword := conf.OldPassword()
if oldPassword != "" {
dialInfo.Username = "admin"
dialInfo.Password = conf.OldPassword()
} else {
dialInfo.Username, dialInfo.Password, err = tagUserCredentials(conf)
if err != nil {
return nil, errors.Trace(err)
}
}
return dialInfo, nil
} | go | func newDialInfo(privateAddr string, conf agent.Config) (*mgo.DialInfo, error) {
dialOpts := mongo.DialOpts{Direct: true}
ssi, ok := conf.StateServingInfo()
if !ok {
return nil, errors.Errorf("cannot get state serving info to dial")
}
info := mongo.Info{
Addrs: []string{net.JoinHostPort(privateAddr, strconv.Itoa(ssi.StatePort))},
CACert: conf.CACert(),
}
dialInfo, err := mongo.DialInfo(info, dialOpts)
if err != nil {
return nil, errors.Annotate(err, "cannot produce a dial info")
}
oldPassword := conf.OldPassword()
if oldPassword != "" {
dialInfo.Username = "admin"
dialInfo.Password = conf.OldPassword()
} else {
dialInfo.Username, dialInfo.Password, err = tagUserCredentials(conf)
if err != nil {
return nil, errors.Trace(err)
}
}
return dialInfo, nil
} | [
"func",
"newDialInfo",
"(",
"privateAddr",
"string",
",",
"conf",
"agent",
".",
"Config",
")",
"(",
"*",
"mgo",
".",
"DialInfo",
",",
"error",
")",
"{",
"dialOpts",
":=",
"mongo",
".",
"DialOpts",
"{",
"Direct",
":",
"true",
"}",
"\n",
"ssi",
",",
"ok",
":=",
"conf",
".",
"StateServingInfo",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"info",
":=",
"mongo",
".",
"Info",
"{",
"Addrs",
":",
"[",
"]",
"string",
"{",
"net",
".",
"JoinHostPort",
"(",
"privateAddr",
",",
"strconv",
".",
"Itoa",
"(",
"ssi",
".",
"StatePort",
")",
")",
"}",
",",
"CACert",
":",
"conf",
".",
"CACert",
"(",
")",
",",
"}",
"\n",
"dialInfo",
",",
"err",
":=",
"mongo",
".",
"DialInfo",
"(",
"info",
",",
"dialOpts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"oldPassword",
":=",
"conf",
".",
"OldPassword",
"(",
")",
"\n",
"if",
"oldPassword",
"!=",
"\"",
"\"",
"{",
"dialInfo",
".",
"Username",
"=",
"\"",
"\"",
"\n",
"dialInfo",
".",
"Password",
"=",
"conf",
".",
"OldPassword",
"(",
")",
"\n",
"}",
"else",
"{",
"dialInfo",
".",
"Username",
",",
"dialInfo",
".",
"Password",
",",
"err",
"=",
"tagUserCredentials",
"(",
"conf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"dialInfo",
",",
"nil",
"\n",
"}"
] | // newDialInfo returns mgo.DialInfo with the given address using the minimal
// possible setup. | [
"newDialInfo",
"returns",
"mgo",
".",
"DialInfo",
"with",
"the",
"given",
"address",
"using",
"the",
"minimal",
"possible",
"setup",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/restore.go#L76-L101 |
5,278 | juju/juju | state/backups/restore.go | updateMachineAddresses | func updateMachineAddresses(machine *state.Machine, privateAddress, publicAddress string) error {
privateAddressAddress := network.Address{
Value: privateAddress,
Type: network.DeriveAddressType(privateAddress),
}
publicAddressAddress := network.Address{
Value: publicAddress,
Type: network.DeriveAddressType(publicAddress),
}
if err := machine.SetProviderAddresses(publicAddressAddress, privateAddressAddress); err != nil {
return errors.Trace(err)
}
return nil
} | go | func updateMachineAddresses(machine *state.Machine, privateAddress, publicAddress string) error {
privateAddressAddress := network.Address{
Value: privateAddress,
Type: network.DeriveAddressType(privateAddress),
}
publicAddressAddress := network.Address{
Value: publicAddress,
Type: network.DeriveAddressType(publicAddress),
}
if err := machine.SetProviderAddresses(publicAddressAddress, privateAddressAddress); err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"updateMachineAddresses",
"(",
"machine",
"*",
"state",
".",
"Machine",
",",
"privateAddress",
",",
"publicAddress",
"string",
")",
"error",
"{",
"privateAddressAddress",
":=",
"network",
".",
"Address",
"{",
"Value",
":",
"privateAddress",
",",
"Type",
":",
"network",
".",
"DeriveAddressType",
"(",
"privateAddress",
")",
",",
"}",
"\n",
"publicAddressAddress",
":=",
"network",
".",
"Address",
"{",
"Value",
":",
"publicAddress",
",",
"Type",
":",
"network",
".",
"DeriveAddressType",
"(",
"publicAddress",
")",
",",
"}",
"\n",
"if",
"err",
":=",
"machine",
".",
"SetProviderAddresses",
"(",
"publicAddressAddress",
",",
"privateAddressAddress",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // updateMachineAddresses will update the machine doc to the current addresses | [
"updateMachineAddresses",
"will",
"update",
"the",
"machine",
"doc",
"to",
"the",
"current",
"addresses"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/restore.go#L124-L137 |
5,279 | juju/juju | state/backups/restore.go | connectToDB | func connectToDB(controllerTag names.ControllerTag, modelTag names.ModelTag, info *mongo.MongoInfo) (*state.StatePool, error) {
// We need to retry here to allow mongo to come up on the restored controller.
// The connection might succeed due to the mongo dial retries but there may still
// be a problem issuing database commands.
var (
pool *state.StatePool
err error
)
const (
newStateConnDelay = 15 * time.Second
newStateConnMinAttempts = 8
)
// TODO(katco): 2016-08-09: lp:1611427
attempt := utils.AttemptStrategy{Delay: newStateConnDelay, Min: newStateConnMinAttempts}
session, err := mongo.DialWithInfo(*info, mongoDefaultDialOpts())
if err != nil {
return nil, errors.Trace(err)
}
defer session.Close()
for a := attempt.Start(); a.Next(); {
pool, err = state.OpenStatePool(state.OpenParams{
Clock: clock.WallClock,
ControllerTag: controllerTag,
ControllerModelTag: modelTag,
MongoSession: session,
NewPolicy: environsGetNewPolicyFunc(),
})
if err == nil {
return pool, nil
}
logger.Errorf("cannot open state, retrying: %v", err)
}
return nil, errors.Annotate(err, "cannot open state")
} | go | func connectToDB(controllerTag names.ControllerTag, modelTag names.ModelTag, info *mongo.MongoInfo) (*state.StatePool, error) {
// We need to retry here to allow mongo to come up on the restored controller.
// The connection might succeed due to the mongo dial retries but there may still
// be a problem issuing database commands.
var (
pool *state.StatePool
err error
)
const (
newStateConnDelay = 15 * time.Second
newStateConnMinAttempts = 8
)
// TODO(katco): 2016-08-09: lp:1611427
attempt := utils.AttemptStrategy{Delay: newStateConnDelay, Min: newStateConnMinAttempts}
session, err := mongo.DialWithInfo(*info, mongoDefaultDialOpts())
if err != nil {
return nil, errors.Trace(err)
}
defer session.Close()
for a := attempt.Start(); a.Next(); {
pool, err = state.OpenStatePool(state.OpenParams{
Clock: clock.WallClock,
ControllerTag: controllerTag,
ControllerModelTag: modelTag,
MongoSession: session,
NewPolicy: environsGetNewPolicyFunc(),
})
if err == nil {
return pool, nil
}
logger.Errorf("cannot open state, retrying: %v", err)
}
return nil, errors.Annotate(err, "cannot open state")
} | [
"func",
"connectToDB",
"(",
"controllerTag",
"names",
".",
"ControllerTag",
",",
"modelTag",
"names",
".",
"ModelTag",
",",
"info",
"*",
"mongo",
".",
"MongoInfo",
")",
"(",
"*",
"state",
".",
"StatePool",
",",
"error",
")",
"{",
"// We need to retry here to allow mongo to come up on the restored controller.",
"// The connection might succeed due to the mongo dial retries but there may still",
"// be a problem issuing database commands.",
"var",
"(",
"pool",
"*",
"state",
".",
"StatePool",
"\n",
"err",
"error",
"\n",
")",
"\n",
"const",
"(",
"newStateConnDelay",
"=",
"15",
"*",
"time",
".",
"Second",
"\n",
"newStateConnMinAttempts",
"=",
"8",
"\n",
")",
"\n",
"// TODO(katco): 2016-08-09: lp:1611427",
"attempt",
":=",
"utils",
".",
"AttemptStrategy",
"{",
"Delay",
":",
"newStateConnDelay",
",",
"Min",
":",
"newStateConnMinAttempts",
"}",
"\n\n",
"session",
",",
"err",
":=",
"mongo",
".",
"DialWithInfo",
"(",
"*",
"info",
",",
"mongoDefaultDialOpts",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"session",
".",
"Close",
"(",
")",
"\n\n",
"for",
"a",
":=",
"attempt",
".",
"Start",
"(",
")",
";",
"a",
".",
"Next",
"(",
")",
";",
"{",
"pool",
",",
"err",
"=",
"state",
".",
"OpenStatePool",
"(",
"state",
".",
"OpenParams",
"{",
"Clock",
":",
"clock",
".",
"WallClock",
",",
"ControllerTag",
":",
"controllerTag",
",",
"ControllerModelTag",
":",
"modelTag",
",",
"MongoSession",
":",
"session",
",",
"NewPolicy",
":",
"environsGetNewPolicyFunc",
"(",
")",
",",
"}",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"pool",
",",
"nil",
"\n",
"}",
"\n",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // connectToDB tries to connect to the newly restored controller. | [
"connectToDB",
"tries",
"to",
"connect",
"to",
"the",
"newly",
"restored",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/restore.go#L144-L179 |
5,280 | juju/juju | state/backups/restore.go | updateAllMachines | func updateAllMachines(privateAddress, publicAddress string, machines []machineModel) error {
var machineUpdating sync.WaitGroup
for _, item := range machines {
machine := item.machine
// A newly resumed controller requires no updating, and more
// than one controller is not yet supported by this code.
if machine.IsManager() || machine.Life() == state.Dead {
continue
}
machineUpdating.Add(1)
go func(machine *state.Machine, model *state.Model) {
defer machineUpdating.Done()
logger.Debugf("updating addresses for machine %s in model %s/%s", machine.Tag().Id(), model.Owner().Id(), model.Name())
// TODO: thumper 2016-09-20
// runMachineUpdate only handles linux machines, what about windows?
err := runMachineUpdate(machine, setAgentAddressScript(privateAddress, publicAddress))
if err != nil {
logger.Errorf("failed updating machine: %v", err)
}
}(machine, item.model)
}
machineUpdating.Wait()
// We should return errors encapsulated in a digest.
return nil
} | go | func updateAllMachines(privateAddress, publicAddress string, machines []machineModel) error {
var machineUpdating sync.WaitGroup
for _, item := range machines {
machine := item.machine
// A newly resumed controller requires no updating, and more
// than one controller is not yet supported by this code.
if machine.IsManager() || machine.Life() == state.Dead {
continue
}
machineUpdating.Add(1)
go func(machine *state.Machine, model *state.Model) {
defer machineUpdating.Done()
logger.Debugf("updating addresses for machine %s in model %s/%s", machine.Tag().Id(), model.Owner().Id(), model.Name())
// TODO: thumper 2016-09-20
// runMachineUpdate only handles linux machines, what about windows?
err := runMachineUpdate(machine, setAgentAddressScript(privateAddress, publicAddress))
if err != nil {
logger.Errorf("failed updating machine: %v", err)
}
}(machine, item.model)
}
machineUpdating.Wait()
// We should return errors encapsulated in a digest.
return nil
} | [
"func",
"updateAllMachines",
"(",
"privateAddress",
",",
"publicAddress",
"string",
",",
"machines",
"[",
"]",
"machineModel",
")",
"error",
"{",
"var",
"machineUpdating",
"sync",
".",
"WaitGroup",
"\n",
"for",
"_",
",",
"item",
":=",
"range",
"machines",
"{",
"machine",
":=",
"item",
".",
"machine",
"\n",
"// A newly resumed controller requires no updating, and more",
"// than one controller is not yet supported by this code.",
"if",
"machine",
".",
"IsManager",
"(",
")",
"||",
"machine",
".",
"Life",
"(",
")",
"==",
"state",
".",
"Dead",
"{",
"continue",
"\n",
"}",
"\n",
"machineUpdating",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"machine",
"*",
"state",
".",
"Machine",
",",
"model",
"*",
"state",
".",
"Model",
")",
"{",
"defer",
"machineUpdating",
".",
"Done",
"(",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"machine",
".",
"Tag",
"(",
")",
".",
"Id",
"(",
")",
",",
"model",
".",
"Owner",
"(",
")",
".",
"Id",
"(",
")",
",",
"model",
".",
"Name",
"(",
")",
")",
"\n",
"// TODO: thumper 2016-09-20",
"// runMachineUpdate only handles linux machines, what about windows?",
"err",
":=",
"runMachineUpdate",
"(",
"machine",
",",
"setAgentAddressScript",
"(",
"privateAddress",
",",
"publicAddress",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
"machine",
",",
"item",
".",
"model",
")",
"\n",
"}",
"\n",
"machineUpdating",
".",
"Wait",
"(",
")",
"\n\n",
"// We should return errors encapsulated in a digest.",
"return",
"nil",
"\n",
"}"
] | // updateAllMachines finds all machines and resets the stored state address
// in each of them. The address does not include the port.
// It is too late to go back and errors in a couple of agents have
// better chance of being fixed by the user, if we were to fail
// we risk an inconsistent controller because of one unresponsive
// agent, we should nevertheless return the err info to the user. | [
"updateAllMachines",
"finds",
"all",
"machines",
"and",
"resets",
"the",
"stored",
"state",
"address",
"in",
"each",
"of",
"them",
".",
"The",
"address",
"does",
"not",
"include",
"the",
"port",
".",
"It",
"is",
"too",
"late",
"to",
"go",
"back",
"and",
"errors",
"in",
"a",
"couple",
"of",
"agents",
"have",
"better",
"chance",
"of",
"being",
"fixed",
"by",
"the",
"user",
"if",
"we",
"were",
"to",
"fail",
"we",
"risk",
"an",
"inconsistent",
"controller",
"because",
"of",
"one",
"unresponsive",
"agent",
"we",
"should",
"nevertheless",
"return",
"the",
"err",
"info",
"to",
"the",
"user",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/restore.go#L192-L217 |
5,281 | juju/juju | state/backups/restore.go | setAgentAddressScript | func setAgentAddressScript(stateAddr, statePubAddr string) string {
var buf bytes.Buffer
err := agentAddressAndRelationsTemplate.Execute(&buf, struct {
Address string
PubAddress string
}{stateAddr, statePubAddr})
if err != nil {
panic(errors.Annotate(err, "template error"))
}
return buf.String()
} | go | func setAgentAddressScript(stateAddr, statePubAddr string) string {
var buf bytes.Buffer
err := agentAddressAndRelationsTemplate.Execute(&buf, struct {
Address string
PubAddress string
}{stateAddr, statePubAddr})
if err != nil {
panic(errors.Annotate(err, "template error"))
}
return buf.String()
} | [
"func",
"setAgentAddressScript",
"(",
"stateAddr",
",",
"statePubAddr",
"string",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"err",
":=",
"agentAddressAndRelationsTemplate",
".",
"Execute",
"(",
"&",
"buf",
",",
"struct",
"{",
"Address",
"string",
"\n",
"PubAddress",
"string",
"\n",
"}",
"{",
"stateAddr",
",",
"statePubAddr",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // setAgentAddressScript generates an ssh script argument to update state addresses. | [
"setAgentAddressScript",
"generates",
"an",
"ssh",
"script",
"argument",
"to",
"update",
"state",
"addresses",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/restore.go#L254-L264 |
5,282 | juju/juju | state/backups/restore.go | runMachineUpdate | func runMachineUpdate(machine *state.Machine, sshArg string) error {
addr, err := machine.PublicAddress()
if err != nil {
if network.IsNoAddressError(err) {
return errors.Annotatef(err, "no appropriate public address found")
}
return errors.Trace(err)
}
return runViaSSH(addr.Value, sshArg)
} | go | func runMachineUpdate(machine *state.Machine, sshArg string) error {
addr, err := machine.PublicAddress()
if err != nil {
if network.IsNoAddressError(err) {
return errors.Annotatef(err, "no appropriate public address found")
}
return errors.Trace(err)
}
return runViaSSH(addr.Value, sshArg)
} | [
"func",
"runMachineUpdate",
"(",
"machine",
"*",
"state",
".",
"Machine",
",",
"sshArg",
"string",
")",
"error",
"{",
"addr",
",",
"err",
":=",
"machine",
".",
"PublicAddress",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"network",
".",
"IsNoAddressError",
"(",
"err",
")",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"runViaSSH",
"(",
"addr",
".",
"Value",
",",
"sshArg",
")",
"\n",
"}"
] | // runMachineUpdate connects via ssh to the machine and runs the update script. | [
"runMachineUpdate",
"connects",
"via",
"ssh",
"to",
"the",
"machine",
"and",
"runs",
"the",
"update",
"script",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/restore.go#L267-L276 |
5,283 | juju/juju | state/backups/restore.go | runViaSSH | func runViaSSH(addr string, script string) error {
sshOptions := ssh.Options{}
sshOptions.SetIdentities("/var/lib/juju/system-identity")
// Disable host key checking. We're not pushing across anything
// sensitive, and there's no guarantee that the machine would
// have published up-to-date host key information.
sshOptions.SetStrictHostKeyChecking(ssh.StrictHostChecksNo)
sshOptions.SetKnownHostsFile(os.DevNull)
userAddr := "ubuntu@" + addr
userCmd := sshCommand(userAddr, []string{"sudo", "-n", "bash", "-c " + utils.ShQuote(script)}, &sshOptions)
var stdoutBuf bytes.Buffer
var stderrBuf bytes.Buffer
userCmd.Stdout = &stdoutBuf
userCmd.Stderr = &stderrBuf
logger.Debugf("updating %s, script:\n%s", addr, script)
if err := userCmd.Run(); err != nil {
return errors.Annotatef(err, "ssh command failed: %q", stderrBuf.String())
}
logger.Debugf("result %s\nstdout: \n%s\nstderr: %s", addr, stdoutBuf.String(), stderrBuf.String())
return nil
} | go | func runViaSSH(addr string, script string) error {
sshOptions := ssh.Options{}
sshOptions.SetIdentities("/var/lib/juju/system-identity")
// Disable host key checking. We're not pushing across anything
// sensitive, and there's no guarantee that the machine would
// have published up-to-date host key information.
sshOptions.SetStrictHostKeyChecking(ssh.StrictHostChecksNo)
sshOptions.SetKnownHostsFile(os.DevNull)
userAddr := "ubuntu@" + addr
userCmd := sshCommand(userAddr, []string{"sudo", "-n", "bash", "-c " + utils.ShQuote(script)}, &sshOptions)
var stdoutBuf bytes.Buffer
var stderrBuf bytes.Buffer
userCmd.Stdout = &stdoutBuf
userCmd.Stderr = &stderrBuf
logger.Debugf("updating %s, script:\n%s", addr, script)
if err := userCmd.Run(); err != nil {
return errors.Annotatef(err, "ssh command failed: %q", stderrBuf.String())
}
logger.Debugf("result %s\nstdout: \n%s\nstderr: %s", addr, stdoutBuf.String(), stderrBuf.String())
return nil
} | [
"func",
"runViaSSH",
"(",
"addr",
"string",
",",
"script",
"string",
")",
"error",
"{",
"sshOptions",
":=",
"ssh",
".",
"Options",
"{",
"}",
"\n",
"sshOptions",
".",
"SetIdentities",
"(",
"\"",
"\"",
")",
"\n",
"// Disable host key checking. We're not pushing across anything",
"// sensitive, and there's no guarantee that the machine would",
"// have published up-to-date host key information.",
"sshOptions",
".",
"SetStrictHostKeyChecking",
"(",
"ssh",
".",
"StrictHostChecksNo",
")",
"\n",
"sshOptions",
".",
"SetKnownHostsFile",
"(",
"os",
".",
"DevNull",
")",
"\n\n",
"userAddr",
":=",
"\"",
"\"",
"+",
"addr",
"\n",
"userCmd",
":=",
"sshCommand",
"(",
"userAddr",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"utils",
".",
"ShQuote",
"(",
"script",
")",
"}",
",",
"&",
"sshOptions",
")",
"\n",
"var",
"stdoutBuf",
"bytes",
".",
"Buffer",
"\n",
"var",
"stderrBuf",
"bytes",
".",
"Buffer",
"\n",
"userCmd",
".",
"Stdout",
"=",
"&",
"stdoutBuf",
"\n",
"userCmd",
".",
"Stderr",
"=",
"&",
"stderrBuf",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"addr",
",",
"script",
")",
"\n",
"if",
"err",
":=",
"userCmd",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
",",
"stderrBuf",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\\n",
"\\n",
"\\n",
"\"",
",",
"addr",
",",
"stdoutBuf",
".",
"String",
"(",
")",
",",
"stderrBuf",
".",
"String",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // runViaSSH runs script in the remote machine with address addr. | [
"runViaSSH",
"runs",
"script",
"in",
"the",
"remote",
"machine",
"with",
"address",
"addr",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/restore.go#L282-L303 |
5,284 | juju/juju | core/instance/placement.go | ParsePlacement | func ParsePlacement(directive string) (*Placement, error) {
if directive == "" {
return nil, nil
}
if colon := strings.IndexRune(directive, ':'); colon != -1 {
scope, directive := directive[:colon], directive[colon+1:]
if scope == "" {
return nil, ErrPlacementScopeMissing
}
// Sanity check: machine/container scopes require a machine ID as the value.
if (scope == MachineScope || isContainerType(scope)) && !names.IsValidMachine(directive) {
return nil, fmt.Errorf("invalid value %q for %q scope: expected machine-id", directive, scope)
}
return &Placement{Scope: scope, Directive: directive}, nil
}
if names.IsValidMachine(directive) {
return &Placement{Scope: MachineScope, Directive: directive}, nil
}
if isContainerType(directive) {
return &Placement{Scope: directive}, nil
}
return nil, ErrPlacementScopeMissing
} | go | func ParsePlacement(directive string) (*Placement, error) {
if directive == "" {
return nil, nil
}
if colon := strings.IndexRune(directive, ':'); colon != -1 {
scope, directive := directive[:colon], directive[colon+1:]
if scope == "" {
return nil, ErrPlacementScopeMissing
}
// Sanity check: machine/container scopes require a machine ID as the value.
if (scope == MachineScope || isContainerType(scope)) && !names.IsValidMachine(directive) {
return nil, fmt.Errorf("invalid value %q for %q scope: expected machine-id", directive, scope)
}
return &Placement{Scope: scope, Directive: directive}, nil
}
if names.IsValidMachine(directive) {
return &Placement{Scope: MachineScope, Directive: directive}, nil
}
if isContainerType(directive) {
return &Placement{Scope: directive}, nil
}
return nil, ErrPlacementScopeMissing
} | [
"func",
"ParsePlacement",
"(",
"directive",
"string",
")",
"(",
"*",
"Placement",
",",
"error",
")",
"{",
"if",
"directive",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"if",
"colon",
":=",
"strings",
".",
"IndexRune",
"(",
"directive",
",",
"':'",
")",
";",
"colon",
"!=",
"-",
"1",
"{",
"scope",
",",
"directive",
":=",
"directive",
"[",
":",
"colon",
"]",
",",
"directive",
"[",
"colon",
"+",
"1",
":",
"]",
"\n",
"if",
"scope",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"ErrPlacementScopeMissing",
"\n",
"}",
"\n",
"// Sanity check: machine/container scopes require a machine ID as the value.",
"if",
"(",
"scope",
"==",
"MachineScope",
"||",
"isContainerType",
"(",
"scope",
")",
")",
"&&",
"!",
"names",
".",
"IsValidMachine",
"(",
"directive",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"directive",
",",
"scope",
")",
"\n",
"}",
"\n",
"return",
"&",
"Placement",
"{",
"Scope",
":",
"scope",
",",
"Directive",
":",
"directive",
"}",
",",
"nil",
"\n",
"}",
"\n",
"if",
"names",
".",
"IsValidMachine",
"(",
"directive",
")",
"{",
"return",
"&",
"Placement",
"{",
"Scope",
":",
"MachineScope",
",",
"Directive",
":",
"directive",
"}",
",",
"nil",
"\n",
"}",
"\n",
"if",
"isContainerType",
"(",
"directive",
")",
"{",
"return",
"&",
"Placement",
"{",
"Scope",
":",
"directive",
"}",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"ErrPlacementScopeMissing",
"\n",
"}"
] | // ParsePlacement attempts to parse the specified string and create a
// corresponding Placement structure.
//
// If the placement directive is non-empty and missing a scope,
// ErrPlacementScopeMissing will be returned as well as a Placement
// with an empty Scope field. | [
"ParsePlacement",
"attempts",
"to",
"parse",
"the",
"specified",
"string",
"and",
"create",
"a",
"corresponding",
"Placement",
"structure",
".",
"If",
"the",
"placement",
"directive",
"is",
"non",
"-",
"empty",
"and",
"missing",
"a",
"scope",
"ErrPlacementScopeMissing",
"will",
"be",
"returned",
"as",
"well",
"as",
"a",
"Placement",
"with",
"an",
"empty",
"Scope",
"field",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/instance/placement.go#L53-L75 |
5,285 | juju/juju | core/instance/placement.go | MustParsePlacement | func MustParsePlacement(directive string) *Placement {
placement, err := ParsePlacement(directive)
if err != nil {
panic(err)
}
return placement
} | go | func MustParsePlacement(directive string) *Placement {
placement, err := ParsePlacement(directive)
if err != nil {
panic(err)
}
return placement
} | [
"func",
"MustParsePlacement",
"(",
"directive",
"string",
")",
"*",
"Placement",
"{",
"placement",
",",
"err",
":=",
"ParsePlacement",
"(",
"directive",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"placement",
"\n",
"}"
] | // MustParsePlacement attempts to parse the specified string and create
// a corresponding Placement structure, panicking if an error occurs. | [
"MustParsePlacement",
"attempts",
"to",
"parse",
"the",
"specified",
"string",
"and",
"create",
"a",
"corresponding",
"Placement",
"structure",
"panicking",
"if",
"an",
"error",
"occurs",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/instance/placement.go#L79-L85 |
5,286 | juju/juju | state/minimumunits.go | SetMinUnits | func (a *Application) SetMinUnits(minUnits int) (err error) {
defer errors.DeferredAnnotatef(&err, "cannot set minimum units for application %q", a)
defer func() {
if err == nil {
a.doc.MinUnits = minUnits
}
}()
if minUnits < 0 {
return errors.New("cannot set a negative minimum number of units")
}
app := &Application{st: a.st, doc: a.doc}
// Removing the document never fails. Racing clients trying to create the
// document generate one failure, but the second attempt should succeed.
// If one client tries to update the document, and a racing client removes
// it, the former should be able to re-create the document in the second
// attempt. If the referred-to application advanced its life cycle to a not
// alive state, an error is returned after the first failing attempt.
buildTxn := func(attempt int) ([]txn.Op, error) {
if attempt > 0 {
if err := app.Refresh(); err != nil {
return nil, err
}
}
if app.doc.Life != Alive {
return nil, errors.New("application is no longer alive")
}
if minUnits == app.doc.MinUnits {
return nil, jujutxn.ErrNoOperations
}
return setMinUnitsOps(app, minUnits), nil
}
return a.st.db().Run(buildTxn)
} | go | func (a *Application) SetMinUnits(minUnits int) (err error) {
defer errors.DeferredAnnotatef(&err, "cannot set minimum units for application %q", a)
defer func() {
if err == nil {
a.doc.MinUnits = minUnits
}
}()
if minUnits < 0 {
return errors.New("cannot set a negative minimum number of units")
}
app := &Application{st: a.st, doc: a.doc}
// Removing the document never fails. Racing clients trying to create the
// document generate one failure, but the second attempt should succeed.
// If one client tries to update the document, and a racing client removes
// it, the former should be able to re-create the document in the second
// attempt. If the referred-to application advanced its life cycle to a not
// alive state, an error is returned after the first failing attempt.
buildTxn := func(attempt int) ([]txn.Op, error) {
if attempt > 0 {
if err := app.Refresh(); err != nil {
return nil, err
}
}
if app.doc.Life != Alive {
return nil, errors.New("application is no longer alive")
}
if minUnits == app.doc.MinUnits {
return nil, jujutxn.ErrNoOperations
}
return setMinUnitsOps(app, minUnits), nil
}
return a.st.db().Run(buildTxn)
} | [
"func",
"(",
"a",
"*",
"Application",
")",
"SetMinUnits",
"(",
"minUnits",
"int",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"errors",
".",
"DeferredAnnotatef",
"(",
"&",
"err",
",",
"\"",
"\"",
",",
"a",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"==",
"nil",
"{",
"a",
".",
"doc",
".",
"MinUnits",
"=",
"minUnits",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"if",
"minUnits",
"<",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"app",
":=",
"&",
"Application",
"{",
"st",
":",
"a",
".",
"st",
",",
"doc",
":",
"a",
".",
"doc",
"}",
"\n",
"// Removing the document never fails. Racing clients trying to create the",
"// document generate one failure, but the second attempt should succeed.",
"// If one client tries to update the document, and a racing client removes",
"// it, the former should be able to re-create the document in the second",
"// attempt. If the referred-to application advanced its life cycle to a not",
"// alive state, an error is returned after the first failing attempt.",
"buildTxn",
":=",
"func",
"(",
"attempt",
"int",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"if",
"attempt",
">",
"0",
"{",
"if",
"err",
":=",
"app",
".",
"Refresh",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"app",
".",
"doc",
".",
"Life",
"!=",
"Alive",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"minUnits",
"==",
"app",
".",
"doc",
".",
"MinUnits",
"{",
"return",
"nil",
",",
"jujutxn",
".",
"ErrNoOperations",
"\n",
"}",
"\n",
"return",
"setMinUnitsOps",
"(",
"app",
",",
"minUnits",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"a",
".",
"st",
".",
"db",
"(",
")",
".",
"Run",
"(",
"buildTxn",
")",
"\n",
"}"
] | // SetMinUnits changes the number of minimum units required by the application. | [
"SetMinUnits",
"changes",
"the",
"number",
"of",
"minimum",
"units",
"required",
"by",
"the",
"application",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/minimumunits.go#L34-L66 |
5,287 | juju/juju | state/minimumunits.go | doesMinUnitsExist | func doesMinUnitsExist(unit *Unit) (bool, error) {
minUnits, closer := unit.st.db().GetCollection(minUnitsC)
defer closer()
var result bson.D
err := minUnits.FindId(unit.ApplicationName()).Select(bson.M{"_id": 1}).One(&result)
if err == nil {
return true, nil
} else if err == mgo.ErrNotFound {
return false, nil
} else {
return false, errors.Trace(err)
}
} | go | func doesMinUnitsExist(unit *Unit) (bool, error) {
minUnits, closer := unit.st.db().GetCollection(minUnitsC)
defer closer()
var result bson.D
err := minUnits.FindId(unit.ApplicationName()).Select(bson.M{"_id": 1}).One(&result)
if err == nil {
return true, nil
} else if err == mgo.ErrNotFound {
return false, nil
} else {
return false, errors.Trace(err)
}
} | [
"func",
"doesMinUnitsExist",
"(",
"unit",
"*",
"Unit",
")",
"(",
"bool",
",",
"error",
")",
"{",
"minUnits",
",",
"closer",
":=",
"unit",
".",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"minUnitsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n",
"var",
"result",
"bson",
".",
"D",
"\n",
"err",
":=",
"minUnits",
".",
"FindId",
"(",
"unit",
".",
"ApplicationName",
"(",
")",
")",
".",
"Select",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"1",
"}",
")",
".",
"One",
"(",
"&",
"result",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"else",
"if",
"err",
"==",
"mgo",
".",
"ErrNotFound",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"else",
"{",
"return",
"false",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // doesMinUnitsExits checks if the minUnits doc exists in the database. | [
"doesMinUnitsExits",
"checks",
"if",
"the",
"minUnits",
"doc",
"exists",
"in",
"the",
"database",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/minimumunits.go#L102-L114 |
5,288 | juju/juju | state/minimumunits.go | minUnitsRemoveOp | func minUnitsRemoveOp(st *State, applicationname string) txn.Op {
return txn.Op{
C: minUnitsC,
Id: st.docID(applicationname),
Remove: true,
}
} | go | func minUnitsRemoveOp(st *State, applicationname string) txn.Op {
return txn.Op{
C: minUnitsC,
Id: st.docID(applicationname),
Remove: true,
}
} | [
"func",
"minUnitsRemoveOp",
"(",
"st",
"*",
"State",
",",
"applicationname",
"string",
")",
"txn",
".",
"Op",
"{",
"return",
"txn",
".",
"Op",
"{",
"C",
":",
"minUnitsC",
",",
"Id",
":",
"st",
".",
"docID",
"(",
"applicationname",
")",
",",
"Remove",
":",
"true",
",",
"}",
"\n",
"}"
] | // minUnitsRemoveOp returns the operation required to remove the minimum
// units document from MongoDB. | [
"minUnitsRemoveOp",
"returns",
"the",
"operation",
"required",
"to",
"remove",
"the",
"minimum",
"units",
"document",
"from",
"MongoDB",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/minimumunits.go#L132-L138 |
5,289 | juju/juju | state/minimumunits.go | EnsureMinUnits | func (a *Application) EnsureMinUnits() (err error) {
defer errors.DeferredAnnotatef(&err, "cannot ensure minimum units for application %q", a)
app := &Application{st: a.st, doc: a.doc}
for {
// Ensure the application is alive.
if app.doc.Life != Alive {
return errors.New("application is not alive")
}
// Exit without errors if the MinUnits for the application is not set.
if app.doc.MinUnits == 0 {
return nil
}
// Retrieve the number of alive units for the application.
aliveUnits, err := aliveUnitsCount(app)
if err != nil {
return err
}
// Calculate the number of required units to be added.
missing := app.doc.MinUnits - aliveUnits
if missing <= 0 {
return nil
}
name, ops, err := ensureMinUnitsOps(app)
if err != nil {
return err
}
// Add missing unit.
switch err := a.st.db().RunTransaction(ops); err {
case nil:
// Assign the new unit.
unit, err := a.st.Unit(name)
if err != nil {
return err
}
if err := app.st.AssignUnit(unit, AssignNew); err != nil {
return err
}
// No need to proceed and refresh the application if this was the
// last/only missing unit.
if missing == 1 {
return nil
}
case txn.ErrAborted:
// Refresh the application and restart the loop.
default:
return err
}
if err := app.Refresh(); err != nil {
return err
}
}
} | go | func (a *Application) EnsureMinUnits() (err error) {
defer errors.DeferredAnnotatef(&err, "cannot ensure minimum units for application %q", a)
app := &Application{st: a.st, doc: a.doc}
for {
// Ensure the application is alive.
if app.doc.Life != Alive {
return errors.New("application is not alive")
}
// Exit without errors if the MinUnits for the application is not set.
if app.doc.MinUnits == 0 {
return nil
}
// Retrieve the number of alive units for the application.
aliveUnits, err := aliveUnitsCount(app)
if err != nil {
return err
}
// Calculate the number of required units to be added.
missing := app.doc.MinUnits - aliveUnits
if missing <= 0 {
return nil
}
name, ops, err := ensureMinUnitsOps(app)
if err != nil {
return err
}
// Add missing unit.
switch err := a.st.db().RunTransaction(ops); err {
case nil:
// Assign the new unit.
unit, err := a.st.Unit(name)
if err != nil {
return err
}
if err := app.st.AssignUnit(unit, AssignNew); err != nil {
return err
}
// No need to proceed and refresh the application if this was the
// last/only missing unit.
if missing == 1 {
return nil
}
case txn.ErrAborted:
// Refresh the application and restart the loop.
default:
return err
}
if err := app.Refresh(); err != nil {
return err
}
}
} | [
"func",
"(",
"a",
"*",
"Application",
")",
"EnsureMinUnits",
"(",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"errors",
".",
"DeferredAnnotatef",
"(",
"&",
"err",
",",
"\"",
"\"",
",",
"a",
")",
"\n",
"app",
":=",
"&",
"Application",
"{",
"st",
":",
"a",
".",
"st",
",",
"doc",
":",
"a",
".",
"doc",
"}",
"\n",
"for",
"{",
"// Ensure the application is alive.",
"if",
"app",
".",
"doc",
".",
"Life",
"!=",
"Alive",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Exit without errors if the MinUnits for the application is not set.",
"if",
"app",
".",
"doc",
".",
"MinUnits",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"// Retrieve the number of alive units for the application.",
"aliveUnits",
",",
"err",
":=",
"aliveUnitsCount",
"(",
"app",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Calculate the number of required units to be added.",
"missing",
":=",
"app",
".",
"doc",
".",
"MinUnits",
"-",
"aliveUnits",
"\n",
"if",
"missing",
"<=",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"name",
",",
"ops",
",",
"err",
":=",
"ensureMinUnitsOps",
"(",
"app",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Add missing unit.",
"switch",
"err",
":=",
"a",
".",
"st",
".",
"db",
"(",
")",
".",
"RunTransaction",
"(",
"ops",
")",
";",
"err",
"{",
"case",
"nil",
":",
"// Assign the new unit.",
"unit",
",",
"err",
":=",
"a",
".",
"st",
".",
"Unit",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"app",
".",
"st",
".",
"AssignUnit",
"(",
"unit",
",",
"AssignNew",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// No need to proceed and refresh the application if this was the",
"// last/only missing unit.",
"if",
"missing",
"==",
"1",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"case",
"txn",
".",
"ErrAborted",
":",
"// Refresh the application and restart the loop.",
"default",
":",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"app",
".",
"Refresh",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // EnsureMinUnits adds new units if the application's MinUnits value is greater
// than the number of alive units. | [
"EnsureMinUnits",
"adds",
"new",
"units",
"if",
"the",
"application",
"s",
"MinUnits",
"value",
"is",
"greater",
"than",
"the",
"number",
"of",
"alive",
"units",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/minimumunits.go#L147-L198 |
5,290 | juju/juju | state/minimumunits.go | aliveUnitsCount | func aliveUnitsCount(app *Application) (int, error) {
units, closer := app.st.db().GetCollection(unitsC)
defer closer()
query := bson.D{{"application", app.doc.Name}, {"life", Alive}}
return units.Find(query).Count()
} | go | func aliveUnitsCount(app *Application) (int, error) {
units, closer := app.st.db().GetCollection(unitsC)
defer closer()
query := bson.D{{"application", app.doc.Name}, {"life", Alive}}
return units.Find(query).Count()
} | [
"func",
"aliveUnitsCount",
"(",
"app",
"*",
"Application",
")",
"(",
"int",
",",
"error",
")",
"{",
"units",
",",
"closer",
":=",
"app",
".",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"unitsC",
")",
"\n",
"defer",
"closer",
"(",
")",
"\n\n",
"query",
":=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"app",
".",
"doc",
".",
"Name",
"}",
",",
"{",
"\"",
"\"",
",",
"Alive",
"}",
"}",
"\n",
"return",
"units",
".",
"Find",
"(",
"query",
")",
".",
"Count",
"(",
")",
"\n",
"}"
] | // aliveUnitsCount returns the number a alive units for the application. | [
"aliveUnitsCount",
"returns",
"the",
"number",
"a",
"alive",
"units",
"for",
"the",
"application",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/minimumunits.go#L201-L207 |
5,291 | juju/juju | state/minimumunits.go | ensureMinUnitsOps | func ensureMinUnitsOps(app *Application) (string, []txn.Op, error) {
asserts := bson.D{{"txn-revno", app.doc.TxnRevno}}
return app.addUnitOps("", AddUnitParams{}, asserts)
} | go | func ensureMinUnitsOps(app *Application) (string, []txn.Op, error) {
asserts := bson.D{{"txn-revno", app.doc.TxnRevno}}
return app.addUnitOps("", AddUnitParams{}, asserts)
} | [
"func",
"ensureMinUnitsOps",
"(",
"app",
"*",
"Application",
")",
"(",
"string",
",",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"asserts",
":=",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"app",
".",
"doc",
".",
"TxnRevno",
"}",
"}",
"\n",
"return",
"app",
".",
"addUnitOps",
"(",
"\"",
"\"",
",",
"AddUnitParams",
"{",
"}",
",",
"asserts",
")",
"\n",
"}"
] | // ensureMinUnitsOps returns the operations required to add a unit for the
// application in MongoDB and the name for the new unit. The resulting transaction
// will be aborted if the application document changes when running the operations. | [
"ensureMinUnitsOps",
"returns",
"the",
"operations",
"required",
"to",
"add",
"a",
"unit",
"for",
"the",
"application",
"in",
"MongoDB",
"and",
"the",
"name",
"for",
"the",
"new",
"unit",
".",
"The",
"resulting",
"transaction",
"will",
"be",
"aborted",
"if",
"the",
"application",
"document",
"changes",
"when",
"running",
"the",
"operations",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/minimumunits.go#L212-L215 |
5,292 | juju/juju | state/containernetworking.go | AutoConfigureContainerNetworking | func (m *Model) AutoConfigureContainerNetworking(environ environs.BootstrapEnviron) error {
updateAttrs := make(map[string]interface{})
modelConfig, err := m.ModelConfig()
if err != nil {
return err
}
fanConfigured, err := m.discoverFan(environ, modelConfig, updateAttrs)
if err != nil {
return err
}
if modelConfig.ContainerNetworkingMethod() != "" {
// Do nothing, user has decided what to do
} else if environs.SupportsContainerAddresses(CallContext(m.st), environ) {
updateAttrs["container-networking-method"] = "provider"
} else if fanConfigured {
updateAttrs["container-networking-method"] = "fan"
} else {
updateAttrs["container-networking-method"] = "local"
}
err = m.UpdateModelConfig(updateAttrs, nil)
return err
} | go | func (m *Model) AutoConfigureContainerNetworking(environ environs.BootstrapEnviron) error {
updateAttrs := make(map[string]interface{})
modelConfig, err := m.ModelConfig()
if err != nil {
return err
}
fanConfigured, err := m.discoverFan(environ, modelConfig, updateAttrs)
if err != nil {
return err
}
if modelConfig.ContainerNetworkingMethod() != "" {
// Do nothing, user has decided what to do
} else if environs.SupportsContainerAddresses(CallContext(m.st), environ) {
updateAttrs["container-networking-method"] = "provider"
} else if fanConfigured {
updateAttrs["container-networking-method"] = "fan"
} else {
updateAttrs["container-networking-method"] = "local"
}
err = m.UpdateModelConfig(updateAttrs, nil)
return err
} | [
"func",
"(",
"m",
"*",
"Model",
")",
"AutoConfigureContainerNetworking",
"(",
"environ",
"environs",
".",
"BootstrapEnviron",
")",
"error",
"{",
"updateAttrs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"modelConfig",
",",
"err",
":=",
"m",
".",
"ModelConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"fanConfigured",
",",
"err",
":=",
"m",
".",
"discoverFan",
"(",
"environ",
",",
"modelConfig",
",",
"updateAttrs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"modelConfig",
".",
"ContainerNetworkingMethod",
"(",
")",
"!=",
"\"",
"\"",
"{",
"// Do nothing, user has decided what to do",
"}",
"else",
"if",
"environs",
".",
"SupportsContainerAddresses",
"(",
"CallContext",
"(",
"m",
".",
"st",
")",
",",
"environ",
")",
"{",
"updateAttrs",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"fanConfigured",
"{",
"updateAttrs",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"updateAttrs",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"err",
"=",
"m",
".",
"UpdateModelConfig",
"(",
"updateAttrs",
",",
"nil",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // AutoConfigureContainerNetworking tries to set up best container networking available
// for the specific model if user hasn't set anything. | [
"AutoConfigureContainerNetworking",
"tries",
"to",
"set",
"up",
"best",
"container",
"networking",
"available",
"for",
"the",
"specific",
"model",
"if",
"user",
"hasn",
"t",
"set",
"anything",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/containernetworking.go#L19-L41 |
5,293 | juju/juju | apiserver/facades/controller/singular/singular.go | NewFacade | func NewFacade(backend Backend, claimer lease.Claimer, auth facade.Authorizer) (*Facade, error) {
if !auth.AuthController() {
return nil, common.ErrPerm
}
return &Facade{
auth: auth,
modelTag: backend.ModelTag(),
controllerTag: backend.ControllerTag(),
singularClaimer: claimer,
}, nil
} | go | func NewFacade(backend Backend, claimer lease.Claimer, auth facade.Authorizer) (*Facade, error) {
if !auth.AuthController() {
return nil, common.ErrPerm
}
return &Facade{
auth: auth,
modelTag: backend.ModelTag(),
controllerTag: backend.ControllerTag(),
singularClaimer: claimer,
}, nil
} | [
"func",
"NewFacade",
"(",
"backend",
"Backend",
",",
"claimer",
"lease",
".",
"Claimer",
",",
"auth",
"facade",
".",
"Authorizer",
")",
"(",
"*",
"Facade",
",",
"error",
")",
"{",
"if",
"!",
"auth",
".",
"AuthController",
"(",
")",
"{",
"return",
"nil",
",",
"common",
".",
"ErrPerm",
"\n",
"}",
"\n",
"return",
"&",
"Facade",
"{",
"auth",
":",
"auth",
",",
"modelTag",
":",
"backend",
".",
"ModelTag",
"(",
")",
",",
"controllerTag",
":",
"backend",
".",
"ControllerTag",
"(",
")",
",",
"singularClaimer",
":",
"claimer",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewFacade returns a singular-controller API facade, backed by the supplied
// state, so long as the authorizer represents a controller machine. | [
"NewFacade",
"returns",
"a",
"singular",
"-",
"controller",
"API",
"facade",
"backed",
"by",
"the",
"supplied",
"state",
"so",
"long",
"as",
"the",
"authorizer",
"represents",
"a",
"controller",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/singular/singular.go#L65-L75 |
5,294 | juju/juju | cloudconfig/cloudinit/utils.go | addPackageSourceCmds | func addPackageSourceCmds(cfg CloudConfig, src packaging.PackageSource) []string {
cmds := []string{}
// if keyfile is required, add it first
if src.Key != "" {
keyFilePath := config.YumKeyfileDir + src.KeyFileName()
cmds = append(cmds, addFileCmds(keyFilePath, []byte(src.Key), 0644, false)...)
}
repoPath := filepath.Join(config.YumSourcesDir, src.Name+".repo")
sourceFile, _ := cfg.getPackagingConfigurer().RenderSource(src)
data := []byte(sourceFile)
cmds = append(cmds, addFileCmds(repoPath, data, 0644, false)...)
return cmds
} | go | func addPackageSourceCmds(cfg CloudConfig, src packaging.PackageSource) []string {
cmds := []string{}
// if keyfile is required, add it first
if src.Key != "" {
keyFilePath := config.YumKeyfileDir + src.KeyFileName()
cmds = append(cmds, addFileCmds(keyFilePath, []byte(src.Key), 0644, false)...)
}
repoPath := filepath.Join(config.YumSourcesDir, src.Name+".repo")
sourceFile, _ := cfg.getPackagingConfigurer().RenderSource(src)
data := []byte(sourceFile)
cmds = append(cmds, addFileCmds(repoPath, data, 0644, false)...)
return cmds
} | [
"func",
"addPackageSourceCmds",
"(",
"cfg",
"CloudConfig",
",",
"src",
"packaging",
".",
"PackageSource",
")",
"[",
"]",
"string",
"{",
"cmds",
":=",
"[",
"]",
"string",
"{",
"}",
"\n\n",
"// if keyfile is required, add it first",
"if",
"src",
".",
"Key",
"!=",
"\"",
"\"",
"{",
"keyFilePath",
":=",
"config",
".",
"YumKeyfileDir",
"+",
"src",
".",
"KeyFileName",
"(",
")",
"\n",
"cmds",
"=",
"append",
"(",
"cmds",
",",
"addFileCmds",
"(",
"keyFilePath",
",",
"[",
"]",
"byte",
"(",
"src",
".",
"Key",
")",
",",
"0644",
",",
"false",
")",
"...",
")",
"\n",
"}",
"\n\n",
"repoPath",
":=",
"filepath",
".",
"Join",
"(",
"config",
".",
"YumSourcesDir",
",",
"src",
".",
"Name",
"+",
"\"",
"\"",
")",
"\n",
"sourceFile",
",",
"_",
":=",
"cfg",
".",
"getPackagingConfigurer",
"(",
")",
".",
"RenderSource",
"(",
"src",
")",
"\n",
"data",
":=",
"[",
"]",
"byte",
"(",
"sourceFile",
")",
"\n",
"cmds",
"=",
"append",
"(",
"cmds",
",",
"addFileCmds",
"(",
"repoPath",
",",
"data",
",",
"0644",
",",
"false",
")",
"...",
")",
"\n\n",
"return",
"cmds",
"\n",
"}"
] | // addPackageSourceCmds is a helper function that returns the corresponding
// runcmds to apply the package source settings on a CentOS machine. | [
"addPackageSourceCmds",
"is",
"a",
"helper",
"function",
"that",
"returns",
"the",
"corresponding",
"runcmds",
"to",
"apply",
"the",
"package",
"source",
"settings",
"on",
"a",
"CentOS",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/cloudinit/utils.go#L19-L34 |
5,295 | juju/juju | cloudconfig/cloudinit/utils.go | removeStringFromSlice | func removeStringFromSlice(slice []string, val string) []string {
for i, str := range slice {
if str == val {
slice = append(slice[:i], slice[i+1:]...)
}
}
return slice
} | go | func removeStringFromSlice(slice []string, val string) []string {
for i, str := range slice {
if str == val {
slice = append(slice[:i], slice[i+1:]...)
}
}
return slice
} | [
"func",
"removeStringFromSlice",
"(",
"slice",
"[",
"]",
"string",
",",
"val",
"string",
")",
"[",
"]",
"string",
"{",
"for",
"i",
",",
"str",
":=",
"range",
"slice",
"{",
"if",
"str",
"==",
"val",
"{",
"slice",
"=",
"append",
"(",
"slice",
"[",
":",
"i",
"]",
",",
"slice",
"[",
"i",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"slice",
"\n",
"}"
] | // removeStringFromSlice is a helper function which removes a given string from
// the given slice, if it exists it returns the slice, be it modified or unmodified | [
"removeStringFromSlice",
"is",
"a",
"helper",
"function",
"which",
"removes",
"a",
"given",
"string",
"from",
"the",
"given",
"slice",
"if",
"it",
"exists",
"it",
"returns",
"the",
"slice",
"be",
"it",
"modified",
"or",
"unmodified"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/cloudinit/utils.go#L63-L71 |
5,296 | juju/juju | cmd/juju/status/formatted.go | machineName | func (s machineStatus) machineName() string {
if s.DisplayName == "" {
return string(s.InstanceId)
}
return s.DisplayName
} | go | func (s machineStatus) machineName() string {
if s.DisplayName == "" {
return string(s.InstanceId)
}
return s.DisplayName
} | [
"func",
"(",
"s",
"machineStatus",
")",
"machineName",
"(",
")",
"string",
"{",
"if",
"s",
".",
"DisplayName",
"==",
"\"",
"\"",
"{",
"return",
"string",
"(",
"s",
".",
"InstanceId",
")",
"\n",
"}",
"\n",
"return",
"s",
".",
"DisplayName",
"\n",
"}"
] | // machineName returns the InstanceId, unless DisplayName is set. | [
"machineName",
"returns",
"the",
"InstanceId",
"unless",
"DisplayName",
"is",
"set",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/status/formatted.go#L101-L106 |
5,297 | juju/juju | cmd/juju/model/destroy.go | NewDestroyCommand | func NewDestroyCommand() cmd.Command {
destroyCmd := &destroyCommand{
clock: jujuclock.WallClock,
}
destroyCmd.CanClearCurrentModel = true
return modelcmd.Wrap(
destroyCmd,
modelcmd.WrapSkipDefaultModel,
modelcmd.WrapSkipModelFlags,
)
} | go | func NewDestroyCommand() cmd.Command {
destroyCmd := &destroyCommand{
clock: jujuclock.WallClock,
}
destroyCmd.CanClearCurrentModel = true
return modelcmd.Wrap(
destroyCmd,
modelcmd.WrapSkipDefaultModel,
modelcmd.WrapSkipModelFlags,
)
} | [
"func",
"NewDestroyCommand",
"(",
")",
"cmd",
".",
"Command",
"{",
"destroyCmd",
":=",
"&",
"destroyCommand",
"{",
"clock",
":",
"jujuclock",
".",
"WallClock",
",",
"}",
"\n",
"destroyCmd",
".",
"CanClearCurrentModel",
"=",
"true",
"\n",
"return",
"modelcmd",
".",
"Wrap",
"(",
"destroyCmd",
",",
"modelcmd",
".",
"WrapSkipDefaultModel",
",",
"modelcmd",
".",
"WrapSkipModelFlags",
",",
")",
"\n",
"}"
] | // NewDestroyCommand returns a command used to destroy a model. | [
"NewDestroyCommand",
"returns",
"a",
"command",
"used",
"to",
"destroy",
"a",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/destroy.go#L43-L53 |
5,298 | juju/juju | container/lxd/manager.go | DestroyContainer | func (m *containerManager) DestroyContainer(id instance.Id) error {
return errors.Trace(m.server.RemoveContainer(string(id)))
} | go | func (m *containerManager) DestroyContainer(id instance.Id) error {
return errors.Trace(m.server.RemoveContainer(string(id)))
} | [
"func",
"(",
"m",
"*",
"containerManager",
")",
"DestroyContainer",
"(",
"id",
"instance",
".",
"Id",
")",
"error",
"{",
"return",
"errors",
".",
"Trace",
"(",
"m",
".",
"server",
".",
"RemoveContainer",
"(",
"string",
"(",
"id",
")",
")",
")",
"\n",
"}"
] | // DestroyContainer implements container.Manager. | [
"DestroyContainer",
"implements",
"container",
".",
"Manager",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/manager.go#L94-L96 |
5,299 | juju/juju | container/lxd/manager.go | CreateContainer | func (m *containerManager) CreateContainer(
instanceConfig *instancecfg.InstanceConfig,
cons constraints.Value,
series string,
networkConfig *container.NetworkConfig,
storageConfig *container.StorageConfig,
callback environs.StatusCallbackFunc,
) (instances.Instance, *instance.HardwareCharacteristics, error) {
callback(status.Provisioning, "Creating container spec", nil)
spec, err := m.getContainerSpec(instanceConfig, cons, series, networkConfig, storageConfig, callback)
if err != nil {
callback(status.ProvisioningError, fmt.Sprintf("Creating container spec: %v", err), nil)
return nil, nil, errors.Trace(err)
}
callback(status.Provisioning, "Creating container", nil)
c, err := m.server.CreateContainerFromSpec(spec)
if err != nil {
callback(status.ProvisioningError, fmt.Sprintf("Creating container: %v", err), nil)
return nil, nil, errors.Trace(err)
}
callback(status.Running, "Container started", nil)
return &lxdInstance{c.Name, m.server.ContainerServer},
&instance.HardwareCharacteristics{AvailabilityZone: &m.availabilityZone}, nil
} | go | func (m *containerManager) CreateContainer(
instanceConfig *instancecfg.InstanceConfig,
cons constraints.Value,
series string,
networkConfig *container.NetworkConfig,
storageConfig *container.StorageConfig,
callback environs.StatusCallbackFunc,
) (instances.Instance, *instance.HardwareCharacteristics, error) {
callback(status.Provisioning, "Creating container spec", nil)
spec, err := m.getContainerSpec(instanceConfig, cons, series, networkConfig, storageConfig, callback)
if err != nil {
callback(status.ProvisioningError, fmt.Sprintf("Creating container spec: %v", err), nil)
return nil, nil, errors.Trace(err)
}
callback(status.Provisioning, "Creating container", nil)
c, err := m.server.CreateContainerFromSpec(spec)
if err != nil {
callback(status.ProvisioningError, fmt.Sprintf("Creating container: %v", err), nil)
return nil, nil, errors.Trace(err)
}
callback(status.Running, "Container started", nil)
return &lxdInstance{c.Name, m.server.ContainerServer},
&instance.HardwareCharacteristics{AvailabilityZone: &m.availabilityZone}, nil
} | [
"func",
"(",
"m",
"*",
"containerManager",
")",
"CreateContainer",
"(",
"instanceConfig",
"*",
"instancecfg",
".",
"InstanceConfig",
",",
"cons",
"constraints",
".",
"Value",
",",
"series",
"string",
",",
"networkConfig",
"*",
"container",
".",
"NetworkConfig",
",",
"storageConfig",
"*",
"container",
".",
"StorageConfig",
",",
"callback",
"environs",
".",
"StatusCallbackFunc",
",",
")",
"(",
"instances",
".",
"Instance",
",",
"*",
"instance",
".",
"HardwareCharacteristics",
",",
"error",
")",
"{",
"callback",
"(",
"status",
".",
"Provisioning",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"spec",
",",
"err",
":=",
"m",
".",
"getContainerSpec",
"(",
"instanceConfig",
",",
"cons",
",",
"series",
",",
"networkConfig",
",",
"storageConfig",
",",
"callback",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"callback",
"(",
"status",
".",
"ProvisioningError",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
",",
"nil",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"callback",
"(",
"status",
".",
"Provisioning",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"c",
",",
"err",
":=",
"m",
".",
"server",
".",
"CreateContainerFromSpec",
"(",
"spec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"callback",
"(",
"status",
".",
"ProvisioningError",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
",",
"nil",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"callback",
"(",
"status",
".",
"Running",
",",
"\"",
"\"",
",",
"nil",
")",
"\n\n",
"return",
"&",
"lxdInstance",
"{",
"c",
".",
"Name",
",",
"m",
".",
"server",
".",
"ContainerServer",
"}",
",",
"&",
"instance",
".",
"HardwareCharacteristics",
"{",
"AvailabilityZone",
":",
"&",
"m",
".",
"availabilityZone",
"}",
",",
"nil",
"\n",
"}"
] | // CreateContainer implements container.Manager. | [
"CreateContainer",
"implements",
"container",
".",
"Manager",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/manager.go#L99-L124 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.