Prefect docker agent failing to update flow status after execution - prefect

Summary
I am trying to understand Prefect docker agents. To do so, I am trying to configure a minimal set up on my local machine. I have managed to get the docker agent to connect to the local server and it looks like it's running the flow. However, it seems that, after the flow is finished, the agent is unable to update the flow's state at the server because it cannot connect to the server back end.
Detail
Here is my flow:
import prefect
from prefect import task, Flow
from prefect.run_configs import DockerRun
#task
def say_hello():
logger = prefect.context.get("logger")
logger.info("Hello, docker!")
with Flow("docker-hello-flow") as flow:
flow.run_config = DockerRun()
say_hello()
# Register the flow under the "tutorial" project
flow.register(project_name="tutorial")
I configure back end to use a local core server:
prefect backend server
I then start the server:
prefect server start -d
I connect to the server UI on localhost:8080 and confirm that it's running.
In the UI, I create the project tutorial.
I then register the flow:
:; python src/hello_docker.py
Flow URL: http://localhost:8080/default/flow/fea8211e-c243-40c8-a01e-f63ab2afcc77
└── ID: 0a7a6cc4-1e7b-4e71-a900-90dffb4362a9
└── Project: tutorial
└── Labels: ['parami']
I then confirm that the flow appears in the UI as expected. Note that my machine name is parami hence the label parami.
I then start a local docker agent specifying the label parami.
:; prefect agent docker start -l parami --log-level DEBUG --show-flow-logs
I then run the flow via the UI. The flow run is called enigmatic-axolotl.
The docker agent's log is as follows:
[2021-11-16 22:47:17,076] DEBUG - agent | No ready flow runs found.
[2021-11-16 22:47:17,076] DEBUG - agent | Sleeping flow run poller for 2.0 seconds...
[2021-11-16 22:47:18,506] DEBUG - agent | {'status': 'Pulling from prefecthq/prefect', 'id': '0.15.7'}
[2021-11-16 22:47:18,509] DEBUG - agent | {'status': 'Digest: sha256:e3f6dece4c8d5d7b289cb6e017d3a3b0617d3084df57c2bb96999a2b3c2470f0'}
[2021-11-16 22:47:18,510] DEBUG - agent | {'status': 'Status: Image is up to date for prefecthq/prefect:0.15.7'}
[2021-11-16 22:47:18,513] INFO - agent | Successfully pulled image prefecthq/prefect:0.15.7
[2021-11-16 22:47:18,513] DEBUG - agent | Creating Docker container prefecthq/prefect:0.15.7
[2021-11-16 22:47:18,578] DEBUG - agent | Starting Docker container with ID 68fea87be44f0332568b2a01e391c5e1822f58f43438df9bb81e228a8edc9625 and name 'enigmatic-axolotl'
[2021-11-16 22:47:18,976] DEBUG - agent | Docker container 68fea87be44f0332568b2a01e391c5e1822f58f43438df9bb81e228a8edc9625 started
[2021-11-16 22:47:18,977] INFO - agent | Completed deployment of flow run b1df1042-96a7-4a09-aee0-820468eccf87
[2021-11-16 22:47:19,076] DEBUG - agent | Querying for ready flow runs...
[2021-11-16 22:47:19,101] DEBUG - agent | No ready flow runs found.
[2021-11-16 22:47:19,101] DEBUG - agent | Sleeping flow run poller for 4.0 seconds...
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/urllib3/connection.py", line 175, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw
File "/usr/local/lib/python3.7/site-packages/urllib3/util/connection.py", line 96, in create_connection
raise err
File "/usr/local/lib/python3.7/site-packages/urllib3/util/connection.py", line 86, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 706, in urlopen
chunked=chunked,
File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 394, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/local/lib/python3.7/site-packages/urllib3/connection.py", line 239, in request
super(HTTPConnection, self).request(method, url, body=body, headers=headers)
File "/usr/local/lib/python3.7/http/client.py", line 1281, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/local/lib/python3.7/http/client.py", line 1327, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/usr/local/lib/python3.7/http/client.py", line 1276, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/usr/local/lib/python3.7/http/client.py", line 1036, in _send_output
self.send(msg)
File "/usr/local/lib/python3.7/http/client.py", line 976, in send
self.connect()
File "/usr/local/lib/python3.7/site-packages/urllib3/connection.py", line 205, in connect
conn = self._new_conn()
File "/usr/local/lib/python3.7/site-packages/urllib3/connection.py", line 187, in _new_conn
self, "Failed to establish a new connection: %s" % e
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7f2e7172e690>: Failed to establish a new connection: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 756, in urlopen
method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
File "/usr/local/lib/python3.7/site-packages/urllib3/util/retry.py", line 574, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='host.docker.internal', port=4200): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2e7172e690>: Failed to establish a new connection: [Errno 111] Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/bin/prefect", line 8, in <module>
sys.exit(cli())
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/prefect/cli/execute.py", line 53, in flow_run
result = client.graphql(query)
File "/usr/local/lib/python3.7/site-packages/prefect/client/client.py", line 554, in graphql
retry_on_api_error=retry_on_api_error,
File "/usr/local/lib/python3.7/site-packages/prefect/client/client.py", line 458, in post
retry_on_api_error=retry_on_api_error,
File "/usr/local/lib/python3.7/site-packages/prefect/client/client.py", line 738, in _request
session=session, method=method, url=url, params=params, headers=headers
File "/usr/local/lib/python3.7/site-packages/prefect/client/client.py", line 606, in _send_request
timeout=prefect.context.config.cloud.request_timeout,
File "/usr/local/lib/python3.7/site-packages/requests/sessions.py", line 590, in post
return self.request('POST', url, data=data, json=json, **kwargs)
File "/usr/local/lib/python3.7/site-packages/requests/sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.7/site-packages/requests/sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.7/site-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='host.docker.internal', port=4200): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2e7172e690>: Failed to establish a new connection: [Errno 111] Connection refused'))
[2021-11-16 22:47:23,101] DEBUG - agent | Querying for ready flow runs...
[2021-11-16 22:47:23,181] DEBUG - agent | No ready flow runs found.
[2021-11-16 22:47:23,181] DEBUG - agent | Sleeping flow run poller for 8.0 seconds...
So, the agent is successfully getting the flow run enigmatic-axolotl from the server and appears to complete the execution. My understanding is that it is then attempting to connect to the server to update the flow run's status. However, it is failing to do so because it is failing to connect to host.docker.internal:4200.
I wondered if host.docker.internal is a valid host so I restarted the agent with the option -a http://localhost:4200. The agent successfully connects to the server at localhost:4200 (it's reported in the log as doing so) but, when I run the flow again, I get the same error as before; that is, it is failing to connect to host.docker.internal:4200.
Finally, I reran the agent with -a http://0.0.0.0:4200. Again, it successfully connects to the server. I then rerun the flow and it fails yet again. However, this time it is trying to connect to 0.0.0.0:4200:
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=4200): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f70738948d0>: Failed to establish a new connection: [Errno 111] Connection refused'))
What am I missing? I assume that there's some configuration that I need to set to make this work.

From Prefect Server 0.15.5 and up, you might need to do
prefect server start --expose. This will allow outside connections to server.
You can find more information in this Github issue: https://github.com/PrefectHQ/prefect/issues/4963

Related

Unable to docker-compose up any project

Whenever I try to docker-compose up any project I get the following error.
I've tried with and without sudo
I am only having this issue on this machine. I am able to run the same containers on my Mac and Amazon WorkSpace.
(myslabs) [austin#localhost myslabs]$ sudo docker-compose up
[sudo] password for austin:
Traceback (most recent call last):
File "urllib3/connectionpool.py", line 677, in urlopen
File "urllib3/connectionpool.py", line 392, in _make_request
File "http/client.py", line 1252, in request
File "http/client.py", line 1298, in _send_request
File "http/client.py", line 1247, in endheaders
File "http/client.py", line 1026, in _send_output
File "http/client.py", line 966, in send
File "docker/transport/unixconn.py", line 43, in connect
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "requests/adapters.py", line 449, in send
File "urllib3/connectionpool.py", line 727, in urlopen
File "urllib3/util/retry.py", line 403, in increment
File "urllib3/packages/six.py", line 734, in reraise
File "urllib3/connectionpool.py", line 677, in urlopen
File "urllib3/connectionpool.py", line 392, in _make_request
File "http/client.py", line 1252, in request
File "http/client.py", line 1298, in _send_request
File "http/client.py", line 1247, in endheaders
File "http/client.py", line 1026, in _send_output
File "http/client.py", line 966, in send
File "docker/transport/unixconn.py", line 43, in connect
urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionRefusedError(111, 'Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "docker/api/client.py", line 205, in _retrieve_server_version
File "docker/api/daemon.py", line 181, in version
File "docker/utils/decorators.py", line 46, in inner
File "docker/api/client.py", line 228, in _get
File "requests/sessions.py", line 543, in get
File "requests/sessions.py", line 530, in request
File "requests/sessions.py", line 643, in send
File "requests/adapters.py", line 498, in send
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionRefusedError(111, 'Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "bin/docker-compose", line 3, in <module>
File "compose/cli/main.py", line 67, in main
File "compose/cli/main.py", line 123, in perform_command
File "compose/cli/command.py", line 69, in project_from_options
File "compose/cli/command.py", line 132, in get_project
File "compose/cli/docker_client.py", line 43, in get_client
File "compose/cli/docker_client.py", line 170, in docker_client
File "docker/api/client.py", line 188, in __init__
File "docker/api/client.py", line 213, in _retrieve_server_version
docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', ConnectionRefusedError(111, 'Connection refused'))
[142201] Failed to execute script docker-compose
I've not been able to find any articles about any similar issues.
I am using Centos 8 running inside of a VirtualBox on Windows.
(myslabs) [austin#localhost myslabs]$ docker --version
Docker version 19.03.13, build 4484c46d9d
(myslabs) [austin#localhost myslabs]$ docker-compose --version
docker-compose version 1.27.3, build 4092ae5d
Any help would greatly be appreciated.
I also encountered the same error as you,My problem is that docker does not start.
check docker status systemctl status docker
systemctl start docker
docker-compose up try again
systemctl enable docker to start on boot
If you're on a Mac, it may mean that Docker itself isn't running. I had rebooted my Mac and Docker wasn't set to automatically launch at login. You can set this as a Docker preference.
If nothing works, run:
sudo chmod +x /usr/local/bin/docker-compose
sudo docker-compose up -d
If On WSL2 ensure that the docker service has been started, use sudo service docker status to check. If it is not running, use the command sudo service docker start to get it running before sudo docker-compose up
Sometimes docker service is stopped. You can check it and restart.Normally happens if error iscontainer. can pruine and start again.
Please restart docker containers and it will work fine.
This issue comes mainly in the case of windows. restart your docker container.
then run the docker command from your terminal

Is there an Eclipse Pydev setting or something in my Python get request preventing me from connecting with a host?

I am trying to read data from an ESA server in a PyDev Eclipse 3.8.1 Environment using Python 3.5.3. An example of a product link is given here:
"https://scihub.copernicus.eu/dhus/odata/v1/Products('c7208694-dedb-4f47-96c0-c8fb03512ff5')
You will need authentication credentials to access the website.
In my Eclipse environment I have manually added in proxy settings by going to Windows-> General -> Network Connections. Authentication is not required for the proxy.
To get the content of the webpage, I use a Python get request to send my query as below:
url = r"https://scihub.copernicus.eu/dhus/odata/v1/Products('c5dc59f0-b041-4f76-a685-49be63491270')"
r = requests.get(url, verify=False, proxies=proxies, auth=auth)
I need the verify=False to disable the certificate check and proxies is a dictionary storing the proxy addresses with the relevant port. Server credentials are given with auth which is a tuple of a username and password.
When I send the request to the server, I get the following error:
Traceback (most recent call last):
File "/lib/python3.5/site-packages/urllib3/connection.py", line 159, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw)
File "/lib/python3.5/site-packages/urllib3/util/connection.py", line 80, in create_connection
raise err
File "/lib/python3.5/site-packages/urllib3/util/connection.py", line 70, in create_connection
sock.connect(sa)
TimeoutError: [Errno 110] Connection timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/lib/python3.5/site-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/lib/python3.5/site-packages/urllib3/connectionpool.py", line 343, in _make_request
self._validate_conn(conn)
File "/lib/python3.5/site-packages/urllib3/connectionpool.py", line 839, in _validate_conn
conn.connect()
File "/lib/python3.5/site-packages/urllib3/connection.py", line 301, in connect
conn = self._new_conn()
File "/lib/python3.5/site-packages/urllib3/connection.py", line 168, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x7fecf00acbe0>: Failed to establish a new connection: [Errno 110] Connection timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/lib/python3.5/site-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/lib/python3.5/site-packages/urllib3/connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "/lib/python3.5/site-packages/urllib3/util/retry.py", line 398, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='scihub.copernicus.eu', port=443): Max retries exceeded with url: /dhus/odata/v1/Products('c5dc59f0-b041-4f76-a685-49be63491270') (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fecf00acbe0>: Failed to establish a new connection: [Errno 110] Connection timed out',))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "download_lib2/download_lib/scihub/download.py", line 325, in <module>
download_url(dl_link, auth, temp_dir)
File "download_lib2/download_lib/scihub/download.py", line 153, in download_url
online = check_url_online(url_to_download, auth)
File "download_lib2/download_lib/scihub/download.py", line 51, in check_url_online
r = requests.get(url, verify=False, proxies=proxies, auth=auth)
File "/lib/python3.5/site-packages/requests/api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "/lib/python3.5/site-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/lib/python3.5/site-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/lib/python3.5/site-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/lib/python3.5/site-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='scihub.copernicus.eu', port=443): Max retries exceeded with url: /dhus/odata/v1/Products('c5dc59f0-b041-4f76-a685-49be63491270') (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fecf00acbe0>: Failed to establish a new connection: [Errno 110] Connection timed out',))
I have tried the same request outside of Eclipse, in IDLE, and I am able to successfully connect and read the content. Is there something wrong with my current Eclipse/PyDev environment that will not allow me to send a get request?
Why is Python not able to connect? I am able to send get requests to this and other websites using other projects in Eclipse (e.g. https://podaac-opendap.jpl.nasa.gov/opendap/allData/oscar/preview/L4/oscar_third_deg/) with no problem whatsoever.
Edit: Added in versions
The socks timeout indicates that your problem is actually the connection to your proxy as opposed to the ESA server. Additionally, I believe the proxy settings in Eclipse are only used for plugins/software updates and not by any code you write.
As an initial step, check your proxy dictionary keys are correct and verify your proxy URLS if you can.
You mention you have other Eclipse projects that can access the internet; it's worth checking what proxy settings they implement and seeing if there are any discrepancies with your current setup.

Accessing https pages with python3

I do not understand how to use urllib3 or requests to connect to an https web site. This is driving me nuts. I have installed certifi and I see the default .pem file it provides. I have tried to set the requests.verify option to requests to every .pem and .crt file on the machine my script runs on [I am not an admin on this device]. I get nothing but errors.
I switched to using urllib3 and am now getting:
H:\Projects\MyScraper\venv\Scripts\python.exe H:/Projects/MyScraper/MyScraper.py
Traceback (most recent call last):
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
chunked=chunked)
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\connectionpool.py", line 343, in _make_request
self._validate_conn(conn)
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\connectionpool.py", line 839, in _validate_conn
conn.connect()
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\connection.py", line 344, in connect
ssl_context=context)
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\util\ssl_.py", line 342, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File "C:\Program Files (x86)\Python36-32\lib\ssl.py", line 407, in wrap_socket
_context=self, _session=session)
File "C:\Program Files (x86)\Python36-32\lib\ssl.py", line 814, in __init__
self.do_handshake()
File "C:\Program Files (x86)\Python36-32\lib\ssl.py", line 1068, in do_handshake
self._sslobj.do_handshake()
File "C:\Program Files (x86)\Python36-32\lib\ssl.py", line 689, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "H:/Projects/MyScraper/MyScraper.py", line 15, in <module>
raw_html = HTTP.request('GET', 'https://portal.xsede.org/course-calendar/')
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\request.py", line 68, in request
**urlopen_kw)
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\request.py", line 89, in request_encode_url
return self.urlopen(method, url, **extra_kw)
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\poolmanager.py", line 323, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\connectionpool.py", line 667, in urlopen
**response_kw)
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\connectionpool.py", line 667, in urlopen
**response_kw)
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\connectionpool.py", line 667, in urlopen
**response_kw)
[Previous line repeated 6 more times]
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "H:\Projects\MyScraper\venv\lib\site-packages\urllib3\util\retry.py", line 398, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='portal.xsede.org', port=443): Max retries exceeded with url: /course-calendar/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)'),))
Process finished with exit code 1
My code looks like:
#!/home/me/virtualenv/python3.6/3.6/bin/python
import certifi
import urllib3
from bs4 import BeautifulSoup
HTTP = urllib3.PoolManager(
cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where(),
retries=10
)
raw_html = HTTP.request('GET', 'https://portal.xsede.org/course-calendar/')
html = BeautifulSoup(raw_html, 'html.parser')
It blows up on the raw_html = HTTP.request(... line. Ideas?
Edit
Huh, this has something to do with my target host. If I go to google.com then several of my pem/crt files work.
The problem is, you are using wrong certificate to make request.
you can run this command to verify which certificate is used when any request is made, and then use that certificate in your request,
openssl s_client -showcerts -connect google.com:443
Please also make sure that you are passing verify the path to CA_BUNDLE file or directory with certificates of trusted CAs.
This list of trusted CAs can also be specified through the REQUESTS_CA_BUNDLE environment variable.
If this doesn't work out for you can explicitly merge the environment settings into your session,
When you are using the prepared request flow, keep in mind that it
does not take into account the environment. This can cause problems if
you are using environment variables to change the behaviour of
requests. For example: Self-signed SSL certificates specified in
REQUESTS_CA_BUNDLE will not be taken into account. As a result an SSL:
CERTIFICATE_VERIFY_FAILED is thrown. You can get around this behaviour
by explicity merging the environment settings into your session:
from requests import Request, Session
s = Session()
req = Request('GET', url)
prepped = s.prepare_request(req)
# Merge environment settings into session
settings = s.merge_environment_settings(prepped.url, None, None, None, None)
resp = s.send(prepped, **settings)
print(resp.status_code)

Python requests module exception SSLError

I am getting a requests module exception error when I try to access the http://www.acastipharma.com/ website. I am not having problems with any other website so I believe this is a website specific issue. Here is some example code
import requests
initialURL = 'http://www.acastipharma.com/'
r = requests.get(initialURL)
When I run this code I get an error message that terminates with
requests.exceptions.SSLError: HTTPSConnectionPool(host='www.acastipharma.com', port=443): Max retries exceeded with url: /investors/ (Caused by SSLError(SSLError(1, '[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:645)'),))
An internet search indicates that the problem might be with acastipharma's SSL certificate. I tried installing pyopenssl to make sure I had the latest version of the the module thats checks SSL certificates but that did not solve the problem. I also tried running the requests.get statement with the verify=False option but that was also unsuccessful.
r = requests.get(initialURL, verify=False)
If anybody has any ideas on how to resolve this issue I would appreciate the assistance. I also tried using the older urllib.request package but ran into the same error.
This is an update to my original question: The error message I posted was from trying to run the requests command on one of the acastipharma's website subpages, here is the complete error message I get when I run the code exactly as shown in this question:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/urllib3/connectionpool.py", line 601, in urlopen
chunked=chunked)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/urllib3/connectionpool.py", line 346, in _make_request
self._validate_conn(conn)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/urllib3/connectionpool.py", line 850, in _validate_conn
conn.connect()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/urllib3/connection.py", line 326, in connect
ssl_context=context)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/urllib3/util/ssl_.py", line 329, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 376, in wrap_socket
_context=self)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 747, in __init__
self.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 983, in do_handshake
self._sslobj.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 628, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:645)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/requests/adapters.py", line 440, in send
timeout=timeout
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/urllib3/connectionpool.py", line 639, in urlopen
_stacktrace=sys.exc_info()[2])
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/urllib3/util/retry.py", line 388, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='www.acastipharma.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, '[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:645)'),))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/requests/api.py", line 72, in get
return request('get', url, params=params, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/requests/sessions.py", line 508, in request
resp = self.send(prep, **send_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/requests/sessions.py", line 640, in send
history = [resp for resp in gen] if allow_redirects else []
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/requests/sessions.py", line 640, in <listcomp>
history = [resp for resp in gen] if allow_redirects else []
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/requests/sessions.py", line 218, in resolve_redirects
**adapter_kwargs
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/requests/sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/requests/adapters.py", line 506, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='www.acastipharma.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, '[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:645)'),))
I am using Python 3.5.1. I am on a Mac using High Sierra version 10.13.2. I am using requests 2.18.4. Since posting the question I believe the problem lies with my IDE PyCharm's environment. If I use my Python 3.5 environment I have the problem as shown in this question, if I switch the project interpreter to a Python 3.6 Anaconda environment requests will work but unfortunately mysql won't import. Thanks
The OpenSSL version is OpenSSL 0.9.8zh 14 Jan 2016
This (very old and long unsupported) version of OpenSSL does not support the newer ciphers required by this specific web server. This server only supports ECDHE key exchange, which is not supported yet by OpenSSL 0.9.8. This means that the client only offers ciphers to the server which the server will not accept and due to no common ciphers the server will close the connection with an SSL handshake alert.
We can ignore this SSL Error using the following:
import warnings
from urllib3.exceptions import InsecureRequestWarning
warnings.simplefilter('ignore',InsecureRequestWarning)

SSLError using Requests and Python 3.6

I'm getting an SSLError while submitting a request against https://myaccount.xcelenergy.com (and am not nearly enough of an SSL expert to understand why). Can you help me see what the issue is (and how to address it)?
Environment
macOS 10.13.2
LibreSSL 2.2.7 (installed via Homebrew)
Python 3.6.4 (installed via Homebrew)
Requests 2.18.4 (installed via pipenv)
Certifi 2017.11.5 (installed via pipenv)
Code
import requests
requests.get('https://myaccount.xcelenergy.com')
Stacktrace
Traceback (most recent call last):
File "/Users/abach/.local/share/virtualenvs/pyxcel-PG9DCiyE/lib/python3.6/site-packages/urllib3/connectionpool.py", line 595, in urlopen
self._prepare_proxy(conn)
File "/Users/abach/.local/share/virtualenvs/pyxcel-PG9DCiyE/lib/python3.6/site-packages/urllib3/connectionpool.py", line 816, in _prepare_proxy
conn.connect()
File "/Users/abach/.local/share/virtualenvs/pyxcel-PG9DCiyE/lib/python3.6/site-packages/urllib3/connection.py", line 326, in connect
ssl_context=context)
File "/Users/abach/.local/share/virtualenvs/pyxcel-PG9DCiyE/lib/python3.6/site-packages/urllib3/util/ssl_.py", line 329, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 407, in wrap_socket
_context=self, _session=session)
File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 814, in __init__
self.do_handshake()
File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 1068, in do_handshake
self._sslobj.do_handshake()
File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 689, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/abach/.local/share/virtualenvs/pyxcel-PG9DCiyE/lib/python3.6/site-packages/requests/adapters.py", line 440, in send
timeout=timeout
File "/Users/abach/.local/share/virtualenvs/pyxcel-PG9DCiyE/lib/python3.6/site-packages/urllib3/connectionpool.py", line 639, in urlopen
_stacktrace=sys.exc_info()[2])
File "/Users/abach/.local/share/virtualenvs/pyxcel-PG9DCiyE/lib/python3.6/site-packages/urllib3/util/retry.py", line 388, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='myaccount.xcelenergy.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)'),))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/abach/.local/share/virtualenvs/pyxcel-PG9DCiyE/lib/python3.6/site-packages/requests/api.py", line 72, in get
return request('get', url, params=params, **kwargs)
File "/Users/abach/.local/share/virtualenvs/pyxcel-PG9DCiyE/lib/python3.6/site-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/Users/abach/.local/share/virtualenvs/pyxcel-PG9DCiyE/lib/python3.6/site-packages/requests/sessions.py", line 508, in request
resp = self.send(prep, **send_kwargs)
File "/Users/abach/.local/share/virtualenvs/pyxcel-PG9DCiyE/lib/python3.6/site-packages/requests/sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "/Users/abach/.local/share/virtualenvs/pyxcel-PG9DCiyE/lib/python3.6/site-packages/requests/adapters.py", line 506, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='myaccount.xcelenergy.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)'),))
What I've Tried (to no avail)
# Specifically calling out local cert chain:
requests.get('https://myaccount.xcelenergy.com', verify='/usr/local/etc/openssl/cert.pem')
# Using Certifi's old chain:
requests.get('https://myaccount.xcelenergy.com', verify=certifi.old_where())
There is currently a known issue with OSX's Python3.6 and OpenSSL that might be related to what you're seeing. I was able to fix it by installing certifi, then making a symlink in OpenSSL's directory. All of that can be done for you by running the following from bash:
Applications/Python 3.6/Install Certificates.command
See this related question: ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:747) on OS X

Resources