host_backend_delegate_impl.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. #include "ash/services/multidevice_setup/host_backend_delegate_impl.h"
  5. #include <algorithm>
  6. #include <sstream>
  7. #include "ash/components/multidevice/logging/logging.h"
  8. #include "ash/components/multidevice/software_feature.h"
  9. #include "ash/components/multidevice/software_feature_state.h"
  10. #include "ash/constants/ash_features.h"
  11. #include "ash/services/device_sync/feature_status_change.h"
  12. #include "ash/services/multidevice_setup/eligible_host_devices_provider.h"
  13. #include "base/bind.h"
  14. #include "base/containers/contains.h"
  15. #include "base/memory/ptr_util.h"
  16. #include "components/prefs/pref_registry_simple.h"
  17. #include "components/prefs/pref_service.h"
  18. namespace ash {
  19. namespace multidevice_setup {
  20. namespace {
  21. // Name of the pref which stores the ID of the host which is pending being set
  22. // on the back-end.
  23. const char kPendingRequestHostIdPrefName[] =
  24. "multidevice_setup.pending_request_host_id";
  25. // String to use for the pending host ID preference entry when the pending
  26. // request is to remove the current host.
  27. const char kPendingRemovalOfCurrentHost[] = "pendingRemovalOfCurrentHost";
  28. // String to use for the pending host ID when there is no pending request.
  29. const char kNoPendingRequest[] = "";
  30. // The number of minutes to wait before retrying a failed attempt.
  31. const int kNumMinutesBetweenRetries = 5;
  32. const char kNoHostForLogging[] = "[no host]";
  33. } // namespace
  34. // static
  35. HostBackendDelegateImpl::Factory*
  36. HostBackendDelegateImpl::Factory::test_factory_ = nullptr;
  37. // static
  38. std::unique_ptr<HostBackendDelegate> HostBackendDelegateImpl::Factory::Create(
  39. EligibleHostDevicesProvider* eligible_host_devices_provider,
  40. PrefService* pref_service,
  41. device_sync::DeviceSyncClient* device_sync_client,
  42. std::unique_ptr<base::OneShotTimer> timer) {
  43. if (test_factory_) {
  44. return test_factory_->CreateInstance(eligible_host_devices_provider,
  45. pref_service, device_sync_client,
  46. std::move(timer));
  47. }
  48. return base::WrapUnique(
  49. new HostBackendDelegateImpl(eligible_host_devices_provider, pref_service,
  50. device_sync_client, std::move(timer)));
  51. }
  52. // static
  53. void HostBackendDelegateImpl::Factory::SetFactoryForTesting(
  54. Factory* test_factory) {
  55. test_factory_ = test_factory;
  56. }
  57. HostBackendDelegateImpl::Factory::~Factory() = default;
  58. // static
  59. void HostBackendDelegateImpl::RegisterPrefs(PrefRegistrySimple* registry) {
  60. registry->RegisterStringPref(kPendingRequestHostIdPrefName,
  61. kNoPendingRequest);
  62. }
  63. HostBackendDelegateImpl::HostBackendDelegateImpl(
  64. EligibleHostDevicesProvider* eligible_host_devices_provider,
  65. PrefService* pref_service,
  66. device_sync::DeviceSyncClient* device_sync_client,
  67. std::unique_ptr<base::OneShotTimer> timer)
  68. : HostBackendDelegate(),
  69. eligible_host_devices_provider_(eligible_host_devices_provider),
  70. pref_service_(pref_service),
  71. device_sync_client_(device_sync_client),
  72. timer_(std::move(timer)) {
  73. device_sync_client_->AddObserver(this);
  74. host_from_last_sync_ = GetHostFromDeviceSync();
  75. if (HasPendingHostRequest())
  76. AttemptNetworkRequest(false /* is_retry */);
  77. }
  78. HostBackendDelegateImpl::~HostBackendDelegateImpl() {
  79. device_sync_client_->RemoveObserver(this);
  80. }
  81. void HostBackendDelegateImpl::AttemptToSetMultiDeviceHostOnBackend(
  82. const absl::optional<multidevice::RemoteDeviceRef>& host_device) {
  83. if (host_device && !IsHostEligible(*host_device)) {
  84. PA_LOG(WARNING) << "HostBackendDelegateImpl::"
  85. << "AttemptToSetMultiDeviceHostOnBackend(): Tried to set a "
  86. << "device as host, but that device is not an eligible "
  87. << "host: " << host_device->GetInstanceIdDeviceIdForLogs();
  88. return;
  89. }
  90. // If the device on the back-end is already |host_device|, there no longer
  91. // needs to be a pending request.
  92. if (host_from_last_sync_ == host_device) {
  93. SetPendingHostRequest(kNoPendingRequest);
  94. return;
  95. }
  96. // Stop the timer, since a new attempt is being started.
  97. timer_->Stop();
  98. if (host_device) {
  99. if (features::ShouldUseV1DeviceSync()) {
  100. SetPendingHostRequest(host_device->GetDeviceId());
  101. } else {
  102. DCHECK(!host_device->instance_id().empty());
  103. SetPendingHostRequest(host_device->instance_id());
  104. }
  105. } else {
  106. SetPendingHostRequest(kPendingRemovalOfCurrentHost);
  107. }
  108. AttemptNetworkRequest(false /* is_retry */);
  109. }
  110. bool HostBackendDelegateImpl::HasPendingHostRequest() {
  111. const std::string pending_host_id_from_prefs =
  112. pref_service_->GetString(kPendingRequestHostIdPrefName);
  113. if (pending_host_id_from_prefs == kNoPendingRequest)
  114. return false;
  115. if (pending_host_id_from_prefs == kPendingRemovalOfCurrentHost) {
  116. // If the pending request is to remove the current host but there is no
  117. // current host, the host was removed by another device while this device
  118. // was offline.
  119. if (!host_from_last_sync_) {
  120. SetPendingHostRequest(kNoPendingRequest);
  121. return false;
  122. }
  123. // Otherwise, there still is a pending request to remove the current host.
  124. return true;
  125. }
  126. // By this point, |pending_host_id_from_prefs| refers to a real device ID and
  127. // not one of the two sentinel values.
  128. if (FindDeviceById(pending_host_id_from_prefs))
  129. return true;
  130. // If a request was pending for a specific host device, but that device is no
  131. // longer present on the user's account, there is no longer a pending request.
  132. // TODO(https://crbug.com/936273): Track frequency of unrecognized host IDs.
  133. // If the following scenarios occur before the pending host request completes,
  134. // the persisted host ID will not be recognized, and the user will need to go
  135. // through setup again:
  136. // * The device was actually removed from the user's account.
  137. // * A public key is persisted, v1 DeviceSync is disabled, and the v2 device
  138. // data hasn't been decrypted.
  139. // * Instance ID is persisted, v1 DeviceSync in re-enabled and the Instance
  140. // ID cannot be found in the device list.
  141. // We expect all of these scenarios to be very rare.
  142. SetPendingHostRequest(kNoPendingRequest);
  143. return false;
  144. }
  145. absl::optional<multidevice::RemoteDeviceRef>
  146. HostBackendDelegateImpl::GetPendingHostRequest() const {
  147. const std::string pending_host_id_from_prefs =
  148. pref_service_->GetString(kPendingRequestHostIdPrefName);
  149. DCHECK_NE(pending_host_id_from_prefs, kNoPendingRequest)
  150. << "HostBackendDelegateImpl::GetPendingHostRequest(): Tried "
  151. << "to get pending host request, but there was no pending "
  152. << "host request.";
  153. if (pending_host_id_from_prefs == kPendingRemovalOfCurrentHost)
  154. return absl::nullopt;
  155. absl::optional<multidevice::RemoteDeviceRef> pending_host =
  156. FindDeviceById(pending_host_id_from_prefs);
  157. DCHECK(pending_host)
  158. << "HostBackendDelegateImpl::GetPendingHostRequest(): Tried to get "
  159. << "pending host request, but the pending host ID was not present.";
  160. return pending_host;
  161. }
  162. absl::optional<multidevice::RemoteDeviceRef>
  163. HostBackendDelegateImpl::GetMultiDeviceHostFromBackend() const {
  164. return host_from_last_sync_;
  165. }
  166. bool HostBackendDelegateImpl::IsHostEligible(
  167. const multidevice::RemoteDeviceRef& provided_host) {
  168. return base::Contains(
  169. eligible_host_devices_provider_->GetEligibleHostDevices(), provided_host);
  170. }
  171. void HostBackendDelegateImpl::SetPendingHostRequest(
  172. const std::string& pending_host_id) {
  173. const std::string host_id_from_prefs_before_call =
  174. pref_service_->GetString(kPendingRequestHostIdPrefName);
  175. if (pending_host_id == host_id_from_prefs_before_call)
  176. return;
  177. pref_service_->SetString(kPendingRequestHostIdPrefName, pending_host_id);
  178. timer_->Stop();
  179. NotifyPendingHostRequestChange();
  180. }
  181. absl::optional<multidevice::RemoteDeviceRef>
  182. HostBackendDelegateImpl::FindDeviceById(const std::string& id) const {
  183. DCHECK(!id.empty());
  184. for (const auto& remote_device : device_sync_client_->GetSyncedDevices()) {
  185. if (features::ShouldUseV1DeviceSync()) {
  186. if (id == remote_device.GetDeviceId())
  187. return remote_device;
  188. } else {
  189. if (id == remote_device.instance_id())
  190. return remote_device;
  191. }
  192. }
  193. return absl::nullopt;
  194. }
  195. void HostBackendDelegateImpl::AttemptNetworkRequest(bool is_retry) {
  196. DCHECK(HasPendingHostRequest())
  197. << "HostBackendDelegateImpl::AttemptNetworkRequest(): Tried to attempt a "
  198. << "network request, but there was no pending host request.";
  199. absl::optional<multidevice::RemoteDeviceRef> pending_host_request =
  200. GetPendingHostRequest();
  201. // If |pending_host_request| is non-null, the request should be to set that
  202. // device. If it is null, the pending request is to remove the current host.
  203. multidevice::RemoteDeviceRef device_to_set =
  204. pending_host_request ? *pending_host_request : *host_from_last_sync_;
  205. // Likewise, if |pending_host_request| is non-null, that device should be
  206. // enabled, and if it is null, the old device should be disabled.
  207. bool should_enable = pending_host_request != absl::nullopt;
  208. PA_LOG(INFO) << "HostBackendDelegateImpl::AttemptNetworkRequest(): "
  209. << (is_retry ? "Retrying attempt" : "Attempting") << " to "
  210. << (should_enable ? "enable" : "disable")
  211. << " the host: " << device_to_set.GetInstanceIdDeviceIdForLogs();
  212. if (features::ShouldUseV1DeviceSync()) {
  213. // Even if the |device_to_set| has a non-trivial Instance ID, we still
  214. // invoke the v1 DeviceSync RPC to set the feature state. This ensures that
  215. // GmsCore will be notified of the change regardless of what version of
  216. // DeviceSync it is running. The v1 and v2 RPCs to change feature states
  217. // ultimately update the same backend database entry. Note: The
  218. // RemoteDeviceProvider guarantees that every device will have a public key
  219. // while v1 DeviceSync is enabled.
  220. DCHECK(!device_to_set.public_key().empty());
  221. device_sync_client_->SetSoftwareFeatureState(
  222. device_to_set.public_key(),
  223. multidevice::SoftwareFeature::kBetterTogetherHost,
  224. should_enable /* enabled */, should_enable /* is_exclusive */,
  225. base::BindOnce(
  226. &HostBackendDelegateImpl::OnSetHostNetworkRequestFinished,
  227. weak_ptr_factory_.GetWeakPtr(), device_to_set, should_enable));
  228. } else {
  229. DCHECK(!device_to_set.instance_id().empty());
  230. device_sync_client_->SetFeatureStatus(
  231. device_to_set.instance_id(),
  232. multidevice::SoftwareFeature::kBetterTogetherHost,
  233. should_enable ? device_sync::FeatureStatusChange::kEnableExclusively
  234. : device_sync::FeatureStatusChange::kDisable,
  235. base::BindOnce(
  236. &HostBackendDelegateImpl::OnSetHostNetworkRequestFinished,
  237. weak_ptr_factory_.GetWeakPtr(), device_to_set, should_enable));
  238. }
  239. }
  240. void HostBackendDelegateImpl::OnNewDevicesSynced() {
  241. absl::optional<multidevice::RemoteDeviceRef> host_from_sync =
  242. GetHostFromDeviceSync();
  243. if (host_from_last_sync_ == host_from_sync)
  244. return;
  245. PA_LOG(INFO) << "HostBackendDelegateImpl::OnNewDevicesSynced(): New host "
  246. << "device has been set. Old host: "
  247. << (host_from_last_sync_
  248. ? host_from_last_sync_->GetInstanceIdDeviceIdForLogs()
  249. : kNoHostForLogging)
  250. << ", New host: "
  251. << (host_from_sync
  252. ? host_from_sync->GetInstanceIdDeviceIdForLogs()
  253. : kNoHostForLogging);
  254. host_from_last_sync_ = host_from_sync;
  255. // If there is a pending request and the new host fulfills that pending
  256. // request, there is no longer a pending request.
  257. if (HasPendingHostRequest() &&
  258. host_from_last_sync_ == GetPendingHostRequest()) {
  259. SetPendingHostRequest(kNoPendingRequest);
  260. }
  261. NotifyHostChangedOnBackend();
  262. }
  263. absl::optional<multidevice::RemoteDeviceRef>
  264. HostBackendDelegateImpl::GetHostFromDeviceSync() {
  265. multidevice::RemoteDeviceRefList synced_devices =
  266. device_sync_client_->GetSyncedDevices();
  267. auto it = std::find_if(
  268. synced_devices.begin(), synced_devices.end(),
  269. [](const auto& remote_device) {
  270. multidevice::SoftwareFeatureState host_state =
  271. remote_device.GetSoftwareFeatureState(
  272. multidevice::SoftwareFeature::kBetterTogetherHost);
  273. return host_state == multidevice::SoftwareFeatureState::kEnabled;
  274. });
  275. if (it == synced_devices.end())
  276. return absl::nullopt;
  277. return *it;
  278. }
  279. void HostBackendDelegateImpl::OnSetHostNetworkRequestFinished(
  280. multidevice::RemoteDeviceRef device_for_request,
  281. bool attempted_to_enable,
  282. device_sync::mojom::NetworkRequestResult result_code) {
  283. bool success =
  284. result_code == device_sync::mojom::NetworkRequestResult::kSuccess;
  285. std::stringstream ss;
  286. ss << "HostBackendDelegateImpl::OnSetHostNetworkRequestFinished(): "
  287. << (success ? "Completed successful" : "Failure requesting") << " "
  288. << "host change for " << device_for_request.GetInstanceIdDeviceIdForLogs()
  289. << ". Attempted to enable: " << (attempted_to_enable ? "true" : "false");
  290. if (success) {
  291. PA_LOG(VERBOSE) << ss.str();
  292. return;
  293. }
  294. ss << ", Error code: " << result_code;
  295. PA_LOG(WARNING) << ss.str();
  296. if (!HasPendingHostRequest())
  297. return;
  298. absl::optional<multidevice::RemoteDeviceRef> pending_host_request =
  299. GetPendingHostRequest();
  300. bool failed_request_was_to_set_pending_host =
  301. attempted_to_enable && pending_host_request &&
  302. *pending_host_request == device_for_request;
  303. bool failed_request_was_to_remove_pending_host =
  304. !attempted_to_enable && !pending_host_request &&
  305. device_for_request == host_from_last_sync_;
  306. // If the request which failed corresponds to the most recent call to
  307. // AttemptToSetMultiDeviceHostOnBackend(), alert observers that this request
  308. // failed and schedule a retry.
  309. if (failed_request_was_to_set_pending_host ||
  310. failed_request_was_to_remove_pending_host) {
  311. NotifyBackendRequestFailed();
  312. timer_->Start(
  313. FROM_HERE, base::Minutes(kNumMinutesBetweenRetries),
  314. base::BindOnce(&HostBackendDelegateImpl::AttemptNetworkRequest,
  315. base::Unretained(this), true /* is_retry */));
  316. }
  317. }
  318. } // namespace multidevice_setup
  319. } // namespace ash