You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DeployHelpers.py 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #coding=UTF-8
  2. ### Helper class for wildfly deployments. ###
  3. # Related files $HOME/.deploy-url $HOME/.deploy-credentials
  4. import sys, json
  5. try:
  6. import requests
  7. except Exception as e:
  8. print("DeployHelpers depends on requests library. Install it with `pip install requests`")
  9. sys.exit(1)
  10. from requests.auth import HTTPDigestAuth
  11. from os.path import join, expanduser, basename
  12. from BuildHelpers import parser, getArgs
  13. from time import sleep
  14. group = parser.add_mutually_exclusive_group(required=True)
  15. group.add_argument("--deploy", dest="deploy_mode", help="Deploy to a remote Wildfly instance", action="store_true")
  16. group.add_argument("--docker", dest="deploy_mode", help="Wrap results into a Docker image", action="store_false")
  17. parser.add_argument("--deployUrl", help="Wildfly management URL to use with --deploy")
  18. parser.add_argument("--deployUser", help="Deployment user to use with --deploy", default=None)
  19. parser.add_argument("--deployPass", help="Deployment password to use with --deploy", default=None)
  20. serverUp = None
  21. def testServer():
  22. global serverUp
  23. if serverUp is not None:
  24. return serverUp
  25. if getUrl() is None:
  26. print("No deploy URL provided")
  27. serverUp = False
  28. return serverUp
  29. print("Checking server status")
  30. i = 0
  31. request = {"operation" : "read-attribute", "name" : "server-state"}
  32. serverUp = False
  33. while not serverUp and i < 2:
  34. try:
  35. print("Trying on url %s" % (getUrl()))
  36. result = doPostJson(url=getUrl(), auth=getAuth(), data=json.dumps(request))
  37. response = result.json()
  38. if "outcome" not in response or response["outcome"] != "success":
  39. # Failure
  40. raise Exception(response)
  41. elif "result" not in response or response["result"] != "running":
  42. # Another failure
  43. raise Exception(response)
  44. # All OK
  45. serverUp = True
  46. print("Got server connection.")
  47. except Exception as e:
  48. print("Exception while checking server state: ", e)
  49. print("Server connection failed, retrying in 5 seconds.")
  50. i = i + 1
  51. sleep(5)
  52. return serverUp
  53. # Helper for handling the full deployment
  54. # name should end with .war
  55. def deployWar(warFile, name=None):
  56. if not testServer():
  57. raise Exception("Server not up. Skipping deployment.")
  58. return
  59. if name is None:
  60. name = basename(warFile).replace('.war', "-%s.war" % (getArgs().version.split('-')[0]))
  61. print("Deploying to context %s" % (name[:-4]))
  62. # Undeploy/Remove old version if needed
  63. if deploymentExists(name):
  64. removeDeployment(name)
  65. # Do upload war file
  66. hash = doUploadWarFile(warFile)
  67. # Do deployment under name
  68. doDeploy(hash, name)
  69. def deploymentExists(name):
  70. # Deployment existence check data
  71. data = {"operation" : "read-attribute", "name": "runtime-name", "address": [{"deployment" : name}]}
  72. result = doPostJson(url=getUrl(), auth=getAuth(), data=json.dumps(data))
  73. return result.json()["outcome"] == "success"
  74. def doDeploy(hash, name):
  75. # Deployment data
  76. data = {}
  77. data["content"] = [{"hash" : hash}]
  78. data["address"] = [{"deployment" : name}]
  79. data["operation"] = "add"
  80. data["enabled"] = True
  81. return doPostJson(data=json.dumps(data), auth=getAuth(), url=getUrl())
  82. # Helper for adding Content-Type to headers
  83. def doPostJson(**kwargs):
  84. r = requests.post(headers={"Content-Type" : "application/json"}, **kwargs)
  85. # Wildfly gives code 500 when asking for a non-existent deployment
  86. if r.status_code == requests.codes.ok or r.status_code == 500:
  87. return r
  88. r.raise_for_status()
  89. def doUploadWarFile(warFile):
  90. # Upload request, just see the outcome
  91. result = requests.post("%s/add-content" % (getUrl()), files={"file" : open(warFile, 'rb')}, auth=getAuth()).json()
  92. if "outcome" not in result or result["outcome"] != "success":
  93. raise Exception("File upload failed.", result)
  94. return result["result"]
  95. # Method for removing an existing deployment
  96. def removeDeployment(name):
  97. data = {}
  98. data["address"] = [{"deployment" : name}]
  99. for i in ["undeploy", "remove"]:
  100. print("%s old deployment of %s" % (i, name))
  101. data["operation"] = i
  102. doPostJson(data=json.dumps(data), auth=getAuth(), url=getUrl())
  103. # Read credentials file and return a HTTPDigestAuth object
  104. def getAuth():
  105. args = getArgs()
  106. return HTTPDigestAuth(args.deployUser, args.deployPass)
  107. # Read the deploy url file and return the url
  108. def getUrl():
  109. return getArgs().deployUrl