NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

#!/usr/bin/python
from __future__ import print_function
from datetime import datetime
import jenkins, time, re, argparse, sys, fileinput, getpass
from xml.etree import ElementTree as ET

if sys.stdin.isatty():
password = getpass.getpass('Password: ')
else:
password = sys.stdin.readline().rstrip()
parser = argparse.ArgumentParser(description=''' ''')
parser.add_argument('-s','--server',default='',nargs="*")
parser.add_argument('-u','--user')
#parser.add_argument('-p','--password')
args = parser.parse_args()

######## HTML CONSTRUCTION FUNCTION ########

def buildHtml():
html = ET.Element('html')
ET.SubElement(ET.SubElement(html, 'head'), 'style').text = "table,th,td{border-width:medium;border-style:solid;margin:auto;border-collapse:collapse;}th,td{border: 1px solid black;border-collapse:collapse;padding:5px;text-align:left;}tr.odd{background-color:LightBlue;}tr.even{background-color:LightGray;}td.info{background-color: Green;}td.warning{background-color:Orange;}td.error{background-color:Red;} .inv{display: none;}select {margin-bottom: 1em;padding: .25em;border: 0;border-bottom: 2px solid currentcolor; font-weight: bold;letter-spacing: .08em;border-radius: 0;select:focus, select:active {outline: 0;border-bottom-color: red;}}button:hover{box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);}"
select = ET.SubElement(ET.SubElement(html, 'body'), 'select', id = 'target')
ET.SubElement(select,'option').text = 'Select jenkins instance'
ET.ElementTree(html).write('resulttmp.html', encoding='utf8',method='html')

def addHtmlTable(instance):
tree = ET.parse('resulttmp.html')
root = tree.getroot()
option = ET.SubElement(root.find(".//select"), 'option', value=instance).text = instance
div = ET.SubElement(root.find(".//body"), 'div', id=instance, attrib={'class': 'inv'})
ET.SubElement(ET.SubElement(div, 'p'), 'button', onclick='sortTable("tab_%s")'%instance).text = 'SORT'
table = ET.SubElement(div, 'table', id='tab_%s'%instance)
ET.SubElement(table, 'th').text = "Job"
ET.SubElement(table, 'th').text = "Job launched by"
ET.SubElement(table, 'th').text = "Last build completed"
ET.SubElement(table, 'th').text = "Build Number"
tree.write('resulttmp.html')


def addHtmlScript():
tree = ET.parse('resulttmp.html')
script = ET.SubElement(tree.getroot().find(".//body"), 'script')
script.text = """function sortTable(server) {var table, rows, switching, i, x, y, shouldSwitch;table = document.getElementById(server);switching = true;while (switching) {switching = false;rows = table.rows;for (i = 1; i < (rows.length - 1); i++) {shouldSwitch = false;x = rows[i].getElementsByTagName("TD")[2];y = rows[i + 1].getElementsByTagName("TD")[2];if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {shouldSwitch = true;break;}}if(shouldSwitch){rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);switching = true;}}} document.getElementById('target').addEventListener('change', function () {'use strict';var vis = document.querySelector('.vis'),target = document.getElementById(this.value);if (vis !== null) {vis.className = 'inv';}if (target !== null ) {target.className = 'vis';}});"""
tree.write('resulttmp.html',encoding='UTF-8')
f = open('resulttmp.html','r')
resulttmp = f.read()
f.close()
f = open('result.html','w')
f.write(resulttmp.replace("&lt;","<").replace("&gt;",">"))
f.close()

def fillHtml(job, date, buildNumber, color, jobUser, background, instance):
tree = ET.parse('resulttmp.html')
tree.write('resulttmp.html')
tr = ET.SubElement(tree.getroot().find('.//table/[@id="tab_%s"]' %instance) , 'tr', attrib={'class': background})
ET.SubElement(ET.SubElement(tr, 'td'),'a', attrib={'href': instance+'/job/'+job+'/configure'}).text = job
ET.SubElement(tr, 'td').text = jobUser
ET.SubElement(tr, 'td', attrib={'class': color}).text = date
ET.SubElement(tr, 'td').text = buildNumber
tree.write('resulttmp.html')

#############################################

########### JENKINS DATA FUNCTION ###########

def findUser(jobName, lastCompletedBuild):
action_list = server.get_build_info(job_name, lastCompletedBuild['number'])['actions']
for item in action_list:
if 'causes' in item:
for element in item['causes']:
if 'shortDescription' in element:
jobUserName = element['shortDescription']
if 'userName' in element:
jobUserName = element['userName']
return jobUserName

def findJobClass(job, instance):
if re.match(r"(UPGRADE_[A-Z]+)|(_LCO-TEST)",str(job.get('name'))):
print('[ERROR] Exclude '+str(job.get('name'))+' from list')
#fillHtml(str(job.get('name')),'Exclude by list exclusion', "null", 'error', 'None', background, instance)
return False
elif (str(job.get('_class'))=="com.cloudbees.hudson.plugins.folder.Folder")|(str(job.get('_class'))=='org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject'):
return False
else:
return True

def evaluateDate(job_name,lastCompletedBuild,background):
jobUserName=findUser(job_name,lastCompletedBuild)
job_date = datetime.fromtimestamp((server.get_build_info(job_name, lastCompletedBuild['number'])['timestamp'])/1000)
delta_job_date = datetime.now() - job_date
if 180 > delta_job_date.days > 90:
print('[WARN] Last completed build for ' + job_name + ' = 33[1;93m ' + str(job_date.strftime('%Y-%m-%d %H:%M:%S'))+' 33[1;39m')
fillHtml(job_name, str(job_date.strftime('%Y-%m-%d %H:%M:%S')), str(lastCompletedBuild['number']), 'warning', jobUserName, background,_server)
if delta_job_date.days > 180:
print('[WARN] Last completed build for ' + job_name + ' = 33[1;31m ' + str(job_date.strftime('%Y-%m-%d %H:%M:%S'))+' 33[1;39m')
fillHtml(job_name, str(job_date.strftime('%Y-%m-%d %H:%M:%S')), str(lastCompletedBuild['number']), 'error', jobUserName, background,_server)
#server.disable_job(job_name)
if delta_job_date.days < 90:
print('[INFO] Last completed build for ' + job_name + ' = 33[1;32m' + str(job_date.strftime('%Y-%m-%d %H:%M:%S'))+' 33[1;39m')
fillHtml(job_name, str(job_date.strftime('%Y-%m-%d %H:%M:%S')), str(lastCompletedBuild['number']), 'info', jobUserName, background,_server)

# Validate Jenkins connexion
def checkLogin(jk_server):
try:
print('[INFO] Logged in as: '+jk_server.get_whoami()["fullName"])
return True
except jenkins.JenkinsException as e:
print('[ERROR] Failed to log in to Jenkins')
return False

#############################################


buildHtml()
for _server in args.server:
print(f'[INFO] Atempting to login as {args.user} to {_server}')
server = jenkins.Jenkins(_server, username=args.user, password=password, timeout=60)
if (checkLogin(server)):
jobs_never_run=[]
#try:
server = jenkins.Jenkins(_server, username=args.user, password=password, timeout=60)
total_job = server.jobs_count()
jobs = server.get_jobs()
print('Total jobs : ' + str(total_job) + ' on '+_server)

#############################################
user = server.get_whoami()
version = server.get_version()
print('Hello %s from Jenkins %s' % (user['fullName'], version))

print(f'Jobs count: {server.jobs_count()}')

jobs = server.get_jobs()

for i in range(len(jobs)):
#print(f'Job name: {jobs[i]["fullname"]}nJob class: {jobs[i]["_class"]}n')
print(f'Job name: {jobs[i]["fullname"]}')
#try:

job_details = server.get_job_info(jobs[i]["fullname"])
#except jenkins.JenkinsException as e:
#print(f'[ERROR] Could not get job details for {jobs[i]["fullname"]}')
#finally:
print(job_details)
if "lastCompletedBuild" in job_details:
#job_details['lastCompletedBuild']
last_build = job_details['lastCompletedBuild']#['number']
#print(last_build)
try:
last_build_number = last_build['number']
except Exception as e:
last_build_number = None

#build_info = server.get_build_info((jobs[i]["fullname"]), last_build_number)
print(last_build_number)
else:
print("NO DATA")
print("n")
#print(build_info)
#print("###########n")
#############################################
addHtmlTable(_server)
background = 'even'
for job in jobs:
if background == 'even':
background = 'odd'
else:
background = 'even'
job_name = str(job.get('name'))
if findJobClass(job,_server) == True:
try:
print(f'[DEBUG] {job_name}')
lastCompletedBuild = server.get_job_info(job_name)['lastCompletedBuild']
if str(lastCompletedBuild) != 'None':
evaluateDate(job_name,lastCompletedBuild,background)
except jenkins.JenkinsException as e:
print('[ERROR] Cannot parse '+job_name)
else:
jobs_never_run.append(job_name)
fillHtml(job_name,'Never launched', "null", 'error', 'None', background, _server)
print('[WARN] Job(s) never use: ')
for _jobs in jobs_never_run:
print(' '+_jobs)
#except jenkins.NotFoundException as e:
# print('[ERROR] '+_server+' not Found')
#except jenkins.JenkinsException as e:
# print('[ERROR] JE NE SAIS PAS POURQUOI'+str(e))
addHtmlScript()

# GROOVY SCRIPT
#import groovy.json.JsonOutput
#
#def result = ["instance":Jenkins.instance.rootUrl, "latest":null]
#def latest = new Date(0)
#
#Jenkins.instance.getAllItems(Job.class).each{
# def jobBuilds=it.getBuilds()
# // Check the last build only
# if (jobBuilds) {
# jobBuilds[0].each { build ->
# def buildTime = build.time
# println "${it.name} - ${it.class}: ${buildTime}"
# if (latest.before(buildTime)){
# result["latest"] = buildTime
# latest = buildTime
# }
# }
# } else {
# println "${it.name} - ${it.class}: no builds"
# }
# result["latest"] = latest
#}
#
#def output = JsonOutput.toJson(result)
#println(output);
#return output
     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.