root/trunk/pdns/pdns/rec_channel_rec.cc @ 1243

Revision 1243, 9.4 KB (checked in by ahu, 5 years ago)

implement get-parameter as suggested by Wouter de Jong of WideXS

Line 
1#include "utility.hh"
2#include "rec_channel.hh"
3#include <boost/lexical_cast.hpp>
4#include <boost/bind.hpp>
5#include <vector>
6#include "misc.hh"
7#include "recursor_cache.hh"
8#include "syncres.hh"
9#include <boost/function.hpp>
10#include <boost/optional.hpp>
11#include <boost/tuple/tuple.hpp>
12#include <boost/format.hpp>
13#include <boost/algorithm/string.hpp>
14#include <sys/types.h>
15#include <sys/stat.h>
16#include <fcntl.h>
17#include "logger.hh"
18#include "dnsparser.hh"
19#include "arguments.hh"
20#ifndef WIN32
21#include <sys/resource.h>
22#include <sys/time.h>
23#endif
24
25using namespace std;
26using namespace boost;
27map<string, const uint32_t*> d_get32bitpointers;
28map<string, const uint64_t*> d_get64bitpointers;
29map<string, function< uint32_t() > >  d_get32bitmembers;
30
31void addGetStat(const string& name, const uint32_t* place)
32{
33  d_get32bitpointers[name]=place;
34}
35void addGetStat(const string& name, const uint64_t* place)
36{
37  d_get64bitpointers[name]=place;
38}
39void addGetStat(const string& name, function<uint32_t ()> f ) 
40{
41  d_get32bitmembers[name]=f;
42}
43
44optional<uint64_t> get(const string& name) 
45{
46  optional<uint64_t> ret;
47
48  if(d_get32bitpointers.count(name))
49    return *d_get32bitpointers.find(name)->second;
50  if(d_get64bitpointers.count(name))
51    return *d_get64bitpointers.find(name)->second;
52  if(d_get32bitmembers.count(name))
53    return d_get32bitmembers.find(name)->second();
54
55  return ret;
56}
57
58
59template<typename T>
60string doGet(T begin, T end)
61{
62  string ret;
63
64  for(T i=begin; i != end; ++i) {
65    optional<uint64_t> num=get(*i);
66    if(num)
67      ret+=lexical_cast<string>(*num)+"\n";
68    else
69      ret+="UNKNOWN\n";
70  }
71  return ret;
72}
73
74template<typename T>
75string doGetParameter(T begin, T end)
76{
77  string ret;
78  string parm;
79  for(T i=begin; i != end; ++i) {
80    if(::arg().parmIsset(*i)) {
81      parm=::arg()[*i];
82      replace_all(parm, "\\", "\\\\");
83      replace_all(parm, "\"", "\\\"");
84      replace_all(parm, "\n", "\\n");
85      ret += *i +"=\""+ parm +"\"\n";
86    }
87    else
88      ret += *i +" not known\n";
89  }
90  return ret;
91}
92
93
94template<typename T>
95string doDumpCache(T begin, T end)
96{
97  T i=begin;
98  string fname;
99
100  if(i!=end) 
101    fname=*i;
102
103  int fd=open(fname.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0660);
104  if(fd < 0) 
105    return "Error opening dump file for writing: "+string(strerror(errno))+"\n";
106
107  RC.doDumpAndClose(fd); 
108
109  return "done\n";
110}
111
112template<typename T>
113string doWipeCache(T begin, T end)
114{
115  int count=0, countNeg=0;
116  for(T i=begin; i != end; ++i) {
117    count+=RC.doWipeCache(toCanonic("", *i));
118    string canon=toCanonic("", *i);
119    countNeg+=SyncRes::s_negcache.count(tie(canon));
120    pair<SyncRes::negcache_t::iterator, SyncRes::negcache_t::iterator> range=SyncRes::s_negcache.equal_range(tie(canon));
121    SyncRes::s_negcache.erase(range.first, range.second);
122  }
123
124  return "wiped "+lexical_cast<string>(count)+" records, "+lexical_cast<string>(countNeg)+" negative records\n";
125}
126
127template<typename T>
128string doSlashCache(T begin, T end)
129{
130  RC.doSlash(10);
131
132  return "done\n";
133}
134
135#if 0  // broken!
136uint32_t getQueryRate()
137{
138  struct timeval now;
139  gettimeofday(&now, 0);
140  optional<float> delay=g_stats.queryrate.get(now, 10);
141  if(delay)
142    return (uint32_t)(1000000/(*delay));
143  else
144    return 0;
145}
146#endif
147
148#ifndef WIN32
149static uint64_t getSysTimeMsec()
150{
151  struct rusage ru;
152  getrusage(RUSAGE_SELF, &ru);
153  return (ru.ru_stime.tv_sec*1000ULL + ru.ru_stime.tv_usec/1000);
154}
155
156static uint64_t getUserTimeMsec()
157{
158  struct rusage ru;
159  getrusage(RUSAGE_SELF, &ru);
160  return (ru.ru_utime.tv_sec*1000ULL + ru.ru_utime.tv_usec/1000);
161}
162#endif
163
164static uint64_t calculateUptime()
165{
166  return time(0) - g_stats.startupTime;
167}
168
169static string doCurrentQueries()
170{
171  ostringstream ostr;
172
173  ostr << MT->d_waiters.size() <<" currently outstanding questions\n";
174
175  boost::format fmt("%1% %|40t|%2% %|47t|%3% %|63t|%4% %|68t|%5%\n");
176
177  ostr << (fmt % "qname" % "qtype" % "remote" % "tcp" % "chained");
178  int n=0;
179  for(MT_t::waiters_t::iterator mthread=MT->d_waiters.begin(); mthread!=MT->d_waiters.end() && n < 100; ++mthread, ++n) {
180    const PacketID& pident = mthread->key;
181    ostr << (fmt
182             % pident.domain % DNSRecordContent::NumberToType(pident.type) 
183             % pident.remote.toString() % (pident.sock ? 'Y' : 'n')
184             % (pident.fd == -1 ? 'Y' : 'n')
185             );
186  }
187  ostr <<" - done\n";
188  return ostr.str();
189}
190
191RecursorControlParser::RecursorControlParser()
192{
193  addGetStat("questions", &g_stats.qcounter);
194  addGetStat("tcp-questions", &g_stats.tcpqcounter);
195
196  addGetStat("cache-hits", &RC.cacheHits);
197  addGetStat("cache-misses", &RC.cacheMisses);
198
199  addGetStat("cache-entries", boost::bind(&MemRecursorCache::size, ref(RC)));
200  addGetStat("servfail-answers", &g_stats.servFails);
201  addGetStat("nxdomain-answers", &g_stats.nxDomains);
202  addGetStat("noerror-answers", &g_stats.noErrors);
203
204  addGetStat("unauthorized-udp", &g_stats.unauthorizedUDP);
205  addGetStat("unauthorized-tcp", &g_stats.unauthorizedTCP);
206  addGetStat("tcp-client-overflow", &g_stats.tcpClientOverflow);
207
208  addGetStat("client-parse-errors", &g_stats.clientParseError);
209  addGetStat("server-parse-errors", &g_stats.serverParseError);
210
211  addGetStat("answers0-1", &g_stats.answers0_1);
212  addGetStat("answers1-10", &g_stats.answers1_10);
213  addGetStat("answers10-100", &g_stats.answers10_100);
214  addGetStat("answers100-1000", &g_stats.answers100_1000);
215  addGetStat("answers-slow", &g_stats.answersSlow);
216
217  addGetStat("qa-latency", &g_stats.avgLatencyUsec);
218  addGetStat("unexpected-packets", &g_stats.unexpectedCount);
219  addGetStat("case-mismatches", &g_stats.caseMismatchCount);
220  addGetStat("spoof-prevents", &g_stats.spoofCount);
221
222  addGetStat("nsset-invalidations", &g_stats.nsSetInvalidations);
223
224  addGetStat("resource-limits", &g_stats.resourceLimits);
225  addGetStat("dlg-only-drops", &SyncRes::s_nodelegated);
226 
227  addGetStat("shunted-queries", &g_stats.shunted);
228  addGetStat("noshunt-size", &g_stats.noShuntSize);
229  addGetStat("noshunt-expired", &g_stats.noShuntExpired);
230  addGetStat("noshunt-nomatch", &g_stats.noShuntNoMatch);
231  addGetStat("noshunt-cname", &g_stats.noShuntCNAME);
232  addGetStat("noshunt-wrong-question", &g_stats.noShuntWrongQuestion);
233  addGetStat("noshunt-wrong-type", &g_stats.noShuntWrongType);
234
235  addGetStat("negcache-entries", boost::bind(&SyncRes::negcache_t::size, ref(SyncRes::s_negcache)));
236  addGetStat("throttle-entries", boost::bind(&SyncRes::throttle_t::size, ref(SyncRes::s_throttle)));
237  addGetStat("nsspeeds-entries", boost::bind(&SyncRes::nsspeeds_t::size, ref(SyncRes::s_nsSpeeds)));
238
239  addGetStat("concurrent-queries", boost::bind(&MTasker<PacketID,string>::numProcesses, ref(MT)));
240  addGetStat("outgoing-timeouts", &SyncRes::s_outgoingtimeouts);
241  addGetStat("tcp-outqueries", &SyncRes::s_tcpoutqueries);
242  addGetStat("all-outqueries", &SyncRes::s_outqueries);
243  addGetStat("ipv6-outqueries", &g_stats.ipv6queries);
244  addGetStat("throttled-outqueries", &SyncRes::s_throttledqueries);
245  addGetStat("throttled-out", &SyncRes::s_throttledqueries);
246  addGetStat("unreachables", &SyncRes::s_unreachables);
247  addGetStat("chain-resends", &g_stats.chainResends);
248
249  addGetStat("uptime", calculateUptime);
250
251#ifndef WIN32
252  //  addGetStat("query-rate", getQueryRate);
253  addGetStat("user-msec", getUserTimeMsec);
254  addGetStat("sys-msec", getSysTimeMsec);
255#endif
256}
257
258static void doExit()
259{
260  L<<Logger::Error<<"Exiting on user request"<<endl;
261  extern RecursorControlChannel s_rcc;
262  s_rcc.~RecursorControlChannel(); 
263
264  extern string s_pidfname;
265  if(!s_pidfname.empty()) 
266    unlink(s_pidfname.c_str()); // we can at least try..
267  _exit(1);
268}
269
270string doTopRemotes()
271{
272  typedef map<ComboAddress, int, ComboAddress::addressOnlyLessThan> counts_t;
273  counts_t counts;
274 
275  unsigned int total=0;
276  for(RecursorStats::remotes_t::const_iterator i=g_stats.remotes.begin(); i != g_stats.remotes.end(); ++i)
277    if(i->sin4.sin_family) {
278      total++;
279      counts[*i]++;
280    }
281
282  typedef multimap<int, ComboAddress> rcounts_t;
283  rcounts_t rcounts;
284 
285  for(counts_t::const_iterator i=counts.begin(); i != counts.end(); ++i)
286    rcounts.insert(make_pair(-i->second, i->first));
287
288  ostringstream ret;
289  ret<<"Over last "<<total<<" queries:\n";
290  format fmt("%.02f%%\t%s\n");
291  int limit=0;
292  if(total)
293    for(rcounts_t::const_iterator i=rcounts.begin(); i != rcounts.end() && limit < 20; ++i, ++limit)
294      ret<< fmt % (-100.0*i->first/total) % i->second.toString();
295
296  return ret.str();
297}
298
299string RecursorControlParser::getAnswer(const string& question, RecursorControlParser::func_t** command)
300{
301  *command=nop;
302  vector<string> words;
303  stringtok(words, question);
304
305  if(words.empty())
306    return "invalid command\n";
307
308  string cmd=toLower(words[0]);
309  vector<string>::const_iterator begin=words.begin()+1, end=words.end();
310
311  if(cmd=="get") 
312    return doGet(begin, end);
313
314  if(cmd=="get-parameter") 
315    return doGetParameter(begin, end);
316
317
318  if(cmd=="quit") {
319    *command=&doExit;
320    return "bye\n";
321  }
322
323  if(cmd=="dump-cache") 
324    return doDumpCache(begin, end);
325
326  if(cmd=="slash-cache") 
327    return doSlashCache(begin, end);
328
329  if(cmd=="wipe-cache") 
330    return doWipeCache(begin, end);
331
332  if(cmd=="reload-lua-script") 
333    return doReloadLuaScript(begin, end);
334
335  if(cmd=="unload-lua-script") {
336    vector<string> empty;
337    empty.push_back(string());
338    return doReloadLuaScript(empty.begin(), empty.end());
339  }
340
341
342  if(cmd=="top-remotes")
343    return doTopRemotes();
344
345  if(cmd=="current-queries")
346    return doCurrentQueries();
347 
348  if(cmd=="ping")
349    return "pong\n";
350
351  if(cmd=="reload-zones") {
352    return reloadAuthAndForwards();
353  }
354
355  return "Unknown command '"+cmd+"'\n";
356}
Note: See TracBrowser for help on using the browser.