Code coverage report for app/controllers/wizard/step8_controller.js

Statements: 65.34% (443 / 678)      Branches: 46.63% (152 / 326)      Functions: 59.51% (97 / 163)      Lines: 65.32% (435 / 666)      Ignored: none     

All files » app/controllers/wizard/ » step8_controller.js
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    1                                     1 1 1   1                                                                                                                                                                                                                                       14                                                                                                   65 65 65 65 65 65 65 65 65 65               7 7 2 2   7 7 7 7                                                         17 17 17 462 42 33 33       17                   1 1 1         1 1 1     1 1 1 1         1 1 1     1                 1 1 1 1 1 1 1                     1 1 1                   1   1 1 1 1       1       1                                   2 1 1 1 1   1                         1 2 2             1                                                                                 1 1 1               1 4         4   4   3   2 2 2 1     1     2 2 2 2   2 1             4                   4                     3 3     3 1   2 2 2     3       1 1 1                               2 2       2                 2 2 1   1                   2 2 2 1   1   2                 2 2 1 1 1 1 1                                                                                                         1 1 1 1                                                                                                                                                     1                           1 1               1                   5 5 12                                   4 4 1     1                           9 9 9 9   9           9 2                 1 1       1                                                                                                                                                 2 2   2                 2 1 1   1                                                                           44 44 44 33   22     22 22 11     33 33   44 44 44 44 44 44 22   44   44 44 44                             2 2 2                                       2 2 1                           12 12     12 71                                                                                                                                         1                                         2 2 1                           6 5                   1   1 1 1 1           1 1   1                                           8     8 16 16 16 96   16   8                 1 1 1 1 1   1                                           1     1 2 2 2 1                             1 1     1 1     1 1               1             1                             1 1                       1 1 1 1   1 1 1 1     1 1 1           1                                                                                 1 1 1 37 2 1         1 1 1 1                         17     17 17 17 17 16 3 13 13           17 17 6 6 3 3 3                         4   3 3 5     3   3                         3                                                                                                 1 1 1 1 1 1 1 1     1 1     1 1 1 1     1 1           1 1               1                                                                                                                                 1 1 3                                                                                           13 13   13 13   13   13   13     13 104     13   13 143 13     13                   13                           45                                                                                                                       2     2 2 4           4   2         4 4 4     4 4         4       4 4 4 7   4       4       4 4 4 4 4 4     4 4 8 6 2       4 2 2 2 2         4       1   1 1 1 1                               1 1   1   1 1 1 1   1 4 3 3 3 3 3         1 1 1   1 4 2     2 2 2 2           2 1 1 1   2   2         2 2     1 2 1   1 2 2 2       2 1   1 1 1       1 1   1       1   1 1 1 1   1   1 1   1                 1 1 1 1 1               1 1 1 1   1   1       1   1 1   1 1 1   1           1 1     3       1           3       1                              
'use strict';
 
;require.register("controllers/wizard/step8_controller", function (exports, require, module) {
  /**
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you 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.
   */
 
  var App = require('app');
  var stringUtils = require('utils/string_utils');
  var fileUtils = require('utils/file_utils');
 
  App.WizardStep8Controller = Em.Controller.extend(App.AddSecurityConfigs, App.wizardDeployProgressControllerMixin, App.ConfigOverridable, App.ConfigsSaverMixin, {
 
    name: 'wizardStep8Controller',
 
    /**
     * @type {boolean}
     */
    isAddService: Em.computed.equal('content.controllerName', 'addServiceController'),
 
    /**
     * @type {boolean}
     */
    isAddHost: Em.computed.equal('content.controllerName', 'addHostController'),
 
    /**
     * @type {boolean}
     */
    isInstaller: Em.computed.equal('content.controllerName', 'installerController'),
 
    /**
     * List of raw data about cluster that should be displayed
     * @type {Array}
     */
    rawContent: [{
      config_name: 'Admin',
      display_name: 'Admin Name',
      config_value: ''
    }, {
      config_name: 'cluster',
      display_name: 'Cluster Name',
      config_value: ''
    }, {
      config_name: 'hosts',
      display_name: 'Total Hosts',
      config_value: ''
    }, {
      config_name: 'Repo',
      display_name: 'Local Repository',
      config_value: ''
    }],
 
    /**
     * List of data about cluster (based on formatted <code>rawContent</code>)
     * @type {Object[]}
     */
    clusterInfo: [],
 
    /**
     * List of services with components assigned to hosts
     * @type {Object[]}
     */
    services: [],
 
    /**
     * @type {Object[]}
     */
    configs: [],
 
    /**
     * True if Kerberos is installed on the cluster and the kdc_type on the server is set to "none"
     * @type {Boolean}
     */
    isManualKerberos: Em.computed.equal('App.router.mainAdminKerberosController.kdc_type', 'none'),
 
    showDownloadCsv: function () {
      return !!App.get('router.mainAdminKerberosController.kdc_type');
    }.property('App.router.mainAdminKerberosController.kdc_type'),
 
    /**
     * Should Submit button be disabled
     * @type {bool}
     */
    isSubmitDisabled: false,
 
    /**
     * Should Back button be disabled
     * @type {bool}
     */
    isBackBtnDisabled: false,
 
    /**
     * Is error appears while <code>ajaxQueue</code> executes
     * @type {bool}
     */
    hasErrorOccurred: false,
 
    /**
     * Are services installed
     * Used to hide Deploy Progress Bar
     * @type {bool}
     */
    servicesInstalled: false,
 
    /**
     * List of service config tags
     * @type {Object[]}
     */
    serviceConfigTags: [],
 
    /**
     * Selected config group
     * @type {Object}
     */
    selectedConfigGroup: null,
 
    /**
     * List of config groups
     * @type {Object[]}
     */
    configGroups: [],
 
    /**
     * List of selected but not installed services
     * @type {Object[]}
     */
    selectedServices: function () {
      return this.get('content.services').filterProperty('isSelected', true).filterProperty('isInstalled', false);
    }.property('content.services.@each.isSelected', 'content.services.@each.isInstalled').cacheable(),
 
    /**
     * List of installed services
     * @type {Object[]}
     */
    installedServices: Em.computed.filterBy('content.services', 'isInstalled', true),
 
    /**
     * Current cluster name
     * @type {string}
     */
    clusterName: Em.computed.alias('content.cluster.name'),
 
    /**
     * List of existing cluster names
     * @type {string[]}
     */
    clusterNames: [],
 
    /**
     * Number of completed cluster delete requests
     * @type {number}
     */
    clusterDeleteRequestsCompleted: 0,
 
    /**
     * Number of existing repo_versions
     * @type {number}
     */
    existingRepositoryVersions: 0,
 
    /**
     * Indicates if all cluster delete requests are completed
     * @type {boolean}
     */
    isAllClusterDeleteRequestsCompleted: Em.computed.equalProperties('clusterDeleteRequestsCompleted', 'clusterNames.length'),
 
    /**
     * Error popup body views for clusters that couldn't be deleted
     * @type {App.AjaxDefaultErrorPopupBodyView[]}
     */
    clusterDeleteErrorViews: [],
 
    /**
     * Clear current step data
     * @method clearStep
     */
    clearStep: function clearStep() {
      this.get('services').clear();
      this.get('configs').clear();
      this.get('clusterInfo').clear();
      this.get('serviceConfigTags').clear();
      this.set('servicesInstalled', false);
      this.set('ajaxQueueLength', 0);
      this.set('ajaxRequestsQueue', App.ajaxQueue.create());
      this.set('ajaxRequestsQueue.finishedCallback', this.ajaxQueueFinished);
      this.get('clusterDeleteErrorViews').clear();
      this.set('clusterDeleteRequestsCompleted', 0);
    },
 
    /**
     * Load current step data
     * @method loadStep
     */
    loadStep: function loadStep() {
      this.clearStep();
      if (this.get('content.serviceConfigProperties')) {
        this.formatProperties();
        this.loadConfigs();
      }
      this.loadClusterInfo();
      this.loadServices();
      this.set('isSubmitDisabled', false);
      this.set('isBackBtnDisabled', false);
    },
 
    /**
     * replace whitespace character with coma between directories
     * @method formatProperties
     */
    formatProperties: function formatProperties() {
      this.get('content.serviceConfigProperties').forEach(function (_configProperty) {
        _configProperty.value = typeof _configProperty.value === "boolean" ? _configProperty.value.toString() : App.config.trimProperty(_configProperty, false);
      });
    },
 
    /**
     * Load all site properties
     * @method loadConfigs
     */
    loadConfigs: function loadConfigs() {
      this.set('configs', this.get('content.serviceConfigProperties').filter(function (config) {
        return !config.group;
      }));
    },
 
    /**
     * Format <code>content.hosts</code> from Object to Array
     * @returns {Array}
     * @method getRegisteredHosts
     */
    getRegisteredHosts: function getRegisteredHosts() {
      var allHosts = this.get('content.hosts');
      var hosts = [];
      for (var hostName in allHosts) {
        if (allHosts.hasOwnProperty(hostName)) {
          if (allHosts[hostName].bootStatus === 'REGISTERED') {
            allHosts[hostName].hostName = allHosts[hostName].name;
            hosts.pushObject(allHosts[hostName]);
          }
        }
      }
      return hosts;
    },
 
    /**
     * Load all info about cluster to <code>clusterInfo</code> variable
     * @method loadClusterInfo
     */
    loadClusterInfo: function loadClusterInfo() {
 
      //Admin name
      var admin = this.rawContent.findProperty('config_name', 'Admin');
      admin.config_value = App.db.getLoginName();
      Iif (admin.config_value) {
        this.get('clusterInfo').pushObject(Ember.Object.create(admin));
      }
 
      // cluster name
      var cluster = this.rawContent.findProperty('config_name', 'cluster');
      cluster.config_value = this.get('content.cluster.name');
      this.get('clusterInfo').pushObject(Ember.Object.create(cluster));
 
      //hosts
      var newHostsCount = 0;
      var totalHostsCount = 0;
      var hosts = this.get('content.hosts');
      for (var hostName in hosts) {
        newHostsCount += ~~!hosts[hostName].isInstalled;
        totalHostsCount++;
      }
 
      var totalHostsObj = this.rawContent.findProperty('config_name', 'hosts');
      totalHostsObj.config_value = totalHostsCount + ' (' + newHostsCount + ' new)';
      this.get('clusterInfo').pushObject(Em.Object.create(totalHostsObj));
 
      //repo
      Iif (this.get('isAddService') || this.get('isAddHost')) {
        // For some stacks there is no info regarding stack versions to upgrade, e.g. HDP-2.1
        if (App.StackVersion.find().get('content.length')) {
          this.loadRepoInfo();
        } else {
          this.loadDefaultRepoInfo();
        }
      } else {
        // from install wizard
        var selectedStack = App.Stack.find().findProperty('isSelected', true);
        var allRepos = [];
        Eif (selectedStack && selectedStack.get('operatingSystems')) {
          selectedStack.get('operatingSystems').forEach(function (os) {
            Eif (os.get('isSelected')) {
              os.get('repositories').forEach(function (repo) {
                Iif (repo.get('showRepo')) {
                  allRepos.push(Em.Object.create({
                    base_url: repo.get('baseUrl'),
                    os_type: repo.get('osType'),
                    repo_id: repo.get('repoId')
                  }));
                }
              }, this);
            }
          }, this);
        }
        allRepos.set('display_name', Em.I18n.t("installer.step8.repoInfo.displayName"));
        this.get('clusterInfo').set('useRedhatSatellite', selectedStack.get('useRedhatSatellite'));
        this.get('clusterInfo').set('repoInfo', allRepos);
      }
    },
 
    /**
     * Load repo info for add Service/Host wizard review page
     * @return {$.ajax|null}
     * @method loadRepoInfo
     */
    loadRepoInfo: function loadRepoInfo() {
      var stackName = App.get('currentStackName');
 
      var currentRepoVersion;
      App.RepositoryVersion.find().forEach(function (repoVersion) {
        Eif (repoVersion.get('stackVersionType') === stackName && repoVersion.get('isCurrent') && repoVersion.get('isStandard')) {
          currentRepoVersion = repoVersion.get('repositoryVersion');
        }
      });
 
      Iif (!currentRepoVersion) {
        console.error('Error while getting current stack repository version');
      }
 
      return App.ajax.send({
        name: 'cluster.load_repo_version',
        sender: this,
        data: {
          stackName: stackName,
          repositoryVersion: currentRepoVersion
        },
        success: 'loadRepoInfoSuccessCallback',
        error: 'loadRepoInfoErrorCallback'
      });
    },
 
    /**
     * Save all repo base URL of all OS type to <code>repoInfo<code>
     * @param {object} data
     * @method loadRepoInfoSuccessCallback
     */
    loadRepoInfoSuccessCallback: function loadRepoInfoSuccessCallback(data) {
      Em.assert('Current repo-version may be only one', data.items.length === 1);
      Eif (data.items.length) {
        var allRepos = this.generateRepoInfo(Em.getWithDefault(data, 'items.0.repository_versions.0.operating_systems', []));
        allRepos.set('display_name', Em.I18n.t("installer.step8.repoInfo.displayName"));
        this.get('clusterInfo').set('repoInfo', allRepos);
        //if the property is missing, set as false
        this.get('clusterInfo').set('useRedhatSatellite', data.items[0].repository_versions[0].operating_systems[0].OperatingSystems.ambari_managed_repositories === false);
      } else {
        this.loadDefaultRepoInfo();
      }
    },
 
    /**
     * Generate list regarding info about OS versions and repositories.
     *
     * @param {Object{}} oses - OS array
     * @returns {Em.Object[]}
     */
    generateRepoInfo: function generateRepoInfo(oses) {
      return oses.map(function (os) {
        return os.repositories.map(function (repository) {
          return Em.Object.create({
            base_url: repository.Repositories.base_url,
            os_type: repository.Repositories.os_type,
            repo_id: repository.Repositories.repo_id
          });
        });
      }).reduce(function (p, c) {
        return p.concat(c);
      });
    },
 
    /**
     * Load repo info from stack. Used if installed stack doesn't have upgrade info.
     *
     * @returns {$.Deferred}
     * @method loadDefaultRepoInfo
     */
    loadDefaultRepoInfo: function loadDefaultRepoInfo() {
      var nameVersionCombo = App.get('currentStackVersion').split('-');
 
      return App.ajax.send({
        name: 'cluster.load_repositories',
        sender: this,
        data: {
          stackName: nameVersionCombo[0],
          stackVersion: nameVersionCombo[1]
        },
        success: 'loadDefaultRepoInfoSuccessCallback',
        error: 'loadRepoInfoErrorCallback'
      });
    },
 
    /**
     * @param {Object} data - JSON data from server
     * @method loadDefaultRepoInfoSuccessCallback
     */
    loadDefaultRepoInfoSuccessCallback: function loadDefaultRepoInfoSuccessCallback(data) {
      var allRepos = this.generateRepoInfo(Em.getWithDefault(data, 'items', []));
      allRepos.set('display_name', Em.I18n.t("installer.step8.repoInfo.displayName"));
      this.get('clusterInfo').set('repoInfo', allRepos);
      //if the property is missing, set as false
      this.get('clusterInfo').set('useRedhatSatellite', data.items[0].OperatingSystems.ambari_managed_repositories === false);
    },
 
    /**
     * @method loadRepoInfoErrorCallback
     */
    loadRepoInfoErrorCallback: function loadRepoInfoErrorCallback() {
      var allRepos = [];
      allRepos.set('display_name', Em.I18n.t("installer.step8.repoInfo.displayName"));
      this.get('clusterInfo').set('repoInfo', allRepos);
    },
 
    /**
     * Load all info about services to <code>services</code> variable
     * @method loadServices
     */
    loadServices: function loadServices() {
      this.get('selectedServices').filterProperty('isHiddenOnSelectServicePage', false).forEach(function (service) {
        var serviceObj = Em.Object.create({
          service_name: service.get('serviceName'),
          display_name: service.get('displayNameOnSelectServicePage'),
          service_components: Em.A([])
        });
        service.get('serviceComponents').forEach(function (component) {
          // show clients for services that have only clients components
          if ((component.get('isClient') || component.get('isRequiredOnAllHosts')) && !service.get('isClientOnlyService')) return;
          // no HA component
          if (component.get('isHAComponentOnly')) return;
          // skip if component is not allowed on single node cluster
          Iif (Object.keys(this.get('content.hosts')).length === 1 && component.get('isNotAllowedOnSingleNodeCluster')) return;
          var displayName;
          if (component.get('isClient')) {
            displayName = Em.I18n.t('common.clients');
          } else {
            // remove service name from component display name
            displayName = App.format.role(component.get('componentName'), false).replace(new RegExp('^' + service.get('serviceName') + '\\s', 'i'), '');
          }
 
          var componentName = component.get('componentName');
          var masterComponents = this.get('content.masterComponentHosts');
          var isMasterComponentSelected = masterComponents.someProperty('component', componentName);
          var isMaster = component.get('isMaster');
 
          if (!isMaster || isMasterComponentSelected) {
            serviceObj.get('service_components').pushObject(Em.Object.create({
              component_name: component.get('isClient') ? Em.I18n.t('common.client').toUpperCase() : component.get('componentName'),
              display_name: displayName,
              component_value: this.assignComponentHosts(component)
            }));
          }
        }, this);
        Iif (service.get('customReviewHandler')) {
          for (var displayName in service.get('customReviewHandler')) {
            serviceObj.get('service_components').pushObject(Em.Object.create({
              display_name: displayName,
              component_value: this.assignComponentHosts(Em.Object.create({
                customHandler: service.get('customReviewHandler.' + displayName)
              }))
            }));
          }
        }
        this.get('services').pushObject(serviceObj);
      }, this);
    },
 
    /**
     * Set <code>component_value</code> property to <code>component</code>
     * @param {Em.Object} component
     * @return {String}
     * @method assignComponentHosts
     */
    assignComponentHosts: function assignComponentHosts(component) {
      var componentValue;
      Iif (component.get('customHandler')) {
        componentValue = this[component.get('customHandler')].call(this, component);
      } else {
        if (component.get('isMaster')) {
          componentValue = this.getMasterComponentValue(component.get('componentName'));
        } else {
          var componentName = component.get('isClient') ? Em.I18n.t('common.client').toUpperCase() : component.get('componentName');
          var hostsLength = this.get('content.slaveComponentHosts').findProperty('componentName', componentName).hosts.length;
          componentValue = hostsLength + Em.I18n.t('installer.step8.host' + (hostsLength > 1 ? 's' : ''));
        }
      }
      return componentValue;
    },
 
    getMasterComponentValue: function getMasterComponentValue(componentName) {
      var masterComponents = this.get('content.masterComponentHosts');
      var hostsCount = masterComponents.filterProperty('component', componentName).length;
      return stringUtils.pluralize(hostsCount, masterComponents.findProperty('component', componentName).hostName, hostsCount + ' ' + Em.I18n.t('installer.step8.hosts'));
    },
 
    loadHiveDbValue: function loadHiveDbValue() {
      return this.loadDbValue('HIVE');
    },
 
    loadOozieDbValue: function loadOozieDbValue() {
      return this.loadDbValue('OOZIE');
    },
 
    /**
     * Set displayed Hive DB value based on DB type
     * @method loadHiveDbValue
     */
    loadDbValue: function loadDbValue(serviceName) {
      var serviceConfigProperties = this.get('content.serviceConfigProperties');
      var dbFull = serviceConfigProperties.findProperty('name', serviceName.toLowerCase() + '_database');
      //db = serviceConfigProperties.findProperty('name', serviceName.toLowerCase() + '_ambari_database');
      //since db.value contains the intial default value of <service>_admin_database (MySQL) and not the actual db type selected,
      //ignore the value when displaying the database name on the summary page
      return dbFull ? dbFull.value : '';
    },
 
    /**
     * Set displayed HBase master value
     * @param {Object} hbaseMaster
     * @method loadHbaseMasterValue
     */
    loadHbaseMasterValue: function loadHbaseMasterValue(hbaseMaster) {
      var hbaseHostName = this.get('content.masterComponentHosts').filterProperty('component', hbaseMaster.component_name);
      if (hbaseHostName.length === 1) {
        hbaseMaster.set('component_value', hbaseHostName[0].hostName);
      } else {
        hbaseMaster.set('component_value', hbaseHostName[0].hostName + " " + Em.I18n.t('installer.step8.other').format(hbaseHostName.length - 1));
      }
    },
 
    /**
     * Set displayed ZooKeeper Server value
     * @param {Object} serverComponent
     * @method loadZkServerValue
     */
    loadZkServerValue: function loadZkServerValue(serverComponent) {
      var zkHostNames = this.get('content.masterComponentHosts').filterProperty('component', serverComponent.component_name).length;
      var hostSuffix;
      if (zkHostNames === 1) {
        hostSuffix = Em.I18n.t('installer.step8.host');
      } else {
        hostSuffix = Em.I18n.t('installer.step8.hosts');
      }
      serverComponent.set('component_value', zkHostNames + hostSuffix);
    },
 
    /**
     * Onclick handler for <code>next</code> button
     * @method submit
     * @return {void}
     */
    submit: function submit() {
      var wizardController;
      if (!this.get('isSubmitDisabled')) {
        wizardController = App.router.get(this.get('content.controllerName'));
        wizardController.setLowerStepsDisable(wizardController.get('currentStep'));
        this.set('isSubmitDisabled', true);
        this.set('isBackBtnDisabled', true);
        this.showRestartWarnings().then(this.checkKDCSession.bind(this));
      }
    },
 
    /**
     * Warn user about services that will be restarted during installation.
     *
     * @returns {$.Deferred}
     */
    showRestartWarnings: function showRestartWarnings() {
      var self = this;
      var dfd = $.Deferred();
      var wizardController = App.router.get(this.get('content.controllerName'));
      var selectedServiceNames = this.get('selectedServices').mapProperty('serviceName');
      var installedServiceNames = this.get('installedServices').mapProperty('serviceName');
 
      if (this.get('isAddService') && selectedServiceNames.contains('OOZIE')) {
        var affectedServices = ['HDFS', 'YARN'].filter(function (serviceName) {
          return installedServiceNames.contains(serviceName);
        });
        if (affectedServices.length) {
          var serviceNames = affectedServices.length > 1 ? '<b>{0}</b> {1} <b>{2}</b>'.format(affectedServices[0], Em.I18n.t('and'), affectedServices[1]) : '<b>' + affectedServices[0] + '</b> ';
          App.ModalPopup.show({
            encodeBody: false,
            header: Em.I18n.t('common.warning'),
            body: Em.I18n.t('installer.step8.services.restart.required').format(serviceNames, stringUtils.pluralize(affectedServices.length, Em.I18n.t('common.service').toLowerCase())),
            secondary: Em.I18n.t('common.cancel'),
            primary: Em.I18n.t('common.proceedAnyway'),
            onPrimary: function onPrimary() {
              this.hide();
              dfd.resolve();
            },
            onClose: function onClose() {
              this.hide();
              self.set('isSubmitDisabled', false);
              self.set('isBackBtnDisabled', false);
              wizardController.setStepsEnable();
              dfd.reject();
            },
            onSecondary: function onSecondary() {
              this.onClose();
            }
          });
        } else {
          dfd.resolve();
        }
      } else {
        dfd.resolve();
      }
      return dfd.promise();
    },
 
    checkKDCSession: function checkKDCSession() {
      var self = this;
      var wizardController = App.router.get(this.get('content.controllerName'));
      Eif (!this.get('isInstaller')) {
        App.get('router.mainAdminKerberosController').getKDCSessionState(this.submitProceed.bind(this), function () {
          self.set('isSubmitDisabled', false);
          self.set('isBackBtnDisabled', false);
          wizardController.setStepsEnable();
          if (self.get('isAddService')) {
            wizardController.setSkipSlavesStep(wizardController.getDBProperty('selectedServiceNames'), 3);
          }
        });
      } else {
        this.submitProceed();
      }
    },
 
    /**
     * Prepare <code>ajaxQueue</code> and start to execute it
     * @method submitProceed
     */
    submitProceed: function submitProceed() {
      var self = this;
      this.set('clusterDeleteRequestsCompleted', 0);
      this.get('clusterDeleteErrorViews').clear();
      if (this.get('isAddHost')) {
        App.router.get('addHostController').setLowerStepsDisable(4);
      }
 
      // checkpoint the cluster status on the server so that the user can resume from where they left off
      switch (this.get('content.controllerName')) {
        case 'installerController':
          App.clusterStatus.setClusterStatus({
            clusterName: this.get('clusterName'),
            clusterState: 'CLUSTER_DEPLOY_PREP_2',
            wizardControllerName: this.get('content.controllerName'),
            localdb: App.db.data
          });
          break;
        case 'addHostController':
          App.clusterStatus.setClusterStatus({
            clusterName: this.get('clusterName'),
            clusterState: 'ADD_HOSTS_DEPLOY_PREP_2',
            wizardControllerName: this.get('content.controllerName'),
            localdb: App.db.data
          });
          break;
        case 'addServiceController':
          App.clusterStatus.setClusterStatus({
            clusterName: this.get('clusterName'),
            clusterState: 'ADD_SERVICES_DEPLOY_PREP_2',
            wizardControllerName: this.get('content.controllerName'),
            localdb: App.db.data
          });
          break;
        default:
          break;
      }
      // delete any existing clusters to start from a clean slate
      // before creating a new cluster in install wizard
      // TODO: modify for multi-cluster support
      this.getExistingClusterNames().complete(function () {
        var clusterNames = self.get('clusterNames');
        if (self.get('isInstaller') && !App.get('testMode') && clusterNames.length) {
          self.deleteClusters(clusterNames);
        } else {
          self.getExistingVersions();
        }
      });
    },
 
    /**
     * Get list of existing cluster names
     * @returns {object|null}
     * returns an array of existing cluster names.
     * returns an empty array if there are no existing clusters.
     * @method getExistingClusterNames
     */
    getExistingClusterNames: function getExistingClusterNames() {
      return App.ajax.send({
        name: 'wizard.step8.existing_cluster_names',
        sender: this,
        success: 'getExistingClusterNamesSuccessCallBack',
        error: 'getExistingClusterNamesErrorCallback'
      });
    },
 
    /**
     * Save received list to <code>clusterNames</code>
     * @param {Object} data
     * @method getExistingClusterNamesSuccessCallBack
     */
    getExistingClusterNamesSuccessCallBack: function getExistingClusterNamesSuccessCallBack(data) {
      var clusterNames = data.items.mapProperty('Clusters.cluster_name');
      this.set('clusterNames', clusterNames);
    },
 
    /**
     * If error appears, set <code>clusterNames</code> to <code>[]</code>
     * @method getExistingClusterNamesErrorCallback
     */
    getExistingClusterNamesErrorCallback: function getExistingClusterNamesErrorCallback() {
      this.set('clusterNames', []);
    },
 
    /**
     * Delete cluster by name
     * One request for one cluster!
     * @param {string[]} clusterNames
     * @method deleteClusters
     */
    deleteClusters: function deleteClusters(clusterNames) {
      this.get('clusterDeleteErrorViews').clear();
      clusterNames.forEach(function (clusterName, index) {
        App.ajax.send({
          name: 'common.delete.cluster',
          sender: this,
          data: {
            name: clusterName,
            isLast: index === clusterNames.length - 1
          },
          success: 'deleteClusterSuccessCallback',
          error: 'deleteClusterErrorCallback'
        });
      }, this);
    },
 
    /**
     * Method to execute after successful cluster deletion
     * @method deleteClusterSuccessCallback
     */
    deleteClusterSuccessCallback: function deleteClusterSuccessCallback() {
      this.incrementProperty('clusterDeleteRequestsCompleted');
      if (this.get('isAllClusterDeleteRequestsCompleted')) {
        Iif (this.get('clusterDeleteErrorViews.length')) {
          this.showDeleteClustersErrorPopup();
        } else {
          this.getExistingVersions();
        }
      }
    },
 
    /**
     * Method to execute after failed cluster deletion
     * @param {object} request
     * @param {string} ajaxOptions
     * @param {string} error
     * @param {object} opt
     * @method deleteClusterErrorCallback
     */
    deleteClusterErrorCallback: function deleteClusterErrorCallback(request, ajaxOptions, error, opt) {
      this.incrementProperty('clusterDeleteRequestsCompleted');
      try {
        var json = $.parseJSON(request.responseText);
        var message = json.message;
      } catch (err) {}
      this.get('clusterDeleteErrorViews').pushObject(App.AjaxDefaultErrorPopupBodyView.create({
        url: opt.url,
        type: opt.type,
        status: request.status,
        message: message
      }));
      if (this.get('isAllClusterDeleteRequestsCompleted')) {
        this.showDeleteClustersErrorPopup();
      }
    },
 
    /**
     * Show error popup if cluster deletion failed
     * @method showDeleteClustersErrorPopup
     */
    showDeleteClustersErrorPopup: function showDeleteClustersErrorPopup() {
      var self = this;
      this.setProperties({
        isSubmitDisabled: false,
        isBackBtnDisabled: false
      });
      App.ModalPopup.show({
        header: Em.I18n.t('common.error'),
        secondary: false,
        onPrimary: function onPrimary() {
          this.hide();
        },
        bodyClass: Em.ContainerView.extend({
          childViews: self.get('clusterDeleteErrorViews')
        })
      });
    },
 
    /**
     * Get existing repo_versions
     * @method getExistingVersions
     */
    getExistingVersions: function getExistingVersions() {
      return App.ajax.send({
        name: 'wizard.get_version_definitions',
        sender: this,
        success: 'getExistingVersionsSuccessCallback'
      });
    },
 
    /**
     * @param {Object} data
     * @method getExistingVersionsSuccessCallback
     */
    getExistingVersionsSuccessCallback: function getExistingVersionsSuccessCallback(data) {
      if (this.get('isInstaller') && !App.get('testMode') && data.items.length) {
        this.set('existingRepositoryVersions', data.items.length);
        this.deleteExistingVersions(data.items);
      } else {
        this.startDeploy();
      }
    },
 
    /**
     * Delete existing repo_versions
     * @param {Array} versions
     * @method deleteExistingVersions
     */
    deleteExistingVersions: function deleteExistingVersions(versions) {
      versions.forEach(function (version) {
        App.ajax.send({
          name: 'wizard.delete_repository_versions',
          sender: this,
          data: {
            id: version.VersionDefinition.id,
            stackName: version.VersionDefinition.stack_name,
            stackVersion: version.VersionDefinition.stack_version
          },
          success: 'deleteExistingVersionsSuccessCallback'
        });
      }, this);
    },
 
    /**
     * Method to execute after successful version deletion
     * @method deleteExistingVersionsSuccessCallback
     */
    deleteExistingVersionsSuccessCallback: function deleteExistingVersionsSuccessCallback() {
      this.decrementProperty('existingRepositoryVersions');
      if (this.get('existingRepositoryVersions') === 0) {
        this.startDeploy();
      }
    },
 
    /**
     * updates kerberosDescriptorConfigs
     * @method updateKerberosDescriptor
     */
    updateKerberosDescriptor: function updateKerberosDescriptor(instant) {
      var kerberosDescriptor = this.get('wizardController').getDBProperty('kerberosDescriptorConfigs');
      var descriptorExists = this.get('wizardController').getDBProperty('isClusterDescriptorExists') === true;
 
      var ajaxOpts = {
        name: descriptorExists ? 'admin.kerberos.cluster.artifact.update' : 'admin.kerberos.cluster.artifact.create',
        data: {
          artifactName: 'kerberos_descriptor',
          data: {
            artifact_data: this.removeIdentityReferences(kerberosDescriptor)
          }
        }
      };
      if (instant) {
        ajaxOpts.sender = this;
        App.ajax.send(ajaxOpts);
      } else {
        this.addRequestToAjaxQueue(ajaxOpts);
      }
    },
 
    /**
     * To Start deploy process
     * @method startDeploy
     */
    startDeploy: function startDeploy() {
      if (!this.get('isInstaller')) {
        this._startDeploy();
      } else {
        var installerController = App.router.get('installerController');
        var versionData = installerController.getSelectedRepoVersionData();
        if (versionData) {
          var self = this;
          installerController.postVersionDefinitionFileStep8(versionData.isXMLdata, versionData.data).done(function (versionInfo) {
            if (versionInfo.id && versionInfo.stackName && versionInfo.stackVersion) {
              var selectedStack = App.Stack.find().findProperty('isSelected', true);
              if (selectedStack) {
                selectedStack.set('versionInfoId', versionInfo.id);
              }
              installerController.updateRepoOSInfo(versionInfo, selectedStack).done(function () {
                self._startDeploy();
              });
            }
          });
        } else {
          this._startDeploy();
        }
      }
    },
 
    /**
     * Start deploy process
     * @method startDeploy
     */
    _startDeploy: function _startDeploy() {
      this.createCluster();
      this.createSelectedServices();
      if (!this.get('isAddHost')) {
        if (this.get('isAddService')) {
          // for manually enabled Kerberos descriptor was updated on transition to this step
          Iif (App.get('isKerberosEnabled') && !this.get('isManualKerberos')) {
            this.updateKerberosDescriptor();
          }
          var fileNamesToUpdate = this.get('wizardController').getDBProperty('fileNamesToUpdate').uniq();
          if (fileNamesToUpdate && fileNamesToUpdate.length) {
            this.applyConfigurationsToCluster(this.generateDesiredConfigsJSON(this.get('configs'), fileNamesToUpdate));
          }
        }
        this.createConfigurations();
        this.applyConfigurationsToCluster(this.get('serviceConfigTags'));
      }
      this.createComponents();
      this.registerHostsToCluster();
      this.createConfigurationGroups();
      this.createMasterHostComponents();
      this.createSlaveAndClientsHostComponents();
      if (this.get('isAddService')) {
        this.createAdditionalClientComponents();
      }
      this.createAdditionalHostComponents();
 
      this.set('ajaxQueueLength', this.get('ajaxRequestsQueue.queue.length'));
      this.get('ajaxRequestsQueue').start();
      this.showLoadingIndicator();
    },
 
    /**
     * *******************************************************************
     * The following create* functions are called upon submitting Step 8.
     * *******************************************************************
     */
 
    /**
     * Create cluster using selected stack version
     * Queued request
     * @method createCluster
     */
    createCluster: function createCluster() {
      Iif (!this.get('isInstaller')) return;
      var stackVersion = this.get('content.installOptions.localRepo') ? App.currentStackVersion.replace(/(-\d+(\.\d)*)/ig, "Local$&") : App.currentStackVersion;
      this.addRequestToAjaxQueue({
        name: 'wizard.step8.create_cluster',
        data: {
          data: JSON.stringify({ "Clusters": { "version": stackVersion } })
        },
        success: 'createClusterSuccess'
      });
    },
 
    createClusterSuccess: function createClusterSuccess(data, xhr, params) {
      App.set('clusterName', params.cluster);
    },
 
    /**
     * Create selected to install services
     * Queued request
     * Skipped if no services where selected!
     * @method createSelectedServices
     */
    createSelectedServices: function createSelectedServices() {
      var data = this.createSelectedServicesData();
      if (!data.length) return;
      this.addRequestToAjaxQueue({
        name: 'wizard.step8.create_selected_services',
        data: {
          data: JSON.stringify(data)
        }
      });
    },
 
    /**
     * Format data for <code>createSelectedServices</code> request
     * @returns {Object[]}
     * @method createSelectedServicesData
     */
    createSelectedServicesData: function createSelectedServicesData() {
      var selectedStack;
      Iif (this.get('isInstaller')) {
        selectedStack = App.Stack.find().findProperty('isSelected', true);
      }
      return this.get('selectedServices').map(function (service) {
        return selectedStack ? { "ServiceInfo": { "service_name": service.get('serviceName'), "desired_repository_version_id": selectedStack.get('versionInfoId') } } : { "ServiceInfo": { "service_name": service.get('serviceName') } };
      });
    },
 
    /**
     * Create components for selected services
     * Queued requests
     * One request for each service!
     * @method createComponents
     */
    createComponents: function createComponents() {
      var serviceComponents = App.StackServiceComponent.find().filterProperty('isInstallable');
      this.get('selectedServices').forEach(function (_service) {
        var serviceName = _service.get('serviceName');
        var componentsData = serviceComponents.filterProperty('serviceName', serviceName).map(function (_component) {
          return { "ServiceComponentInfo": { "component_name": _component.get('componentName') } };
        });
 
        // Service must be specified in terms of a query for creating multiple components at the same time.
        // See AMBARI-1018.
        this.addRequestToCreateComponent(componentsData, serviceName);
      }, this);
 
      if (this.get('isAddHost')) {
        var allServiceComponents = [];
        var services = App.Service.find().mapProperty('serviceName');
        services.forEach(function (_service) {
          var _serviceComponents = App.Service.find(_service).get('serviceComponents');
          allServiceComponents = allServiceComponents.concat(_serviceComponents);
        }, this);
        this.get('content.slaveComponentHosts').forEach(function (component) {
          if (component.componentName !== 'CLIENT' && !allServiceComponents.contains(component.componentName)) {
            this.addRequestToCreateComponent([{ "ServiceComponentInfo": { "component_name": component.componentName } }], App.StackServiceComponent.find().findProperty('componentName', component.componentName).get('serviceName'));
          }
        }, this);
        this.get('content.clients').forEach(function (component) {
          if (!allServiceComponents.contains(component.component_name)) {
            this.addRequestToCreateComponent([{ "ServiceComponentInfo": { "component_name": component.component_name } }], App.StackServiceComponent.find().findProperty('componentName', component.component_name).get('serviceName'));
          }
        }, this);
      }
    },
 
    /**
     * Add request to ajax queue to create service component
     * @param componentsData
     * @param serviceName
     */
    addRequestToCreateComponent: function addRequestToCreateComponent(componentsData, serviceName) {
      this.addRequestToAjaxQueue({
        name: 'wizard.step8.create_components',
        data: {
          data: JSON.stringify({ "components": componentsData }),
          serviceName: serviceName
        }
      });
    },
 
    /**
     * Error callback for new service component request
     * So, if component doesn't exist we should create it
     * @param {object} request
     * @param {object} ajaxOptions
     * @param {string} error
     * @param {object} opt
     * @param {object} params
     * @method newServiceComponentErrorCallback
     */
    newServiceComponentErrorCallback: function newServiceComponentErrorCallback(request, ajaxOptions, error, opt, params) {
      this.addRequestToAjaxQueue({
        name: 'wizard.step8.create_components',
        data: {
          serviceName: params.serviceName,
          data: JSON.stringify({
            "components": [{
              "ServiceComponentInfo": {
                "component_name": params.componentName
              }
            }]
          })
        }
      });
    },
 
    /**
     * Register hosts
     * Queued request
     * @method registerHostsToCluster
     */
    registerHostsToCluster: function registerHostsToCluster() {
      var data = this.createRegisterHostData();
      if (!data.length) return;
      this.addRequestToAjaxQueue({
        name: 'wizard.step8.register_host_to_cluster',
        data: {
          data: JSON.stringify(data)
        }
      });
    },
 
    /**
     * Format request-data for <code>registerHostsToCluster</code>
     * @returns {Object}
     * @method createRegisterHostData
     */
    createRegisterHostData: function createRegisterHostData() {
      return this.getRegisteredHosts().filterProperty('isInstalled', false).map(function (host) {
        return { "Hosts": { "host_name": host.hostName } };
      });
    },
 
    /**
     * Register new master components
     * @uses registerHostsToComponent
     * @method createMasterHostComponents
     */
    createMasterHostComponents: function createMasterHostComponents() {
      var masterOnAllHosts = [];
 
      this.get('content.services').filterProperty('isSelected').forEach(function (service) {
        service.get('serviceComponents').filterProperty('isRequiredOnAllHosts').forEach(function (component) {
          Eif (component.get('isMaster')) {
            masterOnAllHosts.push(component.get('componentName'));
          }
        }, this);
      }, this);
 
      // create master components for only selected services.
      var selectedMasterComponents = this.get('content.masterComponentHosts').filter(function (_component) {
        return this.get('selectedServices').mapProperty('serviceName').contains(_component.serviceId);
      }, this);
      selectedMasterComponents.mapProperty('component').uniq().forEach(function (component) {
        var hostNames = [];
        if (masterOnAllHosts.length > 0) {
          var compOnAllHosts = false;
          for (var i = 0; i < masterOnAllHosts.length; i++) {
            if (component === masterOnAllHosts[i]) {
              compOnAllHosts = true;
              break;
            }
          }
          if (!compOnAllHosts) {
            hostNames = selectedMasterComponents.filterProperty('component', component).filterProperty('isInstalled', false).mapProperty('hostName');
            this.registerHostsToComponent(hostNames, component);
          }
        } else {
          hostNames = selectedMasterComponents.filterProperty('component', component).filterProperty('isInstalled', false).mapProperty('hostName');
          this.registerHostsToComponent(hostNames, component);
        }
      }, this);
    },
 
    getClientsMap: function getClientsMap(flag) {
      var clients = App.StackServiceComponent.find().filterProperty('isClient'),
          clientsMap = {},
          dependedComponents = flag ? App.StackServiceComponent.find().filterProperty(flag) : App.StackServiceComponent.find();
      clients.forEach(function (client) {
        var clientName = client.get('componentName');
        clientsMap[clientName] = Em.A([]);
        dependedComponents.forEach(function (component) {
          if (component.dependsOn(client)) clientsMap[clientName].push(component.get('componentName'));
        });
        if (!clientsMap[clientName].length) delete clientsMap[clientName];
      });
      return clientsMap;
    },
 
    /**
     * Register slave components and clients
     * @uses registerHostsToComponent
     * @method createSlaveAndClientsHostComponents
     */
    createSlaveAndClientsHostComponents: function createSlaveAndClientsHostComponents() {
      var masterHosts = this.get('content.masterComponentHosts');
      var slaveHosts = this.get('content.slaveComponentHosts');
      var clients = this.get('content.clients').filterProperty('isInstalled', false);
      var slaveOnAllHosts = [];
      var clientOnAllHosts = [];
 
      this.get('content.services').filterProperty('isSelected').forEach(function (service) {
        service.get('serviceComponents').filterProperty('isRequiredOnAllHosts').forEach(function (component) {
          if (component.get('isClient')) {
            clientOnAllHosts.push(component.get('componentName'));
          } else if (component.get('isSlave')) {
            slaveOnAllHosts.push(component.get('componentName'));
          }
        }, this);
      }, this);
 
      /**
       * Determines on which hosts client should be installed (based on availability of master components on hosts)
       * @type {Object}
       * Format:
       * <code>
       *  {
       *    CLIENT1: Em.A([MASTER1, MASTER2, ...]),
       *    CLIENT2: Em.A([MASTER3, MASTER1, ...])
       *    ...
       *  }
       * </code>
       */
      var clientsToMasterMap = this.getClientsMap('isMaster'),
          clientsToSlaveMap = this.getClientsMap('isSlave');
 
      slaveHosts.forEach(function (_slave) {
        var hostNames = [];
        var compOnAllHosts;
        if (_slave.componentName !== 'CLIENT') {
          Iif (slaveOnAllHosts.length > 0) {
            compOnAllHosts = false;
            for (var i = 0; i < slaveOnAllHosts.length; i++) {
              if (_slave.componentName === slaveOnAllHosts[i]) {
                // component with ALL cardinality should not
                // registerHostsToComponent in createSlaveAndClientsHostComponents
                compOnAllHosts = true;
                break;
              }
            }
            if (!compOnAllHosts) {
              hostNames = _slave.hosts.filterProperty('isInstalled', false).mapProperty('hostName');
              this.registerHostsToComponent(hostNames, _slave.componentName);
            }
          } else {
            hostNames = _slave.hosts.filterProperty('isInstalled', false).mapProperty('hostName');
            this.registerHostsToComponent(hostNames, _slave.componentName);
          }
        } else {
          clients.forEach(function (_client) {
            hostNames = _slave.hosts.mapProperty('hostName');
            // The below logic to install clients to existing/New master hosts should not be applied to Add Host wizard.
            // This is with the presumption that Add Host controller does not add any new Master component to the cluster
            Eif (!this.get('isAddHost')) {
              Iif (clientsToMasterMap[_client.component_name]) {
                clientsToMasterMap[_client.component_name].forEach(function (componentName) {
                  masterHosts.filterProperty('component', componentName).forEach(function (_masterHost) {
                    hostNames.pushObject(_masterHost.hostName);
                  });
                });
              }
            }
            Iif (clientsToSlaveMap[_client.component_name]) {
              clientsToSlaveMap[_client.component_name].forEach(function (componentName) {
                slaveHosts.filterProperty('componentName', componentName).forEach(function (slaveHost) {
                  hostNames = hostNames.concat(slaveHost.hosts.mapProperty('hostName')).uniq();
                });
              });
            }
            Iif (clientOnAllHosts.length > 0) {
              compOnAllHosts = false;
              for (var i = 0; i < clientOnAllHosts.length; i++) {
                if (_client.component_name === clientOnAllHosts[i]) {
                  // component with ALL cardinality should not
                  // registerHostsToComponent in createSlaveAndClientsHostComponents
                  compOnAllHosts = true;
                  break;
                }
              }
              if (!compOnAllHosts) {
                hostNames = hostNames.uniq();
                this.registerHostsToComponent(hostNames, _client.component_name);
              }
            } else {
              hostNames = hostNames.uniq();
              this.registerHostsToComponent(hostNames, _client.component_name);
            }
          }, this);
        }
      }, this);
    },
 
    /**
     * This function is specific to addServiceController
     * Newly introduced master components requires some existing client components to be hosted along with them
     */
    createAdditionalClientComponents: function createAdditionalClientComponents() {
      var masterHosts = this.get('content.masterComponentHosts');
      var clientHosts = [];
      Eif (this.get('content.slaveComponentHosts').someProperty('componentName', 'CLIENT')) {
        clientHosts = this.get('content.slaveComponentHosts').findProperty('componentName', 'CLIENT').hosts;
      }
      var clients = this.get('content.clients').filterProperty('isInstalled', false);
      var clientsToMasterMap = this.getClientsMap('isMaster');
      var clientsToClientMap = this.getClientsMap('isClient');
      var installedClients = [];
 
      // Get all the installed Client components
      this.get('content.services').filterProperty('isInstalled').forEach(function (_service) {
        var serviceClients = App.StackServiceComponent.find().filterProperty('serviceName', _service.get('serviceName')).filterProperty('isClient');
        serviceClients.forEach(function (client) {
          installedClients.push(client.get('componentName'));
        }, this);
      }, this);
 
      // Check if there is a dependency for being co-hosted between existing client and selected new master
      installedClients.forEach(function (_clientName) {
        if (clientsToMasterMap[_clientName] || clientsToClientMap[_clientName]) {
          var hostNames = [];
          if (clientsToMasterMap[_clientName]) {
            clientsToMasterMap[_clientName].forEach(function (componentName) {
              masterHosts.filterProperty('component', componentName).filterProperty('isInstalled', false).forEach(function (_masterHost) {
                hostNames.pushObject(_masterHost.hostName);
              }, this);
            }, this);
          }
          if (clientsToClientMap[_clientName]) {
            clientsToClientMap[_clientName].forEach(function (componentName) {
              clientHosts.forEach(function (_clientHost) {
                var host = this.get('content.hosts')[_clientHost.hostName];
                var isClientSelected = clients.someProperty('component_name', componentName);
                if (host.isInstalled && isClientSelected && !host.hostComponents.someProperty('HostRoles.component_name', componentName)) {
                  hostNames.pushObject(_clientHost.hostName);
                }
              }, this);
            }, this);
          }
          hostNames = hostNames.uniq();
          if (hostNames.length > 0) {
            // If a dependency for being co-hosted is derived between existing client and selected new master but that
            // dependency is already satisfied in the cluster then disregard the derived dependency
            this.removeClientsFromList(_clientName, hostNames);
            this.registerHostsToComponent(hostNames, _clientName);
            if (hostNames.length > 0) {
              this.get('content.additionalClients').pushObject({ hostNames: hostNames, componentName: _clientName });
            }
          }
        }
      }, this);
    },
 
    /**
     *
     * @param clientName
     * @param hostList
     */
    removeClientsFromList: function removeClientsFromList(clientName, hostList) {
      var clientHosts = [];
      var installedHosts = this.get('content.hosts');
      for (var hostName in installedHosts) {
        if (installedHosts[hostName].isInstalled) {
          if (installedHosts[hostName].hostComponents.mapProperty('HostRoles.component_name').contains(clientName)) {
            clientHosts.push(hostName);
          }
        }
      }
 
      Eif (clientHosts.length > 0) {
        clientHosts.forEach(function (hostName) {
          Eif (hostList.contains(hostName)) {
            hostList.splice(hostList.indexOf(hostName), 1);
          }
        }, this);
      }
    },
 
    /**
     * Register additional components
     * Based on availability of some services
     * @uses registerHostsToComponent
     * @method createAdditionalHostComponents
     */
    createAdditionalHostComponents: function createAdditionalHostComponents() {
      var masterHosts = this.get('content.masterComponentHosts');
 
      // add all components with cardinality == ALL of selected services
      var registeredHosts = this.getRegisteredHosts();
      var notInstalledHosts = registeredHosts.filterProperty('isInstalled', false);
      this.get('content.services').filterProperty('isSelected').forEach(function (service) {
        service.get('serviceComponents').filterProperty('isRequiredOnAllHosts').forEach(function (component) {
          if (service.get('isInstalled') && notInstalledHosts.length) {
            this.registerHostsToComponent(notInstalledHosts.mapProperty('hostName'), component.get('componentName'));
          } else Eif (!service.get('isInstalled') && registeredHosts.length) {
            this.registerHostsToComponent(registeredHosts.mapProperty('hostName'), component.get('componentName'));
          }
        }, this);
      }, this);
 
      // add MySQL Server if Hive is selected
      var hiveService = this.get('content.services').filterProperty('isSelected', true).filterProperty('isInstalled', false).findProperty('serviceName', 'HIVE');
      if (hiveService) {
        var hiveDb = this.get('content.serviceConfigProperties').findProperty('name', 'hive_database');
        if (hiveDb.value === "New MySQL Database") {
          this.registerHostsToComponent(masterHosts.filterProperty('component', 'HIVE_SERVER').mapProperty('hostName'), 'MYSQL_SERVER');
        } else Eif (hiveDb.value === "New PostgreSQL Database") {
          this.registerHostsToComponent(masterHosts.filterProperty('component', 'HIVE_SERVER').mapProperty('hostName'), 'POSTGRESQL_SERVER');
        }
      }
    },
 
    /**
     * Register component to hosts
     * Queued request
     * @param {String[]} hostNames
     * @param {String} componentName
     * @method registerHostsToComponent
     */
    registerHostsToComponent: function registerHostsToComponent(hostNames, componentName) {
      if (!hostNames.length) return;
 
      var queryStr = '';
      hostNames.forEach(function (hostName) {
        queryStr += 'Hosts/host_name=' + hostName + '|';
      });
      //slice off last symbol '|'
      queryStr = queryStr.slice(0, -1);
 
      var data = {
        "RequestInfo": {
          "query": queryStr
        },
        "Body": {
          "host_components": [{
            "HostRoles": {
              "component_name": componentName
            }
          }]
        }
      };
 
      this.addRequestToAjaxQueue({
        name: 'wizard.step8.register_host_to_component',
        data: {
          data: JSON.stringify(data)
        }
      });
    },
 
    /**
     * Create config objects for cluster and services
     * @method createConfigurations
     */
    createConfigurations: function createConfigurations() {
      if (this.get('isInstaller')) {
        /** add cluster-env **/
        this.get('serviceConfigTags').pushObject(this.createDesiredConfig('cluster-env', this.get('configs').filterProperty('filename', 'cluster-env.xml')));
      }
 
      this.get('selectedServices').forEach(function (service) {
        Object.keys(service.get('configTypes')).forEach(function (type) {
          if (!this.get('serviceConfigTags').someProperty('type', type)) {
            var configs = this.get('configs').filterProperty('filename', App.config.getOriginalFileName(type));
            var serviceConfigNote = this.getServiceConfigNote(type, service.get('displayName'));
            this.get('serviceConfigTags').pushObject(this.createDesiredConfig(type, configs, serviceConfigNote));
          }
        }, this);
      }, this);
      this.createNotification();
    },
 
    /**
     * Get config version message
     *
     * @param type
     * @param serviceDisplayName
     * @returns {*}
     */
    getServiceConfigNote: function getServiceConfigNote(type, serviceDisplayName) {
      return this.get('isAddService') && type === 'core-site' ? Em.I18n.t('dashboard.configHistory.table.notes.addService') : Em.I18n.t('dashboard.configHistory.table.notes.default').format(serviceDisplayName);
    },
 
    /**
     * Send <code>serviceConfigTags</code> to server
     * Queued request
     * One request for each service config tag
     * @param serviceConfigTags
     * @method applyConfigurationsToCluster
     */
    applyConfigurationsToCluster: function applyConfigurationsToCluster(serviceConfigTags) {
      var allServices = this.get('installedServices').concat(this.get('selectedServices'));
      var allConfigData = [];
      allServices.forEach(function (service) {
        var serviceConfigData = [];
        Object.keys(service.get('configTypesRendered')).forEach(function (type) {
          var serviceConfigTag = serviceConfigTags.findProperty('type', type);
          Eif (serviceConfigTag) {
            serviceConfigData.pushObject(serviceConfigTag);
          }
        }, this);
        Eif (serviceConfigData.length) {
          allConfigData.pushObject(JSON.stringify({
            Clusters: {
              desired_config: serviceConfigData.map(function (item) {
                var props = {};
                Em.keys(item.properties).forEach(function (propName) {
                  Eif (item.properties[propName] !== null) {
                    props[propName] = item.properties[propName];
                  }
                });
                item.properties = props;
                return item;
              })
            }
          }));
        }
      }, this);
      var clusterConfig = serviceConfigTags.findProperty('type', 'cluster-env');
      Iif (clusterConfig) {
        allConfigData.pushObject(JSON.stringify({
          Clusters: {
            desired_config: [clusterConfig]
          }
        }));
      }
 
      this.addRequestToAjaxQueue({
        name: 'common.across.services.configurations',
        data: {
          data: '[' + allConfigData.toString() + ']'
        }
      });
    },
 
    /**
     * Create and update config groups
     * @method createConfigurationGroups
     */
    createConfigurationGroups: function createConfigurationGroups() {
      var configGroups = this.get('content.configGroups').filterProperty('is_default', false);
      var groupsToDelete = App.router.get(this.get('content.controllerName')).getDBProperty('groupsToDelete');
      if (groupsToDelete && groupsToDelete.length > 0) {
        this.removeInstalledServicesConfigurationGroups(groupsToDelete);
      }
      configGroups.forEach(function (configGroup) {
        if (configGroup.is_for_update || configGroup.is_temporary) {
          this.saveGroup(configGroup.properties, configGroup, this.getServiceConfigNote('', configGroup.service_id));
        }
      }, this);
      App.ServiceConfigGroup.deleteTemporaryRecords();
    },
 
    /**
     * add request to create config group to queue
     *
     * @param data
     * @method createConfigGroup
     */
    createConfigGroup: function createConfigGroup(data) {
      this.addRequestToAjaxQueue({
        name: 'wizard.step8.apply_configuration_groups',
        sender: this,
        data: {
          data: JSON.stringify(data)
        }
      });
    },
 
    /**
     * add request to update config group to queue
     *
     * @param data {Object}
     * @method updateConfigGroup
     */
    updateConfigGroup: function updateConfigGroup(data) {
      this.addRequestToAjaxQueue({
        name: 'config_groups.update_config_group',
        sender: this,
        data: {
          id: data.ConfigGroup.id,
          configGroup: data
        }
      });
    },
 
    /**
     * Delete selected config groups
     * @param {Object[]} groupsToDelete
     * @method removeInstalledServicesConfigurationGroups
     */
    removeInstalledServicesConfigurationGroups: function removeInstalledServicesConfigurationGroups(groupsToDelete) {
      var self = this;
      groupsToDelete.forEach(function (item) {
        self.deleteConfigurationGroup(Em.Object.create(item));
      });
    },
 
    /**
     * Selected and installed services
     * @override
     */
    currentServices: function () {
      return this.get('installedServices').concat(this.get('selectedServices'));
    }.property('installedServices.length', 'selectedServices.length'),
 
    /**
     * Add handling GLUSTREFS properties
     * @param property
     * @returns {*}
     * @override
     */
    formatValueBeforeSave: function formatValueBeforeSave(property) {
      if (this.formatGLUSTERFSProperties(Em.get(property, 'filename'))) {
        switch (property.name) {
          case "fs.default.name":
            return this.get('configs').someProperty('name', 'fs_glusterfs_default_name') ? this.get('configs').findProperty('name', 'fs_glusterfs_default_name').value : null;
          case "fs.defaultFS":
            return this.get('configs').someProperty('name', 'glusterfs_defaultFS_name') ? this.get('configs').findProperty('name', 'glusterfs_defaultFS_name').value : null;
        }
      }
      return this._super(property);
    },
 
    /**
     * Defines if some GLUSTERFS properties should be changed
     *
     * @param {String} type
     * @returns {boolean}
     */
    formatGLUSTERFSProperties: function formatGLUSTERFSProperties(type) {
      return App.config.getConfigTagFromFileName(type) === 'core-site' && this.get('installedServices').concat(this.get('selectedServices')).someProperty('serviceName', 'GLUSTERFS');
    },
 
    /**
     * Create one Alert Notification (if user select this on step7)
     * Only for Install Wizard and stack
     * @method createNotification
     */
    createNotification: function createNotification() {
      Iif (!this.get('isInstaller')) return;
      var miscConfigs = this.get('configs').filterProperty('serviceName', 'MISC'),
          createNotification = miscConfigs.findProperty('name', 'create_notification').value;
      Iif (createNotification !== 'yes') return;
      var predefinedNotificationConfigNames = require('data/configs/alert_notification').mapProperty('name'),
          configsForNotification = this.get('configs').filterProperty('filename', 'alert_notification');
      var properties = {},
          names = ['ambari.dispatch.recipients', 'mail.smtp.host', 'mail.smtp.port', 'mail.smtp.from', 'mail.smtp.starttls.enable', 'mail.smtp.startssl.enable'];
      Eif (miscConfigs.findProperty('name', 'smtp_use_auth').value == 'true') {
        // yes, it's not converted to boolean
        names.pushObjects(['ambari.dispatch.credential.username', 'ambari.dispatch.credential.password']);
      }
 
      names.forEach(function (name) {
        properties[name] = miscConfigs.findProperty('name', name).value;
      });
 
      properties['ambari.dispatch.recipients'] = properties['ambari.dispatch.recipients'].replace(/\s/g, '').split(',');
 
      configsForNotification.forEach(function (config) {
        if (predefinedNotificationConfigNames.contains(config.name)) return;
        properties[config.name] = config.value;
      });
 
      var apiObject = {
        AlertTarget: {
          name: 'Initial Notification',
          description: 'Notification created during cluster installing',
          global: true,
          notification_type: 'EMAIL',
          alert_states: ['OK', 'WARNING', 'CRITICAL', 'UNKNOWN'],
          properties: properties
        }
      };
      this.addRequestToAjaxQueue({
        name: 'alerts.create_alert_notification',
        data: {
          urlParams: 'overwrite_existing=true',
          data: apiObject
        }
      });
    },
 
    /**
     * Should ajax-queue progress bar be displayed
     * @method showLoadingIndicator
     */
    showLoadingIndicator: function showLoadingIndicator() {
      return App.ModalPopup.show({
 
        header: Em.I18n.t('installer.step8.deployPopup.header'),
 
        showFooter: false,
 
        showCloseButton: false,
 
        bodyClass: Em.View.extend({
 
          templateName: require('templates/wizard/step8/step8_log_popup'),
 
          controllerBinding: 'App.router.wizardStep8Controller',
 
          /**
           * Css-property for progress-bar
           * @type {string}
           */
          barWidth: '',
          progressBarClass: 'progress log_popup',
 
          /**
           * Popup-message
           * @type {string}
           */
          message: '',
 
          /**
           * Set progress bar width and popup message when ajax-queue requests are processed
           * @method ajaxQueueChangeObs
           */
          ajaxQueueChangeObs: function () {
            var length = this.get('controller.ajaxQueueLength');
            var left = this.get('controller.ajaxRequestsQueue.queue.length');
            this.set('barWidth', 'width: ' + (length - left) / length * 100 + '%;');
            this.set('message', Em.I18n.t('installer.step8.deployPopup.message').format(length - left, length));
          }.observes('controller.ajaxQueueLength', 'controller.ajaxRequestsQueue.queue.length'),
 
          /**
           * Hide popup when ajax-queue is finished
           * @method autoHide
           */
          autoHide: function () {
            if (this.get('controller.servicesInstalled')) {
              this.get('parentView').hide();
            }
          }.observes('controller.servicesInstalled'),
 
          ajaxQueueErrorAppears: function () {
            if (this.get('controller.hasErrorOccurred')) {
              this.get('parentView').onClose();
            }
          }.observes('controller.hasErrorOccurred')
 
        })
 
      });
    },
 
    getComponentsForHost: function getComponentsForHost(host) {
      Iif (!host.hostComponents) {
        App.router.get('installerController').get('allHosts');
      }
      var componentNameDetail = [];
      host.hostComponents.mapProperty('componentName').forEach(function (componentName) {
        Iif (componentName === 'CLIENT') {
          this.get('content.clients').mapProperty('component_name').forEach(function (clientComponent) {
            componentNameDetail.push({ name: clientComponent });
          }, this);
          return;
        }
        componentNameDetail.push({ name: componentName });
      }, this);
      return componentNameDetail;
    },
 
    getPropertyAttributesForConfigType: function getPropertyAttributesForConfigType(configs) {
      //Currently only looks for final properties, if any
      var finalProperties = configs.filterProperty('isFinal', 'true');
      var propertyAttributes = {};
      finalProperties.forEach(function (finalProperty) {
        propertyAttributes[finalProperty['name']] = "true";
      });
      var finalPropertyMap = {};
      Iif (!App.isEmptyObject(finalProperties)) {
        finalPropertyMap = {
          "isFinal": propertyAttributes
        };
      }
      return finalPropertyMap;
    },
 
    getConfigurationDetailsForConfigType: function getConfigurationDetailsForConfigType(configs) {
      var configDetails = {};
      var self = this;
      configs.forEach(function (propertyObj) {
        configDetails[propertyObj['name']] = propertyObj['value'];
      }, this);
      var configurationsDetails = {
        "properties_attributes": self.getPropertyAttributesForConfigType(configs),
        "properties": configDetails
      };
      return configurationsDetails;
    },
 
    hostInExistingHostGroup: function hostInExistingHostGroup(newHost, host_groups) {
      var hostGroupMatched = false;
      host_groups.some(function (existingHostGroup) {
        Eif (!hostGroupMatched) {
          var fqdnInHostGroup = existingHostGroup.hosts[0].fqdn;
          var componentsInExistingHostGroup = this.getRegisteredHosts().filterProperty('hostName', fqdnInHostGroup)[0].hostComponents;
          Iif (componentsInExistingHostGroup.length !== newHost.hostComponents.length) {
            return;
          } else {
            var componentMismatch = false;
            componentsInExistingHostGroup.forEach(function (componentInExistingHostGroup, index) {
              if (!componentMismatch) {
                if (!newHost.hostComponents.mapProperty('componentName').includes(componentInExistingHostGroup.componentName)) {
                  componentMismatch = true;
                }
              }
            });
            if (!componentMismatch) {
              hostGroupMatched = true;
              existingHostGroup["cardinality"] = parseInt(existingHostGroup["cardinality"]) + 1;
              existingHostGroup.hosts.push({ "fqdn": newHost.hostName });
              return true;
            }
          }
        }
      }, this);
      return hostGroupMatched;
    },
 
    hostInChildHostGroup: function hostInChildHostGroup(presentHostGroup, configGroupName, hostInConfigGroup) {
      return presentHostGroup['childHostGroups'].some(function (childHostGroup) {
        //Check if childHostGroup name is same as this configgroupname, if yes, update childHostGroup else, compare with other childhostgroups
        Eif (childHostGroup.configGroupName === configGroupName) {
          childHostGroup.hosts.push({ "fqdn": hostInConfigGroup });
          childHostGroup['cardinality'] = childHostGroup['cardinality'] + 1;
          return true;
        }
      });
    },
 
    /**
     * Confirmation popup before generate blueprint
     */
    generateBlueprintConfirmation: function generateBlueprintConfirmation() {
      var self = this;
      return App.showConfirmationPopup(function () {
        self.generateBlueprint();
      }, Em.I18n.t('installer.step8.generateBlueprint.popup.msg').format(App.clusterStatus.clusterName));
    },
 
    generateBlueprint: function generateBlueprint() {
      console.log("Prepare blueprint for download...");
      var self = this;
      //service configurations
      var totalConf = [];
      //Add cluster-env
      var clusterEnv = this.get('configs').filterProperty('filename', 'cluster-env.xml');
      var configurations = {};
      configurations["cluster-env"] = self.getConfigurationDetailsForConfigType(clusterEnv);
      totalConf.push(configurations);
      //Add configurations for selected services
      this.get('selectedServices').forEach(function (service) {
        Object.keys(service.get('configTypes')).forEach(function (type) {
          Eif (!this.get('serviceConfigTags').someProperty('type', type)) {
            var configs = this.get('configs').filterProperty('filename', App.config.getOriginalFileName(type));
            var configurations = {};
            configurations[type] = self.getConfigurationDetailsForConfigType(configs);
            totalConf.push(configurations);
          }
        }, this);
      }, this);
 
      var host_groups = [];
      var cluster_template_host_groups = [];
      var counter = 0;
 
      this.getRegisteredHosts().filterProperty('isInstalled', false).map(function (host) {
        if (self.hostInExistingHostGroup(host, host_groups)) {
          return;
        }
        //Create new host_group if host is not mapped to existing host_groups
        var hostGroupId = "host_group_" + counter;
        var hostListForGroup = [];
        hostListForGroup.push({ "fqdn": host.hostName });
        var hostGroupDetail = {
          "name": hostGroupId,
          "components": self.getComponentsForHost(host),
          "hosts": hostListForGroup,
          "cardinality": 1
        };
        hostGroupDetail.toJSON = function () {
          var hostGroupDetailResult = _.omit(this, ["hosts", "childHostGroups"]);
          hostGroupDetailResult["cardinality"] = this["cardinality"].toString();
          return hostGroupDetailResult;
        };
        host_groups.push(hostGroupDetail);
 
        var clusterTemplateHostGroupDetail = {
          "name": hostGroupId,
          "hosts": hostListForGroup
        };
 
        cluster_template_host_groups.push(clusterTemplateHostGroupDetail);
        counter++;
      }, this);
 
      this.get('content.configGroups').filterProperty("is_default", false).forEach(function (configGroup) {
        if (configGroup.properties.length == 0) {
          return;
        }
        configGroup.hosts.forEach(function (hostInConfigGroup) {
          return host_groups.some(function (presentHostGroup) {
            return presentHostGroup.hosts.some(function (hostInPresentHostGroup, index) {
              Iif (hostInConfigGroup !== hostInPresentHostGroup.fqdn) {
                return;
              }
              //Check if childHostGroup already created
              if (presentHostGroup['childHostGroups']) {
                Eif (self.hostInChildHostGroup(presentHostGroup, configGroup.name, hostInConfigGroup)) {
                  // Update to remove parentHostGroup as all the hosts are added to childHostGroup/s
                  presentHostGroup.hosts.splice(index, 1);
                  presentHostGroup["cardinality"] = presentHostGroup['cardinality'] - 1;
                  return true;
                }
              }
              //create configuration object
              var hgConfigurations;
              Iif (presentHostGroup.hosts.length === 1 && presentHostGroup["configurations"]) {
                hgConfigurations = presentHostGroup["configurations"][0];
              } else Iif (presentHostGroup["configurations"]) {
                //Deep copy
                hgConfigurations = jQuery.extend(true, {}, presentHostGroup["configurations"][0]);
              } else {
                hgConfigurations = {};
              }
              configGroup.properties.forEach(function (hgProperties) {
                var type = App.config.getConfigTagFromFileName(hgProperties.filename);
                Eif (!hgConfigurations[type]) {
                  hgConfigurations[type] = { properties: {} };
                }
                hgConfigurations[type]['properties'][hgProperties.name] = hgProperties.value;
              });
              var totalHgConf = [];
              totalHgConf.push(hgConfigurations);
              //If only host in presentHostGroup then merge configuration and return
              Iif (presentHostGroup.hosts.length === 1) {
                //If host_group already has configuration, assigned from previously processed config_group
                if (!presentHostGroup["configurations"]) {
                  presentHostGroup["configurations"] = totalHgConf;
                }
                return true;
              }
 
              //Create new host_group from this host
              var hostGroupId = "host_group_" + counter;
              counter++;
              var hostListForGroup = [];
              hostListForGroup.push({ "fqdn": hostInPresentHostGroup.fqdn });
              var hostGroupDetail = {
                "name": hostGroupId,
                "components": presentHostGroup.components,
                "cardinality": 1,
                "hosts": hostListForGroup,
                "configurations": totalHgConf,
                "configGroupName": configGroup.name
              };
              hostGroupDetail.toJSON = function () {
                var hostGroupDetailResult = _.omit(this, ["hosts", "configGroupName", "childHostGroups"]);
                hostGroupDetailResult["cardinality"] = this["cardinality"].toString();
                return hostGroupDetailResult;
              };
              host_groups.push(hostGroupDetail);
              //Update for clustertemplate file
              var clusterTemplateHostGroupDetail = {
                "name": hostGroupId,
                "hosts": hostListForGroup
              };
              cluster_template_host_groups.push(clusterTemplateHostGroupDetail);
              //Add newly created host_group as child to existing host_group
              Eif (!presentHostGroup['childHostGroups']) {
                presentHostGroup['childHostGroups'] = [];
              }
              presentHostGroup['childHostGroups'].push(hostGroupDetail);
              presentHostGroup.hosts.splice(index, 1);
              presentHostGroup["cardinality"] = presentHostGroup['cardinality'] - 1;
              //return true to indicate that host has been matched
              return true;
            }, this);
          }, this);
        }, this);
      }, this);
 
      var selectedStack = App.Stack.find().findProperty('isSelected', true);
      var blueprint = {
        'configurations': totalConf,
        'host_groups': host_groups.filter(function (item) {
          return item.cardinality > 0;
        }),
        'Blueprints': { 'blueprint_name': App.clusterStatus.clusterName, 'stack_name': selectedStack.get('stackName'), 'stack_version': selectedStack.get('stackVersion') }
      };
      var cluster_template = {
        "blueprint": App.clusterStatus.clusterName,
        "config_recommendation_strategy": "NEVER_APPLY",
        "provision_action": "INSTALL_AND_START",
        "configurations": [],
        "host_groups": cluster_template_host_groups.filter(function (item) {
          return item.hosts.length > 0;
        }),
        "Clusters": { 'cluster_name': App.clusterStatus.clusterName }
      };
      fileUtils.downloadFilesInZip([{
        data: JSON.stringify(blueprint),
        type: 'json',
        name: 'blueprint.json'
      }, {
        data: JSON.stringify(cluster_template),
        type: 'json',
        name: 'clustertemplate.json'
      }]);
    },
 
    downloadCSV: function downloadCSV() {
      App.router.get('kerberosWizardStep5Controller').getCSVData(false);
    }
  });
});