Hyunsun Moon | 6ff622e | 2020-03-11 17:14:48 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | # SPDX-License-Identifier: Apache-2.0 |
| 3 | # Copyright 2020-present Open Networking Foundation |
| 4 | # Copyright(c) 2019 Intel Corporation |
| 5 | |
| 6 | import os |
| 7 | import signal |
| 8 | import socket |
| 9 | import sys |
| 10 | |
| 11 | import iptools |
| 12 | import json |
| 13 | import psutil |
| 14 | from pyroute2 import IPDB |
| 15 | |
| 16 | |
| 17 | def exit(code, msg): |
| 18 | print(msg) |
| 19 | sys.exit(code) |
| 20 | |
| 21 | |
| 22 | def getpid(process_name): |
| 23 | for proc in psutil.process_iter(attrs=['pid', 'name']): |
| 24 | if process_name == proc.info['name']: |
| 25 | return proc.info['pid'] |
| 26 | |
| 27 | |
| 28 | def getpythonpid(process_name): |
| 29 | for proc in psutil.process_iter(attrs=['pid', 'cmdline']): |
| 30 | if len(proc.info['cmdline']) < 2: |
| 31 | continue |
| 32 | if process_name in proc.info['cmdline'][1] and 'python' in proc.info['cmdline'][0]: |
| 33 | return proc.info['pid'] |
| 34 | return |
| 35 | |
| 36 | |
| 37 | def get_json_conf(path, dump): |
| 38 | conf = json.loads(open(path).read()) |
| 39 | if dump: |
| 40 | print(json.dumps(conf, indent=4, sort_keys=True)) |
| 41 | return conf |
| 42 | |
| 43 | |
| 44 | def get_env(varname, default=None): |
| 45 | try: |
| 46 | var = os.environ[varname] |
| 47 | return var |
| 48 | except KeyError: |
| 49 | if default is not None: |
| 50 | return '{}'.format(default) |
| 51 | else: |
| 52 | exit(1, 'Empty env var {}'.format(varname)) |
| 53 | |
| 54 | |
| 55 | def ips_by_interface(name): |
| 56 | ipdb = IPDB() |
| 57 | return [ipobj[0] for ipobj in ipdb.interfaces[name]['ipaddr'].ipv4] |
| 58 | |
| 59 | |
| 60 | def mac_by_interface(name): |
| 61 | ipdb = IPDB() |
| 62 | return ipdb.interfaces[name]['address'] |
| 63 | |
| 64 | |
| 65 | def mac2hex(mac): |
| 66 | return int(mac.replace(':', ''), 16) |
| 67 | |
| 68 | |
| 69 | def peer_by_interface(name): |
| 70 | ipdb = IPDB() |
| 71 | try: |
| 72 | peer_idx = ipdb.interfaces[name]['link'] |
| 73 | peer_name = ipdb.interfaces[peer_idx]['ifname'] |
| 74 | except: |
| 75 | raise Exception('veth interface {} does not exist'.format(name)) |
| 76 | else: |
| 77 | return peer_name |
| 78 | |
| 79 | |
| 80 | def aton(ip): |
| 81 | return socket.inet_aton(ip) |
| 82 | |
| 83 | |
| 84 | def validate_cidr(cidr): |
| 85 | return iptools.ipv4.validate_cidr(cidr) |
| 86 | |
| 87 | |
| 88 | def cidr2mask(cidr): |
| 89 | _, prefix = cidr.split('/') |
| 90 | return format(0xffffffff << (32 - int(prefix)), '08x') |
| 91 | |
| 92 | |
| 93 | def cidr2block(cidr): |
| 94 | return iptools.ipv4.cidr2block(cidr) |
| 95 | |
| 96 | |
| 97 | def ip2hex(ip): |
| 98 | return iptools.ipv4.ip2hex(ip) |
| 99 | |
| 100 | |
| 101 | def ip2long(ip): |
| 102 | return iptools.ipv4.ip2long(ip) |
| 103 | |
| 104 | |
| 105 | def get_process_affinity(): |
| 106 | return psutil.Process().cpu_affinity() |