nexthop.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # /etc/keepalived/nexthop.py
  4. import os
  5. import time
  6. import json
  7. import sys
  8. from kscore.session import get_session
  9. ##################需修改部分Begin####################
  10. region = 'cn-beijing-6' # region code
  11. vpcId = '1858a08a-6cc9-4278-8d0c-d536f441fe8e' # vpcId
  12. ks_access_key_id = '您的ak'
  13. ks_secret_access_key = '您的sk'
  14. DestinationCidrBlock = '172.18.0.253/32' # 修改为VIP
  15. thisInstanceId = '1cf963ff-7847-4859-8462-5405f0facc1d' # 当前主机的Id
  16. ##################需修改部分End######################
  17. log = open('/var/log/keepalived.log', 'a+')
  18. # state_file = open('/var/keepalived/state', 'r')
  19. def get_now_time():
  20. return time.strftime('[%Y-%m-%d %H:%M:%S]', time.localtime(time.time())) + '[pid' + str(os.getpid()) + ']'
  21. def log_write(message=''):
  22. log.write(get_now_time() + " " + str(message) + "\n")
  23. def find_route():
  24. for route in vpcClient.describe_routes()['RouteSet']:
  25. if route['DestinationCidrBlock'] == DestinationCidrBlock:
  26. log_write('an existing route found')
  27. return route['RouteId']
  28. log_write('route not found')
  29. def migrate_vip():
  30. param = {
  31. 'VpcId': vpcId,
  32. 'DestinationCidrBlock': DestinationCidrBlock,
  33. 'RouteType': 'Host',
  34. 'InstanceId': thisInstanceId
  35. }
  36. log_write("migrating vip to another host.")
  37. time.sleep(0.5)
  38. r = find_route()
  39. if r:
  40. print(vpcClient.delete_route(RouteId=r))
  41. log_write(" now change the nexthop of vip to this host." + thisInstanceId)
  42. if vpcClient.create_route(**param):
  43. log_write('migrating vip success')
  44. def print_help():
  45. log_write('''
  46. ./nexthop.py migrate
  47. migrate your vip
  48. ''')
  49. if __name__ == '__main__':
  50. s = get_session()
  51. s.set_credentials(ks_access_key_id, ks_secret_access_key)
  52. vpcClient = s.create_client("vpc", region, use_ssl=True)
  53. if len(sys.argv) == 1:
  54. log_write("nexthop.py: parameter num is 0")
  55. print_help()
  56. elif sys.argv[1] == 'migrate':
  57. migrate_vip()
  58. log_write()
  59. else:
  60. log_write("nexthop.py: misMatched parameter")
  61. print_help()