/silverlining/mgr-scripts/prepare-new-instance.py

https://bitbucket.org/ianb/silverlining/ · Python · 62 lines · 58 code · 3 blank · 1 comment · 0 complexity · 46ce9e01629dda037f61b7c215379e26 MD5 · raw file

  1. #!/usr/bin/env python
  2. import sys
  3. sys.path.insert(0, '/usr/local/share/silverlining/lib')
  4. import os
  5. import glob
  6. import time
  7. from optparse import OptionParser
  8. from silversupport import appdata
  9. parser = OptionParser(
  10. usage="%prog APP_NAME",
  11. description="""\
  12. Prepares a new directory for a new instance to be uploaded. This
  13. creates a new unique name, creates a directory, and hardlink/copies
  14. the directory over to be rsync'd over by the new app. Finally it
  15. prints the new app name for the caller to use.
  16. """)
  17. def prepare_new_site(app_name):
  18. """Creates the new directory and copies it over"""
  19. n = 0
  20. date = time.strftime('%Y-%m-%d')
  21. app_dirs = '/var/www/%s.%s_*' % (app_name, date)
  22. names = list(glob.glob(app_dirs))
  23. if not names:
  24. n = 1
  25. else:
  26. n = max(
  27. [int(name.rsplit('_', 1)[1])
  28. for name in names]) + 1
  29. app_dir = '%s.%s_%03i' % (app_name, date, n)
  30. other_instances = []
  31. print appdata.list_instances()
  32. for instance_name in appdata.list_instances():
  33. if instance_name.startswith('%s.' % app_name):
  34. other_instances.append(instance_name)
  35. if other_instances:
  36. copy_instance = sorted(other_instances)[-1]
  37. hardlink_copy(os.path.join('/var/www', copy_instance),
  38. os.path.join('/var/www', app_dir))
  39. else:
  40. os.mkdir(os.path.join('/var/www', app_dir))
  41. print 'instance_name="%s"' % app_dir
  42. def hardlink_copy(source, dest):
  43. """Copies over a tree, using hard links"""
  44. for dirpath, dirnames, filenames in os.walk(source):
  45. for filename in filenames:
  46. path = os.path.join(dirpath, filename)
  47. assert path.startswith(source)
  48. new_path = path[len(source):].lstrip('/')
  49. new_path = os.path.join(dest, new_path)
  50. if not os.path.exists(os.path.dirname(new_path)):
  51. os.makedirs(os.path.dirname(new_path))
  52. os.link(path, new_path)
  53. if __name__ == '__main__':
  54. options, args = parser.parse_args()
  55. app_name = args[0]
  56. prepare_new_site(app_name)