1 /* Copyright 2019 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 #include "tensorflow/core/profiler/lib/profiler_lock.h"
16 
17 #include <atomic>
18 
19 #include "tensorflow/core/platform/macros.h"
20 #include "tensorflow/core/util/env_var.h"
21 
22 namespace tensorflow {
23 namespace profiler {
24 
25 // Track whether there's an active profiler session.
26 // Prevents another profiler session from creating ProfilerInterface(s).
27 std::atomic<bool> session_active = ATOMIC_VAR_INIT(false);
28 
AcquireProfilerLock()29 bool AcquireProfilerLock() {
30   // Use environment variable to permanently lock the profiler.
31   // This allows running TensorFlow under an external profiling tool with all
32   // built-in profiling disabled.
33   static bool tf_profiler_disabled = [] {
34     bool disabled = false;
35     ReadBoolFromEnvVar("TF_DISABLE_PROFILING", false, &disabled).IgnoreError();
36     return disabled;
37   }();
38   if (TF_PREDICT_FALSE(tf_profiler_disabled)) {
39     LOG(WARNING) << "TensorFlow Profiler is permanently disabled by env var "
40                     "TF_DISABLE_PROFILING.";
41     return false;
42   }
43   return !session_active.exchange(true);
44 }
45 
ReleaseProfilerLock()46 void ReleaseProfilerLock() { session_active.store(false); }
47 
48 }  // namespace profiler
49 }  // namespace tensorflow
50