1"""Utility functions for killing the wrapper softly.
2
3Copyright (C) 2013, Joshua More and Michele Ceriotti
4
5This program is free software: you can redistribute it and/or modify
6it under the terms of the GNU General Public License as published by
7the Free Software Foundation, either version 3 of the License, or
8(at your option) any later version.
9
10This program is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with this program. If not, see <http.//www.gnu.org/licenses/>.
17
18
19Classes:
20   Softexit: Concise class to manage cleaning up in case of an emergency exit.
21"""
22
23import traceback, sys
24from ipi.utils.messages import verbosity, warning
25
26__all__ = ['Softexit', 'softexit']
27
28
29class Softexit(object):
30   """Class to deal with stopping a simulation half way through.
31
32   Holds the functions used to clean up a simulation that has been
33   stopped early, either because of a SIGTERM signal or because the
34   user has added an EXIT file to the directory in which it is
35   running. This will then properly shut down the socket interface,
36   and print out a RESTART file for the appropriate time step.
37
38   Attributes:
39      flist: A list of functions used to close down the socket
40         interface.
41   """
42
43   def __init__(self):
44      """Initializes SoftExit."""
45
46      self.flist = []
47
48   def register(self, func):
49      """Adds another function to flist.
50
51      Args:
52         func: The function to be added to flist.
53      """
54
55      self.flist.append(func)
56
57   def trigger(self, message=""):
58      """Halts the simulation.
59
60      Prints out a warning message, then runs all the exit functions in flist
61      before terminating the simulation.
62
63      Args:
64         message: The message to output to standard output.
65      """
66
67      if message != "":
68         warning("Soft exit has been requested with message: '" + message + "'. Cleaning up.", verbosity.low)
69      for f in self.flist:
70         f()
71      sys.exit()
72
73softexit = Softexit()
74