1 /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. 2 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 ==============================================================================*/ 15 #ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_CANCELLABLE_CALL_H_ 16 #define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_CANCELLABLE_CALL_H_ 17 18 #include <string> 19 #include "tensorflow/core/distributed_runtime/call_options.h" 20 #include "tensorflow/core/distributed_runtime/worker_cache.h" 21 #include "tensorflow/core/framework/cancellation.h" 22 #include "tensorflow/core/platform/mutex.h" 23 24 namespace tensorflow { 25 26 // Supports client side cancellation of WorkerInterface calls via 27 // registration with a CancellationManager. 28 class CancellableCall { 29 public: CancellableCall(CancellationManager * cancel_mgr,const string & remote_worker,WorkerCacheInterface * wc)30 CancellableCall(CancellationManager* cancel_mgr, const string& remote_worker, 31 WorkerCacheInterface* wc) 32 : cancel_mgr_(cancel_mgr), 33 remote_worker_(remote_worker), 34 wc_(wc), 35 wi_(wc_->CreateWorker(remote_worker_)) {} 36 ~CancellableCall()37 virtual ~CancellableCall() { wc_->ReleaseWorker(remote_worker_, wi_); } 38 39 virtual void IssueCall(const StatusCallback& done) = 0; 40 Start(const StatusCallback & done)41 void Start(const StatusCallback& done) { 42 CancellationToken token = cancel_mgr_->get_cancellation_token(); 43 const bool not_yet_cancelled = cancel_mgr_->RegisterCallback( 44 token, [this, token]() { opts_.StartCancel(); }); 45 if (not_yet_cancelled) { 46 IssueCall([this, token, done](const Status& s) { 47 cancel_mgr_->DeregisterCallback(token); 48 done(s); 49 }); 50 } else { 51 done(errors::Cancelled("RPC Request was cancelled")); 52 } 53 } 54 55 protected: 56 mutable mutex mu_; 57 CancellationManager* const cancel_mgr_; // Not owned 58 const string remote_worker_; 59 WorkerCacheInterface* const wc_; // Not owned 60 WorkerInterface* const wi_; // Owned by wc_, must be released. 61 CallOptions opts_; 62 }; 63 64 } // namespace tensorflow 65 #endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_CANCELLABLE_CALL_H_ 66