Salome HOME
Remove the --grid option from the test command and replace it by the --base option
[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 def show_progress(logger, top, delai, ss=""):
26     """shortcut function to display the progression
27     
28     :param logger Logger: The logging instance
29     :param top int: the number to display
30     :param delai int: the number max
31     :param ss str: the string to display
32     """
33     logger.write("\r%s\r%s %s / %s " % ((" " * 30), ss, top, (delai - top)), 4,
34                  False)
35     logger.flush()
36
37 def write_back(logger, message, level):
38     """shortcut function to write at the begin of the line
39     
40     :param logger Logger: The logging instance
41     :param message str: the text to display
42     :param level int: the level of verbosity
43     """
44     logger.write("\r%s\r%s" % ((" " * 40), message), level)
45
46 # Launch command
47 # --------------
48 def launch_command(cmd, logger, cwd, args=[], log=None):
49     if log:
50         log = file(log, "a")
51     logger.write("launch: %s\n" % cmd, 5, screenOnly=True)
52     for arg in args:
53         cmd += " " + arg
54     prs = subprocess.Popen(cmd,
55                            shell=True,
56                            stdout=log,
57                            stderr=subprocess.STDOUT,
58                            cwd=cwd,
59                            executable='/bin/bash')
60     return prs
61
62 # Launch a batch
63 # --------------
64 def batch(cmd, logger, cwd, args=[], log=None, delai=20, sommeil=1):
65     proc = launch_command(cmd, logger, cwd, args, log)
66     top = 0
67     sys.stdout.softspace = True
68     begin = time.time()
69     while proc.poll() is None:
70         if time.time() - begin >= 1:
71             show_progress(logger, top, delai, "batch:")
72             if top == delai:
73                 logger.write("batch: time out KILL\n", 3)
74                 import signal
75                 os.kill(proc.pid, signal.SIGTERM)
76                 break
77             else:
78                 begin = time.time()
79                 time.sleep(sommeil)
80                 top += 1
81         sys.stdout.flush()
82     else:
83         write_back(logger, "batch: exit (%s)\n" % str(proc.returncode), 5)
84     return (proc.returncode == 0), top
85
86 # Launch a salome process
87 # -----------------------
88 def batch_salome(cmd, logger, cwd, args, getTmpDir,
89     pendant="SALOME_Session_Server", fin="killSalome.py",
90     log=None, delai=20, sommeil=1, delaiapp=0):
91
92     beginTime = time.time()
93     launch_command(cmd, logger, cwd, args, log)
94
95     if delaiapp == 0:
96         delaiapp = delai
97
98     # first launch salome (looking for .pidict file)
99     top = 0
100     found = False
101     tmp_dir = getTmpDir()
102     while (not found and top < delaiapp):
103         if os.path.exists(tmp_dir):
104             listFile = os.listdir(tmp_dir)
105         else:
106             listFile = []
107
108         for file_name in listFile:
109             if file_name.endswith("pidict"):
110                 # sometime we get a old file that will be removed by runSalome.
111                 # So we test that we can read it.
112                 currentTime = None
113                 try:
114                     statinfo = os.stat(os.path.join(tmp_dir, file_name))
115                     currentTime = statinfo.st_mtime
116                 except: pass
117
118                 if currentTime and currentTime > beginTime:
119                     try:
120                         file_ = open(os.path.join(tmp_dir, file_name), "r")
121                         process_ids = pickle.load(file_)
122                         file_.close()
123                         for process_id in process_ids:
124                             for __, cmd in process_id.items():
125                                 if cmd == [pendant]:
126                                     found = True
127                                     pidictFile = file_name
128                     except:
129                         file_.close()
130
131         time.sleep(sommeil)
132         top += 1
133         show_progress(logger, top, delaiapp, "launching salome or appli:")
134
135     # continue or not
136     if found:
137         write_back(logger, "batch_salome: started\n", 5)
138     else:
139         logger.write("batch_salome: FAILED to launch salome or appli\n", 3)
140         return False, -1
141
142     # salome launched run the script
143     top = 0
144     code = None
145     while code is None:
146         show_progress(logger, top, delai, "running salome or appli:")
147
148         if not os.access(os.path.join(tmp_dir, pidictFile), os.F_OK):
149             write_back(logger, "batch_salome: exit\n", 5)
150             code = True
151         elif top >= delai:
152             # timeout kill the test
153             os.system(fin)
154             logger.write("batch_salome: time out KILL\n", 3)
155             code = False
156         else:
157             # still waiting
158             time.sleep(sommeil)
159             top = top + 1
160
161     return code, top