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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
juju/juju
state/watcher.go
WatchLeaderSettings
func (a *Application) WatchLeaderSettings() NotifyWatcher { docId := a.st.docID(leadershipSettingsKey(a.Name())) return newEntityWatcher(a.st, settingsC, docId) }
go
func (a *Application) WatchLeaderSettings() NotifyWatcher { docId := a.st.docID(leadershipSettingsKey(a.Name())) return newEntityWatcher(a.st, settingsC, docId) }
[ "func", "(", "a", "*", "Application", ")", "WatchLeaderSettings", "(", ")", "NotifyWatcher", "{", "docId", ":=", "a", ".", "st", ".", "docID", "(", "leadershipSettingsKey", "(", "a", ".", "Name", "(", ")", ")", ")", "\n", "return", "newEntityWatcher", "(...
// WatchLeaderSettings returns a watcher for observing changed to an application's // leader settings.
[ "WatchLeaderSettings", "returns", "a", "watcher", "for", "observing", "changed", "to", "an", "application", "s", "leader", "settings", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1669-L1672
train
juju/juju
state/watcher.go
Watch
func (u *Unit) Watch() NotifyWatcher { return newEntityWatcher(u.st, unitsC, u.doc.DocID) }
go
func (u *Unit) Watch() NotifyWatcher { return newEntityWatcher(u.st, unitsC, u.doc.DocID) }
[ "func", "(", "u", "*", "Unit", ")", "Watch", "(", ")", "NotifyWatcher", "{", "return", "newEntityWatcher", "(", "u", ".", "st", ",", "unitsC", ",", "u", ".", "doc", ".", "DocID", ")", "\n", "}" ]
// Watch returns a watcher for observing changes to a unit.
[ "Watch", "returns", "a", "watcher", "for", "observing", "changes", "to", "a", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1675-L1677
train
juju/juju
state/watcher.go
Watch
func (m *Model) Watch() NotifyWatcher { return newEntityWatcher(m.st, modelsC, m.doc.UUID) }
go
func (m *Model) Watch() NotifyWatcher { return newEntityWatcher(m.st, modelsC, m.doc.UUID) }
[ "func", "(", "m", "*", "Model", ")", "Watch", "(", ")", "NotifyWatcher", "{", "return", "newEntityWatcher", "(", "m", ".", "st", ",", "modelsC", ",", "m", ".", "doc", ".", "UUID", ")", "\n", "}" ]
// Watch returns a watcher for observing changes to a model.
[ "Watch", "returns", "a", "watcher", "for", "observing", "changes", "to", "a", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1680-L1682
train
juju/juju
state/watcher.go
WatchInstanceData
func (m *Machine) WatchInstanceData() NotifyWatcher { return newEntityWatcher(m.st, instanceDataC, m.doc.Id) }
go
func (m *Machine) WatchInstanceData() NotifyWatcher { return newEntityWatcher(m.st, instanceDataC, m.doc.Id) }
[ "func", "(", "m", "*", "Machine", ")", "WatchInstanceData", "(", ")", "NotifyWatcher", "{", "return", "newEntityWatcher", "(", "m", ".", "st", ",", "instanceDataC", ",", "m", ".", "doc", ".", "Id", ")", "\n", "}" ]
// WatchInstanceData returns a watcher for observing changes to a model.
[ "WatchInstanceData", "returns", "a", "watcher", "for", "observing", "changes", "to", "a", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1685-L1687
train
juju/juju
state/watcher.go
WatchForModelConfigChanges
func (model *Model) WatchForModelConfigChanges() NotifyWatcher { return newEntityWatcher(model.st, settingsC, model.st.docID(modelGlobalKey)) }
go
func (model *Model) WatchForModelConfigChanges() NotifyWatcher { return newEntityWatcher(model.st, settingsC, model.st.docID(modelGlobalKey)) }
[ "func", "(", "model", "*", "Model", ")", "WatchForModelConfigChanges", "(", ")", "NotifyWatcher", "{", "return", "newEntityWatcher", "(", "model", ".", "st", ",", "settingsC", ",", "model", ".", "st", ".", "docID", "(", "modelGlobalKey", ")", ")", "\n", "}...
// WatchForModelConfigChanges returns a NotifyWatcher waiting for the Model // Config to change.
[ "WatchForModelConfigChanges", "returns", "a", "NotifyWatcher", "waiting", "for", "the", "Model", "Config", "to", "change", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1703-L1705
train
juju/juju
state/watcher.go
WatchCloudSpecChanges
func (model *Model) WatchCloudSpecChanges() NotifyWatcher { return newEntityWatcher(model.st, cloudsC, model.Cloud()) }
go
func (model *Model) WatchCloudSpecChanges() NotifyWatcher { return newEntityWatcher(model.st, cloudsC, model.Cloud()) }
[ "func", "(", "model", "*", "Model", ")", "WatchCloudSpecChanges", "(", ")", "NotifyWatcher", "{", "return", "newEntityWatcher", "(", "model", ".", "st", ",", "cloudsC", ",", "model", ".", "Cloud", "(", ")", ")", "\n", "}" ]
// WatchCloudSpecChanges returns a NotifyWatcher waiting for the cloud // to change for the model.
[ "WatchCloudSpecChanges", "returns", "a", "NotifyWatcher", "waiting", "for", "the", "cloud", "to", "change", "for", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1709-L1711
train
juju/juju
state/watcher.go
WatchModelEntityReferences
func (st *State) WatchModelEntityReferences(mUUID string) NotifyWatcher { return newEntityWatcher(st, modelEntityRefsC, mUUID) }
go
func (st *State) WatchModelEntityReferences(mUUID string) NotifyWatcher { return newEntityWatcher(st, modelEntityRefsC, mUUID) }
[ "func", "(", "st", "*", "State", ")", "WatchModelEntityReferences", "(", "mUUID", "string", ")", "NotifyWatcher", "{", "return", "newEntityWatcher", "(", "st", ",", "modelEntityRefsC", ",", "mUUID", ")", "\n", "}" ]
// WatchModelEntityReferences returns a NotifyWatcher waiting for the Model // Entity references to change for specified model.
[ "WatchModelEntityReferences", "returns", "a", "NotifyWatcher", "waiting", "for", "the", "Model", "Entity", "references", "to", "change", "for", "specified", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1715-L1717
train
juju/juju
state/watcher.go
WatchStorageAttachment
func (sb *storageBackend) WatchStorageAttachment(s names.StorageTag, u names.UnitTag) NotifyWatcher { id := storageAttachmentId(u.Id(), s.Id()) return newEntityWatcher(sb.mb, storageAttachmentsC, sb.mb.docID(id)) }
go
func (sb *storageBackend) WatchStorageAttachment(s names.StorageTag, u names.UnitTag) NotifyWatcher { id := storageAttachmentId(u.Id(), s.Id()) return newEntityWatcher(sb.mb, storageAttachmentsC, sb.mb.docID(id)) }
[ "func", "(", "sb", "*", "storageBackend", ")", "WatchStorageAttachment", "(", "s", "names", ".", "StorageTag", ",", "u", "names", ".", "UnitTag", ")", "NotifyWatcher", "{", "id", ":=", "storageAttachmentId", "(", "u", ".", "Id", "(", ")", ",", "s", ".", ...
// WatchStorageAttachment returns a watcher for observing changes // to a storage attachment.
[ "WatchStorageAttachment", "returns", "a", "watcher", "for", "observing", "changes", "to", "a", "storage", "attachment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1739-L1742
train
juju/juju
state/watcher.go
WatchVolumeAttachment
func (sb *storageBackend) WatchVolumeAttachment(host names.Tag, v names.VolumeTag) NotifyWatcher { id := volumeAttachmentId(host.Id(), v.Id()) return newEntityWatcher(sb.mb, volumeAttachmentsC, sb.mb.docID(id)) }
go
func (sb *storageBackend) WatchVolumeAttachment(host names.Tag, v names.VolumeTag) NotifyWatcher { id := volumeAttachmentId(host.Id(), v.Id()) return newEntityWatcher(sb.mb, volumeAttachmentsC, sb.mb.docID(id)) }
[ "func", "(", "sb", "*", "storageBackend", ")", "WatchVolumeAttachment", "(", "host", "names", ".", "Tag", ",", "v", "names", ".", "VolumeTag", ")", "NotifyWatcher", "{", "id", ":=", "volumeAttachmentId", "(", "host", ".", "Id", "(", ")", ",", "v", ".", ...
// WatchVolumeAttachment returns a watcher for observing changes // to a volume attachment.
[ "WatchVolumeAttachment", "returns", "a", "watcher", "for", "observing", "changes", "to", "a", "volume", "attachment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1746-L1749
train
juju/juju
state/watcher.go
WatchFilesystemAttachment
func (sb *storageBackend) WatchFilesystemAttachment(host names.Tag, f names.FilesystemTag) NotifyWatcher { id := filesystemAttachmentId(host.Id(), f.Id()) return newEntityWatcher(sb.mb, filesystemAttachmentsC, sb.mb.docID(id)) }
go
func (sb *storageBackend) WatchFilesystemAttachment(host names.Tag, f names.FilesystemTag) NotifyWatcher { id := filesystemAttachmentId(host.Id(), f.Id()) return newEntityWatcher(sb.mb, filesystemAttachmentsC, sb.mb.docID(id)) }
[ "func", "(", "sb", "*", "storageBackend", ")", "WatchFilesystemAttachment", "(", "host", "names", ".", "Tag", ",", "f", "names", ".", "FilesystemTag", ")", "NotifyWatcher", "{", "id", ":=", "filesystemAttachmentId", "(", "host", ".", "Id", "(", ")", ",", "...
// WatchFilesystemAttachment returns a watcher for observing changes // to a filesystem attachment.
[ "WatchFilesystemAttachment", "returns", "a", "watcher", "for", "observing", "changes", "to", "a", "filesystem", "attachment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1753-L1756
train
juju/juju
state/watcher.go
WatchCharmConfig
func (a *Application) WatchCharmConfig() (NotifyWatcher, error) { configKey := a.charmConfigKey() return newEntityWatcher(a.st, settingsC, a.st.docID(configKey)), nil }
go
func (a *Application) WatchCharmConfig() (NotifyWatcher, error) { configKey := a.charmConfigKey() return newEntityWatcher(a.st, settingsC, a.st.docID(configKey)), nil }
[ "func", "(", "a", "*", "Application", ")", "WatchCharmConfig", "(", ")", "(", "NotifyWatcher", ",", "error", ")", "{", "configKey", ":=", "a", ".", "charmConfigKey", "(", ")", "\n", "return", "newEntityWatcher", "(", "a", ".", "st", ",", "settingsC", ","...
// WatchCharmConfig returns a watcher for observing changes to the // application's charm configuration settings. The returned watcher will be // valid only while the application's charm URL is not changed.
[ "WatchCharmConfig", "returns", "a", "watcher", "for", "observing", "changes", "to", "the", "application", "s", "charm", "configuration", "settings", ".", "The", "returned", "watcher", "will", "be", "valid", "only", "while", "the", "application", "s", "charm", "U...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1761-L1764
train
juju/juju
state/watcher.go
WatchApplicationConfigSettings
func (u *Unit) WatchApplicationConfigSettings() (NotifyWatcher, error) { applicationConfigKey := applicationConfigKey(u.ApplicationName()) return newEntityWatcher(u.st, settingsC, u.st.docID(applicationConfigKey)), nil }
go
func (u *Unit) WatchApplicationConfigSettings() (NotifyWatcher, error) { applicationConfigKey := applicationConfigKey(u.ApplicationName()) return newEntityWatcher(u.st, settingsC, u.st.docID(applicationConfigKey)), nil }
[ "func", "(", "u", "*", "Unit", ")", "WatchApplicationConfigSettings", "(", ")", "(", "NotifyWatcher", ",", "error", ")", "{", "applicationConfigKey", ":=", "applicationConfigKey", "(", "u", ".", "ApplicationName", "(", ")", ")", "\n", "return", "newEntityWatcher...
// WatchApplicationConfigSettings is the same as WatchConfigSettings but // notifies on changes to application configuration not charm configuration.
[ "WatchApplicationConfigSettings", "is", "the", "same", "as", "WatchConfigSettings", "but", "notifies", "on", "changes", "to", "application", "configuration", "not", "charm", "configuration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1782-L1785
train
juju/juju
state/watcher.go
WatchConfigSettingsHash
func (u *Unit) WatchConfigSettingsHash() (StringsWatcher, error) { if u.doc.CharmURL == nil { return nil, fmt.Errorf("unit charm not set") } charmConfigKey := applicationCharmConfigKey(u.doc.Application, u.doc.CharmURL) return newSettingsHashWatcher(u.st, charmConfigKey), nil }
go
func (u *Unit) WatchConfigSettingsHash() (StringsWatcher, error) { if u.doc.CharmURL == nil { return nil, fmt.Errorf("unit charm not set") } charmConfigKey := applicationCharmConfigKey(u.doc.Application, u.doc.CharmURL) return newSettingsHashWatcher(u.st, charmConfigKey), nil }
[ "func", "(", "u", "*", "Unit", ")", "WatchConfigSettingsHash", "(", ")", "(", "StringsWatcher", ",", "error", ")", "{", "if", "u", ".", "doc", ".", "CharmURL", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n"...
// WatchConfigSettingsHash returns a watcher that yields a hash of the // unit's charm config settings whenever they are changed. The // returned watcher will be valid only while the application's charm // URL is not changed.
[ "WatchConfigSettingsHash", "returns", "a", "watcher", "that", "yields", "a", "hash", "of", "the", "unit", "s", "charm", "config", "settings", "whenever", "they", "are", "changed", ".", "The", "returned", "watcher", "will", "be", "valid", "only", "while", "the"...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1791-L1797
train
juju/juju
state/watcher.go
WatchApplicationConfigSettingsHash
func (u *Unit) WatchApplicationConfigSettingsHash() (StringsWatcher, error) { applicationConfigKey := applicationConfigKey(u.ApplicationName()) return newSettingsHashWatcher(u.st, applicationConfigKey), nil }
go
func (u *Unit) WatchApplicationConfigSettingsHash() (StringsWatcher, error) { applicationConfigKey := applicationConfigKey(u.ApplicationName()) return newSettingsHashWatcher(u.st, applicationConfigKey), nil }
[ "func", "(", "u", "*", "Unit", ")", "WatchApplicationConfigSettingsHash", "(", ")", "(", "StringsWatcher", ",", "error", ")", "{", "applicationConfigKey", ":=", "applicationConfigKey", "(", "u", ".", "ApplicationName", "(", ")", ")", "\n", "return", "newSettings...
// WatchApplicationConfigSettingsHash is the same as // WatchConfigSettingsHash but watches the application's config rather // than charm configuration. Yields a hash of the application config // with each change.
[ "WatchApplicationConfigSettingsHash", "is", "the", "same", "as", "WatchConfigSettingsHash", "but", "watches", "the", "application", "s", "config", "rather", "than", "charm", "configuration", ".", "Yields", "a", "hash", "of", "the", "application", "config", "with", "...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1803-L1806
train
juju/juju
state/watcher.go
WatchMeterStatus
func (u *Unit) WatchMeterStatus() NotifyWatcher { return newDocWatcher(u.st, []docKey{ { meterStatusC, u.st.docID(u.globalMeterStatusKey()), }, { meterStatusC, metricsManagerKey(u.st), }, }) }
go
func (u *Unit) WatchMeterStatus() NotifyWatcher { return newDocWatcher(u.st, []docKey{ { meterStatusC, u.st.docID(u.globalMeterStatusKey()), }, { meterStatusC, metricsManagerKey(u.st), }, }) }
[ "func", "(", "u", "*", "Unit", ")", "WatchMeterStatus", "(", ")", "NotifyWatcher", "{", "return", "newDocWatcher", "(", "u", ".", "st", ",", "[", "]", "docKey", "{", "{", "meterStatusC", ",", "u", ".", "st", ".", "docID", "(", "u", ".", "globalMeterS...
// WatchMeterStatus returns a watcher observing changes that affect the meter status // of a unit.
[ "WatchMeterStatus", "returns", "a", "watcher", "observing", "changes", "that", "affect", "the", "meter", "status", "of", "a", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1810-L1820
train
juju/juju
state/watcher.go
WatchLXDProfileUpgradeNotifications
func (m *Machine) WatchLXDProfileUpgradeNotifications(applicationName string) (StringsWatcher, error) { app, err := m.st.Application(applicationName) if err != nil { return nil, errors.Trace(err) } watchDocId := app.doc.DocID return watchInstanceCharmProfileCompatibilityData(m.st, watchDocId), nil }
go
func (m *Machine) WatchLXDProfileUpgradeNotifications(applicationName string) (StringsWatcher, error) { app, err := m.st.Application(applicationName) if err != nil { return nil, errors.Trace(err) } watchDocId := app.doc.DocID return watchInstanceCharmProfileCompatibilityData(m.st, watchDocId), nil }
[ "func", "(", "m", "*", "Machine", ")", "WatchLXDProfileUpgradeNotifications", "(", "applicationName", "string", ")", "(", "StringsWatcher", ",", "error", ")", "{", "app", ",", "err", ":=", "m", ".", "st", ".", "Application", "(", "applicationName", ")", "\n"...
// WatchLXDProfileUpgradeNotifications returns a watcher that observes the status // of a lxd profile upgrade by monitoring changes on the unit machine's lxd profile // upgrade completed field that is specific to an application name. Used by // UniterAPI v9.
[ "WatchLXDProfileUpgradeNotifications", "returns", "a", "watcher", "that", "observes", "the", "status", "of", "a", "lxd", "profile", "upgrade", "by", "monitoring", "changes", "on", "the", "unit", "machine", "s", "lxd", "profile", "upgrade", "completed", "field", "t...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1826-L1833
train
juju/juju
state/watcher.go
WatchLXDProfileUpgradeNotifications
func (u *Unit) WatchLXDProfileUpgradeNotifications() (StringsWatcher, error) { app, err := u.Application() if err != nil { return nil, errors.Trace(err) } watchDocId := app.doc.DocID return watchInstanceCharmProfileCompatibilityData(u.st, watchDocId), nil }
go
func (u *Unit) WatchLXDProfileUpgradeNotifications() (StringsWatcher, error) { app, err := u.Application() if err != nil { return nil, errors.Trace(err) } watchDocId := app.doc.DocID return watchInstanceCharmProfileCompatibilityData(u.st, watchDocId), nil }
[ "func", "(", "u", "*", "Unit", ")", "WatchLXDProfileUpgradeNotifications", "(", ")", "(", "StringsWatcher", ",", "error", ")", "{", "app", ",", "err", ":=", "u", ".", "Application", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", ...
// WatchLXDProfileUpgradeNotifications returns a watcher that observes the status // of a lxd profile upgrade by monitoring changes on the unit machine's lxd profile // upgrade completed field that is specific to itself.
[ "WatchLXDProfileUpgradeNotifications", "returns", "a", "watcher", "that", "observes", "the", "status", "of", "a", "lxd", "profile", "upgrade", "by", "monitoring", "changes", "on", "the", "unit", "machine", "s", "lxd", "profile", "upgrade", "completed", "field", "t...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L1838-L1845
train
juju/juju
state/watcher.go
WatchUpgradeSeriesNotifications
func (m *Machine) WatchUpgradeSeriesNotifications() (NotifyWatcher, error) { watch := newEntityWatcher(m.st, machineUpgradeSeriesLocksC, m.doc.DocID) if _, ok := <-watch.Changes(); ok { return watch, nil } return nil, watcher.EnsureErr(watch) }
go
func (m *Machine) WatchUpgradeSeriesNotifications() (NotifyWatcher, error) { watch := newEntityWatcher(m.st, machineUpgradeSeriesLocksC, m.doc.DocID) if _, ok := <-watch.Changes(); ok { return watch, nil } return nil, watcher.EnsureErr(watch) }
[ "func", "(", "m", "*", "Machine", ")", "WatchUpgradeSeriesNotifications", "(", ")", "(", "NotifyWatcher", ",", "error", ")", "{", "watch", ":=", "newEntityWatcher", "(", "m", ".", "st", ",", "machineUpgradeSeriesLocksC", ",", "m", ".", "doc", ".", "DocID", ...
// WatchUpgradeSeriesNotifications returns a watcher that observes the status of // a series upgrade by monitoring changes to its parent machine's upgrade series // lock.
[ "WatchUpgradeSeriesNotifications", "returns", "a", "watcher", "that", "observes", "the", "status", "of", "a", "series", "upgrade", "by", "monitoring", "changes", "to", "its", "parent", "machine", "s", "upgrade", "series", "lock", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2023-L2030
train
juju/juju
state/watcher.go
getTxnRevno
func getTxnRevno(coll mongo.Collection, id interface{}) (int64, error) { doc := struct { TxnRevno int64 `bson:"txn-revno"` }{} fields := bson.D{{"txn-revno", 1}} if err := coll.FindId(id).Select(fields).One(&doc); err == mgo.ErrNotFound { return -1, nil } else if err != nil { return 0, err } return doc.TxnRevno, nil }
go
func getTxnRevno(coll mongo.Collection, id interface{}) (int64, error) { doc := struct { TxnRevno int64 `bson:"txn-revno"` }{} fields := bson.D{{"txn-revno", 1}} if err := coll.FindId(id).Select(fields).One(&doc); err == mgo.ErrNotFound { return -1, nil } else if err != nil { return 0, err } return doc.TxnRevno, nil }
[ "func", "getTxnRevno", "(", "coll", "mongo", ".", "Collection", ",", "id", "interface", "{", "}", ")", "(", "int64", ",", "error", ")", "{", "doc", ":=", "struct", "{", "TxnRevno", "int64", "`bson:\"txn-revno\"`", "\n", "}", "{", "}", "\n", "fields", "...
// getTxnRevno returns the transaction revision number of the // given document id in the given collection. It is useful to enable // a watcher.Watcher to be primed with the correct revision // id.
[ "getTxnRevno", "returns", "the", "transaction", "revision", "number", "of", "the", "given", "document", "id", "in", "the", "given", "collection", ".", "It", "is", "useful", "to", "enable", "a", "watcher", ".", "Watcher", "to", "be", "primed", "with", "the", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2076-L2087
train
juju/juju
state/watcher.go
watchNewUnits
func (w *machineUnitsWatcher) watchNewUnits(unitNames, pending []string, unitColl mongo.Collection) ([]string, error) { if len(unitNames) == 0 { return pending, nil } ids := make([]interface{}, len(unitNames)) for i := range unitNames { ids[i] = w.backend.docID(unitNames[i]) } logger.Tracef("for machine %q watching new units %q", w.machine.doc.DocID, unitNames) err := w.watcher.WatchMulti(unitsC, ids, w.in) if err != nil { return nil, errors.Trace(err) } if unitColl == nil { var closer SessionCloser unitColl, closer = w.db.GetCollection(unitsC) defer closer() } var doc unitDoc iter := unitColl.Find(bson.M{"_id": bson.M{"$in": unitNames}}).Iter() unknownSubs := set.NewStrings() notfound := set.NewStrings(unitNames...) for iter.Next(&doc) { notfound.Remove(doc.Name) w.known[doc.Name] = doc.Life pending = append(pending, doc.Name) // now load subordinates for _, subunitName := range doc.Subordinates { if _, subknown := w.known[subunitName]; !subknown { unknownSubs.Add(subunitName) } } } if err := iter.Close(); err != nil { return nil, errors.Trace(err) } for name := range notfound { logger.Debugf("unit %q referenced but not found", name) w.watcher.Unwatch(unitsC, w.backend.docID(name), w.in) } if !unknownSubs.IsEmpty() { pending, err = w.watchNewUnits(unknownSubs.Values(), pending, unitColl) if err != nil { return nil, errors.Trace(err) } } return pending, nil }
go
func (w *machineUnitsWatcher) watchNewUnits(unitNames, pending []string, unitColl mongo.Collection) ([]string, error) { if len(unitNames) == 0 { return pending, nil } ids := make([]interface{}, len(unitNames)) for i := range unitNames { ids[i] = w.backend.docID(unitNames[i]) } logger.Tracef("for machine %q watching new units %q", w.machine.doc.DocID, unitNames) err := w.watcher.WatchMulti(unitsC, ids, w.in) if err != nil { return nil, errors.Trace(err) } if unitColl == nil { var closer SessionCloser unitColl, closer = w.db.GetCollection(unitsC) defer closer() } var doc unitDoc iter := unitColl.Find(bson.M{"_id": bson.M{"$in": unitNames}}).Iter() unknownSubs := set.NewStrings() notfound := set.NewStrings(unitNames...) for iter.Next(&doc) { notfound.Remove(doc.Name) w.known[doc.Name] = doc.Life pending = append(pending, doc.Name) // now load subordinates for _, subunitName := range doc.Subordinates { if _, subknown := w.known[subunitName]; !subknown { unknownSubs.Add(subunitName) } } } if err := iter.Close(); err != nil { return nil, errors.Trace(err) } for name := range notfound { logger.Debugf("unit %q referenced but not found", name) w.watcher.Unwatch(unitsC, w.backend.docID(name), w.in) } if !unknownSubs.IsEmpty() { pending, err = w.watchNewUnits(unknownSubs.Values(), pending, unitColl) if err != nil { return nil, errors.Trace(err) } } return pending, nil }
[ "func", "(", "w", "*", "machineUnitsWatcher", ")", "watchNewUnits", "(", "unitNames", ",", "pending", "[", "]", "string", ",", "unitColl", "mongo", ".", "Collection", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "len", "(", "unitNames", ...
// watchNewUnits sets up a watcher for all of the named units and then updates pending changes. // There is an assumption that all unitNames being passed are unknown and do not have a watch active for them.
[ "watchNewUnits", "sets", "up", "a", "watcher", "for", "all", "of", "the", "named", "units", "and", "then", "updates", "pending", "changes", ".", "There", "is", "an", "assumption", "that", "all", "unitNames", "being", "passed", "are", "unknown", "and", "do", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2186-L2234
train
juju/juju
state/watcher.go
removeWatchedUnit
func (w *machineUnitsWatcher) removeWatchedUnit(unitName string, doc unitDoc, pending []string) ([]string, error) { logger.Tracef("machineUnitsWatcher removing unit %q for life %q", doc.Name, doc.Life) life, known := w.known[unitName] // Unit was removed or unassigned from w.machine if known { delete(w.known, unitName) docID := w.backend.docID(unitName) w.watcher.Unwatch(unitsC, docID, w.in) if life != Dead && !hasString(pending, unitName) { pending = append(pending, unitName) } for _, subunitName := range doc.Subordinates { if sublife, subknown := w.known[subunitName]; subknown { delete(w.known, subunitName) w.watcher.Unwatch(unitsC, w.backend.docID(subunitName), w.in) if sublife != Dead && !hasString(pending, subunitName) { pending = append(pending, subunitName) } } } } return pending, nil }
go
func (w *machineUnitsWatcher) removeWatchedUnit(unitName string, doc unitDoc, pending []string) ([]string, error) { logger.Tracef("machineUnitsWatcher removing unit %q for life %q", doc.Name, doc.Life) life, known := w.known[unitName] // Unit was removed or unassigned from w.machine if known { delete(w.known, unitName) docID := w.backend.docID(unitName) w.watcher.Unwatch(unitsC, docID, w.in) if life != Dead && !hasString(pending, unitName) { pending = append(pending, unitName) } for _, subunitName := range doc.Subordinates { if sublife, subknown := w.known[subunitName]; subknown { delete(w.known, subunitName) w.watcher.Unwatch(unitsC, w.backend.docID(subunitName), w.in) if sublife != Dead && !hasString(pending, subunitName) { pending = append(pending, subunitName) } } } } return pending, nil }
[ "func", "(", "w", "*", "machineUnitsWatcher", ")", "removeWatchedUnit", "(", "unitName", "string", ",", "doc", "unitDoc", ",", "pending", "[", "]", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "logger", ".", "Tracef", "(", "\"", "\""...
// removeWatchedUnit stops watching the unit, and all subordinates for this unit
[ "removeWatchedUnit", "stops", "watching", "the", "unit", "and", "all", "subordinates", "for", "this", "unit" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2237-L2259
train
juju/juju
state/watcher.go
newActionStatusWatcher
func newActionStatusWatcher(backend modelBackend, receivers []ActionReceiver, statusSet ...ActionStatus) StringsWatcher { watchLogger.Debugf("newActionStatusWatcher receivers:'%+v', statuses'%+v'", receivers, statusSet) w := &actionStatusWatcher{ commonWatcher: newCommonWatcher(backend), source: make(chan watcher.Change), sink: make(chan []string), receiverFilter: actionReceiverInCollectionOp(receivers...), statusFilter: statusInCollectionOp(statusSet...), } w.tomb.Go(func() error { defer close(w.sink) return w.loop() }) return w }
go
func newActionStatusWatcher(backend modelBackend, receivers []ActionReceiver, statusSet ...ActionStatus) StringsWatcher { watchLogger.Debugf("newActionStatusWatcher receivers:'%+v', statuses'%+v'", receivers, statusSet) w := &actionStatusWatcher{ commonWatcher: newCommonWatcher(backend), source: make(chan watcher.Change), sink: make(chan []string), receiverFilter: actionReceiverInCollectionOp(receivers...), statusFilter: statusInCollectionOp(statusSet...), } w.tomb.Go(func() error { defer close(w.sink) return w.loop() }) return w }
[ "func", "newActionStatusWatcher", "(", "backend", "modelBackend", ",", "receivers", "[", "]", "ActionReceiver", ",", "statusSet", "...", "ActionStatus", ")", "StringsWatcher", "{", "watchLogger", ".", "Debugf", "(", "\"", "\"", ",", "receivers", ",", "statusSet", ...
// newActionStatusWatcher returns the StringsWatcher that will notify // on changes to Actions with the given ActionReceiver and ActionStatus // filters.
[ "newActionStatusWatcher", "returns", "the", "StringsWatcher", "that", "will", "notify", "on", "changes", "to", "Actions", "with", "the", "given", "ActionReceiver", "and", "ActionStatus", "filters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2432-L2448
train
juju/juju
state/watcher.go
matchingIds
func (w *actionStatusWatcher) matchingIds(ids ...string) ([]string, error) { watchLogger.Tracef("actionStatusWatcher matchingIds() ids:'%+v'", ids) coll, closer := w.db.GetCollection(actionsC) defer closer() idFilter := localIdInCollectionOp(w.backend, ids...) query := bson.D{{"$and", []bson.D{idFilter, w.receiverFilter, w.statusFilter}}} iter := coll.Find(query).Iter() var found []string var doc actionDoc for iter.Next(&doc) { found = append(found, w.backend.localID(doc.DocId)) } watchLogger.Debugf("actionStatusWatcher matchingIds() ids:'%+v', found:'%+v'", ids, found) return found, iter.Close() }
go
func (w *actionStatusWatcher) matchingIds(ids ...string) ([]string, error) { watchLogger.Tracef("actionStatusWatcher matchingIds() ids:'%+v'", ids) coll, closer := w.db.GetCollection(actionsC) defer closer() idFilter := localIdInCollectionOp(w.backend, ids...) query := bson.D{{"$and", []bson.D{idFilter, w.receiverFilter, w.statusFilter}}} iter := coll.Find(query).Iter() var found []string var doc actionDoc for iter.Next(&doc) { found = append(found, w.backend.localID(doc.DocId)) } watchLogger.Debugf("actionStatusWatcher matchingIds() ids:'%+v', found:'%+v'", ids, found) return found, iter.Close() }
[ "func", "(", "w", "*", "actionStatusWatcher", ")", "matchingIds", "(", "ids", "...", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "watchLogger", ".", "Tracef", "(", "\"", "\"", ",", "ids", ")", "\n\n", "coll", ",", "closer", ":=", ...
// matchingIds is a helper function that filters the actionsC collection // on the ActionReceivers and ActionStatus set defined on the watcher. // If ids are passed in the collection is further filtered to only // Actions that also have one of the supplied _id's.
[ "matchingIds", "is", "a", "helper", "function", "that", "filters", "the", "actionsC", "collection", "on", "the", "ActionReceivers", "and", "ActionStatus", "set", "defined", "on", "the", "watcher", ".", "If", "ids", "are", "passed", "in", "the", "collection", "...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2511-L2527
train
juju/juju
state/watcher.go
filterAndMergeIds
func (w *actionStatusWatcher) filterAndMergeIds(changes *[]string, updates map[interface{}]bool) error { watchLogger.Tracef("actionStatusWatcher filterAndMergeIds(changes:'%+v', updates:'%+v')", changes, updates) var adds []string for id, exists := range updates { switch id := id.(type) { case string: localId := w.backend.localID(id) chIx, idAlreadyInChangeset := indexOf(localId, *changes) if exists { if !idAlreadyInChangeset { adds = append(adds, localId) } } else { if idAlreadyInChangeset { // remove id from changes *changes = append((*changes)[:chIx], (*changes)[chIx+1:]...) } } default: return errors.Errorf("id is not of type string, got %T", id) } } if len(adds) > 0 { ids, err := w.matchingIds(adds...) if err != nil { return errors.Trace(err) } *changes = append(*changes, ids...) } return nil }
go
func (w *actionStatusWatcher) filterAndMergeIds(changes *[]string, updates map[interface{}]bool) error { watchLogger.Tracef("actionStatusWatcher filterAndMergeIds(changes:'%+v', updates:'%+v')", changes, updates) var adds []string for id, exists := range updates { switch id := id.(type) { case string: localId := w.backend.localID(id) chIx, idAlreadyInChangeset := indexOf(localId, *changes) if exists { if !idAlreadyInChangeset { adds = append(adds, localId) } } else { if idAlreadyInChangeset { // remove id from changes *changes = append((*changes)[:chIx], (*changes)[chIx+1:]...) } } default: return errors.Errorf("id is not of type string, got %T", id) } } if len(adds) > 0 { ids, err := w.matchingIds(adds...) if err != nil { return errors.Trace(err) } *changes = append(*changes, ids...) } return nil }
[ "func", "(", "w", "*", "actionStatusWatcher", ")", "filterAndMergeIds", "(", "changes", "*", "[", "]", "string", ",", "updates", "map", "[", "interface", "{", "}", "]", "bool", ")", "error", "{", "watchLogger", ".", "Tracef", "(", "\"", "\"", ",", "cha...
// filterAndMergeIds combines existing pending changes along with // updates from the upstream watcher, and updates the changes set. // If the upstream changes do not match the ActionReceivers and // ActionStatus set filters defined on the watcher, they are silently // dropped.
[ "filterAndMergeIds", "combines", "existing", "pending", "changes", "along", "with", "updates", "from", "the", "upstream", "watcher", "and", "updates", "the", "changes", "set", ".", "If", "the", "upstream", "changes", "do", "not", "match", "the", "ActionReceivers",...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2534-L2564
train
juju/juju
state/watcher.go
inCollectionOp
func inCollectionOp(key string, ids ...string) bson.D { ret := bson.D{} switch len(ids) { case 0: case 1: ret = append(ret, bson.DocElem{key, ids[0]}) default: ret = append(ret, bson.DocElem{key, bson.D{{"$in", ids}}}) } return ret }
go
func inCollectionOp(key string, ids ...string) bson.D { ret := bson.D{} switch len(ids) { case 0: case 1: ret = append(ret, bson.DocElem{key, ids[0]}) default: ret = append(ret, bson.DocElem{key, bson.D{{"$in", ids}}}) } return ret }
[ "func", "inCollectionOp", "(", "key", "string", ",", "ids", "...", "string", ")", "bson", ".", "D", "{", "ret", ":=", "bson", ".", "D", "{", "}", "\n", "switch", "len", "(", "ids", ")", "{", "case", "0", ":", "case", "1", ":", "ret", "=", "appe...
// inCollectionOp takes a key name and a list of potential values and // returns a bson.D Op that will match on the supplied key and values.
[ "inCollectionOp", "takes", "a", "key", "name", "and", "a", "list", "of", "potential", "values", "and", "returns", "a", "bson", ".", "D", "Op", "that", "will", "match", "on", "the", "supplied", "key", "and", "values", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2568-L2578
train
juju/juju
state/watcher.go
localIdInCollectionOp
func localIdInCollectionOp(st modelBackend, localIds ...string) bson.D { ids := make([]string, len(localIds)) for i, id := range localIds { ids[i] = st.docID(id) } return inCollectionOp("_id", ids...) }
go
func localIdInCollectionOp(st modelBackend, localIds ...string) bson.D { ids := make([]string, len(localIds)) for i, id := range localIds { ids[i] = st.docID(id) } return inCollectionOp("_id", ids...) }
[ "func", "localIdInCollectionOp", "(", "st", "modelBackend", ",", "localIds", "...", "string", ")", "bson", ".", "D", "{", "ids", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "localIds", ")", ")", "\n", "for", "i", ",", "id", ":=", "range",...
// localIdInCollectionOp is a special form of inCollectionOp that just // converts id's to their model-uuid prefixed form.
[ "localIdInCollectionOp", "is", "a", "special", "form", "of", "inCollectionOp", "that", "just", "converts", "id", "s", "to", "their", "model", "-", "uuid", "prefixed", "form", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2582-L2588
train
juju/juju
state/watcher.go
newCollectionWatcher
func newCollectionWatcher(backend modelBackend, cfg colWCfg) StringsWatcher { if cfg.global { if cfg.filter == nil { cfg.filter = func(x interface{}) bool { return true } } } else { // Always ensure that there is at least filtering on the // model in place. backstop := isLocalID(backend) if cfg.filter == nil { cfg.filter = backstop } else { innerFilter := cfg.filter cfg.filter = func(id interface{}) bool { if !backstop(id) { return false } return innerFilter(id) } } } w := &collectionWatcher{ colWCfg: cfg, commonWatcher: newCommonWatcher(backend), source: make(chan watcher.Change), sink: make(chan []string), } w.tomb.Go(func() error { defer close(w.sink) defer close(w.source) return w.loop() }) return w }
go
func newCollectionWatcher(backend modelBackend, cfg colWCfg) StringsWatcher { if cfg.global { if cfg.filter == nil { cfg.filter = func(x interface{}) bool { return true } } } else { // Always ensure that there is at least filtering on the // model in place. backstop := isLocalID(backend) if cfg.filter == nil { cfg.filter = backstop } else { innerFilter := cfg.filter cfg.filter = func(id interface{}) bool { if !backstop(id) { return false } return innerFilter(id) } } } w := &collectionWatcher{ colWCfg: cfg, commonWatcher: newCommonWatcher(backend), source: make(chan watcher.Change), sink: make(chan []string), } w.tomb.Go(func() error { defer close(w.sink) defer close(w.source) return w.loop() }) return w }
[ "func", "newCollectionWatcher", "(", "backend", "modelBackend", ",", "cfg", "colWCfg", ")", "StringsWatcher", "{", "if", "cfg", ".", "global", "{", "if", "cfg", ".", "filter", "==", "nil", "{", "cfg", ".", "filter", "=", "func", "(", "x", "interface", "{...
// newCollectionWatcher starts and returns a new StringsWatcher configured // with the given collection and filter function
[ "newCollectionWatcher", "starts", "and", "returns", "a", "new", "StringsWatcher", "configured", "with", "the", "given", "collection", "and", "filter", "function" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2632-L2670
train
juju/juju
state/watcher.go
makeIdFilter
func makeIdFilter(backend modelBackend, marker string, receivers ...ActionReceiver) func(interface{}) bool { if len(receivers) == 0 { return nil } ensureMarkerFn := ensureSuffixFn(marker) prefixes := make([]string, len(receivers)) for ix, receiver := range receivers { prefixes[ix] = backend.docID(ensureMarkerFn(receiver.Tag().Id())) } return func(key interface{}) bool { switch key.(type) { case string: for _, prefix := range prefixes { if strings.HasPrefix(key.(string), prefix) { return true } } default: watchLogger.Errorf("key is not type string, got %T", key) } return false } }
go
func makeIdFilter(backend modelBackend, marker string, receivers ...ActionReceiver) func(interface{}) bool { if len(receivers) == 0 { return nil } ensureMarkerFn := ensureSuffixFn(marker) prefixes := make([]string, len(receivers)) for ix, receiver := range receivers { prefixes[ix] = backend.docID(ensureMarkerFn(receiver.Tag().Id())) } return func(key interface{}) bool { switch key.(type) { case string: for _, prefix := range prefixes { if strings.HasPrefix(key.(string), prefix) { return true } } default: watchLogger.Errorf("key is not type string, got %T", key) } return false } }
[ "func", "makeIdFilter", "(", "backend", "modelBackend", ",", "marker", "string", ",", "receivers", "...", "ActionReceiver", ")", "func", "(", "interface", "{", "}", ")", "bool", "{", "if", "len", "(", "receivers", ")", "==", "0", "{", "return", "nil", "\...
// makeIdFilter constructs a predicate to filter keys that have the // prefix matching one of the passed in ActionReceivers, or returns nil // if tags is empty
[ "makeIdFilter", "constructs", "a", "predicate", "to", "filter", "keys", "that", "have", "the", "prefix", "matching", "one", "of", "the", "passed", "in", "ActionReceivers", "or", "returns", "nil", "if", "tags", "is", "empty" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2721-L2744
train
juju/juju
state/watcher.go
initial
func (w *collectionWatcher) initial() ([]string, error) { var ids []string var doc struct { DocId string `bson:"_id"` } coll, closer := w.db.GetCollection(w.col) defer closer() iter := coll.Find(nil).Iter() for iter.Next(&doc) { if w.filter == nil || w.filter(doc.DocId) { id := doc.DocId if !w.colWCfg.global { id = w.backend.localID(id) } if w.idconv != nil { id = w.idconv(id) } ids = append(ids, id) } } return ids, iter.Close() }
go
func (w *collectionWatcher) initial() ([]string, error) { var ids []string var doc struct { DocId string `bson:"_id"` } coll, closer := w.db.GetCollection(w.col) defer closer() iter := coll.Find(nil).Iter() for iter.Next(&doc) { if w.filter == nil || w.filter(doc.DocId) { id := doc.DocId if !w.colWCfg.global { id = w.backend.localID(id) } if w.idconv != nil { id = w.idconv(id) } ids = append(ids, id) } } return ids, iter.Close() }
[ "func", "(", "w", "*", "collectionWatcher", ")", "initial", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "ids", "[", "]", "string", "\n", "var", "doc", "struct", "{", "DocId", "string", "`bson:\"_id\"`", "\n", "}", "\n", "coll", ...
// initial pre-loads the id's that have already been added to the // collection that would otherwise not normally trigger the watcher
[ "initial", "pre", "-", "loads", "the", "id", "s", "that", "have", "already", "been", "added", "to", "the", "collection", "that", "would", "otherwise", "not", "normally", "trigger", "the", "watcher" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2748-L2769
train
juju/juju
state/watcher.go
mergeIds
func (w *collectionWatcher) mergeIds(changes *[]string, updates map[interface{}]bool) error { return mergeIds(w.backend, changes, updates, w.convertId) }
go
func (w *collectionWatcher) mergeIds(changes *[]string, updates map[interface{}]bool) error { return mergeIds(w.backend, changes, updates, w.convertId) }
[ "func", "(", "w", "*", "collectionWatcher", ")", "mergeIds", "(", "changes", "*", "[", "]", "string", ",", "updates", "map", "[", "interface", "{", "}", "]", "bool", ")", "error", "{", "return", "mergeIds", "(", "w", ".", "backend", ",", "changes", "...
// mergeIds is used for merging actionId's and actionResultId's that // come in via the updates map. It cleans up the pending changes to // account for id's being removed before the watcher consumes them, // and to account for the potential overlap between the id's that were // pending before the watcher started, and the new id's detected by the // watcher. // Additionally, mergeIds strips the model UUID prefix from the id // before emitting it through the watcher.
[ "mergeIds", "is", "used", "for", "merging", "actionId", "s", "and", "actionResultId", "s", "that", "come", "in", "via", "the", "updates", "map", ".", "It", "cleans", "up", "the", "pending", "changes", "to", "account", "for", "id", "s", "being", "removed", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2779-L2781
train
juju/juju
state/watcher.go
ensureSuffixFn
func ensureSuffixFn(marker string) func(string) string { return func(p string) string { if !strings.HasSuffix(p, marker) { p = p + marker } return p } }
go
func ensureSuffixFn(marker string) func(string) string { return func(p string) string { if !strings.HasSuffix(p, marker) { p = p + marker } return p } }
[ "func", "ensureSuffixFn", "(", "marker", "string", ")", "func", "(", "string", ")", "string", "{", "return", "func", "(", "p", "string", ")", "string", "{", "if", "!", "strings", ".", "HasSuffix", "(", "p", ",", "marker", ")", "{", "p", "=", "p", "...
// ensureSuffixFn returns a function that will make sure the passed in // string has the marker token at the end of it
[ "ensureSuffixFn", "returns", "a", "function", "that", "will", "make", "sure", "the", "passed", "in", "string", "has", "the", "marker", "token", "at", "the", "end", "of", "it" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2845-L2852
train
juju/juju
state/watcher.go
watchEnqueuedActionsFilteredBy
func (st *State) watchEnqueuedActionsFilteredBy(receivers ...ActionReceiver) StringsWatcher { return newCollectionWatcher(st, colWCfg{ col: actionNotificationsC, filter: makeIdFilter(st, actionMarker, receivers...), idconv: actionNotificationIdToActionId, }) }
go
func (st *State) watchEnqueuedActionsFilteredBy(receivers ...ActionReceiver) StringsWatcher { return newCollectionWatcher(st, colWCfg{ col: actionNotificationsC, filter: makeIdFilter(st, actionMarker, receivers...), idconv: actionNotificationIdToActionId, }) }
[ "func", "(", "st", "*", "State", ")", "watchEnqueuedActionsFilteredBy", "(", "receivers", "...", "ActionReceiver", ")", "StringsWatcher", "{", "return", "newCollectionWatcher", "(", "st", ",", "colWCfg", "{", "col", ":", "actionNotificationsC", ",", "filter", ":",...
// watchEnqueuedActionsFilteredBy starts and returns a StringsWatcher // that notifies on new Actions being enqueued on the ActionRecevers // being watched.
[ "watchEnqueuedActionsFilteredBy", "starts", "and", "returns", "a", "StringsWatcher", "that", "notifies", "on", "new", "Actions", "being", "enqueued", "on", "the", "ActionRecevers", "being", "watched", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2857-L2863
train
juju/juju
state/watcher.go
WatchActionResultsFilteredBy
func (m *Model) WatchActionResultsFilteredBy(receivers ...ActionReceiver) StringsWatcher { return newActionStatusWatcher(m.st, receivers, []ActionStatus{ActionCompleted, ActionCancelled, ActionFailed}...) }
go
func (m *Model) WatchActionResultsFilteredBy(receivers ...ActionReceiver) StringsWatcher { return newActionStatusWatcher(m.st, receivers, []ActionStatus{ActionCompleted, ActionCancelled, ActionFailed}...) }
[ "func", "(", "m", "*", "Model", ")", "WatchActionResultsFilteredBy", "(", "receivers", "...", "ActionReceiver", ")", "StringsWatcher", "{", "return", "newActionStatusWatcher", "(", "m", ".", "st", ",", "receivers", ",", "[", "]", "ActionStatus", "{", "ActionComp...
// WatchActionResultsFilteredBy starts and returns a StringsWatcher // that notifies on new ActionResults being added for the ActionRecevers // being watched.
[ "WatchActionResultsFilteredBy", "starts", "and", "returns", "a", "StringsWatcher", "that", "notifies", "on", "new", "ActionResults", "being", "added", "for", "the", "ActionRecevers", "being", "watched", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L2941-L2943
train
juju/juju
state/watcher.go
WatchForRebootEvent
func (m *Machine) WatchForRebootEvent() NotifyWatcher { machineIds := m.machinesToCareAboutRebootsFor() machines := set.NewStrings(machineIds...) filter := func(key interface{}) bool { if id, ok := key.(string); ok { if id, err := m.st.strictLocalID(id); err == nil { return machines.Contains(id) } else { return false } } return false } return newNotifyCollWatcher(m.st, rebootC, filter) }
go
func (m *Machine) WatchForRebootEvent() NotifyWatcher { machineIds := m.machinesToCareAboutRebootsFor() machines := set.NewStrings(machineIds...) filter := func(key interface{}) bool { if id, ok := key.(string); ok { if id, err := m.st.strictLocalID(id); err == nil { return machines.Contains(id) } else { return false } } return false } return newNotifyCollWatcher(m.st, rebootC, filter) }
[ "func", "(", "m", "*", "Machine", ")", "WatchForRebootEvent", "(", ")", "NotifyWatcher", "{", "machineIds", ":=", "m", ".", "machinesToCareAboutRebootsFor", "(", ")", "\n", "machines", ":=", "set", ".", "NewStrings", "(", "machineIds", "...", ")", "\n\n", "f...
// WatchForRebootEvent returns a notify watcher that will trigger an event // when the reboot flag is set on our machine agent, our parent machine agent // or grandparent machine agent
[ "WatchForRebootEvent", "returns", "a", "notify", "watcher", "that", "will", "trigger", "an", "event", "when", "the", "reboot", "flag", "is", "set", "on", "our", "machine", "agent", "our", "parent", "machine", "agent", "or", "grandparent", "machine", "agent" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L3090-L3105
train
juju/juju
state/watcher.go
WatchRemoteRelations
func (st *State) WatchRemoteRelations() StringsWatcher { // Use a no-op transform func to record the known ids. known := make(map[interface{}]bool) tr := func(id string) string { known[id] = true return id } filter := func(id interface{}) bool { id, err := st.strictLocalID(id.(string)) if err != nil { return false } // Gather the remote app names. remoteApps, closer := st.db().GetCollection(remoteApplicationsC) defer closer() type remoteAppDoc struct { Name string } remoteAppNameField := bson.D{{"name", 1}} var apps []remoteAppDoc err = remoteApps.Find(nil).Select(remoteAppNameField).All(&apps) if err != nil { watchLogger.Errorf("could not lookup remote application names: %v", err) return false } remoteAppNames := set.NewStrings() for _, a := range apps { remoteAppNames.Add(a.Name) } // Run a query to pickup any relations to those remote apps. relations, closer := st.db().GetCollection(relationsC) defer closer() query := bson.D{ {"key", id}, {"endpoints.applicationname", bson.D{{"$in", remoteAppNames.Values()}}}, } num, err := relations.Find(query).Count() if err != nil { watchLogger.Errorf("could not lookup remote relations: %v", err) return false } // The relation (or remote app) may have been deleted, but if it has been // seen previously, return true. if num == 0 { _, seen := known[id] delete(known, id) return seen } return num > 0 } return newRelationLifeSuspendedWatcher(st, nil, filter, tr) }
go
func (st *State) WatchRemoteRelations() StringsWatcher { // Use a no-op transform func to record the known ids. known := make(map[interface{}]bool) tr := func(id string) string { known[id] = true return id } filter := func(id interface{}) bool { id, err := st.strictLocalID(id.(string)) if err != nil { return false } // Gather the remote app names. remoteApps, closer := st.db().GetCollection(remoteApplicationsC) defer closer() type remoteAppDoc struct { Name string } remoteAppNameField := bson.D{{"name", 1}} var apps []remoteAppDoc err = remoteApps.Find(nil).Select(remoteAppNameField).All(&apps) if err != nil { watchLogger.Errorf("could not lookup remote application names: %v", err) return false } remoteAppNames := set.NewStrings() for _, a := range apps { remoteAppNames.Add(a.Name) } // Run a query to pickup any relations to those remote apps. relations, closer := st.db().GetCollection(relationsC) defer closer() query := bson.D{ {"key", id}, {"endpoints.applicationname", bson.D{{"$in", remoteAppNames.Values()}}}, } num, err := relations.Find(query).Count() if err != nil { watchLogger.Errorf("could not lookup remote relations: %v", err) return false } // The relation (or remote app) may have been deleted, but if it has been // seen previously, return true. if num == 0 { _, seen := known[id] delete(known, id) return seen } return num > 0 } return newRelationLifeSuspendedWatcher(st, nil, filter, tr) }
[ "func", "(", "st", "*", "State", ")", "WatchRemoteRelations", "(", ")", "StringsWatcher", "{", "// Use a no-op transform func to record the known ids.", "known", ":=", "make", "(", "map", "[", "interface", "{", "}", "]", "bool", ")", "\n", "tr", ":=", "func", ...
// WatchRemoteRelations returns a StringsWatcher that notifies of changes to // the lifecycles of the remote relations in the model.
[ "WatchRemoteRelations", "returns", "a", "StringsWatcher", "that", "notifies", "of", "changes", "to", "the", "lifecycles", "of", "the", "remote", "relations", "in", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L3313-L3369
train
juju/juju
state/watcher.go
WatchSubnets
func (st *State) WatchSubnets(subnetFilter func(id interface{}) bool) StringsWatcher { filter := func(id interface{}) bool { subnet, err := st.strictLocalID(id.(string)) if err != nil { return false } if subnetFilter == nil { return true } return subnetFilter(subnet) } return newLifecycleWatcher(st, subnetsC, nil, filter, nil) }
go
func (st *State) WatchSubnets(subnetFilter func(id interface{}) bool) StringsWatcher { filter := func(id interface{}) bool { subnet, err := st.strictLocalID(id.(string)) if err != nil { return false } if subnetFilter == nil { return true } return subnetFilter(subnet) } return newLifecycleWatcher(st, subnetsC, nil, filter, nil) }
[ "func", "(", "st", "*", "State", ")", "WatchSubnets", "(", "subnetFilter", "func", "(", "id", "interface", "{", "}", ")", "bool", ")", "StringsWatcher", "{", "filter", ":=", "func", "(", "id", "interface", "{", "}", ")", "bool", "{", "subnet", ",", "...
// WatchSubnets returns a StringsWatcher that notifies of changes to // the lifecycles of the subnets in the model.
[ "WatchSubnets", "returns", "a", "StringsWatcher", "that", "notifies", "of", "changes", "to", "the", "lifecycles", "of", "the", "subnets", "in", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L3373-L3386
train
juju/juju
state/watcher.go
isLocalID
func isLocalID(st modelBackend) func(interface{}) bool { return func(id interface{}) bool { key, ok := id.(string) if !ok { return false } _, err := st.strictLocalID(key) return err == nil } }
go
func isLocalID(st modelBackend) func(interface{}) bool { return func(id interface{}) bool { key, ok := id.(string) if !ok { return false } _, err := st.strictLocalID(key) return err == nil } }
[ "func", "isLocalID", "(", "st", "modelBackend", ")", "func", "(", "interface", "{", "}", ")", "bool", "{", "return", "func", "(", "id", "interface", "{", "}", ")", "bool", "{", "key", ",", "ok", ":=", "id", ".", "(", "string", ")", "\n", "if", "!...
// isLocalID returns a watcher filter func that rejects ids not specific // to the supplied modelBackend.
[ "isLocalID", "returns", "a", "watcher", "filter", "func", "that", "rejects", "ids", "not", "specific", "to", "the", "supplied", "modelBackend", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L3390-L3399
train
juju/juju
state/watcher.go
WatchRelationIngressNetworks
func (r *Relation) WatchRelationIngressNetworks() StringsWatcher { return newrelationNetworksWatcher(r.st, r.Tag().Id(), ingress) }
go
func (r *Relation) WatchRelationIngressNetworks() StringsWatcher { return newrelationNetworksWatcher(r.st, r.Tag().Id(), ingress) }
[ "func", "(", "r", "*", "Relation", ")", "WatchRelationIngressNetworks", "(", ")", "StringsWatcher", "{", "return", "newrelationNetworksWatcher", "(", "r", ".", "st", ",", "r", ".", "Tag", "(", ")", ".", "Id", "(", ")", ",", "ingress", ")", "\n", "}" ]
// WatchRelationIngressNetworks starts and returns a StringsWatcher notifying // of ingress changes to the relationNetworks collection for the relation.
[ "WatchRelationIngressNetworks", "starts", "and", "returns", "a", "StringsWatcher", "notifying", "of", "ingress", "changes", "to", "the", "relationNetworks", "collection", "for", "the", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L3417-L3419
train
juju/juju
state/watcher.go
WatchRelationEgressNetworks
func (r *Relation) WatchRelationEgressNetworks() StringsWatcher { return newrelationNetworksWatcher(r.st, r.Tag().Id(), egress) }
go
func (r *Relation) WatchRelationEgressNetworks() StringsWatcher { return newrelationNetworksWatcher(r.st, r.Tag().Id(), egress) }
[ "func", "(", "r", "*", "Relation", ")", "WatchRelationEgressNetworks", "(", ")", "StringsWatcher", "{", "return", "newrelationNetworksWatcher", "(", "r", ".", "st", ",", "r", ".", "Tag", "(", ")", ".", "Id", "(", ")", ",", "egress", ")", "\n", "}" ]
// WatchRelationEgressNetworks starts and returns a StringsWatcher notifying // of egress changes to the relationNetworks collection for the relation.
[ "WatchRelationEgressNetworks", "starts", "and", "returns", "a", "StringsWatcher", "notifying", "of", "egress", "changes", "to", "the", "relationNetworks", "collection", "for", "the", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L3423-L3425
train
juju/juju
state/watcher.go
WatchPodSpec
func (m *CAASModel) WatchPodSpec(appTag names.ApplicationTag) (NotifyWatcher, error) { docKeys := []docKey{{ podSpecsC, m.st.docID(applicationGlobalKey(appTag.Id())), }} return newDocWatcher(m.st, docKeys), nil }
go
func (m *CAASModel) WatchPodSpec(appTag names.ApplicationTag) (NotifyWatcher, error) { docKeys := []docKey{{ podSpecsC, m.st.docID(applicationGlobalKey(appTag.Id())), }} return newDocWatcher(m.st, docKeys), nil }
[ "func", "(", "m", "*", "CAASModel", ")", "WatchPodSpec", "(", "appTag", "names", ".", "ApplicationTag", ")", "(", "NotifyWatcher", ",", "error", ")", "{", "docKeys", ":=", "[", "]", "docKey", "{", "{", "podSpecsC", ",", "m", ".", "st", ".", "docID", ...
// WatchPodSpec returns a watcher observing changes that affect the // pod spec for an application or unit.
[ "WatchPodSpec", "returns", "a", "watcher", "observing", "changes", "that", "affect", "the", "pod", "spec", "for", "an", "application", "or", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L3630-L3636
train
juju/juju
state/watcher.go
WatchContainerAddressesHash
func (u *Unit) WatchContainerAddressesHash() StringsWatcher { firstCall := true w := &hashWatcher{ commonWatcher: newCommonWatcher(u.st), out: make(chan []string), collection: cloudContainersC, id: u.st.docID(u.globalKey()), hash: func() (string, error) { result, err := hashContainerAddresses(u, firstCall) firstCall = false return result, err }, } w.start() return w }
go
func (u *Unit) WatchContainerAddressesHash() StringsWatcher { firstCall := true w := &hashWatcher{ commonWatcher: newCommonWatcher(u.st), out: make(chan []string), collection: cloudContainersC, id: u.st.docID(u.globalKey()), hash: func() (string, error) { result, err := hashContainerAddresses(u, firstCall) firstCall = false return result, err }, } w.start() return w }
[ "func", "(", "u", "*", "Unit", ")", "WatchContainerAddressesHash", "(", ")", "StringsWatcher", "{", "firstCall", ":=", "true", "\n", "w", ":=", "&", "hashWatcher", "{", "commonWatcher", ":", "newCommonWatcher", "(", "u", ".", "st", ")", ",", "out", ":", ...
// WatchContainerAddressesHash returns a StringsWatcher that emits a // hash of the unit's container address whenever it changes.
[ "WatchContainerAddressesHash", "returns", "a", "StringsWatcher", "that", "emits", "a", "hash", "of", "the", "unit", "s", "container", "address", "whenever", "it", "changes", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/watcher.go#L3792-L3807
train
juju/juju
cmd/juju/subnet/subnet.go
NewAPI
func (c *SubnetCommandBase) NewAPI() (SubnetAPI, error) { if c.api != nil { // Already created. return c.api, nil } root, err := c.NewAPIRoot() if err != nil { return nil, errors.Trace(err) } // This is tested with a feature test. shim := &mvpAPIShim{ apiState: root, facade: subnets.NewAPI(root), } return shim, nil }
go
func (c *SubnetCommandBase) NewAPI() (SubnetAPI, error) { if c.api != nil { // Already created. return c.api, nil } root, err := c.NewAPIRoot() if err != nil { return nil, errors.Trace(err) } // This is tested with a feature test. shim := &mvpAPIShim{ apiState: root, facade: subnets.NewAPI(root), } return shim, nil }
[ "func", "(", "c", "*", "SubnetCommandBase", ")", "NewAPI", "(", ")", "(", "SubnetAPI", ",", "error", ")", "{", "if", "c", ".", "api", "!=", "nil", "{", "// Already created.", "return", "c", ".", "api", ",", "nil", "\n", "}", "\n", "root", ",", "err...
// NewAPI returns a SubnetAPI for the root api endpoint that the // environment command returns.
[ "NewAPI", "returns", "a", "SubnetAPI", "for", "the", "root", "api", "endpoint", "that", "the", "environment", "command", "returns", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/subnet/subnet.go#L83-L99
train
juju/juju
cmd/juju/subnet/subnet.go
ValidateSpace
func (s *SubnetCommandBase) ValidateSpace(given string) (names.SpaceTag, error) { if !names.IsValidSpace(given) { return names.SpaceTag{}, errors.Errorf("%q is not a valid space name", given) } return names.NewSpaceTag(given), nil }
go
func (s *SubnetCommandBase) ValidateSpace(given string) (names.SpaceTag, error) { if !names.IsValidSpace(given) { return names.SpaceTag{}, errors.Errorf("%q is not a valid space name", given) } return names.NewSpaceTag(given), nil }
[ "func", "(", "s", "*", "SubnetCommandBase", ")", "ValidateSpace", "(", "given", "string", ")", "(", "names", ".", "SpaceTag", ",", "error", ")", "{", "if", "!", "names", ".", "IsValidSpace", "(", "given", ")", "{", "return", "names", ".", "SpaceTag", "...
// ValidateSpace parses given and returns an error if it's not a valid // space name, otherwise returns the parsed tag and no error.
[ "ValidateSpace", "parses", "given", "and", "returns", "an", "error", "if", "it", "s", "not", "a", "valid", "space", "name", "otherwise", "returns", "the", "parsed", "tag", "and", "no", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/subnet/subnet.go#L154-L159
train
juju/juju
worker/state/statetracker.go
Use
func (c *stateTracker) Use() (*state.StatePool, error) { c.mu.Lock() defer c.mu.Unlock() if c.references == 0 { return nil, ErrStateClosed } c.references++ return c.pool, nil }
go
func (c *stateTracker) Use() (*state.StatePool, error) { c.mu.Lock() defer c.mu.Unlock() if c.references == 0 { return nil, ErrStateClosed } c.references++ return c.pool, nil }
[ "func", "(", "c", "*", "stateTracker", ")", "Use", "(", ")", "(", "*", "state", ".", "StatePool", ",", "error", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", ...
// Use implements StateTracker.
[ "Use", "implements", "StateTracker", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/state/statetracker.go#L53-L62
train
juju/juju
worker/state/statetracker.go
Done
func (c *stateTracker) Done() error { c.mu.Lock() defer c.mu.Unlock() if c.references == 0 { return ErrStateClosed } c.references-- if c.references == 0 { if err := c.pool.Close(); err != nil { logger.Errorf("error when closing state pool: %v", err) } } return nil }
go
func (c *stateTracker) Done() error { c.mu.Lock() defer c.mu.Unlock() if c.references == 0 { return ErrStateClosed } c.references-- if c.references == 0 { if err := c.pool.Close(); err != nil { logger.Errorf("error when closing state pool: %v", err) } } return nil }
[ "func", "(", "c", "*", "stateTracker", ")", "Done", "(", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "references", "==", "0", "{", "return", "ErrState...
// Done implements StateTracker.
[ "Done", "implements", "StateTracker", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/state/statetracker.go#L65-L79
train
juju/juju
cmd/juju/controller/listmodels.go
tabularSummaries
func (c *modelsCommand) tabularSummaries(writer io.Writer, modelSet ModelSummarySet) error { tw := output.TabWriter(writer) w := output.Wrapper{tw} c.tabularColumns(tw, w) for _, model := range modelSet.Models { cloudRegion := strings.Trim(model.Cloud+"/"+model.CloudRegion, "/") owner := names.NewUserTag(model.Owner) name := model.Name if c.runVars.currentUser == owner { // No need to display fully qualified model name to its owner. name = model.ShortName } if model.Name == modelSet.CurrentModelQualified { name += "*" w.PrintColor(output.CurrentHighlight, name) } else { w.Print(name) } if c.listUUID { w.Print(model.UUID) } status := "-" if model.Status != nil && model.Status.Current.String() != "" { status = model.Status.Current.String() } w.Print(cloudRegion, model.ProviderType, status) if c.runVars.hasMachinesCount { if v, ok := model.Counts[string(params.Machines)]; ok { w.Print(v) } else { w.Print(0) } } if c.runVars.hasCoresCount { if v, ok := model.Counts[string(params.Cores)]; ok { w.Print(v) } else { w.Print("-") } } if c.runVars.hasUnitsCount { if v, ok := model.Counts[string(params.Units)]; ok { w.Print(v) } else { w.Print("-") } } access := model.UserAccess if access == "" { access = "-" } w.Println(access, model.UserLastConnection) } tw.Flush() return nil }
go
func (c *modelsCommand) tabularSummaries(writer io.Writer, modelSet ModelSummarySet) error { tw := output.TabWriter(writer) w := output.Wrapper{tw} c.tabularColumns(tw, w) for _, model := range modelSet.Models { cloudRegion := strings.Trim(model.Cloud+"/"+model.CloudRegion, "/") owner := names.NewUserTag(model.Owner) name := model.Name if c.runVars.currentUser == owner { // No need to display fully qualified model name to its owner. name = model.ShortName } if model.Name == modelSet.CurrentModelQualified { name += "*" w.PrintColor(output.CurrentHighlight, name) } else { w.Print(name) } if c.listUUID { w.Print(model.UUID) } status := "-" if model.Status != nil && model.Status.Current.String() != "" { status = model.Status.Current.String() } w.Print(cloudRegion, model.ProviderType, status) if c.runVars.hasMachinesCount { if v, ok := model.Counts[string(params.Machines)]; ok { w.Print(v) } else { w.Print(0) } } if c.runVars.hasCoresCount { if v, ok := model.Counts[string(params.Cores)]; ok { w.Print(v) } else { w.Print("-") } } if c.runVars.hasUnitsCount { if v, ok := model.Counts[string(params.Units)]; ok { w.Print(v) } else { w.Print("-") } } access := model.UserAccess if access == "" { access = "-" } w.Println(access, model.UserLastConnection) } tw.Flush() return nil }
[ "func", "(", "c", "*", "modelsCommand", ")", "tabularSummaries", "(", "writer", "io", ".", "Writer", ",", "modelSet", "ModelSummarySet", ")", "error", "{", "tw", ":=", "output", ".", "TabWriter", "(", "writer", ")", "\n", "w", ":=", "output", ".", "Wrapp...
// tabularSummaries takes model summaries set to adhere to the cmd.Formatter interface
[ "tabularSummaries", "takes", "model", "summaries", "set", "to", "adhere", "to", "the", "cmd", ".", "Formatter", "interface" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/controller/listmodels.go#L404-L460
train
juju/juju
api/client.go
Status
func (c *Client) Status(patterns []string) (*params.FullStatus, error) { var result params.FullStatus p := params.StatusParams{Patterns: patterns} if err := c.facade.FacadeCall("FullStatus", p, &result); err != nil { return nil, err } // Older servers don't fill out model type, but // we know a missing type is an "iaas" model. if result.Model.Type == "" { result.Model.Type = model.IAAS.String() } return &result, nil }
go
func (c *Client) Status(patterns []string) (*params.FullStatus, error) { var result params.FullStatus p := params.StatusParams{Patterns: patterns} if err := c.facade.FacadeCall("FullStatus", p, &result); err != nil { return nil, err } // Older servers don't fill out model type, but // we know a missing type is an "iaas" model. if result.Model.Type == "" { result.Model.Type = model.IAAS.String() } return &result, nil }
[ "func", "(", "c", "*", "Client", ")", "Status", "(", "patterns", "[", "]", "string", ")", "(", "*", "params", ".", "FullStatus", ",", "error", ")", "{", "var", "result", "params", ".", "FullStatus", "\n", "p", ":=", "params", ".", "StatusParams", "{"...
// Status returns the status of the juju model.
[ "Status", "returns", "the", "status", "of", "the", "juju", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L51-L63
train
juju/juju
api/client.go
Resolved
func (c *Client) Resolved(unit string, retry bool) error { p := params.Resolved{ UnitName: unit, Retry: retry, } return c.facade.FacadeCall("Resolved", p, nil) }
go
func (c *Client) Resolved(unit string, retry bool) error { p := params.Resolved{ UnitName: unit, Retry: retry, } return c.facade.FacadeCall("Resolved", p, nil) }
[ "func", "(", "c", "*", "Client", ")", "Resolved", "(", "unit", "string", ",", "retry", "bool", ")", "error", "{", "p", ":=", "params", ".", "Resolved", "{", "UnitName", ":", "unit", ",", "Retry", ":", "retry", ",", "}", "\n", "return", "c", ".", ...
// Resolved clears errors on a unit.
[ "Resolved", "clears", "errors", "on", "a", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L116-L122
train
juju/juju
api/client.go
RetryProvisioning
func (c *Client) RetryProvisioning(machines ...names.MachineTag) ([]params.ErrorResult, error) { p := params.Entities{} p.Entities = make([]params.Entity, len(machines)) for i, machine := range machines { p.Entities[i] = params.Entity{Tag: machine.String()} } var results params.ErrorResults err := c.facade.FacadeCall("RetryProvisioning", p, &results) return results.Results, err }
go
func (c *Client) RetryProvisioning(machines ...names.MachineTag) ([]params.ErrorResult, error) { p := params.Entities{} p.Entities = make([]params.Entity, len(machines)) for i, machine := range machines { p.Entities[i] = params.Entity{Tag: machine.String()} } var results params.ErrorResults err := c.facade.FacadeCall("RetryProvisioning", p, &results) return results.Results, err }
[ "func", "(", "c", "*", "Client", ")", "RetryProvisioning", "(", "machines", "...", "names", ".", "MachineTag", ")", "(", "[", "]", "params", ".", "ErrorResult", ",", "error", ")", "{", "p", ":=", "params", ".", "Entities", "{", "}", "\n", "p", ".", ...
// RetryProvisioning updates the provisioning status of a machine allowing the // provisioner to retry.
[ "RetryProvisioning", "updates", "the", "provisioning", "status", "of", "a", "machine", "allowing", "the", "provisioner", "to", "retry", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L126-L135
train
juju/juju
api/client.go
PublicAddress
func (c *Client) PublicAddress(target string) (string, error) { var results params.PublicAddressResults p := params.PublicAddress{Target: target} err := c.facade.FacadeCall("PublicAddress", p, &results) return results.PublicAddress, err }
go
func (c *Client) PublicAddress(target string) (string, error) { var results params.PublicAddressResults p := params.PublicAddress{Target: target} err := c.facade.FacadeCall("PublicAddress", p, &results) return results.PublicAddress, err }
[ "func", "(", "c", "*", "Client", ")", "PublicAddress", "(", "target", "string", ")", "(", "string", ",", "error", ")", "{", "var", "results", "params", ".", "PublicAddressResults", "\n", "p", ":=", "params", ".", "PublicAddress", "{", "Target", ":", "tar...
// PublicAddress returns the public address of the specified // machine or unit. For a machine, target is an id not a tag.
[ "PublicAddress", "returns", "the", "public", "address", "of", "the", "specified", "machine", "or", "unit", ".", "For", "a", "machine", "target", "is", "an", "id", "not", "a", "tag", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L139-L144
train
juju/juju
api/client.go
PrivateAddress
func (c *Client) PrivateAddress(target string) (string, error) { var results params.PrivateAddressResults p := params.PrivateAddress{Target: target} err := c.facade.FacadeCall("PrivateAddress", p, &results) return results.PrivateAddress, err }
go
func (c *Client) PrivateAddress(target string) (string, error) { var results params.PrivateAddressResults p := params.PrivateAddress{Target: target} err := c.facade.FacadeCall("PrivateAddress", p, &results) return results.PrivateAddress, err }
[ "func", "(", "c", "*", "Client", ")", "PrivateAddress", "(", "target", "string", ")", "(", "string", ",", "error", ")", "{", "var", "results", "params", ".", "PrivateAddressResults", "\n", "p", ":=", "params", ".", "PrivateAddress", "{", "Target", ":", "...
// PrivateAddress returns the private address of the specified // machine or unit.
[ "PrivateAddress", "returns", "the", "private", "address", "of", "the", "specified", "machine", "or", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L148-L153
train
juju/juju
api/client.go
SetModelConstraints
func (c *Client) SetModelConstraints(constraints constraints.Value) error { params := params.SetConstraints{ Constraints: constraints, } return c.facade.FacadeCall("SetModelConstraints", params, nil) }
go
func (c *Client) SetModelConstraints(constraints constraints.Value) error { params := params.SetConstraints{ Constraints: constraints, } return c.facade.FacadeCall("SetModelConstraints", params, nil) }
[ "func", "(", "c", "*", "Client", ")", "SetModelConstraints", "(", "constraints", "constraints", ".", "Value", ")", "error", "{", "params", ":=", "params", ".", "SetConstraints", "{", "Constraints", ":", "constraints", ",", "}", "\n", "return", "c", ".", "f...
// SetModelConstraints specifies the constraints for the model.
[ "SetModelConstraints", "specifies", "the", "constraints", "for", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L224-L229
train
juju/juju
api/client.go
ModelUUID
func (c *Client) ModelUUID() (string, bool) { tag, ok := c.st.ModelTag() if !ok { return "", false } return tag.Id(), true }
go
func (c *Client) ModelUUID() (string, bool) { tag, ok := c.st.ModelTag() if !ok { return "", false } return tag.Id(), true }
[ "func", "(", "c", "*", "Client", ")", "ModelUUID", "(", ")", "(", "string", ",", "bool", ")", "{", "tag", ",", "ok", ":=", "c", ".", "st", ".", "ModelTag", "(", ")", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "false", "\n", "}", ...
// ModelUUID returns the model UUID from the client connection // and reports whether it is valued.
[ "ModelUUID", "returns", "the", "model", "UUID", "from", "the", "client", "connection", "and", "reports", "whether", "it", "is", "valued", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L233-L239
train
juju/juju
api/client.go
WatchAll
func (c *Client) WatchAll() (*AllWatcher, error) { var info params.AllWatcherId if err := c.facade.FacadeCall("WatchAll", nil, &info); err != nil { return nil, err } return NewAllWatcher(c.st, &info.AllWatcherId), nil }
go
func (c *Client) WatchAll() (*AllWatcher, error) { var info params.AllWatcherId if err := c.facade.FacadeCall("WatchAll", nil, &info); err != nil { return nil, err } return NewAllWatcher(c.st, &info.AllWatcherId), nil }
[ "func", "(", "c", "*", "Client", ")", "WatchAll", "(", ")", "(", "*", "AllWatcher", ",", "error", ")", "{", "var", "info", "params", ".", "AllWatcherId", "\n", "if", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "nil", ...
// WatchAll returns an AllWatcher, from which you can request the Next // collection of Deltas.
[ "WatchAll", "returns", "an", "AllWatcher", "from", "which", "you", "can", "request", "the", "Next", "collection", "of", "Deltas", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L261-L267
train
juju/juju
api/client.go
SetModelAgentVersion
func (c *Client) SetModelAgentVersion(version version.Number, ignoreAgentVersions bool) error { args := params.SetModelAgentVersion{Version: version, IgnoreAgentVersions: ignoreAgentVersions} return c.facade.FacadeCall("SetModelAgentVersion", args, nil) }
go
func (c *Client) SetModelAgentVersion(version version.Number, ignoreAgentVersions bool) error { args := params.SetModelAgentVersion{Version: version, IgnoreAgentVersions: ignoreAgentVersions} return c.facade.FacadeCall("SetModelAgentVersion", args, nil) }
[ "func", "(", "c", "*", "Client", ")", "SetModelAgentVersion", "(", "version", "version", ".", "Number", ",", "ignoreAgentVersions", "bool", ")", "error", "{", "args", ":=", "params", ".", "SetModelAgentVersion", "{", "Version", ":", "version", ",", "IgnoreAgen...
// SetModelAgentVersion sets the model agent-version setting // to the given value.
[ "SetModelAgentVersion", "sets", "the", "model", "agent", "-", "version", "setting", "to", "the", "given", "value", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L279-L282
train
juju/juju
api/client.go
FindTools
func (c *Client) FindTools(majorVersion, minorVersion int, series, arch, agentStream string) (result params.FindToolsResult, err error) { if c.facade.BestAPIVersion() == 1 && agentStream != "" { return params.FindToolsResult{}, errors.New( "passing agent-stream not supported by the controller") } args := params.FindToolsParams{ MajorVersion: majorVersion, MinorVersion: minorVersion, Arch: arch, Series: series, AgentStream: agentStream, } err = c.facade.FacadeCall("FindTools", args, &result) return result, err }
go
func (c *Client) FindTools(majorVersion, minorVersion int, series, arch, agentStream string) (result params.FindToolsResult, err error) { if c.facade.BestAPIVersion() == 1 && agentStream != "" { return params.FindToolsResult{}, errors.New( "passing agent-stream not supported by the controller") } args := params.FindToolsParams{ MajorVersion: majorVersion, MinorVersion: minorVersion, Arch: arch, Series: series, AgentStream: agentStream, } err = c.facade.FacadeCall("FindTools", args, &result) return result, err }
[ "func", "(", "c", "*", "Client", ")", "FindTools", "(", "majorVersion", ",", "minorVersion", "int", ",", "series", ",", "arch", ",", "agentStream", "string", ")", "(", "result", "params", ".", "FindToolsResult", ",", "err", "error", ")", "{", "if", "c", ...
// FindTools returns a List containing all tools matching the specified parameters.
[ "FindTools", "returns", "a", "List", "containing", "all", "tools", "matching", "the", "specified", "parameters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L291-L305
train
juju/juju
api/client.go
UploadCharm
func (c *Client) UploadCharm(curl *charm.URL, content io.ReadSeeker) (*charm.URL, error) { args := url.Values{} args.Add("series", curl.Series) args.Add("schema", curl.Schema) args.Add("revision", strconv.Itoa(curl.Revision)) apiURI := url.URL{Path: "/charms", RawQuery: args.Encode()} contentType := "application/zip" var resp params.CharmsResponse if err := c.httpPost(content, apiURI.String(), contentType, &resp); err != nil { return nil, errors.Trace(err) } curl, err := charm.ParseURL(resp.CharmURL) if err != nil { return nil, errors.Annotatef(err, "bad charm URL in response") } return curl, nil }
go
func (c *Client) UploadCharm(curl *charm.URL, content io.ReadSeeker) (*charm.URL, error) { args := url.Values{} args.Add("series", curl.Series) args.Add("schema", curl.Schema) args.Add("revision", strconv.Itoa(curl.Revision)) apiURI := url.URL{Path: "/charms", RawQuery: args.Encode()} contentType := "application/zip" var resp params.CharmsResponse if err := c.httpPost(content, apiURI.String(), contentType, &resp); err != nil { return nil, errors.Trace(err) } curl, err := charm.ParseURL(resp.CharmURL) if err != nil { return nil, errors.Annotatef(err, "bad charm URL in response") } return curl, nil }
[ "func", "(", "c", "*", "Client", ")", "UploadCharm", "(", "curl", "*", "charm", ".", "URL", ",", "content", "io", ".", "ReadSeeker", ")", "(", "*", "charm", ".", "URL", ",", "error", ")", "{", "args", ":=", "url", ".", "Values", "{", "}", "\n", ...
// UploadCharm sends the content to the API server using an HTTP post.
[ "UploadCharm", "sends", "the", "content", "to", "the", "API", "server", "using", "an", "HTTP", "post", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L396-L414
train
juju/juju
api/client.go
OpenURI
func (c *Client) OpenURI(uri string, query url.Values) (io.ReadCloser, error) { return openURI(c.st, uri, query) }
go
func (c *Client) OpenURI(uri string, query url.Values) (io.ReadCloser, error) { return openURI(c.st, uri, query) }
[ "func", "(", "c", "*", "Client", ")", "OpenURI", "(", "uri", "string", ",", "query", "url", ".", "Values", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "return", "openURI", "(", "c", ".", "st", ",", "uri", ",", "query", ")", "\n", ...
// OpenURI performs a GET on a Juju HTTP endpoint returning the
[ "OpenURI", "performs", "a", "GET", "on", "a", "Juju", "HTTP", "endpoint", "returning", "the" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L531-L533
train
juju/juju
api/client.go
NewCharmDownloader
func NewCharmDownloader(apiCaller base.APICaller) *downloader.Downloader { dlr := &downloader.Downloader{ OpenBlob: func(url *url.URL) (io.ReadCloser, error) { curl, err := charm.ParseURL(url.String()) if err != nil { return nil, errors.Annotate(err, "did not receive a valid charm URL") } reader, err := OpenCharm(apiCaller, curl) if err != nil { return nil, errors.Trace(err) } return reader, nil }, } return dlr }
go
func NewCharmDownloader(apiCaller base.APICaller) *downloader.Downloader { dlr := &downloader.Downloader{ OpenBlob: func(url *url.URL) (io.ReadCloser, error) { curl, err := charm.ParseURL(url.String()) if err != nil { return nil, errors.Annotate(err, "did not receive a valid charm URL") } reader, err := OpenCharm(apiCaller, curl) if err != nil { return nil, errors.Trace(err) } return reader, nil }, } return dlr }
[ "func", "NewCharmDownloader", "(", "apiCaller", "base", ".", "APICaller", ")", "*", "downloader", ".", "Downloader", "{", "dlr", ":=", "&", "downloader", ".", "Downloader", "{", "OpenBlob", ":", "func", "(", "url", "*", "url", ".", "URL", ")", "(", "io",...
// NewCharmDownloader returns a new charm downloader that wraps the // provided API caller.
[ "NewCharmDownloader", "returns", "a", "new", "charm", "downloader", "that", "wraps", "the", "provided", "API", "caller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L550-L565
train
juju/juju
api/client.go
APIHostPorts
func (c *Client) APIHostPorts() ([][]network.HostPort, error) { var result params.APIHostPortsResult if err := c.facade.FacadeCall("APIHostPorts", nil, &result); err != nil { return nil, err } return result.NetworkHostsPorts(), nil }
go
func (c *Client) APIHostPorts() ([][]network.HostPort, error) { var result params.APIHostPortsResult if err := c.facade.FacadeCall("APIHostPorts", nil, &result); err != nil { return nil, err } return result.NetworkHostsPorts(), nil }
[ "func", "(", "c", "*", "Client", ")", "APIHostPorts", "(", ")", "(", "[", "]", "[", "]", "network", ".", "HostPort", ",", "error", ")", "{", "var", "result", "params", ".", "APIHostPortsResult", "\n", "if", "err", ":=", "c", ".", "facade", ".", "Fa...
// APIHostPorts returns a slice of network.HostPort for each API server.
[ "APIHostPorts", "returns", "a", "slice", "of", "network", ".", "HostPort", "for", "each", "API", "server", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L598-L604
train
juju/juju
api/client.go
AgentVersion
func (c *Client) AgentVersion() (version.Number, error) { var result params.AgentVersionResult if err := c.facade.FacadeCall("AgentVersion", nil, &result); err != nil { return version.Number{}, err } return result.Version, nil }
go
func (c *Client) AgentVersion() (version.Number, error) { var result params.AgentVersionResult if err := c.facade.FacadeCall("AgentVersion", nil, &result); err != nil { return version.Number{}, err } return result.Version, nil }
[ "func", "(", "c", "*", "Client", ")", "AgentVersion", "(", ")", "(", "version", ".", "Number", ",", "error", ")", "{", "var", "result", "params", ".", "AgentVersionResult", "\n", "if", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\...
// AgentVersion reports the version number of the api server.
[ "AgentVersion", "reports", "the", "version", "number", "of", "the", "api", "server", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L607-L613
train
juju/juju
api/client.go
websocketDialWithErrors
func websocketDialWithErrors(dialer WebsocketDialer, urlStr string, requestHeader http.Header) (base.Stream, error) { c, resp, err := dialer.Dial(urlStr, requestHeader) if err != nil { if err == websocket.ErrBadHandshake { // If ErrBadHandshake is returned, a non-nil response // is returned so the client can react to auth errors // (for example). // // The problem here is that there is a response, but the response // body is truncated to 1024 bytes for debugging information, not // for a true response. While this may work for small bodies, it // isn't guaranteed to work for all messages. defer resp.Body.Close() body, readErr := ioutil.ReadAll(resp.Body) if readErr != nil { return nil, err } if resp.Header.Get("Content-Type") == "application/json" { var result params.ErrorResult jsonErr := json.Unmarshal(body, &result) if jsonErr != nil { return nil, errors.Annotate(jsonErr, "reading error response") } return nil, result.Error } err = errors.Errorf( "%s (%s)", strings.TrimSpace(string(body)), http.StatusText(resp.StatusCode), ) } return nil, err } result := DeadlineStream{Conn: c, Timeout: websocketTimeout} return &result, nil }
go
func websocketDialWithErrors(dialer WebsocketDialer, urlStr string, requestHeader http.Header) (base.Stream, error) { c, resp, err := dialer.Dial(urlStr, requestHeader) if err != nil { if err == websocket.ErrBadHandshake { // If ErrBadHandshake is returned, a non-nil response // is returned so the client can react to auth errors // (for example). // // The problem here is that there is a response, but the response // body is truncated to 1024 bytes for debugging information, not // for a true response. While this may work for small bodies, it // isn't guaranteed to work for all messages. defer resp.Body.Close() body, readErr := ioutil.ReadAll(resp.Body) if readErr != nil { return nil, err } if resp.Header.Get("Content-Type") == "application/json" { var result params.ErrorResult jsonErr := json.Unmarshal(body, &result) if jsonErr != nil { return nil, errors.Annotate(jsonErr, "reading error response") } return nil, result.Error } err = errors.Errorf( "%s (%s)", strings.TrimSpace(string(body)), http.StatusText(resp.StatusCode), ) } return nil, err } result := DeadlineStream{Conn: c, Timeout: websocketTimeout} return &result, nil }
[ "func", "websocketDialWithErrors", "(", "dialer", "WebsocketDialer", ",", "urlStr", "string", ",", "requestHeader", "http", ".", "Header", ")", "(", "base", ".", "Stream", ",", "error", ")", "{", "c", ",", "resp", ",", "err", ":=", "dialer", ".", "Dial", ...
// websocketDialWithErrors dials the websocket and extracts any error // from the response if there's a handshake error setting up the // socket. Any other errors are returned normally.
[ "websocketDialWithErrors", "dials", "the", "websocket", "and", "extracts", "any", "error", "from", "the", "response", "if", "there", "s", "a", "handshake", "error", "setting", "up", "the", "socket", ".", "Any", "other", "errors", "are", "returned", "normally", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L628-L664
train
juju/juju
api/client.go
WriteJSON
func (s *DeadlineStream) WriteJSON(v interface{}) error { // This uses a real clock rather than trying to use a clock passed // in because the websocket will use a real clock to determine // whether the deadline has passed anyway. deadline := time.Now().Add(s.Timeout) if err := s.Conn.SetWriteDeadline(deadline); err != nil { return errors.Annotate(err, "setting write deadline") } return errors.Trace(s.Conn.WriteJSON(v)) }
go
func (s *DeadlineStream) WriteJSON(v interface{}) error { // This uses a real clock rather than trying to use a clock passed // in because the websocket will use a real clock to determine // whether the deadline has passed anyway. deadline := time.Now().Add(s.Timeout) if err := s.Conn.SetWriteDeadline(deadline); err != nil { return errors.Annotate(err, "setting write deadline") } return errors.Trace(s.Conn.WriteJSON(v)) }
[ "func", "(", "s", "*", "DeadlineStream", ")", "WriteJSON", "(", "v", "interface", "{", "}", ")", "error", "{", "// This uses a real clock rather than trying to use a clock passed", "// in because the websocket will use a real clock to determine", "// whether the deadline has passed...
// WriteJSON is part of base.Stream.
[ "WriteJSON", "is", "part", "of", "base", ".", "Stream", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L675-L684
train
juju/juju
api/client.go
WatchDebugLog
func (c *Client) WatchDebugLog(args common.DebugLogParams) (<-chan common.LogMessage, error) { return common.StreamDebugLog(c.st, args) }
go
func (c *Client) WatchDebugLog(args common.DebugLogParams) (<-chan common.LogMessage, error) { return common.StreamDebugLog(c.st, args) }
[ "func", "(", "c", "*", "Client", ")", "WatchDebugLog", "(", "args", "common", ".", "DebugLogParams", ")", "(", "<-", "chan", "common", ".", "LogMessage", ",", "error", ")", "{", "return", "common", ".", "StreamDebugLog", "(", "c", ".", "st", ",", "args...
// WatchDebugLog returns a channel of structured Log Messages. Only log entries // that match the filtering specified in the DebugLogParams are returned.
[ "WatchDebugLog", "returns", "a", "channel", "of", "structured", "Log", "Messages", ".", "Only", "log", "entries", "that", "match", "the", "filtering", "specified", "in", "the", "DebugLogParams", "are", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/client.go#L688-L690
train
juju/juju
docker/docker.go
ListOperatorImages
func ListOperatorImages(imagePath string) (tools.Versions, error) { tagsURL := fmt.Sprintf("%s/%s/tags", baseRegistryURL, imagePath) logger.Debugf("operater image tags URL: %v", tagsURL) data, err := HttpGet(tagsURL, 30*time.Second) if err != nil { return nil, errors.Trace(err) } type info struct { Tag string `json:"name"` } var tagInfo []info err = json.Unmarshal(data, &tagInfo) if err != nil { return nil, errors.Trace(err) } var images tools.Versions for _, t := range tagInfo { v, err := version.Parse(t.Tag) if err != nil { logger.Debugf("ignoring unexpected image tag %q", t.Tag) continue } images = append(images, imageInfo{v}) } return images, nil }
go
func ListOperatorImages(imagePath string) (tools.Versions, error) { tagsURL := fmt.Sprintf("%s/%s/tags", baseRegistryURL, imagePath) logger.Debugf("operater image tags URL: %v", tagsURL) data, err := HttpGet(tagsURL, 30*time.Second) if err != nil { return nil, errors.Trace(err) } type info struct { Tag string `json:"name"` } var tagInfo []info err = json.Unmarshal(data, &tagInfo) if err != nil { return nil, errors.Trace(err) } var images tools.Versions for _, t := range tagInfo { v, err := version.Parse(t.Tag) if err != nil { logger.Debugf("ignoring unexpected image tag %q", t.Tag) continue } images = append(images, imageInfo{v}) } return images, nil }
[ "func", "ListOperatorImages", "(", "imagePath", "string", ")", "(", "tools", ".", "Versions", ",", "error", ")", "{", "tagsURL", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "baseRegistryURL", ",", "imagePath", ")", "\n", "logger", ".", "Debugf", "...
// ListOperatorImages queries the standard docker registry and // returns the version tags for images matching imagePath. // The results are used when upgrading Juju to see what's available.
[ "ListOperatorImages", "queries", "the", "standard", "docker", "registry", "and", "returns", "the", "version", "tags", "for", "images", "matching", "imagePath", ".", "The", "results", "are", "used", "when", "upgrading", "Juju", "to", "see", "what", "s", "availabl...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/docker/docker.go#L38-L65
train
juju/juju
apiserver/common/unitstatus.go
UnitStatus
func (c *ModelPresenceContext) UnitStatus(unit UnitStatusGetter) (agent StatusAndErr, workload StatusAndErr) { agent.Status, agent.Err = unit.AgentStatus() workload.Status, workload.Err = unit.Status() if !canBeLost(agent.Status, workload.Status) { // The unit is allocating or installing - there's no point in // enquiring about the agent liveness. return } agentAlive, err := c.unitPresence(unit) if err != nil { return } if unit.Life() != state.Dead && !agentAlive { // If the unit is in error, it would be bad to throw away // the error information as when the agent reconnects, that // error information would then be lost. if workload.Status.Status != status.Error { workload.Status.Status = status.Unknown workload.Status.Message = fmt.Sprintf("agent lost, see 'juju show-status-log %s'", unit.Name()) } agent.Status.Status = status.Lost agent.Status.Message = "agent is not communicating with the server" } return }
go
func (c *ModelPresenceContext) UnitStatus(unit UnitStatusGetter) (agent StatusAndErr, workload StatusAndErr) { agent.Status, agent.Err = unit.AgentStatus() workload.Status, workload.Err = unit.Status() if !canBeLost(agent.Status, workload.Status) { // The unit is allocating or installing - there's no point in // enquiring about the agent liveness. return } agentAlive, err := c.unitPresence(unit) if err != nil { return } if unit.Life() != state.Dead && !agentAlive { // If the unit is in error, it would be bad to throw away // the error information as when the agent reconnects, that // error information would then be lost. if workload.Status.Status != status.Error { workload.Status.Status = status.Unknown workload.Status.Message = fmt.Sprintf("agent lost, see 'juju show-status-log %s'", unit.Name()) } agent.Status.Status = status.Lost agent.Status.Message = "agent is not communicating with the server" } return }
[ "func", "(", "c", "*", "ModelPresenceContext", ")", "UnitStatus", "(", "unit", "UnitStatusGetter", ")", "(", "agent", "StatusAndErr", ",", "workload", "StatusAndErr", ")", "{", "agent", ".", "Status", ",", "agent", ".", "Err", "=", "unit", ".", "AgentStatus"...
// UnitStatus returns the unit agent and workload status for a given // unit, with special handling for agent presence.
[ "UnitStatus", "returns", "the", "unit", "agent", "and", "workload", "status", "for", "a", "given", "unit", "with", "special", "handling", "for", "agent", "presence", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/unitstatus.go#L36-L62
train
juju/juju
api/upgrader/upgrader.go
SetVersion
func (st *State) SetVersion(tag string, v version.Binary) error { var results params.ErrorResults args := params.EntitiesVersion{ AgentTools: []params.EntityVersion{{ Tag: tag, Tools: &params.Version{v}, }}, } err := st.facade.FacadeCall("SetTools", args, &results) if err != nil { // TODO: Not directly tested return err } return results.OneError() }
go
func (st *State) SetVersion(tag string, v version.Binary) error { var results params.ErrorResults args := params.EntitiesVersion{ AgentTools: []params.EntityVersion{{ Tag: tag, Tools: &params.Version{v}, }}, } err := st.facade.FacadeCall("SetTools", args, &results) if err != nil { // TODO: Not directly tested return err } return results.OneError() }
[ "func", "(", "st", "*", "State", ")", "SetVersion", "(", "tag", "string", ",", "v", "version", ".", "Binary", ")", "error", "{", "var", "results", "params", ".", "ErrorResults", "\n", "args", ":=", "params", ".", "EntitiesVersion", "{", "AgentTools", ":"...
// SetVersion sets the tools version associated with the entity with // the given tag, which must be the tag of the entity that the // upgrader is running on behalf of.
[ "SetVersion", "sets", "the", "tools", "version", "associated", "with", "the", "entity", "with", "the", "given", "tag", "which", "must", "be", "the", "tag", "of", "the", "entity", "that", "the", "upgrader", "is", "running", "on", "behalf", "of", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/upgrader/upgrader.go#L32-L46
train
juju/juju
api/upgrader/upgrader.go
Tools
func (st *State) Tools(tag string) (tools.List, error) { var results params.ToolsResults args := params.Entities{ Entities: []params.Entity{{Tag: tag}}, } err := st.facade.FacadeCall("Tools", args, &results) if err != nil { // TODO: Not directly tested return nil, err } if len(results.Results) != 1 { // TODO: Not directly tested return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if err := result.Error; err != nil { return nil, err } return result.ToolsList, nil }
go
func (st *State) Tools(tag string) (tools.List, error) { var results params.ToolsResults args := params.Entities{ Entities: []params.Entity{{Tag: tag}}, } err := st.facade.FacadeCall("Tools", args, &results) if err != nil { // TODO: Not directly tested return nil, err } if len(results.Results) != 1 { // TODO: Not directly tested return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if err := result.Error; err != nil { return nil, err } return result.ToolsList, nil }
[ "func", "(", "st", "*", "State", ")", "Tools", "(", "tag", "string", ")", "(", "tools", ".", "List", ",", "error", ")", "{", "var", "results", "params", ".", "ToolsResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", ...
// Tools returns the agent tools that should run on the given entity, // along with a flag whether to disable SSL hostname verification.
[ "Tools", "returns", "the", "agent", "tools", "that", "should", "run", "on", "the", "given", "entity", "along", "with", "a", "flag", "whether", "to", "disable", "SSL", "hostname", "verification", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/upgrader/upgrader.go#L75-L94
train
juju/juju
state/relation.go
Tag
func (r *Relation) Tag() names.Tag { return names.NewRelationTag(r.doc.Key) }
go
func (r *Relation) Tag() names.Tag { return names.NewRelationTag(r.doc.Key) }
[ "func", "(", "r", "*", "Relation", ")", "Tag", "(", ")", "names", ".", "Tag", "{", "return", "names", ".", "NewRelationTag", "(", "r", ".", "doc", ".", "Key", ")", "\n", "}" ]
// Tag returns a name identifying the relation.
[ "Tag", "returns", "a", "name", "identifying", "the", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L71-L73
train
juju/juju
state/relation.go
Status
func (r *Relation) Status() (status.StatusInfo, error) { rStatus, err := getStatus(r.st.db(), r.globalScope(), "relation") if err != nil { return rStatus, err } return rStatus, nil }
go
func (r *Relation) Status() (status.StatusInfo, error) { rStatus, err := getStatus(r.st.db(), r.globalScope(), "relation") if err != nil { return rStatus, err } return rStatus, nil }
[ "func", "(", "r", "*", "Relation", ")", "Status", "(", ")", "(", "status", ".", "StatusInfo", ",", "error", ")", "{", "rStatus", ",", "err", ":=", "getStatus", "(", "r", ".", "st", ".", "db", "(", ")", ",", "r", ".", "globalScope", "(", ")", ",...
// Status returns the relation's current status data.
[ "Status", "returns", "the", "relation", "s", "current", "status", "data", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L116-L122
train
juju/juju
state/relation.go
SetStatus
func (r *Relation) SetStatus(statusInfo status.StatusInfo) error { currentStatus, err := r.Status() if err != nil { return errors.Trace(err) } if currentStatus.Status != statusInfo.Status { validTransition := true switch statusInfo.Status { case status.Broken: case status.Suspending: validTransition = currentStatus.Status != status.Broken && currentStatus.Status != status.Suspended case status.Joining: validTransition = currentStatus.Status != status.Broken && currentStatus.Status != status.Joined case status.Joined, status.Suspended: validTransition = currentStatus.Status != status.Broken case status.Error: if statusInfo.Message == "" { return errors.Errorf("cannot set status %q without info", statusInfo.Status) } default: return errors.NewNotValid(nil, fmt.Sprintf("cannot set invalid status %q", statusInfo.Status)) } if !validTransition { return errors.NewNotValid(nil, fmt.Sprintf( "cannot set status %q when relation has status %q", statusInfo.Status, currentStatus.Status)) } } return setStatus(r.st.db(), setStatusParams{ badge: "relation", globalKey: r.globalScope(), status: statusInfo.Status, message: statusInfo.Message, rawData: statusInfo.Data, updated: timeOrNow(statusInfo.Since, r.st.clock()), }) }
go
func (r *Relation) SetStatus(statusInfo status.StatusInfo) error { currentStatus, err := r.Status() if err != nil { return errors.Trace(err) } if currentStatus.Status != statusInfo.Status { validTransition := true switch statusInfo.Status { case status.Broken: case status.Suspending: validTransition = currentStatus.Status != status.Broken && currentStatus.Status != status.Suspended case status.Joining: validTransition = currentStatus.Status != status.Broken && currentStatus.Status != status.Joined case status.Joined, status.Suspended: validTransition = currentStatus.Status != status.Broken case status.Error: if statusInfo.Message == "" { return errors.Errorf("cannot set status %q without info", statusInfo.Status) } default: return errors.NewNotValid(nil, fmt.Sprintf("cannot set invalid status %q", statusInfo.Status)) } if !validTransition { return errors.NewNotValid(nil, fmt.Sprintf( "cannot set status %q when relation has status %q", statusInfo.Status, currentStatus.Status)) } } return setStatus(r.st.db(), setStatusParams{ badge: "relation", globalKey: r.globalScope(), status: statusInfo.Status, message: statusInfo.Message, rawData: statusInfo.Data, updated: timeOrNow(statusInfo.Since, r.st.clock()), }) }
[ "func", "(", "r", "*", "Relation", ")", "SetStatus", "(", "statusInfo", "status", ".", "StatusInfo", ")", "error", "{", "currentStatus", ",", "err", ":=", "r", ".", "Status", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Tr...
// SetStatus sets the status of the relation.
[ "SetStatus", "sets", "the", "status", "of", "the", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L125-L161
train
juju/juju
state/relation.go
DestroyOperation
func (r *Relation) DestroyOperation(force bool) *DestroyRelationOperation { return &DestroyRelationOperation{ r: &Relation{r.st, r.doc}, ForcedOperation: ForcedOperation{Force: force}, } }
go
func (r *Relation) DestroyOperation(force bool) *DestroyRelationOperation { return &DestroyRelationOperation{ r: &Relation{r.st, r.doc}, ForcedOperation: ForcedOperation{Force: force}, } }
[ "func", "(", "r", "*", "Relation", ")", "DestroyOperation", "(", "force", "bool", ")", "*", "DestroyRelationOperation", "{", "return", "&", "DestroyRelationOperation", "{", "r", ":", "&", "Relation", "{", "r", ".", "st", ",", "r", ".", "doc", "}", ",", ...
// DestroyOperation returns a model operation that will allow relation to leave scope.
[ "DestroyOperation", "returns", "a", "model", "operation", "that", "will", "allow", "relation", "to", "leave", "scope", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L254-L259
train
juju/juju
state/relation.go
DestroyWithForce
func (r *Relation) DestroyWithForce(force bool, maxWait time.Duration) ([]error, error) { op := r.DestroyOperation(force) op.MaxWait = maxWait err := r.st.ApplyOperation(op) return op.Errors, err }
go
func (r *Relation) DestroyWithForce(force bool, maxWait time.Duration) ([]error, error) { op := r.DestroyOperation(force) op.MaxWait = maxWait err := r.st.ApplyOperation(op) return op.Errors, err }
[ "func", "(", "r", "*", "Relation", ")", "DestroyWithForce", "(", "force", "bool", ",", "maxWait", "time", ".", "Duration", ")", "(", "[", "]", "error", ",", "error", ")", "{", "op", ":=", "r", ".", "DestroyOperation", "(", "force", ")", "\n", "op", ...
// DestroyWithForce may force the destruction of the relation. // In addition, this function also returns all non-fatal operational errors // encountered.
[ "DestroyWithForce", "may", "force", "the", "destruction", "of", "the", "relation", ".", "In", "addition", "this", "function", "also", "returns", "all", "non", "-", "fatal", "operational", "errors", "encountered", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L312-L317
train
juju/juju
state/relation.go
Destroy
func (r *Relation) Destroy() error { _, err := r.DestroyWithForce(false, time.Duration(0)) return err }
go
func (r *Relation) Destroy() error { _, err := r.DestroyWithForce(false, time.Duration(0)) return err }
[ "func", "(", "r", "*", "Relation", ")", "Destroy", "(", ")", "error", "{", "_", ",", "err", ":=", "r", ".", "DestroyWithForce", "(", "false", ",", "time", ".", "Duration", "(", "0", ")", ")", "\n", "return", "err", "\n", "}" ]
// Destroy ensures that the relation will be removed at some point; if no units // are currently in scope, it will be removed immediately.
[ "Destroy", "ensures", "that", "the", "relation", "will", "be", "removed", "at", "some", "point", ";", "if", "no", "units", "are", "currently", "in", "scope", "it", "will", "be", "removed", "immediately", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L321-L324
train
juju/juju
state/relation.go
internalDestroy
func (op *DestroyRelationOperation) internalDestroy() (ops []txn.Op, err error) { if len(op.r.doc.Endpoints) == 1 && op.r.doc.Endpoints[0].Role == charm.RolePeer { return nil, errors.Errorf("is a peer relation") } defer func() { if err == nil { // This is a white lie; the document might actually be removed. op.r.doc.Life = Dying } }() rel := &Relation{op.r.st, op.r.doc} remoteApp, isCrossModel, err := op.r.RemoteApplication() if err != nil { if !op.Force { return nil, errors.Trace(err) } op.AddError(err) } else { // If the status of the consumed app is terminated, we will never // get an orderly exit of units from scope so force the issue. if isCrossModel { statusInfo, err := remoteApp.Status() if err != nil && !errors.IsNotFound(err) { if !op.Force { return nil, errors.Trace(err) } op.AddError(err) } if err == nil && statusInfo.Status == status.Terminated { logger.Debugf("forcing cleanup of units for %v", remoteApp.Name()) remoteUnits, err := rel.AllRemoteUnits(remoteApp.Name()) if err != nil { if !op.Force { return nil, errors.Trace(err) } op.AddError(err) } logger.Debugf("got %v relation units to clean", len(remoteUnits)) failRemoteUnits := false for _, ru := range remoteUnits { leaveScopeOps, err := ru.leaveScopeForcedOps(&op.ForcedOperation) if err != nil && err != jujutxn.ErrNoOperations { op.AddError(err) failRemoteUnits = true } ops = append(ops, leaveScopeOps...) } if !op.Force && failRemoteUnits { return nil, errors.Trace(op.LastError()) } } } } // In this context, aborted transactions indicate that the number of units // in scope have changed between 0 and not-0. The chances of 5 successive // attempts each hitting this change -- which is itself an unlikely one -- // are considered to be extremely small. // When 'force' is set, this call will return needed operations // and accumulate all operational errors encountered in the operation. // If the 'force' is not set, any error will be fatal and no operations will be returned. destroyOps, _, err := rel.destroyOps("", &op.ForcedOperation) if err == errAlreadyDying { return nil, jujutxn.ErrNoOperations } else if err != nil { if !op.Force { return nil, err } op.AddError(err) } return append(ops, destroyOps...), nil }
go
func (op *DestroyRelationOperation) internalDestroy() (ops []txn.Op, err error) { if len(op.r.doc.Endpoints) == 1 && op.r.doc.Endpoints[0].Role == charm.RolePeer { return nil, errors.Errorf("is a peer relation") } defer func() { if err == nil { // This is a white lie; the document might actually be removed. op.r.doc.Life = Dying } }() rel := &Relation{op.r.st, op.r.doc} remoteApp, isCrossModel, err := op.r.RemoteApplication() if err != nil { if !op.Force { return nil, errors.Trace(err) } op.AddError(err) } else { // If the status of the consumed app is terminated, we will never // get an orderly exit of units from scope so force the issue. if isCrossModel { statusInfo, err := remoteApp.Status() if err != nil && !errors.IsNotFound(err) { if !op.Force { return nil, errors.Trace(err) } op.AddError(err) } if err == nil && statusInfo.Status == status.Terminated { logger.Debugf("forcing cleanup of units for %v", remoteApp.Name()) remoteUnits, err := rel.AllRemoteUnits(remoteApp.Name()) if err != nil { if !op.Force { return nil, errors.Trace(err) } op.AddError(err) } logger.Debugf("got %v relation units to clean", len(remoteUnits)) failRemoteUnits := false for _, ru := range remoteUnits { leaveScopeOps, err := ru.leaveScopeForcedOps(&op.ForcedOperation) if err != nil && err != jujutxn.ErrNoOperations { op.AddError(err) failRemoteUnits = true } ops = append(ops, leaveScopeOps...) } if !op.Force && failRemoteUnits { return nil, errors.Trace(op.LastError()) } } } } // In this context, aborted transactions indicate that the number of units // in scope have changed between 0 and not-0. The chances of 5 successive // attempts each hitting this change -- which is itself an unlikely one -- // are considered to be extremely small. // When 'force' is set, this call will return needed operations // and accumulate all operational errors encountered in the operation. // If the 'force' is not set, any error will be fatal and no operations will be returned. destroyOps, _, err := rel.destroyOps("", &op.ForcedOperation) if err == errAlreadyDying { return nil, jujutxn.ErrNoOperations } else if err != nil { if !op.Force { return nil, err } op.AddError(err) } return append(ops, destroyOps...), nil }
[ "func", "(", "op", "*", "DestroyRelationOperation", ")", "internalDestroy", "(", ")", "(", "ops", "[", "]", "txn", ".", "Op", ",", "err", "error", ")", "{", "if", "len", "(", "op", ".", "r", ".", "doc", ".", "Endpoints", ")", "==", "1", "&&", "op...
// When 'force' is set, this call will construct and apply needed operations // as well as accumulate all operational errors encountered. // If the 'force' is not set, any error will be fatal and no operations will be applied.
[ "When", "force", "is", "set", "this", "call", "will", "construct", "and", "apply", "needed", "operations", "as", "well", "as", "accumulate", "all", "operational", "errors", "encountered", ".", "If", "the", "force", "is", "not", "set", "any", "error", "will",...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L329-L401
train
juju/juju
state/relation.go
destroyOps
func (r *Relation) destroyOps(ignoreApplication string, op *ForcedOperation) (ops []txn.Op, isRemove bool, err error) { if r.doc.Life != Alive { if !op.Force { return nil, false, errAlreadyDying } } if r.doc.UnitCount == 0 { // When 'force' is set, this call will return both needed operations // as well as all operational errors encountered. // If the 'force' is not set, any error will be fatal and no operations will be returned. removeOps, err := r.removeOps(ignoreApplication, "", op) if err != nil { if !op.Force { return nil, false, err } logger.Warningf("ignoring error (%v) while constructing relation %v destroy operations since force is used", err, r) } return removeOps, true, nil } return []txn.Op{{ C: relationsC, Id: r.doc.DocID, Assert: bson.D{{"life", Alive}, {"unitcount", bson.D{{"$gt", 0}}}}, Update: bson.D{{"$set", bson.D{{"life", Dying}}}}, }}, false, nil }
go
func (r *Relation) destroyOps(ignoreApplication string, op *ForcedOperation) (ops []txn.Op, isRemove bool, err error) { if r.doc.Life != Alive { if !op.Force { return nil, false, errAlreadyDying } } if r.doc.UnitCount == 0 { // When 'force' is set, this call will return both needed operations // as well as all operational errors encountered. // If the 'force' is not set, any error will be fatal and no operations will be returned. removeOps, err := r.removeOps(ignoreApplication, "", op) if err != nil { if !op.Force { return nil, false, err } logger.Warningf("ignoring error (%v) while constructing relation %v destroy operations since force is used", err, r) } return removeOps, true, nil } return []txn.Op{{ C: relationsC, Id: r.doc.DocID, Assert: bson.D{{"life", Alive}, {"unitcount", bson.D{{"$gt", 0}}}}, Update: bson.D{{"$set", bson.D{{"life", Dying}}}}, }}, false, nil }
[ "func", "(", "r", "*", "Relation", ")", "destroyOps", "(", "ignoreApplication", "string", ",", "op", "*", "ForcedOperation", ")", "(", "ops", "[", "]", "txn", ".", "Op", ",", "isRemove", "bool", ",", "err", "error", ")", "{", "if", "r", ".", "doc", ...
// destroyOps returns the operations necessary to destroy the relation, and // whether those operations will lead to the relation's removal. These // operations may include changes to the relation's applications; however, if // ignoreApplication is not empty, no operations modifying that application will // be generated. // When 'force' is set, this call will return both operations to remove this // relation as well as all operational errors encountered. // If the 'force' is not set, any error will be fatal and no operations will be returned.
[ "destroyOps", "returns", "the", "operations", "necessary", "to", "destroy", "the", "relation", "and", "whether", "those", "operations", "will", "lead", "to", "the", "relation", "s", "removal", ".", "These", "operations", "may", "include", "changes", "to", "the",...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L411-L436
train
juju/juju
state/relation.go
removeOps
func (r *Relation) removeOps(ignoreApplication string, departingUnitName string, op *ForcedOperation) ([]txn.Op, error) { relOp := txn.Op{ C: relationsC, Id: r.doc.DocID, Remove: true, } if departingUnitName != "" { relOp.Assert = bson.D{{"life", Dying}, {"unitcount", 1}} } else { relOp.Assert = bson.D{{"life", Alive}, {"unitcount", 0}} } ops := []txn.Op{relOp} for _, ep := range r.doc.Endpoints { if ep.ApplicationName == ignoreApplication { continue } app, err := applicationByName(r.st, ep.ApplicationName) if err != nil { op.AddError(err) } else { if app.IsRemote() { epOps, err := r.removeRemoteEndpointOps(ep, departingUnitName != "") if err != nil { op.AddError(err) } ops = append(ops, epOps...) } else { // When 'force' is set, this call will return both needed operations // as well as all operational errors encountered. // If the 'force' is not set, any error will be fatal and no operations will be returned. epOps, err := r.removeLocalEndpointOps(ep, departingUnitName, op) if err != nil { op.AddError(err) } ops = append(ops, epOps...) } } } ops = append(ops, removeStatusOp(r.st, r.globalScope())) ops = append(ops, removeRelationNetworksOps(r.st, r.doc.Key)...) re := r.st.RemoteEntities() tokenOps := re.removeRemoteEntityOps(r.Tag()) ops = append(ops, tokenOps...) offerOps := removeOfferConnectionsForRelationOps(r.Id()) ops = append(ops, offerOps...) // This cleanup does not need to be forced. cleanupOp := newCleanupOp(cleanupRelationSettings, fmt.Sprintf("r#%d#", r.Id())) return append(ops, cleanupOp), nil }
go
func (r *Relation) removeOps(ignoreApplication string, departingUnitName string, op *ForcedOperation) ([]txn.Op, error) { relOp := txn.Op{ C: relationsC, Id: r.doc.DocID, Remove: true, } if departingUnitName != "" { relOp.Assert = bson.D{{"life", Dying}, {"unitcount", 1}} } else { relOp.Assert = bson.D{{"life", Alive}, {"unitcount", 0}} } ops := []txn.Op{relOp} for _, ep := range r.doc.Endpoints { if ep.ApplicationName == ignoreApplication { continue } app, err := applicationByName(r.st, ep.ApplicationName) if err != nil { op.AddError(err) } else { if app.IsRemote() { epOps, err := r.removeRemoteEndpointOps(ep, departingUnitName != "") if err != nil { op.AddError(err) } ops = append(ops, epOps...) } else { // When 'force' is set, this call will return both needed operations // as well as all operational errors encountered. // If the 'force' is not set, any error will be fatal and no operations will be returned. epOps, err := r.removeLocalEndpointOps(ep, departingUnitName, op) if err != nil { op.AddError(err) } ops = append(ops, epOps...) } } } ops = append(ops, removeStatusOp(r.st, r.globalScope())) ops = append(ops, removeRelationNetworksOps(r.st, r.doc.Key)...) re := r.st.RemoteEntities() tokenOps := re.removeRemoteEntityOps(r.Tag()) ops = append(ops, tokenOps...) offerOps := removeOfferConnectionsForRelationOps(r.Id()) ops = append(ops, offerOps...) // This cleanup does not need to be forced. cleanupOp := newCleanupOp(cleanupRelationSettings, fmt.Sprintf("r#%d#", r.Id())) return append(ops, cleanupOp), nil }
[ "func", "(", "r", "*", "Relation", ")", "removeOps", "(", "ignoreApplication", "string", ",", "departingUnitName", "string", ",", "op", "*", "ForcedOperation", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "relOp", ":=", "txn", ".", "Op...
// removeOps returns the operations necessary to remove the relation. If // ignoreApplication is not empty, no operations affecting that application will be // included; if departingUnitName is non-empty, this implies that the // relation's applications may be Dying and otherwise unreferenced, and may thus // require removal themselves. // When 'force' is set, this call will return needed operations // and accumulate all operational errors encountered 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", "relation", ".", "If", "ignoreApplication", "is", "not", "empty", "no", "operations", "affecting", "that", "application", "will", "be", "included", ";", "if", "departingUnitName", "is...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L446-L494
train
juju/juju
state/relation.go
removeLocalEndpointOps
func (r *Relation) removeLocalEndpointOps(ep Endpoint, departingUnitName string, op *ForcedOperation) ([]txn.Op, error) { var asserts bson.D hasRelation := bson.D{{"relationcount", bson.D{{"$gt", 0}}}} departingUnitApplicationMatchesEndpoint := func() bool { s, err := names.UnitApplication(departingUnitName) return err == nil && s == ep.ApplicationName } var cleanupOps []txn.Op if departingUnitName == "" { // We're constructing a destroy operation, either of the relation // or one of its applications, and can therefore be assured that both // applications are Alive. asserts = append(hasRelation, isAliveDoc...) } else if departingUnitApplicationMatchesEndpoint() { // This application must have at least one unit -- the one that's // departing the relation -- so it cannot be ready for removal. cannotDieYet := bson.D{{"unitcount", bson.D{{"$gt", 0}}}} asserts = append(hasRelation, cannotDieYet...) } else { // This application may require immediate removal. // Check if the application is Dying, and if so, queue up a potential // cleanup in case this was the last reference. applications, closer := r.st.db().GetCollection(applicationsC) defer closer() asserts = append(hasRelation) var appDoc applicationDoc if err := applications.FindId(ep.ApplicationName).One(&appDoc); err == nil { if appDoc.Life != Alive { cleanupOps = append(cleanupOps, newCleanupOp( cleanupApplication, ep.ApplicationName, false, // destroyStorage op.Force, )) } } else if !op.Force { return nil, errors.Trace(err) } } return append([]txn.Op{{ C: applicationsC, Id: r.st.docID(ep.ApplicationName), Assert: asserts, Update: bson.D{{"$inc", bson.D{{"relationcount", -1}}}}, }}, cleanupOps...), nil }
go
func (r *Relation) removeLocalEndpointOps(ep Endpoint, departingUnitName string, op *ForcedOperation) ([]txn.Op, error) { var asserts bson.D hasRelation := bson.D{{"relationcount", bson.D{{"$gt", 0}}}} departingUnitApplicationMatchesEndpoint := func() bool { s, err := names.UnitApplication(departingUnitName) return err == nil && s == ep.ApplicationName } var cleanupOps []txn.Op if departingUnitName == "" { // We're constructing a destroy operation, either of the relation // or one of its applications, and can therefore be assured that both // applications are Alive. asserts = append(hasRelation, isAliveDoc...) } else if departingUnitApplicationMatchesEndpoint() { // This application must have at least one unit -- the one that's // departing the relation -- so it cannot be ready for removal. cannotDieYet := bson.D{{"unitcount", bson.D{{"$gt", 0}}}} asserts = append(hasRelation, cannotDieYet...) } else { // This application may require immediate removal. // Check if the application is Dying, and if so, queue up a potential // cleanup in case this was the last reference. applications, closer := r.st.db().GetCollection(applicationsC) defer closer() asserts = append(hasRelation) var appDoc applicationDoc if err := applications.FindId(ep.ApplicationName).One(&appDoc); err == nil { if appDoc.Life != Alive { cleanupOps = append(cleanupOps, newCleanupOp( cleanupApplication, ep.ApplicationName, false, // destroyStorage op.Force, )) } } else if !op.Force { return nil, errors.Trace(err) } } return append([]txn.Op{{ C: applicationsC, Id: r.st.docID(ep.ApplicationName), Assert: asserts, Update: bson.D{{"$inc", bson.D{{"relationcount", -1}}}}, }}, cleanupOps...), nil }
[ "func", "(", "r", "*", "Relation", ")", "removeLocalEndpointOps", "(", "ep", "Endpoint", ",", "departingUnitName", "string", ",", "op", "*", "ForcedOperation", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "var", "asserts", "bson", ".", ...
// When 'force' is set, this call will return both needed operations // as well as all operational errors encountered. // 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", "both", "needed", "operations", "as", "well", "as", "all", "operational", "errors", "encountered", ".", "If", "the", "force", "is", "not", "set", "any", "error", "will", "be", "fatal", "and", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L499-L545
train
juju/juju
state/relation.go
Endpoint
func (r *Relation) Endpoint(applicationname string) (Endpoint, error) { for _, ep := range r.doc.Endpoints { if ep.ApplicationName == applicationname { return ep, nil } } msg := fmt.Sprintf("application %q is not a member of %q", applicationname, r) return Endpoint{}, errors.NewNotFound(nil, msg) }
go
func (r *Relation) Endpoint(applicationname string) (Endpoint, error) { for _, ep := range r.doc.Endpoints { if ep.ApplicationName == applicationname { return ep, nil } } msg := fmt.Sprintf("application %q is not a member of %q", applicationname, r) return Endpoint{}, errors.NewNotFound(nil, msg) }
[ "func", "(", "r", "*", "Relation", ")", "Endpoint", "(", "applicationname", "string", ")", "(", "Endpoint", ",", "error", ")", "{", "for", "_", ",", "ep", ":=", "range", "r", ".", "doc", ".", "Endpoints", "{", "if", "ep", ".", "ApplicationName", "=="...
// Endpoint returns the endpoint of the relation for the named application. // If the application is not part of the relation, an error will be returned.
[ "Endpoint", "returns", "the", "endpoint", "of", "the", "relation", "for", "the", "named", "application", ".", "If", "the", "application", "is", "not", "part", "of", "the", "relation", "an", "error", "will", "be", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L597-L605
train
juju/juju
state/relation.go
RelatedEndpoints
func (r *Relation) RelatedEndpoints(applicationname string) ([]Endpoint, error) { local, err := r.Endpoint(applicationname) if err != nil { return nil, err } role := counterpartRole(local.Role) var eps []Endpoint for _, ep := range r.doc.Endpoints { if ep.Role == role { eps = append(eps, ep) } } if eps == nil { return nil, errors.Errorf("no endpoints of %q relate to application %q", r, applicationname) } return eps, nil }
go
func (r *Relation) RelatedEndpoints(applicationname string) ([]Endpoint, error) { local, err := r.Endpoint(applicationname) if err != nil { return nil, err } role := counterpartRole(local.Role) var eps []Endpoint for _, ep := range r.doc.Endpoints { if ep.Role == role { eps = append(eps, ep) } } if eps == nil { return nil, errors.Errorf("no endpoints of %q relate to application %q", r, applicationname) } return eps, nil }
[ "func", "(", "r", "*", "Relation", ")", "RelatedEndpoints", "(", "applicationname", "string", ")", "(", "[", "]", "Endpoint", ",", "error", ")", "{", "local", ",", "err", ":=", "r", ".", "Endpoint", "(", "applicationname", ")", "\n", "if", "err", "!=",...
// RelatedEndpoints returns the endpoints of the relation r with which // units of the named application will establish relations. If the service // is not part of the relation r, an error will be returned.
[ "RelatedEndpoints", "returns", "the", "endpoints", "of", "the", "relation", "r", "with", "which", "units", "of", "the", "named", "application", "will", "establish", "relations", ".", "If", "the", "service", "is", "not", "part", "of", "the", "relation", "r", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L615-L631
train
juju/juju
state/relation.go
RemoteUnit
func (r *Relation) RemoteUnit(unitName string) (*RelationUnit, error) { // Verify that the unit belongs to a remote application. appName, err := names.UnitApplication(unitName) if err != nil { return nil, errors.Trace(err) } if _, err := r.st.RemoteApplication(appName); err != nil { return nil, errors.Trace(err) } // Only non-subordinate applications may be offered for remote // relation, so all remote units are principals. const principal = "" const isPrincipal = true const isLocalUnit = false return r.unit(unitName, principal, isPrincipal, isLocalUnit) }
go
func (r *Relation) RemoteUnit(unitName string) (*RelationUnit, error) { // Verify that the unit belongs to a remote application. appName, err := names.UnitApplication(unitName) if err != nil { return nil, errors.Trace(err) } if _, err := r.st.RemoteApplication(appName); err != nil { return nil, errors.Trace(err) } // Only non-subordinate applications may be offered for remote // relation, so all remote units are principals. const principal = "" const isPrincipal = true const isLocalUnit = false return r.unit(unitName, principal, isPrincipal, isLocalUnit) }
[ "func", "(", "r", "*", "Relation", ")", "RemoteUnit", "(", "unitName", "string", ")", "(", "*", "RelationUnit", ",", "error", ")", "{", "// Verify that the unit belongs to a remote application.", "appName", ",", "err", ":=", "names", ".", "UnitApplication", "(", ...
// RemoteUnit returns a RelationUnit for the supplied unit // of a remote application.
[ "RemoteUnit", "returns", "a", "RelationUnit", "for", "the", "supplied", "unit", "of", "a", "remote", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L641-L656
train
juju/juju
state/relation.go
AllRemoteUnits
func (r *Relation) AllRemoteUnits(appName string) ([]*RelationUnit, error) { // Verify that the unit belongs to a remote application. if _, err := r.st.RemoteApplication(appName); err != nil { return nil, errors.Trace(err) } relationScopes, closer := r.st.db().GetCollection(relationScopesC) defer closer() ep, err := r.Endpoint(appName) if err != nil { return nil, err } scope := r.globalScope() parts := []string{"^" + scope, string(ep.Role), appName + "/"} ruRegex := strings.Join(parts, "#") var docs []relationScopeDoc if err := relationScopes.Find(bson.D{{"key", bson.D{{"$regex", ruRegex}}}}).All(&docs); err != nil { return nil, errors.Trace(err) } result := make([]*RelationUnit, len(docs)) for i, doc := range docs { result[i] = &RelationUnit{ st: r.st, relation: r, unitName: doc.unitName(), isPrincipal: true, isLocalUnit: false, endpoint: ep, scope: scope, } } return result, nil }
go
func (r *Relation) AllRemoteUnits(appName string) ([]*RelationUnit, error) { // Verify that the unit belongs to a remote application. if _, err := r.st.RemoteApplication(appName); err != nil { return nil, errors.Trace(err) } relationScopes, closer := r.st.db().GetCollection(relationScopesC) defer closer() ep, err := r.Endpoint(appName) if err != nil { return nil, err } scope := r.globalScope() parts := []string{"^" + scope, string(ep.Role), appName + "/"} ruRegex := strings.Join(parts, "#") var docs []relationScopeDoc if err := relationScopes.Find(bson.D{{"key", bson.D{{"$regex", ruRegex}}}}).All(&docs); err != nil { return nil, errors.Trace(err) } result := make([]*RelationUnit, len(docs)) for i, doc := range docs { result[i] = &RelationUnit{ st: r.st, relation: r, unitName: doc.unitName(), isPrincipal: true, isLocalUnit: false, endpoint: ep, scope: scope, } } return result, nil }
[ "func", "(", "r", "*", "Relation", ")", "AllRemoteUnits", "(", "appName", "string", ")", "(", "[", "]", "*", "RelationUnit", ",", "error", ")", "{", "// Verify that the unit belongs to a remote application.", "if", "_", ",", "err", ":=", "r", ".", "st", ".",...
// AllRemoteUnits returns all the RelationUnits for the remote // application units for a given application.
[ "AllRemoteUnits", "returns", "all", "the", "RelationUnits", "for", "the", "remote", "application", "units", "for", "a", "given", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L660-L694
train
juju/juju
state/relation.go
RemoteApplication
func (r *Relation) RemoteApplication() (*RemoteApplication, bool, error) { for _, ep := range r.Endpoints() { app, err := r.st.RemoteApplication(ep.ApplicationName) if err == nil { return app, true, nil } else if !errors.IsNotFound(err) { return nil, false, errors.Trace(err) } } return nil, false, nil }
go
func (r *Relation) RemoteApplication() (*RemoteApplication, bool, error) { for _, ep := range r.Endpoints() { app, err := r.st.RemoteApplication(ep.ApplicationName) if err == nil { return app, true, nil } else if !errors.IsNotFound(err) { return nil, false, errors.Trace(err) } } return nil, false, nil }
[ "func", "(", "r", "*", "Relation", ")", "RemoteApplication", "(", ")", "(", "*", "RemoteApplication", ",", "bool", ",", "error", ")", "{", "for", "_", ",", "ep", ":=", "range", "r", ".", "Endpoints", "(", ")", "{", "app", ",", "err", ":=", "r", "...
// RemoteApplication returns the remote application if // this relation is a cross-model relation, and a bool // indicating if it cross-model or not.
[ "RemoteApplication", "returns", "the", "remote", "application", "if", "this", "relation", "is", "a", "cross", "-", "model", "relation", "and", "a", "bool", "indicating", "if", "it", "cross", "-", "model", "or", "not", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/relation.go#L699-L709
train
juju/juju
cloudconfig/userdatacfg_unix.go
ConfigureCustomOverrides
func (w *unixConfigure) ConfigureCustomOverrides() error { for k, v := range w.icfg.CloudInitUserData { // preruncmd was handled in ConfigureBasic() // packages and postruncmd have been handled in ConfigureJuju() if isAllowedOverrideAttr(k) { w.conf.SetAttr(k, v) } } return nil }
go
func (w *unixConfigure) ConfigureCustomOverrides() error { for k, v := range w.icfg.CloudInitUserData { // preruncmd was handled in ConfigureBasic() // packages and postruncmd have been handled in ConfigureJuju() if isAllowedOverrideAttr(k) { w.conf.SetAttr(k, v) } } return nil }
[ "func", "(", "w", "*", "unixConfigure", ")", "ConfigureCustomOverrides", "(", ")", "error", "{", "for", "k", ",", "v", ":=", "range", "w", ".", "icfg", ".", "CloudInitUserData", "{", "// preruncmd was handled in ConfigureBasic()", "// packages and postruncmd have been...
// ConfigureCustomOverrides implements UserdataConfig.ConfigureCustomOverrides
[ "ConfigureCustomOverrides", "implements", "UserdataConfig", ".", "ConfigureCustomOverrides" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/userdatacfg_unix.go#L403-L412
train
juju/juju
cloudconfig/userdatacfg_unix.go
setUpGUI
func (w *unixConfigure) setUpGUI() (func(), error) { if w.icfg.Bootstrap.GUI == nil { // No GUI archives were found on simplestreams, and no development // GUI path has been passed with the JUJU_GUI environment variable. return nil, nil } u, err := url.Parse(w.icfg.Bootstrap.GUI.URL) if err != nil { return nil, errors.Annotate(err, "cannot parse Juju GUI URL") } guiJson, err := json.Marshal(w.icfg.Bootstrap.GUI) if err != nil { return nil, errors.Trace(err) } guiDir := w.icfg.GUITools() w.conf.AddScripts( "gui="+shquote(guiDir), "mkdir -p $gui", ) if u.Scheme == "file" { // Upload the GUI from a local archive file. guiData, err := ioutil.ReadFile(filepath.FromSlash(u.Path)) if err != nil { return nil, errors.Annotate(err, "cannot read Juju GUI archive") } w.conf.AddRunBinaryFile(path.Join(guiDir, "gui.tar.bz2"), guiData, 0644) } else { // Download the GUI from simplestreams. command := "curl -sSf -o $gui/gui.tar.bz2 --retry 10" if w.icfg.DisableSSLHostnameVerification { command += " --insecure" } curlProxyArgs := w.formatCurlProxyArguments() command += curlProxyArgs command += " " + shquote(u.String()) // A failure in fetching the Juju GUI archive should not prevent the // model to be bootstrapped. Better no GUI than no Juju at all. command += " || echo Unable to retrieve Juju GUI" w.conf.AddRunCmd(command) } w.conf.AddScripts( "[ -f $gui/gui.tar.bz2 ] && sha256sum $gui/gui.tar.bz2 > $gui/jujugui.sha256", fmt.Sprintf( `[ -f $gui/jujugui.sha256 ] && (grep '%s' $gui/jujugui.sha256 && printf %%s %s > $gui/downloaded-gui.txt || echo Juju GUI checksum mismatch)`, w.icfg.Bootstrap.GUI.SHA256, shquote(string(guiJson))), ) return func() { // Don't remove the GUI archive until after bootstrap agent runs, // so it has a chance to add it to its catalogue. w.conf.AddRunCmd("rm -f $gui/gui.tar.bz2 $gui/jujugui.sha256 $gui/downloaded-gui.txt") }, nil }
go
func (w *unixConfigure) setUpGUI() (func(), error) { if w.icfg.Bootstrap.GUI == nil { // No GUI archives were found on simplestreams, and no development // GUI path has been passed with the JUJU_GUI environment variable. return nil, nil } u, err := url.Parse(w.icfg.Bootstrap.GUI.URL) if err != nil { return nil, errors.Annotate(err, "cannot parse Juju GUI URL") } guiJson, err := json.Marshal(w.icfg.Bootstrap.GUI) if err != nil { return nil, errors.Trace(err) } guiDir := w.icfg.GUITools() w.conf.AddScripts( "gui="+shquote(guiDir), "mkdir -p $gui", ) if u.Scheme == "file" { // Upload the GUI from a local archive file. guiData, err := ioutil.ReadFile(filepath.FromSlash(u.Path)) if err != nil { return nil, errors.Annotate(err, "cannot read Juju GUI archive") } w.conf.AddRunBinaryFile(path.Join(guiDir, "gui.tar.bz2"), guiData, 0644) } else { // Download the GUI from simplestreams. command := "curl -sSf -o $gui/gui.tar.bz2 --retry 10" if w.icfg.DisableSSLHostnameVerification { command += " --insecure" } curlProxyArgs := w.formatCurlProxyArguments() command += curlProxyArgs command += " " + shquote(u.String()) // A failure in fetching the Juju GUI archive should not prevent the // model to be bootstrapped. Better no GUI than no Juju at all. command += " || echo Unable to retrieve Juju GUI" w.conf.AddRunCmd(command) } w.conf.AddScripts( "[ -f $gui/gui.tar.bz2 ] && sha256sum $gui/gui.tar.bz2 > $gui/jujugui.sha256", fmt.Sprintf( `[ -f $gui/jujugui.sha256 ] && (grep '%s' $gui/jujugui.sha256 && printf %%s %s > $gui/downloaded-gui.txt || echo Juju GUI checksum mismatch)`, w.icfg.Bootstrap.GUI.SHA256, shquote(string(guiJson))), ) return func() { // Don't remove the GUI archive until after bootstrap agent runs, // so it has a chance to add it to its catalogue. w.conf.AddRunCmd("rm -f $gui/gui.tar.bz2 $gui/jujugui.sha256 $gui/downloaded-gui.txt") }, nil }
[ "func", "(", "w", "*", "unixConfigure", ")", "setUpGUI", "(", ")", "(", "func", "(", ")", ",", "error", ")", "{", "if", "w", ".", "icfg", ".", "Bootstrap", ".", "GUI", "==", "nil", "{", "// No GUI archives were found on simplestreams, and no development", "/...
// setUpGUI fetches the Juju GUI archive and save it to the controller. // The returned clean up function must be called when the bootstrapping // process is completed.
[ "setUpGUI", "fetches", "the", "Juju", "GUI", "archive", "and", "save", "it", "to", "the", "controller", ".", "The", "returned", "clean", "up", "function", "must", "be", "called", "when", "the", "bootstrapping", "process", "is", "completed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/userdatacfg_unix.go#L554-L606
train
juju/juju
cloudconfig/userdatacfg_unix.go
toolsDownloadCommand
func toolsDownloadCommand(curlCommand string, urls []string) string { parsedTemplate := template.Must( template.New("ToolsDownload").Funcs( template.FuncMap{"shquote": shquote}, ).Parse(toolsDownloadTemplate), ) var buf bytes.Buffer err := parsedTemplate.Execute(&buf, map[string]interface{}{ "ToolsDownloadCommand": curlCommand, "ToolsDownloadWaitTime": toolsDownloadWaitTime, "URLs": urls, }) if err != nil { panic(errors.Annotate(err, "agent binaries download template error")) } return buf.String() }
go
func toolsDownloadCommand(curlCommand string, urls []string) string { parsedTemplate := template.Must( template.New("ToolsDownload").Funcs( template.FuncMap{"shquote": shquote}, ).Parse(toolsDownloadTemplate), ) var buf bytes.Buffer err := parsedTemplate.Execute(&buf, map[string]interface{}{ "ToolsDownloadCommand": curlCommand, "ToolsDownloadWaitTime": toolsDownloadWaitTime, "URLs": urls, }) if err != nil { panic(errors.Annotate(err, "agent binaries download template error")) } return buf.String() }
[ "func", "toolsDownloadCommand", "(", "curlCommand", "string", ",", "urls", "[", "]", "string", ")", "string", "{", "parsedTemplate", ":=", "template", ".", "Must", "(", "template", ".", "New", "(", "\"", "\"", ")", ".", "Funcs", "(", "template", ".", "Fu...
// toolsDownloadCommand takes a curl command minus the source URL, // and generates a command that will cycle through the URLs until // one succeeds.
[ "toolsDownloadCommand", "takes", "a", "curl", "command", "minus", "the", "source", "URL", "and", "generates", "a", "command", "that", "will", "cycle", "through", "the", "URLs", "until", "one", "succeeds", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/userdatacfg_unix.go#L611-L627
train
juju/juju
cmd/juju/application/bundlediff.go
SetFlags
func (c *bundleDiffCommand) SetFlags(f *gnuflag.FlagSet) { c.ModelCommandBase.SetFlags(f) f.StringVar((*string)(&c.channel), "channel", "", "Channel to use when getting the bundle from the charm store") f.Var(cmd.NewAppendStringsValue(&c.bundleOverlays), "overlay", "Bundles to overlay on the primary bundle, applied in order") f.StringVar(&c.machineMap, "map-machines", "", "Indicates how existing machines correspond to bundle machines") f.BoolVar(&c.annotations, "annotations", false, "Include differences in annotations") }
go
func (c *bundleDiffCommand) SetFlags(f *gnuflag.FlagSet) { c.ModelCommandBase.SetFlags(f) f.StringVar((*string)(&c.channel), "channel", "", "Channel to use when getting the bundle from the charm store") f.Var(cmd.NewAppendStringsValue(&c.bundleOverlays), "overlay", "Bundles to overlay on the primary bundle, applied in order") f.StringVar(&c.machineMap, "map-machines", "", "Indicates how existing machines correspond to bundle machines") f.BoolVar(&c.annotations, "annotations", false, "Include differences in annotations") }
[ "func", "(", "c", "*", "bundleDiffCommand", ")", "SetFlags", "(", "f", "*", "gnuflag", ".", "FlagSet", ")", "{", "c", ".", "ModelCommandBase", ".", "SetFlags", "(", "f", ")", "\n", "f", ".", "StringVar", "(", "(", "*", "string", ")", "(", "&", "c",...
// SetFlags is part of cmd.Command.
[ "SetFlags", "is", "part", "of", "cmd", ".", "Command", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundlediff.go#L89-L95
train
juju/juju
cmd/juju/application/bundlediff.go
GetAnnotations
func (e *extractorImpl) GetAnnotations(tags []string) ([]params.AnnotationsGetResult, error) { return e.annotations.Get(tags) }
go
func (e *extractorImpl) GetAnnotations(tags []string) ([]params.AnnotationsGetResult, error) { return e.annotations.Get(tags) }
[ "func", "(", "e", "*", "extractorImpl", ")", "GetAnnotations", "(", "tags", "[", "]", "string", ")", "(", "[", "]", "params", ".", "AnnotationsGetResult", ",", "error", ")", "{", "return", "e", ".", "annotations", ".", "Get", "(", "tags", ")", "\n", ...
// GetAnnotations is part of ModelExtractor.
[ "GetAnnotations", "is", "part", "of", "ModelExtractor", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundlediff.go#L258-L260
train
juju/juju
cmd/juju/application/bundlediff.go
GetConstraints
func (e *extractorImpl) GetConstraints(applications ...string) ([]constraints.Value, error) { return e.application.GetConstraints(applications...) }
go
func (e *extractorImpl) GetConstraints(applications ...string) ([]constraints.Value, error) { return e.application.GetConstraints(applications...) }
[ "func", "(", "e", "*", "extractorImpl", ")", "GetConstraints", "(", "applications", "...", "string", ")", "(", "[", "]", "constraints", ".", "Value", ",", "error", ")", "{", "return", "e", ".", "application", ".", "GetConstraints", "(", "applications", ".....
// GetConstraints is part of ModelExtractor.
[ "GetConstraints", "is", "part", "of", "ModelExtractor", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundlediff.go#L263-L265
train
juju/juju
cmd/juju/application/bundlediff.go
GetConfig
func (e *extractorImpl) GetConfig(branchName string, applications ...string) ([]map[string]interface{}, error) { return e.application.GetConfig(branchName, applications...) }
go
func (e *extractorImpl) GetConfig(branchName string, applications ...string) ([]map[string]interface{}, error) { return e.application.GetConfig(branchName, applications...) }
[ "func", "(", "e", "*", "extractorImpl", ")", "GetConfig", "(", "branchName", "string", ",", "applications", "...", "string", ")", "(", "[", "]", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "return", "e", ".", "application"...
// GetConfig is part of ModelExtractor.
[ "GetConfig", "is", "part", "of", "ModelExtractor", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundlediff.go#L268-L270
train
juju/juju
cmd/jujud/agent/engine/flag.go
FlagOutput
func FlagOutput(in worker.Worker, out interface{}) error { inFlag, ok := in.(Flag) if !ok { return errors.Errorf("expected in to implement Flag; got a %T", in) } outFlag, ok := out.(*Flag) if !ok { return errors.Errorf("expected out to be a *Flag; got a %T", out) } *outFlag = inFlag return nil }
go
func FlagOutput(in worker.Worker, out interface{}) error { inFlag, ok := in.(Flag) if !ok { return errors.Errorf("expected in to implement Flag; got a %T", in) } outFlag, ok := out.(*Flag) if !ok { return errors.Errorf("expected out to be a *Flag; got a %T", out) } *outFlag = inFlag return nil }
[ "func", "FlagOutput", "(", "in", "worker", ".", "Worker", ",", "out", "interface", "{", "}", ")", "error", "{", "inFlag", ",", "ok", ":=", "in", ".", "(", "Flag", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "Errorf", "(", "\"", "\""...
// FlagOutput will expose, as a Flag, any worker that implements Flag.
[ "FlagOutput", "will", "expose", "as", "a", "Flag", "any", "worker", "that", "implements", "Flag", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/engine/flag.go#L23-L34
train
juju/juju
cmd/jujud/agent/engine/flag.go
NewStaticFlagWorker
func NewStaticFlagWorker(value bool) worker.Worker { w := &staticFlagWorker{value: value} w.tomb.Go(func() error { <-w.tomb.Dying() return tomb.ErrDying }) return w }
go
func NewStaticFlagWorker(value bool) worker.Worker { w := &staticFlagWorker{value: value} w.tomb.Go(func() error { <-w.tomb.Dying() return tomb.ErrDying }) return w }
[ "func", "NewStaticFlagWorker", "(", "value", "bool", ")", "worker", ".", "Worker", "{", "w", ":=", "&", "staticFlagWorker", "{", "value", ":", "value", "}", "\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "<-", "w", ".", "to...
// NewStaticFlagWorker returns a new Worker that implements Flag, // whose Check method always returns the specified value.
[ "NewStaticFlagWorker", "returns", "a", "new", "Worker", "that", "implements", "Flag", "whose", "Check", "method", "always", "returns", "the", "specified", "value", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/engine/flag.go#L43-L50
train
juju/juju
apiserver/facades/controller/remoterelations/remoterelations.go
NewStateRemoteRelationsAPI
func NewStateRemoteRelationsAPI(ctx facade.Context) (*RemoteRelationsAPI, error) { return NewRemoteRelationsAPI( stateShim{st: ctx.State(), Backend: commoncrossmodel.GetBackend(ctx.State())}, common.NewStateControllerConfig(ctx.State()), ctx.Resources(), ctx.Auth(), ) }
go
func NewStateRemoteRelationsAPI(ctx facade.Context) (*RemoteRelationsAPI, error) { return NewRemoteRelationsAPI( stateShim{st: ctx.State(), Backend: commoncrossmodel.GetBackend(ctx.State())}, common.NewStateControllerConfig(ctx.State()), ctx.Resources(), ctx.Auth(), ) }
[ "func", "NewStateRemoteRelationsAPI", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "RemoteRelationsAPI", ",", "error", ")", "{", "return", "NewRemoteRelationsAPI", "(", "stateShim", "{", "st", ":", "ctx", ".", "State", "(", ")", ",", "Backend", ":", ...
// NewStateRemoteRelationsAPI creates a new server-side RemoteRelationsAPI facade // backed by global state.
[ "NewStateRemoteRelationsAPI", "creates", "a", "new", "server", "-", "side", "RemoteRelationsAPI", "facade", "backed", "by", "global", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/remoterelations/remoterelations.go#L28-L35
train
juju/juju
apiserver/facades/controller/remoterelations/remoterelations.go
NewRemoteRelationsAPI
func NewRemoteRelationsAPI( st RemoteRelationsState, controllerCfgAPI *common.ControllerConfigAPI, resources facade.Resources, authorizer facade.Authorizer, ) (*RemoteRelationsAPI, error) { if !authorizer.AuthController() { return nil, common.ErrPerm } return &RemoteRelationsAPI{ st: st, ControllerConfigAPI: controllerCfgAPI, resources: resources, authorizer: authorizer, }, nil }
go
func NewRemoteRelationsAPI( st RemoteRelationsState, controllerCfgAPI *common.ControllerConfigAPI, resources facade.Resources, authorizer facade.Authorizer, ) (*RemoteRelationsAPI, error) { if !authorizer.AuthController() { return nil, common.ErrPerm } return &RemoteRelationsAPI{ st: st, ControllerConfigAPI: controllerCfgAPI, resources: resources, authorizer: authorizer, }, nil }
[ "func", "NewRemoteRelationsAPI", "(", "st", "RemoteRelationsState", ",", "controllerCfgAPI", "*", "common", ".", "ControllerConfigAPI", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ",", ")", "(", "*", "RemoteRelations...
// NewRemoteRelationsAPI returns a new server-side RemoteRelationsAPI facade.
[ "NewRemoteRelationsAPI", "returns", "a", "new", "server", "-", "side", "RemoteRelationsAPI", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/remoterelations/remoterelations.go#L38-L53
train
juju/juju
apiserver/facades/controller/remoterelations/remoterelations.go
ImportRemoteEntities
func (api *RemoteRelationsAPI) ImportRemoteEntities(args params.RemoteEntityTokenArgs) (params.ErrorResults, error) { results := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Args)), } for i, arg := range args.Args { err := api.importRemoteEntity(arg) results.Results[i].Error = common.ServerError(err) } return results, nil }
go
func (api *RemoteRelationsAPI) ImportRemoteEntities(args params.RemoteEntityTokenArgs) (params.ErrorResults, error) { results := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Args)), } for i, arg := range args.Args { err := api.importRemoteEntity(arg) results.Results[i].Error = common.ServerError(err) } return results, nil }
[ "func", "(", "api", "*", "RemoteRelationsAPI", ")", "ImportRemoteEntities", "(", "args", "params", ".", "RemoteEntityTokenArgs", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "results", ":=", "params", ".", "ErrorResults", "{", "Results", ":...
// ImportRemoteEntities adds entities to the remote entities collection with the specified opaque tokens.
[ "ImportRemoteEntities", "adds", "entities", "to", "the", "remote", "entities", "collection", "with", "the", "specified", "opaque", "tokens", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/remoterelations/remoterelations.go#L56-L65
train
juju/juju
apiserver/facades/controller/remoterelations/remoterelations.go
GetTokens
func (api *RemoteRelationsAPI) GetTokens(args params.GetTokenArgs) (params.StringResults, error) { results := params.StringResults{ Results: make([]params.StringResult, len(args.Args)), } for i, arg := range args.Args { entityTag, err := names.ParseTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } token, err := api.st.GetToken(entityTag) if err != nil { results.Results[i].Error = common.ServerError(err) } results.Results[i].Result = token } return results, nil }
go
func (api *RemoteRelationsAPI) GetTokens(args params.GetTokenArgs) (params.StringResults, error) { results := params.StringResults{ Results: make([]params.StringResult, len(args.Args)), } for i, arg := range args.Args { entityTag, err := names.ParseTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } token, err := api.st.GetToken(entityTag) if err != nil { results.Results[i].Error = common.ServerError(err) } results.Results[i].Result = token } return results, nil }
[ "func", "(", "api", "*", "RemoteRelationsAPI", ")", "GetTokens", "(", "args", "params", ".", "GetTokenArgs", ")", "(", "params", ".", "StringResults", ",", "error", ")", "{", "results", ":=", "params", ".", "StringResults", "{", "Results", ":", "make", "("...
// GetTokens returns the token associated with the entities with the given tags for the given models.
[ "GetTokens", "returns", "the", "token", "associated", "with", "the", "entities", "with", "the", "given", "tags", "for", "the", "given", "models", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/remoterelations/remoterelations.go#L99-L116
train
juju/juju
apiserver/facades/controller/remoterelations/remoterelations.go
SaveMacaroons
func (api *RemoteRelationsAPI) SaveMacaroons(args params.EntityMacaroonArgs) (params.ErrorResults, error) { results := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Args)), } for i, arg := range args.Args { entityTag, err := names.ParseTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } err = api.st.SaveMacaroon(entityTag, arg.Macaroon) results.Results[i].Error = common.ServerError(err) } return results, nil }
go
func (api *RemoteRelationsAPI) SaveMacaroons(args params.EntityMacaroonArgs) (params.ErrorResults, error) { results := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Args)), } for i, arg := range args.Args { entityTag, err := names.ParseTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } err = api.st.SaveMacaroon(entityTag, arg.Macaroon) results.Results[i].Error = common.ServerError(err) } return results, nil }
[ "func", "(", "api", "*", "RemoteRelationsAPI", ")", "SaveMacaroons", "(", "args", "params", ".", "EntityMacaroonArgs", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "results", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make...
// SaveMacaroons saves the macaroons for the given entities.
[ "SaveMacaroons", "saves", "the", "macaroons", "for", "the", "given", "entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/remoterelations/remoterelations.go#L119-L133
train
juju/juju
apiserver/facades/controller/remoterelations/remoterelations.go
WatchLocalRelationUnits
func (api *RemoteRelationsAPI) WatchLocalRelationUnits(args params.Entities) (params.RelationUnitsWatchResults, error) { results := params.RelationUnitsWatchResults{ make([]params.RelationUnitsWatchResult, len(args.Entities)), } for i, arg := range args.Entities { relationTag, err := names.ParseRelationTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } w, err := commoncrossmodel.WatchRelationUnits(api.st, relationTag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } changes, ok := <-w.Changes() if !ok { results.Results[i].Error = common.ServerError(watcher.EnsureErr(w)) continue } results.Results[i].RelationUnitsWatcherId = api.resources.Register(w) results.Results[i].Changes = changes } return results, nil }
go
func (api *RemoteRelationsAPI) WatchLocalRelationUnits(args params.Entities) (params.RelationUnitsWatchResults, error) { results := params.RelationUnitsWatchResults{ make([]params.RelationUnitsWatchResult, len(args.Entities)), } for i, arg := range args.Entities { relationTag, err := names.ParseRelationTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } w, err := commoncrossmodel.WatchRelationUnits(api.st, relationTag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } changes, ok := <-w.Changes() if !ok { results.Results[i].Error = common.ServerError(watcher.EnsureErr(w)) continue } results.Results[i].RelationUnitsWatcherId = api.resources.Register(w) results.Results[i].Changes = changes } return results, nil }
[ "func", "(", "api", "*", "RemoteRelationsAPI", ")", "WatchLocalRelationUnits", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "RelationUnitsWatchResults", ",", "error", ")", "{", "results", ":=", "params", ".", "RelationUnitsWatchResults", "{", ...
// WatchLocalRelationUnits starts a RelationUnitsWatcher for watching the local // relation units involved in each specified relation in the local model, // and returns the watcher IDs and initial values, or an error if the relation // units could not be watched.
[ "WatchLocalRelationUnits", "starts", "a", "RelationUnitsWatcher", "for", "watching", "the", "local", "relation", "units", "involved", "in", "each", "specified", "relation", "in", "the", "local", "model", "and", "returns", "the", "watcher", "IDs", "and", "initial", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/remoterelations/remoterelations.go#L302-L326
train
juju/juju
apiserver/facades/controller/remoterelations/remoterelations.go
WatchRemoteApplicationRelations
func (api *RemoteRelationsAPI) WatchRemoteApplicationRelations(args params.Entities) (params.StringsWatchResults, error) { results := params.StringsWatchResults{ make([]params.StringsWatchResult, len(args.Entities)), } for i, arg := range args.Entities { applicationTag, err := names.ParseApplicationTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } appName := applicationTag.Id() w, err := api.st.WatchRemoteApplicationRelations(appName) if err != nil { results.Results[i].Error = common.ServerError(err) continue } changes, ok := <-w.Changes() if !ok { results.Results[i].Error = common.ServerError(watcher.EnsureErr(w)) continue } results.Results[i].StringsWatcherId = api.resources.Register(w) results.Results[i].Changes = changes } return results, nil }
go
func (api *RemoteRelationsAPI) WatchRemoteApplicationRelations(args params.Entities) (params.StringsWatchResults, error) { results := params.StringsWatchResults{ make([]params.StringsWatchResult, len(args.Entities)), } for i, arg := range args.Entities { applicationTag, err := names.ParseApplicationTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } appName := applicationTag.Id() w, err := api.st.WatchRemoteApplicationRelations(appName) if err != nil { results.Results[i].Error = common.ServerError(err) continue } changes, ok := <-w.Changes() if !ok { results.Results[i].Error = common.ServerError(watcher.EnsureErr(w)) continue } results.Results[i].StringsWatcherId = api.resources.Register(w) results.Results[i].Changes = changes } return results, nil }
[ "func", "(", "api", "*", "RemoteRelationsAPI", ")", "WatchRemoteApplicationRelations", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "StringsWatchResults", ",", "error", ")", "{", "results", ":=", "params", ".", "StringsWatchResults", "{", "ma...
// WatchRemoteApplicationRelations starts a StringsWatcher for watching the relations of // each specified application in the local model, and returns the watcher IDs // and initial values, or an error if the services' relations could not be // watched.
[ "WatchRemoteApplicationRelations", "starts", "a", "StringsWatcher", "for", "watching", "the", "relations", "of", "each", "specified", "application", "in", "the", "local", "model", "and", "returns", "the", "watcher", "IDs", "and", "initial", "values", "or", "an", "...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/remoterelations/remoterelations.go#L332-L357
train
juju/juju
apiserver/facades/controller/remoterelations/remoterelations.go
WatchRemoteRelations
func (api *RemoteRelationsAPI) WatchRemoteRelations() (params.StringsWatchResult, error) { w := api.st.WatchRemoteRelations() if changes, ok := <-w.Changes(); ok { return params.StringsWatchResult{ StringsWatcherId: api.resources.Register(w), Changes: changes, }, nil } return params.StringsWatchResult{}, watcher.EnsureErr(w) }
go
func (api *RemoteRelationsAPI) WatchRemoteRelations() (params.StringsWatchResult, error) { w := api.st.WatchRemoteRelations() if changes, ok := <-w.Changes(); ok { return params.StringsWatchResult{ StringsWatcherId: api.resources.Register(w), Changes: changes, }, nil } return params.StringsWatchResult{}, watcher.EnsureErr(w) }
[ "func", "(", "api", "*", "RemoteRelationsAPI", ")", "WatchRemoteRelations", "(", ")", "(", "params", ".", "StringsWatchResult", ",", "error", ")", "{", "w", ":=", "api", ".", "st", ".", "WatchRemoteRelations", "(", ")", "\n", "if", "changes", ",", "ok", ...
// WatchRemoteRelations starts a strings watcher that notifies of the addition, // removal, and lifecycle changes of remote relations in the model; and // returns the watcher ID and initial IDs of remote relations, or an error if // watching failed.
[ "WatchRemoteRelations", "starts", "a", "strings", "watcher", "that", "notifies", "of", "the", "addition", "removal", "and", "lifecycle", "changes", "of", "remote", "relations", "in", "the", "model", ";", "and", "returns", "the", "watcher", "ID", "and", "initial"...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/remoterelations/remoterelations.go#L363-L372
train