host.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import json
  4. from flask import g
  5. from initialize import app
  6. from models import Database as db
  7. __author__ = 'James Iter'
  8. __date__ = '2017/9/19'
  9. __contact__ = 'james.iter.cn@gmail.com'
  10. __copyright__ = '(c) 2017 by James Iter.'
  11. class Host(object):
  12. def __init__(self):
  13. pass
  14. @staticmethod
  15. def alive_check(v):
  16. """
  17. JimV-C 2 秒更新一次宿主机信息,这里以 5 秒内没收到更新,作为判断宿主机是否在线的标准
  18. """
  19. if 'timestamp' not in v:
  20. return v
  21. v['alive'] = False
  22. if v['timestamp'] + 5 >= g.ts:
  23. v['alive'] = True
  24. return v
  25. @staticmethod
  26. def set_allocation_mode(hosts_name=None, random=True):
  27. if not isinstance(hosts_name, list):
  28. raise ValueError('The hosts_name must be a list.')
  29. if random:
  30. db.r.sadd(app.config['compute_nodes_of_allocation_by_nonrandom'], *hosts_name)
  31. else:
  32. db.r.srem(app.config['compute_nodes_of_allocation_by_nonrandom'], *hosts_name)
  33. @classmethod
  34. def get_all(cls):
  35. ret = list()
  36. compute_nodes_of_allocation_by_nonrandom = \
  37. list(db.r.smembers(app.config['compute_nodes_of_allocation_by_nonrandom']))
  38. for k, v in db.r.hgetall(app.config['hosts_info']).items():
  39. v = json.loads(v)
  40. v = cls.alive_check(v)
  41. v['node_id'] = k
  42. if v['hostname'] in compute_nodes_of_allocation_by_nonrandom:
  43. v['nonrandom'] = True
  44. else:
  45. v['nonrandom'] = False
  46. ret.append(v)
  47. if ret.__len__() > 1:
  48. ret.sort(key=lambda _k: _k['boot_time'])
  49. return ret
  50. @classmethod
  51. def get_available_hosts(cls, nonrandom=None):
  52. """
  53. :param nonrandom: {None, True, False}
  54. None for all;
  55. False for host can be allocation guest by random;
  56. True on the contrary.
  57. :return:
  58. """
  59. hosts = list()
  60. for host in cls.get_all():
  61. if not host['alive']:
  62. continue
  63. if nonrandom is not None and host['nonrandom'] != nonrandom:
  64. continue
  65. host['system_load_per_cpu'] = float(host['system_load'][0]) / host['cpu']
  66. hosts.append(host)
  67. hosts.sort(key=lambda _k: _k['system_load_per_cpu'])
  68. return hosts