atomic.lua 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. -- atomic.lua
  2. -- Utilities for transaction-like handling of serialized state files
  3. -- Also for multiple files that must be synchronous, as advtrains currently requires.
  4. -- Managing files and backups
  5. -- ==========================
  6. --[[
  7. The plain scheme just overwrites the file in place. This however poses problems when we are interrupted right within
  8. the write, so we have incomplete data. So, the following scheme is applied:
  9. Unix:
  10. 1. writes to <filename>.new
  11. 2. moves <filename>.new to <filename>, clobbering previous file
  12. Windows:
  13. 1. writes to <filename>.new
  14. 2. delete <filename>
  15. 3. moves <filename>.new to <filename>
  16. We count a new version of the state as "committed" after stage 2.
  17. During loading, we apply the following order of precedence:
  18. 1. <filename>
  19. 2. <filename>.new (windows only, in case we were interrupted just before 3. when saving)
  20. All of these functions return either true on success or nil, error on error.
  21. ]]--
  22. local ser = serialize_lib.serialize
  23. local windows_mode = false
  24. -- == local functions ==
  25. local function save_atomic_move_file(filename)
  26. --2. if windows mode, delete main file
  27. if windows_mode then
  28. local delsucc, err = os.remove(filename)
  29. if not delsucc then
  30. serialize_lib.log_warn("Unable to delete old savefile '"..filename.."':")
  31. serialize_lib.log_warn(err)
  32. serialize_lib.log_info("Trying to replace the save file anyway now...")
  33. end
  34. end
  35. --3. move file
  36. local mvsucc, err = os.rename(filename..".new", filename)
  37. if not mvsucc then
  38. if minetest.settings:get_bool("serialize_lib_no_auto_windows_mode") or windows_mode then
  39. serialize_lib.log_error("Unable to replace save file '"..filename.."':")
  40. serialize_lib.log_error(err)
  41. return nil, err
  42. else
  43. -- enable windows mode and try again
  44. serialize_lib.log_info("Unable to replace save file '"..filename.."' by direct renaming:")
  45. serialize_lib.log_info(err)
  46. serialize_lib.log_info("Enabling Windows mode for atomic saving...")
  47. windows_mode = true
  48. return save_atomic_move_file(filename)
  49. end
  50. end
  51. return true
  52. end
  53. local function open_file_and_save_callback(callback, filename)
  54. local file, err = io.open(filename, "wb")
  55. if not file then
  56. error("Failed opening file '"..filename.."' for write:\n"..err)
  57. end
  58. callback(file)
  59. return true
  60. end
  61. local function open_file_and_load_callback(filename, callback)
  62. local file, err = io.open(filename, "rb")
  63. if not file then
  64. error("Failed opening file '"..filename.."' for read:\n"..err)
  65. end
  66. return callback(file)
  67. end
  68. -- == public functions ==
  69. -- Load a saved state (according to comment above)
  70. -- if 'callback' is nil: reads serialized table.
  71. -- returns the read table, or nil,err on error
  72. -- if 'callback' is a function (signature func(file_handle) ):
  73. -- Counterpart to save_atomic with function argument. Opens the file and calls callback on it.
  74. -- If the callback function throws an error, and strict loading is enabled, that error is propagated.
  75. -- The callback's first return value is returned by load_atomic
  76. function serialize_lib.load_atomic(filename, callback)
  77. local cbfunc = callback or ser.read_from_fd
  78. -- try <filename>
  79. local file, ret = io.open(filename, "rb")
  80. if file then
  81. -- read the file using the callback
  82. local success
  83. success, ret = pcall(cbfunc, file)
  84. if success then
  85. return ret
  86. end
  87. end
  88. if minetest.settings:get_bool("serialize_lib_strict_loading", true) then
  89. serialize_lib.save_lock = true
  90. error("Loading data from file '"..filename.."' failed:\n"
  91. ..ret.."\nDisable Strict Loading to ignore.")
  92. end
  93. serialize_lib.log_warn("Loading data from file '"..filename.."' failed, trying .new fallback:")
  94. serialize_lib.log_warn(ret)
  95. -- try <filename>.new
  96. file, ret = io.open(filename..".new", "rb")
  97. if file then
  98. -- read the file using the callback
  99. local success
  100. success, ret = pcall(cbfunc, file)
  101. if success then
  102. return ret
  103. end
  104. end
  105. serialize_lib.log_error("Unable to load data from '"..filename..".new':")
  106. serialize_lib.log_error(ret)
  107. serialize_lib.log_error("Note: This message is normal when the mod is loaded the first time on this world.")
  108. return nil, ret
  109. end
  110. -- Save a file atomically (as described above)
  111. -- 'data' is the data to be saved (when a callback is used, this can be nil)
  112. -- if 'callback' is nil:
  113. -- data must be a table, and is serialized into the file
  114. -- if 'callback' is a function (signature func(data, file_handle) ):
  115. -- Opens the file and calls callback on it. The 'data' argument is the data passed to save_atomic().
  116. -- If the callback function throws an error, and strict loading is enabled, that error is propagated.
  117. -- The callback's first return value is returned by load_atomic
  118. -- Important: the callback must close the file in all cases!
  119. function serialize_lib.save_atomic(data, filename, callback, config)
  120. if serialize_lib.save_lock then
  121. serialize_lib.log_warn("Instructed to save '"..filename.."', but save lock is active!")
  122. return nil
  123. end
  124. local cbfunc = callback or ser.write_to_fd
  125. local file, ret = io.open(filename..".new", "wb")
  126. if file then
  127. -- save the file using the callback
  128. local success
  129. success, ret = pcall(cbfunc, data, file)
  130. if success then
  131. return save_atomic_move_file(filename)
  132. end
  133. end
  134. serialize_lib.log_error("Unable to save data to '"..filename..".new':")
  135. serialize_lib.log_error(ret)
  136. return nil, ret
  137. end
  138. -- Saves multiple files synchronously. First writes all data to all <filename>.new files,
  139. -- then moves all files in quick succession to avoid inconsistent backups.
  140. -- parts_table is a table where the keys are used as part of the filename and the values
  141. -- are the respective data written to it.
  142. -- e.g. if parts_table={foo={...}, bar={...}}, then <filename_prefix>foo and <filename_prefix>bar are written out.
  143. -- if 'callbacks_table' is defined, it is consulted for callbacks the same way save_atomic does.
  144. -- example: if callbacks_table = {foo = func()...}, then the callback is used during writing of file 'foo' (but not for 'bar')
  145. -- Note however that you must at least insert a "true" in the parts_table if you don't use the data argument.
  146. -- Important: the callback must close the file in all cases!
  147. function serialize_lib.save_atomic_multiple(parts_table, filename_prefix, callbacks_table, config)
  148. if serialize_lib.save_lock then
  149. serialize_lib.log_warn("Instructed to save '"..filename_prefix.."' (multiple), but save lock is active!")
  150. return nil
  151. end
  152. for subfile, data in pairs(parts_table) do
  153. local filename = filename_prefix..subfile
  154. local cbfunc = ser.write_to_fd
  155. if callbacks_table and callbacks_table[subfile] then
  156. cbfunc = callbacks_table[subfile]
  157. end
  158. local success = false
  159. local file, ret = io.open(filename..".new", "wb")
  160. if file then
  161. -- save the file using the callback
  162. success, ret = pcall(cbfunc, data, file, config)
  163. end
  164. if not success then
  165. serialize_lib.log_error("Unable to save data to '"..filename..".new':")
  166. serialize_lib.log_error(ret)
  167. return nil, ret
  168. end
  169. end
  170. local first_error
  171. for file, _ in pairs(parts_table) do
  172. local filename = filename_prefix..file
  173. local succ, err = save_atomic_move_file(filename)
  174. if not succ and not first_error then
  175. first_error = err
  176. end
  177. end
  178. return not first_error, first_error -- either true,nil or nil,error
  179. end