This repository was archived by the owner on Apr 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.py
More file actions
655 lines (511 loc) · 26.7 KB
/
client.py
File metadata and controls
655 lines (511 loc) · 26.7 KB
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
"""
Copyright 2023 Cognitive Scale, Inc. All Rights Reserved.
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
https://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.
"""
import os
import time
from .constant import VERSION
from .experiment.local import LocalExperiment
from .connection import ConnectionClient
from .content import ManagedContentClient
from .models import ModelClient
from .secrets import SecretsClient
from .session import SessionClient
from .skill import SkillClient
from .types import TypeClient
from .experiment import ExperimentClient
from .serviceconnector import ServiceConnector
from .env import CortexEnv
from .exceptions import (
ProjectException,
InvalidMessageTypeException,
IncompleteMessageKeysException,
)
from .message import Message
from .utils import decode_JWT, get_logger, generate_token
log = get_logger(__name__)
class _Token:
def __init__(self, token: str):
self._token = token
self._jwt = None
if token:
self._jwt = decode_JWT(self._token)
def is_expired(self) -> bool:
"""Checks if the token's JWT has expired
:return: A boolean indicating if the JWT has expired
:rtype: bool
"""
current_time = time.time()
return not self._jwt or (self._jwt[0].get("exp", current_time) < current_time)
@property
def token(self) -> str:
"""Returns the token
:return: The token
:rtype: str
"""
return self._token
class Client:
"""
API client used to access Connections, Managed Content, Experiments, Secrets, Models, Sessions, Skills and Types in a Fabric cluster. Experiments also have a `local client` (:class:`cortex.experiment.local.LocalExperiment`) for data scientists to work without access to a Fabric cluster.
Create an instance of the Cortex Fabric client. There are a few different ways in which you can instantiate a Client
1. If the user has the Cortex CLI installed and configured to a Fabric environment, AND a default project is set, they can do the following:
>>> from cortex.client import Cortex; client = Cortex.client()
2. If the user has the Cortex CLI installed and configured, but a default project is not set:
>>> from cortex.client import Cortex; client = Cortex.client(project="some-project")
3. If the user does not have the Cortex CLI installed, or is using the cortex-python package from within a Skill (Daemon) running inside a Fabric cluster, they can simply extract the required parameters from the request object and create a Cortex client like below:
.. code-block::
from cortex.client import Cortex
@app.post('/invoke')
def start(req: dict):
payload = req['payload']
client = Cortex.client(api_endpoint=req["apiEndpoint"], project=req["projectId"], token=req["token"])
client.experiments.list_experiments()
....
4. If the user does not have the Cortex CLI installed, or is using the cortex-python package from within a **Skill(Job)** running inside a Fabric cluster, they can simply pass the `params` object passed into the Job script and create a Cortex client:
.. code-block:: python
# contents of main.py for a Skill (job)
from cortex.client import Cortex
def main(params):
client = Cortex.from_message(params)
if __name__ == "__main__":
if len(sys.argv)<2:
print("Message/payload argument is required")
exit(1)
# The last argument in sys.argv is the payload from cortex
main(json.loads(sys.argv[-1]))
:param url: Cortex fabric url
:param token: (optional) Use JWT token to authenticate requests, will default to settings in ~/.cortex/config if not provided to generate JWT tokens
:param project: (optional) Project name, must specify project for each request
:param version: (optional) Fabric API version (default: 4)
""" # pylint: disable=line-too-long
def __init__(
self,
url: str,
token: _Token = None,
config: dict = None,
project: str = None,
version: int = VERSION,
verify_ssl_cert: bool = False,
):
self._serviceconnector = None
self._token = token
self._config = config
self._project = project
self._url = url
self._version = version
self._verify_ssl_cert = verify_ssl_cert
self._service_clients = {
"connections": ConnectionClient(self),
"content": ManagedContentClient(self),
"experiments": ExperimentClient(self),
"models": ModelClient(self),
"secrets": SecretsClient(self),
"sessions": SessionClient(self),
"skills": SkillClient(self),
"types": TypeClient(self),
}
def message(self, payload: dict, properties: dict = None) -> Message:
"""Constructs a Message from payload and properties if given. This is useful for
testing skills, as this the message passed when skills are invoked
:param payload: The payload to include in the Message.
:param properties: The properties to include in the Message.
:return: A Message object.
"""
if not self._token.token:
self._token = _Token(generate_token(self._serviceconnector._config)) # pylint: disable=protected-access
params = {"payload": payload}
if properties:
params["properties"] = properties
params["apiEndpoint"] = self._url
params["token"] = self._token.token
return Message(params)
def _mk_connector(self):
return ServiceConnector(
self._url,
self._version,
self._token.token,
self._config,
self._verify_ssl_cert,
self._project,
)
# expose this to allow developer to pass client instance into Connectors
def to_connector(self) -> ServiceConnector:
"""_summary_
:return: _description_
:rtype: ServiceConnector
"""
return self._mk_connector()
def _repr_pretty_(self, p, cycle):
# pylint: disable=unused-argument,invalid-name
p.text(str(self))
p.text(f"Url: {self._url}\n")
p.text(f"Project: {self._project}\n")
@property
def experiments(self) -> ExperimentClient:
"""Returns a pre-initialised ExperimentClient whose project has been set to the project configured for the Cortex.client.
If you want to access experiments for a project that is
different from the one configured with Cortex.client, please use :meth:`cortex.client.Client.experiments_client` instead
.. code-block::
## use default .experiments client helper
from cortex.client import Cortex
client = Cortex.client()
client.experiments.list_experiments()
client.experiments.save_experiment()
client.experiments.list_runs()
client.experiments.delete_runs()
Refer to the documentation of :class:`cortex.experiment.ExperimentClient` to learn more about the methods available on the ExperimentClient
:returns: An instance of this helper class that enables access to the Fabric Experiments API.
:rtype: :class:`cortex.experiment.ExperimentClient`
""" # pylint: disable=line-too-long
return self._service_clients.get("experiments")
def experiments_client(self, project: str = None) -> ExperimentClient:
"""Helper method to create a new :class:`cortex.experiment.ExperimentClient` instance that is configured to talk to another `project` than the default :attr:`cortex.client.Client._project`
>>> expc = client.experiments_client(project="another-project")
:param project: Project for which an experiments client is to be created, defaults to (the project configured with cortex.client.Client)
:type project: str, optional
:return: An experiment client
:rtype: :class:`cortex.experiment.ExperimentClient`
""" # pylint: disable=line-too-long
if project is not None:
return ExperimentClient(project=project)
return self.experiments
@property
def connections(self) -> ConnectionClient:
"""Returns a pre-initialised ConnectionClient whose project has been set to the project configured for the Cortex.client.
If you want to access connections for a project that is
different from the one configured with Cortex.client, please use :meth:`cortex.client.Client.connections_client` instead
.. code-block::
## use default .connections client helper
from cortex.client import Cortex
client = Cortex.client()
client.connections.save_connection
client.connections.get_connection
Refer to the documentation of :class:`cortex.connection.ConnectionClient` to learn more about the methods available on the ConnectionClient
:returns: An instance of this helper class that enables access to the Fabric Connections API.
:rtype: :class:`cortex.connection.ConnectionClient`
""" # pylint: disable=line-too-long
return self._service_clients.get("connections")
def connections_client(self, project: str = None) -> ConnectionClient:
"""Helper method to create a new :class:`cortex.connection.ConnectionClient` instance that is configured to talk to another `project` than the default :attr:`cortex.client.Client._project`
>>> connc = client.connections_client(project="another-project")
:param project: Project for which a connections client is to be created, defaults to (the project configured with cortex.client.Client)
:type project: str, optional
:return: A connection client
:rtype: :class:`cortex.connection.ConnectionClient`
""" # pylint: disable=line-too-long
if project is not None:
return ConnectionClient(project=project)
return self.connections
@property
def content(self) -> ManagedContentClient:
"""Returns a pre-initialised ManagedContentClient whose project has been set to the project configured for the Cortex.client.
If you want to access managed content for a project that is
different from the one configured with Cortex.client, please use :meth:`cortex.client.Client.content_client` instead
.. code-block::
## use default .content client helper
from cortex.client import Cortex
client = Cortex.client()
client.content.list
client.content.upload
client.content.exists
.....
Refer to the documentation of :class:`cortex.content.ManagedContentClient` to learn more about the methods available on the ManagedContentClient
:returns: An instance of this helper class that enables access to the Fabric Managed Content API.
:rtype: :class:`cortex.content.ManagedContentClient`
""" # pylint: disable=line-too-long
return self._service_clients.get("content")
def content_client(self, project: str = None) -> ManagedContentClient:
"""Helper method to create a new :class:`cortex.connection.ManagedContentClient` instance that is configured to talk to another `project` than the default :attr:`cortex.client.Client._project`
>>> contentc = client.content_client(project="another-project")
:param project: Project for which a managed content client is to be created, defaults to (the project configured with cortex.client.Client)
:type project: str, optional
:return: A managed content client
:rtype: :class:`cortex.connection.ManagedContentClient`
""" # pylint: disable=line-too-long
if project is not None:
return ManagedContentClient(project=project)
return self.content
@property
def models(self) -> ModelClient:
"""Returns a pre-initialised ModelClient whose project has been set to the project configured for the Cortex.client.
If you want to access models for a project that is
different from the one configured with Cortex.client, please use :meth:`cortex.client.Client.models_client` instead
.. code-block::
## use default .models client helper
from cortex.client import Cortex
client = Cortex.client()
client.models.list_models()
client.models.get_model()
client.models.save_model()
.....
Refer to the documentation of :class:`cortex.model.ModelClient` to learn more about the methods available on the ModelClient
:returns: An instance of this helper class that enables access to the Fabric Models API.
:rtype: :class:`cortex.model.ModelClient`
""" # pylint: disable=line-too-long
return self._service_clients.get("models")
def models_client(self, project: str = None) -> ModelClient:
"""Helper method to create a new :class:`cortex.model.ModelClient` instance that is configured to talk to another `project` than the default :attr:`cortex.client.Client._project`
>>> modelc = client.models_client(project="another-project")
:param project: Project for which a models client is to be created, defaults to (the project configured with cortex.client.Client)
:type project: str, optional
:return: A models client
:rtype: :class:`cortex.model.ModelClient`
""" # pylint: disable=line-too-long
if project is not None:
return ModelClient(project=project)
return self.models
@property
def secrets(self) -> SecretsClient:
"""Returns a pre-initialised SecretsClient whose project has been set to the project configured for the Cortex.client.
.. important::
Note that, as of Fabric 6.3.3 and Fabric 6.4.0., you can only call :meth:`cortex.secrets.SecretsClient.get_secret` from within a skill running inside the Fabric cluster (won't work locally)
If you want to access secrets for a project that is
different from the one configured with Cortex.client, please use :meth:`cortex.client.Client.secrets_client` instead
.. code-block::
## use default .secrets client helper
from cortex.client import Cortex
client = Cortex.client()
client.models.get_secret()
client.models.post_secret()
.....
Refer to the documentation of :class:`cortex.secrets.SecretsClient` to learn more about the methods available on the SecretsClient
:returns: An instance of this helper class that enables access to the Fabric Secrets API.
:rtype: :class:`cortex.secrets.SecretsClient`
""" # pylint: disable=line-too-long
return self._service_clients.get("secrets")
def secrets_client(self, project: str = None) -> SecretsClient:
"""Helper method to create a new :class:`cortex.secrets.SecretsClient` instance that is configured to talk to another `project` than the default :attr:`cortex.client.Client._project`
>>> secretsc = client.secrets_client(project="another-project")
:param project: Project for which a secrets client is to be created, defaults to (the project configured with cortex.client.Client)
:type project: str, optional
:return: A secrets client
:rtype: :class:`cortex.secrets.SecretsClient`
""" # pylint: disable=line-too-long
if project is not None:
return SecretsClient(project=project)
return self.secrets
@property
def skills(self) -> SkillClient:
"""Returns a pre-initialised SkillClient whose project has been set to the project configured for the Cortex.client.Client
If you want to access Skills for a project that is
different from the one configured with Cortex.client, please use :meth:`cortex.client.Client.skills_client` instead
.. code-block::
## use default .skills client helper
from cortex.client import Cortex
client = Cortex.client()
client.skills.get_skill()
client.skills.save_skill()
client.skills.delete_skill()
client.skills.get_logs()
client.skills.deploy()
client.skills.undeploy()
.....
Refer to the documentation of :class:`cortex.skill.SkillClient` to learn more about the methods available on the SkillClient
:returns: An instance of this helper class that enables access to the Fabric SKills API.
:rtype: :class:`cortex.skill.SkillClient`
""" # pylint: disable=line-too-long
return self._service_clients.get("skills")
def skills_client(self, project: str = None) -> SkillClient:
"""Helper method to create a new :class:`cortex.skill.SkillClient` instance that is configured to talk to another `project` than the default :attr:`cortex.client.Client._project`
>>> skillsc = client.skills_client(project="another-project")
:param project: Project for which a Skill client is to be created, defaults to (the project configured with cortex.client.Client)
:type project: str, optional
:return: A Skills client
:rtype: :class:`cortex.skill.SkillClient`
""" # pylint: disable=line-too-long
if project is not None:
return SkillClient(project=project)
return self.skills
@property
def sessions(self) -> SessionClient:
"""Returns a pre-initialised SessionClient whose project has been set to the project configured for the Cortex.client.Client
If you want to access Sessions for a project that is
different from the one configured with Cortex.client, please use :meth:`cortex.client.Client.sessions_client` instead
.. code-block::
## use default .sessions client helper
from cortex.client import Cortex
client = Cortex.client()
client.sessions.start_session()
client.sessions.get_session_data()
client.sessions.put_session_data()
client.sessions.delete_session()
.....
Refer to the documentation of :class:`cortex.session.SessionClient` to learn more about the methods available on the SessionClient
:returns: An instance of this helper class that enables access to the Fabric Sessions API.
:rtype: :class:`cortex.session.SessionClient`
""" # pylint: disable=line-too-long
return self._service_clients.get("sessions")
def sessions_client(self, project: str = None) -> SessionClient:
"""Helper method to create a new :class:`cortex.session.SessionClient` instance that is configured to talk to another `project` than the default :attr:`cortex.client.Client._project`
>>> sessionsc = client.sessions_client(project="another-project")
:param project: Project for which a Sessions client is to be created, defaults to (the project configured with cortex.client.Client)
:type project: str, optional
:return: A Sessions client
:rtype: :class:`cortex.session.SessionClient`
""" # pylint: disable=line-too-long
if project is not None:
return SessionClient(project=project)
return self.sessions
@property
def types(self) -> TypeClient:
"""Returns a pre-initialised TypeClient whose project has been set to the project configured for the Cortex.client.Client
If you want to access Types for a project that is
different from the one configured with Cortex.client, please use :meth:`cortex.client.Client.types_client` instead
.. code-block::
## use default .types client helper
from cortex.client import Cortex
client = Cortex.client()
client.types.get_type()
client.types.save_type()
.....
Refer to the documentation of :class:`cortex.types.TypeClient` to learn more about the methods available on the TypeClient
:returns: An instance of this helper class that enables access to the Fabric Types API.
:rtype: :class:`cortex.types.TypeClient`
""" # pylint: disable=line-too-long
return self._service_clients.get("types")
def types_client(self, project: str = None) -> TypeClient:
"""Helper method to create a new :class:`cortex.types.TypeClient` instance that is configured to talk to another `project` than the default :attr:`cortex.client.Client._project`
>>> typesc = client.types_client(project="another-project")
:param project: Project for which a Types client is to be created, defaults to (the project configured with cortex.client.Client)
:type project: str, optional
:return: A Types client
:rtype: :class:`cortex.types.TypeClient`
""" # pylint: disable=line-too-long
if project is not None:
return TypeClient(project=project)
return self.types
class Local:
"""
Provides local, on-disk implementations of Cortex APIs.
"""
def __init__(self, basedir=None):
self._basedir = basedir
def experiment(self, name: str) -> LocalExperiment:
"""
Create an experiment without connecting to Cortex fabric
:param name: Experiment name
:return: Experiment instance
"""
return LocalExperiment(name, self.basedir)
@property
def basedir(self):
"""Return the configured base directory of this :class:`cortex.client.Local` instance
:return: configured base directory
:rtype: _type_
"""
return self._basedir
class Cortex:
"""
Entry point to the Cortex API.
"""
@staticmethod
def client(
api_endpoint: str = None,
api_version: int = 4,
verify_ssl_cert=None,
token: str = None,
config: dict = None,
project: str = None,
profile: str = None,
) -> Client:
"""
Gets a client with the provided parameters. All parameters are optional and default to environment variable values if not specified. Client creation can fail if you don't have a default project set in your environment variables or the Cortex config file.
.. important::
You can also set a default project when configuring your Cortex CLI using `cortex configure --project <your-project>`.
This value will be updated into the `$HOME/.cortex/config` file. If your Cortex config file `$HOME/.cortex/config` does not contain a default `project` set for the profile being used as the default one, you will need to set the project key when instantiating a :class:`cortex.client.Client`.
**Example**
>>> from cortex.client import Cortex
>>> cortex = Cortex.client(project='example-project')
:param api_endpoint: The Cortex URL.
:param api_version: The version of the API to use with this client.
:param verify_ssl_cert: A boolean to enable/disable SSL validation, or path to a CA_BUNDLE file or directory with certificates of trusted CAs (default: True)
:param project: Cortex Project that you want to use.
:param token: (optional) Use JWT token for authenticating requests, will default to settings in ~/.cortex/config if not provided
:param config: (optional) Use Cortex personal access token config file to generate JWT tokens.
:returns: An instance of :class:`cortex.client.Client`
:rtype: :class:`cortex.client.Client`
""" # pylint: disable=line-too-long
env = CortexEnv(
api_endpoint=api_endpoint,
token=token,
config=config,
project=project,
profile=profile,
)
if not api_endpoint:
api_endpoint = env.api_endpoint
if not token:
token = env.token
if not config:
config = env.config
if not project:
project = env.project
if not project:
raise ProjectException(
"Please Provide Project Name that you want to access Cortex Assets for"
)
tkn = _Token(token)
return Client(
url=api_endpoint,
version=api_version,
token=tkn,
config=config,
project=project,
verify_ssl_cert=verify_ssl_cert,
)
@staticmethod
def from_message(msg, verify_ssl_cert=None) -> Client:
"""Creates a Cortex client from a skill's input message, expects
.. code-block::
{ api_endpoint:"..", token:"..", projectId:".."}
:param msg: A message for constructing a Cortex Client.
:param verify_ssl_cert: A boolean to enable/disable SSL validation, or path to a CA_BUNDLE file or directory with certificates of trusted CAs (default: True)
:returns: A Cortex Client
:rtype: :class:`cortex.client.Client`
""" # pylint: disable=line-too-long
if not isinstance(msg, dict):
raise InvalidMessageTypeException(
f"Skill message must be a `dict` not a {type(msg)}"
)
keys = ("apiEndpoint", "token", "projectId")
if not all(key in msg for key in keys):
raise IncompleteMessageKeysException(
f"Skill message must contain these keys: {keys}"
)
return Cortex.client(
api_endpoint=msg.get("apiEndpoint"),
token=msg.get("token"),
project=msg.get("projectId"),
verify_ssl_cert=verify_ssl_cert,
)
@staticmethod
def local(basedir=None):
"""Create a Local Cortex implementation (mock)
:param basedir: Root filesystem location, defaults to None
:type basedir: str, optional
:return: an instance of :class:`cortex.client.Local`
:rtype: :class:`cortex.client.Local`
"""
return Local(basedir)
@staticmethod
def login():
"""
Login to Cortex6. The function prompts the caller for Cortex Personal Access Config.
**Example**
>>> Cortex.login()
Cortex Personal Access Config: Cortex Personal Access Config
Cortex Project: The project that you to start using you Cortex assets from. (Not required)
"""
config = input("Cortex Personal Access Config: ")
project = input("Project: ")
os.environ["CORTEX_PERSONAL_ACCESS_CONFIG"] = config
if project:
os.environ["CORTEX_PROJECT"] = project