ppctl.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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, random
  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('DRONE_REPO_NAME')
  20. JNLP_STORAGE_CLASS = os.getenv('JNLP_STORAGE_CLASS')
  21. JNLP_DOMAIN = os.getenv('JNLP_DOMAIN')
  22. JNLP_CONTROL = os.getenv('JNLP_CONTROL')
  23. JNLP_REPLICAS = os.getenv('JNLP_REPLICAS')
  24. JNLP_STORAGE_CAPACITY = os.getenv('JNLP_STORAGE_CAPACITY')
  25. JNLP_MOUNT_PATH = os.getenv('JNLP_MOUNT_PATH')
  26. JNLP_SVC_MODE = os.getenv('JNLP_SVC_MODE')
  27. NGINX_SVC = str(JNLP_ENV) + '/' + str(JNLP_CONTROL_NAME) + '-svc:' + str(JNLP_CONTAINER_PORT)
  28. NGINX_PORT = os.getenv('JNLP_CONTAINER_PORT')
  29. RECORD_NAME = os.getenv('JNLP_ENV') + "-" + os.getenv('DRONE_REPO_NAME')
  30. INGRESS_LIST = ["10.26.30.12", "10.26.29.54", "10.26.30.102", "10.26.30.13"]
  31. NGINX_RECORD_IP = random.sample(INGRESS_LIST, 1)[0]
  32. # 生成deploy.yaml文件
  33. def deployYamlCreate():
  34. tmpctl = '''
  35. config=`env|grep JNLP`
  36. template=`cat ./deploy-tmp.yaml`
  37. printf "$config\ncat << EOF\n$template\nEOF" | bash > ./deploy.yaml
  38. '''
  39. f1 = open("tempshell.sh","w")
  40. f1.writelines(tmpctl)
  41. f1.close()
  42. status,output = commands.getstatusoutput("sh tempshell.sh && rm -f tempshell.sh")
  43. print("code:" + str(status) + str(output) + "; create deploy.yaml success !!!")
  44. return status,output
  45. # 生成Dockerfile文件
  46. def DockerfileCreate():
  47. tmp = '''
  48. onfig=`env|grep JNLP`
  49. template=`cat ./Dockerfile`
  50. printf "$config\ncat << EOF\n$template\nEOF" | bash > ./Dockerfile
  51. '''
  52. f2 = open("tmp.sh","w")
  53. f2.writelines(tmp)
  54. f2.close()
  55. status,output = commands.getstatusoutput("sh tmp.sh && rm -f tmp.sh")
  56. print("code:" + str(status) + str(output) + "; create Dockerfile success !!!")
  57. return
  58. # 更新haproxy configmap.json配置文件,生成TCP服务转发记录
  59. def updateConfigMap(file):
  60. if JNLP_SVC_MODE == "tcp":
  61. data = {}
  62. data[NGINX_PORT] = NGINX_SVC
  63. status, output = commands.getstatusoutput("kubectl get cm tcp-services -n ingress-nginx -o=json")
  64. tempdict = eval(output)
  65. tempdict['data'][NGINX_PORT] = NGINX_SVC
  66. newdata = tempdict['data']
  67. print(newdata,status)
  68. old_str = "CMDATA"
  69. new_str = str(newdata).replace("'",'"')
  70. with open(file, "r") as f1,open("%s.bak" % file, "w" ) as f2:
  71. for line in f1:
  72. if old_str in line:
  73. line = line.replace(old_str, new_str)
  74. f2.write(line)
  75. os.remove(file)
  76. os.rename("%s.bak" % file, file)
  77. cmStatus = "1"
  78. else:
  79. print("****** Nginx Tcp Services Configmap.json Do Not Update ******")
  80. cmStatus = "0"
  81. return cmStatus
  82. # 部署应用到kubernetes平台
  83. def deployToKube():
  84. cmStatus = updateConfigMap("configmap.json")
  85. appStatus = commands.getoutput("kubectl get sts $JNLP_CONTROL_NAME -n $JNLP_NAMESPACE|grep $JNLP_CONTROL_NAME|wc -l")
  86. if appStatus == "1" and cmStatus == "1":
  87. print("Warning:" + JNLP_CONTROL_NAME + " is already, i will update it and update nginx tcp proxy !!!")
  88. apply_out = commands.getoutput("kubectl apply -f ./deploy.yaml && kubectl apply -f ./configmap.json")
  89. print("===>>> kubectl apply output <<<===")
  90. print(apply_out)
  91. elif appStatus == "1" and cmStatus == "0":
  92. print("Warning:" + JNLP_CONTROL_NAME + " is already, i will update it !!!")
  93. apply_out = commands.getoutput("kubectl apply -f ./deploy.yaml")
  94. print("===>>> kubectl apply output <<<===")
  95. print(apply_out)
  96. elif appStatus != "1" and cmStatus == "1":
  97. apply_out = commands.getoutput("kubectl apply -f ./deploy.yaml && kubectl apply -f ./configmap.json")
  98. print("===>>> kubectl apply output <<<===")
  99. print(apply_out)
  100. print("===>>> apply is successfull <<<===")
  101. else:
  102. apply_out = commands.getoutput("kubectl apply -f ./deploy.yaml")
  103. print("===>>> kubectl apply output <<<===")
  104. print(apply_out)
  105. print("===>>> apply app successfull <<<===")
  106. return
  107. # 部署应用状态获取
  108. def deployStatus():
  109. kubeconfig = config.kube_config.load_kube_config(config_file="/root/.kube/config")
  110. appsv1_api_instance = client.AppsV1Api(kubeconfig)
  111. namespace = JNLP_ENV
  112. stsname = JNLP_CONTROL_NAME
  113. pretty = "true"
  114. for x in range(20):
  115. try:
  116. sts_response = appsv1_api_instance.read_namespaced_stateful_set_status(stsname, namespace, pretty=pretty)
  117. if sts_response.status.replicas == sts_response.status.ready_replicas :
  118. print("===>>> " +stsname + " is RUNNING <<<===")
  119. chk_status = 1
  120. break
  121. else:
  122. if x < 20:
  123. time.sleep(15)
  124. else:
  125. chk_status = 0
  126. print(stsname + " status check fail !!! , Please contact kubernetes systen administrator")
  127. except ApiException as e:
  128. print("Exception when calling CoreV1Api->list_namespaced_pod: %s\n" % e)
  129. return chk_status
  130. # DNS解析
  131. # 域名由jenkins项目名+命名空间+dns域组合而成
  132. # 如果域名已存在,不会再更新
  133. def dnsAllocation():
  134. if JNLP_INGRESS == "nginx":
  135. httpClient = httplib.HTTPConnection("opsadmin.evbj.easou.com", 80, timeout=30)
  136. headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
  137. 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})
  138. httpClient.request("POST", "/dns/dnsapi/?token=c2d1856be235a3207cd03b6f4d3c4094", params, headers)
  139. response = httpClient.getresponse().read()
  140. jstr = json.loads(response)
  141. nsStatus = jstr['status']
  142. print(NGINX_RECORD_IP)
  143. if nsStatus == "-501":
  144. print(JNLP_ENV + "-" + JNLP_CONTROL_NAME + JNLP_DOMAIN + " is already exist")
  145. elif nsStatus == "0":
  146. httpClient = httplib.HTTPConnection("opsadmin.evbj.easou.com", 80, timeout=30)
  147. httpClient.request("POST", "/dns/mkconfig/?token=c2d1856be235a3207cd03b6f4d3c4094")
  148. response = httpClient.getresponse().read()
  149. jstr = json.loads(response)
  150. upStatus = jstr['status']
  151. print(JNLP_ENV + "-" + JNLP_CONTROL_NAME + JNLP_DOMAIN + " " +upStatus + " add successfull !!!")
  152. else:
  153. print("*****Please contact DNS systen administrator*****")
  154. else :
  155. print(">>> Ingress error, Only nginx !!! <<<")
  156. return
  157. def main(argv=None):
  158. if argv is None:
  159. args = sys.argv[1:]
  160. for opt_name in args :
  161. if opt_name in ('-a','--apply'):
  162. print("===>>> deploy app to kubernetes <<<===")
  163. deployToKube()
  164. time.sleep(10)
  165. sys.exit()
  166. if opt_name in ('-b','--build'):
  167. print("===>>> create deploy.yaml <<<===")
  168. deployYamlCreate()
  169. sys.exit()
  170. if opt_name in ('-c','--check'):
  171. print("===>>> app status check <<<===")
  172. deployStatus()
  173. sys.exit()
  174. if opt_name in ('-d','--dns'):
  175. print("===>>> update dns resolve <<<===")
  176. dnsAllocation()
  177. sys.exit()
  178. return
  179. if __name__ == "__main__":
  180. main()