Salome HOME
Merge branch 'hydro/imps_2015' of https://git.salome-platform.org/gitpub/modules...
[modules/gui.git] / src / PVServerService / ENGINE / PVSERVER_impl.py
1 # Copyright (C) 2007-2015  CEA/DEN, EDF R&D
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19 # Author : Adrien Bruneton (CEA)
20 #
21
22 import subprocess as subp
23 import socket
24 from time import sleep
25 import os
26 from SALOME import SALOME_Exception
27 #from SALOME_utilities import MESSAGE
28
29 def MESSAGE(m):
30     """ Debug function """
31     pass
32     #os.system("echo \"%s\" >> /tmp/paravis_log.txt" % m)
33
34 class PVSERVER_impl(object):
35     """ The core implementation (non CORBA, or Study related).
36         See the IDL for the documentation.
37     """
38     MAX_PVSERVER_PORT_TRIES = 1000  # Maximum number of tries to get a free port for the PVServer
39     PVSERVER_DEFAULT_PORT = 11111   # First port being tried to launch the pvserver
40     
41     def __init__(self):
42         self.pvserverPort = -1
43         self.pvserverPop = None  # Popen object from subprocess module
44         self.isGUIConnected = False  # whether there is an active connection from the GUI.
45         try:
46             import paraview
47             tmp=paraview.__file__
48         except:
49             raise Exception("PVSERVER_Impl.__init__ : \"import paraview\" failed !")
50         # deduce dynamically PARAVIEW_ROOT_DIR from the paraview module location
51         self.PARAVIEW_ROOT_DIR = None
52         ZE_KEY_TO_FIND_PV_ROOT_DIR="lib"
53         li=tmp.split(os.path.sep) ; li.reverse()
54         if ZE_KEY_TO_FIND_PV_ROOT_DIR not in li:
55             raise SALOME_Exception(SALOME.ExceptionStruct(SALOME.INTERNAL_ERROR,
56                       "PVSERVER_Impl.__init__ : error during dynamic deduction of PARAVIEW_ROOT_DIR : Loc of paraview module is \"%s\" ! \"%s\" is supposed to be the key to deduce it !"%(tmp,ZE_KEY_TO_FIND_PV_ROOT_DIR),
57                       "PVSERVER.py", 0))
58         li=li[li.index("lib")+1:] ; li.reverse()
59         self.PARAVIEW_ROOT_DIR = os.path.sep.join(li)
60
61     """
62     Private. Identify a free port to launch the PVServer. 
63     This is done by trying to bind a socket on the port.
64     We are still subject to a race condition between this detection mechanism and the actual launch of the pvserver
65     itself ...
66     """
67     def __getFreePort(self, startPort):
68         cnt = 0
69         currPort = startPort
70         while cnt < self.MAX_PVSERVER_PORT_TRIES:
71             try:
72                 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
73                 s.bind(('', currPort))
74                 s.close()
75                 return currPort
76             except socket.error as e:
77                 cnt += 1
78                 currPort += 1
79                 pass
80         raise SALOME_Exception(SALOME.ExceptionStruct(SALOME.INTERNAL_ERROR,
81                             "[PVSERVER] maximum number of tries to retrieve a free port for the PVServer",
82                             "PVSERVER.py", 0))
83                                            
84     def FindOrStartPVServer( self, port ):
85         MESSAGE("[PVSERVER] FindOrStartPVServer ...")
86         host = "localhost"
87         alive = True
88         if self.pvserverPop is None:
89             alive = False
90         else:
91             # Poll active server to check if still alive
92             self.pvserverPop.poll()
93             if not self.pvserverPop.returncode is None:  # server terminated
94                 alive = False
95         
96         if alive:
97             return "cs://%s:%d" % (host, self.pvserverPort)  
98           
99         # (else) Server not alive, start it:
100         pvServerPath = os.path.join(self.PARAVIEW_ROOT_DIR, 'bin', 'pvserver')
101         opt = []
102         if port <= 0:
103             port = self.__getFreePort(self.PVSERVER_DEFAULT_PORT)
104         self.pvserverPop = subp.Popen([pvServerPath, "--multi-clients", "--server-port=%d" % port, "--use-offscreen-rendering"])
105         sleep(3)  # Give some time to the server to start up to avoid 
106                   # ugly messages on the client side saying that it cannot connect
107         # Is PID still alive? If yes, consider that the launch was successful
108         self.pvserverPop.poll()
109         if self.pvserverPop.returncode is None:
110             success = True
111             self.pvserverPort = port
112             MESSAGE("[PVSERVER] pvserver successfully launched on port %d" % port)
113         else:
114             raise SALOME_Exception(SALOME.ExceptionStruct(SALOME.INTERNAL_ERROR,
115                             "[PVSERVER] Unable to start PVServer on port %d!" % port,
116                             "PVSERVER.py", 0))
117         return "cs://%s:%d" % (host, self.pvserverPort)
118
119     def StopPVServer( self ):
120         MESSAGE("[PVSERVER] Trying to stop PVServer (sending KILL) ...")
121         if not self.pvserverPop is None:
122             self.pvserverPop.poll()
123             if self.pvserverPop.returncode is None:
124                 # Terminate if still running:
125                 self.pvserverPop.terminate()
126                 MESSAGE("[PVSERVER] KILL signal sent.")
127                 return True
128         MESSAGE("[PVSERVER] Nothing to kill.")
129         return False
130       
131     def SetGUIConnected( self, isConnected ):
132         self.isGUIConnected = isConnected
133         
134     def GetGUIConnected( self ):
135         return self.isGUIConnected
136
137
138