Completed
Push — master ( bae705...f2e2b4 )
by Dieter
01:21
created

buildtimetrend.validate_task_parameters()   B

Complexity

Conditions 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 4
dl 0
loc 23
rs 8.7972
1
# vim: set expandtab sw=4 ts=4:
2
"""
3
Service related methods.
4
5
Copyright (C) 2014-2015 Dieter Adriaenssens <[email protected]>
6
7
This file is part of buildtimetrend/python-lib
8
<https://github.com/buildtimetrend/python-lib/>
9
10
This program is free software: you can redistribute it and/or modify
11
it under the terms of the GNU Affero General Public License as published by
12
the Free Software Foundation, either version 3 of the License, or
13
any later version.
14
15
This program is distributed in the hope that it will be useful,
16
but WITHOUT ANY WARRANTY; without even the implied warranty of
17
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18
GNU Affero General Public License for more details.
19
20
You should have received a copy of the GNU Affero General Public License
21
along with this program. If not, see <http://www.gnu.org/licenses/>.
22
"""
23
24
from __future__ import division
25
import cgi
26
from buildtimetrend import logger
27
from buildtimetrend.settings import Settings
28
from buildtimetrend.keenio import has_build_id
29
from buildtimetrend.keenio import keen_is_writable
30
31
32
def is_repo_allowed(repo):
33
    """
34
    Check if repo is allowed.
35
36
    A repository name is checked against a list of denied and allowed repos.
37
    The 'denied_repo' check takes precendence over 'allowed_repo' check.
38
    The list of denied/allowed repos is defined with settings 'denied_repo'
39
    and 'allowed_repo'.
40
    If the settings are not defined,
41
    the repo is not checked against the denied/allowed lists.
42
    Both 'denied_repo' and 'allowed_repo' can have multiple values,
43
    if any of them matches a substring of the repo, the repo is denied/allowed.
44
45
    Parameters:
46
    -repo : repository name
47
    """
48
    if repo is None:
49
        logger.warning("Repo is not defined")
50
        return False
51
52
    denied_message = "Project '%s' is not allowed."
53
    denied_repo = Settings().get_setting("denied_repo")
54
    allowed_repo = Settings().get_setting("allowed_repo")
55
56
    if denied_repo is not None and \
57
            any(x in repo for x in denied_repo) or \
58
            allowed_repo is not None and \
59
            not any(x in repo for x in allowed_repo):
60
        logger.warning(denied_message, repo)
61
        return False
62
63
    return True
64
65
66
def format_duration(duration):
67
    """
68
    Format duration from seconds to hours, minutes and seconds.
69
70
    Parameters:
71
    - duration : duration in seconds
72
    """
73
    if not isinstance(duration, (float, int)) or duration < 0:
74
        return "unknown"
75
76
    # round duration
77
    duration = round(duration)
78
79
    seconds = int(duration % 60)
80
    duration = duration / 60
81
    format_string = "{:d}s".format(seconds)
82
83
    if duration >= 1:
84
        minutes = int(duration % 60)
85
        duration = duration / 60
86
        format_string = "{:d}m {:s}".format(minutes, format_string)
87
88
        if duration >= 1:
89
            hours = int(duration % 60)
90
            format_string = "{:d}h {:s}".format(hours, format_string)
91
92
    return format_string
93
94
95
def check_process_parameters(repo=None, build=None):
96
    """
97
    Process setup parameters.
98
99
    Deprecated : functionality is split into
100
    validate_travis_request() and validate_task_parameters()
101
102
    Check parameters (repo and build)
103
    Returns error message, None when all parameters are fine
104
    """
105
    ret_val = validate_travis_request(repo, build)
106
    if ret_val is not None:
107
        return ret_val
108
    return validate_task_parameters(repo, build)
109
110
111
def validate_travis_request(repo=None, build=None):
112
    """
113
    Validate repo and build parameters of travis web request.
114
115
    Check parameters (repo and build)
116
    Returns error message, None when all parameters are fine.
117
    """
118
    if repo is None or build is None:
119
        logger.warning("Repo or build number are not set")
120
        return "Repo or build are not set, format : " \
121
            "/travis/<repo_owner>/<repo_name>/<build>"
122
123
    # check if repo is allowed
124
    if not is_repo_allowed(repo):
125
        return "Project '{}' is not allowed.".format(cgi.escape(repo))
126
127
    return None
128
129
130
def validate_task_parameters(repo=None, build=None):
131
    """
132
    Validate repo and build parameters of process_travis_buildlog().
133
134
    Check parameters (repo and build)
135
    Returns error message, None when all parameters are fine.
136
    """
137
    if not keen_is_writable():
138
        return "Keen IO write key not set, no data was sent"
139
140
    try:
141
        if has_build_id(repo, build):
142
            template = "Build #{build} of project {repo} " \
143
                "already exists in database"
144
            return template.format(
145
                build=cgi.escape(str(build)), repo=cgi.escape(str(repo))
146
            )
147
    except Exception as msg:
148
        # Raise last exception again
149
        logger.error("Error checking if build exists : {}".format(msg))
150
        raise SystemError("Error checking if build exists.")
151
152
    return None
153