1 pod自动更新

k8s的list-watch机制使得k8s的资源可以实现动态更改。

  1. import os, sys, django
  2. import logging
  3. pwd = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
  4. sys.path.append(pwd)
  5. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "devops_backend.settings")
  6. django.setup()
  7. from kubernetes import client, watch
  8. from cmdb import models as cmdb_models
  9. logger = logging.getLogger(__name__)
  10. class ClientKubernetes(object):
  11. def __init__(self, apitoken, apiserverUrl):
  12. """
  13. method one: copy ~/.kube/config to local~/.kube then do the following
  14. config.load_kube_config()
  15. self.client = client.CoreV1Api()
  16. method two: as you can see in below
  17. """
  18. ApiToken = "****"
  19. configuration = client.Configuration()
  20. setattr(configuration, 'verify_ssl', False)
  21. client.Configuration.set_default(configuration)
  22. configuration.host = apiserverUrl
  23. # configuration.verify_ssl = False
  24. # configuration.debug = True
  25. configuration.api_key = {"authorization": "Bearer " + apitoken}
  26. client.Configuration.set_default(configuration)
  27. self.clientInstance = client.CoreV1Api(client.ApiClient(configuration))
  28. self.clientIngress = client.ExtensionsV1beta1Api()
  29. self.apis_api = client.AppsV1Api()
  30. def get_pod_for_all_namesapces(self):
  31. """
  32. 一共有5个属性api_version,kind,metadata,spec,status
  33. 先暂时取出status属性
  34. :return:
  35. """
  36. result = self.clientInstance.list_pod_for_all_namespaces(watch=False)
  37. temp_result = []
  38. count = 0
  39. for item in result.items:
  40. count += 1
  41. item_dict = item.to_dict()
  42. print(item_dict)
  43. temp_result.append({'podname': item_dict['metadata']['name'], 'kind': item_dict['kind'],
  44. 'annotations': item_dict['metadata']['annotations'],
  45. 'cluster_name': item_dict['metadata']['cluster_name'],
  46. 'labels': item_dict['metadata']['labels'],
  47. 'namespace': item_dict['metadata']['namespace']})
  48. break
  49. return {'pod': temp_result, 'podcount': count}
  50. def get_deployment_pods(self, namespace):
  51. """获取deployment所有的pod"""
  52. if namespace:
  53. result = self.apis_api.list_namespaced_deployment(namespace=namespace).to_dict()
  54. else:
  55. result = self.apis_api.list_deployment_for_all_namespaces().to_dict()
  56. temp_result = []
  57. count = 0
  58. for item in result["items"]:
  59. # print(item)
  60. name = item['metadata']['name']
  61. namespace = item['metadata']['namespace']
  62. replicas = item['spec']['replicas']
  63. selector = item['spec']['selector']
  64. temp_result.append({'name': name, 'namespace': namespace, 'replicas': replicas, 'selector': selector})
  65. count += 1
  66. return {'podcount': count, 'pod': temp_result}
  67. def get_statefulset_pods(self, namespace):
  68. """获取所有的statefulset 所有的pod"""
  69. if namespace:
  70. result = self.apis_api.list_namespaced_stateful_set(namespace=namespace).to_dict()
  71. else:
  72. result = self.apis_api.list_stateful_set_for_all_namespaces().to_dict()
  73. temp_result = []
  74. count = 0
  75. for item in result["items"]:
  76. name = item['metadata']['name']
  77. namespace = item['metadata']['namespace']
  78. replicas = item['spec']['replicas']
  79. selector = item['spec']['selector']
  80. temp_result.append({'name': name, 'namespace': namespace, 'replicas': replicas, 'selector': selector})
  81. count += 1
  82. return {'podcount': count, 'pod': temp_result}
  83. def get_daemonset_pods(self, namespace):
  84. """获取所有的daemonset"""
  85. if namespace:
  86. result = self.apis_api.list_namespaced_daemon_set(namespace=namespace).to_dict()
  87. else:
  88. result = self.apis_api.list_daemon_set_for_all_namespaces().to_dict()
  89. temp_result = []
  90. count = 0
  91. for item in result["items"]:
  92. name = item['metadata']['name']
  93. namespace = item['metadata']['namespace']
  94. selector = item['spec']['selector']
  95. temp_result.append({'name': name, 'namespace': namespace, 'selector': selector})
  96. count += 1
  97. return {'podcount': count, 'pod': temp_result}
  98. def get_all_namespace(self):
  99. """获取所有的namespace"""
  100. result = self.clientInstance.list_namespace().to_dict()
  101. temp_result = []
  102. for item in result['items']:
  103. name = item['metadata']['name']
  104. creation_timestamp = item['metadata']['creation_timestamp']
  105. labels = item['metadata']['labels']
  106. status = item['status']['phase']
  107. temp_result.append(
  108. {'name': name, 'creation_timestamp': creation_timestamp, 'labels': labels, 'status': status})
  109. return temp_result
  110. def get_all_service(self, namespace):
  111. """获取所有的service"""
  112. if namespace:
  113. result = self.clientInstance.list_namespaced_service(namespace=namespace)
  114. else:
  115. result = self.clientInstance.list_service_for_all_namespaces().to_dict()
  116. temp_result = []
  117. count = 0
  118. for item in result['items']:
  119. name = item['metadata']['name']
  120. labels = item['metadata']['labels']
  121. namespace = item['metadata']['namespace']
  122. cluster_ip = item['spec']['cluster_ip']
  123. ports = item['spec']['ports']
  124. temp_result.append(
  125. {'name': name, 'labels': labels, 'namespace': namespace, 'cluster_ip': cluster_ip, 'ports': ports})
  126. count += 1
  127. return {'podcount': count, 'pod': temp_result}
  128. def get_all_ingress(self, namespace):
  129. """获取所有的ingress"""
  130. if namespace:
  131. result = self.clientIngress.list_namespaced_ingress(namespace=namespace).to_dict()
  132. else:
  133. result = self.clientIngress.list_ingress_for_all_namespaces().to_dict()
  134. temp_result = []
  135. count = 0
  136. for item in result['items']:
  137. name = item['metadata']['name']
  138. namespace = item['metadata']['namespace']
  139. rules = item['spec']['rules']
  140. tls = item['spec']['tls']
  141. temp_result.append(
  142. {'name': name, 'rules': rules, 'namespace': namespace, 'tls': tls})
  143. count += 1
  144. return {'podcount': count, 'pod': temp_result}
  145. def get_all_node(self):
  146. """获取集群所有的节点"""
  147. result = self.clientInstance.list_node().to_dict()
  148. temp_result = []
  149. count = 0
  150. for item in result['items']:
  151. name = item['metadata']['name']
  152. labels = item['metadata']['labels']
  153. pod_cidr = item['spec']['pod_cidr']
  154. taints = item['spec']['taints']
  155. temp_result.append({'name': name, 'labels': labels, 'pod_cidr': pod_cidr, 'taints': taints})
  156. count += 1
  157. return {'nodecount': count, 'node': temp_result}
  158. def watch_kubernetes_resouce(self):
  159. w = watch.Watch()
  160. for event in w.stream(self.apis_api.list_namespaced_deployment, namespace='kube-system'):
  161. print(event)
  162. print(type(event))
  163. def get_all_pod_watch(self, clusterId):
  164. """"""
  165. w = watch.Watch()
  166. for event in w.stream(self.apis_api.list_namespaced_deployment, namespace='kube-system'):
  167. result_type = event.get('type')
  168. result_object = event.get('object').to_dict()
  169. result_api_version = result_object.get('api_version')
  170. result_kind = result_object.get('kind')
  171. metadata = result_object.get('metadata')
  172. podname = metadata.get('name')
  173. namespace = metadata.get('namespace')
  174. status = result_object.get('status')
  175. logger.info(
  176. f"result_type: {result_type}, result_api_version: {result_api_version}, result_kind: {result_kind}, podname: {podname}, namespace: {namespace}")
  177. cluster_obj = cmdb_models.Cluster.objects.get(id=clusterId)
  178. namespace_obj = cmdb_models.Namespace.objects.get(namespaceName=namespace, cluster=cluster_obj)
  179. filter_object = cmdb_models.KubernetesApplicationInstance.objects.filter(applicationName=podname,
  180. namespace=namespace_obj,
  181. cluster=cluster_obj)
  182. if filter_object:
  183. filter_object.update(kind=result_kind)
  184. else:
  185. cmdb_models.KubernetesApplicationInstance.objects.create(applicationName=podname, kind=result_kind,
  186. namespace=namespace_obj,
  187. cluster=cluster_obj)
  188. # w.stop()
  189. if __name__ == '__main__':
  190. apitoken = "***"
  191. apiserverUrl = "https://ip:6443"
  192. instance = ClientKubernetes(apitoken=apitoken, apiserverUrl=apiserverUrl)
  193. result = instance.get_all_pod_watch(clusterId=1)

这个程序可以单独独立出django执行