Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
@app.route('/systems/edit/', methods=['GET', 'POST'])
@cortex.lib.user.login_required
def system_edit(id):
if not does_user_have_system_permission(id,"view","systems.all.view"):
abort(403)
# Get the system
system = cortex.lib.systems.get_system_by_id(id)
# Ensure that the system actually exists, and return a 404 if it doesn't
if system is None:
abort(404)
if request.method == 'GET' or request.method == 'HEAD':
system_class = cortex.lib.classes.get(system['class'])
system['review_status_text'] = cortex.lib.systems.REVIEW_STATUS_BY_ID[system['review_status']]
if system['puppet_certname']:
system['puppet_node_status'] = cortex.lib.puppet.puppetdb_get_node_status(system['puppet_certname'])
return render_template('systems/edit.html', system=system, system_class=system_class, active='systems', title=system['name'])
elif request.method == 'POST':
try:
# Get a cursor to the database
curd = g.db.cursor(mysql.cursors.DictCursor)
# Extract CMDB ID from form
if does_user_have_system_permission(id,"edit.cmdb","systems.all.edit.cmdb"):
cmdb_id = request.form.get('cmdb_id',None)
if cmdb_id is not None:
cmdb_id = cmdb_id.strip()
def system(id):
# Check user permissions. User must have either systems.all or specific
# access to the system
if not does_user_have_system_permission(id,"view.detail","systems.all.view"):
abort(403)
# Get the system
system = cortex.lib.systems.get_system_by_id(id)
# Ensure that the system actually exists, and return a 404 if it doesn't
if system is None:
abort(404)
system_class = cortex.lib.classes.get(system['class'])
system['review_status_text'] = cortex.lib.systems.REVIEW_STATUS_BY_ID[system['review_status']]
if system['puppet_certname']:
try:
system['puppet_node_status'] = cortex.lib.puppet.puppetdb_get_node_status(system['puppet_certname'])
except Exception:
system['puppet_node_status'] = 'unknown'
# Generate a 'pretty' display name. This is the format ' ()'
system['allocation_who'] = cortex.lib.systems.generate_pretty_display_name(system['allocation_who'], system['allocation_who_realname'])
system['primary_owner_who'] = cortex.lib.systems.generate_pretty_display_name(system['primary_owner_who'], system['primary_owner_who_realname'])
system['secondary_owner_who'] = cortex.lib.systems.generate_pretty_display_name(system['secondary_owner_who'], system['secondary_owner_who_realname'])
return render_template('systems/view.html', system=system, system_class=system_class, active='systems', title=system['name'])
def puppet_catalog(node):
"""Show the Puppet catalog for a given node."""
# Get the system
system = cortex.lib.systems.get_system_by_puppet_certname(node)
if system == None:
abort(404)
## Check if the user is allowed to edit the Puppet configuration
if not does_user_have_system_permission(system['id'],"view.puppet.catalog","systems.all.view.puppet.catalog"):
abort(403)
dbnode = None
catalog = None
try:
# Connect to PuppetDB, get the node information and then it's catalog.
db = cortex.lib.puppet.puppetdb_connect()
dbnode = db.node(node)
catalog = db.catalog(node)
except HTTPError as he:
# Check that the task exists
task = cortex.lib.core.task_get(id)
if task['username'] != session.get('username', None):
if task['username'] is not None:
return stderr("Permission Denied","This task was started by {}. You do not have permission to complete a task you did not start.".format(task['username']),403)
else:
raise RuntimeError("Task (ID: {}) username cannot be None.".format(task['id']))
if task['status'] == 0:
# Still in progress
return redirect(url_for('decom_step_check_wait', id=task['id']))
elif task['status'] == 1 or task['status'] == 3:
# Task complete
system_id, actions, signed_actions = get_system_actions_from_redis(task)
system = cortex.lib.systems.get_system_by_id(system_id)
return workflow.render_template("check_complete.html", actions=actions, system=system, json_data=signed_actions, title="Decommission Node")
else:
# Task failed.
return stderr("Bad Request", "Task (ID: {}) failed. You cannot complete the decommission at this time.", 404)
def system_power(id):
# Check user permissions. User must have either systems.all or specific
# access to the system
if not does_user_have_system_permission(id,"control.vmware.power", "control.all.vmware.power"):
abort(403)
# Get the system
system = cortex.lib.systems.get_system_by_id(id)
# Ensure that the system actually exists, and return a 404 if it doesn't
if system is None:
abort(404)
try:
if request.form.get('power_action', None) == "on":
cortex.lib.systems.power_on(id)
elif request.form.get('power_action', None) == "shutdown":
cortex.lib.systems.shutdown(id)
elif request.form.get('power_action', None) == "off":
cortex.lib.systems.power_off(id)
elif request.form.get('power_action', None) == "reset":
cortex.lib.systems.reset(id)
#is it an XHR?
if request.headers.get('X-Requested-With', None) == "XMLHttpRequest":
return system_status(id)
else:
return redirect(url_for('system_overview', id=id))
except vim.fault.VimFault as e:
abort(500)
if not review_status in cortex.lib.systems.REVIEW_STATUS_BY_ID:
raise ValueError()
# Extract Review Ticket from form
review_task = request.form.get('review_task', None)
if review_task is not None:
review_task = review_task.strip()
if len(review_task) == 0:
review_task = None
else:
if not re.match('^[A-Z]+TASK[0-9]+$', review_task):
raise ValueError()
# If the review status is "Under review" and a task hasn't been specified,
# then we should create one.
if review_status == cortex.lib.systems.REVIEW_STATUS_BY_NAME['REVIEW'] and review_task is None:
# Build some JSON
task_data = {}
task_data['time_constraint'] = 'asap'
task_data['short_description'] = 'Review necessity of virtual machine ' + system['name']
task_data['description'] = 'Please review the necessity of the virtual machine ' + system['name'] + ' to determine whether we need to keep it or whether it can be decommissioned. Information about the VM and links to ServiceNow can be found on Cortex at https://' + app.config['CORTEX_DOMAIN'] + url_for('system', id=id) + "\n\nOnce reviewed, please edit the system in Cortex using the link above and set it's 'Review Status' to either 'Required' or 'Not Required' and then close the associated project task."
#task_data['opened_by'] = app.config['REVIEW_TASK_OPENER_SYS_ID']
task_data['opened_by'] = 'example'
task_data['assignment_group'] = app.config['REVIEW_TASK_TEAM']
task_data['parent'] = app.config['REVIEW_TASK_PARENT_SYS_ID']
# Make a post request to ServiceNow to create the task
r = requests.post('https://' + app.config['SN_HOST'] + '/api/now/v1/table/pm_project_task', auth=(app.config['SN_USER'], app.config['SN_PASS']), headers={'Accept': 'application/json', 'Content-Type': 'application/json'}, json=task_data)
# If we succeeded, get the task number
if r is not None and r.status_code >= 200 and r.status_code <= 299:
response_json = r.json()
key, etc. Clients can authenticate either via username/password, which
is checked against LDAP, or via the VMware virtual machine UUID, which
is checked against the VMware systems cache."""
# Create a corpus (task helper) object
corpus = Corpus(g.db, app.config)
# Clients can send hostname, username and password (interactive installation)
if 'hostname' in request.form and 'username' in request.form and 'password' in request.form:
# Get the hostname and remove the domain portions, if any
# we want the 'short' hostname / the node name
hostname = cortex.lib.core.fqdn_strip_domain(request.form['hostname'])
# Match the hostname to a system record in the database
system = cortex.lib.systems.get_system_by_name(hostname)
if not system:
app.logger.warn('Could not locate host in systems table for register API (hostname: ' + hostname + ')')
abort(404)
# LDAP username/password authentication
if not cortex.lib.user.authenticate(request.form['username'], request.form['password']):
app.logger.warn('Incorrect username/password when registering ' + hostname + ', username: ' + request.form['username'] + ')')
abort(403)
# LDAP authorisation
if not cortex.lib.user.does_user_have_permission('api.register', request.form['username']):
app.logger.warn('User does not have permission when attempting to register ' + hostname + ', username: ' + request.form['username'] + ')')
abort(403)
interactive = True
@app.route('/systems')
@cortex.lib.user.login_required
def systems():
"""Shows the list of known systems to the user."""
# Get the list of systems
systems = cortex.lib.systems.get_systems()
# Get the list of active classes (used to populate the tab bar)
classes = cortex.lib.classes.list(hide_disabled=True)
# Render
return render_template('systems.html', systems=systems, classes=classes, active='systems', title="Systems")
def dsc_classify_machine(id):
#ADD in test to see if the dsc machine is responding
system = cortex.lib.systems.get_system_by_id(id)
if system == None:
abort(404)
curd = g.db.cursor(mysql.cursors.DictCursor)
# get a proxy to connect to dsc
# Setting up cache
# If loading for remote work, set this to true once and then false
roles_info = {}
if False:
dsc_proxy = cortex.lib.dsc.dsc_connect()
roles_info = cortex.lib.dsc.get_roles(dsc_proxy)
with open('/srv/cortex/dsc_cache.txt', 'w+') as f:
def systems_download_csv():
"""Downloads the list of allocated server names as a CSV file."""
# Check user permissions
if not does_user_have_permission("systems.all.view"):
abort(403)
# Get the list of systems
curd = cortex.lib.systems.get_systems(return_cursor=True, hide_inactive=False)
cortex.lib.core.log(__name__, "systems.csv.download", "CSV of systems downloaded")
# Return the response
return Response(cortex.lib.systems.csv_stream(curd), mimetype="text/csv", headers={'Content-Disposition': 'attachment; filename="systems.csv"'})