aboutsummaryrefslogtreecommitdiff
path: root/modules/private/buildbot/common/build_helpers.py
blob: ed7ada368016b085e4aa8573cfae4ed1958a3d37 (plain) (blame)
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
from buildbot.plugins import util, steps, schedulers
from buildbot_buildslist import BuildsList

__all__ = [
        "force_scheduler", "deploy_scheduler", "hook_scheduler",
        "clean_branch", "package_and_upload", "SlackStatusPush",
        "XMPPStatusPush"
        ]

# Small helpers"
@util.renderer
def clean_branch(props):
    if props.hasProperty("branch") and len(props["branch"]) > 0:
        return props["branch"].replace("/", "_")
    else:
        return "HEAD"

def package_and_upload(package, package_dest, package_url):
    return [
            steps.ShellCommand(name="build package",
                logEnviron=False, haltOnFailure=True, workdir="source",
                command=["git", "archive", "HEAD", "-o", package]),

            steps.FileUpload(name="upload package", workersrc=package,
                workdir="source", masterdest=package_dest,
                url=package_url, mode=0o644),

            steps.ShellCommand(name="cleanup package", logEnviron=False,
                haltOnFailure=True, workdir="source", alwaysRun=True,
                command=["rm", "-f", package]),
            ]

# Schedulers
def force_scheduler(name, builders):
    return schedulers.ForceScheduler(name=name,
        label="Force build", buttonName="Force build",
        reason=util.StringParameter(name="reason", label="Reason", default="Force build"),
        codebases=[
            util.CodebaseParameter("",
                branch=util.StringParameter(
                    name="branch", label="Git reference (tag, branch)", required=True),
                revision=util.FixedParameter(name="revision", default=""),
                repository=util.FixedParameter(name="repository", default=""),
                project=util.FixedParameter(name="project", default=""),
                ),
            ],
        username=util.FixedParameter(name="username", default="Web button"),
        builderNames=builders)

def deploy_scheduler(name, builders):
    return schedulers.ForceScheduler(name=name,
        builderNames=builders,
        label="Deploy built package", buttonName="Deploy",
        username=util.FixedParameter(name="username", default="Web button"),
        codebases=[
            util.CodebaseParameter(codebase="",
                branch=util.FixedParameter(name="branch", default=""),
                revision=util.FixedParameter(name="revision", default=""),
                repository=util.FixedParameter(name="repository", default=""),
                project=util.FixedParameter(name="project", default=""))],
        reason=util.FixedParameter(name="reason", default="Deploy"),
        properties=[
            util.ChoiceStringParameter(label="Environment",
                name="environment", default="integration",
                choices=["integration", "production"]),
            BuildsList(label="Build to deploy", name="build"),
            ]
        )

def hook_scheduler(project, timer=10):
    return schedulers.AnyBranchScheduler(
            change_filter=util.ChangeFilter(category="hooks", project=project),
            name=project, treeStableTimer=timer, builderNames=["{}_build".format(project)])

# Slack/XMPP status push
from buildbot.reporters.http import HttpStatusPushBase
from twisted.internet import defer
from twisted.python import log
from buildbot.util import httpclientservice
from buildbot.reporters import utils
from buildbot.process import results
from twisted.words.protocols.jabber.jid import JID
from wokkel import client, xmppim
from functools import partial

class SlackStatusPush(HttpStatusPushBase):
    name = "SlackStatusPush"

    @defer.inlineCallbacks
    def reconfigService(self, serverUrl, **kwargs):
        yield HttpStatusPushBase.reconfigService(self, **kwargs)
        self._http = yield httpclientservice.HTTPClientService.getService(
            self.master, serverUrl)

    @defer.inlineCallbacks
    def send(self, build):
        yield utils.getDetailsForBuild(self.master, build, wantProperties=True)
        response = yield self._http.post("", json=self.format(build))
        if response.code != 200:
            log.msg("%s: unable to upload status: %s" %
                    (response.code, response.content))

    def format(self, build):
        colors = [
                "#36A64F", # success
                "#F1E903", # warnings
                "#DA0505", # failure
                "#FFFFFF", # skipped
                "#000000", # exception
                "#FFFFFF", # retry
                "#D02CA9", # cancelled
                ]

        if "environment" in build["properties"]:
            msg = "{} environment".format(build["properties"]["environment"][0])
            if "build" in build["properties"]:
                msg = "of archive {} in ".format(build["properties"]["build"][0]) + msg
        elif len(build["buildset"]["sourcestamps"][0]["branch"] or []) > 0:
            msg = "revision {}".format(build["buildset"]["sourcestamps"][0]["branch"])
        else:
            msg = "build"

        if build["complete"]:
            timedelta = int((build["complete_at"] - build["started_at"]).total_seconds())
            hours, rest = divmod(timedelta, 3600)
            minutes, seconds = divmod(rest, 60)
            if hours > 0:
                duration = "{}h {}min {}s".format(hours, minutes, seconds)
            elif minutes > 0:
                duration = "{}min {}s".format(minutes, seconds)
            else:
                duration = "{}s".format(seconds)

            text = "Build <{}|{}> of {}'s {} was {} in {}.".format(
                    build["url"], build["buildid"],
                    build["builder"]["name"],
                    msg,
                    results.Results[build["results"]],
                    duration,
                    )
            fields = [
                    {
                        "title": "Build",
                        "value": "<{}|{}>".format(build["url"], build["buildid"]),
                        "short": True,
                        },
                    {
                        "title": "Project",
                        "value": build["builder"]["name"],
                        "short": True,
                        },
                    {
                        "title": "Build status",
                        "value": results.Results[build["results"]],
                        "short": True,
                        },
                    {
                        "title": "Build duration",
                        "value": duration,
                        "short": True,
                        },
                    ]
            if "environment" in build["properties"]:
                fields.append({
                        "title": "Environment",
                        "value": build["properties"]["environment"][0],
                        "short": True,
                    })
            if "build" in build["properties"]:
                fields.append({
                        "title": "Archive",
                        "value": build["properties"]["build"][0],
                        "short": True,
                    })
            attachments = [{
                    "fallback": "",
                    "color": colors[build["results"]],
                    "fields": fields
                    }]
        else:
            text = "Build <{}|{}> of {}'s {} started.".format(
                    build["url"], build["buildid"],
                    build["builder"]["name"],
                    msg,
                    )
            attachments = []

        return {
                "username": "Buildbot",
                "icon_url": "http://docs.buildbot.net/current/_static/icon.png",
                "text": text,
                "attachments": attachments,
                }

class XMPPStatusPush(HttpStatusPushBase):
    name = "XMPPStatusPush"

    @defer.inlineCallbacks
    def reconfigService(self, password, recipients, **kwargs):
        yield HttpStatusPushBase.reconfigService(self, **kwargs)
        self.password = password
        self.recipients = recipients

    @defer.inlineCallbacks
    def send(self, build):
        yield utils.getDetailsForBuild(self.master, build, wantProperties=True)
        body = self.format(build)
        factory = client.DeferredClientFactory(JID("notify_bot@immae.fr/buildbot"), self.password)
        d = client.clientCreator(factory)
        def send_message(recipient, stream):
            message = xmppim.Message(recipient=JID(recipient), body=body)
            message.stanzaType = 'chat'
            stream.send(message.toElement())
            # To allow chaining
            return stream
        for recipient in self.recipients:
            d.addCallback(partial(send_message, recipient))
        d.addCallback(lambda _: factory.streamManager.xmlstream.sendFooter())
        d.addErrback(log.err)

    def format(self, build):
        if "environment" in build["properties"]:
            msg = "{} environment".format(build["properties"]["environment"][0])
            if "build" in build["properties"]:
                msg = "of archive {} in ".format(build["properties"]["build"][0]) + msg
        elif len(build["buildset"]["sourcestamps"][0]["branch"] or []) > 0:
            msg = "revision {}".format(build["buildset"]["sourcestamps"][0]["branch"])
        else:
            msg = "build"

        if build["complete"]:
            timedelta = int((build["complete_at"] - build["started_at"]).total_seconds())
            hours, rest = divmod(timedelta, 3600)
            minutes, seconds = divmod(rest, 60)
            if hours > 0:
                duration = "{}h {}min {}s".format(hours, minutes, seconds)
            elif minutes > 0:
                duration = "{}min {}s".format(minutes, seconds)
            else:
                duration = "{}s".format(seconds)

            text = "Build {} ( {} ) of {}'s {} was {} in {}.".format(
                    build["buildid"], build["url"],
                    build["builder"]["name"],
                    msg,
                    results.Results[build["results"]],
                    duration,
                    )
        else:
            text = "Build {} ( {} ) of {}'s {} started.".format(
                    build["buildid"], build["url"],
                    build["builder"]["name"],
                    msg,
                    )

        return text