summaryrefslogtreecommitdiff
path: root/raphodo/interprocess.py
blob: 76d9aa486cd86f36d90b564a728a73f332ee50cc (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
# Copyright (C) 2015-2018 Damon Lynch <damonlynch@gmail.com>

# This file is part of Rapid Photo Downloader.
#
# Rapid Photo Downloader is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Rapid Photo Downloader is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Rapid Photo Downloader.  If not,
# see <http://www.gnu.org/licenses/>.

__author__ = 'Damon Lynch'
__copyright__ = "Copyright 2015-2018, Damon Lynch"

import argparse
import sys
import logging
import pickle
import os
import shlex
import time
from collections import deque, namedtuple
from typing import Optional, Set, List, Dict, Sequence, Any, Tuple


import psutil

from PyQt5.QtCore import (pyqtSignal, QObject, pyqtSlot)
from PyQt5.QtGui import (QPixmap, QImage)

import zmq
import zmq.log.handlers
if zmq.pyzmq_version_info()[0] < 17:
    from zmq.eventloop import ioloop
else:
    try:
        from tornado import ioloop
    except ImportError:
        from zmq.eventloop import ioloop  # note: deprecated in pyzmq 17.0.0

from zmq.eventloop.zmqstream import ZMQStream

from raphodo.rpdfile import (RPDFile, FileTypeCounter, FileSizeSum, Photo, Video)
from raphodo.devices import Device
from raphodo.utilities import CacheDirs, set_pdeathsig
from raphodo.constants import (
    RenameAndMoveStatus, ExtractionTask, ExtractionProcessing, CameraErrorCode, FileType,
    FileExtension, BackupStatus
)
from raphodo.proximity import TemporalProximityGroups
from raphodo.storage import StorageSpace
from raphodo.iplogging import ZeroMQSocketHandler
from raphodo.viewutils import ThumbnailDataForProximity
from raphodo.folderspreview import DownloadDestination, FoldersPreview
from raphodo.problemnotification import (
    ScanProblems, CopyingProblems, RenamingProblems, BackingUpProblems
)

logger = logging.getLogger()


def make_filter_from_worker_id(worker_id) -> bytes:
    r"""
    Returns a python byte string from an integer or string

    >>> make_filter_from_worker_id(54)
    b'54'

    >>> make_filter_from_worker_id('54')
    b'54'
    """
    if isinstance(worker_id, int):
        return str(worker_id).encode()
    if isinstance(worker_id, str):
        return worker_id.encode()
    raise(TypeError)

def create_identity(worker_type: str, identity: str) -> bytes:
    r"""Generate identity for a worker's 0mq socket.

    >>> create_identity('Worker', '1')
    b'Worker-1'
    >>> create_identity('Thumbnail Extractor', '2')
    b'Thumbnail-Extractor-2'
    >>> create_identity('Thumbnail Extractor Plus', '22 2')
    b'Thumbnail-Extractor-Plus-22-2'
    """

    # Replace any whitespace in the strings with a hyphen
    return '{}-{}'.format('-'.join(worker_type.split()), '-'.join(identity.split())).encode()

def get_worker_id_from_identity(identity: bytes) -> int:
    r"""Extract worker id from the identity used in a 0mq socket

    >>> get_worker_id_from_identity(b'Worker-1')
    1
    >>> get_worker_id_from_identity(b'Thumbnail-Extractor-2')
    2
    >>> get_worker_id_from_identity(b'Thumbnail-Extractor-Plus-22-2')
    2
    """
    return int(identity.decode().split('-')[-1])


def create_inproc_msg(cmd: bytes,
                      worker_id: Optional[int]=None,
                      data: Optional[Any]=None) -> List[bytes]:
    """
    Create a list of three values to be sent via a PAIR socket
    between main and child threads using 0MQ.
    """

    if worker_id is not None:
        worker_id = make_filter_from_worker_id(worker_id)
    else:
        worker_id = b''

    if data is None:
        data = b''
    else:
        data = pickle.dumps(data, pickle.HIGHEST_PROTOCOL)

    return [cmd, worker_id, data]


class ThreadNames:
    rename = 'rename'
    scan = 'scan'
    copy = 'copy'
    backup = 'backup'
    thumbnail_daemon = 'thumbnail_daemon'
    thumbnailer = 'thumbnailer'
    offload = 'offload'
    logger = 'logger'
    load_balancer = 'load_balancer'
    new_version = 'new_version'


class ProcessManager:
    def __init__(self, logging_port: int,
                 thread_name: str) -> None:

        super().__init__()

        self.logging_port = logging_port

        self.processes = {}  # type: Dict[int, psutil.Process]
        self._process_to_run = ''  # Implement in subclass

        self.thread_name = thread_name

        # Monitor which workers we have running
        self.workers = []  # type: List[int]

    def _get_cmd(self) -> str:
        return '{} {}'.format(
            sys.executable, os.path.join(
                os.path.abspath(os.path.dirname(__file__)), self._process_to_run
            )
        )

    def _get_command_line(self, worker_id: int) -> str:
        """
        Implement in sublcass
        """
        return ''

    def add_worker(self, worker_id: int) -> None:

        command_line = self._get_command_line(worker_id)
        args = shlex.split(command_line)

        # run command immediately, without waiting a reply, and instruct the Linux
        # kernel to send a terminate signal should this process unexpectedly die
        try:
            proc = psutil.Popen(args, preexec_fn=set_pdeathsig())
        except OSError as e:
            logging.critical("Failed to start process: %s", command_line)
            logging.critical('OSError [Errno %s]: %s', e.errno, e.strerror)
            if e.errno == 8:
                logging.critical(
                    "Script shebang line might be malformed or missing: %s", self._get_cmd()
                )
            sys.exit(1)
        logging.debug("Started '%s' with pid %s", command_line, proc.pid)

        # Add to list of running workers
        self.workers.append(worker_id)
        self.processes[worker_id] = proc

    def forcefully_terminate(self) -> None:
        """
        Forcefully terminate any running child processes.
        """

        zombie_processes = [
            p for p in self.processes.values()
            if p.is_running() and p.status() == psutil.STATUS_ZOMBIE
        ]
        running_processes = [
            p for p in self.processes.values()
            if p.is_running() and p.status() != psutil.STATUS_ZOMBIE
        ]
        if hasattr(self, '_process_name'):
            logging.debug(
                "Forcefully terminating processes for %s: %s zombies, %s running.",
                self._process_name, len(zombie_processes), len(running_processes)
            )

        for p in zombie_processes:  # type: psutil.Process
            try:
                logging.debug("Killing zombie process %s with pid %s", p.name(), p.pid)
                p.kill()
            except:
                logging.error("Failed to kill process with pid %s", p.pid)
        for p in running_processes:  # type: psutil.Process
            try:
                logging.debug("Terminating process %s with pid %s", p.name(), p.pid)
                p.terminate()
            except:
                logging.error("Terminating process with pid %s failed", p.pid)
        gone, alive = psutil.wait_procs(running_processes, timeout=2)
        for p in alive:
            try:
                logging.debug("Killing zombie process %s with pid %s", p.name(), p.pid)
                p.kill()
            except:
                logging.error("Failed to kill process with pid %s", p.pid)

    def process_alive(self, worker_id: int) -> bool:
        """
        Process IDs are reused by the system. Check to make sure
        a new process has not been created with the same process id.

        :param worker_id: the process to check
        :return True if the process is the same, False otherwise
        """

        return self.processes[worker_id].is_running()


class PullPipelineManager(ProcessManager, QObject):
    """
    Base class from which more specialized 0MQ classes are derived.

    Receives data into its sink via a ZMQ PULL socket, but does not
    specify how workers should be sent data.

    Outputs signals using Qt.
    """

    message = pyqtSignal(str) # Derived class will change this
    sinkStarted = pyqtSignal()
    workerFinished = pyqtSignal(int)
    workerStopped = pyqtSignal(int)
    receiverPortSignal = pyqtSignal(int)

    def __init__(self, logging_port: int,
                 thread_name: str) -> None:
        super().__init__(logging_port=logging_port, thread_name=thread_name)

    def _start_sockets(self) -> None:

        context = zmq.Context.instance()

        # Subclasses must define the type of port they need to send messages
        self.ventilator_socket = None
        self.ventilator_port = None

        # Sink socket to receive results of the workers
        self.receiver_socket = context.socket(zmq.PULL)
        self.receiver_port = self.receiver_socket.bind_to_random_port('tcp://*')

        # Socket to communicate directly with the sink, bypassing the workers
        self.terminate_socket = context.socket(zmq.PUSH)
        self.terminate_socket.connect("tcp://localhost:{}".format(self.receiver_port))

        # Socket to receive commands from main thread
        self.thread_controller = context.socket(zmq.PAIR)
        self.thread_controller.connect('inproc://{}'.format(self.thread_name))

        self.terminating = False

    @pyqtSlot()
    def run_sink(self) -> None:
        logging.debug("Running sink for %s", self._process_name)

        self._start_sockets()

        poller = zmq.Poller()
        poller.register(self.receiver_socket, zmq.POLLIN)
        poller.register(self.thread_controller, zmq.POLLIN)

        self.receiverPortSignal.emit(self.receiver_port)
        self.sinkStarted.emit()

        while True:
            try:
                socks = dict(poller.poll())
            except KeyboardInterrupt:
                break
            if self.receiver_socket in socks:
                # Receive messages from the workers
                # (or the terminate socket)
                worker_id, directive, content = self.receiver_socket.recv_multipart()

                if directive == b'cmd':
                    command = content
                    assert command in (b"STOPPED", b"FINISHED", b"KILL")
                    if command == b"KILL":
                        # Terminate immediately, without regard for any
                        # incoming messages. This message is only sent
                        # from this manager to itself, using the
                        # self.terminate_socket
                        logging.debug("{} is terminating".format(self._process_name))
                        break
                    # This worker is done; remove from monitored workers and
                    # continue
                    worker_id = int(worker_id)
                    if command == b"STOPPED":
                        logging.debug("%s worker %s has stopped", self._process_name, worker_id)
                        self.workerStopped.emit(worker_id)
                    else:
                        # Worker has finished its work
                        self.workerFinished.emit(worker_id)
                    self.workers.remove(worker_id)
                    del self.processes[worker_id]
                    if not self.workers:
                        logging.debug("{} currently has no workers".format(self._process_name))
                    if not self.workers and self.terminating:
                        logging.debug("{} is exiting".format(self._process_name))
                        break
                else:
                    assert directive == b'data'
                    self.content = content
                    self.process_sink_data()

            if self.thread_controller in socks:
                # Receive messages from the main Rapid Photo Downloader thread
                self.process_thread_directive()

    def process_thread_directive(self) -> None:
        directive, worker_id, data = self.thread_controller.recv_multipart()

        # Directives: START, STOP, TERMINATE, SEND_TO_WORKER, STOP_WORKER, START_WORKER
        if directive == b'START':
            self.start()
        elif directive == b'START_WORKER':
            self.start_worker(worker_id=worker_id, data=data)
        elif directive == b'SEND_TO_WORKER':
            self.send_message_to_worker(worker_id=worker_id, data=data)
        elif directive == b'STOP':
            self.stop()
        elif directive == b'STOP_WORKER':
            self.stop_worker(worker_id=worker_id)
        elif directive == b'PAUSE':
            self.pause()
        elif directive == b'RESUME':
            self.resume(worker_id=worker_id)
        elif directive == b'TERMINATE':
            self.forcefully_terminate()
        else:
            logging.critical("%s received unknown directive %s", directive.decode())

    def process_sink_data(self) -> None:
        data = pickle.loads(self.content)
        self.message.emit(data)

    def terminate_sink(self) -> None:
        self.terminate_socket.send_multipart([b'0', b'cmd', b'KILL'])

    def _get_ventilator_start_message(self, worker_id: bytes) -> list:
        return [worker_id, b'cmd', b'START']

    def start(self) -> None:
        logging.critical(
            "Member function start() not implemented in child class of %s", self._process_name
        )

    def start_worker(self, worker_id: bytes, data: bytes) -> None:
        logging.critical(
            "Member function start_worker() not implemented in child class of %s",
            self._process_name
        )

    def stop(self) -> None:
        logging.critical(
            "Member function stop() not implemented in child class of %s", self._process_name
        )

    def stop_worker(self, worker_id: int) -> None:
        logging.critical(
            "Member function stop_worker() not implemented in child class of %s",
            self._process_name
        )

    def pause(self) -> None:
        logging.critical("Member function pause() not implemented in child class of %s",
                         self._process_name)

    def resume(self, worker_id: Optional[bytes]) -> None:
        logging.critical(
            "Member function stop_worker() not implemented in child class of %s", self._process_name
        )

    def send_message_to_worker(self, data: bytes, worker_id:Optional[bytes]=None) -> None:
        if self.terminating:
            logging.debug(
                "%s not sending message to worker because manager is terminated", self._process_name
            )
            return
        if not self.workers:
            logging.debug(
                "%s not sending message to worker because there are no workers", self._process_name
            )
            return

        assert isinstance(data, bytes)

        if worker_id:
            message = [worker_id, b'data', data]
        else:
            message = [b'data', data]
        self.ventilator_socket.send_multipart(message)

    def forcefully_terminate(self) -> None:
        """
        Forcefully terminate any child processes and clean up.

        Shuts down the sink too.
        """

        super().forcefully_terminate()
        self.terminate_sink()


class LoadBalancerWorkerManager(ProcessManager):
    def __init__(self, no_workers: int,
                 backend_port: int,
                 sink_port: int,
                 logging_port: int) -> None:
        super().__init__(logging_port=logging_port, thread_name='')
        self.no_workers = no_workers
        self.backend_port = backend_port
        self.sink_port = sink_port

    def _get_command_line(self, worker_id: int) -> str:
        cmd = self._get_cmd()

        return '{} --request {} --send {} --identity {} --logging {}'.format(
            cmd,
            self.backend_port,
            self.sink_port,
            worker_id,
            self.logging_port
        )

    def start_workers(self) -> None:
        for worker_id in range(self.no_workers):
            self.add_worker(worker_id)


class LRUQueue:
    """LRUQueue class using ZMQStream/IOLoop for event dispatching"""

    def __init__(self, backend_socket: zmq.Socket,
                 frontend_socket: zmq.Socket,
                 controller_socket: zmq.Socket,
                 worker_type: str,
                 process_manager: LoadBalancerWorkerManager) -> None:

        self.worker_type = worker_type
        self.process_manager = process_manager
        self.workers = deque()
        self.terminating = False
        self.terminating_workers = set()  # type: Set[bytes]
        self.stopped_workers = set()  # type: Set[int]

        self.backend = ZMQStream(backend_socket)
        self.frontend = ZMQStream(frontend_socket)
        self.controller = ZMQStream(controller_socket)
        self.backend.on_recv(self.handle_backend)
        self.controller.on_recv(self.handle_controller)

        self.loop = ioloop.IOLoop.instance()

    def handle_controller(self, msg):
        self.terminating = True
        # logging.debug(
        #     "%s load balancer requesting %s workers to stop", self.worker_type, len(self.workers)
        # )

        while len(self.workers):
            worker_identity = self.workers.popleft()

            logging.debug(
                "%s load balancer sending stop cmd to worker %s",
                self.worker_type, worker_identity.decode()
            )
            self.backend.send_multipart([worker_identity, b'', b'cmd', b'STOP'])
            self.terminating_workers.add(worker_identity)

        self.loop.add_timeout(time.time()+3, self.loop.stop)

    def handle_backend(self, msg):
        # Queue worker address for LRU routing
        worker_identity, empty, client_addr = msg[:3]

        # add worker back to the list of workers
        self.workers.append(worker_identity)

        # Second frame is empty
        assert empty == b''

        if msg[-1] == b'STOPPED' and self.terminating:
            worker_id = get_worker_id_from_identity(worker_identity)
            self.stopped_workers.add(worker_id)
            self.terminating_workers.remove(worker_identity)
            if len(self.terminating_workers) == 0:
                for worker_id in self.stopped_workers:
                    p = self.process_manager.processes[worker_id]  # type: psutil.Process
                    if p.is_running():
                        pid = p.pid
                        if p.status() != psutil.STATUS_SLEEPING:
                            logging.debug(
                                "Waiting on %s process %s...", p.status(), pid
                            )
                            os.waitpid(pid, 0)
                            logging.debug("...process %s is finished", pid)
                        else:
                            logging.debug("Process %s is sleeping", pid)
                self.loop.add_timeout(time.time()+0.5, self.loop.stop)

        if len(self.workers) == 1:
            # on first recv, start accepting frontend messages
            self.frontend.on_recv(self.handle_frontend)

    def handle_frontend(self, request):
        #  Dequeue and drop the next worker address
        worker_identity = self.workers.popleft()

        message = [worker_identity, b''] + request
        self.backend.send_multipart(message)
        if len(self.workers) == 0:
            # stop receiving until workers become available again
            self.frontend.stop_on_recv()


class LoadBalancer:
    def __init__(self, worker_type: str, process_manager) -> None:

        self.parser = argparse.ArgumentParser()
        self.parser.add_argument("--receive", required=True)
        self.parser.add_argument("--send", required=True)
        self.parser.add_argument("--controller", required=True)
        self.parser.add_argument("--logging", required=True)

        args = self.parser.parse_args()
        self.controller_port = args.controller

        context = zmq.Context()
        frontend = context.socket(zmq.PULL)
        frontend_port = frontend.bind_to_random_port('tcp://*')

        backend = context.socket(zmq.ROUTER)
        backend_port = backend.bind_to_random_port('tcp://*')

        reply = context.socket(zmq.REP)
        reply.connect("tcp://localhost:{}".format(args.receive))

        controller = context.socket(zmq.PULL)
        controller.connect('tcp://localhost:{}'.format(self.controller_port))

        sink_port = args.send
        logging_port = args.logging

        self.logger_publisher = ProcessLoggerPublisher(
            context=context, name=worker_type, notification_port=args.logging
        )

        logging.debug(
            "{} load balancer waiting to be notified how many workers to initialize...".format(
                worker_type
            )
        )
        no_workers = int(reply.recv())
        logging.debug("...{} load balancer will use {} workers".format(worker_type, no_workers))
        reply.send(str(frontend_port).encode())

        process_manager = process_manager(no_workers, backend_port, sink_port, logging_port)
        process_manager.start_workers()

        # create queue with the sockets
        queue = LRUQueue(backend, frontend, controller, worker_type, process_manager)

        # start reactor, which is an infinite loop
        ioloop.IOLoop.instance().start()

        # Finished infinite loop: do some housekeeping
        logging.debug("Forcefully terminating load balancer child processes")
        process_manager.forcefully_terminate()

        frontend.close()
        backend.close()


class LoadBalancerManager(ProcessManager, QObject):
    """
    Launches and requests termination of the Load Balancer process
    """

    load_balancer_started = pyqtSignal(int)
    def __init__(self, context: zmq.Context,
                 no_workers: int,
                 sink_port: int,
                 logging_port: int,
                 thread_name: str) -> None:
        super().__init__(logging_port=logging_port, thread_name=thread_name)
        self.no_workers = no_workers
        self.sink_port = sink_port
        self.context = context

    @pyqtSlot()
    def start_load_balancer(self) -> None:

        self.controller_socket = self.context.socket(zmq.PUSH)
        self.controller_port = self.controller_socket.bind_to_random_port('tcp://*')

        self.requester = self.context.socket(zmq.REQ)
        self.requester_port = self.requester.bind_to_random_port('tcp://*')

        self.thread_controller = self. context.socket(zmq.PAIR)
        self.thread_controller.connect('inproc://{}'.format(self.thread_name))

        worker_id = 0
        self.add_worker(worker_id)
        self.requester.send(str(self.no_workers).encode())
        self.frontend_port = int(self.requester.recv())
        self.load_balancer_started.emit(self.frontend_port)

        # wait for stop signal
        directive, worker_id, data = self.thread_controller.recv_multipart()
        assert directive == b'STOP'
        self.stop()

    def stop(self):
        self.controller_socket.send(b'STOP')

    def _get_command_line(self, worker_id: int) -> str:
        cmd = self._get_cmd()

        return '{} --receive {} --send {} --controller {} --logging {}'.format(
            cmd,
            self.requester_port,
            self.sink_port,
            self.controller_port,
            self.logging_port
        )

DAEMON_WORKER_ID = 0


class PushPullDaemonManager(PullPipelineManager):
    """
    Manage a single instance daemon worker process that waits to work on data
    issued by this manager. The data to be worked on is issued in sequence,
    one after the other.

    Because this is a single daemon process, a Push-Pull model is most
    suitable for sending the data.
    """

    def _start_sockets(self) -> None:

        super()._start_sockets()

        context = zmq.Context.instance()

        # Ventilator socket to send message to worker
        self.ventilator_socket = context.socket(zmq.PUSH)
        self.ventilator_port = self.ventilator_socket.bind_to_random_port('tcp://*')

    def stop(self) -> None:
        """
        Permanently stop the daemon process and terminate
        """

        logging.debug("{} halting".format(self._process_name))
        self.terminating = True

        # Only send stop command if the process is still running
        if self.process_alive(DAEMON_WORKER_ID):
            try:
                self.ventilator_socket.send_multipart([b'cmd', b'STOP'], zmq.DONTWAIT)
            except zmq.Again:
                logging.debug(
                    "Terminating %s sink because child process did not receive message",
                    self._process_name
                )
                self.terminate_sink()
        else:
            # The process may have crashed. Stop the sink.
            self.terminate_sink()

    def _get_command_line(self, worker_id: int) -> str:
        cmd = self._get_cmd()

        return '{} --receive {} --send {} --logging {}'.format(
            cmd,
            self.ventilator_port,
            self.receiver_port,
            self.logging_port
        )

    def _get_ventilator_start_message(self, worker_id: int) -> List[bytes]:
        return [b'cmd', b'START']

    def start(self) -> None:
        logging.debug("Starting worker for %s", self._process_name)
        self.add_worker(worker_id=DAEMON_WORKER_ID)


class PublishPullPipelineManager(PullPipelineManager):
    """
    Manage a collection of worker processes that wait to work on data
    issued by this manager. The data to be worked on is issued in sequence,
    one after the other, either once, or many times.

    Because there are multiple worker process, a Publish-Subscribe model is
    most suitable for sending data to workers.
    """

    def _start_sockets(self) -> None:

        super()._start_sockets()

        context = zmq.Context.instance()

        # Ventilator socket to send messages to workers on
        self.ventilator_socket = context.socket(zmq.PUB)
        self.ventilator_port= self.ventilator_socket.bind_to_random_port('tcp://*')

        # Socket to synchronize the start of each worker
        self.sync_service_socket = context.socket(zmq.REP)
        self.sync_service_port = self.sync_service_socket.bind_to_random_port("tcp://*")

        # Socket for worker control: pause, resume, stop
        self.controller_socket = context.socket(zmq.PUB)
        self.controller_port = self.controller_socket.bind_to_random_port("tcp://*")

    def stop(self) -> None:
        """
        Permanently stop all the workers and terminate
        """

        logging.debug("{} halting".format(self._process_name))
        self.terminating = True
        if self.workers:
            # Signal workers they must immediately stop
            termination_signal_sent = False
            alive_workers = [worker_id for worker_id in self.workers if
                             self.process_alive(worker_id)]
            for worker_id in alive_workers:

                message = [make_filter_from_worker_id(worker_id),b'STOP']
                self.controller_socket.send_multipart(message)

                message = [make_filter_from_worker_id(worker_id), b'cmd', b'STOP']
                self.ventilator_socket.send_multipart(message)
                termination_signal_sent = True

            if not termination_signal_sent:
                self.terminate_sink()
        else:
            self.terminate_sink()

    def stop_worker(self, worker_id: bytes) -> None:
        """
        Permanently stop one worker
        """

        if int(worker_id) in self.workers:
            message = [worker_id, b'STOP']
            self.controller_socket.send_multipart(message)
            message = [worker_id, b'cmd', b'STOP']
            self.ventilator_socket.send_multipart(message)

    def start_worker(self, worker_id: bytes, data: bytes) -> None:

        self.add_worker(int(worker_id))

        # Send START commands until scan worker indicates it is ready to
        # receive data
        # Worker ID must be in bytes format
        while True:
            self.ventilator_socket.send_multipart(
                self._get_ventilator_start_message(worker_id))
            try:
                # look for synchronization request
                self.sync_service_socket.recv(zmq.DONTWAIT)
                # send synchronization reply
                self.sync_service_socket.send(b'')
                break
            except zmq.Again:
                # Briefly pause sending out START messages
                # There is no point flooding the network
                time.sleep(.01)

        # Send data to process to tell it what to work on
        self.send_message_to_worker(data=data, worker_id=worker_id)

    def _get_command_line(self, worker_id: int) -> str:
        cmd = self._get_cmd()

        return '{} --receive {} --send {} --controller {} --syncclient {} --filter {} --logging '\
               '{}'.format(
            cmd,
            self.ventilator_port,
            self.receiver_port,
            self.controller_port,
            self.sync_service_port,
            worker_id,
            self.logging_port
        )

    def __len__(self) -> int:
        return len(self.workers)

    def __contains__(self, item) -> bool:
        return item in self.workers

    def pause(self) -> None:
        for worker_id in self.workers:
            message = [make_filter_from_worker_id(worker_id), b'PAUSE']
            self.controller_socket.send_multipart(message)

    def resume(self, worker_id: bytes) -> None:
        if worker_id:
            workers = [int(worker_id)]
        else:
            workers = self.workers
        for worker_id in workers:
            message = [make_filter_from_worker_id(worker_id), b'RESUME']
            self.controller_socket.send_multipart(message)


class ProcessLoggerPublisher:
    """
    Setup the sockets for worker processes to send log messages to the
    main process.

    Two tasks: set up the PUB socket, and then tell the main process
    what port we're using via a second socket, and when we're closing it.
    """

    def __init__(self, context: zmq.Context, name: str, notification_port: int) -> None:

        self.logger_pub = context.socket(zmq.PUB)
        self.logger_pub_port = self.logger_pub.bind_to_random_port("tcp://*")
        self.handler = ZeroMQSocketHandler(self.logger_pub)
        self.handler.setLevel(logging.DEBUG)

        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)
        self.logger.addHandler(self.handler)
    
        self.logger_socket = context.socket(zmq.PUSH)
        self.logger_socket.connect("tcp://localhost:{}".format(notification_port))
        self.logger_socket.send_multipart([b'CONNECT', str(self.logger_pub_port).encode()])

    def close(self):
        self.logger.removeHandler(self.handler)
        self.logger_socket.send_multipart([b'DISCONNECT', str(self.logger_pub_port).encode()])
        self.logger_pub.close()
        self.logger_socket.close()


class WorkerProcess():
    def __init__(self, worker_type: str) -> None:
        super().__init__()
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument("--receive", required=True)
        self.parser.add_argument("--send", required=True)
        self.parser.add_argument("--logging", required=True)

    def cleanup_pre_stop(self) -> None:
        """
        Operations to run if process is stopped.

        Implement in child class if needed.
        """

        pass

    def setup_logging_pub(self, notification_port: int, name: str) -> None:
        """
        Sets up the 0MQ socket that sends out logging messages

        :param notification_port: port that should be notified about
         the new logging publisher
        :param name: descriptive name to place in the log messages
        """

        if self.worker_id is not None:
            name = '{}-{}'.format(name, self.worker_id.decode())
        self.logger_publisher = ProcessLoggerPublisher(
            context=self.context, name=name, notification_port=notification_port
        )

    def send_message_to_sink(self) -> None:

        self.sender.send_multipart([self.worker_id, b'data', self.content])

    def initialise_process(self) -> None:
        # Wait to receive "START" message
        worker_id, directive, content = self.receiver.recv_multipart()
        assert directive == b'cmd'
        assert content == b'START'

        # send a synchronization request
        self.sync_client.send(b'')

        # wait for synchronization reply
        self.sync_client.recv()

        # Receive next "START" message and discard, looking for data message
        while True:
            worker_id, directive, content = self.receiver.recv_multipart()
            if directive == b'data':
                break
            else:
                assert directive == b'cmd'
                assert content == b'START'

        self.content = content

    def do_work(self):
        pass


class DaemonProcess(WorkerProcess):
    """
    Single instance
    """
    def __init__(self, worker_type: str) -> None:
        super().__init__(worker_type)

        args = self.parser.parse_args()

        self.context = zmq.Context()
        # Socket to send messages along the pipe to
        self.sender = self.context.socket(zmq.PUSH)
        self.sender.set_hwm(10)
        self.sender.connect("tcp://localhost:{}".format(args.send))

        self.receiver = self.context.socket(zmq.PULL)
        self.receiver.connect("tcp://localhost:{}".format(args.receive))

        self.worker_id = None

        self.setup_logging_pub(notification_port=args.logging, name=worker_type)

    def run(self) -> None:
        pass

    def check_for_command(self, directive: bytes, content: bytes) -> None:
        if directive == b'cmd':
            assert content == b'STOP'
            self.cleanup_pre_stop()
            # signal to sink that we've terminated before finishing
            self.sender.send_multipart(
                [make_filter_from_worker_id(DAEMON_WORKER_ID), b'cmd', b'STOPPED']
            )
            sys.exit(0)

    def send_message_to_sink(self) -> None:
        # Must use a dummy value for the worker id, as there is only ever one
        # instance.
        self.sender.send_multipart(
            [make_filter_from_worker_id(DAEMON_WORKER_ID), b'data', self.content]
        )


class WorkerInPublishPullPipeline(WorkerProcess):
    """
    Worker counterpart to PublishPullPipelineManager; multiple instance.
    """
    def __init__(self, worker_type: str) -> None:
        super().__init__(worker_type)
        self.add_args()

        args = self.parser.parse_args()

        subscription_filter = self.worker_id = args.filter.encode()
        self.context = zmq.Context()

        self.setup_sockets(args, subscription_filter)
        self.setup_logging_pub(notification_port=args.logging, name=worker_type)

        self.initialise_process()
        self.do_work()

    def add_args(self) -> None:
        self.parser.add_argument("--filter", required=True)
        self.parser.add_argument("--syncclient", required=True)
        self.parser.add_argument("--controller", required=True)

    def setup_sockets(self, args, subscription_filter: bytes) -> None:

        # Socket to send messages along the pipe to
        self.sender = self.context.socket(zmq.PUSH)
        self.sender.set_hwm(10)
        self.sender.connect("tcp://localhost:{}".format(args.send))

        # Socket to receive messages from the pipe
        self.receiver = self.context.socket(zmq.SUB)
        self.receiver.connect("tcp://localhost:{}".format(args.receive))
        self.receiver.setsockopt(zmq.SUBSCRIBE, subscription_filter)

        # Socket to receive controller messages: stop, pause, resume
        self.controller = self.context.socket(zmq.SUB)
        self.controller.connect("tcp://localhost:{}".format(args.controller))
        self.controller.setsockopt(zmq.SUBSCRIBE, subscription_filter)

        # Socket to synchronize the start of receiving data from upstream
        self.sync_client = self.context.socket(zmq.REQ)
        self.sync_client.connect("tcp://localhost:{}".format(args.syncclient))

    def check_for_command(self, directive: bytes, content) -> None:
        if directive == b'cmd':
            try:
                assert content == b'STOP'
            except AssertionError:
                logging.critical("Expected STOP command but instead got %s", content.decode())
            else:
                self.cleanup_pre_stop()
                self.disconnect_logging()
                # signal to sink that we've terminated before finishing
                self.sender.send_multipart([self.worker_id, b'cmd', b'STOPPED'])
                sys.exit(0)

    def check_for_controller_directive(self) -> None:
        try:
            # Don't block if process is running regularly
            # If there is no command,exception will occur
            worker_id, command = self.controller.recv_multipart(zmq.DONTWAIT)
            assert command in [b'PAUSE', b'STOP']
            assert  worker_id == self.worker_id

            if command == b'PAUSE':
                # Because the process is paused, do a blocking read to
                # wait for the next command
                worker_id, command = self.controller.recv_multipart()
                assert (command in [b'RESUME', b'STOP'])
            if command == b'STOP':
                self.cleanup_pre_stop()
                # before finishing, signal to sink that we've terminated
                self.sender.send_multipart([self.worker_id, b'cmd', b'STOPPED'])
                sys.exit(0)
        except zmq.Again:
            pass # Continue working

    def resume_work(self) -> None:
        worker_id, command = self.controller.recv_multipart()
        assert (command in [b'RESUME', b'STOP'])
        if command == b'STOP':
            self.cleanup_pre_stop()
            self.disconnect_logging()
            # before finishing, signal to sink that we've terminated
            self.sender.send_multipart([self.worker_id, b'cmd', b'STOPPED'])
            sys.exit(0)

    def disconnect_logging(self) -> None:
        self.logger_publisher.close()

    def send_finished_command(self) -> None:
        self.sender.send_multipart([self.worker_id, b'cmd', b'FINISHED'])


class LoadBalancerWorker:
    def __init__(self, worker_type: str) -> None:
        super().__init__()
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument("--request", required=True)
        self.parser.add_argument("--send", required=True)
        self.parser.add_argument("--identity", required=True)
        self.parser.add_argument("--logging", required=True)

        args = self.parser.parse_args()

        self.context = zmq.Context()

        self.requester = self.context.socket(zmq.REQ)
        self.identity = create_identity(worker_type, args.identity)
        self.requester.identity = self.identity
        self.requester.connect("tcp://localhost:{}".format(args.request))

        # Sender is located in the main process. It is where output (messages)
        # from this process are are sent to.
        self.sender = self.context.socket(zmq.PUSH)
        self.sender.connect("tcp://localhost:{}".format(args.send))
        
        self.logger_publisher = ProcessLoggerPublisher(context=self.context,
                                                       name=worker_type,
                                                       notification_port=args.logging)

        # Tell the load balancer we are ready for work
        self.requester.send(b"READY")
        self.do_work()

    def do_work(self) -> None:
        # Implement in subclass
        pass

    def cleanup_pre_stop(self) -> None:
        """
        Operations to run if process is stopped.

        Implement in child class if needed.
        """

        pass

    def exit(self):
        self.cleanup_pre_stop()
        identity = self.requester.identity.decode()
        # signal to load balancer that we've terminated before finishing
        self.requester.send_multipart([b'', b'', b'STOPPED'])
        self.requester.close()
        self.sender.close()
        self.logger_publisher.close()
        self.context.term()
        logging.debug("%s with pid %s stopped", identity, os.getpid())
        sys.exit(0)

    def check_for_command(self, directive: bytes, content: bytes):
        if directive == b'cmd':
            assert content == b'STOP'
            self.exit()


class ProcessLoggingManager(QObject):
    """
    Receive and log logging messages from workers.

    An alternative might be using python logging's QueueListener, which
    like this code, runs on its own thread.
    """

    ready = pyqtSignal(int)

    @pyqtSlot()
    def startReceiver(self) -> None:
        context = zmq.Context.instance()
        self.receiver = context.socket(zmq.SUB)
        # Subscribe to all variates of logging messages
        self.receiver.setsockopt(zmq.SUBSCRIBE, b'')

        # Socket to receive subscription information, and the stop command
        info_socket = context.socket(zmq.PULL)
        self.info_port = info_socket.bind_to_random_port('tcp://*')

        poller = zmq.Poller()
        poller.register(self.receiver, zmq.POLLIN)
        poller.register(info_socket, zmq.POLLIN)

        self.ready.emit(self.info_port)

        while True:
            try:
                socks = dict(poller.poll())
            except KeyboardInterrupt:
                break

            if self.receiver in socks:
                message = self.receiver.recv()
                record = logging.makeLogRecord(pickle.loads(message))
                logger.handle(record)

            if info_socket in socks:
                directive, content = info_socket.recv_multipart()
                if directive == b'STOP':
                    break
                elif directive == b'CONNECT':
                    self.addSubscription(content)
                else:
                    assert directive == b'DISCONNECT'
                    self.removeSubscription(content)

    def addSubscription(self, port: bytes) -> None:
        try:
            port = int(port)
        except ValueError:
            logging.critical('Incorrect port value in add logging subscription: %s', port)
        else:
            logging.debug("Subscribing to logging on port %s", port)
            self.receiver.connect("tcp://localhost:{}".format(port))

    def removeSubscription(self, port: bytes):
        try:
            port = int(port)
        except ValueError:
            logging.critical('Incorrect port value in remove logging subscription: %s', port)
        else:
            logging.debug("Unsubscribing to logging on port %s", port)
            self.receiver.disconnect("tcp://localhost:{}".format(port))


def stop_process_logging_manager(info_port: int) -> None:
    """
    Stop ProcessLoggingManager thread

    :param info_port: the port number the manager uses
    """

    context = zmq.Context.instance()
    command =  context.socket(zmq.PUSH)
    command.connect("tcp://localhost:{}".format(info_port))
    command.send_multipart([b'STOP', b''])


class ScanArguments:
    """
    Pass arguments to the scan process
    """
    def __init__(self, device: Device,
                 ignore_other_types: bool,
                 log_gphoto2: bool) -> None:
        """
        Pass arguments to the scan process

        :param device: the device to scan
        :param ignore_other_types: ignore file types like TIFF
        :param log_gphoto2: whether to generate detailed gphoto2 log
         messages
        :param scan_only_DCIM: if the device is an auto-detected volume,
         then if True, scan only in it's DCIM folder
        :param warn_unknown_file: whether to issue a warning when
         encountering an unknown (unrecognized) file
        """

        self.device = device
        self.ignore_other_types = ignore_other_types
        self.log_gphoto2 = log_gphoto2


class ScanResults:
    """
    Receive results from the scan process
    """

    def __init__(self, rpd_files: Optional[List[RPDFile]]=None,
                 file_type_counter: Optional[FileTypeCounter]=None,
                 file_size_sum: Optional[FileSizeSum]=None,
                 error_code: Optional[CameraErrorCode]=None,
                 scan_id: Optional[int]=None,
                 optimal_display_name: Optional[str]=None,
                 storage_space: Optional[List[StorageSpace]]=None,
                 storage_descriptions: Optional[List[str]]=None,
                 sample_photo: Optional[Photo]=None,
                 sample_video: Optional[Video]=None,
                 problems: Optional[ScanProblems]=None,
                 fatal_error: Optional[bool]=None,
                 entire_video_required: Optional[bool]=None) -> None:
        self.rpd_files = rpd_files
        self.file_type_counter = file_type_counter
        self.file_size_sum = file_size_sum
        self.error_code = error_code
        self.scan_id = scan_id
        self.optimal_display_name = optimal_display_name
        self.storage_space = storage_space
        self.storage_descriptions = storage_descriptions
        self.sample_photo = sample_photo
        self.sample_video = sample_video
        self.problems = problems
        self.fatal_error = fatal_error
        self.entire_video_required = entire_video_required


class CopyFilesArguments:
    """
    Pass arguments to the copyfiles process
    """

    def  __init__(self, scan_id: int,
                  device: Device,
                  photo_download_folder: str,
                  video_download_folder: str,
                  files: List[RPDFile],
                  verify_file: bool,
                  generate_thumbnails: bool,
                  log_gphoto2: bool) -> None:
        self.scan_id = scan_id
        self.device = device
        self.photo_download_folder = photo_download_folder
        self.video_download_folder = video_download_folder
        self.files = files
        self.generate_thumbnails = generate_thumbnails
        self.verify_file = verify_file
        self.log_gphoto2 = log_gphoto2


class CopyFilesResults:
    """
    Receive results from the copyfiles process
    """

    def __init__(self, scan_id: Optional[int]=None,
                 photo_temp_dir: Optional[str]=None,
                 video_temp_dir: Optional[str]=None,
                 total_downloaded: Optional[int]=None,
                 chunk_downloaded: Optional[int]=None,
                 copy_succeeded: Optional[bool]=None,
                 rpd_file: Optional[RPDFile]=None,
                 download_count: Optional[int]=None,
                 mdata_exceptions: Optional[Tuple]=None,
                 problems: Optional[CopyingProblems]=None) -> None:
        """

        :param scan_id: scan id of the device the files are being
         downloaded from
        :param photo_temp_dir: temp directory path, used to copy
         photos into until they're renamed
        :param video_temp_dir: temp directory path, used to copy
         videos into until they're renamed
        :param total_downloaded: how many bytes in total have been
         downloaded
        :param chunk_downloaded: how many bytes were downloaded since
         the last message
        :param copy_succeeded: whether the copy was successful or not
        :param rpd_file: details of the file that was copied
        :param download_count: a running count of how many files
         have been copied. Used in download tracking.
        :param mdata_exceptions: details of errors setting file metadata
        :param problems: details of any problems encountered copying files,
         not including metedata write problems.
        """

        self.scan_id = scan_id

        self.photo_temp_dir = photo_temp_dir
        self.video_temp_dir = video_temp_dir

        self.total_downloaded = total_downloaded
        self.chunk_downloaded = chunk_downloaded

        self.copy_succeeded = copy_succeeded
        self.rpd_file = rpd_file
        self.download_count = download_count
        self.mdata_exceptions = mdata_exceptions
        self.problems = problems


class ThumbnailDaemonData:
    """
    Pass arguments to the thumbnail daemon process.

    Occurs after a file is downloaded & renamed, and also
    after a file is backed up.
    """

    def __init__(self, frontend_port: Optional[int]=None,
                 rpd_file: Optional[RPDFile]=None,
                 write_fdo_thumbnail: Optional[bool]=None,
                 use_thumbnail_cache: Optional[bool]=None,
                 backup_full_file_names: Optional[List[str]]=None,
                 fdo_name: Optional[str]=None) -> None:
        self.frontend_port = frontend_port
        self.rpd_file = rpd_file
        self.write_fdo_thumbnail = write_fdo_thumbnail
        self.use_thumbnail_cache = use_thumbnail_cache
        self.backup_full_file_names = backup_full_file_names
        self.fdo_name = fdo_name


class RenameAndMoveFileData:
    """
    Pass arguments to the renameandmovefile process
    """

    def __init__(self, rpd_file: RPDFile=None,
                 download_count: int=None,
                 download_succeeded: bool=None,
                 message: RenameAndMoveStatus=None) -> None:
        self.rpd_file = rpd_file
        self.download_count = download_count
        self.download_succeeded = download_succeeded
        self.message = message


class RenameAndMoveFileResults:
    def __init__(self, move_succeeded: bool=None,
                 rpd_file: RPDFile=None,
                 download_count: int=None,
                 stored_sequence_no: int=None,
                 downloads_today: List[str]=None,
                 problems: Optional[RenamingProblems]=None) -> None:
        self.move_succeeded = move_succeeded
        self.rpd_file = rpd_file
        self.download_count = download_count
        self.stored_sequence_no = stored_sequence_no
        self.downloads_today = downloads_today
        self.problems = problems


class OffloadData:
    def __init__(self, thumbnail_rows: Optional[Sequence[ThumbnailDataForProximity]]=None,
                 proximity_seconds: int=None,
                 rpd_files: Optional[Sequence[RPDFile]]=None,
                 strip_characters: Optional[bool]=None,
                 folders_preview: Optional[FoldersPreview]=None) -> None:
        self.thumbnail_rows = thumbnail_rows
        self.proximity_seconds = proximity_seconds
        self.rpd_files = rpd_files
        self.strip_characters = strip_characters
        self.folders_preview = folders_preview


class OffloadResults:
    def __init__(self, proximity_groups: Optional[TemporalProximityGroups]=None,
                 folders_preview: Optional[FoldersPreview]=None) -> None:
        self.proximity_groups = proximity_groups
        self.folders_preview = folders_preview


class BackupArguments:
    """
    Pass start up data to the back up process
    """
    def __init__(self, path: str, device_name: str) -> None:
        self.path = path
        self.device_name = device_name


class BackupFileData:
    """
    Pass file data to the backup process
    """
    def __init__(self, rpd_file: Optional[RPDFile]=None,
                 move_succeeded: Optional[bool]=None,
                 do_backup: Optional[bool]=None,
                 path_suffix: Optional[str]=None,
                 backup_duplicate_overwrite: Optional[bool]=None,
                 verify_file: Optional[bool]=None,
                 download_count: Optional[int]=None,
                 save_fdo_thumbnail: Optional[int]=None,
                 message: Optional[BackupStatus]=None) -> None:
        self.rpd_file = rpd_file
        self.move_succeeded = move_succeeded
        self.do_backup = do_backup
        self.path_suffix = path_suffix
        self.backup_duplicate_overwrite = backup_duplicate_overwrite
        self.verify_file = verify_file
        self.download_count = download_count
        self.save_fdo_thumbnail = save_fdo_thumbnail
        self.message = message


class BackupResults:
    def __init__(self, scan_id: int,
                 device_id: int,
                 total_downloaded: Optional[int]=None,
                 chunk_downloaded: Optional[int]=None,
                 backup_succeeded: Optional[bool]=None,
                 do_backup: Optional[bool]=None,
                 rpd_file: Optional[RPDFile] = None,
                 backup_full_file_name: Optional[str]=None,
                 mdata_exceptions: Optional[Tuple] = None,
                 problems: Optional[BackingUpProblems]=None) -> None:
        self.scan_id = scan_id
        self.device_id = device_id
        self.total_downloaded = total_downloaded
        self.chunk_downloaded = chunk_downloaded
        self.backup_succeeded = backup_succeeded
        self.do_backup = do_backup
        self.rpd_file = rpd_file
        self.backup_full_file_name = backup_full_file_name
        self.mdata_exceptions = mdata_exceptions
        self.problems = problems


class GenerateThumbnailsArguments:
    def __init__(self, scan_id: int,
                 rpd_files: List[RPDFile],
                 name: str,
                 proximity_seconds: int,
                 cache_dirs: CacheDirs,
                 need_video_cache_dir: bool,
                 frontend_port: int,
                 log_gphoto2: bool,
                 camera: Optional[str]=None,
                 port: Optional[str]=None,
                 entire_video_required: Optional[bool]=None) -> None:
        """
        List of files for which thumbnails are to be generated.
        All files  are assumed to have the same scan id.
        :param scan_id: id of the scan
        :param rpd_files: files from which to extract thumbnails
        :param name: name of the device
        :param proximity_seconds: the time elapsed between consecutive
         shots that is used to prioritize the order of thumbnail
         generation
        :param cache_dirs: the location where the cache directories
         should be created
        :param need_video_cache_dir: if True, must use cache dir
         to extract video thumbnail
        :param frontend_port: port to use to send to load balancer's
         front end
        :param log_gphoto2: if True, log libgphoto2 logging messages
        :param camera: If the thumbnails are being downloaded from a
         camera, this is the name of the camera, else None
        :param port: If the thumbnails are being downloaded from a
         camera, this is the port of the camera, else None
        :param entire_video_required:  if the entire video is
         required to extract the thumbnail
        """

        self.rpd_files = rpd_files
        self.scan_id = scan_id
        self.name = name
        self.proximity_seconds = proximity_seconds
        self.cache_dirs = cache_dirs
        self.need_video_cache_dir = need_video_cache_dir
        self.frontend_port = frontend_port
        if camera is not None:
            assert port is not None
            assert entire_video_required is not None
        self.camera = camera
        self.port = port
        self.log_gphoto2 = log_gphoto2
        self.entire_video_required = entire_video_required


class GenerateThumbnailsResults:
    def __init__(self, rpd_file: Optional[RPDFile]=None,
                 thumbnail_bytes: Optional[bytes]=None,
                 scan_id: Optional[int]=None,
                 cache_dirs: Optional[CacheDirs]=None) -> None:
        self.rpd_file = rpd_file
        # If thumbnail_bytes is None, there is no thumbnail
        self.thumbnail_bytes = thumbnail_bytes
        self.scan_id = scan_id
        self.cache_dirs = cache_dirs


class ThumbnailExtractorArgument:
    def __init__(self, rpd_file: RPDFile,
                 task: ExtractionTask,
                 processing: Set[ExtractionProcessing],
                 full_file_name_to_work_on: str,
                 secondary_full_file_name: str,
                 exif_buffer: Optional[bytearray],
                 thumbnail_bytes: bytes,
                 use_thumbnail_cache: bool,
                 file_to_work_on_is_temporary: bool,
                 write_fdo_thumbnail: bool,
                 send_thumb_to_main: bool) -> None:
        self.rpd_file = rpd_file
        self.task = task
        self.processing = processing
        self.full_file_name_to_work_on = full_file_name_to_work_on
        self.secondary_full_file_name = secondary_full_file_name
        self.file_to_work_on_is_temporary = file_to_work_on_is_temporary
        self.exif_buffer = exif_buffer
        self.thumbnail_bytes = thumbnail_bytes
        self.use_thumbnail_cache = use_thumbnail_cache
        self.write_fdo_thumbnail = write_fdo_thumbnail
        self.send_thumb_to_main = send_thumb_to_main


class RenameMoveFileManager(PushPullDaemonManager):
    """
    Manages the single instance daemon process that renames and moves
    files that have just been downloaded
    """

    message = pyqtSignal(bool, RPDFile, int)
    sequencesUpdate = pyqtSignal(int, list)
    renameProblems = pyqtSignal('PyQt_PyObject')

    def __init__(self, logging_port: int) -> None:
        super().__init__(logging_port=logging_port, thread_name=ThreadNames.rename)
        self._process_name = 'Rename and Move File Manager'
        self._process_to_run = 'renameandmovefile.py'

    def process_sink_data(self):
        data = pickle.loads(self.content)  # type: RenameAndMoveFileResults
        if data.move_succeeded is not None:

            self.message.emit(data.move_succeeded, data.rpd_file, data.download_count)

        elif data.problems is not None:
            self.renameProblems.emit(data.problems)
        else:
            assert data.stored_sequence_no is not None
            assert data.downloads_today is not None
            assert isinstance(data.downloads_today, list)
            self.sequencesUpdate.emit(data.stored_sequence_no, data.downloads_today)


class ThumbnailDaemonManager(PushPullDaemonManager):
    """
    Manages the process that extracts thumbnails after the file
    has already been downloaded and that writes FreeDesktop.org
    thumbnails. Not to be confused with ThumbnailManagerPara, which
    manages thumbnailing using processes that run in parallel,
    one for each device.
    """

    message = pyqtSignal(RPDFile, QPixmap)

    def __init__(self, logging_port: int) -> None:
        super().__init__(logging_port=logging_port, thread_name=ThreadNames.thumbnail_daemon)
        self._process_name = 'Thumbnail Daemon Manager'
        self._process_to_run = 'thumbnaildaemon.py'

    def process_sink_data(self) -> None:
        data = pickle.loads(self.content) # type: GenerateThumbnailsResults
        if data.thumbnail_bytes is None:
            thumbnail = QPixmap()
        else:
            thumbnail = QImage.fromData(data.thumbnail_bytes)
            if thumbnail.isNull():
                thumbnail = QPixmap()
            else:
                thumbnail = QPixmap.fromImage(thumbnail)
        self.message.emit(data.rpd_file, thumbnail)


class OffloadManager(PushPullDaemonManager):
    """
    Handles tasks best run in a separate process
    """

    message = pyqtSignal(TemporalProximityGroups)
    downloadFolders = pyqtSignal(FoldersPreview)

    def __init__(self, logging_port: int) -> None:
        super().__init__(logging_port=logging_port, thread_name=ThreadNames.offload)
        self._process_name = 'Offload Manager'
        self._process_to_run = 'offload.py'

    def process_sink_data(self) -> None:
        data = pickle.loads(self.content)  # type: OffloadResults
        if data.proximity_groups is not None:
            self.message.emit(data.proximity_groups)
        elif data.folders_preview is not None:
            self.downloadFolders.emit(data.folders_preview)


class ScanManager(PublishPullPipelineManager):
    """
    Handles the processes that scan devices (cameras, external devices,
    this computer path)
    """
    scannedFiles = pyqtSignal(
        'PyQt_PyObject', 'PyQt_PyObject', FileTypeCounter, 'PyQt_PyObject', bool
    )
    deviceError = pyqtSignal(int, CameraErrorCode)
    deviceDetails = pyqtSignal(int, 'PyQt_PyObject', 'PyQt_PyObject', str)
    scanProblems = pyqtSignal(int, 'PyQt_PyObject')
    fatalError = pyqtSignal(int)

    def __init__(self, logging_port: int) -> None:
        super().__init__(logging_port=logging_port, thread_name=ThreadNames.scan)
        self._process_name = 'Scan Manager'
        self._process_to_run = 'scan.py'

    def process_sink_data(self) -> None:
        data = pickle.loads(self.content)  # type: ScanResults
        if data.rpd_files is not None:
            assert data.file_type_counter
            assert data.file_size_sum
            assert data.entire_video_required is not None
            self.scannedFiles.emit(
                data.rpd_files,
                (data.sample_photo, data.sample_video),
                data.file_type_counter,
                data.file_size_sum,
                data.entire_video_required
            )
        else:
            assert data.scan_id is not None
            if data.error_code is not None:
                self.deviceError.emit(data.scan_id, data.error_code)
            elif data.optimal_display_name is not None:
                self.deviceDetails.emit(
                    data.scan_id, data.storage_space, data.storage_descriptions,
                    data.optimal_display_name
                )
            elif data.problems is not None:
                self.scanProblems.emit(data.scan_id, data.problems)
            else:
                assert data.fatal_error
                self.fatalError.emit(data.scan_id)


class BackupManager(PublishPullPipelineManager):
    """
    Each backup "device" (it could be an external drive, or a user-
    specified path on the local file system) has associated with it one
    worker process. For example if photos and videos are both being
    backed up to the same external hard drive, one worker process
    handles both the photos and the videos. However if photos are being
    backed up to one drive, and videos to another, there would be a
    worker process for each drive (2 in total).
    """
    message = pyqtSignal(int, bool, bool, RPDFile, str, 'PyQt_PyObject')
    bytesBackedUp = pyqtSignal('PyQt_PyObject', 'PyQt_PyObject')
    backupProblems = pyqtSignal(int, 'PyQt_PyObject')

    def __init__(self, logging_port: int) -> None:
        super().__init__(logging_port=logging_port, thread_name=ThreadNames.backup)
        self._process_name = 'Backup Manager'
        self._process_to_run = 'backupfile.py'

    def process_sink_data(self) -> None:
        data = pickle.loads(self.content) # type: BackupResults
        if data.total_downloaded is not None:
            assert data.scan_id is not None
            assert data.chunk_downloaded >= 0
            assert data.total_downloaded >= 0
            self.bytesBackedUp.emit(data.scan_id, data.chunk_downloaded)
        elif data.backup_succeeded is not None:
            assert data.do_backup is not None
            assert data.rpd_file is not None
            self.message.emit(
                data.device_id, data.backup_succeeded, data.do_backup, data.rpd_file,
                data.backup_full_file_name, data.mdata_exceptions
            )
        else:
            assert data.problems is not None
            self.backupProblems.emit(data.device_id, data.problems)


class CopyFilesManager(PublishPullPipelineManager):
    """
    Manage the processes that copy files from devices to the computer
    during the download process
    """

    message = pyqtSignal(bool, RPDFile, int, 'PyQt_PyObject')
    tempDirs = pyqtSignal(int, str,str)
    bytesDownloaded = pyqtSignal(int, 'PyQt_PyObject', 'PyQt_PyObject')
    copyProblems = pyqtSignal(int, 'PyQt_PyObject')

    def __init__(self, logging_port: int) -> None:
        super().__init__(logging_port=logging_port, thread_name=ThreadNames.copy)
        self._process_name = 'Copy Files Manager'
        self._process_to_run = 'copyfiles.py'

    def process_sink_data(self) -> None:
        data = pickle.loads(self.content) # type: CopyFilesResults
        if data.total_downloaded is not None:
            assert data.scan_id is not None
            if data.chunk_downloaded < 0:
                logging.critical("Chunk downloaded is less than zero: %s", data.chunk_downloaded)
            if data.total_downloaded < 0:
                logging.critical("Chunk downloaded is less than zero: %s", data.total_downloaded)

            self.bytesDownloaded.emit(data.scan_id, data.total_downloaded, data.chunk_downloaded)

        elif data.copy_succeeded is not None:
            assert data.rpd_file is not None
            assert data.download_count is not None
            self.message.emit(
                data.copy_succeeded, data.rpd_file, data.download_count, data.mdata_exceptions
            )

        elif data.problems is not None:
            self.copyProblems.emit(data.scan_id, data.problems)

        else:
            assert (data.photo_temp_dir is not None and
                    data.video_temp_dir is not None)
            assert data.scan_id is not None
            self.tempDirs.emit(data.scan_id, data.photo_temp_dir, data.video_temp_dir)