Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def getClients(admin_mc):
return CustomObjectsApi(admin_mc.k8s_client), \
CoreV1Api(admin_mc.k8s_client)
def delete_instance_expired(self, instances):
"""
Deletes from current list of instances the expired ones.
:returns: None
:instances: current instance list in crowlabs
"""
api_instance = client.CustomObjectsApi()
for instance in instances.get("items"):
# get instance name
name = instance.get("metadata").get("name")
# get instance creation timestamp
creation_timestamp = instance.get("metadata").get("creationTimestamp")
# get instance
namespace = instance.get("metadata").get("namespace")
# retrieve template name
template_name = instance.get("spec").get("template.crownlabs.polito.it/TemplateRef").get("name")
# retrieve template namespace
template_ns = instance.get("spec").get("template.crownlabs.polito.it/TemplateRef").get("namespace", "default")
# retrieve instance life span
logger.debug(f"Processing instance: '{name}' in Namespace: '{namespace}' Created at: '{creation_timestamp}'")
time = self.get_life_span(template_name, template_ns)
if time is None:
run_kinds_filter: List[Enum] = None) -> List[Run]:
"""
Return list of experiment runs.
:param namespace: If provided, only runs from this namespace will be returned
:param state_list: If provided, only runs with given states will be returned
:param name_filter: If provided, only runs matching name_filter regular expression will be returned
:param exp_name_filter: If provided, list of runs is filtered by experiment names from given list
:param excl_state: If provided, only runs with a state other than given will be returned
:param run_kinds_filter: If provided, only runs with a kind that matches to any of the run kinds from given
filtering list will be returned
:return: List of Run objects
In case of problems during getting a list of runs - throws an error
"""
logger.debug('Listing runs.')
config.load_kube_config()
api = client.CustomObjectsApi(client.ApiClient())
if namespace:
raw_runs = api.list_namespaced_custom_object(group=API_GROUP_NAME, namespace=namespace,
plural=RUN_PLURAL, version=RUN_VERSION)
else:
raw_runs = api.list_cluster_custom_object(group=API_GROUP_NAME, plural=RUN_PLURAL, version=RUN_VERSION)
try:
name_regex = re.compile(name_filter) if name_filter else None
except sre_constants.error as e:
error_msg = Texts.REGEX_COMPILATION_FAIL_MSG.format(name_filter=name_filter)
logger.exception(error_msg)
raise InvalidRegularExpressionError(error_msg) from e
run_filters = [partial(filter_by_name_regex, name_regex=name_regex, spec_location=False),
partial(filter_run_by_state, state_list=state_list),
partial(filter_run_by_excl_state, state=excl_state),
timeout=datetime.timedelta(minutes=5),
polling_interval=datetime.timedelta(seconds=30),
status_callback=None):
"""Wait for the specified job to be deleted.
Args:
client: K8s api client.
namespace: namespace for the job.
name: Name of the job.
timeout: How long to wait for the job.
polling_interval: How often to poll for the status of the job.
status_callback: (Optional): Callable. If supplied this callable is
invoked after we poll the job. Callable takes a single argument which
is the job.
"""
crd_api = k8s_client.CustomObjectsApi(client)
end_time = datetime.datetime.now() + timeout
while True:
try:
results = crd_api.get_namespaced_custom_object(
TF_JOB_GROUP, version, namespace, TF_JOB_PLURAL, name)
except rest.ApiException as e:
if e.status == httplib.NOT_FOUND:
return
logging.exception("rest.ApiException thrown")
raise
if status_callback:
status_callback(results)
if datetime.datetime.now() + polling_interval > end_time:
raise util.TimeoutError(
"Timeout waiting for job {0} in namespace {1} to be deleted.".format(
def get_model_deployment_status(self, name):
"""
Get model training status
:param name: name of a model training resource
:return: status
"""
crds = kubernetes.client.CustomObjectsApi()
md = crds.get_namespaced_custom_object(*self._model_deployment_info, name.lower())
print(f'Fetched model training: {md}')
status = md.get('status')
return status if status else {}
@app.route("/")
def guitarslist():
"""
display guitars
"""
if 'KUBERNETES_PORT' in os.environ:
config.load_incluster_config()
else:
config.load_kube_config()
crds = client.CustomObjectsApi()
guitars = crds.list_cluster_custom_object(DOMAIN, "v1", "guitars")["items"]
return render_template("index.html", title="Guitars", guitars=guitars)
def __init_kube_apis(self):
if os.path.exists('/run/secrets/kubernetes.io/serviceaccount/token'):
f = open('/run/secrets/kubernetes.io/serviceaccount/token')
kube_auth_token = f.read()
kube_config = kubernetes.client.Configuration()
kube_config.api_key['authorization'] = 'Bearer ' + kube_auth_token
kube_config.host = os.environ['KUBERNETES_PORT'].replace('tcp://', 'https://', 1)
kube_config.ssl_ca_cert = '/run/secrets/kubernetes.io/serviceaccount/ca.crt'
else:
kubernetes.config.load_kube_config()
kube_config = None
self.api_client = kubernetes.client.ApiClient(kube_config)
self.core_v1_api = kubernetes.client.CoreV1Api(self.api_client)
self.custom_objects_api = kubernetes.client.CustomObjectsApi(self.api_client)
def init_kube_api():
global custom_objects_api, api_client, operator_domain
kubernetes.config.load_kube_config()
api_client = kubernetes.client.ApiClient()
custom_objects_api = kubernetes.client.CustomObjectsApi(api_client)
operator_domain = os.environ.get('OPERATOR_DOMAIN', 'anarchy.gpte.redhat.com')
def clean_nuts(self, valid_id_rotation):
crds = client.CustomObjectsApi()
nuts = crds.list_cluster_custom_object(self.squirrel.domain_api, self.squirrel.api_version, 'nuts')["items"]
for n in nuts:
if n["data"].get("id_rotation", 10000000000) != valid_id_rotation:
try:
api_response = crds.delete_namespaced_custom_object(\
self.squirrel.domain_api, \
self.squirrel.api_version, \
n["metadata"]["namespace"], \
'nuts', \
n["metadata"]["name"],
client.V1DeleteOptions())
print(api_response)
except ApiException as e:
print("Exception when calling CustomObjectsApi->delete_namespaced_custom_object: %s\n" % e)
def get_k8s_api_custom_client(id_token):
custom_obj_api_instance = client.CustomObjectsApi(get_simple_client(id_token))
return custom_obj_api_instance