~apport-hackers/apport/main

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
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
"""Crash database implementation for Launchpad."""

# Copyright (C) 2007 - 2009 Canonical Ltd.
# Authors: Martin Pitt <martin.pitt@ubuntu.com>
#          Markus Korn <thekorn@gmx.de>
#
# This program 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 2 of the License, or (at your
# option) any later version.  See http://www.gnu.org/copyleft/gpl.html for
# the full text of the license.

import atexit
import email
import gzip
import http.client
import io
import os.path
import re
import shutil
import sys
import tempfile
import time
import urllib.parse
import urllib.request

from httplib2 import FailedToDecompressContent

try:
    from launchpadlib.errors import HTTPError, RestfulError
    from launchpadlib.launchpad import Launchpad
except ImportError:
    # if launchpadlib is not available, only client-side reporting will work
    Launchpad = None

import apport
import apport.crashdb

default_credentials_path = os.path.expanduser(
    "~/.cache/apport/launchpad.credentials"
)


def filter_filename(attachments):
    for attachment in attachments:
        try:
            f = attachment.data.open()
        except (HTTPError, FailedToDecompressContent):
            apport.error("Broken attachment on bug, ignoring")
            continue
        name = f.filename
        if name.endswith(".txt") or name.endswith(".gz"):
            yield f


def id_set(tasks):
    # same as set(int(i.bug.id) for i in tasks) but faster
    return set(int(i.self_link.split("/").pop()) for i in tasks)


class CrashDatabase(apport.crashdb.CrashDatabase):
    """Launchpad implementation of crash database interface."""

    def __init__(self, auth, options):
        """Initialize Launchpad crash database.

        You need to specify a launchpadlib-style credentials file to
        access launchpad. If you supply None, it will use
        default_credentials_path (~/.cache/apport/launchpad.credentials).

        Recognized options are:
        - distro: Name of the distribution in Launchpad
        - project: Name of the project in Launchpad
          (Note that exactly one of "distro" or "project" must be given.)
        - launchpad_instance: If set, this uses the given launchpad instance
          instead of production (optional). This can be overriden or set by
          $APPORT_LAUNCHPAD_INSTANCE environment. For example: "qastaging" or
          "staging".
        - cache_dir: Path to a permanent cache directory; by default it uses a
          temporary one. (optional). This can be overridden or set by
          $APPORT_LAUNCHPAD_CACHE environment.
        - escalation_subscription: This subscribes the given person or team to
          a bug once it gets the 10th duplicate.
        - escalation_tag: This adds the given tag to a bug once it gets more
          than 10 duplicates.
        - initial_subscriber: The Launchpad user which gets subscribed to newly
          filed bugs (default: "apport"). It should be a bot user which the
          crash-digger instance runs as, as this will get to see all bug
          details immediately.
        - triaging_team: The Launchpad user/team which gets subscribed after
          updating a crash report bug by the retracer (default:
          "ubuntu-crashes-universe")
        - architecture: If set, this sets and watches out for needs-*-retrace
          tags of this architecture. This is useful when being used with
          apport-retrace and crash-digger to process crash reports of foreign
          architectures. Defaults to system architecture.
        """
        if os.getenv("APPORT_LAUNCHPAD_INSTANCE"):
            options["launchpad_instance"] = os.getenv(
                "APPORT_LAUNCHPAD_INSTANCE"
            )
        if not auth:
            lp_instance = options.get("launchpad_instance")
            if lp_instance:
                auth = (
                    default_credentials_path
                    + "."
                    + lp_instance.split("://", 1)[-1]
                )
            else:
                auth = default_credentials_path
        apport.crashdb.CrashDatabase.__init__(self, auth, options)

        self.distro = options.get("distro")
        if self.distro:
            assert (
                "project" not in options
            ), 'Must not set both "project" and "distro" option'
        else:
            assert (
                "project" in options
            ), 'Need to have either "project" or "distro" option'

        if "architecture" in options:
            self.arch_tag = "need-%s-retrace" % options["architecture"]
        else:
            self.arch_tag = (
                "need-%s-retrace" % apport.packaging.get_system_architecture()
            )
        self.options = options
        self.auth = auth
        assert self.auth

        self.__launchpad = None
        self.__lp_distro = None
        self.__lpcache = os.getenv(
            "APPORT_LAUNCHPAD_CACHE", options.get("cache_dir")
        )
        if not self.__lpcache:
            # use a temporary dir
            self.__lpcache = tempfile.mkdtemp(prefix="launchpadlib.cache.")
            atexit.register(shutil.rmtree, self.__lpcache, ignore_errors=True)

    @property
    def launchpad(self):
        """Return Launchpad instance."""

        if self.__launchpad:
            return self.__launchpad

        if Launchpad is None:
            sys.stderr.write(
                "ERROR: The launchpadlib Python %s module is not installed."
                " Please install the python3-launchpadlib package!\n"
                % sys.version[0]
            )
            sys.exit(1)

        if self.options.get("launchpad_instance"):
            launchpad_instance = self.options.get("launchpad_instance")
        else:
            launchpad_instance = "production"

        auth_dir = os.path.dirname(self.auth)
        if auth_dir and not os.path.isdir(auth_dir):
            os.makedirs(auth_dir)

        try:
            self.__launchpad = Launchpad.login_with(
                "apport-collect",
                launchpad_instance,
                launchpadlib_dir=self.__lpcache,
                allow_access_levels=["WRITE_PRIVATE"],
                credentials_file=self.auth,
                version="1.0",
            )
        except (RestfulError, OSError, ValueError) as error:
            apport.error(
                "connecting to Launchpad failed: %s\n"
                'You can reset the credentials by removing the file "%s"',
                getattr(error, "content", str(error)),
                self.auth,
            )
            sys.exit(99)  # transient error

        return self.__launchpad

    def _get_distro_tasks(self, tasks):
        if not self.distro:
            return

        for t in tasks:
            if t.bug_target_name.lower() == self.distro or re.match(
                r"^.+\(%s.*\)$" % self.distro, t.bug_target_name.lower()
            ):
                yield t

    @property
    def lp_distro(self):
        if self.__lp_distro is None:
            if self.distro:
                self.__lp_distro = self.launchpad.distributions[self.distro]
            elif "project" in self.options:
                self.__lp_distro = self.launchpad.projects[
                    self.options["project"]
                ]
            else:
                raise SystemError(
                    "distro or project needs to be specified"
                    " in crashdb options"
                )

        return self.__lp_distro

    def upload(self, report, progress_callback=None):
        """Upload given problem report return a handle for it.

        This should happen noninteractively.

        If the implementation supports it, and a function progress_callback is
        passed, that is called repeatedly with two arguments: the number of
        bytes already sent, and the total number of bytes to send. This can be
        used to provide a proper upload progress indication on frontends.
        """
        assert self.accepts(report)

        blob_file = self._generate_upload_blob(report)
        ticket = upload_blob(
            blob_file, progress_callback, hostname=self.get_hostname()
        )
        blob_file.close()
        assert ticket
        return ticket

    def get_hostname(self):
        """Return the hostname for the Launchpad instance."""

        launchpad_instance = self.options.get("launchpad_instance")
        if launchpad_instance:
            if launchpad_instance == "qastaging":
                hostname = "qastaging.launchpad.net"
            elif launchpad_instance == "staging":
                hostname = "staging.launchpad.net"
            else:
                hostname = "launchpad.dev"
        else:
            hostname = "launchpad.net"
        return hostname

    def get_comment_url(self, report, handle):
        """Return an URL that should be opened after report has been uploaded
        and upload() returned handle.

        Should return None if no URL should be opened (anonymous filing without
        user comments); in that case this function should do whichever
        interactive steps it wants to perform."""

        args = {}
        title = report.get("Title", report.standard_title())
        if title:
            args["field.title"] = title

        hostname = self.get_hostname()

        if "SnapSource" in report:
            project = report["SnapSource"]
        else:
            project = self.options.get("project")

        if not project:
            if "SourcePackage" in report:
                return "https://bugs.%s/%s/+source/%s/+filebug/%s?%s" % (
                    hostname,
                    self.distro,
                    report["SourcePackage"],
                    handle,
                    urllib.parse.urlencode(args),
                )
            else:
                return "https://bugs.%s/%s/+filebug/%s?%s" % (
                    hostname,
                    self.distro,
                    handle,
                    urllib.parse.urlencode(args),
                )
        else:
            return "https://bugs.%s/%s/+filebug/%s?%s" % (
                hostname,
                project,
                handle,
                urllib.parse.urlencode(args),
            )

    def get_id_url(self, report, crash_id):
        """Return URL for a given report ID.

        The report is passed in case building the URL needs additional
        information from it, such as the SourcePackage name.

        Return None if URL is not available or cannot be determined.
        """
        return "https://bugs.launchpad.net/bugs/" + str(crash_id)

    def download(self, crash_id):
        """Download the problem report from given ID and return a Report."""

        report = apport.Report()
        b = self.launchpad.bugs[crash_id]

        # parse out fields from summary
        m = re.search(r"(ProblemType:.*)$", b.description, re.S)
        if not m:
            m = re.search(r"^--- \r?$[\r\n]*(.*)", b.description, re.M | re.S)
        assert m, "bug description must contain standard apport format data"

        description = (
            m.group(1)
            .encode("UTF-8")
            .replace(b"\xc2\xa0", b" ")
            .replace(b"\r\n", b"\n")
        )

        if b"\n\n" in description:
            # this often happens, remove all empty lines between top and
            # 'Uname'
            if b"Uname:" in description:
                # this will take care of bugs like LP #315728 where stuff
                # is added after the apport data
                (part1, part2) = description.split(b"Uname:", 1)
                description = (
                    part1.replace(b"\n\n", b"\n")
                    + b"Uname:"
                    + part2.split(b"\n\n", 1)[0]
                )
            else:
                # just parse out the Apport block; e. g. LP #269539
                description = description.split(b"\n\n", 1)[0]

        report.load(io.BytesIO(description))

        if "Date" not in report:
            # We had not submitted this field for a while, claiming it
            # redundant. But it is indeed required for up-to-the-minute
            # comparison with log files, etc. For backwards compatibility with
            # those reported bugs, read the creation date
            try:
                report["Date"] = b.date_created.ctime()
            except AttributeError:
                # support older wadllib API which returned strings
                report["Date"] = b.date_created
        if "ProblemType" not in report:
            if "apport-bug" in b.tags:
                report["ProblemType"] = "Bug"
            elif "apport-crash" in b.tags:
                report["ProblemType"] = "Crash"
            elif "apport-kernelcrash" in b.tags:
                report["ProblemType"] = "KernelCrash"
            elif "apport-package" in b.tags:
                report["ProblemType"] = "Package"
            else:
                raise ValueError(
                    "cannot determine ProblemType from tags: " + str(b.tags)
                )

        report["Tags"] = " ".join(b.tags)

        if "Title" in report:
            report["OriginalTitle"] = report["Title"]

        report["Title"] = b.title

        for attachment in filter_filename(b.attachments):
            key, ext = os.path.splitext(attachment.filename)
            # ignore attachments with invalid keys
            try:
                report[key] = ""
            except (AssertionError, TypeError, ValueError):
                continue
            if ext == ".txt":
                report[key] = attachment.read()
                try:
                    report[key] = report[key].decode("UTF-8")
                except UnicodeDecodeError:
                    pass
            elif ext == ".gz":
                try:
                    report[key] = gzip.GzipFile(fileobj=attachment).read()
                except OSError as error:
                    # some attachments are only called .gz, but are
                    # uncompressed (LP #574360)
                    if "Not a gzip" not in str(error):
                        raise
                    attachment.seek(0)
                    report[key] = attachment.read()
            else:
                raise Exception(
                    "Unknown attachment type: " + attachment.filename
                )
        return report

    def update(
        self,
        crash_id,
        report,
        comment,
        change_description=False,
        attachment_comment=None,
        key_filter=None,
    ):
        """Update the given report ID with all data from report.

        This creates a text comment with the "short" data (see
        ProblemReport.write_mime()), and creates attachments for all the
        bulk/binary data.

        If change_description is True, and the crash db implementation supports
        it, the short data will be put into the description instead (like in a
        new bug).

        comment will be added to the "short" data. If attachment_comment is
        given, it will be added to the attachment uploads.

        If key_filter is a list or set, then only those keys will be added.
        """
        bug = self.launchpad.bugs[crash_id]

        # TODO: raise an error if key_filter is not a list or set
        if key_filter:
            skip_keys = set(report.keys()) - set(key_filter)
        else:
            skip_keys = None

        # we want to reuse the knowledge of write_mime() with all its
        # different input types and output formatting; however, we have to
        # dissect the mime ourselves, since we can't just upload it as a blob
        with tempfile.TemporaryFile() as mime:
            report.write_mime(mime, skip_keys=skip_keys)
            mime.flush()
            mime.seek(0)
            msg = email.message_from_binary_file(mime)
            msg_iter = msg.walk()

            # first part is the multipart container
            part = next(msg_iter)
            assert part.is_multipart()

            # second part should be an inline text/plain attachments with
            # all short fields
            part = next(msg_iter)
            assert not part.is_multipart()
            assert part.get_content_type() == "text/plain"

            if not key_filter:
                # when we update a complete report, we are updating
                # an existing bug with apport-collect
                x = bug.tags[:]  # LP#254901 workaround
                x.append("apport-collected")
                # add any tags (like the release) to the bug
                if "Tags" in report:
                    x += self._filter_tag_names(report["Tags"]).split()
                bug.tags = x
                bug.lp_save()
                # fresh bug object, LP#336866 workaround
                bug = self.launchpad.bugs[crash_id]

            # short text data
            text = part.get_payload(decode=True).decode("UTF-8", "replace")
            # text can be empty if you are only adding an attachment to a bug
            if text:
                if change_description:
                    bug.description = bug.description + "\n--- \n" + text
                    bug.lp_save()
                else:
                    if not comment:
                        comment = bug.title
                    bug.newMessage(content=text, subject=comment)

            # other parts are the attachments:
            for part in msg_iter:
                bug.addAttachment(
                    comment=attachment_comment or "",
                    description=part.get_filename(),
                    content_type=None,
                    data=part.get_payload(decode=True),
                    filename=part.get_filename(),
                    is_patch=False,
                )

    def update_traces(self, crash_id, report, comment=""):
        """Update the given report ID for retracing results.

        This updates Stacktrace, ThreadStacktrace, StacktraceTop,
        and StacktraceSource. You can also supply an additional comment.
        """
        apport.crashdb.CrashDatabase.update_traces(
            self, crash_id, report, comment
        )

        bug = self.launchpad.bugs[crash_id]
        # ensure it's assigned to a package
        if "SourcePackage" in report:
            for task in bug.bug_tasks:
                if task.target.resource_type_link.endswith("#distribution"):
                    task.target = self.lp_distro.getSourcePackage(
                        name=report["SourcePackage"]
                    )
                    task.lp_save()
                    bug = self.launchpad.bugs[crash_id]
                    break

        # remove core dump if stack trace is usable
        if report.has_useful_stacktrace():
            for a in bug.attachments:
                if a.title == "CoreDump.gz":
                    try:
                        a.removeFromBug()
                    except HTTPError:
                        pass  # LP#249950 workaround
            try:
                task = self._get_distro_tasks(bug.bug_tasks)
                task = next(task)
                if task.importance == "Undecided":
                    task.importance = "Medium"
                    task.lp_save()
            except StopIteration:
                pass  # no distro tasks

            # update bug title with retraced function name
            fn = report.stacktrace_top_function()
            if fn:
                m = re.match(
                    r"^(.*crashed with SIG.* in )([^( ]+)(\(\).*$)", bug.title
                )
                if m and m.group(2) != fn:
                    bug.title = m.group(1) + fn + m.group(3)
                    try:
                        bug.lp_save()
                    except HTTPError:
                        pass  # LP#336866 workaround
                    bug = self.launchpad.bugs[crash_id]

        self._subscribe_triaging_team(bug, report)

    def get_distro_release(self, crash_id):
        """Get 'DistroRelease: <release>' from the given report ID and return
        it."""
        bug = self.launchpad.bugs[crash_id]
        m = re.search("DistroRelease: ([-a-zA-Z0-9.+/ ]+)", bug.description)
        if m:
            return m.group(1)
        raise ValueError("URL does not contain DistroRelease: field")

    def get_affected_packages(self, crash_id):
        """Return list of affected source packages for given ID."""

        bug_target_re = re.compile(
            r"/%s/(?:(?P<suite>[^/]+)/)?\+source/(?P<source>[^/]+)$"
            % self.distro
        )

        bug = self.launchpad.bugs[crash_id]
        result = []

        for task in bug.bug_tasks:
            match = bug_target_re.search(task.target.self_link)
            if not match:
                continue
            if task.status in ("Invalid", "Won't Fix", "Fix Released"):
                continue
            result.append(match.group("source"))
        return result

    def is_reporter(self, crash_id):
        """Check whether the user is the reporter of given ID."""

        bug = self.launchpad.bugs[crash_id]
        return bug.owner.name == self.launchpad.me.name

    def can_update(self, crash_id):
        """Check whether the user is eligible to update a report.

        A user should add additional information to an existing ID if (s)he is
        the reporter or subscribed, the bug is open, not a duplicate, etc. The
        exact policy and checks should be done according to the particular
        implementation.
        """
        bug = self.launchpad.bugs[crash_id]
        if bug.duplicate_of:
            return False

        if bug.owner.name == self.launchpad.me.name:
            return True

        # check subscription
        me = self.launchpad.me.self_link
        for sub in bug.subscriptions.entries:
            if sub["person_link"] == me:
                return True

        return False

    def get_unretraced(self):
        """Return an ID set of all crashes which have not been retraced yet and
        which happened on the current host architecture."""
        try:
            bugs = self.lp_distro.searchTasks(
                tags=self.arch_tag, created_since="2011-08-01"
            )
            return id_set(bugs)
        except HTTPError as error:
            apport.error("connecting to Launchpad failed: %s", str(error))
            sys.exit(99)  # transient error

    def get_dup_unchecked(self):
        """Return an ID set of all crashes which have not been checked for
        being a duplicate.

        This is mainly useful for crashes of scripting languages such as
        Python, since they do not need to be retraced. It should not return
        bugs that are covered by get_unretraced()."""

        try:
            bugs = self.lp_distro.searchTasks(
                tags="need-duplicate-check", created_since="2011-08-01"
            )
            return id_set(bugs)
        except HTTPError as error:
            apport.error("connecting to Launchpad failed: %s", str(error))
            sys.exit(99)  # transient error

    def get_unfixed(self):
        """Return an ID set of all crashes which are not yet fixed.

        The list must not contain bugs which were rejected or duplicate.

        This function should make sure that the returned list is correct. If
        there are any errors with connecting to the crash database, it should
        raise an exception (preferably OSError)."""

        bugs = self.lp_distro.searchTasks(tags="apport-crash")
        return id_set(bugs)

    def _get_source_version(self, package):
        """Return the version of given source package in the latest release of
        given distribution.

        If 'distro' is None, we will look for a launchpad project .
        """
        sources = self.lp_distro.main_archive.getPublishedSources(
            exact_match=True,
            source_name=package,
            distro_series=self.lp_distro.current_series,
        )
        # first element is the latest one
        return sources[0].source_package_version

    def get_fixed_version(self, crash_id):
        """Return the package version that fixes a given crash.

        Return None if the crash is not yet fixed, or an empty string if the
        crash is fixed, but it cannot be determined by which version. Return
        'invalid' if the crash report got invalidated, such as closed a
        duplicate or rejected.

        This function should make sure that the returned result is correct. If
        there are any errors with connecting to the crash database, it should
        raise an exception (preferably OSError).
        """
        # do not do version tracking yet; for that, we need to get the current
        # distrorelease and the current package version in that distrorelease
        # (or, of course, proper version tracking in Launchpad itself)

        try:
            b = self.launchpad.bugs[crash_id]
        except KeyError:
            return "invalid"

        if b.duplicate_of:
            return "invalid"

        tasks = list(b.bug_tasks)  # just fetch it once

        if self.distro:
            distro_identifier = "(%s)" % self.distro.lower()
            fixed_tasks = list(
                filter(
                    lambda task: task.status == "Fix Released"
                    and distro_identifier
                    in task.bug_target_display_name.lower(),
                    tasks,
                )
            )

            if not fixed_tasks:
                fixed_distro = list(
                    filter(
                        lambda task: task.status == "Fix Released"
                        and task.bug_target_name.lower()
                        == self.distro.lower(),
                        tasks,
                    )
                )
                if fixed_distro:
                    # fixed in distro inself (without source package)
                    return ""

            if len(fixed_tasks) > 1:
                apport.warning(
                    "There is more than one task fixed in %s %s,"
                    " using first one to determine fixed version",
                    self.distro,
                    crash_id,
                )
                return ""

            if fixed_tasks:
                task = fixed_tasks.pop()
                try:
                    return self._get_source_version(
                        task.bug_target_display_name.split()[0]
                    )
                except IndexError:
                    # source does not exist any more
                    return "invalid"
            else:
                # check if there only invalid ones
                invalid_tasks = list(
                    filter(
                        lambda task: task.status
                        in ("Invalid", "Won't Fix", "Expired")
                        and distro_identifier
                        in task.bug_target_display_name.lower(),
                        tasks,
                    )
                )
                if invalid_tasks:
                    non_invalid_tasks = list(
                        filter(
                            lambda task: task.status
                            not in ("Invalid", "Won't Fix", "Expired")
                            and distro_identifier
                            in task.bug_target_display_name.lower(),
                            tasks,
                        )
                    )
                    if not non_invalid_tasks:
                        return "invalid"
        else:
            fixed_tasks = list(
                filter(lambda task: task.status == "Fix Released", tasks)
            )
            if fixed_tasks:
                # TODO: look for current series
                return ""
            # check if there any invalid ones
            if list(filter(lambda task: task.status == "Invalid", tasks)):
                return "invalid"

        return None

    def duplicate_of(self, crash_id):
        """Return master ID for a duplicate bug.

        If the bug is not a duplicate, return None.
        """
        b = self.launchpad.bugs[crash_id].duplicate_of
        if b:
            return b.id
        else:
            return None

    def close_duplicate(self, report, crash_id, master_id):
        """Mark a crash id as duplicate of given master ID.

        If master is None, id gets un-duplicated.
        """
        bug = self.launchpad.bugs[crash_id]

        if master_id:
            assert (
                crash_id != master_id
            ), "cannot mark bug %s as a duplicate of itself" % str(crash_id)

            # check whether the master itself is a dup
            master = self.launchpad.bugs[master_id]
            if master.duplicate_of:
                master = master.duplicate_of
                master_id = master.id
                if master.id == crash_id:
                    # this happens if the bug was manually duped to a newer one
                    apport.warning(
                        "Bug %i was manually marked as a dupe of newer bug %i,"
                        " not closing as duplicate",
                        crash_id,
                        master_id,
                    )
                    return

            for a in bug.attachments:
                if a.title in (
                    "CoreDump.gz",
                    "Stacktrace.txt",
                    "ThreadStacktrace.txt",
                    "ProcMaps.txt",
                    "ProcStatus.txt",
                    "Registers.txt",
                    "Disassembly.txt",
                ):
                    try:
                        a.removeFromBug()
                    except HTTPError:
                        pass  # LP#249950 workaround

            # fresh bug object, LP#336866 workaround
            bug = self.launchpad.bugs[crash_id]
            bug.newMessage(
                content="Thank you for taking the time to report this crash"
                " and helping to make this software better.  This particular"
                " crash has already been reported and is a duplicate of bug"
                " #%i, so is being marked as such.  Please look at the other"
                " bug report to see if there is any missing information that"
                " you can provide, or to see if there is a workaround for the"
                " bug.  Additionally, any further discussion regarding the bug"
                " should occur in the other report.  Please continue to report"
                " any other bugs you may find." % master_id,
                subject="This bug is a duplicate",
            )

            # refresh, LP#336866 workaround
            bug = self.launchpad.bugs[crash_id]
            if bug.private:
                bug.private = False

            # set duplicate last, since we cannot modify already dup'ed bugs
            if not bug.duplicate_of:
                bug.duplicate_of = master

            # cache tags of master bug report instead of performing multiple
            # queries
            master_tags = master.tags

            if len(master.duplicates) == 10:
                if (
                    "escalation_tag" in self.options
                    and self.options["escalation_tag"] not in master_tags
                    and self.options.get("escalated_tag", " invalid ")
                    not in master_tags
                ):
                    master.tags = master_tags + [
                        self.options["escalation_tag"]
                    ]  # LP#254901 workaround
                    master.lp_save()

                if (
                    "escalation_subscription" in self.options
                    and self.options.get("escalated_tag", " invalid ")
                    not in master_tags
                ):
                    p = self.launchpad.people[
                        self.options["escalation_subscription"]
                    ]
                    master.subscribe(person=p)

            # requesting updated stack trace?
            if report.has_useful_stacktrace() and (
                "apport-request-retrace" in master_tags
                or "apport-failed-retrace" in master_tags
            ):
                self.update(
                    master_id,
                    report,
                    "Updated stack trace from duplicate bug %i" % crash_id,
                    key_filter=[
                        "Stacktrace",
                        "ThreadStacktrace",
                        "Package",
                        "Dependencies",
                        "ProcMaps",
                        "ProcCmdline",
                    ],
                )

                master = self.launchpad.bugs[master_id]
                x = master.tags[:]  # LP#254901 workaround
                try:
                    x.remove("apport-failed-retrace")
                except ValueError:
                    pass
                try:
                    x.remove("apport-request-retrace")
                except ValueError:
                    pass
                master.tags = x
                try:
                    master.lp_save()
                except HTTPError:
                    pass  # LP#336866 workaround

            # white list of tags to copy from duplicates bugs to the master
            tags_to_copy = ["bugpattern-needed"]
            for series in self.lp_distro.series:
                if series.status not in [
                    "Active Development",
                    "Current Stable Release",
                    "Supported",
                    "Pre-release Freeze",
                ]:
                    continue
                tags_to_copy.append(series.name)
            # copy tags over from the duplicate bug to the master bug
            dupe_tags = set(bug.tags)
            # reload master tags as they may have changed
            master_tags = master.tags
            missing_tags = dupe_tags.difference(master_tags)

            for tag in missing_tags:
                if tag in tags_to_copy:
                    master_tags.append(tag)

            master.tags = master_tags
            master.lp_save()

        else:
            if bug.duplicate_of:
                bug.duplicate_of = None

        # pylint: disable=protected-access
        if bug._dirty_attributes:  # LP#336866 workaround
            bug.lp_save()

    def mark_regression(self, crash_id, master):
        """Mark a crash id as reintroducing an earlier crash which is
        already marked as fixed (having ID 'master')."""

        bug = self.launchpad.bugs[crash_id]
        bug.newMessage(
            content="This crash has the same stack trace characteristics as"
            " bug #%i. However, the latter was already fixed in an earlier"
            " package version than the one in this report. This might be"
            " a regression or because the problem is in a dependent package."
            % master,
            subject="Possible regression detected",
        )
        # fresh bug object, LP#336866 workaround
        bug = self.launchpad.bugs[crash_id]
        bug.tags = bug.tags + ["regression-retracer"]  # LP#254901 workaround
        bug.lp_save()

    def mark_retraced(self, crash_id):
        """Mark crash id as retraced."""

        bug = self.launchpad.bugs[crash_id]
        if self.arch_tag in bug.tags:
            x = bug.tags[:]  # LP#254901 workaround
            x.remove(self.arch_tag)
            bug.tags = x
            try:
                bug.lp_save()
            except HTTPError:
                pass  # LP#336866 workaround

    def mark_retrace_failed(self, crash_id, invalid_msg=None):
        """Mark crash id as 'failed to retrace'."""

        bug = self.launchpad.bugs[crash_id]
        if invalid_msg:
            try:
                task = self._get_distro_tasks(bug.bug_tasks)
                task = next(task)
            except StopIteration:
                # no distro task, just use the first one
                task = bug.bug_tasks[0]
            task.status = "Invalid"
            task.lp_save()
            bug.newMessage(
                content=invalid_msg, subject="Crash report cannot be processed"
            )

            for a in bug.attachments:
                if a.title == "CoreDump.gz":
                    try:
                        a.removeFromBug()
                    except HTTPError:
                        pass  # LP#249950 workaround
        else:
            if "apport-failed-retrace" not in bug.tags:
                # LP#254901 workaround
                bug.tags = bug.tags + ["apport-failed-retrace"]
                bug.lp_save()

    def _mark_dup_checked(self, crash_id, report):
        """Mark crash id as checked for being a duplicate."""

        bug = self.launchpad.bugs[crash_id]

        # if we have a distro task without a package, fix it
        if "SourcePackage" in report:
            for task in bug.bug_tasks:
                if task.target.resource_type_link.endswith("#distribution"):
                    task.target = self.lp_distro.getSourcePackage(
                        name=report["SourcePackage"]
                    )
                    try:
                        task.lp_save()
                        bug = self.launchpad.bugs[crash_id]
                    except HTTPError:
                        # might fail if there is already another
                        # Ubuntu package task
                        pass
                    break

        if "need-duplicate-check" in bug.tags:
            x = bug.tags[:]  # LP#254901 workaround
            x.remove("need-duplicate-check")
            bug.tags = x
            bug.lp_save()
            if "Traceback" in report:
                for task in bug.bug_tasks:
                    if "#distribution" in task.target.resource_type_link:
                        if task.importance == "Undecided":
                            task.importance = "Medium"
                            task.lp_save()
        self._subscribe_triaging_team(bug, report)

    def known(self, report):
        """Check if the crash db already knows about the crash signature.

        Check if the report has a DuplicateSignature, crash_signature(), or
        StacktraceAddressSignature, and ask the database whether the problem is
        already known. If so, return an URL where the user can check the status
        or subscribe (if available), or just return True if the report is known
        but there is no public URL. In that case the report will not be
        uploaded (i. e. upload() will not be called).

        Return None if the report does not have any signature or the crash
        database does not support checking for duplicates on the client side.

        The default implementation uses a text file format generated by
        duplicate_db_publish() at an URL specified by the "dupdb_url" option.
        Subclasses are free to override this with a custom implementation, such
        as a real database lookup.
        """
        # we override the method here to check if the user actually has access
        # to the bug, and if the bug requests more retraces; in either case we
        # should file it.
        url = apport.crashdb.CrashDatabase.known(self, report)

        if not url:
            return url

        # record the fact that it is a duplicate, for triagers
        report["DuplicateOf"] = url

        try:
            with urllib.request.urlopen(url + "/+text") as f:
                line = f.readline()
                if not line.startswith(b"bug:"):
                    # presumably a 404 etc. page,
                    # which happens for private bugs
                    return True

                # check tags
                for line in f:
                    if line.startswith(b"tags:"):
                        if (
                            b"apport-failed-retrace" in line
                            or b"apport-request-retrace" in line
                        ):
                            return None
                        else:
                            break

                    # stop at the first task, tags are in the first block
                    if not line.strip():
                        break
        except OSError:
            # if we are offline, or LP is down, upload will fail anyway, so we
            # can just as well avoid the upload
            return url

        return url

    def _subscribe_triaging_team(self, bug, report):
        """Subscribe the right triaging team to the bug."""

        # FIXME: this entire function is an ugly Ubuntu specific hack until LP
        # gets a real crash db; see https://wiki.ubuntu.com/CrashReporting

        if (
            "DistroRelease" in report
            and report["DistroRelease"].split()[0] != "Ubuntu"
        ):
            return  # only Ubuntu bugs are filed private

        # use a url hack here, it is faster
        # pylint: disable=protected-access
        person = "%s~%s" % (
            self.launchpad._root_uri,
            self.options.get("triaging_team", "ubuntu-crashes-universe"),
        )
        if not person.replace(str(self.launchpad._root_uri), "").strip(
            "~"
        ) in [
            str(sub).split("/", maxsplit=1)[-1] for sub in bug.subscriptions
        ]:
            bug.subscribe(person=person)

    def _generate_upload_blob(self, report):
        """Generate a multipart/MIME temporary file for uploading.

        You have to close the returned file object after you are done with it.
        """
        # set reprocessing tags
        hdr = {}
        hdr["Tags"] = "apport-%s" % report["ProblemType"].lower()
        a = report.get("PackageArchitecture")
        if not a or a == "all":
            a = report.get("Architecture")
        if a:
            hdr["Tags"] += " " + a
        if "Tags" in report:
            hdr["Tags"] += " " + self._filter_tag_names(report["Tags"])

        # privacy/retracing for distro reports
        # FIXME: ugly hack until LP has a real crash db
        if "DistroRelease" in report:
            if a and (
                "VmCore" in report
                or "CoreDump" in report
                or "LaunchpadPrivate" in report
            ):
                hdr["Private"] = "yes"
                hdr["Subscribers"] = report.get(
                    "LaunchpadSubscribe",
                    self.options.get("initial_subscriber", "apport"),
                )
                hdr["Tags"] += " need-%s-retrace" % a
            elif "Traceback" in report:
                hdr["Private"] = "yes"
                hdr["Subscribers"] = "apport"
                hdr["Tags"] += " need-duplicate-check"
        if (
            "DuplicateSignature" in report
            and "need-duplicate-check" not in hdr["Tags"]
        ):
            hdr["Tags"] += " need-duplicate-check"

        # if we have checkbox submission key, link it to the bug; keep text
        # reference until the link is shown in Launchpad's UI
        if "CheckboxSubmission" in report:
            hdr["HWDB-Submission"] = report["CheckboxSubmission"]

        # order in which keys should appear in the temporary file
        order = [
            "ProblemType",
            "DistroRelease",
            "Package",
            "Regression",
            "Reproducible",
            "TestedUpstream",
            "ProcVersionSignature",
            "Uname",
            "NonfreeKernelModules",
        ]

        # write MIME/Multipart version into temporary file
        # temporary file is returned, pylint: disable=consider-using-with
        mime = tempfile.TemporaryFile()
        report.write_mime(
            mime,
            extra_headers=hdr,
            skip_keys=["Tags", "LaunchpadPrivate", "LaunchpadSubscribe"],
            priority_fields=order,
        )
        mime.flush()
        mime.seek(0)

        return mime

    @classmethod
    def _filter_tag_names(klass, tags):
        """Replace characters from tags which are not palatable to Launchpad"""

        res = ""
        for ch in tags.lower().encode("ASCII", errors="ignore"):
            if ch in b"abcdefghijklmnopqrstuvwxyz0123456789 " or (
                len(res) > 0 and ch in b"+-."
            ):
                res += chr(ch)
            else:
                res += "."

        return res


#
# Launchpad storeblob API (should go into launchpadlib, see LP #315358)
#

_https_upload_callback = None


#
# This progress code is based on KodakLoader by Jason Hildebrand
# <jason@opensky.ca>. See http://www.opensky.ca/~jdhildeb/software/kodakloader/
# for details.
class HTTPSProgressConnection(http.client.HTTPSConnection):
    """Implement a HTTPSConnection with an optional callback function for
    upload progress."""

    def send(self, data):
        # if callback has not been set, call the old method
        if not _https_upload_callback:
            http.client.HTTPSConnection.send(self, data)
            return

        sent = 0
        total = len(data)
        chunksize = 1024
        while sent < total:
            _https_upload_callback(sent, total)
            t1 = time.time()
            http.client.HTTPSConnection.send(
                self, data[sent : (sent + chunksize)]
            )
            sent += chunksize
            t2 = time.time()

            # adjust chunksize so that it takes between .5 and 2
            # seconds to send a chunk
            if chunksize > 1024:
                if t2 - t1 < 0.5:
                    chunksize <<= 1
                elif t2 - t1 > 2:
                    chunksize >>= 1


class HTTPSProgressHandler(urllib.request.HTTPSHandler):
    def https_open(self, req):
        return self.do_open(HTTPSProgressConnection, req)


def upload_blob(blob, progress_callback=None, hostname="launchpad.net"):
    """Upload blob (file-like object) to Launchpad.

    progress_callback can be set to a function(sent, total) which is regularly
    called with the number of bytes already sent and total number of bytes to
    send. It is called every 0.5 to 2 seconds (dynamically adapted to upload
    bandwidth).

    Return None on error, or the ticket number on success.

    By default this uses the production Launchpad hostname. Set
    hostname to 'launchpad.dev', 'qastaging.launchpad.net', or
    'staging.launchpad.net' to use another instance for testing.
    """
    ticket = None
    url = "https://%s/+storeblob" % hostname

    global _https_upload_callback  # pylint: disable=global-statement
    _https_upload_callback = progress_callback

    # build the form-data multipart/MIME request
    data = email.mime.multipart.MIMEMultipart()

    submit = email.mime.text.MIMEText("1")
    submit.add_header("Content-Disposition", 'form-data; name="FORM_SUBMIT"')
    data.attach(submit)

    form_blob = email.mime.base.MIMEBase("application", "octet-stream")
    form_blob.add_header(
        "Content-Disposition", 'form-data; name="field.blob"; filename="x"'
    )
    form_blob.set_payload(blob.read().decode("ascii"))
    data.attach(form_blob)

    data_flat = io.BytesIO()
    gen = email.generator.BytesGenerator(data_flat, mangle_from_=False)
    gen.flatten(data)

    # do the request; we need to explicitly set the content type here, as it
    # defaults to x-www-form-urlencoded
    req = urllib.request.Request(url, data_flat.getvalue())
    req.add_header(
        "Content-Type", "multipart/form-data; boundary=" + data.get_boundary()
    )
    opener = urllib.request.build_opener(HTTPSProgressHandler)
    result = opener.open(req)
    ticket = result.info().get("X-Launchpad-Blob-Token")

    assert ticket
    return ticket


#
# Unit tests
#

if __name__ == "__main__":
    import subprocess
    import unittest
    from unittest.mock import patch

    _CACHE = {}

    def cache(func):
        """Decorator to cache result of function/method call.

        The cache is ignored if force_fresh is set to True.
        """

        def try_to_get_from_cache(*args, **kwargs):
            if kwargs.get("force_fresh", False):
                return func(*args, **kwargs)
            if func.__name__ not in _CACHE:
                _CACHE[func.__name__] = func(*args, **kwargs)
            return _CACHE[func.__name__]

        return try_to_get_from_cache

    class _T(unittest.TestCase):
        # pylint: disable=protected-access

        # this assumes that a source package 'coreutils' exists and builds a
        # binary package 'coreutils'
        test_package = "coreutils"
        test_srcpackage = "coreutils"

        #
        # Generic tests, should work for all CrashDB implementations
        #

        def setUp(self):
            self.crashdb = self._get_instance()

            # create a local reference report so that we can compare
            # DistroRelease, Architecture, etc.
            self.ref_report = apport.Report()
            self.ref_report.add_os_info()
            self.ref_report.add_user_info()
            self.ref_report["SourcePackage"] = "coreutils"

            # Objects tests rely on.
            self._create_project("langpack-o-matic")

        def _create_project(self, name):
            """Create a project using launchpadlib to be used by tests."""

            project = self.crashdb.launchpad.projects[name]
            if not project:
                self.crashdb.launchpad.projects.new_project(
                    description=name + "description",
                    display_name=name,
                    name=name,
                    summary=name + "summary",
                    title=name + "title",
                )

        @property
        def hostname(self):
            """Get the Launchpad hostname for the given crashdb."""

            return self.crashdb.get_hostname()

        @cache
        def get_segv_report(self, force_fresh=False):
            # force_fresh used by @cache, pylint: disable=unused-argument
            """Generate SEGV crash report.

            This is only done once, subsequent calls will return the already
            existing ID, unless force_fresh is True.

            Return the ID.
            """
            r = self._generate_sigsegv_report()
            r.add_package_info(self.test_package)
            r.add_os_info()
            r.add_gdb_info()
            r.add_user_info()
            self.assertEqual(
                r.standard_title(), "crash crashed with SIGSEGV in f()"
            )

            # add some binary gibberish which isn't UTF-8
            r["ShortGibberish"] = ' "]\xb6"\n'
            r["LongGibberish"] = "a\nb\nc\nd\ne\n\xff\xff\xff\n\f"

            # create a bug for the report
            bug_target = self._get_bug_target(self.crashdb, r)
            self.assertTrue(bug_target)

            crash_id = self._file_bug(bug_target, r)
            self.assertTrue(crash_id > 0)

            sys.stderr.write(
                "(Created SEGV report: https://%s/bugs/%i) "
                % (self.hostname, crash_id)
            )
            return crash_id

        @cache
        def get_python_report(self):
            """Generate Python crash report.

            Return the ID.
            """
            r = apport.Report("Crash")
            r["ExecutablePath"] = "/bin/foo"
            r[
                "Traceback"
            ] = """Traceback (most recent call last):
  File "/bin/foo", line 67, in fuzz
    print(weird)
NameError: global name 'weird' is not defined"""
            r["Tags"] = "boogus pybogus"
            r.add_package_info(self.test_package)
            r.add_os_info()
            r.add_user_info()
            self.assertEqual(
                r.standard_title(),
                "foo crashed with NameError in fuzz():"
                " global name 'weird' is not defined",
            )

            bug_target = self._get_bug_target(self.crashdb, r)
            self.assertTrue(bug_target)

            crash_id = self._file_bug(bug_target, r)
            self.assertTrue(crash_id > 0)
            sys.stderr.write(
                "(Created Python report: https://%s/bugs/%i) "
                % (self.hostname, crash_id)
            )
            return crash_id

        @cache
        def get_uncommon_description_report(self, force_fresh=False):
            # force_fresh used by @cache, pylint: disable=unused-argument
            """File a bug report with an uncommon description.

            This is only done once, subsequent calls will return the already
            existing ID, unless force_fresh is True.

            Example taken from real LP bug 269539. It contains only
            ProblemType/Architecture/DistroRelease in the description, and has
            free-form description text after the Apport data.

            Return the ID.
            """
            desc = """problem

ProblemType: Package
Architecture: amd64
DistroRelease: Ubuntu 8.10

more text

and more
"""
            bug = self.crashdb.launchpad.bugs.createBug(
                title="mixed description bug",
                description=desc,
                target=self.crashdb.lp_distro,
            )
            sys.stderr.write(
                "(Created uncommon description: https://%s/bugs/%i) "
                % (self.hostname, bug.id)
            )

            return bug.id

        def test_1_download(self):
            """download()"""

            r = self.crashdb.download(self.get_segv_report())
            self.assertEqual(r["ProblemType"], "Crash")
            self.assertEqual(r["Title"], "crash crashed with SIGSEGV in f()")
            self.assertEqual(
                r["DistroRelease"], self.ref_report["DistroRelease"]
            )
            self.assertEqual(
                r["Architecture"], self.ref_report["Architecture"]
            )
            self.assertEqual(r["Uname"], self.ref_report["Uname"])
            self.assertEqual(
                r.get("NonfreeKernelModules"),
                self.ref_report.get("NonfreeKernelModules"),
            )
            self.assertEqual(
                r.get("UserGroups"), self.ref_report.get("UserGroups")
            )
            tags = set(r["Tags"].split())
            self.assertEqual(
                tags,
                set(
                    [
                        self.crashdb.arch_tag,
                        "apport-crash",
                        apport.packaging.get_system_architecture(),
                    ]
                ),
            )

            self.assertEqual(r["Signal"], "11")
            self.assertTrue(r["ExecutablePath"].endswith("/crash"))
            self.assertEqual(r["SourcePackage"], self.test_srcpackage)
            self.assertTrue(r["Package"].startswith(self.test_package + " "))
            self.assertIn("f (x=42)", r["Stacktrace"])
            self.assertIn("f (x=42)", r["StacktraceTop"])
            self.assertIn("f (x=42)", r["ThreadStacktrace"])
            self.assertGreater(len(r["CoreDump"]), 1000)
            self.assertIn("Dependencies", r)
            self.assertIn("Disassembly", r)
            self.assertIn("Registers", r)

            # check tags
            r = self.crashdb.download(self.get_python_report())
            tags = set(r["Tags"].split())
            self.assertEqual(
                tags,
                set(
                    [
                        "apport-crash",
                        "boogus",
                        "pybogus",
                        "need-duplicate-check",
                        apport.packaging.get_system_architecture(),
                    ]
                ),
            )

        def test_2_update_traces(self):
            """update_traces()"""

            r = self.crashdb.download(self.get_segv_report())
            self.assertIn("CoreDump", r)
            self.assertIn("Dependencies", r)
            self.assertIn("Disassembly", r)
            self.assertIn("Registers", r)
            self.assertIn("Stacktrace", r)
            self.assertIn("ThreadStacktrace", r)
            self.assertEqual(r["Title"], "crash crashed with SIGSEGV in f()")

            # updating with a useless stack trace retains core dump
            r["StacktraceTop"] = "?? ()"
            r["Stacktrace"] = "long\ntrace"
            r["ThreadStacktrace"] = "thread\neven longer\ntrace"
            r["FooBar"] = "bogus"
            self.crashdb.update_traces(
                self.get_segv_report(), r, "I can has a better retrace?"
            )
            r = self.crashdb.download(self.get_segv_report())
            self.assertIn("CoreDump", r)
            self.assertIn("Dependencies", r)
            self.assertIn("Disassembly", r)
            self.assertIn("Registers", r)
            self.assertIn(
                "Stacktrace", r
            )  # TODO: ascertain that it's the updated one
            self.assertIn("ThreadStacktrace", r)
            self.assertNotIn("FooBar", r)
            self.assertEqual(r["Title"], "crash crashed with SIGSEGV in f()")

            tags = self.crashdb.launchpad.bugs[self.get_segv_report()].tags
            self.assertIn("apport-crash", tags)
            self.assertNotIn("apport-collected", tags)

            # updating with a useful stack trace removes core dump
            r["StacktraceTop"] = (
                "read () from /lib/libc.6.so\nfoo (i=1)"
                " from /usr/lib/libfoo.so"
            )
            r["Stacktrace"] = "long\ntrace"
            r["ThreadStacktrace"] = "thread\neven longer\ntrace"
            self.crashdb.update_traces(
                self.get_segv_report(), r, "good retrace!"
            )
            r = self.crashdb.download(self.get_segv_report())
            self.assertNotIn("CoreDump", r)
            self.assertIn("Dependencies", r)
            self.assertIn("Disassembly", r)
            self.assertIn("Registers", r)
            self.assertIn("Stacktrace", r)
            self.assertIn("ThreadStacktrace", r)
            self.assertNotIn("FooBar", r)

            # as previous title had standard form, the top function gets
            # updated
            self.assertEqual(
                r["Title"], "crash crashed with SIGSEGV in read()"
            )

            # respects title amendments
            bug = self.crashdb.launchpad.bugs[self.get_segv_report()]
            bug.title = "crash crashed with SIGSEGV in f() on exit"
            try:
                bug.lp_save()
            except HTTPError:
                pass  # LP#336866 workaround
            r["StacktraceTop"] = (
                "read () from /lib/libc.6.so\nfoo (i=1)"
                " from /usr/lib/libfoo.so"
            )
            self.crashdb.update_traces(
                self.get_segv_report(), r, "good retrace with title amendment"
            )
            r = self.crashdb.download(self.get_segv_report())
            self.assertEqual(
                r["Title"], "crash crashed with SIGSEGV in read() on exit"
            )

            # does not destroy custom titles
            bug = self.crashdb.launchpad.bugs[self.get_segv_report()]
            bug.title = "crash is crashy"
            try:
                bug.lp_save()
            except HTTPError:
                pass  # LP#336866 workaround

            r["StacktraceTop"] = (
                "read () from /lib/libc.6.so\nfoo (i=1)"
                " from /usr/lib/libfoo.so"
            )
            self.crashdb.update_traces(
                self.get_segv_report(), r, "good retrace with custom title"
            )
            r = self.crashdb.download(self.get_segv_report())
            self.assertEqual(r["Title"], "crash is crashy")

            # test various situations which caused crashes
            r["Stacktrace"] = ""  # empty file
            r[
                "ThreadStacktrace"
            ] = '"]\xb6"\n'  # not interpretable as UTF-8, LP #353805
            r["StacktraceSource"] = "a\nb\nc\nd\ne\n\xff\xff\xff\n\f"
            self.crashdb.update_traces(self.get_segv_report(), r, "tests")

        def test_get_comment_url(self):
            """get_comment_url() for non-ASCII titles"""

            title = b"1\xc3\xa4\xe2\x99\xa52"

            # distro, UTF-8 bytestring
            r = apport.Report("Bug")
            r["Title"] = title
            url = self.crashdb.get_comment_url(r, 42)
            self.assertTrue(
                url.endswith(
                    "/ubuntu/+filebug/42?field.title=1%C3%A4%E2%99%A52"
                )
            )

            # distro, unicode
            r["Title"] = title.decode("UTF-8")
            url = self.crashdb.get_comment_url(r, 42)
            self.assertTrue(
                url.endswith(
                    "/ubuntu/+filebug/42?field.title=1%C3%A4%E2%99%A52"
                )
            )

            # package, unicode
            r["SourcePackage"] = "coreutils"
            url = self.crashdb.get_comment_url(r, 42)
            self.assertTrue(
                url.endswith(
                    "/ubuntu/+source/coreutils/+filebug/42"
                    "?field.title=1%C3%A4%E2%99%A52"
                )
            )

        def test_update_description(self):
            """update() with changing description"""

            bug_target = self.crashdb.lp_distro.getSourcePackage(name="bash")
            bug = self.crashdb.launchpad.bugs.createBug(
                description="test description for test bug.",
                target=bug_target,
                title="testbug",
            )
            crash_id = bug.id
            self.assertTrue(crash_id > 0)
            sys.stderr.write(f"(https://{self.hostname}/bugs/{crash_id}) ")

            r = apport.Report("Bug")

            r["OneLiner"] = b"bogus\xe2\x86\x92".decode("UTF-8")
            r["StacktraceTop"] = "f()\ng()\nh(1)"
            r["ShortGoo"] = "lineone\nlinetwo"
            r["DpkgTerminalLog"] = "one\ntwo\nthree\nfour\nfive\nsix"
            r["VarLogDistupgradeBinGoo"] = b"\x01" * 1024

            self.crashdb.update(crash_id, r, "NotMe", change_description=True)

            r = self.crashdb.download(crash_id)

            self.assertEqual(
                r["OneLiner"], b"bogus\xe2\x86\x92".decode("UTF-8")
            )
            self.assertEqual(r["ShortGoo"], "lineone\nlinetwo")
            self.assertEqual(
                r["DpkgTerminalLog"], "one\ntwo\nthree\nfour\nfive\nsix"
            )
            self.assertEqual(r["VarLogDistupgradeBinGoo"], b"\x01" * 1024)

            self.assertEqual(
                self.crashdb.launchpad.bugs[crash_id].tags,
                ["apport-collected"],
            )

        def test_update_comment(self):
            """update() with appending comment"""

            bug_target = self.crashdb.lp_distro.getSourcePackage(name="bash")
            # we need to fake an apport description separator here, since we
            # want to be lazy and use download() for checking the result
            bug = self.crashdb.launchpad.bugs.createBug(
                description="Pr0blem\n\n--- \nProblemType: Bug",
                target=bug_target,
                title="testbug",
            )
            crash_id = bug.id
            self.assertTrue(crash_id > 0)
            sys.stderr.write(f"(https://{self.hostname}/bugs/{crash_id}) ")

            r = apport.Report("Bug")

            r["OneLiner"] = "bogus→"
            r["StacktraceTop"] = "f()\ng()\nh(1)"
            r["ShortGoo"] = "lineone\nlinetwo"
            r["DpkgTerminalLog"] = "one\ntwo\nthree\nfour\nfive\nsix"
            r["VarLogDistupgradeBinGoo"] = "\x01" * 1024

            self.crashdb.update(crash_id, r, "meow", change_description=False)

            r = self.crashdb.download(crash_id)

            self.assertNotIn("OneLiner", r)
            self.assertNotIn("ShortGoo", r)
            self.assertEqual(r["ProblemType"], "Bug")
            self.assertEqual(
                r["DpkgTerminalLog"], "one\ntwo\nthree\nfour\nfive\nsix"
            )
            self.assertEqual(r["VarLogDistupgradeBinGoo"], "\x01" * 1024)

            self.assertEqual(
                self.crashdb.launchpad.bugs[crash_id].tags,
                ["apport-collected"],
            )

        def test_update_filter(self):
            """update() with a key filter"""

            bug_target = self.crashdb.lp_distro.getSourcePackage(name="bash")
            bug = self.crashdb.launchpad.bugs.createBug(
                description="test description for test bug",
                target=bug_target,
                title="testbug",
            )
            crash_id = bug.id
            self.assertTrue(crash_id > 0)
            sys.stderr.write(f"(https://{self.hostname}/bugs/{crash_id}) ")

            r = apport.Report("Bug")

            r["OneLiner"] = "bogus→"
            r["StacktraceTop"] = "f()\ng()\nh(1)"
            r["ShortGoo"] = "lineone\nlinetwo"
            r["DpkgTerminalLog"] = "one\ntwo\nthree\nfour\nfive\nsix"
            r["VarLogDistupgradeBinGoo"] = "\x01" * 1024

            self.crashdb.update(
                crash_id,
                r,
                "NotMe",
                change_description=True,
                key_filter=["ProblemType", "ShortGoo", "DpkgTerminalLog"],
            )

            r = self.crashdb.download(crash_id)

            self.assertNotIn("OneLiner", r)
            self.assertEqual(r["ShortGoo"], "lineone\nlinetwo")
            self.assertEqual(r["ProblemType"], "Bug")
            self.assertEqual(
                r["DpkgTerminalLog"], "one\ntwo\nthree\nfour\nfive\nsix"
            )
            self.assertNotIn("VarLogDistupgradeBinGoo", r)

            self.assertEqual(self.crashdb.launchpad.bugs[crash_id].tags, [])

        def test_get_distro_release(self):
            """get_distro_release()"""

            self.assertEqual(
                self.crashdb.get_distro_release(self.get_segv_report()),
                self.ref_report["DistroRelease"],
            )

        def test_get_affected_packages(self):
            """get_affected_packages()"""

            self.assertEqual(
                self.crashdb.get_affected_packages(self.get_segv_report()),
                [self.ref_report["SourcePackage"]],
            )

        def test_is_reporter(self):
            """is_reporter()"""

            self.assertTrue(self.crashdb.is_reporter(self.get_segv_report()))
            self.assertFalse(self.crashdb.is_reporter(1))

        def test_can_update(self):
            """can_update()"""

            self.assertTrue(self.crashdb.can_update(self.get_segv_report()))
            self.assertFalse(self.crashdb.can_update(1))

        def test_duplicates(self):
            """duplicate handling"""

            # initially we have no dups
            self.assertEqual(
                self.crashdb.duplicate_of(self.get_segv_report()), None
            )
            self.assertEqual(
                self.crashdb.get_fixed_version(self.get_segv_report()), None
            )

            segv_id = self.get_segv_report()
            known_test_id = self.get_uncommon_description_report()
            known_test_id2 = self.get_uncommon_description_report(
                force_fresh=True
            )

            # dupe our segv_report and check that it worked; then undupe it
            r = self.crashdb.download(segv_id)
            self.crashdb.close_duplicate(r, segv_id, known_test_id)
            self.assertEqual(self.crashdb.duplicate_of(segv_id), known_test_id)

            # this should be a no-op
            self.crashdb.close_duplicate(r, segv_id, known_test_id)
            self.assertEqual(self.crashdb.duplicate_of(segv_id), known_test_id)

            self.assertEqual(
                self.crashdb.get_fixed_version(segv_id), "invalid"
            )
            self.crashdb.close_duplicate(r, segv_id, None)
            self.assertEqual(self.crashdb.duplicate_of(segv_id), None)
            self.assertEqual(self.crashdb.get_fixed_version(segv_id), None)

            # this should have removed attachments; note that Stacktrace is
            # short, and thus inline
            r = self.crashdb.download(self.get_segv_report())
            self.assertNotIn("CoreDump", r)
            self.assertNotIn("Disassembly", r)
            self.assertNotIn("ProcMaps", r)
            self.assertNotIn("ProcStatus", r)
            self.assertNotIn("Registers", r)
            self.assertNotIn("ThreadStacktrace", r)

            # now try duplicating to a duplicate bug; this should automatically
            # transition to the master bug
            self.crashdb.close_duplicate(
                apport.Report(), known_test_id, known_test_id2
            )
            self.crashdb.close_duplicate(r, segv_id, known_test_id)
            self.assertEqual(
                self.crashdb.duplicate_of(segv_id), known_test_id2
            )

            self.crashdb.close_duplicate(apport.Report(), known_test_id, None)
            self.crashdb.close_duplicate(apport.Report(), known_test_id2, None)
            self.crashdb.close_duplicate(r, segv_id, None)

            # this should be a no-op
            self.crashdb.close_duplicate(apport.Report(), known_test_id, None)
            self.assertEqual(self.crashdb.duplicate_of(known_test_id), None)

            self.crashdb.mark_regression(segv_id, known_test_id)
            self._verify_marked_regression(segv_id)

        def test_marking_segv(self):
            """processing status markings for signal crashes"""

            # mark_retraced()
            unretraced_before = self.crashdb.get_unretraced()
            self.assertIn(self.get_segv_report(), unretraced_before)
            self.assertNotIn(self.get_python_report(), unretraced_before)
            self.crashdb.mark_retraced(self.get_segv_report())
            unretraced_after = self.crashdb.get_unretraced()
            self.assertNotIn(self.get_segv_report(), unretraced_after)
            self.assertEqual(
                unretraced_before,
                unretraced_after.union(set([self.get_segv_report()])),
            )
            self.assertEqual(
                self.crashdb.get_fixed_version(self.get_segv_report()), None
            )

            # mark_retrace_failed()
            self._mark_needs_retrace(self.get_segv_report())
            self.crashdb.mark_retraced(self.get_segv_report())
            self.crashdb.mark_retrace_failed(self.get_segv_report())
            unretraced_after = self.crashdb.get_unretraced()
            self.assertNotIn(self.get_segv_report(), unretraced_after)
            self.assertEqual(
                unretraced_before,
                unretraced_after.union(set([self.get_segv_report()])),
            )
            self.assertEqual(
                self.crashdb.get_fixed_version(self.get_segv_report()), None
            )

            # mark_retrace_failed() of invalid bug
            self._mark_needs_retrace(self.get_segv_report())
            self.crashdb.mark_retraced(self.get_segv_report())
            self.crashdb.mark_retrace_failed(
                self.get_segv_report(), "I don't like you"
            )
            unretraced_after = self.crashdb.get_unretraced()
            self.assertNotIn(self.get_segv_report(), unretraced_after)
            self.assertEqual(
                unretraced_before,
                unretraced_after.union(set([self.get_segv_report()])),
            )
            self.assertEqual(
                self.crashdb.get_fixed_version(self.get_segv_report()),
                "invalid",
            )

        def test_marking_project(self):
            """processing status markings for a project CrashDB"""

            # create a distro bug
            distro_bug = self.crashdb.launchpad.bugs.createBug(
                description="foo",
                tags=self.crashdb.arch_tag,
                target=self.crashdb.lp_distro,
                title="ubuntu distro retrace bug",
            )

            # create a project crash DB and a bug
            launchpad_instance = (
                os.environ.get("APPORT_LAUNCHPAD_INSTANCE") or "qastaging"
            )

            project_db = CrashDatabase(
                os.environ.get("LP_CREDENTIALS"),
                {
                    "project": "langpack-o-matic",
                    "launchpad_instance": launchpad_instance,
                },
            )
            project_bug = project_db.launchpad.bugs.createBug(
                description="bar",
                tags=project_db.arch_tag,
                target=project_db.lp_distro,
                title="project retrace bug",
            )

            # on project_db, we recognize the project bug and can mark it
            unretraced_before = project_db.get_unretraced()
            self.assertIn(project_bug.id, unretraced_before)
            self.assertNotIn(distro_bug.id, unretraced_before)
            project_db.mark_retraced(project_bug.id)
            unretraced_after = project_db.get_unretraced()
            self.assertNotIn(project_bug.id, unretraced_after)
            self.assertEqual(
                unretraced_before,
                unretraced_after.union(set([project_bug.id])),
            )
            self.assertEqual(
                self.crashdb.get_fixed_version(project_bug.id), None
            )

        def test_marking_foreign_arch(self):
            """processing status markings for a project CrashDB"""

            # create a DB for fake arch
            launchpad_instance = (
                os.environ.get("APPORT_LAUNCHPAD_INSTANCE") or "qastaging"
            )
            fakearch_db = CrashDatabase(
                os.environ.get("LP_CREDENTIALS"),
                {
                    "distro": "ubuntu",
                    "launchpad_instance": launchpad_instance,
                    "architecture": "fakearch",
                },
            )

            fakearch_unretraced_before = fakearch_db.get_unretraced()
            systemarch_unretraced_before = self.crashdb.get_unretraced()

            # create a bug with a fake architecture
            bug = self.crashdb.launchpad.bugs.createBug(
                description="foo",
                tags=["need-fakearch-retrace"],
                target=self.crashdb.lp_distro,
                title="ubuntu distro retrace bug for fakearch",
            )
            print(
                "fake arch bug: https://staging.launchpad.net/bugs/%i" % bug.id
            )

            fakearch_unretraced_after = fakearch_db.get_unretraced()
            systemarch_unretraced_after = self.crashdb.get_unretraced()

            self.assertEqual(
                systemarch_unretraced_before, systemarch_unretraced_after
            )
            self.assertEqual(
                fakearch_unretraced_after,
                fakearch_unretraced_before.union(set([bug.id])),
            )

        def test_marking_python(self):
            """processing status markings for interpreter crashes"""

            unchecked_before = self.crashdb.get_dup_unchecked()
            self.assertIn(self.get_python_report(), unchecked_before)
            self.assertNotIn(self.get_segv_report(), unchecked_before)
            self.crashdb._mark_dup_checked(
                self.get_python_report(), self.ref_report
            )
            unchecked_after = self.crashdb.get_dup_unchecked()
            self.assertNotIn(self.get_python_report(), unchecked_after)
            self.assertEqual(
                unchecked_before,
                unchecked_after.union(set([self.get_python_report()])),
            )
            self.assertEqual(
                self.crashdb.get_fixed_version(self.get_python_report()), None
            )

        def test_update_traces_invalid(self):
            """updating an invalid crash

            This simulates a race condition where a crash being processed gets
            invalidated by marking it as a duplicate.
            """
            crash_id = self.get_segv_report(force_fresh=True)

            r = self.crashdb.download(crash_id)

            self.crashdb.close_duplicate(r, crash_id, self.get_segv_report())

            # updating with a useful stack trace removes core dump
            r["StacktraceTop"] = (
                "read () from /lib/libc.6.so\nfoo (i=1)"
                " from /usr/lib/libfoo.so"
            )
            r["Stacktrace"] = "long\ntrace"
            r["ThreadStacktrace"] = "thread\neven longer\ntrace"
            self.crashdb.update_traces(crash_id, r, "good retrace!")

            r = self.crashdb.download(crash_id)
            self.assertNotIn("CoreDump", r)

        @patch.object(
            CrashDatabase, "_get_source_version", unittest.mock.MagicMock()
        )
        def test_get_fixed_version(self):
            """get_fixed_version() for fixed bugs

            Other cases are already checked in test_marking_segv() (invalid
            bugs) and test_duplicates (duplicate bugs) for efficiency.
            """
            # staging.launchpad.net often does not have Quantal, so mock-patch
            # it to a known value
            CrashDatabase._get_source_version.return_value = "3.14"
            self._mark_report_fixed(self.get_segv_report())
            fixed_ver = self.crashdb.get_fixed_version(self.get_segv_report())
            self.assertEqual(fixed_ver, "3.14")
            self._mark_report_new(self.get_segv_report())
            self.assertEqual(
                self.crashdb.get_fixed_version(self.get_segv_report()), None
            )

        #
        # Launchpad specific implementation and tests
        #

        @classmethod
        @cache
        def _get_instance(klass):
            """Create a CrashDB instance"""

            launchpad_instance = (
                os.environ.get("APPORT_LAUNCHPAD_INSTANCE") or "qastaging"
            )

            return CrashDatabase(
                os.environ.get("LP_CREDENTIALS"),
                {"distro": "ubuntu", "launchpad_instance": launchpad_instance},
            )

        @staticmethod
        def _get_bug_target(db, report):
            """Return the bug_target for this report."""

            project = db.options.get("project")
            if "SourcePackage" in report:
                return db.lp_distro.getSourcePackage(
                    name=report["SourcePackage"]
                )
            elif project:
                return db.launchpad.projects[project]

        def _file_bug(self, bug_target, report, description=None):
            """File a bug report for a report.

            Return the bug ID.
            """
            # unfortunately staging's +storeblob API hardly ever works, so we
            # must avoid using it. Fake it by manually doing the comments and
            # attachments that +filebug would ordinarily do itself when given a
            # blob handle.

            if description is None:
                description = "some description"

            mime = self.crashdb._generate_upload_blob(report)
            msg = email.message_from_binary_file(mime)
            mime.close()
            msg_iter = msg.walk()

            # first one is the multipart container
            header = next(msg_iter)
            assert header.is_multipart()

            # second part should be an inline text/plain attachments
            # with all short fields
            part = next(msg_iter)
            assert not part.is_multipart()
            assert part.get_content_type() == "text/plain"
            description += "\n\n" + part.get_payload(decode=True).decode(
                "UTF-8", "replace"
            )

            # create the bug from header and description data
            bug = self.crashdb.launchpad.bugs.createBug(
                description=description,
                # temporarily disabled to work around SSLHandshakeError on
                # private attachments
                # private=(header['Private'] == 'yes'),
                tags=header["Tags"].split(),
                target=bug_target,
                title=report.get("Title", report.standard_title()),
            )

            # nwo add the attachments
            for part in msg_iter:
                assert not part.is_multipart()
                bug.addAttachment(
                    comment="",
                    description=part.get_filename(),
                    content_type=None,
                    data=part.get_payload(decode=True),
                    filename=part.get_filename(),
                    is_patch=False,
                )

            for subscriber in header["Subscribers"].split():
                sub = self.crashdb.launchpad.people[subscriber]
                if sub:
                    bug.subscribe(person=sub)

            return bug.id

        def _mark_needs_retrace(self, crash_id):
            """Mark a report ID as needing retrace."""

            bug = self.crashdb.launchpad.bugs[crash_id]
            if self.crashdb.arch_tag not in bug.tags:
                bug.tags = bug.tags + [self.crashdb.arch_tag]
                bug.lp_save()

        def _mark_needs_dupcheck(self, crash_id):
            """Mark a report ID as needing duplicate check."""

            bug = self.crashdb.launchpad.bugs[crash_id]
            if "need-duplicate-check" not in bug.tags:
                bug.tags = bug.tags + ["need-duplicate-check"]
                bug.lp_save()

        def _mark_report_fixed(self, crash_id):
            """Close a report ID as "fixed"."""

            bug = self.crashdb.launchpad.bugs[crash_id]
            tasks = list(bug.bug_tasks)
            assert len(tasks) == 1
            t = tasks[0]
            t.status = "Fix Released"
            t.lp_save()

        def _mark_report_new(self, crash_id):
            """Reopen a report ID as "new"."""

            bug = self.crashdb.launchpad.bugs[crash_id]
            tasks = list(bug.bug_tasks)
            assert len(tasks) == 1
            t = tasks[0]
            t.status = "New"
            t.lp_save()

        def _verify_marked_regression(self, crash_id):
            """Verify that report ID is marked as regression."""

            bug = self.crashdb.launchpad.bugs[crash_id]
            self.assertIn("regression-retracer", bug.tags)

        def test_project(self):
            """reporting crashes against a project instead of a distro"""

            launchpad_instance = (
                os.environ.get("APPORT_LAUNCHPAD_INSTANCE") or "qastaging"
            )
            # crash database for langpack-o-matic project (this does not have
            # packages in any distro)
            crashdb = CrashDatabase(
                os.environ.get("LP_CREDENTIALS"),
                {
                    "project": "langpack-o-matic",
                    "launchpad_instance": launchpad_instance,
                },
            )
            self.assertEqual(crashdb.distro, None)

            # create Python crash report
            r = apport.Report("Crash")
            r["ExecutablePath"] = "/bin/foo"
            r[
                "Traceback"
            ] = """Traceback (most recent call last):
  File "/bin/foo", line 67, in fuzz
    print(weird)
NameError: global name 'weird' is not defined"""
            r.add_os_info()
            r.add_user_info()
            self.assertEqual(
                r.standard_title(),
                "foo crashed with NameError in fuzz():"
                " global name 'weird' is not defined",
            )

            # file it
            bug_target = self._get_bug_target(crashdb, r)
            self.assertEqual(bug_target.name, "langpack-o-matic")

            crash_id = self._file_bug(bug_target, r)
            self.assertTrue(crash_id > 0)
            sys.stderr.write(f"(https://{self.hostname}/bugs/{crash_id}) ")

            # update
            r = crashdb.download(crash_id)
            r["StacktraceTop"] = (
                "read () from /lib/libc.6.so\nfoo (i=1)"
                " from /usr/lib/libfoo.so"
            )
            r["Stacktrace"] = "long\ntrace"
            r["ThreadStacktrace"] = "thread\neven longer\ntrace"
            crashdb.update_traces(crash_id, r, "good retrace!")
            r = crashdb.download(crash_id)

            # test fixed version
            self.assertEqual(crashdb.get_fixed_version(crash_id), None)
            crashdb.close_duplicate(
                r, crash_id, self.get_uncommon_description_report()
            )
            self.assertEqual(
                crashdb.duplicate_of(crash_id),
                self.get_uncommon_description_report(),
            )
            self.assertEqual(crashdb.get_fixed_version(crash_id), "invalid")
            crashdb.close_duplicate(r, crash_id, None)
            self.assertEqual(crashdb.duplicate_of(crash_id), None)
            self.assertEqual(crashdb.get_fixed_version(crash_id), None)

        def test_download_robustness(self):
            """download() of uncommon description formats"""

            # only ProblemType/Architecture/DistroRelease in description
            r = self.crashdb.download(self.get_uncommon_description_report())
            self.assertEqual(r["ProblemType"], "Package")
            self.assertEqual(r["Architecture"], "amd64")
            self.assertTrue(r["DistroRelease"].startswith("Ubuntu "))

        def test_escalation(self):
            """Escalating bugs with more than 10 duplicates"""

            launchpad_instance = (
                os.environ.get("APPORT_LAUNCHPAD_INSTANCE") or "qastaging"
            )
            db = CrashDatabase(
                os.environ.get("LP_CREDENTIALS"),
                {
                    "distro": "ubuntu",
                    "launchpad_instance": launchpad_instance,
                    "escalation_tag": "omgkittens",
                    "escalation_subscription": "apport-hackers",
                },
            )

            count = 0
            p = db.launchpad.people[
                db.options["escalation_subscription"]
            ].self_link
            # needs to have 13 consecutive valid bugs without dupes
            first_dup = 10070
            try:
                for b in range(first_dup, first_dup + 13):
                    count += 1
                    sys.stderr.write("%i " % b)
                    db.close_duplicate(
                        apport.Report(), b, self.get_segv_report()
                    )
                    b = db.launchpad.bugs[self.get_segv_report()]
                    has_escalation_tag = db.options["escalation_tag"] in b.tags
                    has_escalation_subscription = any(
                        s.person_link == p for s in b.subscriptions
                    )
                    if count <= 10:
                        self.assertFalse(has_escalation_tag)
                        self.assertFalse(has_escalation_subscription)
                    else:
                        self.assertTrue(has_escalation_tag)
                        self.assertTrue(has_escalation_subscription)
            finally:
                for b in range(first_dup, first_dup + count):
                    sys.stderr.write("R%i " % b)
                    db.close_duplicate(apport.Report(), b, None)
            sys.stderr.write("\n")

        def test_marking_python_task_mangle(self):
            """source package task fixup for marking interpreter crashes"""

            self._mark_needs_dupcheck(self.get_python_report())
            unchecked_before = self.crashdb.get_dup_unchecked()
            self.assertIn(self.get_python_report(), unchecked_before)

            # add an upstream task, and remove the package name from the
            # package task; _mark_dup_checked is supposed to restore the
            # package name
            b = self.crashdb.launchpad.bugs[self.get_python_report()]
            if b.private:
                b.private = False
                b.lp_save()
            t = b.bug_tasks[0]
            t.target = self.crashdb.launchpad.distributions["ubuntu"]
            t.lp_save()
            b.addTask(target=self.crashdb.launchpad.projects["coreutils"])

            r = self.crashdb.download(self.get_python_report())
            self.crashdb._mark_dup_checked(self.get_python_report(), r)

            unchecked_after = self.crashdb.get_dup_unchecked()
            self.assertNotIn(self.get_python_report(), unchecked_after)
            self.assertEqual(
                unchecked_before,
                unchecked_after.union(set([self.get_python_report()])),
            )

            # upstream task should be unmodified
            b = self.crashdb.launchpad.bugs[self.get_python_report()]
            self.assertEqual(b.bug_tasks[0].bug_target_name, "coreutils")
            self.assertEqual(b.bug_tasks[0].status, "New")
            self.assertEqual(b.bug_tasks[0].importance, "Undecided")

            # package-less distro task should have package name fixed
            self.assertEqual(
                b.bug_tasks[1].bug_target_name, "coreutils (Ubuntu)"
            )
            self.assertEqual(b.bug_tasks[1].status, "New")
            self.assertEqual(b.bug_tasks[1].importance, "Medium")

            # should not confuse get_fixed_version()
            self.assertEqual(
                self.crashdb.get_fixed_version(self.get_python_report()), None
            )

        @classmethod
        def _generate_sigsegv_report(klass, signal="11"):
            """Create a test executable which will die with a SIGSEGV, generate
            a core dump for it, create a problem report with those two
            arguments (ExecutablePath and CoreDump) and call add_gdb_info().

            Return the apport.report.Report.
            """
            workdir = None
            orig_cwd = os.getcwd()
            pr = apport.report.Report()
            try:
                workdir = tempfile.mkdtemp()
                atexit.register(shutil.rmtree, workdir)
                os.chdir(workdir)

                # create a test executable
                with open("crash.c", "w", encoding="utf-8") as fd:
                    fd.write(
                        """
int f(x) {
    int* p = 0; *p = x;
    return x+1;
}
int main() { return f(42); }
"""
                    )
                assert (
                    subprocess.call(["gcc", "-g", "crash.c", "-o", "crash"])
                    == 0
                )
                assert os.path.exists("crash")

                # call it through gdb and dump core
                subprocess.call(
                    [
                        "gdb",
                        "--batch",
                        "--ex",
                        "run",
                        "--ex",
                        "generate-core-file core",
                        "./crash",
                    ],
                    stdout=subprocess.PIPE,
                )
                assert os.path.exists("core")
                subprocess.check_call(["sync"])
                assert (
                    subprocess.call(
                        ["readelf", "-n", "core"], stdout=subprocess.PIPE
                    )
                    == 0
                )

                pr["ExecutablePath"] = os.path.join(workdir, "crash")
                pr["CoreDump"] = (os.path.join(workdir, "core"),)
                pr["Signal"] = signal

                pr.add_gdb_info()
            finally:
                os.chdir(orig_cwd)

            return pr

    unittest.main()