Show
Ignore:
Timestamp:
09/27/08 22:02:37 (16 years ago)
Author:
jerome
Message:

Removed unnecessary spaces at EOL.

Files:
1 modified

Legend:

Unmodified
Added
Removed
  • pykota/trunk/pykota/tool.py

    r3411 r3413  
    88# the Free Software Foundation, either version 3 of the License, or 
    99# (at your option) any later version. 
    10 #  
     10# 
    1111# This program is distributed in the hope that it will be useful, 
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of 
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    1414# GNU General Public License for more details. 
    15 #  
     15# 
    1616# You should have received a copy of the GNU General Public License 
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>. 
     
    5353        self.previous = None 
    5454        self.before = time.time() 
    55          
    56     def setSize(self, size) :      
     55 
     56    def setSize(self, size) : 
    5757        """Sets the total size.""" 
    5858        self.number = 0 
     
    6060        if size : 
    6161            self.factor = 100.0 / float(size) 
    62          
    63     def display(self, msg) :     
     62 
     63    def display(self, msg) : 
    6464        """Displays the value.""" 
    6565        self.app.display(msg) 
    66          
    67     def oneMore(self) :     
     66 
     67    def oneMore(self) : 
    6868        """Increments internal counter.""" 
    6969        if self.size : 
     
    7373                self.display("\r%s%%" % percent) 
    7474                self.previous = percent 
    75              
    76     def done(self) :          
     75 
     76    def done(self) : 
    7777        """Displays the 'done' message.""" 
    7878        after = time.time() 
     
    8080            try : 
    8181                speed = self.size / ((after - self.before) + 0.00000000001) # adds an epsilon to avoid an user's problem I can't reproduce... 
    82             except ZeroDivisionError :     
     82            except ZeroDivisionError : 
    8383                speed = 1 # Fake value in case of division by zero, shouldn't happen anyway with the epsilon above... 
    8484            self.display("\r100.00%%\r        \r%s. %s : %.2f %s.\n" \ 
    8585                     % (_("Done"), _("Average speed"), speed, _("entries per second"))) 
    86         else :              
     86        else : 
    8787            self.display("\r100.00%%\r        \r%s.\n" % _("Done")) 
    88          
     88 
    8989class Tool : 
    9090    """Base class for tools with no database access.""" 
     
    9393        self.debug = True # in case of early failure 
    9494        self.logger = logger.openLogger("stderr") 
    95          
     95 
    9696        # Saves a copy of the locale settings 
    9797        (self.language, self.charset) = locale.getlocale() 
     
    100100        if not self.charset : 
    101101            self.charset = "UTF-8" 
    102          
     102 
    103103        # pykota specific stuff 
    104104        self.documentation = doc 
    105          
     105 
    106106        # Extract the effective username 
    107107        uid = os.geteuid() 
    108108        try : 
    109109            self.effectiveUserName = pwd.getpwuid(uid)[0] 
    110         except (KeyError, IndexError), msg :     
     110        except (KeyError, IndexError), msg : 
    111111            self.printInfo(_("Strange problem with uid(%s) : %s") % (uid, msg), "warn") 
    112112            self.effectiveUserName = os.getlogin() 
    113          
    114     def deferredInit(self) :         
     113 
     114    def deferredInit(self) : 
    115115        """Deferred initialization.""" 
    116116        confdir = os.environ.get("PYKOTA_HOME") 
     
    123123                self.pykotauser = pwd.getpwnam("pykota") 
    124124                confdir = self.pykotauser[5] 
    125             except KeyError :     
     125            except KeyError : 
    126126                self.pykotauser = None 
    127127                confdir = "/etc/pykota" 
    128128                missingUser = True 
    129              
     129 
    130130        self.config = config.PyKotaConfig(confdir) 
    131131        self.debug = self.config.getDebug() 
     
    133133        self.maildomain = self.config.getMailDomain() 
    134134        self.logger = logger.openLogger(self.config.getLoggingBackend()) 
    135              
    136         # TODO : We NEED this here, even when not in an accounting filter/backend     
     135 
     136        # TODO : We NEED this here, even when not in an accounting filter/backend 
    137137        self.softwareJobSize = 0 
    138138        self.softwareJobPrice = 0.0 
    139          
     139 
    140140        if environHome : 
    141141            self.printInfo("PYKOTA_HOME environment variable is set. Configuration files were searched in %s" % confdir, "info") 
    142142        else : 
    143             if missingUser :      
     143            if missingUser : 
    144144                self.printInfo("The 'pykota' system account is missing. Configuration files were searched in %s instead." % confdir, "warn") 
    145          
     145 
    146146        self.logdebug("Language in use : %s" % self.language) 
    147147        self.logdebug("Charset in use : %s" % self.charset) 
    148          
     148 
    149149        arguments = " ".join(['"%s"' % arg for arg in sys.argv]) 
    150150        self.logdebug("Command line arguments : %s" % arguments) 
    151          
     151 
    152152    def display(self, message) : 
    153153        """Display a message but only if stdout is a tty.""" 
     
    156156                                            "replace")) 
    157157            sys.stdout.flush() 
    158              
    159     def logdebug(self, message) :     
     158 
     159    def logdebug(self, message) : 
    160160        """Logs something to debug output if debug is enabled.""" 
    161161        if self.debug : 
     
    163163                                                   "replace"), \ 
    164164                                    "debug") 
    165              
    166     def printInfo(self, message, level="info") :         
     165 
     166    def printInfo(self, message, level="info") : 
    167167        """Sends a message to standard error.""" 
    168168        sys.stderr.write("%s: %s\n" % (level.upper(), \ 
     
    170170                                                      "replace"))) 
    171171        sys.stderr.flush() 
    172          
     172 
    173173    def adminOnly(self, restricted=True) : 
    174174        """Raises an exception if the user is not a PyKota administrator.""" 
    175175        if restricted and not self.config.isAdmin : 
    176176            raise PyKotaCommandLineError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command.")) 
    177              
     177 
    178178    def matchString(self, s, patterns) : 
    179179        """Returns True if the string s matches one of the patterns, else False.""" 
    180180        if not patterns : 
    181181            return True # No pattern, always matches. 
    182         else :     
     182        else : 
    183183            for pattern in patterns : 
    184184                if fnmatch.fnmatchcase(s, pattern) : 
    185185                    return True 
    186186            return False 
    187          
     187 
    188188    def sanitizeNames(self, options, names) : 
    189189        """Ensures that an user can only see the datas he is allowed to see, by modifying the list of names.""" 
     
    198198                        return [ g.Name for g in self.storage.getUserGroups(user) ] 
    199199                return [ username ] 
    200         elif not names :         
     200        elif not names : 
    201201            return ["*"] 
    202         else :     
     202        else : 
    203203            return names 
    204          
     204 
    205205    def display_version_and_quit(self) : 
    206206        """Displays version number, then exists successfully.""" 
    207207        try : 
    208208            self.clean() 
    209         except AttributeError :     
     209        except AttributeError : 
    210210            pass 
    211211        print __version__ 
    212212        sys.exit(0) 
    213      
     213 
    214214    def display_usage_and_quit(self) : 
    215215        """Displays command line usage, then exists successfully.""" 
    216216        try : 
    217217            self.clean() 
    218         except AttributeError :     
     218        except AttributeError : 
    219219            pass 
    220220        print _(self.documentation) % globals() 
     
    223223        print _("Please report bugs to :"), __author__ 
    224224        sys.exit(0) 
    225          
    226     def crashed(self, message="Bug in PyKota") :     
     225 
     226    def crashed(self, message="Bug in PyKota") : 
    227227        """Outputs a crash message, and optionally sends it to software author.""" 
    228228        msg = utils.crashed(message) 
     
    248248            self.printInfo("PyKota double crash !", "error") 
    249249            raise 
    250         return fullmessage     
    251          
     250        return fullmessage 
     251 
    252252    def parseCommandline(self, argv, short, long, allownothing=0) : 
    253253        """Parses the command line, controlling options.""" 
     
    269269                withoutarg.append(short[i]) 
    270270            i = ii 
    271                  
     271 
    272272        for option in long : 
    273273            if option[-1] == '=' : 
     
    277277                # doesn't need an argument 
    278278                withoutarg.append(option) 
    279          
     279 
    280280        # then we parse the command line 
    281281        done = 0 
     
    309309            except getopt.error, msg : 
    310310                raise PyKotaCommandLineError, str(msg) 
    311             else :     
     311            else : 
    312312                if parsed["arguments"] or parsed["A"] : 
    313313                    # arguments are in a file, we ignore all other arguments 
     
    321321                        if argi.startswith('"') and argi.endswith('"') : 
    322322                            argv[i] = argi[1:-1] 
    323                 else :     
     323                else : 
    324324                    done = 1 
    325325        return (parsed, args) 
    326      
    327 class PyKotaTool(Tool) :     
     326 
     327class PyKotaTool(Tool) : 
    328328    """Base class for all PyKota command line tools.""" 
    329     def deferredInit(self) :     
     329    def deferredInit(self) : 
    330330        """Deferred initialization.""" 
    331331        Tool.deferredInit(self) 
     
    333333        if self.config.isAdmin : # TODO : We don't know this before, fix this ! 
    334334            self.logdebug("Beware : running as a PyKota administrator !") 
    335         else :     
     335        else : 
    336336            self.logdebug("Don't Panic : running as a mere mortal !") 
    337          
    338     def clean(self) :     
     337 
     338    def clean(self) : 
    339339        """Ensures that the database is closed.""" 
    340340        try : 
    341341            self.storage.close() 
    342         except (TypeError, NameError, AttributeError) :     
     342        except (TypeError, NameError, AttributeError) : 
    343343            pass 
    344              
     344 
    345345    def isValidName(self, name) : 
    346346        """Checks if a user or printer name is valid.""" 
     
    349349            if c in name : 
    350350                return 0 
    351         return 1         
    352          
    353     def _checkUserPQuota(self, userpquota) :             
     351        return 1 
     352 
     353    def _checkUserPQuota(self, userpquota) : 
    354354        """Checks the user quota on a printer and deny or accept the job.""" 
    355355        # then we check the user's own quota 
     
    361361        (policy, dummy) = self.config.getPrinterPolicy(userpquota.Printer.Name) 
    362362        if not userpquota.Exists : 
    363             # Unknown userquota  
     363            # Unknown userquota 
    364364            if policy == "ALLOW" : 
    365365                action = "POLICY_ALLOW" 
    366             else :     
     366            else : 
    367367                action = "POLICY_DENY" 
    368368            self.printInfo(_("Unable to match user %s on printer %s, applying default policy (%s)") % (user.Name, printer.Name, action)) 
    369         else :     
     369        else : 
    370370            pagecounter = int(userpquota.PageCounter or 0) 
    371371            if enforcement == "STRICT" : 
     
    375375                if pagecounter < softlimit : 
    376376                    action = "ALLOW" 
    377                 else :     
     377                else : 
    378378                    if userpquota.HardLimit is None : 
    379379                        # only a soft limit, this is equivalent to having only a hard limit 
    380380                        action = "DENY" 
    381                     else :     
     381                    else : 
    382382                        hardlimit = int(userpquota.HardLimit) 
    383                         if softlimit <= pagecounter < hardlimit :     
     383                        if softlimit <= pagecounter < hardlimit : 
    384384                            now = DateTime.now() 
    385385                            if userpquota.DateLimit is not None : 
     
    390390                            if now < datelimit : 
    391391                                action = "WARN" 
    392                             else :     
     392                            else : 
    393393                                action = "DENY" 
    394                         else :          
     394                        else : 
    395395                            action = "DENY" 
    396             else :         
     396            else : 
    397397                if userpquota.HardLimit is not None : 
    398398                    # no soft limit, only a hard one. 
     
    400400                    if pagecounter < hardlimit : 
    401401                        action = "ALLOW" 
    402                     else :       
     402                    else : 
    403403                        action = "DENY" 
    404404                else : 
     
    406406                    action = "ALLOW" 
    407407        return action 
    408      
    409     def checkGroupPQuota(self, grouppquota) :     
     408 
     409    def checkGroupPQuota(self, grouppquota) : 
    410410        """Checks the group quota on a printer and deny or accept the job.""" 
    411411        group = grouppquota.Group 
     
    413413        enforcement = self.config.getPrinterEnforcement(printer.Name) 
    414414        self.logdebug("Checking group %s's quota on printer %s" % (group.Name, printer.Name)) 
    415         if group.LimitBy and (group.LimitBy.lower() == "balance") :  
     415        if group.LimitBy and (group.LimitBy.lower() == "balance") : 
    416416            val = group.AccountBalance or 0.0 
    417             if enforcement == "STRICT" :  
     417            if enforcement == "STRICT" : 
    418418                val -= self.softwareJobPrice # use precomputed size. 
    419419            balancezero = self.config.getBalanceZero() 
    420420            if val <= balancezero : 
    421421                action = "DENY" 
    422             elif val <= self.config.getPoorMan() :     
     422            elif val <= self.config.getPoorMan() : 
    423423                action = "WARN" 
    424             else :     
     424            else : 
    425425                action = "ALLOW" 
    426426            if (enforcement == "STRICT") and (val == balancezero) : 
     
    434434                if val < softlimit : 
    435435                    action = "ALLOW" 
    436                 else :     
     436                else : 
    437437                    if grouppquota.HardLimit is None : 
    438438                        # only a soft limit, this is equivalent to having only a hard limit 
    439439                        action = "DENY" 
    440                     else :     
     440                    else : 
    441441                        hardlimit = int(grouppquota.HardLimit) 
    442                         if softlimit <= val < hardlimit :     
     442                        if softlimit <= val < hardlimit : 
    443443                            now = DateTime.now() 
    444444                            if grouppquota.DateLimit is not None : 
     
    449449                            if now < datelimit : 
    450450                                action = "WARN" 
    451                             else :     
     451                            else : 
    452452                                action = "DENY" 
    453                         else :          
     453                        else : 
    454454                            action = "DENY" 
    455             else :         
     455            else : 
    456456                if grouppquota.HardLimit is not None : 
    457457                    # no soft limit, only a hard one. 
     
    459459                    if val < hardlimit : 
    460460                        action = "ALLOW" 
    461                     else :       
     461                    else : 
    462462                        action = "DENY" 
    463463                else : 
     
    465465                    action = "ALLOW" 
    466466        return action 
    467      
     467 
    468468    def checkUserPQuota(self, userpquota) : 
    469469        """Checks the user quota on a printer and all its parents and deny or accept the job.""" 
    470470        user = userpquota.User 
    471471        printer = userpquota.Printer 
    472          
     472 
    473473        # indicates that a warning needs to be sent 
    474         warned = 0                 
    475          
     474        warned = 0 
     475 
    476476        # first we check any group the user is a member of 
    477477        for group in self.storage.getUserGroups(user) : 
     
    485485                        if action == "DENY" : 
    486486                            return action 
    487                         elif action == "WARN" :     
     487                        elif action == "WARN" : 
    488488                            warned = 1 
    489                          
     489 
    490490        # Then we check the user's account balance 
    491491        # if we get there we are sure that policy is not EXTERNAL 
    492492        (policy, dummy) = self.config.getPrinterPolicy(printer.Name) 
    493         if user.LimitBy and (user.LimitBy.lower() == "balance") :  
     493        if user.LimitBy and (user.LimitBy.lower() == "balance") : 
    494494            self.logdebug("Checking account balance for user %s" % user.Name) 
    495495            if user.AccountBalance is None : 
    496496                if policy == "ALLOW" : 
    497497                    action = "POLICY_ALLOW" 
    498                 else :     
     498                else : 
    499499                    action = "POLICY_DENY" 
    500500                self.printInfo(_("Unable to find user %s's account balance, applying default policy (%s) for printer %s") % (user.Name, action, printer.Name)) 
    501                 return action         
    502             else :     
     501                return action 
     502            else : 
    503503                if user.OverCharge == 0.0 : 
    504504                    self.printInfo(_("User %s will not be charged for printing.") % user.Name) 
     
    507507                    val = float(user.AccountBalance or 0.0) 
    508508                    enforcement = self.config.getPrinterEnforcement(printer.Name) 
    509                     if enforcement == "STRICT" :  
     509                    if enforcement == "STRICT" : 
    510510                        val -= self.softwareJobPrice # use precomputed size. 
    511                     balancezero = self.config.getBalanceZero()     
     511                    balancezero = self.config.getBalanceZero() 
    512512                    if val <= balancezero : 
    513513                        action = "DENY" 
    514                     elif val <= self.config.getPoorMan() :     
     514                    elif val <= self.config.getPoorMan() : 
    515515                        action = "WARN" 
    516516                    else : 
     
    518518                    if (enforcement == "STRICT") and (val == balancezero) : 
    519519                        action = "WARN" # we can still print until account is 0 
    520                 return action     
    521         else : 
    522             # Then check the user quota on current printer and all its parents.                 
     520                return action 
     521        else : 
     522            # Then check the user quota on current printer and all its parents. 
    523523            policyallowed = 0 
    524             for upquota in [ userpquota ] + userpquota.ParentPrintersUserPQuota :                
     524            for upquota in [ userpquota ] + userpquota.ParentPrintersUserPQuota : 
    525525                action = self._checkUserPQuota(upquota) 
    526526                if action in ("DENY", "POLICY_DENY") : 
    527527                    return action 
    528                 elif action == "WARN" :     
     528                elif action == "WARN" : 
    529529                    warned = 1 
    530                 elif action == "POLICY_ALLOW" :     
     530                elif action == "POLICY_ALLOW" : 
    531531                    policyallowed = 1 
    532             if warned :         
     532            if warned : 
    533533                return "WARN" 
    534             elif policyallowed :     
    535                 return "POLICY_ALLOW"  
    536             else :     
     534            elif policyallowed : 
     535                return "POLICY_ALLOW" 
     536            else : 
    537537                return "ALLOW" 
    538                  
     538 
    539539    def externalMailTo(self, cmd, action, user, printer, message) : 
    540540        """Warns the user with an external command.""" 
     
    545545            email = "%s@%s" % (email, self.maildomain or self.smtpserver) 
    546546        os.system(cmd % locals()) 
    547      
     547 
    548548    def formatCommandLine(self, cmd, user, printer) : 
    549549        """Executes an external command.""" 
     
    551551        printername = printer.Name 
    552552        return cmd % locals() 
    553          
     553