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
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
|
# Copyright 2008-2015 Canonical
# Copyright 2015-2016 Chicharreros (https://launchpad.net/~chicharreros)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# For further info, check http://launchpad.net/magicicada-server
"""The Storage network server.
Handles all the networking part of the server.
All code here must be non blocking and the messages should never leave
the server's scope.
"""
import collections
import inspect
import logging
import os
import re
import sys
import time
import urllib
import uuid
import weakref
from functools import partial, wraps
import psycopg2
import twisted
import twisted.web.error
import metrics
import metrics.services
from twisted.application.service import MultiService, Service
from twisted.application.internet import TCPServer
from twisted.internet.defer import maybeDeferred, inlineCallbacks
from twisted.internet.protocol import Factory
from twisted.internet import defer, reactor, error, task, stdio
from twisted.python.failure import Failure
from ubuntuone.storageprotocol import protocol_pb2, request, sharersp
from ubuntuone.supervisor import utils as supervisor_utils
from magicicada import settings
from magicicada.filesync import errors as dataerror
from magicicada.filesync.notifier import notifier
from magicicada.monitoring.reactor import ReactorInspector
from magicicada.rpcdb import inthread
from magicicada.server import auth, content, errors, stats
from magicicada.server.diskstorage import DiskStorage
try:
from versioninfo import version_info
except ImportError:
version_info = {
'branch_nick': 'Unavailable',
'revno': 'Unavailable',
}
# this is the minimal cap we support (to avoid hardcoding it in the code)
MIN_CAP = frozenset(['no-content', 'account-info', 'resumable-uploads',
'fix462230', 'volumes', 'generations'])
# these are the capabilities combinations that we support
SUPPORTED_CAPS = set([MIN_CAP])
# this is the capabilities combination that we prefer, the latest one
PREFERRED_CAP = MIN_CAP
# these is where we suggest to reconnect in case we deny the capabilities
SUGGESTED_REDIRS = {
# frozenset(['example1']): dict(hostname='fs-3.server.com', port=443)
# frozenset(['example2']): dict(srv_record='_https._tcp.fs.server.com')
}
logger = logging.getLogger(__name__)
def _prettify_traceback(report, context):
"""Make the traceback nicer."""
if 'tb_text' in report:
tb = 'Traceback (most recent call last):\n'
tb += report['tb_text']
tb += "%s: '%s'" % (report['type'], report['value'])
report['tb_text'] = tb
class StorageLogger(object):
"""Create logs for the server.
The log format is:
session_id remote_ip:remote_port username request_type request_id \
message
Unknown fields are replaced with a '-'.
Plus whatever the log handler prepends to the line, normally a timestamp
plus level name.
"""
def __init__(self, protocol):
"""Create the logger."""
self.protocol = protocol
self.critical = partial(self.log, logging.CRITICAL)
self.error = partial(self.log, logging.ERROR)
self.warning = partial(self.log, logging.WARNING)
self.info = partial(self.log, logging.INFO)
self.debug = partial(self.log, logging.DEBUG)
self.trace = partial(self.log, settings.TRACE)
def log(self, lvl, message, *args, **kwargs):
"""Log if gloabl logger is enabled for 'lvl'."""
if not logger.isEnabledFor(lvl):
return
msg_format = '%(uuid)s %(remote)s %(userid)s %(message)s'
extra = {'message': message}
if self.protocol.user is not None:
extra['userid'] = urllib.quote(self.protocol.user.username,
':~/').replace('%', '%%')
else:
extra['userid'] = '-'
# be robust in case we have no transport
if self.protocol.transport is not None:
peer = self.protocol.transport.getPeer()
extra['remote'] = peer.host + ':' + str(peer.port)
else:
extra['remote'] = '%s.transport is None' % self.__class__.__name__
extra['uuid'] = self.protocol.session_id
message = msg_format % extra
logger.log(lvl, message, *args, **kwargs)
def trace_message(self, text, message):
"""Log a message with some pre processing."""
if logger.isEnabledFor(settings.TRACE):
if message.type != protocol_pb2.Message.BYTES:
self.trace(text + (str(message).replace('\n', ' ')))
class StorageServerLogger(StorageLogger):
"""Logger for the server."""
def log(self, lvl, message, *args, **kwargs):
"""Log."""
message = '- - ' + message
super(StorageServerLogger, self).log(lvl, message, *args, **kwargs)
class StorageRequestLogger(StorageLogger):
"""Logger for requests."""
def __init__(self, protocol, request):
"""Create the logger."""
super(StorageRequestLogger, self).__init__(protocol)
self.request_class_name = request.__class__.__name__
self.request_id = request.id
def log(self, lvl, message, *args, **kwargs):
"""Log."""
message = '%s %s - %s' % (self.request_class_name,
self.request_id, message)
super(StorageRequestLogger, self).log(lvl, message, *args, **kwargs)
class NotificationRPCTimeoutError(Exception):
"""RPCTimeoutError but during a notification."""
class PoisonException(Exception):
"""An exception class for poison errors."""
class LoopingPing(object):
"""Execute Ping requests in a given interval and expect a response.
Shutdown the request.RequestHandler if the request takes longer than
the specified timeout.
@param interval: the seconds between each Ping
@param timeout: the seconds to wait for a response before shutting down
the request handler
@param request_handler: a request.RequestHandler instance
"""
def __init__(self, interval, timeout, idle_timeout, request_handler):
self.interval = interval
self.timeout = timeout
self.idle_timeout = idle_timeout
self.request_handler = request_handler
self.shutdown = None
self.next_loop = None
self.running = False
self.pong_count = 0
def start(self):
"""Create the DelayedCall instances."""
self.running = True
self.shutdown = reactor.callLater(
self.timeout, self._shutdown, reason='No Pong response.')
self.next_loop = reactor.callLater(self.interval, self.schedule)
def reset(self):
"""Reset pong count and reschedule."""
self.pong_count = 0
self.reschedule()
def reschedule(self):
"""Reset all delayed calls."""
if self.shutdown is not None and self.shutdown.active():
self.shutdown.reset(self.timeout)
elif self.running:
self.shutdown = reactor.callLater(
self.timeout, self._shutdown, reason='No Pong response.')
if self.next_loop is not None and self.next_loop.active():
self.next_loop.reset(self.interval)
elif self.running:
self.next_loop = reactor.callLater(self.interval, self.schedule)
@defer.inlineCallbacks
def schedule(self):
"""Request a Ping and reset the shutdown timeout."""
yield self.request_handler.ping()
self.pong_count += 1
# check if the client is idling for too long
# if self.idle_timeout is 0, do nothing.
idle_time = self.pong_count * self.interval
if self.idle_timeout != 0 and idle_time >= self.idle_timeout:
self._shutdown(reason='idle timeout %s' % (idle_time,))
else:
self.reschedule()
def _shutdown(self, reason):
"""Shutdown the request_handler."""
self.request_handler.log.info('Disconnecting - %s', reason)
if not self.request_handler.shutting_down:
self.request_handler.shutdown()
def stop(self):
"""Stop all the delayed calls."""
self.running = False
if self.shutdown is not None and self.shutdown.active():
self.shutdown.cancel()
if self.next_loop is not None and self.next_loop.active():
self.next_loop.cancel()
for req in self.request_handler.requests.values():
# cleanup stalled Ping requests
if req.started and isinstance(req, request.Ping):
req.done()
class StorageServer(request.RequestHandler):
"""The Storage network server."""
# the version the client must have (minimum)
VERSION_REQUIRED = 3
PING_TIMEOUT = 480
PING_INTERVAL = 120
def __init__(self, session_id=None):
"""Create a network server. The factory does this."""
request.RequestHandler.__init__(self)
self.user = None
self.factory = None
self.session_id = session_id or uuid.uuid4()
self.log = StorageServerLogger(self)
self.shutting_down = False
self.request_locked = False
self.pending_requests = collections.deque()
self.ping_loop = LoopingPing(StorageServer.PING_INTERVAL,
StorageServer.PING_TIMEOUT,
settings.api_server.IDLE_TIMEOUT,
self)
# capabilities that the server is working with
self.working_caps = MIN_CAP
self.poisoned = []
self.waiting_on_poison = []
self.connection_time = None
self._metadata_count = set()
def set_user(self, user):
"""Set user and adjust values that depend on which user it is."""
self.user = user
def poison(self, tag):
"""Inject a failure in the server. Works with check_poison."""
self.poisoned.append(tag)
def check_poison(self, tag):
"""Fail if poisoned with tag.
Will raise a PoisonException when called and tag matches the poison
condition.
"""
if not self.poisoned:
return
poison = self.poisoned[-1]
if poison == '*' or poison == tag:
self.poisoned.pop()
reactor.callLater(0, self.callback_on_poison, poison)
raise PoisonException('Service was poisoned with: %s' % poison)
def callback_on_poison(self, poison):
"""Call all the deferreds waiting on poison."""
for d in self.waiting_on_poison:
d.callback(poison)
self.waiting_on_poison = []
def wait_for_poison(self):
"""Return a deferred that will be called when we are poisoned."""
d = defer.Deferred()
self.waiting_on_poison.append(d)
return d
def _log_error(self, failure, where, exc_info=None):
"""Auxiliar method to log error."""
self.log.error('Unhandled %s when calling %r', failure,
where.__name__, exc_info=exc_info)
def schedule_request(self, request, callback, head=False):
"""Schedule this request to run."""
if head:
self.pending_requests.appendleft((request, callback))
else:
self.pending_requests.append((request, callback))
# we do care if it fails, means no one handled the failure before
if not isinstance(request, Action):
request.deferred.addErrback(self._log_error, request.__class__)
if not self.request_locked:
self.execute_next_request()
def release(self, request):
"""Request 'request' finished, others may start."""
if self.request_locked is not request:
# a release from someone not holding the lock does nothing
return
self.request_locked = False
if self.pending_requests and not self.shutting_down:
self.execute_next_request()
def execute_next_request(self):
"""Read the queue and execute a request."""
request, callback = self.pending_requests.popleft()
try:
self.request_locked = request
callback()
except Exception as e:
self._log_error(e, request.__class__, exc_info=sys.exc_info())
self.release(request)
def connectionLost(self, reason=None):
"""Unregister this connection and potentially remove user binding."""
if not self.shutting_down:
self.shutdown()
if self.user is not None:
self.user.unregister_protocol(self)
self.factory.protocols.remove(self)
self.log.info('Connection Lost: %s', reason.value)
def connectionMade(self):
"""Called when a connection is made."""
request.RequestHandler.connectionMade(self)
self.factory.protocols.append(self)
self.log.info('Connection Made')
msg = '%d filesync server revision %s.\r\n' % (
self.PROTOCOL_VERSION, version_info['revno'])
self.transport.write(msg)
self.ping_loop.start()
self.factory.metrics.meter('connection_made', 1)
self.factory.metrics.increment('connections_active')
self.connection_time = time.time()
def shutdown(self):
"""Lose connection and abort requests."""
self.log.debug('Shutdown Request')
self.shutting_down = True
self.ping_loop.stop()
self.transport.loseConnection()
self.pending_requests.clear()
# stop all the pending requests
for req in self.requests.values():
req.stop()
if self.connection_time is not None:
delta = time.time() - self.connection_time
self.factory.metrics.timing('connection_closed', delta)
self.factory.metrics.decrement('connections_active')
def wait_for_shutdown(self):
"""Wait until the server has stopped serving this client."""
if not self.factory.graceful_shutdown:
return defer.succeed(True)
d = defer.Deferred()
def wait_for_shutdown_worker():
"""Check, wait and recurse."""
if self.requests:
reactor.callLater(0.1, wait_for_shutdown_worker)
else:
d.callback(True)
wait_for_shutdown_worker()
return d
def dataReceived(self, data):
"""Handle new data."""
try:
self.buildMessage(data)
except Exception as e:
# here we handle and should log all errors
self.shutdown()
if isinstance(e, request.StorageProtocolErrorSizeTooBig):
self.log.warning('---- garbage in, garbage out')
return
self._log_error(e, self.dataReceived, exc_info=sys.exc_info())
def processMessage(self, message):
"""Log errors from requests created by incoming messages."""
# reset the ping loop if the message isn't a PING or a PONG
if message.type not in (protocol_pb2.Message.PING,
protocol_pb2.Message.PONG):
self.ping_loop.reset()
try:
result = request.RequestHandler.processMessage(self, message)
except Exception as e:
self._log_error(e, self.processMessage, exc_info=sys.exc_info())
return
if isinstance(result, defer.Deferred):
result.addErrback(self._log_error, result.__class__)
elif isinstance(result, request.Request):
result.deferred.addErrback(self._log_error, result.__class__)
def handle_PROTOCOL_VERSION(self, message):
"""Handle PROTOCOL_VERSION message.
If the version is less or more than whats allowed, we send an error
and drop the connection.
"""
version = message.protocol.version
response = protocol_pb2.Message()
response.id = message.id
if self.VERSION_REQUIRED <= version <= self.PROTOCOL_VERSION:
response.type = protocol_pb2.Message.PROTOCOL_VERSION
response.protocol.version = self.PROTOCOL_VERSION
self.sendMessage(response)
self.log.debug('client requested protocol version %d', version)
else:
msg = 'client requested invalid version %s' % (version,)
response.type = protocol_pb2.Message.ERROR
response.error.type = protocol_pb2.Error.UNSUPPORTED_VERSION
response.error.comment = msg
self.sendMessage(response)
# wrong protocol version is no longer an error.
self.log.info(msg)
self.shutdown()
def handle_PING(self, message):
"""handle an incoming ping message."""
self.check_poison('ping')
response = protocol_pb2.Message()
response.id = message.id
response.type = protocol_pb2.Message.PONG
self.log.trace('ping pong')
self.sendMessage(response)
def handle_AUTH_REQUEST(self, message):
"""Handle AUTH_REQUEST message.
If already logged in, send an error.
"""
request = AuthenticateResponse(self, message)
request.start()
def handle_MAKE_DIR(self, message):
"""Handle MAKE_DIR message."""
request = MakeResponse(self, message)
request.start()
def handle_MAKE_FILE(self, message):
"""Handle MAKE_FILE message."""
request = MakeResponse(self, message)
request.start()
def handle_GET_DELTA(self, message):
"""Handle GET_DELTA message."""
if message.get_delta.from_scratch:
request = RescanFromScratchResponse(self, message)
else:
request = GetDeltaResponse(self, message)
request.start()
def handle_GET_CONTENT(self, message):
"""Handle GET_CONTENT message."""
request = GetContentResponse(self, message)
request.start()
def handle_MOVE(self, message):
"""Handle MOVE message."""
request = MoveResponse(self, message)
request.start()
def handle_PUT_CONTENT(self, message):
"""Handle PUT_CONTENT message."""
request = PutContentResponse(self, message)
request.start()
def handle_UNLINK(self, message):
"""Handle UNLINK message."""
request = Unlink(self, message)
request.start()
def handle_LIST_PUBLIC_FILES(self, message):
"""Handle LIST_PUBLIC_FILES message."""
request = ListPublicFiles(self, message)
request.start()
def handle_CHANGE_PUBLIC_ACCESS(self, message):
"""Handle UNLINK message."""
request = ChangePublicAccess(self, message)
request.start()
def handle_CREATE_UDF(self, message):
"""Handle CREATE_UDF message."""
request = CreateUDF(self, message)
request.start()
def handle_DELETE_VOLUME(self, message):
"""Handle DELETE_VOLUME message."""
request = DeleteVolume(self, message)
request.start()
def handle_LIST_VOLUMES(self, message):
"""Handle LIST_VOLUMES message."""
request = ListVolumes(self, message)
request.start()
def handle_CREATE_SHARE(self, message):
"""Handle CREATE_SHARE message."""
request = CreateShare(self, message)
request.start()
def handle_SHARE_ACCEPTED(self, message):
"""Handle SHARE_ACCEPTED message."""
request = ShareAccepted(self, message)
request.start()
def handle_LIST_SHARES(self, message):
"""Handle LIST_SHARES message."""
request = ListShares(self, message)
request.start()
def handle_DELETE_SHARE(self, message):
"""Handle DELETE_SHARE message."""
request = DeleteShare(self, message)
request.start()
def handle_CANCEL_REQUEST(self, message):
"""Ignores this misreceived cancel."""
# if this arrives to this Request Handler, it means that what
# we're trying to cancel already finished (and the client will
# receive or already received the ok for that), so we ignore it
def handle_BYTES(self, message):
"""Ignores this misreceived message."""
# if this arrives to this Request Handler, it means that what
# we're receiving messages that hit the network before
# everything is properly cancelled, so we ignore it
handle_EOF = handle_BYTES
def handle_QUERY_CAPS(self, message):
"""Handle QUERY_CAPS message."""
request = QuerySetCapsResponse(self, message)
request.start()
def handle_SET_CAPS(self, message):
"""Handle SET_CAPS message."""
request = QuerySetCapsResponse(self, message, set_mode=True)
request.start()
def handle_FREE_SPACE_INQUIRY(self, message):
"""Handle FREE_SPACE_INQUIRY message."""
request = FreeSpaceResponse(self, message)
request.start()
def handle_ACCOUNT_INQUIRY(self, message):
"""Handle account inquiry message."""
request = AccountResponse(self, message)
request.start()
class BaseRequestResponse(request.RequestResponse):
"""Base RequestResponse class.
It keeps a weak reference of the protocol instead of the real ref.
"""
__slots__ = ('use_protocol_weakref', '_protocol_ref')
def __init__(self, protocol, message):
"""Create the request response."""
self.use_protocol_weakref = settings.api_server.PROTOCOL_WEAKREF
self._protocol_ref = None
super(BaseRequestResponse, self).__init__(protocol, message)
def _get_protocol(self):
"""Return the protocol instance."""
if self.use_protocol_weakref:
protocol = self._protocol_ref()
if protocol is None:
# protocol reference gone,
raise errors.ProtocolReferenceError(str(self._protocol_ref))
return protocol
else:
return self._protocol_ref
def _set_protocol(self, protocol):
"""Set the weak ref. to the protocol instance."""
if self.use_protocol_weakref:
self._protocol_ref = weakref.ref(protocol)
else:
self._protocol_ref = protocol
protocol = property(fget=_get_protocol, fset=_set_protocol)
def _start(self):
"""Override this method to start the request."""
raise NotImplementedError('request needs to do something')
class StorageServerRequestResponse(BaseRequestResponse):
"""Base class for all server request responses."""
__slots__ = ('_id', 'log', 'start_time', 'last_good_state_ts',
'length', 'operation_data')
def __init__(self, protocol, message):
"""Create the request response. Setup logger."""
self._id = None
super(StorageServerRequestResponse, self).__init__(protocol, message)
self.log = StorageRequestLogger(self.protocol, self)
self.start_time = None
self.last_good_state_ts = None
self.length = 1
self.operation_data = None
def _get_id(self):
"""Return this request id."""
return self._id
def _set_id(self, id):
"""Set this request id."""
# check if self.log is defined and isn't None
if getattr(self, 'log', None) is not None:
# update the request_id in self.log
self.log.request_id = id
self._id = id
# override self.id with a property
id = property(fget=_get_id, fset=_set_id)
def _get_node_info(self):
"""Return node info from the message.
This should be overwritten by our children, but it's not mandatory.
"""
def start(self):
"""Schedule the request start for later.
It will be executed when the server has no further pending requests.
"""
def _scheduled_start():
"""The scheduled call."""
self.start_time = time.time()
self.last_good_state_ts = time.time()
super(StorageServerRequestResponse, self).start()
self.protocol.check_poison('request_start')
self.protocol.addProducer(self)
# we add the id to the request here, even if it happens again on the
# super() call in _scheduled_start(), but it's good to have the id
# while scheduled, before really started
self.id = self.source_message.id
self.protocol.requests[self.source_message.id] = self
self.log.info('Request being scheduled')
self.log.trace_message('IN: ', self.source_message)
self.protocol.factory.metrics.increment(
'request_instances.%s' % self.__class__.__name__)
self.protocol.schedule_request(self, _scheduled_start)
self.protocol.check_poison('request_schedule')
def stop(self):
"""Stop the request."""
if self.started:
# cancel the request
self.cancel()
else:
# not even started! just log and cleanup
self.log.debug('Request being released before start')
self.cleanup()
def cleanup(self):
"""remove the reference to self from the request handler"""
super(StorageServerRequestResponse, self).cleanup()
self.protocol.factory.metrics.decrement('request_instances.%s' %
(self.__class__.__name__,))
self.protocol.release(self)
def error(self, failure):
"""Overrided error to add logging. Never fail, always log."""
class_name = self.__class__.__name__
try:
if isinstance(failure, Exception):
failure = Failure(failure)
self.log.error('Request error',
exc_info=(failure.type, failure.value, None))
request.RequestResponse.error(self, failure)
except Exception as e:
msg = 'error() crashed when processing %s: %s'
self.log.error(msg, failure, e, exc_info=sys.exc_info())
else:
self.protocol.factory.sli_metrics.report('sli_error', class_name)
if self.start_time is not None:
delta = time.time() - self.start_time
self.protocol.factory.metrics.timing(
'%s.request_error' % (class_name,), delta)
self.protocol.factory.metrics.timing('request_error', delta)
transferred = getattr(self, 'transferred', None)
if transferred is not None:
msg = '%s.transferred' % (class_name,)
self.protocol.factory.metrics.gauge(msg, transferred)
def done(self, _=None):
"""Overrided done to add logging.
Added an ignored parameter so we can hook this to the defered chain.
"""
try:
if self.operation_data is None:
self.log.info('Request done')
else:
self.log.info('Request done: %s', self.operation_data)
request.RequestResponse.done(self)
except Exception as e:
self.error(Failure(e))
else:
class_name = self.__class__.__name__
factory = self.protocol.factory
transferred = getattr(self, 'transferred', None)
if self.start_time is not None:
delta = time.time() - self.start_time
factory.metrics.timing('%s.request_finished' % (class_name,),
delta)
factory.metrics.timing('request_finished', delta)
# inform SLI metric here if operation has a valid length (some
# operations change it, default is 1 for other operations, and
# Put/GetContentResponse set it to None to not inform *here*)
if self.length:
self.protocol.factory.sli_metrics.timing(
class_name, delta / self.length)
if transferred is not None:
msg = '%s.transferred' % (class_name,)
factory.metrics.gauge(msg, transferred)
# measure specific 'user's client' activity
user_activity = getattr(self, 'user_activity', None)
if user_activity is not None:
user_id = getattr(self.protocol.user, 'id', '')
factory.user_metrics.report(user_activity, str(user_id))
def sendMessage(self, message):
"""Send a message and trace it."""
self.log.trace_message('OUT: ', message)
request.RequestResponse.sendMessage(self, message)
def _processMessage(self, message):
"""Locally overridable part of processMessage."""
def processMessage(self, message):
"""Process the received messages.
If the request already started, really process the message rightaway;
if not, just schedule the processing for later.
"""
result = None
if self.started:
result = self._processMessage(message)
else:
def _process_later():
"""Deferred call to process the message."""
self._processMessage(message)
self.protocol.schedule_request(self, _process_later)
return result
def convert_share_id(self, share_id):
"""Convert a share_id from a message to a UUID or None.
@param share_id: a str representation of a share id
@return: uuid.UUID or None
"""
if share_id != request.ROOT:
return uuid.UUID(share_id)
else:
return None
def queue_action(self, callable_action, head=True):
"""Queue a callable action.
Return a deferred that will be fired when the action finish.
"""
action = Action(self, callable_action)
action.start(head=head)
return action.deferred
def _get_extension(self, path):
"""Return an extension from the name/path."""
parts = path.rsplit('.', 1)
if len(parts) == 2:
endpart = parts[1]
if len(endpart) <= 4:
return endpart
class SimpleRequestResponse(StorageServerRequestResponse):
"""Common request/response bits."""
__slots__ = ()
authentication_required = True
# a list of foreign (non protocol) errors to be filled by heirs
expected_foreign_errors = []
# a list of foreing errors that will always be handled by this super class
# because all operations could generate them (RetryLimitReached because of
# access to the DB, and DoesNotExist because user account becoming
# disabled while connected)
generic_foreign_errors = [
dataerror.RetryLimitReached,
dataerror.DoesNotExist,
dataerror.LockedUserError,
psycopg2.DataError,
]
# convert 'foreign' errors directly to protocol error codes;
# StorageServerError and TryAgain (and heirs) will be handled automatically
# because Failure.check compares exceptions using isinstance().
protocol_errors = {
dataerror.NotEmpty: protocol_pb2.Error.NOT_EMPTY,
dataerror.NotADirectory: protocol_pb2.Error.NOT_A_DIRECTORY,
dataerror.NoPermission: protocol_pb2.Error.NO_PERMISSION,
dataerror.DoesNotExist: protocol_pb2.Error.DOES_NOT_EXIST,
dataerror.AlreadyExists: protocol_pb2.Error.ALREADY_EXISTS,
dataerror.QuotaExceeded: protocol_pb2.Error.QUOTA_EXCEEDED,
dataerror.InvalidFilename: protocol_pb2.Error.INVALID_FILENAME,
psycopg2.DataError: protocol_pb2.Error.INVALID_FILENAME,
# violation of primary key, foreign key, or unique constraints
dataerror.IntegrityError: protocol_pb2.Error.ALREADY_EXISTS,
}
# These get converted to TRY_AGAIN
try_again_errors = [
dataerror.RetryLimitReached,
error.TCPTimedOutError,
]
auth_required_error = 'Authentication required and the user is None.'
upload_not_accepted_error = (
'This upload has not been accepted yet content is being sent.')
def _process(self):
"""Process the request."""
def _send_protocol_error(self, failure):
"""Convert the failure to a protocol error.
Send it if possible; otherwise, continue propagating it.
"""
# Convert try_again_errors that weren't converted at lower levels
if failure.check(*self.try_again_errors):
failure = Failure(errors.TryAgain(failure.value))
foreign_errors = (self.generic_foreign_errors +
self.expected_foreign_errors)
error = failure.check(errors.StorageServerError, *foreign_errors)
comment = failure.getErrorMessage().decode('utf8')
if failure.check(errors.TryAgain):
orig_error_name = failure.value.orig_error.__class__.__name__
comment = '%s: %s' % (orig_error_name, comment)
msg = 'Sending TRY_AGAIN to client because we got: %s', comment
self.log.warning(msg, Failure(failure.value.orig_error))
comment = 'TryAgain (%s)' % comment
metric_name = 'TRY_AGAIN.%s' % orig_error_name
self.protocol.factory.metrics.meter(metric_name, 1)
if error == dataerror.QuotaExceeded:
# handle the case of QuotaExceeded
# XXX: check Bug #605847
protocol_error = self.protocol_errors[error]
free_bytes = failure.value.free_bytes
volume_id = str(failure.value.volume_id or '')
free_space_info = {'share_id': volume_id, 'free_bytes': free_bytes}
self.sendError(protocol_error, comment=comment,
free_space_info=free_space_info)
return # the error has been consumed
elif error in self.protocol_errors:
# an error we expect and can convert to a protocol error
protocol_error = self.protocol_errors[error]
self.sendError(protocol_error, comment=comment)
return # the error has been consumed
elif (error == errors.StorageServerError and
not failure.check(errors.InternalError)):
# an error which corresponds directly to a protocol error
self.sendError(failure.value.errno, comment=comment)
return # the error has been consumed
elif error == dataerror.LockedUserError:
self.log.warning('Shutting down protocol: user locked')
if not self.protocol.shutting_down:
self.protocol.shutdown()
return # the error has been consumed
else:
# an unexpected or unconvertable error
self.sendError(protocol_pb2.Error.INTERNAL_ERROR,
comment=comment)
return failure # propagate the error
def internal_error(self, failure):
"""Handle a failure that caused an INTERNAL_ERROR."""
# only call self.error, if I'm not finished
if not self.finished:
self.error(failure)
# only shutdown the protocol if isn't already doing the shutdown
if not self.protocol.shutting_down:
self.protocol.shutdown()
def _log_start(self):
"""Log that the request started."""
txt = 'Request being started'
on_what = self._get_node_info()
if on_what:
txt += ', working on: ' + str(on_what)
self.log.debug(txt)
def _start(self):
"""Kick off request processing."""
self._log_start()
if self.authentication_required and self.protocol.user is None:
self.sendError(protocol_pb2.Error.AUTHENTICATION_REQUIRED,
comment=self.auth_required_error)
return self.done()
else:
d = maybeDeferred(self._process)
d.addErrback(self._send_protocol_error)
d.addCallbacks(self.done, self.internal_error)
class ListShares(SimpleRequestResponse):
"""LIST_SHARES Request Response."""
__slots__ = ()
@inlineCallbacks
def _process(self):
"""List shares for the client."""
user = self.protocol.user
shared_by, shared_to = yield user.list_shares()
self.length = len(shared_by) + len(shared_to)
for share in shared_by:
# get the volume_id of the shared node.
volume_id = yield user.get_volume_id(share['root_id'])
volume_id = str(volume_id) if volume_id else ''
if volume_id == user.root_volume_id:
# return the protocol root instead of users real root
volume_id = request.ROOT
share_resp = sharersp.ShareResponse.from_params(
share['id'], 'from_me', share['root_id'], share['name'],
share['shared_to_username'] or '',
share['shared_to_visible_name'] or '',
share['accepted'], share['access'],
subtree_volume_id=volume_id)
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.SHARES_INFO
share_resp.dump_to_msg(response.shares)
self.sendMessage(response)
for share in shared_to:
share_resp = sharersp.ShareResponse.from_params(
share['id'], 'to_me', share['root_id'], share['name'],
share['shared_by_username'] or '',
share['shared_by_visible_name'] or '',
share['accepted'], share['access'])
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.SHARES_INFO
share_resp.dump_to_msg(response.shares)
self.sendMessage(response)
# we're done!
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.SHARES_END
self.sendMessage(response)
# save data to be logged on operation end
self.operation_data = 'shared_by=%d shared_to=%d' % (
len(shared_by), len(shared_to))
class ShareAccepted(SimpleRequestResponse):
"""SHARE_ACCEPTED Request Response."""
__slots__ = ()
# these are the valid access levels and their translation from the
# protocol message
_answer_prot2nice = {
protocol_pb2.ShareAccepted.YES: 'Yes',
protocol_pb2.ShareAccepted.NO: 'No',
}
def _get_node_info(self):
"""Return node info from the message."""
share_id = self.source_message.share_accepted.share_id
return 'share: %r' % (share_id,)
@inlineCallbacks
def _process(self):
"""Mark the share as accepted."""
mes = self.source_message.share_accepted
answer = self._answer_prot2nice[mes.answer]
accept_share = self.protocol.user.share_accepted
share_id = self.convert_share_id(mes.share_id)
yield accept_share(share_id, answer)
# send the ok to the requesting client
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.OK
self.sendMessage(response)
# save data to be logged on operation end
self.operation_data = 'vol_id=%s answer=%s' % (share_id, answer)
class CreateShare(SimpleRequestResponse):
"""CREATE_SHARE Request Response."""
__slots__ = ()
expected_foreign_errors = [
dataerror.IntegrityError,
dataerror.NotADirectory,
dataerror.NoPermission,
]
# these are the valid access levels and their translation from the
# protocol message
_valid_access_levels = {
protocol_pb2.CreateShare.VIEW: 'View',
protocol_pb2.CreateShare.MODIFY: 'Modify',
}
user_activity = 'create_share'
@inlineCallbacks
def _process(self):
"""Create the share."""
mes = self.source_message.create_share
access_level = self._valid_access_levels[mes.access_level]
create_share = self.protocol.user.create_share
share_id = yield create_share(mes.node, mes.share_to,
mes.name, access_level)
# send the ok to the requesting client
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.SHARE_CREATED
response.share_created.share_id = str(share_id)
self.sendMessage(response)
# save data to be logged on operation end
self.operation_data = 'vol_id=%s access_level=%s' % (
share_id, access_level)
class DeleteShare(SimpleRequestResponse):
"""Deletes a share we had offered."""
__slots__ = ()
expected_foreign_errors = [
dataerror.IntegrityError,
dataerror.NoPermission,
]
def _get_node_info(self):
"""Return node info from the message."""
share_id = self.source_message.delete_share.share_id
return 'share: %r' % (share_id,)
@inlineCallbacks
def _process(self):
"""Delete the share."""
share_id = self.convert_share_id(
self.source_message.delete_share.share_id)
yield self.protocol.user.delete_share(share_id)
# send the ok to the requesting client
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.OK
self.sendMessage(response)
# save data to be logged on operation end
self.operation_data = 'vol_id=%s' % (share_id,)
class CreateUDF(SimpleRequestResponse):
"""CREATE_UDF Request Response."""
__slots__ = ()
expected_foreign_errors = [dataerror.NoPermission]
user_activity = 'sync_activity'
@inlineCallbacks
def _process(self):
"""Create the share."""
mes = self.source_message.create_udf
data = yield self.protocol.user.create_udf(
mes.path, mes.name, self.protocol.session_id)
udf_id, udf_rootid, udf_path = data
# send the ok to the requesting client
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.VOLUME_CREATED
response.volume_created.type = protocol_pb2.Volumes.UDF
response.volume_created.udf.volume = str(udf_id)
response.volume_created.udf.node = str(udf_rootid)
response.volume_created.udf.suggested_path = udf_path
self.sendMessage(response)
# save data to be logged on operation end
self.operation_data = 'vol_id=%s' % (udf_id,)
class DeleteVolume(SimpleRequestResponse):
"""DELETE_VOLUME Request Response."""
__slots__ = ()
expected_foreign_errors = [dataerror.NoPermission]
user_activity = 'sync_activity'
def _get_node_info(self):
"""Return node info from the message."""
volume_id = self.source_message.delete_volume.volume
return 'volume: %r' % (volume_id,)
@inlineCallbacks
def _process(self):
"""Delete the volume."""
volume_id = self.source_message.delete_volume.volume
if volume_id == request.ROOT:
raise dataerror.NoPermission("Root volume can't be deleted.")
try:
vol_id = uuid.UUID(volume_id)
except ValueError:
raise dataerror.DoesNotExist('No such volume %r' % volume_id)
yield self.protocol.user.delete_volume(
vol_id, self.protocol.session_id)
# send the ok to the requesting client
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.OK
self.sendMessage(response)
# save data to be logged on operation end
self.operation_data = 'vol_id=%s' % (vol_id,)
class ListVolumes(SimpleRequestResponse):
"""LIST_VOLUMES Request Response."""
__slots__ = ()
@inlineCallbacks
def _process(self):
"""List volumes for the client."""
user = self.protocol.user
result = yield user.list_volumes()
root_info, shares, udfs, free_bytes = result
self.length = 1 + len(shares) + len(udfs)
# send root
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.VOLUMES_INFO
response.list_volumes.type = protocol_pb2.Volumes.ROOT
response.list_volumes.root.node = str(root_info['root_id'])
response.list_volumes.root.generation = root_info['generation']
response.list_volumes.root.free_bytes = free_bytes
self.sendMessage(response)
# send shares
for share in shares:
direction = 'to_me'
share_resp = sharersp.ShareResponse.from_params(
share['id'], direction, share['root_id'], share['name'],
share['shared_by_username'] or '',
share['shared_by_visible_name'] or '',
share['accepted'], share['access'])
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.VOLUMES_INFO
response.list_volumes.type = protocol_pb2.Volumes.SHARE
share_resp.dump_to_msg(response.list_volumes.share)
response.list_volumes.share.generation = share['generation']
response.list_volumes.share.free_bytes = share['free_bytes']
self.sendMessage(response)
# send udfs
for udf in udfs:
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.VOLUMES_INFO
response.list_volumes.type = protocol_pb2.Volumes.UDF
response.list_volumes.udf.volume = str(udf['id'])
response.list_volumes.udf.node = str(udf['root_id'])
response.list_volumes.udf.suggested_path = udf['path']
response.list_volumes.udf.generation = udf['generation']
response.list_volumes.udf.free_bytes = free_bytes
self.sendMessage(response)
# we're done!
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.VOLUMES_END
self.sendMessage(response)
# save data to be logged on operation end
self.operation_data = 'root=%s shares=%d udfs=%d' % (
root_info['root_id'], len(shares), len(udfs))
class Unlink(SimpleRequestResponse):
"""UNLINK Request Response."""
__slots__ = ()
expected_foreign_errors = [dataerror.NotEmpty, dataerror.NoPermission]
user_activity = 'sync_activity'
def _get_node_info(self):
"""Return node info from the message."""
node_id = self.source_message.unlink.node
return 'node: %r' % (node_id,)
@inlineCallbacks
def _process(self):
"""Unlink a node."""
share_id = self.convert_share_id(self.source_message.unlink.share)
node_id = self.source_message.unlink.node
generation, kind, name, mime = yield self.protocol.user.unlink_node(
share_id, node_id, session_id=self.protocol.session_id)
# answer the ok to original user
response = protocol_pb2.Message()
response.new_generation = generation
response.type = protocol_pb2.Message.OK
self.sendMessage(response)
# save data to be logged on operation end
extension = self._get_extension(name)
self.operation_data = 'vol_id=%s node_id=%s type=%s mime=%r ext=%r' % (
share_id, node_id, kind, mime, extension)
class ListPublicFiles(SimpleRequestResponse):
"""LIST_PUBLIC_FILES Request Response."""
__slots__ = ()
@inlineCallbacks
def _process(self):
"""List public files for the client."""
user = self.protocol.user
public_files = yield user.list_public_files()
counter = 0
for node in public_files:
message = protocol_pb2.Message()
message.type = protocol_pb2.Message.PUBLIC_FILE_INFO
message.public_file_info.share = node.volume_id or ''
message.public_file_info.node = str(node.id)
message.public_file_info.is_public = node.is_public
message.public_file_info.public_url = str(node.public_url)
self.sendMessage(message)
counter += 1
# we're done!
self.length = counter
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.PUBLIC_FILE_INFO_END
self.sendMessage(response)
# save data to be logged on operation end
self.operation_data = 'public_files=%d' % len(public_files)
class ChangePublicAccess(SimpleRequestResponse):
"""CHANGE_PUBLIC_ACCESS Request Response."""
__slots__ = ()
expected_foreign_errors = [dataerror.NoPermission]
user_activity = 'sync_activity'
def _get_node_info(self):
"""Return node info from the message."""
node_id = self.source_message.change_public_access.node
return 'node: %r' % (node_id,)
@inlineCallbacks
def _process(self):
"""Change the public access to a node."""
share_id = self.convert_share_id(
self.source_message.change_public_access.share)
node_id = self.source_message.change_public_access.node
is_public = self.source_message.change_public_access.is_public
public_url = yield self.protocol.user.change_public_access(
share_id, node_id, is_public, session_id=self.protocol.session_id)
# answer the ok to original user
response = protocol_pb2.Message()
response.public_url = bytes(public_url)
response.type = protocol_pb2.Message.OK
self.sendMessage(response)
# save data to be logged on operation end
self.operation_data = (
'vol_id=%s node_id=%s is_public=%s public_url=%r' % (
share_id, node_id, is_public, public_url))
class BytesMessageProducer(object):
"""Adapt a bytes producer to produce BYTES messages."""
payload_size = request.MAX_PAYLOAD_SIZE
def __init__(self, bytes_producer, request):
self.producer = bytes_producer
self.request = request
bytes_producer.startProducing(self)
def resumeProducing(self):
"""IPushProducer interface."""
logger.trace(
'BytesMessageProducer resumed, http producer: %s', self.producer)
if self.producer:
self.producer.resumeProducing()
def stopProducing(self):
"""IPushProducer interface."""
logger.trace(
'BytesMessageProducer stopped, http producer: %s', self.producer)
if self.producer:
self.producer.stopProducing()
def pauseProducing(self):
"""IPushProducer interface."""
logger.trace(
'BytesMessageProducer paused, http producer: %s', self.producer)
if self.producer:
self.producer.pauseProducing()
def write(self, content):
"""Part of IConsumer."""
p = 0
part = content[p:p + self.payload_size]
while part:
if self.request.cancelled:
# stop generating messages
return
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.BYTES
response.bytes.bytes = part
self.request.transferred += len(part)
self.request.sendMessage(response)
p += self.payload_size
part = content[p:p + self.payload_size]
self.request.last_good_state_ts = time.time()
def cancel_filter(function):
"""Raises RequestCancelledError if the request is cancelled.
This methods exists to be used in a addCallback sequence to assure
that it does not continue if the request is cancelled, like:
>>> d.addCallback(cancel_filter(foo))
>>> d.addCallbacks(done_callback, error_errback)
Note that you may receive RequestCancelledError in your
'error_errback' func.
"""
@wraps(function)
def f(self, *args, **kwargs):
"""Function to be called from twisted when its time arrives."""
if self.cancelled:
raise request.RequestCancelledError(
'The request id=%d '
'is cancelled! (before calling %r)' % (self.id, function))
return function(self, *args, **kwargs)
return f
class GetContentResponse(SimpleRequestResponse):
"""GET_CONTENT Request Response."""
__slots__ = ('cancel_message', 'message_producer',
'transferred', 'init_time')
def __init__(self, protocol, message):
super(GetContentResponse, self).__init__(protocol, message)
self.cancel_message = None
self.message_producer = None
self.transferred = 0
self.init_time = 0
self.length = None # to not inform automatically on done()
def _get_node_info(self):
"""Return node info from the message."""
node_id = self.source_message.get_content.node
return 'node: %r' % (node_id,)
def _send_protocol_error(self, failure):
"""Convert the failure to a protocol error.
Send it if possible; otherwise, continue propagating it.
"""
if failure.check(request.RequestCancelledError) or self.cancelled:
# the normal sequence was interrupted by a cancel
if self.cancel_message is not None:
response = protocol_pb2.Message()
response.id = self.cancel_message.id
response.type = protocol_pb2.Message.CANCELLED
self.sendMessage(response)
else:
msg = 'Got cancelling failure %s but cancel_message is None.'
self.log.warning(msg, failure)
return # the error has been consumed
else:
# handle all the TRY_AGAIN cases
if failure.check(error.ConnectionLost):
failure = Failure(errors.TryAgain(failure.value))
return SimpleRequestResponse._send_protocol_error(self, failure)
def _start(self):
"""Get node content and send it."""
self.init_time = time.time()
self._log_start()
share_id = self.convert_share_id(self.source_message.get_content.share)
def done(result):
"""Send EOF message."""
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.EOF
self.sendMessage(response)
def get_content(node):
"""Get the content for node."""
d = node.get_content(
user=self.protocol.user,
previous_hash=self.source_message.get_content.hash,
start=self.source_message.get_content.offset)
return d
def stop_if_cancelled(producer):
"""Stop the producer if cancelled."""
if self.cancelled:
producer.stopProducing()
return producer
def get_node_attrs(node):
"""Get attributes for 'node' and send them."""
r = protocol_pb2.Message()
r.type = protocol_pb2.Message.NODE_ATTR
r.node_attr.deflated_size = node.deflated_size
r.node_attr.size = node.size
r.node_attr.hash = node.content_hash
r.node_attr.crc32 = node.crc32
self.sendMessage(r)
# save data to be logged on operation end
self.operation_data = 'vol_id=%s node_id=%s hash=%s size=%s' % (
share_id, self.source_message.get_content.node,
node.content_hash, node.size)
return node
if self.protocol.user is None:
self.sendError(protocol_pb2.Error.AUTHENTICATION_REQUIRED,
comment=self.auth_required_error)
self.done()
else:
# get node
d = self.protocol.user.get_node(
share_id,
self.source_message.get_content.node,
self.source_message.get_content.hash)
d.addCallback(self.cancel_filter(get_node_attrs))
# get content and validate hash
d.addCallback(self.cancel_filter(get_content))
# stop producer if cancelled
d.addCallback(stop_if_cancelled)
# send content
d.addCallback(self.cancel_filter(self.send))
# send eof
d.addCallback(self.cancel_filter(done))
d.addErrback(self._send_protocol_error)
d.addCallbacks(self.done, self.internal_error)
def send(self, producer):
"""Send node to the client."""
delta = time.time() - self.init_time
self.protocol.factory.sli_metrics.timing(
'GetContentResponseInit', delta)
message_producer = BytesMessageProducer(producer, self)
self.message_producer = message_producer
self.registerProducer(message_producer, streaming=True)
# release this request early
self.protocol.release(self)
return producer.deferred
def _cancel(self):
"""Cancel the request.
This method is called if the request was not cancelled before
(check self.cancel).
"""
producer = self.message_producer
if producer is not None:
self.unregisterProducer()
producer.stopProducing()
def _processMessage(self, message):
"""Process new messages from the client inside this request."""
if message.type == protocol_pb2.Message.CANCEL_REQUEST:
self.cancel_message = message
self.cancel()
self.protocol.release(self)
else:
self.error(request.StorageProtocolProtocolError(message))
class PutContentResponse(SimpleRequestResponse):
"""PUT_CONTENT Request Response."""
__slots__ = ('cancel_message', 'upload_job', 'transferred',
'state', 'init_time')
expected_foreign_errors = [dataerror.NoPermission, dataerror.QuotaExceeded]
user_activity = 'sync_activity'
# indicators for internal fsm
states = 'INIT UPLOADING COMMITING CANCELING ERROR DONE'
states = collections.namedtuple('States', states.lower())(*states.split())
def __init__(self, protocol, message):
super(PutContentResponse, self).__init__(protocol, message)
self.cancel_message = None
self.upload_job = None
self.transferred = 0
self.state = self.states.init
self.init_time = 0
self.length = None # to not inform automatically on done()
def done(self):
"""Override done to skip and log 'double calls'."""
# Just a hack to avoid the KeyError flood until we find the
# reason of the double done calls.
if self.finished:
# build a call chain of 3 levels
curframe = inspect.currentframe()
calframe1 = inspect.getouterframes(curframe, 2)
callers = [calframe1[i][3] for i in range(1, 4)]
call_chain = ' -> '.join(reversed(callers))
self.log.warning('%s: called done() finished=%s',
call_chain, self.finished)
else:
SimpleRequestResponse.done(self)
def _get_node_info(self):
"""Return node info from the message."""
node_id = self.source_message.put_content.node
return 'node: %r' % (node_id,)
def _start(self):
"""Create upload reservation and start receiving."""
self.init_time = time.time()
self._log_start()
if self.protocol.user is None:
self.sendError(protocol_pb2.Error.AUTHENTICATION_REQUIRED,
comment=self.auth_required_error)
self.state = self.states.done
self.done()
else:
d = self._start_upload()
d.addErrback(self._generic_error)
def _log_exception(self, exc):
"""Log an exception before it is handled by the parent request."""
if self.upload_job is not None:
size_hint = self.upload_job.inflated_size_hint
else:
size_hint = 0
if isinstance(exc, errors.TryAgain):
m = 'Upload failed with TryAgain error: %s, size_hint: %s'
self.log.debug(m, exc.orig_error.__class__.__name__, size_hint)
else:
m = 'Upload failed with error: %s, size_hint: %s'
self.log.debug(m, exc.__class__.__name__, size_hint)
@defer.inlineCallbacks
def _generic_error(self, failure):
"""Process all possible errors."""
# it can be an exception, let's work with a failure from now on
if not isinstance(failure, Failure):
failure = Failure(failure)
exc = failure.value
if failure.check(request.RequestCancelledError):
if self.state == self.states.canceling:
# special error while canceling
self.log.debug('Request cancelled: %s', exc)
return
self.log.warning('Error while in %s: %s (%s)', self.state,
exc.__class__.__name__, exc)
if self.state in (self.states.error, self.states.done):
# if already in error/done state, just ignore it (after logging)
return
self.state = self.states.error
# on any error, we just stop the upload job
if self.upload_job is not None:
self.log.debug('Stoping the upload job after an error')
yield self.upload_job.stop()
# send TryAgain if too may retries on DB
if failure.check(dataerror.RetryLimitReached):
exc = errors.TryAgain(exc)
failure = Failure(exc)
# generic error handler, and done (and really fail if we get
# a problem while doing that)
try:
self._log_exception(exc)
yield self._send_protocol_error(failure)
yield self.done()
except:
yield self.internal_error(Failure())
def _processMessage(self, message):
"""Receive the content for the upload."""
self.log.trace_message('IN: ', message)
if self.state == self.states.uploading:
try:
self._process_while_uploading(message)
except Exception as e:
self._generic_error(e)
return
if self.state == self.states.init:
if message.type == protocol_pb2.Message.CANCEL_REQUEST:
try:
self.state = self.states.canceling
self.cancel_message = message
self.cancel()
except Exception as e:
self._generic_error(e)
return
if self.state == self.states.error:
# just ignore the message
return
self.log.warning('Received out-of-order message: state=%s message=%s',
self.state, message.type)
def _process_while_uploading(self, message):
"""Receive any messages while in UPLOADING."""
if message.type == protocol_pb2.Message.CANCEL_REQUEST:
self.state = self.states.canceling
self.cancel_message = message
self.cancel()
elif message.type == protocol_pb2.Message.EOF:
self.state = self.states.commiting
self.upload_job.add_operation(
self._commit_uploadjob, self._generic_error)
elif message.type == protocol_pb2.Message.BYTES:
# process BYTES, stay here in UPLOADING
received_bytes = message.bytes.bytes
self.transferred += len(received_bytes)
self.upload_job.add_operation(
lambda _: self.upload_job.add_data(received_bytes),
self._generic_error)
self.last_good_state_ts = time.time()
else:
self.log.error('Received unknown message: %s', message.type)
@defer.inlineCallbacks
def _cancel(self):
"""Cancel put content.
This is called from request.Request.cancel(), after a
client's CANCEL_REQUEST or a request.stop().
"""
cancelled_by_user = self.state == self.states.canceling
self.log.debug('Request canceled (in %s)', self.state)
self.state = self.states.canceling
if cancelled_by_user:
# cancel the upload job and answer back
if self.upload_job is not None:
self.log.debug('Canceling the upload job')
yield self.upload_job.cancel()
response = protocol_pb2.Message()
response.id = self.cancel_message.id
response.type = protocol_pb2.Message.CANCELLED
self.sendMessage(response)
else:
# just stop the upload job
if self.upload_job is not None:
self.log.debug('Stoping the upload job after a cancel')
yield self.upload_job.stop()
# done
self.state = self.states.done
self.done()
@defer.inlineCallbacks
def _commit_uploadjob(self, _):
"""Callback for uploadjob when it's complete."""
commit_time = time.time()
if self.state != self.states.commiting:
# if we are not in committing state, bail out
return
def commit():
"""The callable to queue."""
if self.state != self.states.commiting:
# Request has been canceled since we last checked
return defer.succeed(None)
return self.upload_job.commit()
# queue the commit work
new_generation = yield self.queue_action(commit)
if self.state != self.states.commiting:
# if we are not in committing state, bail out
return
# when commit's done, send the ok
self.protocol.factory.sli_metrics.timing('PutContentResponseCommit',
time.time() - commit_time)
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.OK
response.new_generation = new_generation
self.sendMessage(response)
# done
self.state = self.states.done
self.done()
@defer.inlineCallbacks
def _start_upload(self):
"""Setup the upload and tell the client to start uploading."""
self.upload_job = yield self._get_upload_job()
self.upload_job.deferred.addErrback(self._generic_error)
if self.state in (self.states.done, self.states.canceling):
# Manually canceling the upload because we were canceled
# while getting the upload
self.log.debug('Manually canceling the upload job (in %s)',
self.state)
yield self.upload_job.cancel()
return
yield self.upload_job.connect()
# register the client transport as the producer
self.protocol.release(self)
self.state = self.states.uploading
yield self._send_begin()
@defer.inlineCallbacks
@cancel_filter
def _get_upload_job(self):
"""Get the uploadjob."""
share_id = self.convert_share_id(self.source_message.put_content.share)
if settings.api_server.MAGIC_UPLOAD_ACTIVE:
magic_hash = self.source_message.put_content.magic_hash or None
else:
magic_hash = None
# save data to be logged on operation end
self.operation_data = 'vol_id=%s node_id=%s hash=%s size=%s' % (
share_id, self.source_message.put_content.node,
self.source_message.put_content.hash,
self.source_message.put_content.size)
# create upload reservation
uploadjob = yield self.protocol.user.get_upload_job(
share_id,
self.source_message.put_content.node,
self.source_message.put_content.previous_hash,
self.source_message.put_content.hash,
self.source_message.put_content.crc32,
self.source_message.put_content.size,
self.source_message.put_content.deflated_size,
session_id=self.protocol.session_id,
magic_hash=magic_hash,
upload_id=self.source_message.put_content.upload_id or None)
defer.returnValue(uploadjob)
@cancel_filter
def _send_begin(self):
"""Notify the client that he can start sending data."""
delta = time.time() - self.init_time
self.protocol.factory.sli_metrics.timing(
'PutContentResponseInit', delta)
upload_type = self.upload_job.__class__.__name__
offset = self.upload_job.offset
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.BEGIN_CONTENT
response.begin_content.offset = offset
# only send the upload id for a new put content
upload_id = self.upload_job.upload_id
upload_id = '' if upload_id is None else str(upload_id)
if self.source_message.put_content.upload_id != upload_id:
response.begin_content.upload_id = upload_id
self.sendMessage(response)
factory = self.protocol.factory
factory.metrics.meter('%s.upload.begin' % (upload_type,), 1)
factory.metrics.gauge('%s.upload' % (upload_type,), offset)
self.log.debug('%s begin content from offset %d, storing to %s',
upload_type, offset, self.upload_job.storage_key)
class GetDeltaResponse(SimpleRequestResponse):
"""GetDelta Request Response."""
__slots__ = ()
def _get_node_info(self):
"""Return node info from the message."""
volume_id = self.source_message.get_delta.share
return 'volume: %r' % (volume_id,)
@inlineCallbacks
def _process(self):
"""Get the deltas and send messages."""
msg = self.source_message
share_id = self.convert_share_id(msg.get_delta.share)
from_generation = msg.get_delta.from_generation
delta_max_size = settings.api_server.DELTA_MAX_SIZE
delta_info = yield self.protocol.user.get_delta(
share_id, from_generation, limit=delta_max_size)
nodes, vol_generation, free_bytes = delta_info
yield self.send_delta_info(nodes, msg.get_delta.share)
self.length = len(nodes)
# now send the DELTA_END
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.DELTA_END
full = True
if nodes:
full = vol_generation == nodes[-1].generation
response.delta_end.full = full
if full:
response.delta_end.generation = vol_generation
else:
response.delta_end.generation = nodes[-1].generation
response.delta_end.free_bytes = free_bytes
self.sendMessage(response)
# save data to be logged on operation end
t = 'vol_id=%s from_gen=%s current_gen=%s nodes=%d free_bytes=%s' % (
share_id, from_generation, vol_generation, self.length, free_bytes)
self.operation_data = t
def send_delta_info(self, nodes, share_id):
"""Build and send the DELTA_INFO for each node."""
return task.cooperate(
self._send_delta_info(nodes, share_id)).whenDone()
def _send_delta_info(self, nodes, share_id):
"""Build and send the DELTA_INFO for each node."""
count = 0
for node in nodes:
if count == settings.api_server.MAX_DELTA_INFO:
count = 0
yield
message = protocol_pb2.Message()
message.type = protocol_pb2.Message.DELTA_INFO
message.delta_info.type = protocol_pb2.DeltaInfo.FILE_INFO
delta_info = message.delta_info
delta_info.generation = node.generation
delta_info.is_live = node.is_live
if node.is_file:
delta_info.file_info.type = protocol_pb2.FileInfo.FILE
else:
delta_info.file_info.type = protocol_pb2.FileInfo.DIRECTORY
delta_info.file_info.name = node.name
delta_info.file_info.share = share_id
delta_info.file_info.node = str(node.id)
if node.parent_id is None:
delta_info.file_info.parent = ''
else:
delta_info.file_info.parent = str(node.parent_id)
delta_info.file_info.is_public = node.is_public
if node.content_hash is None:
delta_info.file_info.content_hash = ''
else:
delta_info.file_info.content_hash = str(node.content_hash)
delta_info.file_info.crc32 = node.crc32
delta_info.file_info.size = node.size
delta_info.file_info.last_modified = node.last_modified
self.sendMessage(message)
count += 1
class RescanFromScratchResponse(GetDeltaResponse):
"""RescanFromScratch Request Response."""
__slots__ = ()
@inlineCallbacks
def _process(self):
"""Get all the live nodes and send DeltaInfos."""
msg = self.source_message
limit = settings.api_server.GET_FROM_SCRATCH_LIMIT
share_id = self.convert_share_id(msg.get_delta.share)
# get the first chunk
delta_info = yield self.protocol.user.get_from_scratch(
share_id, limit=limit)
# keep vol_generation and free_bytes for later
nodes, vol_generation, free_bytes = delta_info
self.length = len(nodes)
while nodes:
# while it keep returning nodes, send the current nodes
yield self.send_delta_info(nodes, msg.get_delta.share)
# and request more
last_path = (nodes[-1].path, nodes[-1].name)
delta_info = yield self.protocol.user.get_from_scratch(
share_id, start_from_path=last_path, limit=limit,
max_generation=vol_generation)
# but don't overwrite vol_generation or free_bytes in case
# something changes while fetching nodes
nodes, _, _ = delta_info
self.length += len(nodes)
# now send the DELTA_END
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.DELTA_END
response.delta_end.full = True
response.delta_end.generation = vol_generation
response.delta_end.free_bytes = free_bytes
self.sendMessage(response)
# save data to be logged on operation end
t = 'vol_id=%s current_gen=%s nodes=%d free_bytes=%s' % (
share_id, vol_generation, self.length, free_bytes)
self.operation_data = t
class QuerySetCapsResponse(SimpleRequestResponse):
"""QUERY_CAPS and SET_CAPS Request Response."""
__slots__ = ('set_mode',)
authentication_required = False
def __init__(self, protocol, message, set_mode=False):
"""Stores the mode."""
self.set_mode = set_mode
super(QuerySetCapsResponse, self).__init__(protocol, message)
def _process(self):
"""Validate the list of capabilities passed to us."""
if self.set_mode:
msg_caps = self.source_message.set_caps
else:
msg_caps = self.source_message.query_caps
caps = frozenset(q.capability for q in msg_caps)
# after one succesful, no more allowed
if self.protocol.working_caps == MIN_CAP:
accepted = caps in SUPPORTED_CAPS
if self.set_mode:
if accepted:
self.protocol.working_caps = caps
# get the redirecting info
redirect = SUGGESTED_REDIRS.get(caps, {})
red_host, red_port, red_srvr = [redirect.get(x, '')
for x in 'hostname', 'port',
'srvrecord']
else:
accepted = False
red_host = red_port = red_srvr = ''
# log what we just decided
action = 'Set' if self.set_mode else 'Query'
result = 'Accepted' if accepted else 'Rejected'
self.log.info('Capabilities %s %s: %s', action, result, caps)
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.ACCEPT_CAPS
response.accept_caps.accepted = accepted
response.accept_caps.redirect_hostname = red_host
response.accept_caps.redirect_port = red_port
response.accept_caps.redirect_srvrecord = red_srvr
self.sendMessage(response)
class MoveResponse(SimpleRequestResponse):
"""Move Request Response."""
__slots__ = ()
expected_foreign_errors = [
dataerror.InvalidFilename,
dataerror.NoPermission,
dataerror.AlreadyExists,
dataerror.NotADirectory,
]
user_activity = 'sync_activity'
def _get_node_info(self):
"""Return node info from the message."""
node_id = self.source_message.move.node
return 'node: %r' % (node_id,)
@inlineCallbacks
def _process(self):
"""Move the node."""
share_id = self.convert_share_id(self.source_message.move.share)
node_id = self.source_message.move.node
new_parent_id = self.source_message.move.new_parent_node
new_name = self.source_message.move.new_name
generation, mimetype = yield self.protocol.user.move(
share_id, node_id, new_parent_id, new_name,
session_id=self.protocol.session_id)
response = protocol_pb2.Message()
response.new_generation = generation
response.type = protocol_pb2.Message.OK
self.sendMessage(response)
# save data to be logged on operation end
extension = self._get_extension(new_name)
self.operation_data = 'vol_id=%s node_id=%s mime=%r ext=%r' % (
share_id, node_id, mimetype, extension)
class MakeResponse(SimpleRequestResponse):
"""MAKE_[DIR|FILE] Request Response."""
__slots__ = ()
expected_foreign_errors = [
dataerror.InvalidFilename,
dataerror.NoPermission,
dataerror.AlreadyExists,
dataerror.NotADirectory,
]
user_activity = 'sync_activity'
def _get_node_info(self):
"""Return node info from the message."""
parent_id = self.source_message.make.parent_node
return 'parent: %r' % (parent_id,)
@inlineCallbacks
def _process(self):
"""Create the file/directory."""
if self.source_message.type == protocol_pb2.Message.MAKE_DIR:
response_type = protocol_pb2.Message.NEW_DIR
create_method_name = 'make_dir'
elif self.source_message.type == protocol_pb2.Message.MAKE_FILE:
response_type = protocol_pb2.Message.NEW_FILE
create_method_name = 'make_file'
else:
raise request.StorageProtocolError(
'Can not create from message '
'(type %s).' % self.source_message.type)
share_id = self.convert_share_id(self.source_message.make.share)
parent_id = self.source_message.make.parent_node
name = self.source_message.make.name
create_method = getattr(self.protocol.user, create_method_name)
d = create_method(share_id, parent_id, name,
session_id=self.protocol.session_id)
node_id, generation, mimetype = yield d
response = protocol_pb2.Message()
response.type = response_type
response.new_generation = generation
response.new.node = str(node_id)
response.new.parent_node = parent_id
response.new.name = name
self.sendMessage(response)
# save data to be logged on operation end
extension = self._get_extension(name)
self.operation_data = 'type=%s vol_id=%s node_id=%s mime=%r ext=%r' % (
create_method_name, share_id, node_id, mimetype, extension)
class FreeSpaceResponse(SimpleRequestResponse):
"""Implements FREE_SPACE_INQUIRY."""
__slots__ = ()
expected_foreign_errors = [dataerror.NoPermission]
@inlineCallbacks
def _process(self):
"""Reports available space for the given share (or the user's own
storage).
"""
share_id = self.convert_share_id(
self.source_message.free_space_inquiry.share_id)
free_bytes = yield self.protocol.user.get_free_bytes(share_id)
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.FREE_SPACE_INFO
response.free_space_info.free_bytes = free_bytes
self.sendMessage(response)
# save data to be logged on operation end
self.operation_data = 'vol_id=%s free_bytes=%s' % (
share_id, free_bytes)
class AccountResponse(SimpleRequestResponse):
"""Implements ACCOUNT_INQUIRY."""
__slots__ = ()
@inlineCallbacks
def _process(self):
"""Reports user account information."""
(purchased, used) = yield self.protocol.user.get_storage_byte_quota()
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.ACCOUNT_INFO
response.account_info.purchased_bytes = purchased
self.sendMessage(response)
class AuthenticateResponse(SimpleRequestResponse):
"""AUTH_REQUEST Request Response."""
__slots__ = ()
authentication_required = False
not_allowed_re = re.compile('[^\w_]')
user_activity = 'connected'
@inlineCallbacks
def _process(self):
"""Authenticate the user."""
# check that its not already logged in
if self.protocol.user is not None:
raise errors.AuthenticationError('User already logged in.')
self.protocol.check_poison('authenticate_start')
# get metadata and send stats
metadata = dict(
(m.key, m.value) for m in self.source_message.metadata)
if metadata:
self.log.info('Client metadata: %s', metadata)
for key in ('platform', 'version'):
if key in metadata:
value = self.not_allowed_re.sub('_', metadata[key])
self.protocol.factory.metrics.meter('client.%s.%s' %
(key, value), 1)
# do auth
auth_parameters = dict(
(param.name, param.value)
for param in self.source_message.auth_parameters)
authenticate = self.protocol.factory.auth_provider.authenticate
user = yield authenticate(auth_parameters, self.protocol)
self.protocol.check_poison('authenticate_continue')
if user is None:
raise errors.AuthenticationError('Authentication failed.')
# confirm authentication
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.AUTH_AUTHENTICATED
# include the session_id
response.session_id = str(self.protocol.session_id)
self.sendMessage(response)
# set up user for this session
self.protocol.set_user(user)
# let the client know the root
root_id, _ = yield user.get_root()
response = protocol_pb2.Message()
response.type = protocol_pb2.Message.ROOT
response.root.node = str(root_id)
self.sendMessage(response)
class Action(BaseRequestResponse):
"""This is an internal action, that behaves like a request.
We can use this Action class to queue work in the pending_requests without
need to worry of handling errors in the request itself.
"""
__slots__ = ('_callable', 'log')
def __init__(self, request, action):
"""Create the request response. Setup logger."""
self._callable = action
# keep the request logger around
self.log = request.log
super(Action, self).__init__(request.protocol, request.source_message)
def start(self, head=True):
"""Schedule the action start for later.
It will be executed when the server has no further pending requests.
"""
def _scheduled_start():
"""The scheduled call."""
super(Action, self).start()
self.log.debug('Action being scheduled (%s)', self._callable)
self.protocol.factory.metrics.increment('action_instances.%s' %
(self.__class__.__name__,))
self.protocol.schedule_request(self, _scheduled_start, head=head)
def _start(self):
"""Kick off action processing."""
self.log.debug('Action being started, working on: %s', self._callable)
d = maybeDeferred(self._callable)
d.addCallbacks(self.done, self.error)
def cleanup(self):
"""Remove the reference to self from the request handler"""
self.finished = True
self.started = False
self.protocol.factory.metrics.decrement('action_instances.%s' %
(self.__class__.__name__,))
self.protocol.release(self)
def done(self, result):
"""Overrided done to add logging and to use the callable result.
Added an ignored parameter so we can hook this to the defered chain.
"""
try:
self.log.debug('Action done (%s)', self._callable)
self.cleanup()
self.deferred.callback(result)
except Exception as e:
self.error(Failure(e))
def error(self, failure):
"""Rall this to signal that the action finished with failure
@param failure: the failure instance
"""
self.cleanup()
self.deferred.errback(failure)
class StorageServerFactory(Factory):
"""The Storage Server Factory.
@cvar protocol: The class of the server.
"""
protocol = StorageServer
graceful_shutdown = settings.api_server.GRACEFUL_SHUTDOWN
def __init__(self, auth_provider_class=auth.DummyAuthProvider,
content_class=content.ContentManager,
reactor=reactor, servername=None, reactor_inspector=None):
"""Create a StorageServerFactory."""
self.auth_provider = auth_provider_class(self)
self.content = content_class(self)
self.diskstorage = DiskStorage(settings.api_server.STORAGE_BASEDIR)
self.metrics = metrics.get_meter('root')
self.user_metrics = metrics.get_meter('user')
self.sli_metrics = metrics.get_meter('sli')
self.servername = servername
self.reactor_inspector = reactor_inspector
# note that this relies on the notifier calling the
# callback from the reactor thread
notif = notifier.get_notifier()
notif.set_event_callback(
notifier.UDFCreate,
self.event_callback_handler(self.deliver_udf_create))
notif.set_event_callback(
notifier.UDFDelete,
self.event_callback_handler(self.deliver_udf_delete))
notif.set_event_callback(
notifier.ShareCreated,
self.event_callback_handler(self.deliver_share_created))
notif.set_event_callback(
notifier.ShareAccepted,
self.event_callback_handler(self.deliver_share_accepted))
notif.set_event_callback(
notifier.ShareDeclined,
self.event_callback_handler(self.deliver_share_declined))
notif.set_event_callback(
notifier.ShareDeleted,
self.event_callback_handler(self.deliver_share_deleted))
notif.set_event_callback(
notifier.VolumeNewGeneration,
self.event_callback_handler(self.deliver_volume_new_generation))
self.protocols = []
self.reactor = reactor
self.trace_users = set(settings.api_server.TRACE_USERS)
twisted.python.log.addObserver(self._deferror_handler)
def _deferror_handler(self, data):
"""Deferred error handler.
We receive all stuff here, filter the errors and use correct info.
"""
if not data.get('isError', None):
return
try:
failure = data['failure']
except KeyError:
msg = data['message']
failure = None
else:
msg = failure.getTraceback()
# log
logger.error('Unhandled error in deferred! %s', msg)
def event_callback_handler(self, func):
"""Wrap the event callback in an error handler."""
@wraps(func)
def wrapper(notif, **kwargs):
"""The wrapper."""
def notification_error_handler(failure):
"""Handle error while processing a Notification."""
logger.error(
'%s in notification %r while calling %s(**%r)',
failure.value, notif, func.__name__, kwargs)
d = defer.maybeDeferred(func, notif, **kwargs)
d.addErrback(notification_error_handler)
return d
return wrapper
@inlineCallbacks
def deliver_udf_create(self, udf_create):
"""Handle UDF creation notification."""
def notif_filter(protocol):
"""Return True if the client should receive the notification."""
return protocol.session_id != udf_create.source_session
user = yield self.content.get_user_by_id(udf_create.owner_id)
if user: # connected instances for this user?
resp = protocol_pb2.Message()
resp.type = protocol_pb2.Message.VOLUME_CREATED
resp.volume_created.type = protocol_pb2.Volumes.UDF
resp.volume_created.udf.volume = str(udf_create.udf_id)
resp.volume_created.udf.node = str(udf_create.root_id)
resp.volume_created.udf.suggested_path = udf_create.suggested_path
user.broadcast(resp, filter=notif_filter)
@inlineCallbacks
def deliver_share_created(self, share_notif):
"""Handle Share creation notification."""
def notif_filter(protocol):
"""Return True if the client should receive the notification."""
return protocol.session_id != share_notif.source_session
to_user = yield self.content.get_user_by_id(share_notif.shared_to_id)
if to_user is None:
return
share_resp = sharersp.NotifyShareHolder.from_params(
share_notif.share_id, share_notif.root_id, share_notif.name,
to_user.username, to_user.visible_name, share_notif.access)
proto_msg = protocol_pb2.Message()
proto_msg.type = protocol_pb2.Message.NOTIFY_SHARE
share_resp.dump_to_msg(proto_msg.notify_share)
to_user.broadcast(proto_msg, filter=notif_filter)
@inlineCallbacks
def deliver_share_accepted(self, share_notif, recipient_id):
"""Handle Share accepted notification."""
def notif_filter(protocol):
"""Return True if the client should receive the notification."""
return protocol.session_id != share_notif.source_session
def to_notif_filter(protocol):
"""Return True if the client should recieve the notification."""
return protocol.session_id != share_notif.source_session
by_user = yield self.content.get_user_by_id(share_notif.shared_by_id)
to_user = yield self.content.get_user_by_id(share_notif.shared_to_id)
if by_user and recipient_id == by_user.id:
proto_msg = protocol_pb2.Message()
proto_msg.type = protocol_pb2.Message.SHARE_ACCEPTED
proto_msg.share_accepted.share_id = str(share_notif.share_id)
proto_msg.share_accepted.answer = protocol_pb2.ShareAccepted.YES
by_user.broadcast(proto_msg, filter=notif_filter)
if to_user and recipient_id == to_user.id:
if by_user is None:
by_user = yield self.content.get_user_by_id(
share_notif.shared_by_id, required=True)
share_resp = sharersp.ShareResponse.from_params(
str(share_notif.share_id), 'to_me', share_notif.root_id,
share_notif.name, by_user.username or '',
by_user.visible_name or '', protocol_pb2.ShareAccepted.YES,
share_notif.access)
resp = protocol_pb2.Message()
resp.type = protocol_pb2.Message.VOLUME_CREATED
resp.volume_created.type = protocol_pb2.Volumes.SHARE
share_resp.dump_to_msg(resp.volume_created.share)
to_user.broadcast(resp, filter=to_notif_filter)
@inlineCallbacks
def deliver_share_declined(self, share_notif):
"""Handle Share declined notification."""
def notif_filter(protocol):
"""Return True if the client should receive the notification."""
return protocol.session_id != share_notif.source_session
by_user = yield self.content.get_user_by_id(share_notif.shared_by_id)
if by_user:
proto_msg = protocol_pb2.Message()
proto_msg.type = protocol_pb2.Message.SHARE_ACCEPTED
proto_msg.share_accepted.share_id = str(share_notif.share_id)
proto_msg.share_accepted.answer = protocol_pb2.ShareAccepted.NO
by_user.broadcast(proto_msg, filter=notif_filter)
@inlineCallbacks
def deliver_share_deleted(self, share_notif):
"""Handle Share deletion notification."""
def notif_filter(protocol):
"""Return True if the client should receive the notification."""
return protocol.session_id != share_notif.source_session
to_user = yield self.content.get_user_by_id(share_notif.shared_to_id)
# by_user = yield self.content.get_user_by_id(share_notif.shared_by_id)
if to_user is None:
return
proto_msg = protocol_pb2.Message()
proto_msg.type = protocol_pb2.Message.SHARE_DELETED
proto_msg.share_deleted.share_id = str(share_notif.share_id)
if to_user:
to_user.broadcast(proto_msg, filter=notif_filter)
# if by_user:
# by_user.broadcast(proto_msg, filter=notif_filter)
@inlineCallbacks
def deliver_udf_delete(self, udf_delete):
"""Handle UDF deletion notification."""
def notif_filter(protocol):
"""Return True if the client should receive the notification."""
return protocol.session_id != udf_delete.source_session
user = yield self.content.get_user_by_id(udf_delete.owner_id)
if user: # connected instances for this user?
resp = protocol_pb2.Message()
resp.type = protocol_pb2.Message.VOLUME_DELETED
resp.volume_deleted.volume = str(udf_delete.udf_id)
user.broadcast(resp, filter=notif_filter)
@inlineCallbacks
def deliver_volume_new_generation(self, notif):
"""Handle the notification of a new generation for a volume."""
def notif_filter(protocol):
"""Return True if the client should receive the notification."""
return protocol.session_id != notif.source_session
user = yield self.content.get_user_by_id(notif.user_id)
if user: # connected instances for this user?
resp = protocol_pb2.Message()
resp.type = protocol_pb2.Message.VOLUME_NEW_GENERATION
if notif.client_volume_id is None:
resp.volume_new_generation.volume = ''
else:
resp.volume_new_generation.volume = str(notif.client_volume_id)
resp.volume_new_generation.generation = notif.new_generation
user.broadcast(resp, filter=notif_filter)
def wait_for_shutdown(self):
"""Wait until all the current servers have finished serving."""
if not self.protocols or not self.graceful_shutdown:
return defer.succeed(None)
wait_d = [protocol.wait_for_shutdown() for protocol in self.protocols]
done_with_current = self.wait_for_current_shutdown()
d = defer.DeferredList(wait_d + [done_with_current])
return d
def wait_for_current_shutdown(self):
"""wait for the current protocols to end."""
d = defer.Deferred()
def _wait():
'do the waiting'
if self.protocols:
self.reactor.callLater(0.1, _wait)
else:
d.callback(True)
_wait()
return d
class OrderedMultiService(MultiService):
"""A container which starts and shuts down the services in strict order."""
def startService(self):
"""Start the services sequentually. Returns a deferred which
signals completion.
"""
# deliberately skip MultiService's implementation
Service.startService(self)
d = defer.succeed(None)
for service in self:
d.addCallback(lambda _, s: s.startService(), service)
return d
def stopService(self):
"""Stop the services sequentially (in the opposite order they
are started). Returns a deferred which signals completion.
"""
# deliberately skip MultiService's implementation
Service.stopService(self)
d = defer.succeed(None)
services = list(self)
services.reverse()
for service in services:
d.addBoth(lambda _, s: s.stopService(), service)
return d
def get_service_port(service):
"""Returns the actual port a simple service is bound to."""
# we have to query this rather than simply using the port number the
# service was passed at creation time -- if the given port was 0,
# the real port number will have been dynamically assigned
return service._port.getHost().port
class StorageServerService(OrderedMultiService):
"""Wrap the whole TCP StorageServer mess as a single twisted serv."""
def __init__(self, port, auth_provider_class=None,
status_port=0, heartbeat_interval=None):
"""Create a StorageServerService.
@param port: the port to listen on without ssl.
@param auth_provider_class: the authentication provider.
"""
OrderedMultiService.__init__(self)
self.heartbeat_writer = None
if heartbeat_interval is None:
heartbeat_interval = float(settings.api_server.HEARTBEAT_INTERVAL)
self.heartbeat_interval = heartbeat_interval
self.rpc_dal = None
self.servername = settings.api_server.SERVERNAME
logger.info('Starting %s', self.servername)
logger.info(
'protocol buffers implementation: %s',
os.environ.get('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION', 'None'))
self.metrics = metrics.get_meter('service')
listeners = MultiService()
listeners.setName('Listeners')
listeners.setServiceParent(self)
self._reactor_inspector = ReactorInspector(reactor.callFromThread)
self.factory = StorageServerFactory(
auth_provider_class=auth_provider_class,
servername=self.servername,
reactor_inspector=self._reactor_inspector)
self.tcp_service = TCPServer(port, self.factory)
self.tcp_service.setName('TCP')
self.tcp_service.setServiceParent(listeners)
# setup the status service
self.status_service = stats.create_status_service(
self, listeners, status_port)
@property
def port(self):
"""The port without ssl."""
return get_service_port(self.tcp_service)
@property
def status_port(self):
"""The status service port."""
return get_service_port(self.status_service)
def start_rpc_dal(self):
"""Setup the rpc client."""
logger.info('Starting the RPC clients.')
self.rpc_dal = inthread.ThreadedNonRPC()
@inlineCallbacks
def startService(self):
"""Start listening on two ports."""
logger.info('- - - - - SERVER STARTING')
yield OrderedMultiService.startService(self)
yield defer.maybeDeferred(self.start_rpc_dal)
self.factory.content.rpc_dal = self.rpc_dal
self.factory.rpc_dal = self.rpc_dal
self.metrics.meter('server_start')
self.metrics.increment('services_active')
metrics.services.revno()
self._reactor_inspector.start()
# only start the HeartbeatWriter if the interval is > 0
if self.heartbeat_interval > 0:
self.heartbeat_writer = stdio.StandardIO(
supervisor_utils.HeartbeatWriter(self.heartbeat_interval,
logger))
@inlineCallbacks
def stopService(self):
"""Stop listening on both ports."""
logger.info('- - - - - SERVER STOPPING')
yield OrderedMultiService.stopService(self)
yield self.factory.wait_for_shutdown()
self.metrics.meter('server_stop')
self.metrics.decrement('services_active')
self._reactor_inspector.stop()
if self.heartbeat_writer:
self.heartbeat_writer.loseConnection()
self.heartbeat_writer = None
logger.info('- - - - - SERVER STOPPED')
def create_service(status_port=None,
auth_provider_class=auth.DummyAuthProvider):
"""Start the StorageServer service."""
# turn on heapy if must to
if os.getenv('USE_HEAPY'):
logger.debug('importing heapy')
try:
import guppy.heapy.RM
except ImportError:
logger.warning('guppy-pe/heapy not available, remote monitor '
'thread not started')
else:
guppy.heapy.RM.on()
logger.debug('activated heapy remote monitor')
# set GC's debug
if settings.api_server.GC_DEBUG:
import gc
gc.set_debug(gc.DEBUG_UNCOLLECTABLE)
logger.debug('set gc debug on')
if status_port is None:
status_port = settings.api_server.STATUS_PORT
# create the service
service = StorageServerService(
settings.api_server.TCP_PORT, auth_provider_class, status_port)
return service
|