source: cows/branches/migrate-py26-pylons10/cows/pylons/config.py @ 7342

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/cows/branches/migrate-py26-pylons10/cows/pylons/config.py@7342
Revision 7342, 4.4 KB checked in by spascoe, 9 years ago (diff)

New branch for migration to Python-2.6 and Pylons-1.0.

Line 
1# BSD Licence
2# Copyright (c) 2009, Science & Technology Facilities Council (STFC)
3# All rights reserved.
4#
5# See the LICENSE file in the source distribution of this software for
6# the full license text.
7
8"""
9Miscellaneous utility functions/classes
10
11#load csml config options
12#starts symlink checker
13#send email (used by symlink checker
14
15
16"""
17
18import os, time
19import pylons
20from threading import Thread
21import logging
22log=logging.getLogger(__name__)
23
24from email.MIMEMultipart import MIMEMultipart
25from email.MIMEText import MIMEText
26from email.Utils import COMMASPACE, formatdate
27import smtplib
28from cows.service.imps.csmlbackend.config import config
29
30
31def configCSML(app_config=None):
32    """Initialise the configuration of the CSML backend from pylons.config.
33
34    For Pylons>=1.0 the pylons.config object is passed in explicitly.
35    If app_config=None Pylons-0.9.6.1 behaviour is assumed.
36
37    """
38   
39    if app_config is None:
40        app_config = pylons.config
41
42    for k in app_config:
43        parts = k.split('.')
44        if parts[:2] == ['cows', 'csml']:
45            k2 = '.'.join(parts[2:])
46            config[k2] = app_config[k]
47   
48    #set up the CSML symlink checker to check all symlinks in the csmlstore
49    #Symlink checker is currently set to check hourly but can be modified in the pylons ini file by changing csml.cows.symlink_check_interval (in minutes). 
50    if config.has_key('symlink_check_interval'):
51        minutes=float(config['symlink_check_interval'])
52    else:
53        #default to hourly checks
54        minutes=60
55    paths = getCSMLPaths(config['csmlstore'])
56    startSymLinkChecker(paths, minutes)
57       
58def getCSMLPaths(csmldirectory):   
59    paths=[]
60    for dirpath, dirnames, filenames in os.walk(csmldirectory):
61        for filename in filenames:
62            file_id, ext = os.path.splitext(filename)
63            if ext in ('.xml', '.csml'):
64                paths.append(os.path.join(dirpath, filename))
65    return paths
66
67def startSymLinkChecker(paths, minutes):
68    checkerProcess = SymlinkChecker(paths, minutes)
69    checkerProcess.start()
70
71class SymlinkChecker(Thread):
72    ''' This creates a new thread which sleeps most of the time, but occasionally checks that the CSML symlinks are working.'''
73    def __init__ (self,paths, sleepminutes):
74        Thread.__init__(self)
75        #self.setDaemon(True)
76        self.paths=paths
77        self.sleepminutes=sleepminutes
78   
79    def run(self):
80        while 1:
81            for path in self.paths:
82                if os.path.islink(path):
83                    #it's a symlink, get the link path
84                    symlinkpath=os.readlink(path)
85                    #this may be relative so make sure it isn't
86                    fullsymlinkpath=os.path.join(os.path.abspath(os.path.dirname(path) ), symlinkpath)
87                    #now check it's not broken.
88                    if not os.path.exists(fullsymlinkpath):
89                        #if broken, send notification email (if configured) and log a warning message
90                        if config.has_key('send_symlink_warnings_to'):
91                            if config.has_key('send_symlink_warnings_from'):
92                                if config.has_key('symlink_warnings_smtp'):
93                                    to=config['send_symlink_warnings_to'].split(',')
94                                    fro=config['send_symlink_warnings_from']
95                                    smtp=config['symlink_warnings_smtp']
96                                    subject = 'Broken Symlink in visualisation software'
97                                    message= 'This message is from the COWS pylons application. Symlink %s is broken' % path
98                                    sendemail(fro, to, subject, message, smtp)
99                        log.warning('INVESTIGATE: Symlink %s is broken ' % path)
100                    else:
101                        log.info('Symlink OK: %s '%path)
102            time.sleep(self.sleepminutes*60)
103   
104def sendemail(fro, to, subject, message, smtp):
105    ''' send an email '''
106    SERVER = smtp
107    FROM = fro
108    TO = to # must be a list
109    SUBJECT = subject
110    TEXT = message
111   
112    #create the message
113    msg = MIMEMultipart()
114    msg['From'] = FROM
115    msg['To'] = COMMASPACE.join(TO)
116    msg['Date'] = formatdate(localtime=True)
117    msg['Subject'] = SUBJECT
118    msg.attach( MIMEText(TEXT) )
119
120    # Send the mail
121    server = smtplib.SMTP(SERVER)
122    server.sendmail(FROM, TO, msg.as_string())
123    server.quit()
124       
125       
126               
127
128
129   
Note: See TracBrowser for help on using the repository browser.