MythTV  master
autoexpire.cpp
Go to the documentation of this file.
1 // System headers
2 #include <sys/stat.h>
3 #ifdef __linux__
4 # include <sys/vfs.h>
5 #else // if !__linux__
6 # include <sys/param.h>
7 # ifndef _WIN32
8 # include <sys/mount.h>
9 # endif // _WIN32
10 #endif // !__linux__
11 
12 // POSIX headers
13 #include <unistd.h>
14 
15 // C headers
16 #include <cstdlib>
17 
18 // C++ headers
19 #include <iostream>
20 #include <algorithm>
21 using namespace std;
22 
23 // Qt headers
24 #include <QDateTime>
25 #include <QFileInfo>
26 #include <QList>
27 
28 // MythTV headers
29 #include "filesysteminfo.h"
30 #include "autoexpire.h"
31 #include "programinfo.h"
32 #include "mythcorecontext.h"
33 #include "mythdb.h"
34 #include "mythdate.h"
35 #include "storagegroup.h"
36 #include "remoteutil.h"
37 #include "remoteencoder.h"
38 #include "encoderlink.h"
40 #include "mainserver.h"
41 #include "compat.h"
42 #include "mythlogging.h"
43 #include "tv_rec.h"
44 
45 #define LOC QString("AutoExpire: ")
46 #define LOC_ERR QString("AutoExpire Error: ")
47 
48 extern AutoExpire *expirer;
49 
53 #define SPACE_TOO_BIG_KB (3*1024*1024)
54 
57 {
58  RunProlog();
59  m_parent->RunExpirer();
60  RunEpilog();
61 }
62 
72 AutoExpire::AutoExpire(QMap<int, EncoderLink *> *tvList) :
73  m_encoderList(tvList),
74  m_expireThread(new ExpireThread(this)),
75  m_expireThreadRun(true)
76 {
79 }
80 
85 {
86  {
87  QMutexLocker locker(&m_instanceLock);
88  m_expireThreadRun = false;
89  m_instanceCond.wakeAll();
90  }
91 
92  {
93  QMutexLocker locker(&m_updateLock);
94  m_updateQueue.clear();
95  }
96 
97  if (m_expireThread)
98  {
100  m_expireThread->wait();
101  delete m_expireThread;
102  m_expireThread = nullptr;
103  }
104 }
105 
111 uint64_t AutoExpire::GetDesiredSpace(int fsID) const
112 {
113  QMutexLocker locker(&m_instanceLock);
114  if (m_desiredSpace.contains(fsID))
115  return m_desiredSpace[fsID];
116  return 0;
117 }
118 
123 {
124  LOG(VB_FILE, LOG_INFO, LOC + "CalcParams()");
125 
126  QList<FileSystemInfo> fsInfos;
127 
128  m_instanceLock.lock();
129  if (m_mainServer)
130  {
131  // The scheduler relies on something forcing the mainserver
132  // fsinfos cache to get updated periodically. Currently, that
133  // is done here. Don't remove or change this invocation
134  // without handling that issue too. It is done this way
135  // because the scheduler thread can't afford to be blocked by
136  // an unresponsive, remote filesystem and the autoexpirer
137  // thrad can.
138  m_mainServer->GetFilesystemInfos(fsInfos, false);
139  }
140  m_instanceLock.unlock();
141 
142  if (fsInfos.empty())
143  {
144  LOG(VB_GENERAL, LOG_ERR, LOC + "Filesystem Info cache is empty, unable " "to calculate necessary parameters.");
145 
146  return;
147  }
148 
149  uint64_t maxKBperMin = 0;
150  uint64_t extraKB = static_cast<uint64_t>
151  (gCoreContext->GetNumSetting("AutoExpireExtraSpace", 0))
152  << 20;
153 
154  QMap<int, uint64_t> fsMap;
155  QMap<int, vector<int> > fsEncoderMap;
156 
157  // we use this copying on purpose. The used_encoders map ensures
158  // that every encoder writes only to one fs.
159  // Copying the data minimizes the time the lock is held
160  m_instanceLock.lock();
161  QMap<int, int>::const_iterator ueit = m_usedEncoders.begin();
162  while (ueit != m_usedEncoders.end())
163  {
164  fsEncoderMap[*ueit].push_back(ueit.key());
165  ++ueit;
166  }
167  m_instanceLock.unlock();
168 
169  QList<FileSystemInfo>::iterator fsit;
170  for (fsit = fsInfos.begin(); fsit != fsInfos.end(); ++fsit)
171  {
172  if (fsMap.contains(fsit->getFSysID()))
173  continue;
174 
175  fsMap[fsit->getFSysID()] = 0;
176  uint64_t thisKBperMin = 0;
177 
178  // append unknown recordings to all fsIDs
179  foreach (auto unknownfs, fsEncoderMap[-1])
180  fsEncoderMap[fsit->getFSysID()].push_back(unknownfs);
181 
182  if (fsEncoderMap.contains(fsit->getFSysID()))
183  {
184  LOG(VB_FILE, LOG_INFO,
185  QString("fsID #%1: Total: %2 GB Used: %3 GB Free: %4 GB")
186  .arg(fsit->getFSysID())
187  .arg(fsit->getTotalSpace() / 1024.0 / 1024.0, 7, 'f', 1)
188  .arg(fsit->getUsedSpace() / 1024.0 / 1024.0, 7, 'f', 1)
189  .arg(fsit->getFreeSpace() / 1024.0 / 1024.0, 7, 'f', 1));
190 
191  foreach (auto cardid, fsEncoderMap[fsit->getFSysID()])
192  {
193  EncoderLink *enc = *(m_encoderList->find(cardid));
194 
195  if (!enc->IsConnected() || !enc->IsBusy())
196  {
197  // remove encoder since it can't write to any file system
198  LOG(VB_FILE, LOG_INFO, LOC +
199  QString("Cardid %1: is not recoding, removing it "
200  "from used list.").arg(cardid));
201  m_instanceLock.lock();
202  m_usedEncoders.remove(cardid);
203  m_instanceLock.unlock();
204  continue;
205  }
206 
207  uint64_t maxBitrate = enc->GetMaxBitrate();
208  if (maxBitrate==0)
209  maxBitrate = 19500000LL;
210  thisKBperMin += (maxBitrate*((uint64_t)15))>>11;
211  LOG(VB_FILE, LOG_INFO, QString(" Cardid %1: max bitrate "
212  "%2 Kb/sec, fsID %3 max is now %4 KB/min")
213  .arg(enc->GetInputID())
214  .arg(enc->GetMaxBitrate() >> 10)
215  .arg(fsit->getFSysID())
216  .arg(thisKBperMin));
217  }
218  }
219  fsMap[fsit->getFSysID()] = thisKBperMin;
220 
221  if (thisKBperMin > maxKBperMin)
222  {
223  LOG(VB_FILE, LOG_INFO,
224  QString(" Max of %1 KB/min for fsID %2 is higher "
225  "than the existing Max of %3 so we'll use this Max instead")
226  .arg(thisKBperMin).arg(fsit->getFSysID()).arg(maxKBperMin));
227  maxKBperMin = thisKBperMin;
228  }
229  }
230 
231  // Determine frequency to run autoexpire so it doesn't have to free
232  // too much space
233  uint expireFreq = 15;
234  if (maxKBperMin > 0)
235  {
236  expireFreq = SPACE_TOO_BIG_KB / (maxKBperMin + maxKBperMin/3);
237  expireFreq = max(3U, min(expireFreq, 15U));
238  }
239 
240  double expireMinGB = ((maxKBperMin + maxKBperMin/3)
241  * expireFreq + extraKB) >> 20;
242  LOG(VB_GENERAL, LOG_NOTICE, LOC +
243  QString("CalcParams(): Max required Free Space: %1 GB w/freq: %2 min")
244  .arg(expireMinGB, 0, 'f', 1).arg(expireFreq));
245 
246  // lock class and save these parameters.
247  m_instanceLock.lock();
248  m_desiredFreq = expireFreq;
249  // write per file system needed space back, use safety of 33%
250  QMap<int, uint64_t>::iterator it = fsMap.begin();
251  while (it != fsMap.end())
252  {
253  m_desiredSpace[it.key()] = (*it + *it/3) * expireFreq + extraKB;
254  ++it;
255  }
256  m_instanceLock.unlock();
257 }
258 
268 {
269  QElapsedTimer timer;
270  QDateTime curTime;
271  QDateTime next_expire = MythDate::current().addSecs(60);
272 
273  QMutexLocker locker(&m_instanceLock);
274 
275  // wait a little for main server to come up and things to settle down
276  Sleep(20 * 1000);
277 
278  timer.start();
279 
280  while (m_expireThreadRun)
281  {
282  TVRec::s_inputsLock.lockForRead();
283 
284  curTime = MythDate::current();
285  // recalculate auto expire parameters
286  if (curTime >= next_expire)
287  {
288  m_updateLock.lock();
289  while (!m_updateQueue.empty())
290  {
291  UpdateEntry ue = m_updateQueue.dequeue();
292  if (ue.m_encoder > 0)
294  }
295  m_updateLock.unlock();
296 
297  locker.unlock();
298  CalcParams();
299  locker.relock();
300  if (!m_expireThreadRun)
301  break;
302  }
303  timer.restart();
304 
306 
307  // Expire Short LiveTV files for this backend every 2 minutes
308  if ((curTime.time().minute() % 2) == 0)
310 
311  // Expire normal recordings depending on frequency calculated
312  if (curTime >= next_expire)
313  {
314  LOG(VB_FILE, LOG_INFO, LOC + "Running now!");
315  next_expire =
316  MythDate::current().addSecs(m_desiredFreq * 60);
317 
319 
320  int maxAge = gCoreContext->GetNumSetting("DeletedMaxAge", 0);
321  if (maxAge > 0)
323  else if (maxAge == 0)
325 
327 
329  }
330 
331  TVRec::s_inputsLock.unlock();
332 
333  Sleep(60 * 1000 - timer.elapsed());
334  }
335 }
336 
343 void AutoExpire::Sleep(int sleepTime)
344 {
345  if (sleepTime <= 0)
346  return;
347 
348  QDateTime little_tm = MythDate::current().addMSecs(sleepTime);
349  int timeleft = sleepTime;
350  while (m_expireThreadRun && (timeleft > 0))
351  {
352  m_instanceCond.wait(&m_instanceLock, timeleft);
353  timeleft = MythDate::current().secsTo(little_tm) * 1000;
354  }
355 }
356 
361 {
362  pginfolist_t expireList;
363 
364  LOG(VB_FILE, LOG_INFO, LOC + QString("ExpireLiveTV(%1)").arg(type));
365  FillDBOrdered(expireList, type);
366  SendDeleteMessages(expireList);
367  ClearExpireList(expireList);
368 }
369 
374 {
375  pginfolist_t expireList;
376 
377  LOG(VB_FILE, LOG_INFO, LOC + QString("ExpireOldDeleted()"));
378  FillDBOrdered(expireList, emOldDeletedPrograms);
379  SendDeleteMessages(expireList);
380  ClearExpireList(expireList);
381 }
382 
387 {
388  pginfolist_t expireList;
389 
390  LOG(VB_FILE, LOG_INFO, LOC + QString("ExpireQuickDeleted()"));
392  SendDeleteMessages(expireList);
393  ClearExpireList(expireList);
394 }
395 
401 {
402  pginfolist_t expireList;
403  pginfolist_t deleteList;
404  QList<FileSystemInfo> fsInfos;
405  QList<FileSystemInfo>::iterator fsit;
406 
407  LOG(VB_FILE, LOG_INFO, LOC + "ExpireRecordings()");
408 
409  if (m_mainServer)
410  m_mainServer->GetFilesystemInfos(fsInfos, true);
411 
412  if (fsInfos.empty())
413  {
414  LOG(VB_GENERAL, LOG_ERR, LOC + "Filesystem Info cache is empty, unable "
415  "to determine what Recordings to expire");
416 
417  return;
418  }
419 
420  FillExpireList(expireList);
421 
422  QMap <int, bool> truncateMap;
423  MSqlQuery query(MSqlQuery::InitCon());
424  query.prepare("SELECT DISTINCT rechost, recdir "
425  "FROM inuseprograms "
426  "WHERE recusage = 'truncatingdelete' "
427  "AND lastupdatetime > DATE_ADD(NOW(), INTERVAL -2 MINUTE);");
428 
429  if (!query.exec())
430  {
431  MythDB::DBError(LOC + "ExpireRecordings", query);
432  }
433  else
434  {
435  while (query.next())
436  {
437  QString rechost = query.value(0).toString();
438  QString recdir = query.value(1).toString();
439 
440  LOG(VB_FILE, LOG_INFO, LOC +
441  QString("%1:%2 has an in-progress truncating delete.")
442  .arg(rechost).arg(recdir));
443 
444  for (fsit = fsInfos.begin(); fsit != fsInfos.end(); ++fsit)
445  {
446  if ((fsit->getHostname() == rechost) &&
447  (fsit->getPath() == recdir))
448  {
449  truncateMap[fsit->getFSysID()] = true;
450  break;
451  }
452  }
453  }
454  }
455 
456  QMap <int, bool> fsMap;
457  for (fsit = fsInfos.begin(); fsit != fsInfos.end(); ++fsit)
458  {
459  if (fsMap.contains(fsit->getFSysID()))
460  continue;
461 
462  fsMap[fsit->getFSysID()] = true;
463 
464  LOG(VB_FILE, LOG_INFO,
465  QString("fsID #%1: Total: %2 GB Used: %3 GB Free: %4 GB")
466  .arg(fsit->getFSysID())
467  .arg(fsit->getTotalSpace() / 1024.0 / 1024.0, 7, 'f', 1)
468  .arg(fsit->getUsedSpace() / 1024.0 / 1024.0, 7, 'f', 1)
469  .arg(fsit->getFreeSpace() / 1024.0 / 1024.0, 7, 'f', 1));
470 
471  if ((fsit->getTotalSpace() == -1) || (fsit->getUsedSpace() == -1))
472  {
473  LOG(VB_FILE, LOG_ERR, LOC +
474  QString("fsID #%1 has invalid info, AutoExpire cannot run for "
475  "this filesystem. Continuing on to next...")
476  .arg(fsit->getFSysID()));
477  LOG(VB_FILE, LOG_INFO, QString("Directories on filesystem ID %1:")
478  .arg(fsit->getFSysID()));
479  QList<FileSystemInfo>::iterator fsit2;
480  for (fsit2 = fsInfos.begin(); fsit2 != fsInfos.end(); ++fsit2)
481  {
482  if (fsit2->getFSysID() == fsit->getFSysID())
483  {
484  LOG(VB_FILE, LOG_INFO, QString(" %1:%2")
485  .arg(fsit2->getHostname()).arg(fsit2->getPath()));
486  }
487  }
488 
489  continue;
490  }
491 
492  if (truncateMap.contains(fsit->getFSysID()))
493  {
494  LOG(VB_FILE, LOG_INFO,
495  QString(" fsid %1 has a truncating delete in progress, "
496  "AutoExpire cannot run for this filesystem until the "
497  "delete has finished. Continuing on to next...")
498  .arg(fsit->getFSysID()));
499  continue;
500  }
501 
502  if (max((int64_t)0LL, fsit->getFreeSpace()) <
503  m_desiredSpace[fsit->getFSysID()])
504  {
505  LOG(VB_FILE, LOG_INFO,
506  QString(" Not Enough Free Space! We want %1 MB")
507  .arg(m_desiredSpace[fsit->getFSysID()] / 1024));
508 
509  QMap<QString, int> dirList;
510  QList<FileSystemInfo>::iterator fsit2;
511 
512  LOG(VB_FILE, LOG_INFO,
513  QString(" Directories on filesystem ID %1:")
514  .arg(fsit->getFSysID()));
515 
516  for (fsit2 = fsInfos.begin(); fsit2 != fsInfos.end(); ++fsit2)
517  {
518  if (fsit2->getFSysID() == fsit->getFSysID())
519  {
520  LOG(VB_FILE, LOG_INFO, QString(" %1:%2")
521  .arg(fsit2->getHostname()).arg(fsit2->getPath()));
522  dirList[fsit2->getHostname() + ":" + fsit2->getPath()] = 1;
523  }
524  }
525 
526  LOG(VB_FILE, LOG_INFO,
527  " Searching for files expirable in these directories");
528  QString myHostName = gCoreContext->GetHostName();
529  auto it = expireList.begin();
530  while ((it != expireList.end()) &&
531  (max((int64_t)0LL, fsit->getFreeSpace()) <
532  m_desiredSpace[fsit->getFSysID()]))
533  {
534  ProgramInfo *p = *it;
535  ++it;
536 
537  LOG(VB_FILE, LOG_INFO, QString(" Checking %1 => %2")
538  .arg(p->toString(ProgramInfo::kRecordingKey))
539  .arg(p->GetTitle()));
540 
541  if (!p->IsLocal())
542  {
543  bool foundFile = false;
544  QMap<int, EncoderLink *>::Iterator eit =
545  m_encoderList->begin();
546  while (eit != m_encoderList->end())
547  {
548  EncoderLink *el = *eit;
549  eit++;
550 
551  if ((p->GetHostname() == el->GetHostName()) ||
552  ((p->GetHostname() == myHostName) &&
553  (el->IsLocal())))
554  {
555  if (el->IsConnected())
556  foundFile = el->CheckFile(p);
557 
558  eit = m_encoderList->end();
559  }
560  }
561 
562  if (!foundFile && (p->GetHostname() != myHostName))
563  {
564  // Wasn't found so check locally
565  QString file = GetPlaybackURL(p);
566 
567  if (file.startsWith("/"))
568  {
569  p->SetPathname(file);
570  p->SetHostname(myHostName);
571  foundFile = true;
572  }
573  }
574 
575  if (!foundFile)
576  {
577  LOG(VB_FILE, LOG_ERR, LOC +
578  QString(" ERROR: Can't find file for %1")
579  .arg(p->toString(ProgramInfo::kRecordingKey)));
580  continue;
581  }
582  }
583 
584  QFileInfo vidFile(p->GetPathname());
585  if (dirList.contains(p->GetHostname() + ':' + vidFile.path()))
586  {
587  fsit->setUsedSpace(fsit->getUsedSpace()
588  - (p->GetFilesize() / 1024));
589  deleteList.push_back(p);
590 
591  LOG(VB_FILE, LOG_INFO,
592  QString(" FOUND file expirable. "
593  "%1 is located at %2 which is on fsID #%3. "
594  "Adding to deleteList. After deleting we "
595  "should have %4 MB free on this filesystem.")
596  .arg(p->toString(ProgramInfo::kRecordingKey))
597  .arg(p->GetPathname()).arg(fsit->getFSysID())
598  .arg(fsit->getFreeSpace() / 1024));
599  }
600  }
601  }
602  }
603 
604  SendDeleteMessages(deleteList);
605 
606  ClearExpireList(deleteList, false);
607  ClearExpireList(expireList);
608 }
609 
614 {
615  QString msg;
616 
617  if (deleteList.empty())
618  {
619  LOG(VB_FILE, LOG_INFO, LOC + "SendDeleteMessages. Nothing to expire.");
620  return;
621  }
622 
623  LOG(VB_FILE, LOG_INFO, LOC +
624  "SendDeleteMessages, cycling through deleteList.");
625  auto it = deleteList.begin();
626  while (it != deleteList.end())
627  {
628  msg = QString("%1Expiring %2 MB for %3 => %4")
629  .arg(VERBOSE_LEVEL_CHECK(VB_FILE, LOG_ANY) ? " " : "")
630  .arg(((*it)->GetFilesize() >> 20))
631  .arg((*it)->toString(ProgramInfo::kRecordingKey))
632  .arg((*it)->toString(ProgramInfo::kTitleSubtitle));
633 
634  LOG(VB_GENERAL, LOG_NOTICE, msg);
635 
636  // send auto expire message to backend's event thread.
637  MythEvent me(QString("AUTO_EXPIRE %1 %2").arg((*it)->GetChanID())
638  .arg((*it)->GetRecordingStartTime(MythDate::ISODate)));
639  gCoreContext->dispatch(me);
640 
641  ++it; // move on to next program
642  }
643 }
644 
651 {
652  QMap<QString, int> maxEpisodes;
653  QMap<QString, int>::Iterator maxIter;
654  QMap<QString, int> episodeParts;
655  QString episodeKey;
656 
657  QString fileprefix = gCoreContext->GetFilePrefix();
658 
659  MSqlQuery query(MSqlQuery::InitCon());
660  query.prepare("SELECT recordid, maxepisodes, title "
661  "FROM record WHERE maxepisodes > 0 "
662  "ORDER BY recordid ASC, maxepisodes DESC");
663 
664  if (query.exec() && query.isActive() && query.size() > 0)
665  {
666  LOG(VB_FILE, LOG_INFO, LOC +
667  QString("Found %1 record profiles using max episode expiration")
668  .arg(query.size()));
669  while (query.next())
670  {
671  LOG(VB_FILE, LOG_INFO, QString(" %1 (%2 for rec id %3)")
672  .arg(query.value(2).toString())
673  .arg(query.value(1).toInt())
674  .arg(query.value(0).toInt()));
675  maxEpisodes[query.value(0).toString()] = query.value(1).toInt();
676  }
677  }
678 
679  LOG(VB_FILE, LOG_INFO, LOC +
680  "Checking episode count for each recording profile using max episodes");
681  for (maxIter = maxEpisodes.begin(); maxIter != maxEpisodes.end(); ++maxIter)
682  {
683  query.prepare("SELECT chanid, starttime, title, progstart, progend, "
684  "duplicate "
685  "FROM recorded "
686  "WHERE recordid = :RECID AND preserve = 0 "
687  "AND recgroup NOT IN ('LiveTV', 'Deleted') "
688  "ORDER BY starttime DESC;");
689  query.bindValue(":RECID", maxIter.key());
690 
691  if (!query.exec() || !query.isActive())
692  {
693  MythDB::DBError("AutoExpire query failed!", query);
694  continue;
695  }
696 
697  LOG(VB_FILE, LOG_INFO, QString(" Recordid %1 has %2 recordings.")
698  .arg(maxIter.key())
699  .arg(query.size()));
700  if (query.size() > 0)
701  {
702  int found = 1;
703  while (query.next())
704  {
705  uint chanid = query.value(0).toUInt();
706  QDateTime startts = MythDate::as_utc(query.value(1).toDateTime());
707  QString title = query.value(2).toString();
708  QDateTime progstart = MythDate::as_utc(query.value(3).toDateTime());
709  QDateTime progend = MythDate::as_utc(query.value(4).toDateTime());
710  int duplicate = query.value(5).toInt();
711 
712  episodeKey = QString("%1_%2_%3")
713  .arg(chanid)
714  .arg(progstart.toString(Qt::ISODate))
715  .arg(progend.toString(Qt::ISODate));
716 
717  if ((!IsInDontExpireSet(chanid, startts)) &&
718  (!episodeParts.contains(episodeKey)) &&
719  (found > *maxIter))
720  {
721  QString msg =
722  QString("%1Deleting %2 at %3 => %4. "
723  "Too many episodes, we only want to keep %5.")
724  .arg(VERBOSE_LEVEL_CHECK(VB_FILE, LOG_ANY) ?
725  " " : "")
726  .arg(chanid).arg(startts.toString(Qt::ISODate))
727  .arg(title).arg(*maxIter);
728 
729  LOG(VB_GENERAL, LOG_NOTICE, msg);
730 
731  // allow re-record if auto expired
732  RecordingInfo recInfo(chanid, startts);
733  if (gCoreContext->GetBoolSetting("RerecordWatched", false) ||
734  !recInfo.IsWatched())
735  {
736  recInfo.ForgetHistory();
737  }
738  msg = QString("DELETE_RECORDING %1 %2")
739  .arg(chanid)
740  .arg(startts.toString(Qt::ISODate));
741 
742  MythEvent me(msg);
743  gCoreContext->dispatch(me);
744  }
745  else
746  {
747  // keep track of shows we haven't expired so we can
748  // make sure we don't expire another part of the same
749  // episode.
750  if (episodeParts.contains(episodeKey))
751  {
752  episodeParts[episodeKey] = episodeParts[episodeKey] + 1;
753  }
754  else
755  {
756  episodeParts[episodeKey] = 1;
757  if( duplicate )
758  found++;
759  }
760  }
761  }
762  }
763  }
764 }
765 
771 {
772  int expMethod = gCoreContext->GetNumSetting("AutoExpireMethod", 1);
773 
774  ClearExpireList(expireList);
775 
777 
778  switch(expMethod)
779  {
780  case emOldestFirst:
783  FillDBOrdered(expireList, expMethod);
784  break;
785  // default falls through so list is empty so no AutoExpire
786  }
787 }
788 
792 void AutoExpire::PrintExpireList(const QString& expHost)
793 {
794  pginfolist_t expireList;
795 
796  FillExpireList(expireList);
797 
798  QString msg = "MythTV AutoExpire List ";
799  if (expHost != "ALL")
800  msg += QString("for '%1' ").arg(expHost);
801  msg += "(programs listed in order of expiration)";
802  cout << msg.toLocal8Bit().constData() << endl;
803 
804  for (auto first : expireList)
805  {
806  if (expHost != "ALL" && first->GetHostname() != expHost)
807  continue;
808 
809  QString title = first->toString(ProgramInfo::kTitleSubtitle);
810  title = title.leftJustified(39, ' ', true);
811 
812  QString outstr = QString("%1 %2 MB %3 [%4]")
813  .arg(title)
814  .arg(QString::number(first->GetFilesize() >> 20)
815  .rightJustified(5, ' ', true))
816  .arg(first->GetRecordingStartTime(MythDate::ISODate)
817  .leftJustified(24, ' ', true))
818  .arg(QString::number(first->GetRecordingPriority())
819  .rightJustified(3, ' ', true));
820  QByteArray out = outstr.toLocal8Bit();
821 
822  cout << out.constData() << endl;
823  }
824 
825  ClearExpireList(expireList);
826 }
827 
831 void AutoExpire::GetAllExpiring(QStringList &strList)
832 {
833  QMutexLocker lockit(&m_instanceLock);
834  pginfolist_t expireList;
835 
837 
841  FillDBOrdered(expireList, gCoreContext->GetNumSetting("AutoExpireMethod",
842  emOldestFirst));
843 
844  strList << QString::number(expireList.size());
845 
846  for (auto & info : expireList)
847  info->ToStringList(strList);
848 
849  ClearExpireList(expireList);
850 }
851 
856 {
857  QMutexLocker lockit(&m_instanceLock);
858  pginfolist_t expireList;
859 
861 
865  FillDBOrdered(expireList, gCoreContext->GetNumSetting("AutoExpireMethod",
866  emOldestFirst));
867 
868  for (auto & info : expireList)
869  list.push_back( new ProgramInfo( *info ));
870 
871  ClearExpireList(expireList);
872 }
873 
877 void AutoExpire::ClearExpireList(pginfolist_t &expireList, bool deleteProg)
878 {
879  ProgramInfo *pginfo = nullptr;
880  while (!expireList.empty())
881  {
882  if (deleteProg)
883  pginfo = expireList.back();
884 
885  expireList.pop_back();
886 
887  if (deleteProg)
888  delete pginfo;
889  }
890 }
891 
896 void AutoExpire::FillDBOrdered(pginfolist_t &expireList, int expMethod)
897 {
898  QString where;
899  QString orderby;
900  QString msg;
901  int maxAge = 0;
902 
903  switch (expMethod)
904  {
905  default:
906  case emOldestFirst:
907  msg = "Adding programs expirable in Oldest First order";
908  where = "autoexpire > 0";
909  if (gCoreContext->GetBoolSetting("AutoExpireWatchedPriority", false))
910  orderby = "recorded.watched DESC, ";
911  orderby += "starttime ASC";
912  break;
914  msg = "Adding programs expirable in Lowest Priority First order";
915  where = "autoexpire > 0";
916  if (gCoreContext->GetBoolSetting("AutoExpireWatchedPriority", false))
917  orderby = "recorded.watched DESC, ";
918  orderby += "recorded.recpriority ASC, starttime ASC";
919  break;
921  msg = "Adding programs expirable in Weighted Time Priority order";
922  where = "autoexpire > 0";
923  if (gCoreContext->GetBoolSetting("AutoExpireWatchedPriority", false))
924  orderby = "recorded.watched DESC, ";
925  orderby += QString("DATE_ADD(starttime, INTERVAL '%1' * "
926  "recorded.recpriority DAY) ASC")
927  .arg(gCoreContext->GetNumSetting("AutoExpireDayPriority", 3));
928  break;
930  msg = "Adding Short LiveTV programs in starttime order";
931  where = "recgroup = 'LiveTV' "
932  "AND endtime < DATE_ADD(starttime, INTERVAL '30' SECOND) "
933  "AND endtime <= DATE_ADD(NOW(), INTERVAL '-5' MINUTE) ";
934  orderby = "starttime ASC";
935  break;
937  msg = "Adding LiveTV programs in starttime order";
938  where = QString("recgroup = 'LiveTV' "
939  "AND endtime <= DATE_ADD(NOW(), INTERVAL '-%1' DAY) ")
940  .arg(gCoreContext->GetNumSetting("AutoExpireLiveTVMaxAge", 1));
941  orderby = "starttime ASC";
942  break;
944  if ((maxAge = gCoreContext->GetNumSetting("DeletedMaxAge", 0)) <= 0)
945  return;
946  msg = QString("Adding programs deleted more than %1 days ago")
947  .arg(maxAge);
948  where = QString("recgroup = 'Deleted' "
949  "AND lastmodified <= DATE_ADD(NOW(), INTERVAL '-%1' DAY) ")
950  .arg(maxAge);
951  orderby = "starttime ASC";
952  break;
954  if (gCoreContext->GetNumSetting("DeletedMaxAge", 0) != 0)
955  return;
956  msg = QString("Adding programs deleted more than 5 minutes ago");
957  where = QString("recgroup = 'Deleted' "
958  "AND lastmodified <= DATE_ADD(NOW(), INTERVAL '-5' MINUTE) ");
959  orderby = "lastmodified ASC";
960  break;
962  msg = "Adding deleted programs in FIFO order";
963  where = "recgroup = 'Deleted'";
964  orderby = "lastmodified ASC";
965  break;
966  }
967 
968  LOG(VB_FILE, LOG_INFO, LOC + "FillDBOrdered: " + msg);
969 
970  MSqlQuery query(MSqlQuery::InitCon());
971  QString querystr = QString(
972  "SELECT recorded.chanid, starttime "
973  "FROM recorded "
974  "LEFT JOIN channel ON recorded.chanid = channel.chanid "
975  "WHERE %1 AND deletepending = 0 "
976  "ORDER BY autoexpire DESC, %2").arg(where).arg(orderby);
977 
978  query.prepare(querystr);
979 
980  if (!query.exec())
981  return;
982 
983  while (query.next())
984  {
985  uint chanid = query.value(0).toUInt();
986  QDateTime recstartts = MythDate::as_utc(query.value(1).toDateTime());
987 
988  if (IsInDontExpireSet(chanid, recstartts))
989  {
990  LOG(VB_FILE, LOG_INFO, LOC +
991  QString(" Skipping %1 at %2 because it is in Don't Expire "
992  "List")
993  .arg(chanid).arg(recstartts.toString(Qt::ISODate)));
994  }
995  else if (IsInExpireList(expireList, chanid, recstartts))
996  {
997  LOG(VB_FILE, LOG_INFO, LOC +
998  QString(" Skipping %1 at %2 because it is already in Expire "
999  "List")
1000  .arg(chanid).arg(recstartts.toString(Qt::ISODate)));
1001  }
1002  else
1003  {
1004  auto *pginfo = new ProgramInfo(chanid, recstartts);
1005  if (pginfo->GetChanID())
1006  {
1007  LOG(VB_FILE, LOG_INFO, LOC + QString(" Adding %1 at %2")
1008  .arg(chanid).arg(recstartts.toString(Qt::ISODate)));
1009  expireList.push_back(pginfo);
1010  }
1011  else
1012  {
1013  LOG(VB_FILE, LOG_INFO, LOC +
1014  QString(" Skipping %1 at %2 "
1015  "because it could not be loaded from the DB")
1016  .arg(chanid).arg(recstartts.toString(Qt::ISODate)));
1017  delete pginfo;
1018  }
1019  }
1020  }
1021 }
1022 
1034 void AutoExpire::Update(int encoder, int fsID, bool immediately)
1035 {
1036  if (!expirer)
1037  return;
1038 
1039  if (encoder > 0)
1040  {
1041  QString msg = QString("Cardid %1: is starting a recording on")
1042  .arg(encoder);
1043  if (fsID == -1)
1044  msg.append(" an unknown fsID soon.");
1045  else
1046  msg.append(QString(" fsID %2 soon.").arg(fsID));
1047  LOG(VB_FILE, LOG_INFO, LOC + msg);
1048  }
1049 
1050  if (immediately)
1051  {
1052  if (encoder > 0)
1053  {
1054  expirer->m_instanceLock.lock();
1055  expirer->m_usedEncoders[encoder] = fsID;
1056  expirer->m_instanceLock.unlock();
1057  }
1058  expirer->CalcParams();
1059  expirer->m_instanceCond.wakeAll();
1060  }
1061  else
1062  {
1063  expirer->m_updateLock.lock();
1064  expirer->m_updateQueue.append(UpdateEntry(encoder, fsID));
1065  expirer->m_updateLock.unlock();
1066  }
1067 }
1068 
1070 {
1071  m_dontExpireSet.clear();
1072 
1073  MSqlQuery query(MSqlQuery::InitCon());
1074  query.prepare(
1075  "SELECT chanid, starttime, lastupdatetime, recusage, hostname "
1076  "FROM inuseprograms");
1077 
1078  if (!query.exec() || !query.next())
1079  return;
1080 
1081  LOG(VB_FILE, LOG_INFO, LOC + "Adding Programs to 'Do Not Expire' List");
1082  QDateTime curTime = MythDate::current();
1083 
1084  do
1085  {
1086  uint chanid = query.value(0).toUInt();
1087  QDateTime recstartts = MythDate::as_utc(query.value(1).toDateTime());
1088  QDateTime lastupdate = MythDate::as_utc(query.value(2).toDateTime());
1089 
1090  if (lastupdate.secsTo(curTime) < 2 * 60 * 60)
1091  {
1092  QString key = QString("%1_%2")
1093  .arg(chanid).arg(recstartts.toString(Qt::ISODate));
1094  m_dontExpireSet.insert(key);
1095  LOG(VB_FILE, LOG_INFO, QString(" %1 at %2 in use by %3 on %4")
1096  .arg(chanid)
1097  .arg(recstartts.toString(Qt::ISODate))
1098  .arg(query.value(3).toString())
1099  .arg(query.value(4).toString()));
1100  }
1101  }
1102  while (query.next());
1103 }
1104 
1106  uint chanid, const QDateTime &recstartts) const
1107 {
1108  QString key = QString("%1_%2")
1109  .arg(chanid).arg(recstartts.toString(Qt::ISODate));
1110 
1111  return (m_dontExpireSet.find(key) != m_dontExpireSet.end());
1112 }
1113 
1115  const pginfolist_t &expireList, uint chanid, const QDateTime &recstartts)
1116 {
1117  for (auto info : expireList)
1118  {
1119  if ((info->GetChanID() == chanid) &&
1120  (info->GetRecordingStartTime() == recstartts))
1121  {
1122  return true;
1123  }
1124  }
1125  return false;
1126 }
1127 
1128 /* vim: set expandtab tabstop=4 shiftwidth=4: */
bool next(void)
Wrap QSqlQuery::next() so we can display the query results.
Definition: mythdbcon.cpp:783
QMutex m_updateLock
Definition: autoexpire.h:126
~AutoExpire() override
AutoExpire destructor stops auto delete thread if it is running.
Definition: autoexpire.cpp:84
void FillDBOrdered(pginfolist_t &expireList, int expMethod)
Creates a list of programs to delete using the database to order list.
Definition: autoexpire.cpp:896
void bindValue(const QString &placeholder, const QVariant &val)
Add a single binding.
Definition: mythdbcon.cpp:864
bool m_expireThreadRun
Definition: autoexpire.h:115
QMutex m_instanceLock
Definition: autoexpire.h:120
MainServer * m_mainServer
Definition: autoexpire.h:123
ExpireThread * m_expireThread
Definition: autoexpire.h:113
VERBOSE_PREAMBLE Most true
Definition: verbosedefs.h:91
QMap< int, int > m_usedEncoders
Definition: autoexpire.h:118
void ExpireLiveTV(int type)
This expires LiveTV programs.
Definition: autoexpire.cpp:360
#define LOC
Definition: autoexpire.cpp:45
void removeListener(QObject *listener)
Remove a listener to the observable.
QMap< int, EncoderLink * > * m_encoderList
Definition: autoexpire.h:89
QSqlQuery wrapper that fetches a DB connection from the connection pool.
Definition: mythdbcon.h:125
QQueue< UpdateEntry > m_updateQueue
Definition: autoexpire.h:127
bool wait(unsigned long time=ULONG_MAX)
Wait for the MThread to exit, with a maximum timeout.
Definition: mthread.cpp:311
void ExpireRecordings(void)
This expires normal recordings.
Definition: autoexpire.cpp:400
void ExpireQuickDeleted(void)
This expires deleted programs within a few minutes.
Definition: autoexpire.cpp:386
int size(void) const
Definition: mythdbcon.h:203
AutoExpire()=default
Holds information on a TV Program one might wish to record.
Definition: recordinginfo.h:34
bool IsInDontExpireSet(uint chanid, const QDateTime &recstartts) const
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
void addListener(QObject *listener)
Add a listener to the observable.
QDateTime as_utc(const QDateTime &old_dt)
Returns copy of QDateTime with TimeSpec set to UTC.
Definition: mythdate.cpp:23
void CalcParams(void)
Calculates how much space needs to be cleared, and how often.
Definition: autoexpire.cpp:122
static void SendDeleteMessages(pginfolist_t &deleteList)
This sends delete message to main event thread.
Definition: autoexpire.cpp:613
QSet< QString > m_dontExpireSet
Definition: autoexpire.h:112
QVariant value(int i) const
Definition: mythdbcon.h:198
Holds information on recordings and videos.
Definition: programinfo.h:67
static QReadWriteLock s_inputsLock
Definition: tv_rec.h:426
This class is used as a container for messages.
Definition: mythevent.h:16
bool IsWatched(void) const
Definition: programinfo.h:475
void GetFilesystemInfos(QList< FileSystemInfo > &fsInfos, bool useCache=true)
void Sleep(int sleepTime)
Sleeps for sleepTime milliseconds; unless the expire thread is told to quit.
Definition: autoexpire.cpp:343
void ForgetHistory(void)
Forget the recording of a program so it will be recorded again.
#define VERBOSE_LEVEL_CHECK(_MASK_, _LEVEL_)
Definition: mythlogging.h:24
int m_encoder
Definition: autoexpire.h:55
#define SPACE_TOO_BIG_KB
If calculated desired space for 10 min freq is > SPACE_TOO_BIG_KB then we use 5 min expire frequency.
Definition: autoexpire.cpp:53
void ExpireOldDeleted(void)
This expires deleted programs older than DeletedMaxAge.
Definition: autoexpire.cpp:373
QDateTime current(bool stripped)
Returns current Date and Time in UTC.
Definition: mythdate.cpp:10
uint64_t GetDesiredSpace(int fsID) const
Used by the scheduler to select the next recording dir.
Definition: autoexpire.cpp:111
bool isActive(void) const
Definition: mythdbcon.h:204
unsigned int uint
Definition: compat.h:140
static MSqlQueryInfo InitCon(ConnectionReuse _reuse=kNormalConnection)
Only use this in combination with MSqlQuery constructor.
Definition: mythdbcon.cpp:535
void GetAllExpiring(QStringList &strList)
Gets the full list of programs that can expire in expiration order.
Definition: autoexpire.cpp:831
QMap< int, int64_t > m_desiredSpace
Definition: autoexpire.h:117
void dispatch(const MythEvent &event)
uint m_desiredFreq
Definition: autoexpire.h:114
QWaitCondition m_instanceCond
Definition: autoexpire.h:121
int GetNumSetting(const QString &key, int defaultval=0)
void UpdateDontExpireSet(void)
bool prepare(const QString &query)
QSqlQuery::prepare() is not thread safe in Qt <= 3.3.2.
Definition: mythdbcon.cpp:808
#define LOG(_MASK_, _LEVEL_, _STRING_)
Definition: mythlogging.h:41
QString GetFilePrefix(void)
bool GetBoolSetting(const QString &key, bool defaultval=false)
vector< ProgramInfo * > pginfolist_t
Definition: autoexpire.h:25
Used to expire recordings to make space for new recordings.
Definition: autoexpire.h:61
static bool IsInExpireList(const pginfolist_t &expireList, uint chanid, const QDateTime &recstartts)
AutoExpire * expirer
QString GetPlaybackURL(ProgramInfo *pginfo, bool storePath)
static void Update(int encoder, int fsID, bool immediately)
This is used to update the global AutoExpire instance "expirer".
void run(void) override
This calls AutoExpire::RunExpirer() from within a new thread.
Definition: autoexpire.cpp:56
void start(QThread::Priority p=QThread::InheritPriority)
Tell MThread to start running the thread in the near future.
Definition: mthread.cpp:294
void PrintExpireList(const QString &expHost="ALL")
Prints a summary of the files that can be deleted.
Definition: autoexpire.cpp:792
static void ClearExpireList(pginfolist_t &expireList, bool deleteProg=true)
Clears expireList, freeing any ProgramInfo's if necessary.
Definition: autoexpire.cpp:877
void FillExpireList(pginfolist_t &expireList)
Uses the "AutoExpireMethod" setting in the database to fill the list of files that are deletable.
Definition: autoexpire.cpp:770
Default UTC.
Definition: mythdate.h:14
bool exec(void)
Wrap QSqlQuery::exec() so we can display SQL.
Definition: mythdbcon.cpp:603
static void DBError(const QString &where, const MSqlQuery &query)
Definition: mythdb.cpp:179
void ExpireEpisodesOverMax(void)
This deletes programs exceeding the maximum number of episodes of that program desired.
Definition: autoexpire.cpp:650
void RunExpirer(void)
This contains the main loop for the auto expire process.
Definition: autoexpire.cpp:267
QString GetHostName(void)
QMap< int, EncoderLink * > tvList