1 /* Copyright 2020 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
16 #include "tensorflow/core/data/service/grpc_util.h"
17
18 #include "tensorflow/core/distributed_runtime/rpc/grpc_util.h"
19 #include "tensorflow/core/lib/core/errors.h"
20 #include "tensorflow/core/platform/env.h"
21 #include "tensorflow/core/platform/env_time.h"
22 #include "tensorflow/core/platform/errors.h"
23 #include "tensorflow/core/platform/status.h"
24
25 namespace tensorflow {
26 namespace data {
27 namespace grpc_util {
28
WrapError(const std::string & message,const::grpc::Status & status)29 Status WrapError(const std::string& message, const ::grpc::Status& status) {
30 if (status.ok()) {
31 return errors::Internal("Expected a non-ok grpc status. Wrapping message: ",
32 message);
33 } else {
34 Status s = FromGrpcStatus(status);
35 return Status(s.code(),
36 absl::StrCat(message, ": ", status.error_message()));
37 }
38 }
39
Retry(const std::function<Status ()> & f,const std::string & description,int64 deadline_micros)40 Status Retry(const std::function<Status()>& f, const std::string& description,
41 int64 deadline_micros) {
42 Status s = f();
43 for (int num_retries = 0;; ++num_retries) {
44 if (!errors::IsUnavailable(s) && !errors::IsAborted(s) &&
45 !errors::IsCancelled(s)) {
46 return s;
47 }
48 int64 now_micros = EnvTime::NowMicros();
49 if (now_micros > deadline_micros) {
50 return s;
51 }
52 int64 deadline_with_backoff_micros =
53 now_micros + ::tensorflow::ComputeBackoffMicroseconds(num_retries);
54 // Wait for a short period of time before retrying. If our backoff would put
55 // us past the deadline, we truncate it to ensure our attempt starts before
56 // the deadline.
57 int64 backoff_until =
58 std::min(deadline_with_backoff_micros, deadline_micros);
59 int64 wait_time_micros = backoff_until - now_micros;
60 if (wait_time_micros > 100 * 1000) {
61 LOG(INFO) << "Failed to " << description << ": " << s
62 << ". Will retry in " << wait_time_micros / 1000 << "ms.";
63 }
64 Env::Default()->SleepForMicroseconds(wait_time_micros);
65 s = f();
66 }
67 return s;
68 }
69
70 } // namespace grpc_util
71 } // namespace data
72 } // namespace tensorflow
73