File: resourced_client.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (445 lines) | stat: -rw-r--r-- 15,748 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/dbus/resourced/resourced_client.h"

#include "base/check_op.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/observer_list.h"
#include "base/process/process_metrics.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "chromeos/ash/components/dbus/resource_manager/resource_manager.pb.h"
#include "chromeos/ash/components/dbus/resourced/fake_resourced_client.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_proxy.h"
#include "third_party/cros_system_api/dbus/resource_manager/dbus-constants.h"

namespace ash {
namespace {

// Resource manager D-Bus method calls are all simple operations and should
// not take more than 1 second.
constexpr int kResourcedDBusTimeoutMilliseconds = 1000;

ResourcedClient* g_instance = nullptr;

class ResourcedClientImpl : public ResourcedClient {
 public:
  ResourcedClientImpl();
  ~ResourcedClientImpl() override = default;
  ResourcedClientImpl(const ResourcedClientImpl&) = delete;
  ResourcedClientImpl& operator=(const ResourcedClientImpl&) = delete;

  void Init(dbus::Bus* bus) {
    proxy_ = bus->GetObjectProxy(
        resource_manager::kResourceManagerServiceName,
        dbus::ObjectPath(resource_manager::kResourceManagerServicePath));
    proxy_->ConnectToSignal(
        resource_manager::kResourceManagerInterface,
        resource_manager::kMemoryPressureChrome,
        base::BindRepeating(&ResourcedClientImpl::MemoryPressureReceived,
                            weak_factory_.GetWeakPtr()),
        base::BindOnce(&ResourcedClientImpl::MemoryPressureConnected,
                       weak_factory_.GetWeakPtr()));
    proxy_->ConnectToSignal(
        resource_manager::kResourceManagerInterface,
        resource_manager::kMemoryPressureArcContainer,
        base::BindRepeating(
            &ResourcedClientImpl::MemoryPressureArcContainerReceived,
            weak_factory_.GetWeakPtr()),
        base::BindOnce(&ResourcedClientImpl::MemoryPressureConnected,
                       weak_factory_.GetWeakPtr()));
  }

  // ResourcedClient interface.
  void SetGameModeWithTimeout(
      GameMode game_mode,
      uint32_t refresh_seconds,
      chromeos::DBusMethodCallback<GameMode> callback) override;

  void SetMemoryMargins(MemoryMargins margins) override;

  void ReportBrowserProcesses(const std::vector<Process>& processes) override;

  void SetProcessState(base::ProcessId process_id,
                       resource_manager::ProcessState state,
                       SetQoSStateCallback callback) override;

  void SetThreadState(base::ProcessId process_id,
                      base::PlatformThreadId thread_id,
                      resource_manager::ThreadState state,
                      SetQoSStateCallback callback) override;

  void AddObserver(Observer* observer) override;

  void RemoveObserver(Observer* observer) override;

  void AddArcContainerObserver(ArcContainerObserver* observer) override;

  void RemoveArcContainerObserver(ArcContainerObserver* observer) override;

  void WaitForServiceToBeAvailable(
      dbus::ObjectProxy::WaitForServiceToBeAvailableCallback callback) override;

 private:
  // D-Bus response handlers.
  void HandleSetGameModeWithTimeoutResponse(
      chromeos::DBusMethodCallback<GameMode> callback,
      dbus::Response* response);

  // D-Bus signal handlers.
  void MemoryPressureReceived(dbus::Signal* signal);
  void MemoryPressureConnected(const std::string& interface_name,
                               const std::string& signal_name,
                               bool success);

  void MemoryPressureArcContainerReceived(dbus::Signal* signal);

  void HandleSetProcessStateResponse(base::ProcessId process_id,
                                     SetQoSStateCallback callback,
                                     dbus::Response* response,
                                     dbus::ErrorResponse* error);

  void HandleSetThreadStateResponse(base::PlatformThreadId thread_id,
                                    SetQoSStateCallback callback,
                                    dbus::Response* response,
                                    dbus::ErrorResponse* error);

  // Member variables.

  raw_ptr<dbus::ObjectProxy> proxy_ = nullptr;

  // Caches the total memory for reclaim_target_kb sanity check. The default
  // value is 32 GiB in case reading total memory failed.
  uint64_t total_memory_kb_ = 32 * 1024 * 1024;

  // A list of observers that are listening on state changes, etc.
  base::ObserverList<Observer> observers_;

  // A list of observers listening for ARC container memory pressure signals.
  base::ObserverList<ArcContainerObserver> arc_container_observers_;

  base::WeakPtrFactory<ResourcedClientImpl> weak_factory_{this};
};

ResourcedClientImpl::ResourcedClientImpl() {
  base::SystemMemoryInfoKB info;
  if (base::GetSystemMemoryInfo(&info)) {
    total_memory_kb_ = static_cast<uint64_t>(info.total);
  } else {
    PLOG(ERROR) << "Error reading total memory.";
  }
}

void ResourcedClientImpl::MemoryPressureReceived(dbus::Signal* signal) {
  dbus::MessageReader signal_reader(signal);

  memory_pressure::ReclaimTarget reclaim_target;
  uint8_t pressure_level_byte;
  PressureLevel pressure_level;

  if (!signal_reader.PopByte(&pressure_level_byte) ||
      !signal_reader.PopUint64(&reclaim_target.target_kb)) {
    LOG(ERROR) << "Error reading signal from resourced: " << signal->ToString();
    return;
  }

  int64_t signal_origin_timestamp_ms = -1;
  // The signal origin timestamp may not be included by resourced, and if it is,
  // it might be an invalid value.
  if (signal_reader.PopInt64(&signal_origin_timestamp_ms) &&
      signal_origin_timestamp_ms > 0) {
    // Signal origin timestamp is received as a ms value from CLOCK_MONOTONIC.
    reclaim_target.origin_time =
        base::TimeTicks::FromUptimeMillis(signal_origin_timestamp_ms);
  }

  uint8_t discard_type;
  if (signal_reader.PopByte(&discard_type)) {
    if (discard_type == resource_manager::DiscardType::UNPROTECTED) {
      reclaim_target.discard_protected = false;
    } else if (discard_type == resource_manager::DiscardType::PROTECTED) {
      reclaim_target.discard_protected = true;
    } else {
      LOG(ERROR) << "Unknown discard type: " << discard_type;
    }
  }

  if (pressure_level_byte == resource_manager::PressureLevelChrome::NONE) {
    pressure_level = PressureLevel::NONE;
  } else if (pressure_level_byte ==
             resource_manager::PressureLevelChrome::MODERATE) {
    pressure_level = PressureLevel::MODERATE;
  } else if (pressure_level_byte ==
             resource_manager::PressureLevelChrome::CRITICAL) {
    pressure_level = PressureLevel::CRITICAL;
  } else {
    LOG(ERROR) << "Unknown memory pressure level: " << pressure_level_byte;
    return;
  }

  if (reclaim_target.target_kb > total_memory_kb_) {
    LOG(ERROR) << "reclaim_target_kb is too large: "
               << reclaim_target.target_kb;
    return;
  }

  for (auto& observer : observers_) {
    observer.OnMemoryPressure(pressure_level, reclaim_target);
  }
}

void ResourcedClientImpl::MemoryPressureArcContainerReceived(
    dbus::Signal* signal) {
  dbus::MessageReader signal_reader(signal);

  uint8_t pressure_level_byte;
  PressureLevelArcContainer pressure_level;
  uint64_t reclaim_target_kb;

  if (!signal_reader.PopByte(&pressure_level_byte) ||
      !signal_reader.PopUint64(&reclaim_target_kb)) {
    LOG(ERROR) << "Error reading signal from resourced: " << signal->ToString();
    return;
  }
  switch (static_cast<resource_manager::PressureLevelArcContainer>(
      pressure_level_byte)) {
    case resource_manager::PressureLevelArcContainer::NONE:
      pressure_level = PressureLevelArcContainer::kNone;
      break;

    case resource_manager::PressureLevelArcContainer::CACHED:
      pressure_level = PressureLevelArcContainer::kCached;
      break;

    case resource_manager::PressureLevelArcContainer::PERCEPTIBLE:
      pressure_level = PressureLevelArcContainer::kPerceptible;
      break;

    case resource_manager::PressureLevelArcContainer::FOREGROUND:
      pressure_level = PressureLevelArcContainer::kForeground;
      break;

    default:
      LOG(ERROR) << "Unknown memory pressure level: " << pressure_level_byte;
      return;
  }

  if (reclaim_target_kb > total_memory_kb_) {
    LOG(ERROR) << "reclaim_target_kb is too large: " << reclaim_target_kb;
    return;
  }

  for (auto& observer : arc_container_observers_) {
    observer.OnMemoryPressure(pressure_level, reclaim_target_kb);
  }
}

void ResourcedClientImpl::HandleSetProcessStateResponse(
    base::ProcessId process_id,
    SetQoSStateCallback callback,
    dbus::Response* response,
    dbus::ErrorResponse* error) {
  dbus::DBusResult result = dbus::DBusResult::kSuccess;
  if (response == nullptr) {
    result = dbus::GetResult(error);
  }
  std::move(callback).Run(result);
}

void ResourcedClientImpl::HandleSetThreadStateResponse(
    base::PlatformThreadId thread_id,
    SetQoSStateCallback callback,
    dbus::Response* response,
    dbus::ErrorResponse* error) {
  dbus::DBusResult result = dbus::DBusResult::kSuccess;
  if (response == nullptr) {
    result = dbus::GetResult(error);
  }
  std::move(callback).Run(result);
}

void ResourcedClientImpl::MemoryPressureConnected(
    const std::string& interface_name,
    const std::string& signal_name,
    bool success) {
  PLOG_IF(ERROR, !success) << "Failed to connect to signal: " << signal_name;
}

// Response will be true if game mode was on previously, false otherwise.
void ResourcedClientImpl::HandleSetGameModeWithTimeoutResponse(
    chromeos::DBusMethodCallback<GameMode> callback,
    dbus::Response* response) {
  dbus::MessageReader reader(response);
  uint8_t previous;
  if (!reader.PopByte(&previous)) {
    std::move(callback).Run(std::nullopt);
    return;
  }
  std::move(callback).Run(static_cast<GameMode>(previous));
}

void ResourcedClientImpl::SetGameModeWithTimeout(
    GameMode game_mode,
    uint32_t refresh_seconds,
    chromeos::DBusMethodCallback<GameMode> callback) {
  dbus::MethodCall method_call(resource_manager::kResourceManagerInterface,
                               resource_manager::kSetGameModeWithTimeoutMethod);
  dbus::MessageWriter writer(&method_call);
  writer.AppendByte(static_cast<uint8_t>(game_mode));
  writer.AppendUint32(refresh_seconds);

  proxy_->CallMethod(
      &method_call, kResourcedDBusTimeoutMilliseconds,
      base::BindOnce(&ResourcedClientImpl::HandleSetGameModeWithTimeoutResponse,
                     weak_factory_.GetWeakPtr(), std::move(callback)));
}

void ResourcedClientImpl::SetMemoryMargins(MemoryMargins margins) {
  resource_manager::MemoryMargins request;
  request.set_moderate_bps(margins.moderate_bps);
  request.set_critical_bps(margins.critical_bps);
  request.set_critical_protected_bps(margins.critical_protected_bps);

  dbus::MethodCall method_call(resource_manager::kResourceManagerInterface,
                               resource_manager::kSetMemoryMarginsMethod);
  if (!dbus::MessageWriter(&method_call).AppendProtoAsArrayOfBytes(request)) {
    LOG(ERROR) << "Error serializing "
               << resource_manager::kSetMemoryMarginsMethod << " request";
    return;
  }

  proxy_->CallMethod(&method_call, kResourcedDBusTimeoutMilliseconds,
                     base::DoNothing());
}

void ResourcedClientImpl::ReportBrowserProcesses(
    const std::vector<Process>& processes) {
  resource_manager::ReportBrowserProcesses request;

  request.set_browser_type(resource_manager::BrowserType::ASH);

  for (auto it = processes.begin(); it != processes.end(); ++it) {
    auto* process = request.add_processes();
    process->set_pid(it->pid);
    process->set_protected_(it->is_protected);
    process->set_visible(it->is_visible);
    process->set_focused(it->is_focused);
    process->set_last_visible_ms(
        it->last_visible.since_origin().InMilliseconds());
  }

  dbus::MethodCall method_call(resource_manager::kResourceManagerInterface,
                               resource_manager::kReportBrowserProcessesMethod);
  if (!dbus::MessageWriter(&method_call).AppendProtoAsArrayOfBytes(request)) {
    LOG(ERROR) << "Error serializing "
               << resource_manager::kReportBrowserProcessesMethod << " request";
    return;
  }

  proxy_->CallMethod(&method_call, kResourcedDBusTimeoutMilliseconds,
                     base::DoNothing());
}

void ResourcedClientImpl::SetProcessState(base::ProcessId process_id,
                                          resource_manager::ProcessState state,
                                          SetQoSStateCallback callback) {
  dbus::MethodCall method_call(resource_manager::kResourceManagerInterface,
                               resource_manager::kSetProcessStateMethod);
  dbus::MessageWriter writer(&method_call);

  writer.AppendUint32(process_id);
  writer.AppendByte(static_cast<uint8_t>(state));

  proxy_->CallMethodWithErrorResponse(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(&ResourcedClientImpl::HandleSetProcessStateResponse,
                     weak_factory_.GetWeakPtr(), process_id,
                     std::move(callback)));
}

void ResourcedClientImpl::SetThreadState(base::ProcessId process_id,
                                         base::PlatformThreadId thread_id,
                                         resource_manager::ThreadState state,
                                         SetQoSStateCallback callback) {
  dbus::MethodCall method_call(resource_manager::kResourceManagerInterface,
                               resource_manager::kSetThreadStateMethod);
  dbus::MessageWriter writer(&method_call);

  writer.AppendUint32(process_id);
  writer.AppendUint32(thread_id.raw());
  writer.AppendByte(static_cast<uint8_t>(state));

  proxy_->CallMethodWithErrorResponse(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(&ResourcedClientImpl::HandleSetThreadStateResponse,
                     weak_factory_.GetWeakPtr(), thread_id,
                     std::move(callback)));
}

void ResourcedClientImpl::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void ResourcedClientImpl::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

void ResourcedClientImpl::AddArcContainerObserver(
    ArcContainerObserver* observer) {
  arc_container_observers_.AddObserver(observer);
}

void ResourcedClientImpl::RemoveArcContainerObserver(
    ArcContainerObserver* observer) {
  arc_container_observers_.RemoveObserver(observer);
}

void ResourcedClientImpl::WaitForServiceToBeAvailable(
    dbus::ObjectProxy::WaitForServiceToBeAvailableCallback callback) {
  proxy_->WaitForServiceToBeAvailable(std::move(callback));
}

}  // namespace

ResourcedClient::ResourcedClient() {
  CHECK(!g_instance);
  g_instance = this;
}

ResourcedClient::~ResourcedClient() {
  CHECK_EQ(this, g_instance);
  g_instance = nullptr;
}

// static
void ResourcedClient::Initialize(dbus::Bus* bus) {
  CHECK(bus);
  (new ResourcedClientImpl())->Init(bus);
}

// static
FakeResourcedClient* ResourcedClient::InitializeFake() {
  return new FakeResourcedClient();
}

// static
void ResourcedClient::Shutdown() {
  CHECK(g_instance);
  delete g_instance;
  // The destructor resets |g_instance|.
  DCHECK(!g_instance);
}

// static
ResourcedClient* ResourcedClient::Get() {
  return g_instance;
}

}  // namespace ash