11#!/usr/bin/env python
22# -*- coding: utf-8; -*-
33
4- # Copyright (c) 2021, 2022 Oracle and/or its affiliates.
4+ # Copyright (c) 2021, 2023 Oracle and/or its affiliates.
55# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
66
7+ import copy
78import os
89from dataclasses import dataclass
910from typing import Callable , Dict , Optional , Any
1617
1718import ads .telemetry
1819from ads .common import logger
20+ from ads .common .decorator .deprecate import deprecated
1921from ads .common .extended_enum import ExtendedEnumMeta
2022
2123
@@ -255,7 +257,7 @@ def create_signer(
255257
256258 Parameters
257259 ----------
258- auth : Optional[str], default 'api_key'
260+ auth_type : Optional[str], default 'api_key'
259261 'api_key', 'resource_principal' or 'instance_principal'. Enable/disable resource principal identity,
260262 instance principal or keypair identity in a notebook session
261263 oci_config_location: Optional[str], default oci.config.DEFAULT_LOCATION, which is '~/.oci/config'
@@ -378,6 +380,10 @@ def default_signer(client_kwargs: Optional[Dict] = None) -> Dict:
378380 return signer_generator (signer_args ).create_signer ()
379381
380382
383+ @deprecated (
384+ "2.7.3" ,
385+ details = "Deprecated, use: from ads.common.auth import create_signer. https://accelerated-data-science.readthedocs.io/en/latest/user_guide/cli/authentication.html#overriding-defaults." ,
386+ )
381387def get_signer (
382388 oci_config : Optional [str ] = None , oci_profile : Optional [str ] = None , ** client_kwargs
383389) -> Dict :
@@ -686,6 +692,10 @@ class OCIAuthContext:
686692 >>> df_run = DataFlowRun.from_ocid(run_id)
687693 """
688694
695+ @deprecated (
696+ "2.7.3" ,
697+ details = "Deprecated, use: from ads.common.auth import AuthContext" ,
698+ )
689699 def __init__ (self , profile : str = None ):
690700 """
691701 Initialize class OCIAuthContext and saves global state of authentication type and configuration profile.
@@ -700,6 +710,10 @@ def __init__(self, profile: str = None):
700710 self .prev_profile = AuthState ().oci_key_profile
701711 self .oci_cli_auth = AuthState ().oci_cli_auth
702712
713+ @deprecated (
714+ "2.7.3" ,
715+ details = "Deprecated, use: from ads.common.auth import AuthContext" ,
716+ )
703717 def __enter__ (self ):
704718 """
705719 When called by the 'with' statement and if 'profile' provided - 'api_key' authentication with 'profile' used.
@@ -718,3 +732,67 @@ def __exit__(self, exc_type, exc_val, exc_tb):
718732 When called by the 'with' statement restores initial state of authentication type and profile value.
719733 """
720734 ads .set_auth (auth = self .prev_mode , profile = self .prev_profile )
735+
736+
737+ class AuthContext :
738+ """
739+ AuthContext used in 'with' statement for properly managing global authentication type, signer, config
740+ and global configuration parameters.
741+
742+ Examples
743+ --------
744+ >>> from ads import set_auth
745+ >>> from ads.jobs import DataFlowRun
746+ >>> with AuthContext(auth='resource_principal'):
747+ >>> df_run = DataFlowRun.from_ocid(run_id)
748+
749+ >>> from ads.model.framework.sklearn_model import SklearnModel
750+ >>> model = SklearnModel.from_model_artifact(uri="model_artifact_path", artifact_dir="model_artifact_path")
751+ >>> set_auth(auth='api_key', oci_config_location="~/.oci/config")
752+ >>> with AuthContext(auth='api_key', oci_config_location="~/another_config_location/config"):
753+ >>> # upload model to Object Storage using config from another_config_location/config
754+ >>> model.upload_artifact(uri="oci://bucket@namespace/prefix/")
755+ >>> # upload model to Object Storage using config from ~/.oci/config, which was set before 'with AuthContext():'
756+ >>> model.upload_artifact(uri="oci://bucket@namespace/prefix/")
757+ """
758+
759+ def __init__ (self , ** kwargs ):
760+ """
761+ Initialize class AuthContext and saves global state of authentication type, signer, config
762+ and global configuration parameters.
763+
764+ Parameters
765+ ----------
766+ **kwargs: optional, list of parameters passed to ads.set_auth() method, which can be:
767+ auth: Optional[str], default 'api_key'
768+ 'api_key', 'resource_principal' or 'instance_principal'. Enable/disable resource principal
769+ identity, instance principal or keypair identity
770+ oci_config_location: Optional[str], default oci.config.DEFAULT_LOCATION, which is '~/.oci/config'
771+ config file location
772+ profile: Optional[str], default is DEFAULT_PROFILE, which is 'DEFAULT'
773+ profile name for api keys config file
774+ config: Optional[Dict], default {}
775+ created config dictionary
776+ signer: Optional[Any], default None
777+ created signer, can be resource principals signer, instance principal signer or other
778+ signer_callable: Optional[Callable], default None
779+ a callable object that returns signer
780+ signer_kwargs: Optional[Dict], default None
781+ parameters accepted by the signer
782+ """
783+ self .kwargs = kwargs
784+
785+ def __enter__ (self ):
786+ """
787+ When called by the 'with' statement current state of authentication type, signer, config
788+ and configuration parameters saved.
789+ """
790+ self .previous_state = copy .deepcopy (AuthState ())
791+ set_auth (** self .kwargs )
792+
793+ def __exit__ (self , exc_type , exc_val , exc_tb ):
794+ """
795+ When called by the 'with' statement initial state of authentication type, signer, config
796+ and configuration parameters restored.
797+ """
798+ AuthState ().__dict__ .update (self .previous_state .__dict__ )
0 commit comments