/
autoexpire.cpp
1136 lines (970 loc) · 37 KB
/
autoexpire.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// System headers
#include <sys/stat.h>
#ifdef __linux__
# include <sys/vfs.h>
#else // if !__linux__
# include <sys/param.h>
# ifndef USING_MINGW
# include <sys/mount.h>
# endif // USING_MINGW
#endif // !__linux__
// POSIX headers
#include <unistd.h>
#include <signal.h>
// C headers
#include <cstdlib>
// C++ headers
#include <iostream>
#include <algorithm>
using namespace std;
// Qt headers
#include <QDateTime>
#include <QFileInfo>
// MythTV headers
#include "autoexpire.h"
#include "programinfo.h"
#include "mythcorecontext.h"
#include "mythdb.h"
#include "util.h"
#include "storagegroup.h"
#include "remoteutil.h"
#include "remoteencoder.h"
#include "encoderlink.h"
#include "backendutil.h"
#include "mainserver.h"
#include "compat.h"
#define LOC QString("AutoExpire: ")
#define LOC_ERR QString("AutoExpire Error: ")
extern AutoExpire *expirer;
/** If calculated desired space for 10 min freq is > SPACE_TOO_BIG_KB
* then we use 5 min expire frequency.
*/
#define SPACE_TOO_BIG_KB 3*1024*1024
/** \class AutoExpire
* \brief Used to expire recordings to make space for new recordings.
*/
/** \fn AutoExpire::AutoExpire(QMap<int, EncoderLink *> *tvList)
* \brief Creates AutoExpire class, starting the thread.
*
* \param tvList EncoderLink list of all recorders
*/
AutoExpire::AutoExpire(QMap<int, EncoderLink *> *tvList)
{
encoderList = tvList;
expire_thread_running = true;
Init();
pthread_create(&expire_thread, NULL, ExpirerThread, this);
gCoreContext->addListener(this);
}
/** \fn AutoExpire::AutoExpire()
* \brief Creates AutoExpire class
*/
AutoExpire::AutoExpire(void)
{
encoderList = NULL;
expire_thread_running = false;
Init();
}
/** \fn AutoExpire::Init()
* \brief Inits member vars
*/
void AutoExpire::Init(void)
{
mainServer = NULL;
desired_freq = 15;
update_pending = false;
}
/** \fn AutoExpire::~AutoExpire()
* \brief AutoExpire destructor stops auto delete thread if it is running.
*/
AutoExpire::~AutoExpire()
{
instance_lock.lock();
while (update_pending)
instance_cond.wait(&instance_lock);
instance_lock.unlock();
if (expire_thread_running)
{
gCoreContext->removeListener(this);
expire_thread_running = false;
pthread_kill(expire_thread, SIGALRM); // try to speed up join..
VERBOSE(VB_IMPORTANT, LOC + "Warning: Stopping auto expire thread "
"can take several seconds. Please be patient.");
pthread_join(expire_thread, NULL);
}
}
/**
* \brief Used by the scheduler to select the next recording dir
* \return the desired free space for each file system
*/
size_t AutoExpire::GetDesiredSpace(int fsID) const
{
if (desired_space.contains(fsID))
return desired_space[fsID];
return 0;
}
/** \fn AutoExpire::CalcParams()
* Calculates how much space needs to be cleared, and how often.
*/
void AutoExpire::CalcParams()
{
VERBOSE(VB_FILE, LOC + "CalcParams()");
vector<FileSystemInfo> fsInfos;
if (mainServer)
mainServer->GetFilesystemInfos(fsInfos);
if (fsInfos.empty())
{
QString msg = "ERROR: Filesystem Info cache is empty, unable to "
"calculate necessary parameters.";
VERBOSE(VB_IMPORTANT, LOC + msg);
gCoreContext->LogEntry("mythbackend", LP_WARNING,
"Autoexpire CalcParams", msg);
return;
}
size_t maxKBperMin = 0;
size_t extraKB = gCoreContext->GetNumSetting("AutoExpireExtraSpace", 0) << 20;
QMap<int, uint64_t> fsMap;
QMap<int, vector<int> > fsEncoderMap;
// we use this copying on purpose. The used_encoders map ensures
// that every encoder writes only to one fs.
// Copying the data minimizes the time the lock is held
instance_lock.lock();
QMap<int, int>::const_iterator ueit = used_encoders.begin();
while (ueit != used_encoders.end())
{
fsEncoderMap[*ueit].push_back(ueit.key());
++ueit;
}
instance_lock.unlock();
vector<FileSystemInfo>::iterator fsit;
for (fsit = fsInfos.begin(); fsit != fsInfos.end(); ++fsit)
{
if (fsMap.contains(fsit->fsID))
continue;
fsMap[fsit->fsID] = 0;
size_t thisKBperMin = 0;
// append unknown recordings to all fsIDs
vector<int>::iterator unknownfs_it = fsEncoderMap[-1].begin();
for (; unknownfs_it != fsEncoderMap[-1].end(); ++unknownfs_it)
fsEncoderMap[fsit->fsID].push_back(*unknownfs_it);
if (fsEncoderMap.contains(fsit->fsID))
{
VERBOSE(VB_FILE, QString(
"fsID #%1: Total: %2 GB Used: %3 GB Free: %4 GB")
.arg(fsit->fsID)
.arg(fsit->totalSpaceKB / 1024.0 / 1024.0, 7, 'f', 1)
.arg(fsit->usedSpaceKB / 1024.0 / 1024.0, 7, 'f', 1)
.arg(fsit->freeSpaceKB / 1024.0 / 1024.0, 7, 'f', 1));
vector<int>::iterator encit = fsEncoderMap[fsit->fsID].begin();
for (; encit != fsEncoderMap[fsit->fsID].end(); ++encit)
{
EncoderLink *enc = *(encoderList->find(*encit));
if (!enc->IsConnected() || !enc->IsBusy())
{
// remove the encoder since it can't write to any file system
VERBOSE(VB_FILE, LOC
+ QString("Cardid %1: is not recoding, removing it "
"from used list.").arg(*encit));
instance_lock.lock();
used_encoders.remove(*encit);
instance_lock.unlock();
continue;
}
long long maxBitrate = enc->GetMaxBitrate();
if (maxBitrate<=0)
maxBitrate = 19500000LL;
thisKBperMin += (((size_t)maxBitrate)*((size_t)15))>>11;
VERBOSE(VB_FILE, QString(" Cardid %1: max bitrate "
"%2 Kb/sec, fsID %3 max is now %4 KB/min")
.arg(enc->GetCardID())
.arg(enc->GetMaxBitrate() >> 10)
.arg(fsit->fsID)
.arg(thisKBperMin));
}
}
fsMap[fsit->fsID] = thisKBperMin;
if (thisKBperMin > maxKBperMin)
{
VERBOSE(VB_FILE,
QString(" Max of %1 KB/min for fsID %2 is higher "
"than the existing Max of %3 so we'll use this Max instead")
.arg(thisKBperMin).arg(fsit->fsID).arg(maxKBperMin));
maxKBperMin = thisKBperMin;
}
}
// Determine frequency to run autoexpire so it doesn't have to free
// too much space
uint expireFreq = 15;
if (maxKBperMin > 0)
{
expireFreq = SPACE_TOO_BIG_KB / (maxKBperMin + maxKBperMin/3);
expireFreq = max(3U, min(expireFreq, 15U));
}
double expireMinGB = ((maxKBperMin + maxKBperMin/3)
* expireFreq + extraKB) >> 20;
VERBOSE(VB_IMPORTANT, LOC +
QString("CalcParams(): Max required Free Space: %1 GB w/freq: "
"%2 min").arg(expireMinGB, 0, 'f', 1).arg(expireFreq));
// lock class and save these parameters.
instance_lock.lock();
desired_freq = expireFreq;
// write per file system needed space back, use safety of 33%
QMap<int, uint64_t>::iterator it = fsMap.begin();
while (it != fsMap.end())
{
desired_space[it.key()] = (*it + *it/3) * expireFreq + extraKB;
++it;
}
instance_lock.unlock();
}
/** \fn AutoExpire::RunExpirer()
* \brief This contains the main loop for the auto expire process.
*
* Responsible for cleanup of old LiveTV programs as well as deleting as
* many recordings that are expirable as necessary to
* maintain enough free space on all directories in MythTV Storage Groups.
* The thread deletes short LiveTV programs every 2 minutes and long
* LiveTV and regular programs as needed every "desired_freq" minutes.
*/
void AutoExpire::RunExpirer(void)
{
QTime timer;
QDateTime curTime;
QDateTime next_expire = QDateTime::currentDateTime().addSecs(60);
// wait a little for main server to come up and things to settle down
sleep(20);
timer.start();
while (expire_thread_running)
{
curTime = QDateTime::currentDateTime();
// recalculate auto expire parameters
if (curTime >= next_expire)
CalcParams();
timer.restart();
instance_lock.lock();
UpdateDontExpireSet();
// Expire Short LiveTV files for this backend every 2 minutes
if ((curTime.time().minute() % 2) == 0)
ExpireLiveTV(emShortLiveTVPrograms);
// Expire normal recordings depending on frequency calculated
if (curTime >= next_expire)
{
VERBOSE(VB_FILE, LOC + "Running now!");
next_expire =
QDateTime::currentDateTime().addSecs(desired_freq * 60);
ExpireLiveTV(emNormalLiveTVPrograms);
if (gCoreContext->GetNumSetting("DeletedMaxAge", 0))
ExpireOldDeleted();
ExpireEpisodesOverMax();
ExpireRecordings();
}
instance_lock.unlock();
Sleep(60 - (timer.elapsed() / 1000));
}
}
/** \fn AutoExpire::Sleep(int sleepTime)
* \brief Sleeps for sleepTime minutes; unless the expire thread
* is told to quit, then stops sleeping within 5 seconds.
*/
void AutoExpire::Sleep(int sleepTime)
{
int minSleep = 5, timeExpended = 0;
while (expire_thread_running && timeExpended < sleepTime)
{
if (timeExpended > (sleepTime - minSleep))
minSleep = sleepTime - timeExpended;
timeExpended += minSleep - (int)sleep(minSleep);
}
}
/** \fn AutoExpire::ExpireLiveTV(int type)
* \brief This expires LiveTV programs.
*/
void AutoExpire::ExpireLiveTV(int type)
{
pginfolist_t expireList;
VERBOSE(VB_FILE, LOC + QString("ExpireLiveTV(%1)").arg(type));
FillDBOrdered(expireList, type);
SendDeleteMessages(expireList);
ClearExpireList(expireList);
}
/** \fn AutoExpire::ExpireOldDeleted(void)
* \brief This expires deleted programs older than DeletedMaxAge.
*/
void AutoExpire::ExpireOldDeleted(void)
{
pginfolist_t expireList;
VERBOSE(VB_FILE, LOC + QString("ExpireOldDeleted()"));
FillDBOrdered(expireList, emOldDeletedPrograms);
SendDeleteMessages(expireList);
ClearExpireList(expireList);
}
/** \fn AutoExpire::ExpireRecordings()
* \brief This expires normal recordings.
*
*/
void AutoExpire::ExpireRecordings(void)
{
pginfolist_t expireList;
pginfolist_t deleteList;
vector<FileSystemInfo> fsInfos;
vector<FileSystemInfo>::iterator fsit;
VERBOSE(VB_FILE, LOC + "ExpireRecordings()");
if (mainServer)
mainServer->GetFilesystemInfos(fsInfos);
if (fsInfos.empty())
{
QString msg = "ERROR: Filesystem Info cache is empty, unable to "
"determine what Recordings to expire";
VERBOSE(VB_IMPORTANT, LOC + msg);
gCoreContext->LogEntry("mythbackend", LP_WARNING,
"Autoexpire Recording", msg);
return;
}
FillExpireList(expireList);
QMap <int, bool> truncateMap;
MSqlQuery query(MSqlQuery::InitCon());
query.prepare("SELECT DISTINCT rechost, recdir "
"FROM inuseprograms "
"WHERE recusage = 'truncatingdelete' "
"AND lastupdatetime > DATE_ADD(NOW(), INTERVAL -2 MINUTE);");
if (!query.exec())
{
MythDB::DBError(LOC + "ExpireRecordings", query);
}
else
{
while (query.next())
{
QString rechost = query.value(0).toString();
QString recdir = query.value(1).toString();
VERBOSE(VB_FILE, LOC + QString(
"%1:%2 has an in-progress truncating delete.")
.arg(rechost).arg(recdir));
for (fsit = fsInfos.begin(); fsit != fsInfos.end(); ++fsit)
{
if ((fsit->hostname == rechost) &&
(fsit->directory == recdir))
{
truncateMap[fsit->fsID] = true;
break;
}
}
}
}
QMap <int, bool> fsMap;
for (fsit = fsInfos.begin(); fsit != fsInfos.end(); ++fsit)
{
if (fsMap.contains(fsit->fsID))
continue;
fsMap[fsit->fsID] = true;
VERBOSE(VB_FILE, QString(
"fsID #%1: Total: %2 GB Used: %3 GB Free: %4 GB")
.arg(fsit->fsID)
.arg(fsit->totalSpaceKB / 1024.0 / 1024.0, 7, 'f', 1)
.arg(fsit->usedSpaceKB / 1024.0 / 1024.0, 7, 'f', 1)
.arg(fsit->freeSpaceKB / 1024.0 / 1024.0, 7, 'f', 1));
if ((fsit->totalSpaceKB == -1) || (fsit->usedSpaceKB == -1))
{
VERBOSE(VB_FILE, LOC_ERR + QString("fsID #%1 has invalid info, "
"AutoExpire cannot run for this filesystem. "
"Continuing on to next...").arg(fsit->fsID));
VERBOSE(VB_FILE, QString("Directories on filesystem ID %1:")
.arg(fsit->fsID));
vector<FileSystemInfo>::iterator fsit2;
for (fsit2 = fsInfos.begin(); fsit2 != fsInfos.end(); ++fsit2)
{
if (fsit2->fsID == fsit->fsID)
{
VERBOSE(VB_FILE, QString(" %1:%2")
.arg(fsit2->hostname).arg(fsit2->directory));
}
}
continue;
}
if (truncateMap.contains(fsit->fsID))
{
VERBOSE(VB_FILE, QString(
" fsid %1 has a truncating delete in progress, AutoExpire "
"cannot run for this filesystem until the delete has "
"finished. Continuing on to next...").arg(fsit->fsID));
continue;
}
if ((int64_t)max(0LL, fsit->freeSpaceKB) < desired_space[fsit->fsID])
{
VERBOSE(VB_FILE,
QString(" Not Enough Free Space! We want %1 MB")
.arg(desired_space[fsit->fsID] / 1024));
QMap<QString, int> dirList;
vector<FileSystemInfo>::iterator fsit2;
VERBOSE(VB_FILE, QString(" Directories on filesystem ID %1:")
.arg(fsit->fsID));
for (fsit2 = fsInfos.begin(); fsit2 != fsInfos.end(); ++fsit2)
{
if (fsit2->fsID == fsit->fsID)
{
VERBOSE(VB_FILE, QString(" %1:%2")
.arg(fsit2->hostname).arg(fsit2->directory));
dirList[fsit2->hostname + ":" + fsit2->directory] = 1;
}
}
VERBOSE(VB_FILE,
" Searching for files expirable in these directories");
QString myHostName = gCoreContext->GetHostName();
pginfolist_t::iterator it = expireList.begin();
while ((it != expireList.end()) &&
((int64_t)max(0LL, fsit->freeSpaceKB) < desired_space[fsit->fsID]))
{
ProgramInfo *p = *it;
it++;
VERBOSE(VB_FILE, QString(" Checking %1 => %2")
.arg(p->toString(ProgramInfo::kRecordingKey))
.arg(p->GetTitle()));
if (!p->IsLocal())
{
bool foundFile = false;
QMap<int, EncoderLink *>::Iterator eit =
encoderList->begin();
while (eit != encoderList->end())
{
EncoderLink *el = *eit;
eit++;
if ((p->GetHostname() == el->GetHostName()) ||
((p->GetHostname() == myHostName) &&
(el->IsLocal())))
{
if (el->IsConnected())
foundFile = el->CheckFile(p);
eit = encoderList->end();
}
}
if (!foundFile && (p->GetHostname() != myHostName))
{
// Wasn't found so check locally
QString file = GetPlaybackURL(p);
if (file.left(1) == "/")
{
p->SetPathname(file);
p->SetHostname(myHostName);
foundFile = true;
}
}
if (!foundFile)
{
VERBOSE(VB_FILE, LOC_ERR + QString(
" ERROR: Can't find file for %1")
.arg(p->toString(ProgramInfo::kRecordingKey)));
continue;
}
}
QFileInfo vidFile(p->GetPathname());
if (dirList.contains(p->GetHostname() + ':' + vidFile.path()))
{
fsit->freeSpaceKB += (p->GetFilesize() / 1024);
deleteList.push_back(p);
VERBOSE(VB_FILE, QString(" FOUND file expirable. "
"%1 is located at %2 which is on fsID #%3. "
"Adding to deleteList. After deleting we should "
"have %4 MB free on this filesystem.")
.arg(p->toString(ProgramInfo::kRecordingKey))
.arg(p->GetPathname()).arg(fsit->fsID)
.arg(fsit->freeSpaceKB / 1024));
}
}
}
}
SendDeleteMessages(deleteList);
ClearExpireList(deleteList, false);
ClearExpireList(expireList);
}
/**
* \brief This sends delete message to main event thread.
*/
void AutoExpire::SendDeleteMessages(pginfolist_t &deleteList)
{
QString msg;
if (deleteList.empty())
{
VERBOSE(VB_FILE, LOC + "SendDeleteMessages. Nothing to expire.");
return;
}
VERBOSE(VB_FILE, LOC + "SendDeleteMessages, cycling through deleteList.");
pginfolist_t::iterator it = deleteList.begin();
while (it != deleteList.end())
{
msg = QString("Expiring %1 MB for %2 => %3")
.arg(((*it)->GetFilesize() >> 20))
.arg((*it)->toString(ProgramInfo::kRecordingKey))
.arg((*it)->toString(ProgramInfo::kTitleSubtitle));
if (VERBOSE_LEVEL_CHECK(VB_IMPORTANT))
VERBOSE(VB_IMPORTANT, msg);
else
VERBOSE(VB_FILE, QString(" ") + msg);
gCoreContext->LogEntry("autoexpire", LP_NOTICE,
"Expiring Program", msg);
// send auto expire message to backend's event thread.
MythEvent me(QString("AUTO_EXPIRE %1 %2").arg((*it)->GetChanID())
.arg((*it)->GetRecordingStartTime(ISODate)));
gCoreContext->dispatch(me);
deleted_set.insert((*it)->MakeUniqueKey());
++it; // move on to next program
}
}
/** \fn AutoExpire::ExpirerThread(void *)
* \brief This calls RunExpirer() from within a new pthread.
*/
void *AutoExpire::ExpirerThread(void *param)
{
AutoExpire *expirer = static_cast<AutoExpire *>(param);
expirer->RunExpirer();
return NULL;
}
/** \fn AutoExpire::ExpireEpisodesOverMax()
* \brief This deletes programs exceeding the maximum
* number of episodes of that program desired.
* Excludes recordings in the LiveTV Recording Group.
*/
void AutoExpire::ExpireEpisodesOverMax(void)
{
QMap<QString, int> maxEpisodes;
QMap<QString, int>::Iterator maxIter;
QMap<QString, int> episodeParts;
QString episodeKey;
QString fileprefix = gCoreContext->GetFilePrefix();
MSqlQuery query(MSqlQuery::InitCon());
query.prepare("SELECT recordid, maxepisodes, title "
"FROM record WHERE maxepisodes > 0 "
"ORDER BY recordid ASC, maxepisodes DESC");
if (query.exec() && query.isActive() && query.size() > 0)
{
VERBOSE(VB_FILE, LOC + QString("Found %1 record profiles using max "
"episode expiration")
.arg(query.size()));
while (query.next())
{
VERBOSE(VB_FILE, QString(" %1 (%2 for rec id %3)")
.arg(query.value(2).toString())
.arg(query.value(1).toInt())
.arg(query.value(0).toInt()));
maxEpisodes[query.value(0).toString()] = query.value(1).toInt();
}
}
VERBOSE(VB_FILE, LOC + "Checking episode count for each recording "
"profile using max episodes");
for (maxIter = maxEpisodes.begin(); maxIter != maxEpisodes.end(); ++maxIter)
{
query.prepare("SELECT chanid, starttime, title, progstart, progend, "
"filesize, duplicate "
"FROM recorded "
"WHERE recordid = :RECID AND preserve = 0 "
"AND recgroup NOT IN ('LiveTV', 'Deleted') "
"ORDER BY starttime DESC;");
query.bindValue(":RECID", maxIter.key());
if (!query.exec() || !query.isActive())
{
MythDB::DBError("AutoExpire query failed!", query);
continue;
}
VERBOSE(VB_FILE, QString(" Recordid %1 has %2 recordings.")
.arg(maxIter.key())
.arg(query.size()));
if (query.size() > 0)
{
int found = 1;
while (query.next())
{
uint chanid = query.value(0).toUInt();
QDateTime startts = query.value(1).toDateTime();
QString title = query.value(2).toString();
QDateTime progstart = query.value(3).toDateTime();
QDateTime progend = query.value(4).toDateTime();
int duplicate = query.value(6).toInt();
episodeKey = QString("%1_%2_%3")
.arg(chanid)
.arg(progstart.toString(Qt::ISODate))
.arg(progend.toString(Qt::ISODate));
if ((!IsInDontExpireSet(chanid, startts)) &&
(!episodeParts.contains(episodeKey)) &&
(found > *maxIter))
{
long long spaceFreed =
query.value(5).toLongLong() >> 20;
QString msg =
QString("Expiring %1 MBytes for %2 at %3 => %4. Too "
"many episodes, we only want to keep %5.")
.arg(spaceFreed)
.arg(chanid).arg(startts.toString())
.arg(title).arg(*maxIter);
if (VERBOSE_LEVEL_CHECK(VB_IMPORTANT))
VERBOSE(VB_IMPORTANT, msg);
else
VERBOSE(VB_FILE, QString(" ") + msg);
gCoreContext->LogEntry("autoexpire", LP_NOTICE,
"Expired program", msg);
msg = QString("AUTO_EXPIRE %1 %2")
.arg(chanid)
.arg(startts.toString(Qt::ISODate));
MythEvent me(msg);
gCoreContext->dispatch(me);
}
else
{
// keep track of shows we haven't expired so we can
// make sure we don't expire another part of the same
// episode.
if (episodeParts.contains(episodeKey))
{
episodeParts[episodeKey] = episodeParts[episodeKey] + 1;
}
else
{
episodeParts[episodeKey] = 1;
if( duplicate )
found++;
}
}
}
}
}
}
/** \fn AutoExpire::FillExpireList(pginfolist_t&)
* \brief Uses the "AutoExpireMethod" setting in the database to
* fill the list of files that are deletable.
*/
void AutoExpire::FillExpireList(pginfolist_t &expireList)
{
int expMethod = gCoreContext->GetNumSetting("AutoExpireMethod", 1);
ClearExpireList(expireList);
FillDBOrdered(expireList, emNormalDeletedPrograms);
switch(expMethod)
{
case emOldestFirst:
case emLowestPriorityFirst:
case emWeightedTimePriority:
FillDBOrdered(expireList, expMethod);
break;
// default falls through so list is empty so no AutoExpire
}
}
/** \fn AutoExpire::PrintExpireList(QString)
* \brief Prints a summary of the files that can be deleted.
*/
void AutoExpire::PrintExpireList(QString expHost)
{
pginfolist_t expireList;
FillExpireList(expireList);
QString msg = "MythTV AutoExpire List ";
if (expHost != "ALL")
msg += QString("for '%1' ").arg(expHost);
msg += "(programs listed in order of expiration)";
cout << msg.toLocal8Bit().constData() << endl;
pginfolist_t::iterator i = expireList.begin();
for (; i != expireList.end(); ++i)
{
ProgramInfo *first = (*i);
if (expHost != "ALL" && first->GetHostname() != expHost)
continue;
QString title = first->toString(ProgramInfo::kTitleSubtitle);
title = title.leftJustified(39, ' ', true);
QString outstr = QString("%1 %2 MB %3 [%4]")
.arg(title)
.arg(QString::number(first->GetFilesize() >> 20)
.rightJustified(5, ' ', true))
.arg(first->GetRecordingStartTime(ISODate)
.leftJustified(24, ' ', true))
.arg(QString::number(first->GetRecordingPriority())
.rightJustified(3, ' ', true));
QByteArray out = outstr.toLocal8Bit();
cout << out.constData() << endl;
}
ClearExpireList(expireList);
}
/** \fn AutoExpire::GetAllExpiring(QStringList&)
* \brief Gets the full list of programs that can expire in expiration order
*/
void AutoExpire::GetAllExpiring(QStringList &strList)
{
QMutexLocker lockit(&instance_lock);
pginfolist_t expireList;
UpdateDontExpireSet();
FillDBOrdered(expireList, emShortLiveTVPrograms);
FillDBOrdered(expireList, emNormalLiveTVPrograms);
FillDBOrdered(expireList, emNormalDeletedPrograms);
FillDBOrdered(expireList, gCoreContext->GetNumSetting("AutoExpireMethod",
emOldestFirst));
strList << QString::number(expireList.size());
pginfolist_t::iterator it = expireList.begin();
for (; it != expireList.end(); ++it)
(*it)->ToStringList(strList);
ClearExpireList(expireList);
}
/** \fn AutoExpire::GetAllExpiring(pginfolist_t&)
* \brief Gets the full list of programs that can expire in expiration order
*/
void AutoExpire::GetAllExpiring(pginfolist_t &list)
{
QMutexLocker lockit(&instance_lock);
pginfolist_t expireList;
UpdateDontExpireSet();
FillDBOrdered(expireList, emShortLiveTVPrograms);
FillDBOrdered(expireList, emNormalLiveTVPrograms);
FillDBOrdered(expireList, emNormalDeletedPrograms);
FillDBOrdered(expireList, gCoreContext->GetNumSetting("AutoExpireMethod",
emOldestFirst));
pginfolist_t::iterator it = expireList.begin();
for (; it != expireList.end(); ++it)
list.push_back( new ProgramInfo( *(*it) ));
ClearExpireList(expireList);
}
/** \fn AutoExpire::ClearExpireList(pginfolist_t&, bool)
* \brief Clears expireList, freeing any ProgramInfo's if necessary.
*/
void AutoExpire::ClearExpireList(pginfolist_t &expireList, bool deleteProg)
{
ProgramInfo *pginfo = NULL;
while (!expireList.empty())
{
if (deleteProg)
pginfo = expireList.back();
expireList.pop_back();
if (deleteProg)
delete pginfo;
}
}
/** \fn AutoExpire::FillDBOrdered(pginfolist_t&, int)
* \brief Creates a list of programs to delete using the database to
* order list.
*/
void AutoExpire::FillDBOrdered(pginfolist_t &expireList, int expMethod)
{
QString where;
QString orderby;
QString msg;
int maxAge;
switch (expMethod)
{
default:
case emOldestFirst:
msg = "Adding programs expirable in Oldest First order";
where = "autoexpire > 0";
if (gCoreContext->GetNumSetting("AutoExpireWatchedPriority", 0))
orderby = "recorded.watched DESC, ";
orderby += "starttime ASC";
break;
case emLowestPriorityFirst:
msg = "Adding programs expirable in Lowest Priority First order";
where = "autoexpire > 0";
if (gCoreContext->GetNumSetting("AutoExpireWatchedPriority", 0))
orderby = "recorded.watched DESC, ";
orderby += "recorded.recpriority ASC, starttime ASC";
break;
case emWeightedTimePriority:
msg = "Adding programs expirable in Weighted Time Priority order";
where = "autoexpire > 0";
if (gCoreContext->GetNumSetting("AutoExpireWatchedPriority", 0))
orderby = "recorded.watched DESC, ";
orderby += QString("DATE_ADD(starttime, INTERVAL '%1' * "
"recorded.recpriority DAY) ASC")
.arg(gCoreContext->GetNumSetting("AutoExpireDayPriority", 3));
break;
case emShortLiveTVPrograms:
msg = "Adding Short LiveTV programs in starttime order";
where = "recgroup = 'LiveTV' "
"AND endtime < DATE_ADD(starttime, INTERVAL '2' MINUTE) "
"AND endtime <= DATE_ADD(NOW(), INTERVAL '-1' MINUTE) ";
orderby = "starttime ASC";
break;
case emNormalLiveTVPrograms:
msg = "Adding LiveTV programs in starttime order";
where = QString("recgroup = 'LiveTV' "
"AND endtime <= DATE_ADD(NOW(), INTERVAL '-%1' DAY) ")
.arg(gCoreContext->GetNumSetting("AutoExpireLiveTVMaxAge", 1));
orderby = "starttime ASC";
break;
case emOldDeletedPrograms:
if ((maxAge = gCoreContext->GetNumSetting("DeletedMaxAge", 0)) == 0)
return;
msg = QString("Adding programs deleted more than %1 days ago")
.arg(maxAge);
where = QString("recgroup = 'Deleted' "
"AND lastmodified <= DATE_ADD(NOW(), INTERVAL '-%1' DAY) ")
.arg(maxAge);
orderby = "starttime ASC";
break;
case emNormalDeletedPrograms:
if (gCoreContext->GetNumSetting("DeletedFifoOrder", 0) == 0)
return;
msg = "Adding deleted programs in FIFO order";
where = "recgroup = 'Deleted'";
orderby = "lastmodified ASC";
break;
}
VERBOSE(VB_FILE, LOC + "FillDBOrdered: " + msg);
MSqlQuery query(MSqlQuery::InitCon());
QString querystr = QString(
"SELECT recorded.chanid, starttime "
"FROM recorded "
"LEFT JOIN channel ON recorded.chanid = channel.chanid "
"WHERE %1 AND deletepending = 0 "
"ORDER BY autoexpire DESC, %2").arg(where).arg(orderby);
query.prepare(querystr);
if (!query.exec())
return;
while (query.next())
{
uint chanid = query.value(0).toUInt();
QDateTime recstartts = query.value(1).toDateTime();
if (IsInDontExpireSet(chanid, recstartts))
{
VERBOSE(VB_FILE, LOC + QString(
" Skipping %1 at %2 "
"because it is in Don't Expire List")
.arg(chanid).arg(recstartts.toString(Qt::ISODate)));
}
else if (IsInExpireList(expireList, chanid, recstartts))
{
VERBOSE(VB_FILE, LOC + QString(
" Skipping %1 at %2 "
"because it is already in Expire List")
.arg(chanid).arg(recstartts.toString(Qt::ISODate)));
}
else
{
ProgramInfo *pginfo = new ProgramInfo(chanid, recstartts);
if (pginfo->GetChanID())
{
VERBOSE(VB_FILE, LOC +
QString(" Adding %1 at %2")
.arg(chanid).arg(recstartts.toString(Qt::ISODate)));
expireList.push_back(pginfo);
}
else
{
VERBOSE(VB_FILE, LOC + QString(
" Skipping %1 at %2 "
"because it could not be loaded from the DB")
.arg(chanid).arg(recstartts.toString(Qt::ISODate)));
delete pginfo;
}
}
}
}
/** \fn SpawnUpdateThread(void*)