util.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package lib
  2. import (
  3. "fmt"
  4. "log"
  5. "time"
  6. "github.com/keroserene/go-webrtc"
  7. )
  8. const (
  9. LogTimeInterval = 5
  10. )
  11. type IceServerList []webrtc.ConfigurationOption
  12. func (i *IceServerList) String() string {
  13. return fmt.Sprint(*i)
  14. }
  15. type BytesLogger interface {
  16. Log()
  17. AddOutbound(int)
  18. AddInbound(int)
  19. }
  20. // Default BytesLogger does nothing.
  21. type BytesNullLogger struct{}
  22. func (b BytesNullLogger) Log() {}
  23. func (b BytesNullLogger) AddOutbound(amount int) {}
  24. func (b BytesNullLogger) AddInbound(amount int) {}
  25. // BytesSyncLogger uses channels to safely log from multiple sources with output
  26. // occuring at reasonable intervals.
  27. type BytesSyncLogger struct {
  28. OutboundChan chan int
  29. InboundChan chan int
  30. Outbound int
  31. Inbound int
  32. OutEvents int
  33. InEvents int
  34. IsLogging bool
  35. }
  36. func (b *BytesSyncLogger) Log() {
  37. b.IsLogging = true
  38. var amount int
  39. output := func() {
  40. log.Printf("Traffic Bytes (in|out): %d | %d -- (%d OnMessages, %d Sends)",
  41. b.Inbound, b.Outbound, b.InEvents, b.OutEvents)
  42. b.Outbound = 0
  43. b.OutEvents = 0
  44. b.Inbound = 0
  45. b.InEvents = 0
  46. }
  47. last := time.Now()
  48. for {
  49. select {
  50. case amount = <-b.OutboundChan:
  51. b.Outbound += amount
  52. b.OutEvents++
  53. last := time.Now()
  54. if time.Since(last) > time.Second*LogTimeInterval {
  55. last = time.Now()
  56. output()
  57. }
  58. case amount = <-b.InboundChan:
  59. b.Inbound += amount
  60. b.InEvents++
  61. if time.Since(last) > time.Second*LogTimeInterval {
  62. last = time.Now()
  63. output()
  64. }
  65. case <-time.After(time.Second * LogTimeInterval):
  66. if b.InEvents > 0 || b.OutEvents > 0 {
  67. output()
  68. }
  69. }
  70. }
  71. }
  72. func (b *BytesSyncLogger) AddOutbound(amount int) {
  73. if !b.IsLogging {
  74. return
  75. }
  76. b.OutboundChan <- amount
  77. }
  78. func (b *BytesSyncLogger) AddInbound(amount int) {
  79. if !b.IsLogging {
  80. return
  81. }
  82. b.InboundChan <- amount
  83. }