xref: /dpdk/usertools/dpdk-telemetry.py (revision f5057be340e44f3edc0fe90fa875eb89a4c49b4f)
1#! /usr/bin/env python3
2# SPDX-License-Identifier: BSD-3-Clause
3# Copyright(c) 2020 Intel Corporation
4
5"""
6Script to be used with V2 Telemetry.
7Allows the user input commands and read the Telemetry response.
8"""
9
10import socket
11import os
12import glob
13import json
14import readline
15
16# global vars
17TELEMETRY_VERSION = "v2"
18CMDS = []
19
20
21def read_socket(sock, buf_len, echo=True):
22    """ Read data from socket and return it in JSON format """
23    reply = sock.recv(buf_len).decode()
24    try:
25        ret = json.loads(reply)
26    except json.JSONDecodeError:
27        print("Error in reply: ", reply)
28        sock.close()
29        raise
30    if echo:
31        print(json.dumps(ret))
32    return ret
33
34
35def handle_socket(path):
36    """ Connect to socket and handle user input """
37    sock = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
38    global CMDS
39    print("Connecting to " + path)
40    try:
41        sock.connect(path)
42    except OSError:
43        print("Error connecting to " + path)
44        sock.close()
45        return
46    json_reply = read_socket(sock, 1024)
47    output_buf_len = json_reply["max_output_len"]
48
49    # get list of commands for readline completion
50    sock.send("/".encode())
51    CMDS = read_socket(sock, output_buf_len, False)["/"]
52
53    # interactive prompt
54    text = input('--> ').strip()
55    while text != "quit":
56        if text.startswith('/'):
57            sock.send(text.encode())
58            read_socket(sock, output_buf_len)
59        text = input('--> ').strip()
60    sock.close()
61
62
63def readline_complete(text, state):
64    """ Find any matching commands from the list based on user input """
65    all_cmds = ['quit'] + CMDS
66    if text:
67        matches = [c for c in all_cmds if c.startswith(text)]
68    else:
69        matches = all_cmds
70    return matches[state]
71
72
73readline.parse_and_bind('tab: complete')
74readline.set_completer(readline_complete)
75readline.set_completer_delims(readline.get_completer_delims().replace('/', ''))
76
77# Path to sockets for processes run as a root user
78for f in glob.glob('/var/run/dpdk/*/dpdk_telemetry.%s' % TELEMETRY_VERSION):
79    handle_socket(f)
80# Path to sockets for processes run as a regular user
81for f in glob.glob('%s/dpdk/*/dpdk_telemetry.%s' %
82                   (os.environ.get('XDG_RUNTIME_DIR', '/tmp'), TELEMETRY_VERSION)):
83    handle_socket(f)
84