summaryrefslogtreecommitdiffstats
path: root/compass-deck/db/api/cluster.py
blob: 82bcaab6afa5acb987d07c15250e1c40f856df3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
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
# Copyright 2014 Huawei Technologies Co. Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Cluster database operations."""
import copy
import functools
import logging
import re

from compass.db.api import adapter_holder as adapter_api
from compass.db.api import database
from compass.db.api import metadata_holder as metadata_api
from compass.db.api import permission
from compass.db.api import user as user_api
from compass.db.api import utils
from compass.db import exception
from compass.db import models
from compass.utils import util


SUPPORTED_FIELDS = [
    'name', 'os_name', 'owner',
    'adapter_name', 'flavor_name'
]
SUPPORTED_CLUSTERHOST_FIELDS = []
RESP_FIELDS = [
    'id', 'name', 'os_name', 'os_id', 'adapter_id', 'flavor_id',
    'reinstall_distributed_system', 'flavor',
    'distributed_system_installed',
    'owner', 'adapter_name', 'flavor_name',
    'created_at', 'updated_at'
]
RESP_CLUSTERHOST_FIELDS = [
    'id', 'host_id', 'clusterhost_id', 'machine_id',
    'name', 'hostname', 'roles', 'os_installer',
    'cluster_id', 'clustername', 'location', 'tag',
    'networks', 'mac', 'switch_ip', 'port', 'switches',
    'os_installed', 'distributed_system_installed',
    'os_name', 'os_id', 'ip', 'reinstall_os',
    'reinstall_distributed_system', 'owner', 'cluster_id',
    'power_type', 'power_manage',
    'created_at', 'updated_at',
    'patched_roles'
]
RESP_CONFIG_FIELDS = [
    'os_config',
    'package_config',
    'config_step',
    'config_validated',
    'created_at',
    'updated_at'
]
RESP_DEPLOYED_CONFIG_FIELDS = [
    'deployed_os_config',
    'deployed_package_config',
    'created_at',
    'updated_at'
]
RESP_METADATA_FIELDS = [
    'os_config', 'package_config'
]
RESP_CLUSTERHOST_CONFIG_FIELDS = [
    'package_config',
    'os_config',
    'config_step',
    'config_validated',
    'networks',
    'created_at',
    'updated_at'
]
RESP_CLUSTERHOST_DEPLOYED_CONFIG_FIELDS = [
    'deployed_os_config',
    'deployed_package_config',
    'created_at',
    'updated_at'
]
RESP_STATE_FIELDS = [
    'id', 'state', 'percentage', 'message', 'severity',
    'status', 'ready',
    'created_at', 'updated_at'
]
RESP_CLUSTERHOST_STATE_FIELDS = [
    'id', 'state', 'percentage', 'message', 'severity',
    'ready', 'created_at', 'updated_at'
]
RESP_REVIEW_FIELDS = [
    'cluster', 'hosts'
]
RESP_DEPLOY_FIELDS = [
    'status', 'cluster', 'hosts'
]
IGNORE_FIELDS = ['id', 'created_at', 'updated_at']
ADDED_FIELDS = ['name', 'adapter_id', 'os_id']
OPTIONAL_ADDED_FIELDS = ['flavor_id']
UPDATED_FIELDS = ['name', 'reinstall_distributed_system']
ADDED_HOST_FIELDS = ['machine_id']
UPDATED_HOST_FIELDS = ['name', 'reinstall_os']
UPDATED_CLUSTERHOST_FIELDS = ['roles', 'patched_roles']
PATCHED_CLUSTERHOST_FIELDS = ['patched_roles']
UPDATED_CONFIG_FIELDS = [
    'put_os_config', 'put_package_config', 'config_step'
]
UPDATED_DEPLOYED_CONFIG_FIELDS = [
    'deployed_os_config', 'deployed_package_config'
]
PATCHED_CONFIG_FIELDS = [
    'patched_os_config', 'patched_package_config', 'config_step'
]
UPDATED_CLUSTERHOST_CONFIG_FIELDS = [
    'put_os_config',
    'put_package_config'
]
PATCHED_CLUSTERHOST_CONFIG_FIELDS = [
    'patched_os_config',
    'patched_package_config'
]
UPDATED_CLUSTERHOST_DEPLOYED_CONFIG_FIELDS = [
    'deployed_os_config',
    'deployed_package_config'
]
UPDATED_CLUSTERHOST_STATE_FIELDS = [
    'state', 'percentage', 'message', 'severity'
]
UPDATED_CLUSTERHOST_STATE_INTERNAL_FIELDS = [
    'ready'
]
UPDATED_CLUSTER_STATE_FIELDS = ['state']
IGNORE_UPDATED_CLUSTER_STATE_FIELDS = ['percentage', 'message', 'severity']
UPDATED_CLUSTER_STATE_INTERNAL_FIELDS = ['ready']
RESP_CLUSTERHOST_LOG_FIELDS = [
    'clusterhost_id', 'id', 'host_id', 'cluster_id',
    'filename', 'position', 'partial_line',
    'percentage',
    'message', 'severity', 'line_matcher_name'
]
ADDED_CLUSTERHOST_LOG_FIELDS = [
    'filename'
]
UPDATED_CLUSTERHOST_LOG_FIELDS = [
    'position', 'partial_line', 'percentage',
    'message', 'severity', 'line_matcher_name'
]


@utils.supported_filters(optional_support_keys=SUPPORTED_FIELDS)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTERS
)
@utils.wrap_to_dict(RESP_FIELDS)
def list_clusters(user=None, session=None, **filters):
    """List clusters."""
    clusters = utils.list_db_objects(
        session, models.Cluster, **filters
    )
    logging.info('user is %s', user.email)
    if not user.is_admin and len(clusters):
        clusters = [c for c in clusters if c.owner == user.email]
    return clusters


def _get_cluster(cluster_id, session=None, **kwargs):
    """Get cluster by id."""
    if isinstance(cluster_id, (int, long)):
        return utils.get_db_object(
            session, models.Cluster, id=cluster_id, **kwargs
        )
    raise exception.InvalidParameter(
        'cluster id %s type is not int compatible' % cluster_id
    )


def get_cluster_internal(cluster_id, session=None, **kwargs):
    """Helper function to get cluster.

    Should be only used by other files under db/api.
    """
    return _get_cluster(cluster_id, session=session, **kwargs)


def _get_cluster_host(
    cluster_id, host_id, session=None, **kwargs
):
    """Get clusterhost by cluster id and host id."""
    cluster = _get_cluster(cluster_id, session=session, **kwargs)
    from compass.db.api import host as host_api
    host = host_api.get_host_internal(host_id, session=session, **kwargs)
    return utils.get_db_object(
        session, models.ClusterHost,
        cluster_id=cluster.id,
        host_id=host.id,
        **kwargs
    )


def _get_clusterhost(clusterhost_id, session=None, **kwargs):
    """Get clusterhost by clusterhost id."""
    if isinstance(clusterhost_id, (int, long)):
        return utils.get_db_object(
            session, models.ClusterHost,
            clusterhost_id=clusterhost_id,
            **kwargs
        )
    raise exception.InvalidParameter(
        'clusterhost id %s type is not int compatible' % clusterhost_id
    )


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTERS
)
@utils.wrap_to_dict(RESP_FIELDS)
def get_cluster(
    cluster_id, exception_when_missing=True,
    user=None, session=None, **kwargs
):
    """Get cluster info."""
    return _get_cluster(
        cluster_id,
        session=session,
        exception_when_missing=exception_when_missing
    )


@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTERS)
def is_cluster_os_ready(
    cluster_id, exception_when_missing=True,
    user=None, session=None, **kwargs
):
    cluster = utils.get_db_object(
        session, models.Cluster, exception_when_missing, id=cluster_id)

    all_states = ([i.host.state.ready for i in cluster.clusterhosts])

    logging.info("is_cluster_os_ready: all_states %s" % all_states)

    return all(all_states)


def check_cluster_validated(cluster):
    """Check cluster is validated."""
    if not cluster.config_validated:
        raise exception.Forbidden(
            'cluster %s is not validated' % cluster.name
        )


def check_clusterhost_validated(clusterhost):
    """Check clusterhost is validated."""
    if not clusterhost.config_validated:
        raise exception.Forbidden(
            'clusterhost %s is not validated' % clusterhost.name
        )


def check_cluster_editable(
    cluster, user=None,
    check_in_installing=False
):
    """Check if cluster is editable.

    If we try to set cluster
    reinstall_distributed_system attribute or any
    checking to make sure the cluster is not in installing state,
    we can set check_in_installing to True.
    Otherwise we will make sure the cluster is not in deploying or
    deployed.
    If user is not admin or not the owner of the cluster, the check
    will fail to make sure he can not update the cluster attributes.
    """
    if check_in_installing:
        if cluster.state.state == 'INSTALLING':
            raise exception.Forbidden(
                'cluster %s is not editable '
                'when state is installing' % cluster.name
            )
#    elif (
#        cluster.flavor_name and
#        not cluster.reinstall_distributed_system
#    ):
#        raise exception.Forbidden(
#            'cluster %s is not editable '
#            'when not to be reinstalled' % cluster.name
#        )
    if user and not user.is_admin and cluster.creator_id != user.id:
        raise exception.Forbidden(
            'cluster %s is not editable '
            'when user is not admin or cluster owner' % cluster.name
        )


def is_cluster_editable(
    cluster, user=None,
    check_in_installing=False
):
    """Get if cluster is editble."""
    try:
        check_cluster_editable(
            cluster, user=user,
            check_in_installing=check_in_installing
        )
        return True
    except exception.Forbidden:
        return False


@utils.supported_filters(
    ADDED_FIELDS,
    optional_support_keys=OPTIONAL_ADDED_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@utils.input_validates(name=utils.check_name)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_ADD_CLUSTER
)
@utils.wrap_to_dict(RESP_FIELDS)
def add_cluster(
    exception_when_existing=True,
    name=None, adapter_id=None, flavor_id=None,
    user=None, session=None, **kwargs
):
    """Create a cluster."""
    adapter = adapter_api.get_adapter(
        adapter_id, user=user, session=session
    )
    # if flavor_id is not None, also set flavor field.
    # In future maybe we can move the use of flavor from
    # models.py to db/api and explictly get flavor when
    # needed instead of setting flavor into cluster record.
    flavor = {}
    if flavor_id:
        flavor = adapter_api.get_flavor(
            flavor_id,
            user=user, session=session
        )
        if flavor['adapter_id'] != adapter['id']:
            raise exception.InvalidParameter(
                'flavor %s is not of adapter %s' % (
                    flavor_id, adapter_id
                )
            )

    cluster = utils.add_db_object(
        session, models.Cluster, exception_when_existing,
        name, user.id, adapter_id=adapter_id,
        flavor_id=flavor_id, flavor=flavor, **kwargs
    )
    return cluster


@utils.supported_filters(
    optional_support_keys=UPDATED_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@utils.input_validates(name=utils.check_name)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_ADD_CLUSTER
)
@utils.wrap_to_dict(RESP_FIELDS)
def update_cluster(cluster_id, user=None, session=None, **kwargs):
    """Update a cluster."""
    cluster = _get_cluster(
        cluster_id, session=session
    )
    check_cluster_editable(
        cluster, user=user,
        check_in_installing=(
            kwargs.get('reinstall_distributed_system', False)
        )
    )
    return utils.update_db_object(session, cluster, **kwargs)


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_DEL_CLUSTER
)
@utils.wrap_to_dict(
    RESP_FIELDS + ['status', 'cluster', 'hosts'],
    cluster=RESP_FIELDS,
    hosts=RESP_CLUSTERHOST_FIELDS
)
def del_cluster(
    cluster_id, force=False, from_database_only=False,
    delete_underlying_host=False, user=None, session=None, **kwargs
):
    """Delete a cluster.

    If force, the cluster will be deleted anyway. It is used by cli to
    force clean a cluster in any case.
    If from_database_only, the cluster recored will only be removed from
    database. Otherwise, a del task is sent to celery to do clean deletion.
    If delete_underlying_host, all hosts under this cluster will also be
    deleted.
    The backend will call del_cluster again with from_database_only set
    when it has done the deletion work on os installer/package installer.
    """
    cluster = _get_cluster(
        cluster_id, session=session
    )
    logging.debug(
        'delete cluster %s with force=%s '
        'from_database_only=%s delete_underlying_host=%s',
        cluster.id, force, from_database_only, delete_underlying_host
    )
    # force set cluster state to ERROR and the state of any clusterhost
    # in the cluster to ERROR when we want to delete the cluster anyway
    # even the cluster is in installing or already installed.
    # It let the api know the deleting is in doing when backend is doing
    # the real deleting.
    # In future we may import a new state like INDELETE to indicate
    # the deleting is processing.
    # We need discuss about if we can delete a cluster when it is already
    # installed by api.
    for clusterhost in cluster.clusterhosts:
        if clusterhost.state.state != 'UNINITIALIZED' and force:
            clusterhost.state.state = 'ERROR'
        if delete_underlying_host:
            host = clusterhost.host
            if host.state.state != 'UNINITIALIZED' and force:
                host.state.state = 'ERROR'
    if cluster.state.state != 'UNINITIALIZED' and force:
        cluster.state.state = 'ERROR'

    check_cluster_editable(
        cluster, user=user,
        check_in_installing=True
    )

    # delete underlying host if delete_underlying_host is set.
    if delete_underlying_host:
        for clusterhost in cluster.clusterhosts:
            # delete underlying host only user has permission.
            from compass.db.api import host as host_api
            host = clusterhost.host
            if host_api.is_host_editable(
                host, user=user, check_in_installing=True
            ):
                # Delete host record directly in database when there is no need
                # to do the deletion in backend or from_database_only is set.
                if host.state.state == 'UNINITIALIZED' or from_database_only:
                    utils.del_db_object(
                        session, host
                    )

    # Delete cluster record directly in database when there
    # is no need to do the deletion in backend or from_database_only is set.
    if cluster.state.state == 'UNINITIALIZED' or from_database_only:
        return utils.del_db_object(
            session, cluster
        )
    else:
        from compass.tasks import client as celery_client
        logging.info('send del cluster %s task to celery', cluster_id)
        celery_client.celery.send_task(
            'compass.tasks.delete_cluster',
            (
                user.email, cluster.id,
                [
                    clusterhost.host_id
                    for clusterhost in cluster.clusterhosts
                ],
                delete_underlying_host
            ),
            queue=user.email,
            exchange=user.email,
            routing_key=user.email
        )
        return {
            'status': 'delete action is sent',
            'cluster': cluster,
            'hosts': cluster.clusterhosts
        }


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTER_CONFIG
)
@utils.wrap_to_dict(RESP_CONFIG_FIELDS)
def get_cluster_config(cluster_id, user=None, session=None, **kwargs):
    """Get cluster config."""
    return _get_cluster(cluster_id, session=session)


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTER_CONFIG
)
@utils.wrap_to_dict(RESP_DEPLOYED_CONFIG_FIELDS)
def get_cluster_deployed_config(cluster_id, user=None, session=None, **kwargs):
    """Get cluster deployed config."""
    return _get_cluster(cluster_id, session=session)


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_METADATAS
)
@utils.wrap_to_dict(RESP_METADATA_FIELDS)
def get_cluster_metadata(cluster_id, user=None, session=None, **kwargs):
    """Get cluster metadata.

    If no flavor in the cluster, it means this is a os only cluster.
    We ignore package metadata for os only cluster.
    """
    cluster = _get_cluster(cluster_id, session=session)
    metadatas = {}
    os_name = cluster.os_name
    if os_name:
        metadatas.update(
            metadata_api.get_os_metadata(
                os_name, session=session
            )
        )
    flavor_id = cluster.flavor_id
    if flavor_id:
        metadatas.update(
            metadata_api.get_flavor_metadata(
                flavor_id,
                user=user, session=session
            )
        )

    return metadatas


def _cluster_os_config_validates(
    config, cluster, session=None, user=None, **kwargs
):
    """Check cluster os config validation."""
    metadata_api.validate_os_config(
        config, cluster.os_id
    )


def _cluster_package_config_validates(
    config, cluster, session=None, user=None, **kwargs
):
    """Check cluster package config validation."""
    metadata_api.validate_flavor_config(
        config, cluster.flavor_id
    )


@utils.input_validates_with_args(
    put_os_config=_cluster_os_config_validates,
    put_package_config=_cluster_package_config_validates
)
@utils.output_validates_with_args(
    os_config=_cluster_os_config_validates,
    package_config=_cluster_package_config_validates
)
@utils.wrap_to_dict(RESP_CONFIG_FIELDS)
def _update_cluster_config(cluster, session=None, user=None, **kwargs):
    """Update a cluster config."""
    check_cluster_editable(cluster, user=user)
    return utils.update_db_object(
        session, cluster, **kwargs
    )


# replace os_config to deployed_os_config,
# package_config to deployed_package_config
@utils.replace_filters(
    os_config='deployed_os_config',
    package_config='deployed_package_config'
)
@utils.supported_filters(
    optional_support_keys=UPDATED_DEPLOYED_CONFIG_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_ADD_CLUSTER_CONFIG
)
@utils.wrap_to_dict(RESP_DEPLOYED_CONFIG_FIELDS)
def update_cluster_deployed_config(
    cluster_id, user=None, session=None, **kwargs
):
    """Update cluster deployed config."""
    cluster = _get_cluster(cluster_id, session=session)
    check_cluster_editable(cluster, user=user)
    check_cluster_validated(cluster)
    return utils.update_db_object(
        session, cluster, **kwargs
    )


# replace os_config to put_os_config,
# package_config to put_package_config in kwargs.
# It tells db these fields will be updated not patched.
@utils.replace_filters(
    os_config='put_os_config',
    package_config='put_package_config'
)
@utils.supported_filters(
    optional_support_keys=UPDATED_CONFIG_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_ADD_CLUSTER_CONFIG
)
def update_cluster_config(cluster_id, user=None, session=None, **kwargs):
    """Update cluster config."""
    cluster = _get_cluster(cluster_id, session=session)
    return _update_cluster_config(
        cluster, session=session, user=user, **kwargs
    )


# replace os_config to patched_os_config and
# package_config to patched_package_config in kwargs.
# It tells db these fields will be patched not updated.
@utils.replace_filters(
    os_config='patched_os_config',
    package_config='patched_package_config'
)
@utils.supported_filters(
    optional_support_keys=PATCHED_CONFIG_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_ADD_CLUSTER_CONFIG
)
def patch_cluster_config(cluster_id, user=None, session=None, **kwargs):
    """patch cluster config."""
    cluster = _get_cluster(cluster_id, session=session)
    return _update_cluster_config(
        cluster, session=session, user=user, **kwargs
    )


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_DEL_CLUSTER_CONFIG
)
@utils.wrap_to_dict(RESP_CONFIG_FIELDS)
def del_cluster_config(cluster_id, user=None, session=None):
    """Delete a cluster config."""
    cluster = _get_cluster(
        cluster_id, session=session
    )
    check_cluster_editable(cluster, user=user)
    return utils.update_db_object(
        session, cluster, os_config={},
        package_config={}, config_validated=False
    )


def _roles_validates(roles, cluster, session=None, user=None):
    """Check roles is validated to a cluster's roles."""
    if roles:
        if not cluster.flavor_name:
            raise exception.InvalidParameter(
                'not flavor in cluster %s' % cluster.name
            )
        cluster_roles = [role['name'] for role in cluster.flavor['roles']]
        for role in roles:
            if role not in cluster_roles:
                raise exception.InvalidParameter(
                    'role %s is not in cluster roles %s' % (
                        role, cluster_roles
                    )
                )


def _cluster_host_roles_validates(
    value, cluster, host, session=None, user=None, **kwargs
):
    """Check clusterhost roles is validated by cluster and host."""
    _roles_validates(value, cluster, session=session, user=user)


def _clusterhost_roles_validates(
    value, clusterhost, session=None, user=None, **kwargs
):
    """Check clusterhost roles is validated by clusterhost."""
    _roles_validates(
        value, clusterhost.cluster, session=session, user=user
    )


@utils.supported_filters(
    optional_support_keys=UPDATED_HOST_FIELDS,
    ignore_support_keys=UPDATED_CLUSTERHOST_FIELDS
)
@utils.input_validates(name=utils.check_name)
def _add_host_if_not_exist(
    machine_id, cluster, session=None, user=None, **kwargs
):
    """Add underlying host if it does not exist."""
    from compass.db.api import host as host_api
    host = host_api.get_host_internal(
        machine_id, session=session, exception_when_missing=False
    )
    if host:
        if kwargs:
            # ignore update underlying host if host is not editable.
            from compass.db.api import host as host_api
            if host_api.is_host_editable(
                host, user=cluster.creator,
                check_in_installing=kwargs.get('reinstall_os', False),
            ):
                utils.update_db_object(
                    session, host,
                    **kwargs
                )
            else:
                logging.debug(
                    'ignore update host host %s '
                    'since it is not editable' % host.name
                )
        else:
            logging.debug('nothing to update for host %s', host.name)
    else:
        from compass.db.api import adapter_holder as adapter_api
        adapter = adapter_api.get_adapter(
            cluster.adapter_name, user=user, session=session
        )
        host = utils.add_db_object(
            session, models.Host, False, machine_id,
            os_name=cluster.os_name,
            os_installer=adapter['os_installer'],
            creator=cluster.creator,
            **kwargs
        )
    return host


@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTERHOST_FIELDS,
    ignore_support_keys=UPDATED_HOST_FIELDS
)
@utils.input_validates_with_args(
    roles=_cluster_host_roles_validates
)
def _add_clusterhost_only(
    cluster, host,
    exception_when_existing=False,
    session=None, user=None,
    **kwargs
):
    """Get clusterhost only."""
    if not cluster.state.state == "UNINITIALIZED":
        cluster.state.ready = False
        cluster.state.state = "UNINITIALIZED"
        cluster.state.percentage = 0.0
        utils.update_db_object(session, cluster.state, state="UNINITIALIZED")

    return utils.add_db_object(
        session, models.ClusterHost, exception_when_existing,
        cluster.id, host.id, **kwargs
    )


@utils.supported_filters(
    ADDED_HOST_FIELDS,
    optional_support_keys=UPDATED_HOST_FIELDS + UPDATED_CLUSTERHOST_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
def _add_clusterhost(
        cluster,
        exception_when_existing=False,
        session=None, user=None, machine_id=None, **kwargs
):
    """Add clusterhost and add underlying host if it does not exist."""
    host = _add_host_if_not_exist(
        machine_id, cluster, session=session,
        user=user, **kwargs
    )

    return _add_clusterhost_only(
        cluster, host, exception_when_existing=exception_when_existing,
        session=session, user=user, **kwargs
    )


def _add_clusterhosts(cluster, machines, session=None, user=None):
    """Add machines to cluster.

    Args:
       machines: list of dict which contains clusterost attr to update.

    Examples:
       [{'machine_id': 1, 'name': 'host1'}]
    """
    check_cluster_editable(
        cluster, user=user,
        check_in_installing=True
    )
    if cluster.state.state == 'SUCCESSFUL':
        cluster.state.state == 'UPDATE_PREPARING'
    for machine_dict in machines:
        _add_clusterhost(
            cluster, session=session, user=user, **machine_dict
        )


def _remove_clusterhosts(cluster, hosts, session=None, user=None):
    """Remove hosts from cluster.

    Args:
       hosts: list of host id.
    """
    check_cluster_editable(
        cluster, user=user,
        check_in_installing=True
    )
    utils.del_db_objects(
        session, models.ClusterHost,
        cluster_id=cluster.id, host_id=hosts
    )


def _set_clusterhosts(cluster, machines, session=None, user=None):
    """set machines to cluster.

    Args:
       machines: list of dict which contains clusterost attr to update.

    Examples:
       [{'machine_id': 1, 'name': 'host1'}]
    """
    check_cluster_editable(
        cluster, user=user,
        check_in_installing=True
    )
    utils.del_db_objects(
        session, models.ClusterHost,
        cluster_id=cluster.id
    )
    if cluster.state.state == 'SUCCESSFUL':
        cluster.state.state = 'UPDATE_PREPARING'
    for machine_dict in machines:
        _add_clusterhost(
            cluster, True, session=session, user=user, **machine_dict
        )


@utils.supported_filters(optional_support_keys=SUPPORTED_CLUSTERHOST_FIELDS)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTERHOSTS
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_FIELDS)
def list_cluster_hosts(cluster_id, user=None, session=None, **filters):
    """List clusterhosts of a cluster."""
    cluster = _get_cluster(cluster_id, session=session)
    return utils.list_db_objects(
        session, models.ClusterHost, cluster_id=cluster.id,
        **filters
    )


@utils.supported_filters(optional_support_keys=SUPPORTED_CLUSTERHOST_FIELDS)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTERHOSTS
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_FIELDS)
def list_clusterhosts(user=None, session=None, **filters):
    """List all clusterhosts."""
    return utils.list_db_objects(
        session, models.ClusterHost, **filters
    )


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTERHOSTS
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_FIELDS)
def get_cluster_host(
    cluster_id, host_id, exception_when_missing=True,
    user=None, session=None, **kwargs
):
    """Get clusterhost info by cluster id and host id."""
    return _get_cluster_host(
        cluster_id, host_id, session=session,
        exception_when_missing=exception_when_missing,
    )


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTERHOSTS
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_FIELDS)
def get_clusterhost(
    clusterhost_id, exception_when_missing=True,
    user=None, session=None, **kwargs
):
    """Get clusterhost info by clusterhost id."""
    return _get_clusterhost(
        clusterhost_id, session=session,
        exception_when_missing=exception_when_missing,
        user=user
    )


@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_UPDATE_CLUSTER_HOSTS
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_FIELDS)
def add_cluster_host(
    cluster_id, exception_when_existing=True,
    user=None, session=None, **kwargs
):
    """Add a host to a cluster."""
    cluster = _get_cluster(cluster_id, session=session)
    check_cluster_editable(
        cluster, user=user,
        check_in_installing=True
    )
    if cluster.state.state == 'SUCCESSFUL':
        cluster.state.state = 'UPDATE_PREPARING'
    return _add_clusterhost(
        cluster, exception_when_existing,
        session=session, user=user, **kwargs
    )


@utils.supported_filters(
    optional_support_keys=UPDATED_HOST_FIELDS,
    ignore_support_keys=(
        UPDATED_CLUSTERHOST_FIELDS +
        PATCHED_CLUSTERHOST_FIELDS
    )
)
def _update_host_if_necessary(
    clusterhost, session=None, user=None, **kwargs
):
    """Update underlying host if there is something to update."""
    host = clusterhost.host
    if kwargs:
        # ignore update underlying host if the host is not editable.
        from compass.db.api import host as host_api
        if host_api.is_host_editable(
            host, user=clusterhost.cluster.creator,
            check_in_installing=kwargs.get('reinstall_os', False),
        ):
            utils.update_db_object(
                session, host,
                **kwargs
            )
        else:
            logging.debug(
                'ignore update host %s since it is not editable' % host.name
            )
    else:
        logging.debug(
            'nothing to update for host %s', host.name
        )
    return host


@utils.supported_filters(
    optional_support_keys=(
        UPDATED_CLUSTERHOST_FIELDS +
        PATCHED_CLUSTERHOST_FIELDS
    ),
    ignore_support_keys=UPDATED_HOST_FIELDS
)
@utils.input_validates_with_args(
    roles=_clusterhost_roles_validates,
    patched_roles=_clusterhost_roles_validates
)
def _update_clusterhost_only(
    clusterhost, session=None, user=None, **kwargs
):
    """Update clusterhost only."""
    check_cluster_editable(clusterhost.cluster, user=user)
    return utils.update_db_object(
        session, clusterhost, **kwargs
    )


@utils.wrap_to_dict(RESP_CLUSTERHOST_FIELDS)
def _update_clusterhost(clusterhost, session=None, user=None, **kwargs):
    """Update clusterhost and underlying host if necessary."""
    _update_host_if_necessary(
        clusterhost, session=session, user=user, **kwargs
    )
    return _update_clusterhost_only(
        clusterhost, session=session, user=user, **kwargs
    )


@utils.supported_filters(
    optional_support_keys=(UPDATED_HOST_FIELDS + UPDATED_CLUSTERHOST_FIELDS),
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_UPDATE_CLUSTER_HOSTS
)
def update_cluster_host(
    cluster_id, host_id, user=None,
    session=None, **kwargs
):
    """Update clusterhost by cluster id and host id."""
    logging.info('updating kwargs: %s', kwargs)
    clusterhost = _get_cluster_host(
        cluster_id, host_id, session=session
    )
    return _update_clusterhost(
        clusterhost, session=session, user=user, **kwargs
    )


@utils.supported_filters(
    optional_support_keys=(UPDATED_HOST_FIELDS + UPDATED_CLUSTERHOST_FIELDS),
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_UPDATE_CLUSTER_HOSTS
)
def update_clusterhost(
    clusterhost_id, user=None,
    session=None, **kwargs
):
    """Update clusterhost by clusterhost id."""
    clusterhost = _get_clusterhost(
        clusterhost_id, session=session
    )
    return _update_clusterhost(
        clusterhost, session=session, user=user, **kwargs
    )


# replace roles to patched_roles in kwargs.
# It tells db roles field will be patched.
@utils.replace_filters(
    roles='patched_roles'
)
@utils.supported_filters(
    optional_support_keys=PATCHED_CLUSTERHOST_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_UPDATE_CLUSTER_HOSTS
)
def patch_cluster_host(
    cluster_id, host_id, user=None,
    session=None, **kwargs
):
    """Patch clusterhost by cluster id and host id."""
    logging.info("kwargs are %s", kwargs)
    clusterhost = _get_cluster_host(
        cluster_id, host_id, session=session
    )
    updated_clusterhost = _update_clusterhost(
        clusterhost, session=session, user=user, **kwargs
    )
    return updated_clusterhost


# replace roles to patched_roles in kwargs.
# It tells db roles field will be patched.
@utils.replace_filters(
    roles='patched_roles'
)
@utils.supported_filters(
    optional_support_keys=PATCHED_CLUSTERHOST_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_UPDATE_CLUSTER_HOSTS
)
def patch_clusterhost(
    clusterhost_id, user=None, session=None,
    **kwargs
):
    """Patch clusterhost by clusterhost id."""
    clusterhost = _get_clusterhost(
        clusterhost_id, session=session
    )
    return _update_clusterhost(
        clusterhost, session=session, user=user, **kwargs
    )


@user_api.check_user_permission(
    permission.PERMISSION_DEL_CLUSTER_HOST
)
@utils.wrap_to_dict(
    RESP_CLUSTERHOST_FIELDS + ['status', 'host'],
    host=RESP_CLUSTERHOST_FIELDS
)
def _del_cluster_host(
    clusterhost,
    force=False, from_database_only=False,
    delete_underlying_host=False, user=None,
    session=None, **kwargs
):
    """delete clusterhost.

    If force, the cluster host will be deleted anyway.
    If from_database_only, the cluster host recored will only be
    deleted from database. Otherwise a celery task sent to do
    clean deletion.
    If delete_underlying_host, the underlying host will also be deleted.
    The backend will call _del_cluster_host again when the clusterhost is
    deleted from os installer/package installer with from_database_only
    set.
    """
    # force set clusterhost state to ERROR when we want to delete the
    # clusterhost anyway even the clusterhost is in installing or already
    # installed. It let the api know the deleting is in doing when backend
    # is doing the real deleting. In future we may import a new state like
    # INDELETE to indicate the deleting is processing.
    # We need discuss about if we can delete a clusterhost when it is already
    # installed by api.
    if clusterhost.state.state != 'UNINITIALIZED' and force:
        clusterhost.state.state = 'ERROR'
    if not force:
        check_cluster_editable(
            clusterhost.cluster, user=user,
            check_in_installing=True
        )
    # delete underlying host if delete_underlying_host is set.
    if delete_underlying_host:
        host = clusterhost.host
        if host.state.state != 'UNINITIALIZED' and force:
            host.state.state = 'ERROR'
        # only delete the host when user have the permission to delete it.
        import compass.db.api.host as host_api
        if host_api.is_host_editable(
            host, user=user,
            check_in_installing=True
        ):
            # if there is no need to do the deletion by backend or
            # from_database_only is set, we only delete the record
            # in database.
            if host.state.state == 'UNINITIALIZED' or from_database_only:
                utils.del_db_object(
                    session, host
                )

    # if there is no need to do the deletion by backend or
    # from_database_only is set, we only delete the record in database.
    if clusterhost.state.state == 'UNINITIALIZED' or from_database_only:
        return utils.del_db_object(
            session, clusterhost
        )
    else:
        logging.info(
            'send del cluster %s host %s task to celery',
            clusterhost.cluster_id, clusterhost.host_id
        )
        from compass.tasks import client as celery_client
        celery_client.celery.send_task(
            'compass.tasks.delete_cluster_host',
            (
                user.email, clusterhost.cluster_id, clusterhost.host_id,
                delete_underlying_host
            ),
            queue=user.email,
            exchange=user.email,
            routing_key=user.email
        )
        return {
            'status': 'delete action sent',
            'host': clusterhost,
        }


@utils.supported_filters([])
@database.run_in_session()
def del_cluster_host(
    cluster_id, host_id,
    force=False, from_database_only=False,
    delete_underlying_host=False, user=None,
    session=None, **kwargs
):
    """Delete clusterhost by cluster id and host id."""
    clusterhost = _get_cluster_host(
        cluster_id, host_id, session=session
    )
    return _del_cluster_host(
        clusterhost, force=force, from_database_only=from_database_only,
        delete_underlying_host=delete_underlying_host, user=user,
        session=session, **kwargs
    )


@utils.supported_filters([])
@database.run_in_session()
def del_clusterhost(
    clusterhost_id,
    force=False, from_database_only=False,
    delete_underlying_host=False, user=None,
    session=None, **kwargs
):
    """Delete clusterhost by clusterhost id."""
    clusterhost = _get_clusterhost(
        clusterhost_id, session=session
    )
    return _del_cluster_host(
        clusterhost, force=force, from_database_only=from_database_only,
        delete_underlying_host=delete_underlying_host, user=user,
        session=session, **kwargs
    )


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTERHOST_CONFIG
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_CONFIG_FIELDS)
def get_cluster_host_config(
        cluster_id, host_id, user=None,
        session=None, **kwargs
):
    """Get clusterhost config by cluster id and host id."""
    return _get_cluster_host(
        cluster_id, host_id, session=session
    )


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTERHOST_CONFIG
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_DEPLOYED_CONFIG_FIELDS)
def get_cluster_host_deployed_config(
    cluster_id, host_id, user=None, session=None, **kwargs
):
    """Get clusterhost deployed config by cluster id and host id."""
    return _get_cluster_host(
        cluster_id, host_id, session=session
    )


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTERHOST_CONFIG
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_CONFIG_FIELDS)
def get_clusterhost_config(clusterhost_id, user=None, session=None, **kwargs):
    """Get clusterhost config by clusterhost id."""
    return _get_clusterhost(
        clusterhost_id, session=session
    )


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_CLUSTERHOST_CONFIG
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_DEPLOYED_CONFIG_FIELDS)
def get_clusterhost_deployed_config(
    clusterhost_id, user=None,
    session=None, **kwargs
):
    """Get clusterhost deployed config by clusterhost id."""
    return _get_clusterhost(
        clusterhost_id, session=session
    )


def _clusterhost_os_config_validates(
    config, clusterhost, session=None, user=None, **kwargs
):
    """Validate clusterhost's underlying host os config."""
    from compass.db.api import host as host_api
    host = clusterhost.host
    host_api.check_host_editable(host, user=user)
    metadata_api.validate_os_config(
        config, host.os_id
    )


def _clusterhost_package_config_validates(
    config, clusterhost, session=None, user=None, **kwargs
):
    """Validate clusterhost's cluster package config."""
    cluster = clusterhost.cluster
    check_cluster_editable(cluster, user=user)
    metadata_api.validate_flavor_config(
        config, cluster.flavor_id
    )


def _filter_clusterhost_host_editable(
    config, clusterhost, session=None, user=None, **kwargs
):
    """Filter fields if the underlying host is not editable."""
    from compass.db.api import host as host_api
    host = clusterhost.host
    return host_api.is_host_editable(host, user=user)


@utils.input_filters(
    put_os_config=_filter_clusterhost_host_editable,
    patched_os_config=_filter_clusterhost_host_editable
)
@utils.input_validates_with_args(
    put_os_config=_clusterhost_os_config_validates,
    put_package_config=_clusterhost_package_config_validates
)
@utils.output_validates_with_args(
    os_config=_clusterhost_os_config_validates,
    package_config=_clusterhost_package_config_validates
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_CONFIG_FIELDS)
def _update_clusterhost_config(clusterhost, session=None, user=None, **kwargs):
    """Update clusterhost config."""
    return utils.update_db_object(
        session, clusterhost, **kwargs
    )


def _clusterhost_host_validated(
    config, clusterhost, session=None, user=None, **kwargs
):
    """Check clusterhost's underlying host is validated."""
    from compass.db.api import host as host_api
    host = clusterhost.host
    host_api.check_host_editable(host, user=user)
    host_api.check_host_validated(host)


def _clusterhost_cluster_validated(
    config, clusterhost, session=None, user=None, **kwargs
):
    """Check clusterhost's cluster is validated."""
    cluster = clusterhost.cluster
    check_cluster_editable(cluster, user=user)
    check_clusterhost_validated(clusterhost)


@utils.input_filters(
    deployed_os_config=_filter_clusterhost_host_editable,
)
@utils.input_validates_with_args(
    deployed_os_config=_clusterhost_host_validated,
    deployed_package_config=_clusterhost_cluster_validated
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_DEPLOYED_CONFIG_FIELDS)
def _update_clusterhost_deployed_config(
    clusterhost, session=None, user=None, **kwargs
):
    """Update clusterhost deployed config."""
    return utils.update_db_object(
        session, clusterhost, **kwargs
    )


# replace os_config to put_os_config and
# package_config to put_package_config in kwargs.
# It tells db these fields will be updated not patched.
@utils.replace_filters(
    os_config='put_os_config',
    package_config='put_package_config'
)
@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTERHOST_CONFIG_FIELDS,
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_ADD_CLUSTERHOST_CONFIG
)
def update_cluster_host_config(
    cluster_id, host_id, user=None, session=None, **kwargs
):
    """Update clusterhost config by cluster id and host id."""
    clusterhost = _get_cluster_host(
        cluster_id, host_id, session=session
    )
    return _update_clusterhost_config(
        clusterhost, user=user, session=session, **kwargs
    )


# replace os_config to deployed_os_config and
# package_config to deployed_package_config in kwargs.
@utils.replace_filters(
    os_config='deployed_os_config',
    package_config='deployed_package_config'
)
@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTERHOST_DEPLOYED_CONFIG_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_ADD_CLUSTERHOST_CONFIG
)
def update_cluster_host_deployed_config(
    cluster_id, host_id, user=None, session=None, **kwargs
):
    """Update clusterhost deployed config by cluster id and host id."""
    clusterhost = _get_cluster_host(
        cluster_id, host_id, session=session
    )
    return _update_clusterhost_deployed_config(
        clusterhost, session=session, user=user, **kwargs
    )


# replace os_config to put_os_config and
# package_config to put_package_config in kwargs.
# It tells db these fields will be updated not patched.
@utils.replace_filters(
    os_config='put_os_config',
    package_config='put_package_config'
)
@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTERHOST_CONFIG_FIELDS,
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_ADD_CLUSTERHOST_CONFIG
)
def update_clusterhost_config(
    clusterhost_id, user=None, session=None, **kwargs
):
    """Update clusterhost config by clusterhost id."""
    clusterhost = _get_clusterhost(
        clusterhost_id, session=session
    )
    return _update_clusterhost_config(
        clusterhost, session=session, user=user, **kwargs
    )


# replace os_config to deployed_os_config and
# package_config to deployed_package_config in kwargs.
@utils.replace_filters(
    os_config='deployed_os_config',
    package_config='deployed_package_config'
)
@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTERHOST_DEPLOYED_CONFIG_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_ADD_CLUSTERHOST_CONFIG
)
def update_clusterhost_deployed_config(
    clusterhost_id, user=None, session=None, **kwargs
):
    """Update clusterhost deployed config by clusterhost id."""
    clusterhost = _get_clusterhost(
        clusterhost_id, session=session
    )
    return _update_clusterhost_deployed_config(
        clusterhost, session=session, user=user, **kwargs
    )


# replace os_config to patched_os_config and
# package_config to patched_package_config in kwargs
# It tells db these fields will be patched not updated.
@utils.replace_filters(
    os_config='patched_os_config',
    package_config='patched_package_config'
)
@utils.supported_filters(
    optional_support_keys=PATCHED_CLUSTERHOST_CONFIG_FIELDS,
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_ADD_CLUSTERHOST_CONFIG
)
def patch_cluster_host_config(
    cluster_id, host_id, user=None, session=None, **kwargs
):
    """patch clusterhost config by cluster id and host id."""
    clusterhost = _get_cluster_host(
        cluster_id, host_id, session=session
    )
    return _update_clusterhost_config(
        clusterhost, session=session, user=user, **kwargs
    )


# replace os_config to patched_os_config and
# package_config to patched_package_config in kwargs
# It tells db these fields will be patched not updated.
@utils.replace_filters(
    os_config='patched_os_config',
    package_config='patched_package_config'
)
@utils.supported_filters(
    optional_support_keys=PATCHED_CLUSTERHOST_CONFIG_FIELDS,
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_ADD_CLUSTERHOST_CONFIG
)
def patch_clusterhost_config(
    clusterhost_id, user=None, session=None, **kwargs
):
    """patch clusterhost config by clusterhost id."""
    clusterhost = _get_clusterhost(
        clusterhost_id, session=session
    )
    return _update_clusterhost_config(
        clusterhost, session=session, user=user, **kwargs
    )


def _clusterhost_host_editable(
    config, clusterhost, session=None, user=None, **kwargs
):
    """Check clusterhost underlying host is editable."""
    from compass.db.api import host as host_api
    host_api.check_host_editable(clusterhost.host, user=user)


def _clusterhost_cluster_editable(
    config, clusterhost, session=None, user=None, **kwargs
):
    """Check clusterhost's cluster is editable."""
    check_cluster_editable(clusterhost.cluster, user=user)


@utils.supported_filters(
    optional_support_keys=['os_config', 'package_config']
)
@utils.input_filters(
    os_config=_filter_clusterhost_host_editable,
)
@utils.output_validates_with_args(
    package_config=_clusterhost_cluster_editable
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_CONFIG_FIELDS)
def _delete_clusterhost_config(
    clusterhost, session=None, user=None, **kwargs
):
    """delete clusterhost config."""
    return utils.update_db_object(
        session, clusterhost, config_validated=False,
        **kwargs
    )


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_DEL_CLUSTERHOST_CONFIG
)
def delete_cluster_host_config(
    cluster_id, host_id, user=None, session=None
):
    """Delete a clusterhost config by cluster id and host id."""
    clusterhost = _get_cluster_host(
        cluster_id, host_id, session=session
    )
    return _delete_clusterhost_config(
        clusterhost, session=session, user=user,
        os_config={}, package_config={}
    )


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_DEL_CLUSTERHOST_CONFIG
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_CONFIG_FIELDS)
def delete_clusterhost_config(clusterhost_id, user=None, session=None):
    """Delet a clusterhost config by clusterhost id."""
    clusterhost = _get_clusterhost(
        clusterhost_id, session=session
    )
    return _delete_clusterhost_config(
        clusterhost, session=session, user=user,
        os_config={}, package_config={}
    )


@utils.supported_filters(
    optional_support_keys=['add_hosts', 'remove_hosts', 'set_hosts']
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_UPDATE_CLUSTER_HOSTS
)
@utils.wrap_to_dict(
    ['hosts'],
    hosts=RESP_CLUSTERHOST_FIELDS
)
def update_cluster_hosts(
    cluster_id, add_hosts={}, set_hosts=None,
    remove_hosts={}, user=None, session=None
):
    """Update cluster hosts."""
    cluster = _get_cluster(cluster_id, session=session)
    if remove_hosts:
        _remove_clusterhosts(
            cluster, session=session, user=user, **remove_hosts
        )
    if add_hosts:
        _add_clusterhosts(
            cluster, session=session, user=user, **add_hosts
        )
    if set_hosts is not None:
        _set_clusterhosts(
            cluster, session=session, user=user, **set_hosts
        )

    return {
        'hosts': list_cluster_hosts(cluster_id, session=session)
    }


def validate_clusterhost(clusterhost, session=None):
    """validate clusterhost."""
    roles = clusterhost.roles
    if not roles:
        if clusterhost.cluster.flavor_name:
            raise exception.InvalidParameter(
                'empty roles for clusterhost %s' % clusterhost.name
            )


def validate_cluster(cluster, session=None):
    """Validate cluster."""
    if not cluster.clusterhosts:
        raise exception.InvalidParameter(
            'cluster %s does not have any hosts' % cluster.name
        )
    if cluster.flavor_name:
        cluster_roles = cluster.flavor['roles']
    else:
        cluster_roles = []
    necessary_roles = set([
        role['name'] for role in cluster_roles if not role.get('optional')
    ])
    clusterhost_roles = set([])
    interface_subnets = {}
    for clusterhost in cluster.clusterhosts:
        roles = clusterhost.roles
        for role in roles:
            clusterhost_roles.add(role['name'])
        host = clusterhost.host
        for host_network in host.host_networks:
            interface_subnets.setdefault(
                host_network.interface, set([])
            ).add(host_network.subnet.subnet)
    missing_roles = necessary_roles - clusterhost_roles
    if missing_roles:
        raise exception.InvalidParameter(
            'cluster %s have some roles %s not assigned to any host' % (
                cluster.name, list(missing_roles)
            )
        )
    for interface, subnets in interface_subnets.items():
        if len(subnets) > 1:
            raise exception.InvalidParameter(
                'cluster %s multi subnets %s in interface %s' % (
                    cluster.name, list(subnets), interface
                )
            )


@utils.supported_filters(optional_support_keys=['review'])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_REVIEW_CLUSTER
)
@utils.wrap_to_dict(
    RESP_REVIEW_FIELDS,
    cluster=RESP_CONFIG_FIELDS,
    hosts=RESP_CLUSTERHOST_CONFIG_FIELDS
)
def review_cluster(cluster_id, review={}, user=None, session=None, **kwargs):
    """review cluster.

    Args:
       cluster_id: the cluster id.
       review: dict contains hosts to be reviewed. either contains key
               hosts or clusterhosts. where hosts is a list of host id,
               clusterhosts is a list of clusterhost id.
    """
    from compass.db.api import host as host_api
    cluster = _get_cluster(cluster_id, session=session)
    check_cluster_editable(cluster, user=user)
    host_ids = review.get('hosts', [])
    clusterhost_ids = review.get('clusterhosts', [])
    clusterhosts = []
    # Get clusterhosts need to be reviewed.
    for clusterhost in cluster.clusterhosts:
        if (
            clusterhost.clusterhost_id in clusterhost_ids or
            clusterhost.host_id in host_ids
        ):
            clusterhosts.append(clusterhost)

    os_config = copy.deepcopy(cluster.os_config)
    os_config = metadata_api.autofill_os_config(
        os_config, cluster.os_id, cluster=cluster
    )
    metadata_api.validate_os_config(
        os_config, cluster.os_id, True
    )
    for clusterhost in clusterhosts:
        host = clusterhost.host
        # ignore underlying host os config validation
        # since the host is not editable
        if not host_api.is_host_editable(
            host, user=user, check_in_installing=False
        ):
            logging.info(
                'ignore update host %s config '
                'since it is not editable' % host.name
            )
            continue
        host_os_config = copy.deepcopy(host.os_config)
        host_os_config = metadata_api.autofill_os_config(
            host_os_config, host.os_id,
            host=host
        )
        deployed_os_config = util.merge_dict(
            os_config, host_os_config
        )
        metadata_api.validate_os_config(
            deployed_os_config, host.os_id, True
        )
        host_api.validate_host(host)
        utils.update_db_object(
            session, host, os_config=host_os_config, config_validated=True
        )

    package_config = copy.deepcopy(cluster.package_config)
    if cluster.flavor_name:
        package_config = metadata_api.autofill_flavor_config(
            package_config, cluster.flavor_id,
            cluster=cluster
        )
        metadata_api.validate_flavor_config(
            package_config, cluster.flavor_id, True
        )
        for clusterhost in clusterhosts:
            clusterhost_package_config = copy.deepcopy(
                clusterhost.package_config
            )
            clusterhost_package_config = (
                metadata_api.autofill_flavor_config(
                    clusterhost_package_config,
                    cluster.flavor_id,
                    clusterhost=clusterhost
                )
            )
            deployed_package_config = util.merge_dict(
                package_config, clusterhost_package_config
            )
            metadata_api.validate_flavor_config(
                deployed_package_config,
                cluster.flavor_id, True
            )
            validate_clusterhost(clusterhost, session=session)
            utils.update_db_object(
                session, clusterhost,
                package_config=clusterhost_package_config,
                config_validated=True
            )

    validate_cluster(cluster, session=session)
    utils.update_db_object(
        session, cluster, os_config=os_config, package_config=package_config,
        config_validated=True
    )
    return {
        'cluster': cluster,
        'hosts': clusterhosts
    }


@utils.supported_filters(optional_support_keys=['deploy'])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_DEPLOY_CLUSTER
)
@utils.wrap_to_dict(
    RESP_DEPLOY_FIELDS,
    cluster=RESP_CONFIG_FIELDS,
    hosts=RESP_CLUSTERHOST_FIELDS
)
def deploy_cluster(
    cluster_id, deploy={}, user=None, session=None, **kwargs
):
    """deploy cluster.

    Args:
       cluster_id: cluster id.
       deploy: dict contains key either hosts or clusterhosts.
               deploy['hosts'] is a list of host id,
               deploy['clusterhosts'] is a list of clusterhost id.
    """
    from compass.db.api import host as host_api
    from compass.tasks import client as celery_client
    cluster = _get_cluster(cluster_id, session=session)
    host_ids = deploy.get('hosts', [])
    clusterhost_ids = deploy.get('clusterhosts', [])
    clusterhosts = []
    # get clusterhost to deploy.
    for clusterhost in cluster.clusterhosts:
        if (
            clusterhost.clusterhost_id in clusterhost_ids or
            clusterhost.host_id in host_ids
        ):
            clusterhosts.append(clusterhost)
    check_cluster_editable(cluster, user=user)
    check_cluster_validated(cluster)
    utils.update_db_object(session, cluster.state, state='INITIALIZED')
    for clusterhost in clusterhosts:
        host = clusterhost.host
        # ignore checking if underlying host is validated if
        # the host is not editable.
        if host_api.is_host_editable(host, user=user):
            host_api.check_host_validated(host)
            utils.update_db_object(session, host.state, state='INITIALIZED')
        if cluster.flavor_name:
            check_clusterhost_validated(clusterhost)
            utils.update_db_object(
                session, clusterhost.state, state='INITIALIZED'
            )

    celery_client.celery.send_task(
        'compass.tasks.deploy_cluster',
        (
            user.email, cluster_id,
            [clusterhost.host_id for clusterhost in clusterhosts]
        ),
        queue=user.email,
        exchange=user.email,
        routing_key=user.email
    )
    return {
        'status': 'deploy action sent',
        'cluster': cluster,
        'hosts': clusterhosts
    }


@utils.supported_filters(optional_support_keys=['redeploy'])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_DEPLOY_CLUSTER
)
@utils.wrap_to_dict(
    RESP_DEPLOY_FIELDS,
    cluster=RESP_CONFIG_FIELDS,
    hosts=RESP_CLUSTERHOST_FIELDS
)
def redeploy_cluster(
    cluster_id, deploy={}, user=None, session=None, **kwargs
):
    """redeploy cluster.

    Args:
       cluster_id: cluster id.
    """
    from compass.db.api import host as host_api
    from compass.tasks import client as celery_client
    cluster = _get_cluster(cluster_id, session=session)

    check_cluster_editable(cluster, user=user)
    check_cluster_validated(cluster)
    utils.update_db_object(
        session, cluster.state,
        state='INITIALIZED',
        percentage=0,
        ready=False
    )
    for clusterhost in cluster.clusterhosts:
        host = clusterhost.host
        # ignore checking if underlying host is validated if
        # the host is not editable.
        host_api.check_host_validated(host)
        utils.update_db_object(
            session, host.state,
            state='INITIALIZED',
            percentage=0,
            ready=False
        )
        if cluster.flavor_name:
            check_clusterhost_validated(clusterhost)
            utils.update_db_object(
                session,
                clusterhost.state,
                state='INITIALIZED',
                percentage=0,
                ready=False
            )

    celery_client.celery.send_task(
        'compass.tasks.redeploy_cluster',
        (
            user.email, cluster_id
        ),
        queue=user.email,
        exchange=user.email,
        routing_key=user.email
    )
    return {
        'status': 'redeploy action sent',
        'cluster': cluster
    }


@utils.supported_filters(optional_support_keys=['apply_patch'])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_DEPLOY_CLUSTER
)
@utils.wrap_to_dict(
    RESP_DEPLOY_FIELDS,
    cluster=RESP_CONFIG_FIELDS,
    hosts=RESP_CLUSTERHOST_FIELDS
)
def patch_cluster(cluster_id, user=None, session=None, **kwargs):

    from compass.tasks import client as celery_client

    cluster = _get_cluster(cluster_id, session=session)
    celery_client.celery.send_task(
        'compass.tasks.patch_cluster',
        (
            user.email, cluster_id,
        ),
        queue=user.email,
        exchange=user.email,
        routing_key=user.email
    )
    return {
        'status': 'patch action sent',
        'cluster': cluster
    }


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_GET_CLUSTER_STATE
)
@utils.wrap_to_dict(RESP_STATE_FIELDS)
def get_cluster_state(cluster_id, user=None, session=None, **kwargs):
    """Get cluster state info."""
    return _get_cluster(cluster_id, session=session).state_dict()


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_GET_CLUSTERHOST_STATE
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_STATE_FIELDS)
def get_cluster_host_state(
    cluster_id, host_id, user=None, session=None, **kwargs
):
    """Get clusterhost state merged with underlying host state."""
    return _get_cluster_host(
        cluster_id, host_id, session=session
    ).state_dict()


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_GET_CLUSTERHOST_STATE
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_STATE_FIELDS)
def get_cluster_host_self_state(
    cluster_id, host_id, user=None, session=None, **kwargs
):
    """Get clusterhost itself state."""
    return _get_cluster_host(
        cluster_id, host_id, session=session
    ).state


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_GET_CLUSTERHOST_STATE
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_STATE_FIELDS)
def get_clusterhost_state(
    clusterhost_id, user=None, session=None, **kwargs
):
    """Get clusterhost state merged with underlying host state."""
    return _get_clusterhost(
        clusterhost_id, session=session
    ).state_dict()


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_GET_CLUSTERHOST_STATE
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_STATE_FIELDS)
def get_clusterhost_self_state(
    clusterhost_id, user=None, session=None, **kwargs
):
    """Get clusterhost itself state."""
    return _get_clusterhost(
        clusterhost_id, session=session
    ).state


@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTERHOST_STATE_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_UPDATE_CLUSTERHOST_STATE
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_STATE_FIELDS)
def update_cluster_host_state(
    cluster_id, host_id, user=None, session=None, **kwargs
):
    """Update a clusterhost itself state."""
    clusterhost = _get_cluster_host(
        cluster_id, host_id, session=session
    )
    # Modify(harry): without progress_update.py to update cluster state
    # update cluster state here
    cluster = _get_cluster(clusterhost.cluster_id, session=session)
    utils.update_db_object(session, clusterhost.state, **kwargs)
    utils.update_db_object(session, cluster.state, **kwargs)
    return clusterhost.state_dict()


def _update_clusterhost_state(
    clusterhost, from_database_only=False,
    session=None, user=None, **kwargs
):
    """Update clusterhost state.

    If from_database_only, the state will only be updated in database.
    Otherwise a task sent to celery and os installer/package installer
    will also update its state if needed.
    """
    if 'ready' in kwargs and kwargs['ready'] and not clusterhost.state.ready:
        ready_triggered = True
    else:
        ready_triggered = False
    cluster_ready = False
    host = clusterhost.host
    cluster = clusterhost.cluster
    host_ready = not host.state.ready
    if ready_triggered:
        cluster_ready = True
        for clusterhost_in_cluster in cluster.clusterhosts:
            if (
                clusterhost_in_cluster.clusterhost_id
                    == clusterhost.clusterhost_id
            ):
                continue
            if not clusterhost_in_cluster.state.ready:
                cluster_ready = False

    logging.info(
        'clusterhost %s ready: %s',
        clusterhost.name, ready_triggered
    )
    logging.info('cluster ready: %s', cluster_ready)
    logging.info('host ready: %s', host_ready)
    if not ready_triggered or from_database_only:
        logging.info('%s state is set to %s', clusterhost.name, kwargs)
        utils.update_db_object(session, clusterhost.state, **kwargs)
        if not clusterhost.state.ready:
            logging.info('%s state ready is set to False', cluster.name)
            utils.update_db_object(session, cluster.state, ready=False)
        status = '%s state is updated' % clusterhost.name
    else:
        if not user:
            user_id = cluster.creator_id
            user_dict = user_api.get_user(user_id, session=session)
            user_email = user_dict['email']
        else:
            user_email = user.email
        from compass.tasks import client as celery_client
        celery_client.celery.send_task(
            'compass.tasks.package_installed',
            (
                clusterhost.cluster_id, clusterhost.host_id,
                cluster_ready, host_ready
            ),
            queue=user_email,
            exchange=user_email,
            routing_key=user_email
        )
        status = '%s: cluster ready %s host ready %s' % (
            clusterhost.name, cluster_ready, host_ready
        )
        logging.info('action status: %s', status)
    return {
        'status': status,
        'clusterhost': clusterhost.state_dict()
    }


@util.deprecated
@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTERHOST_STATE_INTERNAL_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_UPDATE_CLUSTERHOST_STATE
)
@utils.wrap_to_dict(['status', 'clusterhost'])
def update_cluster_host_state_internal(
    cluster_id, host_id, from_database_only=False,
    user=None, session=None, **kwargs
):
    """Update a clusterhost state by installation process."""
    # TODO(xicheng): it should be merged into update_cluster_host_state
    clusterhost = _get_cluster_host(
        cluster_id, host_id, session=session
    )
    return _update_clusterhost_state(
        clusterhost, from_database_only=from_database_only,
        session=session, users=user, **kwargs
    )


@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTERHOST_STATE_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_UPDATE_CLUSTERHOST_STATE
)
@utils.wrap_to_dict(RESP_CLUSTERHOST_STATE_FIELDS)
def update_clusterhost_state(
    clusterhost_id, user=None, session=None, **kwargs
):
    """Update a clusterhost itself state."""
    clusterhost = _get_clusterhost(
        clusterhost_id, session=session
    )
    # Modify(harry): without progress_update.py to update cluster state
    # update cluster state here
    cluster = _get_cluster(clusterhost.cluster_id, session=session)
    utils.update_db_object(session, clusterhost.state, **kwargs)
    utils.update_db_object(session, cluster.state, **kwargs)
    return clusterhost.state_dict()


@util.deprecated
@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTERHOST_STATE_INTERNAL_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_UPDATE_CLUSTERHOST_STATE
)
@utils.wrap_to_dict(['status', 'clusterhost'])
def update_clusterhost_state_internal(
    clusterhost_id, from_database_only=False,
    user=None, session=None, **kwargs
):
    """Update a clusterhost state by installation process."""
    # TODO(xicheng): it should be merged into update_clusterhost_state
    clusterhost = _get_clusterhost(clusterhost_id, session=session)
    return _update_clusterhost_state(
        clusterhost, from_database_only=from_database_only,
        session=session, user=user, **kwargs
    )


@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTER_STATE_FIELDS,
    ignore_support_keys=(IGNORE_FIELDS + IGNORE_UPDATED_CLUSTER_STATE_FIELDS)
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_UPDATE_CLUSTER_STATE
)
@utils.wrap_to_dict(RESP_STATE_FIELDS)
def update_cluster_state(
    cluster_id, user=None, session=None, **kwargs
):
    """Update a cluster state."""
    cluster = _get_cluster(
        cluster_id, session=session
    )
    utils.update_db_object(session, cluster.state, **kwargs)
    return cluster.state_dict()


@util.deprecated
@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTER_STATE_INTERNAL_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_UPDATE_CLUSTER_STATE
)
@utils.wrap_to_dict(['status', 'cluster'])
def update_cluster_state_internal(
    cluster_id, from_database_only=False,
    user=None, session=None, **kwargs
):
    """Update a cluster state by installation process.

    If from_database_only, the state will only be updated in database.
    Otherwise a task sent to do state update in os installer and
    package installer.
    """
    # TODO(xicheng): it should be merged into update_cluster_state
    cluster = _get_cluster(cluster_id, session=session)
    if 'ready' in kwargs and kwargs['ready'] and not cluster.state.ready:
        ready_triggered = True
    else:
        ready_triggered = False
    clusterhost_ready = {}
    if ready_triggered:
        for clusterhost in cluster.clusterhosts:
            clusterhost_ready[clusterhost.host_id] = (
                not clusterhost.state.ready
            )

    logging.info('cluster %s ready: %s', cluster_id, ready_triggered)
    logging.info('clusterhost ready: %s', clusterhost_ready)

    if not ready_triggered or from_database_only:
        logging.info('%s state is set to %s', cluster.name, kwargs)
        utils.update_db_object(session, cluster.state, **kwargs)
        if not cluster.state.ready:
            for clusterhost in cluster.clusterhosts:
                logging.info('%s state ready is to False', clusterhost.name)
                utils.update_db_object(
                    session, clusterhost.state, ready=False
                )
        status = '%s state is updated' % cluster.name
    else:
        if not user:
            user_id = cluster.creator_id
            user_dict = user_api.get_user(user_id, session=session)
            user_email = user_dict['email']
        else:
            user_email = user.email
        from compass.tasks import client as celery_client
        celery_client.celery.send_task(
            'compass.tasks.cluster_installed',
            (clusterhost.cluster_id, clusterhost_ready),
            queue=user_email,
            exchange=user_email,
            routing_key=user_email
        )
        status = '%s installed action set clusterhost ready %s' % (
            cluster.name, clusterhost_ready
        )
        logging.info('action status: %s', status)
    return {
        'status': status,
        'cluster': cluster.state_dict()
    }


@utils.supported_filters([])
@database.run_in_session()
@utils.wrap_to_dict(RESP_CLUSTERHOST_LOG_FIELDS)
def get_cluster_host_log_histories(
    cluster_id, host_id, user=None, session=None, **kwargs
):
    """Get clusterhost log history by cluster id and host id."""
    return _get_cluster_host(
        cluster_id, host_id, session=session
    ).log_histories


@utils.supported_filters([])
@database.run_in_session()
@utils.wrap_to_dict(RESP_CLUSTERHOST_LOG_FIELDS)
def get_clusterhost_log_histories(
    clusterhost_id, user=None,
    session=None, **kwargs
):
    """Get clusterhost log history by clusterhost id."""
    return _get_clusterhost(
        clusterhost_id, session=session
    ).log_histories


def _get_cluster_host_log_history(
    cluster_id, host_id, filename, session=None, **kwargs
):
    """Get clusterhost log history by cluster id, host id and filename."""
    clusterhost = _get_cluster_host(cluster_id, host_id, session=session)
    return utils.get_db_object(
        session, models.ClusterHostLogHistory,
        clusterhost_id=clusterhost.clusterhost_id, filename=filename,
        **kwargs
    )


def _get_clusterhost_log_history(
    clusterhost_id, filename, session=None, **kwargs
):
    """Get clusterhost log history by clusterhost id and filename."""
    clusterhost = _get_clusterhost(clusterhost_id, session=session)
    return utils.get_db_object(
        session, models.ClusterHostLogHistory,
        clusterhost_id=clusterhost.clusterhost_id, filename=filename,
        **kwargs
    )


@utils.supported_filters([])
@database.run_in_session()
@utils.wrap_to_dict(RESP_CLUSTERHOST_LOG_FIELDS)
def get_cluster_host_log_history(
    cluster_id, host_id, filename, user=None, session=None, **kwargs
):
    """Get clusterhost log history by cluster id, host id and filename."""
    return _get_cluster_host_log_history(
        cluster_id, host_id, filename, session=session
    )


@utils.supported_filters([])
@database.run_in_session()
@utils.wrap_to_dict(RESP_CLUSTERHOST_LOG_FIELDS)
def get_clusterhost_log_history(
    clusterhost_id, filename, user=None, session=None, **kwargs
):
    """Get host log history by clusterhost id and filename."""
    return _get_clusterhost_log_history(
        clusterhost_id, filename, session=session
    )


@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTERHOST_LOG_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@utils.wrap_to_dict(RESP_CLUSTERHOST_LOG_FIELDS)
def update_cluster_host_log_history(
    cluster_id, host_id, filename, user=None, session=None, **kwargs
):
    """Update a host log history by cluster id, host id and filename."""
    cluster_host_log_history = _get_cluster_host_log_history(
        cluster_id, host_id, filename, session=session
    )
    return utils.update_db_object(
        session, cluster_host_log_history, **kwargs
    )


@utils.supported_filters(
    optional_support_keys=UPDATED_CLUSTERHOST_LOG_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@utils.wrap_to_dict(RESP_CLUSTERHOST_LOG_FIELDS)
def update_clusterhost_log_history(
    clusterhost_id, filename, user=None, session=None, **kwargs
):
    """Update a host log history by clusterhost id and filename."""
    clusterhost_log_history = _get_clusterhost_log_history(
        clusterhost_id, filename, session=session
    )
    return utils.update_db_object(session, clusterhost_log_history, **kwargs)


@utils.supported_filters(
    ADDED_CLUSTERHOST_LOG_FIELDS,
    optional_support_keys=UPDATED_CLUSTERHOST_LOG_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@utils.wrap_to_dict(RESP_CLUSTERHOST_LOG_FIELDS)
def add_clusterhost_log_history(
    clusterhost_id, exception_when_existing=False,
    filename=None, user=None, session=None, **kwargs
):
    """add a host log history by clusterhost id and filename."""
    clusterhost = _get_clusterhost(clusterhost_id, session=session)
    return utils.add_db_object(
        session, models.ClusterHostLogHistory,
        exception_when_existing,
        clusterhost.clusterhost_id, filename, **kwargs
    )


@utils.supported_filters(
    ADDED_CLUSTERHOST_LOG_FIELDS,
    optional_support_keys=UPDATED_CLUSTERHOST_LOG_FIELDS,
    ignore_support_keys=IGNORE_FIELDS
)
@database.run_in_session()
@utils.wrap_to_dict(RESP_CLUSTERHOST_LOG_FIELDS)
def add_cluster_host_log_history(
    cluster_id, host_id, exception_when_existing=False,
    filename=None, user=None, session=None, **kwargs
):
    """add a host log history by cluster id, host id and filename."""
    clusterhost = _get_cluster_host(
        cluster_id, host_id, session=session
    )
    return utils.add_db_object(
        session, models.ClusterHostLogHistory, exception_when_existing,
        clusterhost.clusterhost_id, filename, **kwargs
    )