1# Copyright 2015 The Chromium OS 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
6import logging
7import os.path
8import subprocess
9import tempfile
10
11def copy_private_bucket(host, bucket, filename, destination, timeout_s=30):
12    """
13    Copies files/directories from a private google storage location to the DUT.
14    Uses a test server box as a temp location.
15    We do this because it's easier than trying to get the client DUT
16    authenticated. The Test server is already authenticated, so copy to the test
17    server and then send file to client.
18
19    @param host: Autotest host machine object.
20    @param bucket: path to name of gs bucket.
21    @param filename: string, name of the file or dir in 'bucket' to copy.
22    @param destination: path in DUT where the file should be copied to.
23    @param timeout_s: int, timeout in seconds to wait for copy to finish
24
25    """
26
27    assert (bucket.startswith('gs://'))
28    assert (os.path.isdir(destination))
29
30    src = os.path.join(bucket, filename)
31
32    log("SOURCE path: " + src)
33
34    with tempfile.NamedTemporaryFile(suffix='.wpr') as tempsource:
35        tempsourcepath = tempsource.name
36
37        args = ['gsutil', 'cp', src, tempsourcepath]
38        log("Copying to temporary test server destination : " + tempsourcepath)
39
40        p = subprocess.Popen(args,
41                             stdout=subprocess.PIPE,
42                             stderr=subprocess.PIPE)
43
44        output = p.communicate()
45
46        log("STDOUT | " + output[0])
47        log("STDERR | " + output[1])
48
49        if p.returncode:
50            raise subprocess.CalledProcessError(returncode=p.returncode,
51                                                cmd=args)
52
53        host.send_file(tempsourcepath, os.path.join(destination, filename))
54        log("Sent file to DUT : " + host.hostname)
55
56
57def log(message):
58    """
59    Wraps around logging.debug() and adds a prefix to show that messages are
60    coming from this utility.
61
62    @param message: string, the message to log.
63
64    """
65    message = "| gs wrapper | " + message
66    logging.debug(message)