sysmond.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Copyright 2012-2013 AGR Audio, Industria e Comercio LTDA. <contato@moddevices.com>
  2. #
  3. # This program is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, either version 3 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. from tornado import ioloop
  16. from psutil import Process
  17. import socket, functools, json
  18. import psutil
  19. PS=[]
  20. def update_process_list():
  21. global PS
  22. plist = []
  23. for pid in psutil.get_pid_list():
  24. try:
  25. p = Process(pid)
  26. plist.append((p,p.get_cpu_percent(),p.get_memory_percent()))
  27. except psutil.NoSuchProcess:
  28. continue
  29. # copy plist to PS
  30. PS = sorted(plist[:], key=lambda e: e[1] if e[1] > e[2] else e[2], reverse=True)[:25]
  31. def process_stats():
  32. pslist = []
  33. for p, cpu, mem in PS:
  34. try:
  35. pslist.append({'pid': p.pid,
  36. 'name': p.name,
  37. 'cpu': float("%.2f" % p.get_cpu_percent(0)),
  38. 'mem': float("%.2f" % p.get_memory_percent())})
  39. except psutil.NoSuchProcess:
  40. continue
  41. return sorted(pslist, key=lambda p:p['cpu'], reverse=True)
  42. def connection_ready(sock, fd, events):
  43. while True:
  44. try:
  45. connection, address = sock.accept()
  46. except socket.error as e:
  47. if e.args[0] not in (errno.EWOULDBLOCK, errno.EAGAIN):
  48. raise
  49. return
  50. connection.setblocking(0)
  51. connection.send(json.dumps({'ps': process_stats(), 'total_cpu': "%.2f" % psutil.cpu_percent()})+"\0")
  52. connection.close()
  53. return
  54. if __name__ == "__main__":
  55. import thread
  56. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
  57. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  58. sock.setblocking(0)
  59. sock.bind(("", 57890))
  60. sock.listen(128)
  61. io = ioloop.IOLoop.instance()
  62. cb = functools.partial(connection_ready, sock)
  63. io.add_handler(sock.fileno(), cb, io.READ)
  64. ioloop.PeriodicCallback(lambda: thread.start_new_thread(update_process_list,()), 30000, io_loop=io).start()
  65. update_process_list()
  66. io.start()