1 // Copyright 2018 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 CHROME_BROWSER_TASK_MANAGER_SAMPLING_ARC_SHARED_SAMPLER_H_
6 #define CHROME_BROWSER_TASK_MANAGER_SAMPLING_ARC_SHARED_SAMPLER_H_
7 
8 #include <stdint.h>
9 
10 #include <map>
11 
12 #include "base/callback.h"
13 #include "base/containers/flat_map.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/optional.h"
16 #include "base/process/process_handle.h"
17 #include "components/arc/mojom/process.mojom.h"
18 
19 namespace task_manager {
20 
21 // Defines sampler that will retrieve memory footprint metrics for all arc
22 // processes at once. Created by TaskManagerImpl on the UI thread.
23 class ArcSharedSampler {
24  public:
25   ArcSharedSampler();
26   ~ArcSharedSampler();
27 
28   using MemoryFootprintBytes = uint64_t;
29 
30   using OnSamplingCompleteCallback =
31       base::RepeatingCallback<void(base::Optional<MemoryFootprintBytes>)>;
32 
33   // Registers task group specific callback.
34   void RegisterCallback(base::ProcessId process_id,
35                         OnSamplingCompleteCallback on_sampling_complete);
36   // Unregisters task group specific callbacks.
37   void UnregisterCallback(base::ProcessId process_id);
38 
39   // Triggers a refresh of process stats.
40   void Refresh();
41 
42  private:
43   using CallbacksMap =
44       base::flat_map<base::ProcessId, OnSamplingCompleteCallback>;
45 
46   // Called when ArcProcessService returns memory dump.
47   void OnReceiveMemoryDump(
48       int dump_type,
49       std::vector<arc::mojom::ArcMemoryDumpPtr> process_dumps);
50 
51   // Holds callbacks registered by TaskGroup objects.
52   CallbacksMap callbacks_;
53 
54   // Keeps track of whether there is a pending request for memory footprint of
55   // app or system processes.
56   int pending_memory_dump_types_ = 0;
57 
58   // The timestamp of when the last refresh call finished, for system and
59   // app processes.
60   base::Time last_system_refresh_;
61   base::Time last_app_refresh_;
62 
63   base::WeakPtrFactory<ArcSharedSampler> weak_ptr_factory_{this};
64 
65   DISALLOW_COPY_AND_ASSIGN(ArcSharedSampler);
66 };
67 
68 }  // namespace task_manager
69 #endif  // CHROME_BROWSER_TASK_MANAGER_SAMPLING_ARC_SHARED_SAMPLER_H_
70