2 # SPDX-License-Identifier: EPL-1.0
3 ##############################################################################
4 # Copyright (c) 2019 The Linux Foundation and others.
6 # All rights reserved. This program and the accompanying materials
7 # are made available under the terms of the Eclipse Public License v1.0
8 # which accompanies this distribution, and is available at
9 # http://www.eclipse.org/legal/epl-v10.html
10 ##############################################################################
11 echo "---> job-cost.sh"
15 # shellcheck disable=SC1090
18 # AWS job cost not supported, exit
19 if grep -qi amazon /sys/devices/virtual/dmi/id/bios_vendor ; then
20 echo "INFO: Not able to calculate job cost on AWS"
24 lf-activate-venv python-openstackclient
26 if [[ -z ${JOB_NAME:-} ]]; then
27 lf-echo-error "Required Env Variable Unset/Empty: JOB_NAME"
31 # Get the cost of the Openstack agents. The 'stack-cost' file is created when
32 # the 'lftools openstack stack cost' command is called from
33 # 'openstack-stack-delete.sh' script. The 'stack-cost' file will only be created
34 # if this is an openstack job.
35 if [[ -f stack-cost ]]; then
36 echo "DEBUG: $(cat stack-cost)"
37 echo "INFO: Retrieving Stack Cost..."
38 if ! stack_cost=$(grep -F "total: " stack-cost | awk '{print $2}'); then
39 echo "ERROR: Unable to retrieve Stack Cost, continuing anyway"
43 echo "INFO: No Stack..."
47 # Retrieve the current uptime (in seconds)
48 uptime=$(awk '{print $1}' /proc/uptime)
49 # Convert to integer by truncating fractional part' and round up by one
50 ((uptime=${uptime%\.*}+1))
52 # EC2 and OpenStack have simiar instace metadata APIs at this IP
53 # AWS docs: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
54 # Nova docs: https://docs.openstack.org/nova/latest/user/metadata.html
55 instance_type=$(curl -s http://169.254.169.254/latest/meta-data/instance-type)
57 echo "INFO: Retrieving Pricing Info for: $instance_type"
58 url="https://pricing.vexxhost.net/v1/pricing/$instance_type/cost?seconds=$uptime"
59 json_block=$(curl -s "$url")
61 # check if JSON returned and can be parsed
62 if jq <<< "$json_block"; then
63 cost=$(jq .cost <<< "$json_block")
64 resource=$(jq .resource <<< "$json_block" | tr -d '"')
66 echo "ERROR: Pricing API returned invalid json"
71 # Archive the cost date
72 mkdir -p "$WORKSPACE/archives/cost"
74 echo "INFO: Archiving Costs"
76 # Set the timestamp in GMT
77 # This format is readable by spreadsheet and is easily sortable
78 date=$(TZ=GMT date +'%Y-%m-%d %H:%M:%S')
80 cat << EOF > "$WORKSPACE/archives/cost.csv"
81 $JOB_NAME,$BUILD_NUMBER,$date,$resource,$uptime,$cost,$stack_cost