#!/usr/bin/env python2 import subprocess import time import tempfile import urllib import json import sys import os import os.path as path import shutil # Used later when choosing between a dpkg or rpm based distro. def pkg_format(): with open(os.devnull, 'w') as FNULL: try: subprocess.call(['apt-get', '--help'], stdout=FNULL, stderr=FNULL) return 'apt' except: pass try: subprocess.call(['yum', '--help'], stdout=FNULL, stderr=FNULL) return 'yum' except: pass return '' print 'Determining download link...' download_manager = urllib.urlopen('https://s3.amazonaws.com/info-mongodb-com/com-download-center/compass.json') jsn = json.loads(download_manager.read()) download_manager.close() platform = sys.platform # Sometimes sys.platform gives us 'linux2' and we only want 'linux' if platform.startswith('linux'): platform = 'linux' if platform == 'linux' and os.getuid() != 0: print 'You must run this script as root.' sys.exit(1) ver = filter(lambda x: 'Stable' in x['version'], jsn['versions'])[0] links = filter(lambda x: x['os'] == platform, ver['platform']) if len(links) == 0: print 'Platform %s not supported.' % sys.platform sys.exit(1) if platform == 'linux': if pkg_format() == 'apt': links = filter(lambda x: 'Ubuntu' in x['name'], links) elif pkg_format() == 'yum': links = filter(lambda x: 'RedHat' in x['name'], links) else: print 'Unsupported Linux Distribution.' sys.exit(1) dl = links[0]['download_link'] def dl_progress(count, block_size, total_size): global start_time if count == 0: start_time = time.time() return duration = time.time() - start_time progress_size = int(count * block_size) speed = int(progress_size / (1024 * duration)) percent = int(count * block_size * 100 / total_size) sys.stdout.write("\rDownloading Compass... %d%%" % percent) sys.stdout.flush() fn, headers = urllib.urlretrieve(dl, reporthook=dl_progress) # Download progress doesn't end with a newline so add it here. print '' if platform == 'darwin': tmp = tempfile.mkdtemp() subprocess.check_call(['hdiutil', 'attach', '-mountpoint', tmp, fn]) try: apps = [f for f in os.listdir(tmp) if f.endswith('.app')] for a in apps: if path.isdir('/Applications/' + f): print 'Old version found removing...' shutil.rmtree('/Applications/' + f) print 'Copying %s to /Applications' % f shutil.copytree(path.join(tmp, f), '/Applications/' + f) # We don't really care about what errors come up here. Just log the failure # and use the finally to make sure we always unmount the dmg. except Exception as e: print e finally: subprocess.check_call(['hdiutil', 'detach', tmp]) elif platform == 'linux': if pkg_format() == 'yum': install = ['yum', 'install', '--assumeyes', fn] elif pkg_format() == 'apt': install = ['apt-get', 'install', '--yes', fn] else: print 'No available installation methods.' sys.exit(1) subprocess.call(install) else: print 'Unrecognized platform %s' % sys.platform sys.exit(1)