github.com/shashidharatd/test-infra@v0.0.0-20171006011030-71304e1ca560/scenarios/kubernetes_kubelet.py (about)

     1  #!/usr/bin/env python
     2  
     3  # Copyright 2017 The Kubernetes Authors.
     4  #
     5  # Licensed under the Apache License, Version 2.0 (the "License");
     6  # you may not use this file except in compliance with the License.
     7  # You may obtain a copy of the License at
     8  #
     9  #     http://www.apache.org/licenses/LICENSE-2.0
    10  #
    11  # Unless required by applicable law or agreed to in writing, software
    12  # distributed under the License is distributed on an "AS IS" BASIS,
    13  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  # See the License for the specific language governing permissions and
    15  # limitations under the License.
    16  
    17  # Need to figure out why this only fails on travis
    18  # pylint: disable=bad-continuation
    19  
    20  """Runs node and/or kubelet tests for kubernetes/kubernetes."""
    21  
    22  import argparse
    23  import os
    24  import re
    25  import shutil
    26  import subprocess
    27  import sys
    28  
    29  BRANCH_VERSION = {
    30      'release-1.2': 'release-1.4',
    31      'release-1.3': 'release-1.4',
    32      'master': 'release-1.8',
    33  }
    34  
    35  VERSION_TAG = {
    36      'release-1.4': '1.4-latest',
    37      'release-1.5': '1.5-latest',
    38      'release-1.6': '1.6-latest',
    39      'release-1.7': '1.7-latest',
    40      'release-1.8': '1.8-latest',
    41  }
    42  
    43  ORIG_CWD = os.getcwd()  # Checkout changes cwd
    44  
    45  
    46  def check(*cmd):
    47      """Log and run the command, raising on errors."""
    48      print >>sys.stderr, 'Run:', cmd
    49      subprocess.check_call(cmd)
    50  
    51  
    52  def var(path):
    53      """Expands '${foo} interesting' to 'something interesting'."""
    54      return os.path.expandvars(path)
    55  
    56  
    57  def run_docker_mode(script, properties, branch, ssh, ssh_pub, robot):
    58      """Test node branch by sending script specified properties and creds."""
    59      # If branch has 3-part version, only take first 2 parts.
    60      mat = re.match(r'master|release-\d+\.\d+', branch)
    61      if not mat:
    62          raise ValueError(branch)
    63      tag = VERSION_TAG[BRANCH_VERSION.get(mat.group(0), mat.group(0))]
    64      img = 'gcr.io/k8s-testimages/kubekins-node:%s' % tag
    65      artifacts = '%s/_artifacts' % os.environ['WORKSPACE']
    66      if not os.path.isdir(artifacts):
    67          os.makedirs(artifacts)
    68      k8s = os.getcwd()
    69      if not os.path.basename(k8s) == 'kubernetes':
    70          raise ValueError(k8s)
    71  
    72      for path in [ssh, ssh_pub, robot]:
    73          if not os.path.isfile(var(path)):
    74              raise IOError(path, var(path))
    75      private = '/root/.ssh/google_compute_engine'
    76      public = '%s.pub' % private
    77      service = '/service-account.json'
    78  
    79      os.environ['NODE_TEST_SCRIPT'] = script
    80      os.environ['NODE_TEST_PRORPERTIES'] = properties
    81      check('docker', 'pull', img)  # Update image if changed
    82      check(
    83          'docker', 'run', '--rm=true',
    84          '-v', '/etc/localtime:/etc/localtime:ro',
    85          '-v', '/var/run/docker.sock:/var/run/docker.sock',
    86          '-v', '%s:/go/src/k8s.io/kubernetes' % k8s,
    87          '-v', '%s:/workspace/_artifacts' % artifacts,
    88          '-v', '%s:%s:ro' % (robot, service),
    89          '-v', '%s:%s:ro' % (ssh, private),
    90          '-v', '%s:%s:ro' % (ssh_pub, public),
    91          '-e', 'GCE_USER=jenkins',
    92          '-e', 'GOOGLE_APPLICATION_CREDENTIALS=%s' % service,
    93          '-e', 'JENKINS_GCE_SSH_PRIVATE_KEY_FILE=%s' % private,
    94          '-e', 'JENKINS_GCE_SSH_PUBLIC_KEY_FILE=%s' % public,
    95          '-e', 'NODE_TEST_PROPERTIES=%s' % properties,
    96          '-e', 'NODE_TEST_SCRIPT=%s' % script,
    97          '-e', 'REPO_DIR=%s' % k8s,  # TODO(fejta): used?
    98          img,
    99      )
   100  
   101  def test_infra(*paths):
   102      """Return path relative to root of test-infra repo."""
   103      return os.path.join(ORIG_CWD, os.path.dirname(__file__), '..', *paths)
   104  
   105  
   106  def add_gce_ssh(private_key, public_key):
   107      """Copies priv, pub keys to /root/.ssh."""
   108      ssh_dir = '/root/.ssh'
   109      if not os.path.isdir(ssh_dir):
   110          os.makedirs(ssh_dir)
   111      gce_ssh = '%s/google_compute_engine' % ssh_dir
   112      gce_pub = '%s/google_compute_engine.pub' % ssh_dir
   113      shutil.copy(private_key, gce_ssh)
   114      shutil.copy(public_key, gce_pub)
   115  
   116  
   117  def parse_env(env):
   118      """Returns (FOO, BAR=MORE) for FOO=BAR=MORE."""
   119      return env.split('=', 1)
   120  
   121  
   122  def get_envs_from_file(env_file):
   123      """Returns all FOO=BAR lines from env_file."""
   124      envs = []
   125      with open(env_file) as fp:
   126          for line in fp:
   127              line = line.rstrip()
   128              if not line or line.startswith('#'):
   129                  continue
   130              envs.append(parse_env(line))
   131      return dict(envs)
   132  
   133  
   134  def run_local_mode(run_args, private_key, public_key):
   135      """Checkout, build and trigger the node e2e tests locally."""
   136      k8s = os.getcwd()
   137      if not os.path.basename(k8s) == 'kubernetes':
   138          raise ValueError(k8s)
   139      add_gce_ssh(private_key, public_key)
   140      check(
   141          'go', 'run', 'test/e2e_node/runner/remote/run_remote.go',
   142          '--logtostderr',
   143          '--vmodule=*=4',
   144          '--ssh-env=gce',
   145          '--results-dir=%s/_artifacts' % k8s,
   146          *run_args)
   147  
   148  
   149  def main():
   150      if ARGS.mode == 'docker':
   151          run_docker_mode(
   152              ARGS.script,
   153              ARGS.properties,
   154              ARGS.branch,
   155              ARGS.gce_ssh,
   156              ARGS.gce_pub,
   157              ARGS.service_account,
   158          )
   159      elif ARGS.mode == 'local':
   160          run_local_mode(
   161              RUN_ARGS,
   162              ARGS.gce_ssh,
   163              ARGS.gce_pub,
   164          )
   165      else:
   166          raise ValueError(ARGS.mode)
   167  
   168  
   169  if __name__ == '__main__':
   170      PARSER = argparse.ArgumentParser(
   171          'Runs kubelet tests with the specified script, properties and creds')
   172      PARSER.add_argument(
   173          '--gce-ssh',
   174          default=os.environ.get('JENKINS_GCE_SSH_PRIVATE_KEY_FILE'),
   175          help='Path to .ssh/google_compute_engine keys')
   176      PARSER.add_argument(
   177          '--gce-pub',
   178          default=os.environ.get('JENKINS_GCE_SSH_PUBLIC_KEY_FILE'),
   179          help='Path to pub gce ssh key')
   180      PARSER.add_argument(
   181          '--service-account',
   182          default=os.environ.get('GOOGLE_APPLICATION_CREDENTIALS'),
   183          help='Path to service-account.json')
   184      PARSER.add_argument(
   185          '--branch', default='master', help='Branch used for testing')
   186      PARSER.add_argument(
   187          '--properties',
   188          default="test/e2e_node/jenkins/jenkins-ci.properties",
   189          help='Path to a .properties file')
   190      PARSER.add_argument(
   191          '--script',
   192          default='./test/e2e_node/jenkins/e2e-node-jenkins.sh',
   193          help='Script in kubernetes/kubernetes that runs checks')
   194      PARSER.add_argument(
   195          '--mode', default='docker', choices=['local', 'docker'])
   196      ARGS, RUN_ARGS = PARSER.parse_known_args()
   197      main()