def update_ssh_dir_permissions(user='******'): try: # /bin/su -s /bin/bash -c \"%s\" %s uid = pwd.getpwnam(user).pw_uid gid = grp.getgrnam("integralstor").gr_gid path = _get_ssh_dir(user) os.chown(path, uid, gid) ssh_perm = "/bin/su -s /bin/bash -c 'chmod 700 %s' %s" % (path, user) (ret, rc), err = command.execute_with_rc(ssh_perm, True) if err: raise Exception(err) path = _get_authorized_file(user) if not os.path.isfile(path): with open(path, 'w') as f: f.close() os.chown(path, uid, gid) authorized_key = "/bin/su -s /bin/bash -c 'chmod 640 %s' %s" % ( path, user) (ret, rc), err = command.execute_with_rc(authorized_key, True) if err: raise Exception(err) path = _get_known_hosts(user) if not os.path.isfile(path): with open(path, 'w') as f: f.close() if os.path.isfile(path): os.chown(path, uid, gid) return True, None except Exception, e: return False, "Error updating ssh dir permissions: %s" % str(e)
def reboot_or_shutdown(request): return_dict = {} audit_str = "" try: minutes_to_wait = 1 return_dict['minutes_to_wait'] = minutes_to_wait ret, err = django_utils.get_request_parameter_values(request, ['do']) if err: raise Exception(err) if 'do' not in ret: raise Exception("Invalid request, please use the menus.") do = ret['do'] return_dict['do'] = do if request.method == "GET": return django.shortcuts.render_to_response("reboot_or_shutdown.html", return_dict, context_instance=django.template.context.RequestContext(request)) else: if 'conf' not in request.POST: raise Exception('Unknown action. Please use the menus') audit.audit('reboot_shutdown', 'System %s initiated' % do, request) if do == 'reboot': command.execute_with_rc('shutdown -r +%d' % minutes_to_wait) elif do == 'shutdown': command.execute_with_rc('shutdown -h +%d' % minutes_to_wait) return django.shortcuts.render_to_response("reboot_or_shutdown_conf.html", return_dict, context_instance=django.template.context.RequestContext(request)) except Exception, e: return_dict['base_template'] = "system_base.html" return_dict["page_title"] = 'Reboot or Shutdown Failure' return_dict['tab'] = 'reboot_tab' return_dict["error"] = 'Error Rebooting' return_dict["error_details"] = str(e) return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance=django.template.context.RequestContext(request))
def add_acl(target_name, acl): try: if not target_name: raise Exception('No Target Specified') if not acl: raise Exception('No ACL specified') target, err = get_target(target_name) if err: raise Exception(err) if not target: raise Exception('Specified target not found') acls = target['acl'] # First remove ALL from the ACL list if acls and 'ALL' in acls: cmd = 'tgtadm --lld iscsi --mode target --op unbind --tid %d -I ALL' % target['tid'] (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception('Error removind wildcard ACL : %s' % err) cmd = 'tgtadm --lld iscsi --mode target --op bind --tid %d -I %s' % ( target['tid'], acl) (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception(err) conf, err = generate_targets_conf() if err: raise Exception(err) except Exception, e: return False, 'Error adding ACL: %s' % str(e)
def remove_acl(target_name, acl): try: if not target_name: raise Exception('No Target Specified') if not acl: raise Exception('No ACL specified') target, err = get_target(target_name) if err: raise Exception(err) if not target: raise Exception('Specified target not found') acls = target['acl'] if not acls: raise Exception('No ACLs found') if acl not in acls: raise Exception('Specified ACL not found') cmd = 'tgtadm --lld iscsi --mode target --op unbind --tid %d -I %s' % ( target['tid'], acl) (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception(err) if rc != 0: # Could be an initiator name so try this.. cmd = 'tgtadm --lld iscsi --mode target --op unbind --tid %d --initiator-name %s' % ( target['tid'], acl) ret, rc = command.execute_with_rc(cmd) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception(err) conf, err = generate_targets_conf() if err: raise Exception(err) except Exception, e: return False, 'Error removing ACL: %s' % str(e)
def create_target(name): try: targets, err = get_targets() if err: raise Exception(err) highest_tid = 0 if targets: for t in targets: if int(t['tid']) > highest_tid: highest_tid = int(t['tid']) new_tid = highest_tid + 1 target_name = 'com.fractalio.integralstor:%s' % name cmd = 'tgtadm --lld iscsi --mode target --op new --tid %d -T %s' % ( new_tid, target_name) (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception(err) conf, err = generate_targets_conf() if err: raise Exception(err) except Exception, e: return False, 'Error creating target : %s' % str(e)
def get_service_status(service): d = {} try: (ret, rc), err = command.execute_with_rc( 'service %s status' % service[0]) if err: raise Exception(err) d['status_code'] = rc if rc == 0: d['status_str'] = 'Running' elif rc == 3: d['status_str'] = 'Stopped' elif rc == 1: d['status_str'] = 'Error' d['output_str'] = '' out, err = command.get_output_list(ret) if err: raise Exception(err) if out: d['output_str'] += ','.join(out) err, e = command.get_error_list(ret) if e: raise Exception(e) if err: d['output_str'] += ','.join(err) except Exception, e: return None, 'Error retrieving service status : %s' % str(e)
def get_all_disks_by_name(): """Get all disks by their sd* names Returns a list of all disks by name (sda/sbd, etc) in the sytem """ dl = [] try: cmd_dl = "/usr/sbin/smartctl --scan" (ret, rc), err = command.execute_with_rc(cmd_dl) if err: raise Exception(err) disk_list, err = command.get_output_list(ret) if err: raise Exception(err) if ret: # Regex to capture "/dev/sdX" reg_exp_dl = re.compile("(/dev/[a-z]+)") for line in disk_list: d = {} if reg_exp_dl.search(line): result_dl = re.search(r'/dev/sd[a-z]+', line) result_dl1 = re.search(r'/dev/(sd[a-z]+)', line) if result_dl: d["full_path"] = result_dl.group() dname = result_dl1.groups()[0] r = re.match('^sd[a-z]+', dname) d["name"] = r.group() dl.append(d) # print "disk list info: ", dl except Exception, e: return None, "Error retrieving disks by name : %s" % str(e)
def delete_target(name): try: target, err = get_target(name) if err: raise Exception(err) if not target: raise Exception('Specified target not found') cmd = 'tgtadm --lld iscsi --mode target --op delete --tid %d' % target['tid'] (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception(err) conf, err = generate_targets_conf() if err: raise Exception(err) except Exception, e: return False, 'Error deleting target : %s' % str(e)
def delete_target(name): try: target, err = get_target(name) if err: raise Exception(err) if not target: raise Exception('Specified target not found') cmd = 'tgtadm --lld iscsi --mode target --op delete --tid %d' % target[ 'tid'] (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception(err) conf, err = generate_targets_conf() if err: raise Exception(err) except Exception, e: return False, 'Error deleting target : %s' % str(e)
def generate_ssh_key(user='******'): try: cmd = "ssh-keygen -t rsa -f %s -N ''" % ( _get_ssh_dir(user) + "/id_rsa") runuser = "******"%s\" %s " % (cmd, user) (ret, rc), err = command.execute_with_rc(runuser, True) if err: raise Exception(err) return True, None except Exception, e: return None, "Error while generating ssh file for user: %s. Error : %s" % (user, str(e))
def delete_lun(target_name, backing_store): try: if not target_name: raise ('No target name specified') if not backing_store: raise ('No backing store path specified') target, err = get_target(target_name) if err: raise Exception(err) if not target: raise Exception('Specified target not found.') luns = target['luns'] if not luns: raise Exception('Specified target does not have any LUNs.') lun = None for tl in luns: if tl['path'] == backing_store: lun = tl if not lun: raise Exception('Specified LUN not found.') cmd = 'tgtadm --lld iscsi --mode logicalunit --op delete --tid %d --lun %d' % ( target['tid'], lun['id']) (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception(err) conf, err = generate_targets_conf() if err: raise Exception(err) except Exception, e: return False, 'Error Deleting Logical Unit: %s' % str(e)
def create_lun(target_name, backing_store): try: if not target_name: raise Exception('No Target Specified') if not backing_store: raise Exception('No backing storage volume specified') target, err = get_target(target_name) if err: raise Exception(err) if not target: raise Exception('Specified target not found') luns = target['luns'] if not luns: raise Exception('Error retrieving LUN list') highest_lun_id = 0 for lun in luns: if lun['id'] > highest_lun_id: highest_lun_id = lun['id'] new_lun_id = highest_lun_id + 1 cmd = 'tgtadm --lld iscsi --mode logicalunit --op new --tid %d --lun %d --backing-store %s' % ( int(target['tid']), new_lun_id, backing_store) (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception(err) conf, err = generate_targets_conf() if err: raise Exception(err) except Exception, e: return False, 'Error creating LUN : %s' % str(e)
def delete_ramdisk(path, pool): try: if not path: raise Exception('No RAMDisk path specified') res, err = delete_from_ramdisks_config(pool, path) if err: raise Exception(err) if not res: raise Exception("Error removing ramdisk info from the conf file") cmd = 'umount %s' % path lines, err = command.get_command_output(cmd) if err: raise Exception('Error creating ramdisk : %s' % err) (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception('Error unmounting ramdisk : %s' % err) except Exception, e: return False, 'Error destroying ramdisk : %s' % str(e)
def remove_user_authentication(target_name, username, authentication_type): try: if not target_name: raise "Target Not Specified" if not username: raise "Username Not Specified" target, err = get_target(target_name) if err: raise Exception(err) if not target: raise Exception('Specified target not found.') cmd = 'tgtadm --lld iscsi --mode account --op unbind --tid %d --user %s' % ( target['tid'], username) if authentication_type == 'outgoing': cmd += ' --outgoing' (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception(err) conf, err = generate_targets_conf() if err: raise Exception(err) except Exception, e: return False, 'Error removing user autentication: %s' % str(e)
def configure_interface(): try: os.system('clear') interfaces, err = networking.get_interfaces() if err: raise Exception( 'Error retrieving interface information : %s' % err) if not interfaces: raise Exception('No interfaces detected') print print print 'IntegralSTOR interface configuration' print '--------------------------------------------' print print print 'Current network interfaces : ' print for if_name, iface in interfaces.items(): if if_name.startswith('lo'): continue print '- %s' % if_name print valid_input = False while not valid_input: ifname = raw_input( 'Enter the name of the interface that you wish to configure : ') if ifname not in interfaces or ifname.startswith('lo'): print 'Invalid interface name' else: valid_input = True print ip_info, err = networking.get_ip_info(ifname) ''' if err: raise Exception('Error retrieving interface information : %s'%err) ''' if ip_info: ip = ip_info["ipaddr"] netmask = ip_info["netmask"] if "default_gateway" in ip_info: gateway = ip_info["default_gateway"] else: gateway = None else: ip = None netmask = None gateway = None old_boot_proto, err = networking.get_interface_bootproto(ifname) if err: # raise Exception( # 'Error retrieving interface information : %s' % err) old_boot_proto = '' config_changed = False str_to_print = "Configure for DHCP or static addressing (dhcp/static)? : " valid_input = False while not valid_input: input = raw_input(str_to_print) if input: if input.lower() in ['static', 'dhcp']: valid_input = True boot_proto = input.lower() if boot_proto != old_boot_proto: config_changed = True if not valid_input: print "Invalid value. Please try again." print if boot_proto == 'static': if ip: str_to_print = "Enter IP address (currently %s, press enter to retain current value) : " % ip else: str_to_print = "Enter IP address (currently not set) : " valid_input = False while not valid_input: input = raw_input(str_to_print) if input: ok, err = networking.validate_ip(input) if err: raise Exception('Error validating IP : %s' % err) if ok: valid_input = True ip = input config_changed = True elif ip: valid_input = True if not valid_input: print "Invalid value. Please try again." print if netmask: str_to_print = "Enter netmask (currently %s, press enter to retain current value) : " % netmask else: str_to_print = "Enter netmask (currently not set) : " valid_input = False while not valid_input: input = raw_input(str_to_print) if input: ok, err = networking.validate_netmask(input) if err: raise Exception('Error validating netmask : %s' % err) if ok: valid_input = True netmask = input config_changed = True elif netmask: valid_input = True if not valid_input: print "Invalid value. Please try again." print if gateway: str_to_print = "Enter gateway (currently %s, press enter to retain current value) : " % gateway else: str_to_print = "Enter gateway (currently not set) : " valid_input = False while not valid_input: input = raw_input(str_to_print) if input: ok, err = networking.validate_ip(input) if err: raise Exception('Error validating gateway : %s' % err) if ok: valid_input = True gateway = input config_changed = True elif gateway: valid_input = True if not valid_input: print "Invalid value. Please try again." print if config_changed: d = {} d['addr_type'] = boot_proto if boot_proto == 'static': d['ip'] = ip d['netmask'] = netmask d['default_gateway'] = gateway ret, err = networking.update_interface_ip(ifname, d) if not ret: if err: raise Exception( 'Error changing interface address : %s' % err) else: raise Exception('Error changing interface address') restart = False print print valid_input = False while not valid_input: str_to_print = 'Restart network services now (y/n) :' print input = raw_input(str_to_print) if input: if input.lower() in ['y', 'n']: valid_input = True if input.lower() == 'y': restart = True if not valid_input: print "Invalid value. Please try again." print if restart: ret, err = networking.restart_networking() if not ret: if err: raise Exception(err) else: raise Exception("Couldn't restart.") use_salt, err = config.use_salt() if err: raise Exception(err) if use_salt: (r, rc), err = command.execute_with_rc( 'service salt-minion restart') if err: raise Exception(err) if rc == 0: print "Salt minion service restarted succesfully." else: print "Error restarting salt minion services." raw_input('Press enter to return to the main menu') return -1 else: print print raw_input( 'No changes have been made to the configurations. Press enter to return to the main menu.') return 0 except Exception, e: print "Error configuring network settings : %s" % e return -1
def generate_targets_conf(new_user=None): try: targets, err = get_targets() if err: raise Exception(err) config_targets, err = load_targets_conf() if err: raise Exception(err) with open('/tmp/targets.conf', 'w') as f: f.write('default-driver iscsi\n') for target in targets: f.write('\n<target %s>\n' % target['iqn']) for lun in target['luns']: if lun['path'] and lun['path'] != 'None': f.write(' backing-store %s\n' % lun['path']) for acl in target['acl']: if acl != 'ALL': f.write(' initiator-address %s\n' % acl) config_target = None # First process new users if any if new_user and new_user['iqn'] == target['iqn']: if new_user['type'] == 'incoming': f.write(' incominguser %s %s\n' % (new_user['username'], new_user['pswd'])) else: f.write(' outgoinguser %s %s\n' % (new_user['username'], new_user['pswd'])) for account in target['accounts']: # Now process existing users. Take the list from tgtadm, # get pswds from existing config file and write it out # again for ct in config_targets: if ct['iqn'] == target['iqn']: config_target = ct break if account['type'] == 'incoming': for ctiu in config_target['incoming_users']: if ctiu['username'] == account['user']: f.write(' incominguser %s %s\n' % (account['user'], ctiu['pswd'])) else: for ctiu in config_target['outgoing_users']: if ctiu['username'] == account['user']: f.write(' outgoinguser %s %s\n' % (account['user'], ctiu['pswd'])) f.write('</target>\n\n') f.flush() f.close() shutil.move('/tmp/targets.conf', '/etc/tgt/targets.conf') cmd = 'tgt-admin -e' (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception(err) except Exception, e: return False, 'Error generating ISCSI config file: %s' % str(e)
def get_sysd_service_status(service): d = {} d['status'] = {} d['status']['rc'] = '' d['status']['status_str'] = '' d['status']['output_str'] = '' d['is_active'] = {} d['is_active']['rc'] = '' d['is_active']['status_str'] = '' d['is_active']['output_str'] = '' d['is_failed'] = {} d['is_failed']['rc'] = '' d['is_failed']['status_str'] = '' d['is_failed']['output_str'] = '' d['is_enabled'] = {} d['is_enabled']['rc'] = '' d['is_enabled']['status_str'] = '' d['is_enabled']['output_str'] = '' try: (ret, rc), err = command.execute_with_rc( 'systemctl status %s' % service[0]) if err: raise Exception(err) d['status']['rc'] = rc out, err1 = command.get_output_list(ret) if err1: raise Exception(err1) if out: d['status']['output_str'] += ','.join(out) err2, e = command.get_error_list(ret) if e: raise Exception(e) if err2: d['status']['output_str'] += ','.join(err2) if not err: (ret, rc), err = command.execute_with_rc( 'systemctl is-failed %s' % service[0]) if err: raise Exception(err) d['is_failed']['rc'] = rc out, err = command.get_output_list(ret) if err: raise Exception(err) if out: d['is_failed']['output_str'] += ','.join(out) if rc == 0: d['is_failed']['status_str'] = "Failed" d['status']['status_str'] = "Failed" d['status']['output_str'] += ','.join(out) else: (ret, rc), err = command.execute_with_rc( 'systemctl is-active %s' % service[0]) if err: raise Exception(err) d['is_active']['rc'] = rc out, err = command.get_output_list(ret) if err: raise Exception(err) if out: d['is_active']['output_str'] += ','.join(out) if rc == 0: d['is_active']['status_str'] = "Active" d['status']['status_str'] = "Active" d['status']['output_str'] += ','.join(out) elif rc == 3: d['is_active']['status_str'] = "Inactive" d['status']['status_str'] = "Inactive" d['status']['output_str'] += ','.join(out) else: d['status']['status_str'] = "Unknown State" (ret, rc), err = command.execute_with_rc( 'systemctl is-enabled %s' % service[0]) if err: raise Exception(err) d['is_enabled']['rc'] = rc out, err = command.get_output_list(ret) if err: raise Exception(err) if out: d['is_enabled']['output_str'] += ','.join(out) if not rc: d['is_enabled']['status_str'] = "Enabled" else: d['is_enabled']['status_str'] = "Disabled" except Exception, e: return None, 'Error retrieving service status : %s' % str(e)
def run_task(task_id): try: task, err = get_task(task_id) if err: raise Exception(err) now, err = datetime_utils.get_epoch(when='now') if err: raise Exception(err) db_path, err = config.get_db_path() if err: raise Exception(err) if task['last_run_time']: seconds_since_last_run = (now - task['last_run_time']) # retry_interval is in minutes! if seconds_since_last_run < task['retry_interval'] * 60: raise Exception("Too young to attempt") # Mark the task as running cmd = "update tasks set status = 'running', last_run_time=%d where task_id = '%d'" % ( now, task['task_id']) status, err = db.execute_iud(db_path, [ [cmd], ], get_rowid=True) if err: raise Exception(err) audit_str = "%s" % task['description'] audit.audit("task_start", audit_str, None, system_initiated=True) attempts = task['attempts'] run_as_user_name = task['run_as_user_name'] # Now process subtasks for the task subtasks_query = "select * from subtasks where task_id == '%d' and (status == 'error-retrying' or status == 'queued') order by subtask_id" % task[ 'task_id'] subtasks, err = db.get_multiple_rows(db_path, subtasks_query) if err: raise Exception(err) # Assume task is complete unless proven otherwise task_completed = True # Iteriate through all the unfinished subtasks related to the # task for subtask in subtasks: subtask_id = subtask["subtask_id"] status_update = "update subtasks set status = 'running' where subtask_id = '%d' and status is not 'cancelled'" % subtask_id status, err = db.execute_iud(db_path, [ [status_update], ], get_rowid=True) if err: task_completed = False break # Now actually execute the command # This task is not meant to be executed by the current user # so switch to that user (out, return_code), err = command.execute_with_rc( subtask["command"], shell=True, run_as_user_name=run_as_user_name) if out[0]: output = re.sub("'", "", ''.join(out[0])) else: output = None if out[1]: error = re.sub("'", "", ''.join(out[1])) else: error = None if return_code == 0: # This means the command was successful. So update to # completed status_update = "update subtasks set status = 'completed', return_code='%d' where subtask_id = '%d' and status is not 'cancelled';" % ( return_code, subtask_id) status, err = db.execute_iud(db_path, [ [status_update], ], get_rowid=True) if err: task_completed = False break else: continue else: # Subtask command failed if attempts > 1 or attempts == -2: status_update = 'update subtasks set status = "error-retrying", return_code="%d" where subtask_id = "%d" and status is not "cancelled";' % ( return_code, subtask_id) elif attempts in [0, 1]: status_update = 'update subtasks set status = "failed", return_code="%d" where subtask_id = "%d" and status is not "cancelled";' % ( return_code, subtask_id) execute, err = db.execute_iud(db_path, [ [status_update], ], get_rowid=True) task_completed = False break # Capture end time end_time, err = datetime_utils.get_epoch(when='now') if err: raise Exception(err) # Update status if task_completed: status_update = "update tasks set status = 'completed' where task_id = '%d'" % task[ 'task_id'] else: if attempts > 1: status_update = "update tasks set status = 'error-retrying', attempts = %d where task_id = '%d' and status is not 'cancelled'" % ( attempts - 1, task['task_id']) elif attempts == -2: status_update = "update tasks set status = 'error-retrying', attempts = %d where task_id = '%d' and status is not 'cancelled'" % ( -2, task['task_id']) else: status_update = "update tasks set status = 'failed', attempts = '%d' where task_id = '%d' and status is not 'cancelled'" % ( 0, task['task_id']) status, err = db.execute_iud(db_path, [ [status_update], ], get_rowid=True) if err: raise Exception(err) # Update task's end time end_time_update = "update tasks set end_time=%d where task_id = '%d'" % ( end_time, task['task_id']) ret, err = db.execute_iud(db_path, [ [end_time_update], ], get_rowid=True) if err: pass # raise Exception(err) if task_completed: audit.audit("task_complete", audit_str, None, system_initiated=True) else: audit.audit("task_fail", audit_str, None, system_initiated=True) except Exception as e: return False, 'Error processing task: %s' % e else: return True, None
def add_user_authentication(target_name, authentication_type, username, password): try: tid = -1 if not authentication_type: raise Exception('No authentication type specified') if not target_name: raise Exception('No target specified') if not username: raise Exception('No username specified') if not password: raise Exception('No password specified') target, err = get_target(target_name) if err: raise Exception(err) if not target: raise Exception('Specified target not found.') cmd1 = 'tgtadm --lld iscsi --mode account --op new --user %s --password %s' % ( username, password) (ret, rc), err = command.execute_with_rc(cmd1) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception(err) cmd2 = 'tgtadm --lld iscsi --mode account --op bind --tid %d --user %s' % ( target['tid'], username) if authentication_type == 'outgoing': cmd2 += ' --outgoing' (ret, rc), err = command.execute_with_rc(cmd2) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception(err) new_user_dict = {} new_user_dict['iqn'] = target['iqn'] new_user_dict['username'] = username new_user_dict['type'] = authentication_type new_user_dict['pswd'] = password conf, err = generate_targets_conf(new_user_dict) if err: raise Exception(err) except Exception, e: return False, 'Error Adding User: %s' % str(e)
def display_status(): try: hostname = socket.gethostname() use_salt, err = config.use_salt() if err: raise Exception(err) if use_salt: print "Salt master service status :", (r, rc), err = command.execute_with_rc( 'service salt-master status') if err: raise Exception(err) l, err = command.get_output_list(r) if err: raise Exception(err) if l: print '\n'.join(l) else: l, err = command.get_error_list(r) if err: raise Exception(err) if l: print '\n'.join(l) print "Salt minion service status :", (r, rc), err = command.execute_with_rc( 'service salt-minion status') if err: raise Exception(err) l, err = command.get_output_list(r) if err: raise Exception(err) if l: print '\n'.join(l) else: l, err = command.get_error_list(r) if err: raise Exception(err) print l if l: print '\n'.join(l) print "Samba service status :", (r, rc), err = command.execute_with_rc('service smb status') if err: raise Exception(err) l, err = command.get_output_list(r) if err: raise Exception(err) if l: print '\n'.join(l) else: l, err = command.get_error_list(r) if err: raise Exception(err) if l: print '\n'.join(l) print "Winbind service status :", (r, rc), err = command.execute_with_rc('service winbind status') if err: raise Exception(err) l, err = command.get_output_list(r) if err: raise Exception(err) if l: print '\n'.join(l) else: l, err = command.get_error_list(r) if err: raise Exception(err) if l: print '\n'.join(l) except Exception, e: print "Error displaying system status : %s" % e return -1
def run_task(task_id): try: task, err = get_task(task_id) if err: raise Exception(err) now, err = datetime_utils.get_epoch(when='now') if err: raise Exception(err) db_path, err = config.get_db_path() if err: raise Exception(err) if task['last_run_time']: seconds_since_last_run = (now - task['last_run_time']) # retry_interval is in minutes! if seconds_since_last_run < task['retry_interval'] * 60: raise Exception("Too young to attempt") # Mark the task as running cmd = "update tasks set status = 'running', last_run_time=%d where task_id = '%d'" % ( now, task['task_id']) status, err = db.execute_iud( db_path, [[cmd], ], get_rowid=True) if err: raise Exception(err) audit_str = "%s" % task['description'] audit.audit("task_start", audit_str, None, system_initiated=True) attempts = task['attempts'] run_as_user_name = task['run_as_user_name'] # Now process subtasks for the task subtasks_query = "select * from subtasks where task_id == '%d' and (status == 'error-retrying' or status == 'queued') order by subtask_id" % task[ 'task_id'] subtasks, err = db.get_multiple_rows(db_path, subtasks_query) if err: raise Exception(err) # Assume task is complete unless proven otherwise task_completed = True # Iteriate through all the unfinished subtasks related to the # task for subtask in subtasks: subtask_id = subtask["subtask_id"] status_update = "update subtasks set status = 'running' where subtask_id = '%d' and status is not 'cancelled'" % subtask_id status, err = db.execute_iud( db_path, [[status_update], ], get_rowid=True) if err: task_completed = False break # Now actually execute the command # This task is not meant to be executed by the current user # so switch to that user (out, return_code), err = command.execute_with_rc( subtask["command"], shell=True, run_as_user_name=run_as_user_name) if out[0]: output = re.sub("'", "", ''.join(out[0])) else: output = None if out[1]: error = re.sub("'", "", ''.join(out[1])) else: error = None if return_code == 0: # This means the command was successful. So update to # completed status_update = "update subtasks set status = 'completed', return_code='%d' where subtask_id = '%d' and status is not 'cancelled';" % ( return_code, subtask_id) status, err = db.execute_iud( db_path, [[status_update], ], get_rowid=True) if err: task_completed = False break else: continue else: # Subtask command failed if attempts > 1 or attempts == -2: status_update = 'update subtasks set status = "error-retrying", return_code="%d" where subtask_id = "%d" and status is not "cancelled";' % ( return_code, subtask_id) elif attempts in [0, 1]: status_update = 'update subtasks set status = "failed", return_code="%d" where subtask_id = "%d" and status is not "cancelled";' % ( return_code, subtask_id) execute, err = db.execute_iud( db_path, [[status_update], ], get_rowid=True) task_completed = False break # Capture end time end_time, err = datetime_utils.get_epoch(when='now') if err: raise Exception(err) # Update status if task_completed: status_update = "update tasks set status = 'completed' where task_id = '%d'" % task[ 'task_id'] else: if attempts > 1: status_update = "update tasks set status = 'error-retrying', attempts = %d where task_id = '%d' and status is not 'cancelled'" % ( attempts - 1, task['task_id']) elif attempts == -2: status_update = "update tasks set status = 'error-retrying', attempts = %d where task_id = '%d' and status is not 'cancelled'" % ( -2, task['task_id']) else: status_update = "update tasks set status = 'failed', attempts = '%d' where task_id = '%d' and status is not 'cancelled'" % ( 0, task['task_id']) status, err = db.execute_iud( db_path, [[status_update], ], get_rowid=True) if err: raise Exception(err) # Update task's end time end_time_update = "update tasks set end_time=%d where task_id = '%d'" % ( end_time, task['task_id']) ret, err = db.execute_iud( db_path, [[end_time_update], ], get_rowid=True) if err: pass # raise Exception(err) if task_completed: audit.audit("task_complete", audit_str, None, system_initiated=True) else: audit.audit("task_fail", audit_str, None, system_initiated=True) except Exception as e: return False, 'Error processing task: %s' % e else: return True, None
def add_acl(target_name, acl): try: if not target_name: raise Exception('No Target Specified') if not acl: raise Exception('No ACL specified') target, err = get_target(target_name) if err: raise Exception(err) if not target: raise Exception('Specified target not found') acls = target['acl'] # First remove ALL from the ACL list if acls and 'ALL' in acls: cmd = 'tgtadm --lld iscsi --mode target --op unbind --tid %d -I ALL' % target[ 'tid'] (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception('Error removind wildcard ACL : %s' % err) cmd = 'tgtadm --lld iscsi --mode target --op bind --tid %d -I %s' % ( target['tid'], acl) (ret, rc), err = command.execute_with_rc(cmd) if err: raise Exception(err) if rc != 0: err = '' tl, er = command.get_output_list(ret) if er: raise Exception(er) if tl: err = ','.join(tl) tl, er = command.get_error_list(ret) if er: raise Exception(er) if tl: err = err + ','.join(tl) raise Exception(err) conf, err = generate_targets_conf() if err: raise Exception(err) except Exception, e: return False, 'Error adding ACL: %s' % str(e)