Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkpoint and restore the heap in Ruby

Ruby's callcc captures the current continuation, which can be subsequently called to restore the control, but not the data. I would like to capture the current continuation along with the current image of the memory.

It seems to me that capturing the heap shouldn't be very difficult; I can rely on ObjectSpace::each_object and ObjectSpace::dump_all, or Marshal.dump, or simply Object.clone. However, I don't see any straightforward way to restore the heap. Ideally, I would like to traverse the object_id -> object map, restoring the old image of the object for every object_id (and re-adding the object_id if the corresponding object had been GC'd). Unsurprisingly, there is no Ruby-level api that lets me do this. I am wondering if there are any low-level hooks to Ruby's GC that I can use.

Any help is appreciated, including suggestions about alternative approaches.

like image 370
Gowtham Kaki Avatar asked Feb 06 '16 16:02

Gowtham Kaki


1 Answers

To answer my own question, Process.fork can be used to more-or-less achieve the effect of heap checkpointing and restoration. Whenever I have to checkpoint the heap, I fork a new process and let the child continue. The parent process now contains the checkpointed heap:

def checkpoint
  if Process.fork.nil? then # if child, then resume execution immediately
    return
  else # if parent, wait for the child to exit.
    Process.wait 
  end
  return # Parent now resumes execution from state it was in before forking.  
end

When state has to be restored, child process simply exits:

def restore
  Process.exit
end

I am currently using this solution, and haven't encountered any problems so far. I will edit this answer if I find any in the future.

like image 52
Gowtham Kaki Avatar answered Nov 15 '22 03:11

Gowtham Kaki