source: admin/Sources/Clients/ogagent/src/opengnsys/linux/OGAgentService.py @ 1e8645b

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since 1e8645b was c3e7c06, checked in by ramon <ramongomez@…>, 9 years ago

#718: Integrar código fuente de agente OGAgent en rama de desarrollo.

git-svn-id: https://opengnsys.es/svn/branches/version1.1@4865 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100644
File size: 4.9 KB
Line 
1# -*- coding: utf-8 -*-
2#
3# Copyright (c) 2014 Virtual Cable S.L.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without modification,
7# are permitted provided that the following conditions are met:
8#
9#    * Redistributions of source code must retain the above copyright notice,
10#      this list of conditions and the following disclaimer.
11#    * Redistributions in binary form must reproduce the above copyright notice,
12#      this list of conditions and the following disclaimer in the documentation
13#      and/or other materials provided with the distribution.
14#    * Neither the name of Virtual Cable S.L. nor the names of its contributors
15#      may be used to endorse or promote products derived from this software
16#      without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29'''
30@author: Adolfo Gómez, dkmaster at dkmon dot com
31'''
32from __future__ import unicode_literals
33
34from opengnsys.service import CommonService
35from opengnsys.service import IPC_PORT
36from opengnsys import ipc
37
38from opengnsys.log import logger
39
40from opengnsys.linux.daemon import Daemon
41
42import sys
43import signal
44import json
45
46try:
47    from prctl import set_proctitle  # @UnresolvedImport
48except Exception:  # Platform may not include prctl, so in case it's not available, we let the "name" as is
49    def set_proctitle(_):
50        pass
51
52
53class OGAgentSvc(Daemon, CommonService):
54    def __init__(self, args=None):
55        Daemon.__init__(self, '/var/run/opengnsys-agent.pid')
56        CommonService.__init__(self)
57
58    def run(self):
59        logger.debug('** Running Daemon **')
60        set_proctitle('OGAgent')
61
62        self.initialize()
63
64        # Call modules initialization
65        # They are called in sequence, no threading is done at this point, so ensure modules onActivate always returns
66       
67
68        # *********************
69        # * Main Service loop *
70        # *********************
71        # Counter used to check ip changes only once every 10 seconds, for
72        # example
73        try:
74            while self.isAlive:
75                # In milliseconds, will break
76                self.doWait(1000)
77        except (KeyboardInterrupt, SystemExit) as e:
78            logger.error('Requested exit of main loop')
79        except Exception as e:
80            logger.exception()
81            logger.error('Caught exception on main loop: {}'.format(e))
82
83        self.terminate()
84
85        self.notifyStop()
86       
87    def signal_handler(self, signal, frame):
88        self.isAlive = False
89        sys.stderr.write("signal handler: {}".format(signal))
90
91
92def usage():
93    sys.stderr.write("usage: {} start|stop|restart|fg|login 'username'|logout 'username'|message 'module' 'message' 'json'\n".format(sys.argv[0]))
94    sys.exit(2)
95
96if __name__ == '__main__':
97    logger.setLevel('INFO')
98   
99    if len(sys.argv) == 5 and sys.argv[1] == 'message':
100        logger.debug('Running client opengnsys')
101        client = None
102        try:
103            client = ipc.ClientIPC(IPC_PORT)
104            client.sendMessage(sys.argv[2], sys.argv[3], json.loads(sys.argv[4]))
105            sys.exit(0)
106        except Exception as e:
107            logger.error(e)
108       
109
110    if len(sys.argv) == 3 and sys.argv[1] in ('login', 'logout'):
111        logger.debug('Running client opengnsys')
112        client = None
113        try:
114            client = ipc.ClientIPC(IPC_PORT)
115            if 'login' == sys.argv[1]:
116                client.sendLogin(sys.argv[2])
117                sys.exit(0)
118            elif 'logout' == sys.argv[1]:
119                client.sendLogout(sys.argv[2])
120                sys.exit(0)
121            else:
122                usage()
123        except Exception as e:
124            logger.error(e)
125    elif len(sys.argv) != 2:
126        usage()
127
128    logger.debug('Executing actor')
129    daemon = OGAgentSvc()
130   
131    signal.signal(signal.SIGTERM, daemon.signal_handler)
132    signal.signal(signal.SIGINT, daemon.signal_handler)
133
134    if len(sys.argv) == 2:
135        if 'start' == sys.argv[1]:
136            daemon.start()
137        elif 'stop' == sys.argv[1]:
138            daemon.stop()
139        elif 'restart' == sys.argv[1]:
140            daemon.restart()
141        elif 'fg' == sys.argv[1]:
142            daemon.run()
143        else:
144            usage()
145        sys.exit(0)
146    else:
147        usage()
Note: See TracBrowser for help on using the repository browser.