AWS secret manager time out sometimes - python-3.x

I am fetching a secret from secret manager on a lambda. The request fails sometimes. Which is totally strange, it is working fine and couple of hours later I check and I am getting time out.
def get_credentials(self):
"""Retrieve credentials from the Secrets Manager service."""
boto_config = BotoConfig(connect_timeout=3, retries={"max_attempts": 3})
secrets_client = self.boto_session.client(
service_name="secretsmanager",
region_name=self.boto_session.region_name,
config=boto_config,
)
secret_value = secrets_client.get_secret_value(SecretId=self._secret_name)
secret = secret_value["SecretString"]
I try to debug the lambda and later seems to be working again, without any change, those state changes happen in hours. Any hint why that could happen?
Traceback (most recent call last):
File "/opt/python/botocore/endpoint.py", line 249, in _do_get_response
http_response = self._send(request)
File "/opt/python/botocore/endpoint.py", line 321, in _send
return self.http_session.send(request)
File "/opt/python/botocore/httpsession.py", line 438, in send
raise ConnectTimeoutError(endpoint_url=request.url, error=e)
botocore.exceptions.ConnectTimeoutError: Connect timeout on endpoint URL: "https://secretsmanager.eu-central-1.amazonaws.com/"

You are using the legacy retry mode (is the default one in boto3), which has very limited functionality as it only works for a very limited number of errors.
You should try changing your retry strategy to something like Standard retry mode or Adaptative. In that case your code would look like:
from botocore.config import Config as BotoConfig
boto_config = BotoConfig(
connect_timeout=3,
retries={
"max_attempts": 3,
"mode":"standard"
}
)
secrets_client = self.boto_session.client(
service_name="secretsmanager",
region_name=self.boto_session.region_name,
config=boto_config,
)

Related

Websocket error: "Handhshake status 403 forbidden"

i have a problem with my written code which i wrote with the help of this documentation: https://exchange.blockchain.com/api/#introduction.
The code should send messages, receive messages and then i want to work with the received messages. And that 3 times per day (in the morning, noon and evening).
However the code seems to be working sometimes, actually up to 6 days (record, yay!) and then it stops working and i get an error output:
Traceback (most recent call last):
File "<ipython-input-1-052db9d33d34>", line 1, in <module>
runfile('Pathtofile/File.py', wdir='workingdirectory')
File "C:\Users\iamdabest\Downloads\latexNpython\WinPython64-3.6.8.0\python-
3.6.8.amd64\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line
786, in runfile
execfile(filename, namespace)
File "C:\Users\orami?\Downloads\latexNpython\WinPython64-3.6.8.0\python-
3.6.8.amd64\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line
110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "Pathtofile/File.py", line 235, in <module>
main()
File "Pathtofile/File.py", line 229, in main
trigger(updater.bot)
File "Pathtofile/File.py", line 171, in trigger
y = price_func()[0]
File "Pathtofile/File.py", line 46, in price_func
ws = create_connection(url, **options)
File "C:\Users\name\Downloads\latexNpython\WinPython64-3.6.8.0\python-
3.6.8.amd64\lib\site-packages\websocket\_core.py", line 606, in
create_connection
websock.connect(url, **options)
File "C:\Users\name\Downloads\latexNpython\WinPython64-3.6.8.0\python-
3.6.8.amd64\lib\site-packages\websocket\_core.py", line 253, in connect
self.handshake_response = handshake(self.sock, *addrs, **options)
File "C:\Users\name\Downloads\latexNpython\WinPython64-3.6.8.0\python-
3.6.8.amd64\lib\site-packages\websocket\_handshake.py", line 57, in handshake
status, resp = _get_resp_headers(sock)
File "C:\Users\name\Downloads\latexNpython\WinPython64-3.6.8.0\python-
3.6.8.amd64\lib\site-packages\websocket\_handshake.py", line 143, in
_get_resp_headers
raise WebSocketBadStatusException("Handshake status %d %s", status,
status_message, resp_headers)
WebSocketBadStatusException: Handshake status 403 Forbidden
Now please keep in mind that i never got teached this stuff by a trained professional. All the knowledge i gained is from playing around (plotting and analyzing data) with python and the help of the internet.
I don't really understand why it is working few days and then suddenly stops working.
My questions:
In fact i have no problem when the codes doesn't gives an output as long as it keeps running. So how can i tell the code to 'ignore' the error and keep moving or maybe to automatic restart the code if the error occurs? I tried simple stuff like if statement or try and expect but i wasn't successful.
The error comes because the authentication between Server and Client failed? or what does it mean?
Is there another workaround? I already read somewhere to use another websocket (websockets) but wasn't able to get it working.
Here is a (M)WE of my code:
from websocket import create_connection
import json
options = {}
options['origin'] = 'https://exchange.blockchain.com'
url = "wss://ws.prod.blockchain.info/mercury-gateway/v1/ws"
def price_func():
ws = create_connection(url, **options)
msg = '{"token": "mysecretAPItoken", "action": "subscribe", "channel": "auth"}' # here i subscribe
ws.send(msg)
msg = '{"action": "subscribe", "channel": "balances"}' # here i am asking for the json files
ws.send(msg)
result1 = json.loads(ws.recv()) # first answer is the confirmation of connecting
result2 = json.loads(ws.recv()) # save the received answers to work with them later
msg = '{"token": "mysecretAPItoken", "action": "unsubscribe", "channel": "balances"}' # unsubscribing, not sure if i need to do that but it seems to me like 'clean' working; if smth goes wrong it unsubscribes.
ws.send(msg)
msg = '{"token": "mysecretAPItoken", "action": "unsubscribe", "channel": "auth"}' # unsubscribing; same as 3 lines above
ws.send(msg)
ws.close()
return result2['balances'][0]['rate'], result2['balances'][1]['rate'] # gives me the prices
x = price_func()[0]
print('Price of Shitcoin is around' + str(round(x,2)))
Thx for any help.

Python string substitution picking up junk characters in api requests

I am using Pagerduty python api client - pdpyras And below is the block of code
session = APISession(api_token)
changedate = os.popen("date -u -d '24 hours ago' +'%FT%T%.2Z'").read()
print(changedate)
changeurl = "change_events?include[]=integration&since=" + changedate
print(changeurl)
change_dump = session.rget(changeurl)
print(change_dump[0])
This should ideally get me the 1st event from change-events page of pagerduty. However, it fails due to the junk characters that gets added in the changeurl when it is passed to session.rget
See the below output
2021-03-26T09:47:53.2Z
change_events?include[]=integration&since=2021-03-26T09:47:53.2Z
Traceback (most recent call last):
File "dailyincidents.py", line 28, in <module>
change_dump = session.rget(changeurl)
File "/Users/saha/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pdpyras.py", line 190, in call
return method(self, url, **kw)
File "/Users/saha/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pdpyras.py", line 143, in call
r = raise_on_error(method(self, path, **pass_kw))
File "/Users/saha/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pdpyras.py", line 84, in raise_on_error
), response=r
pdpyras.PDClientError: GET /change_events?include%5B%5D=integration&since=2021-03-26T09:47:53.2Z%0A: API responded with non-success status (400)
The problem here is the junk characters you see in the last line of error "include%5B%5D" and then "%0A" in the end. Because if I run the below code block directly, I am able to successfully pull the details.
change_dump = session.rget("change_events?include[]=integration&since=2021-03-26T09:47:53.2Z")
The issue occurs only when the string gets substituted, it takes these junk characters. Not sure how it gets picked and how to get around this. Any pointers?
EDIT
I was able to partly get rid of the junk characters. However, there is still one at the end, which I am not sure how to. Below is the change I did.
parameters = "include[]=integration&since=" + changedate
change_dump = session.rget("change_events", params=parameters)
Now, the error is like below
pdpyras.PDClientError: GET
/change_events?include[]=integration&since=2021-03-26T14:14:08.2Z%0A:
API responded with non-success status (400)
As you can see, now the last 3 characters in the url which is %0A: is causing the problem. Any pointers please?
The below format should work for you.
parameters = "include[]=integration&since=" + changedate
change_dump = session.rget("change_events",params=parameters.rstrip('\n').replace("\n", ""))

Snowflake connector.connect breaks with an error message that tells me nothing

I installed the snowflake connector via the command: pip3 install snowflake-connector-python[pandas]==2.3.3 asn1crypto==1.3.0 --user
I attempted to connect via:
from snowflake import connector
con = connector.connect(
host='.snowflakecomputing.com',
user='THE USER I USE FOR LOGGING IN TO MY TRIAL ACCOUNT',
password='THE PASSWORD I USE FOR LOGGING IN TO MY TRIAL ACCOUNT',
account='zka81761.us-east-1',
warehouse='COMPUTE_WH',
database='DEMO_DB',
schema='PUBLIC',
protocol='https',
port=443)
When executing the above code it just hangs for several minutes then I get an error:
snowflake.connector.errors.OperationalError: 250003: Failed to execute request: encoding with 'idna' codec failed (UnicodeError: label empty or too long)
The longer version is:
File "tests/integration_tests/data_sources/test_snowflake_ds.py", line 6, in test_snowflake_ds
ds = SnowflakeDS(query='SELECT * FROM HEALTHCARE_COSTS', host='.snowflakecomputing.com', user='GEORGE3D6', password='a passwordd', account='zka81761.us-east-1', warehouse='COMPUTE_WH', database='DEMO_DB', schema='PUBLIC', protocol='https', port=443)
File "/home/george/mindsdb_native/mindsdb_native/libs/data_types/data_source.py", line 13, in __init__
df, col_map = self._setup(*args, **kwargs)
File "/home/george/mindsdb_native/mindsdb_native/libs/data_sources/snowflake_ds.py", line 21, in _setup
port=port)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/__init__.py", line 52, in Connect
return SnowflakeConnection(**kwargs)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/connection.py", line 219, in __init__
self.connect(**kwargs)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/connection.py", line 414, in connect
self.__open_connection()
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/connection.py", line 613, in __open_connection
self._authenticate(auth_instance)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/connection.py", line 839, in _authenticate
self.__authenticate(self.__preprocess_auth_instance(auth_instance))
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/connection.py", line 869, in __authenticate
session_parameters=self._session_parameters,
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/auth.py", line 209, in authenticate
socket_timeout=self._rest._connection.login_timeout)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/network.py", line 509, in _post_request
_include_retry_params=_include_retry_params)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/network.py", line 586, in fetch
**kwargs)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/network.py", line 676, in _request_exec_wrapper
conn, full_url, cause)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/network.py", line 706, in handle_invalid_certificate_error
'errno': ER_FAILED_TO_REQUEST,
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/errors.py", line 128, in errorhandler_wrapper
connection.errorhandler(connection, cursor, error_class, error_value)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/errors.py", line 90, in default_errorhandler
done_format_msg=error_value.get('done_format_msg'))
snowflake.connector.errors.OperationalError: 250003: Failed to execute request: encoding with 'idna' codec failed (UnicodeError: label empty or too long)
This error message tells me nothing, any help would be appreicated
According to the documentation on the python API the host field is no longer used so try removing that. Also, even if it was used, you haven't enclosed it properly in quotes:
You have: host='.snowflakecomputing.com,
Should be: host='.snowflakecomputing.com',
First, I'd see if removing the host completely fixes your issue since it shouldn't be used anyway.
Googling the error, and the error message itself, suggests that the issue is due to the URL being too long so I'd say the error is down to the fact that you haven't enclosed it properly.
I used to connect snowflake from python like below:
import snowflake.connector as sf
sfconnection = sf.connect(
user='THE USER I USE FOR LOGGING IN TO MY TRIAL ACCOUNT',
password='THE PASSWORD I USE FOR LOGGING IN TO MY TRIAL ACCOUNT',
account='zka81761.us-east-1',
warehouse='COMPUTE_WH',
database='DEMO_DB',
schema='PUBLIC')
Apparently the docs are wrong and the host should now be the full URL (so, in my case zka81761.us-east-1.snowflakecomputing.com). That is to say, it should include the account.

Trouble sending a batch create entity request in dialogflow

I have defined the following function. The purpose is to make batch create entity request with dialogflow client. I am using this method after sending many individual tests did not scale well.
The problem seems to be the line that defines EntityType. Seems like "entityType" is not valid but that is what is in the dialogflow v2 documentation which is the current version I am using.
Any ideas on what the issue is?
def create_batch_entity_types(self):
client = self.get_entity_client()
print(DialogFlowClient.batch_list)
EntityType = {
"entityTypes": DialogFlowClient.batch_list
}
response = client.batch_update_entity_types(parent=AGENT_PATH, entity_type_batch_inline=EntityType)
def callback(operation_future):
# Handle result.
result = operation_future.result()
print(result)
response.add_done_callback(callback)
After running the function I received this error
Traceback (most recent call last):
File "df_client.py", line 540, in <module>
create_entity_types_from_database()
File "df_client.py", line 426, in create_entity_types_from_database
df.create_batch_entity_types()
File "/Users/andrewflorial/Documents/PROJECTS/curlbot/dialogflow/dialogflow_accessor.py", line 99, in create_batch_entity_types
response = client.batch_update_entity_types(parent=AGENT_PATH, entity_type_batch_inline=EntityType)
File "/Users/andrewflorial/Documents/PROJECTS/curlbot/venv/lib/python3.7/site-packages/dialogflow_v2/gapic/entity_types_client.py", line 767, in batch_update_entity_types
update_mask=update_mask,
ValueError: Protocol message EntityTypeBatch has no "entityTypes" field.
The argument for entity_type_batch_inline must have the same form as EntityTypeBatch.
Look how that type looks like: https://dialogflow-python-client-v2.readthedocs.io/en/latest/gapic/v2/types.html#dialogflow_v2.types.EntityTypeBatch
It has to have entity_types field, not entityTypes.

Azure AD Python - Unexpected polling state invalid_client error

store_token = context.acquire_token_with_device_code(resource_uri, code, client_id)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/authentication_context.py", line 273, in acquire_token_with_device_code
return self._acquire_token(token_func)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/authentication_context.py", line 109, in _acquire_token
return token_func(self)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/authentication_context.py", line 266, in token_func
token = token_request.get_token_with_device_code(user_code_info)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/token_request.py", line 398, in get_token_with_device_code
token = client.get_token_with_polling(oauth_parameters, interval, expires_in)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/oauth2_client.py", line 345, in get_token_with_polling
wire_response)
adal.adal_error.AdalError: Unexpected polling state invalid_client
How could I get rid of this error after input the device code and sign-in successfully.
steps:
From a python interactive prompt, run this code [1] (All modules are already loaded). Where:
authority_url = 'https://login.microsoftonline.com/my_tenant_id'
resource_uri = "https://storage.azure.com/"
context = adal.AuthenticationContext(authority_uri)
code = context.acquire_user_code(resource_uri, client_id)
print(code['message'])
store_token = context.acquire_token_with_device_code(resource_uri, code, client_id)
credentials = AADTokenCredentials(store_token, client_id)
2.Open the URL https://microsoft.com/devicelogin in a browser.
3.Enter the code E8B2DVT67
4.Confirm the application's name, it is correct.
5.Authenticate using the user's credentials.
6.Get a message in browser saying "You have signed in to the TEST-APP application on your device. You may now close this window."
7.Get the error shown in my previous message in the python interactive prompt.
I use a native app and update manifest and set "allowPublicClient": true permission.
Your code works fine.
If we set allowPublicClient:false, we will encounter this error.
After updating allowPublicClient to true, it will work. Note: There will be some delay for the configuration to take effect.

Resources