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,900
juju/juju
state/unit.go
UpdateOperation
func (u *Unit) UpdateOperation(props UnitUpdateProperties) *UpdateUnitOperation { return &UpdateUnitOperation{ unit: &Unit{st: u.st, doc: u.doc, modelType: u.modelType}, props: props, } }
go
func (u *Unit) UpdateOperation(props UnitUpdateProperties) *UpdateUnitOperation { return &UpdateUnitOperation{ unit: &Unit{st: u.st, doc: u.doc, modelType: u.modelType}, props: props, } }
[ "func", "(", "u", "*", "Unit", ")", "UpdateOperation", "(", "props", "UnitUpdateProperties", ")", "*", "UpdateUnitOperation", "{", "return", "&", "UpdateUnitOperation", "{", "unit", ":", "&", "Unit", "{", "st", ":", "u", ".", "st", ",", "doc", ":", "u", ".", "doc", ",", "modelType", ":", "u", ".", "modelType", "}", ",", "props", ":", "props", ",", "}", "\n", "}" ]
// UpdateOperation returns a model operation that will update a unit.
[ "UpdateOperation", "returns", "a", "model", "operation", "that", "will", "update", "a", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L325-L330
156,901
juju/juju
state/unit.go
Destroy
func (u *Unit) Destroy() error { _, err := u.DestroyWithForce(false, time.Duration(0)) return err }
go
func (u *Unit) Destroy() error { _, err := u.DestroyWithForce(false, time.Duration(0)) return err }
[ "func", "(", "u", "*", "Unit", ")", "Destroy", "(", ")", "error", "{", "_", ",", "err", ":=", "u", ".", "DestroyWithForce", "(", "false", ",", "time", ".", "Duration", "(", "0", ")", ")", "\n", "return", "err", "\n", "}" ]
// Destroy, when called on a Alive unit, advances its lifecycle as far as // possible; it otherwise has no effect. In most situations, the unit's // life is just set to Dying; but if a principal unit that is not assigned // to a provisioned machine is Destroyed, it will be removed from state // directly.
[ "Destroy", "when", "called", "on", "a", "Alive", "unit", "advances", "its", "lifecycle", "as", "far", "as", "possible", ";", "it", "otherwise", "has", "no", "effect", ".", "In", "most", "situations", "the", "unit", "s", "life", "is", "just", "set", "to", "Dying", ";", "but", "if", "a", "principal", "unit", "that", "is", "not", "assigned", "to", "a", "provisioned", "machine", "is", "Destroyed", "it", "will", "be", "removed", "from", "state", "directly", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L468-L471
156,902
juju/juju
state/unit.go
DestroyOperation
func (u *Unit) DestroyOperation() *DestroyUnitOperation { return &DestroyUnitOperation{ unit: &Unit{st: u.st, doc: u.doc, modelType: u.modelType}, } }
go
func (u *Unit) DestroyOperation() *DestroyUnitOperation { return &DestroyUnitOperation{ unit: &Unit{st: u.st, doc: u.doc, modelType: u.modelType}, } }
[ "func", "(", "u", "*", "Unit", ")", "DestroyOperation", "(", ")", "*", "DestroyUnitOperation", "{", "return", "&", "DestroyUnitOperation", "{", "unit", ":", "&", "Unit", "{", "st", ":", "u", ".", "st", ",", "doc", ":", "u", ".", "doc", ",", "modelType", ":", "u", ".", "modelType", "}", ",", "}", "\n", "}" ]
// DestroyOperation returns a model operation that will destroy the unit.
[ "DestroyOperation", "returns", "a", "model", "operation", "that", "will", "destroy", "the", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L490-L494
156,903
juju/juju
state/unit.go
removeOps
func (u *Unit) removeOps(asserts bson.D, op *ForcedOperation, destroyStorage bool) ([]txn.Op, error) { app, err := u.st.Application(u.doc.Application) if errors.IsNotFound(err) { // If the application has been removed, the unit must already have been. return nil, errAlreadyRemoved } else if err != nil { // If we cannot find application, no amount of force will succeed after this point. return nil, err } return app.removeUnitOps(u, asserts, op, destroyStorage) }
go
func (u *Unit) removeOps(asserts bson.D, op *ForcedOperation, destroyStorage bool) ([]txn.Op, error) { app, err := u.st.Application(u.doc.Application) if errors.IsNotFound(err) { // If the application has been removed, the unit must already have been. return nil, errAlreadyRemoved } else if err != nil { // If we cannot find application, no amount of force will succeed after this point. return nil, err } return app.removeUnitOps(u, asserts, op, destroyStorage) }
[ "func", "(", "u", "*", "Unit", ")", "removeOps", "(", "asserts", "bson", ".", "D", ",", "op", "*", "ForcedOperation", ",", "destroyStorage", "bool", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "app", ",", "err", ":=", "u", ".", "st", ".", "Application", "(", "u", ".", "doc", ".", "Application", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "// If the application has been removed, the unit must already have been.", "return", "nil", ",", "errAlreadyRemoved", "\n", "}", "else", "if", "err", "!=", "nil", "{", "// If we cannot find application, no amount of force will succeed after this point.", "return", "nil", ",", "err", "\n", "}", "\n", "return", "app", ".", "removeUnitOps", "(", "u", ",", "asserts", ",", "op", ",", "destroyStorage", ")", "\n", "}" ]
// removeOps returns the operations necessary to remove the unit, assuming // the supplied asserts apply to the unit document. // When 'force' is set, this call will return needed operations // accumulating all operational errors in the operation. // If the 'force' is not set, any error will be fatal and no operations will be returned.
[ "removeOps", "returns", "the", "operations", "necessary", "to", "remove", "the", "unit", "assuming", "the", "supplied", "asserts", "apply", "to", "the", "unit", "document", ".", "When", "force", "is", "set", "this", "call", "will", "return", "needed", "operations", "accumulating", "all", "operational", "errors", "in", "the", "operation", ".", "If", "the", "force", "is", "not", "set", "any", "error", "will", "be", "fatal", "and", "no", "operations", "will", "be", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L833-L843
156,904
juju/juju
state/unit.go
EnsureDead
func (u *Unit) EnsureDead() (err error) { if u.doc.Life == Dead { return nil } defer func() { if err == nil { u.doc.Life = Dead } }() assert := append(notDeadDoc, bson.DocElem{ "$and", []bson.D{ unitHasNoSubordinates, unitHasNoStorageAttachments, }, }) ops := []txn.Op{{ C: unitsC, Id: u.doc.DocID, Assert: assert, Update: bson.D{{"$set", bson.D{{"life", Dead}}}}, }} if err := u.st.db().RunTransaction(ops); err != txn.ErrAborted { return err } if notDead, err := isNotDead(u.st, unitsC, u.doc.DocID); err != nil { return err } else if !notDead { return nil } if err := u.Refresh(); errors.IsNotFound(err) { return nil } else if err != nil { return err } if len(u.doc.Subordinates) > 0 { return ErrUnitHasSubordinates } return ErrUnitHasStorageAttachments }
go
func (u *Unit) EnsureDead() (err error) { if u.doc.Life == Dead { return nil } defer func() { if err == nil { u.doc.Life = Dead } }() assert := append(notDeadDoc, bson.DocElem{ "$and", []bson.D{ unitHasNoSubordinates, unitHasNoStorageAttachments, }, }) ops := []txn.Op{{ C: unitsC, Id: u.doc.DocID, Assert: assert, Update: bson.D{{"$set", bson.D{{"life", Dead}}}}, }} if err := u.st.db().RunTransaction(ops); err != txn.ErrAborted { return err } if notDead, err := isNotDead(u.st, unitsC, u.doc.DocID); err != nil { return err } else if !notDead { return nil } if err := u.Refresh(); errors.IsNotFound(err) { return nil } else if err != nil { return err } if len(u.doc.Subordinates) > 0 { return ErrUnitHasSubordinates } return ErrUnitHasStorageAttachments }
[ "func", "(", "u", "*", "Unit", ")", "EnsureDead", "(", ")", "(", "err", "error", ")", "{", "if", "u", ".", "doc", ".", "Life", "==", "Dead", "{", "return", "nil", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "err", "==", "nil", "{", "u", ".", "doc", ".", "Life", "=", "Dead", "\n", "}", "\n", "}", "(", ")", "\n", "assert", ":=", "append", "(", "notDeadDoc", ",", "bson", ".", "DocElem", "{", "\"", "\"", ",", "[", "]", "bson", ".", "D", "{", "unitHasNoSubordinates", ",", "unitHasNoStorageAttachments", ",", "}", ",", "}", ")", "\n", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "unitsC", ",", "Id", ":", "u", ".", "doc", ".", "DocID", ",", "Assert", ":", "assert", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "Dead", "}", "}", "}", "}", ",", "}", "}", "\n", "if", "err", ":=", "u", ".", "st", ".", "db", "(", ")", ".", "RunTransaction", "(", "ops", ")", ";", "err", "!=", "txn", ".", "ErrAborted", "{", "return", "err", "\n", "}", "\n", "if", "notDead", ",", "err", ":=", "isNotDead", "(", "u", ".", "st", ",", "unitsC", ",", "u", ".", "doc", ".", "DocID", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "if", "!", "notDead", "{", "return", "nil", "\n", "}", "\n", "if", "err", ":=", "u", ".", "Refresh", "(", ")", ";", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "u", ".", "doc", ".", "Subordinates", ")", ">", "0", "{", "return", "ErrUnitHasSubordinates", "\n", "}", "\n", "return", "ErrUnitHasStorageAttachments", "\n", "}" ]
// EnsureDead sets the unit lifecycle to Dead if it is Alive or Dying. // It does nothing otherwise. If the unit has subordinates, it will // return ErrUnitHasSubordinates; otherwise, if it has storage instances, // it will return ErrUnitHasStorageInstances.
[ "EnsureDead", "sets", "the", "unit", "lifecycle", "to", "Dead", "if", "it", "is", "Alive", "or", "Dying", ".", "It", "does", "nothing", "otherwise", ".", "If", "the", "unit", "has", "subordinates", "it", "will", "return", "ErrUnitHasSubordinates", ";", "otherwise", "if", "it", "has", "storage", "instances", "it", "will", "return", "ErrUnitHasStorageInstances", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L873-L911
156,905
juju/juju
state/unit.go
RemoveOperation
func (u *Unit) RemoveOperation(force bool) *RemoveUnitOperation { return &RemoveUnitOperation{ unit: &Unit{st: u.st, doc: u.doc, modelType: u.modelType}, ForcedOperation: ForcedOperation{Force: force}, } }
go
func (u *Unit) RemoveOperation(force bool) *RemoveUnitOperation { return &RemoveUnitOperation{ unit: &Unit{st: u.st, doc: u.doc, modelType: u.modelType}, ForcedOperation: ForcedOperation{Force: force}, } }
[ "func", "(", "u", "*", "Unit", ")", "RemoveOperation", "(", "force", "bool", ")", "*", "RemoveUnitOperation", "{", "return", "&", "RemoveUnitOperation", "{", "unit", ":", "&", "Unit", "{", "st", ":", "u", ".", "st", ",", "doc", ":", "u", ".", "doc", ",", "modelType", ":", "u", ".", "modelType", "}", ",", "ForcedOperation", ":", "ForcedOperation", "{", "Force", ":", "force", "}", ",", "}", "\n", "}" ]
// RemoveOperation returns a model operation that will remove the unit.
[ "RemoveOperation", "returns", "a", "model", "operation", "that", "will", "remove", "the", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L914-L919
156,906
juju/juju
state/unit.go
AddError
func (op *ForcedOperation) AddError(one ...error) { op.Errors = append(op.Errors, one...) }
go
func (op *ForcedOperation) AddError(one ...error) { op.Errors = append(op.Errors, one...) }
[ "func", "(", "op", "*", "ForcedOperation", ")", "AddError", "(", "one", "...", "error", ")", "{", "op", ".", "Errors", "=", "append", "(", "op", ".", "Errors", ",", "one", "...", ")", "\n", "}" ]
// AddError adds an error to the collection of errors for this operation.
[ "AddError", "adds", "an", "error", "to", "the", "collection", "of", "errors", "for", "this", "operation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L941-L943
156,907
juju/juju
state/unit.go
Remove
func (u *Unit) Remove() error { _, err := u.RemoveWithForce(false, time.Duration(0)) return err }
go
func (u *Unit) Remove() error { _, err := u.RemoveWithForce(false, time.Duration(0)) return err }
[ "func", "(", "u", "*", "Unit", ")", "Remove", "(", ")", "error", "{", "_", ",", "err", ":=", "u", ".", "RemoveWithForce", "(", "false", ",", "time", ".", "Duration", "(", "0", ")", ")", "\n", "return", "err", "\n", "}" ]
// Remove removes the unit from state, and may remove its application as well, if // the application is Dying and no other references to it exist. It will fail if // the unit is not Dead.
[ "Remove", "removes", "the", "unit", "from", "state", "and", "may", "remove", "its", "application", "as", "well", "if", "the", "application", "is", "Dying", "and", "no", "other", "references", "to", "it", "exist", ".", "It", "will", "fail", "if", "the", "unit", "is", "not", "Dead", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1001-L1004
156,908
juju/juju
state/unit.go
removeOps
func (op *RemoveUnitOperation) removeOps() (ops []txn.Op, err error) { if op.unit.doc.Life != Dead { return nil, errors.New("unit is not dead") } // Now the unit is Dead, we can be sure that it's impossible for it to // enter relation scopes (once it's Dying, we can be sure of this; but // EnsureDead does not require that it already be Dying, so this is the // only point at which we can safely backstop lp:1233457 and mitigate // the impact of unit agent bugs that leave relation scopes occupied). relations, err := applicationRelations(op.unit.st, op.unit.doc.Application) if err != nil { if !op.Force { return nil, err } op.AddError(err) } else { failRelations := false for _, rel := range relations { ru, err := rel.Unit(op.unit) if err != nil { op.AddError(err) failRelations = true continue } leaveScopOps, err := ru.leaveScopeForcedOps(&op.ForcedOperation) if err != nil && err != jujutxn.ErrNoOperations { op.AddError(err) failRelations = true } ops = append(ops, leaveScopOps...) } if !op.Force && failRelations { return nil, op.LastError() } } // Now we're sure we haven't left any scopes occupied by this unit, we // can safely remove the document. unitRemoveOps, err := op.unit.removeOps(isDeadDoc, &op.ForcedOperation, false) if err != nil { if !op.Force { return nil, err } op.AddError(err) } return append(ops, unitRemoveOps...), nil }
go
func (op *RemoveUnitOperation) removeOps() (ops []txn.Op, err error) { if op.unit.doc.Life != Dead { return nil, errors.New("unit is not dead") } // Now the unit is Dead, we can be sure that it's impossible for it to // enter relation scopes (once it's Dying, we can be sure of this; but // EnsureDead does not require that it already be Dying, so this is the // only point at which we can safely backstop lp:1233457 and mitigate // the impact of unit agent bugs that leave relation scopes occupied). relations, err := applicationRelations(op.unit.st, op.unit.doc.Application) if err != nil { if !op.Force { return nil, err } op.AddError(err) } else { failRelations := false for _, rel := range relations { ru, err := rel.Unit(op.unit) if err != nil { op.AddError(err) failRelations = true continue } leaveScopOps, err := ru.leaveScopeForcedOps(&op.ForcedOperation) if err != nil && err != jujutxn.ErrNoOperations { op.AddError(err) failRelations = true } ops = append(ops, leaveScopOps...) } if !op.Force && failRelations { return nil, op.LastError() } } // Now we're sure we haven't left any scopes occupied by this unit, we // can safely remove the document. unitRemoveOps, err := op.unit.removeOps(isDeadDoc, &op.ForcedOperation, false) if err != nil { if !op.Force { return nil, err } op.AddError(err) } return append(ops, unitRemoveOps...), nil }
[ "func", "(", "op", "*", "RemoveUnitOperation", ")", "removeOps", "(", ")", "(", "ops", "[", "]", "txn", ".", "Op", ",", "err", "error", ")", "{", "if", "op", ".", "unit", ".", "doc", ".", "Life", "!=", "Dead", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "// Now the unit is Dead, we can be sure that it's impossible for it to", "// enter relation scopes (once it's Dying, we can be sure of this; but", "// EnsureDead does not require that it already be Dying, so this is the", "// only point at which we can safely backstop lp:1233457 and mitigate", "// the impact of unit agent bugs that leave relation scopes occupied).", "relations", ",", "err", ":=", "applicationRelations", "(", "op", ".", "unit", ".", "st", ",", "op", ".", "unit", ".", "doc", ".", "Application", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "op", ".", "Force", "{", "return", "nil", ",", "err", "\n", "}", "\n", "op", ".", "AddError", "(", "err", ")", "\n", "}", "else", "{", "failRelations", ":=", "false", "\n", "for", "_", ",", "rel", ":=", "range", "relations", "{", "ru", ",", "err", ":=", "rel", ".", "Unit", "(", "op", ".", "unit", ")", "\n", "if", "err", "!=", "nil", "{", "op", ".", "AddError", "(", "err", ")", "\n", "failRelations", "=", "true", "\n", "continue", "\n", "}", "\n", "leaveScopOps", ",", "err", ":=", "ru", ".", "leaveScopeForcedOps", "(", "&", "op", ".", "ForcedOperation", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "jujutxn", ".", "ErrNoOperations", "{", "op", ".", "AddError", "(", "err", ")", "\n", "failRelations", "=", "true", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "leaveScopOps", "...", ")", "\n", "}", "\n", "if", "!", "op", ".", "Force", "&&", "failRelations", "{", "return", "nil", ",", "op", ".", "LastError", "(", ")", "\n", "}", "\n", "}", "\n\n", "// Now we're sure we haven't left any scopes occupied by this unit, we", "// can safely remove the document.", "unitRemoveOps", ",", "err", ":=", "op", ".", "unit", ".", "removeOps", "(", "isDeadDoc", ",", "&", "op", ".", "ForcedOperation", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "op", ".", "Force", "{", "return", "nil", ",", "err", "\n", "}", "\n", "op", ".", "AddError", "(", "err", ")", "\n", "}", "\n", "return", "append", "(", "ops", ",", "unitRemoveOps", "...", ")", ",", "nil", "\n", "}" ]
// When 'force' is set, this call will return needed operations // and all operational errors will be accumulated in operation itself. // If the 'force' is not set, any error will be fatal and no operations will be returned.
[ "When", "force", "is", "set", "this", "call", "will", "return", "needed", "operations", "and", "all", "operational", "errors", "will", "be", "accumulated", "in", "operation", "itself", ".", "If", "the", "force", "is", "not", "set", "any", "error", "will", "be", "fatal", "and", "no", "operations", "will", "be", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1020-L1066
156,909
juju/juju
state/unit.go
SubordinateNames
func (u *Unit) SubordinateNames() []string { subNames := make([]string, len(u.doc.Subordinates)) copy(subNames, u.doc.Subordinates) return subNames }
go
func (u *Unit) SubordinateNames() []string { subNames := make([]string, len(u.doc.Subordinates)) copy(subNames, u.doc.Subordinates) return subNames }
[ "func", "(", "u", "*", "Unit", ")", "SubordinateNames", "(", ")", "[", "]", "string", "{", "subNames", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "u", ".", "doc", ".", "Subordinates", ")", ")", "\n", "copy", "(", "subNames", ",", "u", ".", "doc", ".", "Subordinates", ")", "\n", "return", "subNames", "\n", "}" ]
// SubordinateNames returns the names of any subordinate units.
[ "SubordinateNames", "returns", "the", "names", "of", "any", "subordinate", "units", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1080-L1084
156,910
juju/juju
state/unit.go
RelationsJoined
func (u *Unit) RelationsJoined() ([]*Relation, error) { return u.relations(func(ru *RelationUnit) (bool, error) { return ru.Joined() }) }
go
func (u *Unit) RelationsJoined() ([]*Relation, error) { return u.relations(func(ru *RelationUnit) (bool, error) { return ru.Joined() }) }
[ "func", "(", "u", "*", "Unit", ")", "RelationsJoined", "(", ")", "(", "[", "]", "*", "Relation", ",", "error", ")", "{", "return", "u", ".", "relations", "(", "func", "(", "ru", "*", "RelationUnit", ")", "(", "bool", ",", "error", ")", "{", "return", "ru", ".", "Joined", "(", ")", "\n", "}", ")", "\n", "}" ]
// RelationsJoined returns the relations for which the unit has entered scope // and neither left it nor prepared to leave it
[ "RelationsJoined", "returns", "the", "relations", "for", "which", "the", "unit", "has", "entered", "scope", "and", "neither", "left", "it", "nor", "prepared", "to", "leave", "it" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1088-L1092
156,911
juju/juju
state/unit.go
RelationsInScope
func (u *Unit) RelationsInScope() ([]*Relation, error) { return u.relations(func(ru *RelationUnit) (bool, error) { return ru.InScope() }) }
go
func (u *Unit) RelationsInScope() ([]*Relation, error) { return u.relations(func(ru *RelationUnit) (bool, error) { return ru.InScope() }) }
[ "func", "(", "u", "*", "Unit", ")", "RelationsInScope", "(", ")", "(", "[", "]", "*", "Relation", ",", "error", ")", "{", "return", "u", ".", "relations", "(", "func", "(", "ru", "*", "RelationUnit", ")", "(", "bool", ",", "error", ")", "{", "return", "ru", ".", "InScope", "(", ")", "\n", "}", ")", "\n", "}" ]
// RelationsInScope returns the relations for which the unit has entered scope // and not left it.
[ "RelationsInScope", "returns", "the", "relations", "for", "which", "the", "unit", "has", "entered", "scope", "and", "not", "left", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1096-L1100
156,912
juju/juju
state/unit.go
relations
func (u *Unit) relations(predicate relationPredicate) ([]*Relation, error) { candidates, err := applicationRelations(u.st, u.doc.Application) if err != nil { return nil, err } var filtered []*Relation for _, relation := range candidates { relationUnit, err := relation.Unit(u) if err != nil { return nil, err } if include, err := predicate(relationUnit); err != nil { return nil, err } else if include { filtered = append(filtered, relation) } } return filtered, nil }
go
func (u *Unit) relations(predicate relationPredicate) ([]*Relation, error) { candidates, err := applicationRelations(u.st, u.doc.Application) if err != nil { return nil, err } var filtered []*Relation for _, relation := range candidates { relationUnit, err := relation.Unit(u) if err != nil { return nil, err } if include, err := predicate(relationUnit); err != nil { return nil, err } else if include { filtered = append(filtered, relation) } } return filtered, nil }
[ "func", "(", "u", "*", "Unit", ")", "relations", "(", "predicate", "relationPredicate", ")", "(", "[", "]", "*", "Relation", ",", "error", ")", "{", "candidates", ",", "err", ":=", "applicationRelations", "(", "u", ".", "st", ",", "u", ".", "doc", ".", "Application", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "filtered", "[", "]", "*", "Relation", "\n", "for", "_", ",", "relation", ":=", "range", "candidates", "{", "relationUnit", ",", "err", ":=", "relation", ".", "Unit", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "include", ",", "err", ":=", "predicate", "(", "relationUnit", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "if", "include", "{", "filtered", "=", "append", "(", "filtered", ",", "relation", ")", "\n", "}", "\n", "}", "\n", "return", "filtered", ",", "nil", "\n", "}" ]
// relations implements RelationsJoined and RelationsInScope.
[ "relations", "implements", "RelationsJoined", "and", "RelationsInScope", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1105-L1123
156,913
juju/juju
state/unit.go
DeployerTag
func (u *Unit) DeployerTag() (names.Tag, bool) { if u.doc.Principal != "" { return names.NewUnitTag(u.doc.Principal), true } else if u.doc.MachineId != "" { return names.NewMachineTag(u.doc.MachineId), true } return nil, false }
go
func (u *Unit) DeployerTag() (names.Tag, bool) { if u.doc.Principal != "" { return names.NewUnitTag(u.doc.Principal), true } else if u.doc.MachineId != "" { return names.NewMachineTag(u.doc.MachineId), true } return nil, false }
[ "func", "(", "u", "*", "Unit", ")", "DeployerTag", "(", ")", "(", "names", ".", "Tag", ",", "bool", ")", "{", "if", "u", ".", "doc", ".", "Principal", "!=", "\"", "\"", "{", "return", "names", ".", "NewUnitTag", "(", "u", ".", "doc", ".", "Principal", ")", ",", "true", "\n", "}", "else", "if", "u", ".", "doc", ".", "MachineId", "!=", "\"", "\"", "{", "return", "names", ".", "NewMachineTag", "(", "u", ".", "doc", ".", "MachineId", ")", ",", "true", "\n", "}", "\n", "return", "nil", ",", "false", "\n", "}" ]
// DeployerTag returns the tag of the agent responsible for deploying // the unit. If no such entity can be determined, false is returned.
[ "DeployerTag", "returns", "the", "tag", "of", "the", "agent", "responsible", "for", "deploying", "the", "unit", ".", "If", "no", "such", "entity", "can", "be", "determined", "false", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1127-L1134
156,914
juju/juju
state/unit.go
PrincipalName
func (u *Unit) PrincipalName() (string, bool) { return u.doc.Principal, u.doc.Principal != "" }
go
func (u *Unit) PrincipalName() (string, bool) { return u.doc.Principal, u.doc.Principal != "" }
[ "func", "(", "u", "*", "Unit", ")", "PrincipalName", "(", ")", "(", "string", ",", "bool", ")", "{", "return", "u", ".", "doc", ".", "Principal", ",", "u", ".", "doc", ".", "Principal", "!=", "\"", "\"", "\n", "}" ]
// PrincipalName returns the name of the unit's principal. // If the unit is not a subordinate, false is returned.
[ "PrincipalName", "returns", "the", "name", "of", "the", "unit", "s", "principal", ".", "If", "the", "unit", "is", "not", "a", "subordinate", "false", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1138-L1140
156,915
juju/juju
state/unit.go
machine
func (u *Unit) machine() (*Machine, error) { id, err := u.AssignedMachineId() if err != nil { return nil, errors.Annotatef(err, "unit %v cannot get assigned machine", u) } m, err := u.st.Machine(id) if err != nil { return nil, errors.Annotatef(err, "unit %v misses machine id %v", u, id) } return m, nil }
go
func (u *Unit) machine() (*Machine, error) { id, err := u.AssignedMachineId() if err != nil { return nil, errors.Annotatef(err, "unit %v cannot get assigned machine", u) } m, err := u.st.Machine(id) if err != nil { return nil, errors.Annotatef(err, "unit %v misses machine id %v", u, id) } return m, nil }
[ "func", "(", "u", "*", "Unit", ")", "machine", "(", ")", "(", "*", "Machine", ",", "error", ")", "{", "id", ",", "err", ":=", "u", ".", "AssignedMachineId", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "u", ")", "\n", "}", "\n", "m", ",", "err", ":=", "u", ".", "st", ".", "Machine", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "u", ",", "id", ")", "\n", "}", "\n", "return", "m", ",", "nil", "\n", "}" ]
// machine returns the unit's machine. // // machine is part of the machineAssignable interface.
[ "machine", "returns", "the", "unit", "s", "machine", ".", "machine", "is", "part", "of", "the", "machineAssignable", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1145-L1155
156,916
juju/juju
state/unit.go
noAssignedMachineOp
func (u *Unit) noAssignedMachineOp() txn.Op { id := u.doc.DocID if u.doc.Principal != "" { id = u.doc.Principal } return txn.Op{ C: unitsC, Id: id, Assert: bson.D{{"machineid", ""}}, } }
go
func (u *Unit) noAssignedMachineOp() txn.Op { id := u.doc.DocID if u.doc.Principal != "" { id = u.doc.Principal } return txn.Op{ C: unitsC, Id: id, Assert: bson.D{{"machineid", ""}}, } }
[ "func", "(", "u", "*", "Unit", ")", "noAssignedMachineOp", "(", ")", "txn", ".", "Op", "{", "id", ":=", "u", ".", "doc", ".", "DocID", "\n", "if", "u", ".", "doc", ".", "Principal", "!=", "\"", "\"", "{", "id", "=", "u", ".", "doc", ".", "Principal", "\n", "}", "\n", "return", "txn", ".", "Op", "{", "C", ":", "unitsC", ",", "Id", ":", "id", ",", "Assert", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "\"", "\"", "}", "}", ",", "}", "\n", "}" ]
// noAssignedMachineOp is part of the machineAssignable interface.
[ "noAssignedMachineOp", "is", "part", "of", "the", "machineAssignable", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1158-L1168
156,917
juju/juju
state/unit.go
PublicAddress
func (u *Unit) PublicAddress() (network.Address, error) { if !u.ShouldBeAssigned() { return u.scopedAddress("public") } m, err := u.machine() if err != nil { unitLogger.Tracef("%v", err) return network.Address{}, errors.Trace(err) } return m.PublicAddress() }
go
func (u *Unit) PublicAddress() (network.Address, error) { if !u.ShouldBeAssigned() { return u.scopedAddress("public") } m, err := u.machine() if err != nil { unitLogger.Tracef("%v", err) return network.Address{}, errors.Trace(err) } return m.PublicAddress() }
[ "func", "(", "u", "*", "Unit", ")", "PublicAddress", "(", ")", "(", "network", ".", "Address", ",", "error", ")", "{", "if", "!", "u", ".", "ShouldBeAssigned", "(", ")", "{", "return", "u", ".", "scopedAddress", "(", "\"", "\"", ")", "\n", "}", "\n", "m", ",", "err", ":=", "u", ".", "machine", "(", ")", "\n", "if", "err", "!=", "nil", "{", "unitLogger", ".", "Tracef", "(", "\"", "\"", ",", "err", ")", "\n", "return", "network", ".", "Address", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "m", ".", "PublicAddress", "(", ")", "\n", "}" ]
// PublicAddress returns the public address of the unit.
[ "PublicAddress", "returns", "the", "public", "address", "of", "the", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1171-L1181
156,918
juju/juju
state/unit.go
containerAddress
func (u *Unit) containerAddress() (network.Address, error) { containerInfo, err := u.cloudContainer() if errors.IsNotFound(err) { return network.Address{}, network.NoAddressError("container") } if err != nil { return network.Address{}, errors.Trace(err) } addr := containerInfo.Address if addr == nil { return network.Address{}, network.NoAddressError("container") } return addr.networkAddress(), nil }
go
func (u *Unit) containerAddress() (network.Address, error) { containerInfo, err := u.cloudContainer() if errors.IsNotFound(err) { return network.Address{}, network.NoAddressError("container") } if err != nil { return network.Address{}, errors.Trace(err) } addr := containerInfo.Address if addr == nil { return network.Address{}, network.NoAddressError("container") } return addr.networkAddress(), nil }
[ "func", "(", "u", "*", "Unit", ")", "containerAddress", "(", ")", "(", "network", ".", "Address", ",", "error", ")", "{", "containerInfo", ",", "err", ":=", "u", ".", "cloudContainer", "(", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "network", ".", "Address", "{", "}", ",", "network", ".", "NoAddressError", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "network", ".", "Address", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "addr", ":=", "containerInfo", ".", "Address", "\n", "if", "addr", "==", "nil", "{", "return", "network", ".", "Address", "{", "}", ",", "network", ".", "NoAddressError", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "addr", ".", "networkAddress", "(", ")", ",", "nil", "\n", "}" ]
// containerAddress returns the address of the pod's container.
[ "containerAddress", "returns", "the", "address", "of", "the", "pod", "s", "container", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1242-L1255
156,919
juju/juju
state/unit.go
serviceAddress
func (u *Unit) serviceAddress(scope string) (network.Address, error) { addresses, err := u.AllAddresses() if err != nil { return network.Address{}, errors.Trace(err) } if len(addresses) == 0 { return network.Address{}, network.NoAddressError(scope) } getStrictPublicAddr := func(addresses []network.Address) (network.Address, bool) { addr, ok := network.SelectPublicAddress(addresses) ok = ok && addr.Scope == network.ScopePublic return addr, ok } getInternalAddr := func(addresses []network.Address) (network.Address, bool) { return network.SelectInternalAddress(addresses, false) } var addrMatch func([]network.Address) (network.Address, bool) switch scope { case "public": addrMatch = getStrictPublicAddr case "private": addrMatch = getInternalAddr default: return network.Address{}, errors.NotValidf("address scope %q", scope) } addr, found := addrMatch(addresses) if !found { return network.Address{}, network.NoAddressError(scope) } return addr, nil }
go
func (u *Unit) serviceAddress(scope string) (network.Address, error) { addresses, err := u.AllAddresses() if err != nil { return network.Address{}, errors.Trace(err) } if len(addresses) == 0 { return network.Address{}, network.NoAddressError(scope) } getStrictPublicAddr := func(addresses []network.Address) (network.Address, bool) { addr, ok := network.SelectPublicAddress(addresses) ok = ok && addr.Scope == network.ScopePublic return addr, ok } getInternalAddr := func(addresses []network.Address) (network.Address, bool) { return network.SelectInternalAddress(addresses, false) } var addrMatch func([]network.Address) (network.Address, bool) switch scope { case "public": addrMatch = getStrictPublicAddr case "private": addrMatch = getInternalAddr default: return network.Address{}, errors.NotValidf("address scope %q", scope) } addr, found := addrMatch(addresses) if !found { return network.Address{}, network.NoAddressError(scope) } return addr, nil }
[ "func", "(", "u", "*", "Unit", ")", "serviceAddress", "(", "scope", "string", ")", "(", "network", ".", "Address", ",", "error", ")", "{", "addresses", ",", "err", ":=", "u", ".", "AllAddresses", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "network", ".", "Address", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "addresses", ")", "==", "0", "{", "return", "network", ".", "Address", "{", "}", ",", "network", ".", "NoAddressError", "(", "scope", ")", "\n", "}", "\n\n", "getStrictPublicAddr", ":=", "func", "(", "addresses", "[", "]", "network", ".", "Address", ")", "(", "network", ".", "Address", ",", "bool", ")", "{", "addr", ",", "ok", ":=", "network", ".", "SelectPublicAddress", "(", "addresses", ")", "\n", "ok", "=", "ok", "&&", "addr", ".", "Scope", "==", "network", ".", "ScopePublic", "\n", "return", "addr", ",", "ok", "\n", "}", "\n\n", "getInternalAddr", ":=", "func", "(", "addresses", "[", "]", "network", ".", "Address", ")", "(", "network", ".", "Address", ",", "bool", ")", "{", "return", "network", ".", "SelectInternalAddress", "(", "addresses", ",", "false", ")", "\n", "}", "\n\n", "var", "addrMatch", "func", "(", "[", "]", "network", ".", "Address", ")", "(", "network", ".", "Address", ",", "bool", ")", "\n", "switch", "scope", "{", "case", "\"", "\"", ":", "addrMatch", "=", "getStrictPublicAddr", "\n", "case", "\"", "\"", ":", "addrMatch", "=", "getInternalAddr", "\n", "default", ":", "return", "network", ".", "Address", "{", "}", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "scope", ")", "\n", "}", "\n\n", "addr", ",", "found", ":=", "addrMatch", "(", "addresses", ")", "\n", "if", "!", "found", "{", "return", "network", ".", "Address", "{", "}", ",", "network", ".", "NoAddressError", "(", "scope", ")", "\n", "}", "\n", "return", "addr", ",", "nil", "\n", "}" ]
// serviceAddress returns the address of the service // managing the pods in which the unit workload is running.
[ "serviceAddress", "returns", "the", "address", "of", "the", "service", "managing", "the", "pods", "in", "which", "the", "unit", "workload", "is", "running", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1259-L1293
156,920
juju/juju
state/unit.go
AvailabilityZone
func (u *Unit) AvailabilityZone() (string, error) { m, err := u.machine() if err != nil { return "", errors.Trace(err) } return m.AvailabilityZone() }
go
func (u *Unit) AvailabilityZone() (string, error) { m, err := u.machine() if err != nil { return "", errors.Trace(err) } return m.AvailabilityZone() }
[ "func", "(", "u", "*", "Unit", ")", "AvailabilityZone", "(", ")", "(", "string", ",", "error", ")", "{", "m", ",", "err", ":=", "u", ".", "machine", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "m", ".", "AvailabilityZone", "(", ")", "\n", "}" ]
// AvailabilityZone returns the name of the availability zone into which // the unit's machine instance was provisioned.
[ "AvailabilityZone", "returns", "the", "name", "of", "the", "availability", "zone", "into", "which", "the", "unit", "s", "machine", "instance", "was", "provisioned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1297-L1303
156,921
juju/juju
state/unit.go
Refresh
func (u *Unit) Refresh() error { units, closer := u.st.db().GetCollection(unitsC) defer closer() err := units.FindId(u.doc.DocID).One(&u.doc) if err == mgo.ErrNotFound { return errors.NotFoundf("unit %q", u) } if err != nil { return fmt.Errorf("cannot refresh unit %q: %v", u, err) } return nil }
go
func (u *Unit) Refresh() error { units, closer := u.st.db().GetCollection(unitsC) defer closer() err := units.FindId(u.doc.DocID).One(&u.doc) if err == mgo.ErrNotFound { return errors.NotFoundf("unit %q", u) } if err != nil { return fmt.Errorf("cannot refresh unit %q: %v", u, err) } return nil }
[ "func", "(", "u", "*", "Unit", ")", "Refresh", "(", ")", "error", "{", "units", ",", "closer", ":=", "u", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "unitsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "err", ":=", "units", ".", "FindId", "(", "u", ".", "doc", ".", "DocID", ")", ".", "One", "(", "&", "u", ".", "doc", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "u", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "u", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Refresh refreshes the contents of the Unit from the underlying // state. It an error that satisfies errors.IsNotFound if the unit has // been removed.
[ "Refresh", "refreshes", "the", "contents", "of", "the", "Unit", "from", "the", "underlying", "state", ".", "It", "an", "error", "that", "satisfies", "errors", ".", "IsNotFound", "if", "the", "unit", "has", "been", "removed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1308-L1320
156,922
juju/juju
state/unit.go
Agent
func (u *Unit) Agent() *UnitAgent { return newUnitAgent(u.st, u.Tag(), u.Name()) }
go
func (u *Unit) Agent() *UnitAgent { return newUnitAgent(u.st, u.Tag(), u.Name()) }
[ "func", "(", "u", "*", "Unit", ")", "Agent", "(", ")", "*", "UnitAgent", "{", "return", "newUnitAgent", "(", "u", ".", "st", ",", "u", ".", "Tag", "(", ")", ",", "u", ".", "Name", "(", ")", ")", "\n", "}" ]
// Agent Returns an agent by its unit's name.
[ "Agent", "Returns", "an", "agent", "by", "its", "unit", "s", "name", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1323-L1325
156,923
juju/juju
state/unit.go
SetAgentStatus
func (u *Unit) SetAgentStatus(agentStatus status.StatusInfo) error { agent := newUnitAgent(u.st, u.Tag(), u.Name()) s := status.StatusInfo{ Status: agentStatus.Status, Message: agentStatus.Message, Data: agentStatus.Data, Since: agentStatus.Since, } return agent.SetStatus(s) }
go
func (u *Unit) SetAgentStatus(agentStatus status.StatusInfo) error { agent := newUnitAgent(u.st, u.Tag(), u.Name()) s := status.StatusInfo{ Status: agentStatus.Status, Message: agentStatus.Message, Data: agentStatus.Data, Since: agentStatus.Since, } return agent.SetStatus(s) }
[ "func", "(", "u", "*", "Unit", ")", "SetAgentStatus", "(", "agentStatus", "status", ".", "StatusInfo", ")", "error", "{", "agent", ":=", "newUnitAgent", "(", "u", ".", "st", ",", "u", ".", "Tag", "(", ")", ",", "u", ".", "Name", "(", ")", ")", "\n", "s", ":=", "status", ".", "StatusInfo", "{", "Status", ":", "agentStatus", ".", "Status", ",", "Message", ":", "agentStatus", ".", "Message", ",", "Data", ":", "agentStatus", ".", "Data", ",", "Since", ":", "agentStatus", ".", "Since", ",", "}", "\n", "return", "agent", ".", "SetStatus", "(", "s", ")", "\n", "}" ]
// SetAgentStatus calls SetStatus for this unit's agent, this call // is equivalent to the former call to SetStatus when Agent and Unit // where not separate entities.
[ "SetAgentStatus", "calls", "SetStatus", "for", "this", "unit", "s", "agent", "this", "call", "is", "equivalent", "to", "the", "former", "call", "to", "SetStatus", "when", "Agent", "and", "Unit", "where", "not", "separate", "entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1336-L1345
156,924
juju/juju
state/unit.go
AgentStatus
func (u *Unit) AgentStatus() (status.StatusInfo, error) { agent := newUnitAgent(u.st, u.Tag(), u.Name()) return agent.Status() }
go
func (u *Unit) AgentStatus() (status.StatusInfo, error) { agent := newUnitAgent(u.st, u.Tag(), u.Name()) return agent.Status() }
[ "func", "(", "u", "*", "Unit", ")", "AgentStatus", "(", ")", "(", "status", ".", "StatusInfo", ",", "error", ")", "{", "agent", ":=", "newUnitAgent", "(", "u", ".", "st", ",", "u", ".", "Tag", "(", ")", ",", "u", ".", "Name", "(", ")", ")", "\n", "return", "agent", ".", "Status", "(", ")", "\n", "}" ]
// AgentStatus calls Status for this unit's agent, this call // is equivalent to the former call to Status when Agent and Unit // where not separate entities.
[ "AgentStatus", "calls", "Status", "for", "this", "unit", "s", "agent", "this", "call", "is", "equivalent", "to", "the", "former", "call", "to", "Status", "when", "Agent", "and", "Unit", "where", "not", "separate", "entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1350-L1353
156,925
juju/juju
state/unit.go
Status
func (u *Unit) Status() (status.StatusInfo, error) { // The current health spec says when a hook error occurs, the workload should // be in error state, but the state model more correctly records the agent // itself as being in error. So we'll do that model translation here. // TODO(fwereade) as on unitagent, this transformation does not belong here. // For now, pretend we're always reading the unit status. info, err := getStatus(u.st.db(), u.globalAgentKey(), "unit") if err != nil { return status.StatusInfo{}, err } if info.Status != status.Error { info, err = getStatus(u.st.db(), u.globalKey(), "unit") if err != nil { return status.StatusInfo{}, err } } return info, nil }
go
func (u *Unit) Status() (status.StatusInfo, error) { // The current health spec says when a hook error occurs, the workload should // be in error state, but the state model more correctly records the agent // itself as being in error. So we'll do that model translation here. // TODO(fwereade) as on unitagent, this transformation does not belong here. // For now, pretend we're always reading the unit status. info, err := getStatus(u.st.db(), u.globalAgentKey(), "unit") if err != nil { return status.StatusInfo{}, err } if info.Status != status.Error { info, err = getStatus(u.st.db(), u.globalKey(), "unit") if err != nil { return status.StatusInfo{}, err } } return info, nil }
[ "func", "(", "u", "*", "Unit", ")", "Status", "(", ")", "(", "status", ".", "StatusInfo", ",", "error", ")", "{", "// The current health spec says when a hook error occurs, the workload should", "// be in error state, but the state model more correctly records the agent", "// itself as being in error. So we'll do that model translation here.", "// TODO(fwereade) as on unitagent, this transformation does not belong here.", "// For now, pretend we're always reading the unit status.", "info", ",", "err", ":=", "getStatus", "(", "u", ".", "st", ".", "db", "(", ")", ",", "u", ".", "globalAgentKey", "(", ")", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ".", "StatusInfo", "{", "}", ",", "err", "\n", "}", "\n", "if", "info", ".", "Status", "!=", "status", ".", "Error", "{", "info", ",", "err", "=", "getStatus", "(", "u", ".", "st", ".", "db", "(", ")", ",", "u", ".", "globalKey", "(", ")", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ".", "StatusInfo", "{", "}", ",", "err", "\n", "}", "\n", "}", "\n", "return", "info", ",", "nil", "\n", "}" ]
// Status returns the status of the unit. // This method relies on globalKey instead of globalAgentKey since it is part of // the effort to separate Unit from UnitAgent. Now the Status for UnitAgent is in // the UnitAgent struct.
[ "Status", "returns", "the", "status", "of", "the", "unit", ".", "This", "method", "relies", "on", "globalKey", "instead", "of", "globalAgentKey", "since", "it", "is", "part", "of", "the", "effort", "to", "separate", "Unit", "from", "UnitAgent", ".", "Now", "the", "Status", "for", "UnitAgent", "is", "in", "the", "UnitAgent", "struct", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1371-L1388
156,926
juju/juju
state/unit.go
SetStatus
func (u *Unit) SetStatus(unitStatus status.StatusInfo) error { if !status.ValidWorkloadStatus(unitStatus.Status) { return errors.Errorf("cannot set invalid status %q", unitStatus.Status) } var newHistory *statusDoc if u.modelType == ModelTypeCAAS { // Caas Charms currently have no way to query workload status; // Cloud container status might contradict what the charm is // attempting to set, make sure the right history is set. cloudContainerStatus, err := getStatus(u.st.db(), globalCloudContainerKey(u.Name()), "cloud container") if err != nil { if !errors.IsNotFound(err) { return errors.Trace(err) } } expectWorkload, err := expectWorkload(u.st, u.ApplicationName()) if err != nil { return errors.Trace(err) } newHistory, err = caasHistoryRewriteDoc(unitStatus, cloudContainerStatus, expectWorkload, caasUnitDisplayStatus, u.st.clock()) if err != nil { return errors.Trace(err) } } return setStatus(u.st.db(), setStatusParams{ badge: "unit", globalKey: u.globalKey(), status: unitStatus.Status, message: unitStatus.Message, rawData: unitStatus.Data, updated: timeOrNow(unitStatus.Since, u.st.clock()), historyOverwrite: newHistory, }) }
go
func (u *Unit) SetStatus(unitStatus status.StatusInfo) error { if !status.ValidWorkloadStatus(unitStatus.Status) { return errors.Errorf("cannot set invalid status %q", unitStatus.Status) } var newHistory *statusDoc if u.modelType == ModelTypeCAAS { // Caas Charms currently have no way to query workload status; // Cloud container status might contradict what the charm is // attempting to set, make sure the right history is set. cloudContainerStatus, err := getStatus(u.st.db(), globalCloudContainerKey(u.Name()), "cloud container") if err != nil { if !errors.IsNotFound(err) { return errors.Trace(err) } } expectWorkload, err := expectWorkload(u.st, u.ApplicationName()) if err != nil { return errors.Trace(err) } newHistory, err = caasHistoryRewriteDoc(unitStatus, cloudContainerStatus, expectWorkload, caasUnitDisplayStatus, u.st.clock()) if err != nil { return errors.Trace(err) } } return setStatus(u.st.db(), setStatusParams{ badge: "unit", globalKey: u.globalKey(), status: unitStatus.Status, message: unitStatus.Message, rawData: unitStatus.Data, updated: timeOrNow(unitStatus.Since, u.st.clock()), historyOverwrite: newHistory, }) }
[ "func", "(", "u", "*", "Unit", ")", "SetStatus", "(", "unitStatus", "status", ".", "StatusInfo", ")", "error", "{", "if", "!", "status", ".", "ValidWorkloadStatus", "(", "unitStatus", ".", "Status", ")", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "unitStatus", ".", "Status", ")", "\n", "}", "\n\n", "var", "newHistory", "*", "statusDoc", "\n", "if", "u", ".", "modelType", "==", "ModelTypeCAAS", "{", "// Caas Charms currently have no way to query workload status;", "// Cloud container status might contradict what the charm is", "// attempting to set, make sure the right history is set.", "cloudContainerStatus", ",", "err", ":=", "getStatus", "(", "u", ".", "st", ".", "db", "(", ")", ",", "globalCloudContainerKey", "(", "u", ".", "Name", "(", ")", ")", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "expectWorkload", ",", "err", ":=", "expectWorkload", "(", "u", ".", "st", ",", "u", ".", "ApplicationName", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "newHistory", ",", "err", "=", "caasHistoryRewriteDoc", "(", "unitStatus", ",", "cloudContainerStatus", ",", "expectWorkload", ",", "caasUnitDisplayStatus", ",", "u", ".", "st", ".", "clock", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "setStatus", "(", "u", ".", "st", ".", "db", "(", ")", ",", "setStatusParams", "{", "badge", ":", "\"", "\"", ",", "globalKey", ":", "u", ".", "globalKey", "(", ")", ",", "status", ":", "unitStatus", ".", "Status", ",", "message", ":", "unitStatus", ".", "Message", ",", "rawData", ":", "unitStatus", ".", "Data", ",", "updated", ":", "timeOrNow", "(", "unitStatus", ".", "Since", ",", "u", ".", "st", ".", "clock", "(", ")", ")", ",", "historyOverwrite", ":", "newHistory", ",", "}", ")", "\n", "}" ]
// SetStatus sets the status of the unit agent. The optional values // allow to pass additional helpful status data. // This method relies on globalKey instead of globalAgentKey since it is part of // the effort to separate Unit from UnitAgent. Now the SetStatus for UnitAgent is in // the UnitAgent struct.
[ "SetStatus", "sets", "the", "status", "of", "the", "unit", "agent", ".", "The", "optional", "values", "allow", "to", "pass", "additional", "helpful", "status", "data", ".", "This", "method", "relies", "on", "globalKey", "instead", "of", "globalAgentKey", "since", "it", "is", "part", "of", "the", "effort", "to", "separate", "Unit", "from", "UnitAgent", ".", "Now", "the", "SetStatus", "for", "UnitAgent", "is", "in", "the", "UnitAgent", "struct", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1395-L1430
156,927
juju/juju
state/unit.go
OpenPortsOnSubnet
func (u *Unit) OpenPortsOnSubnet(subnetID, protocol string, fromPort, toPort int) (err error) { ports, err := NewPortRange(u.Name(), fromPort, toPort, protocol) if err != nil { return errors.Annotatef(err, "invalid port range %v-%v/%v", fromPort, toPort, protocol) } defer errors.DeferredAnnotatef(&err, "cannot open ports %v for unit %q on subnet %q", ports, u, subnetID) machineID, err := u.AssignedMachineId() if err != nil { return errors.Annotatef(err, "unit %q has no assigned machine", u) } if err := u.checkSubnetAliveWhenSet(subnetID); err != nil { return errors.Trace(err) } machinePorts, err := getOrCreatePorts(u.st, machineID, subnetID) if err != nil { return errors.Annotate(err, "cannot get or create ports") } return machinePorts.OpenPorts(ports) }
go
func (u *Unit) OpenPortsOnSubnet(subnetID, protocol string, fromPort, toPort int) (err error) { ports, err := NewPortRange(u.Name(), fromPort, toPort, protocol) if err != nil { return errors.Annotatef(err, "invalid port range %v-%v/%v", fromPort, toPort, protocol) } defer errors.DeferredAnnotatef(&err, "cannot open ports %v for unit %q on subnet %q", ports, u, subnetID) machineID, err := u.AssignedMachineId() if err != nil { return errors.Annotatef(err, "unit %q has no assigned machine", u) } if err := u.checkSubnetAliveWhenSet(subnetID); err != nil { return errors.Trace(err) } machinePorts, err := getOrCreatePorts(u.st, machineID, subnetID) if err != nil { return errors.Annotate(err, "cannot get or create ports") } return machinePorts.OpenPorts(ports) }
[ "func", "(", "u", "*", "Unit", ")", "OpenPortsOnSubnet", "(", "subnetID", ",", "protocol", "string", ",", "fromPort", ",", "toPort", "int", ")", "(", "err", "error", ")", "{", "ports", ",", "err", ":=", "NewPortRange", "(", "u", ".", "Name", "(", ")", ",", "fromPort", ",", "toPort", ",", "protocol", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "fromPort", ",", "toPort", ",", "protocol", ")", "\n", "}", "\n", "defer", "errors", ".", "DeferredAnnotatef", "(", "&", "err", ",", "\"", "\"", ",", "ports", ",", "u", ",", "subnetID", ")", "\n\n", "machineID", ",", "err", ":=", "u", ".", "AssignedMachineId", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "u", ")", "\n", "}", "\n\n", "if", "err", ":=", "u", ".", "checkSubnetAliveWhenSet", "(", "subnetID", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "machinePorts", ",", "err", ":=", "getOrCreatePorts", "(", "u", ".", "st", ",", "machineID", ",", "subnetID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "machinePorts", ".", "OpenPorts", "(", "ports", ")", "\n", "}" ]
// OpenPortsOnSubnet opens the given port range and protocol for the unit on the // given subnet, which can be empty. When non-empty, subnetID must refer to an // existing, alive subnet, otherwise an error is returned. Returns an error if // opening the requested range conflicts with another already opened range on // the same subnet and and the unit's assigned machine.
[ "OpenPortsOnSubnet", "opens", "the", "given", "port", "range", "and", "protocol", "for", "the", "unit", "on", "the", "given", "subnet", "which", "can", "be", "empty", ".", "When", "non", "-", "empty", "subnetID", "must", "refer", "to", "an", "existing", "alive", "subnet", "otherwise", "an", "error", "is", "returned", ".", "Returns", "an", "error", "if", "opening", "the", "requested", "range", "conflicts", "with", "another", "already", "opened", "range", "on", "the", "same", "subnet", "and", "and", "the", "unit", "s", "assigned", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1437-L1459
156,928
juju/juju
state/unit.go
OpenPortOnSubnet
func (u *Unit) OpenPortOnSubnet(subnetID, protocol string, number int) error { return u.OpenPortsOnSubnet(subnetID, protocol, number, number) }
go
func (u *Unit) OpenPortOnSubnet(subnetID, protocol string, number int) error { return u.OpenPortsOnSubnet(subnetID, protocol, number, number) }
[ "func", "(", "u", "*", "Unit", ")", "OpenPortOnSubnet", "(", "subnetID", ",", "protocol", "string", ",", "number", "int", ")", "error", "{", "return", "u", ".", "OpenPortsOnSubnet", "(", "subnetID", ",", "protocol", ",", "number", ",", "number", ")", "\n", "}" ]
// OpenPortOnSubnet opens the given port and protocol for the unit on the given // subnet, which can be empty. When non-empty, subnetID must refer to an // existing, alive subnet, otherwise an error is returned.
[ "OpenPortOnSubnet", "opens", "the", "given", "port", "and", "protocol", "for", "the", "unit", "on", "the", "given", "subnet", "which", "can", "be", "empty", ".", "When", "non", "-", "empty", "subnetID", "must", "refer", "to", "an", "existing", "alive", "subnet", "otherwise", "an", "error", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1525-L1527
156,929
juju/juju
state/unit.go
ClosePortOnSubnet
func (u *Unit) ClosePortOnSubnet(subnetID, protocol string, number int) error { return u.ClosePortsOnSubnet(subnetID, protocol, number, number) }
go
func (u *Unit) ClosePortOnSubnet(subnetID, protocol string, number int) error { return u.ClosePortsOnSubnet(subnetID, protocol, number, number) }
[ "func", "(", "u", "*", "Unit", ")", "ClosePortOnSubnet", "(", "subnetID", ",", "protocol", "string", ",", "number", "int", ")", "error", "{", "return", "u", ".", "ClosePortsOnSubnet", "(", "subnetID", ",", "protocol", ",", "number", ",", "number", ")", "\n", "}" ]
// ClosePortOnSubnet closes the given port and protocol for the unit on the given // subnet, which can be empty. When non-empty, subnetID must refer to an // existing, alive subnet, otherwise an error is returned.
[ "ClosePortOnSubnet", "closes", "the", "given", "port", "and", "protocol", "for", "the", "unit", "on", "the", "given", "subnet", "which", "can", "be", "empty", ".", "When", "non", "-", "empty", "subnetID", "must", "refer", "to", "an", "existing", "alive", "subnet", "otherwise", "an", "error", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1532-L1534
156,930
juju/juju
state/unit.go
OpenedPortsOnSubnet
func (u *Unit) OpenedPortsOnSubnet(subnetID string) ([]corenetwork.PortRange, error) { machineID, err := u.AssignedMachineId() if err != nil { return nil, errors.Annotatef(err, "unit %q has no assigned machine", u) } if err := u.checkSubnetAliveWhenSet(subnetID); err != nil { return nil, errors.Trace(err) } machinePorts, err := getPorts(u.st, machineID, subnetID) var result []corenetwork.PortRange if errors.IsNotFound(err) { return result, nil } else if err != nil { return nil, errors.Annotatef(err, "failed getting ports for unit %q, subnet %q", u, subnetID) } ports := machinePorts.PortsForUnit(u.Name()) for _, port := range ports { result = append(result, corenetwork.PortRange{ Protocol: port.Protocol, FromPort: port.FromPort, ToPort: port.ToPort, }) } corenetwork.SortPortRanges(result) return result, nil }
go
func (u *Unit) OpenedPortsOnSubnet(subnetID string) ([]corenetwork.PortRange, error) { machineID, err := u.AssignedMachineId() if err != nil { return nil, errors.Annotatef(err, "unit %q has no assigned machine", u) } if err := u.checkSubnetAliveWhenSet(subnetID); err != nil { return nil, errors.Trace(err) } machinePorts, err := getPorts(u.st, machineID, subnetID) var result []corenetwork.PortRange if errors.IsNotFound(err) { return result, nil } else if err != nil { return nil, errors.Annotatef(err, "failed getting ports for unit %q, subnet %q", u, subnetID) } ports := machinePorts.PortsForUnit(u.Name()) for _, port := range ports { result = append(result, corenetwork.PortRange{ Protocol: port.Protocol, FromPort: port.FromPort, ToPort: port.ToPort, }) } corenetwork.SortPortRanges(result) return result, nil }
[ "func", "(", "u", "*", "Unit", ")", "OpenedPortsOnSubnet", "(", "subnetID", "string", ")", "(", "[", "]", "corenetwork", ".", "PortRange", ",", "error", ")", "{", "machineID", ",", "err", ":=", "u", ".", "AssignedMachineId", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "u", ")", "\n", "}", "\n\n", "if", "err", ":=", "u", ".", "checkSubnetAliveWhenSet", "(", "subnetID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "machinePorts", ",", "err", ":=", "getPorts", "(", "u", ".", "st", ",", "machineID", ",", "subnetID", ")", "\n", "var", "result", "[", "]", "corenetwork", ".", "PortRange", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "result", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "u", ",", "subnetID", ")", "\n", "}", "\n", "ports", ":=", "machinePorts", ".", "PortsForUnit", "(", "u", ".", "Name", "(", ")", ")", "\n", "for", "_", ",", "port", ":=", "range", "ports", "{", "result", "=", "append", "(", "result", ",", "corenetwork", ".", "PortRange", "{", "Protocol", ":", "port", ".", "Protocol", ",", "FromPort", ":", "port", ".", "FromPort", ",", "ToPort", ":", "port", ".", "ToPort", ",", "}", ")", "\n", "}", "\n", "corenetwork", ".", "SortPortRanges", "(", "result", ")", "\n", "return", "result", ",", "nil", "\n", "}" ]
// OpenedPortsOnSubnet returns a slice containing the open port ranges of the // unit on the given subnet ID, which can be empty. When subnetID is not empty, // it must refer to an existing, alive subnet, otherwise an error is returned. // Also, when no ports are yet open for the unit on that subnet, no error and // empty slice is returned.
[ "OpenedPortsOnSubnet", "returns", "a", "slice", "containing", "the", "open", "port", "ranges", "of", "the", "unit", "on", "the", "given", "subnet", "ID", "which", "can", "be", "empty", ".", "When", "subnetID", "is", "not", "empty", "it", "must", "refer", "to", "an", "existing", "alive", "subnet", "otherwise", "an", "error", "is", "returned", ".", "Also", "when", "no", "ports", "are", "yet", "open", "for", "the", "unit", "on", "that", "subnet", "no", "error", "and", "empty", "slice", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1557-L1584
156,931
juju/juju
state/unit.go
CharmURL
func (u *Unit) CharmURL() (*charm.URL, bool) { if u.doc.CharmURL == nil { return nil, false } return u.doc.CharmURL, true }
go
func (u *Unit) CharmURL() (*charm.URL, bool) { if u.doc.CharmURL == nil { return nil, false } return u.doc.CharmURL, true }
[ "func", "(", "u", "*", "Unit", ")", "CharmURL", "(", ")", "(", "*", "charm", ".", "URL", ",", "bool", ")", "{", "if", "u", ".", "doc", ".", "CharmURL", "==", "nil", "{", "return", "nil", ",", "false", "\n", "}", "\n", "return", "u", ".", "doc", ".", "CharmURL", ",", "true", "\n", "}" ]
// CharmURL returns the charm URL this unit is currently using.
[ "CharmURL", "returns", "the", "charm", "URL", "this", "unit", "is", "currently", "using", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1596-L1601
156,932
juju/juju
state/unit.go
charm
func (u *Unit) charm() (*Charm, error) { curl, ok := u.CharmURL() if !ok { app, err := u.Application() if err != nil { return nil, err } curl = app.doc.CharmURL } ch, err := u.st.Charm(curl) return ch, errors.Annotatef(err, "getting charm for %s", u) }
go
func (u *Unit) charm() (*Charm, error) { curl, ok := u.CharmURL() if !ok { app, err := u.Application() if err != nil { return nil, err } curl = app.doc.CharmURL } ch, err := u.st.Charm(curl) return ch, errors.Annotatef(err, "getting charm for %s", u) }
[ "func", "(", "u", "*", "Unit", ")", "charm", "(", ")", "(", "*", "Charm", ",", "error", ")", "{", "curl", ",", "ok", ":=", "u", ".", "CharmURL", "(", ")", "\n", "if", "!", "ok", "{", "app", ",", "err", ":=", "u", ".", "Application", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "curl", "=", "app", ".", "doc", ".", "CharmURL", "\n", "}", "\n", "ch", ",", "err", ":=", "u", ".", "st", ".", "Charm", "(", "curl", ")", "\n", "return", "ch", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "u", ")", "\n", "}" ]
// charm returns the charm for the unit, or the application if the unit's charm // has not been set yet.
[ "charm", "returns", "the", "charm", "for", "the", "unit", "or", "the", "application", "if", "the", "unit", "s", "charm", "has", "not", "been", "set", "yet", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1683-L1694
156,933
juju/juju
state/unit.go
assertCharmOps
func (u *Unit) assertCharmOps(ch *Charm) []txn.Op { ops := []txn.Op{{ C: unitsC, Id: u.doc.Name, Assert: bson.D{{"charmurl", u.doc.CharmURL}}, }} if _, ok := u.CharmURL(); !ok { appName := u.ApplicationName() ops = append(ops, txn.Op{ C: applicationsC, Id: appName, Assert: bson.D{{"charmurl", ch.URL()}}, }) } return ops }
go
func (u *Unit) assertCharmOps(ch *Charm) []txn.Op { ops := []txn.Op{{ C: unitsC, Id: u.doc.Name, Assert: bson.D{{"charmurl", u.doc.CharmURL}}, }} if _, ok := u.CharmURL(); !ok { appName := u.ApplicationName() ops = append(ops, txn.Op{ C: applicationsC, Id: appName, Assert: bson.D{{"charmurl", ch.URL()}}, }) } return ops }
[ "func", "(", "u", "*", "Unit", ")", "assertCharmOps", "(", "ch", "*", "Charm", ")", "[", "]", "txn", ".", "Op", "{", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "unitsC", ",", "Id", ":", "u", ".", "doc", ".", "Name", ",", "Assert", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "u", ".", "doc", ".", "CharmURL", "}", "}", ",", "}", "}", "\n", "if", "_", ",", "ok", ":=", "u", ".", "CharmURL", "(", ")", ";", "!", "ok", "{", "appName", ":=", "u", ".", "ApplicationName", "(", ")", "\n", "ops", "=", "append", "(", "ops", ",", "txn", ".", "Op", "{", "C", ":", "applicationsC", ",", "Id", ":", "appName", ",", "Assert", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "ch", ".", "URL", "(", ")", "}", "}", ",", "}", ")", "\n", "}", "\n", "return", "ops", "\n", "}" ]
// assertCharmOps returns txn.Ops to assert the current charm of the unit. // If the unit currently has no charm URL set, then the application's charm // URL will be checked by the txn.Ops also.
[ "assertCharmOps", "returns", "txn", ".", "Ops", "to", "assert", "the", "current", "charm", "of", "the", "unit", ".", "If", "the", "unit", "currently", "has", "no", "charm", "URL", "set", "then", "the", "application", "s", "charm", "URL", "will", "be", "checked", "by", "the", "txn", ".", "Ops", "also", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1699-L1714
156,934
juju/juju
state/unit.go
WaitAgentPresence
func (u *Unit) WaitAgentPresence(timeout time.Duration) (err error) { defer errors.DeferredAnnotatef(&err, "waiting for agent of unit %q", u) ch := make(chan presence.Change) pwatcher := u.st.workers.presenceWatcher() pwatcher.Watch(u.globalAgentKey(), ch) defer pwatcher.Unwatch(u.globalAgentKey(), ch) pingBatcher := u.st.getPingBatcher() if err := pingBatcher.Sync(); err != nil { return err } for i := 0; i < 2; i++ { select { case change := <-ch: if change.Alive { return nil } case <-time.After(timeout): // TODO(fwereade): 2016-03-17 lp:1558657 return fmt.Errorf("still not alive after timeout") case <-pwatcher.Dead(): return pwatcher.Err() } } panic(fmt.Sprintf("presence reported dead status twice in a row for unit %q", u)) }
go
func (u *Unit) WaitAgentPresence(timeout time.Duration) (err error) { defer errors.DeferredAnnotatef(&err, "waiting for agent of unit %q", u) ch := make(chan presence.Change) pwatcher := u.st.workers.presenceWatcher() pwatcher.Watch(u.globalAgentKey(), ch) defer pwatcher.Unwatch(u.globalAgentKey(), ch) pingBatcher := u.st.getPingBatcher() if err := pingBatcher.Sync(); err != nil { return err } for i := 0; i < 2; i++ { select { case change := <-ch: if change.Alive { return nil } case <-time.After(timeout): // TODO(fwereade): 2016-03-17 lp:1558657 return fmt.Errorf("still not alive after timeout") case <-pwatcher.Dead(): return pwatcher.Err() } } panic(fmt.Sprintf("presence reported dead status twice in a row for unit %q", u)) }
[ "func", "(", "u", "*", "Unit", ")", "WaitAgentPresence", "(", "timeout", "time", ".", "Duration", ")", "(", "err", "error", ")", "{", "defer", "errors", ".", "DeferredAnnotatef", "(", "&", "err", ",", "\"", "\"", ",", "u", ")", "\n", "ch", ":=", "make", "(", "chan", "presence", ".", "Change", ")", "\n", "pwatcher", ":=", "u", ".", "st", ".", "workers", ".", "presenceWatcher", "(", ")", "\n", "pwatcher", ".", "Watch", "(", "u", ".", "globalAgentKey", "(", ")", ",", "ch", ")", "\n", "defer", "pwatcher", ".", "Unwatch", "(", "u", ".", "globalAgentKey", "(", ")", ",", "ch", ")", "\n", "pingBatcher", ":=", "u", ".", "st", ".", "getPingBatcher", "(", ")", "\n", "if", "err", ":=", "pingBatcher", ".", "Sync", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "2", ";", "i", "++", "{", "select", "{", "case", "change", ":=", "<-", "ch", ":", "if", "change", ".", "Alive", "{", "return", "nil", "\n", "}", "\n", "case", "<-", "time", ".", "After", "(", "timeout", ")", ":", "// TODO(fwereade): 2016-03-17 lp:1558657", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "<-", "pwatcher", ".", "Dead", "(", ")", ":", "return", "pwatcher", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "u", ")", ")", "\n", "}" ]
// WaitAgentPresence blocks until the respective agent is alive. // This should really only be used in the test suite.
[ "WaitAgentPresence", "blocks", "until", "the", "respective", "agent", "is", "alive", ".", "This", "should", "really", "only", "be", "used", "in", "the", "test", "suite", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1750-L1774
156,935
juju/juju
state/unit.go
SetAgentPresence
func (u *Unit) SetAgentPresence() (*presence.Pinger, error) { presenceCollection := u.st.getPresenceCollection() recorder := u.st.getPingBatcher() m, err := u.st.Model() if err != nil { return nil, errors.Trace(err) } p := presence.NewPinger(presenceCollection, m.ModelTag(), u.globalAgentKey(), func() presence.PingRecorder { return u.st.getPingBatcher() }) err = p.Start() if err != nil { return nil, err } // Make sure this Agent status is written to the database before returning. recorder.Sync() return p, nil }
go
func (u *Unit) SetAgentPresence() (*presence.Pinger, error) { presenceCollection := u.st.getPresenceCollection() recorder := u.st.getPingBatcher() m, err := u.st.Model() if err != nil { return nil, errors.Trace(err) } p := presence.NewPinger(presenceCollection, m.ModelTag(), u.globalAgentKey(), func() presence.PingRecorder { return u.st.getPingBatcher() }) err = p.Start() if err != nil { return nil, err } // Make sure this Agent status is written to the database before returning. recorder.Sync() return p, nil }
[ "func", "(", "u", "*", "Unit", ")", "SetAgentPresence", "(", ")", "(", "*", "presence", ".", "Pinger", ",", "error", ")", "{", "presenceCollection", ":=", "u", ".", "st", ".", "getPresenceCollection", "(", ")", "\n", "recorder", ":=", "u", ".", "st", ".", "getPingBatcher", "(", ")", "\n", "m", ",", "err", ":=", "u", ".", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "p", ":=", "presence", ".", "NewPinger", "(", "presenceCollection", ",", "m", ".", "ModelTag", "(", ")", ",", "u", ".", "globalAgentKey", "(", ")", ",", "func", "(", ")", "presence", ".", "PingRecorder", "{", "return", "u", ".", "st", ".", "getPingBatcher", "(", ")", "}", ")", "\n", "err", "=", "p", ".", "Start", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Make sure this Agent status is written to the database before returning.", "recorder", ".", "Sync", "(", ")", "\n", "return", "p", ",", "nil", "\n", "}" ]
// SetAgentPresence signals that the agent for unit u is alive. // It returns the started pinger.
[ "SetAgentPresence", "signals", "that", "the", "agent", "for", "unit", "u", "is", "alive", ".", "It", "returns", "the", "started", "pinger", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1778-L1794
156,936
juju/juju
state/unit.go
AssignedMachineId
func (u *Unit) AssignedMachineId() (id string, err error) { if u.IsPrincipal() { if u.doc.MachineId == "" { return "", unitNotAssignedError(u) } return u.doc.MachineId, nil } units, closer := u.st.db().GetCollection(unitsC) defer closer() pudoc := unitDoc{} err = units.FindId(u.doc.Principal).One(&pudoc) if err == mgo.ErrNotFound { return "", errors.NotFoundf("principal unit %q of %q", u.doc.Principal, u) } else if err != nil { return "", err } if pudoc.MachineId == "" { return "", unitNotAssignedError(u) } return pudoc.MachineId, nil }
go
func (u *Unit) AssignedMachineId() (id string, err error) { if u.IsPrincipal() { if u.doc.MachineId == "" { return "", unitNotAssignedError(u) } return u.doc.MachineId, nil } units, closer := u.st.db().GetCollection(unitsC) defer closer() pudoc := unitDoc{} err = units.FindId(u.doc.Principal).One(&pudoc) if err == mgo.ErrNotFound { return "", errors.NotFoundf("principal unit %q of %q", u.doc.Principal, u) } else if err != nil { return "", err } if pudoc.MachineId == "" { return "", unitNotAssignedError(u) } return pudoc.MachineId, nil }
[ "func", "(", "u", "*", "Unit", ")", "AssignedMachineId", "(", ")", "(", "id", "string", ",", "err", "error", ")", "{", "if", "u", ".", "IsPrincipal", "(", ")", "{", "if", "u", ".", "doc", ".", "MachineId", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "unitNotAssignedError", "(", "u", ")", "\n", "}", "\n", "return", "u", ".", "doc", ".", "MachineId", ",", "nil", "\n", "}", "\n\n", "units", ",", "closer", ":=", "u", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "unitsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "pudoc", ":=", "unitDoc", "{", "}", "\n", "err", "=", "units", ".", "FindId", "(", "u", ".", "doc", ".", "Principal", ")", ".", "One", "(", "&", "pudoc", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "\"", "\"", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "u", ".", "doc", ".", "Principal", ",", "u", ")", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "pudoc", ".", "MachineId", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "unitNotAssignedError", "(", "u", ")", "\n", "}", "\n", "return", "pudoc", ".", "MachineId", ",", "nil", "\n", "}" ]
// AssignedMachineId returns the id of the assigned machine.
[ "AssignedMachineId", "returns", "the", "id", "of", "the", "assigned", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1802-L1824
156,937
juju/juju
state/unit.go
assignToMachine
func (u *Unit) assignToMachine(m *Machine, unused bool) (err error) { buildTxn := func(attempt int) ([]txn.Op, error) { u, m := u, m // don't change outer vars if attempt > 0 { var err error u, err = u.st.Unit(u.Name()) if err != nil { return nil, errors.Trace(err) } m, err = u.st.Machine(m.Id()) if err != nil { return nil, errors.Trace(err) } } return u.assignToMachineOps(m, unused) } if err := u.st.db().Run(buildTxn); err != nil { return errors.Trace(err) } u.doc.MachineId = m.doc.Id m.doc.Clean = false return nil }
go
func (u *Unit) assignToMachine(m *Machine, unused bool) (err error) { buildTxn := func(attempt int) ([]txn.Op, error) { u, m := u, m // don't change outer vars if attempt > 0 { var err error u, err = u.st.Unit(u.Name()) if err != nil { return nil, errors.Trace(err) } m, err = u.st.Machine(m.Id()) if err != nil { return nil, errors.Trace(err) } } return u.assignToMachineOps(m, unused) } if err := u.st.db().Run(buildTxn); err != nil { return errors.Trace(err) } u.doc.MachineId = m.doc.Id m.doc.Clean = false return nil }
[ "func", "(", "u", "*", "Unit", ")", "assignToMachine", "(", "m", "*", "Machine", ",", "unused", "bool", ")", "(", "err", "error", ")", "{", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "u", ",", "m", ":=", "u", ",", "m", "// don't change outer vars", "\n", "if", "attempt", ">", "0", "{", "var", "err", "error", "\n", "u", ",", "err", "=", "u", ".", "st", ".", "Unit", "(", "u", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "m", ",", "err", "=", "u", ".", "st", ".", "Machine", "(", "m", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "u", ".", "assignToMachineOps", "(", "m", ",", "unused", ")", "\n", "}", "\n", "if", "err", ":=", "u", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "u", ".", "doc", ".", "MachineId", "=", "m", ".", "doc", ".", "Id", "\n", "m", ".", "doc", ".", "Clean", "=", "false", "\n", "return", "nil", "\n", "}" ]
// assignToMachine is the internal version of AssignToMachine.
[ "assignToMachine", "is", "the", "internal", "version", "of", "AssignToMachine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1833-L1855
156,938
juju/juju
state/unit.go
validateUnitMachineAssignment
func validateUnitMachineAssignment( m *Machine, series string, isSubordinate bool, storagePools set.Strings, ) (err error) { if m.Life() != Alive { return machineNotAliveErr } if isSubordinate { return fmt.Errorf("unit is a subordinate") } if series != m.doc.Series { return fmt.Errorf("series does not match") } canHost := false for _, j := range m.doc.Jobs { if j == JobHostUnits { canHost = true break } } if !canHost { return fmt.Errorf("machine %q cannot host units", m) } sb, err := NewStorageBackend(m.st) if err != nil { return errors.Trace(err) } if err := validateDynamicMachineStoragePools(sb, m, storagePools); err != nil { return errors.Trace(err) } return nil }
go
func validateUnitMachineAssignment( m *Machine, series string, isSubordinate bool, storagePools set.Strings, ) (err error) { if m.Life() != Alive { return machineNotAliveErr } if isSubordinate { return fmt.Errorf("unit is a subordinate") } if series != m.doc.Series { return fmt.Errorf("series does not match") } canHost := false for _, j := range m.doc.Jobs { if j == JobHostUnits { canHost = true break } } if !canHost { return fmt.Errorf("machine %q cannot host units", m) } sb, err := NewStorageBackend(m.st) if err != nil { return errors.Trace(err) } if err := validateDynamicMachineStoragePools(sb, m, storagePools); err != nil { return errors.Trace(err) } return nil }
[ "func", "validateUnitMachineAssignment", "(", "m", "*", "Machine", ",", "series", "string", ",", "isSubordinate", "bool", ",", "storagePools", "set", ".", "Strings", ",", ")", "(", "err", "error", ")", "{", "if", "m", ".", "Life", "(", ")", "!=", "Alive", "{", "return", "machineNotAliveErr", "\n", "}", "\n", "if", "isSubordinate", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "series", "!=", "m", ".", "doc", ".", "Series", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "canHost", ":=", "false", "\n", "for", "_", ",", "j", ":=", "range", "m", ".", "doc", ".", "Jobs", "{", "if", "j", "==", "JobHostUnits", "{", "canHost", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "canHost", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "m", ")", "\n", "}", "\n", "sb", ",", "err", ":=", "NewStorageBackend", "(", "m", ".", "st", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "validateDynamicMachineStoragePools", "(", "sb", ",", "m", ",", "storagePools", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateUnitMachineAssignment validates the parameters for assigning a unit // to a specified machine.
[ "validateUnitMachineAssignment", "validates", "the", "parameters", "for", "assigning", "a", "unit", "to", "a", "specified", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1942-L1975
156,939
juju/juju
state/unit.go
validateDynamicMachineStorageParams
func validateDynamicMachineStorageParams(m *Machine, params *storageParams) error { sb, err := NewStorageBackend(m.st) if err != nil { return errors.Trace(err) } pools, err := storagePools(sb, params) if err != nil { return err } if err := validateDynamicMachineStoragePools(sb, m, pools); err != nil { return err } // Validate the volume/filesystem attachments for the machine. for volumeTag := range params.volumeAttachments { volume, err := getVolumeByTag(sb.mb, volumeTag) if err != nil { return errors.Trace(err) } if !volume.Detachable() && volume.doc.HostId != m.Id() { return errors.Errorf( "storage is non-detachable (bound to machine %s)", volume.doc.HostId, ) } } for filesystemTag := range params.filesystemAttachments { filesystem, err := getFilesystemByTag(sb.mb, filesystemTag) if err != nil { return errors.Trace(err) } if !filesystem.Detachable() && filesystem.doc.HostId != m.Id() { host := storageAttachmentHost(filesystem.doc.HostId) return errors.Errorf( "storage is non-detachable (bound to %s)", names.ReadableString(host), ) } } return nil }
go
func validateDynamicMachineStorageParams(m *Machine, params *storageParams) error { sb, err := NewStorageBackend(m.st) if err != nil { return errors.Trace(err) } pools, err := storagePools(sb, params) if err != nil { return err } if err := validateDynamicMachineStoragePools(sb, m, pools); err != nil { return err } // Validate the volume/filesystem attachments for the machine. for volumeTag := range params.volumeAttachments { volume, err := getVolumeByTag(sb.mb, volumeTag) if err != nil { return errors.Trace(err) } if !volume.Detachable() && volume.doc.HostId != m.Id() { return errors.Errorf( "storage is non-detachable (bound to machine %s)", volume.doc.HostId, ) } } for filesystemTag := range params.filesystemAttachments { filesystem, err := getFilesystemByTag(sb.mb, filesystemTag) if err != nil { return errors.Trace(err) } if !filesystem.Detachable() && filesystem.doc.HostId != m.Id() { host := storageAttachmentHost(filesystem.doc.HostId) return errors.Errorf( "storage is non-detachable (bound to %s)", names.ReadableString(host), ) } } return nil }
[ "func", "validateDynamicMachineStorageParams", "(", "m", "*", "Machine", ",", "params", "*", "storageParams", ")", "error", "{", "sb", ",", "err", ":=", "NewStorageBackend", "(", "m", ".", "st", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "pools", ",", "err", ":=", "storagePools", "(", "sb", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "validateDynamicMachineStoragePools", "(", "sb", ",", "m", ",", "pools", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Validate the volume/filesystem attachments for the machine.", "for", "volumeTag", ":=", "range", "params", ".", "volumeAttachments", "{", "volume", ",", "err", ":=", "getVolumeByTag", "(", "sb", ".", "mb", ",", "volumeTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "volume", ".", "Detachable", "(", ")", "&&", "volume", ".", "doc", ".", "HostId", "!=", "m", ".", "Id", "(", ")", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "volume", ".", "doc", ".", "HostId", ",", ")", "\n", "}", "\n", "}", "\n", "for", "filesystemTag", ":=", "range", "params", ".", "filesystemAttachments", "{", "filesystem", ",", "err", ":=", "getFilesystemByTag", "(", "sb", ".", "mb", ",", "filesystemTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "filesystem", ".", "Detachable", "(", ")", "&&", "filesystem", ".", "doc", ".", "HostId", "!=", "m", ".", "Id", "(", ")", "{", "host", ":=", "storageAttachmentHost", "(", "filesystem", ".", "doc", ".", "HostId", ")", "\n", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "names", ".", "ReadableString", "(", "host", ")", ",", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateDynamicMachineStorageParams validates that the provided machine // storage parameters are compatible with the specified machine.
[ "validateDynamicMachineStorageParams", "validates", "that", "the", "provided", "machine", "storage", "parameters", "are", "compatible", "with", "the", "specified", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L1979-L2018
156,940
juju/juju
state/unit.go
storagePools
func storagePools(sb *storageBackend, params *storageParams) (set.Strings, error) { pools := make(set.Strings) for _, v := range params.volumes { v, err := sb.volumeParamsWithDefaults(v.Volume) if err != nil { return nil, errors.Trace(err) } pools.Add(v.Pool) } for _, f := range params.filesystems { f, err := sb.filesystemParamsWithDefaults(f.Filesystem) if err != nil { return nil, errors.Trace(err) } pools.Add(f.Pool) } for volumeTag := range params.volumeAttachments { volume, err := sb.Volume(volumeTag) if err != nil { return nil, errors.Trace(err) } if params, ok := volume.Params(); ok { pools.Add(params.Pool) } else { info, err := volume.Info() if err != nil { return nil, errors.Trace(err) } pools.Add(info.Pool) } } for filesystemTag := range params.filesystemAttachments { filesystem, err := sb.Filesystem(filesystemTag) if err != nil { return nil, errors.Trace(err) } if params, ok := filesystem.Params(); ok { pools.Add(params.Pool) } else { info, err := filesystem.Info() if err != nil { return nil, errors.Trace(err) } pools.Add(info.Pool) } } return pools, nil }
go
func storagePools(sb *storageBackend, params *storageParams) (set.Strings, error) { pools := make(set.Strings) for _, v := range params.volumes { v, err := sb.volumeParamsWithDefaults(v.Volume) if err != nil { return nil, errors.Trace(err) } pools.Add(v.Pool) } for _, f := range params.filesystems { f, err := sb.filesystemParamsWithDefaults(f.Filesystem) if err != nil { return nil, errors.Trace(err) } pools.Add(f.Pool) } for volumeTag := range params.volumeAttachments { volume, err := sb.Volume(volumeTag) if err != nil { return nil, errors.Trace(err) } if params, ok := volume.Params(); ok { pools.Add(params.Pool) } else { info, err := volume.Info() if err != nil { return nil, errors.Trace(err) } pools.Add(info.Pool) } } for filesystemTag := range params.filesystemAttachments { filesystem, err := sb.Filesystem(filesystemTag) if err != nil { return nil, errors.Trace(err) } if params, ok := filesystem.Params(); ok { pools.Add(params.Pool) } else { info, err := filesystem.Info() if err != nil { return nil, errors.Trace(err) } pools.Add(info.Pool) } } return pools, nil }
[ "func", "storagePools", "(", "sb", "*", "storageBackend", ",", "params", "*", "storageParams", ")", "(", "set", ".", "Strings", ",", "error", ")", "{", "pools", ":=", "make", "(", "set", ".", "Strings", ")", "\n", "for", "_", ",", "v", ":=", "range", "params", ".", "volumes", "{", "v", ",", "err", ":=", "sb", ".", "volumeParamsWithDefaults", "(", "v", ".", "Volume", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "pools", ".", "Add", "(", "v", ".", "Pool", ")", "\n", "}", "\n", "for", "_", ",", "f", ":=", "range", "params", ".", "filesystems", "{", "f", ",", "err", ":=", "sb", ".", "filesystemParamsWithDefaults", "(", "f", ".", "Filesystem", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "pools", ".", "Add", "(", "f", ".", "Pool", ")", "\n", "}", "\n", "for", "volumeTag", ":=", "range", "params", ".", "volumeAttachments", "{", "volume", ",", "err", ":=", "sb", ".", "Volume", "(", "volumeTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "params", ",", "ok", ":=", "volume", ".", "Params", "(", ")", ";", "ok", "{", "pools", ".", "Add", "(", "params", ".", "Pool", ")", "\n", "}", "else", "{", "info", ",", "err", ":=", "volume", ".", "Info", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "pools", ".", "Add", "(", "info", ".", "Pool", ")", "\n", "}", "\n", "}", "\n", "for", "filesystemTag", ":=", "range", "params", ".", "filesystemAttachments", "{", "filesystem", ",", "err", ":=", "sb", ".", "Filesystem", "(", "filesystemTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "params", ",", "ok", ":=", "filesystem", ".", "Params", "(", ")", ";", "ok", "{", "pools", ".", "Add", "(", "params", ".", "Pool", ")", "\n", "}", "else", "{", "info", ",", "err", ":=", "filesystem", ".", "Info", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "pools", ".", "Add", "(", "info", ".", "Pool", ")", "\n", "}", "\n", "}", "\n", "return", "pools", ",", "nil", "\n", "}" ]
// storagePools returns the names of storage pools in each of the // volume, filesystem and attachments in the machine storage parameters.
[ "storagePools", "returns", "the", "names", "of", "storage", "pools", "in", "each", "of", "the", "volume", "filesystem", "and", "attachments", "in", "the", "machine", "storage", "parameters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2022-L2069
156,941
juju/juju
state/unit.go
validateDynamicMachineStoragePools
func validateDynamicMachineStoragePools(sb *storageBackend, m *Machine, pools set.Strings) error { if pools.IsEmpty() { return nil } if m.ContainerType() != "" { // TODO(axw) consult storage providers to check if they // support adding storage to containers. Loop is fine, // for example. // // TODO(axw) later we might allow *any* storage, and // passthrough/bindmount storage. That would imply either // container creation time only, or requiring containers // to be restarted to pick up new configuration. return errors.NotSupportedf("adding storage to %s container", m.ContainerType()) } return validateDynamicStoragePools(sb, pools) }
go
func validateDynamicMachineStoragePools(sb *storageBackend, m *Machine, pools set.Strings) error { if pools.IsEmpty() { return nil } if m.ContainerType() != "" { // TODO(axw) consult storage providers to check if they // support adding storage to containers. Loop is fine, // for example. // // TODO(axw) later we might allow *any* storage, and // passthrough/bindmount storage. That would imply either // container creation time only, or requiring containers // to be restarted to pick up new configuration. return errors.NotSupportedf("adding storage to %s container", m.ContainerType()) } return validateDynamicStoragePools(sb, pools) }
[ "func", "validateDynamicMachineStoragePools", "(", "sb", "*", "storageBackend", ",", "m", "*", "Machine", ",", "pools", "set", ".", "Strings", ")", "error", "{", "if", "pools", ".", "IsEmpty", "(", ")", "{", "return", "nil", "\n", "}", "\n", "if", "m", ".", "ContainerType", "(", ")", "!=", "\"", "\"", "{", "// TODO(axw) consult storage providers to check if they", "// support adding storage to containers. Loop is fine,", "// for example.", "//", "// TODO(axw) later we might allow *any* storage, and", "// passthrough/bindmount storage. That would imply either", "// container creation time only, or requiring containers", "// to be restarted to pick up new configuration.", "return", "errors", ".", "NotSupportedf", "(", "\"", "\"", ",", "m", ".", "ContainerType", "(", ")", ")", "\n", "}", "\n", "return", "validateDynamicStoragePools", "(", "sb", ",", "pools", ")", "\n", "}" ]
// validateDynamicMachineStoragePools validates that all of the specified // storage pools support dynamic storage provisioning. If any provider doesn't // support dynamic storage, then an IsNotSupported error is returned.
[ "validateDynamicMachineStoragePools", "validates", "that", "all", "of", "the", "specified", "storage", "pools", "support", "dynamic", "storage", "provisioning", ".", "If", "any", "provider", "doesn", "t", "support", "dynamic", "storage", "then", "an", "IsNotSupported", "error", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2074-L2090
156,942
juju/juju
state/unit.go
validateDynamicStoragePools
func validateDynamicStoragePools(sb *storageBackend, pools set.Strings) error { for pool := range pools { providerType, provider, _, err := poolStorageProvider(sb, pool) if err != nil { return errors.Trace(err) } if !provider.Dynamic() { return errors.NewNotSupported(err, fmt.Sprintf( "%q storage provider does not support dynamic storage", providerType, )) } } return nil }
go
func validateDynamicStoragePools(sb *storageBackend, pools set.Strings) error { for pool := range pools { providerType, provider, _, err := poolStorageProvider(sb, pool) if err != nil { return errors.Trace(err) } if !provider.Dynamic() { return errors.NewNotSupported(err, fmt.Sprintf( "%q storage provider does not support dynamic storage", providerType, )) } } return nil }
[ "func", "validateDynamicStoragePools", "(", "sb", "*", "storageBackend", ",", "pools", "set", ".", "Strings", ")", "error", "{", "for", "pool", ":=", "range", "pools", "{", "providerType", ",", "provider", ",", "_", ",", "err", ":=", "poolStorageProvider", "(", "sb", ",", "pool", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "provider", ".", "Dynamic", "(", ")", "{", "return", "errors", ".", "NewNotSupported", "(", "err", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "providerType", ",", ")", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateDynamicStoragePools validates that all of the specified storage // providers support dynamic storage provisioning. If any provider doesn't // support dynamic storage, then an IsNotSupported error is returned.
[ "validateDynamicStoragePools", "validates", "that", "all", "of", "the", "specified", "storage", "providers", "support", "dynamic", "storage", "provisioning", ".", "If", "any", "provider", "doesn", "t", "support", "dynamic", "storage", "then", "an", "IsNotSupported", "error", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2095-L2109
156,943
juju/juju
state/unit.go
AssignToMachine
func (u *Unit) AssignToMachine(m *Machine) (err error) { defer assignContextf(&err, u.Name(), fmt.Sprintf("machine %s", m)) return u.assignToMachine(m, false) }
go
func (u *Unit) AssignToMachine(m *Machine) (err error) { defer assignContextf(&err, u.Name(), fmt.Sprintf("machine %s", m)) return u.assignToMachine(m, false) }
[ "func", "(", "u", "*", "Unit", ")", "AssignToMachine", "(", "m", "*", "Machine", ")", "(", "err", "error", ")", "{", "defer", "assignContextf", "(", "&", "err", ",", "u", ".", "Name", "(", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "m", ")", ")", "\n", "return", "u", ".", "assignToMachine", "(", "m", ",", "false", ")", "\n", "}" ]
// AssignToMachine assigns this unit to a given machine.
[ "AssignToMachine", "assigns", "this", "unit", "to", "a", "given", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2121-L2124
156,944
juju/juju
state/unit.go
Constraints
func (u *Unit) Constraints() (*constraints.Value, error) { cons, err := readConstraints(u.st, u.globalAgentKey()) if errors.IsNotFound(err) { // Lack of constraints indicates lack of unit. return nil, errors.NotFoundf("unit") } else if err != nil { return nil, err } return &cons, nil }
go
func (u *Unit) Constraints() (*constraints.Value, error) { cons, err := readConstraints(u.st, u.globalAgentKey()) if errors.IsNotFound(err) { // Lack of constraints indicates lack of unit. return nil, errors.NotFoundf("unit") } else if err != nil { return nil, err } return &cons, nil }
[ "func", "(", "u", "*", "Unit", ")", "Constraints", "(", ")", "(", "*", "constraints", ".", "Value", ",", "error", ")", "{", "cons", ",", "err", ":=", "readConstraints", "(", "u", ".", "st", ",", "u", ".", "globalAgentKey", "(", ")", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "// Lack of constraints indicates lack of unit.", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "cons", ",", "nil", "\n", "}" ]
// Constraints returns the unit's deployment constraints.
[ "Constraints", "returns", "the", "unit", "s", "deployment", "constraints", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2216-L2225
156,945
juju/juju
state/unit.go
AssignToNewMachineOrContainer
func (u *Unit) AssignToNewMachineOrContainer() (err error) { defer assignContextf(&err, u.Name(), "new machine or container") if u.doc.Principal != "" { return fmt.Errorf("unit is a subordinate") } cons, err := u.Constraints() if err != nil { return err } if !cons.HasContainer() { return u.AssignToNewMachine() } // Find a clean, empty machine on which to create a container. hostCons := *cons noContainer := instance.NONE hostCons.Container = &noContainer query, err := u.findCleanMachineQuery(true, &hostCons) if err != nil { return err } machinesCollection, closer := u.st.db().GetCollection(machinesC) defer closer() var host machineDoc if err := machinesCollection.Find(query).One(&host); err == mgo.ErrNotFound { // No existing clean, empty machine so create a new one. The // container constraint will be used by AssignToNewMachine to // create the required container. return u.AssignToNewMachine() } else if err != nil { return err } var m *Machine buildTxn := func(attempt int) ([]txn.Op, error) { var err error u := u // don't change outer var if attempt > 0 { u, err = u.st.Unit(u.Name()) if err != nil { return nil, errors.Trace(err) } } template := MachineTemplate{ Series: u.doc.Series, Constraints: *cons, Jobs: []MachineJob{JobHostUnits}, } var ops []txn.Op m, ops, err = u.assignToNewMachineOps(template, host.Id, *cons.Container) return ops, err } if err := u.st.db().Run(buildTxn); err != nil { if errors.Cause(err) == machineNotCleanErr { // The clean machine was used before we got a chance // to use it so just stick the unit on a new machine. return u.AssignToNewMachine() } return errors.Trace(err) } u.doc.MachineId = m.doc.Id return nil }
go
func (u *Unit) AssignToNewMachineOrContainer() (err error) { defer assignContextf(&err, u.Name(), "new machine or container") if u.doc.Principal != "" { return fmt.Errorf("unit is a subordinate") } cons, err := u.Constraints() if err != nil { return err } if !cons.HasContainer() { return u.AssignToNewMachine() } // Find a clean, empty machine on which to create a container. hostCons := *cons noContainer := instance.NONE hostCons.Container = &noContainer query, err := u.findCleanMachineQuery(true, &hostCons) if err != nil { return err } machinesCollection, closer := u.st.db().GetCollection(machinesC) defer closer() var host machineDoc if err := machinesCollection.Find(query).One(&host); err == mgo.ErrNotFound { // No existing clean, empty machine so create a new one. The // container constraint will be used by AssignToNewMachine to // create the required container. return u.AssignToNewMachine() } else if err != nil { return err } var m *Machine buildTxn := func(attempt int) ([]txn.Op, error) { var err error u := u // don't change outer var if attempt > 0 { u, err = u.st.Unit(u.Name()) if err != nil { return nil, errors.Trace(err) } } template := MachineTemplate{ Series: u.doc.Series, Constraints: *cons, Jobs: []MachineJob{JobHostUnits}, } var ops []txn.Op m, ops, err = u.assignToNewMachineOps(template, host.Id, *cons.Container) return ops, err } if err := u.st.db().Run(buildTxn); err != nil { if errors.Cause(err) == machineNotCleanErr { // The clean machine was used before we got a chance // to use it so just stick the unit on a new machine. return u.AssignToNewMachine() } return errors.Trace(err) } u.doc.MachineId = m.doc.Id return nil }
[ "func", "(", "u", "*", "Unit", ")", "AssignToNewMachineOrContainer", "(", ")", "(", "err", "error", ")", "{", "defer", "assignContextf", "(", "&", "err", ",", "u", ".", "Name", "(", ")", ",", "\"", "\"", ")", "\n", "if", "u", ".", "doc", ".", "Principal", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "cons", ",", "err", ":=", "u", ".", "Constraints", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "cons", ".", "HasContainer", "(", ")", "{", "return", "u", ".", "AssignToNewMachine", "(", ")", "\n", "}", "\n\n", "// Find a clean, empty machine on which to create a container.", "hostCons", ":=", "*", "cons", "\n", "noContainer", ":=", "instance", ".", "NONE", "\n", "hostCons", ".", "Container", "=", "&", "noContainer", "\n", "query", ",", "err", ":=", "u", ".", "findCleanMachineQuery", "(", "true", ",", "&", "hostCons", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "machinesCollection", ",", "closer", ":=", "u", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "machinesC", ")", "\n", "defer", "closer", "(", ")", "\n", "var", "host", "machineDoc", "\n", "if", "err", ":=", "machinesCollection", ".", "Find", "(", "query", ")", ".", "One", "(", "&", "host", ")", ";", "err", "==", "mgo", ".", "ErrNotFound", "{", "// No existing clean, empty machine so create a new one. The", "// container constraint will be used by AssignToNewMachine to", "// create the required container.", "return", "u", ".", "AssignToNewMachine", "(", ")", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "m", "*", "Machine", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "var", "err", "error", "\n", "u", ":=", "u", "// don't change outer var", "\n", "if", "attempt", ">", "0", "{", "u", ",", "err", "=", "u", ".", "st", ".", "Unit", "(", "u", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "template", ":=", "MachineTemplate", "{", "Series", ":", "u", ".", "doc", ".", "Series", ",", "Constraints", ":", "*", "cons", ",", "Jobs", ":", "[", "]", "MachineJob", "{", "JobHostUnits", "}", ",", "}", "\n", "var", "ops", "[", "]", "txn", ".", "Op", "\n", "m", ",", "ops", ",", "err", "=", "u", ".", "assignToNewMachineOps", "(", "template", ",", "host", ".", "Id", ",", "*", "cons", ".", "Container", ")", "\n", "return", "ops", ",", "err", "\n", "}", "\n", "if", "err", ":=", "u", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", ";", "err", "!=", "nil", "{", "if", "errors", ".", "Cause", "(", "err", ")", "==", "machineNotCleanErr", "{", "// The clean machine was used before we got a chance", "// to use it so just stick the unit on a new machine.", "return", "u", ".", "AssignToNewMachine", "(", ")", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "u", ".", "doc", ".", "MachineId", "=", "m", ".", "doc", ".", "Id", "\n", "return", "nil", "\n", "}" ]
// AssignToNewMachineOrContainer assigns the unit to a new machine, // with constraints determined according to the application and // model constraints at the time of unit creation. If a // container is required, a clean, empty machine instance is required // on which to create the container. An existing clean, empty instance // is first searched for, and if not found, a new one is created.
[ "AssignToNewMachineOrContainer", "assigns", "the", "unit", "to", "a", "new", "machine", "with", "constraints", "determined", "according", "to", "the", "application", "and", "model", "constraints", "at", "the", "time", "of", "unit", "creation", ".", "If", "a", "container", "is", "required", "a", "clean", "empty", "machine", "instance", "is", "required", "on", "which", "to", "create", "the", "container", ".", "An", "existing", "clean", "empty", "instance", "is", "first", "searched", "for", "and", "if", "not", "found", "a", "new", "one", "is", "created", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2233-L2295
156,946
juju/juju
state/unit.go
AssignToNewMachine
func (u *Unit) AssignToNewMachine() (err error) { defer assignContextf(&err, u.Name(), "new machine") return u.assignToNewMachine("") }
go
func (u *Unit) AssignToNewMachine() (err error) { defer assignContextf(&err, u.Name(), "new machine") return u.assignToNewMachine("") }
[ "func", "(", "u", "*", "Unit", ")", "AssignToNewMachine", "(", ")", "(", "err", "error", ")", "{", "defer", "assignContextf", "(", "&", "err", ",", "u", ".", "Name", "(", ")", ",", "\"", "\"", ")", "\n", "return", "u", ".", "assignToNewMachine", "(", "\"", "\"", ")", "\n", "}" ]
// AssignToNewMachine assigns the unit to a new machine, with constraints // determined according to the application and model constraints at the // time of unit creation.
[ "AssignToNewMachine", "assigns", "the", "unit", "to", "a", "new", "machine", "with", "constraints", "determined", "according", "to", "the", "application", "and", "model", "constraints", "at", "the", "time", "of", "unit", "creation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2300-L2303
156,947
juju/juju
state/unit.go
assignToNewMachine
func (u *Unit) assignToNewMachine(placement string) error { if u.doc.Principal != "" { return fmt.Errorf("unit is a subordinate") } var m *Machine buildTxn := func(attempt int) ([]txn.Op, error) { var err error u := u // don't change outer var if attempt > 0 { u, err = u.st.Unit(u.Name()) if err != nil { return nil, errors.Trace(err) } } cons, err := u.Constraints() if err != nil { return nil, err } var containerType instance.ContainerType if cons.HasContainer() { containerType = *cons.Container } storageParams, err := u.storageParams() if err != nil { return nil, errors.Trace(err) } template := MachineTemplate{ Series: u.doc.Series, Constraints: *cons, Jobs: []MachineJob{JobHostUnits}, Placement: placement, Dirty: placement != "", Volumes: storageParams.volumes, VolumeAttachments: storageParams.volumeAttachments, Filesystems: storageParams.filesystems, FilesystemAttachments: storageParams.filesystemAttachments, } // Get the ops necessary to create a new machine, and the // machine doc that will be added with those operations // (which includes the machine id). var ops []txn.Op m, ops, err = u.assignToNewMachineOps(template, "", containerType) return ops, err } if err := u.st.db().Run(buildTxn); err != nil { return errors.Trace(err) } u.doc.MachineId = m.doc.Id return nil }
go
func (u *Unit) assignToNewMachine(placement string) error { if u.doc.Principal != "" { return fmt.Errorf("unit is a subordinate") } var m *Machine buildTxn := func(attempt int) ([]txn.Op, error) { var err error u := u // don't change outer var if attempt > 0 { u, err = u.st.Unit(u.Name()) if err != nil { return nil, errors.Trace(err) } } cons, err := u.Constraints() if err != nil { return nil, err } var containerType instance.ContainerType if cons.HasContainer() { containerType = *cons.Container } storageParams, err := u.storageParams() if err != nil { return nil, errors.Trace(err) } template := MachineTemplate{ Series: u.doc.Series, Constraints: *cons, Jobs: []MachineJob{JobHostUnits}, Placement: placement, Dirty: placement != "", Volumes: storageParams.volumes, VolumeAttachments: storageParams.volumeAttachments, Filesystems: storageParams.filesystems, FilesystemAttachments: storageParams.filesystemAttachments, } // Get the ops necessary to create a new machine, and the // machine doc that will be added with those operations // (which includes the machine id). var ops []txn.Op m, ops, err = u.assignToNewMachineOps(template, "", containerType) return ops, err } if err := u.st.db().Run(buildTxn); err != nil { return errors.Trace(err) } u.doc.MachineId = m.doc.Id return nil }
[ "func", "(", "u", "*", "Unit", ")", "assignToNewMachine", "(", "placement", "string", ")", "error", "{", "if", "u", ".", "doc", ".", "Principal", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "m", "*", "Machine", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "var", "err", "error", "\n", "u", ":=", "u", "// don't change outer var", "\n", "if", "attempt", ">", "0", "{", "u", ",", "err", "=", "u", ".", "st", ".", "Unit", "(", "u", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "cons", ",", "err", ":=", "u", ".", "Constraints", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "containerType", "instance", ".", "ContainerType", "\n", "if", "cons", ".", "HasContainer", "(", ")", "{", "containerType", "=", "*", "cons", ".", "Container", "\n", "}", "\n", "storageParams", ",", "err", ":=", "u", ".", "storageParams", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "template", ":=", "MachineTemplate", "{", "Series", ":", "u", ".", "doc", ".", "Series", ",", "Constraints", ":", "*", "cons", ",", "Jobs", ":", "[", "]", "MachineJob", "{", "JobHostUnits", "}", ",", "Placement", ":", "placement", ",", "Dirty", ":", "placement", "!=", "\"", "\"", ",", "Volumes", ":", "storageParams", ".", "volumes", ",", "VolumeAttachments", ":", "storageParams", ".", "volumeAttachments", ",", "Filesystems", ":", "storageParams", ".", "filesystems", ",", "FilesystemAttachments", ":", "storageParams", ".", "filesystemAttachments", ",", "}", "\n", "// Get the ops necessary to create a new machine, and the", "// machine doc that will be added with those operations", "// (which includes the machine id).", "var", "ops", "[", "]", "txn", ".", "Op", "\n", "m", ",", "ops", ",", "err", "=", "u", ".", "assignToNewMachineOps", "(", "template", ",", "\"", "\"", ",", "containerType", ")", "\n", "return", "ops", ",", "err", "\n", "}", "\n", "if", "err", ":=", "u", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "u", ".", "doc", ".", "MachineId", "=", "m", ".", "doc", ".", "Id", "\n", "return", "nil", "\n", "}" ]
// assignToNewMachine assigns the unit to a new machine with the // optional placement directive, with constraints determined according // to the application and model constraints at the time of unit creation.
[ "assignToNewMachine", "assigns", "the", "unit", "to", "a", "new", "machine", "with", "the", "optional", "placement", "directive", "with", "constraints", "determined", "according", "to", "the", "application", "and", "model", "constraints", "at", "the", "time", "of", "unit", "creation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2308-L2357
156,948
juju/juju
state/unit.go
assignToCleanMaybeEmptyMachine
func (u *Unit) assignToCleanMaybeEmptyMachine(requireEmpty bool) (*Machine, error) { var m *Machine buildTxn := func(attempt int) ([]txn.Op, error) { var err error u := u // don't change outer var if attempt > 0 { u, err = u.st.Unit(u.Name()) if err != nil { return nil, errors.Trace(err) } } var ops []txn.Op m, ops, err = u.assignToCleanMaybeEmptyMachineOps(requireEmpty) return ops, err } if err := u.st.db().Run(buildTxn); err != nil { return nil, errors.Trace(err) } u.doc.MachineId = m.doc.Id m.doc.Clean = false return m, nil }
go
func (u *Unit) assignToCleanMaybeEmptyMachine(requireEmpty bool) (*Machine, error) { var m *Machine buildTxn := func(attempt int) ([]txn.Op, error) { var err error u := u // don't change outer var if attempt > 0 { u, err = u.st.Unit(u.Name()) if err != nil { return nil, errors.Trace(err) } } var ops []txn.Op m, ops, err = u.assignToCleanMaybeEmptyMachineOps(requireEmpty) return ops, err } if err := u.st.db().Run(buildTxn); err != nil { return nil, errors.Trace(err) } u.doc.MachineId = m.doc.Id m.doc.Clean = false return m, nil }
[ "func", "(", "u", "*", "Unit", ")", "assignToCleanMaybeEmptyMachine", "(", "requireEmpty", "bool", ")", "(", "*", "Machine", ",", "error", ")", "{", "var", "m", "*", "Machine", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "var", "err", "error", "\n", "u", ":=", "u", "// don't change outer var", "\n", "if", "attempt", ">", "0", "{", "u", ",", "err", "=", "u", ".", "st", ".", "Unit", "(", "u", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "var", "ops", "[", "]", "txn", ".", "Op", "\n", "m", ",", "ops", ",", "err", "=", "u", ".", "assignToCleanMaybeEmptyMachineOps", "(", "requireEmpty", ")", "\n", "return", "ops", ",", "err", "\n", "}", "\n", "if", "err", ":=", "u", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "u", ".", "doc", ".", "MachineId", "=", "m", ".", "doc", ".", "Id", "\n", "m", ".", "doc", ".", "Clean", "=", "false", "\n", "return", "m", ",", "nil", "\n", "}" ]
// assignToCleanMaybeEmptyMachine implements AssignToCleanMachine and AssignToCleanEmptyMachine. // A 'machine' may be a machine instance or container depending on the application constraints.
[ "assignToCleanMaybeEmptyMachine", "implements", "AssignToCleanMachine", "and", "AssignToCleanEmptyMachine", ".", "A", "machine", "may", "be", "a", "machine", "instance", "or", "container", "depending", "on", "the", "application", "constraints", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2729-L2750
156,949
juju/juju
state/unit.go
UnassignFromMachine
func (u *Unit) UnassignFromMachine() (err error) { // TODO check local machine id and add an assert that the // machine id is as expected. ops := []txn.Op{{ C: unitsC, Id: u.doc.DocID, Assert: txn.DocExists, Update: bson.D{{"$set", bson.D{{"machineid", ""}}}}, }} if u.doc.MachineId != "" { ops = append(ops, txn.Op{ C: machinesC, Id: u.st.docID(u.doc.MachineId), Assert: txn.DocExists, Update: bson.D{{"$pull", bson.D{{"principals", u.doc.Name}}}}, }) } err = u.st.db().RunTransaction(ops) if err != nil { return fmt.Errorf("cannot unassign unit %q from machine: %v", u, onAbort(err, errors.NotFoundf("machine"))) } u.doc.MachineId = "" return nil }
go
func (u *Unit) UnassignFromMachine() (err error) { // TODO check local machine id and add an assert that the // machine id is as expected. ops := []txn.Op{{ C: unitsC, Id: u.doc.DocID, Assert: txn.DocExists, Update: bson.D{{"$set", bson.D{{"machineid", ""}}}}, }} if u.doc.MachineId != "" { ops = append(ops, txn.Op{ C: machinesC, Id: u.st.docID(u.doc.MachineId), Assert: txn.DocExists, Update: bson.D{{"$pull", bson.D{{"principals", u.doc.Name}}}}, }) } err = u.st.db().RunTransaction(ops) if err != nil { return fmt.Errorf("cannot unassign unit %q from machine: %v", u, onAbort(err, errors.NotFoundf("machine"))) } u.doc.MachineId = "" return nil }
[ "func", "(", "u", "*", "Unit", ")", "UnassignFromMachine", "(", ")", "(", "err", "error", ")", "{", "// TODO check local machine id and add an assert that the", "// machine id is as expected.", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "unitsC", ",", "Id", ":", "u", ".", "doc", ".", "DocID", ",", "Assert", ":", "txn", ".", "DocExists", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "\"", "\"", "}", "}", "}", "}", ",", "}", "}", "\n", "if", "u", ".", "doc", ".", "MachineId", "!=", "\"", "\"", "{", "ops", "=", "append", "(", "ops", ",", "txn", ".", "Op", "{", "C", ":", "machinesC", ",", "Id", ":", "u", ".", "st", ".", "docID", "(", "u", ".", "doc", ".", "MachineId", ")", ",", "Assert", ":", "txn", ".", "DocExists", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "u", ".", "doc", ".", "Name", "}", "}", "}", "}", ",", "}", ")", "\n", "}", "\n", "err", "=", "u", ".", "st", ".", "db", "(", ")", ".", "RunTransaction", "(", "ops", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "u", ",", "onAbort", "(", "err", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", ")", ")", "\n", "}", "\n", "u", ".", "doc", ".", "MachineId", "=", "\"", "\"", "\n", "return", "nil", "\n", "}" ]
// UnassignFromMachine removes the assignment between this unit and the // machine it's assigned to.
[ "UnassignFromMachine", "removes", "the", "assignment", "between", "this", "unit", "and", "the", "machine", "it", "s", "assigned", "to", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2895-L2918
156,950
juju/juju
state/unit.go
AddAction
func (u *Unit) AddAction(name string, payload map[string]interface{}) (Action, error) { if len(name) == 0 { return nil, errors.New("no action name given") } // If the action is predefined inside juju, get spec from map spec, ok := actions.PredefinedActionsSpec[name] if !ok { specs, err := u.ActionSpecs() if err != nil { return nil, err } spec, ok = specs[name] if !ok { return nil, errors.Errorf("action %q not defined on unit %q", name, u.Name()) } } // Reject bad payloads before attempting to insert defaults. err := spec.ValidateParams(payload) if err != nil { return nil, err } payloadWithDefaults, err := spec.InsertDefaults(payload) if err != nil { return nil, err } m, err := u.st.Model() if err != nil { return nil, errors.Trace(err) } return m.EnqueueAction(u.Tag(), name, payloadWithDefaults) }
go
func (u *Unit) AddAction(name string, payload map[string]interface{}) (Action, error) { if len(name) == 0 { return nil, errors.New("no action name given") } // If the action is predefined inside juju, get spec from map spec, ok := actions.PredefinedActionsSpec[name] if !ok { specs, err := u.ActionSpecs() if err != nil { return nil, err } spec, ok = specs[name] if !ok { return nil, errors.Errorf("action %q not defined on unit %q", name, u.Name()) } } // Reject bad payloads before attempting to insert defaults. err := spec.ValidateParams(payload) if err != nil { return nil, err } payloadWithDefaults, err := spec.InsertDefaults(payload) if err != nil { return nil, err } m, err := u.st.Model() if err != nil { return nil, errors.Trace(err) } return m.EnqueueAction(u.Tag(), name, payloadWithDefaults) }
[ "func", "(", "u", "*", "Unit", ")", "AddAction", "(", "name", "string", ",", "payload", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "Action", ",", "error", ")", "{", "if", "len", "(", "name", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// If the action is predefined inside juju, get spec from map", "spec", ",", "ok", ":=", "actions", ".", "PredefinedActionsSpec", "[", "name", "]", "\n", "if", "!", "ok", "{", "specs", ",", "err", ":=", "u", ".", "ActionSpecs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "spec", ",", "ok", "=", "specs", "[", "name", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "u", ".", "Name", "(", ")", ")", "\n", "}", "\n", "}", "\n", "// Reject bad payloads before attempting to insert defaults.", "err", ":=", "spec", ".", "ValidateParams", "(", "payload", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "payloadWithDefaults", ",", "err", ":=", "spec", ".", "InsertDefaults", "(", "payload", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "m", ",", "err", ":=", "u", ".", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "m", ".", "EnqueueAction", "(", "u", ".", "Tag", "(", ")", ",", "name", ",", "payloadWithDefaults", ")", "\n", "}" ]
// AddAction adds a new Action of type name and using arguments payload to // this Unit, and returns its ID. Note that the use of spec.InsertDefaults // mutates payload.
[ "AddAction", "adds", "a", "new", "Action", "of", "type", "name", "and", "using", "arguments", "payload", "to", "this", "Unit", "and", "returns", "its", "ID", ".", "Note", "that", "the", "use", "of", "spec", ".", "InsertDefaults", "mutates", "payload", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2926-L2958
156,951
juju/juju
state/unit.go
ActionSpecs
func (u *Unit) ActionSpecs() (ActionSpecsByName, error) { none := ActionSpecsByName{} ch, err := u.charm() if err != nil { return none, errors.Trace(err) } chActions := ch.Actions() if chActions == nil || len(chActions.ActionSpecs) == 0 { return none, errors.Errorf("no actions defined on charm %q", ch.String()) } return chActions.ActionSpecs, nil }
go
func (u *Unit) ActionSpecs() (ActionSpecsByName, error) { none := ActionSpecsByName{} ch, err := u.charm() if err != nil { return none, errors.Trace(err) } chActions := ch.Actions() if chActions == nil || len(chActions.ActionSpecs) == 0 { return none, errors.Errorf("no actions defined on charm %q", ch.String()) } return chActions.ActionSpecs, nil }
[ "func", "(", "u", "*", "Unit", ")", "ActionSpecs", "(", ")", "(", "ActionSpecsByName", ",", "error", ")", "{", "none", ":=", "ActionSpecsByName", "{", "}", "\n", "ch", ",", "err", ":=", "u", ".", "charm", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "none", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "chActions", ":=", "ch", ".", "Actions", "(", ")", "\n", "if", "chActions", "==", "nil", "||", "len", "(", "chActions", ".", "ActionSpecs", ")", "==", "0", "{", "return", "none", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "ch", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "chActions", ".", "ActionSpecs", ",", "nil", "\n", "}" ]
// ActionSpecs gets the ActionSpec map for the Unit's charm.
[ "ActionSpecs", "gets", "the", "ActionSpec", "map", "for", "the", "Unit", "s", "charm", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2961-L2972
156,952
juju/juju
state/unit.go
CancelAction
func (u *Unit) CancelAction(action Action) (Action, error) { return action.Finish(ActionResults{Status: ActionCancelled}) }
go
func (u *Unit) CancelAction(action Action) (Action, error) { return action.Finish(ActionResults{Status: ActionCancelled}) }
[ "func", "(", "u", "*", "Unit", ")", "CancelAction", "(", "action", "Action", ")", "(", "Action", ",", "error", ")", "{", "return", "action", ".", "Finish", "(", "ActionResults", "{", "Status", ":", "ActionCancelled", "}", ")", "\n", "}" ]
// CancelAction removes a pending Action from the queue for this // ActionReceiver and marks it as cancelled.
[ "CancelAction", "removes", "a", "pending", "Action", "from", "the", "queue", "for", "this", "ActionReceiver", "and", "marks", "it", "as", "cancelled", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L2976-L2978
156,953
juju/juju
state/unit.go
Resolve
func (u *Unit) Resolve(retryHooks bool) error { // We currently check agent status to see if a unit is // in error state. As the new Juju Health work is completed, // this will change to checking the unit status. statusInfo, err := u.Status() if err != nil { return err } if statusInfo.Status != status.Error { return errors.Errorf("unit %q is not in an error state", u) } mode := ResolvedNoHooks if retryHooks { mode = ResolvedRetryHooks } return u.SetResolved(mode) }
go
func (u *Unit) Resolve(retryHooks bool) error { // We currently check agent status to see if a unit is // in error state. As the new Juju Health work is completed, // this will change to checking the unit status. statusInfo, err := u.Status() if err != nil { return err } if statusInfo.Status != status.Error { return errors.Errorf("unit %q is not in an error state", u) } mode := ResolvedNoHooks if retryHooks { mode = ResolvedRetryHooks } return u.SetResolved(mode) }
[ "func", "(", "u", "*", "Unit", ")", "Resolve", "(", "retryHooks", "bool", ")", "error", "{", "// We currently check agent status to see if a unit is", "// in error state. As the new Juju Health work is completed,", "// this will change to checking the unit status.", "statusInfo", ",", "err", ":=", "u", ".", "Status", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "statusInfo", ".", "Status", "!=", "status", ".", "Error", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "u", ")", "\n", "}", "\n", "mode", ":=", "ResolvedNoHooks", "\n", "if", "retryHooks", "{", "mode", "=", "ResolvedRetryHooks", "\n", "}", "\n", "return", "u", ".", "SetResolved", "(", "mode", ")", "\n", "}" ]
// Resolve marks the unit as having had any previous state transition // problems resolved, and informs the unit that it may attempt to // reestablish normal workflow. The retryHooks parameter informs // whether to attempt to reexecute previous failed hooks or to continue // as if they had succeeded before.
[ "Resolve", "marks", "the", "unit", "as", "having", "had", "any", "previous", "state", "transition", "problems", "resolved", "and", "informs", "the", "unit", "that", "it", "may", "attempt", "to", "reestablish", "normal", "workflow", ".", "The", "retryHooks", "parameter", "informs", "whether", "to", "attempt", "to", "reexecute", "previous", "failed", "hooks", "or", "to", "continue", "as", "if", "they", "had", "succeeded", "before", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L3012-L3028
156,954
juju/juju
state/unit.go
SetResolved
func (u *Unit) SetResolved(mode ResolvedMode) (err error) { defer errors.DeferredAnnotatef(&err, "cannot set resolved mode for unit %q", u) switch mode { case ResolvedRetryHooks, ResolvedNoHooks: default: return fmt.Errorf("invalid error resolution mode: %q", mode) } // TODO(fwereade): assert unit has error status. resolvedNotSet := bson.D{{"resolved", ResolvedNone}} ops := []txn.Op{{ C: unitsC, Id: u.doc.DocID, Assert: append(notDeadDoc, resolvedNotSet...), Update: bson.D{{"$set", bson.D{{"resolved", mode}}}}, }} if err := u.st.db().RunTransaction(ops); err == nil { u.doc.Resolved = mode return nil } else if err != txn.ErrAborted { return err } if ok, err := isNotDead(u.st, unitsC, u.doc.DocID); err != nil { return err } else if !ok { return ErrDead } // For now, the only remaining assert is that resolved was unset. return fmt.Errorf("already resolved") }
go
func (u *Unit) SetResolved(mode ResolvedMode) (err error) { defer errors.DeferredAnnotatef(&err, "cannot set resolved mode for unit %q", u) switch mode { case ResolvedRetryHooks, ResolvedNoHooks: default: return fmt.Errorf("invalid error resolution mode: %q", mode) } // TODO(fwereade): assert unit has error status. resolvedNotSet := bson.D{{"resolved", ResolvedNone}} ops := []txn.Op{{ C: unitsC, Id: u.doc.DocID, Assert: append(notDeadDoc, resolvedNotSet...), Update: bson.D{{"$set", bson.D{{"resolved", mode}}}}, }} if err := u.st.db().RunTransaction(ops); err == nil { u.doc.Resolved = mode return nil } else if err != txn.ErrAborted { return err } if ok, err := isNotDead(u.st, unitsC, u.doc.DocID); err != nil { return err } else if !ok { return ErrDead } // For now, the only remaining assert is that resolved was unset. return fmt.Errorf("already resolved") }
[ "func", "(", "u", "*", "Unit", ")", "SetResolved", "(", "mode", "ResolvedMode", ")", "(", "err", "error", ")", "{", "defer", "errors", ".", "DeferredAnnotatef", "(", "&", "err", ",", "\"", "\"", ",", "u", ")", "\n", "switch", "mode", "{", "case", "ResolvedRetryHooks", ",", "ResolvedNoHooks", ":", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mode", ")", "\n", "}", "\n", "// TODO(fwereade): assert unit has error status.", "resolvedNotSet", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "ResolvedNone", "}", "}", "\n", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "unitsC", ",", "Id", ":", "u", ".", "doc", ".", "DocID", ",", "Assert", ":", "append", "(", "notDeadDoc", ",", "resolvedNotSet", "...", ")", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "mode", "}", "}", "}", "}", ",", "}", "}", "\n", "if", "err", ":=", "u", ".", "st", ".", "db", "(", ")", ".", "RunTransaction", "(", "ops", ")", ";", "err", "==", "nil", "{", "u", ".", "doc", ".", "Resolved", "=", "mode", "\n", "return", "nil", "\n", "}", "else", "if", "err", "!=", "txn", ".", "ErrAborted", "{", "return", "err", "\n", "}", "\n", "if", "ok", ",", "err", ":=", "isNotDead", "(", "u", ".", "st", ",", "unitsC", ",", "u", ".", "doc", ".", "DocID", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "if", "!", "ok", "{", "return", "ErrDead", "\n", "}", "\n", "// For now, the only remaining assert is that resolved was unset.", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// SetResolved marks the unit as having had any previous state transition // problems resolved, and informs the unit that it may attempt to // reestablish normal workflow. The resolved mode parameter informs // whether to attempt to reexecute previous failed hooks or to continue // as if they had succeeded before.
[ "SetResolved", "marks", "the", "unit", "as", "having", "had", "any", "previous", "state", "transition", "problems", "resolved", "and", "informs", "the", "unit", "that", "it", "may", "attempt", "to", "reestablish", "normal", "workflow", ".", "The", "resolved", "mode", "parameter", "informs", "whether", "to", "attempt", "to", "reexecute", "previous", "failed", "hooks", "or", "to", "continue", "as", "if", "they", "had", "succeeded", "before", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L3035-L3063
156,955
juju/juju
state/unit.go
ClearResolved
func (u *Unit) ClearResolved() error { ops := []txn.Op{{ C: unitsC, Id: u.doc.DocID, Assert: txn.DocExists, Update: bson.D{{"$set", bson.D{{"resolved", ResolvedNone}}}}, }} err := u.st.db().RunTransaction(ops) if err != nil { return fmt.Errorf("cannot clear resolved mode for unit %q: %v", u, errors.NotFoundf("unit")) } u.doc.Resolved = ResolvedNone return nil }
go
func (u *Unit) ClearResolved() error { ops := []txn.Op{{ C: unitsC, Id: u.doc.DocID, Assert: txn.DocExists, Update: bson.D{{"$set", bson.D{{"resolved", ResolvedNone}}}}, }} err := u.st.db().RunTransaction(ops) if err != nil { return fmt.Errorf("cannot clear resolved mode for unit %q: %v", u, errors.NotFoundf("unit")) } u.doc.Resolved = ResolvedNone return nil }
[ "func", "(", "u", "*", "Unit", ")", "ClearResolved", "(", ")", "error", "{", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "unitsC", ",", "Id", ":", "u", ".", "doc", ".", "DocID", ",", "Assert", ":", "txn", ".", "DocExists", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "ResolvedNone", "}", "}", "}", "}", ",", "}", "}", "\n", "err", ":=", "u", ".", "st", ".", "db", "(", ")", ".", "RunTransaction", "(", "ops", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "u", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "u", ".", "doc", ".", "Resolved", "=", "ResolvedNone", "\n", "return", "nil", "\n", "}" ]
// ClearResolved removes any resolved setting on the unit.
[ "ClearResolved", "removes", "any", "resolved", "setting", "on", "the", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L3066-L3079
156,956
juju/juju
state/unit.go
StorageConstraints
func (u *Unit) StorageConstraints() (map[string]StorageConstraints, error) { if u.doc.CharmURL == nil { app, err := u.st.Application(u.doc.Application) if err != nil { return nil, errors.Trace(err) } return app.StorageConstraints() } key := applicationStorageConstraintsKey(u.doc.Application, u.doc.CharmURL) cons, err := readStorageConstraints(u.st, key) if errors.IsNotFound(err) { return nil, nil } else if err != nil { return nil, errors.Trace(err) } return cons, nil }
go
func (u *Unit) StorageConstraints() (map[string]StorageConstraints, error) { if u.doc.CharmURL == nil { app, err := u.st.Application(u.doc.Application) if err != nil { return nil, errors.Trace(err) } return app.StorageConstraints() } key := applicationStorageConstraintsKey(u.doc.Application, u.doc.CharmURL) cons, err := readStorageConstraints(u.st, key) if errors.IsNotFound(err) { return nil, nil } else if err != nil { return nil, errors.Trace(err) } return cons, nil }
[ "func", "(", "u", "*", "Unit", ")", "StorageConstraints", "(", ")", "(", "map", "[", "string", "]", "StorageConstraints", ",", "error", ")", "{", "if", "u", ".", "doc", ".", "CharmURL", "==", "nil", "{", "app", ",", "err", ":=", "u", ".", "st", ".", "Application", "(", "u", ".", "doc", ".", "Application", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "app", ".", "StorageConstraints", "(", ")", "\n", "}", "\n", "key", ":=", "applicationStorageConstraintsKey", "(", "u", ".", "doc", ".", "Application", ",", "u", ".", "doc", ".", "CharmURL", ")", "\n", "cons", ",", "err", ":=", "readStorageConstraints", "(", "u", ".", "st", ",", "key", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "cons", ",", "nil", "\n", "}" ]
// StorageConstraints returns the unit's storage constraints.
[ "StorageConstraints", "returns", "the", "unit", "s", "storage", "constraints", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L3082-L3098
156,957
juju/juju
state/unit.go
StatusHistory
func (g *HistoryGetter) StatusHistory(filter status.StatusHistoryFilter) ([]status.StatusInfo, error) { args := &statusHistoryArgs{ db: g.st.db(), globalKey: g.globalKey, filter: filter, } return statusHistory(args) }
go
func (g *HistoryGetter) StatusHistory(filter status.StatusHistoryFilter) ([]status.StatusInfo, error) { args := &statusHistoryArgs{ db: g.st.db(), globalKey: g.globalKey, filter: filter, } return statusHistory(args) }
[ "func", "(", "g", "*", "HistoryGetter", ")", "StatusHistory", "(", "filter", "status", ".", "StatusHistoryFilter", ")", "(", "[", "]", "status", ".", "StatusInfo", ",", "error", ")", "{", "args", ":=", "&", "statusHistoryArgs", "{", "db", ":", "g", ".", "st", ".", "db", "(", ")", ",", "globalKey", ":", "g", ".", "globalKey", ",", "filter", ":", "filter", ",", "}", "\n", "return", "statusHistory", "(", "args", ")", "\n", "}" ]
// StatusHistory implements status.StatusHistoryGetter.
[ "StatusHistory", "implements", "status", ".", "StatusHistoryGetter", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L3164-L3171
156,958
juju/juju
state/unit.go
GetSpaceForBinding
func (u *Unit) GetSpaceForBinding(bindingName string) (string, error) { app, err := u.Application() if err != nil { return "", errors.Trace(err) } bindings, err := app.EndpointBindings() if err != nil { return "", errors.Trace(err) } boundSpace, known := bindings[bindingName] if !known { // If default binding is not explicitly defined we'll use default space if bindingName == environs.DefaultSpaceName { return environs.DefaultSpaceName, nil } return "", errors.NewNotValid(nil, fmt.Sprintf("binding name %q not defined by the unit's charm", bindingName)) } return boundSpace, nil }
go
func (u *Unit) GetSpaceForBinding(bindingName string) (string, error) { app, err := u.Application() if err != nil { return "", errors.Trace(err) } bindings, err := app.EndpointBindings() if err != nil { return "", errors.Trace(err) } boundSpace, known := bindings[bindingName] if !known { // If default binding is not explicitly defined we'll use default space if bindingName == environs.DefaultSpaceName { return environs.DefaultSpaceName, nil } return "", errors.NewNotValid(nil, fmt.Sprintf("binding name %q not defined by the unit's charm", bindingName)) } return boundSpace, nil }
[ "func", "(", "u", "*", "Unit", ")", "GetSpaceForBinding", "(", "bindingName", "string", ")", "(", "string", ",", "error", ")", "{", "app", ",", "err", ":=", "u", ".", "Application", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "bindings", ",", "err", ":=", "app", ".", "EndpointBindings", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "boundSpace", ",", "known", ":=", "bindings", "[", "bindingName", "]", "\n", "if", "!", "known", "{", "// If default binding is not explicitly defined we'll use default space", "if", "bindingName", "==", "environs", ".", "DefaultSpaceName", "{", "return", "environs", ".", "DefaultSpaceName", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "NewNotValid", "(", "nil", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "bindingName", ")", ")", "\n", "}", "\n", "return", "boundSpace", ",", "nil", "\n", "}" ]
// GetSpaceForBinding returns the space name associated with the specified endpoint.
[ "GetSpaceForBinding", "returns", "the", "space", "name", "associated", "with", "the", "specified", "endpoint", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L3174-L3193
156,959
juju/juju
state/unit.go
UpgradeSeriesStatus
func (u *Unit) UpgradeSeriesStatus() (model.UpgradeSeriesStatus, error) { machine, err := u.machine() if err != nil { return "", err } return machine.UpgradeSeriesUnitStatus(u.Name()) }
go
func (u *Unit) UpgradeSeriesStatus() (model.UpgradeSeriesStatus, error) { machine, err := u.machine() if err != nil { return "", err } return machine.UpgradeSeriesUnitStatus(u.Name()) }
[ "func", "(", "u", "*", "Unit", ")", "UpgradeSeriesStatus", "(", ")", "(", "model", ".", "UpgradeSeriesStatus", ",", "error", ")", "{", "machine", ",", "err", ":=", "u", ".", "machine", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "machine", ".", "UpgradeSeriesUnitStatus", "(", "u", ".", "Name", "(", ")", ")", "\n", "}" ]
// UpgradeSeriesStatus returns the upgrade status of the units assigned machine.
[ "UpgradeSeriesStatus", "returns", "the", "upgrade", "status", "of", "the", "units", "assigned", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L3196-L3202
156,960
juju/juju
state/unit.go
SetUpgradeSeriesStatus
func (u *Unit) SetUpgradeSeriesStatus(status model.UpgradeSeriesStatus, message string) error { machine, err := u.machine() if err != nil { return err } return machine.SetUpgradeSeriesUnitStatus(u.Name(), status, message) }
go
func (u *Unit) SetUpgradeSeriesStatus(status model.UpgradeSeriesStatus, message string) error { machine, err := u.machine() if err != nil { return err } return machine.SetUpgradeSeriesUnitStatus(u.Name(), status, message) }
[ "func", "(", "u", "*", "Unit", ")", "SetUpgradeSeriesStatus", "(", "status", "model", ".", "UpgradeSeriesStatus", ",", "message", "string", ")", "error", "{", "machine", ",", "err", ":=", "u", ".", "machine", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "machine", ".", "SetUpgradeSeriesUnitStatus", "(", "u", ".", "Name", "(", ")", ",", "status", ",", "message", ")", "\n", "}" ]
// SetUpgradeSeriesStatus sets the upgrade status of the units assigned machine.
[ "SetUpgradeSeriesStatus", "sets", "the", "upgrade", "status", "of", "the", "units", "assigned", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unit.go#L3205-L3211
156,961
juju/juju
state/allwatcher.go
makeAllWatcherCollectionInfo
func makeAllWatcherCollectionInfo(collNames ...string) map[string]allWatcherStateCollection { seenTypes := make(map[reflect.Type]struct{}) collectionByName := make(map[string]allWatcherStateCollection) for _, collName := range collNames { collection := allWatcherStateCollection{name: collName} switch collName { case modelsC: collection.docType = reflect.TypeOf(backingModel{}) case machinesC: collection.docType = reflect.TypeOf(backingMachine{}) case instanceDataC: collection.docType = reflect.TypeOf(backingInstanceData{}) collection.subsidiary = true case unitsC: collection.docType = reflect.TypeOf(backingUnit{}) case applicationsC: collection.docType = reflect.TypeOf(backingApplication{}) case charmsC: collection.docType = reflect.TypeOf(backingCharm{}) case actionsC: collection.docType = reflect.TypeOf(backingAction{}) case relationsC: collection.docType = reflect.TypeOf(backingRelation{}) case annotationsC: collection.docType = reflect.TypeOf(backingAnnotation{}) case blocksC: collection.docType = reflect.TypeOf(backingBlock{}) case statusesC: collection.docType = reflect.TypeOf(backingStatus{}) collection.subsidiary = true case constraintsC: collection.docType = reflect.TypeOf(backingConstraints{}) collection.subsidiary = true case settingsC: collection.docType = reflect.TypeOf(backingSettings{}) collection.subsidiary = true case openedPortsC: collection.docType = reflect.TypeOf(backingOpenedPorts{}) collection.subsidiary = true case remoteApplicationsC: collection.docType = reflect.TypeOf(backingRemoteApplication{}) case applicationOffersC: collection.docType = reflect.TypeOf(backingApplicationOffer{}) default: panic(errors.Errorf("unknown collection %q", collName)) } docType := collection.docType if _, ok := seenTypes[docType]; ok { panic(errors.Errorf("duplicate collection type %s", docType)) } seenTypes[docType] = struct{}{} if _, ok := collectionByName[collName]; ok { panic(errors.Errorf("duplicate collection name %q", collName)) } collectionByName[collName] = collection } return collectionByName }
go
func makeAllWatcherCollectionInfo(collNames ...string) map[string]allWatcherStateCollection { seenTypes := make(map[reflect.Type]struct{}) collectionByName := make(map[string]allWatcherStateCollection) for _, collName := range collNames { collection := allWatcherStateCollection{name: collName} switch collName { case modelsC: collection.docType = reflect.TypeOf(backingModel{}) case machinesC: collection.docType = reflect.TypeOf(backingMachine{}) case instanceDataC: collection.docType = reflect.TypeOf(backingInstanceData{}) collection.subsidiary = true case unitsC: collection.docType = reflect.TypeOf(backingUnit{}) case applicationsC: collection.docType = reflect.TypeOf(backingApplication{}) case charmsC: collection.docType = reflect.TypeOf(backingCharm{}) case actionsC: collection.docType = reflect.TypeOf(backingAction{}) case relationsC: collection.docType = reflect.TypeOf(backingRelation{}) case annotationsC: collection.docType = reflect.TypeOf(backingAnnotation{}) case blocksC: collection.docType = reflect.TypeOf(backingBlock{}) case statusesC: collection.docType = reflect.TypeOf(backingStatus{}) collection.subsidiary = true case constraintsC: collection.docType = reflect.TypeOf(backingConstraints{}) collection.subsidiary = true case settingsC: collection.docType = reflect.TypeOf(backingSettings{}) collection.subsidiary = true case openedPortsC: collection.docType = reflect.TypeOf(backingOpenedPorts{}) collection.subsidiary = true case remoteApplicationsC: collection.docType = reflect.TypeOf(backingRemoteApplication{}) case applicationOffersC: collection.docType = reflect.TypeOf(backingApplicationOffer{}) default: panic(errors.Errorf("unknown collection %q", collName)) } docType := collection.docType if _, ok := seenTypes[docType]; ok { panic(errors.Errorf("duplicate collection type %s", docType)) } seenTypes[docType] = struct{}{} if _, ok := collectionByName[collName]; ok { panic(errors.Errorf("duplicate collection name %q", collName)) } collectionByName[collName] = collection } return collectionByName }
[ "func", "makeAllWatcherCollectionInfo", "(", "collNames", "...", "string", ")", "map", "[", "string", "]", "allWatcherStateCollection", "{", "seenTypes", ":=", "make", "(", "map", "[", "reflect", ".", "Type", "]", "struct", "{", "}", ")", "\n", "collectionByName", ":=", "make", "(", "map", "[", "string", "]", "allWatcherStateCollection", ")", "\n\n", "for", "_", ",", "collName", ":=", "range", "collNames", "{", "collection", ":=", "allWatcherStateCollection", "{", "name", ":", "collName", "}", "\n", "switch", "collName", "{", "case", "modelsC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingModel", "{", "}", ")", "\n", "case", "machinesC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingMachine", "{", "}", ")", "\n", "case", "instanceDataC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingInstanceData", "{", "}", ")", "\n", "collection", ".", "subsidiary", "=", "true", "\n", "case", "unitsC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingUnit", "{", "}", ")", "\n", "case", "applicationsC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingApplication", "{", "}", ")", "\n", "case", "charmsC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingCharm", "{", "}", ")", "\n", "case", "actionsC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingAction", "{", "}", ")", "\n", "case", "relationsC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingRelation", "{", "}", ")", "\n", "case", "annotationsC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingAnnotation", "{", "}", ")", "\n", "case", "blocksC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingBlock", "{", "}", ")", "\n", "case", "statusesC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingStatus", "{", "}", ")", "\n", "collection", ".", "subsidiary", "=", "true", "\n", "case", "constraintsC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingConstraints", "{", "}", ")", "\n", "collection", ".", "subsidiary", "=", "true", "\n", "case", "settingsC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingSettings", "{", "}", ")", "\n", "collection", ".", "subsidiary", "=", "true", "\n", "case", "openedPortsC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingOpenedPorts", "{", "}", ")", "\n", "collection", ".", "subsidiary", "=", "true", "\n", "case", "remoteApplicationsC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingRemoteApplication", "{", "}", ")", "\n", "case", "applicationOffersC", ":", "collection", ".", "docType", "=", "reflect", ".", "TypeOf", "(", "backingApplicationOffer", "{", "}", ")", "\n", "default", ":", "panic", "(", "errors", ".", "Errorf", "(", "\"", "\"", ",", "collName", ")", ")", "\n", "}", "\n\n", "docType", ":=", "collection", ".", "docType", "\n", "if", "_", ",", "ok", ":=", "seenTypes", "[", "docType", "]", ";", "ok", "{", "panic", "(", "errors", ".", "Errorf", "(", "\"", "\"", ",", "docType", ")", ")", "\n", "}", "\n", "seenTypes", "[", "docType", "]", "=", "struct", "{", "}", "{", "}", "\n\n", "if", "_", ",", "ok", ":=", "collectionByName", "[", "collName", "]", ";", "ok", "{", "panic", "(", "errors", ".", "Errorf", "(", "\"", "\"", ",", "collName", ")", ")", "\n", "}", "\n", "collectionByName", "[", "collName", "]", "=", "collection", "\n", "}", "\n\n", "return", "collectionByName", "\n", "}" ]
// makeAllWatcherCollectionInfo returns a name indexed map of // allWatcherStateCollection instances for the collections specified.
[ "makeAllWatcherCollectionInfo", "returns", "a", "name", "indexed", "map", "of", "allWatcherStateCollection", "instances", "for", "the", "collections", "specified", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/allwatcher.go#L60-L121
156,962
juju/juju
state/allwatcher.go
getUnitAddresses
func getUnitAddresses(u *Unit) (string, string, error) { publicAddress, err := u.PublicAddress() if err != nil { logger.Infof("getting a public address for unit %q failed: %q", u.Name(), err) } privateAddress, err := u.PrivateAddress() if err != nil { logger.Infof("getting a private address for unit %q failed: %q", u.Name(), err) } return publicAddress.Value, privateAddress.Value, nil }
go
func getUnitAddresses(u *Unit) (string, string, error) { publicAddress, err := u.PublicAddress() if err != nil { logger.Infof("getting a public address for unit %q failed: %q", u.Name(), err) } privateAddress, err := u.PrivateAddress() if err != nil { logger.Infof("getting a private address for unit %q failed: %q", u.Name(), err) } return publicAddress.Value, privateAddress.Value, nil }
[ "func", "getUnitAddresses", "(", "u", "*", "Unit", ")", "(", "string", ",", "string", ",", "error", ")", "{", "publicAddress", ",", "err", ":=", "u", ".", "PublicAddress", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "u", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "privateAddress", ",", "err", ":=", "u", ".", "PrivateAddress", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "u", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "return", "publicAddress", ".", "Value", ",", "privateAddress", ".", "Value", ",", "nil", "\n", "}" ]
// getUnitAddresses returns the public and private addresses on a given unit. // As of 1.18, the addresses are stored on the assigned machine but we retain // this approach for backwards compatibility.
[ "getUnitAddresses", "returns", "the", "public", "and", "private", "addresses", "on", "a", "given", "unit", ".", "As", "of", "1", ".", "18", "the", "addresses", "are", "stored", "on", "the", "assigned", "machine", "but", "we", "retain", "this", "approach", "for", "backwards", "compatibility", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/allwatcher.go#L488-L498
156,963
juju/juju
state/allwatcher.go
backingEntityIdForSettingsKey
func backingEntityIdForSettingsKey(modelUUID, key string) (eid multiwatcher.EntityId, extra string, ok bool) { if !strings.HasPrefix(key, "a#") { eid, ok = backingEntityIdForGlobalKey(modelUUID, key) return } key = key[2:] i := strings.Index(key, "#") if i == -1 { return multiwatcher.EntityId{}, "", false } eid = (&multiwatcher.ApplicationInfo{ ModelUUID: modelUUID, Name: key[0:i], }).EntityId() extra = key[i+1:] ok = true return }
go
func backingEntityIdForSettingsKey(modelUUID, key string) (eid multiwatcher.EntityId, extra string, ok bool) { if !strings.HasPrefix(key, "a#") { eid, ok = backingEntityIdForGlobalKey(modelUUID, key) return } key = key[2:] i := strings.Index(key, "#") if i == -1 { return multiwatcher.EntityId{}, "", false } eid = (&multiwatcher.ApplicationInfo{ ModelUUID: modelUUID, Name: key[0:i], }).EntityId() extra = key[i+1:] ok = true return }
[ "func", "backingEntityIdForSettingsKey", "(", "modelUUID", ",", "key", "string", ")", "(", "eid", "multiwatcher", ".", "EntityId", ",", "extra", "string", ",", "ok", "bool", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "key", ",", "\"", "\"", ")", "{", "eid", ",", "ok", "=", "backingEntityIdForGlobalKey", "(", "modelUUID", ",", "key", ")", "\n", "return", "\n", "}", "\n", "key", "=", "key", "[", "2", ":", "]", "\n", "i", ":=", "strings", ".", "Index", "(", "key", ",", "\"", "\"", ")", "\n", "if", "i", "==", "-", "1", "{", "return", "multiwatcher", ".", "EntityId", "{", "}", ",", "\"", "\"", ",", "false", "\n", "}", "\n", "eid", "=", "(", "&", "multiwatcher", ".", "ApplicationInfo", "{", "ModelUUID", ":", "modelUUID", ",", "Name", ":", "key", "[", "0", ":", "i", "]", ",", "}", ")", ".", "EntityId", "(", ")", "\n", "extra", "=", "key", "[", "i", "+", "1", ":", "]", "\n", "ok", "=", "true", "\n", "return", "\n", "}" ]
// backingEntityIdForSettingsKey returns the entity id for the given // settings key. Any extra information in the key is returned in // extra.
[ "backingEntityIdForSettingsKey", "returns", "the", "entity", "id", "for", "the", "given", "settings", "key", ".", "Any", "extra", "information", "in", "the", "key", "is", "returned", "in", "extra", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/allwatcher.go#L1143-L1160
156,964
juju/juju
state/allwatcher.go
updateUnitPorts
func updateUnitPorts(st *State, store *multiwatcherStore, u *Unit) error { eid, ok := backingEntityIdForGlobalKey(st.ModelUUID(), u.globalKey()) if !ok { // This should never happen. return errors.New("cannot retrieve entity id for unit") } switch oldInfo := store.Get(eid).(type) { case nil: // The unit info doesn't exist. This is unlikely to happen, but ignore // the status until a unitInfo is included in the store. return nil case *multiwatcher.UnitInfo: portRanges, compatiblePorts, err := getUnitPortRangesAndPorts(st, oldInfo.Name) if err != nil { return errors.Trace(err) } unitInfo := *oldInfo unitInfo.PortRanges = toMultiwatcherPortRanges(portRanges) unitInfo.Ports = toMultiwatcherPorts(compatiblePorts) store.Update(&unitInfo) default: return nil } return nil }
go
func updateUnitPorts(st *State, store *multiwatcherStore, u *Unit) error { eid, ok := backingEntityIdForGlobalKey(st.ModelUUID(), u.globalKey()) if !ok { // This should never happen. return errors.New("cannot retrieve entity id for unit") } switch oldInfo := store.Get(eid).(type) { case nil: // The unit info doesn't exist. This is unlikely to happen, but ignore // the status until a unitInfo is included in the store. return nil case *multiwatcher.UnitInfo: portRanges, compatiblePorts, err := getUnitPortRangesAndPorts(st, oldInfo.Name) if err != nil { return errors.Trace(err) } unitInfo := *oldInfo unitInfo.PortRanges = toMultiwatcherPortRanges(portRanges) unitInfo.Ports = toMultiwatcherPorts(compatiblePorts) store.Update(&unitInfo) default: return nil } return nil }
[ "func", "updateUnitPorts", "(", "st", "*", "State", ",", "store", "*", "multiwatcherStore", ",", "u", "*", "Unit", ")", "error", "{", "eid", ",", "ok", ":=", "backingEntityIdForGlobalKey", "(", "st", ".", "ModelUUID", "(", ")", ",", "u", ".", "globalKey", "(", ")", ")", "\n", "if", "!", "ok", "{", "// This should never happen.", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "switch", "oldInfo", ":=", "store", ".", "Get", "(", "eid", ")", ".", "(", "type", ")", "{", "case", "nil", ":", "// The unit info doesn't exist. This is unlikely to happen, but ignore", "// the status until a unitInfo is included in the store.", "return", "nil", "\n", "case", "*", "multiwatcher", ".", "UnitInfo", ":", "portRanges", ",", "compatiblePorts", ",", "err", ":=", "getUnitPortRangesAndPorts", "(", "st", ",", "oldInfo", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "unitInfo", ":=", "*", "oldInfo", "\n", "unitInfo", ".", "PortRanges", "=", "toMultiwatcherPortRanges", "(", "portRanges", ")", "\n", "unitInfo", ".", "Ports", "=", "toMultiwatcherPorts", "(", "compatiblePorts", ")", "\n", "store", ".", "Update", "(", "&", "unitInfo", ")", "\n", "default", ":", "return", "nil", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// updateUnitPorts updates the Ports and PortRanges info of the given unit.
[ "updateUnitPorts", "updates", "the", "Ports", "and", "PortRanges", "info", "of", "the", "given", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/allwatcher.go#L1252-L1276
156,965
juju/juju
state/allwatcher.go
backingEntityIdForOpenedPortsKey
func backingEntityIdForOpenedPortsKey(modelUUID, key string) (multiwatcher.EntityId, bool) { parts, err := extractPortsIDParts(key) if err != nil { logger.Debugf("cannot parse ports key %q: %v", key, err) return multiwatcher.EntityId{}, false } return backingEntityIdForGlobalKey(modelUUID, machineGlobalKey(parts[1])) }
go
func backingEntityIdForOpenedPortsKey(modelUUID, key string) (multiwatcher.EntityId, bool) { parts, err := extractPortsIDParts(key) if err != nil { logger.Debugf("cannot parse ports key %q: %v", key, err) return multiwatcher.EntityId{}, false } return backingEntityIdForGlobalKey(modelUUID, machineGlobalKey(parts[1])) }
[ "func", "backingEntityIdForOpenedPortsKey", "(", "modelUUID", ",", "key", "string", ")", "(", "multiwatcher", ".", "EntityId", ",", "bool", ")", "{", "parts", ",", "err", ":=", "extractPortsIDParts", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "key", ",", "err", ")", "\n", "return", "multiwatcher", ".", "EntityId", "{", "}", ",", "false", "\n", "}", "\n", "return", "backingEntityIdForGlobalKey", "(", "modelUUID", ",", "machineGlobalKey", "(", "parts", "[", "1", "]", ")", ")", "\n", "}" ]
// backingEntityIdForOpenedPortsKey returns the entity id for the given // openedPorts key. Any extra information in the key is discarded.
[ "backingEntityIdForOpenedPortsKey", "returns", "the", "entity", "id", "for", "the", "given", "openedPorts", "key", ".", "Any", "extra", "information", "in", "the", "key", "is", "discarded", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/allwatcher.go#L1280-L1287
156,966
juju/juju
state/allwatcher.go
backingEntityIdForGlobalKey
func backingEntityIdForGlobalKey(modelUUID, key string) (multiwatcher.EntityId, bool) { if key == modelGlobalKey { return (&multiwatcher.ModelInfo{ ModelUUID: modelUUID, }).EntityId(), true } else if len(key) < 3 || key[1] != '#' { return multiwatcher.EntityId{}, false } id := key[2:] switch key[0] { case 'm': id = strings.TrimSuffix(id, "#instance") return (&multiwatcher.MachineInfo{ ModelUUID: modelUUID, Id: id, }).EntityId(), true case 'u': id = strings.TrimSuffix(id, "#charm") return (&multiwatcher.UnitInfo{ ModelUUID: modelUUID, Name: id, }).EntityId(), true case 'a': return (&multiwatcher.ApplicationInfo{ ModelUUID: modelUUID, Name: id, }).EntityId(), true case 'c': return (&multiwatcher.RemoteApplicationInfo{ ModelUUID: modelUUID, Name: id, }).EntityId(), true default: return multiwatcher.EntityId{}, false } }
go
func backingEntityIdForGlobalKey(modelUUID, key string) (multiwatcher.EntityId, bool) { if key == modelGlobalKey { return (&multiwatcher.ModelInfo{ ModelUUID: modelUUID, }).EntityId(), true } else if len(key) < 3 || key[1] != '#' { return multiwatcher.EntityId{}, false } id := key[2:] switch key[0] { case 'm': id = strings.TrimSuffix(id, "#instance") return (&multiwatcher.MachineInfo{ ModelUUID: modelUUID, Id: id, }).EntityId(), true case 'u': id = strings.TrimSuffix(id, "#charm") return (&multiwatcher.UnitInfo{ ModelUUID: modelUUID, Name: id, }).EntityId(), true case 'a': return (&multiwatcher.ApplicationInfo{ ModelUUID: modelUUID, Name: id, }).EntityId(), true case 'c': return (&multiwatcher.RemoteApplicationInfo{ ModelUUID: modelUUID, Name: id, }).EntityId(), true default: return multiwatcher.EntityId{}, false } }
[ "func", "backingEntityIdForGlobalKey", "(", "modelUUID", ",", "key", "string", ")", "(", "multiwatcher", ".", "EntityId", ",", "bool", ")", "{", "if", "key", "==", "modelGlobalKey", "{", "return", "(", "&", "multiwatcher", ".", "ModelInfo", "{", "ModelUUID", ":", "modelUUID", ",", "}", ")", ".", "EntityId", "(", ")", ",", "true", "\n", "}", "else", "if", "len", "(", "key", ")", "<", "3", "||", "key", "[", "1", "]", "!=", "'#'", "{", "return", "multiwatcher", ".", "EntityId", "{", "}", ",", "false", "\n", "}", "\n", "id", ":=", "key", "[", "2", ":", "]", "\n", "switch", "key", "[", "0", "]", "{", "case", "'m'", ":", "id", "=", "strings", ".", "TrimSuffix", "(", "id", ",", "\"", "\"", ")", "\n", "return", "(", "&", "multiwatcher", ".", "MachineInfo", "{", "ModelUUID", ":", "modelUUID", ",", "Id", ":", "id", ",", "}", ")", ".", "EntityId", "(", ")", ",", "true", "\n", "case", "'u'", ":", "id", "=", "strings", ".", "TrimSuffix", "(", "id", ",", "\"", "\"", ")", "\n", "return", "(", "&", "multiwatcher", ".", "UnitInfo", "{", "ModelUUID", ":", "modelUUID", ",", "Name", ":", "id", ",", "}", ")", ".", "EntityId", "(", ")", ",", "true", "\n", "case", "'a'", ":", "return", "(", "&", "multiwatcher", ".", "ApplicationInfo", "{", "ModelUUID", ":", "modelUUID", ",", "Name", ":", "id", ",", "}", ")", ".", "EntityId", "(", ")", ",", "true", "\n", "case", "'c'", ":", "return", "(", "&", "multiwatcher", ".", "RemoteApplicationInfo", "{", "ModelUUID", ":", "modelUUID", ",", "Name", ":", "id", ",", "}", ")", ".", "EntityId", "(", ")", ",", "true", "\n", "default", ":", "return", "multiwatcher", ".", "EntityId", "{", "}", ",", "false", "\n", "}", "\n", "}" ]
// backingEntityIdForGlobalKey returns the entity id for the given global key. // It returns false if the key is not recognized.
[ "backingEntityIdForGlobalKey", "returns", "the", "entity", "id", "for", "the", "given", "global", "key", ".", "It", "returns", "false", "if", "the", "key", "is", "not", "recognized", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/allwatcher.go#L1291-L1326
156,967
juju/juju
state/allwatcher.go
Unwatch
func (b *allModelWatcherStateBacking) Unwatch(in chan<- watcher.Change) { for _, c := range b.collectionByName { b.watcher.UnwatchCollection(c.name, in) } }
go
func (b *allModelWatcherStateBacking) Unwatch(in chan<- watcher.Change) { for _, c := range b.collectionByName { b.watcher.UnwatchCollection(c.name, in) } }
[ "func", "(", "b", "*", "allModelWatcherStateBacking", ")", "Unwatch", "(", "in", "chan", "<-", "watcher", ".", "Change", ")", "{", "for", "_", ",", "c", ":=", "range", "b", ".", "collectionByName", "{", "b", ".", "watcher", ".", "UnwatchCollection", "(", "c", ".", "name", ",", "in", ")", "\n", "}", "\n", "}" ]
// Unwatch unwatches all the collections.
[ "Unwatch", "unwatches", "all", "the", "collections", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/allwatcher.go#L1468-L1472
156,968
juju/juju
apiserver/facades/agent/logger/logger.go
NewLoggerAPI
func NewLoggerAPI(ctx facade.Context) (*LoggerAPI, error) { st := ctx.State() resources := ctx.Resources() authorizer := ctx.Auth() if !authorizer.AuthMachineAgent() && !authorizer.AuthUnitAgent() && !authorizer.AuthApplicationAgent() { return nil, common.ErrPerm } m, err := ctx.Controller().Model(st.ModelUUID()) if err != nil { return nil, err } return &LoggerAPI{ controller: ctx.Controller(), model: m, resources: resources, authorizer: authorizer, }, nil }
go
func NewLoggerAPI(ctx facade.Context) (*LoggerAPI, error) { st := ctx.State() resources := ctx.Resources() authorizer := ctx.Auth() if !authorizer.AuthMachineAgent() && !authorizer.AuthUnitAgent() && !authorizer.AuthApplicationAgent() { return nil, common.ErrPerm } m, err := ctx.Controller().Model(st.ModelUUID()) if err != nil { return nil, err } return &LoggerAPI{ controller: ctx.Controller(), model: m, resources: resources, authorizer: authorizer, }, nil }
[ "func", "NewLoggerAPI", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "LoggerAPI", ",", "error", ")", "{", "st", ":=", "ctx", ".", "State", "(", ")", "\n", "resources", ":=", "ctx", ".", "Resources", "(", ")", "\n", "authorizer", ":=", "ctx", ".", "Auth", "(", ")", "\n\n", "if", "!", "authorizer", ".", "AuthMachineAgent", "(", ")", "&&", "!", "authorizer", ".", "AuthUnitAgent", "(", ")", "&&", "!", "authorizer", ".", "AuthApplicationAgent", "(", ")", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n", "m", ",", "err", ":=", "ctx", ".", "Controller", "(", ")", ".", "Model", "(", "st", ".", "ModelUUID", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "LoggerAPI", "{", "controller", ":", "ctx", ".", "Controller", "(", ")", ",", "model", ":", "m", ",", "resources", ":", "resources", ",", "authorizer", ":", "authorizer", ",", "}", ",", "nil", "\n", "}" ]
// NewLoggerAPI creates a new server-side logger API end point.
[ "NewLoggerAPI", "creates", "a", "new", "server", "-", "side", "logger", "API", "end", "point", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/logger/logger.go#L38-L57
156,969
juju/juju
apiserver/facades/agent/logger/logger.go
WatchLoggingConfig
func (api *LoggerAPI) WatchLoggingConfig(arg params.Entities) params.NotifyWatchResults { result := make([]params.NotifyWatchResult, len(arg.Entities)) for i, entity := range arg.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { result[i].Error = common.ServerError(err) continue } err = common.ErrPerm if api.authorizer.AuthOwner(tag) { watch := api.model.WatchConfig("logging-config") // Consume the initial event. Technically, API calls to Watch // 'transmit' the initial event in the Watch response. But // NotifyWatchers have no state to transmit. if _, ok := <-watch.Changes(); ok { result[i].NotifyWatcherId = api.resources.Register(watch) err = nil } else { err = errors.New("programming error: channel should not be closed") } } result[i].Error = common.ServerError(err) } return params.NotifyWatchResults{Results: result} }
go
func (api *LoggerAPI) WatchLoggingConfig(arg params.Entities) params.NotifyWatchResults { result := make([]params.NotifyWatchResult, len(arg.Entities)) for i, entity := range arg.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { result[i].Error = common.ServerError(err) continue } err = common.ErrPerm if api.authorizer.AuthOwner(tag) { watch := api.model.WatchConfig("logging-config") // Consume the initial event. Technically, API calls to Watch // 'transmit' the initial event in the Watch response. But // NotifyWatchers have no state to transmit. if _, ok := <-watch.Changes(); ok { result[i].NotifyWatcherId = api.resources.Register(watch) err = nil } else { err = errors.New("programming error: channel should not be closed") } } result[i].Error = common.ServerError(err) } return params.NotifyWatchResults{Results: result} }
[ "func", "(", "api", "*", "LoggerAPI", ")", "WatchLoggingConfig", "(", "arg", "params", ".", "Entities", ")", "params", ".", "NotifyWatchResults", "{", "result", ":=", "make", "(", "[", "]", "params", ".", "NotifyWatchResult", ",", "len", "(", "arg", ".", "Entities", ")", ")", "\n", "for", "i", ",", "entity", ":=", "range", "arg", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "err", "=", "common", ".", "ErrPerm", "\n", "if", "api", ".", "authorizer", ".", "AuthOwner", "(", "tag", ")", "{", "watch", ":=", "api", ".", "model", ".", "WatchConfig", "(", "\"", "\"", ")", "\n", "// Consume the initial event. Technically, API calls to Watch", "// 'transmit' the initial event in the Watch response. But", "// NotifyWatchers have no state to transmit.", "if", "_", ",", "ok", ":=", "<-", "watch", ".", "Changes", "(", ")", ";", "ok", "{", "result", "[", "i", "]", ".", "NotifyWatcherId", "=", "api", ".", "resources", ".", "Register", "(", "watch", ")", "\n", "err", "=", "nil", "\n", "}", "else", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "result", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "params", ".", "NotifyWatchResults", "{", "Results", ":", "result", "}", "\n", "}" ]
// WatchLoggingConfig starts a watcher to track changes to the logging config // for the agents specified.. Unfortunately the current infrastructure makes // watching parts of the config non-trivial, so currently any change to the // config will cause the watcher to notify the client.
[ "WatchLoggingConfig", "starts", "a", "watcher", "to", "track", "changes", "to", "the", "logging", "config", "for", "the", "agents", "specified", "..", "Unfortunately", "the", "current", "infrastructure", "makes", "watching", "parts", "of", "the", "config", "non", "-", "trivial", "so", "currently", "any", "change", "to", "the", "config", "will", "cause", "the", "watcher", "to", "notify", "the", "client", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/logger/logger.go#L63-L87
156,970
juju/juju
apiserver/facades/agent/logger/logger.go
LoggingConfig
func (api *LoggerAPI) LoggingConfig(arg params.Entities) params.StringResults { if len(arg.Entities) == 0 { return params.StringResults{} } results := make([]params.StringResult, len(arg.Entities)) // TODO: ensure that the cache model can return a proper config object. config, configErr := config.New(config.NoDefaults, api.model.Config()) for i, entity := range arg.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { results[i].Error = common.ServerError(err) continue } err = common.ErrPerm if api.authorizer.AuthOwner(tag) { if configErr == nil { results[i].Result = config.LoggingConfig() err = nil } else { err = configErr } } results[i].Error = common.ServerError(err) } return params.StringResults{Results: results} }
go
func (api *LoggerAPI) LoggingConfig(arg params.Entities) params.StringResults { if len(arg.Entities) == 0 { return params.StringResults{} } results := make([]params.StringResult, len(arg.Entities)) // TODO: ensure that the cache model can return a proper config object. config, configErr := config.New(config.NoDefaults, api.model.Config()) for i, entity := range arg.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { results[i].Error = common.ServerError(err) continue } err = common.ErrPerm if api.authorizer.AuthOwner(tag) { if configErr == nil { results[i].Result = config.LoggingConfig() err = nil } else { err = configErr } } results[i].Error = common.ServerError(err) } return params.StringResults{Results: results} }
[ "func", "(", "api", "*", "LoggerAPI", ")", "LoggingConfig", "(", "arg", "params", ".", "Entities", ")", "params", ".", "StringResults", "{", "if", "len", "(", "arg", ".", "Entities", ")", "==", "0", "{", "return", "params", ".", "StringResults", "{", "}", "\n", "}", "\n", "results", ":=", "make", "(", "[", "]", "params", ".", "StringResult", ",", "len", "(", "arg", ".", "Entities", ")", ")", "\n", "// TODO: ensure that the cache model can return a proper config object.", "config", ",", "configErr", ":=", "config", ".", "New", "(", "config", ".", "NoDefaults", ",", "api", ".", "model", ".", "Config", "(", ")", ")", "\n", "for", "i", ",", "entity", ":=", "range", "arg", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "err", "=", "common", ".", "ErrPerm", "\n", "if", "api", ".", "authorizer", ".", "AuthOwner", "(", "tag", ")", "{", "if", "configErr", "==", "nil", "{", "results", "[", "i", "]", ".", "Result", "=", "config", ".", "LoggingConfig", "(", ")", "\n", "err", "=", "nil", "\n", "}", "else", "{", "err", "=", "configErr", "\n", "}", "\n", "}", "\n", "results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "params", ".", "StringResults", "{", "Results", ":", "results", "}", "\n", "}" ]
// LoggingConfig reports the logging configuration for the agents specified.
[ "LoggingConfig", "reports", "the", "logging", "configuration", "for", "the", "agents", "specified", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/logger/logger.go#L90-L115
156,971
juju/juju
core/raftlease/fsm.go
groupKeyFor
func groupKeyFor(key lease.Key) groupKey { return groupKey{ namespace: key.Namespace, modelUUID: key.ModelUUID, } }
go
func groupKeyFor(key lease.Key) groupKey { return groupKey{ namespace: key.Namespace, modelUUID: key.ModelUUID, } }
[ "func", "groupKeyFor", "(", "key", "lease", ".", "Key", ")", "groupKey", "{", "return", "groupKey", "{", "namespace", ":", "key", ".", "Namespace", ",", "modelUUID", ":", "key", ".", "ModelUUID", ",", "}", "\n", "}" ]
// groupKeyFor builds a group key for the given lease key.
[ "groupKeyFor", "builds", "a", "group", "key", "for", "the", "given", "lease", "key", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L70-L75
156,972
juju/juju
core/raftlease/fsm.go
NewFSM
func NewFSM() *FSM { return &FSM{ groups: make(map[groupKey]map[lease.Key]*entry), pinned: make(map[lease.Key]set.Strings), } }
go
func NewFSM() *FSM { return &FSM{ groups: make(map[groupKey]map[lease.Key]*entry), pinned: make(map[lease.Key]set.Strings), } }
[ "func", "NewFSM", "(", ")", "*", "FSM", "{", "return", "&", "FSM", "{", "groups", ":", "make", "(", "map", "[", "groupKey", "]", "map", "[", "lease", ".", "Key", "]", "*", "entry", ")", ",", "pinned", ":", "make", "(", "map", "[", "lease", ".", "Key", "]", "set", ".", "Strings", ")", ",", "}", "\n", "}" ]
// NewFSM returns a new FSM to store lease information.
[ "NewFSM", "returns", "a", "new", "FSM", "to", "store", "lease", "information", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L78-L83
156,973
juju/juju
core/raftlease/fsm.go
removeExpired
func (f *FSM) removeExpired(newTime time.Time) []lease.Key { var expired []lease.Key for gKey, entries := range f.groups { for key, entry := range entries { expiry := entry.start.Add(entry.duration) if expiry.Before(newTime) && !f.isPinned(key) { delete(entries, key) expired = append(expired, key) } } if len(entries) == 0 { delete(f.groups, gKey) } } return expired }
go
func (f *FSM) removeExpired(newTime time.Time) []lease.Key { var expired []lease.Key for gKey, entries := range f.groups { for key, entry := range entries { expiry := entry.start.Add(entry.duration) if expiry.Before(newTime) && !f.isPinned(key) { delete(entries, key) expired = append(expired, key) } } if len(entries) == 0 { delete(f.groups, gKey) } } return expired }
[ "func", "(", "f", "*", "FSM", ")", "removeExpired", "(", "newTime", "time", ".", "Time", ")", "[", "]", "lease", ".", "Key", "{", "var", "expired", "[", "]", "lease", ".", "Key", "\n", "for", "gKey", ",", "entries", ":=", "range", "f", ".", "groups", "{", "for", "key", ",", "entry", ":=", "range", "entries", "{", "expiry", ":=", "entry", ".", "start", ".", "Add", "(", "entry", ".", "duration", ")", "\n", "if", "expiry", ".", "Before", "(", "newTime", ")", "&&", "!", "f", ".", "isPinned", "(", "key", ")", "{", "delete", "(", "entries", ",", "key", ")", "\n", "expired", "=", "append", "(", "expired", ",", "key", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "entries", ")", "==", "0", "{", "delete", "(", "f", ".", "groups", ",", "gKey", ")", "\n", "}", "\n", "}", "\n", "return", "expired", "\n", "}" ]
// expired returns a collection of keys for leases that have expired. // Any pinned leases are not included in the return.
[ "expired", "returns", "a", "collection", "of", "keys", "for", "leases", "that", "have", "expired", ".", "Any", "pinned", "leases", "are", "not", "included", "in", "the", "return", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L179-L194
156,974
juju/juju
core/raftlease/fsm.go
Leases
func (f *FSM) Leases(getLocalTime func() time.Time, keys ...lease.Key) map[lease.Key]lease.Info { if len(keys) > 0 { return f.filteredLeases(getLocalTime, keys) } return f.allLeases(getLocalTime) }
go
func (f *FSM) Leases(getLocalTime func() time.Time, keys ...lease.Key) map[lease.Key]lease.Info { if len(keys) > 0 { return f.filteredLeases(getLocalTime, keys) } return f.allLeases(getLocalTime) }
[ "func", "(", "f", "*", "FSM", ")", "Leases", "(", "getLocalTime", "func", "(", ")", "time", ".", "Time", ",", "keys", "...", "lease", ".", "Key", ")", "map", "[", "lease", ".", "Key", "]", "lease", ".", "Info", "{", "if", "len", "(", "keys", ")", ">", "0", "{", "return", "f", ".", "filteredLeases", "(", "getLocalTime", ",", "keys", ")", "\n", "}", "\n", "return", "f", ".", "allLeases", "(", "getLocalTime", ")", "\n", "}" ]
// Leases gets information about all of the leases in the system, // optionally filtered by the input lease keys.
[ "Leases", "gets", "information", "about", "all", "of", "the", "leases", "in", "the", "system", "optionally", "filtered", "by", "the", "input", "lease", "keys", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L203-L208
156,975
juju/juju
core/raftlease/fsm.go
filteredLeases
func (f *FSM) filteredLeases(getLocalTime func() time.Time, keys []lease.Key) map[lease.Key]lease.Info { results := make(map[lease.Key]lease.Info) f.mu.Lock() localTime := getLocalTime() for _, key := range keys { entries, found := f.getGroup(key) if !found { continue } if entry, ok := entries[key]; ok { results[key] = f.infoFromEntry(localTime, key, entry) } } f.mu.Unlock() return results }
go
func (f *FSM) filteredLeases(getLocalTime func() time.Time, keys []lease.Key) map[lease.Key]lease.Info { results := make(map[lease.Key]lease.Info) f.mu.Lock() localTime := getLocalTime() for _, key := range keys { entries, found := f.getGroup(key) if !found { continue } if entry, ok := entries[key]; ok { results[key] = f.infoFromEntry(localTime, key, entry) } } f.mu.Unlock() return results }
[ "func", "(", "f", "*", "FSM", ")", "filteredLeases", "(", "getLocalTime", "func", "(", ")", "time", ".", "Time", ",", "keys", "[", "]", "lease", ".", "Key", ")", "map", "[", "lease", ".", "Key", "]", "lease", ".", "Info", "{", "results", ":=", "make", "(", "map", "[", "lease", ".", "Key", "]", "lease", ".", "Info", ")", "\n", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "localTime", ":=", "getLocalTime", "(", ")", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "entries", ",", "found", ":=", "f", ".", "getGroup", "(", "key", ")", "\n", "if", "!", "found", "{", "continue", "\n", "}", "\n", "if", "entry", ",", "ok", ":=", "entries", "[", "key", "]", ";", "ok", "{", "results", "[", "key", "]", "=", "f", ".", "infoFromEntry", "(", "localTime", ",", "key", ",", "entry", ")", "\n", "}", "\n", "}", "\n", "f", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "results", "\n", "}" ]
// filteredLeases is an optimisation for anticipated usage. // There will usually be a single key for filtering, so iterating over the // filter list and retrieving from entries will be fastest by far.
[ "filteredLeases", "is", "an", "optimisation", "for", "anticipated", "usage", ".", "There", "will", "usually", "be", "a", "single", "key", "for", "filtering", "so", "iterating", "over", "the", "filter", "list", "and", "retrieving", "from", "entries", "will", "be", "fastest", "by", "far", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L213-L228
156,976
juju/juju
core/raftlease/fsm.go
Pinned
func (f *FSM) Pinned() map[lease.Key][]string { f.mu.Lock() pinned := make(map[lease.Key][]string) for key, entities := range f.pinned { if !entities.IsEmpty() { pinned[key] = entities.SortedValues() } } f.mu.Unlock() return pinned }
go
func (f *FSM) Pinned() map[lease.Key][]string { f.mu.Lock() pinned := make(map[lease.Key][]string) for key, entities := range f.pinned { if !entities.IsEmpty() { pinned[key] = entities.SortedValues() } } f.mu.Unlock() return pinned }
[ "func", "(", "f", "*", "FSM", ")", "Pinned", "(", ")", "map", "[", "lease", ".", "Key", "]", "[", "]", "string", "{", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "pinned", ":=", "make", "(", "map", "[", "lease", ".", "Key", "]", "[", "]", "string", ")", "\n", "for", "key", ",", "entities", ":=", "range", "f", ".", "pinned", "{", "if", "!", "entities", ".", "IsEmpty", "(", ")", "{", "pinned", "[", "key", "]", "=", "entities", ".", "SortedValues", "(", ")", "\n", "}", "\n", "}", "\n", "f", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "pinned", "\n", "}" ]
// Pinned returns all of the currently known lease pins and applications // requiring the pinned behaviour.
[ "Pinned", "returns", "all", "of", "the", "currently", "known", "lease", "pins", "and", "applications", "requiring", "the", "pinned", "behaviour", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L263-L273
156,977
juju/juju
core/raftlease/fsm.go
Notify
func (r *response) Notify(target NotifyTarget) { // This response is either for a claim (in which case claimer will // be set) or a set-time (so it will have zero or more expiries). if r.claimer != "" { target.Claimed(r.claimed, r.claimer) } for _, expiredKey := range r.expired { target.Expired(expiredKey) } }
go
func (r *response) Notify(target NotifyTarget) { // This response is either for a claim (in which case claimer will // be set) or a set-time (so it will have zero or more expiries). if r.claimer != "" { target.Claimed(r.claimed, r.claimer) } for _, expiredKey := range r.expired { target.Expired(expiredKey) } }
[ "func", "(", "r", "*", "response", ")", "Notify", "(", "target", "NotifyTarget", ")", "{", "// This response is either for a claim (in which case claimer will", "// be set) or a set-time (so it will have zero or more expiries).", "if", "r", ".", "claimer", "!=", "\"", "\"", "{", "target", ".", "Claimed", "(", "r", ".", "claimed", ",", "r", ".", "claimer", ")", "\n", "}", "\n", "for", "_", ",", "expiredKey", ":=", "range", "r", ".", "expired", "{", "target", ".", "Expired", "(", "expiredKey", ")", "\n", "}", "\n", "}" ]
// Notify is part of FSMResponse.
[ "Notify", "is", "part", "of", "FSMResponse", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L308-L317
156,978
juju/juju
core/raftlease/fsm.go
Apply
func (f *FSM) Apply(log *raft.Log) interface{} { var command Command err := yaml.Unmarshal(log.Data, &command) if err != nil { return &response{err: errors.Trace(err)} } if err := command.Validate(); err != nil { return &response{err: errors.Trace(err)} } f.mu.Lock() defer f.mu.Unlock() switch command.Operation { case OperationClaim: return f.claim(command.LeaseKey(), command.Holder, command.Duration) case OperationExtend: return f.extend(command.LeaseKey(), command.Holder, command.Duration) case OperationPin: return f.pin(command.LeaseKey(), command.PinEntity) case OperationUnpin: return f.unpin(command.LeaseKey(), command.PinEntity) case OperationSetTime: return f.setTime(command.OldTime, command.NewTime) default: return &response{err: errors.NotValidf("operation %q", command.Operation)} } }
go
func (f *FSM) Apply(log *raft.Log) interface{} { var command Command err := yaml.Unmarshal(log.Data, &command) if err != nil { return &response{err: errors.Trace(err)} } if err := command.Validate(); err != nil { return &response{err: errors.Trace(err)} } f.mu.Lock() defer f.mu.Unlock() switch command.Operation { case OperationClaim: return f.claim(command.LeaseKey(), command.Holder, command.Duration) case OperationExtend: return f.extend(command.LeaseKey(), command.Holder, command.Duration) case OperationPin: return f.pin(command.LeaseKey(), command.PinEntity) case OperationUnpin: return f.unpin(command.LeaseKey(), command.PinEntity) case OperationSetTime: return f.setTime(command.OldTime, command.NewTime) default: return &response{err: errors.NotValidf("operation %q", command.Operation)} } }
[ "func", "(", "f", "*", "FSM", ")", "Apply", "(", "log", "*", "raft", ".", "Log", ")", "interface", "{", "}", "{", "var", "command", "Command", "\n", "err", ":=", "yaml", ".", "Unmarshal", "(", "log", ".", "Data", ",", "&", "command", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "response", "{", "err", ":", "errors", ".", "Trace", "(", "err", ")", "}", "\n", "}", "\n", "if", "err", ":=", "command", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "&", "response", "{", "err", ":", "errors", ".", "Trace", "(", "err", ")", "}", "\n", "}", "\n\n", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "switch", "command", ".", "Operation", "{", "case", "OperationClaim", ":", "return", "f", ".", "claim", "(", "command", ".", "LeaseKey", "(", ")", ",", "command", ".", "Holder", ",", "command", ".", "Duration", ")", "\n", "case", "OperationExtend", ":", "return", "f", ".", "extend", "(", "command", ".", "LeaseKey", "(", ")", ",", "command", ".", "Holder", ",", "command", ".", "Duration", ")", "\n", "case", "OperationPin", ":", "return", "f", ".", "pin", "(", "command", ".", "LeaseKey", "(", ")", ",", "command", ".", "PinEntity", ")", "\n", "case", "OperationUnpin", ":", "return", "f", ".", "unpin", "(", "command", ".", "LeaseKey", "(", ")", ",", "command", ".", "PinEntity", ")", "\n", "case", "OperationSetTime", ":", "return", "f", ".", "setTime", "(", "command", ".", "OldTime", ",", "command", ".", "NewTime", ")", "\n", "default", ":", "return", "&", "response", "{", "err", ":", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "command", ".", "Operation", ")", "}", "\n", "}", "\n", "}" ]
// Apply is part of raft.FSM.
[ "Apply", "is", "part", "of", "raft", ".", "FSM", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L324-L351
156,979
juju/juju
core/raftlease/fsm.go
Snapshot
func (f *FSM) Snapshot() (raft.FSMSnapshot, error) { f.mu.Lock() entries := make(map[SnapshotKey]SnapshotEntry) for _, group := range f.groups { for key, entry := range group { entries[SnapshotKey{ Namespace: key.Namespace, ModelUUID: key.ModelUUID, Lease: key.Lease, }] = SnapshotEntry{ Holder: entry.holder, Start: entry.start, Duration: entry.duration, } } } pinned := make(map[SnapshotKey][]string) for key, entities := range f.pinned { if entities.IsEmpty() { continue } pinned[SnapshotKey{ Namespace: key.Namespace, ModelUUID: key.ModelUUID, Lease: key.Lease, }] = entities.SortedValues() } f.mu.Unlock() return &Snapshot{ Version: SnapshotVersion, Entries: entries, Pinned: pinned, GlobalTime: f.globalTime, }, nil }
go
func (f *FSM) Snapshot() (raft.FSMSnapshot, error) { f.mu.Lock() entries := make(map[SnapshotKey]SnapshotEntry) for _, group := range f.groups { for key, entry := range group { entries[SnapshotKey{ Namespace: key.Namespace, ModelUUID: key.ModelUUID, Lease: key.Lease, }] = SnapshotEntry{ Holder: entry.holder, Start: entry.start, Duration: entry.duration, } } } pinned := make(map[SnapshotKey][]string) for key, entities := range f.pinned { if entities.IsEmpty() { continue } pinned[SnapshotKey{ Namespace: key.Namespace, ModelUUID: key.ModelUUID, Lease: key.Lease, }] = entities.SortedValues() } f.mu.Unlock() return &Snapshot{ Version: SnapshotVersion, Entries: entries, Pinned: pinned, GlobalTime: f.globalTime, }, nil }
[ "func", "(", "f", "*", "FSM", ")", "Snapshot", "(", ")", "(", "raft", ".", "FSMSnapshot", ",", "error", ")", "{", "f", ".", "mu", ".", "Lock", "(", ")", "\n\n", "entries", ":=", "make", "(", "map", "[", "SnapshotKey", "]", "SnapshotEntry", ")", "\n", "for", "_", ",", "group", ":=", "range", "f", ".", "groups", "{", "for", "key", ",", "entry", ":=", "range", "group", "{", "entries", "[", "SnapshotKey", "{", "Namespace", ":", "key", ".", "Namespace", ",", "ModelUUID", ":", "key", ".", "ModelUUID", ",", "Lease", ":", "key", ".", "Lease", ",", "}", "]", "=", "SnapshotEntry", "{", "Holder", ":", "entry", ".", "holder", ",", "Start", ":", "entry", ".", "start", ",", "Duration", ":", "entry", ".", "duration", ",", "}", "\n", "}", "\n", "}", "\n\n", "pinned", ":=", "make", "(", "map", "[", "SnapshotKey", "]", "[", "]", "string", ")", "\n", "for", "key", ",", "entities", ":=", "range", "f", ".", "pinned", "{", "if", "entities", ".", "IsEmpty", "(", ")", "{", "continue", "\n", "}", "\n", "pinned", "[", "SnapshotKey", "{", "Namespace", ":", "key", ".", "Namespace", ",", "ModelUUID", ":", "key", ".", "ModelUUID", ",", "Lease", ":", "key", ".", "Lease", ",", "}", "]", "=", "entities", ".", "SortedValues", "(", ")", "\n", "}", "\n\n", "f", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "&", "Snapshot", "{", "Version", ":", "SnapshotVersion", ",", "Entries", ":", "entries", ",", "Pinned", ":", "pinned", ",", "GlobalTime", ":", "f", ".", "globalTime", ",", "}", ",", "nil", "\n", "}" ]
// Snapshot is part of raft.FSM.
[ "Snapshot", "is", "part", "of", "raft", ".", "FSM", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L354-L392
156,980
juju/juju
core/raftlease/fsm.go
Restore
func (f *FSM) Restore(reader io.ReadCloser) error { defer reader.Close() var snapshot Snapshot decoder := yaml.NewDecoder(reader) if err := decoder.Decode(&snapshot); err != nil { return errors.Trace(err) } if snapshot.Version != SnapshotVersion { return errors.NotValidf("snapshot version %d", snapshot.Version) } if snapshot.Entries == nil { return errors.NotValidf("nil entries") } newGroups := make(map[groupKey]map[lease.Key]*entry, len(snapshot.Entries)) for key, ssEntry := range snapshot.Entries { gKey := groupKey{ namespace: key.Namespace, modelUUID: key.ModelUUID, } newEntries, found := newGroups[gKey] if !found { newEntries = make(map[lease.Key]*entry) newGroups[gKey] = newEntries } newEntries[lease.Key{ Namespace: key.Namespace, ModelUUID: key.ModelUUID, Lease: key.Lease, }] = &entry{ holder: ssEntry.Holder, start: ssEntry.Start, duration: ssEntry.Duration, } } newPinned := make(map[lease.Key]set.Strings, len(snapshot.Pinned)) for key, entities := range snapshot.Pinned { newPinned[lease.Key{ Namespace: key.Namespace, ModelUUID: key.ModelUUID, Lease: key.Lease, }] = set.NewStrings(entities...) } f.mu.Lock() f.globalTime = snapshot.GlobalTime f.groups = newGroups f.pinned = newPinned f.mu.Unlock() return nil }
go
func (f *FSM) Restore(reader io.ReadCloser) error { defer reader.Close() var snapshot Snapshot decoder := yaml.NewDecoder(reader) if err := decoder.Decode(&snapshot); err != nil { return errors.Trace(err) } if snapshot.Version != SnapshotVersion { return errors.NotValidf("snapshot version %d", snapshot.Version) } if snapshot.Entries == nil { return errors.NotValidf("nil entries") } newGroups := make(map[groupKey]map[lease.Key]*entry, len(snapshot.Entries)) for key, ssEntry := range snapshot.Entries { gKey := groupKey{ namespace: key.Namespace, modelUUID: key.ModelUUID, } newEntries, found := newGroups[gKey] if !found { newEntries = make(map[lease.Key]*entry) newGroups[gKey] = newEntries } newEntries[lease.Key{ Namespace: key.Namespace, ModelUUID: key.ModelUUID, Lease: key.Lease, }] = &entry{ holder: ssEntry.Holder, start: ssEntry.Start, duration: ssEntry.Duration, } } newPinned := make(map[lease.Key]set.Strings, len(snapshot.Pinned)) for key, entities := range snapshot.Pinned { newPinned[lease.Key{ Namespace: key.Namespace, ModelUUID: key.ModelUUID, Lease: key.Lease, }] = set.NewStrings(entities...) } f.mu.Lock() f.globalTime = snapshot.GlobalTime f.groups = newGroups f.pinned = newPinned f.mu.Unlock() return nil }
[ "func", "(", "f", "*", "FSM", ")", "Restore", "(", "reader", "io", ".", "ReadCloser", ")", "error", "{", "defer", "reader", ".", "Close", "(", ")", "\n\n", "var", "snapshot", "Snapshot", "\n", "decoder", ":=", "yaml", ".", "NewDecoder", "(", "reader", ")", "\n", "if", "err", ":=", "decoder", ".", "Decode", "(", "&", "snapshot", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "snapshot", ".", "Version", "!=", "SnapshotVersion", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "snapshot", ".", "Version", ")", "\n", "}", "\n", "if", "snapshot", ".", "Entries", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "newGroups", ":=", "make", "(", "map", "[", "groupKey", "]", "map", "[", "lease", ".", "Key", "]", "*", "entry", ",", "len", "(", "snapshot", ".", "Entries", ")", ")", "\n", "for", "key", ",", "ssEntry", ":=", "range", "snapshot", ".", "Entries", "{", "gKey", ":=", "groupKey", "{", "namespace", ":", "key", ".", "Namespace", ",", "modelUUID", ":", "key", ".", "ModelUUID", ",", "}", "\n", "newEntries", ",", "found", ":=", "newGroups", "[", "gKey", "]", "\n", "if", "!", "found", "{", "newEntries", "=", "make", "(", "map", "[", "lease", ".", "Key", "]", "*", "entry", ")", "\n", "newGroups", "[", "gKey", "]", "=", "newEntries", "\n", "}", "\n\n", "newEntries", "[", "lease", ".", "Key", "{", "Namespace", ":", "key", ".", "Namespace", ",", "ModelUUID", ":", "key", ".", "ModelUUID", ",", "Lease", ":", "key", ".", "Lease", ",", "}", "]", "=", "&", "entry", "{", "holder", ":", "ssEntry", ".", "Holder", ",", "start", ":", "ssEntry", ".", "Start", ",", "duration", ":", "ssEntry", ".", "Duration", ",", "}", "\n", "}", "\n\n", "newPinned", ":=", "make", "(", "map", "[", "lease", ".", "Key", "]", "set", ".", "Strings", ",", "len", "(", "snapshot", ".", "Pinned", ")", ")", "\n", "for", "key", ",", "entities", ":=", "range", "snapshot", ".", "Pinned", "{", "newPinned", "[", "lease", ".", "Key", "{", "Namespace", ":", "key", ".", "Namespace", ",", "ModelUUID", ":", "key", ".", "ModelUUID", ",", "Lease", ":", "key", ".", "Lease", ",", "}", "]", "=", "set", ".", "NewStrings", "(", "entities", "...", ")", "\n", "}", "\n\n", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "f", ".", "globalTime", "=", "snapshot", ".", "GlobalTime", "\n", "f", ".", "groups", "=", "newGroups", "\n", "f", ".", "pinned", "=", "newPinned", "\n", "f", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Restore is part of raft.FSM.
[ "Restore", "is", "part", "of", "raft", ".", "FSM", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L395-L449
156,981
juju/juju
core/raftlease/fsm.go
Persist
func (s *Snapshot) Persist(sink raft.SnapshotSink) (err error) { defer func() { if err != nil { sink.Cancel() } }() encoder := yaml.NewEncoder(sink) if err := encoder.Encode(s); err != nil { return errors.Trace(err) } if err := encoder.Close(); err != nil { return errors.Trace(err) } return sink.Close() }
go
func (s *Snapshot) Persist(sink raft.SnapshotSink) (err error) { defer func() { if err != nil { sink.Cancel() } }() encoder := yaml.NewEncoder(sink) if err := encoder.Encode(s); err != nil { return errors.Trace(err) } if err := encoder.Close(); err != nil { return errors.Trace(err) } return sink.Close() }
[ "func", "(", "s", "*", "Snapshot", ")", "Persist", "(", "sink", "raft", ".", "SnapshotSink", ")", "(", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "sink", ".", "Cancel", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "encoder", ":=", "yaml", ".", "NewEncoder", "(", "sink", ")", "\n", "if", "err", ":=", "encoder", ".", "Encode", "(", "s", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "encoder", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "sink", ".", "Close", "(", ")", "\n", "}" ]
// Persist is part of raft.FSMSnapshot.
[ "Persist", "is", "part", "of", "raft", ".", "FSMSnapshot", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L460-L475
156,982
juju/juju
core/raftlease/fsm.go
Validate
func (c *Command) Validate() error { // For now there's only version 1. if c.Version != 1 { return errors.NotValidf("version %d", c.Version) } switch c.Operation { case OperationClaim, OperationExtend: if err := c.validateLeaseKey(); err != nil { return err } if err := c.validateNoTime(); err != nil { return err } if c.Holder == "" { return errors.NotValidf("%s with empty holder", c.Operation) } if c.Duration == 0 { return errors.NotValidf("%s with zero duration", c.Operation) } if c.PinEntity != "" { return errors.NotValidf("%s with pin entity", c.Operation) } case OperationPin, OperationUnpin: if err := c.validateLeaseKey(); err != nil { return err } if err := c.validateNoTime(); err != nil { return err } if c.Duration != 0 { return errors.NotValidf("%s with duration", c.Operation) } if c.PinEntity == "" { return errors.NotValidf("%s with empty pin entity", c.Operation) } case OperationSetTime: // An old time of 0 is valid when starting up. var zeroTime time.Time if c.NewTime == zeroTime { return errors.NotValidf("setTime with zero new time") } if c.Holder != "" { return errors.NotValidf("setTime with holder") } if c.Duration != 0 { return errors.NotValidf("setTime with duration") } if c.Namespace != "" { return errors.NotValidf("setTime with namespace") } if c.ModelUUID != "" { return errors.NotValidf("setTime with model UUID") } if c.Lease != "" { if c.Holder == "" { return errors.NotValidf("%s with empty holder", c.Operation) } return errors.NotValidf("setTime with lease") } if c.PinEntity != "" { return errors.NotValidf("setTime with pin entity") } default: return errors.NotValidf("operation %q", c.Operation) } return nil }
go
func (c *Command) Validate() error { // For now there's only version 1. if c.Version != 1 { return errors.NotValidf("version %d", c.Version) } switch c.Operation { case OperationClaim, OperationExtend: if err := c.validateLeaseKey(); err != nil { return err } if err := c.validateNoTime(); err != nil { return err } if c.Holder == "" { return errors.NotValidf("%s with empty holder", c.Operation) } if c.Duration == 0 { return errors.NotValidf("%s with zero duration", c.Operation) } if c.PinEntity != "" { return errors.NotValidf("%s with pin entity", c.Operation) } case OperationPin, OperationUnpin: if err := c.validateLeaseKey(); err != nil { return err } if err := c.validateNoTime(); err != nil { return err } if c.Duration != 0 { return errors.NotValidf("%s with duration", c.Operation) } if c.PinEntity == "" { return errors.NotValidf("%s with empty pin entity", c.Operation) } case OperationSetTime: // An old time of 0 is valid when starting up. var zeroTime time.Time if c.NewTime == zeroTime { return errors.NotValidf("setTime with zero new time") } if c.Holder != "" { return errors.NotValidf("setTime with holder") } if c.Duration != 0 { return errors.NotValidf("setTime with duration") } if c.Namespace != "" { return errors.NotValidf("setTime with namespace") } if c.ModelUUID != "" { return errors.NotValidf("setTime with model UUID") } if c.Lease != "" { if c.Holder == "" { return errors.NotValidf("%s with empty holder", c.Operation) } return errors.NotValidf("setTime with lease") } if c.PinEntity != "" { return errors.NotValidf("setTime with pin entity") } default: return errors.NotValidf("operation %q", c.Operation) } return nil }
[ "func", "(", "c", "*", "Command", ")", "Validate", "(", ")", "error", "{", "// For now there's only version 1.", "if", "c", ".", "Version", "!=", "1", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "c", ".", "Version", ")", "\n", "}", "\n", "switch", "c", ".", "Operation", "{", "case", "OperationClaim", ",", "OperationExtend", ":", "if", "err", ":=", "c", ".", "validateLeaseKey", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "validateNoTime", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "c", ".", "Holder", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "c", ".", "Operation", ")", "\n", "}", "\n", "if", "c", ".", "Duration", "==", "0", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "c", ".", "Operation", ")", "\n", "}", "\n", "if", "c", ".", "PinEntity", "!=", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "c", ".", "Operation", ")", "\n", "}", "\n", "case", "OperationPin", ",", "OperationUnpin", ":", "if", "err", ":=", "c", ".", "validateLeaseKey", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "validateNoTime", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "c", ".", "Duration", "!=", "0", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "c", ".", "Operation", ")", "\n", "}", "\n", "if", "c", ".", "PinEntity", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "c", ".", "Operation", ")", "\n", "}", "\n", "case", "OperationSetTime", ":", "// An old time of 0 is valid when starting up.", "var", "zeroTime", "time", ".", "Time", "\n", "if", "c", ".", "NewTime", "==", "zeroTime", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "Holder", "!=", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "Duration", "!=", "0", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "Namespace", "!=", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "ModelUUID", "!=", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "Lease", "!=", "\"", "\"", "{", "if", "c", ".", "Holder", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "c", ".", "Operation", ")", "\n", "}", "\n", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "PinEntity", "!=", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "c", ".", "Operation", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate checks that the command describes a valid state change.
[ "Validate", "checks", "that", "the", "command", "describes", "a", "valid", "state", "change", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L532-L598
156,983
juju/juju
core/raftlease/fsm.go
LeaseKey
func (c *Command) LeaseKey() lease.Key { return lease.Key{ Namespace: c.Namespace, ModelUUID: c.ModelUUID, Lease: c.Lease, } }
go
func (c *Command) LeaseKey() lease.Key { return lease.Key{ Namespace: c.Namespace, ModelUUID: c.ModelUUID, Lease: c.Lease, } }
[ "func", "(", "c", "*", "Command", ")", "LeaseKey", "(", ")", "lease", ".", "Key", "{", "return", "lease", ".", "Key", "{", "Namespace", ":", "c", ".", "Namespace", ",", "ModelUUID", ":", "c", ".", "ModelUUID", ",", "Lease", ":", "c", ".", "Lease", ",", "}", "\n", "}" ]
// LeaseKey makes a lease key from the fields in the command.
[ "LeaseKey", "makes", "a", "lease", "key", "from", "the", "fields", "in", "the", "command", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/raftlease/fsm.go#L625-L631
156,984
juju/juju
worker/provisioner/provisioner.go
NewRetryStrategy
func NewRetryStrategy(delay time.Duration, count int) RetryStrategy { return RetryStrategy{ retryDelay: delay, retryCount: count, } }
go
func NewRetryStrategy(delay time.Duration, count int) RetryStrategy { return RetryStrategy{ retryDelay: delay, retryCount: count, } }
[ "func", "NewRetryStrategy", "(", "delay", "time", ".", "Duration", ",", "count", "int", ")", "RetryStrategy", "{", "return", "RetryStrategy", "{", "retryDelay", ":", "delay", ",", "retryCount", ":", "count", ",", "}", "\n", "}" ]
// NewRetryStrategy returns a new retry strategy with the specified delay and // count for use with retryable provisioning errors.
[ "NewRetryStrategy", "returns", "a", "new", "retry", "strategy", "with", "the", "specified", "delay", "and", "count", "for", "use", "with", "retryable", "provisioning", "errors", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner.go#L85-L90
156,985
juju/juju
worker/provisioner/provisioner.go
notify
func (o *configObserver) notify(cfg *config.Config) { o.Lock() if o.observer != nil { select { case o.observer <- cfg: case <-o.catacomb.Dying(): } } o.Unlock() }
go
func (o *configObserver) notify(cfg *config.Config) { o.Lock() if o.observer != nil { select { case o.observer <- cfg: case <-o.catacomb.Dying(): } } o.Unlock() }
[ "func", "(", "o", "*", "configObserver", ")", "notify", "(", "cfg", "*", "config", ".", "Config", ")", "{", "o", ".", "Lock", "(", ")", "\n", "if", "o", ".", "observer", "!=", "nil", "{", "select", "{", "case", "o", ".", "observer", "<-", "cfg", ":", "case", "<-", "o", ".", "catacomb", ".", "Dying", "(", ")", ":", "}", "\n", "}", "\n", "o", ".", "Unlock", "(", ")", "\n", "}" ]
// notify notifies the observer of a configuration change.
[ "notify", "notifies", "the", "observer", "of", "a", "configuration", "change", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner.go#L104-L113
156,986
juju/juju
worker/provisioner/provisioner.go
getStartTask
func (p *provisioner) getStartTask(harvestMode config.HarvestMode) (ProvisionerTask, error) { auth, err := authentication.NewAPIAuthenticator(p.st) if err != nil { return nil, err } // Start responding to changes in machines, and to any further updates // to the environment config. machineWatcher, err := p.getMachineWatcher() if err != nil { return nil, err } retryWatcher, err := p.getRetryWatcher() if err != nil && !errors.IsNotImplemented(err) { return nil, err } tag := p.agentConfig.Tag() machineTag, ok := tag.(names.MachineTag) if !ok { errors.Errorf("expected names.MachineTag, got %T", tag) } modelCfg, err := p.st.ModelConfig() if err != nil { return nil, errors.Annotate(err, "could not retrieve the model config.") } controllerCfg, err := p.st.ControllerConfig() if err != nil { return nil, errors.Annotate(err, "could not retrieve the controller config.") } task, err := NewProvisionerTask( controllerCfg.ControllerUUID(), machineTag, harvestMode, p.st, p.distributionGroupFinder, p.toolsFinder, machineWatcher, retryWatcher, p.broker, auth, modelCfg.ImageStream(), RetryStrategy{retryDelay: retryStrategyDelay, retryCount: retryStrategyCount}, p.callContext, ) if err != nil { return nil, errors.Trace(err) } return task, nil }
go
func (p *provisioner) getStartTask(harvestMode config.HarvestMode) (ProvisionerTask, error) { auth, err := authentication.NewAPIAuthenticator(p.st) if err != nil { return nil, err } // Start responding to changes in machines, and to any further updates // to the environment config. machineWatcher, err := p.getMachineWatcher() if err != nil { return nil, err } retryWatcher, err := p.getRetryWatcher() if err != nil && !errors.IsNotImplemented(err) { return nil, err } tag := p.agentConfig.Tag() machineTag, ok := tag.(names.MachineTag) if !ok { errors.Errorf("expected names.MachineTag, got %T", tag) } modelCfg, err := p.st.ModelConfig() if err != nil { return nil, errors.Annotate(err, "could not retrieve the model config.") } controllerCfg, err := p.st.ControllerConfig() if err != nil { return nil, errors.Annotate(err, "could not retrieve the controller config.") } task, err := NewProvisionerTask( controllerCfg.ControllerUUID(), machineTag, harvestMode, p.st, p.distributionGroupFinder, p.toolsFinder, machineWatcher, retryWatcher, p.broker, auth, modelCfg.ImageStream(), RetryStrategy{retryDelay: retryStrategyDelay, retryCount: retryStrategyCount}, p.callContext, ) if err != nil { return nil, errors.Trace(err) } return task, nil }
[ "func", "(", "p", "*", "provisioner", ")", "getStartTask", "(", "harvestMode", "config", ".", "HarvestMode", ")", "(", "ProvisionerTask", ",", "error", ")", "{", "auth", ",", "err", ":=", "authentication", ".", "NewAPIAuthenticator", "(", "p", ".", "st", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Start responding to changes in machines, and to any further updates", "// to the environment config.", "machineWatcher", ",", "err", ":=", "p", ".", "getMachineWatcher", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "retryWatcher", ",", "err", ":=", "p", ".", "getRetryWatcher", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotImplemented", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tag", ":=", "p", ".", "agentConfig", ".", "Tag", "(", ")", "\n", "machineTag", ",", "ok", ":=", "tag", ".", "(", "names", ".", "MachineTag", ")", "\n", "if", "!", "ok", "{", "errors", ".", "Errorf", "(", "\"", "\"", ",", "tag", ")", "\n", "}", "\n\n", "modelCfg", ",", "err", ":=", "p", ".", "st", ".", "ModelConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "controllerCfg", ",", "err", ":=", "p", ".", "st", ".", "ControllerConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "task", ",", "err", ":=", "NewProvisionerTask", "(", "controllerCfg", ".", "ControllerUUID", "(", ")", ",", "machineTag", ",", "harvestMode", ",", "p", ".", "st", ",", "p", ".", "distributionGroupFinder", ",", "p", ".", "toolsFinder", ",", "machineWatcher", ",", "retryWatcher", ",", "p", ".", "broker", ",", "auth", ",", "modelCfg", ".", "ImageStream", "(", ")", ",", "RetryStrategy", "{", "retryDelay", ":", "retryStrategyDelay", ",", "retryCount", ":", "retryStrategyCount", "}", ",", "p", ".", "callContext", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "task", ",", "nil", "\n", "}" ]
// getStartTask creates a new worker for the provisioner,
[ "getStartTask", "creates", "a", "new", "worker", "for", "the", "provisioner" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner.go#L138-L188
156,987
juju/juju
worker/provisioner/provisioner.go
NewEnvironProvisioner
func NewEnvironProvisioner(st *apiprovisioner.State, agentConfig agent.Config, environ environs.Environ, credentialAPI common.CredentialAPI, ) (Provisioner, error) { p := &environProvisioner{ provisioner: provisioner{ st: st, agentConfig: agentConfig, toolsFinder: getToolsFinder(st), distributionGroupFinder: getDistributionGroupFinder(st), callContext: common.NewCloudCallContext(credentialAPI, nil), }, environ: environ, } p.Provisioner = p p.broker = environ logger.Tracef("Starting environ provisioner for %q", p.agentConfig.Tag()) err := catacomb.Invoke(catacomb.Plan{ Site: &p.catacomb, Work: p.loop, }) if err != nil { return nil, errors.Trace(err) } return p, nil }
go
func NewEnvironProvisioner(st *apiprovisioner.State, agentConfig agent.Config, environ environs.Environ, credentialAPI common.CredentialAPI, ) (Provisioner, error) { p := &environProvisioner{ provisioner: provisioner{ st: st, agentConfig: agentConfig, toolsFinder: getToolsFinder(st), distributionGroupFinder: getDistributionGroupFinder(st), callContext: common.NewCloudCallContext(credentialAPI, nil), }, environ: environ, } p.Provisioner = p p.broker = environ logger.Tracef("Starting environ provisioner for %q", p.agentConfig.Tag()) err := catacomb.Invoke(catacomb.Plan{ Site: &p.catacomb, Work: p.loop, }) if err != nil { return nil, errors.Trace(err) } return p, nil }
[ "func", "NewEnvironProvisioner", "(", "st", "*", "apiprovisioner", ".", "State", ",", "agentConfig", "agent", ".", "Config", ",", "environ", "environs", ".", "Environ", ",", "credentialAPI", "common", ".", "CredentialAPI", ",", ")", "(", "Provisioner", ",", "error", ")", "{", "p", ":=", "&", "environProvisioner", "{", "provisioner", ":", "provisioner", "{", "st", ":", "st", ",", "agentConfig", ":", "agentConfig", ",", "toolsFinder", ":", "getToolsFinder", "(", "st", ")", ",", "distributionGroupFinder", ":", "getDistributionGroupFinder", "(", "st", ")", ",", "callContext", ":", "common", ".", "NewCloudCallContext", "(", "credentialAPI", ",", "nil", ")", ",", "}", ",", "environ", ":", "environ", ",", "}", "\n", "p", ".", "Provisioner", "=", "p", "\n", "p", ".", "broker", "=", "environ", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "p", ".", "agentConfig", ".", "Tag", "(", ")", ")", "\n\n", "err", ":=", "catacomb", ".", "Invoke", "(", "catacomb", ".", "Plan", "{", "Site", ":", "&", "p", ".", "catacomb", ",", "Work", ":", "p", ".", "loop", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "p", ",", "nil", "\n", "}" ]
// NewEnvironProvisioner returns a new Provisioner for an environment. // When new machines are added to the state, it allocates instances // from the environment and allocates them to the new machines.
[ "NewEnvironProvisioner", "returns", "a", "new", "Provisioner", "for", "an", "environment", ".", "When", "new", "machines", "are", "added", "to", "the", "state", "it", "allocates", "instances", "from", "the", "environment", "and", "allocates", "them", "to", "the", "new", "machines", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner.go#L193-L220
156,988
juju/juju
worker/provisioner/provisioner.go
setConfig
func (p *environProvisioner) setConfig(modelConfig *config.Config) error { if err := p.environ.SetConfig(modelConfig); err != nil { return errors.Trace(err) } p.configObserver.notify(modelConfig) return nil }
go
func (p *environProvisioner) setConfig(modelConfig *config.Config) error { if err := p.environ.SetConfig(modelConfig); err != nil { return errors.Trace(err) } p.configObserver.notify(modelConfig) return nil }
[ "func", "(", "p", "*", "environProvisioner", ")", "setConfig", "(", "modelConfig", "*", "config", ".", "Config", ")", "error", "{", "if", "err", ":=", "p", ".", "environ", ".", "SetConfig", "(", "modelConfig", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "p", ".", "configObserver", ".", "notify", "(", "modelConfig", ")", "\n", "return", "nil", "\n", "}" ]
// setConfig updates the environment configuration and notifies // the config observer.
[ "setConfig", "updates", "the", "environment", "configuration", "and", "notifies", "the", "config", "observer", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner.go#L278-L284
156,989
juju/juju
worker/provisioner/provisioner.go
NewContainerProvisioner
func NewContainerProvisioner( containerType instance.ContainerType, st *apiprovisioner.State, agentConfig agent.Config, broker environs.InstanceBroker, toolsFinder ToolsFinder, distributionGroupFinder DistributionGroupFinder, credentialAPI common.CredentialAPI, ) (Provisioner, error) { p := &containerProvisioner{ provisioner: provisioner{ st: st, agentConfig: agentConfig, broker: broker, toolsFinder: toolsFinder, distributionGroupFinder: distributionGroupFinder, callContext: common.NewCloudCallContext(credentialAPI, nil), }, containerType: containerType, } p.Provisioner = p logger.Tracef("Starting %s provisioner for %q", p.containerType, p.agentConfig.Tag()) err := catacomb.Invoke(catacomb.Plan{ Site: &p.catacomb, Work: p.loop, }) if err != nil { return nil, errors.Trace(err) } return p, nil }
go
func NewContainerProvisioner( containerType instance.ContainerType, st *apiprovisioner.State, agentConfig agent.Config, broker environs.InstanceBroker, toolsFinder ToolsFinder, distributionGroupFinder DistributionGroupFinder, credentialAPI common.CredentialAPI, ) (Provisioner, error) { p := &containerProvisioner{ provisioner: provisioner{ st: st, agentConfig: agentConfig, broker: broker, toolsFinder: toolsFinder, distributionGroupFinder: distributionGroupFinder, callContext: common.NewCloudCallContext(credentialAPI, nil), }, containerType: containerType, } p.Provisioner = p logger.Tracef("Starting %s provisioner for %q", p.containerType, p.agentConfig.Tag()) err := catacomb.Invoke(catacomb.Plan{ Site: &p.catacomb, Work: p.loop, }) if err != nil { return nil, errors.Trace(err) } return p, nil }
[ "func", "NewContainerProvisioner", "(", "containerType", "instance", ".", "ContainerType", ",", "st", "*", "apiprovisioner", ".", "State", ",", "agentConfig", "agent", ".", "Config", ",", "broker", "environs", ".", "InstanceBroker", ",", "toolsFinder", "ToolsFinder", ",", "distributionGroupFinder", "DistributionGroupFinder", ",", "credentialAPI", "common", ".", "CredentialAPI", ",", ")", "(", "Provisioner", ",", "error", ")", "{", "p", ":=", "&", "containerProvisioner", "{", "provisioner", ":", "provisioner", "{", "st", ":", "st", ",", "agentConfig", ":", "agentConfig", ",", "broker", ":", "broker", ",", "toolsFinder", ":", "toolsFinder", ",", "distributionGroupFinder", ":", "distributionGroupFinder", ",", "callContext", ":", "common", ".", "NewCloudCallContext", "(", "credentialAPI", ",", "nil", ")", ",", "}", ",", "containerType", ":", "containerType", ",", "}", "\n", "p", ".", "Provisioner", "=", "p", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "p", ".", "containerType", ",", "p", ".", "agentConfig", ".", "Tag", "(", ")", ")", "\n\n", "err", ":=", "catacomb", ".", "Invoke", "(", "catacomb", ".", "Plan", "{", "Site", ":", "&", "p", ".", "catacomb", ",", "Work", ":", "p", ".", "loop", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "p", ",", "nil", "\n", "}" ]
// NewContainerProvisioner returns a new Provisioner. When new machines // are added to the state, it allocates instances from the environment // and allocates them to the new machines.
[ "NewContainerProvisioner", "returns", "a", "new", "Provisioner", ".", "When", "new", "machines", "are", "added", "to", "the", "state", "it", "allocates", "instances", "from", "the", "environment", "and", "allocates", "them", "to", "the", "new", "machines", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/provisioner.go#L289-L320
156,990
juju/juju
provider/vsphere/environ_availzones.go
Name
func (z *vmwareAvailZone) Name() string { // The name for this zone is the compute resource name and the // path of the pool without the prefix, so for // /QA/host/aron.internal/Resources/High/Child, the name should be // aron.internal/High/Child. path := strings.TrimRight(z.pool.InventoryPath, "/") parts := strings.Split(path, "/") poolPath := "" if len(parts) > poolPathPrefixParts { // This isn't the root pool for this compute resource, include // the pool's path. poolPath = "/" + strings.Join(parts[poolPathPrefixParts:], "/") } return z.r.Name + poolPath }
go
func (z *vmwareAvailZone) Name() string { // The name for this zone is the compute resource name and the // path of the pool without the prefix, so for // /QA/host/aron.internal/Resources/High/Child, the name should be // aron.internal/High/Child. path := strings.TrimRight(z.pool.InventoryPath, "/") parts := strings.Split(path, "/") poolPath := "" if len(parts) > poolPathPrefixParts { // This isn't the root pool for this compute resource, include // the pool's path. poolPath = "/" + strings.Join(parts[poolPathPrefixParts:], "/") } return z.r.Name + poolPath }
[ "func", "(", "z", "*", "vmwareAvailZone", ")", "Name", "(", ")", "string", "{", "// The name for this zone is the compute resource name and the", "// path of the pool without the prefix, so for", "// /QA/host/aron.internal/Resources/High/Child, the name should be", "// aron.internal/High/Child.", "path", ":=", "strings", ".", "TrimRight", "(", "z", ".", "pool", ".", "InventoryPath", ",", "\"", "\"", ")", "\n", "parts", ":=", "strings", ".", "Split", "(", "path", ",", "\"", "\"", ")", "\n", "poolPath", ":=", "\"", "\"", "\n", "if", "len", "(", "parts", ")", ">", "poolPathPrefixParts", "{", "// This isn't the root pool for this compute resource, include", "// the pool's path.", "poolPath", "=", "\"", "\"", "+", "strings", ".", "Join", "(", "parts", "[", "poolPathPrefixParts", ":", "]", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "z", ".", "r", ".", "Name", "+", "poolPath", "\n", "}" ]
// Name implements common.AvailabilityZone
[ "Name", "implements", "common", ".", "AvailabilityZone" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/environ_availzones.go#L33-L48
156,991
juju/juju
worker/presence/presence.go
NewWorker
func NewWorker(config WorkerConfig) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } // Don't return from NewWorker until the loop has started and // has subscribed to everything. started := make(chan struct{}) w := &wrapper{ origin: config.Origin, hub: config.Hub, recorder: config.Recorder, logger: config.Logger, } w.tomb.Go(func() error { return w.loop(started) }) select { case <-started: case <-time.After(10 * time.Second): return nil, errors.New("worker failed to start properly") } return w, nil }
go
func NewWorker(config WorkerConfig) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } // Don't return from NewWorker until the loop has started and // has subscribed to everything. started := make(chan struct{}) w := &wrapper{ origin: config.Origin, hub: config.Hub, recorder: config.Recorder, logger: config.Logger, } w.tomb.Go(func() error { return w.loop(started) }) select { case <-started: case <-time.After(10 * time.Second): return nil, errors.New("worker failed to start properly") } return w, nil }
[ "func", "NewWorker", "(", "config", "WorkerConfig", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// Don't return from NewWorker until the loop has started and", "// has subscribed to everything.", "started", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "w", ":=", "&", "wrapper", "{", "origin", ":", "config", ".", "Origin", ",", "hub", ":", "config", ".", "Hub", ",", "recorder", ":", "config", ".", "Recorder", ",", "logger", ":", "config", ".", "Logger", ",", "}", "\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "return", "w", ".", "loop", "(", "started", ")", "\n", "}", ")", "\n", "select", "{", "case", "<-", "started", ":", "case", "<-", "time", ".", "After", "(", "10", "*", "time", ".", "Second", ")", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "w", ",", "nil", "\n", "}" ]
// NewWorker creates a new presence worker that responds to pubsub connection // messages.
[ "NewWorker", "creates", "a", "new", "presence", "worker", "that", "responds", "to", "pubsub", "connection", "messages", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/presence/presence.go#L47-L69
156,992
juju/juju
worker/presence/presence.go
Report
func (w *wrapper) Report() map[string]interface{} { all := w.recorder.Connections() result := make(map[string]interface{}) servers := all.Servers() for _, name := range servers { conns := all.ForServer(name) result[name] = conns.Count() } return result }
go
func (w *wrapper) Report() map[string]interface{} { all := w.recorder.Connections() result := make(map[string]interface{}) servers := all.Servers() for _, name := range servers { conns := all.ForServer(name) result[name] = conns.Count() } return result }
[ "func", "(", "w", "*", "wrapper", ")", "Report", "(", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "all", ":=", "w", ".", "recorder", ".", "Connections", "(", ")", "\n", "result", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "servers", ":=", "all", ".", "Servers", "(", ")", "\n", "for", "_", ",", "name", ":=", "range", "servers", "{", "conns", ":=", "all", ".", "ForServer", "(", "name", ")", "\n", "result", "[", "name", "]", "=", "conns", ".", "Count", "(", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Report implements worker.Report.
[ "Report", "implements", "worker", ".", "Report", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/presence/presence.go#L80-L89
156,993
juju/juju
apiserver/facades/agent/credentialvalidator/backend.go
ModelUsesCredential
func (b *backend) ModelUsesCredential(tag names.CloudCredentialTag) (bool, error) { m, err := b.Model() if err != nil { return false, errors.Trace(err) } modelCredentialTag, exists := m.CloudCredential() return exists && tag == modelCredentialTag, nil }
go
func (b *backend) ModelUsesCredential(tag names.CloudCredentialTag) (bool, error) { m, err := b.Model() if err != nil { return false, errors.Trace(err) } modelCredentialTag, exists := m.CloudCredential() return exists && tag == modelCredentialTag, nil }
[ "func", "(", "b", "*", "backend", ")", "ModelUsesCredential", "(", "tag", "names", ".", "CloudCredentialTag", ")", "(", "bool", ",", "error", ")", "{", "m", ",", "err", ":=", "b", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "modelCredentialTag", ",", "exists", ":=", "m", ".", "CloudCredential", "(", ")", "\n", "return", "exists", "&&", "tag", "==", "modelCredentialTag", ",", "nil", "\n", "}" ]
// ModelUsesCredential implements Backend.ModelUsesCredential.
[ "ModelUsesCredential", "implements", "Backend", ".", "ModelUsesCredential", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/credentialvalidator/backend.go#L43-L50
156,994
juju/juju
apiserver/facades/agent/credentialvalidator/backend.go
ModelCredential
func (b *backend) ModelCredential() (*ModelCredential, error) { m, err := b.Model() if err != nil { return nil, errors.Trace(err) } modelCredentialTag, exists := m.CloudCredential() result := &ModelCredential{Model: m.ModelTag(), Exists: exists} if !exists { // A model credential is not set, we must check if the model // is on the cloud that requires a credential. supportsEmptyAuth, err := b.cloudSupportsNoAuth(m.Cloud()) if err != nil { return nil, errors.Trace(err) } result.Valid = supportsEmptyAuth if !supportsEmptyAuth { // TODO (anastasiamac 2018-11-12) Figure out how to notify the users here - maybe set a model status?... logger.Warningf("model credential is not set for the model but the cloud requires it") } return result, nil } result.Credential = modelCredentialTag credential, err := b.CloudCredential(modelCredentialTag) if err != nil { if !errors.IsNotFound(err) { return nil, errors.Trace(err) } // In this situation, a model refers to a credential that does not exist in credentials collection. // TODO (anastasiamac 2018-11-12) Figure out how to notify the users here - maybe set a model status?... logger.Warningf("cloud credential reference is set for the model but the credential content is no longer on the controller") result.Valid = false return result, nil } result.Valid = credential.IsValid() return result, nil }
go
func (b *backend) ModelCredential() (*ModelCredential, error) { m, err := b.Model() if err != nil { return nil, errors.Trace(err) } modelCredentialTag, exists := m.CloudCredential() result := &ModelCredential{Model: m.ModelTag(), Exists: exists} if !exists { // A model credential is not set, we must check if the model // is on the cloud that requires a credential. supportsEmptyAuth, err := b.cloudSupportsNoAuth(m.Cloud()) if err != nil { return nil, errors.Trace(err) } result.Valid = supportsEmptyAuth if !supportsEmptyAuth { // TODO (anastasiamac 2018-11-12) Figure out how to notify the users here - maybe set a model status?... logger.Warningf("model credential is not set for the model but the cloud requires it") } return result, nil } result.Credential = modelCredentialTag credential, err := b.CloudCredential(modelCredentialTag) if err != nil { if !errors.IsNotFound(err) { return nil, errors.Trace(err) } // In this situation, a model refers to a credential that does not exist in credentials collection. // TODO (anastasiamac 2018-11-12) Figure out how to notify the users here - maybe set a model status?... logger.Warningf("cloud credential reference is set for the model but the credential content is no longer on the controller") result.Valid = false return result, nil } result.Valid = credential.IsValid() return result, nil }
[ "func", "(", "b", "*", "backend", ")", "ModelCredential", "(", ")", "(", "*", "ModelCredential", ",", "error", ")", "{", "m", ",", "err", ":=", "b", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "modelCredentialTag", ",", "exists", ":=", "m", ".", "CloudCredential", "(", ")", "\n", "result", ":=", "&", "ModelCredential", "{", "Model", ":", "m", ".", "ModelTag", "(", ")", ",", "Exists", ":", "exists", "}", "\n", "if", "!", "exists", "{", "// A model credential is not set, we must check if the model", "// is on the cloud that requires a credential.", "supportsEmptyAuth", ",", "err", ":=", "b", ".", "cloudSupportsNoAuth", "(", "m", ".", "Cloud", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "result", ".", "Valid", "=", "supportsEmptyAuth", "\n", "if", "!", "supportsEmptyAuth", "{", "// TODO (anastasiamac 2018-11-12) Figure out how to notify the users here - maybe set a model status?...", "logger", ".", "Warningf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}", "\n\n", "result", ".", "Credential", "=", "modelCredentialTag", "\n", "credential", ",", "err", ":=", "b", ".", "CloudCredential", "(", "modelCredentialTag", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// In this situation, a model refers to a credential that does not exist in credentials collection.", "// TODO (anastasiamac 2018-11-12) Figure out how to notify the users here - maybe set a model status?...", "logger", ".", "Warningf", "(", "\"", "\"", ")", "\n", "result", ".", "Valid", "=", "false", "\n", "return", "result", ",", "nil", "\n", "}", "\n", "result", ".", "Valid", "=", "credential", ".", "IsValid", "(", ")", "\n", "return", "result", ",", "nil", "\n", "}" ]
// ModelCredential implements Backend.ModelCredential.
[ "ModelCredential", "implements", "Backend", ".", "ModelCredential", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/credentialvalidator/backend.go#L53-L90
156,995
juju/juju
apiserver/facades/agent/credentialvalidator/backend.go
WatchModelCredential
func (b *backend) WatchModelCredential() (state.NotifyWatcher, error) { m, err := b.Model() if err != nil { return nil, errors.Trace(err) } return m.WatchModelCredential(), nil }
go
func (b *backend) WatchModelCredential() (state.NotifyWatcher, error) { m, err := b.Model() if err != nil { return nil, errors.Trace(err) } return m.WatchModelCredential(), nil }
[ "func", "(", "b", "*", "backend", ")", "WatchModelCredential", "(", ")", "(", "state", ".", "NotifyWatcher", ",", "error", ")", "{", "m", ",", "err", ":=", "b", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "m", ".", "WatchModelCredential", "(", ")", ",", "nil", "\n", "}" ]
// WatchModelCredential implements Backend.WatchModelCredential.
[ "WatchModelCredential", "implements", "Backend", ".", "WatchModelCredential", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/credentialvalidator/backend.go#L93-L99
156,996
juju/juju
core/lxdprofile/status.go
UpgradeStatusFinished
func UpgradeStatusFinished(status string) bool { if status == SuccessStatus || status == NotRequiredStatus || status == NotSupportedStatus { return true } return false }
go
func UpgradeStatusFinished(status string) bool { if status == SuccessStatus || status == NotRequiredStatus || status == NotSupportedStatus { return true } return false }
[ "func", "UpgradeStatusFinished", "(", "status", "string", ")", "bool", "{", "if", "status", "==", "SuccessStatus", "||", "status", "==", "NotRequiredStatus", "||", "status", "==", "NotSupportedStatus", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// UpgradeStatusFinished defines if the upgrade has completed
[ "UpgradeStatusFinished", "defines", "if", "the", "upgrade", "has", "completed" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/lxdprofile/status.go#L38-L43
156,997
juju/juju
apiserver/authentication/interactions.go
Start
func (m *Interactions) Start(caveatId []byte, expiry time.Time) (string, error) { id, err := newId() if err != nil { return "", err } m.mu.Lock() defer m.mu.Unlock() m.items[id] = &item{ c: make(chan Interaction, 1), caveatId: caveatId, expiry: expiry, } return id, nil }
go
func (m *Interactions) Start(caveatId []byte, expiry time.Time) (string, error) { id, err := newId() if err != nil { return "", err } m.mu.Lock() defer m.mu.Unlock() m.items[id] = &item{ c: make(chan Interaction, 1), caveatId: caveatId, expiry: expiry, } return id, nil }
[ "func", "(", "m", "*", "Interactions", ")", "Start", "(", "caveatId", "[", "]", "byte", ",", "expiry", "time", ".", "Time", ")", "(", "string", ",", "error", ")", "{", "id", ",", "err", ":=", "newId", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n", "m", ".", "items", "[", "id", "]", "=", "&", "item", "{", "c", ":", "make", "(", "chan", "Interaction", ",", "1", ")", ",", "caveatId", ":", "caveatId", ",", "expiry", ":", "expiry", ",", "}", "\n", "return", "id", ",", "nil", "\n", "}" ]
// Start records the start of an interactive login, and returns a random ID // that uniquely identifies it. A call to Wait with the same ID will return // the Interaction once it is done.
[ "Start", "records", "the", "start", "of", "an", "interactive", "login", "and", "returns", "a", "random", "ID", "that", "uniquely", "identifies", "it", ".", "A", "call", "to", "Wait", "with", "the", "same", "ID", "will", "return", "the", "Interaction", "once", "it", "is", "done", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/authentication/interactions.go#L63-L76
156,998
juju/juju
apiserver/authentication/interactions.go
Done
func (m *Interactions) Done(id string, loginUser names.UserTag, loginError error) error { m.mu.Lock() defer m.mu.Unlock() item := m.items[id] if item == nil { return errors.NotFoundf("interaction %q", id) } if item.done { return errors.Errorf("interaction %q already done", id) } item.done = true item.c <- Interaction{ CaveatId: item.caveatId, LoginUser: loginUser, LoginError: loginError, } return nil }
go
func (m *Interactions) Done(id string, loginUser names.UserTag, loginError error) error { m.mu.Lock() defer m.mu.Unlock() item := m.items[id] if item == nil { return errors.NotFoundf("interaction %q", id) } if item.done { return errors.Errorf("interaction %q already done", id) } item.done = true item.c <- Interaction{ CaveatId: item.caveatId, LoginUser: loginUser, LoginError: loginError, } return nil }
[ "func", "(", "m", "*", "Interactions", ")", "Done", "(", "id", "string", ",", "loginUser", "names", ".", "UserTag", ",", "loginError", "error", ")", "error", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n", "item", ":=", "m", ".", "items", "[", "id", "]", "\n\n", "if", "item", "==", "nil", "{", "return", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "if", "item", ".", "done", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "item", ".", "done", "=", "true", "\n", "item", ".", "c", "<-", "Interaction", "{", "CaveatId", ":", "item", ".", "caveatId", ",", "LoginUser", ":", "loginUser", ",", "LoginError", ":", "loginError", ",", "}", "\n", "return", "nil", "\n", "}" ]
// Done signals that the user has either logged in, or attempted to and failed.
[ "Done", "signals", "that", "the", "user", "has", "either", "logged", "in", "or", "attempted", "to", "and", "failed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/authentication/interactions.go#L79-L97
156,999
juju/juju
apiserver/authentication/interactions.go
Wait
func (m *Interactions) Wait(id string, cancel <-chan struct{}) (*Interaction, error) { m.mu.Lock() item := m.items[id] m.mu.Unlock() if item == nil { return nil, errors.NotFoundf("interaction %q", id) } select { case <-cancel: return nil, ErrWaitCanceled case interaction, ok := <-item.c: if !ok { return nil, ErrExpired } m.mu.Lock() delete(m.items, id) m.mu.Unlock() return &interaction, nil } }
go
func (m *Interactions) Wait(id string, cancel <-chan struct{}) (*Interaction, error) { m.mu.Lock() item := m.items[id] m.mu.Unlock() if item == nil { return nil, errors.NotFoundf("interaction %q", id) } select { case <-cancel: return nil, ErrWaitCanceled case interaction, ok := <-item.c: if !ok { return nil, ErrExpired } m.mu.Lock() delete(m.items, id) m.mu.Unlock() return &interaction, nil } }
[ "func", "(", "m", "*", "Interactions", ")", "Wait", "(", "id", "string", ",", "cancel", "<-", "chan", "struct", "{", "}", ")", "(", "*", "Interaction", ",", "error", ")", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "item", ":=", "m", ".", "items", "[", "id", "]", "\n", "m", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "item", "==", "nil", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "select", "{", "case", "<-", "cancel", ":", "return", "nil", ",", "ErrWaitCanceled", "\n", "case", "interaction", ",", "ok", ":=", "<-", "item", ".", "c", ":", "if", "!", "ok", "{", "return", "nil", ",", "ErrExpired", "\n", "}", "\n", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "delete", "(", "m", ".", "items", ",", "id", ")", "\n", "m", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "&", "interaction", ",", "nil", "\n", "}", "\n", "}" ]
// Wait waits until the identified interaction is done, and returns the // corresponding Interaction. If the cancel channel is signalled before // the interaction is done, then ErrWaitCanceled is returned. If the // interaction expires before it is done, ErrExpired is returned.
[ "Wait", "waits", "until", "the", "identified", "interaction", "is", "done", "and", "returns", "the", "corresponding", "Interaction", ".", "If", "the", "cancel", "channel", "is", "signalled", "before", "the", "interaction", "is", "done", "then", "ErrWaitCanceled", "is", "returned", ".", "If", "the", "interaction", "expires", "before", "it", "is", "done", "ErrExpired", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/authentication/interactions.go#L103-L122