remote.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Remote Builds tool using rsync+ssh
  4. __author__ = "Jérôme Carretero <cJ-waf@zougloub.eu>"
  5. __copyright__ = "Jérôme Carretero, 2013"
  6. """
  7. Simple Remote Builds
  8. ********************
  9. This tool is an *experimental* tool (meaning, do not even try to pollute
  10. the waf bug tracker with bugs in here, contact me directly) providing simple
  11. remote builds.
  12. It uses rsync and ssh to perform the remote builds.
  13. It is intended for performing cross-compilation on platforms where
  14. a cross-compiler is either unavailable (eg. MacOS, QNX) a specific product
  15. does not exist (eg. Windows builds using Visual Studio) or simply not installed.
  16. This tool sends the sources and the waf script to the remote host,
  17. and commands the usual waf execution.
  18. There are alternatives to using this tool, such as setting up shared folders,
  19. logging on to remote machines, and building on the shared folders.
  20. Electing one method or another depends on the size of the program.
  21. Usage
  22. =====
  23. 1. Set your wscript file so it includes a list of variants,
  24. e.g.::
  25. from waflib import Utils
  26. top = '.'
  27. out = 'build'
  28. variants = [
  29. 'linux_64_debug',
  30. 'linux_64_release',
  31. 'linux_32_debug',
  32. 'linux_32_release',
  33. ]
  34. from waflib.extras import remote
  35. def options(opt):
  36. # normal stuff from here on
  37. opt.load('compiler_c')
  38. def configure(conf):
  39. if not conf.variant:
  40. return
  41. # normal stuff from here on
  42. conf.load('compiler_c')
  43. def build(bld):
  44. if not bld.variant:
  45. return
  46. # normal stuff from here on
  47. bld(features='c cprogram', target='app', source='main.c')
  48. 2. Build the waf file, so it includes this tool, and put it in the current
  49. directory
  50. .. code:: bash
  51. ./waf-light --tools=remote
  52. 3. Set the host names to access the hosts:
  53. .. code:: bash
  54. export REMOTE_QNX=user@kiunix
  55. 4. Setup the ssh server and ssh keys
  56. The ssh key should not be protected by a password, or it will prompt for it every time.
  57. Create the key on the client:
  58. .. code:: bash
  59. ssh-keygen -t rsa -f foo.rsa
  60. Then copy foo.rsa.pub to the remote machine (user@kiunix:/home/user/.ssh/authorized_keys),
  61. and make sure the permissions are correct (chmod go-w ~ ~/.ssh ~/.ssh/authorized_keys)
  62. A separate key for the build processes can be set in the environment variable WAF_SSH_KEY.
  63. The tool will then use 'ssh-keyscan' to avoid prompting for remote hosts, so
  64. be warned to use this feature on internal networks only (MITM).
  65. .. code:: bash
  66. export WAF_SSH_KEY=~/foo.rsa
  67. 5. Perform the build:
  68. .. code:: bash
  69. waf configure_all build_all --remote
  70. """
  71. import getpass, os, re, sys
  72. from collections import OrderedDict
  73. from waflib import Context, Options, Utils, ConfigSet
  74. from waflib.Build import BuildContext, CleanContext, InstallContext, UninstallContext
  75. from waflib.Configure import ConfigurationContext
  76. is_remote = False
  77. if '--remote' in sys.argv:
  78. is_remote = True
  79. sys.argv.remove('--remote')
  80. class init(Context.Context):
  81. """
  82. Generates the *_all commands
  83. """
  84. cmd = 'init'
  85. fun = 'init'
  86. def execute(self):
  87. for x in list(Context.g_module.variants):
  88. self.make_variant(x)
  89. lst = ['remote']
  90. for k in Options.commands:
  91. if k.endswith('_all'):
  92. name = k.replace('_all', '')
  93. for x in Context.g_module.variants:
  94. lst.append('%s_%s' % (name, x))
  95. else:
  96. lst.append(k)
  97. del Options.commands[:]
  98. Options.commands += lst
  99. def make_variant(self, x):
  100. for y in (BuildContext, CleanContext, InstallContext, UninstallContext):
  101. name = y.__name__.replace('Context','').lower()
  102. class tmp(y):
  103. cmd = name + '_' + x
  104. fun = 'build'
  105. variant = x
  106. class tmp(ConfigurationContext):
  107. cmd = 'configure_' + x
  108. fun = 'configure'
  109. variant = x
  110. def __init__(self, **kw):
  111. ConfigurationContext.__init__(self, **kw)
  112. self.setenv(x)
  113. class remote(BuildContext):
  114. cmd = 'remote'
  115. fun = 'build'
  116. def get_ssh_hosts(self):
  117. lst = []
  118. for v in Context.g_module.variants:
  119. self.env.HOST = self.login_to_host(self.variant_to_login(v))
  120. cmd = Utils.subst_vars('${SSH_KEYSCAN} -t rsa,ecdsa ${HOST}', self.env)
  121. out, err = self.cmd_and_log(cmd, output=Context.BOTH, quiet=Context.BOTH)
  122. lst.append(out.strip())
  123. return lst
  124. def setup_private_ssh_key(self):
  125. """
  126. When WAF_SSH_KEY points to a private key, a .ssh directory will be created in the build directory
  127. Make sure that the ssh key does not prompt for a password
  128. """
  129. key = os.environ.get('WAF_SSH_KEY', '')
  130. if not key:
  131. return
  132. if not os.path.isfile(key):
  133. self.fatal('Key in WAF_SSH_KEY must point to a valid file')
  134. self.ssh_dir = os.path.join(self.path.abspath(), 'build', '.ssh')
  135. self.ssh_hosts = os.path.join(self.ssh_dir, 'known_hosts')
  136. self.ssh_key = os.path.join(self.ssh_dir, os.path.basename(key))
  137. self.ssh_config = os.path.join(self.ssh_dir, 'config')
  138. for x in self.ssh_hosts, self.ssh_key, self.ssh_config:
  139. if not os.path.isfile(x):
  140. if not os.path.isdir(self.ssh_dir):
  141. os.makedirs(self.ssh_dir)
  142. Utils.writef(self.ssh_key, Utils.readf(key), 'wb')
  143. os.chmod(self.ssh_key, 448)
  144. Utils.writef(self.ssh_hosts, '\n'.join(self.get_ssh_hosts()))
  145. os.chmod(self.ssh_key, 448)
  146. Utils.writef(self.ssh_config, 'UserKnownHostsFile %s' % self.ssh_hosts, 'wb')
  147. os.chmod(self.ssh_config, 448)
  148. self.env.SSH_OPTS = ['-F', self.ssh_config, '-i', self.ssh_key]
  149. self.env.append_value('RSYNC_SEND_OPTS', '--exclude=build/.ssh')
  150. def skip_unbuildable_variant(self):
  151. # skip variants that cannot be built on this OS
  152. for k in Options.commands:
  153. a, _, b = k.partition('_')
  154. if b in Context.g_module.variants:
  155. c, _, _ = b.partition('_')
  156. if c != Utils.unversioned_sys_platform():
  157. Options.commands.remove(k)
  158. def login_to_host(self, login):
  159. return re.sub('(\w+@)', '', login)
  160. def variant_to_login(self, variant):
  161. """linux_32_debug -> search env.LINUX_32 and then env.LINUX"""
  162. x = variant[:variant.rfind('_')]
  163. ret = os.environ.get('REMOTE_' + x.upper(), '')
  164. if not ret:
  165. x = x[:x.find('_')]
  166. ret = os.environ.get('REMOTE_' + x.upper(), '')
  167. if not ret:
  168. ret = '%s@localhost' % getpass.getuser()
  169. return ret
  170. def execute(self):
  171. global is_remote
  172. if not is_remote:
  173. self.skip_unbuildable_variant()
  174. else:
  175. BuildContext.execute(self)
  176. def restore(self):
  177. self.top_dir = os.path.abspath(Context.g_module.top)
  178. self.srcnode = self.root.find_node(self.top_dir)
  179. self.path = self.srcnode
  180. self.out_dir = os.path.join(self.top_dir, Context.g_module.out)
  181. self.bldnode = self.root.make_node(self.out_dir)
  182. self.bldnode.mkdir()
  183. self.env = ConfigSet.ConfigSet()
  184. def extract_groups_of_builds(self):
  185. """Return a dict mapping each variants to the commands to build"""
  186. self.vgroups = {}
  187. for x in reversed(Options.commands):
  188. _, _, variant = x.partition('_')
  189. if variant in Context.g_module.variants:
  190. try:
  191. dct = self.vgroups[variant]
  192. except KeyError:
  193. dct = self.vgroups[variant] = OrderedDict()
  194. try:
  195. dct[variant].append(x)
  196. except KeyError:
  197. dct[variant] = [x]
  198. Options.commands.remove(x)
  199. def custom_options(self, login):
  200. try:
  201. return Context.g_module.host_options[login]
  202. except (AttributeError, KeyError):
  203. return {}
  204. def recurse(self, *k, **kw):
  205. self.env.RSYNC = getattr(Context.g_module, 'rsync', 'rsync -a --chmod=u+rwx')
  206. self.env.SSH = getattr(Context.g_module, 'ssh', 'ssh')
  207. self.env.SSH_KEYSCAN = getattr(Context.g_module, 'ssh_keyscan', 'ssh-keyscan')
  208. try:
  209. self.env.WAF = getattr(Context.g_module, 'waf')
  210. except AttributeError:
  211. try:
  212. os.stat('waf')
  213. except KeyError:
  214. self.fatal('Put a waf file in the directory (./waf-light --tools=remote)')
  215. else:
  216. self.env.WAF = './waf'
  217. self.extract_groups_of_builds()
  218. self.setup_private_ssh_key()
  219. for k, v in self.vgroups.items():
  220. task = self(rule=rsync_and_ssh, always=True)
  221. task.env.login = self.variant_to_login(k)
  222. task.env.commands = []
  223. for opt, value in v.items():
  224. task.env.commands += value
  225. task.env.variant = task.env.commands[0].partition('_')[2]
  226. for opt, value in self.custom_options(k):
  227. task.env[opt] = value
  228. self.jobs = len(self.vgroups)
  229. def make_mkdir_command(self, task):
  230. return Utils.subst_vars('${SSH} ${SSH_OPTS} ${login} "rm -fr ${remote_dir} && mkdir -p ${remote_dir}"', task.env)
  231. def make_send_command(self, task):
  232. return Utils.subst_vars('${RSYNC} ${RSYNC_SEND_OPTS} -e "${SSH} ${SSH_OPTS}" ${local_dir} ${login}:${remote_dir}', task.env)
  233. def make_exec_command(self, task):
  234. txt = '''${SSH} ${SSH_OPTS} ${login} "cd ${remote_dir} && ${WAF} ${commands}"'''
  235. return Utils.subst_vars(txt, task.env)
  236. def make_save_command(self, task):
  237. return Utils.subst_vars('${RSYNC} ${RSYNC_SAVE_OPTS} -e "${SSH} ${SSH_OPTS}" ${login}:${remote_dir_variant} ${build_dir}', task.env)
  238. def rsync_and_ssh(task):
  239. # remove a warning
  240. task.uid_ = id(task)
  241. bld = task.generator.bld
  242. task.env.user, _, _ = task.env.login.partition('@')
  243. task.env.hdir = Utils.to_hex(Utils.h_list((task.generator.path.abspath(), task.env.variant)))
  244. task.env.remote_dir = '~%s/wafremote/%s' % (task.env.user, task.env.hdir)
  245. task.env.local_dir = bld.srcnode.abspath() + '/'
  246. task.env.remote_dir_variant = '%s/%s/%s' % (task.env.remote_dir, Context.g_module.out, task.env.variant)
  247. task.env.build_dir = bld.bldnode.abspath()
  248. ret = task.exec_command(bld.make_mkdir_command(task))
  249. if ret:
  250. return ret
  251. ret = task.exec_command(bld.make_send_command(task))
  252. if ret:
  253. return ret
  254. ret = task.exec_command(bld.make_exec_command(task))
  255. if ret:
  256. return ret
  257. ret = task.exec_command(bld.make_save_command(task))
  258. if ret:
  259. return ret