1#
2# Copyright 2008 Google Inc. All Rights Reserved.
3#
4
5import os
6from autotest_lib.frontend.afe import rpc_client_lib
7from autotest_lib.frontend.afe.json_rpc import proxy
8from autotest_lib.client.common_lib import global_config, utils
9
10GLOBAL_CONFIG = global_config.global_config
11DEFAULT_SERVER = 'autotest'
12AFE_RPC_PATH = '/afe/server/noauth/rpc/'
13TKO_RPC_PATH = '/new_tko/server/noauth/rpc/'
14
15
16class AuthError(Exception):
17    pass
18
19
20def get_autotest_server(web_server=None):
21    if not web_server:
22        if 'AUTOTEST_WEB' in os.environ:
23            web_server = os.environ['AUTOTEST_WEB']
24        else:
25            web_server = GLOBAL_CONFIG.get_config_value(
26                    'SERVER', 'hostname', default=DEFAULT_SERVER)
27
28    web_server = rpc_client_lib.add_protocol(web_server)
29    return web_server
30
31
32class rpc_comm(object):
33    """Shared AFE/TKO RPC class stuff"""
34    def __init__(self, web_server, rpc_path, username):
35        self.username = username
36        self.web_server = get_autotest_server(web_server)
37        try:
38            self.proxy = self._connect(rpc_path)
39        except rpc_client_lib.AuthError, s:
40            raise AuthError(s)
41
42
43    def _connect(self, rpc_path):
44        # This does not fail even if the address is wrong.
45        # We need to wait for an actual RPC to fail
46        headers = rpc_client_lib.authorization_headers(self.username,
47                                                       self.web_server)
48        rpc_server = self.web_server + rpc_path
49        return rpc_client_lib.get_proxy(rpc_server, headers=headers)
50
51
52    def run(self, op, *args, **data):
53        if 'AUTOTEST_CLI_DEBUG' in os.environ:
54            print self.web_server, op, args, data
55        function = getattr(self.proxy, op)
56        result = function(*args, **data)
57        if 'AUTOTEST_CLI_DEBUG' in os.environ:
58            print 'result:', result
59        return result
60
61
62class afe_comm(rpc_comm):
63    """Handles the AFE setup and communication through RPC"""
64    def __init__(self, web_server=None, rpc_path=AFE_RPC_PATH, username=None):
65        super(afe_comm, self).__init__(web_server, rpc_path, username)
66
67
68class tko_comm(rpc_comm):
69    """Handles the TKO setup and communication through RPC"""
70    def __init__(self, web_server=None, rpc_path=TKO_RPC_PATH, username=None):
71        super(tko_comm, self).__init__(web_server, rpc_path, username)
72