glances.py 74.5 KB
Newer Older
A
asergi 已提交
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
#!/usr/bin/env python
#
# Glances is a simple textual monitoring tool
#
# Pre-requisites: Python 2.6+ and PsUtil 0.4.0+ (for full functions)
#
# Copyright (C) Nicolargo 2012 <nicolas@nicolargo.com>
#
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.";
#

from __future__ import generators

__appname__ = 'glances'
__version__ = "1.4"
__author__ = "Nicolas Hennion <nicolas@nicolargo.com>"
__licence__ = "LGPL"

# Libraries
#==========

import os
import sys
import platform
import getopt
import signal
import time
from datetime import datetime, timedelta
import gettext

# International
#==============

gettext.install(__appname__)

# Test methods
#=============

try:
    import curses
    import curses.panel
except ImportError:
    print _('Curses module not found. Glances cannot start.')
    print _('Glances requires at least Python 2.6 or higher.')
    print
    sys.exit(1)

try:
    import psutil
except ImportError:
    print _('PsUtil module not found. Glances cannot start.')
    print
    print _('On Ubuntu 12.04 or higher:')
    print _('$ sudo apt-get install python-psutil')
    print
    print _('To install PsUtil using pip (as root):')
    print _('# pip install psutil')
    print
    sys.exit(1)

try:
    # get_cpu_percent method only available with PsUtil 0.2.0+
    psutil.Process(os.getpid()).get_cpu_percent(interval=0)
except Exception:
    psutil_get_cpu_percent_tag = False
else:
    psutil_get_cpu_percent_tag = True

try:
    # (phy|virt)mem_usage methods only available with PsUtil 0.3.0+
    psutil.phymem_usage()
    psutil.virtmem_usage()
except Exception:
    psutil_mem_usage_tag = False
else:
    psutil_mem_usage_tag = True

try:
    # disk_(partitions|usage) methods only available with PsUtil 0.3.0+
    psutil.disk_partitions()
    psutil.disk_usage('/')
except Exception:
    psutil_fs_usage_tag = False
else:
    psutil_fs_usage_tag = True

try:
    # disk_io_counters method only available with PsUtil 0.4.0+
    psutil.disk_io_counters()
except Exception:
    psutil_disk_io_tag = False
else:
    psutil_disk_io_tag = True

try:
    # network_io_counters method only available with PsUtil 0.4.0+
    psutil.network_io_counters()
except Exception:
    psutil_network_io_tag = False
else:
    psutil_network_io_tag = True

try:
    # HTML output
    import jinja2
except ImportError:
    jinja_tag = False
else:
    jinja_tag = True

try:
    # CSV output
    import csv
except ImportError:
    csvlib_tag = False
else:
    csvlib_tag = True


# Classes
#========

class Timer:
    """
    The timer class
    """

    def __init__(self, duration):
        self.started(duration)

    def started(self, duration):
        self.target = time.time() + duration

    def finished(self):
        return time.time() > self.target


class glancesLimits:
    """
    Manage the limit OK,CAREFUL,WARNING,CRITICAL for each stats
    """

    # The limit list is stored in an hash table:
    #  limits_list[STAT] = [CAREFUL, WARNING, CRITICAL]
    # Exemple:
    #  limits_list['STD'] = [50, 70, 90]

    #_______________________________CAREFUL WARNING CRITICAL
    __limits_list = {'STD': [50, 70, 90],
                     'LOAD': [0.7, 1.0, 5.0]}

    def __init__(self, careful=50, warning=70, critical=90):
        self.__limits_list['STD'] = [careful, warning, critical]

    def getSTDCareful(self):
        return self.__limits_list['STD'][0]

    def getSTDWarning(self):
        return self.__limits_list['STD'][1]

    def getSTDCritical(self):
        return self.__limits_list['STD'][2]

    def getLOADCareful(self, core=1):
        return self.__limits_list['LOAD'][0] * core

    def getLOADWarning(self, core=1):
        return self.__limits_list['LOAD'][1] * core

    def getLOADCritical(self, core=1):
        return self.__limits_list['LOAD'][2] * core


class glancesLogs:
    """
    The main class to manage logs inside the Glances software
    Logs is a list of list:
    [["begin", "end", "WARNING|CRITICAL", "CPU|LOAD|MEM",
      MAX, AVG, MIN, SUM, COUNT],...]
    """

    def __init__(self):
        """
        Init the logs classe
        """
        # Maximum size of the logs list
        self.logs_max = 10

        # Init the logs list
        self.logs_list = []

    def get(self):
        """
        Return the logs list (RAW)
        """
        return self.logs_list

    def len(self):
        """
        Return the number of item in the log list
        """
        return self.logs_list.__len__()

    def __itemexist__(self, item_type):
        """
        An item exist in the list if:
        * end is < 0
        * item_type is matching
        """
        for i in xrange(self.len()):
            if (self.logs_list[i][1] < 0 and
                self.logs_list[i][3] == item_type):
                return i
        return -1

    def add(self, item_state, item_type, item_value):
        """
        item_state = "OK|CAREFUL|WARNING|CRITICAL"
        item_type = "CPU|LOAD|MEM"
        item_value = value
        Item is defined by:
          ["begin", "end", "WARNING|CRITICAL", "CPU|LOAD|MEM",
           MAX, AVG, MIN, SUM, COUNT]
        If item is a 'new one':
          Add the new item at the beginning of the logs list
        Else:
          Update the existing item
        """
        item_index = self.__itemexist__(item_type)
        if item_index < 0:
            # Item did not exist, add if WARNING or CRITICAL
            if (item_state == "WARNING" or
                item_state == "CRITICAL"):
                # Time is stored in Epoch format
                # Epoch -> DMYHMS = datetime.fromtimestamp(epoch)
                item = []
                item.append(time.mktime(datetime.now().timetuple()))
                item.append(-1)
                item.append(item_state)     # STATE: WARNING|CRITICAL
                item.append(item_type)      # TYPE: CPU, LOAD, MEM...
                item.append(item_value)     # MAX
                item.append(item_value)     # AVG
                item.append(item_value)     # MIN
                item.append(item_value)     # SUM
                item.append(1)              # COUNT
                self.logs_list.insert(0, item)
                if self.len() > self.logs_max:
                    self.logs_list.pop()
        else:
            # Item exist, update
            if (item_state == "OK" or
                item_state == "CAREFUL"):
                # Close the item
                self.logs_list[item_index][1] = time.mktime(
                    datetime.now().timetuple())
            else:
                # Update the item
                # State
                if item_state == "CRITICAL":
                    self.logs_list[item_index][2] = item_state
                # Value
                if item_value > self.logs_list[item_index][4]:
                    # MAX
                    self.logs_list[item_index][4] = item_value
                elif item_value < self.logs_list[item_index][6]:
                    # MIN
                    self.logs_list[item_index][6] = item_value
                # AVG
                self.logs_list[item_index][7] += item_value
                self.logs_list[item_index][8] += 1
                self.logs_list[item_index][5] = (
                    self.logs_list[item_index][7] /
                    self.logs_list[item_index][8])

        return self.len()


class glancesGrabFs:
    """
    Get FS stats
    """

    def __init__(self):
        """
        Init FS stats
        """

        # Ignore the following FS name
        self.ignore_fsname = ('', 'none', 'gvfs-fuse-daemon', 'fusectl',
                              'cgroup')

        # Ignore the following FS type
        self.ignore_fstype = ('binfmt_misc', 'devpts', 'iso9660', 'none',
                              'proc', 'sysfs', 'usbfs', 'rootfs', 'autofs',
                              'devtmpfs')

    def __update__(self):
        """
        Update the stats
        """

        # Reset the list
        self.fs_list = []

        # Open the current mounted FS
        fs_stat = psutil.disk_partitions(True)
        for fs in xrange(len(fs_stat)):
            fs_current = {}
            fs_current['device_name'] = fs_stat[fs].device
            if fs_current['device_name'] in self.ignore_fsname:
                continue
            fs_current['fs_type'] = fs_stat[fs].fstype
            if fs_current['fs_type'] in self.ignore_fstype:
                continue
            fs_current['mnt_point'] = fs_stat[fs].mountpoint
            try:
                fs_usage = psutil.disk_usage(fs_current['mnt_point'])
            except Exception:
                continue
            fs_current['size'] = fs_usage.total
            fs_current['used'] = fs_usage.used
            fs_current['avail'] = fs_usage.free
            self.fs_list.append(fs_current)

    def get(self):
        self.__update__()
        return self.fs_list


class glancesStats:
    """
    This class store, update and give stats
    """

    def __init__(self):
        """
        Init the stats
        """

        # Init the fs stats
        try:
            self.glancesgrabfs = glancesGrabFs()
        except Exception:
            self.glancesgrabfs = {}

        # Process list refresh
        self.process_list_refresh = True

    def __update__(self):
        """
        Update the stats
        """

        # Host and OS informations
        self.host = {}
        self.host['os_name'] = platform.system()
        self.host['hostname'] = platform.node()
        self.host['platform'] = platform.architecture()[0]

        # check if it's Arch Linux
        is_archlinux = os.path.exists(os.path.join("/", "etc", "arch-release"))

        try:
            if self.host['os_name'] == "Linux":
                if is_archlinux:
                    self.host['linux_distro'] = "Arch Linux"
                else:
                    linux_distro = platform.linux_distribution()
                    self.host['linux_distro'] = " ".join(linux_distro[:2])
                self.host['os_version'] = platform.release()
            elif self.host['os_name'] == "FreeBSD":
                self.host['os_version'] = platform.release()
            elif self.host['os_name'] == "Darwin":
                self.host['os_version'] = platform.mac_ver()[0]
            elif self.host['os_name'] == "Windows":
                os_version = platform.win32_ver()
                self.host['os_version'] = " ".join(os_version[::2])
            else:
                self.host['os_version'] = ""
        except Exception:
            self.host['os_version'] = ""

        # CPU
        percent = 0
        try:
            self.cputime_old
        except Exception:
            self.cputime_old = psutil.cpu_times()
            self.cputime_total_old = (self.cputime_old.user +
                                      self.cputime_old.system +
                                      self.cputime_old.idle)
            # Only available on some OS
            try:
                self.cputime_total_old += self.cputime_old.nice
            except Exception:
                pass
            try:
                self.cputime_total_old += self.cputime_old.iowait
            except Exception:
                pass
            try:
                self.cputime_total_old += self.cputime_old.irq
            except Exception:
                pass
            try:
                self.cputime_total_old += self.cputime_old.softirq
            except Exception:
                pass
            self.cpu = {}
        else:
            try:
                self.cputime_new = psutil.cpu_times()
                self.cputime_total_new = (self.cputime_new.user +
                                          self.cputime_new.system +
                                          self.cputime_new.idle)
                # Only available on some OS
                try:
                    self.cputime_total_new += self.cputime_new.nice
                except Exception:
                    pass
                try:
                    self.cputime_total_new += self.cputime_new.iowait
                except Exception:
                    pass
                try:
                    self.cputime_total_new += self.cputime_new.irq
                except Exception:
                    pass
                try:
                    self.cputime_total_new += self.cputime_new.softirq
                except Exception:
                    pass
                percent = 100 / (self.cputime_total_new -
                                 self.cputime_total_old)
                self.cpu = {'kernel':
                                (self.cputime_new.system -
                                 self.cputime_old.system) * percent,
                            'user':
                                (self.cputime_new.user -
                                 self.cputime_old.user) * percent,
                            'idle':
                                (self.cputime_new.idle -
                                 self.cputime_old.idle) * percent,
                            'nice':
                                (self.cputime_new.nice -
                                 self.cputime_old.nice) * percent}
                self.cputime_old = self.cputime_new
                self.cputime_total_old = self.cputime_total_new
            except Exception:
                self.cpu = {}

        # LOAD
        try:
            getload = os.getloadavg()
            self.load = {'min1': getload[0],
                         'min5': getload[1],
                         'min15': getload[2]}
        except Exception:
            self.load = {}

        # MEM
        try:
            # Only for Linux
            cachemem = psutil.cached_phymem() + psutil.phymem_buffers()
        except Exception:
            cachemem = 0

        try:
            phymem = psutil.phymem_usage()
            self.mem = {'cache': cachemem,
                        'total': phymem.total,
                        'used': phymem.used,
                        'free': phymem.free,
                        'percent': phymem.percent}
        except Exception:
            self.mem = {}

        try:
            virtmem = psutil.virtmem_usage()
            self.memswap = {'total': virtmem.total,
                            'used': virtmem.used,
                            'free': virtmem.free,
                            'percent': virtmem.percent}
        except Exception:
            self.memswap = {}

        # NET
        if psutil_network_io_tag:
            self.network = []
            try:
                self.network_old
            except Exception:
                if psutil_network_io_tag:
                    self.network_old = psutil.network_io_counters(True)
            else:
                try:
                    self.network_new = psutil.network_io_counters(True)
                except Exception:
                    pass
                else:
                    for net in self.network_new:
                        try:
                            netstat = {}
                            netstat['interface_name'] = net
                            netstat['rx'] = (self.network_new[net].bytes_recv -
                                             self.network_old[net].bytes_recv)
                            netstat['tx'] = (self.network_new[net].bytes_sent -
                                             self.network_old[net].bytes_sent)
                        except Exception:
                            continue
                        else:
                            self.network.append(netstat)
                    self.network_old = self.network_new

        # DISK I/O
        if psutil_disk_io_tag:
            self.diskio = []
            try:
                self.diskio_old
            except Exception:
                if psutil_disk_io_tag:
                    self.diskio_old = psutil.disk_io_counters(True)
            else:
                try:
                    self.diskio_new = psutil.disk_io_counters(True)
                except Exception:
                    pass
                else:
                    for disk in self.diskio_new:
                        try:
                            diskstat = {}
                            diskstat['disk_name'] = disk
                            diskstat['read_bytes'] = (
                                self.diskio_new[disk].read_bytes -
                                self.diskio_old[disk].read_bytes)
                            diskstat['write_bytes'] = (
                                self.diskio_new[disk].write_bytes -
                                self.diskio_old[disk].write_bytes)
                        except Exception:
                            continue
                        else:
                            self.diskio.append(diskstat)
                    self.diskio_old = self.diskio_new

        # FILE SYSTEM
        if psutil_fs_usage_tag:
            try:
                self.fs = self.glancesgrabfs.get()
            except Exception:
                self.fs = {}

        # PROCESS
        # Initialiation of the running processes list
        # Data are refreshed every two cycle (refresh_time * 2)
        if self.process_list_refresh:
            self.process_first_grab = False
            try:
                self.process_all
            except Exception:
                self.process_all = [proc for proc in psutil.process_iter()]
                self.process_first_grab = True
            self.process = []
            self.processcount = {'total': 0, 'running': 0, 'sleeping': 0}
            # Manage new processes
            process_new = [proc.pid for proc in self.process_all]
            for proc in psutil.process_iter():
                if proc.pid not in process_new:
                    self.process_all.append(proc)
            # Grab stats from process list
            for proc in self.process_all[:]:
                try:
                    if not proc.is_running():
                        try:
                            self.process_all.remove(proc)
                        except Exception:
                            pass
                except psutil.error.NoSuchProcess:
                    try:
                        self.process_all.remove(proc)
                    except Exception:
                        pass
                else:
                    # Global stats
                    try:
                        self.processcount[str(proc.status)] += 1
                    except psutil.error.NoSuchProcess:
                        # Process non longer exist
                        pass
                    except KeyError:
                        # Key did not exist, create it
                        self.processcount[str(proc.status)] = 1
                    finally:
                        self.processcount['total'] += 1
                    # Per process stats
                    try:
                        procstat = {}
                        procstat['proc_size'] = proc.get_memory_info().vms
                        procstat['proc_resident'] = proc.get_memory_info().rss
                        if psutil_get_cpu_percent_tag:
                            procstat['cpu_percent'] = \
                                proc.get_cpu_percent(interval=0)
                        procstat['mem_percent'] = proc.get_memory_percent()
                        procstat['pid'] = proc.pid
                        procstat['uid'] = proc.username
                        try:
                            # Deprecated in PsUtil 0.5.0
                            procstat['nice'] = proc.nice
                        except:
                            # Specific for PsUtil 0.5.0
                            procstat['nice'] = proc.get_nice()
                        procstat['status'] = str(proc.status)[:1].upper()
                        procstat['proc_time'] = proc.get_cpu_times()
                        procstat['proc_name'] = proc.name
                        procstat['proc_cmdline'] = " ".join(proc.cmdline)
                        self.process.append(procstat)
                    except Exception:
                        pass

            # If it is the first grab then empty process list
            if self.process_first_grab:
                self.process = []

        self.process_list_refresh = not self.process_list_refresh

        # Get the current date/time
        self.now = datetime.now()

        # Get the number of core (CPU) (Used to display load alerts)
        self.core_number = psutil.NUM_CPUS

    def update(self):
        # Update the stats
        self.__update__()

    def getHost(self):
        return self.host

    def getSystem(self):
        return self.host

    def getCpu(self):
        return self.cpu

    def getCore(self):
        return self.core_number

    def getLoad(self):
        return self.load

    def getMem(self):
        return self.mem

    def getMemSwap(self):
        return self.memswap

    def getNetwork(self):
        if psutil_network_io_tag:
            return sorted(self.network,
                          key=lambda network: network['interface_name'])
        else:
            return 0

    def getDiskIO(self):
        if psutil_disk_io_tag:
            return sorted(self.diskio, key=lambda diskio: diskio['disk_name'])
        else:
            return 0

    def getFs(self):
        if psutil_fs_usage_tag:
            return sorted(self.fs, key=lambda fs: fs['mnt_point'])
        else:
            return 0

    def getProcessCount(self):
        return self.processcount

    def getProcessList(self, sortedby='auto'):
        """
        Return the sorted process list
        """

        sortedReverse = True
        if sortedby == 'auto':
            if psutil_get_cpu_percent_tag:
                sortedby = 'cpu_percent'
            else:
                sortedby = 'mem_percent'
            # Auto selection
            # If global MEM > 70% sort by MEM usage
            # else sort by CPU usage
            real_used_phymem = self.mem['used'] - self.mem['cache']
            try:
                memtotal = (real_used_phymem * 100) / self.mem['total']
            except Exception:
                pass
            else:
                if memtotal > limits.getSTDWarning():
                    sortedby = 'mem_percent'
        elif sortedby == 'proc_name':
            sortedReverse = False

        return sorted(self.process, key=lambda process: process[sortedby],
                      reverse=sortedReverse)

    def getNow(self):
        return self.now


class glancesScreen:
    """
    This class manage the screen (display and key pressed)
    """

    # By default the process list is automatically sorted
    # If global CPU > WANRING => Sorted by CPU usage
    # If global used MEM > WARINING => Sorted by MEM usage
    __process_sortedby = 'auto'

    def __init__(self, refresh_time=1):
        # Global information to display
        self.__version = __version__

        # Init windows positions
        self.term_w = 80
        self.term_h = 24
        self.system_x = 0
        self.system_y = 0
        self.cpu_x = 0
        self.cpu_y = 2
        self.load_x = 19
        self.load_y = 2
        self.mem_x = 39
        self.mem_y = 2
        self.network_x = 0
        self.network_y = 7
        self.diskio_x = 0
        self.diskio_y = -1
        self.fs_x = 0
        self.fs_y = -1
        self.process_x = 29
        self.process_y = 7
        self.log_x = 0
        self.log_y = -1
        self.help_x = 0
        self.help_y = 0
        self.now_x = 79
        self.now_y = 3
        self.caption_x = 0
        self.caption_y = 3

        # Init the curses screen
        self.screen = curses.initscr()
        if not self.screen:
            print _("Error: Cannot init the curses library.\n")

        curses.start_color()
        if hasattr(curses, 'use_default_colors'):
            try:
                curses.use_default_colors()
            except Exception:
                pass
        if hasattr(curses, 'noecho'):
            try:
                curses.noecho()
            except Exception:
                pass
        if hasattr(curses, 'cbreak'):
            try:
                curses.cbreak()
            except Exception:
                pass
        if hasattr(curses, 'curs_set'):
            try:
                curses.curs_set(0)
            except Exception:
                pass

        # Init colors
        self.hascolors = False
        if curses.has_colors() and curses.COLOR_PAIRS > 8:
            self.hascolors = True
            # FG color, BG color
            curses.init_pair(1, curses.COLOR_WHITE, -1)
            curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED)
            curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_GREEN)
            curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE)
            curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_MAGENTA)
            curses.init_pair(6, curses.COLOR_RED, -1)
            curses.init_pair(7, curses.COLOR_GREEN, -1)
            curses.init_pair(8, curses.COLOR_BLUE, -1)
            curses.init_pair(9, curses.COLOR_MAGENTA, -1)
        else:
            self.hascolors = False

        self.title_color = curses.A_BOLD | curses.A_UNDERLINE
        self.help_color = curses.A_BOLD
        if self.hascolors:
            # Colors text styles
            self.no_color = curses.color_pair(1)
            self.default_color = curses.color_pair(3) | curses.A_BOLD
            self.ifCAREFUL_color = curses.color_pair(4) | curses.A_BOLD
            self.ifWARNING_color = curses.color_pair(5) | curses.A_BOLD
            self.ifCRITICAL_color = curses.color_pair(2) | curses.A_BOLD
            self.default_color2 = curses.color_pair(7) | curses.A_BOLD
            self.ifCAREFUL_color2 = curses.color_pair(8) | curses.A_BOLD
            self.ifWARNING_color2 = curses.color_pair(9) | curses.A_BOLD
            self.ifCRITICAL_color2 = curses.color_pair(6) | curses.A_BOLD
        else:
            # B&W text styles
            self.no_color = curses.A_NORMAL
            self.default_color = curses.A_NORMAL
            self.ifCAREFUL_color = curses.A_UNDERLINE
            self.ifWARNING_color = curses.A_BOLD
            self.ifCRITICAL_color = curses.A_REVERSE
            self.default_color2 = curses.A_NORMAL
            self.ifCAREFUL_color2 = curses.A_UNDERLINE
            self.ifWARNING_color2 = curses.A_BOLD
            self.ifCRITICAL_color2 = curses.A_REVERSE

        # Define the colors list (hash table) for logged stats
        self.__colors_list = {
            #         CAREFUL WARNING CRITICAL
            'DEFAULT': self.no_color,
            'OK': self.default_color,
            'CAREFUL': self.ifCAREFUL_color,
            'WARNING': self.ifWARNING_color,
            'CRITICAL': self.ifCRITICAL_color
        }

        # Define the colors list (hash table) for non logged stats
        self.__colors_list2 = {
            #         CAREFUL WARNING CRITICAL
            'DEFAULT': self.no_color,
            'OK': self.default_color2,
            'CAREFUL': self.ifCAREFUL_color2,
            'WARNING': self.ifWARNING_color2,
            'CRITICAL': self.ifCRITICAL_color2
        }

        # What are we going to display
        self.network_tag = psutil_network_io_tag
        self.diskio_tag = psutil_disk_io_tag
        self.fs_tag = psutil_fs_usage_tag
        self.log_tag = True
        self.help_tag = False

        # Init main window
        self.term_window = self.screen.subwin(0, 0)

        # Init refresh time
        self.__refresh_time = refresh_time

        # Catch key pressed with non blocking mode
        self.term_window.keypad(1)
        self.term_window.nodelay(1)
        self.pressedkey = -1

    def setProcessSortedBy(self, sorted):
        self.__process_sortedautoflag = False
        self.__process_sortedby = sorted

    def getProcessSortedBy(self):
        return self.__process_sortedby

    def __autoUnit(self, val):
        """
        Convert val to string and concatenate the good unit
        Exemples:
            960 -> 960
            142948 -> 143K
            560745673 -> 561M
            ...
        """
        symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
        prefix = {
            'Y': 1208925819614629174706176L,
            'Z': 1180591620717411303424L,
            'E': 1152921504606846976L,
            'P': 1125899906842624L,
            'T': 1099511627776L,
            'G': 1073741824,
            'M': 1048576,
            'K': 1024
        }

        for key in reversed(symbols):
            if val >= prefix[key]:
                value = float(val) / prefix[key]
                if key == "M" or key == "K":
                    return "{0:.0f}{1}".format(value, key)
                else:
                    return "{0:.1f}{1}".format(value, key)

        return "{!s}".format(val)

    def __getAlert(self, current=0, max=100):
        # If current < CAREFUL of max then alert = OK
        # If current > CAREFUL of max then alert = CAREFUL
        # If current > WARNING of max then alert = WARNING
        # If current > CRITICAL of max then alert = CRITICAL
        try:
            (current * 100) / max
        except ZeroDivisionError:
            return 'DEFAULT'

        variable = (current * 100) / max

        if variable > limits.getSTDCritical():
            return 'CRITICAL'
        elif variable > limits.getSTDWarning():
            return 'WARNING'
        elif variable > limits.getSTDCareful():
            return 'CAREFUL'

        return 'OK'

    def __getColor(self, current=0, max=100):
        """
        Return colors for logged stats
        """
        return self.__colors_list[self.__getAlert(current, max)]

    def __getColor2(self, current=0, max=100):
        """
        Return colors for non logged stats
        """
        return self.__colors_list2[self.__getAlert(current, max)]

    def __getCpuAlert(self, current=0, max=100):
        return self.__getAlert(current, max)

    def __getCpuColor(self, current=0, max=100):
        return self.__getColor(current, max)

    def __getLoadAlert(self, current=0, core=1):
        # If current < CAREFUL*core of max then alert = OK
        # If current > CAREFUL*core of max then alert = CAREFUL
        # If current > WARNING*core of max then alert = WARNING
        # If current > CRITICAL*core of max then alert = CRITICAL

        if current > limits.getLOADCritical(core):
            return 'CRITICAL'
        elif current > limits.getLOADWarning(core):
            return 'WARNING'
        elif current > limits.getLOADCareful(core):
            return 'CAREFUL'

        return 'OK'

    def __getLoadColor(self, current=0, core=1):
        return self.__colors_list[self.__getLoadAlert(current, core)]

    def __getMemAlert(self, current=0, max=100):
        return self.__getAlert(current, max)

    def __getMemColor(self, current=0, max=100):
        return self.__getColor(current, max)

    def __getNetColor(self, current=0, max=100):
        return self.__getColor2(current, max)

    def __getFsColor(self, current=0, max=100):
        return self.__getColor2(current, max)

    def __getProcessColor(self, current=0, max=100):
        return self.__getColor2(current, max)

    def __catchKey(self):
        # Get key
        self.pressedkey = self.term_window.getch()

        # Actions...
        if (self.pressedkey == 27 or
            self.pressedkey == 113):
            # 'ESC'|'q' > Quit
            end()
        elif self.pressedkey == 97:
            # 'a' > Sort processes automatically
            self.setProcessSortedBy('auto')
        elif self.pressedkey == 99 and psutil_get_cpu_percent_tag:
            # 'c' > Sort processes by CPU usage
            self.setProcessSortedBy('cpu_percent')
        elif self.pressedkey == 100 and psutil_disk_io_tag:
            # 'd' > Show/hide disk I/O stats
            self.diskio_tag = not self.diskio_tag
        elif self.pressedkey == 102 and psutil_fs_usage_tag:
            # 'f' > Show/hide fs stats
            self.fs_tag = not self.fs_tag
        elif self.pressedkey == 104:
            # 'h' > Show/hide help
            self.help_tag = not self.help_tag
        elif self.pressedkey == 108:
            # 'l' > Show/hide log messages
            self.log_tag = not self.log_tag
        elif self.pressedkey == 109:
            # 'm' > Sort processes by MEM usage
            self.setProcessSortedBy('mem_percent')
        elif self.pressedkey == 110 and psutil_network_io_tag:
            # 'n' > Show/hide network stats
            self.network_tag = not self.network_tag
        elif self.pressedkey == 112:
            # 'p' > Sort processes by name
            self.setProcessSortedBy('proc_name')

        # Return the key code
        return self.pressedkey

    def end(self):
        # Shutdown the curses window
        curses.echo()
        curses.nocbreak()
        curses.curs_set(1)
        curses.endwin()

    def display(self, stats):
        # Display stats
        self.displaySystem(stats.getHost(), stats.getSystem())
        self.displayCpu(stats.getCpu())
        self.displayLoad(stats.getLoad(), stats.getCore())
        self.displayMem(stats.getMem(), stats.getMemSwap())
        network_count = self.displayNetwork(stats.getNetwork())
        diskio_count = self.displayDiskIO(stats.getDiskIO(),
                                          self.network_y + network_count)
        fs_count = self.displayFs(stats.getFs(),
                                  self.network_y + network_count +
                                  diskio_count)
        log_count = self.displayLog(self.network_y + network_count +
                                    diskio_count + fs_count)
        self.displayProcess(stats.getProcessCount(),
                            stats.getProcessList(screen.getProcessSortedBy()),
                            log_count)
        self.displayCaption()
        self.displayNow(stats.getNow())
        self.displayHelp()

    def erase(self):
        # Erase the content of the screen
        self.term_window.erase()

    def flush(self, stats):
        # Flush display
        self.erase()
        self.display(stats)

    def update(self, stats):
        # flush display
        self.flush(stats)

        # Wait
        countdown = Timer(self.__refresh_time)
        while (not countdown.finished()):
            # Getkey
            if self.__catchKey() > -1:
                # flush display
                self.flush(stats)
            # Wait 100ms...
            curses.napms(100)

    def displaySystem(self, host, system):
        # System information
        if not host or not system:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.system_y and
            screen_x > self.system_x + 79):
            if host['os_name'] == "Linux":
                system_msg = _("{0} {1} with {2} {3} on {4}").format(
                    system['linux_distro'], system['platform'],
                    system['os_name'], system['os_version'],
                    host['hostname'])
            else:
                system_msg = _("{0} {1} {2} on {3}").format(
                    system['os_name'], system['os_version'],
                    system['platform'], host['hostname'])
            self.term_window.addnstr(self.system_y, self.system_x +
                                     int(screen_x / 2) - len(system_msg) / 2,
                                     system_msg, 80, curses.A_UNDERLINE)

    def displayCpu(self, cpu):
        # CPU %
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.cpu_y + 5 and
            screen_x > self.cpu_x + 18):
            self.term_window.addnstr(self.cpu_y, self.cpu_x, _("CPU"), 8,
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)

            if not cpu:
                self.term_window.addnstr(self.cpu_y + 1, self.cpu_x,
                                         _("Compute data..."), 15)
                return 0

            self.term_window.addnstr(self.cpu_y, self.cpu_x + 10,
                                     "%.1f%%" % (100 - cpu['idle']), 8)
            self.term_window.addnstr(self.cpu_y + 1, self.cpu_x, _("User:"), 8)
            self.term_window.addnstr(self.cpu_y + 2, self.cpu_x,
                                     _("Kernel:"), 8)
            self.term_window.addnstr(self.cpu_y + 3, self.cpu_x, _("Nice:"), 8)

            alert = self.__getCpuAlert(cpu['user'])
            logs.add(alert, "CPU user", cpu['user'])
            self.term_window.addnstr(self.cpu_y + 1, self.cpu_x + 10,
                                     "%.1f" % cpu['user'], 8,
                                     self.__colors_list[alert])

            alert = self.__getCpuAlert(cpu['kernel'])
            logs.add(alert, "CPU kernel", cpu['kernel'])
            self.term_window.addnstr(self.cpu_y + 2, self.cpu_x + 10,
                                     "%.1f" % cpu['kernel'], 8,
                                     self.__colors_list[alert])

            alert = self.__getCpuAlert(cpu['nice'])
            logs.add(alert, "CPU nice", cpu['nice'])
            self.term_window.addnstr(self.cpu_y + 3, self.cpu_x + 10,
                                     "%.1f" % cpu['nice'], 8,
                                     self.__colors_list[alert])

    def displayLoad(self, load, core):
        # Load %
        if not load:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.load_y + 5 and
            screen_x > self.load_x + 18):
            self.term_window.addnstr(self.load_y, self.load_x, _("Load"), 8,
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)
            self.term_window.addnstr(self.load_y, self.load_x + 10,
                                     str(core) + _("-Core"), 8)
            self.term_window.addnstr(self.load_y + 1, self.load_x,
                                     _("1 min:"), 8)
            self.term_window.addnstr(self.load_y + 2, self.load_x,
                                     _("5 min:"), 8)
            self.term_window.addnstr(self.load_y + 3, self.load_x,
                                     _("15 min:"), 8)

            self.term_window.addnstr(self.load_y + 1, self.load_x + 10,
                                     "{:.2f}".format(load['min1']), 8)

            alert = self.__getLoadAlert(load['min5'], core)
            logs.add(alert, "LOAD 5-min", load['min5'])
            self.term_window.addnstr(self.load_y + 2, self.load_x + 10,
                                     "{:.2f}".format(load['min5']), 8,
                                     self.__colors_list[alert])

            alert = self.__getLoadAlert(load['min15'], core)
            logs.add(alert, "LOAD 15-min", load['min15'])
            self.term_window.addnstr(self.load_y + 3, self.load_x + 10,
                                     "{:.2f}".format(load['min15']), 8,
                                     self.__colors_list[alert])

    def displayMem(self, mem, memswap):
        # MEM
        if not mem or not memswap:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.mem_y + 5 and
            screen_x > self.mem_x + 38):
            self.term_window.addnstr(self.mem_y, self.mem_x, _("Mem"), 8,
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)
            self.term_window.addnstr(self.mem_y + 1, self.mem_x,
                                     _("Total:"), 8)
            self.term_window.addnstr(self.mem_y + 2, self.mem_x, _("Used:"), 8)
            self.term_window.addnstr(self.mem_y + 3, self.mem_x, _("Free:"), 8)

            self.term_window.addnstr(self.mem_y, self.mem_x + 9,
                                     "{:.1%}".format(mem['percent'] / 100), 8)
            self.term_window.addnstr(self.mem_y + 1, self.mem_x + 9,
                                     self.__autoUnit(mem['total']), 8)
            self.term_window.addnstr(self.mem_y + 2, self.mem_x + 9,
                                     self.__autoUnit(mem['used']), 8)
            self.term_window.addnstr(self.mem_y + 3, self.mem_x + 9,
                                     self.__autoUnit(mem['free']), 8)

            # real memory usage
            real_used_phymem = mem['used'] - mem['cache']
            real_free_phymem = mem['free'] + mem['cache']
            alert = self.__getMemAlert(real_used_phymem, mem['total'])
            logs.add(alert, "MEM real", real_used_phymem)
            self.term_window.addnstr(
                self.mem_y + 2, self.mem_x + 15,
                "({0})".format(self.__autoUnit(real_used_phymem)), 8,
                self.__colors_list[alert])
            self.term_window.addnstr(
                self.mem_y + 3, self.mem_x + 15,
                "({0})".format(self.__autoUnit(real_free_phymem)), 8)

            # Swap
            self.term_window.addnstr(self.mem_y, self.mem_x + 25, _("Swap"), 8,
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)
            self.term_window.addnstr(self.mem_y + 1, self.mem_x + 25,
                                     _("Total:"), 8)
            self.term_window.addnstr(self.mem_y + 2, self.mem_x + 25,
                                     _("Used:"), 8)
            self.term_window.addnstr(self.mem_y + 3, self.mem_x + 25,
                                     _("Free:"), 8)

            self.term_window.addnstr(self.mem_y, self.mem_x + 34,
                                     "{:.1%}".format(memswap['percent'] / 100),
                                     8)
            alert = self.__getMemAlert(memswap['used'], memswap['total'])
            logs.add(alert, "MEM swap", memswap['used'])
            self.term_window.addnstr(self.mem_y + 1, self.mem_x + 34,
                                     self.__autoUnit(memswap['total']), 8)
            self.term_window.addnstr(self.mem_y + 2, self.mem_x + 34,
                                     self.__autoUnit(memswap['used']), 8,
                                     self.__colors_list[alert])
            self.term_window.addnstr(self.mem_y + 3, self.mem_x + 34,
                                     self.__autoUnit(memswap['free']), 8)

    def displayNetwork(self, network):
        """
        Display the network interface bitrate
        Return the number of interfaces
        """
        # Network interfaces bitrate
        if not self.network_tag:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.network_y + 3 and
            screen_x > self.network_x + 28):
            # Network interfaces bitrate
            self.term_window.addnstr(self.network_y, self.network_x,
                                     _("Network"), 8, self.title_color if
                                     self.hascolors else curses.A_UNDERLINE)
            self.term_window.addnstr(self.network_y, self.network_x + 10,
                                     _("Rx/ps"), 8)
            self.term_window.addnstr(self.network_y, self.network_x + 19,
                                     _("Tx/ps"), 8)

            # If there is no data to display...
            if not network:
                self.term_window.addnstr(self.network_y + 1, self.network_x,
                                         _("Compute data..."), 15)
                return 3

            # Adapt the maximum interface to the screen
            ret = 2
            net_num = min(screen_y - self.network_y - 3, len(network))
            for i in xrange(0, net_num):
                elapsed_time = max(1, self.__refresh_time)
                self.term_window.addnstr(
                    self.network_y + 1 + i, self.network_x,
                    network[i]['interface_name'] + ':', 8)
                self.term_window.addnstr(
                    self.network_y + 1 + i, self.network_x + 10,
                    self.__autoUnit(network[i]['rx'] / elapsed_time * 8) +
                    "b", 8)
                self.term_window.addnstr(
                    self.network_y + 1 + i, self.network_x + 19,
                    self.__autoUnit(network[i]['tx'] / elapsed_time * 8) +
                    "b", 8)
                ret = ret + 1
            return ret
        return 0

    def displayDiskIO(self, diskio, offset_y=0):
        # Disk input/output rate
        if not self.diskio_tag:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        self.diskio_y = offset_y
        if (screen_y > self.diskio_y + 3 and
            screen_x > self.diskio_x + 28):
            self.term_window.addnstr(self.diskio_y, self.diskio_x,
                                     _("Disk I/O"), 8,
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)
            self.term_window.addnstr(self.diskio_y, self.diskio_x + 10,
                                     _("In/ps"), 8)
            self.term_window.addnstr(self.diskio_y, self.diskio_x + 19,
                                     _("Out/ps"), 8)

            # If there is no data to display...
            if not diskio:
                self.term_window.addnstr(self.diskio_y + 1, self.diskio_x,
                                         _("Compute data..."), 15)
                return 3

            # Adapt the maximum disk to the screen
            disk = 0
            disk_num = min(screen_y - self.diskio_y - 3, len(diskio))
            for disk in xrange(0, disk_num):
                elapsed_time = max(1, self.__refresh_time)
                self.term_window.addnstr(
                    self.diskio_y + 1 + disk, self.diskio_x,
                    diskio[disk]['disk_name'] + ':', 8)
                self.term_window.addnstr(
                    self.diskio_y + 1 + disk, self.diskio_x + 10,
                    self.__autoUnit(
                        diskio[disk]['write_bytes'] / elapsed_time) +
                    "B", 8)
                self.term_window.addnstr(
                    self.diskio_y + 1 + disk, self.diskio_x + 19,
                    self.__autoUnit(
                        diskio[disk]['read_bytes'] / elapsed_time) +
                    "B", 8)
            return disk + 3
        return 0

    def displayFs(self, fs, offset_y=0):
        # Filesystem stats
        if not fs or not self.fs_tag:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        self.fs_y = offset_y
        if (screen_y > self.fs_y + 3 and
            screen_x > self.fs_x + 28):
            self.term_window.addnstr(self.fs_y, self.fs_x, _("Mount"), 8,
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)
            self.term_window.addnstr(self.fs_y, self.fs_x + 10, _("Total"), 8)
            self.term_window.addnstr(self.fs_y, self.fs_x + 19, _("Used"), 8)

            # Adapt the maximum disk to the screen
            mounted = 0
            fs_num = min(screen_y - self.fs_y - 3, len(fs))
            for mounted in xrange(0, fs_num):
                self.term_window.addnstr(
                    self.fs_y + 1 + mounted,
                    self.fs_x, fs[mounted]['mnt_point'], 8)
                self.term_window.addnstr(
                    self.fs_y + 1 + mounted,
                    self.fs_x + 10, self.__autoUnit(fs[mounted]['size']), 8)
                self.term_window.addnstr(
                    self.fs_y + 1 + mounted,
                    self.fs_x + 19, self.__autoUnit(fs[mounted]['used']), 8,
                    self.__getFsColor(fs[mounted]['used'],
                                      fs[mounted]['size']))
            return mounted + 3
        return 0

    def displayLog(self, offset_y=0):
        # Logs
        if logs.len() == 0 or not self.log_tag:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        self.log_y = offset_y
        if (screen_y > self.log_y + 3 and
            screen_x > self.log_x + 79):
            self.log_y = max(offset_y, screen_y - 3 -
                             min(offset_y - 3, screen_y - self.log_y,
                                 logs.len()))
            logtodisplay_count = min(screen_y - self.log_y - 3, logs.len())
            logmsg = _("WARNING|CRITICAL logs for CPU|LOAD|MEM")
            if (logtodisplay_count > 1):
                logmsg += (_(" (lasts ") + str(logtodisplay_count) +
                           _(" entries)"))
            else:
                logmsg += _(" (one entry)")
            self.term_window.addnstr(self.log_y, self.log_x, logmsg, 79,
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)

            # Adapt the maximum log to the screen
            logcount = 0
            log = logs.get()
            for logcount in xrange(0, logtodisplay_count):
                logmsg = "  " + str(datetime.fromtimestamp(log[logcount][0]))
                if (log[logcount][1] > 0):
                    logmark = ' '
                    logmsg += (" > " +
                               str(datetime.fromtimestamp(log[logcount][1])))
                else:
                    logmark = '~'
                    logmsg += " > " + "%19s" % "___________________"
                if log[logcount][3][:3] == "MEM":
                    logmsg += " {0} ({1}/{2}/{3})".format(
                        log[logcount][3],
                        self.__autoUnit(log[logcount][6]),
                        self.__autoUnit(log[logcount][5]),
                        self.__autoUnit(log[logcount][4]))
                else:
                    logmsg += " {0} ({1:.1f}/{2:.1f}/{3:.1f})".format(
                        log[logcount][3], log[logcount][6],
                        log[logcount][5], log[logcount][4])
                self.term_window.addnstr(self.log_y + 1 + logcount,
                                         self.log_x, logmsg, 79)
                self.term_window.addnstr(self.log_y + 1 + logcount,
                                         self.log_x, logmark, 1,
                                         self.__colors_list[log[logcount][2]])
            return logcount + 3
        return 0

    def displayProcess(self, processcount, processlist, log_count=0):
        # Process
        if not processcount:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        # If there is no network & diskio & fs stats
        # then increase process window
        if (not self.network_tag and
            not self.diskio_tag and
            not self.fs_tag):
            process_x = 0
        else:
            process_x = self.process_x
        # Display the process summary
        if (screen_y > self.process_y + 3 and
            screen_x > process_x + 48):
            # Processes sumary
            self.term_window.addnstr(self.process_y, process_x, _("Processes"),
                                     9, self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)
            other = (processcount['total'] -
                     stats.getProcessCount()['running'] -
                     stats.getProcessCount()['sleeping'])
            self.term_window.addnstr(
                self.process_y, process_x + 10,
                "{0}, {1} {2}, {3} {4}, {5} {6}".format(
                    str(processcount['total']),
                    str(processcount['running']),
                    _("running"),
                    str(processcount['sleeping']),
                    _("sleeping"),
                    str(other),
                    _("other")), 42)

        # Display the process detail
        tag_pid = False
        tag_uid = False
        tag_nice = False
        tag_status = False
        tag_proc_time = False
        if screen_x > process_x + 55:
            tag_pid = True
        if screen_x > process_x + 64:
            tag_uid = True
        if screen_x > process_x + 70:
            tag_nice = True
        if screen_x > process_x + 74:
            tag_status = True
        if screen_x > process_x + 77:
            tag_proc_time = True

        # Processes detail
        if (screen_y > self.process_y + 8 and
            screen_x > process_x + 49):
            # VMS
            self.term_window.addnstr(
                self.process_y + 2, process_x,
                _("VIRT"), 5)
            # RSS
            self.term_window.addnstr(
                self.process_y + 2, process_x + 7,
                _("RES"), 5)
            # CPU%
            self.term_window.addnstr(
                self.process_y + 2, process_x + 14,
                _("CPU%"), 5, curses.A_UNDERLINE
                if self.getProcessSortedBy() == 'cpu_percent' else 0)
            # MEM%
            self.term_window.addnstr(
                self.process_y + 2, process_x + 21,
                _("MEM%"), 5, curses.A_UNDERLINE
                if self.getProcessSortedBy() == 'mem_percent' else 0)
            process_name_x = 28
            # If screen space (X) is available then:
            # PID
            if tag_pid:
                self.term_window.addnstr(
                    self.process_y + 2, process_x + process_name_x,
                    _("PID"), 6)
                process_name_x += 7
            # UID
            if tag_uid:
                self.term_window.addnstr(
                    self.process_y + 2, process_x + process_name_x,
                    _("USER"), 8)
                process_name_x += 10
            # NICE
            if tag_nice:
                self.term_window.addnstr(
                    self.process_y + 2, process_x + process_name_x,
                    _("NI"), 3)
                process_name_x += 4
            # STATUS
            if tag_status:
                self.term_window.addnstr(
                    self.process_y + 2, process_x + process_name_x,
                    _("S"), 1)
                process_name_x += 3
            # TIME+
            if tag_proc_time:
                self.term_window.addnstr(
                    self.process_y + 2, process_x + process_name_x,
                    _("TIME+"), 8)
                process_name_x += 10
            # PROCESS NAME
            self.term_window.addnstr(
                self.process_y + 2, process_x + process_name_x,
                _("NAME"), 12, curses.A_UNDERLINE
                if self.getProcessSortedBy() == 'proc_name' else 0)

            # If there is no data to display...
            if not processlist:
                self.term_window.addnstr(self.process_y + 3, self.process_x,
                                         _("Compute data..."), 15)
                return 6

            proc_num = min(screen_y - self.term_h +
                           self.process_y - log_count + 5,
                           len(processlist))
            for processes in xrange(0, proc_num):
                # VMS
                process_size = processlist[processes]['proc_size']
                self.term_window.addnstr(
                    self.process_y + 3 + processes, process_x,
                    self.__autoUnit(process_size), 5)
                # RSS
                process_resident = processlist[processes]['proc_resident']
                self.term_window.addnstr(
                    self.process_y + 3 + processes, process_x + 7,
                    self.__autoUnit(process_resident), 5)
                # CPU%
                cpu_percent = processlist[processes]['cpu_percent']
                if psutil_get_cpu_percent_tag:
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 14,
                        "{:.1f}".format(cpu_percent), 5,
                        self.__getProcessColor(cpu_percent))
                else:
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x, "N/A", 8)
                # MEM%
                mem_percent = processlist[processes]['mem_percent']
                self.term_window.addnstr(
                    self.process_y + 3 + processes, process_x + 21,
                    "{:.1f}".format(mem_percent), 5,
                    self.__getProcessColor(mem_percent))
                # If screen space (X) is available then:
                # PID
                if tag_pid:
                    pid = processlist[processes]['pid']
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 28,
                        str(pid), 6)
                # UID
                if tag_uid:
                    uid = processlist[processes]['uid']
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 35,
                        str(uid), 8)
                # NICE
                if tag_nice:
                    nice = processlist[processes]['nice']
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 45,
                        str(nice), 3)
                # STATUS
                if tag_status:
                    status = processlist[processes]['status']
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 49,
                        str(status), 1)
                # TIME+
                if tag_proc_time:
                    process_time = processlist[processes]['proc_time']
                    dtime = timedelta(seconds=sum(process_time))
                    dtime = "{0}:{1}.{2}".format(
                                str(dtime.seconds // 60 % 60).zfill(2),
                                str(dtime.seconds % 60).zfill(2),
                                str(dtime.microseconds)[:2])
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 52,
                        dtime, 8)
                # display process command line
                max_process_name = screen_x - process_x - process_name_x
                process_name = processlist[processes]['proc_name']
                process_cmdline = processlist[processes]['proc_cmdline']
                if (len(process_cmdline) > max_process_name or
                    len(process_cmdline) == 0):
                    command = process_name
                else:
                    command = process_cmdline
                self.term_window.addnstr(self.process_y + 3 + processes,
                                         process_x + process_name_x,
                                         command, max_process_name)

    def displayCaption(self):
        # Caption
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        msg = _("Press 'h' for help")
        if (screen_y > self.caption_y and
            screen_x > self.caption_x + 32):
            self.term_window.addnstr(max(self.caption_y, screen_y - 1),
                                     self.caption_x, msg, self.default_color)

    def displayHelp(self):
        """
        Show the help panel
        """
        if not self.help_tag:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.help_y + 23 and
            screen_x > self.help_x + 79):
            # Console 80x24 is mandatory to display the help message
            self.erase()

            self.term_window.addnstr(
                self.help_y, self.help_x,
                _("Glances {0} with PsUtil {1}").format(
                    self.__version, psutil.__version__),
                79, self.title_color if self.hascolors else 0)

            self.term_window.addnstr(self.help_y + 2, self.help_x,
                                     _("Captions: "), 79)
            self.term_window.addnstr(self.help_y + 2, self.help_x + 10,
                                     _("   OK   "), 8, self.default_color)
            self.term_window.addnstr(self.help_y + 2, self.help_x + 18,
                                     _("CAREFUL "), 8, self.ifCAREFUL_color)
            self.term_window.addnstr(self.help_y + 2, self.help_x + 26,
                                     _("WARNING "), 8, self.ifWARNING_color)
            self.term_window.addnstr(self.help_y + 2, self.help_x + 34,
                                     _("CRITICAL"), 8, self.ifCRITICAL_color)

            width = 5
            self.term_window.addnstr(
                self.help_y + 4, self.help_x,
                "{0:^{width}} {1}".format(
                    _("Key"), _("Function"), width=width),
                79, self.title_color if self.hascolors else 0)
            self.term_window.addnstr(
                self.help_y + 5, self.help_x,
                "{0:^{width}} {1}".format(
                    _("a"), _("Sort processes automatically "
                              "(need PsUtil 0.2.0+)"), width=width),
                79, self.ifCRITICAL_color2
                    if not psutil_get_cpu_percent_tag else 0)
            self.term_window.addnstr(
                self.help_y + 6, self.help_x,
                "{0:^{width}} {1}".format(
                    _("c"), _("Sort processes by CPU% "
                              "(need PsUtil 0.2.0+)"), width=width),
                79, self.ifCRITICAL_color2
                    if not psutil_get_cpu_percent_tag else 0)
            self.term_window.addnstr(
                self.help_y + 7, self.help_x,
                "{0:^{width}} {1}".format(
                    _("m"), _("Sort processes by MEM%"), width=width), 79)
            self.term_window.addnstr(
                self.help_y + 8, self.help_x,
                "{0:^{width}} {1}".format(
                    _("p"), _("Sort processes by name"), width=width), 79)
            self.term_window.addnstr(
                self.help_y + 9, self.help_x,
                "{0:^{width}} {1}".format(
                    _("d"), _("Show/hide disk I/O stats "
                              "(need PsUtil 0.4.0+)"), width=width),
                79, self.ifCRITICAL_color2 if not psutil_disk_io_tag else 0)
            self.term_window.addnstr(
                self.help_y + 10, self.help_x,
                "{0:^{width}} {1}".format(
                    _("f"), _("Show/hide file system stats "
                              "(need PsUtil 0.3.0+)"), width=width),
                79, self.ifCRITICAL_color2 if not psutil_fs_usage_tag else 0)
            self.term_window.addnstr(
                self.help_y + 11, self.help_x,
                "{0:^{width}} {1}".format(
                    _("n"), _("Show/hide network stats "
                              "(need PsUtil 0.3.0+)"), width=width),
                79, self.ifCRITICAL_color2 if not psutil_network_io_tag else 0)
            self.term_window.addnstr(
                self.help_y + 12, self.help_x,
                "{0:^{width}} {1}".format(
                    _("l"), _("Show/hide log messages (only available "
                              "if display > 24 lines)"), width=width), 79)
            self.term_window.addnstr(
                self.help_y + 13, self.help_x,
                "{0:^{width}} {1}".format(
                    _("h"), _("Show/hide this help message"), width=width), 79)
            self.term_window.addnstr(
                self.help_y + 14, self.help_x,
                "{0:^{width}} {1}".format(
                    _("q"), _("Quit (Esc and Ctrl-C also work)"), width=width),
                79)

    def displayNow(self, now):
        # Display the current date and time (now...) - Center
        if not now:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.now_y and
            screen_x > self.now_x):
            now_msg = now.strftime(_("%Y-%m-%d %H:%M:%S"))
            self.term_window.addnstr(
                max(self.now_y, screen_y - 1),
                max(self.now_x, screen_x - 1) - len(now_msg),
                now_msg, len(now_msg))


class glancesHtml:
    """
    This class manages the HTML output
    """

    def __init__(self, htmlfolder="/usr/share", refresh_time=1):
        # Global information to display

        # Init refresh time
        self.__refresh_time = refresh_time

        # Set the templates path
        environment = jinja2.Environment(
            loader=jinja2.FileSystemLoader(htmlfolder + '/html'),
            extensions=['jinja2.ext.loopcontrols'])

        # Open the template
        self.template = environment.get_template('default.html')

        # Define the colors list (hash table) for logged stats
        self.__colors_list = {
            #         CAREFUL WARNING CRITICAL
            'DEFAULT': "bgcdefault fgdefault",
            'OK': "bgcok fgok",
            'CAREFUL': "bgccareful fgcareful",
            'WARNING': "bgcwarning fgcwarning",
            'CRITICAL': "bgcritical fgcritical"
        }

    def __getAlert(self, current=0, max=100):
        # If current < CAREFUL of max then alert = OK
        # If current > CAREFUL of max then alert = CAREFUL
        # If current > WARNING of max then alert = WARNING
        # If current > CRITICAL of max then alert = CRITICAL
        try:
            (current * 100) / max
        except ZeroDivisionError:
            return 'DEFAULT'

        variable = (current * 100) / max

        if variable > limits.getSTDCritical():
            return 'CRITICAL'
        elif variable > limits.getSTDWarning():
            return 'WARNING'
        elif variable > limits.getSTDCareful():
            return 'CAREFUL'

        return 'OK'

    def __getColor(self, current=0, max=100):
        """
        Return colors for logged stats
        """
        return self.__colors_list[self.__getAlert(current, max)]

    def __getCpuColor(self, cpu, max=100):
        cpu['user_color'] = self.__getColor(cpu['user'], max)
        cpu['kernel_color'] = self.__getColor(cpu['kernel'], max)
        cpu['nice_color'] = self.__getColor(cpu['nice'], max)
        return cpu

    def __getLoadAlert(self, current=0, core=1):
        # If current < CAREFUL*core of max then alert = OK
        # If current > CAREFUL*core of max then alert = CAREFUL
        # If current > WARNING*core of max then alert = WARNING
        # If current > CRITICAL*core of max then alert = CRITICAL
        if current > limits.getLOADCritical(core):
            return 'CRITICAL'
        elif current > limits.getLOADWarning(core):
            return 'WARNING'
        elif current > limits.getLOADCareful(core):
            return 'CAREFUL'
        return 'OK'

    def __getLoadColor(self, load, core=1):
        load['min1_color'] = (
            self.__colors_list[self.__getLoadAlert(load['min1'], core)])
        load['min5_color'] = (
            self.__colors_list[self.__getLoadAlert(load['min5'], core)])
        load['min15_color'] = (
            self.__colors_list[self.__getLoadAlert(load['min15'], core)])
        return load

    def __getMemColor(self, mem):
        real_used_phymem = mem['used'] - mem['cache']
        mem['used_color'] = self.__getColor(real_used_phymem, mem['total'])

        return mem

    def __getMemSwapColor(self, memswap):
        memswap['used_color'] = self.__getColor(memswap['used'],
                                                memswap['total'])
        return memswap

    def __getFsColor(self, fs):
        mounted = 0
        for mounted in xrange(0, len(fs)):
            fs[mounted]['used_color'] = self.__getColor(fs[mounted]['used'],
                                                        fs[mounted]['size'])
        return fs

    def update(self, stats):
        if stats.getCpu():
            # Open the output file
            f = open('glances.html', 'w')

            # Process color

            # Render it
            # HTML Refresh is set to 1.5 * refresh_time
            # ... to avoid display while page rendering
            data = self.template.render(
                refresh=int(self.__refresh_time * 1.5),
                host=stats.getHost(),
                system=stats.getSystem(),
                cpu=self.__getCpuColor(stats.getCpu()),
                load=self.__getLoadColor(stats.getLoad(), stats.getCore()),
                core=stats.getCore(),
                mem=self.__getMemColor(stats.getMem()),
                memswap=self.__getMemSwapColor(stats.getMemSwap()),
                net=stats.getNetwork(),
                diskio=stats.getDiskIO(),
                fs=self.__getFsColor(stats.getFs()),
                proccount=stats.getProcessCount(),
                proclist=stats.getProcessList())

            # Write data into the file
            f.write(data)

            # Close the file
            f.close()


class glancesCsv:
    """
    This class manages the Csv output
    """

    def __init__(self, cvsfile="./glances.csv", refresh_time=1):
        # Global information to display

        # Init refresh time
        self.__refresh_time = refresh_time

        # Set the ouput (CSV) path
        try:
            self.__cvsfile_fd = open("%s" % cvsfile, "wb")
            self.__csvfile = csv.writer(self.__cvsfile_fd)
        except IOError, error:
            print "Can not create the output CSV file: ", error[1]
            sys.exit(0)

    def exit(self):
        self.__cvsfile_fd.close()

    def update(self, stats):
        if stats.getCpu():
            # Update CSV with the CPU stats
            cpu = stats.getCpu()
            self.__csvfile.writerow(["cpu", cpu['user'], cpu['kernel'],
                                     cpu['nice']])
        if stats.getLoad():
            # Update CSV with the LOAD stats
            load = stats.getLoad()
            self.__csvfile.writerow(["load", load['min1'], load['min5'],
                                     load['min15']])
        if (stats.getMem() and
            stats.getMemSwap()):
            # Update CSV with the MEM stats
            mem = stats.getMem()
            self.__csvfile.writerow(["mem", mem['total'], mem['used'],
                                     mem['free']])
            memswap = stats.getMemSwap()
            self.__csvfile.writerow(["swap", memswap['total'], memswap['used'],
                                     memswap['free']])
        self.__cvsfile_fd.flush()

# Global def
#===========


def printVersion():
    print _("Glances version ") + __version__


def printSyntax():
    printVersion()
    print _("Usage: glances [-f file] [-o output] [-t sec] [-h] [-v]")
    print ""
    print _("\t-d\t\tDisable disk I/O module")
    print _("\t-f file\t\tSet the output folder (HTML) or file (CSV)")
    print _("\t-h\t\tDisplay the syntax and exit")
    print _("\t-m\t\tDisable mount module")
    print _("\t-n\t\tDisable network module")
    print _("\t-o output\tDefine additional output (available: HTML or CSV)")
    print _("\t-t sec\t\tSet the refresh time in seconds (default: %d)" %
            refresh_time)
    print _("\t-v\t\tDisplay the version and exit")


def init():
    global psutil_disk_io_tag, psutil_fs_usage_tag, psutil_network_io_tag
    global limits, logs, stats, screen
    global htmloutput, csvoutput
    global html_tag, csv_tag
    global refresh_time

    # Set default tags
    html_tag = False
    csv_tag = False

    # Set the default refresh time
    refresh_time = 2

    # Manage args
    try:
        opts, args = getopt.getopt(sys.argv[1:], "dmnho:f:t:v",
                                   ["help", "output", "file",
                                    "time", "version"])
    except getopt.GetoptError, err:
        # Print help information and exit:
        print str(err)
        printSyntax()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-v", "--version"):
            printVersion()
            sys.exit(0)
        elif opt in ("-o", "--output"):
            if arg == "html":
                if jinja_tag:
                    html_tag = True
                else:
                    print _("Error: Need Jinja2 library to export into HTML")
                    print
                    print _("Try to install the python-jinja2 package")
                    sys.exit(2)
            elif arg == "csv":
                if csvlib_tag:
                    csv_tag = True
                else:
                    print _("Error: Need CSV library to export to CSV")
                    sys.exit(2)
            else:
                print _("Error: Unknown output %s" % arg)
                sys.exit(2)
        elif opt in ("-f", "--file"):
            output_file = arg
            output_folder = arg
        elif opt in ("-t", "--time"):
            if int(arg) >= 1:
                refresh_time = int(arg)
            else:
                print _("Error: Refresh time should be a positive integer")
                sys.exit(2)
        elif opt in ("-d", "--diskio"):
            psutil_disk_io_tag = False
        elif opt in ("-m", "--mount"):
            psutil_fs_usage_tag = False
        elif opt in ("-n", "--netrate"):
            psutil_network_io_tag = False
        else:
            printSyntax()
            sys.exit(0)

    # Check options
    if html_tag:
        try:
            output_folder
        except UnboundLocalError:
            print _("Error: HTML export (-o html) need"
                    "output folder definition (-f <folder>)")
            sys.exit(2)

    if csv_tag:
        try:
            output_file
        except UnboundLocalError:
            print _("Error: CSV export (-o csv) need "
                    "output file definition (-f <file>)")
            sys.exit(2)

    # Catch CTRL-C
    signal.signal(signal.SIGINT, signal_handler)

    # Init Limits
    limits = glancesLimits()

    # Init Logs
    logs = glancesLogs()

    # Init stats
    stats = glancesStats()

    # Init HTML output
    if html_tag:
        htmloutput = glancesHtml(htmlfolder=output_folder,
                                 refresh_time=refresh_time)

    # Init CSV output
    if csv_tag:
        csvoutput = glancesCsv(cvsfile=output_file,
                               refresh_time=refresh_time)

    # Init screen
    screen = glancesScreen(refresh_time=refresh_time)


def main():
    # Init stuff
    init()

    # Main loop
    while True:
        # Get informations from libstatgrab and others...
        stats.update()

        # Update the screen
        screen.update(stats)

        # Update the HTML output
        if html_tag:
            htmloutput.update(stats)

        # Update the CSV output
        if csv_tag:
            csvoutput.update(stats)


def end():
    screen.end()

    if csv_tag:
        csvoutput.exit()

    sys.exit(0)


def signal_handler(signal, frame):
    end()

# Main
#=====

if __name__ == "__main__":
    main()

# The end...