main.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "github.com/oz123/gupta"
  8. "log"
  9. "os"
  10. "time"
  11. )
  12. func readProcStatLine(r *os.File) string {
  13. buf := make([]byte, 80)
  14. r.ReadAt(buf, 0)
  15. idx := bytes.Index(buf, []byte("cpu0"))
  16. line := string(buf[:idx])
  17. r.Seek(0, 0)
  18. return line
  19. }
  20. var Usage = func() {
  21. fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
  22. flag.PrintDefaults()
  23. }
  24. func main() {
  25. var interval int
  26. var partition, netInterface string
  27. var load, memory, cpu bool
  28. writer := os.Stdout
  29. enc := json.NewEncoder(writer)
  30. flag.IntVar(&interval, "i", 5, "polling inteval")
  31. flag.BoolVar(&memory, "m", false, "Poll memory")
  32. flag.BoolVar(&load, "l", false, "Poll load")
  33. flag.BoolVar(&cpu, "c", false, "poll CPU usage")
  34. flag.StringVar(&partition, "p", "", "Poll disk usage (partition)")
  35. flag.StringVar(&netInterface, "n", "", "Network usage (interface)")
  36. flag.Parse()
  37. if load == false && memory == false && cpu == false {
  38. Usage()
  39. os.Exit(1)
  40. }
  41. fmt.Println(gupta.Hello())
  42. r, _ := os.Open("/proc/stat")
  43. m, _ := os.Open("/proc/meminfo")
  44. defer r.Close()
  45. defer m.Close()
  46. for true {
  47. report := gupta.GuptaReport{Time: time.Now()}
  48. line := readProcStatLine(r)
  49. time.Sleep(time.Duration(interval) * time.Second)
  50. if cpu {
  51. lineNew := readProcStatLine(r)
  52. cpustat := gupta.NewCPUStat(line, lineNew)
  53. report.CPUUsage = &cpustat
  54. }
  55. if memory {
  56. mem := gupta.NewMemory(m)
  57. report.MemoryUsage = &mem
  58. }
  59. if err := enc.Encode(&report); err != nil {
  60. log.Println(err)
  61. }
  62. r.Seek(0, 0)
  63. m.Seek(0, 0)
  64. }
  65. }