Monday, September 9, 2019

Pharo image shutdown after an OS signal

Sometimes you need to control how a worker image starts and stops right from the operative system. You my do it from the terminal but the really important use for this comes with automation and orchestration.
In airflowing, the Pharo worker images start and stop automatically and on command from the OS and in other to shutdown, the images use the technique I'm describing here.
To do thins you need 3 things:
  1. A VM process listening to the TERM signal
  2. A helper object to hold that VM process
  3. A reaction to handle that signal
The helper object usually instantiates on image start and holds a VM process running in the lowest priority. On start it will listen for the TERM signal:
Helper>>makeStopHook

    "Answers the process that hooks to the 
    OS signal that makes this worker to shutdown
    when the VM process receives a TERM signal from
    the OS."

    ^ [|semaphore|
        semaphore := OSProcess accessor forwardSigTerm.
        semaphore wait.
        self onTerminationSignal] 
            forkAt: Processor systemBackgroundPriority 
            named: 'Image TERM'.
Then you need to implement the reaction to handle that OS signal, and since you probably want a clean shutdown without preserving state, you can use:
Helper>>onTerminationSignal
    "The process for the VM of this image 
    has received a TERM signal from the OS.
    React accordingly"

    self log: 'That''s all folks. This worker is shutting down. Bye bye...' level:#messages.
    OSProcess accessor restoreSigTerm.
    SmalltalkImage current snapshot: false andQuit: true.
Bonus Here is what you do to stop the VM process on that image so you can do a clean exit on any services it might be providing:
Helper>>stopSignalProcesses
    self isOnUnixLikeOS ifFalse:[^nil].
    self log: 'Stopping stop hook...' level:#messages.
    stopHook ifNotNil: [|value|
            value := stopHook.
            stopHook := nil.
            OSProcess accessor restoreSigTerm.
            value].


No comments:

Post a Comment