本文整理汇总了Python中kubernetes.config.load_incluster_config方法的典型用法代码示例。如果您正苦于以下问题:Python config.load_incluster_config方法的具体用法?Python config.load_incluster_config怎么用?Python config.load_incluster_config使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类kubernetes.config
的用法示例。
在下文中一共展示了config.load_incluster_config方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def __init__(self, k8s_config=None, k8s_namespace=None, label_selector=None):
from kubernetes import config, client
from gevent.threadpool import ThreadPool
if k8s_config is not None:
self._k8s_config = k8s_config
elif os.environ.get('KUBE_API_ADDRESS'):
self._k8s_config = client.Configuration()
self._k8s_config.host = os.environ['KUBE_API_ADDRESS']
else:
self._k8s_config = config.load_incluster_config()
self._k8s_namespace = k8s_namespace or os.environ.get('MARS_K8S_POD_NAMESPACE') or 'default'
self._label_selector = label_selector
self._client = client.CoreV1Api(client.ApiClient(self._k8s_config))
self._pool = ThreadPool(1)
self._pod_to_ep = None
示例2: get_k8s_nodes
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def get_k8s_nodes(exclude_node_label_key=app_config["EXCLUDE_NODE_LABEL_KEY"]):
"""
Returns a list of kubernetes nodes
"""
try:
config.load_incluster_config()
except config.ConfigException:
try:
config.load_kube_config()
except config.ConfigException:
raise Exception("Could not configure kubernetes python client")
k8s_api = client.CoreV1Api()
logger.info("Getting k8s nodes...")
response = k8s_api.list_node()
if exclude_node_label_key is not None:
nodes = []
for node in response.items:
if exclude_node_label_key not in node.metadata.labels:
nodes.append(node)
response.items = nodes
logger.info("Current k8s node count is {}".format(len(response.items)))
return response.items
示例3: delete_node
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def delete_node(node_name):
"""
Deletes a kubernetes node from the cluster
"""
try:
config.load_incluster_config()
except config.ConfigException:
try:
config.load_kube_config()
except config.ConfigException:
raise Exception("Could not configure kubernetes python client")
configuration = client.Configuration()
# create an instance of the API class
k8s_api = client.CoreV1Api(client.ApiClient(configuration))
logger.info("Deleting k8s node {}...".format(node_name))
try:
if not app_config['DRY_RUN']:
k8s_api.delete_node(node_name)
else:
k8s_api.delete_node(node_name, dry_run="true")
logger.info("Node deleted")
except ApiException as e:
logger.info("Exception when calling CoreV1Api->delete_node: {}".format(e))
示例4: __init__
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Load kubernetes config here, since this is a Singleton and
# so this __init__ will be run way before anything else gets run.
try:
config.load_incluster_config()
except config.ConfigException:
config.load_kube_config()
self.api = shared_client(self.api_group_name)
# FIXME: Protect against malicious labels?
self.label_selector = ','.join(['{}={}'.format(k, v) for k, v in self.labels.items()])
self.field_selector = ','.join(['{}={}'.format(k, v) for k, v in self.fields.items()])
self.first_load_future = Future()
self._stop_event = threading.Event()
self.start()
示例5: get_conn
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def get_conn(self):
"""
Returns kubernetes api session for use with requests
"""
connection = self.get_connection(self.conn_id)
extras = connection.extra_dejson
if extras.get("extra__kubernetes__in_cluster"):
self.log.debug("loading kube_config from: in_cluster configuration")
config.load_incluster_config()
elif extras.get("extra__kubernetes__kube_config") is None:
self.log.debug("loading kube_config from: default file")
config.load_kube_config()
else:
with tempfile.NamedTemporaryFile() as temp_config:
self.log.debug("loading kube_config from: connection kube_config")
temp_config.write(extras.get("extra__kubernetes__kube_config").encode())
temp_config.flush()
config.load_kube_config(temp_config.name)
return client.ApiClient()
示例6: _configure_k8s
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def _configure_k8s(self):
k8s_config_file = os.environ.get('KUBECONFIG')
if k8s_config_file:
try:
logging.info('Loading kubernetes config from the file %s', k8s_config_file)
config.load_kube_config(config_file=k8s_config_file)
except Exception as e:
raise RuntimeError('Can not load kube config from the file %s, error: %s', k8s_config_file, e)
else:
try:
config.load_incluster_config()
logging.info('Initialized with in-cluster config.')
except:
logging.info('Cannot find in-cluster config, trying the local kubernetes config. ')
try:
config.load_kube_config()
logging.info('Found local kubernetes config. Initialized with kube_config.')
except:
raise RuntimeError('Forgot to run the gcloud command? Check out the link: \
https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-access-for-kubectl for more information')
self._api_client = k8s_client.ApiClient()
self._corev1 = k8s_client.CoreV1Api(self._api_client)
return True
示例7: _load_kfp_environment
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def _load_kfp_environment(self):
self._pod_name = os.environ.get(KFP_POD_ENV_NAME, None)
self._namespace = os.environ.get(KFP_NAMESPACE_ENV_NAME, DEFAULT_NAMESPACE)
if not self._pod_name:
self._k8s_client = None
else:
try:
config.load_incluster_config()
self._k8s_client = client.CoreV1Api()
except Exception as e:
logging.warning('Failed to load kubernetes client:'
' {}.'.format(e))
self._k8s_client = None
if self._pod_name and self._k8s_client:
self._argo_node_name = self._get_argo_node_name()
if not self.under_kfp_environment():
logging.warning('Running without KFP context.')
示例8: __init__
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def __init__(self, k8s_config=None, namespace="default", in_cluster=False):
if not k8s_config:
if in_cluster:
config.load_incluster_config()
else:
config.load_kube_config()
self.api_client = None
else:
self.api_client = client.api_client.ApiClient(configuration=k8s_config)
self._k8s_api = None
self._k8s_batch_api = None
self._k8s_apps_api = None
self._k8s_beta_api = None
self._networking_v1_beta1_api = None
self._k8s_custom_object_api = None
self._k8s_version_api = None
self.namespace = namespace
self.in_cluster = in_cluster
示例9: modify_k8s_autoscaler
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def modify_k8s_autoscaler(action):
"""
Pauses or resumes the Kubernetes autoscaler
"""
try:
config.load_incluster_config()
except config.ConfigException:
try:
config.load_kube_config()
except config.ConfigException:
raise Exception("Could not configure kubernetes python client")
# Configure API key authorization: BearerToken
configuration = client.Configuration()
# create an instance of the API class
k8s_api = client.AppsV1Api(client.ApiClient(configuration))
if action == 'pause':
logger.info('Pausing k8s autoscaler...')
body = {'spec': {'replicas': 0}}
elif action == 'resume':
logger.info('Resuming k8s autoscaler...')
body = {'spec': {'replicas': app_config['K8S_AUTOSCALER_REPLICAS']}}
else:
logger.info('Invalid k8s autoscaler option')
sys.exit(1)
try:
k8s_api.patch_namespaced_deployment(
app_config['K8S_AUTOSCALER_DEPLOYMENT'],
app_config['K8S_AUTOSCALER_NAMESPACE'],
body
)
logger.info('K8s autoscaler modified to replicas: {}'.format(body['spec']['replicas']))
except ApiException as e:
logger.info('Scaling of k8s autoscaler failed. Error code was {}, {}. Exiting.'.format(e.reason, e.body))
sys.exit(1)
示例10: cordon_node
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def cordon_node(node_name):
"""
Cordon a kubernetes node to avoid new pods being scheduled on it
"""
try:
config.load_incluster_config()
except config.ConfigException:
try:
config.load_kube_config()
except config.ConfigException:
raise Exception("Could not configure kubernetes python client")
configuration = client.Configuration()
# create an instance of the API class
k8s_api = client.CoreV1Api(client.ApiClient(configuration))
logger.info("Cordoning k8s node {}...".format(node_name))
try:
api_call_body = client.V1Node(spec=client.V1NodeSpec(unschedulable=True))
if not app_config['DRY_RUN']:
k8s_api.patch_node(node_name, api_call_body)
else:
k8s_api.patch_node(node_name, api_call_body, dry_run=True)
logger.info("Node cordoned")
except ApiException as e:
logger.info("Exception when calling CoreV1Api->patch_node: {}".format(e))
示例11: _get_kube_config
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def _get_kube_config(in_cluster: bool,
cluster_context: Optional[str],
config_file: Optional[str]) -> Optional[Configuration]:
if in_cluster:
# load_incluster_config set default configuration with config populated by k8s
config.load_incluster_config()
return None
else:
# this block can be replaced with just config.load_kube_config once
# refresh_config module is replaced with upstream fix
cfg = RefreshConfiguration()
load_kube_config(
client_configuration=cfg, config_file=config_file, context=cluster_context)
return cfg
示例12: get_k8s_client
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def get_k8s_client():
config.load_incluster_config()
return client.CoreV1Api()
示例13: __init__
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def __init__(self, bearer_token=None):
'''
Initialize connection to Kubernetes
'''
self.bearer_token = bearer_token
api_client = None
try:
config.load_incluster_config()
except config.config_exception.ConfigException:
config.load_kube_config()
if self.bearer_token:
# Configure API key authorization: Bearer Token
configuration = client.Configuration()
configuration.api_key_prefix['authorization'] = 'Bearer'
configuration.api_key['authorization'] = self.bearer_token
api_client = client.ApiClient(configuration)
self.client = client.CoreV1Api(api_client)
self.batch_api = client.BatchV1Api(api_client)
self.batch_v1beta1_api = client.BatchV1beta1Api(api_client)
self.custom_objects = client.CustomObjectsApi(api_client)
self.api_extensions = client.ApiextensionsV1beta1Api(api_client)
self.extension_api = client.ExtensionsV1beta1Api(api_client)
self.apps_v1_api = client.AppsV1Api(api_client)
示例14: log_k8s_event
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def log_k8s_event(self, asg_name, price="", useSpot=False):
msg_str = '{"apiVersion":"v1alpha1","spotPrice":"' + price + '", "useSpot": ' + str(useSpot).lower() + '}'
event_namespace = os.getenv('EVENT_NAMESPACE', 'default')
if not self.incluster:
logger.info(msg_str)
return
try:
config.load_incluster_config()
v1 = client.CoreV1Api()
event_timestamp = datetime.now(pytz.utc)
event_name = "spot-instance-update"
new_event = client.V1Event(
count=1,
first_timestamp=event_timestamp,
involved_object=client.V1ObjectReference(
kind="SpotPriceInfo",
name=asg_name,
namespace=event_namespace,
),
last_timestamp=event_timestamp,
metadata=client.V1ObjectMeta(
generate_name=event_name,
),
message=msg_str,
reason="SpotRecommendationGiven",
source=client.V1EventSource(
component="minion-manager",
),
type="Normal",
)
v1.create_namespaced_event(namespace=event_namespace, body=new_event)
logger.info("Spot price info event logged")
except Exception as e:
logger.info("Failed to log event: " + str(e))
示例15: get_name_for_instance
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import load_incluster_config [as 别名]
def get_name_for_instance(self, instance):
config.load_incluster_config()
v1 = client.CoreV1Api()
for item in v1.list_node().items:
if instance.InstanceId in item.spec.provider_id:
logger.info("Instance name for %s in Kubernetes clusters is %s",
instance.InstanceId, item.metadata.name)
return item.metadata.name
return None