client fails in my sockstunnel case in python3 - python-asyncio

I have a client/server case which is written in python by someone else, and it was working before. Currently I am trying to see if I could have it re-executed but so far no luck.
Anyway, this is the python code on client side, which is written in python3 .
283 -> ssl_ctx_client = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
284 ssl_ctx_client.check_hostname = False
285 ssl_ctx_client.options |= (
286 ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_COMPRESSION
287 )
288 ssl_ctx_client.set_ciphers("ECDHE-RSA-AES128-GCM-SHA256")
(Pdb++)
289 ssl_ctx_client.load_verify_locations(ssl_ca_file)
290 ssl_ctx_client.load_cert_chain(certfile=ssl_cert_file, keyfile=ssl_key_file)
291
292 # asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
293 loop = asyncio.get_event_loop()
294
295 # Each client connection will create a new protocol instance
296 coro_tunnel = loop.create_connection(
297 lambda: TunnelServer(is_server=False),
298 tunnel_host,
299 tunnel_port,
(Pdb++)
300 ssl=ssl_ctx_client,
301 )
302
303 loop.run_until_complete(coro_tunnel)
304
...
I have the server started first, but during the client call, it gives such return message:
/client.py", line 303, in socks_tunnel_client
loop.run_until_complete(coro_tunnel)
File "/usr/lib/python3.7/asyncio/base_events.py", line 583, in run_until_complete
return future.result()
File "/usr/lib/python3.7/asyncio/base_events.py", line 985, in create_connection
ssl_handshake_timeout=ssl_handshake_timeout)
File "/usr/lib/python3.7/asyncio/base_events.py", line 1013, in _create_connection_transport
await waiter
ConnectionResetError
If I was to find out the cause of this connection failure, what calls I should check first on the server side, that when client was to make call in "_create_connection_transport", what would be the relevant call triggered on server side ?
Thanks for the help.
Jack

Related

trainer.train() in Kaggle: StdinNotImplementedError: getpass was called, but this frontend does not support input requests

When saving a version in Kaggle, I get StdinNotImplementedError: getpass was called, but this frontend does not support input requests whenever I use the Transformers.Trainer class. The general code I use:
from transformers import Trainer, TrainingArguments
training_args = TrainingArguments(params)
trainer = Trainer(params)
trainer.train()
And the specific cell I am running now:
from transformers import Trainer, TrainingArguments,EarlyStoppingCallback
early_stopping = EarlyStoppingCallback()
training_args = TrainingArguments(
output_dir=OUT_FINETUNED_MODEL_PATH,
num_train_epochs=20,
per_device_train_batch_size=16,
per_device_eval_batch_size=16,
warmup_steps=0,
weight_decay=0.01,
logging_dir='./logs',
logging_steps=100,
evaluation_strategy="steps",
eval_steps=100,
load_best_model_at_end=True,
metric_for_best_model="eval_loss",
greater_is_better=False
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=val_dataset,
callbacks=[early_stopping]
)
trainer.train()
When trainer.train() is called, I get the error below, which I do not get if I train with native PyTorch. I understood that the error arises since I am asked to input a password, but no password is asked when using native PyTorch code, nor when using the same code with trainer.train() on Google Colab.
Any solution would be ok, like:
Avoid being asked the password.
Enable input requests when saving a notebook on Kaggle. After that, if I understood correctly, I would need to go to https://wandb.ai/authorize (after having created an account) and copy the generated key to console. However, I do not understand why wandb should be necessary since I never explicitly used it so far.
wandb: You can find your API key in your browser here: https://wandb.ai/authorize
Traceback (most recent call last):
File "/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_init.py", line 741, in init
wi.setup(kwargs)
File "/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_init.py", line 155, in setup
wandb_login._login(anonymous=anonymous, force=force, _disable_warning=True)
File "/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_login.py", line 210, in _login
wlogin.prompt_api_key()
File "/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_login.py", line 144, in prompt_api_key
no_create=self._settings.force,
File "/opt/conda/lib/python3.7/site-packages/wandb/sdk/lib/apikey.py", line 135, in prompt_api_key
key = input_callback(api_ask).strip()
File "/opt/conda/lib/python3.7/site-packages/ipykernel/kernelbase.py", line 825, in getpass
"getpass was called, but this frontend does not support input requests."
IPython.core.error.StdinNotImplementedError: getpass was called, but this frontend does not support input requests.
wandb: ERROR Abnormal program exit
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_init.py in init(job_type, dir, config, project, entity, reinit, tags, group, name, notes, magic, config_exclude_keys, config_include_keys, anonymous, mode, allow_val_change, resume, force, tensorboard, sync_tensorboard, monitor_gym, save_code, id, settings)
740 wi = _WandbInit()
--> 741 wi.setup(kwargs)
742 except_exit = wi.settings._except_exit
/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_init.py in setup(self, kwargs)
154 if not settings._offline and not settings._noop:
--> 155 wandb_login._login(anonymous=anonymous, force=force, _disable_warning=True)
156
/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_login.py in _login(anonymous, key, relogin, host, force, _backend, _silent, _disable_warning)
209 if not key:
--> 210 wlogin.prompt_api_key()
211
/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_login.py in prompt_api_key(self)
143 no_offline=self._settings.force,
--> 144 no_create=self._settings.force,
145 )
/opt/conda/lib/python3.7/site-packages/wandb/sdk/lib/apikey.py in prompt_api_key(settings, api, input_callback, browser_callback, no_offline, no_create, local)
134 )
--> 135 key = input_callback(api_ask).strip()
136 write_key(settings, key, api=api)
/opt/conda/lib/python3.7/site-packages/ipykernel/kernelbase.py in getpass(self, prompt, stream)
824 raise StdinNotImplementedError(
--> 825 "getpass was called, but this frontend does not support input requests."
826 )
StdinNotImplementedError: getpass was called, but this frontend does not support input requests.
The above exception was the direct cause of the following exception:
Exception Traceback (most recent call last)
<ipython-input-82-4d1046ab80b8> in <module>
42 )
43
---> 44 trainer.train()
/opt/conda/lib/python3.7/site-packages/transformers/trainer.py in train(self, resume_from_checkpoint, trial, **kwargs)
1067 model.zero_grad()
1068
-> 1069 self.control = self.callback_handler.on_train_begin(self.args, self.state, self.control)
1070
1071 # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point.
/opt/conda/lib/python3.7/site-packages/transformers/trainer_callback.py in on_train_begin(self, args, state, control)
338 def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
339 control.should_training_stop = False
--> 340 return self.call_event("on_train_begin", args, state, control)
341
342 def on_train_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
/opt/conda/lib/python3.7/site-packages/transformers/trainer_callback.py in call_event(self, event, args, state, control, **kwargs)
386 train_dataloader=self.train_dataloader,
387 eval_dataloader=self.eval_dataloader,
--> 388 **kwargs,
389 )
390 # A Callback can skip the return of `control` if it doesn't change it.
/opt/conda/lib/python3.7/site-packages/transformers/integrations.py in on_train_begin(self, args, state, control, model, **kwargs)
627 self._wandb.finish()
628 if not self._initialized:
--> 629 self.setup(args, state, model, **kwargs)
630
631 def on_train_end(self, args, state, control, model=None, tokenizer=None, **kwargs):
/opt/conda/lib/python3.7/site-packages/transformers/integrations.py in setup(self, args, state, model, **kwargs)
604 project=os.getenv("WANDB_PROJECT", "huggingface"),
605 name=run_name,
--> 606 **init_args,
607 )
608 # add config parameters (run may have been created manually)
/opt/conda/lib/python3.7/site-packages/wandb/sdk/wandb_init.py in init(job_type, dir, config, project, entity, reinit, tags, group, name, notes, magic, config_exclude_keys, config_include_keys, anonymous, mode, allow_val_change, resume, force, tensorboard, sync_tensorboard, monitor_gym, save_code, id, settings)
779 if except_exit:
780 os._exit(-1)
--> 781 six.raise_from(Exception("problem"), error_seen)
782 return run
/opt/conda/lib/python3.7/site-packages/six.py in raise_from(value, from_value)
Exception: problem
You may want to try adding report_to="tensorboard" or any other reasonable string array in your TrainingArguments
https://huggingface.co/transformers/main_classes/trainer.html#transformers.TrainingArguments
If you have multiple logger that you want to use report_to="all" (the default value)
try os.environ["WANDB_DISABLED"] = "true" such that wandb is always disabled.
see: https://huggingface.co/transformers/main_classes/trainer.html#transformers.TFTrainer.setup_wandb

How do I access SparkContext in Dataproc?

My goal is to use the elasticsearch-hadoop connector to load data directly into ES with pySpark.
I'm quite new to dataproc and pySpark and got stuck quite early.
I run a single node cluster (Image 1.3 ,Debian 9,Hadoop 2.9,Spark 2.3)
and this my code. I assume I need to install Java.
Thanks!
from pyspark.sql import SQLContext
from pyspark.sql.functions import lit
import os
from pyspark.sql import SparkSession
def install_java():
!apt-get install -y openjdk-8-jdk-headless -qq > /dev/null #install openjdk
os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64" #set environment
variable
!java -version #check java version
install_java()
conf = SparkConf().setAppName("testing").setMaster('ip-address')
sc = SparkContext.getOrCreate()
ExceptionTraceback (most recent call last)
<ipython-input-18-df37a24b7514> in <module>()
----> 1 sc = SparkContext.getOrCreate()
/usr/lib/spark/python/pyspark/context.pyc in getOrCreate(cls, conf)
361 with SparkContext._lock:
362 if SparkContext._active_spark_context is None:
--> 363 SparkContext(conf=conf or SparkConf())
364 return SparkContext._active_spark_context
365
/usr/lib/spark/python/pyspark/context.pyc in __init__(self, master, appName, sparkHome,
pyFiles, environment, batchSize, serializer, conf, gateway, jsc, profiler_cls)
127 " note this option will be removed in Spark 3.0")
128
--> 129 SparkContext._ensure_initialized(self, gateway=gateway, conf=conf)
130 try:
131 self._do_init(master, appName, sparkHome, pyFiles, environment, batchSize,
serializer,
/usr/lib/spark/python/pyspark/context.pyc in _ensure_initialized(cls, instance, gateway,
conf)
310 with SparkContext._lock:
311 if not SparkContext._gateway:
--> 312 SparkContext._gateway = gateway or launch_gateway(conf)
313 SparkContext._jvm = SparkContext._gateway.jvm
314
/usr/lib/spark/python/pyspark/java_gateway.pyc in launch_gateway(conf)
44 :return: a JVM gateway
45 """
---> 46 return _launch_gateway(conf)
47
48
/usr/lib/spark/python/pyspark/java_gateway.pyc in _launch_gateway(conf, insecure)
106
107 if not os.path.isfile(conn_info_file):
--> 108 raise Exception("Java gateway process exited before sending its port
number")
109
110 with open(conn_info_file, "rb") as info:
Exception: Java gateway process exited before sending its port number
Ok, solved, I needed to stop the current context before I create my new SparkContext.
sc.stop()

ansible tower cannot get license list after installation

I am trying out ansible tower on Red Hat Enterprise Linux Server 7.7 (Maipo) but could not get my license list. Following error occurs
It seems that the server cannot connect to "subscription.rhsm.redhat.com"
Traceback (most recent call last):
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/urllib3/connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/urllib3/util/retry.py", line 399, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='subscription.rhsm.redhat.com', port=443): Max retries exceeded with url: /subscription/users/altangerel_g/owners (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f99cead8b00>: 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 "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/api/views/root.py", line 194, in post
validated = get_licenser().validate_rh(user, pw)
File "/__init__.py", line 241, in validate_rh
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/requests/api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
i can curl "subscription.rhsm.redhat.com" so firewall is not blocking it.
and also configured proxy parameters in /etc/rhsm/rhsm.conf
sslCACert is pointing to /usr/share/rhn/RHNS-CA-CERT
DNS server is present in /etc/resolv.conf
what am i missing? please help me out.
I had the same problem today, it seems we need a direct internet access. But I have find a way to bypass this and hardcode the proxy:
[root#ansible requests]# pwd
/var/lib/awx/venv/awx/lib64/python3.6/site-packages/requests
[root#ansible requests]# grep 192.168.5.25 *
grep: __pycache__: est un dossier
sessions.py: 'http': 'http://192.168.5.25:3128',
sessions.py: 'https': 'http://192.168.5.25:3128',
[root#ansible requests]# vi sessions.py
def __init__(self):
366
367 #: A case-insensitive dictionary of headers to be sent on each
368 #: :class:`Request <Request>` sent from this
369 #: :class:`Session <Session>`.
370 self.headers = default_headers()
371
372 #: Default Authentication tuple or object to attach to
373 #: :class:`Request <Request>`.
374 self.auth = None
375
376 #: Dictionary mapping protocol or protocol and host to the URL of the proxy
377 #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
378 #: be used on each :class:`Request <Request>`.
379 self.proxies = {
380 'http': 'http://192.168.5.25:3128',
381 'https': 'http://192.168.5.25:3128',
382 }
ADD these 4 lines with your proxy config.
It worked for me and I got my license. Please, don't forget to backup the file sessions.py.
regards

AttributeError: 'NoneType' object has no attribute 'ReadAsArray' when loading an image, what could be the cause?

I'm trying to build a convolutional neural network for image classification in Python.
I run my code on CoLab and have loaded my data on Google Drive.
I can see all the files and folders in my google drive from python, but when I try to actually load an image it gives me the error in the title.
I'm using the skimage.io package, I'm actually just running a notebook I found on kaggle so the code should run fine, only difference I noticed is that the kaggle user was probably not working on CoLab with his data in GoogleDrive so I think maybe that's the problem, anyway here's my code:
from skimage.io import imread
img=imread('/content/drive/My Drive/CoLab/Data/chest_xray/train/PNEUMONIA/person53_bacteria_255.jpeg')
Which gives me the following error:
AttributeError: 'NoneType' object has no attribute 'ReadAsArray'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-12-4a64aebb8504> in <module>()
----> 1 img=imread('/content/drive/My Drive/CoLab/Data/chest_xray/train/PNEUMONIA/person53_bacteria_255.jpeg')
4 frames
/usr/local/lib/python3.6/dist-packages/skimage/io/_io.py in imread(fname, as_gray, plugin, flatten, **plugin_args)
59
60 with file_or_url_context(fname) as fname:
---> 61 img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
62
63 if not hasattr(img, 'ndim'):
/usr/local/lib/python3.6/dist-packages/skimage/io/manage_plugins.py in call_plugin(kind, *args, **kwargs)
208 (plugin, kind))
209
--> 210 return func(*args, **kwargs)
211
212
/usr/local/lib/python3.6/dist-packages/imageio/core/functions.py in imread(uri, format, **kwargs)
221 reader = read(uri, format, "i", **kwargs)
222 with reader:
--> 223 return reader.get_data(0)
224
225
/usr/local/lib/python3.6/dist-packages/imageio/core/format.py in get_data(self, index, **kwargs)
345 self._checkClosed()
346 self._BaseReaderWriter_last_index = index
--> 347 im, meta = self._get_data(index, **kwargs)
348 return Array(im, meta) # Array tests im and meta
349
/usr/local/lib/python3.6/dist-packages/imageio/plugins/gdal.py in _get_data(self, index)
64 if index != 0:
65 raise IndexError("Gdal file contains only one dataset")
---> 66 return self._ds.ReadAsArray(), self._get_meta_data(index)
67
68 def _get_meta_data(self, index):
AttributeError: 'NoneType' object has no attribute 'ReadAsArray'
Frist instead of My Drive it should be MyDrive (no space).
If it still doesn't work, you can try the following:
%cd /content/drive/MyDrive/CoLab/Data/chest_xray/train/PNEUMONIA
img=imread('person53_bacteria_255.jpeg')```

Compatibility issues with H2O.ai Hadoop on MapR 6.0 via python API?

Having apparent compatibility issues running H2O (via the 3.18.0.2 MapR 5.2 driver (trying with the latest driver (3.20.0.7) as recommended in another SO post did not help the problem)) on MapR 6.0.
While able to start an H2O cluster on MapR 6.0 (via something like hadoop jar h2odriver.jar -nodes 3 -mapperXmx 6g -output hdfsOutputDirName
) and seem to be able to access h2o Flow UI, having problems accessing the cluster via python API (pip show h2o confirms matching package version to driver being used).
Is the MapR 5.2 driver (currently the latest MapR driver version offered by H2O) incompatible with MapR 6.0 (would not be asking if not for the fact that seem to be able to use the H2O Flow UI on cluster instance started on MapR 6.0)? Any workaround other than standalone driver version (would like to still be able to leverage YARN on hadoop cluster)?
The code and error being seen when trying to connect to the running H2O using the python APIis shown below.
# connect to h2o service
h2o.init(ip=h2o_cnxn_ip)
where the h2o_cnxn_ip is the IP and port generated after starting the h2o cluster on the MapR 6.0 system. Produces error
Checking whether there is an H2O instance running at http://172.18.0.123:54321...
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-5-1728877a03a2> in <module>()
1 # connect to h2o service
----> 2 h2o.init(ip=h2o_cnxn_ip)
/home/me/projects/myproject/lib/python2.7/site-packages/h2o/h2o.pyc in init(url, ip, port, https, insecure, username, password, cookies, proxy, start_h2o, nthreads, ice_root, enable_assertions, max_mem_size, min_mem_size, strict_version_check, ignore_config, extra_classpath, **kwargs)
250 auth=auth, proxy=proxy,cookies=cookies, verbose=True,
251 _msgs=("Checking whether there is an H2O instance running at {url}",
--> 252 "connected.", "not found."))
253 except H2OConnectionError:
254 # Backward compatibility: in init() port parameter really meant "baseport" when starting a local server...
/home/me/projects/myproject/lib/python2.7/site-packages/h2o/backend/connection.pyc in open(server, url, ip, port, https, auth, verify_ssl_certificates, proxy, cookies, verbose, _msgs)
316 conn._stage = 1
317 conn._timeout = 3.0
--> 318 conn._cluster = conn._test_connection(retries, messages=_msgs)
319 # If a server is unable to respond within 1s, it should be considered a bug. However we disable this
320 # setting for now, for no good reason other than to ignore all those bugs :(
/home/me/projects/myproject/lib/python2.7/site-packages/h2o/backend/connection.pyc in _test_connection(self, max_retries, messages)
558 raise H2OServerError("Local server was unable to start")
559 try:
--> 560 cld = self.request("GET /3/Cloud")
561 if cld.consensus and cld.cloud_healthy:
562 self._print(" " + messages[1])
/home/me/projects/myproject/lib/python2.7/site-packages/h2o/backend/connection.pyc in request(self, endpoint, data, json, filename, save_to)
400 auth=self._auth, verify=self._verify_ssl_cert, proxies=self._proxies)
401 self._log_end_transaction(start_time, resp)
--> 402 return self._process_response(resp, save_to)
403
404 except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e:
/home/me/projects/myproject/lib/python2.7/site-packages/h2o/backend/connection.pyc in _process_response(response, save_to)
711 if content_type == "application/json":
712 try:
--> 713 data = response.json(object_pairs_hook=H2OResponse)
714 except (JSONDecodeError, requests.exceptions.ContentDecodingError) as e:
715 raise H2OServerError("Malformed JSON from server (%s):\n%s" % (str(e), response.text))
/home/me/projects/myproject/lib/python2.7/site-packages/requests/models.pyc in json(self, **kwargs)
882 try:
883 return complexjson.loads(
--> 884 self.content.decode(encoding), **kwargs
885 )
886 except UnicodeDecodeError:
/usr/lib64/python2.7/json/__init__.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
349 if parse_constant is not None:
350 kw['parse_constant'] = parse_constant
--> 351 return cls(encoding=encoding, **kw).decode(s)
/usr/lib64/python2.7/json/decoder.pyc in decode(self, s, _w)
364
365 """
--> 366 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
367 end = _w(s, end).end()
368 if end != len(s):
/usr/lib64/python2.7/json/decoder.pyc in raw_decode(self, s, idx)
380 """
381 try:
--> 382 obj, end = self.scan_once(s, idx)
383 except StopIteration:
384 raise ValueError("No JSON object could be decoded")
/home/me/projects/myproject/lib/python2.7/site-packages/h2o/backend/connection.pyc in __new__(cls, keyvals)
823 for k, v in keyvals:
824 if k == "__meta" and isinstance(v, dict):
--> 825 schema = v["schema_name"]
826 break
827 if k == "__schema" and is_type(v, str):
KeyError: u'schema_name'
MapR 6 is not currently supported by H2O. Currently H2O supports up to MapR 5.2.
Please see the downloads page for supported Hadoop versions.

Resources