Skip to content

Commit 70440cc

Browse files
authored
Fixes to handle multi-file upload. (#40)
* Fixes to handle multi-file upload. * Creates manifest when generating tar.gz with specified files * Updates collect role to use package_reports output * Removed upload files after upload * Switch to a 3 day lookback window to reduce the size of the view.
1 parent e7a5355 commit 70440cc

9 files changed

+55
-20
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,6 @@ molecule/test-local/.kube/
66

77
# testing directory for local development to modify openshift resources
88
testing/
9+
10+
# vscode settings
11+
.vscode/

molecule/crds/report_crd.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
---
12
kind: CustomResourceDefinition
23
apiVersion: apiextensions.k8s.io/v1beta1
34
metadata:

molecule/crds/report_datasource_crd.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
---
12
kind: CustomResourceDefinition
23
apiVersion: apiextensions.k8s.io/v1beta1
34
metadata:

molecule/crds/report_query_crd.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
---
12
kind: CustomResourceDefinition
23
apiVersion: apiextensions.k8s.io/v1beta1
34
metadata:

roles/collect/files/package_report.py

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
import sys
2727
import tarfile
2828
from datetime import datetime
29-
29+
from uuid import uuid4
3030

3131
DEFAULT_MAX_SIZE = 100
3232
MEGABYTE = 1024 * 1024
@@ -82,7 +82,6 @@ def parse_args():
8282
help="OCP Cluster ID")
8383
parser.add_argument("-v", "--verbosity", action="count",
8484
default=0, help="increase verbosity (up to -vvv)")
85-
parser.add_argument("--manifest-id", required=True, help="Manifest UUID")
8685
return parser.parse_args()
8786

8887

@@ -179,19 +178,25 @@ def split_files(filepath, max_size):
179178
LOG.info(f"Split files: {split_files}")
180179

181180

182-
def render_manifest(args):
181+
def render_manifest(args, archivefiles=[]):
183182
"""Render the manifest template and write it to a file.
184183
185184
Args:
186185
args (Namespace) an ArgumentParser Namespace object
187186
188187
Returns:
189188
(str) the rendered manifest file name
189+
(str) the manifest uuid
190190
"""
191191
manifest = TEMPLATE
192+
manifest_uuid = str(uuid4())
192193
manifest["cluster_id"] = args.ocp_cluster_id
193-
manifest["files"] = os.listdir(args.filepath)
194-
manifest["uuid"] = args.manifest_id
194+
manifest["uuid"] = manifest_uuid
195+
manifest_files = []
196+
for idx in range(len(archivefiles)):
197+
upload_name = f"{manifest_uuid}_openshift_usage_report.{idx}.csv"
198+
manifest_files.append(upload_name)
199+
manifest["files"] = manifest_files
195200
LOG.debug(f"rendered manifest: {manifest}")
196201
manifest_filename = f"{args.filepath}/manifest.json"
197202

@@ -206,13 +211,14 @@ def render_manifest(args):
206211
LOG.critical(f"Fatal error: {exc}")
207212
sys.exit(2)
208213
LOG.info(f"manifest generated")
209-
return manifest_filename
214+
return (manifest_filename, manifest_uuid)
210215

211216

212-
def write_tarball(tarfilename, archivefiles=[]):
217+
def write_tarball(args, tarfilename, archivefiles=[]):
213218
"""Write a tarball, adding the given files to the archive.
214219
215220
Args:
221+
args (Namespace) an ArgumentParser Namespace object
216222
tarfilename (str) the name of the tarball to create
217223
archivefiles (list) the list of files to include in the archive
218224
@@ -222,11 +228,20 @@ def write_tarball(tarfilename, archivefiles=[]):
222228
Raises:
223229
FileExistsError if tarfilename already exists
224230
"""
231+
if not archivefiles:
232+
return None
233+
234+
manifest_filename, manifest_uuid = render_manifest(args, archivefiles)
225235
try:
226236
with tarfile.open(tarfilename, f"{FILE_FLAG}:gz") as tarball:
237+
file_count = 0
227238
for fname in archivefiles:
228239
LOG.debug(f"Adding {fname} to {tarfilename}: ")
229-
tarball.add(fname, arcname=os.path.sep)
240+
if fname.endswith(".csv"):
241+
upload_name = f"{manifest_uuid}_openshift_usage_report.{file_count}.csv"
242+
tarball.add(fname, arcname=upload_name)
243+
file_count += 1
244+
tarball.add(manifest_filename, arcname="manifest.json")
230245
except FileExistsError as exc:
231246
LOG.critical(exc)
232247
sys.exit(2)
@@ -247,20 +262,22 @@ def write_tarball(tarfilename, archivefiles=[]):
247262
need_split = need_split(args.filepath, args.max_size)
248263
if need_split:
249264
split_files(args.filepath, args.max_size)
250-
manifest_filename = render_manifest(args)
251-
252265
tarpath = args.filepath + "/../"
253266
tarfiletmpl = "cost-mgmt{}.tar.gz"
254267
for idx, filename in enumerate(os.listdir(args.filepath)):
255268
if ".csv" in filename:
256269
tarfilename = os.path.abspath(
257270
tarpath + tarfiletmpl.format(idx))
258-
out_files.append(write_tarball(
259-
tarfilename, [f"{args.filepath}/{filename}", manifest_filename]))
271+
output_tar = write_tarball(args,
272+
tarfilename, [f"{args.filepath}/{filename}"])
273+
if output_tar:
274+
out_files.append(output_tar)
260275
else:
261-
render_manifest(args)
262276
tarfilename = os.path.abspath(args.filepath + "/../cost-mgmt.tar.gz")
263-
out_files.append(write_tarball(tarfilename, [args.filepath]))
277+
files = [f"{args.filepath}/{filename}" for filename in os.listdir(args.filepath)]
278+
output_tar = write_tarball(args, tarfilename, files)
279+
if output_tar:
280+
out_files.append(output_tar)
264281

265282
for fname in out_files:
266283
print(fname)

roles/collect/tasks/main.yml

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@
320320
- '{{ csv_stat_result.results }}'
321321

322322
- name: Run packaging script to prepare reports for sending to Insights
323-
script: package_report.py --filepath {{ ocp_cluster_id }} --max-size {{ collect_max_csvfile_size }} --ocp-cluster-id {{ ocp_cluster_id }} --overwrite --manifest-id {{ collect_file_prefix }}
323+
script: package_report.py --filepath {{ ocp_cluster_id }} --max-size {{ collect_max_csvfile_size }} --ocp-cluster-id {{ ocp_cluster_id }} --overwrite
324324
args:
325325
chdir: '{{ collect_download_path }}'
326326
register: packaged_reports
@@ -336,12 +336,24 @@
336336

337337
- name: Upload the cost report to ingress using basic auth
338338
shell:
339-
cmd: 'curl -vvvv -F "file=@cost-mgmt.tar.gz;type=application/vnd.redhat.hccm.tar+tgz" {{ ingress_url }} -u {{ username }}:{{ password }} --cacert {{ cacert_path }}'
339+
cmd: 'curl -vvvv -F "file=@{{ item }};type=application/vnd.redhat.hccm.tar+tgz" {{ ingress_url }} -u {{ username }}:{{ password }} --cacert {{ cacert_path }}'
340340
chdir: '{{ collect_download_path }}'
341+
with_items:
342+
- '{{ packaged_reports.stdout_lines }}'
341343
when: authentication == 'basic'
342344

343345
- name: Upload the cost report to ingress using token auth
344346
shell:
345-
cmd: 'curl -vvvv -F "file=@cost-mgmt.tar.gz;type=application/vnd.redhat.hccm.tar+tgz" {{ ingress_url }} -H "Authorization: Bearer {{ authentication_token }}" -H "User-Agent: cost-mgmt-operator/{{ source_commit }} cluster/{{ ocp_cluster_id }}" --cacert {{ cacert_path }}'
347+
cmd: 'curl -vvvv -F "file=@{{ item }};type=application/vnd.redhat.hccm.tar+tgz" {{ ingress_url }} -H "Authorization: Bearer {{ authentication_token }}" -H "User-Agent: cost-mgmt-operator/{{ source_commit }} cluster/{{ ocp_cluster_id }}" --cacert {{ cacert_path }}'
346348
chdir: '{{ collect_download_path }}'
349+
with_items:
350+
- '{{ packaged_reports.stdout_lines }}'
347351
when: authentication == 'token'
352+
353+
- name: Remove upload files
354+
file:
355+
path: '{{ collect_download_path }}/{{ item }}'
356+
state: absent
357+
with_items:
358+
- '{{ packaged_reports.stdout_lines }}'
359+
when: collect_delete_after | bool

roles/setup/files/cm_openshift_node_labels_lookback_report_query.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,4 @@ spec:
4040
interval_end,
4141
node_labels
4242
FROM {| .Report.Inputs.CostManagementOpenShiftNodeLabelsReportName | reportTableName |}
43-
WHERE {| .Report.Inputs.CostManagementOpenShiftNodeLabelsReportName | reportTableName |}.interval_start >= timestamp '{| default .Report.ReportingStart .Report.Inputs.ReportingStart | prestoTimestamp |}' - interval '10' day
43+
WHERE {| .Report.Inputs.CostManagementOpenShiftNodeLabelsReportName | reportTableName |}.interval_start >= timestamp '{| default .Report.ReportingStart .Report.Inputs.ReportingStart | prestoTimestamp |}' - interval '3' day

roles/setup/files/cm_openshift_persistentvolumeclaim_lookback_report_query.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,4 @@ spec:
7575
persistentvolume_labels,
7676
persistentvolumeclaim_labels
7777
FROM {| .Report.Inputs.PersistentVolumeClaimUsageReportName | reportTableName |}
78-
WHERE {| .Report.Inputs.PersistentVolumeClaimUsageReportName | reportTableName |}.interval_start >= timestamp '{| default .Report.ReportingStart .Report.Inputs.ReportingStart | prestoTimestamp |}' - interval '10' day
78+
WHERE {| .Report.Inputs.PersistentVolumeClaimUsageReportName | reportTableName |}.interval_start >= timestamp '{| default .Report.ReportingStart .Report.Inputs.ReportingStart | prestoTimestamp |}' - interval '3' day

roles/setup/files/cm_openshift_usage_lookback_report_query.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,4 +91,4 @@ spec:
9191
resource_id,
9292
pod_labels
9393
FROM {| .Report.Inputs.CostManagementOpenShiftUsageReportName | reportTableName |}
94-
WHERE {| .Report.Inputs.CostManagementOpenShiftUsageReportName | reportTableName |}.interval_start >= timestamp '{| default .Report.ReportingStart .Report.Inputs.ReportingStart | prestoTimestamp |}' - interval '10' day
94+
WHERE {| .Report.Inputs.CostManagementOpenShiftUsageReportName | reportTableName |}.interval_start >= timestamp '{| default .Report.ReportingStart .Report.Inputs.ReportingStart | prestoTimestamp |}' - interval '3' day

0 commit comments

Comments
 (0)