/
base.py
2058 lines (1655 loc) · 81.3 KB
/
base.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2017 D-Wave Systems Inc.
#
# 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.
"""
D-Wave API clients handle communications with :term:`solver` resources: problem submittal,
monitoring, samples retrieval, etc.
Examples:
This example creates a client using the local system's default D-Wave Cloud Client
configuration file, which is configured to access a D-Wave 2000Q QPU, submits
a :term:`QUBO` problem (a Boolean NOT gate represented by a penalty model), and
samples 5 times.
>>> from dwave.cloud import Client
>>> Q = {(0, 0): -1, (0, 4): 0, (4, 0): 2, (4, 4): -1}
>>> with Client.from_config() as client: # doctest: +SKIP
... solver = client.get_solver()
... computation = solver.sample_qubo(Q, num_reads=5)
...
>>> for i in range(5): # doctest: +SKIP
... print(computation.samples[i][0], computation.samples[i][4])
...
(1, 0)
(1, 0)
(0, 1)
(0, 1)
(0, 1)
"""
import re
import sys
import time
import json
import copy
import queue
import logging
import inspect
import warnings
import operator
import threading
import base64
import hashlib
import codecs
import concurrent.futures
from itertools import chain, zip_longest
from functools import partial, wraps, lru_cache
from collections import abc, namedtuple, OrderedDict
from concurrent.futures import ThreadPoolExecutor
from typing import Optional, Tuple, Dict
import requests
import urllib3
from dateutil.parser import parse as parse_datetime
from plucky import pluck
from dwave.cloud import api
from dwave.cloud.package_info import __packagename__, __version__
from dwave.cloud.exceptions import * # TODO: fix
from dwave.cloud.computation import Future
from dwave.cloud.config import (
load_config, parse_float, parse_int, parse_boolean, update_config)
from dwave.cloud.solver import Solver, available_solvers
from dwave.cloud.concurrency import PriorityThreadPoolExecutor
from dwave.cloud.upload import ChunkedData
from dwave.cloud.events import dispatches_events
from dwave.cloud.utils import (
TimeoutingHTTPAdapter, BaseUrlSession, user_agent,
datetime_to_timestamp, utcnow, epochnow, cached, retried, is_caused_by)
__all__ = ['Client']
logger = logging.getLogger(__name__)
class Client(object):
"""Base client class for all D-Wave API clients. Used by QPU, software and
hybrid :term:`sampler` classes.
Manages workers and handles thread pools for submitting problems, cancelling
tasks, polling problem status, and retrieving results.
Args:
region (str, optional, default='na-west-1'):
D-Wave Solver API region. To see available regions use
:meth:`.Client.get_regions`.
endpoint (str, optional):
D-Wave Solver API endpoint URL. If undefined, inferred from
``region`` code.
token (str):
Authentication token for the D-Wave API.
solver (dict/str, optional):
Default solver features (or simply solver name) to use in
:meth:`.Client.get_solver`.
Defined via dictionary of solver feature constraints
(see :meth:`.Client.get_solvers`).
For backward compatibility, a solver name, as a string, is also
accepted and converted to ``{"name": <solver name>}``.
proxy (str, optional):
Proxy URL to be used for accessing the D-Wave API.
permissive_ssl (bool, default=False):
Disables SSL verification.
request_timeout (float, default=60):
Connect and read timeout, in seconds, for all requests to the
D-Wave API.
polling_timeout (float, optional):
Problem status polling timeout, in seconds, after which polling is
aborted.
connection_close (bool, default=False):
Force HTTP(S) connection close after each request. Set to ``True``
to prevent intermediate network equipment closing idle connections.
headers (dict/str, optional):
Newline-separated additional HTTP headers to include with each
API request, or a dictionary of (key, value) pairs.
client_cert (str, optional):
Path to client side certificate file.
client_cert_key (str, optional):
Path to client side certificate key file.
poll_backoff_min (float, default=0.05):
Problem status is polled with exponential back-off schedule.
Duration of the first interval (between first and second poll) is
set to ``poll_backoff_min`` seconds.
poll_backoff_max (float, default=60):
Problem status is polled with exponential back-off schedule.
Maximum back-off period is limited to ``poll_backoff_max`` seconds.
http_retry_total (int, default=10):
Total number of retries of failing idempotent HTTP requests to
allow. Takes precedence over other counts.
See ``total`` in :class:`~urllib3.util.retry.Retry` for details.
http_retry_connect (int, default=None):
How many connection-related errors to retry on.
See ``connect`` in :class:`~urllib3.util.retry.Retry` for details.
http_retry_read (int, default=None):
How many times to retry on read errors.
See ``read`` in :class:`~urllib3.util.retry.Retry` for details.
http_retry_redirect (int, default=None):
How many redirects to perform.
See ``redirect`` in :class:`~urllib3.util.retry.Retry` for details.
http_retry_status (int, default=None):
How many times to retry on bad status codes.
See ``status`` in :class:`~urllib3.util.retry.Retry` for details.
http_retry_backoff_factor (float, default=0.01):
A backoff factor to apply between attempts after the second try.
Sleep between retries, in seconds::
{backoff factor} * (2 ** ({number of total retries} - 1))
See ``backoff_factor`` in :class:`~urllib3.util.retry.Retry` for
details.
http_retry_backoff_max (float, default=60):
Maximum backoff time in seconds.
See :attr:`~urllib3.util.retry.Retry.BACKOFF_MAX` for details.
metadata_api_endpoint (str, optional):
D-Wave Metadata API endpoint. Central for all regions, used for
regional SAPI endpoint discovery.
defaults (dict, optional):
Defaults for the client instance that override the class
:attr:`.Client.DEFAULTS`.
Note:
Default values of all constructor arguments listed above are kept in
a class variable :attr:`.Client.DEFAULTS`.
Instance-level defaults can be specified via ``defaults`` argument.
Examples:
This example directly initializes a :class:`.Client`.
Direct initialization uses class constructor arguments, the minimum
being a value for ``token``.
>>> from dwave.cloud import Client
>>> client = Client(token='secret') # doctest: +SKIP
>>> # code that uses client
>>> client.close() # doctest: +SKIP
"""
# The status flags that a problem can have
STATUS_IN_PROGRESS = 'IN_PROGRESS'
STATUS_PENDING = 'PENDING'
STATUS_COMPLETE = 'COMPLETED'
STATUS_FAILED = 'FAILED'
STATUS_CANCELLED = 'CANCELLED'
# Cases when multiple status flags qualify
ANY_STATUS_ONGOING = [STATUS_IN_PROGRESS, STATUS_PENDING]
ANY_STATUS_NO_RESULT = [STATUS_FAILED, STATUS_CANCELLED]
# Default API endpoint
# TODO: remove when refactored to use `dwave.cloud.api`?
DEFAULT_API_ENDPOINT = api.constants.DEFAULT_SOLVER_API_ENDPOINT
DEFAULT_API_REGION = api.constants.DEFAULT_REGION
# Class-level defaults for all constructor and factory arguments
DEFAULTS = {
# factory only
'config_file': None,
'profile': None,
'client': 'base',
# constructor (and factory)
'metadata_api_endpoint': api.constants.DEFAULT_METADATA_API_ENDPOINT,
'region': DEFAULT_API_REGION,
# NOTE: should we rename endpoint to solver_api_endpoint for clarity?
'endpoint': None, # defined via region, resolved on client init
'token': None,
'solver': None,
'proxy': None,
'permissive_ssl': False,
'request_timeout': 60,
'polling_timeout': None,
'connection_close': False,
'headers': None,
'client_cert': None,
'client_cert_key': None,
# poll back-off schedule defaults [sec]
'poll_backoff_min': 0.05,
'poll_backoff_max': 60,
# idempotent http requests retry params
'http_retry_total': 10,
'http_retry_connect': None,
'http_retry_read': None,
'http_retry_redirect': None,
'http_retry_status': None,
'http_retry_backoff_factor': 0.01,
'http_retry_backoff_max': 60,
}
# Number of problems to include in a submit/status query
_SUBMIT_BATCH_SIZE = 20
_STATUS_QUERY_SIZE = 100
# Number of worker threads for each problem processing task
_SUBMISSION_THREAD_COUNT = 5
_UPLOAD_PROBLEM_THREAD_COUNT = 1
_UPLOAD_PART_THREAD_COUNT = 10
_ENCODE_PROBLEM_THREAD_COUNT = _UPLOAD_PROBLEM_THREAD_COUNT
_CANCEL_THREAD_COUNT = 1
_POLL_THREAD_COUNT = 2
_LOAD_THREAD_COUNT = 5
# Poll grouping time frame; two scheduled polls are grouped if closer than [sec]:
_POLL_GROUP_TIMEFRAME = 2
# Downloaded solver definition cache maxage [sec]
_SOLVERS_CACHE_MAXAGE = 300 # 5 min
# Downloaded region metadata cache maxage [sec]
_REGIONS_CACHE_MAXAGE = 86400 # 1 day
# Multipart upload parameters
_UPLOAD_PART_SIZE_BYTES = 5 * 1024 * 1024
_UPLOAD_PART_RETRIES = 2
_UPLOAD_REQUEST_RETRIES = 2
_UPLOAD_RETRIES_BACKOFF = lambda retry: 2 ** retry
@classmethod
def from_config(cls, config_file=None, profile=None, client=None, **kwargs):
"""Client factory method to instantiate a client instance from configuration.
Configuration values can be specified in multiple ways, ranked in the following
order (with 1 the highest ranked):
1. Values specified as keyword arguments in :func:`from_config()`
2. Values specified as environment variables
3. Values specified in the configuration file
4. Values specified as :class:`.Client` instance defaults
5. Values specified in :class:`.Client` class :attr:`.Client.DEFAULTS`
Configuration-file format and environment variables are described in
:mod:`dwave.cloud.config`.
File/environment configuration loading mechanism is described in
:func:`~dwave.cloud.config.load_config`.
Args:
config_file (str/[str]/None/False/True, default=None):
Path to configuration file. For interpretation, see
:func:`~dwave.cloud.config.load_config`.
profile (str, default=None):
Profile name. For interpretation, see
:func:`~dwave.cloud.config.load_config`.
client (str, default=None):
Client type used for accessing the API. Supported values are
``qpu`` for :class:`dwave.cloud.qpu.Client`,
``sw`` for :class:`dwave.cloud.sw.Client` and
``hybrid`` for :class:`dwave.cloud.hybrid.Client`.
**kwargs (dict):
:class:`.Client` constructor options.
Returns:
:class:`~dwave.cloud.client.Client` subclass:
Appropriate instance of a QPU/software/hybrid client.
Raises:
:exc:`~dwave.cloud.exceptions.ConfigFileReadError`:
Config file specified or detected could not be opened or read.
:exc:`~dwave.cloud.exceptions.ConfigFileParseError`:
Config file parse failed.
:exc:`ValueError`:
Invalid (non-existing) profile name.
"""
# load configuration from config file(s) and environment
config = load_config(config_file=config_file, profile=profile,
client=client, **kwargs)
logger.debug("Config loaded: %r", config)
from dwave.cloud.client import qpu, sw, hybrid
_clients = {
'base': cls,
'qpu': qpu.Client,
'sw': sw.Client,
'hybrid': hybrid.Client,
}
_client = config.pop('client', None) or 'base'
logger.debug("Creating %s.Client() with: %r", _client, config)
return _clients[_client](**config)
def _resolve_region_endpoint(self, *,
region: Optional[str] = None,
endpoint: Optional[str] = None) -> Tuple[str, str]:
"""For a region/endpoint pair from config, return the Solver API
endpoint to use (and the matching region).
Explicit endpoint will override the region (i.e. region extension is
backwards-compatible).
Regional endpoint is fetched from Metadata API. If Metadata API is not
available, default global endpoint is used.
"""
if endpoint:
return (region, endpoint)
if not region:
return (self.DEFAULT_API_REGION, self.DEFAULT_API_ENDPOINT)
try:
regions = self.get_regions()
except (api.exceptions.RequestError, ValueError) as exc:
logger.warning("Failed to fetch available regions: %r. "
"Using the default Solver API endpoint.", exc)
return (self.DEFAULT_API_REGION, self.DEFAULT_API_ENDPOINT)
if region not in regions:
raise ValueError(f"Region {region!r} unknown. "
f"Try one of {list(regions.keys())!r}.")
return (region, regions[region]['endpoint'])
@dispatches_events('client_init')
def __init__(self, endpoint=None, token=None, solver=None, **kwargs):
# for (reasonable) backwards compatibility, accept only the first few
# positional args.
# TODO: deprecate the use of positional args
if endpoint is not None:
kwargs.setdefault('endpoint', endpoint)
if token is not None:
kwargs.setdefault('token', token)
if solver is not None:
kwargs.setdefault('solver', solver)
logger.debug("Client init called with: %r", kwargs)
# derive instance-level defaults from class defaults and init defaults
self.defaults = copy.deepcopy(self.DEFAULTS)
user_defaults = kwargs.pop('defaults', None)
if user_defaults is None:
user_defaults = {}
update_config(self.defaults, user_defaults)
# combine instance-level defaults with file/env/kwarg option values
# note: treat empty string values (e.g. from file/env) as undefined/None
options = copy.deepcopy(self.defaults)
update_config(options, kwargs)
logger.debug("Client options with defaults: %r", options)
# configure MetadataAPI access -- needed by Client.get_regions()
self.metadata_api_endpoint = options['metadata_api_endpoint']
# parse headers as they might be needed by Client.get_regions()
headers = options['headers']
if not headers:
headers_dict = {}
elif isinstance(headers, abc.Mapping):
headers_dict = headers
elif isinstance(headers, str):
try:
# valid headers = "Field-1: value-1\nField-2: value-2"
headers_dict = {key.strip(): val.strip()
for key, val in [line.split(':')
for line in headers.strip().split('\n')]}
except Exception as e:
logger.debug("Invalid headers: %r", headers)
headers_dict = {}
else:
raise ValueError("HTTP headers expected in a dict, or a string")
logger.debug("Parsed headers=%r", headers_dict)
self.headers = headers_dict
# resolve endpoint using region
region, endpoint = self._resolve_region_endpoint(
region=options.get('region'), endpoint=options.get('endpoint'))
# sanity check
if not endpoint:
raise ValueError("API endpoint not defined")
token = options['token']
if not token:
raise ValueError("API token not defined")
# parse optional client certificate
client_cert = options['client_cert']
client_cert_key = options['client_cert_key']
if client_cert_key is not None:
if client_cert is not None:
client_cert = (client_cert, client_cert_key)
else:
raise ValueError(
"Client certificate key given, but the cert is missing")
# parse solver
solver = options['solver']
if not solver:
solver_def = {}
elif isinstance(solver, abc.Mapping):
solver_def = solver
elif isinstance(solver, str):
# support features dict encoded as JSON in our config INI file
# TODO: push this decoding to the config module, once we switch to a
# richer config format (JSON or YAML)
try:
solver_def = json.loads(solver)
except Exception:
# unparseable json, assume string name for solver
# we'll deprecate this eventually, but for now just convert it to
# features dict (equality constraint on full solver name)
logger.debug("Invalid solver JSON, assuming string name: %r", solver)
solver_def = dict(name__eq=solver)
else:
raise ValueError("Expecting a features dictionary or a string name for 'solver'")
logger.debug("Parsed solver=%r", solver_def)
# Store connection/session parameters
# TODO: consolidate all options under Client.options or similar
self.region = region # for record only
self.endpoint = endpoint
self.token = token
self.default_solver = solver_def
self.client_cert = client_cert
self.request_timeout = parse_float(options['request_timeout'])
self.polling_timeout = parse_float(options['polling_timeout'])
self.proxy = options['proxy']
self.permissive_ssl = parse_boolean(options['permissive_ssl'])
self.connection_close = parse_boolean(options['connection_close'])
self.poll_backoff_min = parse_float(options['poll_backoff_min'])
self.poll_backoff_max = parse_float(options['poll_backoff_max'])
self.http_retry_total = parse_int(options['http_retry_total'])
self.http_retry_connect = parse_int(options['http_retry_connect'])
self.http_retry_read = parse_int(options['http_retry_read'])
self.http_retry_redirect = parse_int(options['http_retry_redirect'])
self.http_retry_status = parse_int(options['http_retry_status'])
self.http_retry_backoff_factor = parse_float(options['http_retry_backoff_factor'])
self.http_retry_backoff_max = parse_float(options['http_retry_backoff_max'])
opts = (
'region', 'endpoint', 'token', 'default_solver',
'client_cert', 'request_timeout', 'polling_timeout',
'proxy', 'headers', 'permissive_ssl', 'connection_close',
'poll_backoff_min', 'poll_backoff_max',
'http_retry_total', 'http_retry_connect', 'http_retry_read',
'http_retry_redirect', 'http_retry_status',
'http_retry_backoff_factor', 'http_retry_backoff_max')
logger.debug(
"Client initialized with (%s)",
", ".join("{}={!r}".format(o, getattr(self, o)) for o in opts))
# Create session for main thread only
self.session = self.create_session()
# Build the problem submission queue, start its workers
self._submission_queue = queue.Queue()
self._submission_workers = []
for _ in range(self._SUBMISSION_THREAD_COUNT):
worker = threading.Thread(target=self._do_submit_problems)
worker.daemon = True
worker.start()
self._submission_workers.append(worker)
# Build the cancel problem queue, start its workers
self._cancel_queue = queue.Queue()
self._cancel_workers = []
for _ in range(self._CANCEL_THREAD_COUNT):
worker = threading.Thread(target=self._do_cancel_problems)
worker.daemon = True
worker.start()
self._cancel_workers.append(worker)
# Build the problem status polling queue, start its workers
self._poll_queue = queue.PriorityQueue()
self._poll_workers = []
for _ in range(self._POLL_THREAD_COUNT):
worker = threading.Thread(target=self._do_poll_problems)
worker.daemon = True
worker.start()
self._poll_workers.append(worker)
# Build the result loading queue, start its workers
self._load_queue = queue.Queue()
self._load_workers = []
for _ in range(self._LOAD_THREAD_COUNT):
worker = threading.Thread(target=self._do_load_results)
worker.daemon = True
worker.start()
self._load_workers.append(worker)
# Setup multipart upload executors
self._upload_problem_executor = \
ThreadPoolExecutor(self._UPLOAD_PROBLEM_THREAD_COUNT)
self._upload_part_executor = \
PriorityThreadPoolExecutor(self._UPLOAD_PART_THREAD_COUNT)
self._encode_problem_executor = \
ThreadPoolExecutor(self._ENCODE_PROBLEM_THREAD_COUNT)
# note: @cached_property available only in py38+
@property
@lru_cache(maxsize=None)
def _user_agent(self):
"""User-Agent string for this client instance, as returned by
:meth:`~dwave.cloud.utils.user_agent`, computed on first access and
cached for the lifespan of the client.
Note:
The only tags that might change are platform tags, as returned by
``dwave.common.platform.tags`` entry points, and `platform.platform()`
(like linux kernel version). Assuming OS/machine won't change during
client's lifespan, and typical platform tags defined via entry points
depend on process environments (which rarely change), it's pretty safe
to always use the per-instance cached user agent.
"""
return user_agent(__packagename__, __version__)
def create_session(self):
"""Create a new requests session based on client's (self) params.
Note: since `requests.Session` is NOT thread-safe, every thread should
create and use an isolated session.
"""
# allow endpoint path to not end with /
endpoint = self.endpoint
if not endpoint.endswith('/'):
endpoint += '/'
# create http idempotent Retry config
def get_retry_conf():
# need a subclass to override the backoff_max
class Retry(urllib3.Retry):
BACKOFF_MAX = self.http_retry_backoff_max
return Retry(
total=self.http_retry_total,
connect=self.http_retry_connect,
read=self.http_retry_read,
redirect=self.http_retry_redirect,
status=self.http_retry_status,
backoff_factor=self.http_retry_backoff_factor,
raise_on_redirect=True,
raise_on_status=True,
respect_retry_after_header=True)
session = BaseUrlSession(base_url=endpoint)
session.mount('http://',
TimeoutingHTTPAdapter(timeout=self.request_timeout,
max_retries=get_retry_conf()))
session.mount('https://',
TimeoutingHTTPAdapter(timeout=self.request_timeout,
max_retries=get_retry_conf()))
session.headers.update({'User-Agent': self._user_agent})
if self.headers:
session.headers.update(self.headers)
if self.token:
session.headers.update({'X-Auth-Token': self.token})
if self.client_cert:
session.cert = self.client_cert
session.proxies = {'http': self.proxy, 'https': self.proxy}
if self.permissive_ssl:
session.verify = False
if self.connection_close:
session.headers.update({'Connection': 'close'})
# Debug-log headers
logger.debug("create_session(session.headers=%r)", session.headers)
return session
def close(self):
"""Perform a clean shutdown.
Waits for all the currently scheduled work to finish, kills the workers,
and closes the connection pool.
.. note:: Ensure your code does not submit new work while the connection is closing.
Where possible, it is recommended you use a context manager (a :code:`with Client.from_config(...) as`
construct) to ensure your code properly closes all resources.
Examples:
This example creates a client (based on an auto-detected configuration file), executes
some code (represented by a placeholder comment), and then closes the client.
>>> from dwave.cloud import Client
>>> client = Client.from_config() # doctest: +SKIP
>>> # code that uses client
>>> client.close() # doctest: +SKIP
"""
# Finish all the work that requires the connection
logger.debug("Joining submission queue")
self._submission_queue.join()
logger.debug("Joining cancel queue")
self._cancel_queue.join()
logger.debug("Joining poll queue")
self._poll_queue.join()
logger.debug("Joining load queue")
self._load_queue.join()
logger.debug("Shutting down problem upload executor")
self._upload_problem_executor.shutdown()
logger.debug("Shutting down problem part upload executor")
self._upload_part_executor.shutdown()
logger.debug("Shutting down problem encoder executor")
self._encode_problem_executor.shutdown()
# Send kill-task to all worker threads
# Note: threads can't be 'killed' in Python, they have to die by
# natural causes
for _ in self._submission_workers:
self._submission_queue.put(None)
for _ in self._cancel_workers:
self._cancel_queue.put(None)
for _ in self._poll_workers:
self._poll_queue.put((-1, None))
for _ in self._load_workers:
self._load_queue.put(None)
# Wait for threads to die
for worker in chain(self._submission_workers, self._cancel_workers,
self._poll_workers, self._load_workers):
worker.join()
# Close the main thread's session
self.session.close()
def __enter__(self):
"""Let connections be used in with blocks."""
return self
def __exit__(self, *args):
"""At the end of a with block perform a clean shutdown of the connection."""
self.close()
return False
@staticmethod
def is_solver_handled(solver):
"""Determine if the specified solver should be handled by this client.
Default implementation accepts all solvers (always returns True). Override this
predicate function with a subclass if you want to specialize your client for a
particular type of solvers.
Examples:
This function accepts only solvers named "My_Solver_*".
.. code:: python
@staticmethod
def is_solver_handled(solver):
return solver and solver.id.startswith('My_Solver_')
"""
return True
@staticmethod
@cached.ondisk(maxage=_REGIONS_CACHE_MAXAGE)
def _fetch_available_regions(metadata_api_endpoint, **config):
logger.info("Fetching available regions from the Metadata API at %r",
metadata_api_endpoint)
with api.Regions(endpoint=metadata_api_endpoint, **config) as regions:
data = regions.list_regions()
logger.trace("Received region metadata: %r", data)
return data
def get_regions(self, refresh: bool = False) -> Dict[str, Dict[str, str]]:
"""Retrieve available API regions.
Args:
refresh:
Force cache refresh.
Returns:
Mapping of region details (name and endpoint) over region codes.
"""
try:
rs = Client._fetch_available_regions(
metadata_api_endpoint=self.metadata_api_endpoint,
headers=self.headers,
refresh_=refresh)
except api.exceptions.RequestError as exc:
logger.exception("Metadata API unavailable")
raise ValueError(
f"Metadata API unavailable at {self.metadata_api_endpoint!r}")
logger.debug("Using region metadata: %r", rs)
return {r.code: {"name": r.name, "endpoint": r.endpoint} for r in rs}
@cached(maxage=_SOLVERS_CACHE_MAXAGE)
def _fetch_solvers(self, name=None):
if name is not None:
logger.info("Fetching definition of a solver with name=%r", name)
url = 'solvers/remote/{}/'.format(name)
else:
logger.info("Fetching definitions of all available solvers")
url = 'solvers/remote/'
try:
data = Client._sapi_request(self.session.get, url)
except SAPIError as exc:
if name is not None and exc.error_code == 404:
raise SolverNotFoundError("No solver with name={!r} available".format(name))
else:
raise
if name is not None:
data = [data]
logger.debug("Received solver data for %d solver(s).", len(data))
logger.trace("Solver data received for solver name=%r: %r", name, data)
solvers = []
for solver_desc in data:
for solver_class in available_solvers:
try:
logger.debug("Trying to instantiate %r", solver_class.__name__)
solver = solver_class(self, solver_desc)
if self.is_solver_handled(solver):
solvers.append(solver)
logger.info("Adding solver %r", solver)
break
else:
logger.debug("Skipping solver %r (not handled by this client)", solver)
except UnsupportedSolverError as e:
logger.debug("Skipping solver due to %r", e)
# propagate all other/decoding errors, like InvalidAPIResponseError, etc.
return solvers
def retrieve_answer(self, id_):
"""Retrieve a problem by id.
Args:
id_ (str):
As returned by :attr:`Future.id`.
Returns:
:class:`Future`
"""
future = Future(None, id_)
self._load(future)
return future
@dispatches_events('get_solvers')
def get_solvers(self, refresh=False, order_by='avg_load', **filters):
"""Return a filtered list of solvers handled by this client.
Args:
refresh (bool, default=False):
Force refresh of cached list of solvers/properties.
order_by (callable/str/None, default='avg_load'):
Solver sorting key function (or :class:`~dwave.cloud.solver.Solver`
attribute/item dot-separated path). By default, solvers are sorted
by average load. To explicitly not sort the solvers (and use the
API-returned order), set ``order_by=None``.
Signature of the `key` `callable` is::
key :: (Solver s, Ord k) => s -> k
Basic structure of the `key` string path is::
"-"? (attr|item) ( "." (attr|item) )*
For example, to use solver property named ``max_anneal_schedule_points``,
available in ``Solver.properties`` dict, you can either specify a
callable `key`::
key=lambda solver: solver.properties['max_anneal_schedule_points']
or, you can use a short string path based key::
key='properties.max_anneal_schedule_points'
Solver derived properties, available as :class:`Solver` properties
can also be used (e.g. ``num_active_qubits``, ``online``,
``avg_load``, etc).
Ascending sort order is implied, unless the key string path does
not start with ``-``, in which case descending sort is used.
Note: the sort used for ordering solvers by `key` is **stable**,
meaning that if multiple solvers have the same value for the
key, their relative order is preserved, and effectively they are
in the same order as returned by the API.
Note: solvers with ``None`` for key appear last in the list of
solvers. When providing a key callable, ensure all values returned
are of the same type (particularly in Python 3). For solvers with
undefined key value, return ``None``.
**filters:
See `Filtering forms` and `Operators` below.
Solver filters are defined, similarly to Django QuerySet filters, with
keyword arguments of form `<key1>__...__<keyN>[__<operator>]=<value>`.
Each `<operator>` is a predicate (boolean) function that acts on two
arguments: value of feature `<name>` (described with keys path
`<key1.key2...keyN>`) and the required `<value>`.
Feature `<name>` can be:
1) a derived solver property, available as an identically named
:class:`Solver`'s property (`name`, `qpu`, `hybrid`, `software`,
`online`, `num_active_qubits`, `avg_load`)
2) a solver parameter, available in :obj:`Solver.parameters`
3) a solver property, available in :obj:`Solver.properties`
4) a path describing a property in nested dictionaries
Filtering forms are:
* <derived_property>__<operator> (object <value>)
* <derived_property> (bool)
This form ensures the value of solver's property bound to `derived_property`,
after applying `operator` equals the `value`. The default operator is `eq`.
For example::
>>> client.get_solvers(avg_load__gt=0.5)
but also::
>>> client.get_solvers(online=True)
>>> # identical to:
>>> client.get_solvers(online__eq=True)
* <parameter>__<operator> (object <value>)
* <parameter> (bool)
This form ensures that the solver supports `parameter`. General operator form can
be used but usually does not make sense for parameters, since values are human-readable
descriptions. The default operator is `available`.
Example::
>>> client.get_solvers(flux_biases=True)
>>> # identical to:
>>> client.get_solvers(flux_biases__available=True)
* <property>__<operator> (object <value>)
* <property> (bool)
This form ensures the value of the solver's `property`, after applying `operator`
equals the righthand side `value`. The default operator is `eq`.
Note: if a non-existing parameter/property name/key given, the default operator is `eq`.
Operators are:
* `available` (<name>: str, <value>: bool):
Test availability of <name> feature.
* `eq`, `lt`, `lte`, `gt`, `gte` (<name>: str, <value>: any):
Standard relational operators that compare feature <name> value with <value>.
* `regex` (<name>: str, <value>: str):
Test regular expression matching feature value.
* `covers` (<name>: str, <value>: single value or range expressed as 2-tuple/list):
Test feature <name> value (which should be a *range*) covers a given value or a subrange.
* `within` (<name>: str, <value>: range expressed as 2-tuple/list):
Test feature <name> value (which can be a *single value* or a *range*) is within a given range.
* `in` (<name>: str, <value>: container type):
Test feature <name> value is *in* <value> container.
* `contains` (<name>: str, <value>: any):
Test feature <name> value (container type) *contains* <value>.
* `issubset` (<name>: str, <value>: container type):
Test feature <name> value (container type) is a subset of <value>.
* `issuperset` (<name>: str, <value>: container type):
Test feature <name> value (container type) is a superset of <value>.
Derived properies are:
* `name` (str): Solver name/id.
* `qpu` (bool): Solver is a QPU?
* `software` (bool): Solver is a software solver?
* `online` (bool, default=True): Is solver online?
* `num_active_qubits` (int): Number of active qubits. Less then or equal to `num_qubits`.
* `avg_load` (float): Solver's average load (similar to Unix load average).
Common solver parameters are:
* `flux_biases`: Should solver accept flux biases?
* `anneal_schedule`: Should solver accept anneal schedule?
Common solver properties are:
* `num_qubits` (int): Number of qubits available.
* `vfyc` (bool): Should solver work on "virtual full-yield chip"?
* `max_anneal_schedule_points` (int): Piecewise linear annealing schedule points.
* `h_range` ([int,int]), j_range ([int,int]): Biases/couplings values range.
* `num_reads_range` ([int,int]): Range of allowed values for `num_reads` parameter.
Returns:
list[Solver]: List of all solvers that satisfy the conditions.
Note:
Client subclasses (e.g. :class:`dwave.cloud.qpu.Client` or
:class:`dwave.cloud.hybrid.Client`) already filter solvers by resource
type, so for `qpu` and `hybrid` filters to have effect, call :meth:`.get_solvers`
on base :class:`~dwave.cloud.client.Client` class.
Examples::
client.get_solvers(
num_qubits__gt=2000, # we need more than 2000 qubits
num_qubits__lt=4000, # ... but fewer than 4000 qubits
num_qubits__within=(2000, 4000), # an alternative to the previous two lines
num_active_qubits=1089, # we want a particular number of active qubits
vfyc=True, # we require a fully yielded Chimera
vfyc__in=[False, None], # inverse of the previous filter
vfyc__available=False, # we want solvers that do not advertize the vfyc property
anneal_schedule=True, # we need support for custom anneal schedule
max_anneal_schedule_points__gte=4, # we need at least 4 points for our anneal schedule
num_reads_range__covers=1000, # our solver must support returning 1000 reads