Experimental-ish rollback functionality
[oweals/minetest.git] / src / rollback.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2012 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program 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
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "rollback.h"
21 #include <fstream>
22 #include <list>
23 #include <sstream>
24 #include "log.h"
25 #include "mapnode.h"
26 #include "gamedef.h"
27 #include "nodedef.h"
28 #include "util/serialize.h"
29 #include "util/string.h"
30 #include "strfnd.h"
31 #include "inventorymanager.h" // deserializing InventoryLocations
32
33 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
34
35 class RollbackManager: public IRollbackManager
36 {
37 public:
38         // IRollbackManager interface
39
40         void reportAction(const RollbackAction &action_)
41         {
42                 // Ignore if not important
43                 if(!action_.isImportant(m_gamedef))
44                         return;
45                 RollbackAction action = action_;
46                 action.unix_time = time(0);
47                 action.actor = m_current_actor;
48                 infostream<<"RollbackManager::reportAction():"
49                                 <<" time="<<action.unix_time
50                                 <<" actor=\""<<action.actor<<"\""
51                                 <<" action="<<action.toString()
52                                 <<std::endl;
53                 addAction(action);
54         }
55         std::string getActor()
56         {
57                 return m_current_actor;
58         }
59         void setActor(const std::string &actor)
60         {
61                 m_current_actor = actor;
62         }
63         void flush()
64         {
65                 infostream<<"RollbackManager::flush()"<<std::endl;
66                 std::ofstream of(m_filepath.c_str(), std::ios::app);
67                 if(!of.good()){
68                         errorstream<<"RollbackManager::flush(): Could not open file "
69                                         <<"for appending: \""<<m_filepath<<"\""<<std::endl;
70                         return;
71                 }
72                 for(std::list<RollbackAction>::const_iterator
73                                 i = m_action_todisk_buffer.begin();
74                                 i != m_action_todisk_buffer.end(); i++)
75                 {
76                         // Do not save stuff that does not have an actor
77                         if(i->actor == "")
78                                 continue;
79                         of<<i->unix_time;
80                         of<<" ";
81                         of<<serializeJsonString(i->actor);
82                         of<<" ";
83                         std::string action_s = i->toString();
84                         of<<action_s<<std::endl;
85                 }
86                 m_action_todisk_buffer.clear();
87         }
88         
89         // Other
90
91         RollbackManager(const std::string &filepath, IGameDef *gamedef):
92                 m_filepath(filepath),
93                 m_gamedef(gamedef)
94         {
95                 infostream<<"RollbackManager::RollbackManager("<<filepath<<")"
96                                 <<std::endl;
97         }
98         ~RollbackManager()
99         {
100                 infostream<<"RollbackManager::~RollbackManager()"<<std::endl;
101                 flush();
102         }
103
104         void addAction(const RollbackAction &action)
105         {
106                 m_action_todisk_buffer.push_back(action);
107                 m_action_latest_buffer.push_back(action);
108
109                 // Flush to disk sometimes
110                 if(m_action_todisk_buffer.size() >= 100)
111                         flush();
112         }
113         
114         bool readFile(std::list<RollbackAction> &dst)
115         {
116                 // Load whole file to memory
117                 std::ifstream f(m_filepath.c_str(), std::ios::in);
118                 if(!f.good()){
119                         errorstream<<"RollbackManager::readFile(): Could not open "
120                                         <<"file for reading: \""<<m_filepath<<"\""<<std::endl;
121                         return false;
122                 }
123                 for(;;){
124                         if(f.eof() || !f.good())
125                                 break;
126                         std::string line;
127                         std::getline(f, line);
128                         line = trim(line);
129                         if(line == "")
130                                 continue;
131                         std::istringstream is(line);
132                         
133                         try{
134                                 std::string action_time_raw;
135                                 std::getline(is, action_time_raw, ' ');
136                                 std::string action_actor;
137                                 try{
138                                         action_actor = deSerializeJsonString(is);
139                                 }catch(SerializationError &e){
140                                         errorstream<<"RollbackManager: Error deserializing actor: "
141                                                         <<e.what()<<std::endl;
142                                         throw e;
143                                 }
144                                 RollbackAction action;
145                                 action.unix_time = stoi(action_time_raw);
146                                 action.actor = action_actor;
147                                 int c = is.get();
148                                 if(c != ' '){
149                                         is.putback(c);
150                                         throw SerializationError("readFile(): second ' ' not found");
151                                 }
152                                 action.fromStream(is);
153                                 /*infostream<<"RollbackManager::readFile(): Action from disk: "
154                                                 <<action.toString()<<std::endl;*/
155                                 dst.push_back(action);
156                         }
157                         catch(SerializationError &e){
158                                 errorstream<<"RollbackManager: Error on line: "<<line<<std::endl;
159                                 errorstream<<"RollbackManager: ^ error: "<<e.what()<<std::endl;
160                         }
161                 }
162                 return true;
163         }
164
165         std::list<RollbackAction> getEntriesSince(int first_time)
166         {
167                 infostream<<"RollbackManager::getEntriesSince("<<first_time<<")"<<std::endl;
168                 // Collect enough data to this buffer
169                 std::list<RollbackAction> action_buffer;
170                 // Use the latest buffer if it is long enough
171                 if(!m_action_latest_buffer.empty() &&
172                                 m_action_latest_buffer.begin()->unix_time <= first_time){
173                         action_buffer = m_action_latest_buffer;
174                 }
175                 else
176                 {
177                         // Save all remaining stuff
178                         flush();
179                         // Load whole file to memory
180                         bool good = readFile(action_buffer);
181                         if(!good){
182                                 errorstream<<"RollbackManager::getEntriesSince(): Failed to"
183                                                 <<" open file; using data in memory."<<std::endl;
184                                 action_buffer = m_action_latest_buffer;
185                         }
186                 }
187                 return action_buffer;
188         }
189         
190         std::string getLastNodeActor(v3s16 p, int range, int seconds,
191                         v3s16 *act_p, int *act_seconds)
192         {
193                 infostream<<"RollbackManager::getLastNodeActor("<<PP(p)
194                                 <<", "<<seconds<<")"<<std::endl;
195                 // Figure out time
196                 int cur_time = time(0);
197                 int first_time = cur_time - seconds;
198
199                 std::list<RollbackAction> action_buffer = getEntriesSince(first_time);
200                 
201                 std::list<RollbackAction> result;
202
203                 for(std::list<RollbackAction>::const_reverse_iterator
204                                 i = action_buffer.rbegin();
205                                 i != action_buffer.rend(); i++)
206                 {
207                         if(i->unix_time < first_time)
208                                 break;
209
210                         // Find position of action or continue
211                         v3s16 action_p;
212
213                         if(i->type == RollbackAction::TYPE_SET_NODE)
214                         {
215                                 action_p = i->p;
216                         }
217                         else if(i->type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK)
218                         {
219                                 InventoryLocation loc;
220                                 loc.deSerialize(i->inventory_location);
221                                 if(loc.type != InventoryLocation::NODEMETA)
222                                         continue;
223                                 action_p = loc.p;
224                         }
225                         else
226                                 continue;
227
228                         if(range == 0){
229                                 if(action_p != p)
230                                         continue;
231                         } else {
232                                 if(abs(action_p.X - p.X) > range ||
233                                                 abs(action_p.Y - p.Y) > range ||
234                                                 abs(action_p.Z - p.Z) > range)
235                                         continue;
236                         }
237                         
238                         if(act_p)
239                                 *act_p = action_p;
240                         if(act_seconds)
241                                 *act_seconds = cur_time - i->unix_time;
242                         return i->actor;
243                 }
244                 return "";
245         }
246
247         std::list<RollbackAction> getRevertActions(const std::string &actor_filter,
248                         int seconds)
249         {
250                 infostream<<"RollbackManager::getRevertActions("<<actor_filter
251                                 <<", "<<seconds<<")"<<std::endl;
252                 // Figure out time
253                 int cur_time = time(0);
254                 int first_time = cur_time - seconds;
255                 
256                 std::list<RollbackAction> action_buffer = getEntriesSince(first_time);
257                 
258                 std::list<RollbackAction> result;
259
260                 for(std::list<RollbackAction>::const_reverse_iterator
261                                 i = action_buffer.rbegin();
262                                 i != action_buffer.rend(); i++)
263                 {
264                         if(i->unix_time < first_time)
265                                 break;
266                         if(i->actor != actor_filter)
267                                 continue;
268                         const RollbackAction &action = *i;
269                         /*infostream<<"RollbackManager::revertAction(): Should revert"
270                                         <<" time="<<action.unix_time
271                                         <<" actor=\""<<action.actor<<"\""
272                                         <<" action="<<action.toString()
273                                         <<std::endl;*/
274                         result.push_back(action);
275                 }
276
277                 return result;
278         }
279
280 private:
281         std::string m_filepath;
282         IGameDef *m_gamedef;
283         std::string m_current_actor;
284         std::list<RollbackAction> m_action_todisk_buffer;
285         std::list<RollbackAction> m_action_latest_buffer;
286 };
287
288 IRollbackManager *createRollbackManager(const std::string &filepath, IGameDef *gamedef)
289 {
290         return new RollbackManager(filepath, gamedef);
291 }
292
293