probe.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright (c) 2011 CZ.NIC z.s.p.o. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // blame: jnml, labs.nic.cz
  5. package storage
  6. import "sync/atomic"
  7. // Probe collects usage statistics of the embeded Accessor.
  8. // Probe itself IS an Accessor.
  9. type Probe struct {
  10. Accessor
  11. Chain *Probe
  12. OpsRd int64
  13. OpsWr int64
  14. BytesRd int64
  15. BytesWr int64
  16. SectorsRd int64 // Assuming 512 byte sector size
  17. SectorsWr int64
  18. }
  19. // NewProbe returns a newly created probe which embedes the src Accessor.
  20. // The retuned *Probe satisfies Accessor. if chain != nil then Reset()
  21. // is cascaded down the chained Probes.
  22. func NewProbe(src Accessor, chain *Probe) *Probe {
  23. return &Probe{Accessor: src, Chain: chain}
  24. }
  25. func reset(n *int64) {
  26. atomic.AddInt64(n, -atomic.AddInt64(n, 0))
  27. }
  28. // Reset zeroes the collected statistics of p.
  29. func (p *Probe) Reset() {
  30. if p.Chain != nil {
  31. p.Chain.Reset()
  32. }
  33. reset(&p.OpsRd)
  34. reset(&p.OpsWr)
  35. reset(&p.BytesRd)
  36. reset(&p.BytesWr)
  37. reset(&p.SectorsRd)
  38. reset(&p.SectorsWr)
  39. }
  40. func (p *Probe) ReadAt(b []byte, off int64) (n int, err error) {
  41. n, err = p.Accessor.ReadAt(b, off)
  42. atomic.AddInt64(&p.OpsRd, 1)
  43. atomic.AddInt64(&p.BytesRd, int64(n))
  44. if n <= 0 {
  45. return
  46. }
  47. sectorFirst := off >> 9
  48. sectorLast := (off + int64(n) - 1) >> 9
  49. atomic.AddInt64(&p.SectorsRd, sectorLast-sectorFirst+1)
  50. return
  51. }
  52. func (p *Probe) WriteAt(b []byte, off int64) (n int, err error) {
  53. n, err = p.Accessor.WriteAt(b, off)
  54. atomic.AddInt64(&p.OpsWr, 1)
  55. atomic.AddInt64(&p.BytesWr, int64(n))
  56. if n <= 0 {
  57. return
  58. }
  59. sectorFirst := off >> 9
  60. sectorLast := (off + int64(n) - 1) >> 9
  61. atomic.AddInt64(&p.SectorsWr, sectorLast-sectorFirst+1)
  62. return
  63. }