Skip to content

dynamic port assignment while creating user session #736

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/oci_cli/cli_setup_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import oci._vendor.jwt as jwt
import oci
import oci.regions as regions
import socket
import os
import sys
import uuid
Expand All @@ -39,6 +40,25 @@
@cli_util.help_option
@click.pass_context
@cli_util.wrap_exceptions
def is_port_available(port):
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind('',port)
return True
except OSError as e:
return False


def find_port(start_port,max_attempts=100):
"""Find an available port starting from start_port"""
if is_port_available(start_port):
return start_port
for port in range(start_port+1,start_port+max_attempts+1):
if is_port_available(port):
return port
raise OSError(f"Could not find an available port in the range {start_port + 1} to {start_port + max_attempts}.")


def bootstrap_oci_cli(ctx, profile_name, config_location):
region_param = ctx.obj['region'] if ctx.obj['region'] else ''
user_session = create_user_session(region=region_param)
Expand Down Expand Up @@ -114,8 +134,12 @@ def create_user_session(region='', tenancy_name=None):
if region == '':
region = cli_setup.prompt_for_region()



# try to set up http server so we can fail early if the required port is in use
try:
# Firstly, we will check if PORT is available or not
BOOTSTRAP_SERVICE_PORT=is_port_available(BOOTSTRAP_SERVICE_PORT)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Convention requires constants to be referenced in uppercase and immutable, so I would suggest creating DEFAULT_BOOTSTRAP_SERVICE_PORT as 8181 (at the top of the file) and then setting boot_strap_service_port here in lowercase, as it's a variable, not a constant.

Also, shouldn't this be calling find_port instead of is_port_available?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, it should be calling find_port, just saw that typo.

server_address = ('', BOOTSTRAP_SERVICE_PORT)
httpd = StoppableHttpServer(server_address, StoppableHttpRequestHandler)
except OSError as e:
Expand Down