source: ogAgent-Git/src/opengnsys/modules/server/OpenGnSys/__init__.py @ 1506c1b

browser-nuevodecorare-oglive-methodsexec-ogbrowserfix-urlfixes-winlgromero-filebeatlog-sess-lenmainmodulesnew-browserno-ptt-paramno-tlsogadmcliogadmclient-statusogagent-jobsogagent-macosogagentuser-sigtermogcore1oggitoggit-notlsogliveoglogoglog2override-moduleping1ping2ping3ping4py3-winpython3qndtestreport-progresssched-tasktlstls-againunification2unification3versionswindows-fixes
Last change on this file since 1506c1b was 11f7a07, 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: 8.1 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@author: Adolfo Gómez, dkmaster at dkmon dot com
30'''
31from __future__ import unicode_literals
32
33from opengnsys.workers import ServerWorker
34
35from opengnsys import REST, RESTError
36from opengnsys import operations
37from opengnsys.log import logger
38from opengnsys.scriptThread import ScriptExecutorThread
39
40import subprocess
41import threading
42import thread
43import os
44import platform
45import time
46
47# Error handler decorator.
48def catchBackgroundError(fnc):
49    def wrapper(*args, **kwargs):
50        this = args[0]
51        try:
52            fnc(*args, **kwargs)
53        except Exception as e:
54            this.REST.sendMessage('error?id={}'.format(kwargs.get('requestId', 'error')), {'error': '{}'.format(e)})
55    return wrapper
56
57class OpenGnSysWorker(ServerWorker):
58    name = 'opengnsys'
59    interface = None  # Binded interface for OpenGnsys
60    loggedin = False  #
61    locked = {}
62   
63    def onActivation(self):
64        self.cmd = None
65        # Ensure cfg has required configuration variables or an exception will be thrown
66       
67        self.REST = REST(self.service.config.get('opengnsys', 'remote'))
68       
69        # Get network interfaces
70        self.interface = list(operations.getNetworkInfo())[0]  # Get first network interface
71       
72        # Send an initialize message
73        #self.REST.sendMessage('initialize/{}/{}'.format(self.interface.mac, self.interface.ip))
74       
75        # Send an POST message
76        self.REST.sendMessage('ogagent/started', {'mac': self.interface.mac, 'ip': self.interface.ip})
77       
78    def onDeactivation(self):
79        #self.REST.sendMessage('deinitialize/{}/{}'.format(self.interface.mac, self.interface.ip))
80        logger.debug('onDeactivation')
81        self.REST.sendMessage('ogagent/stopped', {'mac': self.interface.mac, 'ip': self.interface.ip})
82   
83    # Processes message "doit" (sample)   
84    #def process_doit(self, path, getParams, postParams):
85    #   # Send a sample message to client
86    #   logger.debug('Processing doit')
87    #   self.sendClientMessage('doit', {'param1': 'test', 'param2': 'test2'})
88    #   return 'Processed message for {}, {}, {}'.format(path, getParams, postParams)
89   
90    def process_script(self, path, getParams, postParams):
91        '''
92        Processes an script execution (script is encoded in base64)
93        '''
94        logger.debug('Processing script request')
95        script = postParams.get('script')
96        if postParams.get('client', 'false') == 'false':
97            thr = ScriptExecutorThread(script=script.decode('base64'))
98            thr.start()
99        else:
100            self.sendScriptMessage(script)
101           
102        return 'ok'
103   
104    def processClientMessage(self, message, data):
105        logger.debug('Got OpenGnsys message from client: {}, data {}'.format(message, data))
106   
107    def process_client_doit(self, params):
108        self.REST.sendMessage('doit_done', params)
109   
110    def onLogin(self, user):
111        logger.debug('Received login for {}'.format(user))
112        self.loggedin = True
113        self.REST.sendMessage('ogagent/loggedin', {'ip': self.interface.ip, "user": user})
114       
115    def onLogout(self, user):
116        logger.debug('Received logout for {}'.format(user))
117        self.loggedin = False
118        self.REST.sendMessage('ogagent/loggedout', {'ip': self.interface.ip, "user": user})
119
120    def process_ogclient(self, path, getParams, postParams):
121        '''
122        This method can be overriden to provide your own message proccessor, or better you can
123        implement a method that is called exactly as "process_" + path[0] (module name has been removed from path array) and this default processMessage will invoke it
124        * Example:
125            Imagine this invocation url (no matter if GET or POST): http://example.com:9999/Sample/mazinger/Z
126            The HTTP Server will remove "Sample" from path, parse arguments and invoke this method as this:
127            module.processMessage(["mazinger","Z"], getParams, postParams)
128           
129            This method will process "mazinger", and look for a "self" method that is called "process_mazinger", and invoke it this way:
130               return self.process_mazinger(["Z"], getParams, postParams)
131               
132            In the case path is empty (that is, the path is composed only by the module name, like in "http://example.com/Sample", the "process" method
133            will be invoked directly
134           
135            The methods must return data that can be serialized to json (i.e. Ojects are not serializable to json, basic type are)
136        '''
137        if len(path) == 0:
138            return "ok"
139        try:
140            operation = getattr(self, 'ogclient_' + path[0])
141        except Exception:
142            raise Exception('Message processor for "{}" not found'.format(path[0]))
143       
144        return operation(path[1:], getParams, postParams)
145       
146    ###### EN PRUEBAS ######
147    def process_status(self, path, getParams, postParams):
148        '''
149        Returns client status.
150        '''
151        res = { 'status': '', 'loggedin': self.loggedin }
152        if platform.system() == 'Linux':        # GNU/Linux
153            # Check if it's OpenGnsys Client.
154            if os.path.exists('/scripts/oginit'):
155                # Check if OpenGnsys Client is busy.
156                if self.locked:
157                    res['status'] = 'BSY'
158                else:
159                    res['status'] = 'OPG'
160            else:
161                # Check if there is an active session.
162                res['status'] = 'LNX'
163        elif platform.system() == 'Windows':    # Windows
164            # Check if there is an active session.
165            res['status'] = 'WIN'
166        elif platform.system() == 'Darwin':     # Mac OS X  ??
167            res['status'] = 'OSX'
168        return res
169   
170    def process_reboot(self, path, getParams, postParams):
171        '''
172        Launches a system reboot operation.
173        '''
174        logger.debug('Received reboot operation')
175        def rebt():
176            operations.reboot()
177        threading.Thread(target=rebt).start()
178        return {'op': 'launched'}
179
180    def process_poweroff(self, path, getParams, postParams):
181        '''
182        Launches a system power off operation.
183        '''
184        logger.debug('Received poweroff operation')
185        def pwoff():
186            time.sleep(2)
187            operations.poweroff()
188        threading.Thread(target=pwoff).start()
189        return {'op': 'launched'}
190
191    def process_logoff(self, path, getParams, postParams):
192        '''
193        Closes user session.
194        '''
195        logger.debug('Received logoff operation')
196        self.sendClientMessage('logoff', {})
197        return 'Logoff operation was sended to client'
198
Note: See TracBrowser for help on using the repository browser.