group_host.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- coding:utf-8 -*-
  2. # Copyright 2017 Xiaomi, Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. __author__ = 'Ulric Qin'
  16. from .bean import Bean
  17. from rrd.store import db
  18. from .host import Host
  19. class GroupHost(Bean):
  20. _tbl = 'grp_host'
  21. _cols = 'grp_id, host_id'
  22. def __init__(self, grp_id, host_id):
  23. self.grp_id = grp_id
  24. self.host_id = host_id
  25. @classmethod
  26. def unbind(cls, grp_id, host_ids):
  27. return cls.delete('grp_id = %s and host_id in (%s)' % (grp_id, host_ids))
  28. @classmethod
  29. def bind(cls, group_id, hostname):
  30. h = Host.read('hostname = %s', [hostname])
  31. if not h:
  32. Host.create(hostname)
  33. h = Host.read('hostname = %s', [hostname])
  34. if not h:
  35. return 'host auto add failed'
  36. if cls.exists('grp_id = %s and host_id = %s', [group_id, h.id]):
  37. return 'already existent'
  38. if db.update('insert into grp_host(grp_id, host_id) values(%s, %s)', [group_id, h.id]) <= 0:
  39. return 'failure'
  40. return ''
  41. @classmethod
  42. def bind_host_id(cls, group_id, host_id):
  43. if not Host.get(host_id):
  44. return 'no such host_id'
  45. if cls.exists('grp_id = %s and host_id = %s', [group_id, host_id]):
  46. return 'already existent'
  47. if db.update('insert into grp_host(grp_id, host_id) values(%s, %s)', [group_id, host_id]) <= 0:
  48. return 'failure'
  49. return ''
  50. @classmethod
  51. def group_ids(cls, host_id):
  52. return cls.column('grp_id', where='host_id = %s', params=[host_id])