-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.py
329 lines (276 loc) · 9.26 KB
/
plugin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
#
# Copyright 2023 SUSE LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Implements the CSP hook functions for Amazon AWS. This handles the
metered billing of product usage in the AWS Marketplace.
"""
import boto3
import json
import logging
import time
import urllib.request
import urllib.error
import csp_billing_adapter
from datetime import datetime
from socket import (has_ipv6, create_connection)
from csp_billing_adapter.config import Config
from csp_billing_adapter_amazon import __version__
log = logging.getLogger('CSPBillingAdapter')
@csp_billing_adapter.hookimpl
def setup_adapter(config: Config):
"""Handle any plugin specific setup at adapter start"""
pass
def meter_usage(
status: dict,
config: Config,
region: str,
timestamp: datetime,
dimensions: dict,
dry_run: str
):
for dimension_name, usage_quantity in dimensions.items():
retries = 3
while retries > 0:
try:
client = boto3.client(
'meteringmarketplace',
region_name=region
)
response = client.meter_usage(
ProductCode=config.product_code,
Timestamp=timestamp,
UsageDimension=dimension_name,
UsageQuantity=usage_quantity,
DryRun=dry_run
)
except Exception as error:
exc = error
retries -= 1
continue
else:
record_id = response.get('MeteringRecordId', None)
log.info(f'New metered billing record with ID: {record_id}')
status[dimension_name] = {
'record_id': record_id,
'status': 'submitted'
}
exc = None
break
if exc:
msg = (
f'Failed to meter bill dimension {dimension_name}: {str(exc)}'
)
status[dimension_name] = {
'error': msg,
'status': 'failed'
}
log.error(msg)
def batch_meter_usage(
status: dict,
config: Config,
region: str,
timestamp: datetime,
dimensions: dict,
customer_id: str
):
records = []
for dimension_name, usage_quantity in dimensions.items():
records.append({
'Timstamp': timestamp,
'CustomerIdentifier': customer_id,
'Dimension': dimension_name,
'Quantity': usage_quantity
})
retries = 3
exc = None
while retries > 0:
try:
client = boto3.client(
'meteringmarketplace',
region_name=region
)
response = client.batch_meter_usage(
UsageRecords=records,
ProductCode=config.product_code
)
except Exception as error:
exc = error
retries -= 1
continue
else:
for record in response.get('Results', []):
dimension = record['UsageRecord']['Dimension']
record_id = record.get('MeteringRecordId', None)
dim_status = record.get('Status')
if not dim_status:
msg = f'Status unknown for dimension: {dimension}'
status[dimension] = {
'error': msg,
'status': 'failed'
}
log.error(msg)
elif dim_status == 'CustomerNotSubscribed':
msg = f'Customer not subscribed to {config.product_code}'
status[dimension] = {
'error': msg,
'status': 'failed'
}
log.error(msg)
else:
status[dimension] = {
'record_id': record_id,
'status': 'submitted'
}
log.info(
'New batch metered billing record '
f'with ID: {record_id} for dimension: {dimension}'
)
for record in response.get('UnprocessedRecords', []):
dimension = record['Dimension']
msg = f'Unable to process metering for dimension: {dimension}'
status[dimension] = {
'error': msg,
'status': 'failed'
}
log.error(msg)
break
if exc:
msg = (
f'Failed to meter bill. {str(exc)}'
)
log.error(msg)
for record in records:
status[record['Dimension']] = {
'error': msg,
'status': 'failed'
}
@csp_billing_adapter.hookimpl(trylast=True)
def meter_billing(
config: Config,
dimensions: dict,
timestamp: datetime,
dry_run: bool,
customer_id: str = None
):
"""
Process a metered billing based on the dimensions provided
If a single dimension is provided the meter_usage API is
used for the metering. If there is an error the metering
is attempted 3 times before re-raising the exception to
calling scope.
"""
region = get_region()
status = {}
if customer_id:
batch_meter_usage(
status,
config,
region,
timestamp,
dimensions,
customer_id
)
else:
meter_usage(status, config, region, timestamp, dimensions, dry_run)
return status
@csp_billing_adapter.hookimpl(trylast=True)
def get_csp_name(config: Config):
"""Return CSP provider name"""
return 'amazon'
def get_region():
"""Return the region name"""
api_header = _get_api_header()
document = _fetch_metadata('document', api_header)
metadata = json.loads(document)
region = metadata.get('region')
if not region:
raise Exception('Unable to retrieve current region.')
return region
@csp_billing_adapter.hookimpl(trylast=True)
def get_account_info(config: Config):
"""
Return a dictionary with account information
The information contains the metadata for document, signature and pkcs7.
"""
account_info = _get_metadata()
account_info['document'] = json.loads(account_info.get('document', '{}'))
account_info['cloud_provider'] = get_csp_name(config)
return account_info
def _get_ip_addr():
metadata_ip_addrs = {
'ipv6_addr': 'fd00:ec2::254',
'ipv4_addr': '169.254.169.254'
}
# Check if the Python implementation has IPv6 support in the first place
if not has_ipv6:
return metadata_ip_addrs.get('ipv4_addr')
for ip_family, ip_addr in metadata_ip_addrs.items():
for i in range(3):
try:
socket = create_connection((ip_addr, 80), timeout=1)
socket.close()
if ip_family == 'ipv6_addr':
# Make the IPv6 address http friendly
ip_addr = f'[{ip_addr}]'
return ip_addr
except OSError:
# Cannot reach the network
break
except TimeoutError:
# Not ready yet wait a little bit
time.sleep(1)
def _get_api_header():
"""
Get the header to be used in requests
Prefer IMDSv2 which requires a token.
"""
ip_addr = _get_ip_addr()
request = urllib.request.Request(
f'http://{ip_addr}/latest/api/token',
headers={'X-aws-ec2-metadata-token-ttl-seconds': '21600'},
method='PUT'
)
try:
token = urllib.request.urlopen(request).read().decode()
except urllib.error.URLError as error:
error_message = f'Failed to retrieve metadata token: {str(error)}'
log.error(error_message)
raise Exception(error_message)
return {'X-aws-ec2-metadata-token': token}
def _get_metadata():
metadata_options = ['document', 'signature', 'pkcs7']
metadata = {}
request_header = _get_api_header()
for metadata_option in metadata_options:
metadata[metadata_option] = _fetch_metadata(
metadata_option,
request_header
)
return metadata
def _fetch_metadata(uri, request_header):
"""Return the response of the metadata request."""
ip_addr = _get_ip_addr()
url = f'http://{ip_addr}/latest/dynamic/instance-identity/{uri}'
data_request = urllib.request.Request(url, headers=request_header)
try:
value = urllib.request.urlopen(data_request).read()
except urllib.error.URLError as error:
log.error(f'Failed to retrieve metadata for: {url}. {str(error)}')
return None
return value.decode()
@csp_billing_adapter.hookimpl
def get_version():
return ('amazon_plugin', __version__)