Example #1
0
def systems_cmdb_json():
	"""Used by DataTables to extract information from the ServiceNow CMDB CI
	cache. The parameters and return format are as dictated by DataTables"""

	# Check user permissions	
	# either they have systems.all.view (view all systems)
	# OR they have at least one instance of the per-system permission 'edit.cmdb' 
	# (cos if they have that they need to be able to list the CMDB entries)
	# or if they have systems.all.edit.cmdb 

	if not does_user_have_permission("systems.all.view") and not does_user_have_permission("systems.all.edit.cmdb"):
		if not does_user_have_any_system_permission("edit.cmdb"):
			abort(403)

	# Extract information from DataTables
	(draw, start, length, order_column, order_asc, search) = _systems_extract_datatables()

	# Validate and convert the ordering column number to the name of the
	# column as it is in the database
	if order_column == 0:
		order_column = 'u_number'
	elif order_column == 1:
		order_column = 'short_description'
	else:
		app.logger.warn('Invalid ordering column parameter in DataTables request')
		abort(400)

	# Get results of query
	total_count    = cortex.lib.cmdb.get_ci_count()
	filtered_count = cortex.lib.cmdb.get_ci_count(search)
	results        = cortex.lib.cmdb.get_cis(start, length, search, order_column, order_asc)

	system_data = []
	for row in results:
		system_data.append([row['u_number'], row['name'], row['sys_id']])

	# Return JSON data in the format DataTables wants
	return jsonify(draw=draw, recordsTotal=total_count, recordsFiltered=filtered_count, data=system_data)
Example #2
0
def systems_cmdb_json():
	"""Used by DataTables to extract information from the ServiceNow CMDB CI
	cache. The parameters and return format are as dictated by DataTables"""

	# Check user permissions	
	# either they have systems.all.view (view all systems)
	# OR they have at least one instance of the per-system permission 'edit.cmdb' 
	# (cos if they have that they need to be able to list the CMDB entries)
	# or if they have systems.all.edit.cmdb 

	if not does_user_have_permission("systems.all.view") and not does_user_have_permission("systems.all.edit.cmdb"):
		if not does_user_have_any_system_permission("edit.cmdb"):
			abort(403)

	# Extract information from DataTables
	(draw, start, length, order_column, order_asc, search) = _systems_extract_datatables()

	# Validate and convert the ordering column number to the name of the
	# column as it is in the database
	if order_column == 0:
		order_column = 'u_number'
	elif order_column == 1:
		order_column = 'short_description'
	else:
		app.logger.warn('Invalid ordering column parameter in DataTables request')
		abort(400)

	# Get results of query
	total_count    = cortex.lib.cmdb.get_ci_count()
	filtered_count = cortex.lib.cmdb.get_ci_count(search)
	results        = cortex.lib.cmdb.get_cis(start, length, search, order_column, order_asc)

	system_data = []
	for row in results:
		system_data.append([row['u_number'], row['name'], row['sys_id']])

	# Return JSON data in the format DataTables wants
	return jsonify(draw=draw, recordsTotal=total_count, recordsFiltered=filtered_count, data=system_data)
Example #3
0
def snapshot_create():

    # Get systems depending on permissions.
    if does_user_have_workflow_permission('systems.all.snapshot'):
        # User can snapshot all systems.
        systems = get_systems(order='id', order_asc=False, virtual_only=True)
    elif does_user_have_any_system_permission('snapshot'):
        # Select all VMs where the user has permission to snapshot
        query_where = (
            """WHERE (`cmdb_id` IS NOT NULL AND `cmdb_operational_status` = "In Service") AND `vmware_uuid` IS NOT NULL AND (`id` IN (SELECT `system_id` FROM `p_system_perms_view` WHERE (`type` = '0' AND `perm` = 'snapshot' AND `who` = %s) OR (`type` = '1' AND `perm` = 'snapshot' AND `who` IN (SELECT `group` FROM `ldap_group_cache` WHERE `username` = %s)))) ORDER BY `id` DESC""",
            (session["username"], session["username"]),
        )
        systems = get_systems(where_clause=query_where)
    else:
        abort(403)

    # Create the values dict.
    values = {}

    if request.method == 'POST':

        values['snapshot_name'] = request.form.get(
            'snapshot_name', 'Snapshot - {}'.format(session['username']))[:80]
        values['snapshot_task'] = request.form.get('snapshot_task', '')
        values['snapshot_expiry'] = request.form.get('snapshot_expiry', None)
        values['snapshot_comments'] = request.form.get('snapshot_comments', '')
        values['snapshot_username'] = session['username']
        values['snapshot_memory'] = 'snapshot_memory' in request.form
        values['snapshot_cold'] = 'snapshot_cold' in request.form

        values['systems'] = list(set(request.form.getlist('systems[]')))
        values['snapshot_systems'] = []

        # Before starting the task check the permissions.
        error = False
        if not does_user_have_workflow_permission('systems.all.snapshot'):
            for system in values['systems']:
                try:
                    vm = next(i for i in systems if i['name'] == system)
                except StopIteration:
                    flash(
                        'You do not have permission to snapshot one or more select VMs. Please try again.',
                        'alert-danger')
                    error = True
                else:
                    values['snapshot_systems'].append(vm)
                    if not does_user_have_system_permission(
                            vm['id'], 'snapshot'):
                        flash(
                            'You do not have permission to snapshot {}, please remove this from the list of systems and try again.'
                            .format(vm['name']), 'alert-danger')
                        error = True

        if error:
            return workflow.render_template('create.html',
                                            title='Create VMware Snapshot',
                                            systems=systems,
                                            values=values)

        # Task Options
        options = {}
        options['wfconfig'] = workflow.config
        options['values'] = values

        # Everything should be good - start a task.
        neocortex = cortex.lib.core.neocortex_connect()
        task_id = neocortex.create_task(__name__,
                                        session['username'],
                                        options,
                                        description='Create a VMware Snapshot')

        # Redirect to the status page for the task
        return redirect(url_for('task_status', task_id=task_id))

    if 'systems' in request.args:
        values['snapshot_systems'] = []
        for system in request.args['systems'].strip(',').split(','):
            try:
                vm = next(i for i in systems if i['id'] == int(system))
            except StopIteration:
                pass  # System not in Systems List (Likely not a VM then).
            except ValueError:
                pass  # System was not an int.
            else:
                values['snapshot_systems'].append(vm)

    return workflow.render_template('create.html',
                                    title='Create VMware Snapshot',
                                    systems=systems,
                                    values=values)
Example #4
0
def snapshot_create_permission_callback():
    return does_user_have_workflow_permission(
        'systems.all.snapshot') or does_user_have_any_system_permission(
            'snapshot')
Example #5
0
def systems_vmware_json():
	"""Used by DataTables to extract infromation from the VMware cache. The
	parameters and return format are dictated by DataTables"""

	# Check user permissions	
	# either they have systems.all.view (view all systems)
	# OR they have at least one instance of the per-system permission 'edit.vmware' 
	# (cos if they have that they need to be able to list the VMWare UUIDs)
	# or if they have systems.all.edit.vmware 

	if not does_user_have_permission("systems.all.view") and not does_user_have_permission("systems.all.edit.vmware"):
		if not does_user_have_any_system_permission("edit.vmware"):
			abort(403)

	# Extract information from DataTables
	(draw, start, length, order_column, order_asc, search) = _systems_extract_datatables()

	# Validate and extract ordering direction. 'asc' for ascending, 'desc' for
	# descending.
	if order_asc:
		order_dir = "ASC"
	else:
		order_dir = "DESC"

	# Validate and convert the ordering column number to the name of the
	# column as it is in the database
	if order_column == 0:
		order_column = 'name'
	elif order_column == 1:
		order_column = 'uuid'
	else:
		app.logger.warn('Invalid ordering column parameter in DataTables request')
		abort(400)

	# Query the database
	curd = g.db.cursor(mysql.cursors.DictCursor)

	# Get total number of VMs in cache
	curd.execute('SELECT COUNT(*) AS `count` FROM `vmware_cache_vm`;')
	total_count = curd.fetchone()['count']

	# Get total number of VMs that match query
	if search is not None:
		curd.execute('SELECT COUNT(*) AS `count` FROM `vmware_cache_vm` WHERE `name` LIKE %s', ("%" + search + "%",))
		filtered_count = curd.fetchone()['count']
	else:
		# If unfiltered, return the total count
		filtered_count = total_count

	# Build query	
	query = 'SELECT `name`, `uuid` FROM `vmware_cache_vm` '
	query_params = ()
	if search is not None:
		query = query + 'WHERE `name` LIKE %s '
		query_params = ("%" + search + "%",)

	# Add on ordering
	query = query + "ORDER BY " + order_column + " " + order_dir + " "

	# Add on query limits
	query = query + "LIMIT " + str(start)
	if length is not None:
		query = query + "," + str(length)
	else:
		query = query + ",18446744073709551610"

	# Perform the query
	curd.execute(query, query_params)

	# Turn the results in to an appropriately shaped arrau
	row = curd.fetchone()
	system_data = []
	while row is not None:
		system_data.append([row['name'], row['uuid']])
		row = curd.fetchone()

	# Return JSON data in the format DataTables wants
	return jsonify(draw=draw, recordsTotal=total_count, recordsFiltered=filtered_count, data=system_data)
Example #6
0
def adddisk_add():

	selected_system = None
	systems = None
	if request.method == "GET" and "system" in request.args and request.args["system"].strip():
		try:
			selected_system = get_system_by_id(int(request.args["system"].strip()))
		except ValueError:
			pass # System was not an int.
		else:
			# Ensure the system is actually a VM
			selected_system = selected_system if selected_system["vmware_uuid"] else None

		# Check permissions on this system
		if not does_user_have_system_permission(selected_system["id"], "adddisk") and not does_user_have_workflow_permission("systems.all.adddisk"):
			abort(403)

	# If a system was not selected, get all systems
	if not selected_system:
		# Get systems depending on permissions.
		if does_user_have_workflow_permission("systems.all.adddisk"):
			# User can add disks to all systems.
			systems = get_systems(order='id', order_asc=False, virtual_only=True)
		elif does_user_have_any_system_permission("adddisk"):
			# Select all VMs where the user has permission to add disks
			query_where = (
				"""WHERE (`cmdb_id` IS NOT NULL AND `cmdb_operational_status` = "In Service") AND `vmware_uuid` IS NOT NULL AND (`id` IN (SELECT `system_id` FROM `system_perms_view` WHERE (`type` = '0' AND `perm` = 'adddisk' AND `who` = %s) OR (`type` = '1' AND `perm` = 'adddisk' AND `who` IN (SELECT `group` FROM `ldap_group_cache` WHERE `username` = %s)))) ORDER BY `id` DESC""",
				(session["username"], session["username"]),
			)
			systems = get_systems(where_clause=query_where)
		else:
			abort(403)

	if request.method == "POST":
		# Get the values
		values = {k: request.form.get(k) if k in request.form else abort(400) for k in ["adddisk_task", "adddisk_size", "adddisk_system_id"]}
		values["adddisk_task"] = values["adddisk_task"] if values["adddisk_task"] else "unknown"

		try:
			values["adddisk_size"] = int(values["adddisk_size"])
		except ValueError:
			abort(400)

		if not MIN_DISK_SIZE <= values["adddisk_size"] <= MAX_DISK_SIZE:
			flash("Invalid disk size! Please choose a size between {} and {} GiB".format(MIN_DISK_SIZE, MAX_DISK_SIZE))
		else:

			# Check permissions before starting task
			if not does_user_have_system_permission(values["adddisk_system_id"], "adddisk") and not does_user_have_workflow_permission("systems.all.adddisk"):
				abort(403)

			# Task Options
			options = {}
			options["wfconfig"] = workflow.config
			options["values"] = values

			# Everything should be good - start a task.
			neocortex = cortex.lib.core.neocortex_connect()
			task_id = neocortex.create_task(__name__, session["username"], options, description="Add VMware disk")

			# Log the Task ID
			cortex.lib.core.log(__name__, "workflow.adddisk.add", "Add disk task {} started by {} with ServiceNow task {}".format(task_id, session["username"], values["adddisk_task"]))

			# Redirect to the status page for the task
			return redirect(url_for("task_status", task_id=task_id))

	return workflow.render_template("add.html", title="Add VMware Disk", selected_system=selected_system, systems=systems)
Example #7
0
def adddisk_create_permission_callback():
	return does_user_have_workflow_permission("systems.all.adddisk") or does_user_have_any_system_permission("adddisk")
Example #8
0
def systems_vmware_json():
	"""Used by DataTables to extract infromation from the VMware cache. The
	parameters and return format are dictated by DataTables"""

	# Check user permissions	
	# either they have systems.all.view (view all systems)
	# OR they have at least one instance of the per-system permission 'edit.vmware' 
	# (cos if they have that they need to be able to list the VMWare UUIDs)
	# or if they have systems.all.edit.vmware 

	if not does_user_have_permission("systems.all.view") and not does_user_have_permission("systems.all.edit.vmware"):
		if not does_user_have_any_system_permission("edit.vmware"):
			abort(403)

	# Extract information from DataTables
	(draw, start, length, order_column, order_asc, search) = _systems_extract_datatables()

	# Validate and extract ordering direction. 'asc' for ascending, 'desc' for
	# descending.
	if order_asc:
		order_dir = "ASC"
	else:
		order_dir = "DESC"

	# Validate and convert the ordering column number to the name of the
	# column as it is in the database
	if order_column == 0:
		order_column = 'name'
	elif order_column == 1:
		order_column = 'uuid'
	else:
		app.logger.warn('Invalid ordering column parameter in DataTables request')
		abort(400)

	# Query the database
	curd = g.db.cursor(mysql.cursors.DictCursor)

	# Get total number of VMs in cache
	curd.execute('SELECT COUNT(*) AS `count` FROM `vmware_cache_vm`;')
	total_count = curd.fetchone()['count']

	# Get total number of VMs that match query
	if search is not None:
		curd.execute('SELECT COUNT(*) AS `count` FROM `vmware_cache_vm` WHERE `name` LIKE %s', ("%" + search + "%"))
		filtered_count = curd.fetchone()['count']
	else:
		# If unfiltered, return the total count
		filtered_count = total_count

	# Build query	
	query = 'SELECT `name`, `uuid` FROM `vmware_cache_vm` '
	query_params = ()
	if search is not None:
		query = query + 'WHERE `name` LIKE %s '
		query_params = ("%" + search + "%")

	# Add on ordering
	query = query + "ORDER BY " + order_column + " " + order_dir + " "

	# Add on query limits
	query = query + "LIMIT " + str(start)
	if length is not None:
		query = query + "," + str(length)
	else:
		query = query + ",18446744073709551610"

	# Perform the query
	curd.execute(query, query_params)

	# Turn the results in to an appropriately shaped arrau
	row = curd.fetchone()
	system_data = []
	while row is not None:
		system_data.append([row['name'], row['uuid']])
		row = curd.fetchone()

	# Return JSON data in the format DataTables wants
	return jsonify(draw=draw, recordsTotal=total_count, recordsFiltered=filtered_count, data=system_data)
Example #9
0
def snapshot_create():
    # Don't go any further if workflows are currently locked
    raise_if_workflows_locked()

    # Get systems depending on permissions.
    if does_user_have_workflow_permission('systems.all.snapshot'):
        # User can snapshot all systems.
        systems = get_systems(order='id', order_asc=False, virtual_only=True)
    elif does_user_have_any_system_permission('snapshot'):
        # User can only snapshot certain systems.
        systems = get_systems(order='id',
                              order_asc=False,
                              virtual_only=True,
                              show_allocated_and_perms=True,
                              only_allocated_by=session['username'])
    else:
        abort(403)

    # Create the values dict.
    values = {}

    if request.method == 'GET':
        if 'systems' in request.args:
            values['snapshot_systems'] = []
            for system in request.args['systems'].strip(',').split(','):
                try:
                    vm = next(i for i in systems if i['id'] == int(system))
                except StopIteration:
                    pass  # System not in Systems List (Likely not a VM then).
                except ValueError:
                    pass  # System was not an int.
                else:
                    values['snapshot_systems'].append(vm)

        return workflow.render_template('create.html',
                                        systems=systems,
                                        values=values)

    elif request.method == 'POST':

        values['snapshot_name'] = request.form.get('snapshot_name', '')
        values['snapshot_task'] = request.form.get('snapshot_task', '')
        values['snapshot_expiry'] = request.form.get('snapshot_expiry', None)
        values['snapshot_comments'] = request.form.get('snapshot_comments', '')
        values['snapshot_username'] = session['username']
        values['snapshot_memory'] = 'snapshot_memory' in request.form
        values['snapshot_cold'] = 'snapshot_cold' in request.form

        values['systems'] = list(set(request.form.getlist('systems[]')))
        values['snapshot_systems'] = []

        # Before starting the task check the permissions.
        error = False
        if not does_user_have_workflow_permission('systems.all.snapshot'):
            for system in values['systems']:
                try:
                    vm = next(i for i in systems if i['name'] == system)
                except StopIteration:
                    flash(
                        'You do not have permission to snapshot one or more select VMs. Please try again.',
                        'alert-danger')
                    error = True
                else:
                    values['snapshot_systems'].append(vm)
                    if not does_user_have_system_permission(
                            vm['id'], 'snapshot'):
                        flash(
                            'You do not have permission to snapshot {}, please remove this from the list of systems and try again.'
                            .format(vm['name']), 'alert-danger')
                        error = True

        if error:
            return workflow.render_template('create.html',
                                            systems=systems,
                                            values=values)

        # Task Options
        options = {}
        options['wfconfig'] = workflow.config
        options['values'] = values

        # Everything should be good - start a task.
        neocortex = cortex.lib.core.neocortex_connect()
        task_id = neocortex.create_task(__name__,
                                        session['username'],
                                        options,
                                        description='Create a VMware Snapshot')

        # Redirect to the status page for the task
        return redirect(url_for('task_status', id=task_id))