comparison gcp_batch_netcat.py @ 6:d25792770df8 draft

planemo upload for repository https://github.com/afgane/gcp_batch_netcat commit ece227052d14d755b0d0b07a827152b2e98fb94b-dirty
author enis
date Thu, 24 Jul 2025 21:59:57 +0000
parents b2ce158b4f22
children fcfb703748b1
comparison
equal deleted inserted replaced
5:b2ce158b4f22 6:d25792770df8
12 format='%(asctime)s - %(levelname)s - %(message)s', 12 format='%(asctime)s - %(levelname)s - %(message)s',
13 stream=sys.stdout 13 stream=sys.stdout
14 ) 14 )
15 logger = logging.getLogger(__name__) 15 logger = logging.getLogger(__name__)
16 16
17 def discover_nfs_loadbalancer_ip():
18 """
19 Try to discover NFS LoadBalancer IP via Kubernetes API
20 Returns the external IP if found, None otherwise
21 """
22 try:
23 import subprocess
24 logger.info("Attempting to discover NFS LoadBalancer IP via kubectl...")
25 result = subprocess.run(['kubectl', 'get', 'svc', '-n', 'nfs-provisioner', '-o', 'json'], capture_output=True, text=True)
26 if result.returncode == 0:
27 services = json.loads(result.stdout)
28 for item in services.get('items', []):
29 name = item.get('metadata', {}).get('name', '')
30 # Look for NFS-related service names
31 if any(keyword in name.lower() for keyword in ['nfs-provisioner-nfs-server-provisioner']):
32 spec = item.get('spec', {})
33 if spec.get('type') == 'LoadBalancer':
34 ingress = item.get('status', {}).get('loadBalancer', {}).get('ingress', [])
35 if ingress:
36 ip = ingress[0].get('ip')
37 if ip:
38 logger.info(f"Found NFS LoadBalancer service '{name}' with external IP: {ip}")
39 return ip
40 logger.warning("No NFS LoadBalancer services found via kubectl")
41 else:
42 logger.warning(f"kubectl command failed: {result.stderr}")
43 except Exception as e:
44 logger.warning(f"Could not discover NFS LoadBalancer IP via kubectl: {e}")
45 return None
46
17 def determine_test_target(args): 47 def determine_test_target(args):
18 """Determine the target host and port based on test type""" 48 """Determine the target host and port based on test type"""
19 49
20 if args.test_type == 'custom': 50 if args.test_type == 'nfs':
21 if not args.custom_host:
22 raise ValueError("custom_host is required when test_type is 'custom'")
23 return args.custom_host, args.custom_port
24
25 elif args.test_type == 'nfs':
26 # Extract NFS server address if not provided 51 # Extract NFS server address if not provided
27 if args.nfs_address: 52 if args.nfs_address:
28 nfs_address = args.nfs_address 53 nfs_address = args.nfs_address
29 logger.info(f"Using provided NFS address: {nfs_address}") 54 logger.info(f"Using provided NFS address: {nfs_address}")
30 else: 55 else:
31 try: 56 # Try to auto-discover NFS LoadBalancer IP via Kubernetes API
32 # Try to detect NFS server from /galaxy/server/database/ mount 57 nfs_address = discover_nfs_loadbalancer_ip()
33 import subprocess 58 if not nfs_address:
34 result = subprocess.run(['mount'], capture_output=True, text=True) 59 raise ValueError("Could not auto-detect NFS LoadBalancer IP. Please provide --nfs_address parameter with the LoadBalancer external IP.")
35 nfs_address = None
36
37 for line in result.stdout.split('\n'):
38 if '/galaxy/server/database' in line and ':' in line:
39 # Look for NFS mount pattern: server:/path on /galaxy/server/database
40 parts = line.split()
41 for part in parts:
42 if ':' in part and part.count(':') == 1:
43 nfs_address = part.split(':')[0]
44 break
45 if nfs_address:
46 logger.info(f"Detected NFS address from mount: {nfs_address}")
47 break
48
49 if not nfs_address:
50 # Fallback: try to parse /proc/mounts
51 try:
52 with open('/proc/mounts', 'r') as f:
53 for line in f:
54 if '/galaxy/server/database' in line and ':' in line:
55 parts = line.split()
56 if len(parts) > 0 and ':' in parts[0]:
57 nfs_address = parts[0].split(':')[0]
58 logger.info(f"Detected NFS address from /proc/mounts: {nfs_address}")
59 break
60 except:
61 pass
62
63 if not nfs_address:
64 raise ValueError("Could not auto-detect NFS server address from /galaxy/server/database/ mount")
65
66 logger.info(f"Auto-detected NFS address from mount: {nfs_address}")
67 except Exception as e:
68 logger.error(f"Failed to auto-detect NFS address: {e}")
69 raise
70 return nfs_address, 2049 60 return nfs_address, 2049
71
72 elif args.test_type == 'galaxy_web':
73 # Try to detect Galaxy web service
74 try:
75 import subprocess
76 result = subprocess.run(['kubectl', 'get', 'svc', '-o', 'json'], capture_output=True, text=True)
77 if result.returncode == 0:
78 services = json.loads(result.stdout)
79 for item in services.get('items', []):
80 name = item.get('metadata', {}).get('name', '')
81 if 'galaxy' in name.lower() and ('web' in name.lower() or 'nginx' in name.lower()):
82 # Found a Galaxy web service
83 spec = item.get('spec', {})
84 if spec.get('type') == 'LoadBalancer':
85 ingress = item.get('status', {}).get('loadBalancer', {}).get('ingress', [])
86 if ingress:
87 ip = ingress[0].get('ip')
88 if ip:
89 port = 80
90 for port_spec in spec.get('ports', []):
91 if port_spec.get('port'):
92 port = port_spec['port']
93 break
94 logger.info(f"Found Galaxy web service LoadBalancer: {ip}:{port}")
95 return ip, port
96 # Fallback to ClusterIP
97 cluster_ip = spec.get('clusterIP')
98 if cluster_ip and cluster_ip != 'None':
99 port = 80
100 for port_spec in spec.get('ports', []):
101 if port_spec.get('port'):
102 port = port_spec['port']
103 break
104 logger.info(f"Found Galaxy web service ClusterIP: {cluster_ip}:{port}")
105 return cluster_ip, port
106 except Exception as e:
107 logger.warning(f"Could not auto-detect Galaxy web service: {e}")
108
109 # Fallback: try common Galaxy service names
110 common_hosts = ['galaxy-web', 'galaxy-nginx', 'galaxy']
111 logger.info(f"Trying common Galaxy service name: {common_hosts[0]}")
112 return common_hosts[0], 80
113
114 elif args.test_type == 'k8s_dns':
115 # Test Kubernetes DNS resolution
116 return 'kubernetes.default.svc.cluster.local', 443
117
118 elif args.test_type == 'google_dns':
119 # Test external connectivity
120 return '8.8.8.8', 53
121 61
122 else: 62 else:
123 raise ValueError(f"Unsupported test type: {args.test_type}") 63 raise ValueError(f"Unsupported test type: {args.test_type}")
124 64
125 def main(): 65 def main():
126 parser = argparse.ArgumentParser() 66 parser = argparse.ArgumentParser()
127 parser.add_argument('--nfs_address', required=False, help='NFS server address (if not provided, will be auto-detected from /galaxy/server/database/ mount)') 67 parser.add_argument('--nfs_address', required=False, help='NFS server LoadBalancer IP address (if not provided, will be auto-detected via Kubernetes API)')
128 parser.add_argument('--output', required=True) 68 parser.add_argument('--output', required=True)
129 parser.add_argument('--project', required=False, help='GCP Project ID (if not provided, will be extracted from service account key)') 69 parser.add_argument('--project', required=False, help='GCP Project ID (if not provided, will be extracted from service account key)')
130 parser.add_argument('--region', required=True) 70 parser.add_argument('--region', required=True)
131 parser.add_argument('--network', default='default', help='GCP Network name') 71 parser.add_argument('--network', default='default', help='GCP Network name')
132 parser.add_argument('--subnet', default='default', help='GCP Subnet name') 72 parser.add_argument('--subnet', default='default', help='GCP Subnet name')
133 parser.add_argument('--service_account_key', required=True) 73 parser.add_argument('--service_account_key', required=True)
134 parser.add_argument('--test_type', default='nfs', choices=['nfs', 'galaxy_web', 'k8s_dns', 'google_dns', 'custom'],
135 help='Type of connectivity test to perform')
136 parser.add_argument('--custom_host', required=False, help='Custom host to test (required if test_type is custom)')
137 parser.add_argument('--custom_port', type=int, default=80, help='Custom port to test (default: 80)')
138 args = parser.parse_args() 74 args = parser.parse_args()
75
76 # Default to NFS test type since that's what this tool is for
77 args.test_type = 'nfs'
139 78
140 # Set up authentication using the service account key 79 # Set up authentication using the service account key
141 os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = args.service_account_key 80 os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = args.service_account_key
142 logger.info(f"Authentication configured with service account: {args.service_account_key}") 81 logger.info(f"Authentication configured with service account: {args.service_account_key}")
143 82
180 runnable.container.image_uri = "afgane/gcp-batch-netcat:0.2.0" 119 runnable.container.image_uri = "afgane/gcp-batch-netcat:0.2.0"
181 120
182 # Create a comprehensive test script 121 # Create a comprehensive test script
183 test_script = f'''#!/bin/bash 122 test_script = f'''#!/bin/bash
184 set -e 123 set -e
185 echo "=== GCP Batch Connectivity Test ===" 124 echo "=== GCP Batch NFS Connectivity Test ==="
186 echo "Test Type: {args.test_type}"
187 echo "Target: {target_host}:{target_port}" 125 echo "Target: {target_host}:{target_port}"
188 echo "Timestamp: $(date)" 126 echo "Timestamp: $(date)"
189 echo "Container hostname: $(hostname)" 127 echo "Container hostname: $(hostname)"
190 echo "" 128 echo ""
191 129
212 nslookup {target_host} 8.8.8.8 || echo "DNS resolution failed even with Google DNS" 150 nslookup {target_host} 8.8.8.8 || echo "DNS resolution failed even with Google DNS"
213 }} 151 }}
214 echo "" 152 echo ""
215 153
216 # Basic connectivity test 154 # Basic connectivity test
217 echo "=== Primary Connectivity Test ===" 155 echo "=== Primary NFS Connectivity Test ==="
218 echo "Testing connection to {target_host}:{target_port}..." 156 echo "Testing connection to NFS server {target_host}:{target_port}..."
219 timeout 30 nc -z -v -w 10 {target_host} {target_port} 157 timeout 30 nc -z -v -w 10 {target_host} {target_port}
220 nc_result=$? 158 nc_result=$?
221 echo "Netcat result: $nc_result" 159 echo "Netcat result: $nc_result"
222 echo "" 160 echo ""
223 161
224 # Additional connectivity tests 162 # Additional connectivity tests
225 echo "=== Additional Connectivity Tests ===" 163 echo "=== Additional Connectivity Tests ==="
226 echo "Testing Google DNS (8.8.8.8:53):" 164 echo "Testing external connectivity (Google DNS 8.8.8.8:53):"
227 timeout 10 nc -z -v -w 5 8.8.8.8 53 && echo "✓ External DNS reachable" || echo "✗ External DNS unreachable" 165 timeout 10 nc -z -v -w 5 8.8.8.8 53 && echo "✓ External DNS reachable" || echo "✗ External DNS unreachable"
228
229 echo "Testing Kubernetes API (if accessible):"
230 timeout 10 nc -z -v -w 5 kubernetes.default.svc.cluster.local 443 2>/dev/null && echo "✓ Kubernetes API reachable" || echo "✗ Kubernetes API unreachable"
231 166
232 echo "" 167 echo ""
233 echo "=== Network Troubleshooting ===" 168 echo "=== Network Troubleshooting ==="
234 echo "Route table:" 169 echo "Route table:"
235 ip route 170 ip route
236 echo "" 171 echo ""
237 echo "ARP table:"
238 arp -a 2>/dev/null || echo "ARP command not available"
239 echo ""
240 172
241 echo "=== Final Result ===" 173 echo "=== Final Result ==="
242 if [ $nc_result -eq 0 ]; then 174 if [ $nc_result -eq 0 ]; then
243 echo "✓ SUCCESS: Connection to {target_host}:{target_port} successful" 175 echo "✓ SUCCESS: Connection to NFS server {target_host}:{target_port} successful"
244 exit 0 176 exit 0
245 else 177 else
246 echo "✗ FAILED: Connection to {target_host}:{target_port} failed" 178 echo "✗ FAILED: Connection to NFS server {target_host}:{target_port} failed"
247 echo "This suggests a network connectivity issue between GCP Batch and the target service." 179 echo "This suggests a network connectivity issue between GCP Batch and the NFS server."
248 echo "Common causes:" 180 echo "Common causes:"
249 echo "- Firewall rules blocking traffic" 181 echo "- Firewall rules blocking NFS traffic (port 2049)"
250 echo "- Service not accessible from external networks" 182 echo "- NFS service not accessible from external networks (only ClusterIP)"
251 echo "- Target service only accepting internal cluster traffic" 183 echo "- NFS server not properly exposed via LoadBalancer"
184 echo ""
185 echo "Solutions:"
186 echo "- Ensure NFS service has type LoadBalancer with external IP"
187 echo "- Check GCP firewall rules allow traffic from Batch subnet to NFS"
188 echo "- Verify the IP address is the LoadBalancer external IP, not ClusterIP"
252 exit 1 189 exit 1
253 fi 190 fi
254 ''' 191 '''
255 192
256 runnable.container.entrypoint = "/bin/bash" 193 runnable.container.entrypoint = "/bin/bash"
315 f.write(f"Job name: {job_name}\n") 252 f.write(f"Job name: {job_name}\n")
316 f.write(f"Job response name: {job_response.name}\n") 253 f.write(f"Job response name: {job_response.name}\n")
317 f.write(f"Job UID: {job_response.uid}\n") 254 f.write(f"Job UID: {job_response.uid}\n")
318 f.write(f"Project: {project_id}\n") 255 f.write(f"Project: {project_id}\n")
319 f.write(f"Region: {args.region}\n") 256 f.write(f"Region: {args.region}\n")
320 f.write(f"Test Type: {args.test_type}\n") 257 f.write(f"NFS Target: {target_host}:{target_port}\n")
321 f.write(f"Target: {target_host}:{target_port}\n")
322 f.write(f"\nTo view job logs, run:\n") 258 f.write(f"\nTo view job logs, run:\n")
323 f.write(f"gcloud logging read 'resource.type=gce_instance AND resource.labels.instance_id={job_name}' --project={project_id}\n") 259 f.write(f"gcloud logging read 'resource.type=gce_instance AND resource.labels.instance_id={job_name}' --project={project_id}\n")
324 260
325 except Exception as e: 261 except Exception as e:
326 logger.error(f"Error submitting job: {type(e).__name__}: {e}") 262 logger.error(f"Error submitting job: {type(e).__name__}: {e}")
332 f.write(f"Error submitting job: {type(e).__name__}: {e}\n") 268 f.write(f"Error submitting job: {type(e).__name__}: {e}\n")
333 f.write(f"Error details: {str(e)}\n") 269 f.write(f"Error details: {str(e)}\n")
334 f.write(f"Job name: {job_name}\n") 270 f.write(f"Job name: {job_name}\n")
335 f.write(f"Project: {project_id}\n") 271 f.write(f"Project: {project_id}\n")
336 f.write(f"Region: {args.region}\n") 272 f.write(f"Region: {args.region}\n")
337 f.write(f"Test Type: {args.test_type}\n") 273 f.write(f"NFS Target: {target_host}:{target_port}\n")
338 f.write(f"Target: {target_host}:{target_port}\n")
339 f.write(f"Traceback:\n") 274 f.write(f"Traceback:\n")
340 f.write(traceback.format_exc()) 275 f.write(traceback.format_exc())
341 276
342 if __name__ == '__main__': 277 if __name__ == '__main__':
343 main() 278 main()