Completed
Pull Request — master (#963)
by
unknown
01:02
created

main()   F

Complexity

Conditions 12

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 12
c 2
b 0
f 0
dl 0
loc 40
rs 2.7855

How to fix   Complexity   

Complexity

Complex classes like main() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2016 Nicolargo <[email protected]>
6
#
7
# Glances is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU Lesser General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# Glances is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
16
#
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
#
20
21
"""Init the Glances software."""
22
23
# Import system libs
24
import locale
25
import platform
26
import signal
27
import sys
28
29
# Global name
30
__appname__ = 'glances'
31
__version__ = '2.8_DEVELOP'
32
__author__ = 'Nicolas Hennion <[email protected]>'
33
__license__ = 'LGPL'
34
35
# Import psutil
36
try:
37
    from psutil import __version__ as psutil_version
38
except ImportError:
39
    print('PSutil library not found. Glances cannot start.')
40
    sys.exit(1)
41
42
# Import Glances libs
43
# Note: others Glances libs will be imported optionally
44
from glances.logger import logger
45
from glances.main import GlancesMain
46
from glances.globals import WINDOWS
47
48
# Check locale
49
try:
50
    locale.setlocale(locale.LC_ALL, '')
51
except locale.Error:
52
    print("Warning: Unable to set locale. Expect encoding problems.")
53
54
# Check Python version
55
if sys.version_info[:2] == (2, 6):
56
    import warnings
57
    warnings.warn('Python 2.6 support is dropped. Please switch to at '
58
                  'least Python 2.7/3.3+ or downgrade to Glances 2.6.2.')
59
if sys.version_info < (2, 7) or (3, 0) <= sys.version_info < (3, 3):
60
    print('Glances requires at least Python 2.7 or 3.3 to run.')
61
    sys.exit(1)
62
63
# Check PSutil version
64
psutil_min_version = (2, 0, 0)
65
psutil_version_info = tuple([int(num) for num in psutil_version.split('.')])
66
if psutil_version_info < psutil_min_version:
67
    print('PSutil 2.0 or higher is needed. Glances cannot start.')
68
    sys.exit(1)
69
70
71
def __signal_handler(signal, frame):
72
    """Callback for CTRL-C."""
73
    end()
74
75
76
def end():
77
    """Stop Glances."""
78
    if core.is_standalone():
79
        # Stop the standalone (CLI)
80
        standalone.end()
81
        logger.info("Stop Glances (with CTRL-C)")
82
    elif core.is_client():
83
        # Stop the client
84
        client.end()
85
        logger.info("Stop Glances client (with CTRL-C)")
86
    elif core.is_server():
87
        # Stop the server
88
        server.end()
89
        logger.info("Stop Glances server (with CTRL-C)")
90
    elif core.is_webserver():
91
        # Stop the Web server
92
        webserver.end()
93
        logger.info("Stop Glances web server(with CTRL-C)")
94
95
    # The end...
96
    sys.exit(0)
97
98
99
def start_standalone(config, args):
100
    """Start the standalone mode"""
101
    logger.info("Start standalone mode")
102
103
    # Share global var
104
    global standalone
105
106
    # Import the Glances standalone module
107
    from glances.standalone import GlancesStandalone
108
109
    # Init the standalone mode
110
    standalone = GlancesStandalone(config=config, args=args)
111
112
    # Start the standalone (CLI) loop
113
    standalone.serve_forever()
114
115
116
def start_clientbrowser(config, args):
117
    """Start the browser client mode"""
118
    logger.info("Start client mode (browser)")
119
120
    # Share global var
121
    global client
122
123
    # Import the Glances client browser module
124
    from glances.client_browser import GlancesClientBrowser
125
126
    # Init the client
127
    client = GlancesClientBrowser(config=config, args=args)
128
129
    # Start the client loop
130
    client.serve_forever()
131
132
    # Shutdown the client
133
    client.end()
134
135
136
def start_client(config, args):
137
    """Start the client mode"""
138
    logger.info("Start client mode")
139
140
    # Share global var
141
    global client
142
143
    # Import the Glances client browser module
144
    from glances.client import GlancesClient
145
146
    # Init the client
147
    client = GlancesClient(config=config, args=args)
148
149
    # Test if client and server are in the same major version
150
    if not client.login():
151
        logger.critical("The server version is not compatible with the client")
152
        sys.exit(2)
153
154
    # Start the client loop
155
    client.serve_forever()
156
157
    # Shutdown the client
158
    client.end()
159
160
161
def start_server(config, args):
162
    """Start the server mode"""
163
    logger.info("Start server mode")
164
165
    # Share global var
166
    global server
167
168
    # Import the Glances server module
169
    from glances.server import GlancesServer
170
171
    server = GlancesServer(cached_time=args.cached_time,
172
                           config=config,
173
                           args=args)
174
    print('Glances server is running on {}:{}'.format(args.bind_address, args.port))
175
176
    # Set the server login/password (if -P/--password tag)
177
    if args.password != "":
178
        server.add_user(args.username, args.password)
179
180
    # Start the server loop
181
    server.serve_forever()
182
183
    # Shutdown the server?
184
    server.server_close()
185
186
187
def start_webserver(config, args):
188
    """Start the Web server mode"""
189
    logger.info("Start web server mode")
190
191
    # Share global var
192
    global webserver
193
194
    # Import the Glances web server module
195
    from glances.webserver import GlancesWebServer
196
197
    # Init the web server mode
198
    webserver = GlancesWebServer(config=config, args=args)
199
200
    # Start the web server loop
201
    webserver.serve_forever()
202
203
204
def main():
205
    """Main entry point for Glances.
206
207
    Select the mode (standalone, client or server)
208
    Run it...
209
    """
210
    # Log Glances and PSutil version
211
    logger.info('Start Glances {}'.format(__version__))
212
    logger.info('{} {} and PSutil {} detected'.format(
213
        platform.python_implementation(),
214
        platform.python_version(),
215
        psutil_version))
216
217
    # Share global var
218
    global core
219
220
    # Create the Glances main instance
221
    core = GlancesMain()
222
    config = core.get_config()
223
    args = core.get_args()
224
225
    # Catch the CTRL-C signal
226
    signal.signal(signal.SIGINT, __signal_handler)
227
228
    # Glances can be ran in standalone, client or server mode
229
    if core.is_standalone() and not WINDOWS:
230
        start_standalone(config=config, args=args)
231
    elif core.is_client() and not WINDOWS:
232
        if core.is_client_browser():
233
            start_clientbrowser(config=config, args=args)
234
        else:
235
            start_client(config=config, args=args)
236
    elif core.is_server():
237
        start_server(config=config, args=args)
238
    elif core.is_webserver() or (core.is_standalone() and WINDOWS):
239
        # Web server mode replace the standalone mode on Windows OS
240
        # In this case, try to start the web browser mode automaticaly
241
        if core.is_standalone() and WINDOWS:
242
            args.open_web_browser = True
243
        start_webserver(config=config, args=args)
244