Salome HOME
0023671: [CEA 13012] Cannot import Paraview simple (pvsimple)
[modules/gui.git] / src / PVServerService / ENGINE / PVSERVER_impl.py
1 # Copyright (C) 2015-2016  CEA/DEN, EDF R&D, OPEN CASCADE
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 import sys
27 from SALOME import SALOME_Exception, ExceptionStruct, INTERNAL_ERROR
28 #from SALOME_utilities import MESSAGE
29
30 def MESSAGE(m):
31     """ Debug function """
32     pass
33     #os.system("echo \"%s\" >> /tmp/paravis_log.txt" % m)
34
35 class PVSERVER_impl(object):
36     """ The core implementation (non CORBA, or Study related).
37         See the IDL for the documentation.
38     """
39     MAX_PVSERVER_PORT_TRIES = 1000  # Maximum number of tries to get a free port for the PVServer
40     PVSERVER_DEFAULT_PORT = 11111   # First port being tried to launch the pvserver
41     
42     def __init__(self):
43         self.pvserverPort = -1
44         self.pvserverPop = None  # Popen object from subprocess module
45         self.isGUIConnected = False  # whether there is an active connection from the GUI.
46         try:
47             import paraview
48             tmp=paraview.__file__
49         except:
50             raise Exception("PVSERVER_Impl.__init__ : \"import paraview\" failed !")
51         # deduce dynamically PARAVIEW_ROOT_DIR from the paraview module location
52         self.PARAVIEW_ROOT_DIR = None
53         if sys.platform == "win32":
54           ZE_KEY_TO_FIND_PV_ROOT_DIR="Lib"
55           upCount =2
56         else:
57           ZE_KEY_TO_FIND_PV_ROOT_DIR="lib"
58           upCount =1
59         tmp = os.path.sep.join(tmp.split('/'))
60         li=tmp.split(os.path.sep) ; li.reverse()
61         if ZE_KEY_TO_FIND_PV_ROOT_DIR not in li:
62             raise SALOME_Exception(ExceptionStruct(INTERNAL_ERROR,
63                       "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),
64                       "PVSERVER.py", 0))
65         li=li[li.index(ZE_KEY_TO_FIND_PV_ROOT_DIR)+upCount:] ; li.reverse()
66         self.PARAVIEW_ROOT_DIR = os.path.sep.join(li)
67
68     """
69     Private. Identify a free port to launch the PVServer. 
70     This is done by trying to bind a socket on the port.
71     We are still subject to a race condition between this detection mechanism and the actual launch of the pvserver
72     itself ...
73     """
74     def __getFreePort(self, startPort):
75         cnt = 0
76         currPort = startPort
77         while cnt < self.MAX_PVSERVER_PORT_TRIES:
78             try:
79                 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
80                 s.bind(('', currPort))
81                 s.close()
82                 return currPort
83             except socket.error as e:
84                 cnt += 1
85                 currPort += 1
86                 pass
87         raise SALOME_Exception(ExceptionStruct(INTERNAL_ERROR,
88                             "[PVSERVER] maximum number of tries to retrieve a free port for the PVServer",
89                             "PVSERVER.py", 0))
90                                            
91     def FindOrStartPVServer( self, port ):
92         MESSAGE("[PVSERVER] FindOrStartPVServer ...")
93         host = "localhost"
94         alive = True
95         if self.pvserverPop is None:
96             alive = False
97         else:
98             # Poll active server to check if still alive
99             self.pvserverPop.poll()
100             if not self.pvserverPop.returncode is None:  # server terminated
101                 alive = False
102         
103         if alive:
104             return "cs://%s:%d" % (host, self.pvserverPort)  
105           
106         # (else) Server not alive, start it:
107         pvServerPath = os.path.join(self.PARAVIEW_ROOT_DIR, 'bin', 'pvserver')
108         opt = []
109         if port <= 0:
110             port = self.__getFreePort(self.PVSERVER_DEFAULT_PORT)
111         self.pvserverPop = subp.Popen([pvServerPath, "--multi-clients", "--server-port=%d" % port, "--use-offscreen-rendering"])
112         sleep(3)  # Give some time to the server to start up to avoid 
113                   # ugly messages on the client side saying that it cannot connect
114         # Is PID still alive? If yes, consider that the launch was successful
115         self.pvserverPop.poll()
116         if self.pvserverPop.returncode is None:
117             success = True
118             self.pvserverPort = port
119             MESSAGE("[PVSERVER] pvserver successfully launched on port %d" % port)
120         else:
121             raise SALOME_Exception(ExceptionStruct(INTERNAL_ERROR,
122                             "[PVSERVER] Unable to start PVServer on port %d!" % port,
123                             "PVSERVER.py", 0))
124         return "cs://%s:%d" % (host, self.pvserverPort)
125
126     def StopPVServer( self ):
127         MESSAGE("[PVSERVER] Trying to stop PVServer (sending KILL) ...")
128         if not self.pvserverPop is None:
129             self.pvserverPop.poll()
130             if self.pvserverPop.returncode is None:
131                 # Terminate if still running:
132                 self.pvserverPop.terminate()
133                 MESSAGE("[PVSERVER] KILL signal sent.")
134                 return True
135         MESSAGE("[PVSERVER] Nothing to kill.")
136         return False
137       
138     def SetGUIConnected( self, isConnected ):
139         self.isGUIConnected = isConnected
140         
141     def GetGUIConnected( self ):
142         return self.isGUIConnected
143
144
145