-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-ingress
executable file
·190 lines (168 loc) · 9.36 KB
/
test-ingress
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#!/usr/bin/env python3
import argparse
import json
import subprocess
import yaml
from ansi.colour import fg, fx
# TODO: test ports correspondences ingress -> service -> pod
# TODO: test ingress certificates
def title(text):
return f'{fg.blue}{fx.bold}{text}{fx.reset}{fx.reset}'
def check(text, condition):
color = fg.green if condition else fg.red
return f'{color}{fx.bold}{text}{fx.reset}{fx.reset}'
def _main():
parser = argparse.ArgumentParser(description='Diagnosis Ingress')
parser.add_argument('host', help='Host to diagnose')
parser.add_argument('--path', default='/', help='Path to diagnose')
parser.add_argument('--namespace', help='Namespace search on', action='append')
arguments = parser.parse_args()
print(f'Host: {arguments.host}')
print(f'Path: {arguments.path}')
print(f'Namespace: {", ".join(arguments.namespace)}')
#-o, --output='':
# Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file, #custom-columns, custom-columns-file, wide). See custom columns [https://kubernetes.io/docs/reference/kubectl/#custom-columns], golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [https://kubernetes.io/docs/reference/kubectl/jsonpath/].
ingress_raw = {}
for namespace in arguments.namespace:
ingress_raw[namespace] = json.loads(subprocess.run(['kubectl', f'--namespace={namespace}', 'get', 'ingresses.networking.k8s.io', '--output=json'],
stdout=subprocess.PIPE, check=True, encoding='utf-8').stdout)
all_paths = []
essential = {}
for namespace, ingresses in ingress_raw.items():
for item in ingresses['items']:
for rule in item['spec']['rules']:
if arguments.host in rule['host']:
for path in rule['http']['paths']:
all_paths.append(path['path'] )
essential[path['path']] ={
'namespace': namespace,
'name': item['metadata']['name'],
'pathType': path['pathType'],
'service': path['backend']['service']['name'],
'port': path['backend']['service']['port']['number'],
'status': item['status']
}
choose_path = None
for path in all_paths:
if arguments.path.startswith(path) and len(path) > len(choose_path or ''):
choose_path = path
ingress = essential[choose_path]
print()
print("Found ingress:")
for path, item in essential.items():
print()
print(title(f"{item['namespace']}:{item['name']}:"))
if path == choose_path:
print(f'{fg.green}{fx.bold} Path: {path} <={fx.reset}{fx.reset}')
else:
print(f" Path: {path}")
print(f" PathType: {item['pathType']}")
print(f" Service: {item['service']}:{item['port']}")
if item['status']:
print(" Status:")
for line in yaml.dump(item['status'], default_flow_style=False).strip().split('\n'):
print(f" {line}")
service = json.loads(subprocess.run(['kubectl', f'--namespace={ingress["namespace"]}', 'get', 'services', ingress["service"], '--output=json'],
stdout=subprocess.PIPE, check=True, encoding='utf-8').stdout)
service_name = service['metadata']['name']
print()
print(title(f"Service {service_name}:"))
print(f" Type: {service['spec']['type']}")
print(f" ClusterIP: {service['spec']['clusterIP']}")
print(f" ClusterIPs: {', '.join(service['spec']['clusterIPs'])}")
port_found = False
for port in service['spec']['ports']:
if port['port'] == ingress['port']:
print(" Port:")
print(f" Name: {port['name']}")
print(f" Protocol: {port['protocol']}")
print(f" TargetPort: {port['targetPort']}")
port_found = True
if not port_found:
print(f" Port: {ingress['port']} not found!!")
if service['status']:
print(" Status:")
for line in yaml.dump(service['status'], default_flow_style=False).strip().split('\n'):
print(f" {line}")
print(' Selector:')
for key, value in service['spec']['selector'].items():
print(f" {key}: {value}")
endpoints = json.loads(subprocess.run(['kubectl', f'--namespace={ingress["namespace"]}', 'get', 'endpoints', service_name, '--output=json'],
stdout=subprocess.PIPE, check=True, encoding='utf-8').stdout)
pods = {}
print()
print(title(f"Endpoints for {service_name}:"))
if 'subsets' not in endpoints:
print(check(" No endpoints found for this service, this probably means that there are no ready pods.", False))
else:
for endpoint in endpoints['subsets']:
for address in endpoints.get('addresses', []):
print(f" IP: {address['ip']}")
print(f" {address['targetRef']['kind']}: {address['targetRef']['namespace']}:{address['targetRef']['name']}")
pods[f"{address['targetRef']['namespace']}:{address['targetRef']['name']}"] = {
'namespace': address['targetRef']['namespace'],
'name': address['targetRef']['name'],
}
for port in endpoint['ports']:
print(f" Port {port['port']}:")
print(f" Name: {port.get('name')}")
all_endpointslice = json.loads(subprocess.run(['kubectl', f'--namespace={ingress["namespace"]}', 'get', 'endpointslices', '--output=json'],
stdout=subprocess.PIPE, check=True, encoding='utf-8').stdout)
print()
print(f"Endpointslice for {service_name}:")
for endpointslice in all_endpointslice['items']:
found = False
for ownerReference in endpointslice['metadata']['ownerReferences']:
if ownerReference['kind'] == 'Service' and ownerReference['name'] == service_name:
found = True
break
if not found:
continue
print(f" Name: {endpointslice['metadata']['name']}")
print(" Endpoints:")
if 'endpoints' not in endpointslice or endpointslice['endpoints'] is None:
print(check(" No endpoints found for this service Endpointslice, this probably means that there are no ready pods.", False))
continue
else:
for endpoint in endpointslice['endpoints']:
print(f" IP: {', '.join(endpoint['addresses'])}")
print(f" {endpoint['targetRef']['kind']}: {endpoint['targetRef']['namespace']}:{endpoint['targetRef']['name']}")
pods[f"{endpoint['targetRef']['namespace']}:{endpoint['targetRef']['name']}"] = {
'namespace': endpoint['targetRef']['namespace'],
'name': endpoint['targetRef']['name'],
}
print(" Conditions:")
print(check(f" Ready: {endpoint['conditions']['ready']}", endpoint['conditions']['ready']))
print(check(f" Serving: {endpoint['conditions']['serving']}", endpoint['conditions']['serving']))
print(f" Terminating: {endpoint['conditions']['terminating']}")
print(" Ports:")
for port in endpointslice['ports']:
print(f" Name: {port['name']}")
print(f" Protocol: {port['protocol']}")
print(f" Port: {port['port']}")
print()
pods_raw = {
'items': []}
if pods:
for pod in pods.values():
pod_raw = json.loads(subprocess.run(['kubectl', f'--namespace={pod["namespace"]}', 'get', 'pods', pod["name"], '--output=json'],
stdout=subprocess.PIPE, check=True, encoding='utf-8').stdout)
pods_raw['items'].append(pod_raw)
elif service.get('spec', {}).get('selector'):
# get pods with service selector labels
pods_raw = json.loads(subprocess.run(['kubectl', f'--namespace={ingress["namespace"]}', 'get', 'pods', '--output=json', f'--selector={",".join([f"{key}={value}" for key, value in service["spec"]["selector"].items()])}'],
stdout=subprocess.PIPE, check=True, encoding='utf-8').stdout)
if not pods_raw['items']:
print(check("No pods found for this service, this probably means that there are no ready pods.", False))
for pod_raw in pods_raw['items']:
print(title(f"{pod['namespace']}:{pod['name']}:"))
print(check(f" Status: {pod_raw['status']['phase']}", pod_raw['status']['phase'] == 'Running'))
for condition in pod_raw['status']['conditions']:
check(f"{condition['type']}: {condition['status']}", condition['status'] == 'True')
print(" Containers status:")
for container_status in pod_raw['status']['containerStatuses']:
print(title(f" {container_status['name']}:"))
print(check(f" Ready: {container_status['ready']}", container_status['ready']))
print(check(f" Started: {container_status['started']}", container_status['started']))
if __name__ == '__main__':
_main()