1# Copyright 2016 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5
6from recipe_engine import recipe_api
7
8
9INFRA_GO_PKG = 'go.skia.org/infra'
10UPDATE_GO_ATTEMPTS = 5
11UPLOAD_ATTEMPTS = 5
12
13
14class InfraApi(recipe_api.RecipeApi):
15  @property
16  def goroot(self):
17    return self.m.vars.slave_dir.join('go', 'go')
18
19  @property
20  def go_bin(self):
21    return self.goroot.join('bin')
22
23  @property
24  def go_exe(self):
25    return self.go_bin.join('go')
26
27  @property
28  def go_env(self):
29    return {
30        'GOCACHE': self.m.vars.cache_dir.join('go_cache'),
31        'GOPATH': self.gopath,
32        'GOROOT': self.goroot,
33        'PATH': '%s:%s:%%(PATH)s' % (self.go_bin, self.gopath.join('bin')),
34    }
35
36  @property
37  def gopath(self):
38    return self.m.vars.slave_dir.join('go_deps')
39
40  def go_version(self):
41    """Print the Go version."""
42    env = self.m.context.env
43    env.update(self.go_env)
44    with self.m.context(env=env):
45      self.m.run(
46          self.m.step,
47          'go version',
48          cmd=[self.go_exe, 'version'])
49      self.m.run(
50          self.m.step,
51          'env go version',
52          cmd=['go', 'version'])
53
54  class MetadataFetch():
55    def __init__(self, api, metadata_key, local_file, **kwargs):
56      self.m = api
57      self._key = metadata_key
58      self._local_file = local_file
59
60    def __enter__(self):
61      return self.m.python.inline(
62          'download ' + self._local_file,
63        """
64import os
65import urllib2
66
67TOKEN_FILE = '%s'
68TOKEN_URL = 'http://metadata/computeMetadata/v1/project/attributes/%s'
69
70req = urllib2.Request(TOKEN_URL, headers={'Metadata-Flavor': 'Google'})
71contents = urllib2.urlopen(req).read()
72
73home = os.path.expanduser('~')
74token_file = os.path.join(home, TOKEN_FILE)
75
76with open(token_file, 'w') as f:
77  f.write(contents)
78        """ % (self._local_file, self._key),
79      )
80
81    def __exit__(self, t, v, tb):
82      self.m.python.inline(
83          'cleanup ' + self._local_file,
84        """
85import os
86
87
88TOKEN_FILE = '%s'
89
90
91home = os.path.expanduser('~')
92token_file = os.path.join(home, TOKEN_FILE)
93if os.path.isfile(token_file):
94  os.remove(token_file)
95          """ % (self._local_file),
96      )
97      return v is None
98