RDK Documentation (Open Sourced RDK Components)
hangdetector_utils.h
1 /*
2  * If not stated otherwise in this file or this component's Licenses.txt file the
3  * following copyright and licenses apply:
4  *
5  * Copyright 2016 RDK Management
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18 */
19 #ifndef HANGDETECTOR_UTILS_H
20 #define HANGDETECTOR_UTILS_H
21 
22 #include <glib.h>
23 #include "logger.h"
24 
25 #include <thread>
26 #include <atomic>
27 #include <sys/types.h>
28 #include <unistd.h>
29 
30 namespace Utils
31 {
32 
34 {
35  std::unique_ptr<std::thread> m_thread;
36  std::atomic_bool m_running {false};
37  std::atomic_int m_resetCount {0};
38  std::atomic_int m_threshold {30};
39 
40  void runWatchDog()
41  {
42  while(m_running)
43  {
44  std::this_thread::sleep_for(std::chrono::seconds(1));
45  if (m_resetCount > m_threshold)
46  {
47  printf("hang detected\n"); fflush(stdout);
48  kill(getpid(), SIGFPE);
49  }
50  else if (m_resetCount > (m_threshold / 2))
51  {
52  printf("hang detector will force crash in %d seconds...\n", m_threshold - m_resetCount); fflush(stdout);
53  }
54  ++m_resetCount;
55  }
56  }
57 
58  void resetWatchDog()
59  {
60  m_resetCount = 0;
61  }
62 
63  void initThreshold()
64  {
65  const char* var = getenv("RTRMFPLAYER_HANG_DETECTOR_THRESHOLD_SEC");
66  if (var)
67  {
68  try
69  {
70  int tmp = std::atoi(var);
71  if (tmp > 5)
72  {
73  m_threshold = tmp;
74  }
75  } catch (...) {}
76  }
77  }
78 
79 public:
80  ~HangDetector()
81  {
82  stop();
83  }
84 
85  void start()
86  {
87  if (m_thread)
88  return;
89  initThreshold();
90 
91  m_running = true;
92 
93  g_timeout_add_seconds(1, [](gpointer data) -> gboolean {
94  static_cast<HangDetector*>(data)->resetWatchDog();
95  return G_SOURCE_CONTINUE;
96  }, this);
97 
98  m_thread.reset(new std::thread(&HangDetector::runWatchDog, this));
99  }
100 
101  void stop()
102  {
103  m_running = true;
104  m_thread->join();
105  }
106 };
107 
108 } // namespace utils
109 
110 #endif // HANGDETECTOR_H
Utils::HangDetector
Definition: hangdetector_utils.h:33