Skip to content

Commit afa06c7

Browse files
committed
dynamic port assignment while creating user session
Signed-off-by: Anurav Modak <[email protected]>
1 parent 02c2dbf commit afa06c7

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/oci_cli/cli_setup_bootstrap.py

+24
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import oci._vendor.jwt as jwt
1616
import oci
1717
import oci.regions as regions
18+
import socket
1819
import os
1920
import sys
2021
import uuid
@@ -39,6 +40,25 @@
3940
@cli_util.help_option
4041
@click.pass_context
4142
@cli_util.wrap_exceptions
43+
def is_port_available(port):
44+
try:
45+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
46+
s.bind('',port)
47+
return True
48+
except OSError as e:
49+
return False
50+
51+
52+
def find_port(start_port,max_attempts=100):
53+
"""Find an available port starting from start_port"""
54+
if is_port_available(start_port):
55+
return start_port
56+
for port in range(start_port+1,start_port+max_attempts+1):
57+
if is_port_available(port):
58+
return port
59+
raise OSError(f"Could not find an available port in the range {start_port + 1} to {start_port + max_attempts}.")
60+
61+
4262
def bootstrap_oci_cli(ctx, profile_name, config_location):
4363
region_param = ctx.obj['region'] if ctx.obj['region'] else ''
4464
user_session = create_user_session(region=region_param)
@@ -114,8 +134,12 @@ def create_user_session(region='', tenancy_name=None):
114134
if region == '':
115135
region = cli_setup.prompt_for_region()
116136

137+
138+
117139
# try to set up http server so we can fail early if the required port is in use
118140
try:
141+
# Firstly, we will check if PORT is available or not
142+
BOOTSTRAP_SERVICE_PORT=is_port_available(BOOTSTRAP_SERVICE_PORT)
119143
server_address = ('', BOOTSTRAP_SERVICE_PORT)
120144
httpd = StoppableHttpServer(server_address, StoppableHttpRequestHandler)
121145
except OSError as e:

0 commit comments

Comments
 (0)