Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def mock_iter_resp_lines(resp):
for name in ['test1', 'test2', 'test3']:
yield json.dumps({
'type': 'ADDED',
'object': models.V1DeploymentConfig(
metadata=k8s_models.V1ObjectMeta(
name=name,
resource_version=1
),
spec=models.V1DeploymentConfigSpec()
).to_dict()
})
oapi = client.OapiApi()
monkeypatch.setattr(oapi, 'list_deployment_config_for_all_namespaces', MockHTTPResponse)
monkeypatch.setattr(k8s_watch.watch, 'iter_resp_lines', mock_iter_resp_lines)
count = 2
names = ['test1', 'test2', 'test3']
w = watch.Watch(return_type="V1DeploymentConfig")
for event in w.stream(oapi.list_deployment_config_for_all_namespaces, _request_timeout=2):
assert event['object'].metadata.name in names
names.remove(event['object'].metadata.name)
count -= 1
if not count:
w.stop()
logging.info("For %s : %s" %(podType.upper(), get_helm))
helm = subprocess.check_output("%s" %get_helm, shell=True)
helm = helm.decode(encoding)
#print("\n%s\n" %helm)
allHelm = helm.splitlines()[1:]
for helmEntry in allHelm:
helm = helmEntry.split(' ')[0]
#print("\n%s\n" %patt.findall(helmEntry)[0])
if patt.findall(helmEntry)[0].find(podType) == -1:
continue
return patt.findall(helmEntry)[0].strip(' ')
logging.error(display_colored_text('31m',"ERROR: No helm chart for %s in %s namespace" %(podType, namespace)))
raise exception("FAILED : Could not get logs for AKO pod")
except subprocess.CalledProcessError:
traceback.print_exc(file=sys.stdout)
raise exception("FAILED : Could not get helm chart name")
Pods = subprocess.check_output("%s" %get_pod , shell=True)
Pods = Pods.decode(encoding)
#In case of an error, an empty output is returned by the kubectl get command
if len(Pods)==0:
raise exception("FAILED: : Error in getting the pod name from the helm chart in the given namespace")
allPods = Pods.splitlines()[1:]
for podLine in allPods:
podName = podLine.split(' ')[0]
if podName.find(podType) == -1:
continue
return podName
raise exception("FAILED: : No amko pod in the specified helm chart")
except subprocess.CalledProcessError:
print("")
traceback.print_exc(file=sys.stdout)
raise exception("FAILED: : Could not get pod name")
def delete_old_images(image_name):
# Let's ignore the registry prefix for now because sometimes our tag doesn't match the registry
registry, image_name = image_name.split('/', 1)
try:
oapi = openshift_client.OapiApi()
image_list = get_registry_images()
for image in image_list['items']:
image_fqn, image_sha = image['dockerImageReference'].split("@")
if image_name in image_fqn:
print("Found image: %s" % image_fqn)
if registry not in image_fqn:
# This warning will only get displayed if a user has used --registry-route
# This is because the route name gets collapsed into the service hostname
# when pushed to the registry.
print("Warning: Tagged image registry prefix doesn't match. Deleting anyway. Given: %s; Found: %s"
% (registry, image_fqn.split('/')[0]))
oapi.delete_image(name=image_sha, body={})
print("Successfully deleted %s" % image_sha)
except Exception as e:
print("Exception deleting old images: %s" % e)
def removeDir(folderName):
rm_dir = "rm -r %s" %folderName
logging.info("Clean up: %s" %rm_dir)
try:
output = subprocess.check_output("%s" %rm_dir, shell=True)
except subprocess.CalledProcessError:
print("")
traceback.print_exc(file=sys.stdout)
raise exception("FAILED:: : Could not delete the directory %s" %folderName)
def findPVCName(helmResult, namespace, helmchart, since, podType):
start = helmResult.find("persistentVolumeClaim") + len("persistentVolumeClaim:")
end = helmResult.find("\n", start)
if start==-1 or end==-1:
raise exception("FAILED: : Helm chart details does not contain any field named persistentVolumeClaim to get the PVC name")
pvcName = helmResult[start:end].strip().strip("\"")
if len(pvcName) > 0:
logging.info("PVC name is %s" %pvcName)
return pvcName
else:
getLogsFromPod(namespace, helmchart, since, podType)
return "done"
def copyLogsFromPVC(namespace, podName, pvMount, logFileName, folderName, pvcName, podType):
kubectl_cp = "kubectl cp %s/%s:%s/%s %s/%s.log" %(namespace,podName,pvMount,logFileName,folderName, podType)
logging.info("%s" %kubectl_cp)
try:
output = subprocess.check_output("%s" %kubectl_cp, shell=True)
if len(output) > 0:
logging.error(display_colored_text('31m',"ERROR: ") + "\n" + output.decode(encoding))
logging.error(display_colored_text('34m',"WARNING: ") + "Because of the above error, skipping the log collection and proceeding with code")
return
except:
print("")
traceback.print_exc(file=sys.stdout)
removeDir(folderName)
raise exception("FAILED: : Could not collect logs from %s/%s of PVC %s " %(pvMount, logFileName, pvcName))
def findPVMount(helmResult):
start = helmResult.find("mountPath") + len("mountPath:")
end = helmResult.find("\n", start)
if start==-1 or end==-1:
raise exception("FAILED: : Helm chart details does not contain any field named mountPath to get the pvc mount path details")
pvcMount = helmResult[start:end].strip().strip("\"")
if len(pvcMount) > 0 :
logging.info("PVC mount point found - %s" %pvcMount)
return pvcMount[1:]
else:
logging.error(display_colored_text('34m',"WARNING: ") + "PV mount path is has no value. Taking /log as the default mount path\n")
return "/log"
try:
pvMount = helmResult['containers'][0]['volumeMounts'][0]['mountPath']
return pvMount
except KeyError:
raise exception("FAILED : The results of helm get all aren't as expected")
def createBackupPod():
create_backup_pod = "kubectl apply -f pod.yaml"
logging.info("%s" %create_backup_pod)
try:
output = subprocess.check_output("%s" %create_backup_pod, shell=True)
except subprocess.CalledProcessError:
traceback.print_exc(file=sys.stdout)
raise exception("FAILED: : Exception occured while creating backup pod custom-backup-pod")
def deletePodFile(podFile):
rm_file = "rm %s" %podFile
logging.info("Clean up: %s" %rm_file)
try:
output = subprocess.check_output("%s" %rm_file, shell=True)
except subprocess.CalledProcessError:
traceback.print_exc(file=sys.stdout)
raise exception("FAILED at clean up stage : Exception occured while deleting pod.yaml file")