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.
 
 
 
 

500 lines
18 KiB

  1. #!/usr/bin/env python3
  2. from __future__ import print_function
  3. import os
  4. import sys
  5. import subprocess
  6. import getpass
  7. import json
  8. import multiprocessing
  9. import shutil
  10. import platform
  11. import warnings
  12. import datetime
  13. tmp_bench_repo = os.path.join('/', 'tmp', '.bench')
  14. tmp_log_folder = os.path.join('/', 'tmp', 'logs')
  15. execution_timestamp = datetime.datetime.utcnow()
  16. execution_day = "{:%Y-%m-%d}".format(execution_timestamp)
  17. execution_time = "{:%H:%M}".format(execution_timestamp)
  18. log_file_name = "easy-install__{0}__{1}.log".format(execution_day, execution_time.replace(':', '-'))
  19. log_path = os.path.join(tmp_log_folder, log_file_name)
  20. log_stream = sys.stdout
  21. distro_required = not ((sys.version_info.major < 3) or (sys.version_info.major == 3 and sys.version_info.minor < 5))
  22. def log(message, level=0):
  23. levels = {
  24. 0: '\033[94m', # normal
  25. 1: '\033[92m', # success
  26. 2: '\033[91m', # fail
  27. 3: '\033[93m' # warn/suggest
  28. }
  29. start = levels.get(level) or ''
  30. end = '\033[0m'
  31. print(start + message + end)
  32. def setup_log_stream(args):
  33. global log_stream
  34. sys.stderr = sys.stdout
  35. if not args.verbose:
  36. if not os.path.exists(tmp_log_folder):
  37. os.makedirs(tmp_log_folder)
  38. log_stream = open(log_path, 'w')
  39. log("Logs are saved under {0}".format(log_path), level=3)
  40. print("Install script run at {0} on {1}\n\n".format(execution_time, execution_day), file=log_stream)
  41. def check_environment():
  42. needed_environ_vars = ['LANG', 'LC_ALL']
  43. message = ''
  44. for var in needed_environ_vars:
  45. if var not in os.environ:
  46. message += "\nexport {0}=C.UTF-8".format(var)
  47. if message:
  48. log("Bench's CLI needs these to be defined!", level=3)
  49. log("Run the following commands in shell: {0}".format(message), level=2)
  50. sys.exit()
  51. def check_system_package_managers():
  52. if 'Darwin' in os.uname():
  53. if not shutil.which('brew'):
  54. raise Exception('''
  55. Please install brew package manager before proceeding with bench setup. Please run following
  56. to install brew package manager on your machine,
  57. /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  58. ''')
  59. if 'Linux' in os.uname():
  60. if not any([shutil.which(x) for x in ['apt-get', 'yum']]):
  61. raise Exception('Cannot find any compatible package manager!')
  62. def check_distribution_compatibility():
  63. dist_name, dist_version = get_distribution_info()
  64. supported_dists = {
  65. 'macos': [10.9, 10.10, 10.11, 10.12],
  66. 'ubuntu': [14, 15, 16, 18, 19, 20],
  67. 'debian': [8, 9, 10],
  68. 'centos': [7]
  69. }
  70. log("Checking System Compatibility...")
  71. if dist_name in supported_dists:
  72. if float(dist_version) in supported_dists[dist_name]:
  73. log("{0} {1} is compatible!".format(dist_name, dist_version), level=1)
  74. else:
  75. log("{0} {1} is detected".format(dist_name, dist_version), level=1)
  76. log("Install on {0} {1} instead".format(dist_name, supported_dists[dist_name][-1]), level=3)
  77. else:
  78. log("Sorry, the installer doesn't support {0}. Aborting installation!".format(dist_name), level=2)
  79. def import_with_install(package):
  80. # copied from https://discuss.influxerp.com/u/nikunj_patel
  81. # https://discuss.influxerp.com/t/easy-install-setup-guide-for-influxerp-installation-on-ubuntu-20-04-lts-with-some-modification-of-course/62375/5
  82. # need to move to top said v13 for fully python3 era
  83. import importlib
  84. try:
  85. importlib.import_module(package)
  86. except ImportError:
  87. # caveat : pip3 must be installed
  88. import pip
  89. pip.main(['install', package])
  90. finally:
  91. globals()[package] = importlib.import_module(package)
  92. def get_distribution_info():
  93. # return distribution name and major version
  94. if platform.system() == "Linux":
  95. if distro_required:
  96. current_dist = distro.linux_distribution(full_distribution_name=True)
  97. else:
  98. current_dist = platform.dist()
  99. return current_dist[0].lower(), current_dist[1].rsplit('.')[0]
  100. elif platform.system() == "Darwin":
  101. current_dist = platform.mac_ver()
  102. return "macos", current_dist[0].rsplit('.', 1)[0]
  103. def run_os_command(command_map):
  104. '''command_map is a dictionary of {'executable': command}. For ex. {'apt-get': 'sudo apt-get install -y python2.7'}'''
  105. success = True
  106. for executable, commands in command_map.items():
  107. if shutil.which(executable):
  108. if isinstance(commands, str):
  109. commands = [commands]
  110. for command in commands:
  111. returncode = subprocess.check_call(command, shell=True, stdout=log_stream, stderr=sys.stderr)
  112. success = success and (returncode == 0)
  113. return success
  114. def install_prerequisites():
  115. # pre-requisites for bench repo cloning
  116. run_os_command({
  117. 'apt-get': [
  118. 'sudo apt-get update',
  119. 'sudo apt-get install -y git build-essential python3-setuptools python3-dev libffi-dev'
  120. ],
  121. 'yum': [
  122. 'sudo yum groupinstall -y "Development tools"',
  123. 'sudo yum install -y epel-release redhat-lsb-core git python-setuptools python-devel openssl-devel libffi-devel'
  124. ]
  125. })
  126. # until psycopg2-binary is available for aarch64 (Arm 64-bit), we'll need libpq and libssl dev packages to build psycopg2 from source
  127. if platform.machine() == 'aarch64':
  128. log("Installing libpq and libssl dev packages to build psycopg2 for aarch64...")
  129. run_os_command({
  130. 'apt-get': ['sudo apt-get install -y libpq-dev libssl-dev'],
  131. 'yum': ['sudo yum install -y libpq-devel openssl-devel']
  132. })
  133. install_package('curl')
  134. install_package('wget')
  135. install_package('git')
  136. install_package('pip3', 'python3-pip')
  137. run_os_command({
  138. 'python3': "sudo -H python3 -m pip install --upgrade pip setuptools-rust"
  139. })
  140. success = run_os_command({
  141. 'python3': "sudo -H python3 -m pip install --upgrade setuptools wheel cryptography ansible~=2.8.15"
  142. })
  143. if not (success or shutil.which('ansible')):
  144. could_not_install('Ansible')
  145. def could_not_install(package):
  146. raise Exception('Could not install {0}. Please install it manually.'.format(package))
  147. def is_sudo_user():
  148. return os.geteuid() == 0
  149. def install_package(package, package_name=None):
  150. if shutil.which(package):
  151. log("{0} already installed!".format(package), level=1)
  152. else:
  153. log("Installing {0}...".format(package))
  154. package_name = package_name or package
  155. success = run_os_command({
  156. 'apt-get': ['sudo apt-get install -y {0}'.format(package_name)],
  157. 'yum': ['sudo yum install -y {0}'.format(package_name)],
  158. 'brew': ['brew install {0}'.format(package_name)]
  159. })
  160. if success:
  161. log("{0} installed!".format(package), level=1)
  162. return success
  163. could_not_install(package)
  164. def install_bench(args):
  165. # clone bench repo
  166. if not args.run_travis:
  167. clone_bench_repo(args)
  168. if not args.user:
  169. if args.production:
  170. args.user = 'influxframework'
  171. elif 'SUDO_USER' in os.environ:
  172. args.user = os.environ['SUDO_USER']
  173. else:
  174. args.user = getpass.getuser()
  175. if args.user == 'root':
  176. raise Exception('Please run this script as a non-root user with sudo privileges, but without using sudo or pass --user=USER')
  177. # Python executable
  178. dist_name, dist_version = get_distribution_info()
  179. if dist_name=='centos':
  180. args.python = 'python3.6'
  181. else:
  182. args.python = 'python3'
  183. # create user if not exists
  184. extra_vars = vars(args)
  185. extra_vars.update(influxframework_user=args.user)
  186. extra_vars.update(user_directory=get_user_home_directory(args.user))
  187. if os.path.exists(tmp_bench_repo):
  188. repo_path = tmp_bench_repo
  189. else:
  190. repo_path = os.path.join(os.path.expanduser('~'), 'bench')
  191. extra_vars.update(repo_path=repo_path)
  192. run_playbook('create_user.yml', extra_vars=extra_vars)
  193. extra_vars.update(get_passwords(args))
  194. if args.production:
  195. extra_vars.update(max_worker_connections=multiprocessing.cpu_count() * 1024)
  196. if args.version <= 10:
  197. influxframework_branch = "{0}.x.x".format(args.version)
  198. influxerp_branch = "{0}.x.x".format(args.version)
  199. else:
  200. influxframework_branch = "version-{0}".format(args.version)
  201. influxerp_branch = "version-{0}".format(args.version)
  202. # Allow override of influxframework_branch and influxerp_branch, regardless of args.version (which always has a default set)
  203. if args.influxframework_branch:
  204. influxframework_branch = args.influxframework_branch
  205. if args.influxerp_branch:
  206. influxerp_branch = args.influxerp_branch
  207. extra_vars.update(influxframework_branch=influxframework_branch)
  208. extra_vars.update(influxerp_branch=influxerp_branch)
  209. bench_name = 'influxframework-bench' if not args.bench_name else args.bench_name
  210. extra_vars.update(bench_name=bench_name)
  211. # Will install InfluxERP production setup by default
  212. if args.without_influxerp:
  213. log("Initializing bench {bench_name}:\n\tInfluxFramework Branch: {influxframework_branch}\n\tInfluxERP will not be installed due to --without-influxerp".format(bench_name=bench_name, influxframework_branch=influxframework_branch))
  214. else:
  215. log("Initializing bench {bench_name}:\n\tInfluxFramework Branch: {influxframework_branch}\n\tInfluxERP Branch: {influxerp_branch}".format(bench_name=bench_name, influxframework_branch=influxframework_branch, influxerp_branch=influxerp_branch))
  216. run_playbook('site.yml', sudo=True, extra_vars=extra_vars)
  217. if os.path.exists(tmp_bench_repo):
  218. shutil.rmtree(tmp_bench_repo)
  219. def clone_bench_repo(args):
  220. '''Clones the bench repository in the user folder'''
  221. branch = args.bench_branch or 'develop'
  222. repo_url = args.repo_url or 'https://lab.membtech.com/influxframework/bench'
  223. if os.path.exists(tmp_bench_repo):
  224. log('Not cloning already existing Bench repository at {tmp_bench_repo}'.format(tmp_bench_repo=tmp_bench_repo))
  225. return 0
  226. elif args.without_bench_setup:
  227. clone_path = os.path.join(os.path.expanduser('~'), 'bench')
  228. log('--without-bench-setup specified, clone path is: {clone_path}'.format(clone_path=clone_path))
  229. else:
  230. clone_path = tmp_bench_repo
  231. # Not logging repo_url to avoid accidental credential leak in case credential is embedded in URL
  232. log('Cloning bench repository branch {branch} into {clone_path}'.format(branch=branch, clone_path=clone_path))
  233. success = run_os_command(
  234. {'git': 'git clone --quiet {repo_url} {bench_repo} --depth 1 --branch {branch}'.format(
  235. repo_url=repo_url, bench_repo=clone_path, branch=branch)}
  236. )
  237. return success
  238. def passwords_didnt_match(context=''):
  239. log("{} passwords did not match!".format(context), level=3)
  240. def get_passwords(args):
  241. """
  242. Returns a dict of passwords for further use
  243. and creates passwords.txt in the bench user's home directory
  244. """
  245. log("Input MySQL and InfluxFramework Administrator passwords:")
  246. ignore_prompt = args.run_travis or args.without_bench_setup
  247. mysql_root_password, admin_password = '', ''
  248. passwords_file_path = os.path.join(os.path.expanduser('~' + args.user), 'passwords.txt')
  249. if not ignore_prompt:
  250. # set passwords from existing passwords.txt
  251. if os.path.isfile(passwords_file_path):
  252. with open(passwords_file_path, 'r') as f:
  253. passwords = json.load(f)
  254. mysql_root_password, admin_password = passwords['mysql_root_password'], passwords['admin_password']
  255. # set passwords from cli args
  256. if args.mysql_root_password:
  257. mysql_root_password = args.mysql_root_password
  258. if args.admin_password:
  259. admin_password = args.admin_password
  260. # prompt for passwords
  261. pass_set = True
  262. while pass_set:
  263. # mysql root password
  264. if not mysql_root_password:
  265. mysql_root_password = getpass.unix_getpass(prompt='Please enter mysql root password: ')
  266. conf_mysql_passwd = getpass.unix_getpass(prompt='Re-enter mysql root password: ')
  267. if mysql_root_password != conf_mysql_passwd or mysql_root_password == '':
  268. passwords_didnt_match("MySQL")
  269. mysql_root_password = ''
  270. continue
  271. # admin password, only needed if we're also creating a site
  272. if not admin_password and not args.without_site:
  273. admin_password = getpass.unix_getpass(prompt='Please enter the default Administrator user password: ')
  274. conf_admin_passswd = getpass.unix_getpass(prompt='Re-enter Administrator password: ')
  275. if admin_password != conf_admin_passswd or admin_password == '':
  276. passwords_didnt_match("Administrator")
  277. admin_password = ''
  278. continue
  279. elif args.without_site:
  280. log("Not creating a new site due to --without-site")
  281. pass_set = False
  282. else:
  283. mysql_root_password = admin_password = 'travis'
  284. passwords = {
  285. 'mysql_root_password': mysql_root_password,
  286. 'admin_password': admin_password
  287. }
  288. if not ignore_prompt:
  289. with open(passwords_file_path, 'w') as f:
  290. json.dump(passwords, f, indent=1)
  291. log('Passwords saved at ~/passwords.txt')
  292. return passwords
  293. def get_extra_vars_json(extra_args):
  294. # We need to pass production as extra_vars to the playbook to execute conditionals in the
  295. # playbook. Extra variables can passed as json or key=value pair. Here, we will use JSON.
  296. json_path = os.path.join('/', 'tmp', 'extra_vars.json')
  297. extra_vars = dict(list(extra_args.items()))
  298. with open(json_path, mode='w') as j:
  299. json.dump(extra_vars, j, indent=1, sort_keys=True)
  300. return ('@' + json_path)
  301. def get_user_home_directory(user):
  302. # Return home directory /home/USERNAME or anything else defined as home directory in
  303. # passwd for user.
  304. return os.path.expanduser('~'+user)
  305. def run_playbook(playbook_name, sudo=False, extra_vars=None):
  306. args = ['ansible-playbook', '-c', 'local', playbook_name , '-vvvv']
  307. if extra_vars:
  308. args.extend(['-e', get_extra_vars_json(extra_vars)])
  309. if sudo:
  310. user = extra_vars.get('user') or getpass.getuser()
  311. args.extend(['--become', '--become-user={0}'.format(user)])
  312. if os.path.exists(tmp_bench_repo):
  313. cwd = tmp_bench_repo
  314. else:
  315. cwd = os.path.join(os.path.expanduser('~'), 'bench')
  316. playbooks_locations = [os.path.join(cwd, 'bench', 'playbooks'), os.path.join(cwd, 'playbooks')]
  317. playbooks_folder = [x for x in playbooks_locations if os.path.exists(x)][0]
  318. success = subprocess.check_call(args, cwd=playbooks_folder, stdout=log_stream, stderr=sys.stderr)
  319. return success
  320. def setup_script_requirements():
  321. if distro_required:
  322. install_package('pip3', 'python3-pip')
  323. import_with_install('distro')
  324. def parse_commandline_args():
  325. import argparse
  326. parser = argparse.ArgumentParser(description='InfluxFramework Installer')
  327. # Arguments develop and production are mutually exclusive both can't be specified together.
  328. # Hence, we need to create a group for discouraging use of both options at the same time.
  329. args_group = parser.add_mutually_exclusive_group()
  330. args_group.add_argument('--develop', dest='develop', action='store_true', default=False, help='Install developer setup')
  331. args_group.add_argument('--production', dest='production', action='store_true', default=False, help='Setup Production environment for bench')
  332. parser.add_argument('--site', dest='site', action='store', default='site1.local', help='Specify name for your first InfluxERP site')
  333. parser.add_argument('--without-site', dest='without_site', action='store_true', default=False, help='Do not create a new site')
  334. parser.add_argument('--verbose', dest='verbose', action='store_true', default=False, help='Run the script in verbose mode')
  335. parser.add_argument('--user', dest='user', help='Install influxframework-bench for this user')
  336. parser.add_argument('--bench-branch', dest='bench_branch', help='Clone a particular branch of bench repository')
  337. parser.add_argument('--repo-url', dest='repo_url', help='Clone bench from the given url')
  338. parser.add_argument('--influxframework-repo-url', dest='influxframework_repo_url', action='store', default='https://lab.membtech.com/influxframework/influxframework', help='Clone influxframework from the given url')
  339. parser.add_argument('--influxframework-branch', dest='influxframework_branch', action='store', help='Clone a particular branch of influxframework')
  340. parser.add_argument('--influxerp-repo-url', dest='influxerp_repo_url', action='store', default='https://lab.membtech.com/influxframework/influxerp', help='Clone influxerp from the given url')
  341. parser.add_argument('--influxerp-branch', dest='influxerp_branch', action='store', help='Clone a particular branch of influxerp')
  342. parser.add_argument('--without-influxerp', dest='without_influxerp', action='store_true', default=False, help='Prevent fetching InfluxERP')
  343. # direct provision to install versions
  344. parser.add_argument('--version', dest='version', action='store', default=13, type=int, help='Clone particular version of influxframework and influxerp')
  345. # To enable testing of script using Travis, this should skip the prompt
  346. parser.add_argument('--run-travis', dest='run_travis', action='store_true', default=False, help=argparse.SUPPRESS)
  347. parser.add_argument('--without-bench-setup', dest='without_bench_setup', action='store_true', default=False, help=argparse.SUPPRESS)
  348. # whether to overwrite an existing bench
  349. parser.add_argument('--overwrite', dest='overwrite', action='store_true', default=False, help='Whether to overwrite an existing bench')
  350. # set passwords
  351. parser.add_argument('--mysql-root-password', dest='mysql_root_password', help='Set mysql root password')
  352. parser.add_argument('--mariadb-version', dest='mariadb_version', default='10.4', help='Specify mariadb version')
  353. parser.add_argument('--admin-password', dest='admin_password', help='Set admin password')
  354. parser.add_argument('--bench-name', dest='bench_name', help='Create bench with specified name. Default name is influxframework-bench')
  355. # Python interpreter to be used
  356. parser.add_argument('--python', dest='python', default='python3', help=argparse.SUPPRESS)
  357. # LXC Support
  358. parser.add_argument('--container', dest='container', default=False, action='store_true', help='Use if you\'re creating inside LXC')
  359. args = parser.parse_args()
  360. return args
  361. if __name__ == '__main__':
  362. if sys.version[0] == '2':
  363. if not os.environ.get('CI'):
  364. if not raw_input("It is recommended to run this script with Python 3\nDo you still wish to continue? [Y/n]: ").lower() == "y":
  365. sys.exit()
  366. try:
  367. from distutils.spawn import find_executable
  368. except ImportError:
  369. try:
  370. subprocess.check_call('pip install --upgrade setuptools')
  371. except subprocess.CalledProcessError:
  372. print("Install distutils or use Python3 to run the script")
  373. sys.exit(1)
  374. shutil.which = find_executable
  375. if not is_sudo_user():
  376. log("Please run this script as a non-root user with sudo privileges", level=3)
  377. sys.exit()
  378. args = parse_commandline_args()
  379. with warnings.catch_warnings():
  380. warnings.simplefilter("ignore")
  381. setup_log_stream(args)
  382. install_prerequisites()
  383. setup_script_requirements()
  384. check_distribution_compatibility()
  385. check_system_package_managers()
  386. check_environment()
  387. install_bench(args)
  388. log("Bench + InfluxFramework + InfluxERP has been successfully installed!")