aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/bigtable/kernels/bigtable_kernels.cc
blob: a6755a3496f3e1720f1c8c67f75521f2380a9845 (plain)
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
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/contrib/bigtable/kernels/bigtable_lib.h"

#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/core/threadpool.h"

namespace tensorflow {

namespace {

class BigtableClientOp : public OpKernel {
 public:
  explicit BigtableClientOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("project_id", &project_id_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("instance_id", &instance_id_));
    OP_REQUIRES(ctx, !project_id_.empty(),
                errors::InvalidArgument("project_id must be non-empty"));
    OP_REQUIRES(ctx, !instance_id_.empty(),
                errors::InvalidArgument("instance_id must be non-empty"));

    OP_REQUIRES_OK(
        ctx, ctx->GetAttr("connection_pool_size", &connection_pool_size_));
    // If left unset by the client code, set it to a default of 100. Note: the
    // cloud-cpp default of 4 concurrent connections is far too low for high
    // performance streaming.
    if (connection_pool_size_ == -1) {
      connection_pool_size_ = 100;
    }

    OP_REQUIRES_OK(ctx, ctx->GetAttr("max_receive_message_size",
                                     &max_receive_message_size_));
    // If left unset by the client code, set it to a default of 100. Note: the
    // cloud-cpp default of 4 concurrent connections is far too low for high
    // performance streaming.
    if (max_receive_message_size_ == -1) {
      max_receive_message_size_ = 1 << 24;  // 16 MBytes
    }
    OP_REQUIRES(ctx, max_receive_message_size_ > 0,
                errors::InvalidArgument("connection_pool_size must be > 0"));
  }

  ~BigtableClientOp() override {
    if (cinfo_.resource_is_private_to_kernel()) {
      if (!cinfo_.resource_manager()
               ->Delete<BigtableClientResource>(cinfo_.container(),
                                                cinfo_.name())
               .ok()) {
        // Do nothing; the resource can have been deleted by session resets.
      }
    }
  }

  void Compute(OpKernelContext* ctx) override LOCKS_EXCLUDED(mu_) {
    mutex_lock l(mu_);
    if (!initialized_) {
      ResourceMgr* mgr = ctx->resource_manager();
      OP_REQUIRES_OK(ctx, cinfo_.Init(mgr, def()));
      BigtableClientResource* resource;
      OP_REQUIRES_OK(
          ctx,
          mgr->LookupOrCreate<BigtableClientResource>(
              cinfo_.container(), cinfo_.name(), &resource,
              [this, ctx](
                  BigtableClientResource** ret) EXCLUSIVE_LOCKS_REQUIRED(mu_) {
                auto client_options =
                    google::cloud::bigtable::ClientOptions()
                        .set_connection_pool_size(connection_pool_size_)
                        .set_data_endpoint("batch-bigtable.googleapis.com");
                auto channel_args = client_options.channel_arguments();
                channel_args.SetMaxReceiveMessageSize(
                    max_receive_message_size_);
                channel_args.SetUserAgentPrefix("tensorflow");
                client_options.set_channel_arguments(channel_args);
                std::shared_ptr<google::cloud::bigtable::DataClient> client =
                    google::cloud::bigtable::CreateDefaultDataClient(
                        project_id_, instance_id_, std::move(client_options));
                *ret = new BigtableClientResource(project_id_, instance_id_,
                                                  std::move(client));
                return Status::OK();
              }));
      core::ScopedUnref resource_cleanup(resource);
      initialized_ = true;
    }
    OP_REQUIRES_OK(ctx, MakeResourceHandleToOutput(
                            ctx, 0, cinfo_.container(), cinfo_.name(),
                            MakeTypeIndex<BigtableClientResource>()));
  }

 private:
  string project_id_;
  string instance_id_;
  int64 connection_pool_size_;
  int32 max_receive_message_size_;

  mutex mu_;
  ContainerInfo cinfo_ GUARDED_BY(mu_);
  bool initialized_ GUARDED_BY(mu_) = false;
};

REGISTER_KERNEL_BUILDER(Name("BigtableClient").Device(DEVICE_CPU),
                        BigtableClientOp);

class BigtableTableOp : public OpKernel {
 public:
  explicit BigtableTableOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("table_name", &table_));
    OP_REQUIRES(ctx, !table_.empty(),
                errors::InvalidArgument("table_name must be non-empty"));
  }

  ~BigtableTableOp() override {
    if (cinfo_.resource_is_private_to_kernel()) {
      if (!cinfo_.resource_manager()
               ->Delete<BigtableTableResource>(cinfo_.container(),
                                               cinfo_.name())
               .ok()) {
        // Do nothing; the resource can have been deleted by session resets.
      }
    }
  }

  void Compute(OpKernelContext* ctx) override LOCKS_EXCLUDED(mu_) {
    mutex_lock l(mu_);
    if (!initialized_) {
      ResourceMgr* mgr = ctx->resource_manager();
      OP_REQUIRES_OK(ctx, cinfo_.Init(mgr, def()));

      BigtableClientResource* client_resource;
      OP_REQUIRES_OK(
          ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &client_resource));
      core::ScopedUnref unref_client(client_resource);

      BigtableTableResource* resource;
      OP_REQUIRES_OK(
          ctx, mgr->LookupOrCreate<BigtableTableResource>(
                   cinfo_.container(), cinfo_.name(), &resource,
                   [this, client_resource](BigtableTableResource** ret) {
                     *ret = new BigtableTableResource(client_resource, table_);
                     return Status::OK();
                   }));
      initialized_ = true;
    }
    OP_REQUIRES_OK(ctx, MakeResourceHandleToOutput(
                            ctx, 0, cinfo_.container(), cinfo_.name(),
                            MakeTypeIndex<BigtableTableResource>()));
  }

 private:
  string table_;  // Note: this is const after construction.

  mutex mu_;
  ContainerInfo cinfo_ GUARDED_BY(mu_);
  bool initialized_ GUARDED_BY(mu_) = false;
};

REGISTER_KERNEL_BUILDER(Name("BigtableTable").Device(DEVICE_CPU),
                        BigtableTableOp);

class ToBigtableOp : public AsyncOpKernel {
 public:
  explicit ToBigtableOp(OpKernelConstruction* ctx)
      : AsyncOpKernel(ctx),
        thread_pool_(new thread::ThreadPool(
            ctx->env(), ThreadOptions(),
            strings::StrCat("to_bigtable_op_", SanitizeThreadSuffix(name())),
            /* num_threads = */ 1, /* low_latency_hint = */ false)) {}

  void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override {
    // The call to `iterator->GetNext()` may block and depend on an
    // inter-op thread pool thread, so we issue the call from the
    // owned thread pool.
    thread_pool_->Schedule([this, ctx, done]() {
      const Tensor* column_families_tensor;
      OP_REQUIRES_OK_ASYNC(
          ctx, ctx->input("column_families", &column_families_tensor), done);
      OP_REQUIRES_ASYNC(
          ctx, column_families_tensor->dims() == 1,
          errors::InvalidArgument("`column_families` must be a vector."), done);

      const Tensor* columns_tensor;
      OP_REQUIRES_OK_ASYNC(ctx, ctx->input("columns", &columns_tensor), done);
      OP_REQUIRES_ASYNC(ctx, columns_tensor->dims() == 1,
                        errors::InvalidArgument("`columns` must be a vector."),
                        done);
      OP_REQUIRES_ASYNC(
          ctx,
          columns_tensor->NumElements() ==
              column_families_tensor->NumElements(),
          errors::InvalidArgument("len(column_families) != len(columns)"),
          done);

      std::vector<string> column_families;
      column_families.reserve(column_families_tensor->NumElements());
      std::vector<string> columns;
      columns.reserve(column_families_tensor->NumElements());
      for (uint64 i = 0; i < column_families_tensor->NumElements(); ++i) {
        column_families.push_back(column_families_tensor->flat<string>()(i));
        columns.push_back(columns_tensor->flat<string>()(i));
      }

      DatasetBase* dataset;
      OP_REQUIRES_OK_ASYNC(
          ctx, GetDatasetFromVariantTensor(ctx->input(1), &dataset), done);

      IteratorContext iter_ctx = dataset::MakeIteratorContext(ctx);
      std::unique_ptr<IteratorBase> iterator;
      OP_REQUIRES_OK_ASYNC(
          ctx,
          dataset->MakeIterator(&iter_ctx, "ToBigtableOpIterator", &iterator),
          done);

      int64 timestamp_int;
      OP_REQUIRES_OK_ASYNC(
          ctx, ParseScalarArgument<int64>(ctx, "timestamp", &timestamp_int),
          done);
      OP_REQUIRES_ASYNC(ctx, timestamp_int >= -1,
                        errors::InvalidArgument("timestamp must be >= -1"),
                        done);

      BigtableTableResource* resource;
      OP_REQUIRES_OK_ASYNC(
          ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &resource), done);
      core::ScopedUnref resource_cleanup(resource);

      std::vector<Tensor> components;
      components.reserve(dataset->output_dtypes().size());
      bool end_of_sequence = false;
      do {
        ::google::cloud::bigtable::BulkMutation mutation;
        // TODO(saeta): Make # of mutations configurable.
        for (uint64 i = 0; i < 100 && !end_of_sequence; ++i) {
          OP_REQUIRES_OK_ASYNC(
              ctx, iterator->GetNext(&iter_ctx, &components, &end_of_sequence),
              done);
          if (!end_of_sequence) {
            OP_REQUIRES_OK_ASYNC(
                ctx,
                CreateMutation(std::move(components), column_families, columns,
                               timestamp_int, &mutation),
                done);
          }
          components.clear();
        }
        grpc::Status mutation_status;
        std::vector<::google::cloud::bigtable::FailedMutation> failures =
            resource->table().BulkApply(std::move(mutation), mutation_status);
        if (!mutation_status.ok()) {
          LOG(ERROR) << "Failure applying mutation: "
                     << mutation_status.error_code() << " - "
                     << mutation_status.error_message() << " ("
                     << mutation_status.error_details() << ").";
        }
        if (!failures.empty()) {
          for (const auto& failure : failures) {
            LOG(ERROR) << "Failure applying mutation on row ("
                       << failure.original_index()
                       << "): " << failure.mutation().row_key()
                       << " - error: " << failure.status().error_message()
                       << " (Details: " << failure.status().error_details()
                       << ").";
          }
        }
        OP_REQUIRES_ASYNC(
            ctx, failures.empty() && mutation_status.ok(),
            errors::Unknown("Failure while writing to Cloud Bigtable: ",
                            mutation_status.error_code(), " - ",
                            mutation_status.error_message(), " (",
                            mutation_status.error_details(),
                            "), # of mutation failures: ", failures.size(),
                            ". See the log for the specific error details."),
            done);
      } while (!end_of_sequence);
      done();
    });
  }

 private:
  static string SanitizeThreadSuffix(string suffix) {
    string clean;
    for (int i = 0; i < suffix.size(); ++i) {
      const char ch = suffix[i];
      if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
          (ch >= '0' && ch <= '9') || ch == '_' || ch == '-') {
        clean += ch;
      } else {
        clean += '_';
      }
    }
    return clean;
  }

  Status CreateMutation(
      std::vector<Tensor> tensors, const std::vector<string>& column_families,
      const std::vector<string>& columns, int64 timestamp_int,
      ::google::cloud::bigtable::BulkMutation* bulk_mutation) {
    if (tensors.size() != column_families.size() + 1) {
      return errors::InvalidArgument(
          "Iterator produced a set of Tensors shorter than expected");
    }
    ::google::cloud::bigtable::SingleRowMutation mutation(
        std::move(tensors[0].scalar<string>()()));
    std::chrono::milliseconds timestamp(timestamp_int);
    for (size_t i = 1; i < tensors.size(); ++i) {
      if (!TensorShapeUtils::IsScalar(tensors[i].shape())) {
        return errors::Internal("Output tensor ", i, " was not a scalar");
      }
      if (timestamp_int == -1) {
        mutation.emplace_back(::google::cloud::bigtable::SetCell(
            column_families[i - 1], columns[i - 1],
            std::move(tensors[i].scalar<string>()())));
      } else {
        mutation.emplace_back(::google::cloud::bigtable::SetCell(
            column_families[i - 1], columns[i - 1], timestamp,
            std::move(tensors[i].scalar<string>()())));
      }
    }
    bulk_mutation->emplace_back(std::move(mutation));
    return Status::OK();
  }

  template <typename T>
  Status ParseScalarArgument(OpKernelContext* ctx,
                             const StringPiece& argument_name, T* output) {
    const Tensor* argument_t;
    TF_RETURN_IF_ERROR(ctx->input(argument_name, &argument_t));
    if (!TensorShapeUtils::IsScalar(argument_t->shape())) {
      return errors::InvalidArgument(argument_name, " must be a scalar");
    }
    *output = argument_t->scalar<T>()();
    return Status::OK();
  }

  std::unique_ptr<thread::ThreadPool> thread_pool_;
};

REGISTER_KERNEL_BUILDER(Name("DatasetToBigtable").Device(DEVICE_CPU),
                        ToBigtableOp);

}  // namespace

}  // namespace tensorflow