Skip to content

Commit

Permalink
Code optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
taleksovska committed Mar 7, 2024
1 parent c51d97a commit c06fed4
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 107 deletions.
2 changes: 1 addition & 1 deletion enabler/commands/cmd_apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def ns(ctx, kube_context_cli, kube_context, name):
capture_output=True)
if ns_exists.returncode != 0:
try:
app_ns = s.run(['kubectl',
app_ns = s.run(['kubectl', # noqa
'create',
'ns',
name,
Expand Down
77 changes: 31 additions & 46 deletions enabler/commands/cmd_kind.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,20 @@ def cli(ctx, kube_context_cli):
@click.pass_context
@pass_environment
def create(ctx, kube_context_cli, kube_context, configfile):
"""Create a kind cluster"""

if ctx.kube_context is not None:
kube_context=ctx.kube_context
kube_context = ctx.kube_context
if ctx.kube_context is None and kube_context is None:

logger.error("--kube-context was not specified")
raise click.Abort()

#Check if config file exists
# Check if config file exists
base_name, extension = os.path.splitext(configfile)
if not os.path.exists(configfile) or extension!='.yaml':
if not os.path.exists(configfile) or extension != '.yaml':
logger.error('Config file not found.')
raise click.Abort()

kind_configfile_validation(configfile)
#Check if kind cluster is already created

# Check if kind cluster is already created
if kind.kind_get(kube_context):
logger.error('Kind cluster \'' + kube_context + '\' already exists')
raise click.Abort()
Expand All @@ -58,12 +55,10 @@ def create(ctx, kube_context_cli, kube_context, configfile):
'--name',
kube_context,
'--config',
click.format_filename(configfile)],
click.format_filename(configfile)],
capture_output=False, check=True)
except s.CalledProcessError as error:
logger.critical('Could not create kind cluster: ' +
str(error))

logger.critical('Could not create kind cluster: ' + str(error))


@cli.command('delete', short_help='Delete cluster')
Expand All @@ -80,7 +75,6 @@ def delete(ctx, kube_context_cli, kube_context):
if ctx.kube_context is None and kube_context is None:
logger.error("--kube-context was not specified")
raise click.Abort()

if not kind.kind_get(kube_context):
logger.error('Kind cluster \'' + kube_context + '\' doesn\'t exist')
raise click.Abort()
Expand Down Expand Up @@ -125,7 +119,7 @@ def status(ctx, kube_context):
required=False)
@click.pass_context
@pass_environment
def start(ctx,kube_context_cli, kube_context):
def start(ctx, kube_context_cli, kube_context):
"""Start kind cluster"""

# Kind creates containers with a label io.x-k8s.kind.cluster
Expand All @@ -139,7 +133,6 @@ def start(ctx,kube_context_cli, kube_context):
logger.error("--kube-context was not specified")
raise click.Abort()


kind_cp = kube_context + '-control-plane'
kind_workers = kube_context + '-worker'

Expand Down Expand Up @@ -199,7 +192,7 @@ def start(ctx,kube_context_cli, kube_context):
required=False)
@click.pass_context
@pass_environment
def stop(ctx,kube_context_cli, kube_context):
def stop(ctx, kube_context_cli, kube_context):
"""Stop kind cluster"""
# Check if the cluster exists
if ctx.kube_context is not None:
Expand All @@ -224,7 +217,8 @@ def stop(ctx,kube_context_cli, kube_context):
if kind_cp in container.name or kind_workers in container.name:
if container.status == 'running':
container.stop()
logger.debug('Container ' + container.name + ' stopped')
logger.debug('Container ' + container.name
+ ' stopped')
else:
logger.debug('Container ' + container.name +
' is already stopped')
Expand All @@ -233,59 +227,50 @@ def stop(ctx,kube_context_cli, kube_context):
logger.error('Kind cluster \'' + kube_context + '\' does not exist.')



#Functions to check if config file has neccessary fields and localhost port is free
# Functions to check if config file has neccessary fields
# and localhost port is free
def kind_configfile_validation(configfile):
"""Validates kind-cluster.yaml file"""

#Get content of configfile
# Get content of configfile
with open(configfile, 'r') as yaml_file:
yaml_content = yaml_file.read()

keywords_to_check = ['kind', 'apiVersion', 'nodes']
lines = yaml_content.split('\n')

keywords_in_file=[]
keywords_in_file = []
for line in lines:
#Check if there is hostPort field in the .yaml file to check if the port is free
index= line.find('hostPort:')
index = line.find('hostPort:')
if index != -1:
line_content=line.strip().split(" ")
port=line_content[1]
try:
if check_if_port_is_free(int(port))==False:
logger.warn("Possible port conflict on hostPort: "+port+' in '+ configfile +'.')
except:
line_content = line.strip().split(" ")
port = line_content[1]
if check_if_port_is_free(int(port)) is not True:
logger.warn("Possible port conflict on hostPort: " + port
+ ' in ' + configfile + '.')
pass

#Check if all key parameters are present and at level 1
# Check if all key parameters are present and at level 1
for key in keywords_to_check:
if f'{key}:' in line[0:len(key)+1]:
if f'{key}:' in line[0:len(key)+1]:
keywords_in_file.append(key)

#Get only unique key words that are missing from yaml
# Get only unique key words that are missing from yaml
difference = list(set(keywords_to_check) - set(keywords_in_file))
missing_string=",".join(difference)
missing_string = ",".join(difference)

if len(difference)==1:
if len(difference) == 1:
logger.warn("Field "+missing_string+" missing in "+configfile+'.')
elif len(difference)>=2:
elif len(difference) >= 2:
logger.warn("Fields "+missing_string+" missing in "+configfile+'.')


def check_if_port_is_free(port_number):
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(2)
s.bind(("127.0.0.1",port_number))
s.settimeout(2)
s.bind(("127.0.0.1", port_number))
s.listen(1)
except (socket.error, ConnectionRefusedError):
return False

return True







23 changes: 11 additions & 12 deletions enabler/commands/cmd_platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import git
import os
import subprocess as s
import pkg_resources


# App group of commands
Expand Down Expand Up @@ -44,11 +43,11 @@ def init(ctx, kube_context_cli, submodules, repopath):
with click_spinner.spinner():
for submodule in submodules:
try:
smodule=repo.submodule(submodule)
smodule = repo.submodule(submodule)
smodule.update()
logger.info('Fetching latest changes for {}'.format(submodule))
except Exception as e:
logger.error(f'An error occurred while updating {submodule}: {e}'.format(submodule,e))
logger.error(f'An error occurred while updating {submodule}: {e}' .format(submodule,e)) # noqa

logger.info('Platform initialized.')

Expand Down Expand Up @@ -80,7 +79,7 @@ def info(ctx, kube_context_cli, kube_context):
capture_output=True, check=True)
logger.info('Platform can be accessed through the URL:')
logger.info(u'\u2023' + ' http://' + gw_url.stdout.decode('utf-8'))
kube_info=s.run(['kubectl', 'cluster-info'],capture_output=True, check=True)
kube_info = s.run(['kubectl', 'cluster-info'], capture_output=True, check=True) # noqa
logger.info(kube_info.stdout.decode('utf-8'))
except s.CalledProcessError as error:
logger.error(error.stderr.decode('utf-8'))
Expand Down Expand Up @@ -162,6 +161,8 @@ def release(ctx, kube_context_cli, version, submodules, repopath):
# TODO: Tag platform and all submodules at their respective SHAs
pass
# TODO: beautify output, check if remotes are ahead, warn anti-patern


@cli.command('version', short_help='Get all versions of components')
@click.argument('submodules',
required=True,
Expand All @@ -182,7 +183,7 @@ def version(ctx, kube_context_cli, submodules, repopath):
repo = get_repo(repopath)
submodules = get_submodules(repo, submodules)
except Exception as e:
logger.error(f'An error occurred while getting {submodule}: {e}'.format(submodule,e))
logger.error(f'An error occurred while getting {submodule}: {e}'.format(submodule, e)) # noqa

# Do something with the submodules
all_sm_details = []
Expand Down Expand Up @@ -217,8 +218,8 @@ def version(ctx, kube_context_cli, submodules, repopath):
sm_details['commits_behind'] = sum(1 for c in commits_behind)
except TypeError as error:
if smrepo.head.is_detached:
commit=smrepo.head.commit.hexsha
sm_details['branch'] ='HEAD detached at '+str(commit)
commit = smrepo.head.commit.hexsha
sm_details['branch'] = 'HEAD detached at ' + str(commit)
else:
logger.error(error)

Expand All @@ -233,7 +234,6 @@ def version(ctx, kube_context_cli, submodules, repopath):
# Add submodule details to the list
all_sm_details.append(sm_details)


for sm_details in all_sm_details:
logger.info(sm_details['repo'] + ':')
if 'branch' in sm_details:
Expand All @@ -242,8 +242,7 @@ def version(ctx, kube_context_cli, submodules, repopath):
if 'tag' in sm_details:
logger.info(u'\u2023' + ' Tag: ' + str(sm_details['tag']))
if 'commits_ahead' in sm_details and sm_details['commits_ahead'] > 0:
logger.info(u'\u2023' + ' Ahead by: ' +
str(sm_details['commits_ahead']) + ' commits')
logger.info(u'\u2023' + ' Ahead by: ' + str(sm_details['commits_ahead']) + ' commits') # noqa

if 'commits_behind' in sm_details and sm_details['commits_behind'] > 0:
logger.info(u'\u2023' + ' Behind by: ' +
str(sm_details['commits_behind']) + ' commits')
logger.info(u'\u2023' + ' Behind by: ' + str(sm_details['commits_behind']) + ' commits') # noqa
Loading

0 comments on commit c06fed4

Please sign in to comment.