blob: ff59d2c3aedd60f49c4be1711a5327fbc22433c8 [file] [log] [blame]
Dan Shi54682e72014-10-08 19:10:56 +00001#!/usr/bin/env python
2
3# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""
8This script provides functions to:
91. collect: Collect all hosts and their labels to metaDB, can be scheduled
10 run daily, e.g.,
Dan Shi17ecbbf2014-10-06 13:56:34 -070011 ./site_utils/host_label_utils.py collect
Dan Shi54682e72014-10-08 19:10:56 +0000122. query: Query for hosts and their labels information at a given day, e.g.,
Dan Shi17ecbbf2014-10-06 13:56:34 -070013 ./site_utils/host_label_utils.py query -n 172.27.213.193 -l peppy
Dan Shi54682e72014-10-08 19:10:56 +000014"""
15
16import argparse
Dan Shi1c3b0d12014-09-26 17:15:41 -070017import itertools
Dan Shi54682e72014-10-08 19:10:56 +000018import logging
19import pprint
20import time
21
22import common
23from autotest_lib.client.common_lib import time_utils
24from autotest_lib.client.common_lib.cros.graphite import es_utils
25from autotest_lib.frontend import setup_django_environment
26from autotest_lib.frontend.afe import models
27
28
29# _type used for ES
30_HOST_LABEL_TYPE = 'host_labels'
31_HOST_LABEL_TIME_INDEX_TYPE = 'host_labels_time_index'
32
33
Dan Shi1c3b0d12014-09-26 17:15:41 -070034def get_all_boards():
35 """Get a list of boards from host labels.
36
37 Scan through all labels of all duts and get all possible boards based on
38 label of name board:*
39
40 @return: A list of board names, e.g., ['peppy', 'daisy']
41 """
42 host_labels = get_host_labels()
43 board_labels = [[label[6:] for label in labels
44 if label.startswith('board:')]
45 for labels in host_labels.values()]
46 boards = list(set(itertools.chain.from_iterable(board_labels)))
47 return boards
48
49
Dan Shi54682e72014-10-08 19:10:56 +000050def get_host_labels(days_back=0, hostname=None, labels=None):
51 """Get the labels for a given host or all hosts.
52
53 @param days_back: Get the label info around that number of days back. The
54 default is 0, i.e., the latest label information.
55 @param hostname: Name of the host, if set to None, return labels for all
56 hosts. Default is None.
57 @param labels: A list of labels to filter hosts.
58 @return: A dictionary of host labels, key is the hostname, and value is a
59 list of labels, e.g.,
60 {'host1': ['board:daisy', 'pool:bvt']}
61 """
62 # Search for the latest logged labels before the given days_back.
63 # Default is 0, which means the last time host labels were logged.
64 t_end = time.time() - days_back*24*3600
65 query_time_index = es_utils.create_range_eq_query_multiple(
66 fields_returned=['time_index'],
67 equality_constraints=[('_type', _HOST_LABEL_TIME_INDEX_TYPE),],
68 range_constraints=[('time_index', None, t_end)],
69 size=1,
70 sort_specs=[{'time_index': 'desc'}])
71 results = es_utils.execute_query(query_time_index)
72 count = int(results['hits']['total'])
73 t_end_str = time_utils.epoch_time_to_date_string(t_end)
74 if count == 0:
75 logging.error('No label information was logged before %s.', t_end_str)
76 return
77 time_index = results['hits']['hits'][0]['fields']['time_index'][0]
78 logging.info('Host labels were recorded at %s',
79 time_utils.epoch_time_to_date_string(time_index))
80
81 # Search for labels for a given host or all hosts, at time_index.
82 equality_constraints=[('_type', _HOST_LABEL_TYPE),
83 ('time_index', time_index),]
84 if hostname:
85 equality_constraints.append(('hostname', hostname))
86 if labels:
87 for label in labels:
88 equality_constraints.append(('labels', label))
89 query_labels = es_utils.create_range_eq_query_multiple(
90 fields_returned=['hostname', 'labels'],
91 equality_constraints=equality_constraints)
92 results = es_utils.execute_query(query_labels)
93
94 host_labels = {}
95 for hit in results['hits']['hits']:
96 hit = es_utils.convert_hit(hit['fields'])
Dan Shic6509e62014-10-20 11:19:51 -070097 if 'labels' in hit:
98 host_labels[hit['hostname']] = hit['labels']
Dan Shi54682e72014-10-08 19:10:56 +000099
100 return host_labels
101
102
103def collect_info():
104 """Collect label info and report to metaDB.
105 """
106 # time_index is to index all host labels collected together. It's
107 # converted to int to make search faster.
108 time_index = int(time.time())
109 hosts = models.Host.objects.filter(invalid=False)
110 for host in hosts:
111 info = {'hostname': host.hostname,
112 'labels': [label.name for label in host.labels.all()],
113 'time_index': time_index}
114 es_utils.ESMetadata().post(type_str=_HOST_LABEL_TYPE, metadata=info,
115 log_time_recorded=False)
116
117 # After all host label information is logged, save the time stamp.
118 es_utils.ESMetadata().post(type_str=_HOST_LABEL_TIME_INDEX_TYPE,
119 metadata={'time_index': time_index},
120 log_time_recorded=False)
121 logging.info('Finished collecting host labels for %d hosts.', len(hosts))
122
123
124def main():
125 """Main script.
126 """
127 parser = argparse.ArgumentParser()
128 parser.add_argument('action',
129 help=('collect or query. Action collect will collect '
130 'all hosts and their labels to metaDB. Action '
131 'query will query for hosts and their labels '
132 'information at a given day'))
133 parser.add_argument('-d', '--days_back', type=int, dest='days_back',
134 help=('Number of days before current time. Query will '
135 'get host label information collected before that'
136 ' time. The option is applicable to query only. '
137 'Default to 0, i.e., get the latest label info.'),
138 default=0)
139 parser.add_argument('-n', '--hostname', type=str, dest='hostname',
140 help=('Name of the host to query label information for.'
141 'The option is applicable to query only. '
142 'Default to None, i.e., return label info for all'
143 ' hosts.'),
144 default=None)
145 parser.add_argument('-l', '--labels', nargs='+', dest='labels',
146 help=('A list of labels to filter hosts. The option is '
147 'applicable to query only. Default to None.'),
148 default=None)
149 parser.add_argument('-v', '--verbose', action="store_true", dest='verbose',
150 help='Allow more detail information to be shown.')
151 options = parser.parse_args()
152
153 logging.getLogger().setLevel(logging.INFO if options.verbose
154 else logging.WARN)
155 if options.action == 'collect':
156 collect_info()
157 elif options.action == 'query':
158 host_labels = get_host_labels(options.days_back, options.hostname,
159 options.labels)
160 pprint.pprint(host_labels)
161 else:
162 logging.error('action %s is not supported, can only be collect or '
163 'query!', options.action)
164
165
166if __name__ == '__main__':
167 main()