1
0

host_group.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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.config import MAINTAINERS
  18. from rrd.store import db
  19. from rrd.model.user import User
  20. class HostGroup(Bean):
  21. _tbl = 'grp'
  22. _cols = 'id, grp_name, create_user, come_from'
  23. _id = 'id'
  24. def __init__(self, _id, grp_name, create_user, come_from):
  25. self.id = _id
  26. self.grp_name = grp_name
  27. self.create_user = create_user
  28. self.come_from = come_from
  29. #TODO:admin should manage the group
  30. def writable(self, user):
  31. #user can be str or User obj
  32. if isinstance(user, str):
  33. user = User.get_by_name(user)
  34. if not user:
  35. return False
  36. if self.create_user == user.name or user.name in MAINTAINERS or user.is_admin() or user.is_root():
  37. return True
  38. return False
  39. @classmethod
  40. def query(cls, page, limit, query, me=None):
  41. where = ''
  42. params = []
  43. if me is not None:
  44. where = 'create_user = %s'
  45. params = [me]
  46. if query:
  47. where += ' and ' if where else ''
  48. where += 'grp_name like %s'
  49. params.append('%' + query + '%')
  50. vs = cls.select_vs(where=where, params=params, page=page, limit=limit, order='grp_name')
  51. total = cls.total(where, params)
  52. return vs, total
  53. @classmethod
  54. def create(cls, grp_name, user_name, come_from):
  55. # check duplicate grp_name
  56. if cls.column('id', where='grp_name = %s', params=[grp_name]):
  57. return -1
  58. return cls.insert({'grp_name': grp_name, 'create_user': user_name, 'come_from': come_from})
  59. @classmethod
  60. def all_group_dict(cls):
  61. rows = db.query_all('select id, grp_name from grp where come_from = 0')
  62. return [{'id': row[0], 'name': row[1]} for row in rows]
  63. @classmethod
  64. def all_set(cls):
  65. sql = 'select id, grp_name from %s' % cls._tbl
  66. rows = db.query_all(sql)
  67. name_set = dict()
  68. name_id = dict()
  69. for row in rows:
  70. name = row[1]
  71. name_set[name] = set(name.split('_'))
  72. name_id[name] = row[0]
  73. return name_set, name_id