procfs_stat_cpu_parser.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2021 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef SERVICES_DEVICE_COMPUTE_PRESSURE_PROCFS_STAT_CPU_PARSER_H_
  5. #define SERVICES_DEVICE_COMPUTE_PRESSURE_PROCFS_STAT_CPU_PARSER_H_
  6. #include <stdint.h>
  7. #include <vector>
  8. #include "base/files/file_path.h"
  9. #include "base/sequence_checker.h"
  10. #include "base/strings/string_piece.h"
  11. #include "base/thread_annotations.h"
  12. #include "services/device/compute_pressure/core_times.h"
  13. namespace device {
  14. // Parses CPU time usage stats from procfs (/proc/stat).
  15. //
  16. // This class is not thread-safe. Each instance must be used on the same
  17. // sequence, which must allow blocking I/O. The constructor may be used on a
  18. // different sequence.
  19. class ProcfsStatCpuParser {
  20. public:
  21. // The "production" `procfs_path` value for the constructor.
  22. static constexpr base::FilePath::CharType kProcfsStatPath[] =
  23. FILE_PATH_LITERAL("/proc/stat");
  24. // `stat_path` is exposed for testing. Production instances should be
  25. // constructed using base::FilePath(kProcfsStatPath).
  26. explicit ProcfsStatCpuParser(base::FilePath stat_path);
  27. ~ProcfsStatCpuParser();
  28. ProcfsStatCpuParser(const ProcfsStatCpuParser&) = delete;
  29. ProcfsStatCpuParser& operator=(const ProcfsStatCpuParser&) = delete;
  30. const std::vector<CoreTimes>& core_times() const {
  31. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  32. return core_times_;
  33. }
  34. // Reads /proc/stat and updates the vector returned by core_times().
  35. //
  36. // Returns false if parsing fails. This only happens if /proc/stat is not
  37. // accessible. Invalid data is ignored.
  38. //
  39. // Cores without entries in /proc/stat will remain unchanged. Counters that
  40. // decrease below the last parsed value are ignored.
  41. bool Update();
  42. private:
  43. // Returns -1 if the line does not include any CPU.
  44. static int CoreIdFromLine(base::StringPiece stat_line);
  45. static void UpdateCore(base::StringPiece core_line, CoreTimes& core_times);
  46. SEQUENCE_CHECKER(sequence_checker_);
  47. const base::FilePath stat_path_;
  48. std::vector<CoreTimes> core_times_ GUARDED_BY_CONTEXT(sequence_checker_);
  49. };
  50. } // namespace device
  51. #endif // SERVICES_DEVICE_COMPUTE_PRESSURE_PROCFS_STAT_CPU_PARSER_H_