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