1 // Copyright 2017 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 
5 #ifndef BASE_TRACE_EVENT_MEMORY_DUMP_SCHEDULER_H
6 #define BASE_TRACE_EVENT_MEMORY_DUMP_SCHEDULER_H
7 
8 #include <stdint.h>
9 
10 #include <vector>
11 
12 #include "base/base_export.h"
13 #include "base/callback.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/trace_event/memory_dump_request_args.h"
16 
17 namespace base {
18 class SequencedTaskRunner;
19 
20 namespace trace_event {
21 
22 // Schedules global dump requests based on the triggers added. The methods of
23 // this class are NOT thread safe and the client has to take care of invoking
24 // all the methods of the class safely.
25 class BASE_EXPORT MemoryDumpScheduler {
26  public:
27   using PeriodicCallback = RepeatingCallback<void(MemoryDumpLevelOfDetail)>;
28 
29   // Passed to Start().
30   struct BASE_EXPORT Config {
31     struct Trigger {
32       MemoryDumpLevelOfDetail level_of_detail;
33       uint32_t period_ms;
34     };
35 
36     Config();
37     Config(const Config&);
38     ~Config();
39 
40     std::vector<Trigger> triggers;
41     PeriodicCallback callback;
42   };
43 
44   static MemoryDumpScheduler* GetInstance();
45 
46   void Start(Config, scoped_refptr<SequencedTaskRunner> task_runner);
47   void Stop();
is_enabled_for_testing()48   bool is_enabled_for_testing() const { return bool(task_runner_); }
49 
50  private:
51   friend class MemoryDumpSchedulerTest;
52   MemoryDumpScheduler();
53   ~MemoryDumpScheduler();
54 
55   void StartInternal(Config);
56   void StopInternal();
57   void Tick(uint32_t expected_generation);
58 
59   // Accessed only by the public methods (never from the task runner itself).
60   scoped_refptr<SequencedTaskRunner> task_runner_;
61 
62   // These fields instead are only accessed from within the task runner.
63   uint32_t period_ms_;   // 0 == disabled.
64   uint32_t generation_;  // Used to invalidate outstanding tasks after Stop().
65   uint32_t tick_count_;
66   uint32_t light_dump_rate_;
67   uint32_t heavy_dump_rate_;
68   PeriodicCallback callback_;
69 
70   DISALLOW_COPY_AND_ASSIGN(MemoryDumpScheduler);
71 };
72 
73 }  // namespace trace_event
74 }  // namespace base
75 
76 #endif  // BASE_TRACE_EVENT_MEMORY_DUMP_SCHEDULER_H
77