Skip to content

Commit a9bb8a6

Browse files
author
Himani Anil Deshpande
committed
Cookstyle and code-linters corrections
* Correcting Kitchen and Unit tests * Adding share_compute_fleet_dna.py for tox checks
1 parent adc3aff commit a9bb8a6

File tree

11 files changed

+209
-133
lines changed

11 files changed

+209
-133
lines changed

cookbooks/aws-parallelcluster-environment/files/cfn_hup_configuration/share_compute_fleet_dna.py

Lines changed: 49 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -11,30 +11,36 @@
1111
# limitations under the License.
1212

1313

14-
import configparser
1514
import argparse
16-
from email import message_from_string
15+
import base64
16+
import configparser
1717
import json
18+
import logging
1819
import os
20+
from email import message_from_string
21+
1922
import boto3
20-
from botocore.config import Config
2123
import yaml
22-
import base64
23-
import logging
24+
from botocore.config import Config
2425
from retrying import retry
2526

2627
COMPUTE_FLEET_SHARED_LOCATION = "/opt/parallelcluster/shared/"
2728

28-
COMPUTE_FLEET_SHARED_DNA_LOCATION = COMPUTE_FLEET_SHARED_LOCATION + 'dna/'
29+
COMPUTE_FLEET_SHARED_DNA_LOCATION = COMPUTE_FLEET_SHARED_LOCATION + "dna/"
2930

30-
COMPUTE_FLEET_LAUNCH_TEMPLATE_CONFIG = COMPUTE_FLEET_SHARED_LOCATION + 'launch-templates-config.json'
31+
COMPUTE_FLEET_LAUNCH_TEMPLATE_CONFIG = COMPUTE_FLEET_SHARED_LOCATION + "launch-templates-config.json"
3132

3233
logger = logging.getLogger(__name__)
3334
logging.basicConfig(level=logging.INFO)
3435

36+
3537
def get_compute_launch_template_ids(lt_config_file_name):
36-
"""Load launch-templates-config.json which contains ID, Version number and Logical ID of all queues in Compute Fleet's Launch Template.
37-
The format of launch-templates-config.json is
38+
"""
39+
Load launch-templates-config.json.
40+
41+
It contains ID, Version number and Logical ID of all queues in Compute Fleet's Launch Template.
42+
43+
The format of launch-templates-config.json:
3844
{
3945
"Queues": {
4046
"queue1": {
@@ -61,24 +67,25 @@ def get_compute_launch_template_ids(lt_config_file_name):
6167
}
6268
}
6369
}
70+
6471
"""
6572
lt_config = None
6673
try:
67-
with open(lt_config_file_name, 'r') as file:
74+
with open(lt_config_file_name, "r") as file:
6875
lt_config = json.loads(file.read())
6976
except Exception as err:
70-
logger.warn("Unable to read %s due to %s", lt_config_file_name, err)
77+
logger.warning("Unable to read %s due to %s", lt_config_file_name, err)
7178

72-
return lt_config
79+
return lt_config
7380

7481

7582
def share_compute_fleet_dna(args):
76-
"""Creates all dna.json for each queue in cluster."""
83+
"""Create dna.json for each queue in cluster."""
7784
lt_config = get_compute_launch_template_ids(COMPUTE_FLEET_LAUNCH_TEMPLATE_CONFIG)
7885
if lt_config:
79-
all_queues = lt_config.get('Queues')
86+
all_queues = lt_config.get("Queues")
8087
for _, queues in all_queues.items():
81-
compute_resources = queues.get('ComputeResources')
88+
compute_resources = queues.get("ComputeResources")
8289
for _, compute_res in compute_resources.items():
8390
get_latest_dna_data(compute_res, COMPUTE_FLEET_SHARED_DNA_LOCATION, args)
8491

@@ -98,63 +105,62 @@ def parse_proxy_config():
98105
@retry(stop_max_attempt_number=5, wait_fixed=3000)
99106
def get_user_data(lt_id, lt_version, region_name):
100107
"""
101-
Calls EC2 DescribeLaunchTemplateVersions API to get UserData from Launch Template specified.
108+
Get UserData from specified Launch Template using EC2 DescribeLaunchTemplateVersions API.
109+
102110
:param lt_id: Launch Template ID (eg: lt-12345678901234567)
103111
:param lt_version: Launch Template latest Version Number (eg: 2)
104112
:param region_name: AWS region name (eg: us-east-1)
105-
:return: User_data in MIME format
113+
:return: string of user_data in MIME format
106114
"""
107115
decoded_data = None
108116
try:
109117
proxy_config = parse_proxy_config()
110118

111119
ec2_client = boto3.client("ec2", region_name=region_name, config=proxy_config)
112120
response = ec2_client.describe_launch_template_versions(
113-
LaunchTemplateId= lt_id,
121+
LaunchTemplateId=lt_id,
114122
Versions=[
115123
lt_version,
116124
],
117-
).get('LaunchTemplateVersions')
118-
decoded_data = base64.b64decode(response[0]['LaunchTemplateData']['UserData'], validate=True).decode('utf-8')
125+
).get("LaunchTemplateVersions")
126+
decoded_data = base64.b64decode(response[0]["LaunchTemplateData"]["UserData"], validate=True).decode("utf-8")
119127
except Exception as err:
120128
if hasattr(err, "message"):
121129
err = err.message
122130
logger.error(
123-
"Unable to get UserData for launch template %s with version %s.\nException: %s",
124-
lt_id, lt_version, err
131+
"Unable to get UserData for launch template %s with version %s.\nException: %s", lt_id, lt_version, err
125132
)
126133

127134
return decoded_data
128135

129136

130137
def get_write_directives_section(user_data):
131-
"""
132-
Parses MIME formatted UserData that we get from EC2 to extract write_files section from cloud-config section.
133-
"""
138+
"""Get write_files section from cloud-config section of MIME formatted UserData."""
134139
write_directives_section = None
135140
try:
136141
data = message_from_string(user_data)
137142
for cloud_config_section in data.walk():
138-
if cloud_config_section.get_content_type() == 'text/cloud-config':
139-
write_directives_section = yaml.safe_load(cloud_config_section._payload).get('write_files')
143+
if cloud_config_section.get_content_type() == "text/cloud-config":
144+
write_directives_section = yaml.safe_load(cloud_config_section._payload).get("write_files")
140145
except Exception as err:
141146
logger.error("Error occurred while parsing write_files section.\nException: %s", err)
142147
return write_directives_section
143148

144149

145150
def write_dna_files(write_files_section, shared_storage_loc):
146151
"""
147-
Writes the dna.json in shared location after extracting it from write_files section of UserData.
152+
After extracting dna.json from write_files section of UserData, write it in shared location.
153+
148154
:param write_files_section: Entire write_files section from UserData
149155
:param shared_storage_loc: Shared Storage Location of where to write dna.json
150156
:return: None
151157
"""
152158
try:
153-
file_path = shared_storage_loc+"-dna.json"
159+
file_path = shared_storage_loc + "-dna.json"
154160
for data in write_files_section:
155-
if data['path'] in ['/tmp/dna.json']:
156-
with open(file_path,"w") as file:
157-
file.write(json.dumps(json.loads(data['content']),indent=4))
161+
if data["path"] in ["/tmp/dna.json"]:
162+
with open(file_path, "w", encoding="utf-8") as file:
163+
file.write(json.dumps(json.loads(data["content"]), indent=4))
158164
except Exception as err:
159165
if hasattr(err, "message"):
160166
err = err.message
@@ -163,16 +169,19 @@ def write_dna_files(write_files_section, shared_storage_loc):
163169

164170
def get_latest_dna_data(resource, output_location, args):
165171
"""
166-
Function to get latest User Data, extract relevant details and write dna.json.
172+
Get latest User Data, extract relevant details and write dna.json.
173+
167174
:param resource: Resource containing LT ID, Version and Logical id
168175
:param output_location: Shared Storage Location were we want to write dna.json
169176
:param args: Command Line arguments
170177
:rtype: None
171178
"""
172-
user_data = get_user_data(resource.get('LaunchTemplate').get('Id'), resource.get('LaunchTemplate').get('Version'), args.region)
179+
user_data = get_user_data(
180+
resource.get("LaunchTemplate").get("Id"), resource.get("LaunchTemplate").get("Version"), args.region
181+
)
173182
if user_data:
174183
write_directives = get_write_directives_section(user_data)
175-
write_dna_files(write_directives, output_location+resource.get('LaunchTemplate').get("LogicalId"))
184+
write_dna_files(write_directives, output_location + resource.get("LaunchTemplate").get("LogicalId"))
176185

177186

178187
def cleanup(directory_loc):
@@ -183,7 +192,7 @@ def cleanup(directory_loc):
183192
if os.path.isfile(f_path):
184193
os.remove(f_path)
185194
except Exception as err:
186-
logger.warn(f"Unable to delete %s due to %s", f_path, err)
195+
logger.warning("Unable to delete %s due to %s", f_path, err)
187196

188197

189198
def _parse_cli_args():
@@ -224,9 +233,11 @@ def main():
224233
except Exception as err:
225234
if hasattr(err, "message"):
226235
err = err.message
227-
logger.exception("Encountered exception when fetching latest dna.json for ComputeFleet, exiting gracefully: %s", err)
236+
logger.exception(
237+
"Encountered exception when fetching latest dna.json for ComputeFleet, exiting gracefully: %s", err
238+
)
228239
raise SystemExit(0)
229240

230241

231242
if __name__ == "__main__":
232-
main()
243+
main()

cookbooks/aws-parallelcluster-environment/recipes/install/cfn_bootstrap.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@
9494

9595
# Add cfn-hup runner
9696
template "#{node['cluster']['scripts_dir']}/cfn-hup-runner.sh" do
97-
source "cfn_bootstrap/cfn-hup-runner.sh.erb"
97+
source "cfn_hup_configuration/cfn-hup-runner.sh.erb"
9898
owner 'root'
9999
group 'root'
100100
mode '0744'

cookbooks/aws-parallelcluster-environment/spec/unit/recipes/cfn_bootstrap_spec.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@
7777

7878
it 'adds cfn-hup runner' do
7979
is_expected.to create_template("#{node['cluster']['scripts_dir']}/cfn-hup-runner.sh").with(
80-
source: "cfn_bootstrap/cfn-hup-runner.sh.erb",
80+
source: "cfn_hup_configuration/cfn-hup-runner.sh.erb",
8181
owner: 'root',
8282
group: 'root',
8383
mode: '0744',

cookbooks/aws-parallelcluster-environment/spec/unit/recipes/config_spec.rb

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
aws-parallelcluster-environment::raid
2828
aws-parallelcluster-environment::efs
2929
aws-parallelcluster-environment::fsx
30-
aws-parallelcluster-environment::config_cfn_hup
3130
)
3231
@expected_recipes.each do |recipe_name|
3332
allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).with(recipe_name) do

cookbooks/aws-parallelcluster-environment/spec/unit/resources/cfn_hup_configuration_spec.rb

Lines changed: 41 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def self.configure(chef_run)
1818
LAUNCH_TEMPLATE_ID = "LAUNCH_TEMPLATE_ID".freeze
1919
SCRIPT_DIR = "SCRIPT_DIR".freeze
2020
MONITOR_SHARED_DIR = "MONITOR_SHARED_DIR".freeze
21-
NODE_BOOTSTRAP_TIMEOUT = "1800"
21+
NODE_BOOTSTRAP_TIMEOUT = "1800".freeze
2222

2323
describe 'cfn_hup_configuration:configure' do
2424
for_all_oses do |platform, version|
@@ -29,8 +29,8 @@ def self.configure(chef_run)
2929
runner = runner(platform: platform, version: version, step_into: ['cfn_hup_configuration']) do |node|
3030
allow_any_instance_of(Object).to receive(:get_metadata_token).and_return("IMDS_TOKEN")
3131
allow_any_instance_of(Object).to receive(:get_metadata_with_token)
32-
.with("IMDS_TOKEN", URI("http://169.254.169.254/latest/meta-data/iam/security-credentials"))
33-
.and_return(INSTANCE_ROLE_NAME)
32+
.with("IMDS_TOKEN", URI("http://169.254.169.254/latest/meta-data/iam/security-credentials"))
33+
.and_return(INSTANCE_ROLE_NAME)
3434
node.override["cluster"]["node_type"] = node_type
3535
node.override["cluster"]["region"] = AWS_REGION
3636
node.override["cluster"]["aws_domain"] = AWS_DOMAIN
@@ -49,63 +49,63 @@ def self.configure(chef_run)
4949
%w(/etc/cfn /etc/cfn/hooks.d).each do |dir|
5050
it "creates the directory #{dir}" do
5151
is_expected.to create_directory(dir)
52-
.with(owner: 'root')
53-
.with(group: 'root')
54-
.with(mode: "0700")
55-
.with(recursive: true)
52+
.with(owner: 'root')
53+
.with(group: 'root')
54+
.with(mode: "0700")
55+
.with(recursive: true)
5656
end
5757
end
5858

5959
it "creates the file /etc/cfn/cfn-hup.conf" do
6060
is_expected.to create_template("/etc/cfn/cfn-hup.conf")
61-
.with(source: 'cfn_hup_configuration/cfn-hup.conf.erb')
62-
.with(user: "root")
63-
.with(group: "root")
64-
.with(mode: "0400")
65-
.with(variables: {
66-
stack_id: STACK_ID,
67-
region: AWS_REGION,
68-
cloudformation_url: CLOUDFORMATION_URL,
69-
cfn_init_role: INSTANCE_ROLE_NAME,
70-
})
61+
.with(source: 'cfn_hup_configuration/cfn-hup.conf.erb')
62+
.with(user: "root")
63+
.with(group: "root")
64+
.with(mode: "0400")
65+
.with(variables: {
66+
stack_id: STACK_ID,
67+
region: AWS_REGION,
68+
cloudformation_url: CLOUDFORMATION_URL,
69+
cfn_init_role: INSTANCE_ROLE_NAME,
70+
})
7171
end
7272

7373
it "creates the file /etc/cfn/hooks.d/pcluster-update.conf" do
7474
is_expected.to create_template("/etc/cfn/hooks.d/pcluster-update.conf")
75-
.with(source: 'cfn_hup_configuration/cfn-hook-update.conf.erb')
76-
.with(user: "root")
77-
.with(group: "root")
78-
.with(mode: "0400")
79-
.with(variables: {
80-
stack_id: STACK_ID,
81-
region: AWS_REGION,
82-
cloudformation_url: CLOUDFORMATION_URL,
83-
cfn_init_role: INSTANCE_ROLE_NAME,
84-
launch_template_resource_id: LAUNCH_TEMPLATE_ID,
85-
update_hook_script_dir: SCRIPT_DIR,
86-
node_bootstrap_timeout: NODE_BOOTSTRAP_TIMEOUT,
87-
})
75+
.with(source: 'cfn_hup_configuration/cfn-hook-update.conf.erb')
76+
.with(user: "root")
77+
.with(group: "root")
78+
.with(mode: "0400")
79+
.with(variables: {
80+
stack_id: STACK_ID,
81+
region: AWS_REGION,
82+
cloudformation_url: CLOUDFORMATION_URL,
83+
cfn_init_role: INSTANCE_ROLE_NAME,
84+
launch_template_resource_id: LAUNCH_TEMPLATE_ID,
85+
update_hook_script_dir: SCRIPT_DIR,
86+
node_bootstrap_timeout: NODE_BOOTSTRAP_TIMEOUT,
87+
})
8888
end
8989

9090
if %(ComputeFleet).include?(node_type)
9191
it "creates the file #{SCRIPT_DIR}/cfn-hup-update-action.sh" do
9292
is_expected.to create_template("#{SCRIPT_DIR}/cfn-hup-update-action.sh")
93-
.with(source: "cfn_hup_configuration/#{node_type}/cfn-hup-update-action.sh.erb")
94-
.with(user: "root")
95-
.with(group: "root")
96-
.with(mode: "0700")
97-
.with(variables: {
98-
monitor_shared_dir: "#{MONITOR_SHARED_DIR}/dna",
99-
launch_template_resource_id: LAUNCH_TEMPLATE_ID,
93+
.with(source: "cfn_hup_configuration/#{node_type}/cfn-hup-update-action.sh.erb")
94+
.with(user: "root")
95+
.with(group: "root")
96+
.with(mode: "0700")
97+
.with(variables: {
98+
monitor_shared_dir: "#{MONITOR_SHARED_DIR}/dna",
99+
launch_template_resource_id: LAUNCH_TEMPLATE_ID,
100100
})
101101
end
102102
elsif node_type == 'HeadNode'
103103
it "creates #{SCRIPT_DIR}/share_compute_fleet_dna.py" do
104104
is_expected.to create_if_missing_cookbook_file("#{SCRIPT_DIR}/share_compute_fleet_dna.py")
105-
.with(source: 'cfn_hup_configuration/share_compute_fleet_dna.py')
106-
.with(user: 'root')
107-
.with(group: 'root')
108-
.with(mode: '0700')
105+
.with(source: 'cfn_hup_configuration/share_compute_fleet_dna.py')
106+
.with(user: 'root')
107+
.with(group: 'root')
108+
.with(mode: '0700')
109109
end
110110

111111
it "creates the directory #{MONITOR_SHARED_DIR}/dna" do

cookbooks/aws-parallelcluster-environment/test/controls/cfn_hup_configuration_spec.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
its('group') { should eq 'root' }
4343
end
4444

45-
describe directory("#{node['cluster']['base_dir']}/dna") do
45+
describe directory("#{node['cluster']['shared_dir']}/dna") do
4646
it { should exist }
4747
end
4848
end

cookbooks/aws-parallelcluster-platform/spec/unit/resources/fetch_dna_files_spec.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def self.cleanup(chef_run)
3535
node.override['cluster']['region'] = region
3636
node.override['kitchen'] = true
3737
end
38-
ConvergeFetchDnaFiles.share(runner, extra_chef_attribute_location: "#{kitchen_instance_types_data_path}")
38+
ConvergeFetchDnaFiles.share(runner, extra_chef_attribute_location: "#{kitchen_instance_types_data_path}")
3939
end
4040
cached(:node) { chef_run.node }
4141

@@ -46,7 +46,7 @@ def self.cleanup(chef_run)
4646
# end
4747

4848
it 'runs share_compute_fleet_dna.py to get dna files' do
49-
is_expected.to run_execute('Share dna.json with ComputeFleet').with(
49+
is_expected.to run_execute('Run share_compute_fleet_dna.py to get user_data.sh and share dna.json with ComputeFleet').with(
5050
command: "#{cookbook_virtualenv_path}/bin/python #{node['cluster']['scripts_dir']}/share_compute_fleet_dna.py" \
5151
" --region #{node['cluster']['region']}"
5252
)

cookbooks/aws-parallelcluster-slurm/recipes/update/update_head_node.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,4 +284,4 @@ def update_nodes_in_queue(strategy, queues)
284284

285285
fetch_dna_files 'Cleanup' do
286286
action :cleanup
287-
end
287+
end

0 commit comments

Comments
 (0)