def create_user(user): '''Create a new system user.''' roles = AAA.session_roles() if not AAA.UserRecord.authorize(roles, AAA.Create): raise Unauthorized(details="Not authorized to create users") Manager.create_user(user) logger.info("New system user: %s", user.username)
def shutdown_thread(): import time logging.info("Shutdown process started") Manager.shutdown() time.sleep(1) logging.critical("Shutdown complete, exiting") os._exit(0)
def delete_simulation(simid): '''Delete a simulation. This fails if the simulation is still running. ''' simdb = repo().SIM try: sim = simdb.get(simid) if sim.get('type', None) != "simoutput": raise NotFound(details="There is no simulation with this id") simdb.delete(simid) except (dpcmrepo.NotFound, NotFound): logger.debug('In api.delete_simulation(%s)', simid, exc_info=1) pass # Ignore # Now, get the job simjob = Manager.get_job_by_simid(simid) if simjob is None: raise NotFound("There is no simulation with this id") if simjob.state != 'PASSIVE': raise BadRequest("Cannot delete unfinished simulation") Manager.delete_job(simid)
def view_simhome(xtor, name): # check that the sim exists selected_file = request.query.selected try: executor = Manager.executor(xtor) fileloc = os.path.join(executor.homedir, name) job = Manager.get_job_by_fileloc(fileloc) if job is None: raise KeyError("No such job:", xtor, name) except: logging.info("Cannot find simulation", exc_info=True) abort(400, "Cannot find simulation.") job_status = job.status + ( ("[%s]" % job.last_status) if job.status == 'ABORTED' else "") job_created = job.tscreated.strftime("%y/%m/%d %H:%M:%S") job_runtime = str(job.tsinstatus - job.tscreated) basic_url = "/admin/simhomes/%s/%s" % (xtor, name) repo_simoutput = repo_url(SIM, Manager.get_simid(xtor, name)) def myurl(sel=selected_file): if sel is None: return basic_url else: return "%s?selected=%s" % (basic_url, sel) # create homedir file list files = [] viewer_type = None for f in os.listdir(fileloc): fpath = os.path.join(fileloc, f) if os.path.isfile(fpath): files.append(f) if f == selected_file: if any(f.endswith(s) for s in ('.txt', '.ini')): viewer_type = 'text' with open(fpath, 'r') as fs: viewer_content = fs.read() elif any(f.endswith(s) for s in ('.jpg', '.png')): viewer_type = 'image' elif f.endswith('.json'): viewer_type = 'text' with open(fpath, 'r') as fs: unformatted = fs.read() try: viewer_content = json.dumps(json.loads(unformatted), indent=4, sort_keys=True) except: viewer_content = unformatted else: viewer_type = 'binary' files.sort() # return view refresh_page = job.state != 'PASSIVE' thispage = myurl() return locals()
def delete_user(username): '''Delete a system user.''' roles = AAA.session_roles() if AAA.current_user() == username: roles.add(AAA.Owner) if not AAA.UserRecord.authorize(roles, AAA.Delete): raise Unauthorized(details="Not authorized to delete users") Manager.delete_user(username) logger.info("Deleted user: %s", username)
def change_admin_status(username, is_admin): '''Change the admin status of a user.''' roles = AAA.session_roles() if AAA.current_user() == username: roles.add(AAA.Owner) if not AAA.UserRecord.authorize(roles, AAA.ChangeAdminStatus): raise Unauthorized( details="Not authorized to change the admin flag for this user") Manager.update_user(username, is_admin=is_admin) logger.info("Changed admin status for user '%s' to %s", username, is_admin)
def change_user_password(username, password): '''Change the password for a user.''' roles = AAA.session_roles() if AAA.current_user() == username: roles.add(AAA.Owner) if not AAA.UserRecord.authorize(roles, AAA.ChangeUserPassword): raise Unauthorized( details="Not authorized to change the password for this user") Manager.update_user(username, password=password) logger.info("Changed password for user: %s", username)
def get_simfile(xtor, name, fname): try: executor = Manager.executor(xtor) fileloc = os.path.join(executor.homedir, name) return static_file(fname, root=fileloc) except: logging.info("Cannot find simulation", exc_info=True) abort(400, "Cannot find simulation.")
def current_user_is_admin(): ''' Return True iff current user is an administrator. ''' cu = current_user() if cu is not None: user = Manager.get_user(cu) assert isinstance(user, User) return user.is_admin
def create_simulation(nsdid, xtorname=None): ''' Create a simulation in the project repository and start a job for it. nsdid - the id of the NSD for the new simulation Return the new sim object created. Raises ValueError if nsdid is not in database PR.SIM ''' # Get the executor xtor = Manager.executor(xtorname) # create the simoutput object sim, url, simhome = create_simoutput(xtor, repo(), nsdid) logfile = create_logstatistics(simhome) # create the job Manager.create_job(xtor, url, simhome) return sim
def submit_job(self): try: #url for the sim.json file arg in create_job root_url = "file:" + self.simfile #simhome is job's fileloc self.simhome = Manager.create_job(root_url) except: print("Failed submitting new job") self.download_plan( self.read_json_file_argument(self.nsdfile, "plan_id")) self.download_project( self.read_json_file_argument(self.nsdfile, "project_id")) try: #get job's id self.retrieve_job() Manager.copy_simfiles(self.nsdfile, self.simfile, self.simhome) except: print("Failed copying sim and nsd files to local path")
def verify_password(username, password): user = Manager.get_user(username) return user is not None and user.password == password
def retrieve_job(self): jobs = Manager.get_jobId(self.simhome) for job in jobs: jobid = job.jobid self.simjobid = jobid
def start(args): # configure logging config_log(args) logging.info("WSN-DPCM Network Simulation Execution Monitor") # Read configuration file configure('sim_runner', args.config) # daemonize if needed if args.daemon: daemon_init() # redirect Python's standard streams to the log stdout_logger = logging.getLogger('STDOUT') sl = StreamToLogger(stdout_logger, logging.INFO) sys.stdout = sl stderr_logger = logging.getLogger('STDERR') sl = StreamToLogger(stderr_logger, logging.ERROR) sys.stderr = sl print("In Stdout: this is my PID:", os.getpid()) logging.critical("My Pid= %s", os.getpid()) # Does this have to go higher? mp.set_start_method('forkserver') # check Castalia configuration try: assertCastaliaSetup() # also check that setup_castalia has been run assertFileExists(castalia_path(), "makefrag.inc") except AssertionError: logging.exception("Checking castalia setup") logging.critical("Cannot execute simulations. Exiting.") return # check database configuration DAO.check_database(args, postgresql_connection()) logging.info("Verified database configuration") # check gui file location if not os.access(os.path.join(gui_file_path(), "mainpage.html"), os.R_OK): logging.critical("Cannot find the GUI files in location %s", gui_file_path()) os._exit(1) logging.info("Gui files located") # initialize project repository initialize_repo() # # ok, enough checks, now we go ahead with the boot # # Augment for Omnet++ augmentEnvironment() logging.info("Set up envorinemt vars for OmNet++") # boot the monitors try: Manager.initialize(postgresql_connection()) except Exception as e: logging.critical("Failed to initialize Manager") logging.exception("Exception from Manager.initialize") os._exit(1) logging.info("Starting gui") guiapp.start_gui(args, gui_bind_address()) logging.info("Starting shutdown") Manager.shutdown() logging.warning("Shutdown complete")