JIRA: BOTTLENECKS-29
[bottlenecks.git] / vstf / vstf / agent / env / basic / source_manager.py
1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 import os
11 import logging
12 import contextlib
13 from subprocess import CalledProcessError
14 from vstf.common.utils import check_call
15
16 LOG = logging.getLogger(__name__)
17
18
19 @contextlib.contextmanager
20 def my_chdir(file_path):
21     old_cwd = os.path.realpath(os.curdir)
22     os.chdir(file_path)
23     LOG.info("cd %s", file_path)
24     yield
25     os.chdir(old_cwd)
26     LOG.info("cd %s", old_cwd)
27
28
29 class SourceCodeManager(object):
30     def __init__(self):
31         super(SourceCodeManager, self).__init__()
32         self.base_path = '/opt/vstf/'
33
34     @staticmethod
35     def _git_pull(url, dest):
36         if not os.path.isdir(dest):
37             check_call("git clone %s %s" % (url, dest), shell=True)
38         else:
39             with my_chdir(dest):
40                 check_call("git pull", shell=True)
41
42     @staticmethod
43     def _install(dest):
44         with my_chdir(dest):
45             try:
46                 check_call("make && make install", shell=True)
47             except CalledProcessError:
48                 LOG.info("retry make again")
49                 check_call("make clean; make && make install", shell=True)
50
51     def src_install(self, cfg):
52         for key, item in cfg.items():
53             repo_type = item['repo_type']
54             url = item['url']
55             install = item['install']
56             if install is True:
57                 LOG.info("installing src repo:%s", key)
58                 if repo_type == "git":
59                     target = self.base_path + key
60                     self._git_pull(url, target)
61                     self._install(target)
62                 else:
63                     raise Exception("unsupported repo type:%s" % repo_type)
64             else:
65                 LOG.info("skip src repo:%s", key)
66         return True
67
68
69 if __name__ == '__main__':
70     import argparse
71     import json
72     parser = argparse.ArgumentParser()
73     parser.add_argument('--config', help='config file to parse')
74     args = parser.parse_args()
75     logging.basicConfig(level=logging.INFO)
76     cfg = json.load(open(args.config))
77     mgr = SourceCodeManager()
78     mgr.src_install(cfg)