TensorFlow Serving C++ API Documentation
log_collector.cc
1 /* Copyright 2016 Google Inc. 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_serving/core/log_collector.h"
17 
18 #include <memory>
19 #include <unordered_map>
20 
21 #include "tensorflow/core/lib/core/errors.h"
22 #include "tensorflow/core/lib/strings/scanner.h"
23 #include "tensorflow/core/platform/mutex.h"
24 #include "tensorflow/core/platform/thread_annotations.h"
25 
26 namespace tensorflow {
27 namespace serving {
28 namespace {
29 
30 // This class is thread-safe.
31 class Registry {
32  public:
33  Status Register(const string& type, const LogCollector::Factory& factory)
34  TF_LOCKS_EXCLUDED(mu_) {
35  mutex_lock l(mu_);
36  const auto found_it = factory_map_.find(type);
37  if (found_it != factory_map_.end()) {
38  return errors::AlreadyExists("Type ", type, " already registered.");
39  }
40  factory_map_.insert({type, factory});
41  return OkStatus();
42  }
43 
44  const LogCollector::Factory* Lookup(const string& type) const
45  TF_LOCKS_EXCLUDED(mu_) {
46  mutex_lock l(mu_);
47  const auto found_it = factory_map_.find(type);
48  if (found_it == factory_map_.end()) {
49  return nullptr;
50  }
51  return &(found_it->second);
52  }
53 
54  private:
55  mutable mutex mu_;
56  std::unordered_map<string, LogCollector::Factory> factory_map_
57  TF_GUARDED_BY(mu_);
58 };
59 
60 Registry* GetRegistry() {
61  static auto* registry = new Registry();
62  return registry;
63 }
64 
65 } // namespace
66 
67 Status LogCollector::RegisterFactory(const string& type,
68  const Factory& factory) {
69  return GetRegistry()->Register(type, factory);
70 }
71 
72 Status LogCollector::Create(
73  const LogCollectorConfig& config, const uint32 id,
74  std::unique_ptr<LogCollector>* const log_collector) {
75  auto* factory = GetRegistry()->Lookup(config.type());
76  if (factory == nullptr) {
77  return errors::NotFound("Cannot find LogCollector::Factory for type: ",
78  config.type());
79  }
80  return (*factory)(config, id, log_collector);
81 }
82 
83 } // namespace serving
84 } // namespace tensorflow