id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
156,300
juju/juju
state/storage.go
AttachStorage
func (sb *storageBackend) AttachStorage(storage names.StorageTag, unit names.UnitTag) (err error) { defer errors.DeferredAnnotatef(&err, "cannot attach %s to %s", names.ReadableString(storage), names.ReadableString(unit), ) buildTxn := func(attempt int) ([]txn.Op, error) { si, err := sb.storageInstance(storage) if err != nil { return nil, errors.Trace(err) } u, err := sb.unit(unit.Id()) if err != nil { return nil, errors.Trace(err) } if u.Life() != Alive { return nil, errors.New("unit not alive") } ch, err := u.charm() if err != nil { return nil, errors.Annotate(err, "getting charm") } ops, err := sb.attachStorageOps(si, u.UnitTag(), u.Series(), ch, u) if err != nil { return nil, errors.Trace(err) } if si.doc.Owner == "" { // The storage instance will be owned by the unit, so we // must increment the unit's refcount for the storage name. // // Make sure that we *can* assign another storage instance // to the unit. _, currentCountOp, err := validateStorageCountChange( sb, u.UnitTag(), si.StorageName(), 1, ch.Meta(), ) if err != nil { return nil, errors.Trace(err) } incRefOp, err := increfEntityStorageOp(sb.mb, u.UnitTag(), si.StorageName(), 1) if err != nil { return nil, errors.Trace(err) } ops = append(ops, currentCountOp, incRefOp) } ops = append(ops, txn.Op{ C: unitsC, Id: u.doc.Name, Assert: isAliveDoc, Update: bson.D{{"$inc", bson.D{{"storageattachmentcount", 1}}}}, }) ops = append(ops, u.assertCharmOps(ch)...) return ops, nil } return sb.mb.db().Run(buildTxn) }
go
func (sb *storageBackend) AttachStorage(storage names.StorageTag, unit names.UnitTag) (err error) { defer errors.DeferredAnnotatef(&err, "cannot attach %s to %s", names.ReadableString(storage), names.ReadableString(unit), ) buildTxn := func(attempt int) ([]txn.Op, error) { si, err := sb.storageInstance(storage) if err != nil { return nil, errors.Trace(err) } u, err := sb.unit(unit.Id()) if err != nil { return nil, errors.Trace(err) } if u.Life() != Alive { return nil, errors.New("unit not alive") } ch, err := u.charm() if err != nil { return nil, errors.Annotate(err, "getting charm") } ops, err := sb.attachStorageOps(si, u.UnitTag(), u.Series(), ch, u) if err != nil { return nil, errors.Trace(err) } if si.doc.Owner == "" { // The storage instance will be owned by the unit, so we // must increment the unit's refcount for the storage name. // // Make sure that we *can* assign another storage instance // to the unit. _, currentCountOp, err := validateStorageCountChange( sb, u.UnitTag(), si.StorageName(), 1, ch.Meta(), ) if err != nil { return nil, errors.Trace(err) } incRefOp, err := increfEntityStorageOp(sb.mb, u.UnitTag(), si.StorageName(), 1) if err != nil { return nil, errors.Trace(err) } ops = append(ops, currentCountOp, incRefOp) } ops = append(ops, txn.Op{ C: unitsC, Id: u.doc.Name, Assert: isAliveDoc, Update: bson.D{{"$inc", bson.D{{"storageattachmentcount", 1}}}}, }) ops = append(ops, u.assertCharmOps(ch)...) return ops, nil } return sb.mb.db().Run(buildTxn) }
[ "func", "(", "sb", "*", "storageBackend", ")", "AttachStorage", "(", "storage", "names", ".", "StorageTag", ",", "unit", "names", ".", "UnitTag", ")", "(", "err", "error", ")", "{", "defer", "errors", ".", "DeferredAnnotatef", "(", "&", "err", ",", "\"", "\"", ",", "names", ".", "ReadableString", "(", "storage", ")", ",", "names", ".", "ReadableString", "(", "unit", ")", ",", ")", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "si", ",", "err", ":=", "sb", ".", "storageInstance", "(", "storage", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "u", ",", "err", ":=", "sb", ".", "unit", "(", "unit", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "u", ".", "Life", "(", ")", "!=", "Alive", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "ch", ",", "err", ":=", "u", ".", "charm", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "ops", ",", "err", ":=", "sb", ".", "attachStorageOps", "(", "si", ",", "u", ".", "UnitTag", "(", ")", ",", "u", ".", "Series", "(", ")", ",", "ch", ",", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "si", ".", "doc", ".", "Owner", "==", "\"", "\"", "{", "// The storage instance will be owned by the unit, so we", "// must increment the unit's refcount for the storage name.", "//", "// Make sure that we *can* assign another storage instance", "// to the unit.", "_", ",", "currentCountOp", ",", "err", ":=", "validateStorageCountChange", "(", "sb", ",", "u", ".", "UnitTag", "(", ")", ",", "si", ".", "StorageName", "(", ")", ",", "1", ",", "ch", ".", "Meta", "(", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "incRefOp", ",", "err", ":=", "increfEntityStorageOp", "(", "sb", ".", "mb", ",", "u", ".", "UnitTag", "(", ")", ",", "si", ".", "StorageName", "(", ")", ",", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "currentCountOp", ",", "incRefOp", ")", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "txn", ".", "Op", "{", "C", ":", "unitsC", ",", "Id", ":", "u", ".", "doc", ".", "Name", ",", "Assert", ":", "isAliveDoc", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "1", "}", "}", "}", "}", ",", "}", ")", "\n", "ops", "=", "append", "(", "ops", ",", "u", ".", "assertCharmOps", "(", "ch", ")", "...", ")", "\n", "return", "ops", ",", "nil", "\n", "}", "\n", "return", "sb", ".", "mb", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "}" ]
// AttachStorage attaches storage to a unit, creating and attaching machine // storage as necessary.
[ "AttachStorage", "attaches", "storage", "to", "a", "unit", "creating", "and", "attaching", "machine", "storage", "as", "necessary", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage.go#L1021-L1075
156,301
juju/juju
state/storage.go
DestroyUnitStorageAttachments
func (sb *storageBackend) DestroyUnitStorageAttachments(unit names.UnitTag) (err error) { defer errors.DeferredAnnotatef(&err, "cannot destroy unit %s storage attachments", unit.Id()) buildTxn := func(attempt int) ([]txn.Op, error) { attachments, err := sb.UnitStorageAttachments(unit) if err != nil { return nil, errors.Trace(err) } ops := make([]txn.Op, 0, len(attachments)) for _, attachment := range attachments { if attachment.Life() != Alive { continue } ops = append(ops, detachStorageOps( attachment.StorageInstance(), unit, )...) } if len(ops) == 0 { return nil, jujutxn.ErrNoOperations } return ops, nil } return sb.mb.db().Run(buildTxn) }
go
func (sb *storageBackend) DestroyUnitStorageAttachments(unit names.UnitTag) (err error) { defer errors.DeferredAnnotatef(&err, "cannot destroy unit %s storage attachments", unit.Id()) buildTxn := func(attempt int) ([]txn.Op, error) { attachments, err := sb.UnitStorageAttachments(unit) if err != nil { return nil, errors.Trace(err) } ops := make([]txn.Op, 0, len(attachments)) for _, attachment := range attachments { if attachment.Life() != Alive { continue } ops = append(ops, detachStorageOps( attachment.StorageInstance(), unit, )...) } if len(ops) == 0 { return nil, jujutxn.ErrNoOperations } return ops, nil } return sb.mb.db().Run(buildTxn) }
[ "func", "(", "sb", "*", "storageBackend", ")", "DestroyUnitStorageAttachments", "(", "unit", "names", ".", "UnitTag", ")", "(", "err", "error", ")", "{", "defer", "errors", ".", "DeferredAnnotatef", "(", "&", "err", ",", "\"", "\"", ",", "unit", ".", "Id", "(", ")", ")", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "attachments", ",", "err", ":=", "sb", ".", "UnitStorageAttachments", "(", "unit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ops", ":=", "make", "(", "[", "]", "txn", ".", "Op", ",", "0", ",", "len", "(", "attachments", ")", ")", "\n", "for", "_", ",", "attachment", ":=", "range", "attachments", "{", "if", "attachment", ".", "Life", "(", ")", "!=", "Alive", "{", "continue", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "detachStorageOps", "(", "attachment", ".", "StorageInstance", "(", ")", ",", "unit", ",", ")", "...", ")", "\n", "}", "\n", "if", "len", "(", "ops", ")", "==", "0", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "\n", "return", "ops", ",", "nil", "\n", "}", "\n", "return", "sb", ".", "mb", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "}" ]
// DetachStorage ensures that the existing storage attachments of // the specified unit are removed at some point.
[ "DetachStorage", "ensures", "that", "the", "existing", "storage", "attachments", "of", "the", "specified", "unit", "are", "removed", "at", "some", "point", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage.go#L1171-L1193
156,302
juju/juju
state/storage.go
RemoveStorageAttachment
func (sb *storageBackend) RemoveStorageAttachment(storage names.StorageTag, unit names.UnitTag, force bool) (err error) { defer errors.DeferredAnnotatef(&err, "cannot remove storage attachment %s:%s", storage.Id(), unit.Id()) buildTxn := func(attempt int) ([]txn.Op, error) { s, err := sb.storageAttachment(storage, unit) if errors.IsNotFound(err) && attempt > 0 { // On the first attempt, we expect it to exist. return nil, jujutxn.ErrNoOperations } else if err != nil { return nil, errors.Trace(err) } if s.doc.Life != Dying { // TODO (anastasiamac 2019-04-05) We might want to ignore this when forcing... return nil, errors.New("storage attachment is not dying") } inst, err := sb.storageInstance(storage) if errors.IsNotFound(err) { // This implies that the attachment was removed // after the call to st.storageAttachment. return nil, jujutxn.ErrNoOperations } else if err != nil { return nil, errors.Trace(err) } ops, err := removeStorageAttachmentOps(sb, s, inst, force, bson.D{{"life", Dying}}) if err != nil { return nil, errors.Trace(err) } return ops, nil } return sb.mb.db().Run(buildTxn) }
go
func (sb *storageBackend) RemoveStorageAttachment(storage names.StorageTag, unit names.UnitTag, force bool) (err error) { defer errors.DeferredAnnotatef(&err, "cannot remove storage attachment %s:%s", storage.Id(), unit.Id()) buildTxn := func(attempt int) ([]txn.Op, error) { s, err := sb.storageAttachment(storage, unit) if errors.IsNotFound(err) && attempt > 0 { // On the first attempt, we expect it to exist. return nil, jujutxn.ErrNoOperations } else if err != nil { return nil, errors.Trace(err) } if s.doc.Life != Dying { // TODO (anastasiamac 2019-04-05) We might want to ignore this when forcing... return nil, errors.New("storage attachment is not dying") } inst, err := sb.storageInstance(storage) if errors.IsNotFound(err) { // This implies that the attachment was removed // after the call to st.storageAttachment. return nil, jujutxn.ErrNoOperations } else if err != nil { return nil, errors.Trace(err) } ops, err := removeStorageAttachmentOps(sb, s, inst, force, bson.D{{"life", Dying}}) if err != nil { return nil, errors.Trace(err) } return ops, nil } return sb.mb.db().Run(buildTxn) }
[ "func", "(", "sb", "*", "storageBackend", ")", "RemoveStorageAttachment", "(", "storage", "names", ".", "StorageTag", ",", "unit", "names", ".", "UnitTag", ",", "force", "bool", ")", "(", "err", "error", ")", "{", "defer", "errors", ".", "DeferredAnnotatef", "(", "&", "err", ",", "\"", "\"", ",", "storage", ".", "Id", "(", ")", ",", "unit", ".", "Id", "(", ")", ")", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "s", ",", "err", ":=", "sb", ".", "storageAttachment", "(", "storage", ",", "unit", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "&&", "attempt", ">", "0", "{", "// On the first attempt, we expect it to exist.", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "s", ".", "doc", ".", "Life", "!=", "Dying", "{", "// TODO (anastasiamac 2019-04-05) We might want to ignore this when forcing...", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "inst", ",", "err", ":=", "sb", ".", "storageInstance", "(", "storage", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "// This implies that the attachment was removed", "// after the call to st.storageAttachment.", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ops", ",", "err", ":=", "removeStorageAttachmentOps", "(", "sb", ",", "s", ",", "inst", ",", "force", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "Dying", "}", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "ops", ",", "nil", "\n", "}", "\n", "return", "sb", ".", "mb", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "}" ]
// Remove removes the storage attachment from state, and may remove its storage // instance as well, if the storage instance is Dying and no other references to // it exist. It will fail if the storage attachment is not Dying.
[ "Remove", "removes", "the", "storage", "attachment", "from", "state", "and", "may", "remove", "its", "storage", "instance", "as", "well", "if", "the", "storage", "instance", "is", "Dying", "and", "no", "other", "references", "to", "it", "exist", ".", "It", "will", "fail", "if", "the", "storage", "attachment", "is", "not", "Dying", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage.go#L1363-L1392
156,303
juju/juju
state/storage.go
removeStorageInstancesOps
func removeStorageInstancesOps(im *storageBackend, owner names.Tag, force bool) ([]txn.Op, error) { coll, closer := im.mb.db().GetCollection(storageInstancesC) defer closer() var docs []storageInstanceDoc err := coll.Find(bson.D{{"owner", owner.String()}}).Select(bson.D{{"id", true}}).All(&docs) if err != nil { return nil, errors.Annotatef(err, "cannot get storage instances for %s", owner) } ops := make([]txn.Op, 0, len(docs)) var removalErr error for _, doc := range docs { si := &storageInstance{im, doc} storageInstanceOps, err := removeStorageInstanceOps(si, nil, force) if err != nil { removalErr = errors.Trace(err) logger.Warningf("error determining operations for storage instance %v removal: %v", si.StorageTag().Id(), err) } ops = append(ops, storageInstanceOps...) } if !force && removalErr != nil { return nil, removalErr } return ops, nil }
go
func removeStorageInstancesOps(im *storageBackend, owner names.Tag, force bool) ([]txn.Op, error) { coll, closer := im.mb.db().GetCollection(storageInstancesC) defer closer() var docs []storageInstanceDoc err := coll.Find(bson.D{{"owner", owner.String()}}).Select(bson.D{{"id", true}}).All(&docs) if err != nil { return nil, errors.Annotatef(err, "cannot get storage instances for %s", owner) } ops := make([]txn.Op, 0, len(docs)) var removalErr error for _, doc := range docs { si := &storageInstance{im, doc} storageInstanceOps, err := removeStorageInstanceOps(si, nil, force) if err != nil { removalErr = errors.Trace(err) logger.Warningf("error determining operations for storage instance %v removal: %v", si.StorageTag().Id(), err) } ops = append(ops, storageInstanceOps...) } if !force && removalErr != nil { return nil, removalErr } return ops, nil }
[ "func", "removeStorageInstancesOps", "(", "im", "*", "storageBackend", ",", "owner", "names", ".", "Tag", ",", "force", "bool", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "coll", ",", "closer", ":=", "im", ".", "mb", ".", "db", "(", ")", ".", "GetCollection", "(", "storageInstancesC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "var", "docs", "[", "]", "storageInstanceDoc", "\n", "err", ":=", "coll", ".", "Find", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "owner", ".", "String", "(", ")", "}", "}", ")", ".", "Select", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "true", "}", "}", ")", ".", "All", "(", "&", "docs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "owner", ")", "\n", "}", "\n", "ops", ":=", "make", "(", "[", "]", "txn", ".", "Op", ",", "0", ",", "len", "(", "docs", ")", ")", "\n", "var", "removalErr", "error", "\n", "for", "_", ",", "doc", ":=", "range", "docs", "{", "si", ":=", "&", "storageInstance", "{", "im", ",", "doc", "}", "\n", "storageInstanceOps", ",", "err", ":=", "removeStorageInstanceOps", "(", "si", ",", "nil", ",", "force", ")", "\n", "if", "err", "!=", "nil", "{", "removalErr", "=", "errors", ".", "Trace", "(", "err", ")", "\n", "logger", ".", "Warningf", "(", "\"", "\"", ",", "si", ".", "StorageTag", "(", ")", ".", "Id", "(", ")", ",", "err", ")", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "storageInstanceOps", "...", ")", "\n", "}", "\n", "if", "!", "force", "&&", "removalErr", "!=", "nil", "{", "return", "nil", ",", "removalErr", "\n", "}", "\n", "return", "ops", ",", "nil", "\n", "}" ]
// removeStorageInstancesOps returns the transaction operations to remove all // storage instances owned by the specified entity.
[ "removeStorageInstancesOps", "returns", "the", "transaction", "operations", "to", "remove", "all", "storage", "instances", "owned", "by", "the", "specified", "entity", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage.go#L1627-L1651
156,304
juju/juju
state/storage.go
validateStoragePool
func validateStoragePool( sb *storageBackend, poolName string, kind storage.StorageKind, machineId *string, ) error { if poolName == "" { return errors.New("pool name is required") } providerType, aProvider, poolConfig, err := poolStorageProvider(sb, poolName) if err != nil { return errors.Trace(err) } // Ensure the storage provider supports the specified kind. kindSupported := aProvider.Supports(kind) if !kindSupported && kind == storage.StorageKindFilesystem { // Filesystems can be created if either filesystem // or block storage are supported. The scope of the // filesystem is the same as the backing volume. kindSupported = aProvider.Supports(storage.StorageKindBlock) } if !kindSupported { return errors.Errorf("%q provider does not support %q storage", providerType, kind) } // Check the storage scope. if machineId != nil { switch aProvider.Scope() { case storage.ScopeMachine: if *machineId == "" { return errors.Annotate(err, "machine unspecified for machine-scoped storage") } default: // The storage is not machine-scoped, so we clear out // the machine ID to inform the caller that the storage // scope should be the model. *machineId = "" } } // Validate any k8s config. if sb.modelType == ModelTypeCAAS { if err := k8sprovider.ValidateStorageProvider(providerType, poolConfig); err != nil { return errors.Annotatef(err, "invalid storage config") } } return nil }
go
func validateStoragePool( sb *storageBackend, poolName string, kind storage.StorageKind, machineId *string, ) error { if poolName == "" { return errors.New("pool name is required") } providerType, aProvider, poolConfig, err := poolStorageProvider(sb, poolName) if err != nil { return errors.Trace(err) } // Ensure the storage provider supports the specified kind. kindSupported := aProvider.Supports(kind) if !kindSupported && kind == storage.StorageKindFilesystem { // Filesystems can be created if either filesystem // or block storage are supported. The scope of the // filesystem is the same as the backing volume. kindSupported = aProvider.Supports(storage.StorageKindBlock) } if !kindSupported { return errors.Errorf("%q provider does not support %q storage", providerType, kind) } // Check the storage scope. if machineId != nil { switch aProvider.Scope() { case storage.ScopeMachine: if *machineId == "" { return errors.Annotate(err, "machine unspecified for machine-scoped storage") } default: // The storage is not machine-scoped, so we clear out // the machine ID to inform the caller that the storage // scope should be the model. *machineId = "" } } // Validate any k8s config. if sb.modelType == ModelTypeCAAS { if err := k8sprovider.ValidateStorageProvider(providerType, poolConfig); err != nil { return errors.Annotatef(err, "invalid storage config") } } return nil }
[ "func", "validateStoragePool", "(", "sb", "*", "storageBackend", ",", "poolName", "string", ",", "kind", "storage", ".", "StorageKind", ",", "machineId", "*", "string", ",", ")", "error", "{", "if", "poolName", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "providerType", ",", "aProvider", ",", "poolConfig", ",", "err", ":=", "poolStorageProvider", "(", "sb", ",", "poolName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Ensure the storage provider supports the specified kind.", "kindSupported", ":=", "aProvider", ".", "Supports", "(", "kind", ")", "\n", "if", "!", "kindSupported", "&&", "kind", "==", "storage", ".", "StorageKindFilesystem", "{", "// Filesystems can be created if either filesystem", "// or block storage are supported. The scope of the", "// filesystem is the same as the backing volume.", "kindSupported", "=", "aProvider", ".", "Supports", "(", "storage", ".", "StorageKindBlock", ")", "\n", "}", "\n", "if", "!", "kindSupported", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "providerType", ",", "kind", ")", "\n", "}", "\n\n", "// Check the storage scope.", "if", "machineId", "!=", "nil", "{", "switch", "aProvider", ".", "Scope", "(", ")", "{", "case", "storage", ".", "ScopeMachine", ":", "if", "*", "machineId", "==", "\"", "\"", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "// The storage is not machine-scoped, so we clear out", "// the machine ID to inform the caller that the storage", "// scope should be the model.", "*", "machineId", "=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "// Validate any k8s config.", "if", "sb", ".", "modelType", "==", "ModelTypeCAAS", "{", "if", "err", ":=", "k8sprovider", ".", "ValidateStorageProvider", "(", "providerType", ",", "poolConfig", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validateStoragePool validates the storage pool for the model. // If machineId is non-nil, the storage scope will be validated against // the machineId; if the storage is not machine-scoped, then the machineId // will be updated to "".
[ "validateStoragePool", "validates", "the", "storage", "pool", "for", "the", "model", ".", "If", "machineId", "is", "non", "-", "nil", "the", "storage", "scope", "will", "be", "validated", "against", "the", "machineId", ";", "if", "the", "storage", "is", "not", "machine", "-", "scoped", "then", "the", "machineId", "will", "be", "updated", "to", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage.go#L1838-L1884
156,305
juju/juju
state/storage.go
storageConstraintsWithDefaults
func storageConstraintsWithDefaults( modelType ModelType, cfg *config.Config, charmStorage charm.Storage, name string, cons StorageConstraints, ) (StorageConstraints, error) { withDefaults := cons // If no pool is specified, determine the pool from the env config and other constraints. if cons.Pool == "" { kind := storageKind(charmStorage.Type) poolName, err := defaultStoragePool(modelType, cfg, kind, cons) if err != nil { return withDefaults, errors.Annotatef(err, "finding default pool for %q storage", name) } withDefaults.Pool = poolName } // If no size is specified, we default to the min size specified by the // charm, or 1GiB. if cons.Size == 0 { if charmStorage.MinimumSize > 0 { withDefaults.Size = charmStorage.MinimumSize } else { withDefaults.Size = 1024 } } if cons.Count == 0 { withDefaults.Count = uint64(charmStorage.CountMin) } return withDefaults, nil }
go
func storageConstraintsWithDefaults( modelType ModelType, cfg *config.Config, charmStorage charm.Storage, name string, cons StorageConstraints, ) (StorageConstraints, error) { withDefaults := cons // If no pool is specified, determine the pool from the env config and other constraints. if cons.Pool == "" { kind := storageKind(charmStorage.Type) poolName, err := defaultStoragePool(modelType, cfg, kind, cons) if err != nil { return withDefaults, errors.Annotatef(err, "finding default pool for %q storage", name) } withDefaults.Pool = poolName } // If no size is specified, we default to the min size specified by the // charm, or 1GiB. if cons.Size == 0 { if charmStorage.MinimumSize > 0 { withDefaults.Size = charmStorage.MinimumSize } else { withDefaults.Size = 1024 } } if cons.Count == 0 { withDefaults.Count = uint64(charmStorage.CountMin) } return withDefaults, nil }
[ "func", "storageConstraintsWithDefaults", "(", "modelType", "ModelType", ",", "cfg", "*", "config", ".", "Config", ",", "charmStorage", "charm", ".", "Storage", ",", "name", "string", ",", "cons", "StorageConstraints", ",", ")", "(", "StorageConstraints", ",", "error", ")", "{", "withDefaults", ":=", "cons", "\n\n", "// If no pool is specified, determine the pool from the env config and other constraints.", "if", "cons", ".", "Pool", "==", "\"", "\"", "{", "kind", ":=", "storageKind", "(", "charmStorage", ".", "Type", ")", "\n", "poolName", ",", "err", ":=", "defaultStoragePool", "(", "modelType", ",", "cfg", ",", "kind", ",", "cons", ")", "\n", "if", "err", "!=", "nil", "{", "return", "withDefaults", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "withDefaults", ".", "Pool", "=", "poolName", "\n", "}", "\n\n", "// If no size is specified, we default to the min size specified by the", "// charm, or 1GiB.", "if", "cons", ".", "Size", "==", "0", "{", "if", "charmStorage", ".", "MinimumSize", ">", "0", "{", "withDefaults", ".", "Size", "=", "charmStorage", ".", "MinimumSize", "\n", "}", "else", "{", "withDefaults", ".", "Size", "=", "1024", "\n", "}", "\n", "}", "\n", "if", "cons", ".", "Count", "==", "0", "{", "withDefaults", ".", "Count", "=", "uint64", "(", "charmStorage", ".", "CountMin", ")", "\n", "}", "\n", "return", "withDefaults", ",", "nil", "\n", "}" ]
// storageConstraintsWithDefaults returns a constraints // derived from cons, with any defaults filled in.
[ "storageConstraintsWithDefaults", "returns", "a", "constraints", "derived", "from", "cons", "with", "any", "defaults", "filled", "in", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage.go#L1947-L1979
156,306
juju/juju
state/storage.go
defaultStoragePool
func defaultStoragePool(modelType ModelType, cfg *config.Config, kind storage.StorageKind, cons StorageConstraints) (string, error) { switch kind { case storage.StorageKindBlock: fallbackPool := string(provider.LoopProviderType) if modelType == ModelTypeCAAS { fallbackPool = string(k8sprovider.K8s_ProviderType) } emptyConstraints := StorageConstraints{} if cons == emptyConstraints { // No constraints at all: use fallback. return fallbackPool, nil } // Either size or count specified, use env default. defaultPool, ok := cfg.StorageDefaultBlockSource() if !ok { defaultPool = fallbackPool } return defaultPool, nil case storage.StorageKindFilesystem: fallbackPool := string(provider.RootfsProviderType) if modelType == ModelTypeCAAS { fallbackPool = string(k8sprovider.K8s_ProviderType) } emptyConstraints := StorageConstraints{} if cons == emptyConstraints { return fallbackPool, nil } // If a filesystem source is specified in config, // use that; otherwise if a block source is specified, // use that and create a filesystem within. defaultPool, ok := cfg.StorageDefaultFilesystemSource() if !ok { defaultPool, ok = cfg.StorageDefaultBlockSource() if !ok { // No filesystem or block source, // so just use rootfs. defaultPool = fallbackPool } } return defaultPool, nil } return "", ErrNoDefaultStoragePool }
go
func defaultStoragePool(modelType ModelType, cfg *config.Config, kind storage.StorageKind, cons StorageConstraints) (string, error) { switch kind { case storage.StorageKindBlock: fallbackPool := string(provider.LoopProviderType) if modelType == ModelTypeCAAS { fallbackPool = string(k8sprovider.K8s_ProviderType) } emptyConstraints := StorageConstraints{} if cons == emptyConstraints { // No constraints at all: use fallback. return fallbackPool, nil } // Either size or count specified, use env default. defaultPool, ok := cfg.StorageDefaultBlockSource() if !ok { defaultPool = fallbackPool } return defaultPool, nil case storage.StorageKindFilesystem: fallbackPool := string(provider.RootfsProviderType) if modelType == ModelTypeCAAS { fallbackPool = string(k8sprovider.K8s_ProviderType) } emptyConstraints := StorageConstraints{} if cons == emptyConstraints { return fallbackPool, nil } // If a filesystem source is specified in config, // use that; otherwise if a block source is specified, // use that and create a filesystem within. defaultPool, ok := cfg.StorageDefaultFilesystemSource() if !ok { defaultPool, ok = cfg.StorageDefaultBlockSource() if !ok { // No filesystem or block source, // so just use rootfs. defaultPool = fallbackPool } } return defaultPool, nil } return "", ErrNoDefaultStoragePool }
[ "func", "defaultStoragePool", "(", "modelType", "ModelType", ",", "cfg", "*", "config", ".", "Config", ",", "kind", "storage", ".", "StorageKind", ",", "cons", "StorageConstraints", ")", "(", "string", ",", "error", ")", "{", "switch", "kind", "{", "case", "storage", ".", "StorageKindBlock", ":", "fallbackPool", ":=", "string", "(", "provider", ".", "LoopProviderType", ")", "\n", "if", "modelType", "==", "ModelTypeCAAS", "{", "fallbackPool", "=", "string", "(", "k8sprovider", ".", "K8s_ProviderType", ")", "\n", "}", "\n\n", "emptyConstraints", ":=", "StorageConstraints", "{", "}", "\n", "if", "cons", "==", "emptyConstraints", "{", "// No constraints at all: use fallback.", "return", "fallbackPool", ",", "nil", "\n", "}", "\n", "// Either size or count specified, use env default.", "defaultPool", ",", "ok", ":=", "cfg", ".", "StorageDefaultBlockSource", "(", ")", "\n", "if", "!", "ok", "{", "defaultPool", "=", "fallbackPool", "\n", "}", "\n", "return", "defaultPool", ",", "nil", "\n\n", "case", "storage", ".", "StorageKindFilesystem", ":", "fallbackPool", ":=", "string", "(", "provider", ".", "RootfsProviderType", ")", "\n", "if", "modelType", "==", "ModelTypeCAAS", "{", "fallbackPool", "=", "string", "(", "k8sprovider", ".", "K8s_ProviderType", ")", "\n", "}", "\n", "emptyConstraints", ":=", "StorageConstraints", "{", "}", "\n", "if", "cons", "==", "emptyConstraints", "{", "return", "fallbackPool", ",", "nil", "\n", "}", "\n\n", "// If a filesystem source is specified in config,", "// use that; otherwise if a block source is specified,", "// use that and create a filesystem within.", "defaultPool", ",", "ok", ":=", "cfg", ".", "StorageDefaultFilesystemSource", "(", ")", "\n", "if", "!", "ok", "{", "defaultPool", ",", "ok", "=", "cfg", ".", "StorageDefaultBlockSource", "(", ")", "\n", "if", "!", "ok", "{", "// No filesystem or block source,", "// so just use rootfs.", "defaultPool", "=", "fallbackPool", "\n", "}", "\n", "}", "\n", "return", "defaultPool", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "ErrNoDefaultStoragePool", "\n", "}" ]
// defaultStoragePool returns the default storage pool for the model. // The default pool is either user specified, or one that is registered by the provider itself.
[ "defaultStoragePool", "returns", "the", "default", "storage", "pool", "for", "the", "model", ".", "The", "default", "pool", "is", "either", "user", "specified", "or", "one", "that", "is", "registered", "by", "the", "provider", "itself", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage.go#L1983-L2028
156,307
juju/juju
state/storage.go
AddStorageForUnit
func (sb *storageBackend) AddStorageForUnit( tag names.UnitTag, name string, cons StorageConstraints, ) ([]names.StorageTag, error) { u, err := sb.unit(tag.Id()) if err != nil { return nil, errors.Trace(err) } var tags []names.StorageTag buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := u.Refresh(); err != nil { return nil, errors.Trace(err) } } var ops []txn.Op var err error tags, ops, err = sb.addStorageForUnitOps(u, name, cons) return ops, err } if err := sb.mb.db().Run(buildTxn); err != nil { return nil, errors.Annotatef(err, "adding %q storage to %s", name, u) } return tags, nil }
go
func (sb *storageBackend) AddStorageForUnit( tag names.UnitTag, name string, cons StorageConstraints, ) ([]names.StorageTag, error) { u, err := sb.unit(tag.Id()) if err != nil { return nil, errors.Trace(err) } var tags []names.StorageTag buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { if err := u.Refresh(); err != nil { return nil, errors.Trace(err) } } var ops []txn.Op var err error tags, ops, err = sb.addStorageForUnitOps(u, name, cons) return ops, err } if err := sb.mb.db().Run(buildTxn); err != nil { return nil, errors.Annotatef(err, "adding %q storage to %s", name, u) } return tags, nil }
[ "func", "(", "sb", "*", "storageBackend", ")", "AddStorageForUnit", "(", "tag", "names", ".", "UnitTag", ",", "name", "string", ",", "cons", "StorageConstraints", ",", ")", "(", "[", "]", "names", ".", "StorageTag", ",", "error", ")", "{", "u", ",", "err", ":=", "sb", ".", "unit", "(", "tag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "tags", "[", "]", "names", ".", "StorageTag", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "attempt", ">", "0", "{", "if", "err", ":=", "u", ".", "Refresh", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "var", "ops", "[", "]", "txn", ".", "Op", "\n", "var", "err", "error", "\n", "tags", ",", "ops", ",", "err", "=", "sb", ".", "addStorageForUnitOps", "(", "u", ",", "name", ",", "cons", ")", "\n", "return", "ops", ",", "err", "\n", "}", "\n", "if", "err", ":=", "sb", ".", "mb", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "name", ",", "u", ")", "\n", "}", "\n", "return", "tags", ",", "nil", "\n", "}" ]
// AddStorageForUnit adds storage instances to given unit as specified. // // Missing storage constraints are populated based on model defaults. // Storage store name is used to retrieve existing storage instances // for this store. Combination of existing storage instances and // anticipated additional storage instances is validated against the // store as specified in the charm.
[ "AddStorageForUnit", "adds", "storage", "instances", "to", "given", "unit", "as", "specified", ".", "Missing", "storage", "constraints", "are", "populated", "based", "on", "model", "defaults", ".", "Storage", "store", "name", "is", "used", "to", "retrieve", "existing", "storage", "instances", "for", "this", "store", ".", "Combination", "of", "existing", "storage", "instances", "and", "anticipated", "additional", "storage", "instances", "is", "validated", "against", "the", "store", "as", "specified", "in", "the", "charm", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage.go#L2037-L2060
156,308
juju/juju
state/storage.go
addStorageForUnitOps
func (sb *storageBackend) addStorageForUnitOps( u *Unit, storageName string, cons StorageConstraints, ) ([]names.StorageTag, []txn.Op, error) { if u.Life() != Alive { return nil, nil, unitNotAliveErr } // Storage addition is based on the charm metadata; u.charm() // returns txn.Ops that ensure the charm URL does not change // during the transaction. ch, err := u.charm() if err != nil { return nil, nil, errors.Trace(err) } charmMeta := ch.Meta() charmStorageMeta, ok := charmMeta.Storage[storageName] if !ok { return nil, nil, errors.NotFoundf("charm storage %q", storageName) } ops := u.assertCharmOps(ch) if cons.Pool == "" || cons.Size == 0 { // Either pool or size, or both, were not specified. Take the // values from the unit's recorded storage constraints. allCons, err := u.StorageConstraints() if err != nil { return nil, nil, errors.Trace(err) } if uCons, ok := allCons[storageName]; ok { if cons.Pool == "" { cons.Pool = uCons.Pool } if cons.Size == 0 { cons.Size = uCons.Size } } // Populate missing configuration parameters with defaults. if cons.Pool == "" || cons.Size == 0 { modelConfig, err := sb.config() if err != nil { return nil, nil, errors.Trace(err) } completeCons, err := storageConstraintsWithDefaults( sb.modelType, modelConfig, charmStorageMeta, storageName, cons, ) if err != nil { return nil, nil, errors.Trace(err) } cons = completeCons } } // This can happen for charm stores that specify instances range from 0, // and no count was specified at deploy as storage constraints for this store, // and no count was specified to storage add as a contraint either. if cons.Count == 0 { return nil, nil, errors.NotValidf("adding storage where instance count is 0") } tags, addUnitStorageOps, err := sb.addUnitStorageOps(charmMeta, u, storageName, cons, -1) if err != nil { return nil, nil, errors.Trace(err) } ops = append(ops, addUnitStorageOps...) return tags, ops, nil }
go
func (sb *storageBackend) addStorageForUnitOps( u *Unit, storageName string, cons StorageConstraints, ) ([]names.StorageTag, []txn.Op, error) { if u.Life() != Alive { return nil, nil, unitNotAliveErr } // Storage addition is based on the charm metadata; u.charm() // returns txn.Ops that ensure the charm URL does not change // during the transaction. ch, err := u.charm() if err != nil { return nil, nil, errors.Trace(err) } charmMeta := ch.Meta() charmStorageMeta, ok := charmMeta.Storage[storageName] if !ok { return nil, nil, errors.NotFoundf("charm storage %q", storageName) } ops := u.assertCharmOps(ch) if cons.Pool == "" || cons.Size == 0 { // Either pool or size, or both, were not specified. Take the // values from the unit's recorded storage constraints. allCons, err := u.StorageConstraints() if err != nil { return nil, nil, errors.Trace(err) } if uCons, ok := allCons[storageName]; ok { if cons.Pool == "" { cons.Pool = uCons.Pool } if cons.Size == 0 { cons.Size = uCons.Size } } // Populate missing configuration parameters with defaults. if cons.Pool == "" || cons.Size == 0 { modelConfig, err := sb.config() if err != nil { return nil, nil, errors.Trace(err) } completeCons, err := storageConstraintsWithDefaults( sb.modelType, modelConfig, charmStorageMeta, storageName, cons, ) if err != nil { return nil, nil, errors.Trace(err) } cons = completeCons } } // This can happen for charm stores that specify instances range from 0, // and no count was specified at deploy as storage constraints for this store, // and no count was specified to storage add as a contraint either. if cons.Count == 0 { return nil, nil, errors.NotValidf("adding storage where instance count is 0") } tags, addUnitStorageOps, err := sb.addUnitStorageOps(charmMeta, u, storageName, cons, -1) if err != nil { return nil, nil, errors.Trace(err) } ops = append(ops, addUnitStorageOps...) return tags, ops, nil }
[ "func", "(", "sb", "*", "storageBackend", ")", "addStorageForUnitOps", "(", "u", "*", "Unit", ",", "storageName", "string", ",", "cons", "StorageConstraints", ",", ")", "(", "[", "]", "names", ".", "StorageTag", ",", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "u", ".", "Life", "(", ")", "!=", "Alive", "{", "return", "nil", ",", "nil", ",", "unitNotAliveErr", "\n", "}", "\n\n", "// Storage addition is based on the charm metadata; u.charm()", "// returns txn.Ops that ensure the charm URL does not change", "// during the transaction.", "ch", ",", "err", ":=", "u", ".", "charm", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "charmMeta", ":=", "ch", ".", "Meta", "(", ")", "\n", "charmStorageMeta", ",", "ok", ":=", "charmMeta", ".", "Storage", "[", "storageName", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "storageName", ")", "\n", "}", "\n", "ops", ":=", "u", ".", "assertCharmOps", "(", "ch", ")", "\n\n", "if", "cons", ".", "Pool", "==", "\"", "\"", "||", "cons", ".", "Size", "==", "0", "{", "// Either pool or size, or both, were not specified. Take the", "// values from the unit's recorded storage constraints.", "allCons", ",", "err", ":=", "u", ".", "StorageConstraints", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "uCons", ",", "ok", ":=", "allCons", "[", "storageName", "]", ";", "ok", "{", "if", "cons", ".", "Pool", "==", "\"", "\"", "{", "cons", ".", "Pool", "=", "uCons", ".", "Pool", "\n", "}", "\n", "if", "cons", ".", "Size", "==", "0", "{", "cons", ".", "Size", "=", "uCons", ".", "Size", "\n", "}", "\n", "}", "\n\n", "// Populate missing configuration parameters with defaults.", "if", "cons", ".", "Pool", "==", "\"", "\"", "||", "cons", ".", "Size", "==", "0", "{", "modelConfig", ",", "err", ":=", "sb", ".", "config", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "completeCons", ",", "err", ":=", "storageConstraintsWithDefaults", "(", "sb", ".", "modelType", ",", "modelConfig", ",", "charmStorageMeta", ",", "storageName", ",", "cons", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "cons", "=", "completeCons", "\n", "}", "\n", "}", "\n\n", "// This can happen for charm stores that specify instances range from 0,", "// and no count was specified at deploy as storage constraints for this store,", "// and no count was specified to storage add as a contraint either.", "if", "cons", ".", "Count", "==", "0", "{", "return", "nil", ",", "nil", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "tags", ",", "addUnitStorageOps", ",", "err", ":=", "sb", ".", "addUnitStorageOps", "(", "charmMeta", ",", "u", ",", "storageName", ",", "cons", ",", "-", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "addUnitStorageOps", "...", ")", "\n", "return", "tags", ",", "ops", ",", "nil", "\n", "}" ]
// addStorage adds storage instances to given unit as specified.
[ "addStorage", "adds", "storage", "instances", "to", "given", "unit", "as", "specified", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage.go#L2063-L2135
156,309
juju/juju
state/storage.go
addUnitStorageOps
func (sb *storageBackend) addUnitStorageOps( charmMeta *charm.Meta, u *Unit, storageName string, cons StorageConstraints, countMin int, ) ([]names.StorageTag, []txn.Op, error) { var ops []txn.Op consTotal := cons if countMin < 0 { // Validate that the requested number of storage // instances can be added to the unit. currentCount, currentCountOp, err := validateStorageCountChange( sb, u.Tag(), storageName, int(cons.Count), charmMeta, ) if err != nil { return nil, nil, errors.Trace(err) } ops = append(ops, currentCountOp) consTotal.Count += uint64(currentCount) } else { currentCountOp, currentCount, err := sb.countEntityStorageInstances(u.Tag(), storageName) if err != nil { return nil, nil, errors.Trace(err) } ops = append(ops, currentCountOp) if currentCount >= countMin { return nil, ops, nil } cons.Count = uint64(countMin) } if err := validateStorageConstraintsAgainstCharm(sb, map[string]StorageConstraints{storageName: consTotal}, charmMeta, ); err != nil { return nil, nil, errors.Trace(err) } // Create storage db operations storageOps, storageTags, _, err := createStorageOps( sb, u.Tag(), charmMeta, map[string]StorageConstraints{storageName: cons}, u.Series(), u, ) if err != nil { return nil, nil, errors.Trace(err) } // Increment reference counts for the named storage for each // instance we create. We'll use the reference counts to ensure // we don't exceed limits when adding storage, and for // maintaining model integrity during charm upgrades. var allTags []names.StorageTag for name, tags := range storageTags { count := len(tags) incRefOp, err := increfEntityStorageOp(sb.mb, u.Tag(), name, count) if err != nil { return nil, nil, errors.Trace(err) } storageOps = append(storageOps, incRefOp) allTags = append(allTags, tags...) } ops = append(ops, txn.Op{ C: unitsC, Id: u.doc.DocID, Assert: isAliveDoc, Update: bson.D{{"$inc", bson.D{{"storageattachmentcount", int(cons.Count)}}}}, }) return allTags, append(ops, storageOps...), nil }
go
func (sb *storageBackend) addUnitStorageOps( charmMeta *charm.Meta, u *Unit, storageName string, cons StorageConstraints, countMin int, ) ([]names.StorageTag, []txn.Op, error) { var ops []txn.Op consTotal := cons if countMin < 0 { // Validate that the requested number of storage // instances can be added to the unit. currentCount, currentCountOp, err := validateStorageCountChange( sb, u.Tag(), storageName, int(cons.Count), charmMeta, ) if err != nil { return nil, nil, errors.Trace(err) } ops = append(ops, currentCountOp) consTotal.Count += uint64(currentCount) } else { currentCountOp, currentCount, err := sb.countEntityStorageInstances(u.Tag(), storageName) if err != nil { return nil, nil, errors.Trace(err) } ops = append(ops, currentCountOp) if currentCount >= countMin { return nil, ops, nil } cons.Count = uint64(countMin) } if err := validateStorageConstraintsAgainstCharm(sb, map[string]StorageConstraints{storageName: consTotal}, charmMeta, ); err != nil { return nil, nil, errors.Trace(err) } // Create storage db operations storageOps, storageTags, _, err := createStorageOps( sb, u.Tag(), charmMeta, map[string]StorageConstraints{storageName: cons}, u.Series(), u, ) if err != nil { return nil, nil, errors.Trace(err) } // Increment reference counts for the named storage for each // instance we create. We'll use the reference counts to ensure // we don't exceed limits when adding storage, and for // maintaining model integrity during charm upgrades. var allTags []names.StorageTag for name, tags := range storageTags { count := len(tags) incRefOp, err := increfEntityStorageOp(sb.mb, u.Tag(), name, count) if err != nil { return nil, nil, errors.Trace(err) } storageOps = append(storageOps, incRefOp) allTags = append(allTags, tags...) } ops = append(ops, txn.Op{ C: unitsC, Id: u.doc.DocID, Assert: isAliveDoc, Update: bson.D{{"$inc", bson.D{{"storageattachmentcount", int(cons.Count)}}}}, }) return allTags, append(ops, storageOps...), nil }
[ "func", "(", "sb", "*", "storageBackend", ")", "addUnitStorageOps", "(", "charmMeta", "*", "charm", ".", "Meta", ",", "u", "*", "Unit", ",", "storageName", "string", ",", "cons", "StorageConstraints", ",", "countMin", "int", ",", ")", "(", "[", "]", "names", ".", "StorageTag", ",", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "var", "ops", "[", "]", "txn", ".", "Op", "\n\n", "consTotal", ":=", "cons", "\n", "if", "countMin", "<", "0", "{", "// Validate that the requested number of storage", "// instances can be added to the unit.", "currentCount", ",", "currentCountOp", ",", "err", ":=", "validateStorageCountChange", "(", "sb", ",", "u", ".", "Tag", "(", ")", ",", "storageName", ",", "int", "(", "cons", ".", "Count", ")", ",", "charmMeta", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "currentCountOp", ")", "\n", "consTotal", ".", "Count", "+=", "uint64", "(", "currentCount", ")", "\n", "}", "else", "{", "currentCountOp", ",", "currentCount", ",", "err", ":=", "sb", ".", "countEntityStorageInstances", "(", "u", ".", "Tag", "(", ")", ",", "storageName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "currentCountOp", ")", "\n", "if", "currentCount", ">=", "countMin", "{", "return", "nil", ",", "ops", ",", "nil", "\n", "}", "\n", "cons", ".", "Count", "=", "uint64", "(", "countMin", ")", "\n", "}", "\n\n", "if", "err", ":=", "validateStorageConstraintsAgainstCharm", "(", "sb", ",", "map", "[", "string", "]", "StorageConstraints", "{", "storageName", ":", "consTotal", "}", ",", "charmMeta", ",", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Create storage db operations", "storageOps", ",", "storageTags", ",", "_", ",", "err", ":=", "createStorageOps", "(", "sb", ",", "u", ".", "Tag", "(", ")", ",", "charmMeta", ",", "map", "[", "string", "]", "StorageConstraints", "{", "storageName", ":", "cons", "}", ",", "u", ".", "Series", "(", ")", ",", "u", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// Increment reference counts for the named storage for each", "// instance we create. We'll use the reference counts to ensure", "// we don't exceed limits when adding storage, and for", "// maintaining model integrity during charm upgrades.", "var", "allTags", "[", "]", "names", ".", "StorageTag", "\n", "for", "name", ",", "tags", ":=", "range", "storageTags", "{", "count", ":=", "len", "(", "tags", ")", "\n", "incRefOp", ",", "err", ":=", "increfEntityStorageOp", "(", "sb", ".", "mb", ",", "u", ".", "Tag", "(", ")", ",", "name", ",", "count", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "storageOps", "=", "append", "(", "storageOps", ",", "incRefOp", ")", "\n", "allTags", "=", "append", "(", "allTags", ",", "tags", "...", ")", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "txn", ".", "Op", "{", "C", ":", "unitsC", ",", "Id", ":", "u", ".", "doc", ".", "DocID", ",", "Assert", ":", "isAliveDoc", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "int", "(", "cons", ".", "Count", ")", "}", "}", "}", "}", ",", "}", ")", "\n", "return", "allTags", ",", "append", "(", "ops", ",", "storageOps", "...", ")", ",", "nil", "\n", "}" ]
// addUnitStorageOps returns transaction ops to create storage for the given // unit. If countMin is non-negative, the Count field of the constraints will // be ignored, and as many storage instances as necessary to make up the // shortfall will be created.
[ "addUnitStorageOps", "returns", "transaction", "ops", "to", "create", "storage", "for", "the", "given", "unit", ".", "If", "countMin", "is", "non", "-", "negative", "the", "Count", "field", "of", "the", "constraints", "will", "be", "ignored", "and", "as", "many", "storage", "instances", "as", "necessary", "to", "make", "up", "the", "shortfall", "will", "be", "created", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage.go#L2141-L2215
156,310
juju/juju
state/storage.go
hostStorageOps
func (sb *storageBackend) hostStorageOps( hostId string, args *storageParams, ) ([]txn.Op, []volumeAttachmentTemplate, []filesystemAttachmentTemplate, error) { var filesystemOps, volumeOps []txn.Op var fsAttachments []filesystemAttachmentTemplate var volumeAttachments []volumeAttachmentTemplate const ( createAndAttach = false attachOnly = true ) // Create filesystems and filesystem attachments. for _, f := range args.filesystems { ops, filesystemTag, volumeTag, err := sb.addFilesystemOps(f.Filesystem, hostId) if err != nil { return nil, nil, nil, errors.Trace(err) } filesystemOps = append(filesystemOps, ops...) fsAttachments = append(fsAttachments, filesystemAttachmentTemplate{ filesystemTag, f.Filesystem.storage, f.Attachment, createAndAttach, }) if volumeTag != (names.VolumeTag{}) { // The filesystem requires a volume, so create a volume attachment too. volumeAttachments = append(volumeAttachments, volumeAttachmentTemplate{ volumeTag, VolumeAttachmentParams{}, createAndAttach, }) } } for tag, filesystemAttachment := range args.filesystemAttachments { fsAttachments = append(fsAttachments, filesystemAttachmentTemplate{ tag, names.StorageTag{}, filesystemAttachment, attachOnly, }) } // Create volumes and volume attachments. for _, v := range args.volumes { ops, tag, err := sb.addVolumeOps(v.Volume, hostId) if err != nil { return nil, nil, nil, errors.Trace(err) } volumeOps = append(volumeOps, ops...) volumeAttachments = append(volumeAttachments, volumeAttachmentTemplate{ tag, v.Attachment, createAndAttach, }) } for tag, volumeAttachment := range args.volumeAttachments { volumeAttachments = append(volumeAttachments, volumeAttachmentTemplate{ tag, volumeAttachment, attachOnly, }) } ops := make([]txn.Op, 0, len(filesystemOps)+len(volumeOps)+len(fsAttachments)+len(volumeAttachments)) if len(fsAttachments) > 0 { attachmentOps := createMachineFilesystemAttachmentsOps(hostId, fsAttachments) ops = append(ops, filesystemOps...) ops = append(ops, attachmentOps...) } if len(volumeAttachments) > 0 { attachmentOps := createMachineVolumeAttachmentsOps(hostId, volumeAttachments) ops = append(ops, volumeOps...) ops = append(ops, attachmentOps...) } return ops, volumeAttachments, fsAttachments, nil }
go
func (sb *storageBackend) hostStorageOps( hostId string, args *storageParams, ) ([]txn.Op, []volumeAttachmentTemplate, []filesystemAttachmentTemplate, error) { var filesystemOps, volumeOps []txn.Op var fsAttachments []filesystemAttachmentTemplate var volumeAttachments []volumeAttachmentTemplate const ( createAndAttach = false attachOnly = true ) // Create filesystems and filesystem attachments. for _, f := range args.filesystems { ops, filesystemTag, volumeTag, err := sb.addFilesystemOps(f.Filesystem, hostId) if err != nil { return nil, nil, nil, errors.Trace(err) } filesystemOps = append(filesystemOps, ops...) fsAttachments = append(fsAttachments, filesystemAttachmentTemplate{ filesystemTag, f.Filesystem.storage, f.Attachment, createAndAttach, }) if volumeTag != (names.VolumeTag{}) { // The filesystem requires a volume, so create a volume attachment too. volumeAttachments = append(volumeAttachments, volumeAttachmentTemplate{ volumeTag, VolumeAttachmentParams{}, createAndAttach, }) } } for tag, filesystemAttachment := range args.filesystemAttachments { fsAttachments = append(fsAttachments, filesystemAttachmentTemplate{ tag, names.StorageTag{}, filesystemAttachment, attachOnly, }) } // Create volumes and volume attachments. for _, v := range args.volumes { ops, tag, err := sb.addVolumeOps(v.Volume, hostId) if err != nil { return nil, nil, nil, errors.Trace(err) } volumeOps = append(volumeOps, ops...) volumeAttachments = append(volumeAttachments, volumeAttachmentTemplate{ tag, v.Attachment, createAndAttach, }) } for tag, volumeAttachment := range args.volumeAttachments { volumeAttachments = append(volumeAttachments, volumeAttachmentTemplate{ tag, volumeAttachment, attachOnly, }) } ops := make([]txn.Op, 0, len(filesystemOps)+len(volumeOps)+len(fsAttachments)+len(volumeAttachments)) if len(fsAttachments) > 0 { attachmentOps := createMachineFilesystemAttachmentsOps(hostId, fsAttachments) ops = append(ops, filesystemOps...) ops = append(ops, attachmentOps...) } if len(volumeAttachments) > 0 { attachmentOps := createMachineVolumeAttachmentsOps(hostId, volumeAttachments) ops = append(ops, volumeOps...) ops = append(ops, attachmentOps...) } return ops, volumeAttachments, fsAttachments, nil }
[ "func", "(", "sb", "*", "storageBackend", ")", "hostStorageOps", "(", "hostId", "string", ",", "args", "*", "storageParams", ",", ")", "(", "[", "]", "txn", ".", "Op", ",", "[", "]", "volumeAttachmentTemplate", ",", "[", "]", "filesystemAttachmentTemplate", ",", "error", ")", "{", "var", "filesystemOps", ",", "volumeOps", "[", "]", "txn", ".", "Op", "\n", "var", "fsAttachments", "[", "]", "filesystemAttachmentTemplate", "\n", "var", "volumeAttachments", "[", "]", "volumeAttachmentTemplate", "\n\n", "const", "(", "createAndAttach", "=", "false", "\n", "attachOnly", "=", "true", "\n", ")", "\n\n", "// Create filesystems and filesystem attachments.", "for", "_", ",", "f", ":=", "range", "args", ".", "filesystems", "{", "ops", ",", "filesystemTag", ",", "volumeTag", ",", "err", ":=", "sb", ".", "addFilesystemOps", "(", "f", ".", "Filesystem", ",", "hostId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "filesystemOps", "=", "append", "(", "filesystemOps", ",", "ops", "...", ")", "\n", "fsAttachments", "=", "append", "(", "fsAttachments", ",", "filesystemAttachmentTemplate", "{", "filesystemTag", ",", "f", ".", "Filesystem", ".", "storage", ",", "f", ".", "Attachment", ",", "createAndAttach", ",", "}", ")", "\n", "if", "volumeTag", "!=", "(", "names", ".", "VolumeTag", "{", "}", ")", "{", "// The filesystem requires a volume, so create a volume attachment too.", "volumeAttachments", "=", "append", "(", "volumeAttachments", ",", "volumeAttachmentTemplate", "{", "volumeTag", ",", "VolumeAttachmentParams", "{", "}", ",", "createAndAttach", ",", "}", ")", "\n", "}", "\n", "}", "\n", "for", "tag", ",", "filesystemAttachment", ":=", "range", "args", ".", "filesystemAttachments", "{", "fsAttachments", "=", "append", "(", "fsAttachments", ",", "filesystemAttachmentTemplate", "{", "tag", ",", "names", ".", "StorageTag", "{", "}", ",", "filesystemAttachment", ",", "attachOnly", ",", "}", ")", "\n", "}", "\n\n", "// Create volumes and volume attachments.", "for", "_", ",", "v", ":=", "range", "args", ".", "volumes", "{", "ops", ",", "tag", ",", "err", ":=", "sb", ".", "addVolumeOps", "(", "v", ".", "Volume", ",", "hostId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "volumeOps", "=", "append", "(", "volumeOps", ",", "ops", "...", ")", "\n", "volumeAttachments", "=", "append", "(", "volumeAttachments", ",", "volumeAttachmentTemplate", "{", "tag", ",", "v", ".", "Attachment", ",", "createAndAttach", ",", "}", ")", "\n", "}", "\n", "for", "tag", ",", "volumeAttachment", ":=", "range", "args", ".", "volumeAttachments", "{", "volumeAttachments", "=", "append", "(", "volumeAttachments", ",", "volumeAttachmentTemplate", "{", "tag", ",", "volumeAttachment", ",", "attachOnly", ",", "}", ")", "\n", "}", "\n\n", "ops", ":=", "make", "(", "[", "]", "txn", ".", "Op", ",", "0", ",", "len", "(", "filesystemOps", ")", "+", "len", "(", "volumeOps", ")", "+", "len", "(", "fsAttachments", ")", "+", "len", "(", "volumeAttachments", ")", ")", "\n", "if", "len", "(", "fsAttachments", ")", ">", "0", "{", "attachmentOps", ":=", "createMachineFilesystemAttachmentsOps", "(", "hostId", ",", "fsAttachments", ")", "\n", "ops", "=", "append", "(", "ops", ",", "filesystemOps", "...", ")", "\n", "ops", "=", "append", "(", "ops", ",", "attachmentOps", "...", ")", "\n", "}", "\n", "if", "len", "(", "volumeAttachments", ")", ">", "0", "{", "attachmentOps", ":=", "createMachineVolumeAttachmentsOps", "(", "hostId", ",", "volumeAttachments", ")", "\n", "ops", "=", "append", "(", "ops", ",", "volumeOps", "...", ")", "\n", "ops", "=", "append", "(", "ops", ",", "attachmentOps", "...", ")", "\n", "}", "\n", "return", "ops", ",", "volumeAttachments", ",", "fsAttachments", ",", "nil", "\n", "}" ]
// hostStorageOps creates txn.Ops for creating volumes, filesystems, // and attachments to the specified host. The results are the txn.Ops, // and the tags of volumes and filesystems newly attached to the host.
[ "hostStorageOps", "creates", "txn", ".", "Ops", "for", "creating", "volumes", "filesystems", "and", "attachments", "to", "the", "specified", "host", ".", "The", "results", "are", "the", "txn", ".", "Ops", "and", "the", "tags", "of", "volumes", "and", "filesystems", "newly", "attached", "to", "the", "host", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage.go#L2259-L2323
156,311
juju/juju
state/storage.go
addMachineStorageAttachmentsOps
func addMachineStorageAttachmentsOps( machine *Machine, volumes []volumeAttachmentTemplate, filesystems []filesystemAttachmentTemplate, ) ([]txn.Op, error) { var addToSet bson.D assert := isAliveDoc if len(volumes) > 0 { volumeIds := make([]string, len(volumes)) for i, v := range volumes { volumeIds[i] = v.tag.Id() } addToSet = append(addToSet, bson.DocElem{ "volumes", bson.D{{"$each", volumeIds}}, }) } if len(filesystems) > 0 { filesystemIds := make([]string, len(filesystems)) var withLocation []filesystemAttachmentTemplate for i, f := range filesystems { filesystemIds[i] = f.tag.Id() if !f.params.locationAutoGenerated { // If the location was not automatically // generated, we must ensure it does not // conflict with any existing storage. // Generated paths are guaranteed to be // unique. withLocation = append(withLocation, f) } } addToSet = append(addToSet, bson.DocElem{ "filesystems", bson.D{{"$each", filesystemIds}}, }) if len(withLocation) > 0 { if err := validateFilesystemMountPoints(machine, withLocation); err != nil { return nil, errors.Annotate(err, "validating filesystem mount points") } // Make sure no filesystems are added concurrently. assert = append(assert, bson.DocElem{ "filesystems", bson.D{{"$not", bson.D{{ "$elemMatch", bson.D{{ "$nin", machine.doc.Filesystems, }}, }}}}, }) } } var update interface{} if len(addToSet) > 0 { update = bson.D{{"$addToSet", addToSet}} } return []txn.Op{{ C: machinesC, Id: machine.doc.Id, Assert: assert, Update: update, }}, nil }
go
func addMachineStorageAttachmentsOps( machine *Machine, volumes []volumeAttachmentTemplate, filesystems []filesystemAttachmentTemplate, ) ([]txn.Op, error) { var addToSet bson.D assert := isAliveDoc if len(volumes) > 0 { volumeIds := make([]string, len(volumes)) for i, v := range volumes { volumeIds[i] = v.tag.Id() } addToSet = append(addToSet, bson.DocElem{ "volumes", bson.D{{"$each", volumeIds}}, }) } if len(filesystems) > 0 { filesystemIds := make([]string, len(filesystems)) var withLocation []filesystemAttachmentTemplate for i, f := range filesystems { filesystemIds[i] = f.tag.Id() if !f.params.locationAutoGenerated { // If the location was not automatically // generated, we must ensure it does not // conflict with any existing storage. // Generated paths are guaranteed to be // unique. withLocation = append(withLocation, f) } } addToSet = append(addToSet, bson.DocElem{ "filesystems", bson.D{{"$each", filesystemIds}}, }) if len(withLocation) > 0 { if err := validateFilesystemMountPoints(machine, withLocation); err != nil { return nil, errors.Annotate(err, "validating filesystem mount points") } // Make sure no filesystems are added concurrently. assert = append(assert, bson.DocElem{ "filesystems", bson.D{{"$not", bson.D{{ "$elemMatch", bson.D{{ "$nin", machine.doc.Filesystems, }}, }}}}, }) } } var update interface{} if len(addToSet) > 0 { update = bson.D{{"$addToSet", addToSet}} } return []txn.Op{{ C: machinesC, Id: machine.doc.Id, Assert: assert, Update: update, }}, nil }
[ "func", "addMachineStorageAttachmentsOps", "(", "machine", "*", "Machine", ",", "volumes", "[", "]", "volumeAttachmentTemplate", ",", "filesystems", "[", "]", "filesystemAttachmentTemplate", ",", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "var", "addToSet", "bson", ".", "D", "\n", "assert", ":=", "isAliveDoc", "\n", "if", "len", "(", "volumes", ")", ">", "0", "{", "volumeIds", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "volumes", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "volumes", "{", "volumeIds", "[", "i", "]", "=", "v", ".", "tag", ".", "Id", "(", ")", "\n", "}", "\n", "addToSet", "=", "append", "(", "addToSet", ",", "bson", ".", "DocElem", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "volumeIds", "}", "}", ",", "}", ")", "\n", "}", "\n", "if", "len", "(", "filesystems", ")", ">", "0", "{", "filesystemIds", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "filesystems", ")", ")", "\n", "var", "withLocation", "[", "]", "filesystemAttachmentTemplate", "\n", "for", "i", ",", "f", ":=", "range", "filesystems", "{", "filesystemIds", "[", "i", "]", "=", "f", ".", "tag", ".", "Id", "(", ")", "\n", "if", "!", "f", ".", "params", ".", "locationAutoGenerated", "{", "// If the location was not automatically", "// generated, we must ensure it does not", "// conflict with any existing storage.", "// Generated paths are guaranteed to be", "// unique.", "withLocation", "=", "append", "(", "withLocation", ",", "f", ")", "\n", "}", "\n", "}", "\n", "addToSet", "=", "append", "(", "addToSet", ",", "bson", ".", "DocElem", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "filesystemIds", "}", "}", ",", "}", ")", "\n", "if", "len", "(", "withLocation", ")", ">", "0", "{", "if", "err", ":=", "validateFilesystemMountPoints", "(", "machine", ",", "withLocation", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "// Make sure no filesystems are added concurrently.", "assert", "=", "append", "(", "assert", ",", "bson", ".", "DocElem", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "machine", ".", "doc", ".", "Filesystems", ",", "}", "}", ",", "}", "}", "}", "}", ",", "}", ")", "\n", "}", "\n", "}", "\n", "var", "update", "interface", "{", "}", "\n", "if", "len", "(", "addToSet", ")", ">", "0", "{", "update", "=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "addToSet", "}", "}", "\n", "}", "\n", "return", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "machinesC", ",", "Id", ":", "machine", ".", "doc", ".", "Id", ",", "Assert", ":", "assert", ",", "Update", ":", "update", ",", "}", "}", ",", "nil", "\n", "}" ]
// addMachineStorageAttachmentsOps returns txn.Ops for adding the IDs of // attached volumes and filesystems to an existing machine. Filesystem // mount points are checked against existing filesystem attachments for // conflicts, with a txn.Op added to prevent concurrent additions as // necessary.
[ "addMachineStorageAttachmentsOps", "returns", "txn", ".", "Ops", "for", "adding", "the", "IDs", "of", "attached", "volumes", "and", "filesystems", "to", "an", "existing", "machine", ".", "Filesystem", "mount", "points", "are", "checked", "against", "existing", "filesystem", "attachments", "for", "conflicts", "with", "a", "txn", ".", "Op", "added", "to", "prevent", "concurrent", "additions", "as", "necessary", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage.go#L2330-L2387
156,312
juju/juju
worker/logforwarder/sinks/syslog.go
OpenSyslog
func OpenSyslog(cfg *syslog.RawConfig) (*logforwarder.LogSink, error) { if !cfg.Enabled { return nil, errors.New("log forwarding not enabled") } client, err := syslog.Open(*cfg) if err != nil { return nil, errors.Trace(err) } if client == nil { // TODO(axw) we should be returning an error // which we interpret up the stack. return &logforwarder.LogSink{ SendCloser: emptySendCloser{}, }, nil } sink := &logforwarder.LogSink{ SendCloser: client, } return sink, nil }
go
func OpenSyslog(cfg *syslog.RawConfig) (*logforwarder.LogSink, error) { if !cfg.Enabled { return nil, errors.New("log forwarding not enabled") } client, err := syslog.Open(*cfg) if err != nil { return nil, errors.Trace(err) } if client == nil { // TODO(axw) we should be returning an error // which we interpret up the stack. return &logforwarder.LogSink{ SendCloser: emptySendCloser{}, }, nil } sink := &logforwarder.LogSink{ SendCloser: client, } return sink, nil }
[ "func", "OpenSyslog", "(", "cfg", "*", "syslog", ".", "RawConfig", ")", "(", "*", "logforwarder", ".", "LogSink", ",", "error", ")", "{", "if", "!", "cfg", ".", "Enabled", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "client", ",", "err", ":=", "syslog", ".", "Open", "(", "*", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "client", "==", "nil", "{", "// TODO(axw) we should be returning an error", "// which we interpret up the stack.", "return", "&", "logforwarder", ".", "LogSink", "{", "SendCloser", ":", "emptySendCloser", "{", "}", ",", "}", ",", "nil", "\n", "}", "\n", "sink", ":=", "&", "logforwarder", ".", "LogSink", "{", "SendCloser", ":", "client", ",", "}", "\n", "return", "sink", ",", "nil", "\n", "}" ]
// OpenSyslog returns a sink used to receive log messages to be forwarded.
[ "OpenSyslog", "returns", "a", "sink", "used", "to", "receive", "log", "messages", "to", "be", "forwarded", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/logforwarder/sinks/syslog.go#L15-L34
156,313
juju/juju
apiserver/restrict_restore.go
aboutToRestoreMethodsOnly
func aboutToRestoreMethodsOnly(facadeName string, methodName string) error { fullName := facadeName + "." + methodName if !allowedMethodsAboutToRestore.Contains(fullName) { return aboutToRestoreError } return nil }
go
func aboutToRestoreMethodsOnly(facadeName string, methodName string) error { fullName := facadeName + "." + methodName if !allowedMethodsAboutToRestore.Contains(fullName) { return aboutToRestoreError } return nil }
[ "func", "aboutToRestoreMethodsOnly", "(", "facadeName", "string", ",", "methodName", "string", ")", "error", "{", "fullName", ":=", "facadeName", "+", "\"", "\"", "+", "methodName", "\n", "if", "!", "allowedMethodsAboutToRestore", ".", "Contains", "(", "fullName", ")", "{", "return", "aboutToRestoreError", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// aboutToRestoreMethodsOnly can be used with restrictRoot to restrict // the API to the methods allowed when the server is in // state.RestorePreparing mode.
[ "aboutToRestoreMethodsOnly", "can", "be", "used", "with", "restrictRoot", "to", "restrict", "the", "API", "to", "the", "methods", "allowed", "when", "the", "server", "is", "in", "state", ".", "RestorePreparing", "mode", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/restrict_restore.go#L17-L23
156,314
juju/juju
caas/kubernetes/provider/mocks/serviceaccount_mock.go
NewMockServiceAccountInterface
func NewMockServiceAccountInterface(ctrl *gomock.Controller) *MockServiceAccountInterface { mock := &MockServiceAccountInterface{ctrl: ctrl} mock.recorder = &MockServiceAccountInterfaceMockRecorder{mock} return mock }
go
func NewMockServiceAccountInterface(ctrl *gomock.Controller) *MockServiceAccountInterface { mock := &MockServiceAccountInterface{ctrl: ctrl} mock.recorder = &MockServiceAccountInterfaceMockRecorder{mock} return mock }
[ "func", "NewMockServiceAccountInterface", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockServiceAccountInterface", "{", "mock", ":=", "&", "MockServiceAccountInterface", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockServiceAccountInterfaceMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockServiceAccountInterface creates a new mock instance
[ "NewMockServiceAccountInterface", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/serviceaccount_mock.go#L29-L33
156,315
juju/juju
caas/kubernetes/provider/mocks/serviceaccount_mock.go
CreateToken
func (m *MockServiceAccountInterface) CreateToken(arg0 string, arg1 *v1.TokenRequest) (*v1.TokenRequest, error) { ret := m.ctrl.Call(m, "CreateToken", arg0, arg1) ret0, _ := ret[0].(*v1.TokenRequest) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockServiceAccountInterface) CreateToken(arg0 string, arg1 *v1.TokenRequest) (*v1.TokenRequest, error) { ret := m.ctrl.Call(m, "CreateToken", arg0, arg1) ret0, _ := ret[0].(*v1.TokenRequest) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockServiceAccountInterface", ")", "CreateToken", "(", "arg0", "string", ",", "arg1", "*", "v1", ".", "TokenRequest", ")", "(", "*", "v1", ".", "TokenRequest", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "*", "v1", ".", "TokenRequest", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "error", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// CreateToken mocks base method
[ "CreateToken", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/serviceaccount_mock.go#L54-L59
156,316
juju/juju
apiserver/params/network.go
FromNetworkPort
func FromNetworkPort(p corenetwork.Port) Port { return Port{ Protocol: p.Protocol, Number: p.Number, } }
go
func FromNetworkPort(p corenetwork.Port) Port { return Port{ Protocol: p.Protocol, Number: p.Number, } }
[ "func", "FromNetworkPort", "(", "p", "corenetwork", ".", "Port", ")", "Port", "{", "return", "Port", "{", "Protocol", ":", "p", ".", "Protocol", ",", "Number", ":", "p", ".", "Number", ",", "}", "\n", "}" ]
// FromNetworkPort is a convenience helper to create a parameter // out of the network type, here for Port.
[ "FromNetworkPort", "is", "a", "convenience", "helper", "to", "create", "a", "parameter", "out", "of", "the", "network", "type", "here", "for", "Port", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L209-L214
156,317
juju/juju
apiserver/params/network.go
NetworkPort
func (p Port) NetworkPort() corenetwork.Port { return corenetwork.Port{ Protocol: p.Protocol, Number: p.Number, } }
go
func (p Port) NetworkPort() corenetwork.Port { return corenetwork.Port{ Protocol: p.Protocol, Number: p.Number, } }
[ "func", "(", "p", "Port", ")", "NetworkPort", "(", ")", "corenetwork", ".", "Port", "{", "return", "corenetwork", ".", "Port", "{", "Protocol", ":", "p", ".", "Protocol", ",", "Number", ":", "p", ".", "Number", ",", "}", "\n", "}" ]
// NetworkPort is a convenience helper to return the parameter // as network type, here for Port.
[ "NetworkPort", "is", "a", "convenience", "helper", "to", "return", "the", "parameter", "as", "network", "type", "here", "for", "Port", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L218-L223
156,318
juju/juju
apiserver/params/network.go
FromNetworkPortRange
func FromNetworkPortRange(pr corenetwork.PortRange) PortRange { return PortRange{ FromPort: pr.FromPort, ToPort: pr.ToPort, Protocol: pr.Protocol, } }
go
func FromNetworkPortRange(pr corenetwork.PortRange) PortRange { return PortRange{ FromPort: pr.FromPort, ToPort: pr.ToPort, Protocol: pr.Protocol, } }
[ "func", "FromNetworkPortRange", "(", "pr", "corenetwork", ".", "PortRange", ")", "PortRange", "{", "return", "PortRange", "{", "FromPort", ":", "pr", ".", "FromPort", ",", "ToPort", ":", "pr", ".", "ToPort", ",", "Protocol", ":", "pr", ".", "Protocol", ",", "}", "\n", "}" ]
// FromNetworkPortRange is a convenience helper to create a parameter // out of the network type, here for PortRange.
[ "FromNetworkPortRange", "is", "a", "convenience", "helper", "to", "create", "a", "parameter", "out", "of", "the", "network", "type", "here", "for", "PortRange", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L236-L242
156,319
juju/juju
apiserver/params/network.go
NetworkPortRange
func (pr PortRange) NetworkPortRange() corenetwork.PortRange { return corenetwork.PortRange{ FromPort: pr.FromPort, ToPort: pr.ToPort, Protocol: pr.Protocol, } }
go
func (pr PortRange) NetworkPortRange() corenetwork.PortRange { return corenetwork.PortRange{ FromPort: pr.FromPort, ToPort: pr.ToPort, Protocol: pr.Protocol, } }
[ "func", "(", "pr", "PortRange", ")", "NetworkPortRange", "(", ")", "corenetwork", ".", "PortRange", "{", "return", "corenetwork", ".", "PortRange", "{", "FromPort", ":", "pr", ".", "FromPort", ",", "ToPort", ":", "pr", ".", "ToPort", ",", "Protocol", ":", "pr", ".", "Protocol", ",", "}", "\n", "}" ]
// NetworkPortRange is a convenience helper to return the parameter // as network type, here for PortRange.
[ "NetworkPortRange", "is", "a", "convenience", "helper", "to", "return", "the", "parameter", "as", "network", "type", "here", "for", "PortRange", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L246-L252
156,320
juju/juju
apiserver/params/network.go
FromNetworkAddress
func FromNetworkAddress(naddr network.Address) Address { return Address{ Value: naddr.Value, Type: string(naddr.Type), Scope: string(naddr.Scope), SpaceName: string(naddr.SpaceName), } }
go
func FromNetworkAddress(naddr network.Address) Address { return Address{ Value: naddr.Value, Type: string(naddr.Type), Scope: string(naddr.Scope), SpaceName: string(naddr.SpaceName), } }
[ "func", "FromNetworkAddress", "(", "naddr", "network", ".", "Address", ")", "Address", "{", "return", "Address", "{", "Value", ":", "naddr", ".", "Value", ",", "Type", ":", "string", "(", "naddr", ".", "Type", ")", ",", "Scope", ":", "string", "(", "naddr", ".", "Scope", ")", ",", "SpaceName", ":", "string", "(", "naddr", ".", "SpaceName", ")", ",", "}", "\n", "}" ]
// FromNetworkAddress is a convenience helper to create a parameter // out of the network type, here for Address.
[ "FromNetworkAddress", "is", "a", "convenience", "helper", "to", "create", "a", "parameter", "out", "of", "the", "network", "type", "here", "for", "Address", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L294-L301
156,321
juju/juju
apiserver/params/network.go
NetworkAddress
func (addr Address) NetworkAddress() network.Address { return network.Address{ Value: addr.Value, Type: network.AddressType(addr.Type), Scope: network.Scope(addr.Scope), SpaceName: network.SpaceName(addr.SpaceName), } }
go
func (addr Address) NetworkAddress() network.Address { return network.Address{ Value: addr.Value, Type: network.AddressType(addr.Type), Scope: network.Scope(addr.Scope), SpaceName: network.SpaceName(addr.SpaceName), } }
[ "func", "(", "addr", "Address", ")", "NetworkAddress", "(", ")", "network", ".", "Address", "{", "return", "network", ".", "Address", "{", "Value", ":", "addr", ".", "Value", ",", "Type", ":", "network", ".", "AddressType", "(", "addr", ".", "Type", ")", ",", "Scope", ":", "network", ".", "Scope", "(", "addr", ".", "Scope", ")", ",", "SpaceName", ":", "network", ".", "SpaceName", "(", "addr", ".", "SpaceName", ")", ",", "}", "\n", "}" ]
// NetworkAddress is a convenience helper to return the parameter // as network type, here for Address.
[ "NetworkAddress", "is", "a", "convenience", "helper", "to", "return", "the", "parameter", "as", "network", "type", "here", "for", "Address", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L305-L312
156,322
juju/juju
apiserver/params/network.go
FromNetworkAddresses
func FromNetworkAddresses(naddrs ...network.Address) []Address { addrs := make([]Address, len(naddrs)) for i, naddr := range naddrs { addrs[i] = FromNetworkAddress(naddr) } return addrs }
go
func FromNetworkAddresses(naddrs ...network.Address) []Address { addrs := make([]Address, len(naddrs)) for i, naddr := range naddrs { addrs[i] = FromNetworkAddress(naddr) } return addrs }
[ "func", "FromNetworkAddresses", "(", "naddrs", "...", "network", ".", "Address", ")", "[", "]", "Address", "{", "addrs", ":=", "make", "(", "[", "]", "Address", ",", "len", "(", "naddrs", ")", ")", "\n", "for", "i", ",", "naddr", ":=", "range", "naddrs", "{", "addrs", "[", "i", "]", "=", "FromNetworkAddress", "(", "naddr", ")", "\n", "}", "\n", "return", "addrs", "\n", "}" ]
// FromNetworkAddresses is a convenience helper to create a parameter // out of the network type, here for a slice of Address.
[ "FromNetworkAddresses", "is", "a", "convenience", "helper", "to", "create", "a", "parameter", "out", "of", "the", "network", "type", "here", "for", "a", "slice", "of", "Address", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L316-L322
156,323
juju/juju
apiserver/params/network.go
NetworkAddresses
func NetworkAddresses(addrs ...Address) []network.Address { naddrs := make([]network.Address, len(addrs)) for i, addr := range addrs { naddrs[i] = addr.NetworkAddress() } return naddrs }
go
func NetworkAddresses(addrs ...Address) []network.Address { naddrs := make([]network.Address, len(addrs)) for i, addr := range addrs { naddrs[i] = addr.NetworkAddress() } return naddrs }
[ "func", "NetworkAddresses", "(", "addrs", "...", "Address", ")", "[", "]", "network", ".", "Address", "{", "naddrs", ":=", "make", "(", "[", "]", "network", ".", "Address", ",", "len", "(", "addrs", ")", ")", "\n", "for", "i", ",", "addr", ":=", "range", "addrs", "{", "naddrs", "[", "i", "]", "=", "addr", ".", "NetworkAddress", "(", ")", "\n", "}", "\n", "return", "naddrs", "\n", "}" ]
// NetworkAddresses is a convenience helper to return the parameter // as network type, here for a slice of Address.
[ "NetworkAddresses", "is", "a", "convenience", "helper", "to", "return", "the", "parameter", "as", "network", "type", "here", "for", "a", "slice", "of", "Address", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L326-L332
156,324
juju/juju
apiserver/params/network.go
FromNetworkHostPort
func FromNetworkHostPort(nhp network.HostPort) HostPort { return HostPort{FromNetworkAddress(nhp.Address), nhp.Port} }
go
func FromNetworkHostPort(nhp network.HostPort) HostPort { return HostPort{FromNetworkAddress(nhp.Address), nhp.Port} }
[ "func", "FromNetworkHostPort", "(", "nhp", "network", ".", "HostPort", ")", "HostPort", "{", "return", "HostPort", "{", "FromNetworkAddress", "(", "nhp", ".", "Address", ")", ",", "nhp", ".", "Port", "}", "\n", "}" ]
// FromNetworkHostPort is a convenience helper to create a parameter // out of the network type, here for HostPort.
[ "FromNetworkHostPort", "is", "a", "convenience", "helper", "to", "create", "a", "parameter", "out", "of", "the", "network", "type", "here", "for", "HostPort", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L344-L346
156,325
juju/juju
apiserver/params/network.go
NetworkHostPort
func (hp HostPort) NetworkHostPort() network.HostPort { return network.HostPort{hp.Address.NetworkAddress(), hp.Port} }
go
func (hp HostPort) NetworkHostPort() network.HostPort { return network.HostPort{hp.Address.NetworkAddress(), hp.Port} }
[ "func", "(", "hp", "HostPort", ")", "NetworkHostPort", "(", ")", "network", ".", "HostPort", "{", "return", "network", ".", "HostPort", "{", "hp", ".", "Address", ".", "NetworkAddress", "(", ")", ",", "hp", ".", "Port", "}", "\n", "}" ]
// NetworkHostPort is a convenience helper to return the parameter // as network type, here for HostPort.
[ "NetworkHostPort", "is", "a", "convenience", "helper", "to", "return", "the", "parameter", "as", "network", "type", "here", "for", "HostPort", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L350-L352
156,326
juju/juju
apiserver/params/network.go
FromNetworkHostPorts
func FromNetworkHostPorts(nhps []network.HostPort) []HostPort { hps := make([]HostPort, len(nhps)) for i, nhp := range nhps { hps[i] = FromNetworkHostPort(nhp) } return hps }
go
func FromNetworkHostPorts(nhps []network.HostPort) []HostPort { hps := make([]HostPort, len(nhps)) for i, nhp := range nhps { hps[i] = FromNetworkHostPort(nhp) } return hps }
[ "func", "FromNetworkHostPorts", "(", "nhps", "[", "]", "network", ".", "HostPort", ")", "[", "]", "HostPort", "{", "hps", ":=", "make", "(", "[", "]", "HostPort", ",", "len", "(", "nhps", ")", ")", "\n", "for", "i", ",", "nhp", ":=", "range", "nhps", "{", "hps", "[", "i", "]", "=", "FromNetworkHostPort", "(", "nhp", ")", "\n", "}", "\n", "return", "hps", "\n", "}" ]
// FromNetworkHostPorts is a helper to create a parameter // out of the network type, here for a slice of HostPort.
[ "FromNetworkHostPorts", "is", "a", "helper", "to", "create", "a", "parameter", "out", "of", "the", "network", "type", "here", "for", "a", "slice", "of", "HostPort", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L356-L362
156,327
juju/juju
apiserver/params/network.go
NetworkHostPorts
func NetworkHostPorts(hps []HostPort) []network.HostPort { nhps := make([]network.HostPort, len(hps)) for i, hp := range hps { nhps[i] = hp.NetworkHostPort() } return nhps }
go
func NetworkHostPorts(hps []HostPort) []network.HostPort { nhps := make([]network.HostPort, len(hps)) for i, hp := range hps { nhps[i] = hp.NetworkHostPort() } return nhps }
[ "func", "NetworkHostPorts", "(", "hps", "[", "]", "HostPort", ")", "[", "]", "network", ".", "HostPort", "{", "nhps", ":=", "make", "(", "[", "]", "network", ".", "HostPort", ",", "len", "(", "hps", ")", ")", "\n", "for", "i", ",", "hp", ":=", "range", "hps", "{", "nhps", "[", "i", "]", "=", "hp", ".", "NetworkHostPort", "(", ")", "\n", "}", "\n", "return", "nhps", "\n", "}" ]
// NetworkHostPorts is a convenience helper to return the parameter // as network type, here for a slice of HostPort.
[ "NetworkHostPorts", "is", "a", "convenience", "helper", "to", "return", "the", "parameter", "as", "network", "type", "here", "for", "a", "slice", "of", "HostPort", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L366-L372
156,328
juju/juju
apiserver/params/network.go
FromNetworkHostsPorts
func FromNetworkHostsPorts(nhpm [][]network.HostPort) [][]HostPort { hpm := make([][]HostPort, len(nhpm)) for i, nhps := range nhpm { hpm[i] = FromNetworkHostPorts(nhps) } return hpm }
go
func FromNetworkHostsPorts(nhpm [][]network.HostPort) [][]HostPort { hpm := make([][]HostPort, len(nhpm)) for i, nhps := range nhpm { hpm[i] = FromNetworkHostPorts(nhps) } return hpm }
[ "func", "FromNetworkHostsPorts", "(", "nhpm", "[", "]", "[", "]", "network", ".", "HostPort", ")", "[", "]", "[", "]", "HostPort", "{", "hpm", ":=", "make", "(", "[", "]", "[", "]", "HostPort", ",", "len", "(", "nhpm", ")", ")", "\n", "for", "i", ",", "nhps", ":=", "range", "nhpm", "{", "hpm", "[", "i", "]", "=", "FromNetworkHostPorts", "(", "nhps", ")", "\n", "}", "\n", "return", "hpm", "\n", "}" ]
// FromNetworkHostsPorts is a helper to create a parameter // out of the network type, here for a nested slice of HostPort.
[ "FromNetworkHostsPorts", "is", "a", "helper", "to", "create", "a", "parameter", "out", "of", "the", "network", "type", "here", "for", "a", "nested", "slice", "of", "HostPort", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L376-L382
156,329
juju/juju
apiserver/params/network.go
NetworkHostsPorts
func NetworkHostsPorts(hpm [][]HostPort) [][]network.HostPort { nhpm := make([][]network.HostPort, len(hpm)) for i, hps := range hpm { nhpm[i] = NetworkHostPorts(hps) } return nhpm }
go
func NetworkHostsPorts(hpm [][]HostPort) [][]network.HostPort { nhpm := make([][]network.HostPort, len(hpm)) for i, hps := range hpm { nhpm[i] = NetworkHostPorts(hps) } return nhpm }
[ "func", "NetworkHostsPorts", "(", "hpm", "[", "]", "[", "]", "HostPort", ")", "[", "]", "[", "]", "network", ".", "HostPort", "{", "nhpm", ":=", "make", "(", "[", "]", "[", "]", "network", ".", "HostPort", ",", "len", "(", "hpm", ")", ")", "\n", "for", "i", ",", "hps", ":=", "range", "hpm", "{", "nhpm", "[", "i", "]", "=", "NetworkHostPorts", "(", "hps", ")", "\n", "}", "\n", "return", "nhpm", "\n", "}" ]
// NetworkHostsPorts is a convenience helper to return the parameter // as network type, here for a nested slice of HostPort.
[ "NetworkHostsPorts", "is", "a", "convenience", "helper", "to", "return", "the", "parameter", "as", "network", "type", "here", "for", "a", "nested", "slice", "of", "HostPort", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/network.go#L386-L392
156,330
juju/juju
upgrades/steps_25.go
stateStepsFor25
func stateStepsFor25() []Step { return []Step{ &upgradeStep{ description: `migrate storage records to use "hostid" field`, targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().MigrateStorageMachineIdFields() }, }, &upgradeStep{ description: "migrate legacy leases into raft", targets: []Target{Controller}, run: MigrateLegacyLeases, }, &upgradeStep{ description: "migrate add-model permissions", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().MigrateAddModelPermissions() }, }, &upgradeStep{ description: "set enable-disk-uuid (if on vsphere)", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().SetEnableDiskUUIDOnVsphere() }, }, } }
go
func stateStepsFor25() []Step { return []Step{ &upgradeStep{ description: `migrate storage records to use "hostid" field`, targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().MigrateStorageMachineIdFields() }, }, &upgradeStep{ description: "migrate legacy leases into raft", targets: []Target{Controller}, run: MigrateLegacyLeases, }, &upgradeStep{ description: "migrate add-model permissions", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().MigrateAddModelPermissions() }, }, &upgradeStep{ description: "set enable-disk-uuid (if on vsphere)", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().SetEnableDiskUUIDOnVsphere() }, }, } }
[ "func", "stateStepsFor25", "(", ")", "[", "]", "Step", "{", "return", "[", "]", "Step", "{", "&", "upgradeStep", "{", "description", ":", "`migrate storage records to use \"hostid\" field`", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "context", ".", "State", "(", ")", ".", "MigrateStorageMachineIdFields", "(", ")", "\n", "}", ",", "}", ",", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "Controller", "}", ",", "run", ":", "MigrateLegacyLeases", ",", "}", ",", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "context", ".", "State", "(", ")", ".", "MigrateAddModelPermissions", "(", ")", "\n", "}", ",", "}", ",", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "context", ".", "State", "(", ")", ".", "SetEnableDiskUUIDOnVsphere", "(", ")", "\n", "}", ",", "}", ",", "}", "\n", "}" ]
// stateStepsFor25 returns upgrade steps for Juju 2.5.0 that manipulate state directly.
[ "stateStepsFor25", "returns", "upgrade", "steps", "for", "Juju", "2", ".", "5", ".", "0", "that", "manipulate", "state", "directly", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/steps_25.go#L7-L36
156,331
juju/juju
apiserver/root.go
newAPIHandler
func newAPIHandler(srv *Server, st *state.State, rpcConn *rpc.Conn, modelUUID string, connectionID uint64, serverHost string) (*apiHandler, error) { m, err := st.Model() if err != nil { if !errors.IsNotFound(err) { return nil, errors.Trace(err) } // If this model used to be hosted on this controller but got // migrated allow clients to connect and wait for a login // request to decide whether the users should be redirected to // the new controller for this model or not. if _, migErr := st.LatestRemovedModelMigration(); migErr != nil { return nil, errors.Trace(err) // return original NotFound error } } r := &apiHandler{ state: st, model: m, resources: common.NewResources(), shared: srv.shared, rpcConn: rpcConn, modelUUID: modelUUID, connectionID: connectionID, serverHost: serverHost, } if err := r.resources.RegisterNamed("machineID", common.StringResource(srv.tag.Id())); err != nil { return nil, errors.Trace(err) } if err := r.resources.RegisterNamed("dataDir", common.StringResource(srv.dataDir)); err != nil { return nil, errors.Trace(err) } if err := r.resources.RegisterNamed("logDir", common.StringResource(srv.logDir)); err != nil { return nil, errors.Trace(err) } // Facades involved with managing application offers need the auth context // to mint and validate macaroons. localOfferAccessEndpoint := url.URL{ Scheme: "https", Host: serverHost, Path: localOfferAccessLocationPath, } offerAuthCtxt := srv.offerAuthCtxt.WithDischargeURL(localOfferAccessEndpoint.String()) if err := r.resources.RegisterNamed( "offerAccessAuthContext", common.ValueResource{Value: offerAuthCtxt}, ); err != nil { return nil, errors.Trace(err) } return r, nil }
go
func newAPIHandler(srv *Server, st *state.State, rpcConn *rpc.Conn, modelUUID string, connectionID uint64, serverHost string) (*apiHandler, error) { m, err := st.Model() if err != nil { if !errors.IsNotFound(err) { return nil, errors.Trace(err) } // If this model used to be hosted on this controller but got // migrated allow clients to connect and wait for a login // request to decide whether the users should be redirected to // the new controller for this model or not. if _, migErr := st.LatestRemovedModelMigration(); migErr != nil { return nil, errors.Trace(err) // return original NotFound error } } r := &apiHandler{ state: st, model: m, resources: common.NewResources(), shared: srv.shared, rpcConn: rpcConn, modelUUID: modelUUID, connectionID: connectionID, serverHost: serverHost, } if err := r.resources.RegisterNamed("machineID", common.StringResource(srv.tag.Id())); err != nil { return nil, errors.Trace(err) } if err := r.resources.RegisterNamed("dataDir", common.StringResource(srv.dataDir)); err != nil { return nil, errors.Trace(err) } if err := r.resources.RegisterNamed("logDir", common.StringResource(srv.logDir)); err != nil { return nil, errors.Trace(err) } // Facades involved with managing application offers need the auth context // to mint and validate macaroons. localOfferAccessEndpoint := url.URL{ Scheme: "https", Host: serverHost, Path: localOfferAccessLocationPath, } offerAuthCtxt := srv.offerAuthCtxt.WithDischargeURL(localOfferAccessEndpoint.String()) if err := r.resources.RegisterNamed( "offerAccessAuthContext", common.ValueResource{Value: offerAuthCtxt}, ); err != nil { return nil, errors.Trace(err) } return r, nil }
[ "func", "newAPIHandler", "(", "srv", "*", "Server", ",", "st", "*", "state", ".", "State", ",", "rpcConn", "*", "rpc", ".", "Conn", ",", "modelUUID", "string", ",", "connectionID", "uint64", ",", "serverHost", "string", ")", "(", "*", "apiHandler", ",", "error", ")", "{", "m", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// If this model used to be hosted on this controller but got", "// migrated allow clients to connect and wait for a login", "// request to decide whether the users should be redirected to", "// the new controller for this model or not.", "if", "_", ",", "migErr", ":=", "st", ".", "LatestRemovedModelMigration", "(", ")", ";", "migErr", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "// return original NotFound error", "\n", "}", "\n", "}", "\n\n", "r", ":=", "&", "apiHandler", "{", "state", ":", "st", ",", "model", ":", "m", ",", "resources", ":", "common", ".", "NewResources", "(", ")", ",", "shared", ":", "srv", ".", "shared", ",", "rpcConn", ":", "rpcConn", ",", "modelUUID", ":", "modelUUID", ",", "connectionID", ":", "connectionID", ",", "serverHost", ":", "serverHost", ",", "}", "\n\n", "if", "err", ":=", "r", ".", "resources", ".", "RegisterNamed", "(", "\"", "\"", ",", "common", ".", "StringResource", "(", "srv", ".", "tag", ".", "Id", "(", ")", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "r", ".", "resources", ".", "RegisterNamed", "(", "\"", "\"", ",", "common", ".", "StringResource", "(", "srv", ".", "dataDir", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "r", ".", "resources", ".", "RegisterNamed", "(", "\"", "\"", ",", "common", ".", "StringResource", "(", "srv", ".", "logDir", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Facades involved with managing application offers need the auth context", "// to mint and validate macaroons.", "localOfferAccessEndpoint", ":=", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "serverHost", ",", "Path", ":", "localOfferAccessLocationPath", ",", "}", "\n", "offerAuthCtxt", ":=", "srv", ".", "offerAuthCtxt", ".", "WithDischargeURL", "(", "localOfferAccessEndpoint", ".", "String", "(", ")", ")", "\n", "if", "err", ":=", "r", ".", "resources", ".", "RegisterNamed", "(", "\"", "\"", ",", "common", ".", "ValueResource", "{", "Value", ":", "offerAuthCtxt", "}", ",", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "r", ",", "nil", "\n", "}" ]
// newAPIHandler returns a new apiHandler.
[ "newAPIHandler", "returns", "a", "new", "apiHandler", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L73-L125
156,332
juju/juju
apiserver/root.go
Call
func (s *srvCaller) Call(ctx context.Context, objId string, arg reflect.Value) (reflect.Value, error) { objVal, err := s.creator(objId) if err != nil { return reflect.Value{}, err } return s.objMethod.Call(ctx, objVal, arg) }
go
func (s *srvCaller) Call(ctx context.Context, objId string, arg reflect.Value) (reflect.Value, error) { objVal, err := s.creator(objId) if err != nil { return reflect.Value{}, err } return s.objMethod.Call(ctx, objVal, arg) }
[ "func", "(", "s", "*", "srvCaller", ")", "Call", "(", "ctx", "context", ".", "Context", ",", "objId", "string", ",", "arg", "reflect", ".", "Value", ")", "(", "reflect", ".", "Value", ",", "error", ")", "{", "objVal", ",", "err", ":=", "s", ".", "creator", "(", "objId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "reflect", ".", "Value", "{", "}", ",", "err", "\n", "}", "\n", "return", "s", ".", "objMethod", ".", "Call", "(", "ctx", ",", "objVal", ",", "arg", ")", "\n", "}" ]
// Call takes the object Id and an instance of ParamsType to create an object and place // a call on its method. It then returns an instance of ResultType.
[ "Call", "takes", "the", "object", "Id", "and", "an", "instance", "of", "ParamsType", "to", "create", "an", "object", "and", "place", "a", "call", "on", "its", "method", ".", "It", "then", "returns", "an", "instance", "of", "ResultType", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L165-L171
156,333
juju/juju
apiserver/root.go
newAPIRoot
func newAPIRoot(st *state.State, shared *sharedServerContext, facades *facade.Registry, resources *common.Resources, authorizer facade.Authorizer) *apiRoot { r := &apiRoot{ state: st, shared: shared, facades: facades, resources: resources, authorizer: authorizer, objectCache: make(map[objectKey]reflect.Value), } return r }
go
func newAPIRoot(st *state.State, shared *sharedServerContext, facades *facade.Registry, resources *common.Resources, authorizer facade.Authorizer) *apiRoot { r := &apiRoot{ state: st, shared: shared, facades: facades, resources: resources, authorizer: authorizer, objectCache: make(map[objectKey]reflect.Value), } return r }
[ "func", "newAPIRoot", "(", "st", "*", "state", ".", "State", ",", "shared", "*", "sharedServerContext", ",", "facades", "*", "facade", ".", "Registry", ",", "resources", "*", "common", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ")", "*", "apiRoot", "{", "r", ":=", "&", "apiRoot", "{", "state", ":", "st", ",", "shared", ":", "shared", ",", "facades", ":", "facades", ",", "resources", ":", "resources", ",", "authorizer", ":", "authorizer", ",", "objectCache", ":", "make", "(", "map", "[", "objectKey", "]", "reflect", ".", "Value", ")", ",", "}", "\n", "return", "r", "\n", "}" ]
// newAPIRoot returns a new apiRoot.
[ "newAPIRoot", "returns", "a", "new", "apiRoot", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L185-L195
156,334
juju/juju
apiserver/root.go
restrictAPIRoot
func restrictAPIRoot( srv *Server, apiRoot rpc.Root, model *state.Model, auth authResult, ) (rpc.Root, error) { if !auth.controllerMachineLogin { // Controller agents are allowed to // connect even during maintenance. restrictedRoot, err := restrictAPIRootDuringMaintenance( srv, apiRoot, model, auth.tag, auth.controllerMachineLogin, ) if err != nil { return nil, errors.Trace(err) } apiRoot = restrictedRoot } if auth.controllerOnlyLogin { apiRoot = restrictRoot(apiRoot, controllerFacadesOnly) } else { apiRoot = restrictRoot(apiRoot, modelFacadesOnly) if model.Type() == state.ModelTypeCAAS { apiRoot = restrictRoot(apiRoot, caasModelFacadesOnly) } } return apiRoot, nil }
go
func restrictAPIRoot( srv *Server, apiRoot rpc.Root, model *state.Model, auth authResult, ) (rpc.Root, error) { if !auth.controllerMachineLogin { // Controller agents are allowed to // connect even during maintenance. restrictedRoot, err := restrictAPIRootDuringMaintenance( srv, apiRoot, model, auth.tag, auth.controllerMachineLogin, ) if err != nil { return nil, errors.Trace(err) } apiRoot = restrictedRoot } if auth.controllerOnlyLogin { apiRoot = restrictRoot(apiRoot, controllerFacadesOnly) } else { apiRoot = restrictRoot(apiRoot, modelFacadesOnly) if model.Type() == state.ModelTypeCAAS { apiRoot = restrictRoot(apiRoot, caasModelFacadesOnly) } } return apiRoot, nil }
[ "func", "restrictAPIRoot", "(", "srv", "*", "Server", ",", "apiRoot", "rpc", ".", "Root", ",", "model", "*", "state", ".", "Model", ",", "auth", "authResult", ",", ")", "(", "rpc", ".", "Root", ",", "error", ")", "{", "if", "!", "auth", ".", "controllerMachineLogin", "{", "// Controller agents are allowed to", "// connect even during maintenance.", "restrictedRoot", ",", "err", ":=", "restrictAPIRootDuringMaintenance", "(", "srv", ",", "apiRoot", ",", "model", ",", "auth", ".", "tag", ",", "auth", ".", "controllerMachineLogin", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "apiRoot", "=", "restrictedRoot", "\n", "}", "\n", "if", "auth", ".", "controllerOnlyLogin", "{", "apiRoot", "=", "restrictRoot", "(", "apiRoot", ",", "controllerFacadesOnly", ")", "\n", "}", "else", "{", "apiRoot", "=", "restrictRoot", "(", "apiRoot", ",", "modelFacadesOnly", ")", "\n", "if", "model", ".", "Type", "(", ")", "==", "state", ".", "ModelTypeCAAS", "{", "apiRoot", "=", "restrictRoot", "(", "apiRoot", ",", "caasModelFacadesOnly", ")", "\n", "}", "\n", "}", "\n", "return", "apiRoot", ",", "nil", "\n", "}" ]
// restrictAPIRoot calls restrictAPIRootDuringMaintenance, and // then restricts the result further to the controller or model // facades, depending on the type of login.
[ "restrictAPIRoot", "calls", "restrictAPIRootDuringMaintenance", "and", "then", "restricts", "the", "result", "further", "to", "the", "controller", "or", "model", "facades", "depending", "on", "the", "type", "of", "login", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L200-L226
156,335
juju/juju
apiserver/root.go
ModelPresence
func (ctx *facadeContext) ModelPresence(modelUUID string) facade.ModelPresence { if ctx.r.shared.featureEnabled(feature.OldPresence) { // Used in common/presence.go to determine which code path to follow. return nil } return ctx.r.shared.presence.Connections().ForModel(modelUUID) }
go
func (ctx *facadeContext) ModelPresence(modelUUID string) facade.ModelPresence { if ctx.r.shared.featureEnabled(feature.OldPresence) { // Used in common/presence.go to determine which code path to follow. return nil } return ctx.r.shared.presence.Connections().ForModel(modelUUID) }
[ "func", "(", "ctx", "*", "facadeContext", ")", "ModelPresence", "(", "modelUUID", "string", ")", "facade", ".", "ModelPresence", "{", "if", "ctx", ".", "r", ".", "shared", ".", "featureEnabled", "(", "feature", ".", "OldPresence", ")", "{", "// Used in common/presence.go to determine which code path to follow.", "return", "nil", "\n", "}", "\n", "return", "ctx", ".", "r", ".", "shared", ".", "presence", ".", "Connections", "(", ")", ".", "ForModel", "(", "modelUUID", ")", "\n", "}" ]
// ModelPresence implements facade.ModelPresence.
[ "ModelPresence", "implements", "facade", ".", "ModelPresence", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L422-L428
156,336
juju/juju
apiserver/root.go
LeadershipClaimer
func (ctx *facadeContext) LeadershipClaimer(modelUUID string) (leadership.Claimer, error) { if ctx.r.shared.featureEnabled(feature.LegacyLeases) { if modelUUID != ctx.State().ModelUUID() { return nil, errors.Errorf("can't get leadership claimer for different model with legacy lease manager") } return ctx.State().LeadershipClaimer(), nil } claimer, err := ctx.r.shared.leaseManager.Claimer( lease.ApplicationLeadershipNamespace, modelUUID, ) if err != nil { return nil, errors.Trace(err) } return leadershipClaimer{claimer}, nil }
go
func (ctx *facadeContext) LeadershipClaimer(modelUUID string) (leadership.Claimer, error) { if ctx.r.shared.featureEnabled(feature.LegacyLeases) { if modelUUID != ctx.State().ModelUUID() { return nil, errors.Errorf("can't get leadership claimer for different model with legacy lease manager") } return ctx.State().LeadershipClaimer(), nil } claimer, err := ctx.r.shared.leaseManager.Claimer( lease.ApplicationLeadershipNamespace, modelUUID, ) if err != nil { return nil, errors.Trace(err) } return leadershipClaimer{claimer}, nil }
[ "func", "(", "ctx", "*", "facadeContext", ")", "LeadershipClaimer", "(", "modelUUID", "string", ")", "(", "leadership", ".", "Claimer", ",", "error", ")", "{", "if", "ctx", ".", "r", ".", "shared", ".", "featureEnabled", "(", "feature", ".", "LegacyLeases", ")", "{", "if", "modelUUID", "!=", "ctx", ".", "State", "(", ")", ".", "ModelUUID", "(", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "ctx", ".", "State", "(", ")", ".", "LeadershipClaimer", "(", ")", ",", "nil", "\n", "}", "\n", "claimer", ",", "err", ":=", "ctx", ".", "r", ".", "shared", ".", "leaseManager", ".", "Claimer", "(", "lease", ".", "ApplicationLeadershipNamespace", ",", "modelUUID", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "leadershipClaimer", "{", "claimer", "}", ",", "nil", "\n", "}" ]
// LeadershipClaimer is part of the facade.Context interface. Getting // a claimer for an arbitrary model is only supported for raft leases // - only a claimer for the current model can be obtained with legacy // leases.
[ "LeadershipClaimer", "is", "part", "of", "the", "facade", ".", "Context", "interface", ".", "Getting", "a", "claimer", "for", "an", "arbitrary", "model", "is", "only", "supported", "for", "raft", "leases", "-", "only", "a", "claimer", "for", "the", "current", "model", "can", "be", "obtained", "with", "legacy", "leases", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L459-L474
156,337
juju/juju
apiserver/root.go
LeadershipChecker
func (ctx *facadeContext) LeadershipChecker() (leadership.Checker, error) { if ctx.r.shared.featureEnabled(feature.LegacyLeases) { return ctx.State().LeadershipChecker(), nil } checker, err := ctx.r.shared.leaseManager.Checker( lease.ApplicationLeadershipNamespace, ctx.State().ModelUUID(), ) if err != nil { return nil, errors.Trace(err) } return leadershipChecker{checker}, nil }
go
func (ctx *facadeContext) LeadershipChecker() (leadership.Checker, error) { if ctx.r.shared.featureEnabled(feature.LegacyLeases) { return ctx.State().LeadershipChecker(), nil } checker, err := ctx.r.shared.leaseManager.Checker( lease.ApplicationLeadershipNamespace, ctx.State().ModelUUID(), ) if err != nil { return nil, errors.Trace(err) } return leadershipChecker{checker}, nil }
[ "func", "(", "ctx", "*", "facadeContext", ")", "LeadershipChecker", "(", ")", "(", "leadership", ".", "Checker", ",", "error", ")", "{", "if", "ctx", ".", "r", ".", "shared", ".", "featureEnabled", "(", "feature", ".", "LegacyLeases", ")", "{", "return", "ctx", ".", "State", "(", ")", ".", "LeadershipChecker", "(", ")", ",", "nil", "\n", "}", "\n", "checker", ",", "err", ":=", "ctx", ".", "r", ".", "shared", ".", "leaseManager", ".", "Checker", "(", "lease", ".", "ApplicationLeadershipNamespace", ",", "ctx", ".", "State", "(", ")", ".", "ModelUUID", "(", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "leadershipChecker", "{", "checker", "}", ",", "nil", "\n", "}" ]
// LeadershipChecker is part of the facade.Context interface.
[ "LeadershipChecker", "is", "part", "of", "the", "facade", ".", "Context", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L477-L489
156,338
juju/juju
apiserver/root.go
LeadershipPinner
func (ctx *facadeContext) LeadershipPinner(modelUUID string) (leadership.Pinner, error) { if ctx.r.shared.featureEnabled(feature.LegacyLeases) { return nil, errors.NotImplementedf( "unable to get leadership pinner; pinning is not available with the legacy lease manager") } pinner, err := ctx.r.shared.leaseManager.Pinner( lease.ApplicationLeadershipNamespace, modelUUID, ) if err != nil { return nil, errors.Trace(err) } return leadershipPinner{pinner}, nil }
go
func (ctx *facadeContext) LeadershipPinner(modelUUID string) (leadership.Pinner, error) { if ctx.r.shared.featureEnabled(feature.LegacyLeases) { return nil, errors.NotImplementedf( "unable to get leadership pinner; pinning is not available with the legacy lease manager") } pinner, err := ctx.r.shared.leaseManager.Pinner( lease.ApplicationLeadershipNamespace, modelUUID, ) if err != nil { return nil, errors.Trace(err) } return leadershipPinner{pinner}, nil }
[ "func", "(", "ctx", "*", "facadeContext", ")", "LeadershipPinner", "(", "modelUUID", "string", ")", "(", "leadership", ".", "Pinner", ",", "error", ")", "{", "if", "ctx", ".", "r", ".", "shared", ".", "featureEnabled", "(", "feature", ".", "LegacyLeases", ")", "{", "return", "nil", ",", "errors", ".", "NotImplementedf", "(", "\"", "\"", ")", "\n", "}", "\n", "pinner", ",", "err", ":=", "ctx", ".", "r", ".", "shared", ".", "leaseManager", ".", "Pinner", "(", "lease", ".", "ApplicationLeadershipNamespace", ",", "modelUUID", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "leadershipPinner", "{", "pinner", "}", ",", "nil", "\n", "}" ]
// LeadershipPinner is part of the facade.Context interface. // Pinning functionality is only available with the Raft leases implementation.
[ "LeadershipPinner", "is", "part", "of", "the", "facade", ".", "Context", "interface", ".", "Pinning", "functionality", "is", "only", "available", "with", "the", "Raft", "leases", "implementation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L493-L506
156,339
juju/juju
apiserver/root.go
LeadershipReader
func (ctx *facadeContext) LeadershipReader(modelUUID string) (leadership.Reader, error) { if ctx.r.shared.featureEnabled(feature.LegacyLeases) { return legacyLeadershipReader{ctx.State()}, nil } reader, err := ctx.r.shared.leaseManager.Reader( lease.ApplicationLeadershipNamespace, modelUUID, ) if err != nil { return nil, errors.Trace(err) } return leadershipReader{reader}, nil }
go
func (ctx *facadeContext) LeadershipReader(modelUUID string) (leadership.Reader, error) { if ctx.r.shared.featureEnabled(feature.LegacyLeases) { return legacyLeadershipReader{ctx.State()}, nil } reader, err := ctx.r.shared.leaseManager.Reader( lease.ApplicationLeadershipNamespace, modelUUID, ) if err != nil { return nil, errors.Trace(err) } return leadershipReader{reader}, nil }
[ "func", "(", "ctx", "*", "facadeContext", ")", "LeadershipReader", "(", "modelUUID", "string", ")", "(", "leadership", ".", "Reader", ",", "error", ")", "{", "if", "ctx", ".", "r", ".", "shared", ".", "featureEnabled", "(", "feature", ".", "LegacyLeases", ")", "{", "return", "legacyLeadershipReader", "{", "ctx", ".", "State", "(", ")", "}", ",", "nil", "\n", "}", "\n", "reader", ",", "err", ":=", "ctx", ".", "r", ".", "shared", ".", "leaseManager", ".", "Reader", "(", "lease", ".", "ApplicationLeadershipNamespace", ",", "modelUUID", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "leadershipReader", "{", "reader", "}", ",", "nil", "\n", "}" ]
// LeadershipReader is part of the facade.Context interface. // It returns a reader that can be used to return all application leaders // in the model.
[ "LeadershipReader", "is", "part", "of", "the", "facade", ".", "Context", "interface", ".", "It", "returns", "a", "reader", "that", "can", "be", "used", "to", "return", "all", "application", "leaders", "in", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L511-L523
156,340
juju/juju
apiserver/root.go
SingularClaimer
func (ctx *facadeContext) SingularClaimer() (lease.Claimer, error) { if ctx.r.shared.featureEnabled(feature.LegacyLeases) { return ctx.State().SingularClaimer(), nil } return ctx.r.shared.leaseManager.Claimer( lease.SingularControllerNamespace, ctx.State().ModelUUID(), ) }
go
func (ctx *facadeContext) SingularClaimer() (lease.Claimer, error) { if ctx.r.shared.featureEnabled(feature.LegacyLeases) { return ctx.State().SingularClaimer(), nil } return ctx.r.shared.leaseManager.Claimer( lease.SingularControllerNamespace, ctx.State().ModelUUID(), ) }
[ "func", "(", "ctx", "*", "facadeContext", ")", "SingularClaimer", "(", ")", "(", "lease", ".", "Claimer", ",", "error", ")", "{", "if", "ctx", ".", "r", ".", "shared", ".", "featureEnabled", "(", "feature", ".", "LegacyLeases", ")", "{", "return", "ctx", ".", "State", "(", ")", ".", "SingularClaimer", "(", ")", ",", "nil", "\n", "}", "\n", "return", "ctx", ".", "r", ".", "shared", ".", "leaseManager", ".", "Claimer", "(", "lease", ".", "SingularControllerNamespace", ",", "ctx", ".", "State", "(", ")", ".", "ModelUUID", "(", ")", ",", ")", "\n", "}" ]
// SingularClaimer is part of the facade.Context interface.
[ "SingularClaimer", "is", "part", "of", "the", "facade", ".", "Context", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L526-L534
156,341
juju/juju
apiserver/root.go
newAdminRoot
func newAdminRoot(h *apiHandler, adminAPIs map[int]interface{}) *adminRoot { r := &adminRoot{ apiHandler: h, adminAPIs: adminAPIs, } return r }
go
func newAdminRoot(h *apiHandler, adminAPIs map[int]interface{}) *adminRoot { r := &adminRoot{ apiHandler: h, adminAPIs: adminAPIs, } return r }
[ "func", "newAdminRoot", "(", "h", "*", "apiHandler", ",", "adminAPIs", "map", "[", "int", "]", "interface", "{", "}", ")", "*", "adminRoot", "{", "r", ":=", "&", "adminRoot", "{", "apiHandler", ":", "h", ",", "adminAPIs", ":", "adminAPIs", ",", "}", "\n", "return", "r", "\n", "}" ]
// newAdminRoot creates a new AnonRoot which dispatches to the given Admin API implementation.
[ "newAdminRoot", "creates", "a", "new", "AnonRoot", "which", "dispatches", "to", "the", "given", "Admin", "API", "implementation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L544-L550
156,342
juju/juju
apiserver/root.go
AuthMachineAgent
func (r *apiHandler) AuthMachineAgent() bool { _, isMachine := r.GetAuthTag().(names.MachineTag) return isMachine }
go
func (r *apiHandler) AuthMachineAgent() bool { _, isMachine := r.GetAuthTag().(names.MachineTag) return isMachine }
[ "func", "(", "r", "*", "apiHandler", ")", "AuthMachineAgent", "(", ")", "bool", "{", "_", ",", "isMachine", ":=", "r", ".", "GetAuthTag", "(", ")", ".", "(", "names", ".", "MachineTag", ")", "\n", "return", "isMachine", "\n", "}" ]
// AuthMachineAgent returns whether the current client is a machine agent.
[ "AuthMachineAgent", "returns", "whether", "the", "current", "client", "is", "a", "machine", "agent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L569-L572
156,343
juju/juju
apiserver/root.go
AuthApplicationAgent
func (r *apiHandler) AuthApplicationAgent() bool { _, isApp := r.GetAuthTag().(names.ApplicationTag) return isApp }
go
func (r *apiHandler) AuthApplicationAgent() bool { _, isApp := r.GetAuthTag().(names.ApplicationTag) return isApp }
[ "func", "(", "r", "*", "apiHandler", ")", "AuthApplicationAgent", "(", ")", "bool", "{", "_", ",", "isApp", ":=", "r", ".", "GetAuthTag", "(", ")", ".", "(", "names", ".", "ApplicationTag", ")", "\n", "return", "isApp", "\n", "}" ]
// AuthApplicationAgent returns whether the current client is an application operator.
[ "AuthApplicationAgent", "returns", "whether", "the", "current", "client", "is", "an", "application", "operator", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L575-L578
156,344
juju/juju
apiserver/root.go
AuthUnitAgent
func (r *apiHandler) AuthUnitAgent() bool { _, isUnit := r.GetAuthTag().(names.UnitTag) return isUnit }
go
func (r *apiHandler) AuthUnitAgent() bool { _, isUnit := r.GetAuthTag().(names.UnitTag) return isUnit }
[ "func", "(", "r", "*", "apiHandler", ")", "AuthUnitAgent", "(", ")", "bool", "{", "_", ",", "isUnit", ":=", "r", ".", "GetAuthTag", "(", ")", ".", "(", "names", ".", "UnitTag", ")", "\n", "return", "isUnit", "\n", "}" ]
// AuthUnitAgent returns whether the current client is a unit agent.
[ "AuthUnitAgent", "returns", "whether", "the", "current", "client", "is", "a", "unit", "agent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L581-L584
156,345
juju/juju
apiserver/root.go
AuthOwner
func (r *apiHandler) AuthOwner(tag names.Tag) bool { return r.entity.Tag() == tag }
go
func (r *apiHandler) AuthOwner(tag names.Tag) bool { return r.entity.Tag() == tag }
[ "func", "(", "r", "*", "apiHandler", ")", "AuthOwner", "(", "tag", "names", ".", "Tag", ")", "bool", "{", "return", "r", ".", "entity", ".", "Tag", "(", ")", "==", "tag", "\n", "}" ]
// AuthOwner returns whether the authenticated user's tag matches the // given entity tag.
[ "AuthOwner", "returns", "whether", "the", "authenticated", "user", "s", "tag", "matches", "the", "given", "entity", "tag", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L588-L590
156,346
juju/juju
apiserver/root.go
AuthController
func (r *apiHandler) AuthController() bool { type hasIsManager interface { IsManager() bool } m, ok := r.entity.(hasIsManager) return ok && m.IsManager() }
go
func (r *apiHandler) AuthController() bool { type hasIsManager interface { IsManager() bool } m, ok := r.entity.(hasIsManager) return ok && m.IsManager() }
[ "func", "(", "r", "*", "apiHandler", ")", "AuthController", "(", ")", "bool", "{", "type", "hasIsManager", "interface", "{", "IsManager", "(", ")", "bool", "\n", "}", "\n", "m", ",", "ok", ":=", "r", ".", "entity", ".", "(", "hasIsManager", ")", "\n", "return", "ok", "&&", "m", ".", "IsManager", "(", ")", "\n", "}" ]
// AuthController returns whether the authenticated user is a // machine with running the ManageEnviron job.
[ "AuthController", "returns", "whether", "the", "authenticated", "user", "is", "a", "machine", "with", "running", "the", "ManageEnviron", "job", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L594-L600
156,347
juju/juju
apiserver/root.go
AuthClient
func (r *apiHandler) AuthClient() bool { _, isUser := r.GetAuthTag().(names.UserTag) return isUser }
go
func (r *apiHandler) AuthClient() bool { _, isUser := r.GetAuthTag().(names.UserTag) return isUser }
[ "func", "(", "r", "*", "apiHandler", ")", "AuthClient", "(", ")", "bool", "{", "_", ",", "isUser", ":=", "r", ".", "GetAuthTag", "(", ")", ".", "(", "names", ".", "UserTag", ")", "\n", "return", "isUser", "\n", "}" ]
// AuthClient returns whether the authenticated entity is a client // user.
[ "AuthClient", "returns", "whether", "the", "authenticated", "entity", "is", "a", "client", "user", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L604-L607
156,348
juju/juju
apiserver/root.go
GetAuthTag
func (r *apiHandler) GetAuthTag() names.Tag { if r.entity == nil { return nil } return r.entity.Tag() }
go
func (r *apiHandler) GetAuthTag() names.Tag { if r.entity == nil { return nil } return r.entity.Tag() }
[ "func", "(", "r", "*", "apiHandler", ")", "GetAuthTag", "(", ")", "names", ".", "Tag", "{", "if", "r", ".", "entity", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "r", ".", "entity", ".", "Tag", "(", ")", "\n", "}" ]
// GetAuthTag returns the tag of the authenticated entity, if any.
[ "GetAuthTag", "returns", "the", "tag", "of", "the", "authenticated", "entity", "if", "any", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L610-L615
156,349
juju/juju
apiserver/root.go
DescribeFacades
func DescribeFacades(registry *facade.Registry) []params.FacadeVersions { facades := registry.List() result := make([]params.FacadeVersions, len(facades)) for i, f := range facades { result[i].Name = f.Name result[i].Versions = f.Versions } return result }
go
func DescribeFacades(registry *facade.Registry) []params.FacadeVersions { facades := registry.List() result := make([]params.FacadeVersions, len(facades)) for i, f := range facades { result[i].Name = f.Name result[i].Versions = f.Versions } return result }
[ "func", "DescribeFacades", "(", "registry", "*", "facade", ".", "Registry", ")", "[", "]", "params", ".", "FacadeVersions", "{", "facades", ":=", "registry", ".", "List", "(", ")", "\n", "result", ":=", "make", "(", "[", "]", "params", ".", "FacadeVersions", ",", "len", "(", "facades", ")", ")", "\n", "for", "i", ",", "f", ":=", "range", "facades", "{", "result", "[", "i", "]", ".", "Name", "=", "f", ".", "Name", "\n", "result", "[", "i", "]", ".", "Versions", "=", "f", ".", "Versions", "\n", "}", "\n", "return", "result", "\n", "}" ]
// DescribeFacades returns the list of available Facades and their Versions
[ "DescribeFacades", "returns", "the", "list", "of", "available", "Facades", "and", "their", "Versions" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/root.go#L636-L644
156,350
juju/juju
cmd/juju/gui/gui.go
guiAddr
func guiAddr(conn api.Connection) string { if dnsName := conn.PublicDNSName(); dnsName != "" { return dnsName } return conn.Addr() }
go
func guiAddr(conn api.Connection) string { if dnsName := conn.PublicDNSName(); dnsName != "" { return dnsName } return conn.Addr() }
[ "func", "guiAddr", "(", "conn", "api", ".", "Connection", ")", "string", "{", "if", "dnsName", ":=", "conn", ".", "PublicDNSName", "(", ")", ";", "dnsName", "!=", "\"", "\"", "{", "return", "dnsName", "\n", "}", "\n", "return", "conn", ".", "Addr", "(", ")", "\n", "}" ]
// guiAddr returns an address where the GUI is available.
[ "guiAddr", "returns", "an", "address", "where", "the", "GUI", "is", "available", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/gui/gui.go#L159-L164
156,351
juju/juju
cmd/juju/gui/gui.go
checkAvailable
func (c *guiCommand) checkAvailable(rawURL, newRawURL string, conn api.Connection) (string, error) { client, err := conn.HTTPClient() if err != nil { return "", errors.Annotate(err, "cannot retrieve HTTP client") } if err = clientGet(client, newRawURL); err == nil { return newRawURL, nil } if err = clientGet(client, rawURL); err != nil { return "", errors.Annotate(err, "Juju GUI is not available") } return rawURL, nil }
go
func (c *guiCommand) checkAvailable(rawURL, newRawURL string, conn api.Connection) (string, error) { client, err := conn.HTTPClient() if err != nil { return "", errors.Annotate(err, "cannot retrieve HTTP client") } if err = clientGet(client, newRawURL); err == nil { return newRawURL, nil } if err = clientGet(client, rawURL); err != nil { return "", errors.Annotate(err, "Juju GUI is not available") } return rawURL, nil }
[ "func", "(", "c", "*", "guiCommand", ")", "checkAvailable", "(", "rawURL", ",", "newRawURL", "string", ",", "conn", "api", ".", "Connection", ")", "(", "string", ",", "error", ")", "{", "client", ",", "err", ":=", "conn", ".", "HTTPClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "=", "clientGet", "(", "client", ",", "newRawURL", ")", ";", "err", "==", "nil", "{", "return", "newRawURL", ",", "nil", "\n", "}", "\n", "if", "err", "=", "clientGet", "(", "client", ",", "rawURL", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "rawURL", ",", "nil", "\n", "}" ]
// checkAvailable ensures the Juju GUI is available on the controller at // one of the given URLs, returning the successful URL.
[ "checkAvailable", "ensures", "the", "Juju", "GUI", "is", "available", "on", "the", "controller", "at", "one", "of", "the", "given", "URLs", "returning", "the", "successful", "URL", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/gui/gui.go#L168-L180
156,352
juju/juju
cmd/juju/gui/gui.go
openBrowser
func (c *guiCommand) openBrowser(ctx *cmd.Context, rawURL string, vers *version.Number) error { u, err := url.Parse(rawURL) if err != nil { return errors.Annotate(err, "cannot parse Juju GUI URL") } if c.noBrowser && !c.browser { versInfo := "" if vers != nil { versInfo = fmt.Sprintf("%v ", vers) } modelName, err := c.ModelName() if err != nil { return errors.Trace(err) } ctx.Infof("GUI %sfor model %q is enabled at:\n %s", versInfo, modelName, u.String()) return nil } err = webbrowserOpen(u) if err == nil { ctx.Infof("Opening the Juju GUI in your browser.") ctx.Infof("If it does not open, open this URL:\n%s", u) return nil } if err == webbrowser.ErrNoBrowser { ctx.Infof("Open this URL in your browser:\n%s", u) return nil } return errors.Annotate(err, "cannot open web browser") }
go
func (c *guiCommand) openBrowser(ctx *cmd.Context, rawURL string, vers *version.Number) error { u, err := url.Parse(rawURL) if err != nil { return errors.Annotate(err, "cannot parse Juju GUI URL") } if c.noBrowser && !c.browser { versInfo := "" if vers != nil { versInfo = fmt.Sprintf("%v ", vers) } modelName, err := c.ModelName() if err != nil { return errors.Trace(err) } ctx.Infof("GUI %sfor model %q is enabled at:\n %s", versInfo, modelName, u.String()) return nil } err = webbrowserOpen(u) if err == nil { ctx.Infof("Opening the Juju GUI in your browser.") ctx.Infof("If it does not open, open this URL:\n%s", u) return nil } if err == webbrowser.ErrNoBrowser { ctx.Infof("Open this URL in your browser:\n%s", u) return nil } return errors.Annotate(err, "cannot open web browser") }
[ "func", "(", "c", "*", "guiCommand", ")", "openBrowser", "(", "ctx", "*", "cmd", ".", "Context", ",", "rawURL", "string", ",", "vers", "*", "version", ".", "Number", ")", "error", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "rawURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "noBrowser", "&&", "!", "c", ".", "browser", "{", "versInfo", ":=", "\"", "\"", "\n", "if", "vers", "!=", "nil", "{", "versInfo", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "vers", ")", "\n", "}", "\n", "modelName", ",", "err", ":=", "c", ".", "ModelName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ctx", ".", "Infof", "(", "\"", "\\n", "\"", ",", "versInfo", ",", "modelName", ",", "u", ".", "String", "(", ")", ")", "\n", "return", "nil", "\n", "}", "\n", "err", "=", "webbrowserOpen", "(", "u", ")", "\n", "if", "err", "==", "nil", "{", "ctx", ".", "Infof", "(", "\"", "\"", ")", "\n", "ctx", ".", "Infof", "(", "\"", "\\n", "\"", ",", "u", ")", "\n", "return", "nil", "\n", "}", "\n", "if", "err", "==", "webbrowser", ".", "ErrNoBrowser", "{", "ctx", ".", "Infof", "(", "\"", "\\n", "\"", ",", "u", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// openBrowser opens the Juju GUI at the given URL.
[ "openBrowser", "opens", "the", "Juju", "GUI", "at", "the", "given", "URL", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/gui/gui.go#L183-L211
156,353
juju/juju
cmd/juju/gui/gui.go
showCredentials
func (c *guiCommand) showCredentials(ctx *cmd.Context) error { if c.hideCreds || !c.showCreds { return nil } // TODO(wallyworld) - what to do if we are using a macaroon. accountDetails, err := c.CurrentAccountDetails() if err != nil { return errors.Annotate(err, "cannot retrieve credentials") } password := accountDetails.Password if password == "" { // TODO(wallyworld) - fix this password = "<unknown> (password has been changed by the user)" } ctx.Infof("Your login credential is:\n username: %s\n password: %s", accountDetails.User, password) return nil }
go
func (c *guiCommand) showCredentials(ctx *cmd.Context) error { if c.hideCreds || !c.showCreds { return nil } // TODO(wallyworld) - what to do if we are using a macaroon. accountDetails, err := c.CurrentAccountDetails() if err != nil { return errors.Annotate(err, "cannot retrieve credentials") } password := accountDetails.Password if password == "" { // TODO(wallyworld) - fix this password = "<unknown> (password has been changed by the user)" } ctx.Infof("Your login credential is:\n username: %s\n password: %s", accountDetails.User, password) return nil }
[ "func", "(", "c", "*", "guiCommand", ")", "showCredentials", "(", "ctx", "*", "cmd", ".", "Context", ")", "error", "{", "if", "c", ".", "hideCreds", "||", "!", "c", ".", "showCreds", "{", "return", "nil", "\n", "}", "\n", "// TODO(wallyworld) - what to do if we are using a macaroon.", "accountDetails", ",", "err", ":=", "c", ".", "CurrentAccountDetails", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "password", ":=", "accountDetails", ".", "Password", "\n", "if", "password", "==", "\"", "\"", "{", "// TODO(wallyworld) - fix this", "password", "=", "\"", "\"", "\n", "}", "\n", "ctx", ".", "Infof", "(", "\"", "\\n", "\\n", "\"", ",", "accountDetails", ".", "User", ",", "password", ")", "\n", "return", "nil", "\n", "}" ]
// showCredentials shows the admin username and password.
[ "showCredentials", "shows", "the", "admin", "username", "and", "password", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/gui/gui.go#L214-L230
156,354
juju/juju
apiserver/common/storagecommon/storage.go
volumeAttachmentDevicePath
func volumeAttachmentDevicePath( volumeInfo state.VolumeInfo, volumeAttachmentInfo state.VolumeAttachmentInfo, blockDevice state.BlockDeviceInfo, ) (string, error) { if volumeInfo.HardwareId != "" || volumeInfo.WWN != "" || volumeAttachmentInfo.DeviceName != "" || volumeAttachmentInfo.DeviceLink != "" { // Prefer the volume attachment's information over what is // in the published block device information, but only if the // block device information actually has any device links. In // some cases, the block device has very little hw info published. var deviceLinks []string if volumeAttachmentInfo.DeviceLink != "" && len(blockDevice.DeviceLinks) > 0 { deviceLinks = []string{volumeAttachmentInfo.DeviceLink} } var deviceName string if blockDevice.DeviceName != "" { deviceName = blockDevice.DeviceName } else { deviceName = volumeAttachmentInfo.DeviceName } return storage.BlockDevicePath(storage.BlockDevice{ HardwareId: volumeInfo.HardwareId, WWN: volumeInfo.WWN, DeviceName: deviceName, DeviceLinks: deviceLinks, }) } return storage.BlockDevicePath(BlockDeviceFromState(blockDevice)) }
go
func volumeAttachmentDevicePath( volumeInfo state.VolumeInfo, volumeAttachmentInfo state.VolumeAttachmentInfo, blockDevice state.BlockDeviceInfo, ) (string, error) { if volumeInfo.HardwareId != "" || volumeInfo.WWN != "" || volumeAttachmentInfo.DeviceName != "" || volumeAttachmentInfo.DeviceLink != "" { // Prefer the volume attachment's information over what is // in the published block device information, but only if the // block device information actually has any device links. In // some cases, the block device has very little hw info published. var deviceLinks []string if volumeAttachmentInfo.DeviceLink != "" && len(blockDevice.DeviceLinks) > 0 { deviceLinks = []string{volumeAttachmentInfo.DeviceLink} } var deviceName string if blockDevice.DeviceName != "" { deviceName = blockDevice.DeviceName } else { deviceName = volumeAttachmentInfo.DeviceName } return storage.BlockDevicePath(storage.BlockDevice{ HardwareId: volumeInfo.HardwareId, WWN: volumeInfo.WWN, DeviceName: deviceName, DeviceLinks: deviceLinks, }) } return storage.BlockDevicePath(BlockDeviceFromState(blockDevice)) }
[ "func", "volumeAttachmentDevicePath", "(", "volumeInfo", "state", ".", "VolumeInfo", ",", "volumeAttachmentInfo", "state", ".", "VolumeAttachmentInfo", ",", "blockDevice", "state", ".", "BlockDeviceInfo", ",", ")", "(", "string", ",", "error", ")", "{", "if", "volumeInfo", ".", "HardwareId", "!=", "\"", "\"", "||", "volumeInfo", ".", "WWN", "!=", "\"", "\"", "||", "volumeAttachmentInfo", ".", "DeviceName", "!=", "\"", "\"", "||", "volumeAttachmentInfo", ".", "DeviceLink", "!=", "\"", "\"", "{", "// Prefer the volume attachment's information over what is", "// in the published block device information, but only if the", "// block device information actually has any device links. In", "// some cases, the block device has very little hw info published.", "var", "deviceLinks", "[", "]", "string", "\n", "if", "volumeAttachmentInfo", ".", "DeviceLink", "!=", "\"", "\"", "&&", "len", "(", "blockDevice", ".", "DeviceLinks", ")", ">", "0", "{", "deviceLinks", "=", "[", "]", "string", "{", "volumeAttachmentInfo", ".", "DeviceLink", "}", "\n", "}", "\n", "var", "deviceName", "string", "\n", "if", "blockDevice", ".", "DeviceName", "!=", "\"", "\"", "{", "deviceName", "=", "blockDevice", ".", "DeviceName", "\n", "}", "else", "{", "deviceName", "=", "volumeAttachmentInfo", ".", "DeviceName", "\n", "}", "\n", "return", "storage", ".", "BlockDevicePath", "(", "storage", ".", "BlockDevice", "{", "HardwareId", ":", "volumeInfo", ".", "HardwareId", ",", "WWN", ":", "volumeInfo", ".", "WWN", ",", "DeviceName", ":", "deviceName", ",", "DeviceLinks", ":", "deviceLinks", ",", "}", ")", "\n", "}", "\n", "return", "storage", ".", "BlockDevicePath", "(", "BlockDeviceFromState", "(", "blockDevice", ")", ")", "\n", "}" ]
// volumeAttachmentDevicePath returns the absolute device path for // a volume attachment. The value is only meaningful in the context // of the machine that the volume is attached to.
[ "volumeAttachmentDevicePath", "returns", "the", "absolute", "device", "path", "for", "a", "volume", "attachment", ".", "The", "value", "is", "only", "meaningful", "in", "the", "context", "of", "the", "machine", "that", "the", "volume", "is", "attached", "to", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/storagecommon/storage.go#L210-L241
156,355
juju/juju
apiserver/common/storagecommon/storage.go
StorageTags
func StorageTags( storageInstance state.StorageInstance, modelUUID, controllerUUID string, tagger tags.ResourceTagger, ) (map[string]string, error) { storageTags := tags.ResourceTags( names.NewModelTag(modelUUID), names.NewControllerTag(controllerUUID), tagger, ) if storageInstance != nil { storageTags[tags.JujuStorageInstance] = storageInstance.Tag().Id() if owner, ok := storageInstance.Owner(); ok { storageTags[tags.JujuStorageOwner] = owner.Id() } } return storageTags, nil }
go
func StorageTags( storageInstance state.StorageInstance, modelUUID, controllerUUID string, tagger tags.ResourceTagger, ) (map[string]string, error) { storageTags := tags.ResourceTags( names.NewModelTag(modelUUID), names.NewControllerTag(controllerUUID), tagger, ) if storageInstance != nil { storageTags[tags.JujuStorageInstance] = storageInstance.Tag().Id() if owner, ok := storageInstance.Owner(); ok { storageTags[tags.JujuStorageOwner] = owner.Id() } } return storageTags, nil }
[ "func", "StorageTags", "(", "storageInstance", "state", ".", "StorageInstance", ",", "modelUUID", ",", "controllerUUID", "string", ",", "tagger", "tags", ".", "ResourceTagger", ",", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "storageTags", ":=", "tags", ".", "ResourceTags", "(", "names", ".", "NewModelTag", "(", "modelUUID", ")", ",", "names", ".", "NewControllerTag", "(", "controllerUUID", ")", ",", "tagger", ",", ")", "\n", "if", "storageInstance", "!=", "nil", "{", "storageTags", "[", "tags", ".", "JujuStorageInstance", "]", "=", "storageInstance", ".", "Tag", "(", ")", ".", "Id", "(", ")", "\n", "if", "owner", ",", "ok", ":=", "storageInstance", ".", "Owner", "(", ")", ";", "ok", "{", "storageTags", "[", "tags", ".", "JujuStorageOwner", "]", "=", "owner", ".", "Id", "(", ")", "\n", "}", "\n", "}", "\n", "return", "storageTags", ",", "nil", "\n", "}" ]
// StorageTags returns the tags that should be set on a volume or filesystem, // if the provider supports them.
[ "StorageTags", "returns", "the", "tags", "that", "should", "be", "set", "on", "a", "volume", "or", "filesystem", "if", "the", "provider", "supports", "them", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/storagecommon/storage.go#L266-L283
156,356
juju/juju
apiserver/common/storagecommon/storage.go
ClassifyDetachedStorage
func ClassifyDetachedStorage( stVolume VolumeAccess, stFile FilesystemAccess, storage []state.StorageInstance, ) (destroyed, detached []params.Entity, _ error) { for _, storage := range storage { var detachable bool switch storage.Kind() { case state.StorageKindFilesystem: if stFile == nil { return nil, nil, errors.NotImplementedf("FilesystemStorage instance") } f, err := stFile.StorageInstanceFilesystem(storage.StorageTag()) if errors.IsNotFound(err) { continue } else if err != nil { return nil, nil, err } detachable = f.Detachable() case state.StorageKindBlock: if stVolume == nil { return nil, nil, errors.NotImplementedf("BlockStorage instance") } v, err := stVolume.StorageInstanceVolume(storage.StorageTag()) if errors.IsNotFound(err) { continue } else if err != nil { return nil, nil, err } detachable = v.Detachable() default: return nil, nil, errors.NotValidf("storage kind %s", storage.Kind()) } entity := params.Entity{storage.StorageTag().String()} if detachable { detached = append(detached, entity) } else { destroyed = append(destroyed, entity) } } return destroyed, detached, nil }
go
func ClassifyDetachedStorage( stVolume VolumeAccess, stFile FilesystemAccess, storage []state.StorageInstance, ) (destroyed, detached []params.Entity, _ error) { for _, storage := range storage { var detachable bool switch storage.Kind() { case state.StorageKindFilesystem: if stFile == nil { return nil, nil, errors.NotImplementedf("FilesystemStorage instance") } f, err := stFile.StorageInstanceFilesystem(storage.StorageTag()) if errors.IsNotFound(err) { continue } else if err != nil { return nil, nil, err } detachable = f.Detachable() case state.StorageKindBlock: if stVolume == nil { return nil, nil, errors.NotImplementedf("BlockStorage instance") } v, err := stVolume.StorageInstanceVolume(storage.StorageTag()) if errors.IsNotFound(err) { continue } else if err != nil { return nil, nil, err } detachable = v.Detachable() default: return nil, nil, errors.NotValidf("storage kind %s", storage.Kind()) } entity := params.Entity{storage.StorageTag().String()} if detachable { detached = append(detached, entity) } else { destroyed = append(destroyed, entity) } } return destroyed, detached, nil }
[ "func", "ClassifyDetachedStorage", "(", "stVolume", "VolumeAccess", ",", "stFile", "FilesystemAccess", ",", "storage", "[", "]", "state", ".", "StorageInstance", ",", ")", "(", "destroyed", ",", "detached", "[", "]", "params", ".", "Entity", ",", "_", "error", ")", "{", "for", "_", ",", "storage", ":=", "range", "storage", "{", "var", "detachable", "bool", "\n", "switch", "storage", ".", "Kind", "(", ")", "{", "case", "state", ".", "StorageKindFilesystem", ":", "if", "stFile", "==", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "NotImplementedf", "(", "\"", "\"", ")", "\n", "}", "\n", "f", ",", "err", ":=", "stFile", ".", "StorageInstanceFilesystem", "(", "storage", ".", "StorageTag", "(", ")", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "continue", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "detachable", "=", "f", ".", "Detachable", "(", ")", "\n", "case", "state", ".", "StorageKindBlock", ":", "if", "stVolume", "==", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "NotImplementedf", "(", "\"", "\"", ")", "\n", "}", "\n", "v", ",", "err", ":=", "stVolume", ".", "StorageInstanceVolume", "(", "storage", ".", "StorageTag", "(", ")", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "continue", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "detachable", "=", "v", ".", "Detachable", "(", ")", "\n", "default", ":", "return", "nil", ",", "nil", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "storage", ".", "Kind", "(", ")", ")", "\n", "}", "\n", "entity", ":=", "params", ".", "Entity", "{", "storage", ".", "StorageTag", "(", ")", ".", "String", "(", ")", "}", "\n", "if", "detachable", "{", "detached", "=", "append", "(", "detached", ",", "entity", ")", "\n", "}", "else", "{", "destroyed", "=", "append", "(", "destroyed", ",", "entity", ")", "\n", "}", "\n", "}", "\n", "return", "destroyed", ",", "detached", ",", "nil", "\n", "}" ]
// ClassifyDetachedStorage classifies storage instances into those that will // be destroyed, and those that will be detached, when their attachment is // removed. Any storage that is not found will be omitted.
[ "ClassifyDetachedStorage", "classifies", "storage", "instances", "into", "those", "that", "will", "be", "destroyed", "and", "those", "that", "will", "be", "detached", "when", "their", "attachment", "is", "removed", ".", "Any", "storage", "that", "is", "not", "found", "will", "be", "omitted", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/storagecommon/storage.go#L310-L351
156,357
juju/juju
cmd/juju/controller/listcontrollers.go
NewListControllersCommand
func NewListControllersCommand() cmd.Command { cmd := &listControllersCommand{ store: jujuclient.NewFileClientStore(), } return modelcmd.WrapBase(cmd) }
go
func NewListControllersCommand() cmd.Command { cmd := &listControllersCommand{ store: jujuclient.NewFileClientStore(), } return modelcmd.WrapBase(cmd) }
[ "func", "NewListControllersCommand", "(", ")", "cmd", ".", "Command", "{", "cmd", ":=", "&", "listControllersCommand", "{", "store", ":", "jujuclient", ".", "NewFileClientStore", "(", ")", ",", "}", "\n", "return", "modelcmd", ".", "WrapBase", "(", "cmd", ")", "\n", "}" ]
// NewListControllersCommand returns a command to list registered controllers.
[ "NewListControllersCommand", "returns", "a", "command", "to", "list", "registered", "controllers", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/listcontrollers.go#L41-L46
156,358
juju/juju
watcher/legacy/stringsworker.go
NewStringsWorker
func NewStringsWorker(handler StringsWatchHandler) worker.Worker { sw := &stringsWorker{ handler: handler, } sw.tomb.Go(sw.loop) return sw }
go
func NewStringsWorker(handler StringsWatchHandler) worker.Worker { sw := &stringsWorker{ handler: handler, } sw.tomb.Go(sw.loop) return sw }
[ "func", "NewStringsWorker", "(", "handler", "StringsWatchHandler", ")", "worker", ".", "Worker", "{", "sw", ":=", "&", "stringsWorker", "{", "handler", ":", "handler", ",", "}", "\n", "sw", ".", "tomb", ".", "Go", "(", "sw", ".", "loop", ")", "\n", "return", "sw", "\n", "}" ]
// NewStringsWorker starts a new worker running the business logic // from the handler. The worker loop is started in another goroutine // as a side effect of calling this.
[ "NewStringsWorker", "starts", "a", "new", "worker", "running", "the", "business", "logic", "from", "the", "handler", ".", "The", "worker", "loop", "is", "started", "in", "another", "goroutine", "as", "a", "side", "effect", "of", "calling", "this", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/watcher/legacy/stringsworker.go#L41-L47
156,359
juju/juju
provider/cloudsigma/instance.go
Id
func (i sigmaInstance) Id() instance.Id { id := instance.Id(i.server.UUID()) logger.Tracef("sigmaInstance.Id: %s", id) return id }
go
func (i sigmaInstance) Id() instance.Id { id := instance.Id(i.server.UUID()) logger.Tracef("sigmaInstance.Id: %s", id) return id }
[ "func", "(", "i", "sigmaInstance", ")", "Id", "(", ")", "instance", ".", "Id", "{", "id", ":=", "instance", ".", "Id", "(", "i", ".", "server", ".", "UUID", "(", ")", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "id", ")", "\n", "return", "id", "\n", "}" ]
// Id returns a provider-generated identifier for the Instance.
[ "Id", "returns", "a", "provider", "-", "generated", "identifier", "for", "the", "Instance", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/cloudsigma/instance.go#L26-L30
156,360
juju/juju
provider/cloudsigma/instance.go
Status
func (i sigmaInstance) Status(ctx context.ProviderCallContext) instance.Status { entityStatus := i.server.Status() logger.Tracef("sigmaInstance.Status: %s", entityStatus) jujuStatus := status.Pending switch entityStatus { case gosigma.ServerStarting: jujuStatus = status.Allocating case gosigma.ServerRunning: jujuStatus = status.Running case gosigma.ServerStopping, gosigma.ServerStopped: jujuStatus = status.Empty case gosigma.ServerUnavailable: // I am not sure about this one. jujuStatus = status.Pending default: jujuStatus = status.Pending } return instance.Status{ Status: jujuStatus, Message: entityStatus, } }
go
func (i sigmaInstance) Status(ctx context.ProviderCallContext) instance.Status { entityStatus := i.server.Status() logger.Tracef("sigmaInstance.Status: %s", entityStatus) jujuStatus := status.Pending switch entityStatus { case gosigma.ServerStarting: jujuStatus = status.Allocating case gosigma.ServerRunning: jujuStatus = status.Running case gosigma.ServerStopping, gosigma.ServerStopped: jujuStatus = status.Empty case gosigma.ServerUnavailable: // I am not sure about this one. jujuStatus = status.Pending default: jujuStatus = status.Pending } return instance.Status{ Status: jujuStatus, Message: entityStatus, } }
[ "func", "(", "i", "sigmaInstance", ")", "Status", "(", "ctx", "context", ".", "ProviderCallContext", ")", "instance", ".", "Status", "{", "entityStatus", ":=", "i", ".", "server", ".", "Status", "(", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "entityStatus", ")", "\n", "jujuStatus", ":=", "status", ".", "Pending", "\n", "switch", "entityStatus", "{", "case", "gosigma", ".", "ServerStarting", ":", "jujuStatus", "=", "status", ".", "Allocating", "\n", "case", "gosigma", ".", "ServerRunning", ":", "jujuStatus", "=", "status", ".", "Running", "\n", "case", "gosigma", ".", "ServerStopping", ",", "gosigma", ".", "ServerStopped", ":", "jujuStatus", "=", "status", ".", "Empty", "\n", "case", "gosigma", ".", "ServerUnavailable", ":", "// I am not sure about this one.", "jujuStatus", "=", "status", ".", "Pending", "\n", "default", ":", "jujuStatus", "=", "status", ".", "Pending", "\n", "}", "\n\n", "return", "instance", ".", "Status", "{", "Status", ":", "jujuStatus", ",", "Message", ":", "entityStatus", ",", "}", "\n\n", "}" ]
// Status returns the provider-specific status for the instance.
[ "Status", "returns", "the", "provider", "-", "specific", "status", "for", "the", "instance", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/cloudsigma/instance.go#L33-L56
156,361
juju/juju
provider/cloudsigma/instance.go
Addresses
func (i sigmaInstance) Addresses(ctx context.ProviderCallContext) ([]network.Address, error) { ip := i.findIPv4() if ip != "" { addr := network.Address{ Value: ip, Type: network.IPv4Address, Scope: network.ScopePublic, } logger.Tracef("sigmaInstance.Addresses: %v", addr) return []network.Address{addr}, nil } return []network.Address{}, nil }
go
func (i sigmaInstance) Addresses(ctx context.ProviderCallContext) ([]network.Address, error) { ip := i.findIPv4() if ip != "" { addr := network.Address{ Value: ip, Type: network.IPv4Address, Scope: network.ScopePublic, } logger.Tracef("sigmaInstance.Addresses: %v", addr) return []network.Address{addr}, nil } return []network.Address{}, nil }
[ "func", "(", "i", "sigmaInstance", ")", "Addresses", "(", "ctx", "context", ".", "ProviderCallContext", ")", "(", "[", "]", "network", ".", "Address", ",", "error", ")", "{", "ip", ":=", "i", ".", "findIPv4", "(", ")", "\n\n", "if", "ip", "!=", "\"", "\"", "{", "addr", ":=", "network", ".", "Address", "{", "Value", ":", "ip", ",", "Type", ":", "network", ".", "IPv4Address", ",", "Scope", ":", "network", ".", "ScopePublic", ",", "}", "\n\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "addr", ")", "\n\n", "return", "[", "]", "network", ".", "Address", "{", "addr", "}", ",", "nil", "\n", "}", "\n", "return", "[", "]", "network", ".", "Address", "{", "}", ",", "nil", "\n", "}" ]
// Addresses returns a list of hostnames or ip addresses // associated with the instance. This will supercede DNSName // which can be implemented by selecting a preferred address.
[ "Addresses", "returns", "a", "list", "of", "hostnames", "or", "ip", "addresses", "associated", "with", "the", "instance", ".", "This", "will", "supercede", "DNSName", "which", "can", "be", "implemented", "by", "selecting", "a", "preferred", "address", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/cloudsigma/instance.go#L61-L76
156,362
juju/juju
provider/cloudsigma/instance.go
OpenPorts
func (i sigmaInstance) OpenPorts(ctx context.ProviderCallContext, machineID string, ports []network.IngressRule) error { return errors.NotImplementedf("OpenPorts") }
go
func (i sigmaInstance) OpenPorts(ctx context.ProviderCallContext, machineID string, ports []network.IngressRule) error { return errors.NotImplementedf("OpenPorts") }
[ "func", "(", "i", "sigmaInstance", ")", "OpenPorts", "(", "ctx", "context", ".", "ProviderCallContext", ",", "machineID", "string", ",", "ports", "[", "]", "network", ".", "IngressRule", ")", "error", "{", "return", "errors", ".", "NotImplementedf", "(", "\"", "\"", ")", "\n", "}" ]
// OpenPorts opens the given ports on the instance, which // should have been started with the given machine id.
[ "OpenPorts", "opens", "the", "given", "ports", "on", "the", "instance", "which", "should", "have", "been", "started", "with", "the", "given", "machine", "id", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/cloudsigma/instance.go#L80-L82
156,363
juju/juju
provider/cloudsigma/instance.go
IngressRules
func (i sigmaInstance) IngressRules(ctx context.ProviderCallContext, machineID string) ([]network.IngressRule, error) { return nil, errors.NotImplementedf("InstanceRules") }
go
func (i sigmaInstance) IngressRules(ctx context.ProviderCallContext, machineID string) ([]network.IngressRule, error) { return nil, errors.NotImplementedf("InstanceRules") }
[ "func", "(", "i", "sigmaInstance", ")", "IngressRules", "(", "ctx", "context", ".", "ProviderCallContext", ",", "machineID", "string", ")", "(", "[", "]", "network", ".", "IngressRule", ",", "error", ")", "{", "return", "nil", ",", "errors", ".", "NotImplementedf", "(", "\"", "\"", ")", "\n", "}" ]
// IngressRules returns the set of ports open on the instance, which // should have been started with the given machine id. // The rules are returned as sorted by SortInstanceRules.
[ "IngressRules", "returns", "the", "set", "of", "ports", "open", "on", "the", "instance", "which", "should", "have", "been", "started", "with", "the", "given", "machine", "id", ".", "The", "rules", "are", "returned", "as", "sorted", "by", "SortInstanceRules", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/cloudsigma/instance.go#L93-L95
156,364
juju/juju
state/linklayerdevices_ipaddresses.go
IsValidAddressConfigMethod
func IsValidAddressConfigMethod(value string) bool { switch AddressConfigMethod(value) { case LoopbackAddress, StaticAddress, DynamicAddress, ManualAddress: return true } return false }
go
func IsValidAddressConfigMethod(value string) bool { switch AddressConfigMethod(value) { case LoopbackAddress, StaticAddress, DynamicAddress, ManualAddress: return true } return false }
[ "func", "IsValidAddressConfigMethod", "(", "value", "string", ")", "bool", "{", "switch", "AddressConfigMethod", "(", "value", ")", "{", "case", "LoopbackAddress", ",", "StaticAddress", ",", "DynamicAddress", ",", "ManualAddress", ":", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsValidAddressConfigMethod returns whether the given value is a valid method // to configure a link-layer network device's IP address.
[ "IsValidAddressConfigMethod", "returns", "whether", "the", "given", "value", "is", "a", "valid", "method", "to", "configure", "a", "link", "-", "layer", "network", "device", "s", "IP", "address", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_ipaddresses.go#L84-L90
156,365
juju/juju
state/linklayerdevices_ipaddresses.go
DocID
func (addr *Address) DocID() string { return addr.st.docID(addr.doc.DocID) }
go
func (addr *Address) DocID() string { return addr.st.docID(addr.doc.DocID) }
[ "func", "(", "addr", "*", "Address", ")", "DocID", "(", ")", "string", "{", "return", "addr", ".", "st", ".", "docID", "(", "addr", ".", "doc", ".", "DocID", ")", "\n", "}" ]
// DocID returns the globally unique ID of the IP address, including the model // UUID as prefix.
[ "DocID", "returns", "the", "globally", "unique", "ID", "of", "the", "IP", "address", "including", "the", "model", "UUID", "as", "prefix", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_ipaddresses.go#L110-L112
156,366
juju/juju
state/linklayerdevices_ipaddresses.go
ProviderID
func (addr *Address) ProviderID() network.Id { return network.Id(addr.doc.ProviderID) }
go
func (addr *Address) ProviderID() network.Id { return network.Id(addr.doc.ProviderID) }
[ "func", "(", "addr", "*", "Address", ")", "ProviderID", "(", ")", "network", ".", "Id", "{", "return", "network", ".", "Id", "(", "addr", ".", "doc", ".", "ProviderID", ")", "\n", "}" ]
// ProviderID returns the provider-specific IP address ID, if set.
[ "ProviderID", "returns", "the", "provider", "-", "specific", "IP", "address", "ID", "if", "set", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_ipaddresses.go#L115-L117
156,367
juju/juju
state/linklayerdevices_ipaddresses.go
Machine
func (addr *Address) Machine() (*Machine, error) { return addr.st.Machine(addr.doc.MachineID) }
go
func (addr *Address) Machine() (*Machine, error) { return addr.st.Machine(addr.doc.MachineID) }
[ "func", "(", "addr", "*", "Address", ")", "Machine", "(", ")", "(", "*", "Machine", ",", "error", ")", "{", "return", "addr", ".", "st", ".", "Machine", "(", "addr", ".", "doc", ".", "MachineID", ")", "\n", "}" ]
// Machine returns the Machine this IP address belongs to.
[ "Machine", "returns", "the", "Machine", "this", "IP", "address", "belongs", "to", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_ipaddresses.go#L125-L127
156,368
juju/juju
state/linklayerdevices_ipaddresses.go
Device
func (addr *Address) Device() (*LinkLayerDevice, error) { return addr.machineProxy().LinkLayerDevice(addr.doc.DeviceName) }
go
func (addr *Address) Device() (*LinkLayerDevice, error) { return addr.machineProxy().LinkLayerDevice(addr.doc.DeviceName) }
[ "func", "(", "addr", "*", "Address", ")", "Device", "(", ")", "(", "*", "LinkLayerDevice", ",", "error", ")", "{", "return", "addr", ".", "machineProxy", "(", ")", ".", "LinkLayerDevice", "(", "addr", ".", "doc", ".", "DeviceName", ")", "\n", "}" ]
// Device returns the LinkLayeyDevice this IP address is assigned to.
[ "Device", "returns", "the", "LinkLayeyDevice", "this", "IP", "address", "is", "assigned", "to", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_ipaddresses.go#L142-L144
156,369
juju/juju
state/linklayerdevices_ipaddresses.go
String
func (addr *Address) String() string { return fmt.Sprintf( "%s address %q of device %q on machine %q", addr.doc.ConfigMethod, addr.doc.Value, addr.doc.DeviceName, addr.doc.MachineID, ) }
go
func (addr *Address) String() string { return fmt.Sprintf( "%s address %q of device %q on machine %q", addr.doc.ConfigMethod, addr.doc.Value, addr.doc.DeviceName, addr.doc.MachineID, ) }
[ "func", "(", "addr", "*", "Address", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "addr", ".", "doc", ".", "ConfigMethod", ",", "addr", ".", "doc", ".", "Value", ",", "addr", ".", "doc", ".", "DeviceName", ",", "addr", ".", "doc", ".", "MachineID", ",", ")", "\n", "}" ]
// String returns a human-readable representation of the IP address.
[ "String", "returns", "a", "human", "-", "readable", "representation", "of", "the", "IP", "address", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_ipaddresses.go#L196-L202
156,370
juju/juju
state/linklayerdevices_ipaddresses.go
Remove
func (addr *Address) Remove() (err error) { defer errors.DeferredAnnotatef(&err, "cannot remove %s", addr) removeOp := removeIPAddressDocOp(addr.doc.DocID) ops := []txn.Op{removeOp} if addr.ProviderID() != "" { op := addr.st.networkEntityGlobalKeyRemoveOp("address", addr.ProviderID()) ops = append(ops, op) } return addr.st.db().RunTransaction(ops) }
go
func (addr *Address) Remove() (err error) { defer errors.DeferredAnnotatef(&err, "cannot remove %s", addr) removeOp := removeIPAddressDocOp(addr.doc.DocID) ops := []txn.Op{removeOp} if addr.ProviderID() != "" { op := addr.st.networkEntityGlobalKeyRemoveOp("address", addr.ProviderID()) ops = append(ops, op) } return addr.st.db().RunTransaction(ops) }
[ "func", "(", "addr", "*", "Address", ")", "Remove", "(", ")", "(", "err", "error", ")", "{", "defer", "errors", ".", "DeferredAnnotatef", "(", "&", "err", ",", "\"", "\"", ",", "addr", ")", "\n\n", "removeOp", ":=", "removeIPAddressDocOp", "(", "addr", ".", "doc", ".", "DocID", ")", "\n", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "removeOp", "}", "\n", "if", "addr", ".", "ProviderID", "(", ")", "!=", "\"", "\"", "{", "op", ":=", "addr", ".", "st", ".", "networkEntityGlobalKeyRemoveOp", "(", "\"", "\"", ",", "addr", ".", "ProviderID", "(", ")", ")", "\n", "ops", "=", "append", "(", "ops", ",", "op", ")", "\n", "}", "\n", "return", "addr", ".", "st", ".", "db", "(", ")", ".", "RunTransaction", "(", "ops", ")", "\n", "}" ]
// Remove removes the IP address, if it exists. No error is returned when the // address was already removed.
[ "Remove", "removes", "the", "IP", "address", "if", "it", "exists", ".", "No", "error", "is", "returned", "when", "the", "address", "was", "already", "removed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_ipaddresses.go#L218-L228
156,371
juju/juju
state/linklayerdevices_ipaddresses.go
removeIPAddressDocOp
func removeIPAddressDocOp(ipAddressDocID string) txn.Op { return txn.Op{ C: ipAddressesC, Id: ipAddressDocID, Remove: true, } }
go
func removeIPAddressDocOp(ipAddressDocID string) txn.Op { return txn.Op{ C: ipAddressesC, Id: ipAddressDocID, Remove: true, } }
[ "func", "removeIPAddressDocOp", "(", "ipAddressDocID", "string", ")", "txn", ".", "Op", "{", "return", "txn", ".", "Op", "{", "C", ":", "ipAddressesC", ",", "Id", ":", "ipAddressDocID", ",", "Remove", ":", "true", ",", "}", "\n", "}" ]
// removeIPAddressDocOpOp returns an operation to remove the ipAddressDoc // matching the given ipAddressDocID, without asserting it still exists.
[ "removeIPAddressDocOpOp", "returns", "an", "operation", "to", "remove", "the", "ipAddressDoc", "matching", "the", "given", "ipAddressDocID", "without", "asserting", "it", "still", "exists", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_ipaddresses.go#L232-L238
156,372
juju/juju
state/linklayerdevices_ipaddresses.go
insertIPAddressDocOp
func insertIPAddressDocOp(newDoc *ipAddressDoc) txn.Op { return txn.Op{ C: ipAddressesC, Id: newDoc.DocID, Assert: txn.DocMissing, Insert: *newDoc, } }
go
func insertIPAddressDocOp(newDoc *ipAddressDoc) txn.Op { return txn.Op{ C: ipAddressesC, Id: newDoc.DocID, Assert: txn.DocMissing, Insert: *newDoc, } }
[ "func", "insertIPAddressDocOp", "(", "newDoc", "*", "ipAddressDoc", ")", "txn", ".", "Op", "{", "return", "txn", ".", "Op", "{", "C", ":", "ipAddressesC", ",", "Id", ":", "newDoc", ".", "DocID", ",", "Assert", ":", "txn", ".", "DocMissing", ",", "Insert", ":", "*", "newDoc", ",", "}", "\n", "}" ]
// insertIPAddressDocOp returns an operation inserting the given newDoc, // asserting it does not exist yet.
[ "insertIPAddressDocOp", "returns", "an", "operation", "inserting", "the", "given", "newDoc", "asserting", "it", "does", "not", "exist", "yet", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_ipaddresses.go#L242-L249
156,373
juju/juju
state/linklayerdevices_ipaddresses.go
updateIPAddressDocOp
func updateIPAddressDocOp(existingDoc, newDoc *ipAddressDoc) (txn.Op, bool) { changes := make(bson.M) deletes := make(bson.M) if existingDoc.ProviderID == "" && newDoc.ProviderID != "" { // Only allow changing the ProviderID if it was empty. changes["providerid"] = newDoc.ProviderID } if existingDoc.ConfigMethod != newDoc.ConfigMethod { changes["config-method"] = newDoc.ConfigMethod } if existingDoc.SubnetCIDR != newDoc.SubnetCIDR { changes["subnet-cidr"] = newDoc.SubnetCIDR } if strsDiffer(newDoc.DNSServers, existingDoc.DNSServers) { if len(newDoc.DNSServers) == 0 { deletes["dns-servers"] = 1 } else { changes["dns-servers"] = newDoc.DNSServers } } if strsDiffer(newDoc.DNSSearchDomains, existingDoc.DNSSearchDomains) { if len(newDoc.DNSSearchDomains) == 0 { deletes["dns-search-domains"] = 1 } else { changes["dns-search-domains"] = newDoc.DNSSearchDomains } } if existingDoc.GatewayAddress != newDoc.GatewayAddress { changes["gateway-address"] = newDoc.GatewayAddress } var updates bson.D if len(changes) > 0 { updates = append(updates, bson.DocElem{Name: "$set", Value: changes}) } if len(deletes) > 0 { updates = append(updates, bson.DocElem{Name: "$unset", Value: deletes}) } return txn.Op{ C: ipAddressesC, Id: existingDoc.DocID, Assert: txn.DocExists, Update: updates, }, len(updates) > 0 }
go
func updateIPAddressDocOp(existingDoc, newDoc *ipAddressDoc) (txn.Op, bool) { changes := make(bson.M) deletes := make(bson.M) if existingDoc.ProviderID == "" && newDoc.ProviderID != "" { // Only allow changing the ProviderID if it was empty. changes["providerid"] = newDoc.ProviderID } if existingDoc.ConfigMethod != newDoc.ConfigMethod { changes["config-method"] = newDoc.ConfigMethod } if existingDoc.SubnetCIDR != newDoc.SubnetCIDR { changes["subnet-cidr"] = newDoc.SubnetCIDR } if strsDiffer(newDoc.DNSServers, existingDoc.DNSServers) { if len(newDoc.DNSServers) == 0 { deletes["dns-servers"] = 1 } else { changes["dns-servers"] = newDoc.DNSServers } } if strsDiffer(newDoc.DNSSearchDomains, existingDoc.DNSSearchDomains) { if len(newDoc.DNSSearchDomains) == 0 { deletes["dns-search-domains"] = 1 } else { changes["dns-search-domains"] = newDoc.DNSSearchDomains } } if existingDoc.GatewayAddress != newDoc.GatewayAddress { changes["gateway-address"] = newDoc.GatewayAddress } var updates bson.D if len(changes) > 0 { updates = append(updates, bson.DocElem{Name: "$set", Value: changes}) } if len(deletes) > 0 { updates = append(updates, bson.DocElem{Name: "$unset", Value: deletes}) } return txn.Op{ C: ipAddressesC, Id: existingDoc.DocID, Assert: txn.DocExists, Update: updates, }, len(updates) > 0 }
[ "func", "updateIPAddressDocOp", "(", "existingDoc", ",", "newDoc", "*", "ipAddressDoc", ")", "(", "txn", ".", "Op", ",", "bool", ")", "{", "changes", ":=", "make", "(", "bson", ".", "M", ")", "\n", "deletes", ":=", "make", "(", "bson", ".", "M", ")", "\n", "if", "existingDoc", ".", "ProviderID", "==", "\"", "\"", "&&", "newDoc", ".", "ProviderID", "!=", "\"", "\"", "{", "// Only allow changing the ProviderID if it was empty.", "changes", "[", "\"", "\"", "]", "=", "newDoc", ".", "ProviderID", "\n", "}", "\n", "if", "existingDoc", ".", "ConfigMethod", "!=", "newDoc", ".", "ConfigMethod", "{", "changes", "[", "\"", "\"", "]", "=", "newDoc", ".", "ConfigMethod", "\n", "}", "\n\n", "if", "existingDoc", ".", "SubnetCIDR", "!=", "newDoc", ".", "SubnetCIDR", "{", "changes", "[", "\"", "\"", "]", "=", "newDoc", ".", "SubnetCIDR", "\n", "}", "\n\n", "if", "strsDiffer", "(", "newDoc", ".", "DNSServers", ",", "existingDoc", ".", "DNSServers", ")", "{", "if", "len", "(", "newDoc", ".", "DNSServers", ")", "==", "0", "{", "deletes", "[", "\"", "\"", "]", "=", "1", "\n", "}", "else", "{", "changes", "[", "\"", "\"", "]", "=", "newDoc", ".", "DNSServers", "\n", "}", "\n", "}", "\n", "if", "strsDiffer", "(", "newDoc", ".", "DNSSearchDomains", ",", "existingDoc", ".", "DNSSearchDomains", ")", "{", "if", "len", "(", "newDoc", ".", "DNSSearchDomains", ")", "==", "0", "{", "deletes", "[", "\"", "\"", "]", "=", "1", "\n", "}", "else", "{", "changes", "[", "\"", "\"", "]", "=", "newDoc", ".", "DNSSearchDomains", "\n", "}", "\n", "}", "\n\n", "if", "existingDoc", ".", "GatewayAddress", "!=", "newDoc", ".", "GatewayAddress", "{", "changes", "[", "\"", "\"", "]", "=", "newDoc", ".", "GatewayAddress", "\n", "}", "\n\n", "var", "updates", "bson", ".", "D", "\n", "if", "len", "(", "changes", ")", ">", "0", "{", "updates", "=", "append", "(", "updates", ",", "bson", ".", "DocElem", "{", "Name", ":", "\"", "\"", ",", "Value", ":", "changes", "}", ")", "\n", "}", "\n", "if", "len", "(", "deletes", ")", ">", "0", "{", "updates", "=", "append", "(", "updates", ",", "bson", ".", "DocElem", "{", "Name", ":", "\"", "\"", ",", "Value", ":", "deletes", "}", ")", "\n", "}", "\n\n", "return", "txn", ".", "Op", "{", "C", ":", "ipAddressesC", ",", "Id", ":", "existingDoc", ".", "DocID", ",", "Assert", ":", "txn", ".", "DocExists", ",", "Update", ":", "updates", ",", "}", ",", "len", "(", "updates", ")", ">", "0", "\n", "}" ]
// updateIPAddressDocOp returns an operation updating the fields of existingDoc // with the respective values of those fields in newDoc. DocID, ModelUUID, // Value, MachineID, and DeviceName cannot be changed. ProviderID cannot be // changed once set. DNSServers and DNSSearchDomains are deleted when nil. In // all other cases newDoc values overwrites existingDoc values.
[ "updateIPAddressDocOp", "returns", "an", "operation", "updating", "the", "fields", "of", "existingDoc", "with", "the", "respective", "values", "of", "those", "fields", "in", "newDoc", ".", "DocID", "ModelUUID", "Value", "MachineID", "and", "DeviceName", "cannot", "be", "changed", ".", "ProviderID", "cannot", "be", "changed", "once", "set", ".", "DNSServers", "and", "DNSSearchDomains", "are", "deleted", "when", "nil", ".", "In", "all", "other", "cases", "newDoc", "values", "overwrites", "existingDoc", "values", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_ipaddresses.go#L268-L316
156,374
juju/juju
state/linklayerdevices_ipaddresses.go
AllIPAddresses
func (st *State) AllIPAddresses() (addresses []*Address, err error) { addressesCollection, closer := st.db().GetCollection(ipAddressesC) defer closer() sdocs := []ipAddressDoc{} err = addressesCollection.Find(bson.D{}).All(&sdocs) if err != nil { return nil, errors.Errorf("cannot get all ip addresses") } for _, a := range sdocs { addresses = append(addresses, newIPAddress(st, a)) } return addresses, nil }
go
func (st *State) AllIPAddresses() (addresses []*Address, err error) { addressesCollection, closer := st.db().GetCollection(ipAddressesC) defer closer() sdocs := []ipAddressDoc{} err = addressesCollection.Find(bson.D{}).All(&sdocs) if err != nil { return nil, errors.Errorf("cannot get all ip addresses") } for _, a := range sdocs { addresses = append(addresses, newIPAddress(st, a)) } return addresses, nil }
[ "func", "(", "st", "*", "State", ")", "AllIPAddresses", "(", ")", "(", "addresses", "[", "]", "*", "Address", ",", "err", "error", ")", "{", "addressesCollection", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "ipAddressesC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "sdocs", ":=", "[", "]", "ipAddressDoc", "{", "}", "\n", "err", "=", "addressesCollection", ".", "Find", "(", "bson", ".", "D", "{", "}", ")", ".", "All", "(", "&", "sdocs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "a", ":=", "range", "sdocs", "{", "addresses", "=", "append", "(", "addresses", ",", "newIPAddress", "(", "st", ",", "a", ")", ")", "\n", "}", "\n", "return", "addresses", ",", "nil", "\n", "}" ]
// AllIPAddresses returns all ip addresses in the model.
[ "AllIPAddresses", "returns", "all", "ip", "addresses", "in", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/linklayerdevices_ipaddresses.go#L364-L377
156,375
juju/juju
cmd/juju/commands/ssh_common.go
defaultReachableChecker
func defaultReachableChecker() jujussh.ReachableChecker { return jujussh.NewReachableChecker(&net.Dialer{Timeout: SSHRetryDelay}, SSHTimeout) }
go
func defaultReachableChecker() jujussh.ReachableChecker { return jujussh.NewReachableChecker(&net.Dialer{Timeout: SSHRetryDelay}, SSHTimeout) }
[ "func", "defaultReachableChecker", "(", ")", "jujussh", ".", "ReachableChecker", "{", "return", "jujussh", ".", "NewReachableChecker", "(", "&", "net", ".", "Dialer", "{", "Timeout", ":", "SSHRetryDelay", "}", ",", "SSHTimeout", ")", "\n", "}" ]
// defaultReachableChecker returns a jujussh.ReachableChecker with a connection // timeout of SSHRetryDelay and an overall timout of SSHTimeout
[ "defaultReachableChecker", "returns", "a", "jujussh", ".", "ReachableChecker", "with", "a", "connection", "timeout", "of", "SSHRetryDelay", "and", "an", "overall", "timout", "of", "SSHTimeout" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/ssh_common.go#L120-L122
156,376
juju/juju
cmd/juju/commands/ssh_common.go
initRun
func (c *SSHCommon) initRun() error { if err := c.ensureAPIClient(); err != nil { return errors.Trace(err) } if proxy, err := c.proxySSH(); err != nil { return errors.Trace(err) } else { c.proxy = proxy } // Used mostly for testing, but useful for debugging and/or // backwards-compatibility with some scripts. c.forceAPIv1 = os.Getenv(jujuSSHClientForceAPIv1) != "" return nil }
go
func (c *SSHCommon) initRun() error { if err := c.ensureAPIClient(); err != nil { return errors.Trace(err) } if proxy, err := c.proxySSH(); err != nil { return errors.Trace(err) } else { c.proxy = proxy } // Used mostly for testing, but useful for debugging and/or // backwards-compatibility with some scripts. c.forceAPIv1 = os.Getenv(jujuSSHClientForceAPIv1) != "" return nil }
[ "func", "(", "c", "*", "SSHCommon", ")", "initRun", "(", ")", "error", "{", "if", "err", ":=", "c", ".", "ensureAPIClient", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "proxy", ",", "err", ":=", "c", ".", "proxySSH", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "else", "{", "c", ".", "proxy", "=", "proxy", "\n", "}", "\n\n", "// Used mostly for testing, but useful for debugging and/or", "// backwards-compatibility with some scripts.", "c", ".", "forceAPIv1", "=", "os", ".", "Getenv", "(", "jujuSSHClientForceAPIv1", ")", "!=", "\"", "\"", "\n", "return", "nil", "\n", "}" ]
// initRun initializes the API connection if required, and determines // if SSH proxying is required. It must be called at the top of the // command's Run method. // // The apiClient, apiAddr and proxy fields are initialized after this call.
[ "initRun", "initializes", "the", "API", "connection", "if", "required", "and", "determines", "if", "SSH", "proxying", "is", "required", ".", "It", "must", "be", "called", "at", "the", "top", "of", "the", "command", "s", "Run", "method", ".", "The", "apiClient", "apiAddr", "and", "proxy", "fields", "are", "initialized", "after", "this", "call", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/ssh_common.go#L136-L151
156,377
juju/juju
cmd/juju/commands/ssh_common.go
getSSHOptions
func (c *SSHCommon) getSSHOptions(enablePty bool, targets ...*resolvedTarget) (*ssh.Options, error) { var options ssh.Options if c.noHostKeyChecks { options.SetStrictHostKeyChecking(ssh.StrictHostChecksNo) options.SetKnownHostsFile(os.DevNull) } else { knownHostsPath, err := c.generateKnownHosts(targets) if err != nil { return nil, errors.Trace(err) } // There might not be a custom known_hosts file if the SSH // targets are specified using arbitrary hostnames or // addresses. In this case, the user's personal known_hosts // file is used. if knownHostsPath != "" { // When a known_hosts file has been generated, enforce // strict host key checking. options.SetStrictHostKeyChecking(ssh.StrictHostChecksYes) options.SetKnownHostsFile(knownHostsPath) } } if enablePty { options.EnablePTY() } if c.proxy { if err := c.setProxyCommand(&options); err != nil { return nil, err } } return &options, nil }
go
func (c *SSHCommon) getSSHOptions(enablePty bool, targets ...*resolvedTarget) (*ssh.Options, error) { var options ssh.Options if c.noHostKeyChecks { options.SetStrictHostKeyChecking(ssh.StrictHostChecksNo) options.SetKnownHostsFile(os.DevNull) } else { knownHostsPath, err := c.generateKnownHosts(targets) if err != nil { return nil, errors.Trace(err) } // There might not be a custom known_hosts file if the SSH // targets are specified using arbitrary hostnames or // addresses. In this case, the user's personal known_hosts // file is used. if knownHostsPath != "" { // When a known_hosts file has been generated, enforce // strict host key checking. options.SetStrictHostKeyChecking(ssh.StrictHostChecksYes) options.SetKnownHostsFile(knownHostsPath) } } if enablePty { options.EnablePTY() } if c.proxy { if err := c.setProxyCommand(&options); err != nil { return nil, err } } return &options, nil }
[ "func", "(", "c", "*", "SSHCommon", ")", "getSSHOptions", "(", "enablePty", "bool", ",", "targets", "...", "*", "resolvedTarget", ")", "(", "*", "ssh", ".", "Options", ",", "error", ")", "{", "var", "options", "ssh", ".", "Options", "\n\n", "if", "c", ".", "noHostKeyChecks", "{", "options", ".", "SetStrictHostKeyChecking", "(", "ssh", ".", "StrictHostChecksNo", ")", "\n", "options", ".", "SetKnownHostsFile", "(", "os", ".", "DevNull", ")", "\n", "}", "else", "{", "knownHostsPath", ",", "err", ":=", "c", ".", "generateKnownHosts", "(", "targets", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// There might not be a custom known_hosts file if the SSH", "// targets are specified using arbitrary hostnames or", "// addresses. In this case, the user's personal known_hosts", "// file is used.", "if", "knownHostsPath", "!=", "\"", "\"", "{", "// When a known_hosts file has been generated, enforce", "// strict host key checking.", "options", ".", "SetStrictHostKeyChecking", "(", "ssh", ".", "StrictHostChecksYes", ")", "\n", "options", ".", "SetKnownHostsFile", "(", "knownHostsPath", ")", "\n", "}", "\n", "}", "\n\n", "if", "enablePty", "{", "options", ".", "EnablePTY", "(", ")", "\n", "}", "\n\n", "if", "c", ".", "proxy", "{", "if", "err", ":=", "c", ".", "setProxyCommand", "(", "&", "options", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "&", "options", ",", "nil", "\n", "}" ]
// getSSHOptions configures SSH options based on command line // arguments and the SSH targets specified.
[ "getSSHOptions", "configures", "SSH", "options", "based", "on", "command", "line", "arguments", "and", "the", "SSH", "targets", "specified", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/ssh_common.go#L169-L205
156,378
juju/juju
cmd/juju/commands/ssh_common.go
generateKnownHosts
func (c *SSHCommon) generateKnownHosts(targets []*resolvedTarget) (string, error) { knownHosts := newKnownHostsBuilder() agentCount := 0 nonAgentCount := 0 for _, target := range targets { if target.isAgent() { agentCount++ keys, err := c.apiClient.PublicKeys(target.entity) if err != nil { return "", errors.Annotatef(err, "retrieving SSH host keys for %q", target.entity) } knownHosts.add(target.host, keys) } else { nonAgentCount++ } } if agentCount > 0 && nonAgentCount > 0 { return "", errors.New("can't determine host keys for all targets: consider --no-host-key-checks") } if knownHosts.size() == 0 { // No public keys to write so exit early. return "", nil } f, err := ioutil.TempFile("", "ssh_known_hosts") if err != nil { return "", errors.Annotate(err, "creating known hosts file") } defer f.Close() c.knownHostsPath = f.Name() // Record for later deletion if knownHosts.write(f); err != nil { return "", errors.Trace(err) } return c.knownHostsPath, nil }
go
func (c *SSHCommon) generateKnownHosts(targets []*resolvedTarget) (string, error) { knownHosts := newKnownHostsBuilder() agentCount := 0 nonAgentCount := 0 for _, target := range targets { if target.isAgent() { agentCount++ keys, err := c.apiClient.PublicKeys(target.entity) if err != nil { return "", errors.Annotatef(err, "retrieving SSH host keys for %q", target.entity) } knownHosts.add(target.host, keys) } else { nonAgentCount++ } } if agentCount > 0 && nonAgentCount > 0 { return "", errors.New("can't determine host keys for all targets: consider --no-host-key-checks") } if knownHosts.size() == 0 { // No public keys to write so exit early. return "", nil } f, err := ioutil.TempFile("", "ssh_known_hosts") if err != nil { return "", errors.Annotate(err, "creating known hosts file") } defer f.Close() c.knownHostsPath = f.Name() // Record for later deletion if knownHosts.write(f); err != nil { return "", errors.Trace(err) } return c.knownHostsPath, nil }
[ "func", "(", "c", "*", "SSHCommon", ")", "generateKnownHosts", "(", "targets", "[", "]", "*", "resolvedTarget", ")", "(", "string", ",", "error", ")", "{", "knownHosts", ":=", "newKnownHostsBuilder", "(", ")", "\n", "agentCount", ":=", "0", "\n", "nonAgentCount", ":=", "0", "\n", "for", "_", ",", "target", ":=", "range", "targets", "{", "if", "target", ".", "isAgent", "(", ")", "{", "agentCount", "++", "\n", "keys", ",", "err", ":=", "c", ".", "apiClient", ".", "PublicKeys", "(", "target", ".", "entity", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "target", ".", "entity", ")", "\n", "}", "\n", "knownHosts", ".", "add", "(", "target", ".", "host", ",", "keys", ")", "\n", "}", "else", "{", "nonAgentCount", "++", "\n", "}", "\n", "}", "\n\n", "if", "agentCount", ">", "0", "&&", "nonAgentCount", ">", "0", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "knownHosts", ".", "size", "(", ")", "==", "0", "{", "// No public keys to write so exit early.", "return", "\"", "\"", ",", "nil", "\n", "}", "\n\n", "f", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "c", ".", "knownHostsPath", "=", "f", ".", "Name", "(", ")", "// Record for later deletion", "\n", "if", "knownHosts", ".", "write", "(", "f", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "c", ".", "knownHostsPath", ",", "nil", "\n", "}" ]
// generateKnownHosts takes the provided targets, retrieves the SSH // public host keys for them and generates a temporary known_hosts // file for them.
[ "generateKnownHosts", "takes", "the", "provided", "targets", "retrieves", "the", "SSH", "public", "host", "keys", "for", "them", "and", "generates", "a", "temporary", "known_hosts", "file", "for", "them", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/ssh_common.go#L210-L246
156,379
juju/juju
cmd/juju/commands/ssh_common.go
setProxyCommand
func (c *SSHCommon) setProxyCommand(options *ssh.Options) error { apiServerHost, _, err := net.SplitHostPort(c.apiAddr) if err != nil { return errors.Errorf("failed to get proxy address: %v", err) } juju, err := getJujuExecutable() if err != nil { return errors.Errorf("failed to get juju executable path: %v", err) } modelName, err := c.ModelName() if err != nil { return errors.Trace(err) } // TODO(mjs) 2016-05-09 LP #1579592 - It would be good to check the // host key of the controller machine being used for proxying // here. This isn't too serious as all traffic passing through the // controller host is encrypted and the host key of the ultimate // target host is verified but it would still be better to perform // this extra level of checking. options.SetProxyCommand( juju, "ssh", "--model="+modelName, "--proxy=false", "--no-host-key-checks", "--pty=false", "ubuntu@"+apiServerHost, "-q", "nc %h %p", ) return nil }
go
func (c *SSHCommon) setProxyCommand(options *ssh.Options) error { apiServerHost, _, err := net.SplitHostPort(c.apiAddr) if err != nil { return errors.Errorf("failed to get proxy address: %v", err) } juju, err := getJujuExecutable() if err != nil { return errors.Errorf("failed to get juju executable path: %v", err) } modelName, err := c.ModelName() if err != nil { return errors.Trace(err) } // TODO(mjs) 2016-05-09 LP #1579592 - It would be good to check the // host key of the controller machine being used for proxying // here. This isn't too serious as all traffic passing through the // controller host is encrypted and the host key of the ultimate // target host is verified but it would still be better to perform // this extra level of checking. options.SetProxyCommand( juju, "ssh", "--model="+modelName, "--proxy=false", "--no-host-key-checks", "--pty=false", "ubuntu@"+apiServerHost, "-q", "nc %h %p", ) return nil }
[ "func", "(", "c", "*", "SSHCommon", ")", "setProxyCommand", "(", "options", "*", "ssh", ".", "Options", ")", "error", "{", "apiServerHost", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "c", ".", "apiAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "juju", ",", "err", ":=", "getJujuExecutable", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "modelName", ",", "err", ":=", "c", ".", "ModelName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// TODO(mjs) 2016-05-09 LP #1579592 - It would be good to check the", "// host key of the controller machine being used for proxying", "// here. This isn't too serious as all traffic passing through the", "// controller host is encrypted and the host key of the ultimate", "// target host is verified but it would still be better to perform", "// this extra level of checking.", "options", ".", "SetProxyCommand", "(", "juju", ",", "\"", "\"", ",", "\"", "\"", "+", "modelName", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "+", "apiServerHost", ",", "\"", "\"", ",", "\"", "\"", ",", ")", "\n", "return", "nil", "\n", "}" ]
// setProxyCommand sets the proxy command option.
[ "setProxyCommand", "sets", "the", "proxy", "command", "option", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/ssh_common.go#L265-L296
156,380
juju/juju
cmd/juju/commands/ssh_common.go
initAPIClient
func (c *SSHCommon) initAPIClient() error { conn, err := c.NewAPIRoot() if err != nil { return errors.Trace(err) } c.apiClient = sshclient.NewFacade(conn) c.apiAddr = conn.Addr() return nil }
go
func (c *SSHCommon) initAPIClient() error { conn, err := c.NewAPIRoot() if err != nil { return errors.Trace(err) } c.apiClient = sshclient.NewFacade(conn) c.apiAddr = conn.Addr() return nil }
[ "func", "(", "c", "*", "SSHCommon", ")", "initAPIClient", "(", ")", "error", "{", "conn", ",", "err", ":=", "c", ".", "NewAPIRoot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "c", ".", "apiClient", "=", "sshclient", ".", "NewFacade", "(", "conn", ")", "\n", "c", ".", "apiAddr", "=", "conn", ".", "Addr", "(", ")", "\n", "return", "nil", "\n", "}" ]
// initAPIClient initialises the API connection.
[ "initAPIClient", "initialises", "the", "API", "connection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/ssh_common.go#L306-L314
156,381
juju/juju
cmd/juju/commands/ssh_common.go
reachableAddressGetter
func (c *SSHCommon) reachableAddressGetter(entity string) (string, error) { addresses, err := c.apiClient.AllAddresses(entity) if err != nil { return "", errors.Trace(err) } else if len(addresses) == 0 { return "", network.NoAddressError("available") } else if len(addresses) == 1 { logger.Debugf("Only one SSH address provided (%s), using it without probing", addresses[0]) return addresses[0], nil } publicKeys := []string{} if !c.noHostKeyChecks { publicKeys, err = c.apiClient.PublicKeys(entity) if err != nil { return "", errors.Annotatef(err, "retrieving SSH host keys for %q", entity) } } hostPorts := network.NewHostPorts(SSHPort, addresses...) usableHPs := network.FilterUnusableHostPorts(hostPorts) bestHP, err := c.hostChecker.FindHost(usableHPs, publicKeys) if err != nil { return "", errors.Trace(err) } return bestHP.Address.Value, nil }
go
func (c *SSHCommon) reachableAddressGetter(entity string) (string, error) { addresses, err := c.apiClient.AllAddresses(entity) if err != nil { return "", errors.Trace(err) } else if len(addresses) == 0 { return "", network.NoAddressError("available") } else if len(addresses) == 1 { logger.Debugf("Only one SSH address provided (%s), using it without probing", addresses[0]) return addresses[0], nil } publicKeys := []string{} if !c.noHostKeyChecks { publicKeys, err = c.apiClient.PublicKeys(entity) if err != nil { return "", errors.Annotatef(err, "retrieving SSH host keys for %q", entity) } } hostPorts := network.NewHostPorts(SSHPort, addresses...) usableHPs := network.FilterUnusableHostPorts(hostPorts) bestHP, err := c.hostChecker.FindHost(usableHPs, publicKeys) if err != nil { return "", errors.Trace(err) } return bestHP.Address.Value, nil }
[ "func", "(", "c", "*", "SSHCommon", ")", "reachableAddressGetter", "(", "entity", "string", ")", "(", "string", ",", "error", ")", "{", "addresses", ",", "err", ":=", "c", ".", "apiClient", ".", "AllAddresses", "(", "entity", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "else", "if", "len", "(", "addresses", ")", "==", "0", "{", "return", "\"", "\"", ",", "network", ".", "NoAddressError", "(", "\"", "\"", ")", "\n", "}", "else", "if", "len", "(", "addresses", ")", "==", "1", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "addresses", "[", "0", "]", ")", "\n", "return", "addresses", "[", "0", "]", ",", "nil", "\n", "}", "\n", "publicKeys", ":=", "[", "]", "string", "{", "}", "\n", "if", "!", "c", ".", "noHostKeyChecks", "{", "publicKeys", ",", "err", "=", "c", ".", "apiClient", ".", "PublicKeys", "(", "entity", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "entity", ")", "\n", "}", "\n", "}", "\n\n", "hostPorts", ":=", "network", ".", "NewHostPorts", "(", "SSHPort", ",", "addresses", "...", ")", "\n", "usableHPs", ":=", "network", ".", "FilterUnusableHostPorts", "(", "hostPorts", ")", "\n", "bestHP", ",", "err", ":=", "c", ".", "hostChecker", ".", "FindHost", "(", "usableHPs", ",", "publicKeys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "bestHP", ".", "Address", ".", "Value", ",", "nil", "\n", "}" ]
// reachableAddressGetter dials all addresses of the given entity, returning the // first one that succeeds. Only used with SSHClient API facade v2 or later is // available. It does not try to dial if only one address is available.
[ "reachableAddressGetter", "dials", "all", "addresses", "of", "the", "given", "entity", "returning", "the", "first", "one", "that", "succeeds", ".", "Only", "used", "with", "SSHClient", "API", "facade", "v2", "or", "later", "is", "available", ".", "It", "does", "not", "try", "to", "dial", "if", "only", "one", "address", "is", "available", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/ssh_common.go#L402-L428
156,382
juju/juju
environs/tools/simplestreams.go
NewVersionedToolsConstraint
func NewVersionedToolsConstraint(vers version.Number, params simplestreams.LookupParams) *ToolsConstraint { return &ToolsConstraint{LookupParams: params, Version: vers} }
go
func NewVersionedToolsConstraint(vers version.Number, params simplestreams.LookupParams) *ToolsConstraint { return &ToolsConstraint{LookupParams: params, Version: vers} }
[ "func", "NewVersionedToolsConstraint", "(", "vers", "version", ".", "Number", ",", "params", "simplestreams", ".", "LookupParams", ")", "*", "ToolsConstraint", "{", "return", "&", "ToolsConstraint", "{", "LookupParams", ":", "params", ",", "Version", ":", "vers", "}", "\n", "}" ]
// NewVersionedToolsConstraint returns a ToolsConstraint for a tools with a specific version.
[ "NewVersionedToolsConstraint", "returns", "a", "ToolsConstraint", "for", "a", "tools", "with", "a", "specific", "version", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L76-L78
156,383
juju/juju
environs/tools/simplestreams.go
sortString
func (t *ToolsMetadata) sortString() string { return fmt.Sprintf("%v-%s-%s", t.Version, t.Release, t.Arch) }
go
func (t *ToolsMetadata) sortString() string { return fmt.Sprintf("%v-%s-%s", t.Version, t.Release, t.Arch) }
[ "func", "(", "t", "*", "ToolsMetadata", ")", "sortString", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ".", "Version", ",", "t", ".", "Release", ",", "t", ".", "Arch", ")", "\n", "}" ]
// sortString is used by byVersion to sort a list of ToolsMetadata.
[ "sortString", "is", "used", "by", "byVersion", "to", "sort", "a", "list", "of", "ToolsMetadata", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L132-L134
156,384
juju/juju
environs/tools/simplestreams.go
binary
func (t *ToolsMetadata) binary() (version.Binary, error) { num, err := version.Parse(t.Version) if err != nil { return version.Binary{}, errors.Trace(err) } return version.Binary{ Number: num, Series: t.Release, Arch: t.Arch, }, nil }
go
func (t *ToolsMetadata) binary() (version.Binary, error) { num, err := version.Parse(t.Version) if err != nil { return version.Binary{}, errors.Trace(err) } return version.Binary{ Number: num, Series: t.Release, Arch: t.Arch, }, nil }
[ "func", "(", "t", "*", "ToolsMetadata", ")", "binary", "(", ")", "(", "version", ".", "Binary", ",", "error", ")", "{", "num", ",", "err", ":=", "version", ".", "Parse", "(", "t", ".", "Version", ")", "\n", "if", "err", "!=", "nil", "{", "return", "version", ".", "Binary", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "version", ".", "Binary", "{", "Number", ":", "num", ",", "Series", ":", "t", ".", "Release", ",", "Arch", ":", "t", ".", "Arch", ",", "}", ",", "nil", "\n", "}" ]
// binary returns the tools metadata's binary version, which may be used for // map lookup.
[ "binary", "returns", "the", "tools", "metadata", "s", "binary", "version", "which", "may", "be", "used", "for", "map", "lookup", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L138-L148
156,385
juju/juju
environs/tools/simplestreams.go
Fetch
func Fetch( sources []simplestreams.DataSource, cons *ToolsConstraint, ) ([]*ToolsMetadata, *simplestreams.ResolveInfo, error) { params := simplestreams.GetMetadataParams{ StreamsVersion: currentStreamsVersion, LookupConstraint: cons, ValueParams: simplestreams.ValueParams{ DataType: ContentDownload, FilterFunc: appendMatchingTools, MirrorContentId: ToolsContentId(cons.Stream), ValueTemplate: ToolsMetadata{}, }, } items, resolveInfo, err := simplestreams.GetMetadata(sources, params) if err != nil { return nil, nil, err } metadata := make([]*ToolsMetadata, len(items)) for i, md := range items { metadata[i] = md.(*ToolsMetadata) } // Sorting the metadata is not strictly necessary, but it ensures consistent ordering for // all compilers, and it just makes it easier to look at the data. Sort(metadata) return metadata, resolveInfo, nil }
go
func Fetch( sources []simplestreams.DataSource, cons *ToolsConstraint, ) ([]*ToolsMetadata, *simplestreams.ResolveInfo, error) { params := simplestreams.GetMetadataParams{ StreamsVersion: currentStreamsVersion, LookupConstraint: cons, ValueParams: simplestreams.ValueParams{ DataType: ContentDownload, FilterFunc: appendMatchingTools, MirrorContentId: ToolsContentId(cons.Stream), ValueTemplate: ToolsMetadata{}, }, } items, resolveInfo, err := simplestreams.GetMetadata(sources, params) if err != nil { return nil, nil, err } metadata := make([]*ToolsMetadata, len(items)) for i, md := range items { metadata[i] = md.(*ToolsMetadata) } // Sorting the metadata is not strictly necessary, but it ensures consistent ordering for // all compilers, and it just makes it easier to look at the data. Sort(metadata) return metadata, resolveInfo, nil }
[ "func", "Fetch", "(", "sources", "[", "]", "simplestreams", ".", "DataSource", ",", "cons", "*", "ToolsConstraint", ",", ")", "(", "[", "]", "*", "ToolsMetadata", ",", "*", "simplestreams", ".", "ResolveInfo", ",", "error", ")", "{", "params", ":=", "simplestreams", ".", "GetMetadataParams", "{", "StreamsVersion", ":", "currentStreamsVersion", ",", "LookupConstraint", ":", "cons", ",", "ValueParams", ":", "simplestreams", ".", "ValueParams", "{", "DataType", ":", "ContentDownload", ",", "FilterFunc", ":", "appendMatchingTools", ",", "MirrorContentId", ":", "ToolsContentId", "(", "cons", ".", "Stream", ")", ",", "ValueTemplate", ":", "ToolsMetadata", "{", "}", ",", "}", ",", "}", "\n", "items", ",", "resolveInfo", ",", "err", ":=", "simplestreams", ".", "GetMetadata", "(", "sources", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "metadata", ":=", "make", "(", "[", "]", "*", "ToolsMetadata", ",", "len", "(", "items", ")", ")", "\n", "for", "i", ",", "md", ":=", "range", "items", "{", "metadata", "[", "i", "]", "=", "md", ".", "(", "*", "ToolsMetadata", ")", "\n", "}", "\n", "// Sorting the metadata is not strictly necessary, but it ensures consistent ordering for", "// all compilers, and it just makes it easier to look at the data.", "Sort", "(", "metadata", ")", "\n", "return", "metadata", ",", "resolveInfo", ",", "nil", "\n", "}" ]
// Fetch returns a list of tools for the specified cloud matching the constraint. // The base URL locations are as specified - the first location which has a file is the one used. // Signed data is preferred, but if there is no signed data available and onlySigned is false, // then unsigned data is used.
[ "Fetch", "returns", "a", "list", "of", "tools", "for", "the", "specified", "cloud", "matching", "the", "constraint", ".", "The", "base", "URL", "locations", "are", "as", "specified", "-", "the", "first", "location", "which", "has", "a", "file", "is", "the", "one", "used", ".", "Signed", "data", "is", "preferred", "but", "if", "there", "is", "no", "signed", "data", "available", "and", "onlySigned", "is", "false", "then", "unsigned", "data", "is", "used", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L162-L188
156,386
juju/juju
environs/tools/simplestreams.go
appendMatchingTools
func appendMatchingTools(source simplestreams.DataSource, matchingTools []interface{}, tools map[string]interface{}, cons simplestreams.LookupConstraint) ([]interface{}, error) { toolsMap := make(map[version.Binary]*ToolsMetadata, len(matchingTools)) for _, val := range matchingTools { tm := val.(*ToolsMetadata) binary, err := tm.binary() if err != nil { return nil, errors.Trace(err) } toolsMap[binary] = tm } for _, val := range tools { tm := val.(*ToolsMetadata) if !set.NewStrings(cons.Params().Series...).Contains(tm.Release) { continue } if toolsConstraint, ok := cons.(*ToolsConstraint); ok { tmNumber := version.MustParse(tm.Version) if toolsConstraint.Version == version.Zero { if toolsConstraint.MajorVersion >= 0 && toolsConstraint.MajorVersion != tmNumber.Major { continue } if toolsConstraint.MinorVersion >= 0 && toolsConstraint.MinorVersion != tmNumber.Minor { continue } } else { if toolsConstraint.Version != tmNumber { continue } } } binary, err := tm.binary() if err != nil { return nil, errors.Trace(err) } if _, ok := toolsMap[binary]; !ok { tm.FullPath, _ = source.URL(tm.Path) matchingTools = append(matchingTools, tm) } } return matchingTools, nil }
go
func appendMatchingTools(source simplestreams.DataSource, matchingTools []interface{}, tools map[string]interface{}, cons simplestreams.LookupConstraint) ([]interface{}, error) { toolsMap := make(map[version.Binary]*ToolsMetadata, len(matchingTools)) for _, val := range matchingTools { tm := val.(*ToolsMetadata) binary, err := tm.binary() if err != nil { return nil, errors.Trace(err) } toolsMap[binary] = tm } for _, val := range tools { tm := val.(*ToolsMetadata) if !set.NewStrings(cons.Params().Series...).Contains(tm.Release) { continue } if toolsConstraint, ok := cons.(*ToolsConstraint); ok { tmNumber := version.MustParse(tm.Version) if toolsConstraint.Version == version.Zero { if toolsConstraint.MajorVersion >= 0 && toolsConstraint.MajorVersion != tmNumber.Major { continue } if toolsConstraint.MinorVersion >= 0 && toolsConstraint.MinorVersion != tmNumber.Minor { continue } } else { if toolsConstraint.Version != tmNumber { continue } } } binary, err := tm.binary() if err != nil { return nil, errors.Trace(err) } if _, ok := toolsMap[binary]; !ok { tm.FullPath, _ = source.URL(tm.Path) matchingTools = append(matchingTools, tm) } } return matchingTools, nil }
[ "func", "appendMatchingTools", "(", "source", "simplestreams", ".", "DataSource", ",", "matchingTools", "[", "]", "interface", "{", "}", ",", "tools", "map", "[", "string", "]", "interface", "{", "}", ",", "cons", "simplestreams", ".", "LookupConstraint", ")", "(", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "toolsMap", ":=", "make", "(", "map", "[", "version", ".", "Binary", "]", "*", "ToolsMetadata", ",", "len", "(", "matchingTools", ")", ")", "\n", "for", "_", ",", "val", ":=", "range", "matchingTools", "{", "tm", ":=", "val", ".", "(", "*", "ToolsMetadata", ")", "\n", "binary", ",", "err", ":=", "tm", ".", "binary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "toolsMap", "[", "binary", "]", "=", "tm", "\n", "}", "\n", "for", "_", ",", "val", ":=", "range", "tools", "{", "tm", ":=", "val", ".", "(", "*", "ToolsMetadata", ")", "\n", "if", "!", "set", ".", "NewStrings", "(", "cons", ".", "Params", "(", ")", ".", "Series", "...", ")", ".", "Contains", "(", "tm", ".", "Release", ")", "{", "continue", "\n", "}", "\n", "if", "toolsConstraint", ",", "ok", ":=", "cons", ".", "(", "*", "ToolsConstraint", ")", ";", "ok", "{", "tmNumber", ":=", "version", ".", "MustParse", "(", "tm", ".", "Version", ")", "\n", "if", "toolsConstraint", ".", "Version", "==", "version", ".", "Zero", "{", "if", "toolsConstraint", ".", "MajorVersion", ">=", "0", "&&", "toolsConstraint", ".", "MajorVersion", "!=", "tmNumber", ".", "Major", "{", "continue", "\n", "}", "\n", "if", "toolsConstraint", ".", "MinorVersion", ">=", "0", "&&", "toolsConstraint", ".", "MinorVersion", "!=", "tmNumber", ".", "Minor", "{", "continue", "\n", "}", "\n", "}", "else", "{", "if", "toolsConstraint", ".", "Version", "!=", "tmNumber", "{", "continue", "\n", "}", "\n", "}", "\n", "}", "\n", "binary", ",", "err", ":=", "tm", ".", "binary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "toolsMap", "[", "binary", "]", ";", "!", "ok", "{", "tm", ".", "FullPath", ",", "_", "=", "source", ".", "URL", "(", "tm", ".", "Path", ")", "\n", "matchingTools", "=", "append", "(", "matchingTools", ",", "tm", ")", "\n", "}", "\n", "}", "\n", "return", "matchingTools", ",", "nil", "\n", "}" ]
// appendMatchingTools updates matchingTools with tools metadata records from tools which belong to the // specified series. If a tools record already exists in matchingTools, it is not overwritten.
[ "appendMatchingTools", "updates", "matchingTools", "with", "tools", "metadata", "records", "from", "tools", "which", "belong", "to", "the", "specified", "series", ".", "If", "a", "tools", "record", "already", "exists", "in", "matchingTools", "it", "is", "not", "overwritten", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L204-L246
156,387
juju/juju
environs/tools/simplestreams.go
MetadataFromTools
func MetadataFromTools(toolsList coretools.List, toolsDir string) []*ToolsMetadata { metadata := make([]*ToolsMetadata, len(toolsList)) for i, t := range toolsList { path := fmt.Sprintf("%s/juju-%s-%s-%s.tgz", toolsDir, t.Version.Number, t.Version.Series, t.Version.Arch) metadata[i] = &ToolsMetadata{ Release: t.Version.Series, Version: t.Version.Number.String(), Arch: t.Version.Arch, Path: path, FileType: "tar.gz", Size: t.Size, SHA256: t.SHA256, } } return metadata }
go
func MetadataFromTools(toolsList coretools.List, toolsDir string) []*ToolsMetadata { metadata := make([]*ToolsMetadata, len(toolsList)) for i, t := range toolsList { path := fmt.Sprintf("%s/juju-%s-%s-%s.tgz", toolsDir, t.Version.Number, t.Version.Series, t.Version.Arch) metadata[i] = &ToolsMetadata{ Release: t.Version.Series, Version: t.Version.Number.String(), Arch: t.Version.Arch, Path: path, FileType: "tar.gz", Size: t.Size, SHA256: t.SHA256, } } return metadata }
[ "func", "MetadataFromTools", "(", "toolsList", "coretools", ".", "List", ",", "toolsDir", "string", ")", "[", "]", "*", "ToolsMetadata", "{", "metadata", ":=", "make", "(", "[", "]", "*", "ToolsMetadata", ",", "len", "(", "toolsList", ")", ")", "\n", "for", "i", ",", "t", ":=", "range", "toolsList", "{", "path", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "toolsDir", ",", "t", ".", "Version", ".", "Number", ",", "t", ".", "Version", ".", "Series", ",", "t", ".", "Version", ".", "Arch", ")", "\n", "metadata", "[", "i", "]", "=", "&", "ToolsMetadata", "{", "Release", ":", "t", ".", "Version", ".", "Series", ",", "Version", ":", "t", ".", "Version", ".", "Number", ".", "String", "(", ")", ",", "Arch", ":", "t", ".", "Version", ".", "Arch", ",", "Path", ":", "path", ",", "FileType", ":", "\"", "\"", ",", "Size", ":", "t", ".", "Size", ",", "SHA256", ":", "t", ".", "SHA256", ",", "}", "\n", "}", "\n", "return", "metadata", "\n", "}" ]
// MetadataFromTools returns a tools metadata list derived from the // given tools list. The size and sha256 will not be computed if // missing.
[ "MetadataFromTools", "returns", "a", "tools", "metadata", "list", "derived", "from", "the", "given", "tools", "list", ".", "The", "size", "and", "sha256", "will", "not", "be", "computed", "if", "missing", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L256-L271
156,388
juju/juju
environs/tools/simplestreams.go
ResolveMetadata
func ResolveMetadata(stor storage.StorageReader, toolsDir string, metadata []*ToolsMetadata) error { for _, md := range metadata { if md.Size != 0 { continue } binary, err := md.binary() if err != nil { return errors.Annotate(err, "cannot resolve metadata") } logger.Infof("Fetching agent binaries from dir %q to generate hash: %v", toolsDir, binary) size, sha256hash, err := fetchToolsHash(stor, toolsDir, binary) // Older versions of Juju only know about ppc64, not ppc64el, // so if there's no metadata for ppc64, dd metadata for that arch. if errors.IsNotFound(err) && binary.Arch == arch.LEGACY_PPC64 { ppc64elBinary := binary ppc64elBinary.Arch = arch.PPC64EL md.Path = strings.Replace(md.Path, binary.Arch, ppc64elBinary.Arch, -1) size, sha256hash, err = fetchToolsHash(stor, toolsDir, ppc64elBinary) } if err != nil { return err } md.Size = size md.SHA256 = fmt.Sprintf("%x", sha256hash.Sum(nil)) } return nil }
go
func ResolveMetadata(stor storage.StorageReader, toolsDir string, metadata []*ToolsMetadata) error { for _, md := range metadata { if md.Size != 0 { continue } binary, err := md.binary() if err != nil { return errors.Annotate(err, "cannot resolve metadata") } logger.Infof("Fetching agent binaries from dir %q to generate hash: %v", toolsDir, binary) size, sha256hash, err := fetchToolsHash(stor, toolsDir, binary) // Older versions of Juju only know about ppc64, not ppc64el, // so if there's no metadata for ppc64, dd metadata for that arch. if errors.IsNotFound(err) && binary.Arch == arch.LEGACY_PPC64 { ppc64elBinary := binary ppc64elBinary.Arch = arch.PPC64EL md.Path = strings.Replace(md.Path, binary.Arch, ppc64elBinary.Arch, -1) size, sha256hash, err = fetchToolsHash(stor, toolsDir, ppc64elBinary) } if err != nil { return err } md.Size = size md.SHA256 = fmt.Sprintf("%x", sha256hash.Sum(nil)) } return nil }
[ "func", "ResolveMetadata", "(", "stor", "storage", ".", "StorageReader", ",", "toolsDir", "string", ",", "metadata", "[", "]", "*", "ToolsMetadata", ")", "error", "{", "for", "_", ",", "md", ":=", "range", "metadata", "{", "if", "md", ".", "Size", "!=", "0", "{", "continue", "\n", "}", "\n", "binary", ",", "err", ":=", "md", ".", "binary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "toolsDir", ",", "binary", ")", "\n", "size", ",", "sha256hash", ",", "err", ":=", "fetchToolsHash", "(", "stor", ",", "toolsDir", ",", "binary", ")", "\n", "// Older versions of Juju only know about ppc64, not ppc64el,", "// so if there's no metadata for ppc64, dd metadata for that arch.", "if", "errors", ".", "IsNotFound", "(", "err", ")", "&&", "binary", ".", "Arch", "==", "arch", ".", "LEGACY_PPC64", "{", "ppc64elBinary", ":=", "binary", "\n", "ppc64elBinary", ".", "Arch", "=", "arch", ".", "PPC64EL", "\n", "md", ".", "Path", "=", "strings", ".", "Replace", "(", "md", ".", "Path", ",", "binary", ".", "Arch", ",", "ppc64elBinary", ".", "Arch", ",", "-", "1", ")", "\n", "size", ",", "sha256hash", ",", "err", "=", "fetchToolsHash", "(", "stor", ",", "toolsDir", ",", "ppc64elBinary", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "md", ".", "Size", "=", "size", "\n", "md", ".", "SHA256", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "sha256hash", ".", "Sum", "(", "nil", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ResolveMetadata resolves incomplete metadata // by fetching the tools from storage and computing // the size and hash locally.
[ "ResolveMetadata", "resolves", "incomplete", "metadata", "by", "fetching", "the", "tools", "from", "storage", "and", "computing", "the", "size", "and", "hash", "locally", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L276-L302
156,389
juju/juju
environs/tools/simplestreams.go
ReadMetadata
func ReadMetadata(store storage.StorageReader, stream string) ([]*ToolsMetadata, error) { dataSource := storage.NewStorageSimpleStreamsDataSource("existing metadata", store, storage.BaseToolsPath, simplestreams.EXISTING_CLOUD_DATA, false) toolsConstraint, err := makeToolsConstraint(simplestreams.CloudSpec{}, stream, -1, -1, coretools.Filter{}) if err != nil { return nil, err } metadata, _, err := Fetch([]simplestreams.DataSource{dataSource}, toolsConstraint) if err != nil && !errors.IsNotFound(err) { return nil, err } return metadata, nil }
go
func ReadMetadata(store storage.StorageReader, stream string) ([]*ToolsMetadata, error) { dataSource := storage.NewStorageSimpleStreamsDataSource("existing metadata", store, storage.BaseToolsPath, simplestreams.EXISTING_CLOUD_DATA, false) toolsConstraint, err := makeToolsConstraint(simplestreams.CloudSpec{}, stream, -1, -1, coretools.Filter{}) if err != nil { return nil, err } metadata, _, err := Fetch([]simplestreams.DataSource{dataSource}, toolsConstraint) if err != nil && !errors.IsNotFound(err) { return nil, err } return metadata, nil }
[ "func", "ReadMetadata", "(", "store", "storage", ".", "StorageReader", ",", "stream", "string", ")", "(", "[", "]", "*", "ToolsMetadata", ",", "error", ")", "{", "dataSource", ":=", "storage", ".", "NewStorageSimpleStreamsDataSource", "(", "\"", "\"", ",", "store", ",", "storage", ".", "BaseToolsPath", ",", "simplestreams", ".", "EXISTING_CLOUD_DATA", ",", "false", ")", "\n", "toolsConstraint", ",", "err", ":=", "makeToolsConstraint", "(", "simplestreams", ".", "CloudSpec", "{", "}", ",", "stream", ",", "-", "1", ",", "-", "1", ",", "coretools", ".", "Filter", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "metadata", ",", "_", ",", "err", ":=", "Fetch", "(", "[", "]", "simplestreams", ".", "DataSource", "{", "dataSource", "}", ",", "toolsConstraint", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "metadata", ",", "nil", "\n", "}" ]
// ReadMetadata returns the tools metadata from the given storage for the specified stream.
[ "ReadMetadata", "returns", "the", "tools", "metadata", "from", "the", "given", "storage", "for", "the", "specified", "stream", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L349-L360
156,390
juju/juju
environs/tools/simplestreams.go
ReadAllMetadata
func ReadAllMetadata(store storage.StorageReader) (map[string][]*ToolsMetadata, error) { streamMetadata := make(map[string][]*ToolsMetadata) for _, stream := range AllMetadataStreams { metadata, err := ReadMetadata(store, stream) if err != nil { return nil, err } if len(metadata) == 0 { continue } streamMetadata[stream] = metadata } return streamMetadata, nil }
go
func ReadAllMetadata(store storage.StorageReader) (map[string][]*ToolsMetadata, error) { streamMetadata := make(map[string][]*ToolsMetadata) for _, stream := range AllMetadataStreams { metadata, err := ReadMetadata(store, stream) if err != nil { return nil, err } if len(metadata) == 0 { continue } streamMetadata[stream] = metadata } return streamMetadata, nil }
[ "func", "ReadAllMetadata", "(", "store", "storage", ".", "StorageReader", ")", "(", "map", "[", "string", "]", "[", "]", "*", "ToolsMetadata", ",", "error", ")", "{", "streamMetadata", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "ToolsMetadata", ")", "\n", "for", "_", ",", "stream", ":=", "range", "AllMetadataStreams", "{", "metadata", ",", "err", ":=", "ReadMetadata", "(", "store", ",", "stream", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "metadata", ")", "==", "0", "{", "continue", "\n", "}", "\n", "streamMetadata", "[", "stream", "]", "=", "metadata", "\n", "}", "\n", "return", "streamMetadata", ",", "nil", "\n", "}" ]
// ReadAllMetadata returns the tools metadata from the given storage for all streams. // The result is a map of metadata slices, keyed on stream.
[ "ReadAllMetadata", "returns", "the", "tools", "metadata", "from", "the", "given", "storage", "for", "all", "streams", ".", "The", "result", "is", "a", "map", "of", "metadata", "slices", "keyed", "on", "stream", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L367-L380
156,391
juju/juju
environs/tools/simplestreams.go
removeMetadataUpdated
func removeMetadataUpdated(metadataBytes []byte) (string, error) { var metadata map[string]interface{} err := json.Unmarshal(metadataBytes, &metadata) if err != nil { return "", err } delete(metadata, "updated") metadataJson, err := json.Marshal(metadata) if err != nil { return "", err } return string(metadataJson), nil }
go
func removeMetadataUpdated(metadataBytes []byte) (string, error) { var metadata map[string]interface{} err := json.Unmarshal(metadataBytes, &metadata) if err != nil { return "", err } delete(metadata, "updated") metadataJson, err := json.Marshal(metadata) if err != nil { return "", err } return string(metadataJson), nil }
[ "func", "removeMetadataUpdated", "(", "metadataBytes", "[", "]", "byte", ")", "(", "string", ",", "error", ")", "{", "var", "metadata", "map", "[", "string", "]", "interface", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "metadataBytes", ",", "&", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "delete", "(", "metadata", ",", "\"", "\"", ")", "\n\n", "metadataJson", ",", "err", ":=", "json", ".", "Marshal", "(", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "string", "(", "metadataJson", ")", ",", "nil", "\n", "}" ]
// removeMetadataUpdated unmarshalls simplestreams metadata, clears the // updated attribute, and then marshalls back to a string.
[ "removeMetadataUpdated", "unmarshalls", "simplestreams", "metadata", "clears", "the", "updated", "attribute", "and", "then", "marshalls", "back", "to", "a", "string", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L384-L397
156,392
juju/juju
environs/tools/simplestreams.go
metadataUnchanged
func metadataUnchanged(stor storage.Storage, stream string, generatedMetadata []byte) (bool, error) { mdPath := ProductMetadataPath(stream) filePath := path.Join(storage.BaseToolsPath, mdPath) existingDataReader, err := stor.Get(filePath) // If the file can't be retrieved, consider it has changed. if err != nil { return false, nil } defer existingDataReader.Close() existingData, err := ioutil.ReadAll(existingDataReader) if err != nil { return false, err } // To do the comparison, we unmarshall the metadata, clear the // updated value, and marshall back to a string. existingMetadata, err := removeMetadataUpdated(existingData) if err != nil { return false, err } newMetadata, err := removeMetadataUpdated(generatedMetadata) if err != nil { return false, err } return existingMetadata == newMetadata, nil }
go
func metadataUnchanged(stor storage.Storage, stream string, generatedMetadata []byte) (bool, error) { mdPath := ProductMetadataPath(stream) filePath := path.Join(storage.BaseToolsPath, mdPath) existingDataReader, err := stor.Get(filePath) // If the file can't be retrieved, consider it has changed. if err != nil { return false, nil } defer existingDataReader.Close() existingData, err := ioutil.ReadAll(existingDataReader) if err != nil { return false, err } // To do the comparison, we unmarshall the metadata, clear the // updated value, and marshall back to a string. existingMetadata, err := removeMetadataUpdated(existingData) if err != nil { return false, err } newMetadata, err := removeMetadataUpdated(generatedMetadata) if err != nil { return false, err } return existingMetadata == newMetadata, nil }
[ "func", "metadataUnchanged", "(", "stor", "storage", ".", "Storage", ",", "stream", "string", ",", "generatedMetadata", "[", "]", "byte", ")", "(", "bool", ",", "error", ")", "{", "mdPath", ":=", "ProductMetadataPath", "(", "stream", ")", "\n", "filePath", ":=", "path", ".", "Join", "(", "storage", ".", "BaseToolsPath", ",", "mdPath", ")", "\n", "existingDataReader", ",", "err", ":=", "stor", ".", "Get", "(", "filePath", ")", "\n", "// If the file can't be retrieved, consider it has changed.", "if", "err", "!=", "nil", "{", "return", "false", ",", "nil", "\n", "}", "\n", "defer", "existingDataReader", ".", "Close", "(", ")", "\n", "existingData", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "existingDataReader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "// To do the comparison, we unmarshall the metadata, clear the", "// updated value, and marshall back to a string.", "existingMetadata", ",", "err", ":=", "removeMetadataUpdated", "(", "existingData", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "newMetadata", ",", "err", ":=", "removeMetadataUpdated", "(", "generatedMetadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "existingMetadata", "==", "newMetadata", ",", "nil", "\n", "}" ]
// metadataUnchanged returns true if the content of metadata for stream in stor is the same // as generatedMetadata, ignoring the "updated" attribute.
[ "metadataUnchanged", "returns", "true", "if", "the", "content", "of", "metadata", "for", "stream", "in", "stor", "is", "the", "same", "as", "generatedMetadata", "ignoring", "the", "updated", "attribute", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L401-L426
156,393
juju/juju
environs/tools/simplestreams.go
WriteMetadata
func WriteMetadata(stor storage.Storage, streamMetadata map[string][]*ToolsMetadata, streams []string, writeMirrors ShouldWriteMirrors) error { // TODO(perrito666) 2016-05-02 lp:1558657 updated := time.Now() index, legacyIndex, products, err := MarshalToolsMetadataJSON(streamMetadata, updated) if err != nil { return err } metadataInfo := []MetadataFile{ {simplestreams.UnsignedIndex(currentStreamsVersion, IndexFileVersion), index}, } if legacyIndex != nil { metadataInfo = append(metadataInfo, MetadataFile{ simplestreams.UnsignedIndex(currentStreamsVersion, 1), legacyIndex, }) } for _, stream := range streams { if metadata, ok := products[stream]; ok { // If metadata hasn't changed, do not overwrite. unchanged, err := metadataUnchanged(stor, stream, metadata) if err != nil { return err } if unchanged { logger.Infof("Metadata for stream %q unchanged", stream) continue } // Metadata is different, so include it. metadataInfo = append(metadataInfo, MetadataFile{ProductMetadataPath(stream), metadata}) } } if writeMirrors { streamsMirrorsMetadata := make(map[string][]simplestreams.MirrorReference) for stream := range streamMetadata { streamsMirrorsMetadata[ToolsContentId(stream)] = []simplestreams.MirrorReference{{ Updated: updated.Format("20060102"), // YYYYMMDD DataType: ContentDownload, Format: simplestreams.MirrorFormat, Path: simplestreams.MirrorFile, }} } mirrorsMetadata := map[string]map[string][]simplestreams.MirrorReference{ "mirrors": streamsMirrorsMetadata, } mirrorsInfo, err := json.MarshalIndent(&mirrorsMetadata, "", " ") if err != nil { return err } metadataInfo = append( metadataInfo, MetadataFile{simplestreams.UnsignedMirror(currentStreamsVersion), mirrorsInfo}) } return writeMetadataFiles(stor, metadataInfo) }
go
func WriteMetadata(stor storage.Storage, streamMetadata map[string][]*ToolsMetadata, streams []string, writeMirrors ShouldWriteMirrors) error { // TODO(perrito666) 2016-05-02 lp:1558657 updated := time.Now() index, legacyIndex, products, err := MarshalToolsMetadataJSON(streamMetadata, updated) if err != nil { return err } metadataInfo := []MetadataFile{ {simplestreams.UnsignedIndex(currentStreamsVersion, IndexFileVersion), index}, } if legacyIndex != nil { metadataInfo = append(metadataInfo, MetadataFile{ simplestreams.UnsignedIndex(currentStreamsVersion, 1), legacyIndex, }) } for _, stream := range streams { if metadata, ok := products[stream]; ok { // If metadata hasn't changed, do not overwrite. unchanged, err := metadataUnchanged(stor, stream, metadata) if err != nil { return err } if unchanged { logger.Infof("Metadata for stream %q unchanged", stream) continue } // Metadata is different, so include it. metadataInfo = append(metadataInfo, MetadataFile{ProductMetadataPath(stream), metadata}) } } if writeMirrors { streamsMirrorsMetadata := make(map[string][]simplestreams.MirrorReference) for stream := range streamMetadata { streamsMirrorsMetadata[ToolsContentId(stream)] = []simplestreams.MirrorReference{{ Updated: updated.Format("20060102"), // YYYYMMDD DataType: ContentDownload, Format: simplestreams.MirrorFormat, Path: simplestreams.MirrorFile, }} } mirrorsMetadata := map[string]map[string][]simplestreams.MirrorReference{ "mirrors": streamsMirrorsMetadata, } mirrorsInfo, err := json.MarshalIndent(&mirrorsMetadata, "", " ") if err != nil { return err } metadataInfo = append( metadataInfo, MetadataFile{simplestreams.UnsignedMirror(currentStreamsVersion), mirrorsInfo}) } return writeMetadataFiles(stor, metadataInfo) }
[ "func", "WriteMetadata", "(", "stor", "storage", ".", "Storage", ",", "streamMetadata", "map", "[", "string", "]", "[", "]", "*", "ToolsMetadata", ",", "streams", "[", "]", "string", ",", "writeMirrors", "ShouldWriteMirrors", ")", "error", "{", "// TODO(perrito666) 2016-05-02 lp:1558657", "updated", ":=", "time", ".", "Now", "(", ")", "\n", "index", ",", "legacyIndex", ",", "products", ",", "err", ":=", "MarshalToolsMetadataJSON", "(", "streamMetadata", ",", "updated", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "metadataInfo", ":=", "[", "]", "MetadataFile", "{", "{", "simplestreams", ".", "UnsignedIndex", "(", "currentStreamsVersion", ",", "IndexFileVersion", ")", ",", "index", "}", ",", "}", "\n", "if", "legacyIndex", "!=", "nil", "{", "metadataInfo", "=", "append", "(", "metadataInfo", ",", "MetadataFile", "{", "simplestreams", ".", "UnsignedIndex", "(", "currentStreamsVersion", ",", "1", ")", ",", "legacyIndex", ",", "}", ")", "\n", "}", "\n", "for", "_", ",", "stream", ":=", "range", "streams", "{", "if", "metadata", ",", "ok", ":=", "products", "[", "stream", "]", ";", "ok", "{", "// If metadata hasn't changed, do not overwrite.", "unchanged", ",", "err", ":=", "metadataUnchanged", "(", "stor", ",", "stream", ",", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "unchanged", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "stream", ")", "\n", "continue", "\n", "}", "\n", "// Metadata is different, so include it.", "metadataInfo", "=", "append", "(", "metadataInfo", ",", "MetadataFile", "{", "ProductMetadataPath", "(", "stream", ")", ",", "metadata", "}", ")", "\n", "}", "\n", "}", "\n", "if", "writeMirrors", "{", "streamsMirrorsMetadata", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "simplestreams", ".", "MirrorReference", ")", "\n", "for", "stream", ":=", "range", "streamMetadata", "{", "streamsMirrorsMetadata", "[", "ToolsContentId", "(", "stream", ")", "]", "=", "[", "]", "simplestreams", ".", "MirrorReference", "{", "{", "Updated", ":", "updated", ".", "Format", "(", "\"", "\"", ")", ",", "// YYYYMMDD", "DataType", ":", "ContentDownload", ",", "Format", ":", "simplestreams", ".", "MirrorFormat", ",", "Path", ":", "simplestreams", ".", "MirrorFile", ",", "}", "}", "\n", "}", "\n", "mirrorsMetadata", ":=", "map", "[", "string", "]", "map", "[", "string", "]", "[", "]", "simplestreams", ".", "MirrorReference", "{", "\"", "\"", ":", "streamsMirrorsMetadata", ",", "}", "\n", "mirrorsInfo", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "&", "mirrorsMetadata", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "metadataInfo", "=", "append", "(", "metadataInfo", ",", "MetadataFile", "{", "simplestreams", ".", "UnsignedMirror", "(", "currentStreamsVersion", ")", ",", "mirrorsInfo", "}", ")", "\n", "}", "\n", "return", "writeMetadataFiles", "(", "stor", ",", "metadataInfo", ")", "\n", "}" ]
// WriteMetadata writes the given tools metadata for the specified streams to the given storage. // streamMetadata contains all known metadata so that the correct index files can be written. // Only product files for the specified streams are written.
[ "WriteMetadata", "writes", "the", "given", "tools", "metadata", "for", "the", "specified", "streams", "to", "the", "given", "storage", ".", "streamMetadata", "contains", "all", "known", "metadata", "so", "that", "the", "correct", "index", "files", "can", "be", "written", ".", "Only", "product", "files", "for", "the", "specified", "streams", "are", "written", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L431-L482
156,394
juju/juju
environs/tools/simplestreams.go
fetchToolsHash
func fetchToolsHash(stor storage.StorageReader, stream string, ver version.Binary) (size int64, sha256hash hash.Hash, err error) { r, err := storage.Get(stor, StorageName(ver, stream)) if err != nil { return 0, nil, err } defer r.Close() sha256hash = sha256.New() size, err = io.Copy(sha256hash, r) return size, sha256hash, err }
go
func fetchToolsHash(stor storage.StorageReader, stream string, ver version.Binary) (size int64, sha256hash hash.Hash, err error) { r, err := storage.Get(stor, StorageName(ver, stream)) if err != nil { return 0, nil, err } defer r.Close() sha256hash = sha256.New() size, err = io.Copy(sha256hash, r) return size, sha256hash, err }
[ "func", "fetchToolsHash", "(", "stor", "storage", ".", "StorageReader", ",", "stream", "string", ",", "ver", "version", ".", "Binary", ")", "(", "size", "int64", ",", "sha256hash", "hash", ".", "Hash", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "storage", ".", "Get", "(", "stor", ",", "StorageName", "(", "ver", ",", "stream", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n", "defer", "r", ".", "Close", "(", ")", "\n", "sha256hash", "=", "sha256", ".", "New", "(", ")", "\n", "size", ",", "err", "=", "io", ".", "Copy", "(", "sha256hash", ",", "r", ")", "\n", "return", "size", ",", "sha256hash", ",", "err", "\n", "}" ]
// fetchToolsHash fetches the tools from storage and calculates // its size in bytes and computes a SHA256 hash of its contents.
[ "fetchToolsHash", "fetches", "the", "tools", "from", "storage", "and", "calculates", "its", "size", "in", "bytes", "and", "computes", "a", "SHA256", "hash", "of", "its", "contents", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/simplestreams.go#L521-L530
156,395
juju/juju
worker/uniter/runner/context/action.go
NewActionData
func NewActionData(name string, tag *names.ActionTag, params map[string]interface{}) *ActionData { return &ActionData{ Name: name, Tag: *tag, Params: params, ResultsMap: map[string]interface{}{}, } }
go
func NewActionData(name string, tag *names.ActionTag, params map[string]interface{}) *ActionData { return &ActionData{ Name: name, Tag: *tag, Params: params, ResultsMap: map[string]interface{}{}, } }
[ "func", "NewActionData", "(", "name", "string", ",", "tag", "*", "names", ".", "ActionTag", ",", "params", "map", "[", "string", "]", "interface", "{", "}", ")", "*", "ActionData", "{", "return", "&", "ActionData", "{", "Name", ":", "name", ",", "Tag", ":", "*", "tag", ",", "Params", ":", "params", ",", "ResultsMap", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "}", ",", "}", "\n", "}" ]
// NewActionData builds a suitable ActionData struct with no nil members. // this should only be called in the event that an Action hook is being requested.
[ "NewActionData", "builds", "a", "suitable", "ActionData", "struct", "with", "no", "nil", "members", ".", "this", "should", "only", "be", "called", "in", "the", "event", "that", "an", "Action", "hook", "is", "being", "requested", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/context/action.go#L22-L29
156,396
juju/juju
container/kvm/run_linux.go
runAsLibvirt
func runAsLibvirt(dir, command string, args ...string) (string, error) { uid, gid, err := getUserUIDGID(libvirtUser) if err != nil { return "", errors.Trace(err) } cmd := exec.Command(command, args...) if dir != "" { cmd.Dir = dir } if dir == "" { dir, _ = os.Getwd() } logger.Debugf("running: %s %v from %s", command, args, dir) logger.Debugf("running as uid: %d, gid: %d\n", uid, gid) cmd.SysProcAttr = &syscall.SysProcAttr{} cmd.SysProcAttr.Credential = &syscall.Credential{ Uid: uint32(uid), Gid: uint32(gid), } out, err := cmd.CombinedOutput() output := string(out) logger.Debugf("output: %v", output) return output, err }
go
func runAsLibvirt(dir, command string, args ...string) (string, error) { uid, gid, err := getUserUIDGID(libvirtUser) if err != nil { return "", errors.Trace(err) } cmd := exec.Command(command, args...) if dir != "" { cmd.Dir = dir } if dir == "" { dir, _ = os.Getwd() } logger.Debugf("running: %s %v from %s", command, args, dir) logger.Debugf("running as uid: %d, gid: %d\n", uid, gid) cmd.SysProcAttr = &syscall.SysProcAttr{} cmd.SysProcAttr.Credential = &syscall.Credential{ Uid: uint32(uid), Gid: uint32(gid), } out, err := cmd.CombinedOutput() output := string(out) logger.Debugf("output: %v", output) return output, err }
[ "func", "runAsLibvirt", "(", "dir", ",", "command", "string", ",", "args", "...", "string", ")", "(", "string", ",", "error", ")", "{", "uid", ",", "gid", ",", "err", ":=", "getUserUIDGID", "(", "libvirtUser", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "cmd", ":=", "exec", ".", "Command", "(", "command", ",", "args", "...", ")", "\n", "if", "dir", "!=", "\"", "\"", "{", "cmd", ".", "Dir", "=", "dir", "\n", "}", "\n\n", "if", "dir", "==", "\"", "\"", "{", "dir", ",", "_", "=", "os", ".", "Getwd", "(", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "command", ",", "args", ",", "dir", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\\n", "\"", ",", "uid", ",", "gid", ")", "\n\n", "cmd", ".", "SysProcAttr", "=", "&", "syscall", ".", "SysProcAttr", "{", "}", "\n", "cmd", ".", "SysProcAttr", ".", "Credential", "=", "&", "syscall", ".", "Credential", "{", "Uid", ":", "uint32", "(", "uid", ")", ",", "Gid", ":", "uint32", "(", "gid", ")", ",", "}", "\n\n", "out", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", "\n", "output", ":=", "string", "(", "out", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "output", ")", "\n\n", "return", "output", ",", "err", "\n\n", "}" ]
// Run the command as user libvirt-qemu and return the combined output. // If dir is non-empty, use it as the working directory.
[ "Run", "the", "command", "as", "user", "libvirt", "-", "qemu", "and", "return", "the", "combined", "output", ".", "If", "dir", "is", "non", "-", "empty", "use", "it", "as", "the", "working", "directory", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/run_linux.go#L20-L49
156,397
juju/juju
cloudconfig/cloudinit/network_ubuntu.go
GenerateNetplan
func GenerateNetplan(interfaces []network.InterfaceInfo) (string, error) { if len(interfaces) == 0 { return "", errors.Errorf("missing container network config") } logger.Debugf("generating netplan from %#v", interfaces) var netPlan netplan.Netplan netPlan.Network.Ethernets = make(map[string]netplan.Ethernet) netPlan.Network.Version = 2 for _, info := range interfaces { var iface netplan.Ethernet if cidr := info.CIDRAddress(); cidr != "" { iface.Addresses = append(iface.Addresses, cidr) } else if info.ConfigType == network.ConfigDHCP { t := true iface.DHCP4 = &t } for _, dns := range info.DNSServers { iface.Nameservers.Addresses = append(iface.Nameservers.Addresses, dns.Value) } iface.Nameservers.Search = append(iface.Nameservers.Search, info.DNSSearchDomains...) if info.GatewayAddress.Value != "" { switch { case info.GatewayAddress.Type == network.IPv4Address: iface.Gateway4 = info.GatewayAddress.Value case info.GatewayAddress.Type == network.IPv6Address: iface.Gateway6 = info.GatewayAddress.Value } } if info.MTU != 0 && info.MTU != 1500 { iface.MTU = info.MTU } if info.MACAddress != "" { iface.Match = map[string]string{"macaddress": info.MACAddress} } else { iface.Match = map[string]string{"name": info.InterfaceName} } for _, route := range info.Routes { route := netplan.Route{ To: route.DestinationCIDR, Via: route.GatewayIP, Metric: &route.Metric, } iface.Routes = append(iface.Routes, route) } netPlan.Network.Ethernets[info.InterfaceName] = iface } out, err := netplan.Marshal(&netPlan) if err != nil { return "", errors.Trace(err) } return string(out), nil }
go
func GenerateNetplan(interfaces []network.InterfaceInfo) (string, error) { if len(interfaces) == 0 { return "", errors.Errorf("missing container network config") } logger.Debugf("generating netplan from %#v", interfaces) var netPlan netplan.Netplan netPlan.Network.Ethernets = make(map[string]netplan.Ethernet) netPlan.Network.Version = 2 for _, info := range interfaces { var iface netplan.Ethernet if cidr := info.CIDRAddress(); cidr != "" { iface.Addresses = append(iface.Addresses, cidr) } else if info.ConfigType == network.ConfigDHCP { t := true iface.DHCP4 = &t } for _, dns := range info.DNSServers { iface.Nameservers.Addresses = append(iface.Nameservers.Addresses, dns.Value) } iface.Nameservers.Search = append(iface.Nameservers.Search, info.DNSSearchDomains...) if info.GatewayAddress.Value != "" { switch { case info.GatewayAddress.Type == network.IPv4Address: iface.Gateway4 = info.GatewayAddress.Value case info.GatewayAddress.Type == network.IPv6Address: iface.Gateway6 = info.GatewayAddress.Value } } if info.MTU != 0 && info.MTU != 1500 { iface.MTU = info.MTU } if info.MACAddress != "" { iface.Match = map[string]string{"macaddress": info.MACAddress} } else { iface.Match = map[string]string{"name": info.InterfaceName} } for _, route := range info.Routes { route := netplan.Route{ To: route.DestinationCIDR, Via: route.GatewayIP, Metric: &route.Metric, } iface.Routes = append(iface.Routes, route) } netPlan.Network.Ethernets[info.InterfaceName] = iface } out, err := netplan.Marshal(&netPlan) if err != nil { return "", errors.Trace(err) } return string(out), nil }
[ "func", "GenerateNetplan", "(", "interfaces", "[", "]", "network", ".", "InterfaceInfo", ")", "(", "string", ",", "error", ")", "{", "if", "len", "(", "interfaces", ")", "==", "0", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "interfaces", ")", "\n", "var", "netPlan", "netplan", ".", "Netplan", "\n", "netPlan", ".", "Network", ".", "Ethernets", "=", "make", "(", "map", "[", "string", "]", "netplan", ".", "Ethernet", ")", "\n", "netPlan", ".", "Network", ".", "Version", "=", "2", "\n", "for", "_", ",", "info", ":=", "range", "interfaces", "{", "var", "iface", "netplan", ".", "Ethernet", "\n", "if", "cidr", ":=", "info", ".", "CIDRAddress", "(", ")", ";", "cidr", "!=", "\"", "\"", "{", "iface", ".", "Addresses", "=", "append", "(", "iface", ".", "Addresses", ",", "cidr", ")", "\n", "}", "else", "if", "info", ".", "ConfigType", "==", "network", ".", "ConfigDHCP", "{", "t", ":=", "true", "\n", "iface", ".", "DHCP4", "=", "&", "t", "\n", "}", "\n\n", "for", "_", ",", "dns", ":=", "range", "info", ".", "DNSServers", "{", "iface", ".", "Nameservers", ".", "Addresses", "=", "append", "(", "iface", ".", "Nameservers", ".", "Addresses", ",", "dns", ".", "Value", ")", "\n", "}", "\n", "iface", ".", "Nameservers", ".", "Search", "=", "append", "(", "iface", ".", "Nameservers", ".", "Search", ",", "info", ".", "DNSSearchDomains", "...", ")", "\n\n", "if", "info", ".", "GatewayAddress", ".", "Value", "!=", "\"", "\"", "{", "switch", "{", "case", "info", ".", "GatewayAddress", ".", "Type", "==", "network", ".", "IPv4Address", ":", "iface", ".", "Gateway4", "=", "info", ".", "GatewayAddress", ".", "Value", "\n", "case", "info", ".", "GatewayAddress", ".", "Type", "==", "network", ".", "IPv6Address", ":", "iface", ".", "Gateway6", "=", "info", ".", "GatewayAddress", ".", "Value", "\n", "}", "\n", "}", "\n\n", "if", "info", ".", "MTU", "!=", "0", "&&", "info", ".", "MTU", "!=", "1500", "{", "iface", ".", "MTU", "=", "info", ".", "MTU", "\n", "}", "\n", "if", "info", ".", "MACAddress", "!=", "\"", "\"", "{", "iface", ".", "Match", "=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "info", ".", "MACAddress", "}", "\n", "}", "else", "{", "iface", ".", "Match", "=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "info", ".", "InterfaceName", "}", "\n", "}", "\n", "for", "_", ",", "route", ":=", "range", "info", ".", "Routes", "{", "route", ":=", "netplan", ".", "Route", "{", "To", ":", "route", ".", "DestinationCIDR", ",", "Via", ":", "route", ".", "GatewayIP", ",", "Metric", ":", "&", "route", ".", "Metric", ",", "}", "\n", "iface", ".", "Routes", "=", "append", "(", "iface", ".", "Routes", ",", "route", ")", "\n", "}", "\n", "netPlan", ".", "Network", ".", "Ethernets", "[", "info", ".", "InterfaceName", "]", "=", "iface", "\n", "}", "\n", "out", ",", "err", ":=", "netplan", ".", "Marshal", "(", "&", "netPlan", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "string", "(", "out", ")", ",", "nil", "\n", "}" ]
// GenerateNetplan renders a netplan file for one or more network // interfaces, using the given non-empty list of interfaces.
[ "GenerateNetplan", "renders", "a", "netplan", "file", "for", "one", "or", "more", "network", "interfaces", "using", "the", "given", "non", "-", "empty", "list", "of", "interfaces", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/cloudinit/network_ubuntu.go#L140-L194
156,398
juju/juju
cloudconfig/cloudinit/network_ubuntu.go
PrepareNetworkConfigFromInterfaces
func PrepareNetworkConfigFromInterfaces(interfaces []network.InterfaceInfo) *PreparedConfig { dnsServers := set.NewStrings() dnsSearchDomains := set.NewStrings() gateway4Address := "" gateway6Address := "" namesInOrder := make([]string, 1, len(interfaces)+1) nameToAddress := make(map[string]string) nameToRoutes := make(map[string][]network.Route) nameToMTU := make(map[string]int) // Always include the loopback. namesInOrder[0] = "lo" autoStarted := set.NewStrings("lo") // We need to check if we have a host-provided default GW and use it. // Otherwise we'll use the first device with a gateway address, // it'll be filled in the second loop. for _, info := range interfaces { if info.IsDefaultGateway { switch info.GatewayAddress.Type { case network.IPv4Address: gateway4Address = info.GatewayAddress.Value case network.IPv6Address: gateway6Address = info.GatewayAddress.Value } } } for _, info := range interfaces { ifaceName := strings.Replace(info.MACAddress, ":", "_", -1) // prepend eth because .format of python wont like a tag starting with numbers. ifaceName = fmt.Sprintf("{eth%s}", ifaceName) if !info.NoAutoStart { autoStarted.Add(ifaceName) } if cidr := info.CIDRAddress(); cidr != "" { nameToAddress[ifaceName] = cidr } else if info.ConfigType == network.ConfigDHCP { nameToAddress[ifaceName] = string(network.ConfigDHCP) } nameToRoutes[ifaceName] = info.Routes for _, dns := range info.DNSServers { dnsServers.Add(dns.Value) } dnsSearchDomains = dnsSearchDomains.Union(set.NewStrings(info.DNSSearchDomains...)) if info.GatewayAddress.Value != "" { switch { case gateway4Address == "" && info.GatewayAddress.Type == network.IPv4Address: gateway4Address = info.GatewayAddress.Value case gateway6Address == "" && info.GatewayAddress.Type == network.IPv6Address: gateway6Address = info.GatewayAddress.Value } } if info.MTU != 0 && info.MTU != 1500 { nameToMTU[ifaceName] = info.MTU } namesInOrder = append(namesInOrder, ifaceName) } prepared := &PreparedConfig{ InterfaceNames: namesInOrder, NameToAddress: nameToAddress, NameToRoutes: nameToRoutes, NameToMTU: nameToMTU, AutoStarted: autoStarted.SortedValues(), DNSServers: dnsServers.SortedValues(), DNSSearchDomains: dnsSearchDomains.SortedValues(), Gateway4Address: gateway4Address, Gateway6Address: gateway6Address, } logger.Debugf("prepared network config for rendering: %+v", prepared) return prepared }
go
func PrepareNetworkConfigFromInterfaces(interfaces []network.InterfaceInfo) *PreparedConfig { dnsServers := set.NewStrings() dnsSearchDomains := set.NewStrings() gateway4Address := "" gateway6Address := "" namesInOrder := make([]string, 1, len(interfaces)+1) nameToAddress := make(map[string]string) nameToRoutes := make(map[string][]network.Route) nameToMTU := make(map[string]int) // Always include the loopback. namesInOrder[0] = "lo" autoStarted := set.NewStrings("lo") // We need to check if we have a host-provided default GW and use it. // Otherwise we'll use the first device with a gateway address, // it'll be filled in the second loop. for _, info := range interfaces { if info.IsDefaultGateway { switch info.GatewayAddress.Type { case network.IPv4Address: gateway4Address = info.GatewayAddress.Value case network.IPv6Address: gateway6Address = info.GatewayAddress.Value } } } for _, info := range interfaces { ifaceName := strings.Replace(info.MACAddress, ":", "_", -1) // prepend eth because .format of python wont like a tag starting with numbers. ifaceName = fmt.Sprintf("{eth%s}", ifaceName) if !info.NoAutoStart { autoStarted.Add(ifaceName) } if cidr := info.CIDRAddress(); cidr != "" { nameToAddress[ifaceName] = cidr } else if info.ConfigType == network.ConfigDHCP { nameToAddress[ifaceName] = string(network.ConfigDHCP) } nameToRoutes[ifaceName] = info.Routes for _, dns := range info.DNSServers { dnsServers.Add(dns.Value) } dnsSearchDomains = dnsSearchDomains.Union(set.NewStrings(info.DNSSearchDomains...)) if info.GatewayAddress.Value != "" { switch { case gateway4Address == "" && info.GatewayAddress.Type == network.IPv4Address: gateway4Address = info.GatewayAddress.Value case gateway6Address == "" && info.GatewayAddress.Type == network.IPv6Address: gateway6Address = info.GatewayAddress.Value } } if info.MTU != 0 && info.MTU != 1500 { nameToMTU[ifaceName] = info.MTU } namesInOrder = append(namesInOrder, ifaceName) } prepared := &PreparedConfig{ InterfaceNames: namesInOrder, NameToAddress: nameToAddress, NameToRoutes: nameToRoutes, NameToMTU: nameToMTU, AutoStarted: autoStarted.SortedValues(), DNSServers: dnsServers.SortedValues(), DNSSearchDomains: dnsSearchDomains.SortedValues(), Gateway4Address: gateway4Address, Gateway6Address: gateway6Address, } logger.Debugf("prepared network config for rendering: %+v", prepared) return prepared }
[ "func", "PrepareNetworkConfigFromInterfaces", "(", "interfaces", "[", "]", "network", ".", "InterfaceInfo", ")", "*", "PreparedConfig", "{", "dnsServers", ":=", "set", ".", "NewStrings", "(", ")", "\n", "dnsSearchDomains", ":=", "set", ".", "NewStrings", "(", ")", "\n", "gateway4Address", ":=", "\"", "\"", "\n", "gateway6Address", ":=", "\"", "\"", "\n", "namesInOrder", ":=", "make", "(", "[", "]", "string", ",", "1", ",", "len", "(", "interfaces", ")", "+", "1", ")", "\n", "nameToAddress", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "nameToRoutes", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "network", ".", "Route", ")", "\n", "nameToMTU", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n\n", "// Always include the loopback.", "namesInOrder", "[", "0", "]", "=", "\"", "\"", "\n", "autoStarted", ":=", "set", ".", "NewStrings", "(", "\"", "\"", ")", "\n\n", "// We need to check if we have a host-provided default GW and use it.", "// Otherwise we'll use the first device with a gateway address,", "// it'll be filled in the second loop.", "for", "_", ",", "info", ":=", "range", "interfaces", "{", "if", "info", ".", "IsDefaultGateway", "{", "switch", "info", ".", "GatewayAddress", ".", "Type", "{", "case", "network", ".", "IPv4Address", ":", "gateway4Address", "=", "info", ".", "GatewayAddress", ".", "Value", "\n", "case", "network", ".", "IPv6Address", ":", "gateway6Address", "=", "info", ".", "GatewayAddress", ".", "Value", "\n", "}", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "info", ":=", "range", "interfaces", "{", "ifaceName", ":=", "strings", ".", "Replace", "(", "info", ".", "MACAddress", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "// prepend eth because .format of python wont like a tag starting with numbers.", "ifaceName", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ifaceName", ")", "\n\n", "if", "!", "info", ".", "NoAutoStart", "{", "autoStarted", ".", "Add", "(", "ifaceName", ")", "\n", "}", "\n\n", "if", "cidr", ":=", "info", ".", "CIDRAddress", "(", ")", ";", "cidr", "!=", "\"", "\"", "{", "nameToAddress", "[", "ifaceName", "]", "=", "cidr", "\n", "}", "else", "if", "info", ".", "ConfigType", "==", "network", ".", "ConfigDHCP", "{", "nameToAddress", "[", "ifaceName", "]", "=", "string", "(", "network", ".", "ConfigDHCP", ")", "\n", "}", "\n", "nameToRoutes", "[", "ifaceName", "]", "=", "info", ".", "Routes", "\n\n", "for", "_", ",", "dns", ":=", "range", "info", ".", "DNSServers", "{", "dnsServers", ".", "Add", "(", "dns", ".", "Value", ")", "\n", "}", "\n\n", "dnsSearchDomains", "=", "dnsSearchDomains", ".", "Union", "(", "set", ".", "NewStrings", "(", "info", ".", "DNSSearchDomains", "...", ")", ")", "\n\n", "if", "info", ".", "GatewayAddress", ".", "Value", "!=", "\"", "\"", "{", "switch", "{", "case", "gateway4Address", "==", "\"", "\"", "&&", "info", ".", "GatewayAddress", ".", "Type", "==", "network", ".", "IPv4Address", ":", "gateway4Address", "=", "info", ".", "GatewayAddress", ".", "Value", "\n\n", "case", "gateway6Address", "==", "\"", "\"", "&&", "info", ".", "GatewayAddress", ".", "Type", "==", "network", ".", "IPv6Address", ":", "gateway6Address", "=", "info", ".", "GatewayAddress", ".", "Value", "\n", "}", "\n", "}", "\n\n", "if", "info", ".", "MTU", "!=", "0", "&&", "info", ".", "MTU", "!=", "1500", "{", "nameToMTU", "[", "ifaceName", "]", "=", "info", ".", "MTU", "\n", "}", "\n\n", "namesInOrder", "=", "append", "(", "namesInOrder", ",", "ifaceName", ")", "\n", "}", "\n\n", "prepared", ":=", "&", "PreparedConfig", "{", "InterfaceNames", ":", "namesInOrder", ",", "NameToAddress", ":", "nameToAddress", ",", "NameToRoutes", ":", "nameToRoutes", ",", "NameToMTU", ":", "nameToMTU", ",", "AutoStarted", ":", "autoStarted", ".", "SortedValues", "(", ")", ",", "DNSServers", ":", "dnsServers", ".", "SortedValues", "(", ")", ",", "DNSSearchDomains", ":", "dnsSearchDomains", ".", "SortedValues", "(", ")", ",", "Gateway4Address", ":", "gateway4Address", ",", "Gateway6Address", ":", "gateway6Address", ",", "}", "\n\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "prepared", ")", "\n", "return", "prepared", "\n", "}" ]
// PrepareNetworkConfigFromInterfaces collects the necessary information to // render a persistent network config from the given slice of // network.InterfaceInfo. The result always includes the loopback interface.
[ "PrepareNetworkConfigFromInterfaces", "collects", "the", "necessary", "information", "to", "render", "a", "persistent", "network", "config", "from", "the", "given", "slice", "of", "network", ".", "InterfaceInfo", ".", "The", "result", "always", "includes", "the", "loopback", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/cloudinit/network_ubuntu.go#L213-L294
156,399
juju/juju
worker/storageprovisioner/config.go
Validate
func (config Config) Validate() error { switch config.Scope.(type) { case nil: return errors.NotValidf("nil Scope") case names.ModelTag: if config.StorageDir != "" { return errors.NotValidf("environ Scope with non-empty StorageDir") } case names.MachineTag: if config.StorageDir == "" { return errors.NotValidf("machine Scope with empty StorageDir") } if config.Machines == nil { return errors.NotValidf("nil Machines") } case names.ApplicationTag: if config.StorageDir != "" { return errors.NotValidf("application Scope with StorageDir") } if config.Applications == nil { return errors.NotValidf("nil Applications") } default: return errors.NotValidf("%T Scope", config.Scope) } if config.Volumes == nil { return errors.NotValidf("nil Volumes") } if config.Filesystems == nil { return errors.NotValidf("nil Filesystems") } if config.Life == nil { return errors.NotValidf("nil Life") } if config.Registry == nil { return errors.NotValidf("nil Registry") } if config.Status == nil { return errors.NotValidf("nil Status") } if config.Clock == nil { return errors.NotValidf("nil Clock") } if config.CloudCallContext == nil { return errors.NotValidf("nil CloudCallContext") } return nil }
go
func (config Config) Validate() error { switch config.Scope.(type) { case nil: return errors.NotValidf("nil Scope") case names.ModelTag: if config.StorageDir != "" { return errors.NotValidf("environ Scope with non-empty StorageDir") } case names.MachineTag: if config.StorageDir == "" { return errors.NotValidf("machine Scope with empty StorageDir") } if config.Machines == nil { return errors.NotValidf("nil Machines") } case names.ApplicationTag: if config.StorageDir != "" { return errors.NotValidf("application Scope with StorageDir") } if config.Applications == nil { return errors.NotValidf("nil Applications") } default: return errors.NotValidf("%T Scope", config.Scope) } if config.Volumes == nil { return errors.NotValidf("nil Volumes") } if config.Filesystems == nil { return errors.NotValidf("nil Filesystems") } if config.Life == nil { return errors.NotValidf("nil Life") } if config.Registry == nil { return errors.NotValidf("nil Registry") } if config.Status == nil { return errors.NotValidf("nil Status") } if config.Clock == nil { return errors.NotValidf("nil Clock") } if config.CloudCallContext == nil { return errors.NotValidf("nil CloudCallContext") } return nil }
[ "func", "(", "config", "Config", ")", "Validate", "(", ")", "error", "{", "switch", "config", ".", "Scope", ".", "(", "type", ")", "{", "case", "nil", ":", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "case", "names", ".", "ModelTag", ":", "if", "config", ".", "StorageDir", "!=", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "case", "names", ".", "MachineTag", ":", "if", "config", ".", "StorageDir", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Machines", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "case", "names", ".", "ApplicationTag", ":", "if", "config", ".", "StorageDir", "!=", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Applications", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "config", ".", "Scope", ")", "\n", "}", "\n", "if", "config", ".", "Volumes", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Filesystems", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Life", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Registry", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Status", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Clock", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "CloudCallContext", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate returns an error if the config cannot be relied upon to start a worker.
[ "Validate", "returns", "an", "error", "if", "the", "config", "cannot", "be", "relied", "upon", "to", "start", "a", "worker", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/config.go#L32-L79