id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens listlengths 21 1.41k | docstring stringlengths 6 2.61k | docstring_tokens listlengths 3 215 | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4,700 | juju/juju | apiserver/facades/client/modelgeneration/mocks/package_mock.go | AssignedUnits | func (mr *MockGenerationMockRecorder) AssignedUnits() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AssignedUnits", reflect.TypeOf((*MockGeneration)(nil).AssignedUnits))
} | go | func (mr *MockGenerationMockRecorder) AssignedUnits() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AssignedUnits", reflect.TypeOf((*MockGeneration)(nil).AssignedUnits))
} | [
"func",
"(",
"mr",
"*",
"MockGenerationMockRecorder",
")",
"AssignedUnits",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
"."... | // AssignedUnits indicates an expected call of AssignedUnits | [
"AssignedUnits",
"indicates",
"an",
"expected",
"call",
"of",
"AssignedUnits"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelgeneration/mocks/package_mock.go#L205-L207 |
4,701 | juju/juju | apiserver/facades/client/modelgeneration/mocks/package_mock.go | Commit | func (m *MockGeneration) Commit(arg0 string) (int, error) {
ret := m.ctrl.Call(m, "Commit", arg0)
ret0, _ := ret[0].(int)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockGeneration) Commit(arg0 string) (int, error) {
ret := m.ctrl.Call(m, "Commit", arg0)
ret0, _ := ret[0].(int)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockGeneration",
")",
"Commit",
"(",
"arg0",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":=",
"re... | // Commit mocks base method | [
"Commit",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelgeneration/mocks/package_mock.go#L222-L227 |
4,702 | juju/juju | apiserver/facades/client/modelgeneration/mocks/package_mock.go | Created | func (m *MockGeneration) Created() int64 {
ret := m.ctrl.Call(m, "Created")
ret0, _ := ret[0].(int64)
return ret0
} | go | func (m *MockGeneration) Created() int64 {
ret := m.ctrl.Call(m, "Created")
ret0, _ := ret[0].(int64)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockGeneration",
")",
"Created",
"(",
")",
"int64",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"int64",
")",
"\n",
"... | // Created mocks base method | [
"Created",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelgeneration/mocks/package_mock.go#L247-L251 |
4,703 | juju/juju | apiserver/facades/client/modelgeneration/mocks/package_mock.go | CreatedBy | func (m *MockGeneration) CreatedBy() string {
ret := m.ctrl.Call(m, "CreatedBy")
ret0, _ := ret[0].(string)
return ret0
} | go | func (m *MockGeneration) CreatedBy() string {
ret := m.ctrl.Call(m, "CreatedBy")
ret0, _ := ret[0].(string)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockGeneration",
")",
"CreatedBy",
"(",
")",
"string",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"string",
")",
"\n",... | // CreatedBy mocks base method | [
"CreatedBy",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelgeneration/mocks/package_mock.go#L259-L263 |
4,704 | juju/juju | apiserver/facades/client/modelgeneration/mocks/package_mock.go | DefaultCharmConfig | func (m *MockApplication) DefaultCharmConfig() (charm_v6.Settings, error) {
ret := m.ctrl.Call(m, "DefaultCharmConfig")
ret0, _ := ret[0].(charm_v6.Settings)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockApplication) DefaultCharmConfig() (charm_v6.Settings, error) {
ret := m.ctrl.Call(m, "DefaultCharmConfig")
ret0, _ := ret[0].(charm_v6.Settings)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockApplication",
")",
"DefaultCharmConfig",
"(",
")",
"(",
"charm_v6",
".",
"Settings",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"re... | // DefaultCharmConfig mocks base method | [
"DefaultCharmConfig",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelgeneration/mocks/package_mock.go#L294-L299 |
4,705 | juju/juju | apiserver/facades/client/modelgeneration/mocks/package_mock.go | UnitNames | func (m *MockApplication) UnitNames() ([]string, error) {
ret := m.ctrl.Call(m, "UnitNames")
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockApplication) UnitNames() ([]string, error) {
ret := m.ctrl.Call(m, "UnitNames")
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockApplication",
")",
"UnitNames",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
... | // UnitNames mocks base method | [
"UnitNames",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelgeneration/mocks/package_mock.go#L307-L312 |
4,706 | juju/juju | worker/lease/block.go | invoke | func (b block) invoke(ch chan<- block) error {
for {
select {
case <-b.stop:
return errStopped
case <-b.cancel:
return lease.ErrWaitCancelled
case ch <- b:
ch = nil
case <-b.unblock:
return nil
}
}
} | go | func (b block) invoke(ch chan<- block) error {
for {
select {
case <-b.stop:
return errStopped
case <-b.cancel:
return lease.ErrWaitCancelled
case ch <- b:
ch = nil
case <-b.unblock:
return nil
}
}
} | [
"func",
"(",
"b",
"block",
")",
"invoke",
"(",
"ch",
"chan",
"<-",
"block",
")",
"error",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"b",
".",
"stop",
":",
"return",
"errStopped",
"\n",
"case",
"<-",
"b",
".",
"cancel",
":",
"return",
"lease",
... | // invoke sends the block request on the supplied channel, and waits for the
// unblock channel to be closed. | [
"invoke",
"sends",
"the",
"block",
"request",
"on",
"the",
"supplied",
"channel",
"and",
"waits",
"for",
"the",
"unblock",
"channel",
"to",
"be",
"closed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/lease/block.go#L19-L32 |
4,707 | juju/juju | worker/lease/block.go | add | func (b blocks) add(block block) {
b[block.leaseKey] = append(b[block.leaseKey], block.unblock)
} | go | func (b blocks) add(block block) {
b[block.leaseKey] = append(b[block.leaseKey], block.unblock)
} | [
"func",
"(",
"b",
"blocks",
")",
"add",
"(",
"block",
"block",
")",
"{",
"b",
"[",
"block",
".",
"leaseKey",
"]",
"=",
"append",
"(",
"b",
"[",
"block",
".",
"leaseKey",
"]",
",",
"block",
".",
"unblock",
")",
"\n",
"}"
] | // add records the block's unblock channel under the block's lease key. | [
"add",
"records",
"the",
"block",
"s",
"unblock",
"channel",
"under",
"the",
"block",
"s",
"lease",
"key",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/lease/block.go#L39-L41 |
4,708 | juju/juju | worker/lease/block.go | unblock | func (b blocks) unblock(lease lease.Key) {
unblocks := b[lease]
delete(b, lease)
for _, unblock := range unblocks {
close(unblock)
}
} | go | func (b blocks) unblock(lease lease.Key) {
unblocks := b[lease]
delete(b, lease)
for _, unblock := range unblocks {
close(unblock)
}
} | [
"func",
"(",
"b",
"blocks",
")",
"unblock",
"(",
"lease",
"lease",
".",
"Key",
")",
"{",
"unblocks",
":=",
"b",
"[",
"lease",
"]",
"\n",
"delete",
"(",
"b",
",",
"lease",
")",
"\n",
"for",
"_",
",",
"unblock",
":=",
"range",
"unblocks",
"{",
"clo... | // unblock closes all channels added under the supplied key and removes
// them from blocks. | [
"unblock",
"closes",
"all",
"channels",
"added",
"under",
"the",
"supplied",
"key",
"and",
"removes",
"them",
"from",
"blocks",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/lease/block.go#L45-L51 |
4,709 | juju/juju | worker/upgradesteps/worker.go | NewLock | func NewLock(agentConfig agent.Config) gate.Lock {
lock := gate.NewLock()
if wrench.IsActive(wrenchKey(agentConfig), "always-try-upgrade") {
// Always enter upgrade mode. This allows test of upgrades
// even when there's actually no upgrade steps to run.
return lock
}
// Build numbers are irrelevant to upgrade steps.
upgradedToVersion := agentConfig.UpgradedToVersion()
upgradedToVersion.Build = 0
currentVersion := jujuversion.Current
currentVersion.Build = 0
if upgradedToVersion == currentVersion {
logger.Infof(
"upgrade steps for %v have already been run.",
jujuversion.Current,
)
lock.Unlock()
}
return lock
} | go | func NewLock(agentConfig agent.Config) gate.Lock {
lock := gate.NewLock()
if wrench.IsActive(wrenchKey(agentConfig), "always-try-upgrade") {
// Always enter upgrade mode. This allows test of upgrades
// even when there's actually no upgrade steps to run.
return lock
}
// Build numbers are irrelevant to upgrade steps.
upgradedToVersion := agentConfig.UpgradedToVersion()
upgradedToVersion.Build = 0
currentVersion := jujuversion.Current
currentVersion.Build = 0
if upgradedToVersion == currentVersion {
logger.Infof(
"upgrade steps for %v have already been run.",
jujuversion.Current,
)
lock.Unlock()
}
return lock
} | [
"func",
"NewLock",
"(",
"agentConfig",
"agent",
".",
"Config",
")",
"gate",
".",
"Lock",
"{",
"lock",
":=",
"gate",
".",
"NewLock",
"(",
")",
"\n\n",
"if",
"wrench",
".",
"IsActive",
"(",
"wrenchKey",
"(",
"agentConfig",
")",
",",
"\"",
"\"",
")",
"{... | // NewLock creates a gate.Lock to be used to synchronise workers which
// need to start after upgrades have completed. The returned Lock should
// be passed to NewWorker. If the agent has already upgraded to the
// current version, then the lock will be returned in the released state. | [
"NewLock",
"creates",
"a",
"gate",
".",
"Lock",
"to",
"be",
"used",
"to",
"synchronise",
"workers",
"which",
"need",
"to",
"start",
"after",
"upgrades",
"have",
"completed",
".",
"The",
"returned",
"Lock",
"should",
"be",
"passed",
"to",
"NewWorker",
".",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradesteps/worker.go#L58-L81 |
4,710 | juju/juju | worker/upgradesteps/worker.go | NewWorker | func NewWorker(
upgradeComplete gate.Lock,
agent agent.Agent,
apiConn api.Connection,
jobs []multiwatcher.MachineJob,
openState func() (*state.StatePool, error),
preUpgradeSteps func(st *state.StatePool, agentConf agent.Config, isController, isMasterServer, isCaas bool) error,
machine StatusSetter,
isCaas bool,
) (worker.Worker, error) {
w := &upgradesteps{
upgradeComplete: upgradeComplete,
agent: agent,
apiConn: apiConn,
jobs: jobs,
openState: openState,
preUpgradeSteps: preUpgradeSteps,
machine: machine,
tag: agent.CurrentConfig().Tag(),
isCaas: isCaas,
}
w.tomb.Go(w.run)
return w, nil
} | go | func NewWorker(
upgradeComplete gate.Lock,
agent agent.Agent,
apiConn api.Connection,
jobs []multiwatcher.MachineJob,
openState func() (*state.StatePool, error),
preUpgradeSteps func(st *state.StatePool, agentConf agent.Config, isController, isMasterServer, isCaas bool) error,
machine StatusSetter,
isCaas bool,
) (worker.Worker, error) {
w := &upgradesteps{
upgradeComplete: upgradeComplete,
agent: agent,
apiConn: apiConn,
jobs: jobs,
openState: openState,
preUpgradeSteps: preUpgradeSteps,
machine: machine,
tag: agent.CurrentConfig().Tag(),
isCaas: isCaas,
}
w.tomb.Go(w.run)
return w, nil
} | [
"func",
"NewWorker",
"(",
"upgradeComplete",
"gate",
".",
"Lock",
",",
"agent",
"agent",
".",
"Agent",
",",
"apiConn",
"api",
".",
"Connection",
",",
"jobs",
"[",
"]",
"multiwatcher",
".",
"MachineJob",
",",
"openState",
"func",
"(",
")",
"(",
"*",
"stat... | // NewWorker returns a new instance of the upgradesteps worker. It
// will run any required steps to upgrade to the currently running
// Juju version. | [
"NewWorker",
"returns",
"a",
"new",
"instance",
"of",
"the",
"upgradesteps",
"worker",
".",
"It",
"will",
"run",
"any",
"required",
"steps",
"to",
"upgrade",
"to",
"the",
"currently",
"running",
"Juju",
"version",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradesteps/worker.go#L92-L115 |
4,711 | juju/juju | worker/upgradesteps/worker.go | runUpgrades | func (w *upgradesteps) runUpgrades() error {
upgradeInfo, err := w.prepareForUpgrade()
if err != nil {
return err
}
if wrench.IsActive(w.wrenchKey(), "fail-upgrade") {
return errors.New("wrench")
}
if err := w.agent.ChangeConfig(w.runUpgradeSteps); err != nil {
return err
}
if err := w.finaliseUpgrade(upgradeInfo); err != nil {
return err
}
return nil
} | go | func (w *upgradesteps) runUpgrades() error {
upgradeInfo, err := w.prepareForUpgrade()
if err != nil {
return err
}
if wrench.IsActive(w.wrenchKey(), "fail-upgrade") {
return errors.New("wrench")
}
if err := w.agent.ChangeConfig(w.runUpgradeSteps); err != nil {
return err
}
if err := w.finaliseUpgrade(upgradeInfo); err != nil {
return err
}
return nil
} | [
"func",
"(",
"w",
"*",
"upgradesteps",
")",
"runUpgrades",
"(",
")",
"error",
"{",
"upgradeInfo",
",",
"err",
":=",
"w",
".",
"prepareForUpgrade",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"wrench",
".",... | // runUpgrades runs the upgrade operations for each job type and
// updates the updatedToVersion on success. | [
"runUpgrades",
"runs",
"the",
"upgrade",
"operations",
"for",
"each",
"job",
"type",
"and",
"updates",
"the",
"updatedToVersion",
"on",
"success",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradesteps/worker.go#L243-L261 |
4,712 | juju/juju | worker/upgradesteps/worker.go | runUpgradeSteps | func (w *upgradesteps) runUpgradeSteps(agentConfig agent.ConfigSetter) error {
var upgradeErr error
w.machine.SetStatus(status.Started, fmt.Sprintf("upgrading to %v", w.toVersion), nil)
stBackend := upgrades.NewStateBackend(w.pool)
context := upgrades.NewContext(agentConfig, w.apiConn, stBackend)
logger.Infof("starting upgrade from %v to %v for %q", w.fromVersion, w.toVersion, w.tag)
targets := jobsToTargets(w.jobs, w.isMaster)
attempts := getUpgradeRetryStrategy()
for attempt := attempts.Start(); attempt.Next(); {
upgradeErr = PerformUpgrade(w.fromVersion, targets, context)
if upgradeErr == nil {
break
}
if cmdutil.ConnectionIsDead(logger, w.apiConn) {
// API connection has gone away - abort!
return &apiLostDuringUpgrade{upgradeErr}
}
if attempt.HasNext() {
w.reportUpgradeFailure(upgradeErr, true)
}
}
if upgradeErr != nil {
return upgradeErr
}
agentConfig.SetUpgradedToVersion(w.toVersion)
return nil
} | go | func (w *upgradesteps) runUpgradeSteps(agentConfig agent.ConfigSetter) error {
var upgradeErr error
w.machine.SetStatus(status.Started, fmt.Sprintf("upgrading to %v", w.toVersion), nil)
stBackend := upgrades.NewStateBackend(w.pool)
context := upgrades.NewContext(agentConfig, w.apiConn, stBackend)
logger.Infof("starting upgrade from %v to %v for %q", w.fromVersion, w.toVersion, w.tag)
targets := jobsToTargets(w.jobs, w.isMaster)
attempts := getUpgradeRetryStrategy()
for attempt := attempts.Start(); attempt.Next(); {
upgradeErr = PerformUpgrade(w.fromVersion, targets, context)
if upgradeErr == nil {
break
}
if cmdutil.ConnectionIsDead(logger, w.apiConn) {
// API connection has gone away - abort!
return &apiLostDuringUpgrade{upgradeErr}
}
if attempt.HasNext() {
w.reportUpgradeFailure(upgradeErr, true)
}
}
if upgradeErr != nil {
return upgradeErr
}
agentConfig.SetUpgradedToVersion(w.toVersion)
return nil
} | [
"func",
"(",
"w",
"*",
"upgradesteps",
")",
"runUpgradeSteps",
"(",
"agentConfig",
"agent",
".",
"ConfigSetter",
")",
"error",
"{",
"var",
"upgradeErr",
"error",
"\n",
"w",
".",
"machine",
".",
"SetStatus",
"(",
"status",
".",
"Started",
",",
"fmt",
".",
... | // runUpgradeSteps runs the required upgrade steps for the agent,
// retrying on failure. The agent's UpgradedToVersion is set
// once the upgrade is complete.
//
// This function conforms to the agent.ConfigMutator type and is
// designed to be called via an agent's ChangeConfig method. | [
"runUpgradeSteps",
"runs",
"the",
"required",
"upgrade",
"steps",
"for",
"the",
"agent",
"retrying",
"on",
"failure",
".",
"The",
"agent",
"s",
"UpgradedToVersion",
"is",
"set",
"once",
"the",
"upgrade",
"is",
"complete",
".",
"This",
"function",
"conforms",
"... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradesteps/worker.go#L357-L385 |
4,713 | juju/juju | worker/upgradesteps/worker.go | jobsToTargets | func jobsToTargets(jobs []multiwatcher.MachineJob, isMaster bool) (targets []upgrades.Target) {
if jobs == nil {
return
}
for _, job := range jobs {
switch job {
case multiwatcher.JobManageModel:
targets = append(targets, upgrades.Controller)
if isMaster {
targets = append(targets, upgrades.DatabaseMaster)
}
case multiwatcher.JobHostUnits:
targets = append(targets, upgrades.HostMachine)
}
}
return
} | go | func jobsToTargets(jobs []multiwatcher.MachineJob, isMaster bool) (targets []upgrades.Target) {
if jobs == nil {
return
}
for _, job := range jobs {
switch job {
case multiwatcher.JobManageModel:
targets = append(targets, upgrades.Controller)
if isMaster {
targets = append(targets, upgrades.DatabaseMaster)
}
case multiwatcher.JobHostUnits:
targets = append(targets, upgrades.HostMachine)
}
}
return
} | [
"func",
"jobsToTargets",
"(",
"jobs",
"[",
"]",
"multiwatcher",
".",
"MachineJob",
",",
"isMaster",
"bool",
")",
"(",
"targets",
"[",
"]",
"upgrades",
".",
"Target",
")",
"{",
"if",
"jobs",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"for",
"_",
","... | // jobsToTargets determines the upgrade targets corresponding to the
// jobs assigned to an agent. This determines the upgrade steps
// which will run during an upgrade. | [
"jobsToTargets",
"determines",
"the",
"upgrade",
"targets",
"corresponding",
"to",
"the",
"jobs",
"assigned",
"to",
"an",
"agent",
".",
"This",
"determines",
"the",
"upgrade",
"steps",
"which",
"will",
"run",
"during",
"an",
"upgrade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradesteps/worker.go#L468-L484 |
4,714 | juju/juju | worker/applicationscaler/worker.go | Validate | func (config Config) Validate() error {
if config.Facade == nil {
return errors.NotValidf("nil Facade")
}
return nil
} | go | func (config Config) Validate() error {
if config.Facade == nil {
return errors.NotValidf("nil Facade")
}
return nil
} | [
"func",
"(",
"config",
"Config",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"config",
".",
"Facade",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate returns an error if the config can't be expected
// to run a functional worker. | [
"Validate",
"returns",
"an",
"error",
"if",
"the",
"config",
"can",
"t",
"be",
"expected",
"to",
"run",
"a",
"functional",
"worker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/applicationscaler/worker.go#L32-L37 |
4,715 | juju/juju | worker/applicationscaler/worker.go | New | func New(config Config) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
swConfig := watcher.StringsConfig{
Handler: &handler{config},
}
return watcher.NewStringsWorker(swConfig)
} | go | func New(config Config) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
swConfig := watcher.StringsConfig{
Handler: &handler{config},
}
return watcher.NewStringsWorker(swConfig)
} | [
"func",
"New",
"(",
"config",
"Config",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"if",
"err",
":=",
"config",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")"... | // New returns a worker that will attempt to rescale any
// applications that might be undersized. | [
"New",
"returns",
"a",
"worker",
"that",
"will",
"attempt",
"to",
"rescale",
"any",
"applications",
"that",
"might",
"be",
"undersized",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/applicationscaler/worker.go#L41-L49 |
4,716 | juju/juju | worker/applicationscaler/worker.go | Handle | func (handler *handler) Handle(_ <-chan struct{}, applications []string) error {
return handler.config.Facade.Rescale(applications)
} | go | func (handler *handler) Handle(_ <-chan struct{}, applications []string) error {
return handler.config.Facade.Rescale(applications)
} | [
"func",
"(",
"handler",
"*",
"handler",
")",
"Handle",
"(",
"_",
"<-",
"chan",
"struct",
"{",
"}",
",",
"applications",
"[",
"]",
"string",
")",
"error",
"{",
"return",
"handler",
".",
"config",
".",
"Facade",
".",
"Rescale",
"(",
"applications",
")",
... | // Handle is part of the watcher.StringsHandler interface. | [
"Handle",
"is",
"part",
"of",
"the",
"watcher",
".",
"StringsHandler",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/applicationscaler/worker.go#L63-L65 |
4,717 | juju/juju | state/presence/presence.go | docIDInt64 | func docIDInt64(modelUUID string, localID int64) string {
return modelUUID + ":" + strconv.FormatInt(localID, 10)
} | go | func docIDInt64(modelUUID string, localID int64) string {
return modelUUID + ":" + strconv.FormatInt(localID, 10)
} | [
"func",
"docIDInt64",
"(",
"modelUUID",
"string",
",",
"localID",
"int64",
")",
"string",
"{",
"return",
"modelUUID",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"FormatInt",
"(",
"localID",
",",
"10",
")",
"\n",
"}"
] | // docIDInt64 generates a globally unique id value
// where the model uuid is prefixed to the
// given int64 localID. | [
"docIDInt64",
"generates",
"a",
"globally",
"unique",
"id",
"value",
"where",
"the",
"model",
"uuid",
"is",
"prefixed",
"to",
"the",
"given",
"int64",
"localID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L50-L52 |
4,718 | juju/juju | state/presence/presence.go | NewDeadWatcher | func NewDeadWatcher(err error) *Watcher {
var w Watcher
w.tomb.Kill(errors.Trace(err))
return &w
} | go | func NewDeadWatcher(err error) *Watcher {
var w Watcher
w.tomb.Kill(errors.Trace(err))
return &w
} | [
"func",
"NewDeadWatcher",
"(",
"err",
"error",
")",
"*",
"Watcher",
"{",
"var",
"w",
"Watcher",
"\n",
"w",
".",
"tomb",
".",
"Kill",
"(",
"errors",
".",
"Trace",
"(",
"err",
")",
")",
"\n",
"return",
"&",
"w",
"\n",
"}"
] | // NewDeadWatcher returns a new watcher that is already dead
// and always returns the given error from its Err method. | [
"NewDeadWatcher",
"returns",
"a",
"new",
"watcher",
"that",
"is",
"already",
"dead",
"and",
"always",
"returns",
"the",
"given",
"error",
"from",
"its",
"Err",
"method",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L168-L172 |
4,719 | juju/juju | state/presence/presence.go | NewWatcher | func NewWatcher(base *mgo.Collection, modelTag names.ModelTag) *Watcher {
w := &Watcher{
modelUUID: modelTag.Id(),
base: base,
pings: pingsC(base),
beings: beingsC(base),
beingKey: make(map[int64]string),
beingSeq: make(map[string]int64),
watches: make(map[string][]chan<- Change),
request: make(chan interface{}),
ignoredSeqs: make(map[int64]string),
}
w.tomb.Go(func() error {
err := w.loop()
cause := errors.Cause(err)
// tomb expects ErrDying or ErrStillAlive as
// exact values, so we need to log and unwrap
// the error first.
if err != nil && cause != tomb.ErrDying {
logger.Infof("watcher loop failed: %v", err)
}
return cause
})
return w
} | go | func NewWatcher(base *mgo.Collection, modelTag names.ModelTag) *Watcher {
w := &Watcher{
modelUUID: modelTag.Id(),
base: base,
pings: pingsC(base),
beings: beingsC(base),
beingKey: make(map[int64]string),
beingSeq: make(map[string]int64),
watches: make(map[string][]chan<- Change),
request: make(chan interface{}),
ignoredSeqs: make(map[int64]string),
}
w.tomb.Go(func() error {
err := w.loop()
cause := errors.Cause(err)
// tomb expects ErrDying or ErrStillAlive as
// exact values, so we need to log and unwrap
// the error first.
if err != nil && cause != tomb.ErrDying {
logger.Infof("watcher loop failed: %v", err)
}
return cause
})
return w
} | [
"func",
"NewWatcher",
"(",
"base",
"*",
"mgo",
".",
"Collection",
",",
"modelTag",
"names",
".",
"ModelTag",
")",
"*",
"Watcher",
"{",
"w",
":=",
"&",
"Watcher",
"{",
"modelUUID",
":",
"modelTag",
".",
"Id",
"(",
")",
",",
"base",
":",
"base",
",",
... | // NewWatcher returns a new Watcher. | [
"NewWatcher",
"returns",
"a",
"new",
"Watcher",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L175-L199 |
4,720 | juju/juju | state/presence/presence.go | Watch | func (w *Watcher) Watch(key string, ch chan<- Change) {
w.sendReq(reqWatch{key, ch})
} | go | func (w *Watcher) Watch(key string, ch chan<- Change) {
w.sendReq(reqWatch{key, ch})
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Watch",
"(",
"key",
"string",
",",
"ch",
"chan",
"<-",
"Change",
")",
"{",
"w",
".",
"sendReq",
"(",
"reqWatch",
"{",
"key",
",",
"ch",
"}",
")",
"\n",
"}"
] | // Watch starts watching the liveness of key. An event will
// be sent onto ch to report the initial status for the key, and
// from then on a new event will be sent whenever a change is
// detected. Change values sent to the channel must be consumed,
// or the whole watcher will blocked. | [
"Watch",
"starts",
"watching",
"the",
"liveness",
"of",
"key",
".",
"An",
"event",
"will",
"be",
"sent",
"onto",
"ch",
"to",
"report",
"the",
"initial",
"status",
"for",
"the",
"key",
"and",
"from",
"then",
"on",
"a",
"new",
"event",
"will",
"be",
"sen... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L260-L262 |
4,721 | juju/juju | state/presence/presence.go | Unwatch | func (w *Watcher) Unwatch(key string, ch chan<- Change) {
w.sendReq(reqUnwatch{key, ch})
} | go | func (w *Watcher) Unwatch(key string, ch chan<- Change) {
w.sendReq(reqUnwatch{key, ch})
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Unwatch",
"(",
"key",
"string",
",",
"ch",
"chan",
"<-",
"Change",
")",
"{",
"w",
".",
"sendReq",
"(",
"reqUnwatch",
"{",
"key",
",",
"ch",
"}",
")",
"\n",
"}"
] | // Unwatch stops watching the liveness of key via ch. | [
"Unwatch",
"stops",
"watching",
"the",
"liveness",
"of",
"key",
"via",
"ch",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L265-L267 |
4,722 | juju/juju | state/presence/presence.go | Sync | func (w *Watcher) Sync() {
done := make(chan bool)
w.sendReq(reqSync{done})
select {
case <-done:
case <-w.tomb.Dying():
}
} | go | func (w *Watcher) Sync() {
done := make(chan bool)
w.sendReq(reqSync{done})
select {
case <-done:
case <-w.tomb.Dying():
}
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Sync",
"(",
")",
"{",
"done",
":=",
"make",
"(",
"chan",
"bool",
")",
"\n",
"w",
".",
"sendReq",
"(",
"reqSync",
"{",
"done",
"}",
")",
"\n",
"select",
"{",
"case",
"<-",
"done",
":",
"case",
"<-",
"w",
... | // Sync forces the watcher to load new events from the database and blocks
// until all events have been dispatched. | [
"Sync",
"forces",
"the",
"watcher",
"to",
"load",
"new",
"events",
"from",
"the",
"database",
"and",
"blocks",
"until",
"all",
"events",
"have",
"been",
"dispatched",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L276-L283 |
4,723 | juju/juju | state/presence/presence.go | Alive | func (w *Watcher) Alive(key string) (bool, error) {
result := make(chan bool, 1)
w.sendReq(reqAlive{key, result})
var alive bool
select {
case alive = <-result:
case <-w.tomb.Dying():
return false, errors.Errorf("cannot check liveness: watcher is dying")
}
logger.Tracef("[%s] Alive(%q) -> %v", w.modelUUID[:6], key, alive)
return alive, nil
} | go | func (w *Watcher) Alive(key string) (bool, error) {
result := make(chan bool, 1)
w.sendReq(reqAlive{key, result})
var alive bool
select {
case alive = <-result:
case <-w.tomb.Dying():
return false, errors.Errorf("cannot check liveness: watcher is dying")
}
logger.Tracef("[%s] Alive(%q) -> %v", w.modelUUID[:6], key, alive)
return alive, nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Alive",
"(",
"key",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"result",
":=",
"make",
"(",
"chan",
"bool",
",",
"1",
")",
"\n",
"w",
".",
"sendReq",
"(",
"reqAlive",
"{",
"key",
",",
"result",
"... | // Alive returns whether the key is currently considered alive by w,
// or an error in case the watcher is dying. | [
"Alive",
"returns",
"whether",
"the",
"key",
"is",
"currently",
"considered",
"alive",
"by",
"w",
"or",
"an",
"error",
"in",
"case",
"the",
"watcher",
"is",
"dying",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L287-L298 |
4,724 | juju/juju | state/presence/presence.go | loop | func (w *Watcher) loop() error {
var err error
if w.delta, err = clockDelta(w.base); err != nil {
return errors.Trace(err)
}
// Always sync before handling request.
if err := w.sync(); err != nil {
return errors.Trace(err)
}
w.next = time.After(time.Duration(period) * time.Second)
for {
select {
case <-w.tomb.Dying():
return errors.Trace(tomb.ErrDying)
case <-w.next:
w.next = time.After(time.Duration(period) * time.Second)
syncDone := w.syncDone
w.syncDone = nil
if err := w.sync(); err != nil {
return errors.Trace(err)
}
w.flush()
for _, done := range syncDone {
close(done)
}
w.syncsSinceLastPrune++
w.checkShouldPrune()
case req := <-w.request:
w.handle(req)
w.flush()
}
}
} | go | func (w *Watcher) loop() error {
var err error
if w.delta, err = clockDelta(w.base); err != nil {
return errors.Trace(err)
}
// Always sync before handling request.
if err := w.sync(); err != nil {
return errors.Trace(err)
}
w.next = time.After(time.Duration(period) * time.Second)
for {
select {
case <-w.tomb.Dying():
return errors.Trace(tomb.ErrDying)
case <-w.next:
w.next = time.After(time.Duration(period) * time.Second)
syncDone := w.syncDone
w.syncDone = nil
if err := w.sync(); err != nil {
return errors.Trace(err)
}
w.flush()
for _, done := range syncDone {
close(done)
}
w.syncsSinceLastPrune++
w.checkShouldPrune()
case req := <-w.request:
w.handle(req)
w.flush()
}
}
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"loop",
"(",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"if",
"w",
".",
"delta",
",",
"err",
"=",
"clockDelta",
"(",
"w",
".",
"base",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trac... | // loop implements the main watcher loop. | [
"loop",
"implements",
"the",
"main",
"watcher",
"loop",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L307-L339 |
4,725 | juju/juju | state/presence/presence.go | checkShouldPrune | func (w *Watcher) checkShouldPrune() {
chanceToPrune := float64(w.syncsSinceLastPrune) * psuedoRandomFactor
if chanceToPrune < 1.0 && rand.Float64() > chanceToPrune {
return
}
// When we decide to prune, we also drop our old cached beings
logger.Debugf("watcher %q decided to prune %q and %q", w.modelUUID, w.beings.Name, w.pings.Name)
w.syncsSinceLastPrune = 0
pruner := NewPruner(w.modelUUID, w.beings, w.pings, w.delta)
err := pruner.Prune(w.ignoredSeqs)
if err != nil {
logger.Warningf("error while pruning %q for %q: %v", w.beings.Name, w.modelUUID, err)
}
} | go | func (w *Watcher) checkShouldPrune() {
chanceToPrune := float64(w.syncsSinceLastPrune) * psuedoRandomFactor
if chanceToPrune < 1.0 && rand.Float64() > chanceToPrune {
return
}
// When we decide to prune, we also drop our old cached beings
logger.Debugf("watcher %q decided to prune %q and %q", w.modelUUID, w.beings.Name, w.pings.Name)
w.syncsSinceLastPrune = 0
pruner := NewPruner(w.modelUUID, w.beings, w.pings, w.delta)
err := pruner.Prune(w.ignoredSeqs)
if err != nil {
logger.Warningf("error while pruning %q for %q: %v", w.beings.Name, w.modelUUID, err)
}
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"checkShouldPrune",
"(",
")",
"{",
"chanceToPrune",
":=",
"float64",
"(",
"w",
".",
"syncsSinceLastPrune",
")",
"*",
"psuedoRandomFactor",
"\n",
"if",
"chanceToPrune",
"<",
"1.0",
"&&",
"rand",
".",
"Float64",
"(",
")... | // checkShouldPrune looks at whether we should run a prune step this time | [
"checkShouldPrune",
"looks",
"at",
"whether",
"we",
"should",
"run",
"a",
"prune",
"step",
"this",
"time"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L369-L382 |
4,726 | juju/juju | state/presence/presence.go | decompressPings | func decompressPings(maps []map[string]int64) ([]int64, error) {
if len(maps) == 0 {
return nil, nil
}
// First step, merge all value structures together.
// Every ping has a bit field in an int64. However, bitwise-or preserves
// everything that was ever alive without having to decode them multiple times.
baseToBits := make(map[string]int64, len(maps[0]))
for i := range maps {
for hexbase, bits := range maps[i] {
baseToBits[hexbase] |= bits
}
}
sequences := make([]int64, 0, len(baseToBits)*30)
for hexbase, bits := range baseToBits {
base, err := strconv.ParseInt(hexbase, 16, 64)
if err != nil {
return nil, errors.Annotatef(err, "presence cannot parse alive key: %q", base)
}
base *= 63
for i := int64(0); i < 63 && bits > 0; i++ {
on := (bits&1 == 1)
bits >>= 1
if !on {
continue
}
seq := base + i
sequences = append(sequences, seq)
}
}
return sequences, nil
} | go | func decompressPings(maps []map[string]int64) ([]int64, error) {
if len(maps) == 0 {
return nil, nil
}
// First step, merge all value structures together.
// Every ping has a bit field in an int64. However, bitwise-or preserves
// everything that was ever alive without having to decode them multiple times.
baseToBits := make(map[string]int64, len(maps[0]))
for i := range maps {
for hexbase, bits := range maps[i] {
baseToBits[hexbase] |= bits
}
}
sequences := make([]int64, 0, len(baseToBits)*30)
for hexbase, bits := range baseToBits {
base, err := strconv.ParseInt(hexbase, 16, 64)
if err != nil {
return nil, errors.Annotatef(err, "presence cannot parse alive key: %q", base)
}
base *= 63
for i := int64(0); i < 63 && bits > 0; i++ {
on := (bits&1 == 1)
bits >>= 1
if !on {
continue
}
seq := base + i
sequences = append(sequences, seq)
}
}
return sequences, nil
} | [
"func",
"decompressPings",
"(",
"maps",
"[",
"]",
"map",
"[",
"string",
"]",
"int64",
")",
"(",
"[",
"]",
"int64",
",",
"error",
")",
"{",
"if",
"len",
"(",
"maps",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"// First step... | // decompressPings looks at a map like 'Alive' and turns it into an array of
// sequences that were seen in those maps | [
"decompressPings",
"looks",
"at",
"a",
"map",
"like",
"Alive",
"and",
"turns",
"it",
"into",
"an",
"array",
"of",
"sequences",
"that",
"were",
"seen",
"in",
"those",
"maps"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L475-L506 |
4,727 | juju/juju | state/presence/presence.go | sync | func (w *Watcher) sync() error {
session := w.pings.Database.Session.Copy()
defer session.Close()
pings, err := w.lookupPings(session)
if err != nil {
return err
}
dead, err := w.lookForDead(pings)
if err != nil {
return err
}
alive, unknownSeqs, err := w.handleAlive(pings)
if err != nil {
return err
}
err = w.lookupUnknownSeqs(unknownSeqs, dead, session)
if err != nil {
return err
}
// Pingers that were known to be alive and haven't reported
// in the last two slots are now considered dead. Dispatch
// the respective events and forget their sequences.
for seq, key := range w.beingKey {
if dead[seq] || !alive[seq] {
logger.Tracef("[%s] removing seq=%d with key %q", w.modelUUID[:6], seq, key)
delete(w.beingKey, seq)
delete(w.beingSeq, key)
for _, ch := range w.watches[key] {
w.pending = append(w.pending, event{ch, key, false})
}
}
}
return nil
} | go | func (w *Watcher) sync() error {
session := w.pings.Database.Session.Copy()
defer session.Close()
pings, err := w.lookupPings(session)
if err != nil {
return err
}
dead, err := w.lookForDead(pings)
if err != nil {
return err
}
alive, unknownSeqs, err := w.handleAlive(pings)
if err != nil {
return err
}
err = w.lookupUnknownSeqs(unknownSeqs, dead, session)
if err != nil {
return err
}
// Pingers that were known to be alive and haven't reported
// in the last two slots are now considered dead. Dispatch
// the respective events and forget their sequences.
for seq, key := range w.beingKey {
if dead[seq] || !alive[seq] {
logger.Tracef("[%s] removing seq=%d with key %q", w.modelUUID[:6], seq, key)
delete(w.beingKey, seq)
delete(w.beingSeq, key)
for _, ch := range w.watches[key] {
w.pending = append(w.pending, event{ch, key, false})
}
}
}
return nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"sync",
"(",
")",
"error",
"{",
"session",
":=",
"w",
".",
"pings",
".",
"Database",
".",
"Session",
".",
"Copy",
"(",
")",
"\n",
"defer",
"session",
".",
"Close",
"(",
")",
"\n",
"pings",
",",
"err",
":=",
... | // sync updates the watcher knowledge from the database, and
// queues events to observing channels. It fetches the last two time
// slots and compares the union of both to the in-memory state. | [
"sync",
"updates",
"the",
"watcher",
"knowledge",
"from",
"the",
"database",
"and",
"queues",
"events",
"to",
"observing",
"channels",
".",
"It",
"fetches",
"the",
"last",
"two",
"time",
"slots",
"and",
"compares",
"the",
"union",
"of",
"both",
"to",
"the",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L655-L689 |
4,728 | juju/juju | state/presence/presence.go | NewPinger | func NewPinger(base *mgo.Collection, modelTag names.ModelTag, key string, recorderFunc func() PingRecorder) *Pinger {
return &Pinger{
base: base,
pings: pingsC(base),
beingKey: key,
modelUUID: modelTag.Id(),
recorderFunc: recorderFunc,
}
} | go | func NewPinger(base *mgo.Collection, modelTag names.ModelTag, key string, recorderFunc func() PingRecorder) *Pinger {
return &Pinger{
base: base,
pings: pingsC(base),
beingKey: key,
modelUUID: modelTag.Id(),
recorderFunc: recorderFunc,
}
} | [
"func",
"NewPinger",
"(",
"base",
"*",
"mgo",
".",
"Collection",
",",
"modelTag",
"names",
".",
"ModelTag",
",",
"key",
"string",
",",
"recorderFunc",
"func",
"(",
")",
"PingRecorder",
")",
"*",
"Pinger",
"{",
"return",
"&",
"Pinger",
"{",
"base",
":",
... | // NewPinger returns a new Pinger to report that key is alive.
// It starts reporting after Start is called. | [
"NewPinger",
"returns",
"a",
"new",
"Pinger",
"to",
"report",
"that",
"key",
"is",
"alive",
".",
"It",
"starts",
"reporting",
"after",
"Start",
"is",
"called",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L715-L723 |
4,729 | juju/juju | state/presence/presence.go | Start | func (p *Pinger) Start() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.started {
return errors.Errorf("pinger already started")
}
p.tomb = tomb.Tomb{}
if err := p.prepare(); err != nil {
return errors.Trace(err)
}
logger.Tracef("[%s] starting pinger for %q with seq=%d", p.modelUUID[:6], p.beingKey, p.beingSeq)
if err := p.ping(); err != nil {
return errors.Trace(err)
}
p.started = true
p.tomb.Go(func() error {
err := p.loop()
cause := errors.Cause(err)
// tomb expects ErrDying or ErrStillAlive as
// exact values, so we need to log and unwrap
// the error first.
if err != nil && cause != tomb.ErrDying {
logger.Infof("pinger loop failed: %v", err)
}
return cause
})
return nil
} | go | func (p *Pinger) Start() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.started {
return errors.Errorf("pinger already started")
}
p.tomb = tomb.Tomb{}
if err := p.prepare(); err != nil {
return errors.Trace(err)
}
logger.Tracef("[%s] starting pinger for %q with seq=%d", p.modelUUID[:6], p.beingKey, p.beingSeq)
if err := p.ping(); err != nil {
return errors.Trace(err)
}
p.started = true
p.tomb.Go(func() error {
err := p.loop()
cause := errors.Cause(err)
// tomb expects ErrDying or ErrStillAlive as
// exact values, so we need to log and unwrap
// the error first.
if err != nil && cause != tomb.ErrDying {
logger.Infof("pinger loop failed: %v", err)
}
return cause
})
return nil
} | [
"func",
"(",
"p",
"*",
"Pinger",
")",
"Start",
"(",
")",
"error",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"p",
".",
"started",
"{",
"return",
"errors",
".",
"Errorf",
"("... | // Start starts periodically reporting that p's key is alive. | [
"Start",
"starts",
"periodically",
"reporting",
"that",
"p",
"s",
"key",
"is",
"alive",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L726-L753 |
4,730 | juju/juju | state/presence/presence.go | Stop | func (p *Pinger) Stop() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.started {
logger.Tracef("[%s] stopping pinger for %q with seq=%d", p.modelUUID[:6], p.beingKey, p.beingSeq)
}
p.tomb.Kill(nil)
err := p.tomb.Wait()
// TODO ping one more time to guarantee a late timeout.
p.started = false
return errors.Trace(err)
} | go | func (p *Pinger) Stop() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.started {
logger.Tracef("[%s] stopping pinger for %q with seq=%d", p.modelUUID[:6], p.beingKey, p.beingSeq)
}
p.tomb.Kill(nil)
err := p.tomb.Wait()
// TODO ping one more time to guarantee a late timeout.
p.started = false
return errors.Trace(err)
} | [
"func",
"(",
"p",
"*",
"Pinger",
")",
"Stop",
"(",
")",
"error",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"p",
".",
"started",
"{",
"logger",
".",
"Tracef",
"(",
"\"",
"... | // Stop stops p's periodical ping.
// Watchers will not notice p has stopped pinging until the
// previous ping times out. | [
"Stop",
"stops",
"p",
"s",
"periodical",
"ping",
".",
"Watchers",
"will",
"not",
"notice",
"p",
"has",
"stopped",
"pinging",
"until",
"the",
"previous",
"ping",
"times",
"out",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L769-L781 |
4,731 | juju/juju | state/presence/presence.go | killStarted | func (p *Pinger) killStarted() error {
p.tomb.Kill(nil)
killErr := p.tomb.Wait()
p.started = false
slot := p.lastSlot
udoc := bson.D{
{"$set", bson.D{{"slot", slot}}},
{"$inc", bson.D{{"dead." + p.fieldKey, p.fieldBit}}}}
session := p.pings.Database.Session.Copy()
defer session.Close()
pings := p.pings.With(session)
if _, err := pings.UpsertId(docIDInt64(p.modelUUID, slot), udoc); err != nil {
return errors.Trace(err)
}
return errors.Trace(killErr)
} | go | func (p *Pinger) killStarted() error {
p.tomb.Kill(nil)
killErr := p.tomb.Wait()
p.started = false
slot := p.lastSlot
udoc := bson.D{
{"$set", bson.D{{"slot", slot}}},
{"$inc", bson.D{{"dead." + p.fieldKey, p.fieldBit}}}}
session := p.pings.Database.Session.Copy()
defer session.Close()
pings := p.pings.With(session)
if _, err := pings.UpsertId(docIDInt64(p.modelUUID, slot), udoc); err != nil {
return errors.Trace(err)
}
return errors.Trace(killErr)
} | [
"func",
"(",
"p",
"*",
"Pinger",
")",
"killStarted",
"(",
")",
"error",
"{",
"p",
".",
"tomb",
".",
"Kill",
"(",
"nil",
")",
"\n",
"killErr",
":=",
"p",
".",
"tomb",
".",
"Wait",
"(",
")",
"\n",
"p",
".",
"started",
"=",
"false",
"\n\n",
"slot"... | // killStarted kills the pinger while it is running, by first
// stopping it and then recording in the last pinged slot that
// the pinger was killed. | [
"killStarted",
"kills",
"the",
"pinger",
"while",
"it",
"is",
"running",
"by",
"first",
"stopping",
"it",
"and",
"then",
"recording",
"in",
"the",
"last",
"pinged",
"slot",
"that",
"the",
"pinger",
"was",
"killed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L799-L815 |
4,732 | juju/juju | state/presence/presence.go | killStopped | func (p *Pinger) killStopped() error {
if err := p.prepare(); err != nil {
return err
}
// TODO(perrito666) 2016-05-02 lp:1558657
slot := timeSlot(time.Now(), p.delta)
udoc := bson.D{
{"$set", bson.D{{"slot", slot}}},
{"$inc", bson.D{
{"dead." + p.fieldKey, p.fieldBit},
{"alive." + p.fieldKey, p.fieldBit},
}}}
session := p.pings.Database.Session.Copy()
defer session.Close()
pings := p.pings.With(session)
_, err := pings.UpsertId(docIDInt64(p.modelUUID, slot), udoc)
return errors.Trace(err)
} | go | func (p *Pinger) killStopped() error {
if err := p.prepare(); err != nil {
return err
}
// TODO(perrito666) 2016-05-02 lp:1558657
slot := timeSlot(time.Now(), p.delta)
udoc := bson.D{
{"$set", bson.D{{"slot", slot}}},
{"$inc", bson.D{
{"dead." + p.fieldKey, p.fieldBit},
{"alive." + p.fieldKey, p.fieldBit},
}}}
session := p.pings.Database.Session.Copy()
defer session.Close()
pings := p.pings.With(session)
_, err := pings.UpsertId(docIDInt64(p.modelUUID, slot), udoc)
return errors.Trace(err)
} | [
"func",
"(",
"p",
"*",
"Pinger",
")",
"killStopped",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"p",
".",
"prepare",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// TODO(perrito666) 2016-05-02 lp:1558657",
"slot",
":=",
"t... | // killStopped kills the pinger while it is not running, by
// first allocating a new sequence, and then atomically recording
// the new sequence both as alive and dead at once. | [
"killStopped",
"kills",
"the",
"pinger",
"while",
"it",
"is",
"not",
"running",
"by",
"first",
"allocating",
"a",
"new",
"sequence",
"and",
"then",
"atomically",
"recording",
"the",
"new",
"sequence",
"both",
"as",
"alive",
"and",
"dead",
"at",
"once",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L820-L837 |
4,733 | juju/juju | state/presence/presence.go | loop | func (p *Pinger) loop() error {
for {
select {
case <-p.tomb.Dying():
return errors.Trace(tomb.ErrDying)
case <-time.After(time.Duration(float64(period+1)*0.75) * time.Second):
if err := p.ping(); err != nil {
return errors.Trace(err)
}
}
}
} | go | func (p *Pinger) loop() error {
for {
select {
case <-p.tomb.Dying():
return errors.Trace(tomb.ErrDying)
case <-time.After(time.Duration(float64(period+1)*0.75) * time.Second):
if err := p.ping(); err != nil {
return errors.Trace(err)
}
}
}
} | [
"func",
"(",
"p",
"*",
"Pinger",
")",
"loop",
"(",
")",
"error",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"p",
".",
"tomb",
".",
"Dying",
"(",
")",
":",
"return",
"errors",
".",
"Trace",
"(",
"tomb",
".",
"ErrDying",
")",
"\n",
"case",
"<-... | // loop is the main pinger loop that runs while it is
// in started state. | [
"loop",
"is",
"the",
"main",
"pinger",
"loop",
"that",
"runs",
"while",
"it",
"is",
"in",
"started",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L841-L852 |
4,734 | juju/juju | state/presence/presence.go | prepare | func (p *Pinger) prepare() error {
change := mgo.Change{
Update: bson.D{{"$inc", bson.D{{"seq", int64(1)}}}},
Upsert: true,
ReturnNew: true,
}
session := p.base.Database.Session.Copy()
defer session.Close()
base := p.base.With(session)
seqs := seqsC(base)
var seq struct{ Seq int64 }
seqID := docIDStr(p.modelUUID, "beings")
if _, err := seqs.FindId(seqID).Apply(change, &seq); err != nil {
return errors.Trace(err)
}
p.beingSeq = seq.Seq
p.fieldKey = fmt.Sprintf("%x", p.beingSeq/63)
p.fieldBit = 1 << uint64(p.beingSeq%63)
p.lastSlot = 0
beings := beingsC(base)
return errors.Trace(beings.Insert(
beingInfo{
DocID: docIDInt64(p.modelUUID, p.beingSeq),
Seq: p.beingSeq,
Key: p.beingKey,
},
))
} | go | func (p *Pinger) prepare() error {
change := mgo.Change{
Update: bson.D{{"$inc", bson.D{{"seq", int64(1)}}}},
Upsert: true,
ReturnNew: true,
}
session := p.base.Database.Session.Copy()
defer session.Close()
base := p.base.With(session)
seqs := seqsC(base)
var seq struct{ Seq int64 }
seqID := docIDStr(p.modelUUID, "beings")
if _, err := seqs.FindId(seqID).Apply(change, &seq); err != nil {
return errors.Trace(err)
}
p.beingSeq = seq.Seq
p.fieldKey = fmt.Sprintf("%x", p.beingSeq/63)
p.fieldBit = 1 << uint64(p.beingSeq%63)
p.lastSlot = 0
beings := beingsC(base)
return errors.Trace(beings.Insert(
beingInfo{
DocID: docIDInt64(p.modelUUID, p.beingSeq),
Seq: p.beingSeq,
Key: p.beingKey,
},
))
} | [
"func",
"(",
"p",
"*",
"Pinger",
")",
"prepare",
"(",
")",
"error",
"{",
"change",
":=",
"mgo",
".",
"Change",
"{",
"Update",
":",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"bson",
".",
"D",
"{",
"{",
"\"",
"\"",
",",
"int64",
"(",
"1",
... | // prepare allocates a new unique sequence for the
// pinger key and prepares the pinger to use it. | [
"prepare",
"allocates",
"a",
"new",
"unique",
"sequence",
"for",
"the",
"pinger",
"key",
"and",
"prepares",
"the",
"pinger",
"to",
"use",
"it",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L856-L883 |
4,735 | juju/juju | state/presence/presence.go | ping | func (p *Pinger) ping() (err error) {
logger.Tracef("[%s] pinging %q with seq=%d", p.modelUUID[:6], p.beingKey, p.beingSeq)
defer func() {
// If the session is killed from underneath us, it panics when we
// try to copy it, so deal with that here.
if v := recover(); v != nil {
err = fmt.Errorf("%v", v)
}
}()
if p.delta == 0 {
session := p.pings.Database.Session.Copy()
defer session.Close()
base := p.base.With(session)
delta, err := clockDelta(base)
if err != nil {
return errors.Trace(err)
}
p.delta = delta
}
// TODO(perrito666) 2016-05-02 lp:1558657
slot := timeSlot(time.Now(), p.delta)
if slot == p.lastSlot {
// Never, ever, ping the same slot twice.
// The increment below would corrupt the slot.
return nil
}
p.lastSlot = slot
p.recorderFunc().Ping(p.modelUUID, slot, p.fieldKey, p.fieldBit)
return errors.Trace(err)
} | go | func (p *Pinger) ping() (err error) {
logger.Tracef("[%s] pinging %q with seq=%d", p.modelUUID[:6], p.beingKey, p.beingSeq)
defer func() {
// If the session is killed from underneath us, it panics when we
// try to copy it, so deal with that here.
if v := recover(); v != nil {
err = fmt.Errorf("%v", v)
}
}()
if p.delta == 0 {
session := p.pings.Database.Session.Copy()
defer session.Close()
base := p.base.With(session)
delta, err := clockDelta(base)
if err != nil {
return errors.Trace(err)
}
p.delta = delta
}
// TODO(perrito666) 2016-05-02 lp:1558657
slot := timeSlot(time.Now(), p.delta)
if slot == p.lastSlot {
// Never, ever, ping the same slot twice.
// The increment below would corrupt the slot.
return nil
}
p.lastSlot = slot
p.recorderFunc().Ping(p.modelUUID, slot, p.fieldKey, p.fieldBit)
return errors.Trace(err)
} | [
"func",
"(",
"p",
"*",
"Pinger",
")",
"ping",
"(",
")",
"(",
"err",
"error",
")",
"{",
"logger",
".",
"Tracef",
"(",
"\"",
"\"",
",",
"p",
".",
"modelUUID",
"[",
":",
"6",
"]",
",",
"p",
".",
"beingKey",
",",
"p",
".",
"beingSeq",
")",
"\n",
... | // ping records updates the current time slot with the
// sequence in use by the pinger. | [
"ping",
"records",
"updates",
"the",
"current",
"time",
"slot",
"with",
"the",
"sequence",
"in",
"use",
"by",
"the",
"pinger",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L887-L916 |
4,736 | juju/juju | state/presence/presence.go | clockDelta | func clockDelta(c *mgo.Collection) (time.Duration, error) {
var server struct {
time.Time `bson:"retval"`
}
var isMaster struct {
LocalTime time.Time `bson:"localTime"`
}
var after time.Time
var before time.Time
var serverDelay time.Duration
supportsMasterLocalTime := true
session := c.Database.Session.Copy()
defer session.Close()
db := c.Database.With(session)
for i := 0; i < 10; i++ {
if supportsMasterLocalTime {
// Try isMaster.localTime, which is present since MongoDB 2.2
// and does not require admin privileges.
// TODO(perrito666) 2016-05-02 lp:1558657
before = time.Now()
err := db.Run("isMaster", &isMaster)
// TODO(perrito666) 2016-05-02 lp:1558657
after = time.Now()
if err != nil {
return 0, errors.Trace(err)
}
if isMaster.LocalTime.IsZero() {
supportsMasterLocalTime = false
continue
} else {
serverDelay = isMaster.LocalTime.Sub(before)
}
} else {
// If MongoDB doesn't have localTime as part of
// isMaster result, it means that the server is likely
// a MongoDB older than 2.2.
//
// Fallback to 'eval' works fine on versions older than
// 2.4 where it does not require admin privileges.
//
// NOTE: 'eval' takes a global write lock unless you
// specify 'nolock' (which we are not doing below, for
// no apparent reason), so it is quite likely that the
// eval could take a relatively long time to acquire
// the lock and thus cause a retry on the callDelay
// check below on a busy server.
// TODO(perrito666) 2016-05-02 lp:1558657
before = time.Now()
err := db.Run(bson.D{{"$eval", "function() { return new Date(); }"}}, &server)
// TODO(perrito666) 2016-05-02 lp:1558657
after = time.Now()
if err != nil {
return 0, errors.Trace(err)
}
serverDelay = server.Sub(before)
}
// If the call to the server takes longer than a few seconds we
// retry it a couple more times before giving up. It is unclear
// why the retry would help at all here.
//
// If the server takes longer than the specified amount of time
// on every single try, then we simply give up.
callDelay := after.Sub(before)
if callDelay > 5*time.Second {
continue
}
return serverDelay, nil
}
return 0, errors.Errorf("cannot synchronize clock with database server")
} | go | func clockDelta(c *mgo.Collection) (time.Duration, error) {
var server struct {
time.Time `bson:"retval"`
}
var isMaster struct {
LocalTime time.Time `bson:"localTime"`
}
var after time.Time
var before time.Time
var serverDelay time.Duration
supportsMasterLocalTime := true
session := c.Database.Session.Copy()
defer session.Close()
db := c.Database.With(session)
for i := 0; i < 10; i++ {
if supportsMasterLocalTime {
// Try isMaster.localTime, which is present since MongoDB 2.2
// and does not require admin privileges.
// TODO(perrito666) 2016-05-02 lp:1558657
before = time.Now()
err := db.Run("isMaster", &isMaster)
// TODO(perrito666) 2016-05-02 lp:1558657
after = time.Now()
if err != nil {
return 0, errors.Trace(err)
}
if isMaster.LocalTime.IsZero() {
supportsMasterLocalTime = false
continue
} else {
serverDelay = isMaster.LocalTime.Sub(before)
}
} else {
// If MongoDB doesn't have localTime as part of
// isMaster result, it means that the server is likely
// a MongoDB older than 2.2.
//
// Fallback to 'eval' works fine on versions older than
// 2.4 where it does not require admin privileges.
//
// NOTE: 'eval' takes a global write lock unless you
// specify 'nolock' (which we are not doing below, for
// no apparent reason), so it is quite likely that the
// eval could take a relatively long time to acquire
// the lock and thus cause a retry on the callDelay
// check below on a busy server.
// TODO(perrito666) 2016-05-02 lp:1558657
before = time.Now()
err := db.Run(bson.D{{"$eval", "function() { return new Date(); }"}}, &server)
// TODO(perrito666) 2016-05-02 lp:1558657
after = time.Now()
if err != nil {
return 0, errors.Trace(err)
}
serverDelay = server.Sub(before)
}
// If the call to the server takes longer than a few seconds we
// retry it a couple more times before giving up. It is unclear
// why the retry would help at all here.
//
// If the server takes longer than the specified amount of time
// on every single try, then we simply give up.
callDelay := after.Sub(before)
if callDelay > 5*time.Second {
continue
}
return serverDelay, nil
}
return 0, errors.Errorf("cannot synchronize clock with database server")
} | [
"func",
"clockDelta",
"(",
"c",
"*",
"mgo",
".",
"Collection",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"var",
"server",
"struct",
"{",
"time",
".",
"Time",
"`bson:\"retval\"`",
"\n",
"}",
"\n",
"var",
"isMaster",
"struct",
"{",
"Loca... | // clockDelta returns the approximate skew between
// the local clock and the database clock. | [
"clockDelta",
"returns",
"the",
"approximate",
"skew",
"between",
"the",
"local",
"clock",
"and",
"the",
"database",
"clock",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L927-L996 |
4,737 | juju/juju | state/presence/presence.go | timeSlot | func timeSlot(now time.Time, delta time.Duration) int64 {
fakeMutex.Lock()
fake := !fakeNow.IsZero()
if fake {
now = fakeNow
}
slot := now.Add(delta).Unix()
slot -= slot % period
if fake {
slot += int64(fakeOffset) * period
}
fakeMutex.Unlock()
return slot
} | go | func timeSlot(now time.Time, delta time.Duration) int64 {
fakeMutex.Lock()
fake := !fakeNow.IsZero()
if fake {
now = fakeNow
}
slot := now.Add(delta).Unix()
slot -= slot % period
if fake {
slot += int64(fakeOffset) * period
}
fakeMutex.Unlock()
return slot
} | [
"func",
"timeSlot",
"(",
"now",
"time",
".",
"Time",
",",
"delta",
"time",
".",
"Duration",
")",
"int64",
"{",
"fakeMutex",
".",
"Lock",
"(",
")",
"\n",
"fake",
":=",
"!",
"fakeNow",
".",
"IsZero",
"(",
")",
"\n",
"if",
"fake",
"{",
"now",
"=",
"... | // timeSlot returns the current time slot, in seconds since the
// epoch, for the provided now time. The delta skew is applied
// to the now time to improve the synchronization with a
// centrally agreed time.
//
// The result of this method may be manipulated for test purposes
// by fakeTimeSlot and realTimeSlot. | [
"timeSlot",
"returns",
"the",
"current",
"time",
"slot",
"in",
"seconds",
"since",
"the",
"epoch",
"for",
"the",
"provided",
"now",
"time",
".",
"The",
"delta",
"skew",
"is",
"applied",
"to",
"the",
"now",
"time",
"to",
"improve",
"the",
"synchronization",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L1005-L1018 |
4,738 | juju/juju | state/presence/presence.go | realTimeSlot | func realTimeSlot() {
fakeMutex.Lock()
fakeNow = time.Time{}
fakeOffset = 0
fakeMutex.Unlock()
logger.Infof("not faking presence time. Real time slot in use.")
} | go | func realTimeSlot() {
fakeMutex.Lock()
fakeNow = time.Time{}
fakeOffset = 0
fakeMutex.Unlock()
logger.Infof("not faking presence time. Real time slot in use.")
} | [
"func",
"realTimeSlot",
"(",
")",
"{",
"fakeMutex",
".",
"Lock",
"(",
")",
"\n",
"fakeNow",
"=",
"time",
".",
"Time",
"{",
"}",
"\n",
"fakeOffset",
"=",
"0",
"\n",
"fakeMutex",
".",
"Unlock",
"(",
")",
"\n",
"logger",
".",
"Infof",
"(",
"\"",
"\"",... | // realTimeSlot disables the hardcoding introduced by fakeTimeSlot. | [
"realTimeSlot",
"disables",
"the",
"hardcoding",
"introduced",
"by",
"fakeTimeSlot",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L1041-L1047 |
4,739 | juju/juju | state/presence/presence.go | RemovePresenceForModel | func RemovePresenceForModel(base *mgo.Collection, modelTag names.ModelTag) error {
errs := make([]error, 0)
for _, f := range []func(*mgo.Collection) *mgo.Collection{pingsC, beingsC, seqsC} {
err := removeModelFromCollection(f(base), modelTag.Id())
if err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return errors.Errorf("errors removing presence for model %q: %v", modelTag.Id(), errs)
}
return nil
} | go | func RemovePresenceForModel(base *mgo.Collection, modelTag names.ModelTag) error {
errs := make([]error, 0)
for _, f := range []func(*mgo.Collection) *mgo.Collection{pingsC, beingsC, seqsC} {
err := removeModelFromCollection(f(base), modelTag.Id())
if err != nil {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return errors.Errorf("errors removing presence for model %q: %v", modelTag.Id(), errs)
}
return nil
} | [
"func",
"RemovePresenceForModel",
"(",
"base",
"*",
"mgo",
".",
"Collection",
",",
"modelTag",
"names",
".",
"ModelTag",
")",
"error",
"{",
"errs",
":=",
"make",
"(",
"[",
"]",
"error",
",",
"0",
")",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"[",
... | // RemovePresenceForModel removes all of the records of entities for a given model
// across all of the collections. | [
"RemovePresenceForModel",
"removes",
"all",
"of",
"the",
"records",
"of",
"entities",
"for",
"a",
"given",
"model",
"across",
"all",
"of",
"the",
"collections",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/presence.go#L1078-L1090 |
4,740 | juju/juju | cmd/juju/space/space.go | CheckName | func CheckName(name string) (string, error) {
// Validate given name.
if !names.IsValidSpace(name) {
return "", errors.Errorf("%q is not a valid space name", name)
}
return name, nil
} | go | func CheckName(name string) (string, error) {
// Validate given name.
if !names.IsValidSpace(name) {
return "", errors.Errorf("%q is not a valid space name", name)
}
return name, nil
} | [
"func",
"CheckName",
"(",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Validate given name.",
"if",
"!",
"names",
".",
"IsValidSpace",
"(",
"name",
")",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",... | // CheckName checks whether name is a valid space name. | [
"CheckName",
"checks",
"whether",
"name",
"is",
"a",
"valid",
"space",
"name",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/space/space.go#L86-L92 |
4,741 | juju/juju | cmd/juju/space/space.go | CheckCIDRs | func CheckCIDRs(args []string, cidrsOptional bool) (set.Strings, error) {
// Validate any given CIDRs.
CIDRs := set.NewStrings()
for _, arg := range args {
_, ipNet, err := net.ParseCIDR(arg)
if err != nil {
logger.Debugf("cannot parse %q: %v", arg, err)
return CIDRs, errors.Errorf("%q is not a valid CIDR", arg)
}
cidr := ipNet.String()
if CIDRs.Contains(cidr) {
if cidr == arg {
return CIDRs, errors.Errorf("duplicate subnet %q specified", cidr)
}
return CIDRs, errors.Errorf("subnet %q overlaps with %q", arg, cidr)
}
CIDRs.Add(cidr)
}
if CIDRs.IsEmpty() && !cidrsOptional {
return CIDRs, errors.New("CIDRs required but not provided")
}
return CIDRs, nil
} | go | func CheckCIDRs(args []string, cidrsOptional bool) (set.Strings, error) {
// Validate any given CIDRs.
CIDRs := set.NewStrings()
for _, arg := range args {
_, ipNet, err := net.ParseCIDR(arg)
if err != nil {
logger.Debugf("cannot parse %q: %v", arg, err)
return CIDRs, errors.Errorf("%q is not a valid CIDR", arg)
}
cidr := ipNet.String()
if CIDRs.Contains(cidr) {
if cidr == arg {
return CIDRs, errors.Errorf("duplicate subnet %q specified", cidr)
}
return CIDRs, errors.Errorf("subnet %q overlaps with %q", arg, cidr)
}
CIDRs.Add(cidr)
}
if CIDRs.IsEmpty() && !cidrsOptional {
return CIDRs, errors.New("CIDRs required but not provided")
}
return CIDRs, nil
} | [
"func",
"CheckCIDRs",
"(",
"args",
"[",
"]",
"string",
",",
"cidrsOptional",
"bool",
")",
"(",
"set",
".",
"Strings",
",",
"error",
")",
"{",
"// Validate any given CIDRs.",
"CIDRs",
":=",
"set",
".",
"NewStrings",
"(",
")",
"\n",
"for",
"_",
",",
"arg",... | // CheckCIDRs parses the list of strings as CIDRs, checking for
// correct formatting, no duplication and no overlaps. Returns error
// if no CIDRs are provided, unless cidrsOptional is true. | [
"CheckCIDRs",
"parses",
"the",
"list",
"of",
"strings",
"as",
"CIDRs",
"checking",
"for",
"correct",
"formatting",
"no",
"duplication",
"and",
"no",
"overlaps",
".",
"Returns",
"error",
"if",
"no",
"CIDRs",
"are",
"provided",
"unless",
"cidrsOptional",
"is",
"... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/space/space.go#L97-L121 |
4,742 | juju/juju | cmd/juju/space/space.go | NewAPI | func (c *SpaceCommandBase) NewAPI() (SpaceAPI, error) {
if c.api != nil {
// Already addd.
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: spaces.NewAPI(root),
}
return shim, nil
} | go | func (c *SpaceCommandBase) NewAPI() (SpaceAPI, error) {
if c.api != nil {
// Already addd.
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: spaces.NewAPI(root),
}
return shim, nil
} | [
"func",
"(",
"c",
"*",
"SpaceCommandBase",
")",
"NewAPI",
"(",
")",
"(",
"SpaceAPI",
",",
"error",
")",
"{",
"if",
"c",
".",
"api",
"!=",
"nil",
"{",
"// Already addd.",
"return",
"c",
".",
"api",
",",
"nil",
"\n",
"}",
"\n",
"root",
",",
"err",
... | // NewAPI returns a SpaceAPI for the root api endpoint that the
// environment command returns. | [
"NewAPI",
"returns",
"a",
"SpaceAPI",
"for",
"the",
"root",
"api",
"endpoint",
"that",
"the",
"environment",
"command",
"returns",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/space/space.go#L150-L166 |
4,743 | juju/juju | worker/uniter/resolver/loop.go | updateCharmDir | func updateCharmDir(opState operation.State, guard fortress.Guard, abort fortress.Abort) error {
var changing bool
// Determine if the charm content is changing.
if opState.Kind == operation.Install || opState.Kind == operation.Upgrade {
changing = true
} else if opState.Kind == operation.RunHook && opState.Hook != nil && opState.Hook.Kind == hooks.UpgradeCharm {
changing = true
}
available := opState.Started && !opState.Stopped && !changing
logger.Tracef("charmdir: available=%v opState: started=%v stopped=%v changing=%v",
available, opState.Started, opState.Stopped, changing)
if available {
return guard.Unlock()
} else {
return guard.Lockdown(abort)
}
} | go | func updateCharmDir(opState operation.State, guard fortress.Guard, abort fortress.Abort) error {
var changing bool
// Determine if the charm content is changing.
if opState.Kind == operation.Install || opState.Kind == operation.Upgrade {
changing = true
} else if opState.Kind == operation.RunHook && opState.Hook != nil && opState.Hook.Kind == hooks.UpgradeCharm {
changing = true
}
available := opState.Started && !opState.Stopped && !changing
logger.Tracef("charmdir: available=%v opState: started=%v stopped=%v changing=%v",
available, opState.Started, opState.Stopped, changing)
if available {
return guard.Unlock()
} else {
return guard.Lockdown(abort)
}
} | [
"func",
"updateCharmDir",
"(",
"opState",
"operation",
".",
"State",
",",
"guard",
"fortress",
".",
"Guard",
",",
"abort",
"fortress",
".",
"Abort",
")",
"error",
"{",
"var",
"changing",
"bool",
"\n\n",
"// Determine if the charm content is changing.",
"if",
"opSt... | // updateCharmDir sets charm directory availability for sharing among
// concurrent workers according to local operation state. | [
"updateCharmDir",
"sets",
"charm",
"directory",
"availability",
"for",
"sharing",
"among",
"concurrent",
"workers",
"according",
"to",
"local",
"operation",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/resolver/loop.go#L111-L129 |
4,744 | juju/juju | caas/kubernetes/provider/mocks/storagev1_mock.go | NewMockStorageV1Interface | func NewMockStorageV1Interface(ctrl *gomock.Controller) *MockStorageV1Interface {
mock := &MockStorageV1Interface{ctrl: ctrl}
mock.recorder = &MockStorageV1InterfaceMockRecorder{mock}
return mock
} | go | func NewMockStorageV1Interface(ctrl *gomock.Controller) *MockStorageV1Interface {
mock := &MockStorageV1Interface{ctrl: ctrl}
mock.recorder = &MockStorageV1InterfaceMockRecorder{mock}
return mock
} | [
"func",
"NewMockStorageV1Interface",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockStorageV1Interface",
"{",
"mock",
":=",
"&",
"MockStorageV1Interface",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockStorageV1Interf... | // NewMockStorageV1Interface creates a new mock instance | [
"NewMockStorageV1Interface",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/storagev1_mock.go#L31-L35 |
4,745 | juju/juju | caas/kubernetes/provider/mocks/storagev1_mock.go | StorageClasses | func (m *MockStorageV1Interface) StorageClasses() v11.StorageClassInterface {
ret := m.ctrl.Call(m, "StorageClasses")
ret0, _ := ret[0].(v11.StorageClassInterface)
return ret0
} | go | func (m *MockStorageV1Interface) StorageClasses() v11.StorageClassInterface {
ret := m.ctrl.Call(m, "StorageClasses")
ret0, _ := ret[0].(v11.StorageClassInterface)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockStorageV1Interface",
")",
"StorageClasses",
"(",
")",
"v11",
".",
"StorageClassInterface",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"... | // StorageClasses mocks base method | [
"StorageClasses",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/storagev1_mock.go#L55-L59 |
4,746 | juju/juju | caas/kubernetes/provider/mocks/storagev1_mock.go | NewMockStorageClassInterface | func NewMockStorageClassInterface(ctrl *gomock.Controller) *MockStorageClassInterface {
mock := &MockStorageClassInterface{ctrl: ctrl}
mock.recorder = &MockStorageClassInterfaceMockRecorder{mock}
return mock
} | go | func NewMockStorageClassInterface(ctrl *gomock.Controller) *MockStorageClassInterface {
mock := &MockStorageClassInterface{ctrl: ctrl}
mock.recorder = &MockStorageClassInterfaceMockRecorder{mock}
return mock
} | [
"func",
"NewMockStorageClassInterface",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockStorageClassInterface",
"{",
"mock",
":=",
"&",
"MockStorageClassInterface",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockStorag... | // NewMockStorageClassInterface creates a new mock instance | [
"NewMockStorageClassInterface",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/storagev1_mock.go#L78-L82 |
4,747 | juju/juju | state/modelmigration.go | Phase | func (mig *modelMigration) Phase() (migration.Phase, error) {
phase, ok := migration.ParsePhase(mig.statusDoc.Phase)
if !ok {
return phase, errors.Errorf("invalid phase in DB: %v", mig.statusDoc.Phase)
}
return phase, nil
} | go | func (mig *modelMigration) Phase() (migration.Phase, error) {
phase, ok := migration.ParsePhase(mig.statusDoc.Phase)
if !ok {
return phase, errors.Errorf("invalid phase in DB: %v", mig.statusDoc.Phase)
}
return phase, nil
} | [
"func",
"(",
"mig",
"*",
"modelMigration",
")",
"Phase",
"(",
")",
"(",
"migration",
".",
"Phase",
",",
"error",
")",
"{",
"phase",
",",
"ok",
":=",
"migration",
".",
"ParsePhase",
"(",
"mig",
".",
"statusDoc",
".",
"Phase",
")",
"\n",
"if",
"!",
"... | // Phase implements ModelMigration. | [
"Phase",
"implements",
"ModelMigration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L250-L256 |
4,748 | juju/juju | state/modelmigration.go | TargetInfo | func (mig *modelMigration) TargetInfo() (*migration.TargetInfo, error) {
authTag, err := names.ParseUserTag(mig.doc.TargetAuthTag)
if err != nil {
return nil, errors.Trace(err)
}
macs, err := jsonToMacaroons(mig.doc.TargetMacaroons)
if err != nil {
return nil, errors.Trace(err)
}
return &migration.TargetInfo{
ControllerTag: names.NewControllerTag(mig.doc.TargetController),
ControllerAlias: mig.doc.TargetControllerAlias,
Addrs: mig.doc.TargetAddrs,
CACert: mig.doc.TargetCACert,
AuthTag: authTag,
Password: mig.doc.TargetPassword,
Macaroons: macs,
}, nil
} | go | func (mig *modelMigration) TargetInfo() (*migration.TargetInfo, error) {
authTag, err := names.ParseUserTag(mig.doc.TargetAuthTag)
if err != nil {
return nil, errors.Trace(err)
}
macs, err := jsonToMacaroons(mig.doc.TargetMacaroons)
if err != nil {
return nil, errors.Trace(err)
}
return &migration.TargetInfo{
ControllerTag: names.NewControllerTag(mig.doc.TargetController),
ControllerAlias: mig.doc.TargetControllerAlias,
Addrs: mig.doc.TargetAddrs,
CACert: mig.doc.TargetCACert,
AuthTag: authTag,
Password: mig.doc.TargetPassword,
Macaroons: macs,
}, nil
} | [
"func",
"(",
"mig",
"*",
"modelMigration",
")",
"TargetInfo",
"(",
")",
"(",
"*",
"migration",
".",
"TargetInfo",
",",
"error",
")",
"{",
"authTag",
",",
"err",
":=",
"names",
".",
"ParseUserTag",
"(",
"mig",
".",
"doc",
".",
"TargetAuthTag",
")",
"\n"... | // TargetInfo implements ModelMigration. | [
"TargetInfo",
"implements",
"ModelMigration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L274-L292 |
4,749 | juju/juju | state/modelmigration.go | SetPhase | func (mig *modelMigration) SetPhase(nextPhase migration.Phase) error {
now := mig.st.clock().Now().UnixNano()
phase, err := mig.Phase()
if err != nil {
return errors.Trace(err)
}
if nextPhase == phase {
return nil // Already at that phase. Nothing to do.
}
if !phase.CanTransitionTo(nextPhase) {
return errors.Errorf("illegal phase change: %s -> %s", phase, nextPhase)
}
nextDoc := mig.statusDoc
nextDoc.Phase = nextPhase.String()
nextDoc.PhaseChangedTime = now
update := bson.M{
"phase": nextDoc.Phase,
"phase-changed-time": now,
}
if nextPhase == migration.SUCCESS {
nextDoc.SuccessTime = now
update["success-time"] = now
}
ops, err := migStatusHistoryAndOps(mig.st, nextPhase, now, mig.StatusMessage())
if err != nil {
return errors.Trace(err)
}
// If the migration aborted, make the model active again.
if nextPhase == migration.ABORTDONE {
ops = append(ops, txn.Op{
C: modelsC,
Id: mig.doc.ModelUUID,
Assert: txn.DocExists,
Update: bson.M{
"$set": bson.M{"migration-mode": MigrationModeNone},
},
})
}
// Set end timestamps and mark migration as no longer active if a
// terminal phase is hit.
if nextPhase.IsTerminal() {
nextDoc.EndTime = now
update["end-time"] = now
ops = append(ops, txn.Op{
C: migrationsActiveC,
Id: mig.doc.ModelUUID,
Assert: txn.DocExists,
Remove: true,
})
}
ops = append(ops, txn.Op{
C: migrationsStatusC,
Id: mig.statusDoc.Id,
Update: bson.M{"$set": update},
// Ensure phase hasn't changed underneath us
Assert: bson.M{"phase": mig.statusDoc.Phase},
})
if err := mig.st.db().RunTransaction(ops); err == txn.ErrAborted {
return errors.New("phase already changed")
} else if err != nil {
return errors.Annotate(err, "failed to update phase")
}
mig.statusDoc = nextDoc
return nil
} | go | func (mig *modelMigration) SetPhase(nextPhase migration.Phase) error {
now := mig.st.clock().Now().UnixNano()
phase, err := mig.Phase()
if err != nil {
return errors.Trace(err)
}
if nextPhase == phase {
return nil // Already at that phase. Nothing to do.
}
if !phase.CanTransitionTo(nextPhase) {
return errors.Errorf("illegal phase change: %s -> %s", phase, nextPhase)
}
nextDoc := mig.statusDoc
nextDoc.Phase = nextPhase.String()
nextDoc.PhaseChangedTime = now
update := bson.M{
"phase": nextDoc.Phase,
"phase-changed-time": now,
}
if nextPhase == migration.SUCCESS {
nextDoc.SuccessTime = now
update["success-time"] = now
}
ops, err := migStatusHistoryAndOps(mig.st, nextPhase, now, mig.StatusMessage())
if err != nil {
return errors.Trace(err)
}
// If the migration aborted, make the model active again.
if nextPhase == migration.ABORTDONE {
ops = append(ops, txn.Op{
C: modelsC,
Id: mig.doc.ModelUUID,
Assert: txn.DocExists,
Update: bson.M{
"$set": bson.M{"migration-mode": MigrationModeNone},
},
})
}
// Set end timestamps and mark migration as no longer active if a
// terminal phase is hit.
if nextPhase.IsTerminal() {
nextDoc.EndTime = now
update["end-time"] = now
ops = append(ops, txn.Op{
C: migrationsActiveC,
Id: mig.doc.ModelUUID,
Assert: txn.DocExists,
Remove: true,
})
}
ops = append(ops, txn.Op{
C: migrationsStatusC,
Id: mig.statusDoc.Id,
Update: bson.M{"$set": update},
// Ensure phase hasn't changed underneath us
Assert: bson.M{"phase": mig.statusDoc.Phase},
})
if err := mig.st.db().RunTransaction(ops); err == txn.ErrAborted {
return errors.New("phase already changed")
} else if err != nil {
return errors.Annotate(err, "failed to update phase")
}
mig.statusDoc = nextDoc
return nil
} | [
"func",
"(",
"mig",
"*",
"modelMigration",
")",
"SetPhase",
"(",
"nextPhase",
"migration",
".",
"Phase",
")",
"error",
"{",
"now",
":=",
"mig",
".",
"st",
".",
"clock",
"(",
")",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
"\n\n",
"phase",
","... | // SetPhase implements ModelMigration. | [
"SetPhase",
"implements",
"ModelMigration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L295-L368 |
4,750 | juju/juju | state/modelmigration.go | migStatusHistoryAndOps | func migStatusHistoryAndOps(st *State, phase migration.Phase, now int64, msg string) ([]txn.Op, error) {
switch phase {
case migration.REAP, migration.DONE:
// if we're reaping/have reaped the model, setting status on it is both
// pointless and potentially problematic.
return nil, nil
}
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
globalKey := model.globalKey()
modelStatus := status.Busy
if phase.IsTerminal() {
modelStatus = status.Available
}
if msg != "" {
msg = "migrating: " + msg
}
doc := statusDoc{
Status: modelStatus,
StatusInfo: msg,
Updated: now,
}
ops, err := statusSetOps(st.db(), doc, globalKey)
if err != nil {
return nil, errors.Trace(err)
}
probablyUpdateStatusHistory(st.db(), globalKey, doc)
return ops, nil
} | go | func migStatusHistoryAndOps(st *State, phase migration.Phase, now int64, msg string) ([]txn.Op, error) {
switch phase {
case migration.REAP, migration.DONE:
// if we're reaping/have reaped the model, setting status on it is both
// pointless and potentially problematic.
return nil, nil
}
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
globalKey := model.globalKey()
modelStatus := status.Busy
if phase.IsTerminal() {
modelStatus = status.Available
}
if msg != "" {
msg = "migrating: " + msg
}
doc := statusDoc{
Status: modelStatus,
StatusInfo: msg,
Updated: now,
}
ops, err := statusSetOps(st.db(), doc, globalKey)
if err != nil {
return nil, errors.Trace(err)
}
probablyUpdateStatusHistory(st.db(), globalKey, doc)
return ops, nil
} | [
"func",
"migStatusHistoryAndOps",
"(",
"st",
"*",
"State",
",",
"phase",
"migration",
".",
"Phase",
",",
"now",
"int64",
",",
"msg",
"string",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"switch",
"phase",
"{",
"case",
"migration",
... | // migStatusHistoryAndOps sets the model's status history and returns ops for
// setting model status according to the phase and message. | [
"migStatusHistoryAndOps",
"sets",
"the",
"model",
"s",
"status",
"history",
"and",
"returns",
"ops",
"for",
"setting",
"model",
"status",
"according",
"to",
"the",
"phase",
"and",
"message",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L372-L403 |
4,751 | juju/juju | state/modelmigration.go | SetStatusMessage | func (mig *modelMigration) SetStatusMessage(text string) error {
phase, err := mig.Phase()
if err != nil {
return errors.Trace(err)
}
ops, err := migStatusHistoryAndOps(mig.st, phase, mig.st.clock().Now().UnixNano(), text)
if err != nil {
return errors.Trace(err)
}
ops = append(ops, txn.Op{
C: migrationsStatusC,
Id: mig.statusDoc.Id,
Update: bson.M{"$set": bson.M{"status-message": text}},
Assert: txn.DocExists,
})
if err := mig.st.db().RunTransaction(ops); err != nil {
return errors.Annotate(err, "failed to set migration status")
}
mig.statusDoc.StatusMessage = text
return nil
} | go | func (mig *modelMigration) SetStatusMessage(text string) error {
phase, err := mig.Phase()
if err != nil {
return errors.Trace(err)
}
ops, err := migStatusHistoryAndOps(mig.st, phase, mig.st.clock().Now().UnixNano(), text)
if err != nil {
return errors.Trace(err)
}
ops = append(ops, txn.Op{
C: migrationsStatusC,
Id: mig.statusDoc.Id,
Update: bson.M{"$set": bson.M{"status-message": text}},
Assert: txn.DocExists,
})
if err := mig.st.db().RunTransaction(ops); err != nil {
return errors.Annotate(err, "failed to set migration status")
}
mig.statusDoc.StatusMessage = text
return nil
} | [
"func",
"(",
"mig",
"*",
"modelMigration",
")",
"SetStatusMessage",
"(",
"text",
"string",
")",
"error",
"{",
"phase",
",",
"err",
":=",
"mig",
".",
"Phase",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",... | // SetStatusMessage implements ModelMigration. | [
"SetStatusMessage",
"implements",
"ModelMigration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L406-L428 |
4,752 | juju/juju | state/modelmigration.go | SubmitMinionReport | func (mig *modelMigration) SubmitMinionReport(tag names.Tag, phase migration.Phase, success bool) error {
globalKey, err := agentTagToGlobalKey(tag)
if err != nil {
return errors.Trace(err)
}
docID := mig.minionReportId(phase, globalKey)
doc := modelMigMinionSyncDoc{
Id: docID,
MigrationId: mig.Id(),
Phase: phase.String(),
EntityKey: globalKey,
Time: mig.st.clock().Now().UnixNano(),
Success: success,
}
ops := []txn.Op{{
C: migrationsMinionSyncC,
Id: docID,
Insert: doc,
Assert: txn.DocMissing,
}}
err = mig.st.db().RunTransaction(ops)
if errors.Cause(err) == txn.ErrAborted {
coll, closer := mig.st.db().GetCollection(migrationsMinionSyncC)
defer closer()
var existingDoc modelMigMinionSyncDoc
err := coll.FindId(docID).Select(bson.M{"success": 1}).One(&existingDoc)
if err != nil {
return errors.Annotate(err, "checking existing report")
}
if existingDoc.Success != success {
return errors.Errorf("conflicting reports received for %s/%s/%s",
mig.Id(), phase.String(), tag)
}
return nil
} else if err != nil {
return errors.Trace(err)
}
return nil
} | go | func (mig *modelMigration) SubmitMinionReport(tag names.Tag, phase migration.Phase, success bool) error {
globalKey, err := agentTagToGlobalKey(tag)
if err != nil {
return errors.Trace(err)
}
docID := mig.minionReportId(phase, globalKey)
doc := modelMigMinionSyncDoc{
Id: docID,
MigrationId: mig.Id(),
Phase: phase.String(),
EntityKey: globalKey,
Time: mig.st.clock().Now().UnixNano(),
Success: success,
}
ops := []txn.Op{{
C: migrationsMinionSyncC,
Id: docID,
Insert: doc,
Assert: txn.DocMissing,
}}
err = mig.st.db().RunTransaction(ops)
if errors.Cause(err) == txn.ErrAborted {
coll, closer := mig.st.db().GetCollection(migrationsMinionSyncC)
defer closer()
var existingDoc modelMigMinionSyncDoc
err := coll.FindId(docID).Select(bson.M{"success": 1}).One(&existingDoc)
if err != nil {
return errors.Annotate(err, "checking existing report")
}
if existingDoc.Success != success {
return errors.Errorf("conflicting reports received for %s/%s/%s",
mig.Id(), phase.String(), tag)
}
return nil
} else if err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"(",
"mig",
"*",
"modelMigration",
")",
"SubmitMinionReport",
"(",
"tag",
"names",
".",
"Tag",
",",
"phase",
"migration",
".",
"Phase",
",",
"success",
"bool",
")",
"error",
"{",
"globalKey",
",",
"err",
":=",
"agentTagToGlobalKey",
"(",
"tag",
")"... | // SubmitMinionReport implements ModelMigration. | [
"SubmitMinionReport",
"implements",
"ModelMigration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L431-L469 |
4,753 | juju/juju | state/modelmigration.go | MinionReports | func (mig *modelMigration) MinionReports() (*MinionReports, error) {
all, err := mig.getAllAgents()
if err != nil {
return nil, errors.Trace(err)
}
phase, err := mig.Phase()
if err != nil {
return nil, errors.Annotate(err, "retrieving phase")
}
coll, closer := mig.st.db().GetCollection(migrationsMinionSyncC)
defer closer()
query := coll.Find(bson.M{"_id": bson.M{
"$regex": "^" + mig.minionReportId(phase, ".+"),
}})
query = query.Select(bson.M{
"entity-key": 1,
"success": 1,
})
var docs []bson.M
if err := query.All(&docs); err != nil {
return nil, errors.Annotate(err, "retrieving minion reports")
}
succeeded := names.NewSet()
failed := names.NewSet()
for _, doc := range docs {
entityKey, ok := doc["entity-key"].(string)
if !ok {
return nil, errors.Errorf("unexpected entity-key %v", doc["entity-key"])
}
tag, err := globalKeyToAgentTag(entityKey)
if err != nil {
return nil, errors.Trace(err)
}
success, ok := doc["success"].(bool)
if !ok {
return nil, errors.Errorf("unexpected success value: %v", doc["success"])
}
if success {
succeeded.Add(tag)
} else {
failed.Add(tag)
}
}
unknown := all.Difference(succeeded).Difference(failed)
return &MinionReports{
Succeeded: succeeded.Values(),
Failed: failed.Values(),
Unknown: unknown.Values(),
}, nil
} | go | func (mig *modelMigration) MinionReports() (*MinionReports, error) {
all, err := mig.getAllAgents()
if err != nil {
return nil, errors.Trace(err)
}
phase, err := mig.Phase()
if err != nil {
return nil, errors.Annotate(err, "retrieving phase")
}
coll, closer := mig.st.db().GetCollection(migrationsMinionSyncC)
defer closer()
query := coll.Find(bson.M{"_id": bson.M{
"$regex": "^" + mig.minionReportId(phase, ".+"),
}})
query = query.Select(bson.M{
"entity-key": 1,
"success": 1,
})
var docs []bson.M
if err := query.All(&docs); err != nil {
return nil, errors.Annotate(err, "retrieving minion reports")
}
succeeded := names.NewSet()
failed := names.NewSet()
for _, doc := range docs {
entityKey, ok := doc["entity-key"].(string)
if !ok {
return nil, errors.Errorf("unexpected entity-key %v", doc["entity-key"])
}
tag, err := globalKeyToAgentTag(entityKey)
if err != nil {
return nil, errors.Trace(err)
}
success, ok := doc["success"].(bool)
if !ok {
return nil, errors.Errorf("unexpected success value: %v", doc["success"])
}
if success {
succeeded.Add(tag)
} else {
failed.Add(tag)
}
}
unknown := all.Difference(succeeded).Difference(failed)
return &MinionReports{
Succeeded: succeeded.Values(),
Failed: failed.Values(),
Unknown: unknown.Values(),
}, nil
} | [
"func",
"(",
"mig",
"*",
"modelMigration",
")",
"MinionReports",
"(",
")",
"(",
"*",
"MinionReports",
",",
"error",
")",
"{",
"all",
",",
"err",
":=",
"mig",
".",
"getAllAgents",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
... | // MinionReports implements ModelMigration. | [
"MinionReports",
"implements",
"ModelMigration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L472-L526 |
4,754 | juju/juju | state/modelmigration.go | WatchMinionReports | func (mig *modelMigration) WatchMinionReports() (NotifyWatcher, error) {
phase, err := mig.Phase()
if err != nil {
return nil, errors.Annotate(err, "retrieving phase")
}
prefix := mig.minionReportId(phase, "")
filter := func(rawId interface{}) bool {
id, ok := rawId.(string)
if !ok {
return false
}
return strings.HasPrefix(id, prefix)
}
return newNotifyCollWatcher(mig.st, migrationsMinionSyncC, filter), nil
} | go | func (mig *modelMigration) WatchMinionReports() (NotifyWatcher, error) {
phase, err := mig.Phase()
if err != nil {
return nil, errors.Annotate(err, "retrieving phase")
}
prefix := mig.minionReportId(phase, "")
filter := func(rawId interface{}) bool {
id, ok := rawId.(string)
if !ok {
return false
}
return strings.HasPrefix(id, prefix)
}
return newNotifyCollWatcher(mig.st, migrationsMinionSyncC, filter), nil
} | [
"func",
"(",
"mig",
"*",
"modelMigration",
")",
"WatchMinionReports",
"(",
")",
"(",
"NotifyWatcher",
",",
"error",
")",
"{",
"phase",
",",
"err",
":=",
"mig",
".",
"Phase",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors... | // WatchMinionReports implements ModelMigration. | [
"WatchMinionReports",
"implements",
"ModelMigration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L529-L543 |
4,755 | juju/juju | state/modelmigration.go | Refresh | func (mig *modelMigration) Refresh() error {
// Only the status document is updated. The modelMigDoc is static
// after creation.
statusColl, closer := mig.st.db().GetCollection(migrationsStatusC)
defer closer()
var statusDoc modelMigStatusDoc
err := statusColl.FindId(mig.doc.Id).One(&statusDoc)
if err == mgo.ErrNotFound {
return errors.NotFoundf("migration status")
} else if err != nil {
return errors.Annotate(err, "migration status lookup failed")
}
mig.statusDoc = statusDoc
return nil
} | go | func (mig *modelMigration) Refresh() error {
// Only the status document is updated. The modelMigDoc is static
// after creation.
statusColl, closer := mig.st.db().GetCollection(migrationsStatusC)
defer closer()
var statusDoc modelMigStatusDoc
err := statusColl.FindId(mig.doc.Id).One(&statusDoc)
if err == mgo.ErrNotFound {
return errors.NotFoundf("migration status")
} else if err != nil {
return errors.Annotate(err, "migration status lookup failed")
}
mig.statusDoc = statusDoc
return nil
} | [
"func",
"(",
"mig",
"*",
"modelMigration",
")",
"Refresh",
"(",
")",
"error",
"{",
"// Only the status document is updated. The modelMigDoc is static",
"// after creation.",
"statusColl",
",",
"closer",
":=",
"mig",
".",
"st",
".",
"db",
"(",
")",
".",
"GetCollectio... | // Refresh implements ModelMigration. | [
"Refresh",
"implements",
"ModelMigration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L607-L622 |
4,756 | juju/juju | state/modelmigration.go | ModelUserAccess | func (mig *modelMigration) ModelUserAccess(tag names.Tag) permission.Access {
id := tag.Id()
for _, user := range mig.doc.ModelUsers {
if user.UserID == id {
return user.Access
}
}
return permission.NoAccess
} | go | func (mig *modelMigration) ModelUserAccess(tag names.Tag) permission.Access {
id := tag.Id()
for _, user := range mig.doc.ModelUsers {
if user.UserID == id {
return user.Access
}
}
return permission.NoAccess
} | [
"func",
"(",
"mig",
"*",
"modelMigration",
")",
"ModelUserAccess",
"(",
"tag",
"names",
".",
"Tag",
")",
"permission",
".",
"Access",
"{",
"id",
":=",
"tag",
".",
"Id",
"(",
")",
"\n",
"for",
"_",
",",
"user",
":=",
"range",
"mig",
".",
"doc",
".",... | // ModelUserAccess implements ModelMigration. | [
"ModelUserAccess",
"implements",
"ModelMigration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L625-L634 |
4,757 | juju/juju | state/modelmigration.go | Validate | func (spec *MigrationSpec) Validate() error {
if !names.IsValidUser(spec.InitiatedBy.Id()) {
return errors.NotValidf("InitiatedBy")
}
return spec.TargetInfo.Validate()
} | go | func (spec *MigrationSpec) Validate() error {
if !names.IsValidUser(spec.InitiatedBy.Id()) {
return errors.NotValidf("InitiatedBy")
}
return spec.TargetInfo.Validate()
} | [
"func",
"(",
"spec",
"*",
"MigrationSpec",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"!",
"names",
".",
"IsValidUser",
"(",
"spec",
".",
"InitiatedBy",
".",
"Id",
"(",
")",
")",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
... | // Validate returns an error if the MigrationSpec contains bad
// data. Nil is returned otherwise. | [
"Validate",
"returns",
"an",
"error",
"if",
"the",
"MigrationSpec",
"contains",
"bad",
"data",
".",
"Nil",
"is",
"returned",
"otherwise",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L645-L650 |
4,758 | juju/juju | state/modelmigration.go | Migration | func (st *State) Migration(id string) (ModelMigration, error) {
migColl, closer := st.db().GetCollection(migrationsC)
defer closer()
mig, err := st.migrationFromQuery(migColl.FindId(id))
if err != nil {
return nil, errors.Trace(err)
}
return mig, nil
} | go | func (st *State) Migration(id string) (ModelMigration, error) {
migColl, closer := st.db().GetCollection(migrationsC)
defer closer()
mig, err := st.migrationFromQuery(migColl.FindId(id))
if err != nil {
return nil, errors.Trace(err)
}
return mig, nil
} | [
"func",
"(",
"st",
"*",
"State",
")",
"Migration",
"(",
"id",
"string",
")",
"(",
"ModelMigration",
",",
"error",
")",
"{",
"migColl",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"migrationsC",
")",
"\n",
"defer",
"clos... | // Migration retrieves a specific ModelMigration by its id. See also
// LatestMigration and LatestCompletedMigration. | [
"Migration",
"retrieves",
"a",
"specific",
"ModelMigration",
"by",
"its",
"id",
".",
"See",
"also",
"LatestMigration",
"and",
"LatestCompletedMigration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L882-L890 |
4,759 | juju/juju | state/modelmigration.go | IsMigrationActive | func IsMigrationActive(st *State, modelUUID string) (bool, error) {
active, closer := st.db().GetCollection(migrationsActiveC)
defer closer()
n, err := active.FindId(modelUUID).Count()
if err != nil {
return false, errors.Trace(err)
}
return n > 0, nil
} | go | func IsMigrationActive(st *State, modelUUID string) (bool, error) {
active, closer := st.db().GetCollection(migrationsActiveC)
defer closer()
n, err := active.FindId(modelUUID).Count()
if err != nil {
return false, errors.Trace(err)
}
return n > 0, nil
} | [
"func",
"IsMigrationActive",
"(",
"st",
"*",
"State",
",",
"modelUUID",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"active",
",",
"closer",
":=",
"st",
".",
"db",
"(",
")",
".",
"GetCollection",
"(",
"migrationsActiveC",
")",
"\n",
"defer",
"c... | // IsMigrationActive returns true if a migration is in progress for
// the model with the given UUID. The State provided need not be for
// the model in question. | [
"IsMigrationActive",
"returns",
"true",
"if",
"a",
"migration",
"is",
"in",
"progress",
"for",
"the",
"model",
"with",
"the",
"given",
"UUID",
".",
"The",
"State",
"provided",
"need",
"not",
"be",
"for",
"the",
"model",
"in",
"question",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/modelmigration.go#L927-L935 |
4,760 | juju/juju | cmd/jujud/agent/engine/housing.go | Decorate | func (housing Housing) Decorate(base dependency.Manifold) dependency.Manifold {
manifold := base
// Apply Occupy wrapping first, so that it will be the last
// wrapper to execute before calling the original Start func, so
// as to minimise the time we hold the fortress open.
if housing.Occupy != "" {
manifold.Inputs = maybeAdd(manifold.Inputs, housing.Occupy)
manifold.Start = occupyStart(manifold.Start, housing.Occupy)
}
for _, name := range housing.Flags {
manifold.Inputs = maybeAdd(manifold.Inputs, name)
manifold.Start = flagStart(manifold.Start, name)
}
if housing.Filter != nil {
manifold.Filter = housing.Filter
}
return manifold
} | go | func (housing Housing) Decorate(base dependency.Manifold) dependency.Manifold {
manifold := base
// Apply Occupy wrapping first, so that it will be the last
// wrapper to execute before calling the original Start func, so
// as to minimise the time we hold the fortress open.
if housing.Occupy != "" {
manifold.Inputs = maybeAdd(manifold.Inputs, housing.Occupy)
manifold.Start = occupyStart(manifold.Start, housing.Occupy)
}
for _, name := range housing.Flags {
manifold.Inputs = maybeAdd(manifold.Inputs, name)
manifold.Start = flagStart(manifold.Start, name)
}
if housing.Filter != nil {
manifold.Filter = housing.Filter
}
return manifold
} | [
"func",
"(",
"housing",
"Housing",
")",
"Decorate",
"(",
"base",
"dependency",
".",
"Manifold",
")",
"dependency",
".",
"Manifold",
"{",
"manifold",
":=",
"base",
"\n",
"// Apply Occupy wrapping first, so that it will be the last",
"// wrapper to execute before calling the ... | // Decorate is part of the Decorator interface. | [
"Decorate",
"is",
"part",
"of",
"the",
"Decorator",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/engine/housing.go#L51-L68 |
4,761 | juju/juju | apiserver/facades/client/payloads/facade.go | List | func (a API) List(args params.PayloadListArgs) (params.PayloadListResults, error) {
var r params.PayloadListResults
payloads, err := a.backend.ListAll()
if err != nil {
return r, errors.Trace(err)
}
filters, err := payload.BuildPredicatesFor(args.Patterns)
if err != nil {
return r, errors.Trace(err)
}
payloads = payload.Filter(payloads, filters...)
for _, payload := range payloads {
apiInfo := api.Payload2api(payload)
r.Results = append(r.Results, apiInfo)
}
return r, nil
} | go | func (a API) List(args params.PayloadListArgs) (params.PayloadListResults, error) {
var r params.PayloadListResults
payloads, err := a.backend.ListAll()
if err != nil {
return r, errors.Trace(err)
}
filters, err := payload.BuildPredicatesFor(args.Patterns)
if err != nil {
return r, errors.Trace(err)
}
payloads = payload.Filter(payloads, filters...)
for _, payload := range payloads {
apiInfo := api.Payload2api(payload)
r.Results = append(r.Results, apiInfo)
}
return r, nil
} | [
"func",
"(",
"a",
"API",
")",
"List",
"(",
"args",
"params",
".",
"PayloadListArgs",
")",
"(",
"params",
".",
"PayloadListResults",
",",
"error",
")",
"{",
"var",
"r",
"params",
".",
"PayloadListResults",
"\n\n",
"payloads",
",",
"err",
":=",
"a",
".",
... | // List builds the list of payloads being tracked for
// the given unit and IDs. If no IDs are provided then all tracked
// payloads for the unit are returned. | [
"List",
"builds",
"the",
"list",
"of",
"payloads",
"being",
"tracked",
"for",
"the",
"given",
"unit",
"and",
"IDs",
".",
"If",
"no",
"IDs",
"are",
"provided",
"then",
"all",
"tracked",
"payloads",
"for",
"the",
"unit",
"are",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/payloads/facade.go#L49-L68 |
4,762 | juju/juju | container/interface.go | PopValue | func (m ManagerConfig) PopValue(key string) string {
value := m[key]
delete(m, key)
return value
} | go | func (m ManagerConfig) PopValue(key string) string {
value := m[key]
delete(m, key)
return value
} | [
"func",
"(",
"m",
"ManagerConfig",
")",
"PopValue",
"(",
"key",
"string",
")",
"string",
"{",
"value",
":=",
"m",
"[",
"key",
"]",
"\n",
"delete",
"(",
"m",
",",
"key",
")",
"\n",
"return",
"value",
"\n",
"}"
] | // PopValue returns the requested key from the config map. If the value
// doesn't exist, the function returns the empty string. If the value does
// exist, the value is returned, and the element removed from the map. | [
"PopValue",
"returns",
"the",
"requested",
"key",
"from",
"the",
"config",
"map",
".",
"If",
"the",
"value",
"doesn",
"t",
"exist",
"the",
"function",
"returns",
"the",
"empty",
"string",
".",
"If",
"the",
"value",
"does",
"exist",
"the",
"value",
"is",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/interface.go#L70-L74 |
4,763 | juju/juju | container/interface.go | WarnAboutUnused | func (m ManagerConfig) WarnAboutUnused() {
for key, value := range m {
logger.Infof("unused config option: %q -> %q", key, value)
}
} | go | func (m ManagerConfig) WarnAboutUnused() {
for key, value := range m {
logger.Infof("unused config option: %q -> %q", key, value)
}
} | [
"func",
"(",
"m",
"ManagerConfig",
")",
"WarnAboutUnused",
"(",
")",
"{",
"for",
"key",
",",
"value",
":=",
"range",
"m",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"key",
",",
"value",
")",
"\n",
"}",
"\n",
"}"
] | // WarnAboutUnused emits a warning about each value in the map. | [
"WarnAboutUnused",
"emits",
"a",
"warning",
"about",
"each",
"value",
"in",
"the",
"map",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/interface.go#L77-L81 |
4,764 | juju/juju | apiserver/rest.go | ServeHTTP | func (h *RestHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var err error
switch r.Method {
case "GET":
err = errors.Annotate(h.GetHandler(w, r), "cannot retrieve model data")
default:
err = emitUnsupportedMethodErr(r.Method)
}
if err != nil {
if err := sendJSONError(w, r, errors.Trace(err)); err != nil {
logger.Errorf("%v", errors.Annotate(err, "cannot return error to user"))
}
}
} | go | func (h *RestHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var err error
switch r.Method {
case "GET":
err = errors.Annotate(h.GetHandler(w, r), "cannot retrieve model data")
default:
err = emitUnsupportedMethodErr(r.Method)
}
if err != nil {
if err := sendJSONError(w, r, errors.Trace(err)); err != nil {
logger.Errorf("%v", errors.Annotate(err, "cannot return error to user"))
}
}
} | [
"func",
"(",
"h",
"*",
"RestHTTPHandler",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"var",
"err",
"error",
"\n",
"switch",
"r",
".",
"Method",
"{",
"case",
"\"",
"\"",
":",
"err",
"=... | // ServeHTTP is defined on handler.Handler. | [
"ServeHTTP",
"is",
"defined",
"on",
"handler",
".",
"Handler",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/rest.go#L27-L41 |
4,765 | juju/juju | apiserver/rest.go | ServeGet | func (h *modelRestHandler) ServeGet(w http.ResponseWriter, r *http.Request) error {
if r.Method != "GET" {
return errors.Trace(emitUnsupportedMethodErr(r.Method))
}
st, _, err := h.ctxt.stateForRequestAuthenticated(r)
if err != nil {
return errors.Trace(err)
}
defer st.Release()
return errors.Trace(h.processGet(r, w, st.State))
} | go | func (h *modelRestHandler) ServeGet(w http.ResponseWriter, r *http.Request) error {
if r.Method != "GET" {
return errors.Trace(emitUnsupportedMethodErr(r.Method))
}
st, _, err := h.ctxt.stateForRequestAuthenticated(r)
if err != nil {
return errors.Trace(err)
}
defer st.Release()
return errors.Trace(h.processGet(r, w, st.State))
} | [
"func",
"(",
"h",
"*",
"modelRestHandler",
")",
"ServeGet",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"if",
"r",
".",
"Method",
"!=",
"\"",
"\"",
"{",
"return",
"errors",
".",
"Trace",
"(",
"... | // ServeGet handles http GET requests. | [
"ServeGet",
"handles",
"http",
"GET",
"requests",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/rest.go#L51-L63 |
4,766 | juju/juju | apiserver/rest.go | processGet | func (h *modelRestHandler) processGet(r *http.Request, w http.ResponseWriter, st *state.State) error {
query := r.URL.Query()
entity := query.Get(":entity")
// TODO(wallyworld) - support more than just "remote-application"
switch entity {
case "remote-application":
return h.processRemoteApplication(r, w, st)
default:
return errors.NotSupportedf("entity %v", entity)
}
} | go | func (h *modelRestHandler) processGet(r *http.Request, w http.ResponseWriter, st *state.State) error {
query := r.URL.Query()
entity := query.Get(":entity")
// TODO(wallyworld) - support more than just "remote-application"
switch entity {
case "remote-application":
return h.processRemoteApplication(r, w, st)
default:
return errors.NotSupportedf("entity %v", entity)
}
} | [
"func",
"(",
"h",
"*",
"modelRestHandler",
")",
"processGet",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"st",
"*",
"state",
".",
"State",
")",
"error",
"{",
"query",
":=",
"r",
".",
"URL",
".",
"Query",
"(... | // processGet handles a ReST GET request after authentication. | [
"processGet",
"handles",
"a",
"ReST",
"GET",
"request",
"after",
"authentication",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/rest.go#L66-L76 |
4,767 | juju/juju | apiserver/rest.go | processRemoteApplication | func (h *modelRestHandler) processRemoteApplication(r *http.Request, w http.ResponseWriter, st *state.State) error {
query := r.URL.Query()
name := query.Get(":name")
remoteApp, err := st.RemoteApplication(name)
if err != nil {
return errors.Trace(err)
}
attribute := query.Get(":attribute")
// TODO(wallyworld) - support more than just "icon"
if attribute != "icon" {
return errors.NotSupportedf("attribute %v on entity %v", attribute, name)
}
// Get the backend state for the source model so we can lookup the app in that model to get the charm details.
offerUUID := remoteApp.OfferUUID()
sourceModelUUID := remoteApp.SourceModel().Id()
sourceSt, err := h.ctxt.srv.shared.statePool.Get(sourceModelUUID)
if err != nil {
return errors.Trace(err)
}
defer sourceSt.Release()
offers := state.NewApplicationOffers(sourceSt.State)
offer, err := offers.ApplicationOfferForUUID(offerUUID)
if err != nil {
return errors.Trace(err)
}
app, err := sourceSt.Application(offer.ApplicationName)
if err != nil {
return errors.Trace(err)
}
ch, _, err := app.Charm()
if err != nil {
return errors.Trace(err)
}
store := storage.NewStorage(sourceSt.ModelUUID(), sourceSt.MongoSession())
// Use the storage to retrieve and save the charm archive.
charmPath, err := common.ReadCharmFromStorage(store, h.dataDir, ch.StoragePath())
if errors.IsNotFound(err) {
return h.byteSender(w, ".svg", []byte(common.DefaultCharmIcon))
}
if err != nil {
return errors.Trace(err)
}
iconContents, err := common.CharmArchiveEntry(charmPath, "icon.svg", true)
if errors.IsNotFound(err) {
return h.byteSender(w, ".svg", []byte(common.DefaultCharmIcon))
}
if err != nil {
return errors.Trace(err)
}
return h.byteSender(w, ".svg", iconContents)
} | go | func (h *modelRestHandler) processRemoteApplication(r *http.Request, w http.ResponseWriter, st *state.State) error {
query := r.URL.Query()
name := query.Get(":name")
remoteApp, err := st.RemoteApplication(name)
if err != nil {
return errors.Trace(err)
}
attribute := query.Get(":attribute")
// TODO(wallyworld) - support more than just "icon"
if attribute != "icon" {
return errors.NotSupportedf("attribute %v on entity %v", attribute, name)
}
// Get the backend state for the source model so we can lookup the app in that model to get the charm details.
offerUUID := remoteApp.OfferUUID()
sourceModelUUID := remoteApp.SourceModel().Id()
sourceSt, err := h.ctxt.srv.shared.statePool.Get(sourceModelUUID)
if err != nil {
return errors.Trace(err)
}
defer sourceSt.Release()
offers := state.NewApplicationOffers(sourceSt.State)
offer, err := offers.ApplicationOfferForUUID(offerUUID)
if err != nil {
return errors.Trace(err)
}
app, err := sourceSt.Application(offer.ApplicationName)
if err != nil {
return errors.Trace(err)
}
ch, _, err := app.Charm()
if err != nil {
return errors.Trace(err)
}
store := storage.NewStorage(sourceSt.ModelUUID(), sourceSt.MongoSession())
// Use the storage to retrieve and save the charm archive.
charmPath, err := common.ReadCharmFromStorage(store, h.dataDir, ch.StoragePath())
if errors.IsNotFound(err) {
return h.byteSender(w, ".svg", []byte(common.DefaultCharmIcon))
}
if err != nil {
return errors.Trace(err)
}
iconContents, err := common.CharmArchiveEntry(charmPath, "icon.svg", true)
if errors.IsNotFound(err) {
return h.byteSender(w, ".svg", []byte(common.DefaultCharmIcon))
}
if err != nil {
return errors.Trace(err)
}
return h.byteSender(w, ".svg", iconContents)
} | [
"func",
"(",
"h",
"*",
"modelRestHandler",
")",
"processRemoteApplication",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"st",
"*",
"state",
".",
"State",
")",
"error",
"{",
"query",
":=",
"r",
".",
"URL",
".",
... | // processRemoteApplication handles a request for attributes on remote applications. | [
"processRemoteApplication",
"handles",
"a",
"request",
"for",
"attributes",
"on",
"remote",
"applications",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/rest.go#L79-L132 |
4,768 | juju/juju | apiserver/facades/agent/instancemutater/mocks/watcher_mock.go | NewMockNotifyWatcher | func NewMockNotifyWatcher(ctrl *gomock.Controller) *MockNotifyWatcher {
mock := &MockNotifyWatcher{ctrl: ctrl}
mock.recorder = &MockNotifyWatcherMockRecorder{mock}
return mock
} | go | func NewMockNotifyWatcher(ctrl *gomock.Controller) *MockNotifyWatcher {
mock := &MockNotifyWatcher{ctrl: ctrl}
mock.recorder = &MockNotifyWatcherMockRecorder{mock}
return mock
} | [
"func",
"NewMockNotifyWatcher",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockNotifyWatcher",
"{",
"mock",
":=",
"&",
"MockNotifyWatcher",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockNotifyWatcherMockRecorder",
... | // NewMockNotifyWatcher creates a new mock instance | [
"NewMockNotifyWatcher",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/watcher_mock.go#L24-L28 |
4,769 | juju/juju | apiserver/facades/agent/instancemutater/mocks/watcher_mock.go | NewMockStringsWatcher | func NewMockStringsWatcher(ctrl *gomock.Controller) *MockStringsWatcher {
mock := &MockStringsWatcher{ctrl: ctrl}
mock.recorder = &MockStringsWatcherMockRecorder{mock}
return mock
} | go | func NewMockStringsWatcher(ctrl *gomock.Controller) *MockStringsWatcher {
mock := &MockStringsWatcher{ctrl: ctrl}
mock.recorder = &MockStringsWatcherMockRecorder{mock}
return mock
} | [
"func",
"NewMockStringsWatcher",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockStringsWatcher",
"{",
"mock",
":=",
"&",
"MockStringsWatcher",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockStringsWatcherMockRecorder"... | // NewMockStringsWatcher creates a new mock instance | [
"NewMockStringsWatcher",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/watcher_mock.go#L93-L97 |
4,770 | juju/juju | provider/oracle/images.go | checkImageList | func checkImageList(c EnvironAPI) ([]*imagemetadata.ImageMetadata, error) {
if c == nil {
return nil, errors.NotFoundf("oracle client")
}
// take a list of all images that are in the oracle cloud account
resp, err := c.AllImageLists(nil)
if err != nil {
return nil, errors.Trace(err)
}
// if we don't have any images that are in
// the oracle cloud account under your username namespace
// we should let the user know this
n := len(resp.Result)
if n == 0 {
return nil, errors.NotFoundf(
"images under the current client username are",
)
}
images := make([]*imagemetadata.ImageMetadata, 0, n)
for _, val := range resp.Result {
uri, err := url.Parse(val.Uri)
if err != nil {
logger.Warningf("image with ID %q had invalid resource URI %q", val.Name, val.Uri)
continue
}
requestUri := strings.Split(uri.RequestURI(), "/")
if len(requestUri) == 0 {
continue
}
name := requestUri[len(requestUri)-1]
metadata, err := parseImageName(name, uri)
if err != nil {
logger.Warningf("failed to parse image name %s. Error was: %q", name, err)
continue
}
logger.Infof("adding image %v to metadata", metadata.String())
images = append(images, metadata)
}
return images, nil
} | go | func checkImageList(c EnvironAPI) ([]*imagemetadata.ImageMetadata, error) {
if c == nil {
return nil, errors.NotFoundf("oracle client")
}
// take a list of all images that are in the oracle cloud account
resp, err := c.AllImageLists(nil)
if err != nil {
return nil, errors.Trace(err)
}
// if we don't have any images that are in
// the oracle cloud account under your username namespace
// we should let the user know this
n := len(resp.Result)
if n == 0 {
return nil, errors.NotFoundf(
"images under the current client username are",
)
}
images := make([]*imagemetadata.ImageMetadata, 0, n)
for _, val := range resp.Result {
uri, err := url.Parse(val.Uri)
if err != nil {
logger.Warningf("image with ID %q had invalid resource URI %q", val.Name, val.Uri)
continue
}
requestUri := strings.Split(uri.RequestURI(), "/")
if len(requestUri) == 0 {
continue
}
name := requestUri[len(requestUri)-1]
metadata, err := parseImageName(name, uri)
if err != nil {
logger.Warningf("failed to parse image name %s. Error was: %q", name, err)
continue
}
logger.Infof("adding image %v to metadata", metadata.String())
images = append(images, metadata)
}
return images, nil
} | [
"func",
"checkImageList",
"(",
"c",
"EnvironAPI",
")",
"(",
"[",
"]",
"*",
"imagemetadata",
".",
"ImageMetadata",
",",
"error",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
")",
"\n",
"}",
... | // checkImageList creates image metadata from the oracle image list | [
"checkImageList",
"creates",
"image",
"metadata",
"from",
"the",
"oracle",
"image",
"list"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/images.go#L125-L167 |
4,771 | juju/juju | provider/oracle/images.go | getImageName | func getImageName(c EnvironAPI, id string) (string, error) {
if id == "" {
return "", errors.NotFoundf("empty id")
}
resp, err := c.AllImageLists(nil)
if err != nil {
return "", errors.Trace(err)
}
// if we don't have any images that are in
// the oracle cloud account under your username namespace
// we should let the user know this
if resp.Result == nil {
return "", errors.NotFoundf(
"no usable images found in your account. Please add images from the oracle market",
)
}
for _, val := range resp.Result {
if strings.Contains(val.Name, id) {
s := strings.Split(val.Name, "/")
return s[len(s)-1], nil
}
}
return "", errors.NotFoundf("image not found: %q", id)
} | go | func getImageName(c EnvironAPI, id string) (string, error) {
if id == "" {
return "", errors.NotFoundf("empty id")
}
resp, err := c.AllImageLists(nil)
if err != nil {
return "", errors.Trace(err)
}
// if we don't have any images that are in
// the oracle cloud account under your username namespace
// we should let the user know this
if resp.Result == nil {
return "", errors.NotFoundf(
"no usable images found in your account. Please add images from the oracle market",
)
}
for _, val := range resp.Result {
if strings.Contains(val.Name, id) {
s := strings.Split(val.Name, "/")
return s[len(s)-1], nil
}
}
return "", errors.NotFoundf("image not found: %q", id)
} | [
"func",
"getImageName",
"(",
"c",
"EnvironAPI",
",",
"id",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"id",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"r... | // getImageName gets the name of the image represented by the supplied ID | [
"getImageName",
"gets",
"the",
"name",
"of",
"the",
"image",
"represented",
"by",
"the",
"supplied",
"ID"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/images.go#L170-L197 |
4,772 | juju/juju | core/watcher/strings.go | Validate | func (config StringsConfig) Validate() error {
if config.Handler == nil {
return errors.NotValidf("nil Handler")
}
return nil
} | go | func (config StringsConfig) Validate() error {
if config.Handler == nil {
return errors.NotValidf("nil Handler")
}
return nil
} | [
"func",
"(",
"config",
"StringsConfig",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"config",
".",
"Handler",
"==",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate returns ann error if the config cannot start a StringsWorker. | [
"Validate",
"returns",
"ann",
"error",
"if",
"the",
"config",
"cannot",
"start",
"a",
"StringsWorker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/watcher/strings.go#L54-L59 |
4,773 | juju/juju | core/watcher/strings.go | NewStringsWorker | func NewStringsWorker(config StringsConfig) (*StringsWorker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
sw := &StringsWorker{
config: config,
}
err := catacomb.Invoke(catacomb.Plan{
Site: &sw.catacomb,
Work: sw.loop,
})
if err != nil {
return nil, errors.Trace(err)
}
return sw, nil
} | go | func NewStringsWorker(config StringsConfig) (*StringsWorker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
sw := &StringsWorker{
config: config,
}
err := catacomb.Invoke(catacomb.Plan{
Site: &sw.catacomb,
Work: sw.loop,
})
if err != nil {
return nil, errors.Trace(err)
}
return sw, nil
} | [
"func",
"NewStringsWorker",
"(",
"config",
"StringsConfig",
")",
"(",
"*",
"StringsWorker",
",",
"error",
")",
"{",
"if",
"err",
":=",
"config",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",... | // NewStringsWorker starts a new worker that runs a StringsHandler. | [
"NewStringsWorker",
"starts",
"a",
"new",
"worker",
"that",
"runs",
"a",
"StringsHandler",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/watcher/strings.go#L62-L77 |
4,774 | juju/juju | storage/provider/managedfs.go | NewManagedFilesystemSource | func NewManagedFilesystemSource(
volumeBlockDevices map[names.VolumeTag]storage.BlockDevice,
filesystems map[names.FilesystemTag]storage.Filesystem,
) storage.FilesystemSource {
return &managedFilesystemSource{
logAndExec,
&osDirFuncs{logAndExec},
volumeBlockDevices, filesystems,
}
} | go | func NewManagedFilesystemSource(
volumeBlockDevices map[names.VolumeTag]storage.BlockDevice,
filesystems map[names.FilesystemTag]storage.Filesystem,
) storage.FilesystemSource {
return &managedFilesystemSource{
logAndExec,
&osDirFuncs{logAndExec},
volumeBlockDevices, filesystems,
}
} | [
"func",
"NewManagedFilesystemSource",
"(",
"volumeBlockDevices",
"map",
"[",
"names",
".",
"VolumeTag",
"]",
"storage",
".",
"BlockDevice",
",",
"filesystems",
"map",
"[",
"names",
".",
"FilesystemTag",
"]",
"storage",
".",
"Filesystem",
",",
")",
"storage",
"."... | // NewManagedFilesystemSource returns a storage.FilesystemSource that manages
// filesystems on block devices on the host machine.
//
// The parameters are maps that the caller will update with information about
// block devices and filesystems created by the source. The caller must not
// update the maps during calls to the source's methods. | [
"NewManagedFilesystemSource",
"returns",
"a",
"storage",
".",
"FilesystemSource",
"that",
"manages",
"filesystems",
"on",
"block",
"devices",
"on",
"the",
"host",
"machine",
".",
"The",
"parameters",
"are",
"maps",
"that",
"the",
"caller",
"will",
"update",
"with"... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/managedfs.go#L45-L54 |
4,775 | juju/juju | storage/provider/managedfs.go | isDiskDevice | func isDiskDevice(devicePath string) bool {
var last rune
for _, r := range devicePath {
last = r
}
return !unicode.IsDigit(last)
} | go | func isDiskDevice(devicePath string) bool {
var last rune
for _, r := range devicePath {
last = r
}
return !unicode.IsDigit(last)
} | [
"func",
"isDiskDevice",
"(",
"devicePath",
"string",
")",
"bool",
"{",
"var",
"last",
"rune",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"devicePath",
"{",
"last",
"=",
"r",
"\n",
"}",
"\n",
"return",
"!",
"unicode",
".",
"IsDigit",
"(",
"last",
")",... | // isDiskDevice reports whether or not the device is a full disk, as opposed
// to a partition or a loop device. We create a partition on disks to contain
// filesystems. | [
"isDiskDevice",
"reports",
"whether",
"or",
"not",
"the",
"device",
"is",
"a",
"full",
"disk",
"as",
"opposed",
"to",
"a",
"partition",
"or",
"a",
"loop",
"device",
".",
"We",
"create",
"a",
"partition",
"on",
"disks",
"to",
"contain",
"filesystems",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/managedfs.go#L396-L402 |
4,776 | juju/juju | worker/storageprovisioner/machines.go | watchMachine | func watchMachine(ctx *context, tag names.MachineTag) {
_, ok := ctx.machines[tag]
if ok {
return
}
w, err := newMachineWatcher(ctx.config.Machines, tag, ctx.machineChanges)
if err != nil {
ctx.kill(errors.Trace(err))
} else if err := ctx.addWorker(w); err != nil {
ctx.kill(errors.Trace(err))
} else {
ctx.machines[tag] = w
}
} | go | func watchMachine(ctx *context, tag names.MachineTag) {
_, ok := ctx.machines[tag]
if ok {
return
}
w, err := newMachineWatcher(ctx.config.Machines, tag, ctx.machineChanges)
if err != nil {
ctx.kill(errors.Trace(err))
} else if err := ctx.addWorker(w); err != nil {
ctx.kill(errors.Trace(err))
} else {
ctx.machines[tag] = w
}
} | [
"func",
"watchMachine",
"(",
"ctx",
"*",
"context",
",",
"tag",
"names",
".",
"MachineTag",
")",
"{",
"_",
",",
"ok",
":=",
"ctx",
".",
"machines",
"[",
"tag",
"]",
"\n",
"if",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"w",
",",
"err",
":=",
"newMach... | // watchMachine starts a machine watcher if there is not already one for the
// specified tag. The watcher will notify the worker when the machine changes,
// for example when it is provisioned. | [
"watchMachine",
"starts",
"a",
"machine",
"watcher",
"if",
"there",
"is",
"not",
"already",
"one",
"for",
"the",
"specified",
"tag",
".",
"The",
"watcher",
"will",
"notify",
"the",
"worker",
"when",
"the",
"machine",
"changes",
"for",
"example",
"when",
"it"... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/machines.go#L19-L32 |
4,777 | juju/juju | worker/storageprovisioner/machines.go | refreshMachine | func refreshMachine(ctx *context, tag names.MachineTag) error {
w, ok := ctx.machines[tag]
if !ok {
return errors.Errorf("machine %s is not being watched", tag.Id())
}
stopAndRemove := func() error {
worker.Stop(w)
delete(ctx.machines, tag)
return nil
}
results, err := ctx.config.Machines.InstanceIds([]names.MachineTag{tag})
if err != nil {
return errors.Annotate(err, "getting machine instance ID")
}
if err := results[0].Error; err != nil {
if params.IsCodeNotProvisioned(err) {
return nil
} else if params.IsCodeNotFound(err) {
// Machine is gone, so stop watching.
return stopAndRemove()
}
return errors.Annotate(err, "getting machine instance ID")
}
machineProvisioned(ctx, tag, instance.Id(results[0].Result))
// machine provisioning is the only thing we care about;
// stop the watcher.
return stopAndRemove()
} | go | func refreshMachine(ctx *context, tag names.MachineTag) error {
w, ok := ctx.machines[tag]
if !ok {
return errors.Errorf("machine %s is not being watched", tag.Id())
}
stopAndRemove := func() error {
worker.Stop(w)
delete(ctx.machines, tag)
return nil
}
results, err := ctx.config.Machines.InstanceIds([]names.MachineTag{tag})
if err != nil {
return errors.Annotate(err, "getting machine instance ID")
}
if err := results[0].Error; err != nil {
if params.IsCodeNotProvisioned(err) {
return nil
} else if params.IsCodeNotFound(err) {
// Machine is gone, so stop watching.
return stopAndRemove()
}
return errors.Annotate(err, "getting machine instance ID")
}
machineProvisioned(ctx, tag, instance.Id(results[0].Result))
// machine provisioning is the only thing we care about;
// stop the watcher.
return stopAndRemove()
} | [
"func",
"refreshMachine",
"(",
"ctx",
"*",
"context",
",",
"tag",
"names",
".",
"MachineTag",
")",
"error",
"{",
"w",
",",
"ok",
":=",
"ctx",
".",
"machines",
"[",
"tag",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\""... | // refreshMachine refreshes the specified machine's instance ID. If it is set,
// then the machine watcher is stopped and pending entities' parameters are
// updated. If the machine is not provisioned yet, this method is a no-op. | [
"refreshMachine",
"refreshes",
"the",
"specified",
"machine",
"s",
"instance",
"ID",
".",
"If",
"it",
"is",
"set",
"then",
"the",
"machine",
"watcher",
"is",
"stopped",
"and",
"pending",
"entities",
"parameters",
"are",
"updated",
".",
"If",
"the",
"machine",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/machines.go#L37-L64 |
4,778 | juju/juju | worker/storageprovisioner/machines.go | machineProvisioned | func machineProvisioned(ctx *context, tag names.MachineTag, instanceId instance.Id) {
for _, params := range ctx.incompleteVolumeParams {
if params.Attachment.Machine != tag || params.Attachment.InstanceId != "" {
continue
}
params.Attachment.InstanceId = instanceId
updatePendingVolume(ctx, params)
}
for id, params := range ctx.incompleteVolumeAttachmentParams {
if params.Machine != tag || params.InstanceId != "" {
continue
}
params.InstanceId = instanceId
updatePendingVolumeAttachment(ctx, id, params)
}
for id, params := range ctx.incompleteFilesystemAttachmentParams {
if params.Machine != tag || params.InstanceId != "" {
continue
}
params.InstanceId = instanceId
updatePendingFilesystemAttachment(ctx, id, params)
}
} | go | func machineProvisioned(ctx *context, tag names.MachineTag, instanceId instance.Id) {
for _, params := range ctx.incompleteVolumeParams {
if params.Attachment.Machine != tag || params.Attachment.InstanceId != "" {
continue
}
params.Attachment.InstanceId = instanceId
updatePendingVolume(ctx, params)
}
for id, params := range ctx.incompleteVolumeAttachmentParams {
if params.Machine != tag || params.InstanceId != "" {
continue
}
params.InstanceId = instanceId
updatePendingVolumeAttachment(ctx, id, params)
}
for id, params := range ctx.incompleteFilesystemAttachmentParams {
if params.Machine != tag || params.InstanceId != "" {
continue
}
params.InstanceId = instanceId
updatePendingFilesystemAttachment(ctx, id, params)
}
} | [
"func",
"machineProvisioned",
"(",
"ctx",
"*",
"context",
",",
"tag",
"names",
".",
"MachineTag",
",",
"instanceId",
"instance",
".",
"Id",
")",
"{",
"for",
"_",
",",
"params",
":=",
"range",
"ctx",
".",
"incompleteVolumeParams",
"{",
"if",
"params",
".",
... | // machineProvisioned is called when a watched machine is provisioned. | [
"machineProvisioned",
"is",
"called",
"when",
"a",
"watched",
"machine",
"is",
"provisioned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/machines.go#L67-L89 |
4,779 | juju/juju | worker/globalclockupdater/manifold.go | Manifold | func Manifold(config ManifoldConfig) dependency.Manifold {
inputs := []string{config.ClockName}
if config.StateName != "" {
inputs = append(inputs, config.StateName)
} else {
inputs = append(inputs, config.LeaseManagerName)
}
if config.RaftName != "" {
inputs = append(inputs, config.RaftName)
}
return dependency.Manifold{
Inputs: inputs,
Start: config.start,
}
} | go | func Manifold(config ManifoldConfig) dependency.Manifold {
inputs := []string{config.ClockName}
if config.StateName != "" {
inputs = append(inputs, config.StateName)
} else {
inputs = append(inputs, config.LeaseManagerName)
}
if config.RaftName != "" {
inputs = append(inputs, config.RaftName)
}
return dependency.Manifold{
Inputs: inputs,
Start: config.start,
}
} | [
"func",
"Manifold",
"(",
"config",
"ManifoldConfig",
")",
"dependency",
".",
"Manifold",
"{",
"inputs",
":=",
"[",
"]",
"string",
"{",
"config",
".",
"ClockName",
"}",
"\n",
"if",
"config",
".",
"StateName",
"!=",
"\"",
"\"",
"{",
"inputs",
"=",
"append"... | // Manifold returns a dependency.Manifold that will run a global clock
// updater worker. | [
"Manifold",
"returns",
"a",
"dependency",
".",
"Manifold",
"that",
"will",
"run",
"a",
"global",
"clock",
"updater",
"worker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/globalclockupdater/manifold.go#L62-L76 |
4,780 | juju/juju | core/cache/lxdprofilewatcher.go | init | func (w *MachineLXDProfileWatcher) init(machine *Machine) error {
units, err := machine.Units()
if err != nil {
return errors.Annotatef(err, "failed to get units to start MachineLXDProfileWatcher")
}
for _, unit := range units {
appName := unit.Application()
unitName := unit.Name()
if info, found := w.applications[appName]; found {
info.units.Add(unitName)
continue
}
app, err := w.modeler.Application(appName)
if errors.IsNotFound(err) {
// This is unlikely, but could happen because Units()
// added the parent'd machine id to subordinates.
// If the unit has no machineId, it will be added
// to what is watched when the machineId is assigned.
// Otherwise return an error.
if unit.MachineId() != "" {
return errors.Errorf("programming error, unit %s has machineId but not application", unitName)
}
logger.Errorf("unit %s has no application, nor machine id, start watching when machine id assigned.", unitName)
w.metrics.LXDProfileChangeError.Inc()
continue
}
chURL := app.CharmURL()
info := appInfo{
charmURL: chURL,
units: set.NewStrings(unitName),
}
ch, err := w.modeler.Charm(chURL)
if err != nil {
return err
}
lxdProfile := ch.LXDProfile()
if !lxdProfile.Empty() {
info.charmProfile = lxdProfile
}
w.applications[appName] = info
}
return nil
} | go | func (w *MachineLXDProfileWatcher) init(machine *Machine) error {
units, err := machine.Units()
if err != nil {
return errors.Annotatef(err, "failed to get units to start MachineLXDProfileWatcher")
}
for _, unit := range units {
appName := unit.Application()
unitName := unit.Name()
if info, found := w.applications[appName]; found {
info.units.Add(unitName)
continue
}
app, err := w.modeler.Application(appName)
if errors.IsNotFound(err) {
// This is unlikely, but could happen because Units()
// added the parent'd machine id to subordinates.
// If the unit has no machineId, it will be added
// to what is watched when the machineId is assigned.
// Otherwise return an error.
if unit.MachineId() != "" {
return errors.Errorf("programming error, unit %s has machineId but not application", unitName)
}
logger.Errorf("unit %s has no application, nor machine id, start watching when machine id assigned.", unitName)
w.metrics.LXDProfileChangeError.Inc()
continue
}
chURL := app.CharmURL()
info := appInfo{
charmURL: chURL,
units: set.NewStrings(unitName),
}
ch, err := w.modeler.Charm(chURL)
if err != nil {
return err
}
lxdProfile := ch.LXDProfile()
if !lxdProfile.Empty() {
info.charmProfile = lxdProfile
}
w.applications[appName] = info
}
return nil
} | [
"func",
"(",
"w",
"*",
"MachineLXDProfileWatcher",
")",
"init",
"(",
"machine",
"*",
"Machine",
")",
"error",
"{",
"units",
",",
"err",
":=",
"machine",
".",
"Units",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
... | // init sets up the initial data used to determine when a notify occurs. | [
"init",
"sets",
"up",
"the",
"initial",
"data",
"used",
"to",
"determine",
"when",
"a",
"notify",
"occurs",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/lxdprofilewatcher.go#L91-L139 |
4,781 | juju/juju | core/cache/lxdprofilewatcher.go | applicationCharmURLChange | func (w *MachineLXDProfileWatcher) applicationCharmURLChange(topic string, value interface{}) {
// We don't want to respond to any events until we have been fully initialized.
select {
case <-w.initialized:
case <-w.tomb.Dying():
return
}
var notify bool
defer func(notify *bool) {
if *notify {
w.notify()
w.metrics.LXDProfileChangeHit.Inc()
} else {
w.metrics.LXDProfileChangeMiss.Inc()
}
}(¬ify)
values, ok := value.(appCharmUrlChange)
if !ok {
w.logError("programming error, value not of type appCharmUrlChange")
return
}
appName, chURL := values.appName, values.chURL
info, ok := w.applications[appName]
if ok {
ch, err := w.modeler.Charm(chURL)
if err != nil {
w.logError(fmt.Sprintf("error getting charm %s to evaluate for lxd profile notification: %s", chURL, err))
return
}
// notify if:
// 1. the prior charm had a profile and the new one does not.
// 2. the new profile is not empty.
lxdProfile := ch.LXDProfile()
if (!info.charmProfile.Empty() && lxdProfile.Empty()) || !lxdProfile.Empty() {
logger.Tracef("notifying due to change of charm lxd profile for %s, machine-%s", appName, w.machineId)
notify = true
} else {
logger.Tracef("no notification of charm lxd profile needed for %s, machine-%s", appName, w.machineId)
}
info.charmProfile = lxdProfile
info.charmURL = chURL
w.applications[appName] = info
} else {
logger.Tracef("not watching %s on machine-%s", appName, w.machineId)
}
logger.Tracef("end of application charm url change %#v", w.applications)
} | go | func (w *MachineLXDProfileWatcher) applicationCharmURLChange(topic string, value interface{}) {
// We don't want to respond to any events until we have been fully initialized.
select {
case <-w.initialized:
case <-w.tomb.Dying():
return
}
var notify bool
defer func(notify *bool) {
if *notify {
w.notify()
w.metrics.LXDProfileChangeHit.Inc()
} else {
w.metrics.LXDProfileChangeMiss.Inc()
}
}(¬ify)
values, ok := value.(appCharmUrlChange)
if !ok {
w.logError("programming error, value not of type appCharmUrlChange")
return
}
appName, chURL := values.appName, values.chURL
info, ok := w.applications[appName]
if ok {
ch, err := w.modeler.Charm(chURL)
if err != nil {
w.logError(fmt.Sprintf("error getting charm %s to evaluate for lxd profile notification: %s", chURL, err))
return
}
// notify if:
// 1. the prior charm had a profile and the new one does not.
// 2. the new profile is not empty.
lxdProfile := ch.LXDProfile()
if (!info.charmProfile.Empty() && lxdProfile.Empty()) || !lxdProfile.Empty() {
logger.Tracef("notifying due to change of charm lxd profile for %s, machine-%s", appName, w.machineId)
notify = true
} else {
logger.Tracef("no notification of charm lxd profile needed for %s, machine-%s", appName, w.machineId)
}
info.charmProfile = lxdProfile
info.charmURL = chURL
w.applications[appName] = info
} else {
logger.Tracef("not watching %s on machine-%s", appName, w.machineId)
}
logger.Tracef("end of application charm url change %#v", w.applications)
} | [
"func",
"(",
"w",
"*",
"MachineLXDProfileWatcher",
")",
"applicationCharmURLChange",
"(",
"topic",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"// We don't want to respond to any events until we have been fully initialized.",
"select",
"{",
"case",
"<-",
"w",... | // applicationCharmURLChange sends a notification if what is saved for its
// charm lxdprofile changes. No notification is sent if the profile pointer
// begins and ends as nil. | [
"applicationCharmURLChange",
"sends",
"a",
"notification",
"if",
"what",
"is",
"saved",
"for",
"its",
"charm",
"lxdprofile",
"changes",
".",
"No",
"notification",
"is",
"sent",
"if",
"the",
"profile",
"pointer",
"begins",
"and",
"ends",
"as",
"nil",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/lxdprofilewatcher.go#L144-L193 |
4,782 | juju/juju | core/cache/lxdprofilewatcher.go | addUnit | func (w *MachineLXDProfileWatcher) addUnit(topic string, value interface{}) {
// We don't want to respond to any events until we have been fully initialized.
select {
case <-w.initialized:
case <-w.tomb.Dying():
return
}
var notify bool
defer func(notify *bool) {
if *notify {
logger.Tracef("notifying due to add unit requires lxd profile change machine-%s", w.machineId)
w.notify()
w.metrics.LXDProfileChangeHit.Inc()
} else {
w.metrics.LXDProfileChangeMiss.Inc()
}
}(¬ify)
unit, okUnit := value.(*Unit)
if !okUnit {
w.logError("programming error, value not of type *Unit")
return
}
isSubordinate := unit.Subordinate()
unitMachineId := unit.MachineId()
unitName := unit.Name()
switch {
case unitMachineId == "" && !isSubordinate:
logger.Tracef("%s has no machineId and not a sub", unitName)
return
case isSubordinate:
principal, err := w.modeler.Unit(unit.Principal())
if err != nil {
logger.Tracef("unit %s is subordinate, principal %s not found", unitName, unit.Principal())
return
}
if w.machineId != principal.MachineId() {
logger.Tracef("watching unit changes on machine-%s not machine-%s", w.machineId, unitMachineId)
return
}
case w.machineId != unitMachineId:
logger.Tracef("watching unit changes on machine-%s not machine-%s", w.machineId, unitMachineId)
return
}
logger.Tracef("start watching %q on machine-%s", unitName, w.machineId)
notify = w.add(unit)
logger.Debugf("end of unit change %#v", w.applications)
} | go | func (w *MachineLXDProfileWatcher) addUnit(topic string, value interface{}) {
// We don't want to respond to any events until we have been fully initialized.
select {
case <-w.initialized:
case <-w.tomb.Dying():
return
}
var notify bool
defer func(notify *bool) {
if *notify {
logger.Tracef("notifying due to add unit requires lxd profile change machine-%s", w.machineId)
w.notify()
w.metrics.LXDProfileChangeHit.Inc()
} else {
w.metrics.LXDProfileChangeMiss.Inc()
}
}(¬ify)
unit, okUnit := value.(*Unit)
if !okUnit {
w.logError("programming error, value not of type *Unit")
return
}
isSubordinate := unit.Subordinate()
unitMachineId := unit.MachineId()
unitName := unit.Name()
switch {
case unitMachineId == "" && !isSubordinate:
logger.Tracef("%s has no machineId and not a sub", unitName)
return
case isSubordinate:
principal, err := w.modeler.Unit(unit.Principal())
if err != nil {
logger.Tracef("unit %s is subordinate, principal %s not found", unitName, unit.Principal())
return
}
if w.machineId != principal.MachineId() {
logger.Tracef("watching unit changes on machine-%s not machine-%s", w.machineId, unitMachineId)
return
}
case w.machineId != unitMachineId:
logger.Tracef("watching unit changes on machine-%s not machine-%s", w.machineId, unitMachineId)
return
}
logger.Tracef("start watching %q on machine-%s", unitName, w.machineId)
notify = w.add(unit)
logger.Debugf("end of unit change %#v", w.applications)
} | [
"func",
"(",
"w",
"*",
"MachineLXDProfileWatcher",
")",
"addUnit",
"(",
"topic",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"// We don't want to respond to any events until we have been fully initialized.",
"select",
"{",
"case",
"<-",
"w",
".",
"initial... | // addUnit modifies the map of applications being watched when a unit is
// added to the machine. Notification is sent if a new unit whose charm has
// an lxd profile is added. | [
"addUnit",
"modifies",
"the",
"map",
"of",
"applications",
"being",
"watched",
"when",
"a",
"unit",
"is",
"added",
"to",
"the",
"machine",
".",
"Notification",
"is",
"sent",
"if",
"a",
"new",
"unit",
"whose",
"charm",
"has",
"an",
"lxd",
"profile",
"is",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/lxdprofilewatcher.go#L198-L247 |
4,783 | juju/juju | core/cache/lxdprofilewatcher.go | removeUnit | func (w *MachineLXDProfileWatcher) removeUnit(topic string, value interface{}) {
// We don't want to respond to any events until we have been fully initialized.
select {
case <-w.initialized:
case <-w.tomb.Dying():
return
}
var notify bool
defer func(notify *bool) {
if *notify {
logger.Tracef("notifying due to remove unit requires lxd profile change machine-%s", w.machineId)
w.notify()
w.metrics.LXDProfileChangeHit.Inc()
} else {
w.metrics.LXDProfileChangeMiss.Inc()
}
}(¬ify)
rUnit, ok := value.(unitLXDProfileRemove)
if !ok {
w.logError("programming error, value not of type unitLXDProfileRemove")
return
}
app, ok := w.applications[rUnit.appName]
if !ok {
w.logError("programming error, unit removed before being added, application name not found")
return
}
if !app.units.Contains(rUnit.name) {
return
}
profile := app.charmProfile
app.units.Remove(rUnit.name)
if app.units.Size() == 0 {
// the application has no more units on this machine,
// stop watching it.
delete(w.applications, rUnit.appName)
}
// If there are additional units on the machine and the current
// application has an lxd profile, notify so it can be removed
// from the machine.
if len(w.applications) > 0 && !profile.Empty() {
notify = true
}
return
} | go | func (w *MachineLXDProfileWatcher) removeUnit(topic string, value interface{}) {
// We don't want to respond to any events until we have been fully initialized.
select {
case <-w.initialized:
case <-w.tomb.Dying():
return
}
var notify bool
defer func(notify *bool) {
if *notify {
logger.Tracef("notifying due to remove unit requires lxd profile change machine-%s", w.machineId)
w.notify()
w.metrics.LXDProfileChangeHit.Inc()
} else {
w.metrics.LXDProfileChangeMiss.Inc()
}
}(¬ify)
rUnit, ok := value.(unitLXDProfileRemove)
if !ok {
w.logError("programming error, value not of type unitLXDProfileRemove")
return
}
app, ok := w.applications[rUnit.appName]
if !ok {
w.logError("programming error, unit removed before being added, application name not found")
return
}
if !app.units.Contains(rUnit.name) {
return
}
profile := app.charmProfile
app.units.Remove(rUnit.name)
if app.units.Size() == 0 {
// the application has no more units on this machine,
// stop watching it.
delete(w.applications, rUnit.appName)
}
// If there are additional units on the machine and the current
// application has an lxd profile, notify so it can be removed
// from the machine.
if len(w.applications) > 0 && !profile.Empty() {
notify = true
}
return
} | [
"func",
"(",
"w",
"*",
"MachineLXDProfileWatcher",
")",
"removeUnit",
"(",
"topic",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"// We don't want to respond to any events until we have been fully initialized.",
"select",
"{",
"case",
"<-",
"w",
".",
"init... | // removeUnit modifies the map of applications being watched when a unit is
// removed from the machine. Notification is sent if a unit being removed
// has a profile and other units exist on the machine. | [
"removeUnit",
"modifies",
"the",
"map",
"of",
"applications",
"being",
"watched",
"when",
"a",
"unit",
"is",
"removed",
"from",
"the",
"machine",
".",
"Notification",
"is",
"sent",
"if",
"a",
"unit",
"being",
"removed",
"has",
"a",
"profile",
"and",
"other",... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/lxdprofilewatcher.go#L292-L338 |
4,784 | juju/juju | core/cache/lxdprofilewatcher.go | provisionedChange | func (w *MachineLXDProfileWatcher) provisionedChange(topic string, _ interface{}) {
// We don't want to respond to any events until we have been fully initialized.
select {
case <-w.initialized:
case <-w.tomb.Dying():
return
}
logger.Tracef("notifying due to machine-%s now provisioned", w.machineId)
w.metrics.LXDProfileChangeHit.Inc()
w.notify()
} | go | func (w *MachineLXDProfileWatcher) provisionedChange(topic string, _ interface{}) {
// We don't want to respond to any events until we have been fully initialized.
select {
case <-w.initialized:
case <-w.tomb.Dying():
return
}
logger.Tracef("notifying due to machine-%s now provisioned", w.machineId)
w.metrics.LXDProfileChangeHit.Inc()
w.notify()
} | [
"func",
"(",
"w",
"*",
"MachineLXDProfileWatcher",
")",
"provisionedChange",
"(",
"topic",
"string",
",",
"_",
"interface",
"{",
"}",
")",
"{",
"// We don't want to respond to any events until we have been fully initialized.",
"select",
"{",
"case",
"<-",
"w",
".",
"i... | // provisionedChanged notifies when called. Topic subscribed to is specific to
// this machine. | [
"provisionedChanged",
"notifies",
"when",
"called",
".",
"Topic",
"subscribed",
"to",
"is",
"specific",
"to",
"this",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/lxdprofilewatcher.go#L342-L353 |
4,785 | juju/juju | state/machine.go | ToParams | func (job MachineJob) ToParams() multiwatcher.MachineJob {
if jujuJob, ok := jobNames[job]; ok {
return jujuJob
}
return multiwatcher.MachineJob(fmt.Sprintf("<unknown job %d>", int(job)))
} | go | func (job MachineJob) ToParams() multiwatcher.MachineJob {
if jujuJob, ok := jobNames[job]; ok {
return jujuJob
}
return multiwatcher.MachineJob(fmt.Sprintf("<unknown job %d>", int(job)))
} | [
"func",
"(",
"job",
"MachineJob",
")",
"ToParams",
"(",
")",
"multiwatcher",
".",
"MachineJob",
"{",
"if",
"jujuJob",
",",
"ok",
":=",
"jobNames",
"[",
"job",
"]",
";",
"ok",
"{",
"return",
"jujuJob",
"\n",
"}",
"\n",
"return",
"multiwatcher",
".",
"Ma... | // ToParams returns the job as multiwatcher.MachineJob. | [
"ToParams",
"returns",
"the",
"job",
"as",
"multiwatcher",
".",
"MachineJob",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L61-L66 |
4,786 | juju/juju | state/machine.go | paramsJobsFromJobs | func paramsJobsFromJobs(jobs []MachineJob) []multiwatcher.MachineJob {
jujuJobs := make([]multiwatcher.MachineJob, len(jobs))
for i, machineJob := range jobs {
jujuJobs[i] = machineJob.ToParams()
}
return jujuJobs
} | go | func paramsJobsFromJobs(jobs []MachineJob) []multiwatcher.MachineJob {
jujuJobs := make([]multiwatcher.MachineJob, len(jobs))
for i, machineJob := range jobs {
jujuJobs[i] = machineJob.ToParams()
}
return jujuJobs
} | [
"func",
"paramsJobsFromJobs",
"(",
"jobs",
"[",
"]",
"MachineJob",
")",
"[",
"]",
"multiwatcher",
".",
"MachineJob",
"{",
"jujuJobs",
":=",
"make",
"(",
"[",
"]",
"multiwatcher",
".",
"MachineJob",
",",
"len",
"(",
"jobs",
")",
")",
"\n",
"for",
"i",
"... | // params.JobsFromJobs converts state jobs to juju jobs. | [
"params",
".",
"JobsFromJobs",
"converts",
"state",
"jobs",
"to",
"juju",
"jobs",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L69-L75 |
4,787 | juju/juju | state/machine.go | MigrationValue | func (job MachineJob) MigrationValue() string {
if value, ok := jobMigrationValue[job]; ok {
return value
}
return "unknown"
} | go | func (job MachineJob) MigrationValue() string {
if value, ok := jobMigrationValue[job]; ok {
return value
}
return "unknown"
} | [
"func",
"(",
"job",
"MachineJob",
")",
"MigrationValue",
"(",
")",
"string",
"{",
"if",
"value",
",",
"ok",
":=",
"jobMigrationValue",
"[",
"job",
"]",
";",
"ok",
"{",
"return",
"value",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // MigrationValue converts the state job into a useful human readable
// string for model migration. | [
"MigrationValue",
"converts",
"the",
"state",
"job",
"into",
"a",
"useful",
"human",
"readable",
"string",
"for",
"model",
"migration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L79-L84 |
4,788 | juju/juju | state/machine.go | ContainerType | func (m *Machine) ContainerType() instance.ContainerType {
return instance.ContainerType(m.doc.ContainerType)
} | go | func (m *Machine) ContainerType() instance.ContainerType {
return instance.ContainerType(m.doc.ContainerType)
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"ContainerType",
"(",
")",
"instance",
".",
"ContainerType",
"{",
"return",
"instance",
".",
"ContainerType",
"(",
"m",
".",
"doc",
".",
"ContainerType",
")",
"\n",
"}"
] | // ContainerType returns the type of container hosting this machine. | [
"ContainerType",
"returns",
"the",
"type",
"of",
"container",
"hosting",
"this",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L174-L176 |
4,789 | juju/juju | state/machine.go | SetKeepInstance | func (m *Machine) SetKeepInstance(keepInstance bool) error {
ops := []txn.Op{{
C: instanceDataC,
Id: m.doc.DocID,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"keep-instance", keepInstance}}}},
}}
if err := m.st.db().RunTransaction(ops); err != nil {
// If instance doc doesn't exist, that's ok; there's nothing to keep,
// but that's not an error we care about.
return errors.Annotatef(onAbort(err, nil), "cannot set KeepInstance on machine %v", m)
}
return nil
} | go | func (m *Machine) SetKeepInstance(keepInstance bool) error {
ops := []txn.Op{{
C: instanceDataC,
Id: m.doc.DocID,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"keep-instance", keepInstance}}}},
}}
if err := m.st.db().RunTransaction(ops); err != nil {
// If instance doc doesn't exist, that's ok; there's nothing to keep,
// but that's not an error we care about.
return errors.Annotatef(onAbort(err, nil), "cannot set KeepInstance on machine %v", m)
}
return nil
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"SetKeepInstance",
"(",
"keepInstance",
"bool",
")",
"error",
"{",
"ops",
":=",
"[",
"]",
"txn",
".",
"Op",
"{",
"{",
"C",
":",
"instanceDataC",
",",
"Id",
":",
"m",
".",
"doc",
".",
"DocID",
",",
"Assert",
... | // SetKeepInstance sets whether the cloud machine instance
// will be retained when the machine is removed from Juju.
// This is only relevant if an instance exists. | [
"SetKeepInstance",
"sets",
"whether",
"the",
"cloud",
"machine",
"instance",
"will",
"be",
"retained",
"when",
"the",
"machine",
"is",
"removed",
"from",
"Juju",
".",
"This",
"is",
"only",
"relevant",
"if",
"an",
"instance",
"exists",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L308-L321 |
4,790 | juju/juju | state/machine.go | KeepInstance | func (m *Machine) KeepInstance() (bool, error) {
instData, err := getInstanceData(m.st, m.Id())
if err != nil {
return false, err
}
return instData.KeepInstance, nil
} | go | func (m *Machine) KeepInstance() (bool, error) {
instData, err := getInstanceData(m.st, m.Id())
if err != nil {
return false, err
}
return instData.KeepInstance, nil
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"KeepInstance",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"instData",
",",
"err",
":=",
"getInstanceData",
"(",
"m",
".",
"st",
",",
"m",
".",
"Id",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",... | // KeepInstance reports whether a machine, when removed from
// Juju, will cause the corresponding cloud instance to be stopped. | [
"KeepInstance",
"reports",
"whether",
"a",
"machine",
"when",
"removed",
"from",
"Juju",
"will",
"cause",
"the",
"corresponding",
"cloud",
"instance",
"to",
"be",
"stopped",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L325-L331 |
4,791 | juju/juju | state/machine.go | CharmProfiles | func (m *Machine) CharmProfiles() ([]string, error) {
instData, err := getInstanceData(m.st, m.Id())
if errors.IsNotFound(err) {
err = errors.NotProvisionedf("machine %v", m.Id())
}
if err != nil {
return nil, err
}
return instData.CharmProfiles, nil
} | go | func (m *Machine) CharmProfiles() ([]string, error) {
instData, err := getInstanceData(m.st, m.Id())
if errors.IsNotFound(err) {
err = errors.NotProvisionedf("machine %v", m.Id())
}
if err != nil {
return nil, err
}
return instData.CharmProfiles, nil
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"CharmProfiles",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"instData",
",",
"err",
":=",
"getInstanceData",
"(",
"m",
".",
"st",
",",
"m",
".",
"Id",
"(",
")",
")",
"\n",
"if",
"errors",
"... | // CharmProfiles returns the names of any LXD profiles used by the machine,
// which were defined in the charm deployed to that machine. | [
"CharmProfiles",
"returns",
"the",
"names",
"of",
"any",
"LXD",
"profiles",
"used",
"by",
"the",
"machine",
"which",
"were",
"defined",
"in",
"the",
"charm",
"deployed",
"to",
"that",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L335-L344 |
4,792 | juju/juju | state/machine.go | SetCharmProfiles | func (m *Machine) SetCharmProfiles(profiles []string) error {
if len(profiles) == 0 {
return nil
}
buildTxn := func(attempt int) ([]txn.Op, error) {
if attempt > 0 {
if err := m.Refresh(); err != nil {
return nil, errors.Trace(err)
}
}
// Exit early if the Machine profiles doesn't need to change.
mProfiles, err := m.CharmProfiles()
if err != nil {
return nil, errors.Trace(err)
}
mProfilesSet := set.NewStrings(mProfiles...)
if mProfilesSet.Union(set.NewStrings(profiles...)).Size() == mProfilesSet.Size() {
return nil, jujutxn.ErrNoOperations
}
ops := []txn.Op{{
C: instanceDataC,
Id: m.doc.DocID,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"charm-profiles", profiles}}}},
}}
return ops, nil
}
err := m.st.db().Run(buildTxn)
return errors.Annotatef(err, "cannot update profiles for %q to %s", m, strings.Join(profiles, ", "))
} | go | func (m *Machine) SetCharmProfiles(profiles []string) error {
if len(profiles) == 0 {
return nil
}
buildTxn := func(attempt int) ([]txn.Op, error) {
if attempt > 0 {
if err := m.Refresh(); err != nil {
return nil, errors.Trace(err)
}
}
// Exit early if the Machine profiles doesn't need to change.
mProfiles, err := m.CharmProfiles()
if err != nil {
return nil, errors.Trace(err)
}
mProfilesSet := set.NewStrings(mProfiles...)
if mProfilesSet.Union(set.NewStrings(profiles...)).Size() == mProfilesSet.Size() {
return nil, jujutxn.ErrNoOperations
}
ops := []txn.Op{{
C: instanceDataC,
Id: m.doc.DocID,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"charm-profiles", profiles}}}},
}}
return ops, nil
}
err := m.st.db().Run(buildTxn)
return errors.Annotatef(err, "cannot update profiles for %q to %s", m, strings.Join(profiles, ", "))
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"SetCharmProfiles",
"(",
"profiles",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"len",
"(",
"profiles",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"buildTxn",
":=",
"func",
"(",
"attempt",
"int",
... | // SetCharmProfiles sets the names of the charm profiles used on a machine
// in its instanceData. | [
"SetCharmProfiles",
"sets",
"the",
"names",
"of",
"the",
"charm",
"profiles",
"used",
"on",
"a",
"machine",
"in",
"its",
"instanceData",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L348-L379 |
4,793 | juju/juju | state/machine.go | WantsVote | func (m *Machine) WantsVote() bool {
return wantsVote(m.doc.Jobs, m.doc.NoVote)
} | go | func (m *Machine) WantsVote() bool {
return wantsVote(m.doc.Jobs, m.doc.NoVote)
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"WantsVote",
"(",
")",
"bool",
"{",
"return",
"wantsVote",
"(",
"m",
".",
"doc",
".",
"Jobs",
",",
"m",
".",
"doc",
".",
"NoVote",
")",
"\n",
"}"
] | // WantsVote reports whether the machine is a controller
// that wants to take part in peer voting. | [
"WantsVote",
"reports",
"whether",
"the",
"machine",
"is",
"a",
"controller",
"that",
"wants",
"to",
"take",
"part",
"in",
"peer",
"voting",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L383-L385 |
4,794 | juju/juju | state/machine.go | SetHasVote | func (m *Machine) SetHasVote(hasVote bool) error {
op := m.UpdateOperation()
op.HasVote = &hasVote
if err := m.st.ApplyOperation(op); err != nil {
return errors.Trace(err)
}
m.doc.HasVote = hasVote
return nil
} | go | func (m *Machine) SetHasVote(hasVote bool) error {
op := m.UpdateOperation()
op.HasVote = &hasVote
if err := m.st.ApplyOperation(op); err != nil {
return errors.Trace(err)
}
m.doc.HasVote = hasVote
return nil
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"SetHasVote",
"(",
"hasVote",
"bool",
")",
"error",
"{",
"op",
":=",
"m",
".",
"UpdateOperation",
"(",
")",
"\n",
"op",
".",
"HasVote",
"=",
"&",
"hasVote",
"\n",
"if",
"err",
":=",
"m",
".",
"st",
".",
"App... | // SetHasVote sets whether the machine is currently a voting
// member of the replica set. It should only be called
// from the worker that maintains the replica set. | [
"SetHasVote",
"sets",
"whether",
"the",
"machine",
"is",
"currently",
"a",
"voting",
"member",
"of",
"the",
"replica",
"set",
".",
"It",
"should",
"only",
"be",
"called",
"from",
"the",
"worker",
"that",
"maintains",
"the",
"replica",
"set",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L396-L404 |
4,795 | juju/juju | state/machine.go | SetStopMongoUntilVersion | func (m *Machine) SetStopMongoUntilVersion(v mongo.Version) error {
ops := []txn.Op{{
C: machinesC,
Id: m.doc.DocID,
Update: bson.D{{"$set", bson.D{{"stopmongountilversion", v.String()}}}},
}}
if err := m.st.db().RunTransaction(ops); err != nil {
return fmt.Errorf("cannot set StopMongoUntilVersion %v: %v", m, onAbort(err, ErrDead))
}
m.doc.StopMongoUntilVersion = v.String()
return nil
} | go | func (m *Machine) SetStopMongoUntilVersion(v mongo.Version) error {
ops := []txn.Op{{
C: machinesC,
Id: m.doc.DocID,
Update: bson.D{{"$set", bson.D{{"stopmongountilversion", v.String()}}}},
}}
if err := m.st.db().RunTransaction(ops); err != nil {
return fmt.Errorf("cannot set StopMongoUntilVersion %v: %v", m, onAbort(err, ErrDead))
}
m.doc.StopMongoUntilVersion = v.String()
return nil
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"SetStopMongoUntilVersion",
"(",
"v",
"mongo",
".",
"Version",
")",
"error",
"{",
"ops",
":=",
"[",
"]",
"txn",
".",
"Op",
"{",
"{",
"C",
":",
"machinesC",
",",
"Id",
":",
"m",
".",
"doc",
".",
"DocID",
",",... | // SetStopMongoUntilVersion sets a version that is to be checked against
// the agent config before deciding if mongo must be started on a
// state server. | [
"SetStopMongoUntilVersion",
"sets",
"a",
"version",
"that",
"is",
"to",
"be",
"checked",
"against",
"the",
"agent",
"config",
"before",
"deciding",
"if",
"mongo",
"must",
"be",
"started",
"on",
"a",
"state",
"server",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L422-L433 |
4,796 | juju/juju | state/machine.go | StopMongoUntilVersion | func (m *Machine) StopMongoUntilVersion() (mongo.Version, error) {
return mongo.NewVersion(m.doc.StopMongoUntilVersion)
} | go | func (m *Machine) StopMongoUntilVersion() (mongo.Version, error) {
return mongo.NewVersion(m.doc.StopMongoUntilVersion)
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"StopMongoUntilVersion",
"(",
")",
"(",
"mongo",
".",
"Version",
",",
"error",
")",
"{",
"return",
"mongo",
".",
"NewVersion",
"(",
"m",
".",
"doc",
".",
"StopMongoUntilVersion",
")",
"\n",
"}"
] | // StopMongoUntilVersion returns the current minimum version that
// is required for this machine to have mongo running. | [
"StopMongoUntilVersion",
"returns",
"the",
"current",
"minimum",
"version",
"that",
"is",
"required",
"for",
"this",
"machine",
"to",
"have",
"mongo",
"running",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L437-L439 |
4,797 | juju/juju | state/machine.go | IsManual | func (m *Machine) IsManual() (bool, error) {
// Apart from the bootstrap machine, manually provisioned
// machines have a nonce prefixed with "manual:". This is
// unique to manual provisioning.
if strings.HasPrefix(m.doc.Nonce, manualMachinePrefix) {
return true, nil
}
// The bootstrap machine uses BootstrapNonce, so in that
// case we need to check if its provider type is "manual".
// We also check for "null", which is an alias for manual.
if m.doc.Id == "0" {
model, err := m.st.Model()
if err != nil {
return false, errors.Trace(err)
}
cfg, err := model.ModelConfig()
if err != nil {
return false, err
}
t := cfg.Type()
return t == "null" || t == "manual", nil
}
return false, nil
} | go | func (m *Machine) IsManual() (bool, error) {
// Apart from the bootstrap machine, manually provisioned
// machines have a nonce prefixed with "manual:". This is
// unique to manual provisioning.
if strings.HasPrefix(m.doc.Nonce, manualMachinePrefix) {
return true, nil
}
// The bootstrap machine uses BootstrapNonce, so in that
// case we need to check if its provider type is "manual".
// We also check for "null", which is an alias for manual.
if m.doc.Id == "0" {
model, err := m.st.Model()
if err != nil {
return false, errors.Trace(err)
}
cfg, err := model.ModelConfig()
if err != nil {
return false, err
}
t := cfg.Type()
return t == "null" || t == "manual", nil
}
return false, nil
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"IsManual",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"// Apart from the bootstrap machine, manually provisioned",
"// machines have a nonce prefixed with \"manual:\". This is",
"// unique to manual provisioning.",
"if",
"strings",
... | // IsManual returns true if the machine was manually provisioned. | [
"IsManual",
"returns",
"true",
"if",
"the",
"machine",
"was",
"manually",
"provisioned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L447-L471 |
4,798 | juju/juju | state/machine.go | AgentTools | func (m *Machine) AgentTools() (*tools.Tools, error) {
if m.doc.Tools == nil {
return nil, errors.NotFoundf("agent binaries for machine %v", m)
}
tools := *m.doc.Tools
return &tools, nil
} | go | func (m *Machine) AgentTools() (*tools.Tools, error) {
if m.doc.Tools == nil {
return nil, errors.NotFoundf("agent binaries for machine %v", m)
}
tools := *m.doc.Tools
return &tools, nil
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"AgentTools",
"(",
")",
"(",
"*",
"tools",
".",
"Tools",
",",
"error",
")",
"{",
"if",
"m",
".",
"doc",
".",
"Tools",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"NotFoundf",
"(",
"\"",
"\"",
",... | // AgentTools returns the tools that the agent is currently running.
// It returns an error that satisfies errors.IsNotFound if the tools
// have not yet been set. | [
"AgentTools",
"returns",
"the",
"tools",
"that",
"the",
"agent",
"is",
"currently",
"running",
".",
"It",
"returns",
"an",
"error",
"that",
"satisfies",
"errors",
".",
"IsNotFound",
"if",
"the",
"tools",
"have",
"not",
"yet",
"been",
"set",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L476-L482 |
4,799 | juju/juju | state/machine.go | checkVersionValidity | func checkVersionValidity(v version.Binary) error {
if v.Series == "" || v.Arch == "" {
return fmt.Errorf("empty series or arch")
}
return nil
} | go | func checkVersionValidity(v version.Binary) error {
if v.Series == "" || v.Arch == "" {
return fmt.Errorf("empty series or arch")
}
return nil
} | [
"func",
"checkVersionValidity",
"(",
"v",
"version",
".",
"Binary",
")",
"error",
"{",
"if",
"v",
".",
"Series",
"==",
"\"",
"\"",
"||",
"v",
".",
"Arch",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n... | // checkVersionValidity checks whether the given version is suitable
// for passing to SetAgentVersion. | [
"checkVersionValidity",
"checks",
"whether",
"the",
"given",
"version",
"is",
"suitable",
"for",
"passing",
"to",
"SetAgentVersion",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machine.go#L486-L491 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.