]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/coremods/core_stats.cpp
Merge branch 'insp20' into master.
[user/henk/code/inspircd.git] / src / coremods / core_stats.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007-2008 Craig Edwards <craigedwards@brainbox.cc>
6  *   Copyright (C) 2007 Robin Burchell <robin+git@viroteck.net>
7  *
8  * This file is part of InspIRCd.  InspIRCd is free software: you can
9  * redistribute it and/or modify it under the terms of the GNU General Public
10  * License as published by the Free Software Foundation, version 2.
11  *
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
15  * details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21
22 #include "inspircd.h"
23 #include "xline.h"
24
25 #ifdef _WIN32
26 #include <psapi.h>
27 #pragma comment(lib, "psapi.lib") // For GetProcessMemoryInfo()
28 #endif
29
30 /** Handle /STATS.
31  */
32 class CommandStats : public Command
33 {
34         void DoStats(Stats::Context& stats);
35  public:
36         /** Constructor for stats.
37          */
38         CommandStats ( Module* parent) : Command(parent,"STATS",1,2) { allow_empty_last_param = false; syntax = "<stats-symbol> [<servername>]"; }
39         /** Handle command.
40          * @param parameters The parameters to the command
41          * @param user The user issuing the command
42          * @return A value from CmdResult to indicate command success or failure.
43          */
44         CmdResult Handle(const std::vector<std::string>& parameters, User* user) CXX11_OVERRIDE;
45         RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) CXX11_OVERRIDE
46         {
47                 if ((parameters.size() > 1) && (parameters[1].find('.') != std::string::npos))
48                         return ROUTE_UNICAST(parameters[1]);
49                 return ROUTE_LOCALONLY;
50         }
51 };
52
53 static void GenerateStatsLl(Stats::Context& stats)
54 {
55         stats.AddRow(211, InspIRCd::Format("nick[ident@%s] sendq cmds_out bytes_out cmds_in bytes_in time_open", (stats.GetSymbol() == 'l' ? "host" : "ip")));
56
57         const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
58         for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
59         {
60                 LocalUser* u = *i;
61                 stats.AddRow(211, u->nick+"["+u->ident+"@"+(stats.GetSymbol() == 'l' ? u->GetDisplayedHost() : u->GetIPString())+"] "+ConvToStr(u->eh.getSendQSize())+" "+ConvToStr(u->cmds_out)+" "+ConvToStr(u->bytes_out)+" "+ConvToStr(u->cmds_in)+" "+ConvToStr(u->bytes_in)+" "+ConvToStr(ServerInstance->Time() - u->signon));
62         }
63 }
64
65 void CommandStats::DoStats(Stats::Context& stats)
66 {
67         User* const user = stats.GetSource();
68         const char statschar = stats.GetSymbol();
69
70         bool isPublic = ServerInstance->Config->UserStats.find(statschar) != std::string::npos;
71         bool isRemoteOper = IS_REMOTE(user) && (user->IsOper());
72         bool isLocalOperWithPrivs = IS_LOCAL(user) && user->HasPrivPermission("servers/auspex");
73
74         if (!isPublic && !isRemoteOper && !isLocalOperWithPrivs)
75         {
76                 ServerInstance->SNO->WriteToSnoMask('t',
77                                 "%s '%c' denied for %s (%s@%s)",
78                                 (IS_LOCAL(user) ? "Stats" : "Remote stats"),
79                                 statschar, user->nick.c_str(), user->ident.c_str(), user->GetRealHost().c_str());
80                 stats.AddRow(481, (std::string("Permission Denied - STATS ") + statschar + " requires the servers/auspex priv."));
81                 return;
82         }
83
84         ModResult MOD_RESULT;
85         FIRST_MOD_RESULT(OnStats, MOD_RESULT, (stats));
86         if (MOD_RESULT == MOD_RES_DENY)
87         {
88                 stats.AddRow(219, statschar, "End of /STATS report");
89                 ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",
90                         (IS_LOCAL(user) ? "Stats" : "Remote stats"), statschar, user->nick.c_str(), user->ident.c_str(), user->GetRealHost().c_str());
91                 return;
92         }
93
94         switch (statschar)
95         {
96                 /* stats p (show listening ports) */
97                 case 'p':
98                 {
99                         for (std::vector<ListenSocket*>::const_iterator i = ServerInstance->ports.begin(); i != ServerInstance->ports.end(); ++i)
100                         {
101                                 ListenSocket* ls = *i;
102                                 std::string type = ls->bind_tag->getString("type", "clients");
103                                 std::string hook = ls->bind_tag->getString("ssl", "plaintext");
104
105                                 stats.AddRow(249, ls->bind_sa.str() + " (" + type + ", " + hook + ")");
106                         }
107                 }
108                 break;
109
110                 /* These stats symbols must be handled by a linking module */
111                 case 'n':
112                 case 'c':
113                 break;
114
115                 case 'i':
116                 {
117                         for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
118                         {
119                                 ConnectClass* c = *i;
120                                 Stats::Row row(215);
121                                 row.push("I").push(c->name);
122
123                                 std::string param;
124                                 if (c->type == CC_ALLOW)
125                                         param.push_back('+');
126                                 if (c->type == CC_DENY)
127                                         param.push_back('-');
128
129                                 if (c->type == CC_NAMED)
130                                         param.push_back('*');
131                                 else
132                                         param.append(c->host);
133
134                                 row.push(param).push(c->config->getString("port", "*"));
135                                 row.push(ConvToStr(c->GetRecvqMax())).push(ConvToStr(c->GetSendqSoftMax())).push(ConvToStr(c->GetSendqHardMax())).push(ConvToStr(c->GetCommandRate()));
136
137                                 param = ConvToStr(c->GetPenaltyThreshold());
138                                 if (c->fakelag)
139                                         param.push_back('*');
140                                 row.push(param);
141
142                                 stats.AddRow(row);
143                         }
144                 }
145                 break;
146
147                 case 'Y':
148                 {
149                         int idx = 0;
150                         for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
151                         {
152                                 ConnectClass* c = *i;
153                                 stats.AddRow(215, 'i', "NOMATCH", '*', c->GetHost(), (c->limit ? c->limit : SocketEngine::GetMaxFds()), idx, ServerInstance->Config->ServerName, '*');
154                                 stats.AddRow(218, 'Y', idx, c->GetPingTime(), '0', c->GetSendqHardMax(), ConvToStr(c->GetRecvqMax())+" "+ConvToStr(c->GetRegTimeout()));
155                                 idx++;
156                         }
157                 }
158                 break;
159
160                 case 'P':
161                 {
162                         unsigned int idx = 0;
163                         const UserManager::OperList& opers = ServerInstance->Users->all_opers;
164                         for (UserManager::OperList::const_iterator i = opers.begin(); i != opers.end(); ++i)
165                         {
166                                 User* oper = *i;
167                                 if (!oper->server->IsULine())
168                                 {
169                                         LocalUser* lu = IS_LOCAL(oper);
170                                         stats.AddRow(249, oper->nick + " (" + oper->ident + "@" + oper->GetDisplayedHost() + ") Idle: " +
171                                                         (lu ? ConvToStr(ServerInstance->Time() - lu->idle_lastmsg) + " secs" : "unavailable"));
172                                         idx++;
173                                 }
174                         }
175                         stats.AddRow(249, ConvToStr(idx)+" OPER(s)");
176                 }
177                 break;
178
179                 case 'k':
180                         ServerInstance->XLines->InvokeStats("K",216,stats);
181                 break;
182                 case 'g':
183                         ServerInstance->XLines->InvokeStats("G",223,stats);
184                 break;
185                 case 'q':
186                         ServerInstance->XLines->InvokeStats("Q",217,stats);
187                 break;
188                 case 'Z':
189                         ServerInstance->XLines->InvokeStats("Z",223,stats);
190                 break;
191                 case 'e':
192                         ServerInstance->XLines->InvokeStats("E",223,stats);
193                 break;
194                 case 'E':
195                 {
196                         const SocketEngine::Statistics& sestats = SocketEngine::GetStats();
197                         stats.AddRow(249, "Total events: "+ConvToStr(sestats.TotalEvents));
198                         stats.AddRow(249, "Read events:  "+ConvToStr(sestats.ReadEvents));
199                         stats.AddRow(249, "Write events: "+ConvToStr(sestats.WriteEvents));
200                         stats.AddRow(249, "Error events: "+ConvToStr(sestats.ErrorEvents));
201                         break;
202                 }
203
204                 /* stats m (list number of times each command has been used, plus bytecount) */
205                 case 'm':
206                 {
207                         const CommandParser::CommandMap& commands = ServerInstance->Parser.GetCommands();
208                         for (CommandParser::CommandMap::const_iterator i = commands.begin(); i != commands.end(); ++i)
209                         {
210                                 if (i->second->use_count)
211                                 {
212                                         /* RPL_STATSCOMMANDS */
213                                         stats.AddRow(212, i->second->name, i->second->use_count);
214                                 }
215                         }
216                 }
217                 break;
218
219                 /* stats z (debug and memory info) */
220                 case 'z':
221                 {
222                         stats.AddRow(249, "Users: "+ConvToStr(ServerInstance->Users->GetUsers().size()));
223                         stats.AddRow(249, "Channels: "+ConvToStr(ServerInstance->GetChans().size()));
224                         stats.AddRow(249, "Commands: "+ConvToStr(ServerInstance->Parser.GetCommands().size()));
225
226                         float kbitpersec_in, kbitpersec_out, kbitpersec_total;
227                         SocketEngine::GetStats().GetBandwidth(kbitpersec_in, kbitpersec_out, kbitpersec_total);
228
229                         stats.AddRow(249, InspIRCd::Format("Bandwidth total:  %03.5f kilobits/sec", kbitpersec_total));
230                         stats.AddRow(249, InspIRCd::Format("Bandwidth out:    %03.5f kilobits/sec", kbitpersec_out));
231                         stats.AddRow(249, InspIRCd::Format("Bandwidth in:     %03.5f kilobits/sec", kbitpersec_in));
232
233 #ifndef _WIN32
234                         /* Moved this down here so all the not-windows stuff (look w00tie, I didn't say win32!) is in one ifndef.
235                          * Also cuts out some identical code in both branches of the ifndef. -- Om
236                          */
237                         rusage R;
238
239                         /* Not sure why we were doing '0' with a RUSAGE_SELF comment rather than just using RUSAGE_SELF -- Om */
240                         if (!getrusage(RUSAGE_SELF,&R)) /* RUSAGE_SELF */
241                         {
242                                 stats.AddRow(249, "Total allocation: "+ConvToStr(R.ru_maxrss)+"K");
243                                 stats.AddRow(249, "Signals:          "+ConvToStr(R.ru_nsignals));
244                                 stats.AddRow(249, "Page faults:      "+ConvToStr(R.ru_majflt));
245                                 stats.AddRow(249, "Swaps:            "+ConvToStr(R.ru_nswap));
246                                 stats.AddRow(249, "Context Switches: Voluntary; "+ConvToStr(R.ru_nvcsw)+" Involuntary; "+ConvToStr(R.ru_nivcsw));
247
248                                 float n_elapsed = (ServerInstance->Time() - ServerInstance->stats.LastSampled.tv_sec) * 1000000
249                                         + (ServerInstance->Time_ns() - ServerInstance->stats.LastSampled.tv_nsec) / 1000;
250                                 float n_eaten = ((R.ru_utime.tv_sec - ServerInstance->stats.LastCPU.tv_sec) * 1000000 + R.ru_utime.tv_usec - ServerInstance->stats.LastCPU.tv_usec);
251                                 float per = (n_eaten / n_elapsed) * 100;
252
253                                 stats.AddRow(249, InspIRCd::Format("CPU Use (now):    %03.5f%%", per));
254
255                                 n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
256                                 n_eaten = (float)R.ru_utime.tv_sec + R.ru_utime.tv_usec / 100000.0;
257                                 per = (n_eaten / n_elapsed) * 100;
258
259                                 stats.AddRow(249, InspIRCd::Format("CPU Use (total):  %03.5f%%", per));
260                         }
261 #else
262                         PROCESS_MEMORY_COUNTERS MemCounters;
263                         if (GetProcessMemoryInfo(GetCurrentProcess(), &MemCounters, sizeof(MemCounters)))
264                         {
265                                 stats.AddRow(249, "Total allocation: "+ConvToStr((MemCounters.WorkingSetSize + MemCounters.PagefileUsage) / 1024)+"K");
266                                 stats.AddRow(249, "Pagefile usage:   "+ConvToStr(MemCounters.PagefileUsage / 1024)+"K");
267                                 stats.AddRow(249, "Page faults:      "+ConvToStr(MemCounters.PageFaultCount));
268                         }
269
270                         FILETIME CreationTime;
271                         FILETIME ExitTime;
272                         FILETIME KernelTime;
273                         FILETIME UserTime;
274                         LARGE_INTEGER ThisSample;
275                         if(GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime) &&
276                                 QueryPerformanceCounter(&ThisSample))
277                         {
278                                 KernelTime.dwHighDateTime += UserTime.dwHighDateTime;
279                                 KernelTime.dwLowDateTime += UserTime.dwLowDateTime;
280                                 double n_eaten = (double)( ( (uint64_t)(KernelTime.dwHighDateTime - ServerInstance->stats.LastCPU.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime - ServerInstance->stats.LastCPU.dwLowDateTime) )/100000;
281                                 double n_elapsed = (double)(ThisSample.QuadPart - ServerInstance->stats.LastSampled.QuadPart) / ServerInstance->stats.QPFrequency.QuadPart;
282                                 double per = (n_eaten/n_elapsed);
283
284                                 stats.AddRow(249, InspIRCd::Format("CPU Use (now):    %03.5f%%", per));
285
286                                 n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
287                                 n_eaten = (double)(( (uint64_t)(KernelTime.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime))/100000;
288                                 per = (n_eaten / n_elapsed);
289
290                                 stats.AddRow(249, InspIRCd::Format("CPU Use (total):  %03.5f%%", per));
291                         }
292 #endif
293                 }
294                 break;
295
296                 case 'T':
297                 {
298                         stats.AddRow(249, "accepts "+ConvToStr(ServerInstance->stats.Accept)+" refused "+ConvToStr(ServerInstance->stats.Refused));
299                         stats.AddRow(249, "unknown commands "+ConvToStr(ServerInstance->stats.Unknown));
300                         stats.AddRow(249, "nick collisions "+ConvToStr(ServerInstance->stats.Collisions));
301                         stats.AddRow(249, "dns requests "+ConvToStr(ServerInstance->stats.DnsGood+ServerInstance->stats.DnsBad)+" succeeded "+ConvToStr(ServerInstance->stats.DnsGood)+" failed "+ConvToStr(ServerInstance->stats.DnsBad));
302                         stats.AddRow(249, "connection count "+ConvToStr(ServerInstance->stats.Connects));
303                         stats.AddRow(249, InspIRCd::Format("bytes sent %5.2fK recv %5.2fK",
304                                 ServerInstance->stats.Sent / 1024.0, ServerInstance->stats.Recv / 1024.0));
305                 }
306                 break;
307
308                 /* stats o */
309                 case 'o':
310                 {
311                         ConfigTagList tags = ServerInstance->Config->ConfTags("oper");
312                         for(ConfigIter i = tags.first; i != tags.second; ++i)
313                         {
314                                 ConfigTag* tag = i->second;
315                                 stats.AddRow(243, 'O', tag->getString("host"), '*', tag->getString("name"), tag->getString("type"), '0');
316                         }
317                 }
318                 break;
319                 case 'O':
320                 {
321                         for (ServerConfig::OperIndex::const_iterator i = ServerInstance->Config->OperTypes.begin(); i != ServerInstance->Config->OperTypes.end(); ++i)
322                         {
323                                 OperInfo* tag = i->second;
324                                 tag->init();
325                                 std::string umodes;
326                                 std::string cmodes;
327                                 for(char c='A'; c <= 'z'; c++)
328                                 {
329                                         ModeHandler* mh = ServerInstance->Modes->FindMode(c, MODETYPE_USER);
330                                         if (mh && mh->NeedsOper() && tag->AllowedUserModes[c - 'A'])
331                                                 umodes.push_back(c);
332                                         mh = ServerInstance->Modes->FindMode(c, MODETYPE_CHANNEL);
333                                         if (mh && mh->NeedsOper() && tag->AllowedChanModes[c - 'A'])
334                                                 cmodes.push_back(c);
335                                 }
336                                 stats.AddRow(243, 'O', tag->name, umodes, cmodes);
337                         }
338                 }
339                 break;
340
341                 /* stats l (show user I/O stats) */
342                 case 'l':
343                 /* stats L (show user I/O stats with IP addresses) */
344                 case 'L':
345                         GenerateStatsLl(stats);
346                 break;
347
348                 /* stats u (show server uptime) */
349                 case 'u':
350                 {
351                         unsigned int up = static_cast<unsigned int>(ServerInstance->Time() - ServerInstance->startup_time);
352                         stats.AddRow(242, InspIRCd::Format("Server up %u days, %.2u:%.2u:%.2u",
353                                 up / 86400, (up / 3600) % 24, (up / 60) % 60, up % 60));
354                 }
355                 break;
356
357                 default:
358                 break;
359         }
360
361         stats.AddRow(219, statschar, "End of /STATS report");
362         ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",
363                 (IS_LOCAL(user) ? "Stats" : "Remote stats"), statschar, user->nick.c_str(), user->ident.c_str(), user->GetRealHost().c_str());
364         return;
365 }
366
367 CmdResult CommandStats::Handle (const std::vector<std::string>& parameters, User *user)
368 {
369         if (parameters.size() > 1 && parameters[1] != ServerInstance->Config->ServerName)
370         {
371                 // Give extra penalty if a non-oper does /STATS <remoteserver>
372                 LocalUser* localuser = IS_LOCAL(user);
373                 if ((localuser) && (!user->IsOper()))
374                         localuser->CommandFloodPenalty += 2000;
375                 return CMD_SUCCESS;
376         }
377         Stats::Context stats(user, parameters[0][0]);
378         DoStats(stats);
379         const std::vector<Stats::Row>& rows = stats.GetRows();
380         for (std::vector<Stats::Row>::const_iterator i = rows.begin(); i != rows.end(); ++i)
381         {
382                 const Stats::Row& row = *i;
383                 user->WriteRemoteNumeric(row);
384         }
385
386         return CMD_SUCCESS;
387 }
388
389 COMMAND_INIT(CommandStats)