def run(self): if os.fork() == 0: for i in xrange(1, 1024): try: os.close(i) except OSError: pass try: passwd = pwd.getpwnam(self.cron_user.encode('utf8')) os.umask(0) os.setgid(passwd.pw_gid) os.setuid(passwd.pw_uid) try: os.chdir(passwd.pw_dir) except: pass proc = subprocess.Popen( '%s | logger -t cron' % self.commandline(), shell=True, env={ 'PATH': ('/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:' '/usr/local/sbin:/root/bin'), }, ) except Exception, e: log.debug("Failed to run cron") log_traceback(log=log) os._exit(0)
def generate(self, request=None): """ Tree Menu Auto Generate Every app listed at INSTALLED_APPS is scanned 1st - app_name.forms is imported. All its objects/classes are scanned looking for ModelForm classes 2nd - app_name.nav is imported. TreeNode classes are scanned for hard-coded menu entries or overwriting 3rd - app_name.models is imported. models.Model classes are scanned, if a related ModelForm is found several entries are Added to the Menu - Objects - Add (Model) - View (Model) """ self._generated = True self._navs.clear() tree_roots.clear() childs_of = [] for app in settings.INSTALLED_APPS: # If the app is listed at settings.BLACKLIST_NAV, skip it! if app in getattr(settings, 'BLACKLIST_NAV', []): continue try: self._generate_app(app, request, tree_roots, childs_of) except Exception, e: log.error( "Failed to generate navtree for app %s: %s", app, e) log_traceback(log=log)
def generate(self, request=None): """ Tree Menu Auto Generate Every app listed at INSTALLED_APPS is scanned 1st - app_name.forms is imported. All its objects/classes are scanned looking for ModelForm classes 2nd - app_name.nav is imported. TreeNode classes are scanned for hard-coded menu entries or overwriting 3rd - app_name.models is imported. models.Model classes are scanned, if a related ModelForm is found several entries are Added to the Menu - Objects - Add (Model) - View (Model) """ self._generated = True self._navs.clear() tree_roots.clear() childs_of = [] for app in settings.INSTALLED_APPS: # If the app is listed at settings.BLACKLIST_NAV, skip it! if app in getattr(settings, 'BLACKLIST_NAV', []): continue try: self._generate_app(app, request, tree_roots, childs_of) except Exception, e: log.error("Failed to generate navtree for app %s: %s", app, e) log_traceback(log=log)
def run(self): if os.fork() == 0: for i in xrange(1, 1024): try: os.close(i) except OSError: pass try: passwd = pwd.getpwnam(self.rsync_user.encode('utf8')) os.umask(0) os.setgid(passwd.pw_gid) os.setuid(passwd.pw_uid) try: os.chdir(passwd.pw_dir) except: pass proc = subprocess.Popen( '%s 2>&1 | logger -t rsync' % self.commandline(), shell=True, env={ 'PATH': ( '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:' '/usr/local/sbin:/root/bin' ), }, ) proc.communicate() except Exception: log.debug("Failed to run rsync") log_traceback(log=log) os._exit(0)
def save(self, *args, **kwargs): rv = super(Model, self).save(*args, **kwargs) from freenasUI.common.system import backup_database try: # TODO: maybe we should do this in a thread # to do not wait operation to finish backup_database() except Exception, e: log.debug("Failed to backup database on model delete") log_traceback(log=log)
def dispatch(self, request_type, request, *args, **kwargs): try: return super(ResourceMixin, self).dispatch(request_type, request, *args, **kwargs) except (MiddlewareError, ServiceFailed, UnsupportedFormat), e: log_traceback(log=log) raise ImmediateHttpResponse( response=self.error_response(request, { 'error_message': unicode(e), }))
def _handle_500(self, request, exception, *args, **kwargs): log_traceback(log=log) if isinstance(exception, (NotFound, ObjectDoesNotExist, Http404, UnsupportedFormat)): return super(ResourceMixin, self)._handle_500(request, exception, *args, **kwargs) else: the_trace = '\n'.join(traceback.format_exception(*(sys.exc_info()))) data = { "error_message": sanitize(six.text_type(exception)), "traceback": the_trace, } return self.error_response(request, data, response_class=http.HttpApplicationError)
def dispatch(self, request_type, request, *args, **kwargs): try: return super(ResourceMixin, self).dispatch( request_type, request, *args, **kwargs ) except (MiddlewareError, ServiceFailed, UnsupportedFormat), e: log_traceback(log=log) raise ImmediateHttpResponse( response=self.error_response(request, { 'error_message': unicode(e), }) )
def add_nt4_conf(client, smb4_conf): # TODO: These are unused, will they be at some point? # rid_range_start = 20000 # rid_range_end = 20000000 try: nt4 = Struct( client.call('datastore.query', 'directoryservice.nt4', None, {'get': True})) nt4.ds_type = 4 # FIXME: DS_TYPE_NT4 = 4 except: return dc_ip = None try: answers = resolver.query(nt4.nt4_dcname, 'A') dc_ip = answers[0] except Exception as e: log.debug("resolver query for {0}'s A record failed with {1}".format( nt4.nt4_dcname, e)) log_traceback(log=log) dc_ip = nt4.nt4_dcname nt4_workgroup = nt4.nt4_workgroup.upper() with open("/usr/local/etc/lmhosts", "w") as f: f.write("%s\t%s\n" % (dc_ip, nt4.nt4_dcname.upper())) confset2(smb4_conf, "workgroup = %s", nt4_workgroup) confset1(smb4_conf, "security = domain") confset1(smb4_conf, "password server = *") idmap = Struct( client.call('notifier.ds_get_idmap_object', nt4.ds_type, nt4.id, nt4.nt4_idmap_backend)) configure_idmap_backend(client, smb4_conf, idmap, nt4_workgroup) confset1(smb4_conf, "winbind cache time = 7200") confset1(smb4_conf, "winbind offline logon = yes") confset1(smb4_conf, "winbind enum users = yes") confset1(smb4_conf, "winbind enum groups = yes") confset1(smb4_conf, "winbind nested groups = yes") confset2(smb4_conf, "winbind use default domain = %s", "yes" if nt4.nt4_use_default_domain else "no") confset1(smb4_conf, "template shell = /bin/sh") confset1(smb4_conf, "local master = no") confset1(smb4_conf, "domain master = no") confset1(smb4_conf, "preferred master = no")
def add_nt4_conf(client, smb4_conf): # TODO: These are unused, will they be at some point? # rid_range_start = 20000 # rid_range_end = 20000000 try: nt4 = Struct(client.call('datastore.query', 'directoryservice.nt4', None, {'get': True})) nt4.ds_type = 4 # FIXME: DS_TYPE_NT4 = 4 except: return dc_ip = None try: answers = resolver.query(nt4.nt4_dcname, 'A') dc_ip = answers[0] except Exception as e: log.debug( "resolver query for {0}'s A record failed with {1}".format(nt4.nt4_dcname, e) ) log_traceback(log=log) dc_ip = nt4.nt4_dcname nt4_workgroup = nt4.nt4_workgroup.upper() with open("/usr/local/etc/lmhosts", "w") as f: f.write("%s\t%s\n" % (dc_ip, nt4.nt4_dcname.upper())) confset2(smb4_conf, "workgroup = %s", nt4_workgroup) confset1(smb4_conf, "security = domain") confset1(smb4_conf, "password server = *") idmap = Struct(client.call('notifier.ds_get_idmap_object', nt4.ds_type, nt4.id, nt4.nt4_idmap_backend)) configure_idmap_backend(client, smb4_conf, idmap, nt4_workgroup) confset1(smb4_conf, "winbind cache time = 7200") confset1(smb4_conf, "winbind offline logon = yes") confset1(smb4_conf, "winbind enum users = yes") confset1(smb4_conf, "winbind enum groups = yes") confset1(smb4_conf, "winbind nested groups = yes") confset2( smb4_conf, "winbind use default domain = %s", "yes" if nt4.nt4_use_default_domain else "no" ) confset1(smb4_conf, "template shell = /bin/sh") confset1(smb4_conf, "local master = no") confset1(smb4_conf, "domain master = no") confset1(smb4_conf, "preferred master = no")
def smb4_get_database_SID(client): SID = None try: cifs = Struct(client.call('datastore.query', 'services.cifs', None, {'get': True})) if cifs: SID = cifs.cifs_SID except Exception as e: log.debug( 'The following exception occured while trying to obtain database SID: {0}'.format(e) ) log_traceback(log=log) SID = None return SID
def smb4_get_database_SID(): SID = None try: cifs = CIFS.objects.all()[0] if cifs: SID = cifs.cifs_SID except Exception as e: log.debug( 'The following exception occured while trying to obtain database SID: {0}'.format(e) ) log_traceback(log=log) SID = None return SID
def smb4_restore_tdbfile(tdb_src, tdb_dst): proc = subprocess.Popen( "/usr/local/bin/tdbdump {} | /usr/local/bin/tdbrestore {}".format( tdb_src, tdb_dst, ), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, encoding='utf8', ) err = proc.communicate()[1] if proc.returncode != 0: log.error("Failed to dump and restore tdb: {}".format(err)) log_traceback(log=log) return False return True
def smb4_set_database_SID(SID): ret = False if not SID: return ret try: cifs = CIFS.objects.all()[0] cifs.cifs_SID = SID cifs.save() ret = True except Exception as e: log.debug( 'The following exception occured while trying to set database SID: {0}'.format(e) ) log_traceback(log=log) ret = False return ret
def smb4_set_database_SID(client, SID): ret = False if not SID: return ret try: cifs = Struct(client.call('datastore.query', 'services.cifs', None, {'get': True})) cifs.cifs_SID = SID cifs.save() ret = True except Exception as e: log.debug( 'The following exception occured while trying to set database SID: {0}'.format(e) ) log_traceback(log=log) ret = False return ret
def run(self): from freenasUI.middleware.notifier import notifier from freenasUI.common.log import log_traceback # FIXME: cache IP value s = notifier().failover_rpc() try: with Journal() as f: if f.queries: f.queries.append((self._sql, self._params)) else: s.run_sql(self._sql, self._params) except socket.error as err: with Journal() as f: f.queries.append((self._sql, self._params)) return False except Exception as err: log_traceback(log=log) log.error('Failed to run SQL remotely %s: %s', self._sql, err) return False return True
def smb4_get_system_SID(): SID = None p = pipeopen("/usr/local/bin/net -d 0 getlocalsid") net_out = p.communicate() if p.returncode != 0: return None if not net_out: return None net_out = net_out[0] parts = net_out.split() try: SID = parts[5] except Exception as e: log.debug( 'The following exception occured while trying to obtain system SID: {0}'.format(e) ) log_traceback(log=log) SID = None return SID
def smb4_restore_tdbfile(tdb_src, tdb_dst): try: db_r = tdb.open(tdb_src, flags=os.O_RDONLY) except Exception as e: print >> sys.stderr, "Unable to open %s: %s" % (tdb_src, e) log.error("Unable to open {0}: {1}".format(tdb_src, e)) log_traceback(log=log) return False try: db_w = tdb.open(tdb_dst, flags=os.O_RDWR) except Exception as e: print >> sys.stderr, "Unable to open %s: %s" % (tdb_dst, e) log.error("Unable to open {0}: {1}".format(tdb_dst, e)) log_traceback(log=log) return False for key in db_r.iterkeys(): try: db_w.transaction_start() db_w.lock_all() db_w[key] = db_r.get(key) db_w.unlock_all() db_w.transaction_prepare_commit() db_w.transaction_commit() except Exception as e: print >> sys.stderr, "Transaction for key %s failed: %s" % (key, e) log.error("Transaction for key {0} failed: {1}".format(key, e)) log_traceback(log=log) db_w.transaction_cancel() db_r.close() db_w.close() return True
def generate(self, request=None): """ Tree Menu Auto Generate Every app listed at INSTALLED_APPS is scanned 1st - app_name.forms is imported. All its objects/classes are scanned looking for ModelForm classes 2nd - app_name.nav is imported. TreeNode classes are scanned for hard-coded menu entries or overwriting 3rd - app_name.models is imported. models.Model classes are scanned, if a related ModelForm is found several entries are Added to the Menu - Objects - Add (Model) - View (Model) """ self._generated = True self._navs.clear() tree_roots.clear() childs_of = [] if hasattr(notifier, 'failover_status'): fstatus = notifier().failover_status() else: fstatus = 'SINGLE' for app in settings.INSTALLED_APPS: # If the app is listed at settings.BLACKLIST_NAV, skip it! if app in getattr(settings, 'BLACKLIST_NAV', []): continue try: self._generate_app(app, request, tree_roots, childs_of, fstatus) except Exception as e: log.error("Failed to generate navtree for app %s: %s", app, e) log_traceback(log=log) nav = TreeRoot( 'documentation', name=_('Guide'), icon=get_sw_name() + 'GuideIcon', action='opendocumentation', view='documentation_home', order=970, ) tree_roots.register(nav) nav = TreeRoot( 'display', name=_('Display System Processes'), action='displayprocs', icon='TopIcon', order=985, ) tree_roots.register(nav) if fstatus in ('MASTER', 'SINGLE'): nav = TreeRoot( 'initialwizard', name=_('Wizard'), icon='WizardIcon', action='wizard', order=980, ) tree_roots.register(nav) nav = TreeRoot( 'shell', name=_('Shell'), icon='ShellIcon', action='shell', order=990, ) tree_roots.register(nav) nav = TreeRoot( 'logout', name=_('Log Out'), icon='LogOutIcon', action='logout', order=995, ) tree_roots.register(nav) nav = TreeRoot( 'reboot', name=_('Reboot'), action='reboot', icon='RebootIcon', type='scary_dialog', view='system_reboot_dialog', order=999, ) tree_roots.register(nav) nav = TreeRoot( 'shutdown', name=_('Shutdown'), icon='ShutdownIcon', type='scary_dialog', view='system_shutdown_dialog', order=1000, ) tree_roots.register(nav) for opt, model in childs_of: for nav in tree_roots: exists = nav.find_gname(model._admin.menu_child_of) if exists is not False: exists.append_child(opt) break if exists is False: log.debug("Could not find %s to attach %r", model._admin.menu_child_of, opt) self.replace_navs(tree_roots) jails = [] # FIXME: use .filter for j in Jails.objects.all(): if (j.jail_type == WARDEN_TYPE_PLUGINJAIL and j.jail_status == WARDEN_STATUS_RUNNING): jails.append(j) self._get_plugins_nodes(request, jails)
def generate(self, request=None): """ Tree Menu Auto Generate Every app listed at INSTALLED_APPS is scanned 1st - app_name.forms is imported. All its objects/classes are scanned looking for ModelForm classes 2nd - app_name.nav is imported. TreeNode classes are scanned for hard-coded menu entries or overwriting 3rd - app_name.models is imported. models.Model classes are scanned, if a related ModelForm is found several entries are Added to the Menu - Objects - Add (Model) - View (Model) """ self._generated = True self._navs.clear() tree_roots.clear() childs_of = [] if hasattr(notifier, 'failover_status'): fstatus = notifier().failover_status() else: fstatus = 'SINGLE' for app in settings.INSTALLED_APPS: # If the app is listed at settings.BLACKLIST_NAV, skip it! if app in getattr(settings, 'BLACKLIST_NAV', []): continue try: self._generate_app(app, request, tree_roots, childs_of, fstatus) except Exception as e: log.error( "Failed to generate navtree for app %s: %s", app, e) log_traceback(log=log) nav = TreeRoot( 'documentation', name=_('Guide'), icon=get_sw_name() + 'GuideIcon', action='opendocumentation', view='documentation_home', order=970, ) tree_roots.register(nav) nav = TreeRoot( 'display', name=_('Display System Processes'), action='displayprocs', icon='TopIcon', order=985, ) tree_roots.register(nav) if fstatus in ('MASTER', 'SINGLE'): nav = TreeRoot( 'initialwizard', name=_('Wizard'), icon='WizardIcon', action='wizard', order=980, ) tree_roots.register(nav) nav = TreeRoot( 'shell', name=_('Shell'), icon='ShellIcon', action='shell', order=990, ) tree_roots.register(nav) nav = TreeRoot( 'logout', name=_('Log Out'), icon='LogOutIcon', action='logout', order=995, ) tree_roots.register(nav) nav = TreeRoot( 'reboot', name=_('Reboot'), action='reboot', icon='RebootIcon', type='scary_dialog', view='system_reboot_dialog', order=999, ) tree_roots.register(nav) nav = TreeRoot( 'shutdown', name=_('Shutdown'), icon='ShutdownIcon', type='scary_dialog', view='system_shutdown_dialog', order=1000, ) tree_roots.register(nav) for opt, model in childs_of: for nav in tree_roots: exists = nav.find_gname(model._admin.menu_child_of) if exists is not False: exists.append_child(opt) break if exists is False: log.debug( "Could not find %s to attach %r", model._admin.menu_child_of, opt) self.replace_navs(tree_roots) jails = [] # FIXME: use .filter for j in Jails.objects.all(): if ( j.jail_type == WARDEN_TYPE_PLUGINJAIL and j.jail_status == WARDEN_STATUS_RUNNING ): jails.append(j) self._get_plugins_nodes(request, jails)
parser.add_argument('-d', '--download', action='store_true', help='Download updates') parser.add_argument('-t', '--train', help='Train name') parser.add_argument('-c', '--cache', help='Path to the cache directory') args = parser.parse_args() handler = UpdateHandler(apply_=args.apply) handler.dump() print handler.uuid sys.stdout.flush() log.debug("Entering in daemon mode") with context: log.debug("Entered in daemon context") try: main(handler, args) except Exception, e: log.debug('Exception on update') log_traceback(log=log) handler.error = unicode(e) handler.finished = True handler.dump() log.debug("Exiting daemon process") sys.exit(0)
def _handle_500(self, *args, **kwargs): log_traceback(log=log) return super(ResourceMixin, self)._handle_500(*args, **kwargs)
) proc.communicate() if __name__ == "__main__": context = daemon.DaemonContext( working_directory="/root", umask=0o002, stdout=sys.stdout, stdin=sys.stdin, stderr=sys.stderr, detach_process=True, ) parser = argparse.ArgumentParser() parser.add_argument("-t", "--type", help="Job type") parser.add_argument("-i", "--id", help="ID of the job") args = parser.parse_args() with context: log.debug("Entered in daemon context") try: main(args) except Exception, e: log.debug("Exception on run now") log_traceback(log=log) log.debug("Exiting runnow process") sys.exit(0)
def update_check(request): try: updateobj = models.Update.objects.order_by('-id')[0] except IndexError: updateobj = models.Update.objects.create() if request.method == 'POST': uuid = request.GET.get('uuid') if request.POST.get('apply') == '1': apply_ = True else: apply_ = False handler = UpdateHandler(uuid=uuid, apply_=apply_) if not uuid: #FIXME: ugly pid = os.fork() if pid != 0: return HttpResponse(handler.uuid, status=202) else: handler.pid = os.getpid() handler.dump() path = notifier().system_dataset_path() if not path: raise MiddlewareError(_('System dataset not configured')) try: if handler.apply: Update( train=updateobj.get_train(), get_handler=handler.get_handler, install_handler=handler.install_handler, cache_dir='%s/update' % path, ) else: DownloadUpdate( updateobj.get_train(), '%s/update' % path, check_handler=handler.get_handler, get_handler=handler.get_file_handler, ) except Exception, e: from freenasUI.common.log import log_traceback log_traceback(log=log) handler.error = unicode(e) handler.finished = True handler.dump() os.kill(handler.pid, 9) else: if handler.error is not False: raise MiddlewareError(handler.error) if not handler.finished: return HttpResponse(handler.uuid, status=202) handler.exit() if handler.apply: request.session['allow_reboot'] = True return render(request, 'system/done.html') else: return JsonResp( request, message=_('Packages downloaded'), )
class ResourceMixin(object): def method_check(self, request, allowed=None): """ Make sure only OAuth2 is allowed to POST/PUT/DELETE """ if self.is_webclient(request): try: self.is_authenticated(request) allowed = ['get'] except: pass return super(ResourceMixin, self).method_check( request, allowed=allowed ) def is_webclient(self, request): # Do not treat passwordless API auth as webclient if not bsdUsers.has_root_password(): return None if ( request.META.get('HTTP_X_REQUESTED_FROM') == 'WebUI' or not request.META.get('HTTP_AUTHORIZATION', '').startswith('Basic') ): return True def get_list(self, request, **kwargs): """ XXXXXX This method was retrieved from django-tastypie It had to be modified that way to set the Content-Range response header so ranges could workd well with dojo XXXXXX """ base_bundle = self.build_bundle(request=request) objects = self.obj_get_list( bundle=base_bundle, **self.remove_api_resource_names(kwargs) ) sorted_objects = self.apply_sorting(objects, options=request.GET) paginator = self._meta.paginator_class( request, sorted_objects, resource_uri=self.get_resource_uri(), limit=self._meta.limit ) to_be_serialized = paginator.page() bundles = [ self.build_bundle(obj=obj, request=request) for obj in to_be_serialized['objects'] ] to_be_serialized['objects'] = [ self.full_dehydrate(bundle) for bundle in bundles ] length = len(to_be_serialized['objects']) to_be_serialized = self.alter_list_data_to_serialize( request, to_be_serialized ) response = self.create_response(request, to_be_serialized) response['Content-Range'] = 'items %d-%d/%d' % ( paginator.offset, paginator.offset+length-1, len(sorted_objects) ) return response def _handle_500(self, *args, **kwargs): log_traceback(log=log) return super(ResourceMixin, self)._handle_500(*args, **kwargs) def dispatch(self, request_type, request, *args, **kwargs): try: return super(ResourceMixin, self).dispatch( request_type, request, *args, **kwargs ) except (MiddlewareError, ServiceFailed, UnsupportedFormat), e: log_traceback(log=log) raise ImmediateHttpResponse( response=self.error_response(request, { 'error_message': unicode(e), }) ) except Exception, e: log_traceback(log=log) raise