Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def create_namespace(self, ns_name):
self.cluster.create_namespace(client.V1Namespace(metadata=client.V1ObjectMeta(name=ns_name)))
def setUpClass(cls):
cls.config = base.get_e2e_configuration()
cls.path_prefix = "kubernetes/e2e_test/test_yaml/"
cls.test_namespace = "e2e-test-utils"
k8s_client = client.api_client.ApiClient(configuration=cls.config)
core_v1 = client.CoreV1Api(api_client=k8s_client)
body = client.V1Namespace(metadata=client.V1ObjectMeta(name=cls.test_namespace))
core_v1.create_namespace(body=body)
def add(self, result):
stream = six.StringIO(result)
for item in yaml.safe_load_all(stream):
id = (item['apiVersion'], item['kind'], item['metadata']['name'])
if id in self.items:
log.warning("Duplicate item #{}".format(id))
api = [p.capitalize() for p in id[0].split('/', 1)]
klass = getattr(client, "".join([api[-1], id[1]]))
api_client = client.ApiClient()
self.items[id] = api_client._ApiClient__deserialize_model(item, klass)
def __init__(self):
if 'KUBERNETES_PORT' in os.environ:
k8s.config.load_incluster_config()
else:
k8s.config.load_kube_config()
config = k8s.client.Configuration()
config.assert_hostname = False
self.api = k8s.client.api_client.ApiClient(configuration=config)
self.ext_api = k8s.client.ApiextensionsV1beta1Api(self.api)
self.crd_api = k8s.client.CustomObjectsApi(self.api)
volume_mounts = []
# Create mount paths for the volumes
for volume in volumes:
volume_mounts.append(client.V1VolumeMount(mount_path=volume[1],
name=volume[0]))
resources = client.V1ResourceRequirements(limits={'cpu': str(self.max_cpu),
'memory': self.max_mem},
requests={'cpu': str(self.init_cpu),
'memory': self.init_mem}
)
# Configure Pod template container
container = client.V1Container(
name=pod_name,
image=image,
resources=resources,
ports=[client.V1ContainerPort(container_port=port)],
volume_mounts=volume_mounts,
command=['/bin/bash'],
args=launch_args,
env=[environment_vars],
security_context=security_context)
# Create a secret to enable pulling images from secure repositories
secret = None
if self.secret:
secret = client.V1LocalObjectReference(name=self.secret)
# Create list of volumes from (pvc, mount) tuples
volume_defs = []
for volume in volumes:
volume_defs.append(client.V1Volume(name=volume[0],
persistent_volume_claim=client.V1PersistentVolumeClaimVolumeSource(
from kubernetes import client
access_key = access_key or environ.get('V3IO_ACCESS_KEY')
remote = str(remote)
if remote.startswith('~/'):
user = environ.get('V3IO_USERNAME', user)
if not user:
raise ValueError('user name/env must be specified when using "~" in path')
if remote == '~/':
remote = 'users/' + user
else:
remote = 'users/' + user + remote[1:]
container, subpath = split_path(remote)
opts = {'accessKey': access_key, 'container': container, 'subPath': subpath}
vol = client.V1Volume(name=name, flex_volume=client.V1FlexVolumeSource('v3io/fuse', options=opts))
return vol
os.remove(kubeconfig)
logger.info('Building the kubeconfig file for {}'.format(cluster_name))
create_kubeconfig(cluster_name)
logger.info('Generating bearer token')
token = get_bearer_token(cluster_name)
# Configure the kubenetes client
config.load_kube_config(kubeconfig)
configuration = client.Configuration()
configuration.api_key['authorization'] = token
configuration.api_key_prefix['authorization'] = 'Bearer'
# Configure the API
api = client.ApiClient(configuration)
v1 = client.CoreV1Api(api)
try:
if not node_exists(v1, node_name):
# Don't delay if the node already doesn't exist
global delay
del delay
complete_lifecycle(detail)
return
# Cordon the node, sleep for 2s remove all pods and complete the lifecycle
cordon_node(v1, node_name)
time.sleep(2)
remove_all_pods(v1, node_name)
complete_lifecycle(detail)
def _update(name: str, namespace: str, body: object) -> (KubernetesObject, Run):
"""
Patch a Run object for a given data
:param name run name to update
:param namespace where Run will be updated
:param body: patch object to apply
:return: in case of any problems during update it throws an exception
"""
config.load_kube_config()
api = client.CustomObjectsApi(client.ApiClient())
try:
raw_run = api.patch_namespaced_custom_object(group='aggregator.aipg.intel.com', namespace=namespace, body=body,
plural=RUN_PLURAL, version=RUN_VERSION, name=name)
schema = RunKubernetesSchema()
run, err = schema.load(raw_run)
if err:
raise RuntimeError(Texts.K8S_RESPONSE_LOAD_ERROR_MSG.format(err=err))
logger.debug(f"Run patch response : {raw_run}")
return run, Run.from_k8s_response_dict(raw_run)
except ApiException as exe:
err_message = Texts.RUN_UPDATE_ERROR_MSG
logger.exception(err_message)
raise RuntimeError(err_message) from exe
def _create_config_service(self):
metadata = k8s_client.V1ObjectMeta(namespace=self._namespace, name=self.config_path, labels=self._labels)
body = k8s_client.V1Service(metadata=metadata, spec=k8s_client.V1ServiceSpec(cluster_ip='None'))
try:
if not self._api.create_namespaced_service(self._namespace, body):
return
except Exception as e:
if not isinstance(e, k8s_client.rest.ApiException) or e.status != 409: # Service already exists
return logger.exception('create_config_service failed')
self._should_create_config_service = False