summaryrefslogtreecommitdiff
path: root/linaro_metrics/crowd.py
blob: 1aab51b52c3291bcae30e7daa15d804e0b494961 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
# Copyright (C) 2013 Linaro
#
# Author: Milo Casagrande <milo.casagrande@linaro.org>
# This file is part of the Patchmetrics package.
#
# Patchmetrics is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Patchmetrics is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Patchwork; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import base64
import contextlib
import fcntl
import httplib
import json
import time
import urllib


class CrowdException(Exception):
    """Base class for Crowd exceptions."""


class CrowdNotFoundException(CrowdException):
    """An exception for 404 status."""


class CrowdForbiddenException(CrowdException):
    """An exception for 403 status."""


class CrowdUnauthorizedException(CrowdException):
    """ An exception for 401 status."""


class Crowd(object):
    """A Crowd object used to perform query operations."""

    def __init__(self, usr, pwd, url):
        self._cache = None
        self._usr = usr
        self._pwd = pwd
        assert url.startswith('https://')
        _, _, self._host, self._uri = url.split('/', 3)
        if ":" in self._host:
            self._host, self._port = self._host.split(':')
        else:
            self._port = 443

        self._auth = base64.encodestring(
            '%s:%s' % (self._usr, self._pwd)).strip()
        self._headers = {
            'Authorization': 'Basic ' + self._auth,
            'Accept': 'application/json'
        }

    @contextlib.contextmanager
    def cached(self, cache_file):
        '''provide a cached version of the api to speed things up'''
        with open(cache_file, 'a+') as f:
            try:
                fcntl.lockf(f, fcntl.LOCK_EX)
                f.seek(0)
                try:
                    self._cache = json.load(f)
                except:
                    self._cache = {}  # in case things are corrupted

                yield
                self._cache_clean()

                f.truncate(0)
                f.seek(0)
                json.dump(self._cache, f)
            finally:
                fcntl.lockf(f, fcntl.LOCK_UN)
                self._cache = None

    def _cached(self, email):
        if self._cache is None:
            return None
        user = self._cache.get(email)
        if user and user['expires'] < time.time():
                return None
        return user

    def _cache_user(self, email, valid):
        if self._cache is None:
            return None
        self._cache[email] = {
            'email': email,
            'valid': valid,
            'expires': time.time() + 60 * 60 * 24 * 7  # one week
        }

    def _cache_clean(self):
        # remove stale entries so file doesn't grow out of hand
        now = time.time()
        self._cache = {k: v for (k, v) in self._cache.iteritems()
                       if v['expires'] > now}

    def get_user_no_cache(self, email):
        params = {'username': email.encode('utf-8')}
        resource = '/user?{0}'.format(urllib.urlencode(params))
        try:
            resp = json.loads(self._get_rest_usermanagement(resource))
        except CrowdNotFoundException:
            resp = None
        return resp

    def user_valid(self, email):
        user = self._cached(email)
        if user:
            return user['valid']
        valid = self.get_user_no_cache(email) is not None
        self._cache_user(email, valid)
        return valid

    def get_group(self, grp):
        resource = '/group/user/nested?' + urllib.urlencode({'groupname': grp})
        users = json.loads(self._get_rest_usermanagement(resource))['users']
        return [x['name'] for x in users]

    def _get_rest_usermanagement(self, resource):
        api_url = "/{0}{1}".format(self._uri, resource)
        return self._get(api_url)

    def _get(self, api_url):
        connection = httplib.HTTPSConnection(self._host, self._port)
        connection.request("GET", api_url, headers=self._headers)
        resp = connection.getresponse()

        if resp.status == 200:
            return resp.read()
        elif resp.status == 404:
            raise CrowdNotFoundException('Resource not found')
        elif resp.status == 401:
            raise CrowdUnauthorizedException(
                'Authorization not granted to fulfill the request')
        elif resp.status == 403:
            raise CrowdForbiddenException(
                'Access forbidden to fulfill the request')
        else:
            raise CrowdException(
                'Unknown Crowd status {0}'.format(resp.status))