github.com/cloud-green/juju@v0.0.0-20151002100041-a00291338d3d/worker/metrics/collect/context.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package collect 5 6 import ( 7 "fmt" 8 "math/rand" 9 "os" 10 "time" 11 12 "github.com/juju/errors" 13 14 "github.com/juju/juju/worker/metrics/spool" 15 "github.com/juju/juju/worker/uniter/runner/context" 16 "github.com/juju/juju/worker/uniter/runner/jujuc" 17 ) 18 19 type hookContext struct { 20 jujuc.RestrictedContext 21 22 unitName string 23 id string 24 recorder spool.MetricRecorder 25 } 26 27 func newHookContext(unitName string, recorder spool.MetricRecorder) *hookContext { 28 id := fmt.Sprintf("%s-%s-%d", unitName, "collect-metrics", rand.New(rand.NewSource(time.Now().Unix())).Int63()) 29 return &hookContext{unitName: unitName, id: id, recorder: recorder} 30 } 31 32 // HookVars implements runner.Context. 33 func (ctx *hookContext) HookVars(paths context.Paths) ([]string, error) { 34 vars := []string{ 35 "JUJU_CHARM_DIR=" + paths.GetCharmDir(), 36 "JUJU_CONTEXT_ID=" + ctx.id, 37 "JUJU_AGENT_SOCKET=" + paths.GetJujucSocket(), 38 "JUJU_UNIT_NAME=" + ctx.unitName, 39 } 40 return append(vars, context.OSDependentEnvVars(paths)...), nil 41 } 42 43 // UnitName implements runner.Context. 44 func (ctx *hookContext) UnitName() string { 45 return ctx.unitName 46 } 47 48 // Flush implements runner.Context. 49 func (ctx *hookContext) Flush(process string, ctxErr error) (err error) { 50 return ctx.recorder.Close() 51 } 52 53 // AddMetric implements runner.Context. 54 func (ctx *hookContext) AddMetric(key string, value string, created time.Time) error { 55 return ctx.recorder.AddMetric(key, value, created) 56 } 57 58 // addJujuUnitsMetric adds the juju-units built in metric if it 59 // is defined for this context. 60 func (ctx *hookContext) addJujuUnitsMetric() error { 61 if ctx.recorder.IsDeclaredMetric("juju-units") { 62 err := ctx.recorder.AddMetric("juju-units", "1", time.Now().UTC()) 63 if err != nil { 64 return errors.Trace(err) 65 } 66 } 67 return nil 68 } 69 70 // SetProcess implements runner.Context. 71 func (ctx *hookContext) SetProcess(process *os.Process) {} 72 73 // ActionData implements runner.Context. 74 func (ctx *hookContext) ActionData() (*context.ActionData, error) { 75 return nil, jujuc.ErrRestrictedContext 76 } 77 78 // HasExecutionSetUnitStatus implements runner.Context. 79 func (ctx *hookContext) HasExecutionSetUnitStatus() bool { return false } 80 81 // ResetExecutionSetUnitStatus implements runner.Context. 82 func (ctx *hookContext) ResetExecutionSetUnitStatus() {} 83 84 // Id implements runner.Context. 85 func (ctx *hookContext) Id() string { return ctx.id } 86 87 // Prepare implements runner.Context. 88 func (ctx *hookContext) Prepare() error { 89 return jujuc.ErrRestrictedContext 90 }