Salome HOME
spns #8471 : add Windows case to launch tests with the command 'sat test'
[tools/sat.git] / src / fork.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  CEA/DEN
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18
19 import os
20 import sys
21 import time
22 import pickle
23 import subprocess
24
25 # OP
26 import src
27
28 def show_progress(logger, top, delai, ss=""):
29     """shortcut function to display the progression
30     
31     :param logger Logger: The logging instance
32     :param top int: the number to display
33     :param delai int: the number max
34     :param ss str: the string to display
35     """
36     logger.write("\r%s\r%s %s / %s " % ((" " * 30), ss, top, (delai - top)), 4,
37                  False)
38     logger.flush()
39
40 def write_back(logger, message, level):
41     """shortcut function to write at the begin of the line
42     
43     :param logger Logger: The logging instance
44     :param message str: the text to display
45     :param level int: the level of verbosity
46     """
47     logger.write("\r%s\r%s" % ((" " * 40), message), level)
48
49 # Launch command
50 # --------------
51 def launch_command(cmd, logger, cwd, args=[], log=None):
52     if log:
53         log = file(log, "a")
54     logger.write("launch: %s\n" % cmd, 5, screenOnly=True)
55     for arg in args:
56         cmd += " " + arg
57
58     # OP Add Windows case
59     if src.architecture.is_windows():
60         prs = subprocess.Popen(cmd,
61                            shell=True,
62                            stdout=log,
63                            stderr=subprocess.STDOUT,
64                            cwd=cwd)
65         pass
66     else:
67         prs = subprocess.Popen(cmd,
68                            shell=True,
69                            stdout=log,
70                            stderr=subprocess.STDOUT,
71                            cwd=cwd,
72                            executable='/bin/bash')
73         pass
74     # END OP
75     return prs
76
77 # Launch a batch
78 # --------------
79 def batch(cmd, logger, cwd, args=[], log=None, delai=20, sommeil=1):
80     proc = launch_command(cmd, logger, cwd, args, log)
81     top = 0
82     sys.stdout.softspace = True
83     begin = time.time()
84     while proc.poll() is None:
85         if time.time() - begin >= 1:
86             show_progress(logger, top, delai, "batch:")
87             if top == delai:
88                 logger.write("batch: time out KILL\n", 3)
89                 import signal
90                 os.kill(proc.pid, signal.SIGTERM)
91                 break
92             else:
93                 begin = time.time()
94                 time.sleep(sommeil)
95                 top += 1
96         sys.stdout.flush()
97     else:
98         write_back(logger, "batch: exit (%s)\n" % str(proc.returncode), 5)
99     return (proc.returncode == 0), top
100
101 # Launch a salome process
102 # -----------------------
103 def batch_salome(cmd, logger, cwd, args, getTmpDir,
104     pendant="SALOME_Session_Server", fin="killSalome.py",
105     log=None, delai=20, sommeil=1, delaiapp=0):
106
107     beginTime = time.time()
108     launch_command(cmd, logger, cwd, args, log)
109
110     if delaiapp == 0:
111         delaiapp = delai
112
113     # first launch salome (looking for .pidict file)
114     top = 0
115     found = False
116     tmp_dir = getTmpDir()
117     while (not found and top < delaiapp):
118         if os.path.exists(tmp_dir):
119             listFile = os.listdir(tmp_dir)
120         else:
121             listFile = []
122
123         for file_name in listFile:
124             if file_name.endswith("pidict"):
125                 # sometime we get a old file that will be removed by runSalome.
126                 # So we test that we can read it.
127                 currentTime = None
128                 try:
129                     statinfo = os.stat(os.path.join(tmp_dir, file_name))
130                     currentTime = statinfo.st_mtime
131                 except: pass
132
133                 if currentTime and currentTime > beginTime:
134                     try:
135                         file_ = open(os.path.join(tmp_dir, file_name), "r")
136                         process_ids = pickle.load(file_)
137                         file_.close()
138                         for process_id in process_ids:
139                             for __, cmd in process_id.items():
140                                 if cmd == [pendant]:
141                                     found = True
142                                     pidictFile = file_name
143                     except:
144                         file_.close()
145
146         time.sleep(sommeil)
147         top += 1
148         show_progress(logger, top, delaiapp, "launching salome or appli:")
149
150     # continue or not
151     if found:
152         write_back(logger, "batch_salome: started\n", 5)
153     else:
154         logger.write("batch_salome: FAILED to launch salome or appli\n", 3)
155         return False, -1
156
157     # salome launched run the script
158     top = 0
159     code = None
160     while code is None:
161         show_progress(logger, top, delai, "running salome or appli:")
162
163         if not os.access(os.path.join(tmp_dir, pidictFile), os.F_OK):
164             write_back(logger, "batch_salome: exit\n", 5)
165             code = True
166         elif top >= delai:
167             # timeout kill the test
168             os.system(fin)
169             logger.write("batch_salome: time out KILL\n", 3)
170             code = False
171         else:
172             # still waiting
173             time.sleep(sommeil)
174             top = top + 1
175
176     return code, top