switchRs.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #!/usr/bin/python
  2. # -*- encoding:utf-8 -*-
  3. import json,pprint
  4. from prettyprinter import prettyPrinter
  5. from kscore.session import get_session
  6. def getCurrentRealserver(listenerId):
  7. param= {
  8. 'Filter.1.Name': 'listener-id',
  9. 'Filter.1.Value.1': listenerId
  10. }
  11. allServer=slbClient.describe_instances_with_listener(**param)
  12. #currentServer=allServer['RealServerSet'][0]['RegisterId']
  13. currentServer=allServer['RealServerSet'][0]
  14. return currentServer
  15. def deregisterServer(registerId):
  16. slbClient.deregister_instances_from_listener(**{'RegisterId':registerId})
  17. def registerServer(param):
  18. slbClient.register_instances_with_listener(**param)
  19. def makeSwitch(listenerId,master,backup):
  20. target = master
  21. currentRealserver=getCurrentRealserver(listenerId)
  22. if master==currentRealserver['RealServerIp']:
  23. target=backup
  24. deregisterServer(currentRealserver['RegisterId'])
  25. param={
  26. 'ListenerId': listenerId,
  27. 'RealServerIp':target,
  28. 'RealServerPort':'80',
  29. 'RealServerType':'host',
  30. 'Weight':10
  31. }
  32. registerServer(param)
  33. if __name__ == "__main__":
  34. s = get_session()
  35. region='cn-shanghai-2'
  36. slbClient = s.create_client("slb", region, use_ssl=True)
  37. listenerId = 'e4faa0c6-3644-4f46-a2d0-d152c83d29f5'
  38. masterIp='10.0.2.2'
  39. backupIp='10.0.1.4'
  40. makeSwitch(listenerId,masterIp,backupIp)