1#!/usr/bin/env python3 2# Copyright 2020 the V8 project authors. All rights reserved. 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6import heapq 7import os 8import platform 9import random 10import signal 11import subprocess 12 13# Base dir of the build products for Release and Debug. 14OUT_DIR = os.path.abspath( 15 os.path.join(os.path.dirname(__file__), '..', '..', '..', 'out')) 16 17 18def list_processes_linux(): 19 """Returns list of tuples (pid, command) of processes running in the same out 20 directory as this checkout. 21 """ 22 if platform.system() != 'Linux': 23 return [] 24 try: 25 cmd = 'pgrep -fa %s' % OUT_DIR 26 output = subprocess.check_output(cmd, shell=True) or '' 27 processes = [ 28 (int(line.split()[0]), line[line.index(OUT_DIR):]) 29 for line in output.splitlines() 30 ] 31 # Filter strange process with name as out dir. 32 return [p for p in processes if p[1] != OUT_DIR] 33 except: 34 return [] 35 36 37def kill_processes_linux(): 38 """Kill stray processes on the system that started in the same out directory. 39 40 All swarming tasks share the same out directory location. 41 """ 42 if platform.system() != 'Linux': 43 return 44 for pid, cmd in list_processes_linux(): 45 try: 46 print('Attempting to kill %d - %s' % (pid, cmd)) 47 os.kill(pid, signal.SIGKILL) 48 except: 49 pass 50 51 52class FixedSizeTopList(): 53 """Utility collection for gathering a fixed number of elements with the 54 biggest value for the given key. It employs a heap from which we pop the 55 smallest element when the collection is 'full'. 56 57 If you need a reversed behaviour (collect min values) just provide an 58 inverse key.""" 59 60 def __init__(self, size, key=None): 61 self.size = size 62 self.key = key or (lambda x: x) 63 self.data = [] 64 self.discriminator = 0 65 66 def add(self, elem): 67 elem_k = self.key(elem) 68 heapq.heappush(self.data, (elem_k, self.extra_key(), elem)) 69 if len(self.data) > self.size: 70 heapq.heappop(self.data) 71 72 def extra_key(self): 73 # Avoid key clash in tuples sent to the heap. 74 # We want to avoid comparisons on the last element of the tuple 75 # since those elements might not be comparable. 76 self.discriminator += 1 77 return self.discriminator 78 79 def as_list(self): 80 original_data = [rec for (_, _, rec) in self.data] 81 return sorted(original_data, key=self.key, reverse=True) 82