ppctl.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. from __future__ import print_function
  4. import os
  5. import commands
  6. import httplib, urllib
  7. import json
  8. import time
  9. from kubernetes.client.rest import ApiException
  10. from pprint import pprint
  11. from kubernetes import client, config
  12. import sys, getopt
  13. JNLP_ENV = os.getenv('JNLP_ENV')
  14. JNLP_TAG = os.getenv('JNLP_TAG')
  15. JNLP_CONTAINER_PORT = os.getenv('JNLP_CONTAINER_PORT')
  16. JNLP_WAR = os.getenv('JNLP_WAR')
  17. JNLP_INGRESS = os.getenv('JNLP_INGRESS')
  18. JNLP_IMAGE = os.getenv('JNLP_IMAGE')
  19. JNLP_CONTROL_NAME = os.getenv('JNLP_CONTROL_NAME')
  20. JNLP_STORAGE_CLASS = os.getenv('JNLP_STORAGE_CLASS')
  21. JNLP_HUB = os.getenv('JNLP_HUB')
  22. JNLP_DOMAIN = os.getenv('JNLP_DOMAIN')
  23. JNLP_CONTROL = os.getenv('JNLP_CONTROL')
  24. JNLP_REPLICAS = os.getenv('JNLP_REPLICAS')
  25. JNLP_STORAGE_CAPACITY = os.getenv('JNLP_STORAGE_CAPACITY')
  26. JNLP_MOUNT_PATH = os.getenv('JNLP_MOUNT_PATH')
  27. JNLP_SVC_MODE = os.getenv('JNLP_SVC_MODE')
  28. NGINX_SVC = str(JNLP_ENV) + '/' + str(JNLP_CONTROL_NAME) + '-svc:' + str(JNLP_CONTAINER_PORT)
  29. NGINX_PORT = JNLP_CONTAINER_PORT
  30. RECORD_NAME = os.getenv('JNLP_ENV') + "-" + os.getenv('JNLP_CONTROL_NAME')
  31. NGINX_RECORD_IP = "10.26.30.12"
  32. # 定义nacos配置中心地址
  33. def httpGet(url):
  34. conn=httplib.HTTPConnection(host='10.26.32.40', port=8848, strict=False, timeout=30)
  35. conn.request(method='GET',url=url)
  36. content = conn.getresponse().read()
  37. return content
  38. # 生成deployment-template.yaml模版文件
  39. def deployGenerate(filename,url):
  40. f = open(filename,"w")
  41. content = httpGet(url)
  42. f.writelines(content)
  43. f.close()
  44. return 1
  45. # 生成deploy.yaml文件
  46. def deployYamlCreate():
  47. tmpctl = '''
  48. config=`env|grep JNLP`
  49. template=`cat ./deploy-tmp.yaml`
  50. printf "$config\ncat << EOF\n$template\nEOF" | bash > ./deploy.yaml
  51. '''
  52. f1 = open("tempshell.sh","w")
  53. f1.writelines(tmpctl)
  54. f1.close()
  55. status,output = commands.getstatusoutput("sh tempshell.sh && rm -f tempshell.sh")
  56. print("code:" + str(status) + str(output) + "; create deploy.yaml success !!!")
  57. return status,output
  58. # 生成Dockerfile文件
  59. def DockerfileCreate():
  60. tmp = '''
  61. onfig=`env|grep JNLP`
  62. template=`cat ./Dockerfile`
  63. printf "$config\ncat << EOF\n$template\nEOF" | bash > ./Dockerfile
  64. '''
  65. f2 = open("tmp.sh","w")
  66. f2.writelines(tmp)
  67. f2.close()
  68. status,output = commands.getstatusoutput("sh tmp.sh && rm -f tmp.sh")
  69. print("code:" + str(status) + str(output) + "; create Dockerfile success !!!")
  70. return
  71. # 更新haproxy configmap.json配置文件,生成TCP服务转发记录
  72. def updateConfigMap(file):
  73. if JNLP_SVC_MODE == "tcp":
  74. data = {}
  75. data[NGINX_PORT] = NGINX_SVC
  76. status, output = commands.getstatusoutput("kubectl get cm tcp-services -n ingress-nginx -o=json")
  77. tempdict = eval(output)
  78. tempdict['data'][NGINX_PORT] = NGINX_SVC
  79. newdata = tempdict['data']
  80. print(newdata,status)
  81. old_str = "CMDATA"
  82. new_str = str(newdata).replace("'",'"')
  83. with open(file, "r") as f1,open("%s.bak" % file, "w" ) as f2:
  84. for line in f1:
  85. if old_str in line:
  86. line = line.replace(old_str, new_str)
  87. f2.write(line)
  88. os.remove(file)
  89. os.rename("%s.bak" % file, file)
  90. cmStatus = "1"
  91. else:
  92. print("****** Nginx Tcp Services Configmap.json Do Not Update ******")
  93. cmStatus = "0"
  94. return cmStatus
  95. # 部署应用到kubernetes平台
  96. def deployToKube():
  97. cmStatus = updateConfigMap("configmap.json")
  98. appStatus = commands.getoutput("kubectl get sts $JNLP_CONTROL_NAME -n $JNLP_NAMESPACE|grep $JNLP_CONTROL_NAME|wc -l")
  99. if appStatus == "1" and cmStatus == "1":
  100. #print("Warning:" + JNLP_CONTROL_NAME + " is already, i will delete it and create new one !!!")
  101. #del_out = commands.getoutput("kubectl delete -f ./deploy.yaml")
  102. apply_out = commands.getoutput("kubectl apply -f ./deploy.yaml && kubectl apply -f ./configmap.json")
  103. #print("===>>> kubectl delete output <<<===")
  104. #print(del_out)
  105. print("===>>> kubectl apply output <<<===")
  106. print(apply_out)
  107. elif appStatus == "1" and cmStatus == "0":
  108. #print("Warning:" + JNLP_CONTROL_NAME + " is already, i will delete it and create new one !!!")
  109. #del_out = commands.getoutput("kubectl delete -f ./deploy.yaml")
  110. apply_out = commands.getoutput("kubectl apply -f ./deploy.yaml")
  111. #print("===>>> kubectl delete output <<<===")
  112. #print(del_out)
  113. print("===>>> kubectl apply output <<<===")
  114. print(apply_out)
  115. elif appStatus != "1" and cmStatus == "1":
  116. apply_out = commands.getoutput("kubectl apply -f ./deploy.yaml && kubectl apply -f ./configmap.json")
  117. print("===>>> kubectl apply output <<<===")
  118. print(apply_out)
  119. print("===>>> apply is successfull <<<===")
  120. else:
  121. apply_out = commands.getoutput("kubectl apply -f ./deploy.yaml")
  122. print("===>>> kubectl apply output <<<===")
  123. print(apply_out)
  124. print("===>>> apply is successfull <<<===")
  125. return
  126. # 部署应用状态获取
  127. def deployStatus():
  128. kubeconfig = config.kube_config.load_kube_config(config_file="/root/.kube/config")
  129. # create an instance of the API class
  130. # corev1_api_instance = client.CoreV1Api(kubeconfig)
  131. appsv1_api_instance = client.AppsV1Api(kubeconfig)
  132. namespace = JNLP_ENV
  133. stsname = JNLP_CONTROL_NAME
  134. # podname = "op-scofield-demo001-0"
  135. pretty = "true"
  136. for x in range(20):
  137. try:
  138. sts_response = appsv1_api_instance.read_namespaced_stateful_set_status(stsname, namespace, pretty=pretty)
  139. if sts_response.status.replicas == sts_response.status.ready_replicas :
  140. print("===>>> " +stsname + " is RUNNING <<<===")
  141. chk_status = 1
  142. break
  143. else:
  144. if x < 20:
  145. time.sleep(15)
  146. else:
  147. chk_status = 0
  148. print(stsname + " status check fail !!! , Please contact kubernetes systen administrator")
  149. except ApiException as e:
  150. print("Exception when calling CoreV1Api->list_namespaced_pod: %s\n" % e)
  151. return chk_status
  152. # DNS解析
  153. # 域名由jenkins项目名+命名空间+dns域组合而成
  154. # 如果域名已存在,不会再更新
  155. def dnsAllocation():
  156. if JNLP_INGRESS == "nginx":
  157. httpClient = httplib.HTTPConnection("10.26.31.137", 80, timeout=30)
  158. headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
  159. params = urllib.urlencode({'method': 'add', 'type': 'record', 'domain_id': 24, 'record_type': 'A', 'record_name': RECORD_NAME ,'record_ip': NGINX_RECORD_IP , 'record_ttl': 180})
  160. httpClient.request("POST", "/dns/dnsapi/?token=c2d1856be235a3207cd03b6f4d3c4094", params, headers)
  161. response = httpClient.getresponse().read()
  162. jstr = json.loads(response)
  163. nsStatus = jstr['status']
  164. if nsStatus == "-501":
  165. print(JNLP_ENV + "-" + JNLP_CONTROL_NAME + JNLP_DOMAIN + " is already exist")
  166. elif nsStatus == "0":
  167. httpClient = httplib.HTTPConnection("10.26.31.137", 80, timeout=30)
  168. httpClient.request("POST", "/dns/mkconfig/?token=c2d1856be235a3207cd03b6f4d3c4094")
  169. response = httpClient.getresponse().read()
  170. jstr = json.loads(response)
  171. upStatus = jstr['status']
  172. print(JNLP_ENV + "-" + JNLP_CONTROL_NAME + JNLP_DOMAIN + " " +upStatus + " add successfull !!!")
  173. else:
  174. print("*****Please contact DNS systen administrator*****")
  175. else :
  176. print(">>> Ingress error, Only nginx !!! <<<")
  177. return
  178. def main(argv=None):
  179. if argv is None:
  180. args = sys.argv[1:]
  181. for opt_name in args :
  182. if opt_name in ('-a','--apply'):
  183. print("===>>> deploy app to kubernetes <<<===")
  184. deployToKube()
  185. time.sleep(10)
  186. sys.exit()
  187. if opt_name in ('-b','--build'):
  188. print("===>>> create deploy.yaml <<<===")
  189. deployYamlCreate()
  190. sys.exit()
  191. if opt_name in ('-c','--check'):
  192. print("===>>> app status check <<<===")
  193. deployStatus()
  194. sys.exit()
  195. if opt_name in ('-d','--dns'):
  196. print("===>>> update dns resolve <<<===")
  197. dnsAllocation()
  198. sys.exit()
  199. return
  200. if __name__ == "__main__":
  201. main()