From 8d213e2b1c934f6861f76aad5eb7c11097fa97de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isma=C3=ABl=20Bouya?= Date: Wed, 22 May 2019 20:55:28 +0200 Subject: Move rest of the modules outside of nixops --- .../private/buildbot/projects/caldance/__init__.py | 190 +++++++++++++++++++++ 1 file changed, 190 insertions(+) create mode 100644 modules/private/buildbot/projects/caldance/__init__.py (limited to 'modules/private/buildbot/projects/caldance') diff --git a/modules/private/buildbot/projects/caldance/__init__.py b/modules/private/buildbot/projects/caldance/__init__.py new file mode 100644 index 0000000..2c0bad5 --- /dev/null +++ b/modules/private/buildbot/projects/caldance/__init__.py @@ -0,0 +1,190 @@ +from buildbot.plugins import * +from buildbot_common.build_helpers import * +import os +from buildbot.util import bytes2unicode +import json + +__all__ = [ "configure", "E" ] + +class E(): + PROJECT = "caldance" + BUILDBOT_URL = "https://git.immae.eu/buildbot/{}/".format(PROJECT) + SOCKET = "unix:/run/buildbot/{}.sock".format(PROJECT) + PB_SOCKET = "unix:address=/run/buildbot/{}_pb.sock".format(PROJECT) + RELEASE_PATH = "/var/lib/ftp/release.immae.eu/{}".format(PROJECT) + RELEASE_URL = "https://release.immae.eu/{}".format(PROJECT) + GIT_URL = "gitolite@git.immae.eu:perso/simon_descarpentries/www.cal-dance.com" + SSH_KEY_PATH = "/var/lib/buildbot/buildbot_key" + SSH_HOST_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIFbhFTl2A2RJn5L51yxJM4XfCS2ZaiSX/jo9jFSdghF" + LDAP_HOST = "ldap.immae.eu" + LDAP_DN = "cn=buildbot,ou=services,dc=immae,dc=eu" + LDAP_ROLES_BASE = "ou=roles,ou=hosts,dc=immae,dc=eu" + XMPP_RECIPIENTS = os.environ["BUILDBOT_XMPP_RECIPIENTS"].split(" ") + + PUPPET_HOST = { + "integration": "root@caldance.immae.eu", + } + + # master.cfg + SECRETS_FILE = os.getcwd() + "/secrets" + LDAP_URL = "ldaps://ldap.immae.eu:636" + LDAP_ADMIN_USER = "cn=buildbot,ou=services,dc=immae,dc=eu" + LDAP_BASE = "dc=immae,dc=eu" + LDAP_PATTERN = "(uid=%(username)s)" + LDAP_GROUP_PATTERN = "(&(memberOf=cn=groups,ou=caldance,cn=buildbot,ou=services,dc=immae,dc=eu)(member=%(dn)s))" + TITLE_URL = "https://caldance.immae.eu" + TITLE = "Caldance" + +class CustomBase(webhooks.base): + def getChanges(self, request): + try: + content = request.content.read() + args = json.loads(bytes2unicode(content)) + except Exception as e: + raise ValueError("Error loading JSON: " + str(e)) + + args.setdefault("comments", "") + args.setdefault("repository", "") + args.setdefault("author", args.get("who", "unknown")) + + if args["category"] == "deploy_webhook": + args = { + "category": "deploy_webhook", + "comments": "", + "repository": "", + "author": "webhook", + "project": "Caldance", + "properties": { + "environment": args.get("environment", "integration"), + "build": "caldance_{}.tar.gz".format(args.get("build", "master")) + } + } + + return ([args], None) + +def deploy_hook_scheduler(project, timer=1): + return schedulers.AnyBranchScheduler( + change_filter=util.ChangeFilter(category="deploy_webhook", project=project), + name="{}_deploy".format(project), treeStableTimer=timer, builderNames=["{}_deploy".format(project)]) + +def configure(c): + c["buildbotURL"] = E.BUILDBOT_URL + c["www"]["port"] = E.SOCKET + + c["www"]["change_hook_dialects"]["base"] = { + "custom_class": CustomBase + } + c['workers'].append(worker.LocalWorker("generic-worker")) + c['workers'].append(worker.LocalWorker("deploy-worker")) + + c['schedulers'].append(hook_scheduler("Caldance", timer=1)) + c['schedulers'].append(force_scheduler("force_caldance", ["Caldance_build"])) + c['schedulers'].append(deploy_scheduler("deploy_caldance", ["Caldance_deploy"])) + c['schedulers'].append(deploy_hook_scheduler("Caldance", timer=1)) + + c['builders'].append(factory("caldance")) + + c['builders'].append(deploy_factory("caldance")) + + c['services'].append(SlackStatusPush( + name="slack_status_caldance", + builders=["Caldance_build", "Caldance_deploy"], + serverUrl=open(E.SECRETS_FILE + "/slack_webhook", "r").read().rstrip())) + c['services'].append(XMPPStatusPush( + name="xmpp_status_caldance", + builders=["Caldance_build", "Caldance_deploy"], + recipients=E.XMPP_RECIPIENTS, + password=open(E.SECRETS_FILE + "/notify_xmpp_password", "r").read().rstrip())) + +def factory(project, ignore_fails=False): + release_file = "{1}/{0}_%(kw:clean_branch)s.tar.gz" + + package = util.Interpolate("{0}_%(kw:clean_branch)s.tar.gz".format(project), clean_branch=clean_branch) + package_dest = util.Interpolate(release_file.format(project, E.RELEASE_PATH), clean_branch=clean_branch) + package_url = util.Interpolate(release_file.format(project, E.RELEASE_URL), clean_branch=clean_branch) + + factory = util.BuildFactory() + factory.addStep(steps.Git(logEnviron=False, repourl=E.GIT_URL, + sshPrivateKey=open(E.SSH_KEY_PATH).read().rstrip(), + sshHostKey=E.SSH_HOST_KEY, mode="full", method="copy")) + factory.addSteps(package_and_upload(package, package_dest, package_url)) + + return util.BuilderConfig( + name="{}_build".format(project.capitalize()), + workernames=["generic-worker"], factory=factory) + +def compute_build_infos(project): + @util.renderer + def compute(props): + import re, hashlib + build_file = props.getProperty("build") + package_dest = "{1}/{0}".format(build_file, E.RELEASE_PATH) + version = re.match(r"{0}_(.*).tar.gz".format(project), build_file).group(1) + with open(package_dest, "rb") as f: + sha = hashlib.sha256(f.read()).hexdigest() + return { + "build_version": version, + "build_hash": sha, + } + return compute + +@util.renderer +def puppet_host(props): + environment = props["environment"] if props.hasProperty("environment") else "integration" + return E.PUPPET_HOST.get(environment, "host.invalid") + +def deploy_factory(project): + package_dest = util.Interpolate("{0}/%(prop:build)s".format(E.RELEASE_PATH)) + + factory = util.BuildFactory() + factory.addStep(steps.MasterShellCommand(command=["test", "-f", package_dest])) + factory.addStep(steps.SetProperties(properties=compute_build_infos(project))) + factory.addStep(LdapPush(environment=util.Property("environment"), + project=project, build_version=util.Property("build_version"), + build_hash=util.Property("build_hash"), ldap_password=util.Secret("ldap"))) + factory.addStep(steps.MasterShellCommand(command=[ + "ssh", "-o", "UserKnownHostsFile=/dev/null", "-o", "StrictHostKeyChecking=no", "-o", "CheckHostIP=no", "-i", E.SSH_KEY_PATH, puppet_host])) + return util.BuilderConfig(name="{}_deploy".format(project.capitalize()), workernames=["deploy-worker"], factory=factory) + +from twisted.internet import defer +from buildbot.process.buildstep import FAILURE +from buildbot.process.buildstep import SUCCESS +from buildbot.process.buildstep import BuildStep + +class LdapPush(BuildStep): + name = "LdapPush" + renderables = ["environment", "project", "build_version", "build_hash", "ldap_password"] + + def __init__(self, **kwargs): + self.environment = kwargs.pop("environment") + self.project = kwargs.pop("project") + self.build_version = kwargs.pop("build_version") + self.build_hash = kwargs.pop("build_hash") + self.ldap_password = kwargs.pop("ldap_password") + self.ldap_host = kwargs.pop("ldap_host", E.LDAP_HOST) + super().__init__(**kwargs) + + def run(self): + import json + from ldap3 import Reader, Writer, Server, Connection, ObjectDef + server = Server(self.ldap_host) + conn = Connection(server, + user=E.LDAP_DN, + password=self.ldap_password) + conn.bind() + obj = ObjectDef("immaePuppetClass", conn) + r = Reader(conn, obj, + "cn=caldance.{},{}".format(self.environment, E.LDAP_ROLES_BASE)) + r.search() + if len(r) > 0: + w = Writer.from_cursor(r) + for value in w[0].immaePuppetJson.values: + config = json.loads(value) + if "role::caldance::{}_version".format(self.project) in config: + config["role::caldance::{}_version".format(self.project)] = self.build_version + config["role::caldance::{}_sha256".format(self.project)] = self.build_hash + w[0].immaePuppetJson -= value + w[0].immaePuppetJson += json.dumps(config, indent=" ") + w.commit() + return defer.succeed(SUCCESS) + return defer.succeed(FAILURE) -- cgit v1.2.3