api.rotator.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. <?php
  2. /**
  3. * Performs chunks cleanup to prevent storages exhaust
  4. */
  5. class Rotator {
  6. /**
  7. * Contains alter config as key=>value
  8. *
  9. * @var array
  10. */
  11. protected $altCfg = array();
  12. /**
  13. * Contains binpaths config as key=>value
  14. *
  15. * @var array
  16. */
  17. protected $binPaths = array();
  18. /**
  19. * Contains percent of reserved space for each storage
  20. *
  21. * @var int
  22. */
  23. protected $reservedSpacePercent = 10;
  24. /**
  25. * Storages instance placeholder.
  26. *
  27. * @var object
  28. */
  29. protected $storages = '';
  30. /**
  31. * Cameras instance placeholder
  32. *
  33. * @var object
  34. */
  35. protected $cameras = '';
  36. /**
  37. * Contains full cameras data as cameraId=>fullCameraData
  38. *
  39. * @var array
  40. */
  41. protected $allCamerasData = array();
  42. /**
  43. * Contains all storages data as storageId=>storageData
  44. *
  45. * @var array
  46. */
  47. protected $allStoragesData = array();
  48. /**
  49. * Debugging mode flag
  50. *
  51. * @var bool
  52. */
  53. protected $debugFlag = false;
  54. /**
  55. * Use fast rotator for channels cleanup?
  56. *
  57. * @var bool
  58. */
  59. protected $fastFlag = false;
  60. /**
  61. * Other predefined stuff
  62. */
  63. const ROTATOR_PID = 'ROTATOR';
  64. const DEBUG_LOG = 'exports/rotator_debug.log';
  65. public function __construct() {
  66. $this->loadConfigs();
  67. $this->initStorages();
  68. $this->initCameras();
  69. }
  70. /**
  71. * Loads all required configs
  72. *
  73. * @global object $ubillingConfig
  74. *
  75. * @return void
  76. */
  77. protected function loadConfigs() {
  78. global $ubillingConfig;
  79. $this->altCfg = $ubillingConfig->getAlter();
  80. $this->binPaths = $ubillingConfig->getBinpaths();
  81. $this->reservedSpacePercent = $this->altCfg['STORAGE_RESERVED_SPACE'];
  82. if (isset($this->altCfg['ROTATOR_DEBUG'])) {
  83. if ($this->altCfg['ROTATOR_DEBUG']) {
  84. $this->debugFlag = true;
  85. }
  86. }
  87. if (isset($this->altCfg['ROTATOR_FAST'])) {
  88. if ($this->altCfg['ROTATOR_FAST']) {
  89. $this->fastFlag = true;
  90. }
  91. }
  92. }
  93. /**
  94. * Inits storages into protected prop for further usage
  95. *
  96. * @return void
  97. */
  98. protected function initStorages() {
  99. $this->storages = new Storages();
  100. $this->allStoragesData = $this->storages->getAllStoragesData();
  101. }
  102. /**
  103. * Inits cameras into protected prop and loads its full data
  104. *
  105. * @return void
  106. */
  107. protected function initCameras() {
  108. $this->cameras = new Cameras();
  109. $this->allCamerasData = $this->cameras->getAllCamerasFullData();
  110. }
  111. /**
  112. * Returns existing channels list available in storage depends of camera setup
  113. *
  114. * @return array
  115. */
  116. protected function getStorageChannels($storageId) {
  117. $result = array();
  118. if (isset($this->allStoragesData[$storageId])) {
  119. if (!empty($this->allCamerasData)) {
  120. foreach ($this->allCamerasData as $io => $eachCameraData) {
  121. if ($eachCameraData['CAMERA']['storageid'] == $storageId) {
  122. $storagePath = $eachCameraData['STORAGE']['path'];
  123. $storagePathLastChar = substr($storagePath, 0, -1);
  124. if ($storagePathLastChar != '/') {
  125. $storagePath = $storagePath . '/';
  126. }
  127. $channelName = $eachCameraData['CAMERA']['channel'];
  128. $channelFullPath = $storagePath . $channelName;
  129. if (file_exists($channelFullPath)) {
  130. if (is_writable($channelFullPath)) {
  131. $result[$channelName] = $channelFullPath;
  132. }
  133. }
  134. }
  135. }
  136. }
  137. }
  138. return($result);
  139. }
  140. /**
  141. * Just deletes oldest chunk from some channel
  142. *
  143. * @param int $storageId
  144. * @param string $channel
  145. *
  146. * @return string/void
  147. */
  148. protected function flushChannelOldestChunk($storageId, $channel) {
  149. $result = '';
  150. $chunksList = $this->storages->getChannelChunks($storageId, $channel);
  151. if (!empty($chunksList)) {
  152. $chunksCount = sizeof($chunksList);
  153. //does not kill a single chunk. It may be the current recording.
  154. if ($chunksCount > 1) {
  155. $oldestChunk = reset($chunksList);
  156. unlink($oldestChunk);
  157. $result = $oldestChunk;
  158. }
  159. }
  160. return($result);
  161. }
  162. /**
  163. * Checks, is channel locked by another background process or not?
  164. *
  165. * @param string $channelId
  166. *
  167. * @return bool
  168. */
  169. protected function channelNotLocked($channelId) {
  170. $result = true;
  171. $channelPid = new StarDust(Export::PID_EXPORT . $channelId);
  172. if ($channelPid->isRunning()) {
  173. $result = false;
  174. }
  175. return($result);
  176. }
  177. /**
  178. * Cleanups channel chunks until total size will be less than specified
  179. *
  180. * @param array $chunksList
  181. * @param int $expectedSize
  182. *
  183. * @return array
  184. */
  185. protected function flushChunksBySize($chunksList, $expectedSize) {
  186. $bytesFree = 0;
  187. $chunksDeleted = 0;
  188. if ((!empty($chunksList)) AND ( $expectedSize > 0)) {
  189. foreach ($chunksList as $eachTimeStamp => $chunksData) {
  190. if ($bytesFree < $expectedSize) {
  191. unlink($chunksData['path']);
  192. $chunksDeleted++;
  193. $bytesFree += $chunksData['size'];
  194. }
  195. }
  196. }
  197. $result = array('count' => $chunksDeleted, 'free' => $bytesFree);
  198. return($result);
  199. }
  200. /**
  201. * Performs old chunks rotation for all cameras
  202. *
  203. * @return void
  204. */
  205. public function run() {
  206. $rotatorProcess = new StarDust(self::ROTATOR_PID);
  207. if ($rotatorProcess->notRunning()) {
  208. $rotatorProcess->start();
  209. if (!empty($this->allStoragesData)) {
  210. foreach ($this->allStoragesData as $io => $eachStorage) {
  211. $storageTotalSpace = disk_total_space($eachStorage['path']);
  212. $storageFreeSpace = disk_free_space($eachStorage['path']);
  213. $usedStorageSpace = $storageTotalSpace - $storageFreeSpace;
  214. $maxUsagePercent = 100 - ($this->reservedSpacePercent);
  215. $maxUsageSpace = zb_Percent($storageTotalSpace, $maxUsagePercent);
  216. $mustBeFree = $storageTotalSpace - $maxUsageSpace;
  217. $allChannelsSpace = 0;
  218. //storage cleanup required?
  219. if ($storageFreeSpace < $mustBeFree) {
  220. $eachStorageChannels = $this->getStorageChannels($eachStorage['id']);
  221. //this storage must be cleaned
  222. if (!empty($eachStorageChannels)) {
  223. //count of channels
  224. $storageChannelsCount = sizeof($eachStorageChannels);
  225. foreach ($eachStorageChannels as $eachChannel => $chanPath) {
  226. $allChannelsSpace += $this->storages->getChannelSize($eachStorage['id'], $eachChannel);
  227. }
  228. $avgChanSize = $allChannelsSpace / $storageChannelsCount;
  229. $usedBySystem = $usedStorageSpace - $allChannelsSpace;
  230. //fair?
  231. $maxChannelAllocSize = round((($storageFreeSpace - $mustBeFree) + $allChannelsSpace) / $storageChannelsCount);
  232. foreach ($eachStorageChannels as $eachChannel => $chanPath) {
  233. if ($this->channelNotLocked($eachChannel)) {
  234. //
  235. // Fast rotator here
  236. //
  237. if ($this->fastFlag) {
  238. $eachChannelChunksAlloc = $this->storages->getChunksAllocSpaces($eachStorage['id'], $eachChannel);
  239. $eachChannelSize = $this->storages->calcChunksListSize($eachChannelChunksAlloc);
  240. //this channel is exhausted his reserved size?
  241. if ($eachChannelSize > $maxChannelAllocSize) {
  242. file_put_contents(self::DEBUG_LOG, curdatetime() . ' ' . wr_convertSize($eachChannelSize) . ' > OF ' . wr_convertSize($maxChannelAllocSize) . ' ' . $eachChannel . PHP_EOL, FILE_APPEND);
  243. $requiredToFree = $eachChannelSize - $maxChannelAllocSize;
  244. $cleanResult = $this->flushChunksBySize($eachChannelChunksAlloc, $requiredToFree);
  245. if ($this->debugFlag) {
  246. file_put_contents(self::DEBUG_LOG, curdatetime() . ' ' . wr_convertSize($cleanResult['free']) . ' CLEANED IN ' . $eachChannel . ' DELETED ' . $cleanResult['count'] . ' CHUNKS' . PHP_EOL, FILE_APPEND);
  247. }
  248. } else {
  249. //and there some rotation skips logging
  250. if ($this->debugFlag) {
  251. file_put_contents(self::DEBUG_LOG, curdatetime() . ' ' . wr_convertSize($eachChannelSize) . ' < OF ' . wr_convertSize($maxChannelAllocSize) . ' ' . $eachChannel . PHP_EOL, FILE_APPEND);
  252. }
  253. }
  254. } else {
  255. //
  256. // Stable rotator model
  257. //
  258. $eachChannelSize = $this->storages->getChannelSize($eachStorage['id'], $eachChannel);
  259. //this channel is exhausted his reserved size?
  260. if ($eachChannelSize > $maxChannelAllocSize) {
  261. while ($eachChannelSize > $maxChannelAllocSize) {
  262. $this->flushChannelOldestChunk($eachStorage['id'], $eachChannel);
  263. $eachChannelSize = $this->storages->getChannelSize($eachStorage['id'], $eachChannel);
  264. //some debug logging here
  265. if ($this->debugFlag) {
  266. file_put_contents(self::DEBUG_LOG, curdatetime() . ' ' . wr_convertSize($eachChannelSize) . ' > OF ' . wr_convertSize($maxChannelAllocSize) . ' ' . $eachChannel . PHP_EOL, FILE_APPEND);
  267. }
  268. }
  269. } else {
  270. //and there some rotation skips logging
  271. if ($this->debugFlag) {
  272. file_put_contents(self::DEBUG_LOG, curdatetime() . ' ' . wr_convertSize($eachChannelSize) . ' < OF ' . wr_convertSize($maxChannelAllocSize) . ' ' . $eachChannel . PHP_EOL, FILE_APPEND);
  273. }
  274. }
  275. }
  276. } else {
  277. //and there some rotation skips on export logging
  278. if ($this->debugFlag) {
  279. file_put_contents(self::DEBUG_LOG, curdatetime() . ' SKIPPED LOCKED BY EXPORT ' . $eachChannel . PHP_EOL, FILE_APPEND);
  280. }
  281. }
  282. }
  283. }
  284. }
  285. }
  286. }
  287. $rotatorProcess->stop();
  288. }
  289. }
  290. }