sysvitals_client 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/python
  2. import ConfigParser
  3. import json
  4. import os
  5. from os import path
  6. import socket
  7. import sys
  8. import urllib2
  9. import psutil
  10. is_root = (os.getuid() == 0)
  11. config = ConfigParser.RawConfigParser()
  12. if is_root:
  13. cfg_path = '/etc/sysvitals.cfg'
  14. else:
  15. cfg_path = path.join(path.dirname(path.abspath(__file__)), 'sysvitals.cfg')
  16. def post():
  17. if not config.read(cfg_path):
  18. sys.exit('no config found at %s' % cfg_path)
  19. cpu = psutil.cpu_times()
  20. mem = psutil.virtual_memory()
  21. net = psutil.net_io_counters()
  22. datum = {
  23. 'cpu': cpu._asdict(),
  24. 'mem': {
  25. 'total': mem.total,
  26. 'used': mem.used,
  27. 'buffers': mem.buffers,
  28. 'cached': mem.cached,
  29. },
  30. 'net': net._asdict(),
  31. 'disk': {}
  32. }
  33. datum['cpu']['num_cpus'] = psutil.NUM_CPUS
  34. for partition in psutil.disk_partitions():
  35. usage = psutil.disk_usage(partition.mountpoint)
  36. datum['disk'][partition.mountpoint] = {
  37. 'total': usage.total,
  38. 'used': usage.used,
  39. }
  40. api_server = config.get('client', 'api_server')
  41. group_id = config.get('client', 'group_id')
  42. server_id = config.get('client', 'server_id')
  43. url = '%s/v1/%s/datum/%s' % (api_server, group_id, server_id)
  44. urllib2.urlopen(url, json.dumps(datum))
  45. def configure():
  46. if not is_root:
  47. print 'configuring sysvitals client not as root will create a local config'
  48. if raw_input('are you sure you want to continue? [y/N] ') != 'y':
  49. return
  50. if path.exists(cfg_path):
  51. print cfg_path, 'already exists'
  52. if raw_input('are you sure you want to continue? [y/N] ') != 'y':
  53. return
  54. default_api_server = 'http://localhost:8892'
  55. config.add_section('client')
  56. config.set('client', 'api_server', default_api_server)
  57. group_id = None
  58. while group_id is None:
  59. group_id = raw_input('group_id: ')
  60. try:
  61. int(group_id)
  62. except ValueError:
  63. group_id = None
  64. print 'group_id should be numeric'
  65. config.set('client', 'group_id', group_id)
  66. print 'getting a brand new server id'
  67. try:
  68. url = '%s/v1/%s/register_server' % (default_api_server, group_id)
  69. r = urllib2.urlopen(url, json.dumps({'hostname': socket.getfqdn()}))
  70. server_id = json.load(r)['server_id']
  71. except Exception as e:
  72. sys.exit('an error occurred while getting the new server id:\n%r' % e)
  73. config.set('client', 'server_id', server_id)
  74. print 'writing config to', cfg_path
  75. with open(cfg_path, 'w') as f:
  76. config.write(f)
  77. if len(sys.argv) > 1 and sys.argv[1] == '--configure':
  78. configure()
  79. else:
  80. post()