ccplugin.py 6.77 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# -*- coding: utf-8 -*-
"""update-webstats cubicweb plugin

Usage: cubicweb-ctl update-webstats [options] <instance-name>

This command will generate webstats objects for all linked document types.
"""

from datetime import datetime
from logilab.common.date import first_day, last_day

from cubicweb import cwconfig
from cubicweb import AuthenticationError
from cubicweb.dbapi import in_memory_repo_cnx

from cubicweb.toolsutils import Command
from cubicweb.cwctl import CWCTL

from utils import SECTIONSPEC, extract_stats_dict, eid_from_url

def url_count_from_stats(stats_dict):
Arthur Lutz's avatar
Arthur Lutz committed
22
23
24
25
26
27
    '''
    parse most visited urls in stats_dict generated from awstats txt file

    returns two dictionnaries with eid as key and sequence of values as value
    one for normal navigation, the other for rdf navigation
    '''
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    visit_count_dict = {}
    visit_count_rdf_dict = {}
    for item in stats_dict['SIDER'].values():
        url = item[SECTIONSPEC['SIDER'][0]]
        hits = int(item[SECTIONSPEC['SIDER'][1]])
        eid = eid_from_url(url)
        if not eid:
            continue
        if 'rdf' in url:
            visit_count_rdf_dict.setdefault(eid, [])
            visit_count_rdf_dict[eid].append((hits, url))
        else:
            visit_count_dict.setdefault(eid, [])
            visit_count_dict[eid].append((hits, url))
    return visit_count_dict, visit_count_rdf_dict


class UpdateWebstatsCommand(Command):
    """ Update web stats """

    arguments = '<instance>'
    name = 'update-webstats'
    min_args = 1

    def get_current_stats_period(self, session, chosendate):
Arthur Lutz's avatar
Arthur Lutz committed
53
        """ return a statperiod for the current month, if it doesn't exist, create it """
54
55
        start = first_day(chosendate)
        end = last_day(start)
Arthur Lutz's avatar
Arthur Lutz committed
56
57
58
59
        rql = 'Any P WHERE P is StatPeriod, P start "%(start_date)s", P stop "%(end_date)s"'
        rset = session.execute(rql %
                               {'start_date':start,
                                'end_date':end})
60
        if rset:
Arthur Lutz's avatar
Arthur Lutz committed
61
            return rset.get_entity(0, 0)
62
63
64
65
        else:
            return session.create_entity('StatPeriod', start=start, stop=end)

    def update_stats(self, session, args):
Arthur Lutz's avatar
Arthur Lutz committed
66
67
        ''' parses awstats and creates or updates the corresponding
        data in the cubicweb instance'''
68
69
70
71
        if args:
            chosendate = datetime.strptime(args[0], '%m/%Y')
        else:
            chosendate = datetime.now()
Arthur Lutz's avatar
Arthur Lutz committed
72
        stats_period = self.get_current_stats_period(session, chosendate)
73
74
75
76
77
78
        awstatsdir = session.vreg.config.get('awstats-dir', '/var/lib/awstats')
        domain = session.vreg.config.get('awstats-domain', '')
        filename = 'awstats%s%s.txt' % (chosendate.strftime('%m%Y'), domain and '.%s' % domain)
        stats_dict = extract_stats_dict(awstatsdir, filename)
        normal_dict, rdf_dict = url_count_from_stats(stats_dict)
        is_rdf = False
Arthur Lutz's avatar
Arthur Lutz committed
79
80
        rql = 'Any N WHERE X relation_type R, R name "stats_about", X to_entity Y, Y name N'
        rset = session.execute(rql)
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
        allowed_types = [item[0] for item in rset]
        update_stats = {'updated':0,
                        'created':0,
                        'exists no change':0,
                        'skipped':0,
                        }
        for count_dict, is_rdf in ((normal_dict, False),
                                   (rdf_dict, True)):
            for eid, values in count_dict.items():
                visit_count = visit_count_rdf = 0
                total_hits = sum([item[0] for item in values])
                entity = session.entity_from_eid(eid)
                if not entity.__regid__ in allowed_types:
                    update_stats['skipped'] += 1
                    continue
Arthur Lutz's avatar
Arthur Lutz committed
96
97
                rql = 'Any X,V WHERE X is Hits, X count V, X hit_type "%(hit_type)s",' \
                      'X stats_about E, E eid %(e)s, X period P, P eid %(sp)s'
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
                rset = session.execute(rql % {'e':eid,
                                              'sp':stats_period.eid,
                                              'hit_type': is_rdf and 'rdf' or 'normal'})
                if rset:
                    if rset[0][1] != total_hits:
                        print 'update', entity
                        update_stats['updated'] += 1
                        session.execute('SET X count %(hits)s WHERE X eid %(e)s' %
                                         {'e':rset[0][0],
                                          'hits':total_hits})
                    else:
                        print 'no change', entity
                        update_stats['exists no change'] += 1
                else:
                    print 'create', entity
                    update_stats['created'] += 1
Arthur Lutz's avatar
Arthur Lutz committed
114
115
116
117
                    session.create_entity('Hits', count = total_hits,
                                          period=stats_period,
                                          stats_about = entity,
                                          hit_type=is_rdf and u'rdf' or u'normal')
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
        print update_stats


    def _init_cw_connection(self, appid):
        self.config = config = cwconfig.instance_configuration(appid)
        sourcescfg = config.sources()
        config.set_sources_mode(('system',))
        cnx = repo = None
        while cnx is None:
            try:
                login = sourcescfg['admin']['login']
                pwd = sourcescfg['admin']['password']
            except KeyError:
                login, pwd = manager_userpasswd()
            try:
                repo, cnx = in_memory_repo_cnx(config, login=login, password=pwd)
            except AuthenticationError:
                print 'wrong user/password'
            else:
                break
        session = repo._get_session(cnx.sessionid)
        # XXX keep reference on cnx otherwise cnx.__del__ will cause trouble
        #     (file a ticket)
        return cnx, session

    def main_run(self, args, rcfile=None):
        """Run the command and return status 0 if everything went fine.

        If :exc:`CommandError` is raised by the underlying command, simply log
        the error and return status 2.

        Any other exceptions, including :exc:`BadCommandUsage` will be
        propagated.
        """
        # XXX (adim): rcfile handling is spectacularly messy but I can't
        #             get it right without refactoring pivotdoc for now
        if rcfile is None:
            if '-c' in args:
                rcfile = args[args.index('-c')+1]
            elif '--config' in args:
                rcfile = args[args.index('--config')+1]
            else:
                rcfile = None#self.config.config
        return Command.main_run(self, args, rcfile)

    def run(self, args):
        appid = args.pop(0)
        cw_cnx, session = self._init_cw_connection(appid)
        session.set_pool()
        self.update_stats(session, args)
        session.commit()


CWCTL.register(UpdateWebstatsCommand)