1
2
3
4
5
6
7
8
9
10
11
12 import subprocess
13 import socket
14 import sys
15 import os
16 import optparse
17 import tempfile
18
19 """
20 This utility will create a unix socket connection to rrdcached. It
21 can be used to send commands to the rrdcached daemon managed by
22 zenrrdcached.
23 """
24
25
27 path = "%s/perf/Devices/%s" % (os.environ['ZENHOME'], device)
28 if not os.path.isdir(path):
29
30 return
31 with tempfile.NamedTemporaryFile('r+w') as t:
32 p = subprocess.Popen(["find", path, "-name", "*.rrd"],
33 stdout=subprocess.PIPE)
34 stdout, err = p.communicate()
35
36 for rrds in stdout.splitlines():
37 if rrds:
38 t.write("FLUSH ")
39 t.write(rrds.replace(" ", "\\ "))
40 t.write("\n")
41 t.flush()
42 t.seek(0)
43 p = subprocess.Popen([os.path.abspath(__file__), '-'], stdin=t)
44 p.wait()
45
46
48 s = None
49 sockfile = None
50 try:
51 zenhome = os.environ['ZENHOME']
52
53 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
54 s.connect(zenhome + "/var/rrdcached.sock")
55 sockfile = s.makefile('rw', 1024)
56 if sys.stdin.isatty():
57 prompt = "rrdcached> "
58 else:
59 prompt = ""
60
61 in_batch = False
62 while True:
63 if cmds is not None:
64 cmd = cmds.pop(0)
65 else:
66 try:
67 cmd = raw_input(prompt)
68 upper_cmd = cmd.rstrip().upper()
69 if upper_cmd in ('\Q', 'QUIT', 'EXIT', 'BYE', ':Q'):
70 break
71 except EOFError:
72 break
73
74 if cmd:
75 sockfile.write(cmd + "\n")
76 sockfile.flush()
77
78
79
80
81 if in_batch and cmd == ".":
82 in_batch = False
83
84 if not in_batch:
85 data = sockfile.readline().rstrip()
86 numlines, message = data.split(None, 1)
87 numlines = int(numlines)
88 print data
89 for i in range(numlines):
90 print sockfile.readline(),
91 if cmd.upper() == "BATCH":
92 in_batch = True
93
94 if cmds is not None and len(cmds) == 0:
95 break
96
97 finally:
98 if sockfile:
99 sockfile.write("QUIT\n")
100 sockfile.flush()
101 sockfile.readline()
102 sockfile.close()
103 if s:
104 s.close()
105
106 with open(os.devnull, 'rw') as devnull:
107 subprocess.call('stty sane', shell=True, stdout=devnull,
108 stderr=devnull)
109
110 if __name__ == "__main__":
111 usage = """usage: %prog COMMAND
112
113 - Interactively send commands to rrdcached.
114 flush DEVICE_ID Flush all the RRD files for the given device.
115 stats Print zenrrdcached STATS."""
116 parser = optparse.OptionParser(usage=usage)
117 options, args = parser.parse_args()
118
119 if len(args) == 0:
120 parser.print_usage()
121 elif args[0] == "-":
122 commandLoop()
123 elif args[0].lower() == "flush":
124 if len(args) < 2:
125 parser.print_usage()
126 for d in args[1:]:
127 flushDevice(d)
128 elif args[0].lower() == 'stats':
129 commandLoop(['STATS'])
130 else:
131 parser.print_usage()
132