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.

194 lines
6.9 KiB

4 years ago
  1. #!/home/alpcentaur/ProjektA/PrototypeWebApp/venv/bin/python3.5
  2. # Copyright (c) 2009 Chris Moyer http://kopertop.blogspot.com/
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a
  5. # copy of this software and associated documentation files (the
  6. # "Software"), to deal in the Software without restriction, including
  7. # without limitation the rights to use, copy, modify, merge, publish, dis-
  8. # tribute, sublicense, and/or sell copies of the Software, and to permit
  9. # persons to whom the Software is furnished to do so, subject to the fol-
  10. # lowing conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included
  13. # in all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
  17. # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  18. # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  21. #
  22. # Tools to dump and recover an SDB domain
  23. #
  24. VERSION = "%prog version 1.0"
  25. import boto
  26. import time
  27. from boto import sdb
  28. from boto.compat import json
  29. def choice_input(options, default=None, title=None):
  30. """
  31. Choice input
  32. """
  33. if title == None:
  34. title = "Please choose"
  35. print title
  36. objects = []
  37. for n, obj in enumerate(options):
  38. print "%s: %s" % (n, obj)
  39. objects.append(obj)
  40. choice = int(raw_input(">>> "))
  41. try:
  42. choice = objects[choice]
  43. except:
  44. choice = default
  45. return choice
  46. def confirm(message="Are you sure?"):
  47. choice = raw_input("%s [yN] " % message)
  48. return choice and len(choice) > 0 and choice[0].lower() == "y"
  49. def dump_db(domain, file_name, use_json=False, sort_attributes=False):
  50. """
  51. Dump SDB domain to file
  52. """
  53. f = open(file_name, "w")
  54. if use_json:
  55. for item in domain:
  56. data = {"name": item.name, "attributes": item}
  57. print >> f, json.dumps(data, sort_keys=sort_attributes)
  58. else:
  59. doc = domain.to_xml(f)
  60. def empty_db(domain):
  61. """
  62. Remove all entries from domain
  63. """
  64. for item in domain:
  65. item.delete()
  66. def load_db(domain, file, use_json=False):
  67. """
  68. Load a domain from a file, this doesn't overwrite any existing
  69. data in the file so if you want to do a full recovery and restore
  70. you need to call empty_db before calling this
  71. :param domain: The SDB Domain object to load to
  72. :param file: The File to load the DB from
  73. """
  74. if use_json:
  75. for line in file.readlines():
  76. if line:
  77. data = json.loads(line)
  78. item = domain.new_item(data['name'])
  79. item.update(data['attributes'])
  80. item.save()
  81. else:
  82. domain.from_xml(file)
  83. def check_valid_region(conn, region):
  84. if conn is None:
  85. print 'Invalid region (%s)' % region
  86. sys.exit(1)
  87. def create_db(domain_name, region_name):
  88. """Create a new DB
  89. :param domain: Name of the domain to create
  90. :type domain: str
  91. """
  92. sdb = boto.sdb.connect_to_region(region_name)
  93. check_valid_region(sdb, region_name)
  94. return sdb.create_domain(domain_name)
  95. if __name__ == "__main__":
  96. from optparse import OptionParser
  97. parser = OptionParser(version=VERSION, usage="Usage: %prog [--dump|--load|--empty|--list|-l] [options]")
  98. # Commands
  99. parser.add_option("--dump", help="Dump domain to file", dest="dump", default=False, action="store_true")
  100. parser.add_option("--load", help="Load domain contents from file", dest="load", default=False, action="store_true")
  101. parser.add_option("--empty", help="Empty all contents of domain", dest="empty", default=False, action="store_true")
  102. parser.add_option("-l", "--list", help="List All domains", dest="list", default=False, action="store_true")
  103. parser.add_option("-c", "--create", help="Create domain", dest="create", default=False, action="store_true")
  104. parser.add_option("-a", "--all-domains", help="Operate on all domains", action="store_true", default=False, dest="all_domains")
  105. if json:
  106. parser.add_option("-j", "--use-json", help="Load/Store as JSON instead of XML", action="store_true", default=False, dest="json")
  107. parser.add_option("-s", "--sort-attibutes", help="Sort the element attributes", action="store_true", default=False, dest="sort_attributes")
  108. parser.add_option("-d", "--domain", help="Do functions on domain (may be more then one)", action="append", dest="domains")
  109. parser.add_option("-f", "--file", help="Input/Output file we're operating on", dest="file_name")
  110. parser.add_option("-r", "--region", help="Region (e.g. us-east-1[default] or eu-west-1)", default="us-east-1", dest="region_name")
  111. (options, args) = parser.parse_args()
  112. if options.create:
  113. for domain_name in options.domains:
  114. create_db(domain_name, options.region_name)
  115. exit()
  116. sdb = boto.sdb.connect_to_region(options.region_name)
  117. check_valid_region(sdb, options.region_name)
  118. if options.list:
  119. for db in sdb.get_all_domains():
  120. print db
  121. exit()
  122. if not options.dump and not options.load and not options.empty:
  123. parser.print_help()
  124. exit()
  125. #
  126. # Setup
  127. #
  128. if options.domains:
  129. domains = []
  130. for domain_name in options.domains:
  131. domains.append(sdb.get_domain(domain_name))
  132. elif options.all_domains:
  133. domains = sdb.get_all_domains()
  134. else:
  135. domains = [choice_input(options=sdb.get_all_domains(), title="No domain specified, please choose one")]
  136. #
  137. # Execute the commands
  138. #
  139. stime = time.time()
  140. if options.empty:
  141. if confirm("WARNING!!! Are you sure you want to empty the following domains?: %s" % domains):
  142. stime = time.time()
  143. for domain in domains:
  144. print "--------> Emptying %s <--------" % domain.name
  145. empty_db(domain)
  146. else:
  147. print "Canceling operations"
  148. exit()
  149. if options.dump:
  150. for domain in domains:
  151. print "--------> Dumping %s <---------" % domain.name
  152. if options.file_name:
  153. file_name = options.file_name
  154. else:
  155. file_name = "%s.db" % domain.name
  156. dump_db(domain, file_name, options.json, options.sort_attributes)
  157. if options.load:
  158. for domain in domains:
  159. print "---------> Loading %s <----------" % domain.name
  160. if options.file_name:
  161. file_name = options.file_name
  162. else:
  163. file_name = "%s.db" % domain.name
  164. load_db(domain, open(file_name, "rb"), options.json)
  165. total_time = round(time.time() - stime, 2)
  166. print "--------> Finished in %s <--------" % total_time