File: Profiling.cpp

package info (click to toggle)
i2pd 2.58.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,612 kB
  • sloc: cpp: 59,663; makefile: 224; sh: 138
file content (422 lines) | stat: -rw-r--r-- 12,598 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/*
* Copyright (c) 2013-2025, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/

#include <sys/stat.h>
#include <unordered_map>
#include <list>
#include <thread>
#include <iomanip>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include "Base.h"
#include "FS.h"
#include "Log.h"
#include "Timestamp.h"
#include "NetDb.hpp"
#include "Profiling.h"

namespace i2p
{
namespace data
{
	static i2p::fs::HashedStorage g_ProfilesStorage("peerProfiles", "p", "profile-", "txt");
	static std::unordered_map<i2p::data::IdentHash, std::shared_ptr<RouterProfile> > g_Profiles;
	static std::mutex g_ProfilesMutex;
	static std::list<std::pair<i2p::data::IdentHash, std::function<void (std::shared_ptr<RouterProfile>)> > > g_PostponedUpdates;
	static std::mutex g_PostponedUpdatesMutex;
	
	RouterProfile::RouterProfile ():
		m_IsUpdated (false), m_LastDeclineTime (0), m_LastUnreachableTime (0),
		m_LastUpdateTime (i2p::util::GetSecondsSinceEpoch ()), m_LastAccessTime (0),
		m_LastPersistTime (0), m_NumTunnelsAgreed (0), m_NumTunnelsDeclined (0),
		m_NumTunnelsNonReplied (0),m_NumTimesTaken (0), m_NumTimesRejected (0),
		m_HasConnected (false), m_IsDuplicated (false)
	{
	}

	void RouterProfile::UpdateTime ()
	{
		m_LastUpdateTime = i2p::util::GetSecondsSinceEpoch ();
		m_IsUpdated = true;
	}

	void RouterProfile::Save (const IdentHash& identHash)
	{
		// fill sections
		boost::property_tree::ptree participation;
		participation.put (PEER_PROFILE_PARTICIPATION_AGREED, m_NumTunnelsAgreed);
		participation.put (PEER_PROFILE_PARTICIPATION_DECLINED, m_NumTunnelsDeclined);
		participation.put (PEER_PROFILE_PARTICIPATION_NON_REPLIED, m_NumTunnelsNonReplied);
		boost::property_tree::ptree usage;
		usage.put (PEER_PROFILE_USAGE_TAKEN, m_NumTimesTaken);
		usage.put (PEER_PROFILE_USAGE_REJECTED, m_NumTimesRejected);
		usage.put (PEER_PROFILE_USAGE_CONNECTED, m_HasConnected);
		if (m_IsDuplicated)
			usage.put (PEER_PROFILE_USAGE_DUPLICATED, true);
		// fill property tree
		boost::property_tree::ptree pt;
		pt.put (PEER_PROFILE_LAST_UPDATE_TIMESTAMP, m_LastUpdateTime);
		if (m_LastUnreachableTime)
			pt.put (PEER_PROFILE_LAST_UNREACHABLE_TIME, m_LastUnreachableTime);
		pt.put_child (PEER_PROFILE_SECTION_PARTICIPATION, participation);
		pt.put_child (PEER_PROFILE_SECTION_USAGE, usage);

		// save to file
		std::string ident = identHash.ToBase64 ();
		std::string path = g_ProfilesStorage.Path(ident);

		try {
			boost::property_tree::write_ini (path, pt);
		} catch (std::exception& ex) {
			/* boost exception verbose enough */
			LogPrint (eLogError, "Profiling: ", ex.what ());
		}
	}

	void RouterProfile::Load (const IdentHash& identHash)
	{
		m_IsUpdated = false;
		std::string ident = identHash.ToBase64 ();
		std::string path = g_ProfilesStorage.Path(ident);
		boost::property_tree::ptree pt;

		if (!i2p::fs::Exists(path))
		{
			LogPrint(eLogWarning, "Profiling: No profile yet for ", ident);
			return;
		}

		try
		{
			boost::property_tree::read_ini (path, pt);
		} catch (std::exception& ex)
		{
			/* boost exception verbose enough */
			LogPrint (eLogError, "Profiling: ", ex.what ());
			return;
		}

		try
		{
			auto ts = pt.get (PEER_PROFILE_LAST_UPDATE_TIMESTAMP, 0);
			if (ts)
				m_LastUpdateTime = ts;
			else	
			{	
				// try old lastupdatetime 
				auto ut = pt.get (PEER_PROFILE_LAST_UPDATE_TIME, "");
				if (ut.length () > 0)
				{	
					std::istringstream ss (ut); std::tm t;
					ss >> std::get_time(&t, "%Y-%b-%d %H:%M:%S");
					if (!ss.fail())
						m_LastUpdateTime = mktime (&t); // t is local time
				}	
			}	
			if (i2p::util::GetSecondsSinceEpoch () - m_LastUpdateTime < PEER_PROFILE_EXPIRATION_TIMEOUT)
			{
				m_LastUnreachableTime = pt.get (PEER_PROFILE_LAST_UNREACHABLE_TIME, 0);
				try
				{
					// read participations
					auto participations = pt.get_child (PEER_PROFILE_SECTION_PARTICIPATION);
					m_NumTunnelsAgreed = participations.get (PEER_PROFILE_PARTICIPATION_AGREED, 0);
					m_NumTunnelsDeclined = participations.get (PEER_PROFILE_PARTICIPATION_DECLINED, 0);
					m_NumTunnelsNonReplied = participations.get (PEER_PROFILE_PARTICIPATION_NON_REPLIED, 0);
				}
				catch (boost::property_tree::ptree_bad_path& ex)
				{
					LogPrint (eLogWarning, "Profiling: Missing section ", PEER_PROFILE_SECTION_PARTICIPATION, " in profile for ", ident);
				}
				try
				{
					// read usage
					auto usage = pt.get_child (PEER_PROFILE_SECTION_USAGE);
					m_NumTimesTaken = usage.get (PEER_PROFILE_USAGE_TAKEN, 0);
					m_NumTimesRejected = usage.get (PEER_PROFILE_USAGE_REJECTED, 0);
					m_HasConnected = usage.get (PEER_PROFILE_USAGE_CONNECTED, false);
					m_IsDuplicated = usage.get (PEER_PROFILE_USAGE_DUPLICATED, false);
				}
				catch (boost::property_tree::ptree_bad_path& ex)
				{
					LogPrint (eLogWarning, "Profiling: Missing section ", PEER_PROFILE_SECTION_USAGE, " in profile for ", ident);
				}
			}
			else
				*this = RouterProfile ();
		}
		catch (std::exception& ex)
		{
			LogPrint (eLogError, "Profiling: Can't read profile ", ident, " :", ex.what ());
		}
	}

	void RouterProfile::TunnelBuildResponse (uint8_t ret)
	{
		UpdateTime ();
		if (ret > 0)
		{
			m_NumTunnelsDeclined++;
			m_LastDeclineTime = i2p::util::GetSecondsSinceEpoch ();
		}
		else
		{
		    m_NumTunnelsAgreed++;
			m_LastDeclineTime = 0;
		}
	}

	void RouterProfile::TunnelNonReplied ()
	{
	    m_NumTunnelsNonReplied++;
		UpdateTime ();
		if (m_NumTunnelsNonReplied > 2*m_NumTunnelsAgreed && m_NumTunnelsNonReplied > 3)
		{
			m_LastDeclineTime = i2p::util::GetSecondsSinceEpoch ();
		}
	}

	void RouterProfile::Unreachable (bool unreachable)
	{
		m_LastUnreachableTime = unreachable ? i2p::util::GetSecondsSinceEpoch () : 0;
		UpdateTime ();
	}
		
	void RouterProfile::Connected ()
	{
		m_HasConnected = true;
		UpdateTime ();
	}

	void RouterProfile::Duplicated ()
	{
		m_IsDuplicated = true;
	}	
		
	bool RouterProfile::IsLowPartcipationRate () const
	{
		return 4*m_NumTunnelsAgreed < m_NumTunnelsDeclined; // < 20% rate
	}

	bool RouterProfile::IsLowReplyRate () const
	{
		auto total = m_NumTunnelsAgreed + m_NumTunnelsDeclined;
		return m_NumTunnelsNonReplied > 10*(total + 1);
	}

	bool RouterProfile::IsDeclinedRecently (uint64_t ts)
	{
		if (!m_LastDeclineTime) return false;
		if (ts > m_LastDeclineTime + PEER_PROFILE_DECLINED_RECENTLY_INTERVAL ||
		    ts + PEER_PROFILE_DECLINED_RECENTLY_INTERVAL < m_LastDeclineTime)
			m_LastDeclineTime = 0;
		return (bool)m_LastDeclineTime;
	}

	bool RouterProfile::IsBad ()
	{
		if (IsUnreachable () || m_IsDuplicated) return true;
		auto ts = i2p::util::GetSecondsSinceEpoch ();
		if (ts > PEER_PROFILE_MAX_DECLINED_INTERVAL + m_LastDeclineTime) return false;
		if (IsDeclinedRecently (ts)) return true; 
		auto isBad = IsAlwaysDeclining () || IsLowPartcipationRate () /*|| IsLowReplyRate ()*/;
		if (isBad && m_NumTimesRejected > 10*(m_NumTimesTaken + 1))
		{
			// reset profile
			m_NumTunnelsAgreed = 0;
			m_NumTunnelsDeclined = 0;
			m_NumTunnelsNonReplied = 0;
			isBad = false;
		}
		if (isBad) m_NumTimesRejected++; else m_NumTimesTaken++;
		return isBad;
	}

	bool RouterProfile::IsUnreachable ()
	{
		if (!m_LastUnreachableTime) return false;
		auto ts = i2p::util::GetSecondsSinceEpoch ();
		if (ts > m_LastUnreachableTime + PEER_PROFILE_UNREACHABLE_INTERVAL ||
		    ts + PEER_PROFILE_UNREACHABLE_INTERVAL < m_LastUnreachableTime)
			m_LastUnreachableTime = 0;
		return (bool)m_LastUnreachableTime;
	}

	bool RouterProfile::IsUseful() const 
	{
	    return IsReal () || m_NumTunnelsNonReplied >= PEER_PROFILE_USEFUL_THRESHOLD;
	}

	std::shared_ptr<RouterProfile> GetRouterProfile (const IdentHash& identHash)
	{
		{
			std::unique_lock<std::mutex> l(g_ProfilesMutex);
			auto it = g_Profiles.find (identHash);
			if (it != g_Profiles.end ())
			{
				it->second->SetLastAccessTime (i2p::util::GetSecondsSinceEpoch ());
				return it->second;
			}	
		}
		auto profile = netdb.NewRouterProfile ();
		profile->Load (identHash); // if possible
		std::lock_guard<std::mutex> l(g_ProfilesMutex);
		g_Profiles.emplace (identHash, profile);
		return profile;
	}

	bool IsRouterBanned (const IdentHash& identHash)
	{
		std::lock_guard<std::mutex> l(g_ProfilesMutex);
		auto it = g_Profiles.find (identHash);
		if (it != g_Profiles.end ())
			return it->second->IsUnreachable ();
		return false;
	}	

	bool IsRouterDuplicated (const IdentHash& identHash)
	{
		std::lock_guard<std::mutex> l(g_ProfilesMutex);
		auto it = g_Profiles.find (identHash);
		if (it != g_Profiles.end ())
			return it->second->IsDuplicated ();
		return false;
	}	
		
	void InitProfilesStorage ()
	{
		g_ProfilesStorage.SetPlace(i2p::fs::GetDataDir());
		g_ProfilesStorage.Init(i2p::data::GetBase64SubstitutionTable(), 64);
	}
		
	static void SaveProfilesToDisk (std::list<std::pair<i2p::data::IdentHash, std::shared_ptr<RouterProfile> > >&& profiles)
	{
		for (auto& it: profiles)
			if (it.second) it.second->Save (it.first);
	}	
		
	std::future<void> PersistProfiles ()
	{
		auto ts = i2p::util::GetSecondsSinceEpoch ();
		std::list<std::pair<i2p::data::IdentHash, std::shared_ptr<RouterProfile> > > tmp;
		{
			std::lock_guard<std::mutex> l(g_ProfilesMutex);
			for (auto it = g_Profiles.begin (); it != g_Profiles.end ();)
			{
				if (it->second->IsUpdated () && ts > it->second->GetLastPersistTime () + PEER_PROFILE_PERSIST_INTERVAL)
				{
					tmp.push_back (*it);
					it->second->SetLastPersistTime (ts);
					it->second->SetUpdated (false);
				}	
				if (!it->second->IsUpdated () && ts > std::max (it->second->GetLastUpdateTime (), it->second->GetLastAccessTime ()) + PEER_PROFILE_PERSIST_INTERVAL)
					it = g_Profiles.erase (it);
				else
					it++;
			}
		}
		if (!tmp.empty ())
			return std::async (std::launch::async, SaveProfilesToDisk, std::move (tmp));
		return std::future<void>();
	}

	void SaveProfiles ()
	{
		std::unordered_map<i2p::data::IdentHash, std::shared_ptr<RouterProfile> > tmp;
		{
			std::lock_guard<std::mutex> l(g_ProfilesMutex);
			std::swap (tmp, g_Profiles);
		}
		auto ts = i2p::util::GetSecondsSinceEpoch ();
		for (auto& it: tmp)
			if (it.second->IsUseful() && (it.second->IsUpdated () || ts - it.second->GetLastUpdateTime () < PEER_PROFILE_EXPIRATION_TIMEOUT))
				it.second->Save (it.first);
	}

	static void DeleteFilesFromDisk ()
	{
		std::vector<std::string> files;
		g_ProfilesStorage.Traverse(files);
		
		struct stat st;
		std::time_t now = std::time(nullptr);
		for (const auto& path: files) 
		{
			if (stat(path.c_str(), &st) != 0) 
			{	
				LogPrint(eLogWarning, "Profiling: Can't stat(): ", path);
				continue;
			}
			if (now - st.st_mtime >= PEER_PROFILE_EXPIRATION_TIMEOUT) 
			{
				LogPrint(eLogDebug, "Profiling: Removing expired peer profile: ", path);
				i2p::fs::Remove(path);
			}
		}
	}	
		
	std::future<void> DeleteObsoleteProfiles ()
	{
		{
			auto ts = i2p::util::GetSecondsSinceEpoch ();
			std::lock_guard<std::mutex> l(g_ProfilesMutex);
			for (auto it = g_Profiles.begin (); it != g_Profiles.end ();)
			{
				if (ts - it->second->GetLastUpdateTime () >= PEER_PROFILE_EXPIRATION_TIMEOUT)
					it = g_Profiles.erase (it);
				else
					it++;
			}
		}

		return std::async (std::launch::async, DeleteFilesFromDisk);
	}

	bool UpdateRouterProfile (const IdentHash& identHash, std::function<void (std::shared_ptr<RouterProfile>)> update)
	{
		if (!update) return true;
		std::shared_ptr<RouterProfile> profile;
		{
			std::lock_guard<std::mutex> l(g_ProfilesMutex);
			auto it = g_Profiles.find (identHash);
			if (it != g_Profiles.end ())
				profile = it->second;
		}
		if (profile)
		{
			update (profile);
			return true;
		}	
		// postpone
		std::lock_guard<std::mutex> l(g_PostponedUpdatesMutex);
		g_PostponedUpdates.emplace_back (identHash, update);
		return false;
	}	

	static void ApplyPostponedUpdates (std::list<std::pair<i2p::data::IdentHash, std::function<void (std::shared_ptr<RouterProfile>)> > >&& updates)
	{
		for (const auto& [ident, update] : updates)
		{
			auto profile = GetRouterProfile (ident);
			update (profile);
		}	
	}	
		
	std::future<void> FlushPostponedRouterProfileUpdates ()
	{
		if (g_PostponedUpdates.empty ()) return std::future<void>();

		std::list<std::pair<i2p::data::IdentHash, std::function<void (std::shared_ptr<RouterProfile>)> > > updates;
		{
			std::lock_guard<std::mutex> l(g_PostponedUpdatesMutex);
			g_PostponedUpdates.swap (updates);
		}		
		return std::async (std::launch::async, ApplyPostponedUpdates, std::move (updates));	
	}	
}
}