Przeglądaj źródła

daemon/stats_collector: refactor getSystemCpuUsage

Signed-off-by: Cristian Staretu <cristian.staretu@gmail.com>
unclejack 10 lat temu
rodzic
commit
25f776451e
1 zmienionych plików z 15 dodań i 4 usunięć
  1. 15 4
      daemon/stats_collector.go

+ 15 - 4
daemon/stats_collector.go

@@ -24,6 +24,7 @@ func newStatsCollector(interval time.Duration) *statsCollector {
 		interval:   interval,
 		interval:   interval,
 		publishers: make(map[*Container]*pubsub.Publisher),
 		publishers: make(map[*Container]*pubsub.Publisher),
 		clockTicks: uint64(system.GetClockTicks()),
 		clockTicks: uint64(system.GetClockTicks()),
+		bufReader:  bufio.NewReaderSize(nil, 128),
 	}
 	}
 	go s.run()
 	go s.run()
 	return s
 	return s
@@ -35,6 +36,7 @@ type statsCollector struct {
 	interval   time.Duration
 	interval   time.Duration
 	clockTicks uint64
 	clockTicks uint64
 	publishers map[*Container]*pubsub.Publisher
 	publishers map[*Container]*pubsub.Publisher
+	bufReader  *bufio.Reader
 }
 }
 
 
 // collect registers the container with the collector and adds it to
 // collect registers the container with the collector and adds it to
@@ -121,14 +123,23 @@ const nanoSeconds = 1e9
 // getSystemCpuUSage returns the host system's cpu usage in nanoseconds
 // getSystemCpuUSage returns the host system's cpu usage in nanoseconds
 // for the system to match the cgroup readings are returned in the same format.
 // for the system to match the cgroup readings are returned in the same format.
 func (s *statsCollector) getSystemCpuUsage() (uint64, error) {
 func (s *statsCollector) getSystemCpuUsage() (uint64, error) {
+	var line string
 	f, err := os.Open("/proc/stat")
 	f, err := os.Open("/proc/stat")
 	if err != nil {
 	if err != nil {
 		return 0, err
 		return 0, err
 	}
 	}
-	defer f.Close()
-	sc := bufio.NewScanner(f)
-	for sc.Scan() {
-		parts := strings.Fields(sc.Text())
+	defer func() {
+		s.bufReader.Reset(nil)
+		f.Close()
+	}()
+	s.bufReader.Reset(f)
+	err = nil
+	for err == nil {
+		line, err = s.bufReader.ReadString('\n')
+		if err != nil {
+			break
+		}
+		parts := strings.Fields(line)
 		switch parts[0] {
 		switch parts[0] {
 		case "cpu":
 		case "cpu":
 			if len(parts) < 8 {
 			if len(parts) < 8 {