diff --git a/.drone.env b/.drone.env deleted file mode 100644 index 9ccb5612549..00000000000 --- a/.drone.env +++ /dev/null @@ -1,3 +0,0 @@ -# The test runner source for UI tests -WEB_COMMITID=39d6215da6daa184cd2365966915a659bdbd2c8b -WEB_BRANCH=stable-12.3 diff --git a/.drone.star b/.drone.star deleted file mode 100644 index 35bba97746b..00000000000 --- a/.drone.star +++ /dev/null @@ -1,4091 +0,0 @@ -"""oCIS CI definition -""" - -# Production release tags -# NOTE: need to be updated if new production releases are determined -# - follow semver -# - omit 'v' prefix -PRODUCTION_RELEASE_TAGS = ["5.0", "7", "8"] - -# images -ALPINE_GIT = "alpine/git:latest" -APACHE_TIKA = "apache/tika:3.2.2.0-full" -CHKO_DOCKER_PUSHRM = "chko/docker-pushrm:1" -COLLABORA_CODE = "collabora/code:24.04.5.1.1" -AXLLENT_MAILPIT = "axllent/mailpit:v1.22.3" -MINIO_MC = "minio/mc:RELEASE.2021-10-07T04-19-58Z" -OC_CI_ALPINE = "owncloudci/alpine:latest" -OC_CI_BAZEL_BUILDIFIER = "owncloudci/bazel-buildifier:latest" -OC_CI_CLAMAVD = "owncloudci/clamavd" -OC_CI_DRONE_ANSIBLE = "owncloudci/drone-ansible:latest" -OC_CI_DRONE_SKIP_PIPELINE = "owncloudci/drone-skip-pipeline" -OC_CI_GOLANG = "owncloudci/golang:1.25" -OC_CI_NODEJS = "owncloudci/nodejs:%s" -OC_CI_PHP = "owncloudci/php:%s" -OC_CI_WAIT_FOR = "owncloudci/wait-for:latest" -OC_CS3_API_VALIDATOR = "owncloud/cs3api-validator:0.2.1" -OC_LITMUS = "owncloudci/litmus:latest" -OC_UBUNTU = "owncloud/ubuntu:20.04" -ONLYOFFICE_DOCUMENT_SERVER = "onlyoffice/documentserver:9.0.0" -PLUGINS_CODACY = "plugins/codacy:1" -PLUGINS_DOCKER = "plugins/docker:latest" -PLUGINS_GH_PAGES = "plugins/gh-pages:1" -PLUGINS_GITHUB_RELEASE = "plugins/github-release:1" -PLUGINS_GIT_ACTION = "plugins/git-action:1" -PLUGINS_MANIFEST = "plugins/manifest:1" - -# 1.4.0 is required due to minio compatibility -PLUGINS_S3 = "plugins/s3:1.4.0" -PLUGINS_S3_CACHE = "plugins/s3-cache:1" -REDIS = "redis:6-alpine" -SONARSOURCE_SONAR_SCANNER_CLI = "sonarsource/sonar-scanner-cli:11.0" -KEYCLOAK_IMAGE = "quay.io/keycloak/keycloak:26.2.5" -POSTGRES_ALPINE_IMAGE = "postgres:alpine3.18" -TRIVY_IMAGE = "aquasec/trivy:latest" -K3D_IMAGE = "ghcr.io/k3d-io/k3d:5-dind" -CODACY_COVERAGE_REPORTER = "codacy/codacy-coverage-reporter:latest" -CS3ORG_WOPISERVER = "cs3org/wopiserver:v10.4.0" -OC_CI_WOPI_VALIDATOR = "owncloudci/wopi-validator" - -# the hugo version needs to be the same as in owncloud.github.io -OC_CI_HUGO_STATIC_IMAGE = "hugomods/hugo:base-0.129.0" - -DEFAULT_PHP_VERSION = "8.4" -DEFAULT_NODEJS_VERSION = "24" - -dirs = { - "base": "/drone/src", - "web": "/drone/src/webTestRunner", - "zip": "/drone/src/zip", - "webZip": "/drone/src/zip/web.tar.gz", - "webPnpmZip": "/drone/src/zip/pnpm-store.tar.gz", - "gobinTar": "go-bin.tar.gz", - "gobinTarPath": "/drone/src/go-bin.tar.gz", - "ocisConfig": "tests/config/drone/ocis-config.json", - "ocis": "/srv/app/tmp/ocis", - "ocisRevaDataRoot": "/srv/app/tmp/ocis/owncloud/data", - "ocisWrapper": "/drone/src/tests/ociswrapper", - "bannedPasswordList": "tests/config/drone/banned-password-list.txt", - "ocmProviders": "tests/config/drone/providers.json", -} - -# OCIS URLs -OCIS_SERVER_NAME = "ocis-server" -OCIS_URL = "https://%s:9200" % OCIS_SERVER_NAME -OCIS_DOMAIN = "%s:9200" % OCIS_SERVER_NAME -FED_OCIS_SERVER_NAME = "federation-%s" % OCIS_SERVER_NAME -OCIS_FED_URL = "https://%s:10200" % FED_OCIS_SERVER_NAME -OCIS_FED_DOMAIN = "%s:10200" % FED_OCIS_SERVER_NAME - -# urls for k8s deployment -OCIS_URL_K8S = "https://%s" % OCIS_SERVER_NAME -OCIS_FED_URL_K8S = "https://%s" % FED_OCIS_SERVER_NAME - -# emails -EMAIL_PORT = "8025" -EMAIL_SMTP_PORT = "1025" -EMAIL_SMTP_HOST = "email" -EMAIL_SMTP_SENDER = "ownCloud " - -S3_CACHE_SERVER = "https://cache.owncloud.com" -S3_CACHE_BUCKET = "cache" -S3_PUBLIC_CACHE_BUCKET = "public" - -# configuration -config = { - "cs3ApiTests": { - "skip": False, - }, - "wopiValidatorTests": { - "skip": False, - }, - "k6LoadTests": { - "skip": False, - }, - "localApiTests": { - "contractAndLock": { - "suites": [ - "apiContract", - "apiLocks", - ], - "skip": False, - "k8s": True, - }, - "settingsAndNotification": { - "suites": [ - "apiSettings", - "apiNotification", - "apiCors", - ], - "skip": False, - "withRemotePhp": [False], - "k8s": True, - "emailNeeded": True, - "extraEnvironment": { - "EMAIL_HOST": EMAIL_SMTP_HOST, - "EMAIL_PORT": EMAIL_PORT, - }, - "extraServerEnvironment": { - "OCIS_ADD_RUN_SERVICES": "notifications", - "NOTIFICATIONS_SMTP_HOST": EMAIL_SMTP_HOST, - "NOTIFICATIONS_SMTP_PORT": EMAIL_SMTP_PORT, - "NOTIFICATIONS_SMTP_INSECURE": "true", - "NOTIFICATIONS_SMTP_SENDER": EMAIL_SMTP_SENDER, - "NOTIFICATIONS_DEBUG_ADDR": "0.0.0.0:9174", - }, - }, - "graphUser": { - "suites": [ - "apiGraphUser", - ], - "skip": False, - "withRemotePhp": [False], - "k8s": True, - }, - "spaces": { - "suites": [ - "apiSpaces", - ], - "skip": False, - "k8s": True, - }, - "spacesShares": { - "suites": [ - "apiSpacesShares", - ], - "skip": False, - "k8s": True, - }, - "davOperations": { - "suites": [ - "apiSpacesDavOperation", - "apiDownloads", - "apiAsyncUpload", - "apiDepthInfinity", - "apiArchiver", - "apiActivities", - ], - "skip": False, - "k8s": True, - }, - "groupAndSearch1": { - "suites": [ - "apiSearch1", - "apiGraph", - "apiGraphGroup", - ], - "skip": False, - "k8s": True, - }, - "search2": { - "suites": [ - "apiSearch2", - "apiSearchContent", - ], - "tikaNeeded": True, - "skip": False, - "k8s": True, - }, - "sharingNg1": { - "suites": [ - "apiSharingNgShares", - "apiReshare", - "apiSharingNgPermissions", - ], - "skip": False, - "withRemotePhp": [False], - "k8s": True, - }, - "sharingNgAdditionalShareRole": { - "suites": [ - "apiSharingNgAdditionalShareRole", - ], - "skip": False, - "k8s": True, - "withRemotePhp": [False], - }, - "sharingNgShareInvitation": { - "suites": [ - "apiSharingNgDriveInvitation", - "apiSharingNgItemInvitation", - ], - "skip": False, - "withRemotePhp": [False], - "k8s": True, - }, - "sharingNgLinkShare": { - "suites": [ - "apiSharingNgDriveLinkShare", - "apiSharingNgItemLinkShare", - "apiSharingNgLinkShareManagement", - ], - "skip": False, - "k8s": True, - "withRemotePhp": [False], - }, - "antivirus": { - "suites": [ - "apiAntivirus", - ], - "skip": False, - "k8s": True, - "antivirusNeeded": True, - "extraServerEnvironment": { - "ANTIVIRUS_SCANNER_TYPE": "clamav", - "ANTIVIRUS_CLAMAV_SOCKET": "tcp://clamav:3310", - "POSTPROCESSING_STEPS": "virusscan", - "OCIS_ADD_RUN_SERVICES": "antivirus", - "ANTIVIRUS_DEBUG_ADDR": "0.0.0.0:9277", - }, - }, - "ocm": { - "suites": [ - "apiOcm", - ], - "skip": False, - "k8s": True, - "withRemotePhp": [False], - "federationServer": True, - "emailNeeded": True, - "extraEnvironment": { - "EMAIL_HOST": EMAIL_SMTP_HOST, - "EMAIL_PORT": EMAIL_PORT, - }, - "extraServerEnvironment": { - "OCIS_ADD_RUN_SERVICES": "ocm,notifications", - "OCIS_ENABLE_OCM": True, - "OCM_OCM_INVITE_MANAGER_INSECURE": True, - "OCM_OCM_SHARE_PROVIDER_INSECURE": True, - "OCM_OCM_STORAGE_PROVIDER_INSECURE": True, - "OCM_OCM_PROVIDER_AUTHORIZER_PROVIDERS_FILE": "%s" % dirs["ocmProviders"], - # mail notifications - "NOTIFICATIONS_SMTP_HOST": EMAIL_SMTP_HOST, - "NOTIFICATIONS_SMTP_PORT": EMAIL_SMTP_PORT, - "NOTIFICATIONS_SMTP_INSECURE": "true", - "NOTIFICATIONS_SMTP_SENDER": EMAIL_SMTP_SENDER, - }, - }, - "authApp": { - "suites": [ - "apiAuthApp", - ], - "skip": False, - "k8s": True, - "withRemotePhp": [False], - "extraServerEnvironment": { - "OCIS_ADD_RUN_SERVICES": "auth-app", - "PROXY_ENABLE_APP_AUTH": True, - }, - }, - "wopi": { - "suites": [ - "apiCollaboration", - ], - "skip": False, - "k8s": True, - "withRemotePhp": [False], - "collaborationServiceNeeded": True, - "extraServerEnvironment": { - "GATEWAY_GRPC_ADDR": "0.0.0.0:9142", - }, - }, - "cliCommands": { - "suites": [ - "cliCommands", - "apiServiceAvailability", - ], - "skip": False, - "withRemotePhp": [False], - "antivirusNeeded": True, - "emailNeeded": True, - "extraEnvironment": { - "EMAIL_HOST": EMAIL_SMTP_HOST, - "EMAIL_PORT": EMAIL_PORT, - }, - "extraServerEnvironment": { - "NOTIFICATIONS_SMTP_HOST": EMAIL_SMTP_HOST, - "NOTIFICATIONS_SMTP_PORT": EMAIL_SMTP_PORT, - "NOTIFICATIONS_SMTP_INSECURE": "true", - "NOTIFICATIONS_SMTP_SENDER": EMAIL_SMTP_SENDER, - "NOTIFICATIONS_DEBUG_ADDR": "0.0.0.0:9174", - "ANTIVIRUS_SCANNER_TYPE": "clamav", - "ANTIVIRUS_CLAMAV_SOCKET": "tcp://clamav:3310", - "ANTIVIRUS_DEBUG_ADDR": "0.0.0.0:9277", - "OCIS_ADD_RUN_SERVICES": "antivirus,notifications", - }, - }, - }, - "coreApiTests": { - "1": { - "suites": [ - "coreApiAuth", - "coreApiCapabilities", - "coreApiFavorites", - "coreApiMain", - "coreApiVersions", - ], - "skip": False, - "withRemotePhp": [False], - "k8s": True, - }, - "2": { - "suites": [ - "coreApiShareManagementBasicToShares", - "coreApiShareManagementToShares", - ], - "skip": False, - "k8s": True, - "withRemotePhp": [False], - }, - "3": { - "suites": [ - "coreApiSharees", - "coreApiSharePublicLink2", - ], - "skip": False, - "withRemotePhp": [False], - "k8s": True, - }, - "4": { - "suites": [ - "coreApiShareOperationsToShares1", - "coreApiShareOperationsToShares2", - "coreApiSharePublicLink1", - "coreApiShareCreateSpecialToShares1", - "coreApiShareCreateSpecialToShares2", - "coreApiShareUpdateToShares", - ], - "skip": False, - "k8s": True, - "withRemotePhp": [False], - }, - "5": { - "suites": [ - "coreApiTrashbin", - "coreApiTrashbinRestore", - "coreApiWebdavEtagPropagation1", - "coreApiWebdavEtagPropagation2", - ], - "skip": False, - "k8s": True, - }, - "6": { - "suites": [ - "coreApiWebdavDelete", - "coreApiWebdavOperations", - "coreApiWebdavMove2", - ], - "skip": False, - "k8s": True, - }, - "7": { - "suites": [ - "coreApiWebdavProperties", - ], - "skip": False, - "k8s": True, - }, - "8": { - "suites": [ - "coreApiWebdavMove1", - "coreApiWebdavPreviews", - "coreApiWebdavUpload", - "coreApiWebdavUploadTUS", - ], - "skip": False, - "k8s": True, - }, - }, - "e2eTests": { - "part": { - "skip": False, - "totalParts": 4, # divide and run all suites in parts (divide pipelines) - "xsuites": ["search", "app-provider", "ocm", "keycloak"], # suites to skip - }, - "search": { - "skip": False, - "suites": ["search"], # suites to run - "tikaNeeded": True, - }, - "keycloak": { - "skip": False, - "suites": ["journeys", "keycloak"], - "keycloakNeeded": True, - }, - }, - "e2eMultiService": { - "testSuites": { - "skip": False, - "suites": [ - "smoke", - "shares", - "search", - "journeys", - "file-action", - "spaces", - ], - "tikaNeeded": True, - }, - }, - "binaryReleases": { - "os": ["linux", "darwin"], - }, - "dockerReleases": { - "architectures": ["arm64", "amd64"], - }, - "litmus": True, - "codestyle": True, -} - -# volume for steps to cache Go dependencies between steps of a pipeline -# GOPATH must be set to /go inside the image, which is the case -stepVolumeGo = \ - { - "name": "gopath", - "path": "/go", - } - -# volume for pipeline to cache Go dependencies between steps of a pipeline -# to be used in combination with stepVolumeGo -pipelineVolumeGo = \ - { - "name": "gopath", - "temp": {}, - } - -stepVolumeOcisStorage = \ - { - "name": "storage", - "path": "/root/.ocis", - } - -# minio mc environment variables -MINIO_MC_ENV = { - "CACHE_BUCKET": S3_CACHE_BUCKET, - "MC_HOST": S3_CACHE_SERVER, - "AWS_ACCESS_KEY_ID": { - "from_secret": "cache_s3_access_key", - }, - "AWS_SECRET_ACCESS_KEY": { - "from_secret": "cache_s3_secret_key", - }, -} - -DRONE_HTTP_PROXY_ENV = { - "HTTP_PROXY": { - "from_secret": "drone_http_proxy", - }, - "HTTPS_PROXY": { - "from_secret": "drone_http_proxy", - }, -} - -def pipelineDependsOn(pipeline, dependant_pipelines): - if "depends_on" in pipeline.keys(): - pipeline["depends_on"] = pipeline["depends_on"] + getPipelineNames(dependant_pipelines) - else: - pipeline["depends_on"] = getPipelineNames(dependant_pipelines) - return pipeline - -def pipelinesDependsOn(pipelines, dependant_pipelines): - pipes = [] - for pipeline in pipelines: - pipes.append(pipelineDependsOn(pipeline, dependant_pipelines)) - - return pipes - -def getPipelineNames(pipelines = []): - """getPipelineNames returns names of pipelines as a string array - - Args: - pipelines: array of drone pipelines - - Returns: - names of the given pipelines as string array - """ - names = [] - for pipeline in pipelines: - names.append(pipeline["name"]) - return names - -def main(ctx): - """main is the entrypoint for drone - - Args: - ctx: drone passes a context with information which the pipeline can be adapted to - - Returns: - none - """ - - pipelines = [] - - build_release_helpers = \ - changelog() + \ - documentation() + \ - licenseCheck(ctx) - - test_pipelines = \ - codestyle(ctx) + \ - checkGherkinLint(ctx) + \ - checkTestSuitesInExpectedFailures(ctx) + \ - buildWebCache(ctx) + \ - getGoBinForTesting(ctx) + \ - buildOcisBinaryForTesting(ctx) + \ - checkStarlark() + \ - build_release_helpers + \ - testOcisAndUploadResults(ctx) + \ - testPipelines(ctx) - - build_release_pipelines = \ - dockerReleases(ctx) + \ - binaryReleases(ctx) - - test_pipelines.append( - pipelineDependsOn( - purgeBuildArtifactCache(ctx), - testPipelines(ctx), - ), - ) - - test_pipelines.append( - pipelineDependsOn( - uploadAPITestCoverageReport(ctx), - testPipelines(ctx), - ), - ) - - pipelines = test_pipelines + build_release_pipelines - - # nightly Trivy security scan (non-blocking) - pipelines.append(trivyScan(ctx)) - - if ctx.build.event == "cron": - pipelines = \ - pipelines + \ - example_deploys(ctx) - else: - pipelines = \ - pipelines + \ - pipelinesDependsOn( - example_deploys(ctx), - pipelines, - ) - - pipelineSanityChecks(ctx, pipelines) - return pipelines - -def cachePipeline(name, steps): - return { - "kind": "pipeline", - "type": "docker", - "name": "build-%s-cache" % name, - "clone": { - "disable": True, - }, - "steps": steps, - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/tags/**", - "refs/pull/**", - ], - }, - } - -def buildWebCache(ctx): - return [ - cachePipeline("web", generateWebCache(ctx)), - cachePipeline("web-pnpm", generateWebPnpmCache(ctx)), - ] - -def testOcisAndUploadResults(ctx): - pipeline = testOcis(ctx) - - ###################################################################### - # The triggers have been disabled for now, since the govulncheck can # - # not silence single, acceptable vulnerabilities. # - # See https://github.com/owncloud/ocis/issues/9527 for more details. # - # FIXME: RE-ENABLE THIS ASAP!!! # - ###################################################################### - - scan_result_upload = uploadScanResults(ctx) - scan_result_upload["depends_on"] = getPipelineNames([pipeline]) - - #security_scan = scanOcis(ctx) - #return [security_scan, pipeline, scan_result_upload] - return [pipeline, scan_result_upload] - -def testPipelines(ctx): - pipelines = [] - - if config["litmus"]: - pipelines += litmus(ctx, "ocis") - - if "skip" not in config["cs3ApiTests"] or not config["cs3ApiTests"]["skip"]: - pipelines.append(cs3ApiTests(ctx, "ocis")) - if "skip" not in config["wopiValidatorTests"] or not config["wopiValidatorTests"]["skip"]: - pipelines.append(wopiValidatorTests(ctx, "ocis", "builtin")) - pipelines.append(wopiValidatorTests(ctx, "ocis", "cs3")) - - pipelines += localApiTestPipeline(ctx) - pipelines += coreApiTestPipeline(ctx) - - pipelines += e2eTestPipeline(ctx) + multiServiceE2ePipeline(ctx) - - if ("skip" not in config["k6LoadTests"] or not config["k6LoadTests"]["skip"]) and ("k6-test" in ctx.build.title.lower() or ctx.build.event == "cron"): - pipelines += k6LoadTests(ctx) - - return pipelines - -def getGoBinForTesting(ctx): - return [{ - "kind": "pipeline", - "type": "docker", - "name": "get-go-bin-cache", - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": skipIfUnchanged(ctx, "unit-tests") + - checkGoBinCache() + - cacheGoBin(), - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - }, - "volumes": [pipelineVolumeGo], - }] - -def checkGoBinCache(): - return [{ - "name": "check-go-bin-cache", - "image": MINIO_MC, - "environment": MINIO_MC_ENV, - "commands": [ - "mc alias set s3 $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", - "bash -x %s/tests/config/drone/check_go_bin_cache.sh %s %s" % (dirs["base"], dirs["base"], dirs["gobinTar"]), - ], - }] - -def cacheGoBin(): - return [ - { - "name": "bingo-get", - "image": OC_CI_GOLANG, - "commands": [ - "make bingo-update", - ], - "volumes": [stepVolumeGo], - "environment": DRONE_HTTP_PROXY_ENV, - }, - { - "name": "archive-go-bin", - "image": OC_UBUNTU, - "commands": [ - "tar -czvf %s /go/bin" % dirs["gobinTarPath"], - ], - "volumes": [stepVolumeGo], - }, - { - "name": "cache-go-bin", - "image": MINIO_MC, - "environment": MINIO_MC_ENV, - "commands": [ - # .bingo folder will change after 'bingo-get' - # so get the stored hash of a .bingo folder - "BINGO_HASH=$(cat %s/.bingo_hash)" % dirs["base"], - # cache using the minio client to the public bucket (long term bucket) - "mc alias set s3 $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", - "mc cp -r %s s3/$CACHE_BUCKET/ocis/go-bin/$BINGO_HASH" % (dirs["gobinTarPath"]), - ], - "volumes": [stepVolumeGo], - }, - ] - -def restoreGoBinCache(): - return [ - { - "name": "restore-go-bin-cache", - "image": MINIO_MC, - "environment": MINIO_MC_ENV, - "commands": [ - "BINGO_HASH=$(cat %s/.bingo/* | sha256sum | cut -d ' ' -f 1)" % dirs["base"], - "mc alias set s3 $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", - "mc cp -r -a s3/$CACHE_BUCKET/ocis/go-bin/$BINGO_HASH/%s %s" % (dirs["gobinTar"], dirs["base"]), - ], - "volumes": [stepVolumeGo], - }, - { - "name": "extract-go-bin-cache", - "image": OC_UBUNTU, - "commands": [ - "tar -xvmf %s -C /" % dirs["gobinTarPath"], - ], - "volumes": [stepVolumeGo], - }, - ] - -def testOcis(ctx): - steps = skipIfUnchanged(ctx, "unit-tests") + restoreGoBinCache() + makeGoGenerate("") + [ - { - "name": "golangci-lint", - "image": OC_CI_GOLANG, - "commands": [ - "mkdir -p cache/checkstyle", - "make ci-golangci-lint", - "mv checkstyle.xml cache/checkstyle/checkstyle.xml", - ], - "environment": DRONE_HTTP_PROXY_ENV, - "volumes": [stepVolumeGo], - }, - { - "name": "test", - "image": OC_CI_GOLANG, - "environment": DRONE_HTTP_PROXY_ENV, - "commands": [ - "mkdir -p cache/coverage", - "make test", - "mv coverage.out cache/coverage/", - ], - "volumes": [stepVolumeGo], - }, - { - "name": "scan-result-cache", - "image": PLUGINS_S3, - "settings": { - "endpoint": MINIO_MC_ENV["MC_HOST"], - "bucket": MINIO_MC_ENV["CACHE_BUCKET"], - "source": "cache/**/*", - "target": "%s/%s" % (ctx.repo.slug, ctx.build.commit + "-${DRONE_BUILD_NUMBER}"), - "path_style": True, - "access_key": MINIO_MC_ENV["AWS_ACCESS_KEY_ID"], - "secret_key": MINIO_MC_ENV["AWS_SECRET_ACCESS_KEY"], - }, - }, - ] - - return { - "kind": "pipeline", - "type": "docker", - "name": "linting_and_unitTests", - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": steps, - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - }, - "depends_on": getPipelineNames(getGoBinForTesting(ctx)), - "volumes": [pipelineVolumeGo], - } - -def scanOcis(ctx): - steps = skipIfUnchanged(ctx, "unit-tests") + restoreGoBinCache() + makeGoGenerate("") + [ - { - "name": "govulncheck", - "image": OC_CI_GOLANG, - "commands": [ - "make govulncheck", - ], - "environment": DRONE_HTTP_PROXY_ENV, - "volumes": [stepVolumeGo], - }, - ] - - return { - "kind": "pipeline", - "type": "docker", - "name": "go-vulnerability-scanning", - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": steps, - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - }, - "depends_on": getPipelineNames(getGoBinForTesting(ctx)), - "volumes": [pipelineVolumeGo], - } - -def buildOcisBinaryForTesting(ctx): - return [{ - "kind": "pipeline", - "type": "docker", - "name": "build_ocis_binary_for_testing", - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": skipIfUnchanged(ctx, "acceptance-tests") + - makeNodeGenerate("") + - makeGoGenerate("") + - build() + - buildDebug() + - rebuildBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin"), - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - }, - "volumes": [pipelineVolumeGo], - }] - -def uploadScanResults(ctx): - sonar_env = { - "SONAR_TOKEN": { - "from_secret": "sonar_token", - }, - } - if ctx.build.event == "pull_request": - sonar_env.update({ - "SONAR_PULL_REQUEST_BASE": "%s" % (ctx.build.target), - "SONAR_PULL_REQUEST_BRANCH": "%s" % (ctx.build.source), - "SONAR_PULL_REQUEST_KEY": "%s" % (ctx.build.ref.replace("refs/pull/", "").split("/")[0]), - }) - - fork_handling = [] - if ctx.build.source_repo != "" and ctx.build.source_repo != ctx.repo.slug: - fork_handling = [ - "git remote add fork https://github.com/%s.git" % (ctx.build.source_repo), - "git fetch fork", - ] - - return { - "kind": "pipeline", - "type": "docker", - "name": "upload-scan-results", - "platform": { - "os": "linux", - "arch": "amd64", - }, - "clone": { - "disable": True, # Sonarcloud does not apply issues on already merged branch - }, - "steps": [ - { - "name": "clone", - "image": ALPINE_GIT, - "commands": [ - # Always use the owncloud/ocis repository as base to have an up to date default branch. - # This is needed for the skipIfUnchanged step, since it references a commit on master (which could be absent on a fork) - "git clone https://github.com/%s.git ." % (ctx.repo.slug), - ] + fork_handling + - [ - "git checkout $DRONE_COMMIT", - ], - }, - ] + skipIfUnchanged(ctx, "unit-tests") + [ - { - "name": "sync-from-cache", - "image": MINIO_MC, - "environment": MINIO_MC_ENV, - "commands": [ - "mkdir -p cache", - "mc alias set cachebucket $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", - "mc mirror cachebucket/$CACHE_BUCKET/%s/%s/cache cache/ || true" % (ctx.repo.slug, ctx.build.commit + "-${DRONE_BUILD_NUMBER}"), - ], - }, - { - "name": "codacy", - "image": CODACY_COVERAGE_REPORTER, - "environment": { - "CODACY_PROJECT_TOKEN": { - "from_secret": "codacy_token", - }, - }, - "commands": [ - "/app/codacy-coverage-reporter report --force-coverage-parser go -r cache/coverage/coverage.out", - ], - }, - { - "name": "sonarcloud", - "image": SONARSOURCE_SONAR_SCANNER_CLI, - "environment": sonar_env, - }, - { - "name": "purge-cache", - "image": MINIO_MC, - "environment": MINIO_MC_ENV, - "commands": [ - "mc alias set cachebucket $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", - "mc rm --recursive --force cachebucket/$CACHE_BUCKET/%s/%s/cache || true" % (ctx.repo.slug, ctx.build.commit + "-${DRONE_BUILD_NUMBER}"), - ], - }, - ], - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - "status": [ - "success", - "failure", - ], - }, - } - -def vendorbinCodestyle(phpVersion): - return [{ - "name": "vendorbin-codestyle", - "image": OC_CI_PHP % phpVersion, - "environment": { - "COMPOSER_HOME": "%s/.cache/composer" % dirs["base"], - }, - "commands": [ - "make vendor-bin-codestyle", - ], - }] - -def vendorbinCodesniffer(phpVersion): - return [{ - "name": "vendorbin-codesniffer", - "image": OC_CI_PHP % phpVersion, - "environment": { - "COMPOSER_HOME": "%s/.cache/composer" % dirs["base"], - }, - "commands": [ - "make vendor-bin-codesniffer", - ], - }] - -def checkTestSuitesInExpectedFailures(ctx): - return [{ - "kind": "pipeline", - "type": "docker", - "name": "check-suites-in-expected-failures", - "steps": [ - { - "name": "check-suites", - "image": OC_CI_ALPINE, - "commands": [ - "%s/tests/acceptance/check-deleted-suites-in-expected-failure.sh" % dirs["base"], - ], - }, - ], - "trigger": { - "ref": [ - "refs/pull/**", - ], - }, - }] - -def checkGherkinLint(ctx): - return [{ - "kind": "pipeline", - "type": "docker", - "name": "check-gherkin-standard", - "steps": [ - { - "name": "lint-feature-files", - "image": OC_CI_NODEJS % DEFAULT_NODEJS_VERSION, - "commands": [ - "npm install -g @gherlint/gherlint@1.1.0", - "make test-gherkin-lint", - ], - }, - ], - "trigger": { - "ref": [ - "refs/pull/**", - ], - }, - }] - -def codestyle(ctx): - pipelines = [] - - if "codestyle" not in config: - return [] - - default = { - "phpVersions": [DEFAULT_PHP_VERSION], - } - - if "defaults" in config: - if "codestyle" in config["defaults"]: - for item in config["defaults"]["codestyle"]: - default[item] = config["defaults"]["codestyle"][item] - - codestyleConfig = config["codestyle"] - - if type(codestyleConfig) == "bool": - if codestyleConfig: - # the config has 'codestyle' true, so specify an empty dict that will get the defaults - codestyleConfig = {} - else: - return pipelines - - if len(codestyleConfig) == 0: - # 'codestyle' is an empty dict, so specify a single section that will get the defaults - codestyleConfig = {"doDefault": {}} - - for category, matrix in codestyleConfig.items(): - params = {} - for item in default: - params[item] = matrix[item] if item in matrix else default[item] - - for phpVersion in params["phpVersions"]: - name = "coding-standard-php%s" % phpVersion - - result = { - "kind": "pipeline", - "type": "docker", - "name": name, - "workspace": { - "base": "/drone", - "path": "src", - }, - "steps": skipIfUnchanged(ctx, "lint") + - vendorbinCodestyle(phpVersion) + - vendorbinCodesniffer(phpVersion) + - [ - { - "name": "php-style", - "image": OC_CI_PHP % phpVersion, - "commands": [ - "make test-php-style", - ], - }, - { - "name": "check-env-var-annotations", - "image": OC_CI_PHP % phpVersion, - "commands": [ - "make check-env-var-annotations", - ], - }, - ], - "depends_on": [], - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - }, - } - - pipelines.append(result) - - return pipelines - -def localApiTestPipeline(ctx): - pipelines = [] - - with_remote_php = [False] - if ctx.build.event == "cron" or "full-ci" in ctx.build.title.lower(): - with_remote_php.append(True) - - defaults = { - "suites": {}, - "skip": False, - "extraEnvironment": {}, - "extraServerEnvironment": {}, - "storages": ["ocis"], - "emailNeeded": False, - "antivirusNeeded": False, - "tikaNeeded": False, - "federationServer": False, - "collaborationServiceNeeded": False, - "extraCollaborationEnvironment": {}, - "withRemotePhp": with_remote_php, - "k8s": False, - } - - if "localApiTests" in config: - for name, matrix in config["localApiTests"].items(): - if "skip" not in matrix or not matrix["skip"]: - params = {} - for item in defaults: - params[item] = matrix[item] if item in matrix else defaults[item] - for storage in params["storages"]: - for run_with_remote_php in params["withRemotePhp"]: - run_on_k8s = params["k8s"] and ctx.build.event == "cron" - - #################### - # SETUP STEPS # - #################### - setup_steps = skipIfUnchanged(ctx, "acceptance-tests") - if params["tikaNeeded"]: - setup_steps += waitForServices("tika", ["tika:9998"]) - if params["antivirusNeeded"]: - setup_steps += waitForServices("clamav", ["clamav:3310"]) - if params["emailNeeded"]: - setup_steps += waitForServices("email", ["%s:%s" % (EMAIL_SMTP_HOST, EMAIL_PORT)]) - if params["collaborationServiceNeeded"]: - setup_steps += waitForServices("online-offices", ["collabora:9980", "onlyoffice:443", "fakeoffice:8080"]) - - if run_on_k8s: - enable_auth_app = False - if "OCIS_ADD_RUN_SERVICES" in params["extraServerEnvironment"]: - enable_auth_app = "auth-app" in params["extraServerEnvironment"]["OCIS_ADD_RUN_SERVICES"] - setup_steps += ocisServerK8s( - params["federationServer"], - params["antivirusNeeded"], - params["emailNeeded"], - params["tikaNeeded"], - params["collaborationServiceNeeded"], - enable_auth_app, - ) - - if params["collaborationServiceNeeded"]: - setup_steps += exposeNodePortsK8s([ - ["collaboration-collabora", 9300], - ["collaboration-fakeoffice", 9300], - ["collaboration-onlyoffice", 9300], - ["collaboration-fakeoffice", 9304], - ]) - else: - setup_steps += restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin") - setup_steps += ocisServer( - storage, - extra_server_environment = params["extraServerEnvironment"], - with_wrapper = True, - tika_enabled = params["tikaNeeded"], - volumes = [stepVolumeOcisStorage], - ) - - if params["federationServer"]: - setup_steps += ocisServer( - storage, - deploy_type = "federation", - extra_server_environment = params["extraServerEnvironment"], - ) - if params["collaborationServiceNeeded"]: - setup_steps += wopiCollaborationService("fakeoffice") + \ - wopiCollaborationService("collabora") + \ - wopiCollaborationService("onlyoffice") + \ - ocisHealthCheck("wopi", ["wopi-collabora:9304", "wopi-onlyoffice:9304", "wopi-fakeoffice:9304"]) - - #################### - # SERVICES # - #################### - services = [] - if params["tikaNeeded"]: - services += tikaService() - if params["emailNeeded"]: - services += emailService() - if params["antivirusNeeded"]: - services += clamavService() - if params["collaborationServiceNeeded"]: - services += fakeOffice() + collaboraService() + onlyofficeService() - if run_on_k8s: - services += k3sCluster(ocm = params["federationServer"]) - if params["federationServer"]: - services += k3sCluster(name = FED_OCIS_SERVER_NAME, ocm = True) - - #################### - # PIPELINE # - #################### - pipeline_name = "%s-%s" % ("CLI" if name.startswith("cli") else "API", name) - if run_with_remote_php: - pipeline_name += "-withRemotePhp" - if run_on_k8s: - pipeline_name += "-k8s" - pipeline = { - "kind": "pipeline", - "type": "docker", - "name": pipeline_name, - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": setup_steps + - localApiTests( - name, - params["suites"], - storage, - params["extraEnvironment"], - run_with_remote_php, - k8s = run_on_k8s, - ) + - apiTestFailureLog() + - (generateCoverageFromAPITest(ctx, name) if not run_on_k8s else []), - "services": services, - "depends_on": [] if run_on_k8s else getPipelineNames(buildOcisBinaryForTesting(ctx)), - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - }, - "volumes": [{ - "name": "storage", - "temp": {}, - }], - } - pipelines.append(pipeline) - return pipelines - -def generateCoverageFromAPITest(ctx, name): - environment = { - "GOCOVERDIR": "reports", - } - - return [ - { - "name": "coverageReport-%s" % name, - "image": OC_CI_GOLANG, - "environment": environment, - "commands": [ - "go tool covdata percent -i=$GOCOVERDIR -o=coverage-%s.out" % name, - ], - }, - { - "name": "coverage-locate", - "image": OC_UBUNTU, - "commands": [ - "mkdir -p cache/acceptance/coverage/", - "mv coverage-%s.out cache/acceptance/coverage/" % name, - ], - }, - { - "name": "coverage-cache-1", - "image": PLUGINS_S3, - "settings": { - "endpoint": MINIO_MC_ENV["MC_HOST"], - "bucket": MINIO_MC_ENV["CACHE_BUCKET"], - "source": "cache/acceptance/coverage/coverage-%s.out" % name, - "target": "%s/%s/coverage" % (ctx.repo.slug, ctx.build.commit + "-${DRONE_BUILD_NUMBER}"), - "path_style": True, - "access_key": MINIO_MC_ENV["AWS_ACCESS_KEY_ID"], - "secret_key": MINIO_MC_ENV["AWS_SECRET_ACCESS_KEY"], - }, - }, - ] - -def localApiTests(name, suites, storage = "ocis", extra_environment = {}, with_remote_php = False, k8s = False): - test_dir = "%s/tests/acceptance" % dirs["base"] - expected_failures_file = "%s/expected-failures-localAPI-on-%s-storage.md" % (test_dir, storage.upper()) - wrapper_url = "http://%s:5200" % OCIS_SERVER_NAME - ocis_url = OCIS_URL - ocis_fed_url = OCIS_FED_URL - - if k8s: - ocis_url = OCIS_URL_K8S - ocis_fed_url = OCIS_FED_URL_K8S - wrapper_url = "http://ociswrapper:5200" - - environment = { - "TEST_SERVER_URL": ocis_url, - "TEST_SERVER_FED_URL": ocis_fed_url, - "OCIS_REVA_DATA_ROOT": "%s" % (dirs["ocisRevaDataRoot"] if storage == "owncloud" else ""), - "STORAGE_DRIVER": storage, - "BEHAT_SUITES": ",".join(suites), - "BEHAT_FILTER_TAGS": "~@skip&&~@skipOnGraph&&~@skipOnOcis-%s-Storage" % ("OC" if storage == "owncloud" else "OCIS"), - "EXPECTED_FAILURES_FILE": expected_failures_file, - "UPLOAD_DELETE_WAIT_TIME": "1" if storage == "owncloud" else 0, - "OCIS_WRAPPER_URL": wrapper_url, - "WITH_REMOTE_PHP": with_remote_php, - "COLLABORATION_SERVICE_URL": "http://ocis-server:9304" if k8s else "http://wopi-fakeoffice:9300", - "K8S": k8s, - } - - for item in extra_environment: - environment[item] = extra_environment[item] - - return [{ - "name": "localApiTests-%s" % name, - "image": OC_CI_PHP % DEFAULT_PHP_VERSION, - "environment": environment, - "commands": [ - # merge the expected failures - "" if with_remote_php else "cat %s/expected-failures-without-remotephp.md >> %s" % (test_dir, expected_failures_file), - "mkdir -p /etc/ocis/", - "make -C %s test-acceptance-api" % (dirs["base"]), - ], - "volumes": [stepVolumeOcisStorage], - }] - -def cs3ApiTests(ctx, storage): - return { - "kind": "pipeline", - "type": "docker", - "name": "cs3ApiTests", - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": skipIfUnchanged(ctx, "acceptance-tests") + - restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin") + - ocisServer(storage, [], [], "cs3api_validator") + - [ - { - "name": "cs3ApiTests", - "image": OC_CS3_API_VALIDATOR, - "environment": {}, - "commands": [ - "/usr/bin/cs3api-validator /var/lib/cs3api-validator --endpoint=%s:9142" % OCIS_SERVER_NAME, - ], - }, - ], - "depends_on": getPipelineNames(buildOcisBinaryForTesting(ctx)), - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - }, - } - -def wopiValidatorTests(ctx, storage, wopiServerType): - testgroups = [ - "BaseWopiViewing", - "CheckFileInfoSchema", - "EditFlows", - "Locks", - "AccessTokens", - "GetLock", - "ExtendedLockLength", - "FileVersion", - "Features", - ] - builtinOnlyTestGroups = [ - "PutRelativeFile", - "RenameFileIfCreateChildFileIsNotSupported", - ] - - validatorTests = [] - wopiServer = [] - extra_server_environment = {} - - if wopiServerType == "cs3": - wopiServer = [ - { - "name": "wopi-fakeoffice", - "image": CS3ORG_WOPISERVER, - "detach": True, - "commands": [ - "cp %s/tests/config/drone/wopiserver.conf /etc/wopi/wopiserver.conf" % (dirs["base"]), - "echo 123 > /etc/wopi/wopisecret", - "/app/wopiserver.py", - ], - }, - ] - else: - extra_server_environment = { - "OCIS_EXCLUDE_RUN_SERVICES": "app-provider", - } - - wopiServer = wopiCollaborationService("fakeoffice") - - for testgroup in testgroups: - validatorTests.append({ - "name": "wopiValidatorTests-%s" % testgroup, - "image": OC_CI_WOPI_VALIDATOR, - "commands": [ - "export WOPI_TOKEN=$(cat accesstoken)", - "echo $WOPI_TOKEN", - "export WOPI_TTL=$(cat accesstokenttl)", - "echo $WOPI_TTL", - "export WOPI_SRC=$(cat wopisrc)", - "echo $WOPI_SRC", - "cd /app", - "/app/Microsoft.Office.WopiValidator -t $WOPI_TOKEN -w $WOPI_SRC -l $WOPI_TTL --testgroup %s" % testgroup, - ], - }) - if wopiServerType == "builtin": - for builtinOnlyGroup in builtinOnlyTestGroups: - validatorTests.append({ - "name": "wopiValidatorTests-%s" % builtinOnlyGroup, - "image": OC_CI_WOPI_VALIDATOR, - "commands": [ - "export WOPI_TOKEN=$(cat accesstoken)", - "echo $WOPI_TOKEN", - "export WOPI_TTL=$(cat accesstokenttl)", - "echo $WOPI_TTL", - "export WOPI_SRC=$(cat wopisrc)", - "echo $WOPI_SRC", - "cd /app", - "/app/Microsoft.Office.WopiValidator -s -t $WOPI_TOKEN -w $WOPI_SRC -l $WOPI_TTL --testgroup %s" % builtinOnlyGroup, - ], - }) - - return { - "kind": "pipeline", - "type": "docker", - "name": "wopiValidatorTests-%s" % wopiServerType, - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": skipIfUnchanged(ctx, "acceptance-tests") + - restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin") + - fakeOffice() + - waitForServices("fake-office", ["fakeoffice:8080"]) + - ocisServer(storage, deploy_type = "wopi_validator", extra_server_environment = extra_server_environment) + - wopiServer + - waitForServices("wopi-fakeoffice", ["wopi-fakeoffice:9300"]) + - [ - { - "name": "prepare-test-file", - "image": OC_CI_ALPINE, - "environment": {}, - "commands": [ - "curl -v -X PUT '%s/remote.php/webdav/test.wopitest' -k --fail --retry-connrefused --retry 7 --retry-all-errors -u admin:admin -D headers.txt" % OCIS_URL, - "cat headers.txt", - "export FILE_ID=$(cat headers.txt | sed -n -e 's/^.*Oc-Fileid: //p')", - "export URL=\"%s/app/open?app_name=FakeOffice&file_id=$FILE_ID\"" % OCIS_URL, - "export URL=$(echo $URL | tr -d '[:cntrl:]')", - "curl -v -X POST \"$URL\" -k --fail --retry-connrefused --retry 7 --retry-all-errors -u admin:admin > open.json", - "cat open.json", - "cat open.json | jq .form_parameters.access_token | tr -d '\"' > accesstoken", - "cat open.json | jq .form_parameters.access_token_ttl | tr -d '\"' > accesstokenttl", - "echo -n 'http://wopi-fakeoffice:9300/wopi/files/' > wopisrc", - "cat open.json | jq .app_url | sed -n -e 's/^.*files%2F//p' | tr -d '\"' >> wopisrc", - ], - }, - ] + - validatorTests, - "depends_on": getPipelineNames(buildOcisBinaryForTesting(ctx)), - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - }, - } - -def coreApiTestPipeline(ctx): - pipelines = [] - - with_remote_php = [False] - if ctx.build.event == "cron" or "full-ci" in ctx.build.title.lower(): - with_remote_php.append(True) - - defaults = { - "suites": {}, - "skip": False, - "extraEnvironment": {}, - "extraServerEnvironment": {}, - "storages": ["ocis"], - "emailNeeded": False, - "antivirusNeeded": False, - "tikaNeeded": False, - "withRemotePhp": with_remote_php, - "k8s": False, - } - test_dir = "%s/tests/acceptance" % dirs["base"] - - if "coreApiTests" not in config: - return pipelines - - for name, matrix in config["coreApiTests"].items(): - if "skip" not in matrix or not matrix["skip"]: - params = {} - for item in defaults: - params[item] = matrix[item] if item in matrix else defaults[item] - for storage in params["storages"]: - for run_with_remote_php in params["withRemotePhp"]: - filter_tags = "~@skipOnGraph&&~@skipOnOcis-%s-Storage" % ("OC" if storage == "owncloud" else "OCIS") - expected_failures_file = "%s/expected-failures-API-on-%s-storage.md" % (test_dir, storage.upper()) - run_on_k8s = params["k8s"] and ctx.build.event == "cron" - ocis_url = OCIS_URL - wrapper_url = "http://%s:5200" % OCIS_SERVER_NAME - - #################### - # SETUP STEPS # - #################### - setup_steps = skipIfUnchanged(ctx, "acceptance-tests") - if params["tikaNeeded"]: - setup_steps += waitForServices("tika", ["tika:9998"]) - if params["antivirusNeeded"]: - setup_steps += waitForServices("clamav", ["clamav:3310"]) - if params["emailNeeded"]: - setup_steps += waitForServices("email", ["%s:%s" % (EMAIL_SMTP_HOST, EMAIL_PORT)]) - - if run_on_k8s: - ocis_url = OCIS_URL_K8S - wrapper_url = "http://ociswrapper:5200" - - setup_steps += ocisServerK8s(antivirus = params["antivirusNeeded"], email = params["emailNeeded"]) - else: - setup_steps += restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin") - setup_steps += ocisServer( - storage, - extra_server_environment = params["extraServerEnvironment"], - with_wrapper = True, - tika_enabled = params["tikaNeeded"], - volumes = ([stepVolumeOcisStorage]), - ) - - #################### - # SERVICES # - #################### - services = [] - if params["tikaNeeded"]: - services += tikaService() - if params["emailNeeded"]: - services += emailService() - if params["antivirusNeeded"]: - services += clamavService() - if run_on_k8s: - services += k3sCluster() - - #################### - # PIPELINE # - #################### - pipeline = { - "kind": "pipeline", - "type": "docker", - "name": "Core-API-%s%s%s" % (name, "-withRemotePhp" if run_with_remote_php else "", "-k8s" if run_on_k8s else ""), - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": setup_steps + - [ - { - "name": "run-api-tests", - "image": OC_CI_PHP % DEFAULT_PHP_VERSION, - "environment": { - "TEST_SERVER_URL": ocis_url, - "OCIS_REVA_DATA_ROOT": "%s" % (dirs["ocisRevaDataRoot"] if storage == "owncloud" else ""), - "STORAGE_DRIVER": storage, - "BEHAT_FILTER_TAGS": filter_tags, - "BEHAT_SUITES": ",".join(params["suites"]), - "ACCEPTANCE_TEST_TYPE": "core-api", - "EXPECTED_FAILURES_FILE": expected_failures_file, - "UPLOAD_DELETE_WAIT_TIME": "1" if storage == "owncloud" else 0, - "OCIS_WRAPPER_URL": wrapper_url, - "WITH_REMOTE_PHP": run_with_remote_php, - "K8S": run_on_k8s, - }, - "commands": [ - # merge the expected failures - "" if run_with_remote_php else "cat %s/expected-failures-without-remotephp.md >> %s" % (test_dir, expected_failures_file), - "make -C %s test-acceptance-api" % (dirs["base"]), - ], - }, - ] + - apiTestFailureLog() + - ([] if run_on_k8s else generateCoverageFromAPITest(ctx, name)), - "services": services, - "depends_on": [] if run_on_k8s else getPipelineNames(buildOcisBinaryForTesting(ctx)), - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - }, - "volumes": [{ - "name": "storage", - "temp": {}, - }], - } - pipelines.append(pipeline) - return pipelines - -def e2eTestPipeline(ctx): - defaults = { - "skip": False, - "suites": [], - "xsuites": [], - "totalParts": 0, - "tikaNeeded": False, - "keycloakNeeded": False, - } - - extra_server_environment = { - "OCIS_PASSWORD_POLICY_BANNED_PASSWORDS_LIST": "%s" % dirs["bannedPasswordList"], - "GRAPH_AVAILABLE_ROLES": "b1e2218d-eef8-4d4c-b82d-0f1a1b48f3b5,a8d5fe5e-96e3-418d-825b-534dbdf22b99,fb6c3e19-e378-47e5-b277-9732f9de6e21,58c63c02-1d89-4572-916a-870abc5a1b7d,2d00ce52-1fc2-4dbc-8b95-a73b73395f5a,1c996275-f1c9-4e71-abdf-a42f6495e960,312c0871-5ef7-4b3a-85b6-0e4074c64049,aa97fe03-7980-45ac-9e50-b325749fd7e6,63e64e19-8d43-42ec-a738-2b6af2610efa", - "FRONTEND_CONFIGURABLE_NOTIFICATIONS": "true", - } - - e2e_trigger = { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/tags/**", - "refs/pull/**", - ], - } - - e2e_volumes = [{ - "name": "uploads", - "temp": {}, - }, { - "name": "configs", - "temp": {}, - }, { - "name": "gopath", - "temp": {}, - }] - - pipelines = [] - - if ("skip-e2e" in ctx.build.title.lower()): - return pipelines - - if (ctx.build.event == "tag"): - return pipelines - - for name, suite in config["e2eTests"].items(): - if "skip" in suite and suite["skip"]: - continue - - params = {} - for item in defaults: - params[item] = suite[item] if item in suite else defaults[item] - - e2e_args = "" - if params["totalParts"] > 0: - e2e_args = "--total-parts %d" % params["totalParts"] - elif params["suites"]: - e2e_args = "--suites %s" % ",".join(params["suites"]) - - # suites to skip - if params["xsuites"]: - e2e_args += " --xsuites %s" % ",".join(params["xsuites"]) - - test_environment = { - "BASE_URL_OCIS": OCIS_DOMAIN, - "HEADLESS": "true", - "RETRY": "1", - "REPORT_TRACING": "with-tracing" in ctx.build.title.lower(), - "SKIP_A11Y_TESTS": "true", - } - - # configs to setup ocis with keycloak - if params["keycloakNeeded"]: - extra_server_environment.update({ - "PROXY_AUTOPROVISION_ACCOUNTS": "true", - "PROXY_ROLE_ASSIGNMENT_DRIVER": "oidc", - "OCIS_OIDC_ISSUER": "https://keycloak:8443/realms/oCIS", - "PROXY_OIDC_REWRITE_WELLKNOWN": "true", - "WEB_OIDC_CLIENT_ID": "web", - "PROXY_USER_OIDC_CLAIM": "preferred_username", - "PROXY_USER_CS3_CLAIM": "username", - "OCIS_ADMIN_USER_ID": "", - "OCIS_EXCLUDE_RUN_SERVICES": "idp", - "GRAPH_ASSIGN_DEFAULT_USER_ROLE": "false", - "GRAPH_USERNAME_MATCH": "none", - "KEYCLOAK_DOMAIN": "keycloak:8443", - "PROXY_CSP_CONFIG_FILE_LOCATION": "%s/tests/config/drone/csp.yaml" % dirs["base"], - "IDM_CREATE_DEMO_USERS": False, - }) - test_environment.update({ - "KEYCLOAK": "true", - "KEYCLOAK_HOST": "keycloak:8443", - }) - - services = postgresService() if params["keycloakNeeded"] else [] - services += tikaService() if params["tikaNeeded"] else [] - - steps_before = \ - skipIfUnchanged(ctx, "e2e-tests") + \ - restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin/ocis") + \ - restoreWebCache() + \ - restoreWebPnpmCache() + \ - (waitForServices("tika", ["tika:9998"]) if params["tikaNeeded"] else []) + \ - (keycloakService() if params["keycloakNeeded"] else []) + \ - ocisServer(extra_server_environment = extra_server_environment, with_wrapper = not params["keycloakNeeded"], tika_enabled = params["tikaNeeded"], debug = False, external_idp = params["keycloakNeeded"]) - - step_e2e = { - "name": "e2e-tests", - "image": OC_CI_NODEJS % DEFAULT_NODEJS_VERSION, - "environment": test_environment, - "commands": [ - "cd %s/tests/e2e" % dirs["web"], - ], - } - - steps_after = uploadTracingResult(ctx) + \ - logTracingResults() - - if params["totalParts"]: - for index in range(params["totalParts"]): - run_part = index + 1 - run_e2e = {} - run_e2e.update(step_e2e) - run_e2e["commands"] = [ - "cd %s/tests/e2e" % dirs["web"], - "bash run-e2e.sh %s --run-part %d" % (e2e_args, run_part), - ] - pipelines.append({ - "kind": "pipeline", - "type": "docker", - "name": "e2e-tests-%s-%s" % (name, run_part), - "steps": steps_before + [run_e2e] + steps_after, - "depends_on": getPipelineNames(buildOcisBinaryForTesting(ctx) + buildWebCache(ctx)), - "trigger": e2e_trigger, - "volumes": e2e_volumes, - "services": services, - }) - else: - step_e2e["commands"].append("bash run-e2e.sh %s" % e2e_args) - pipelines.append({ - "kind": "pipeline", - "type": "docker", - "name": "e2e-tests-%s" % name, - "steps": steps_before + [step_e2e] + steps_after, - "depends_on": getPipelineNames(buildOcisBinaryForTesting(ctx) + buildWebCache(ctx)), - "trigger": e2e_trigger, - "volumes": e2e_volumes, - "services": services, - }) - - return pipelines - -def multiServiceE2ePipeline(ctx): - pipelines = [] - - defaults = { - "skip": False, - "suites": [], - "xsuites": [], - "tikaNeeded": False, - } - - e2e_trigger = { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - } - - if ("skip-e2e" in ctx.build.title.lower()): - return pipelines - - # run this pipeline only for cron jobs and full-ci PRs - if (not "full-ci" in ctx.build.title.lower() and ctx.build.event != "cron"): - return pipelines - - extra_server_environment = { - "OCIS_PASSWORD_POLICY_BANNED_PASSWORDS_LIST": "%s" % dirs["bannedPasswordList"], - "OCIS_JWT_SECRET": "some-ocis-jwt-secret", - "OCIS_SERVICE_ACCOUNT_ID": "service-account-id", - "OCIS_SERVICE_ACCOUNT_SECRET": "service-account-secret", - "OCIS_EXCLUDE_RUN_SERVICES": "storage-users", - "OCIS_GATEWAY_GRPC_ADDR": "0.0.0.0:9142", - "SETTINGS_GRPC_ADDR": "0.0.0.0:9191", - "GATEWAY_STORAGE_USERS_MOUNT_ID": "storage-users-id", - "GRAPH_AVAILABLE_ROLES": "b1e2218d-eef8-4d4c-b82d-0f1a1b48f3b5,a8d5fe5e-96e3-418d-825b-534dbdf22b99,fb6c3e19-e378-47e5-b277-9732f9de6e21,58c63c02-1d89-4572-916a-870abc5a1b7d,2d00ce52-1fc2-4dbc-8b95-a73b73395f5a,1c996275-f1c9-4e71-abdf-a42f6495e960,312c0871-5ef7-4b3a-85b6-0e4074c64049,aa97fe03-7980-45ac-9e50-b325749fd7e6,63e64e19-8d43-42ec-a738-2b6af2610efa", - "FRONTEND_CONFIGURABLE_NOTIFICATIONS": "true", - } - - storage_users_environment = { - "OCIS_CORS_ALLOW_ORIGINS": "%s,https://%s:9201" % (OCIS_URL, OCIS_SERVER_NAME), - "STORAGE_USERS_JWT_SECRET": "some-ocis-jwt-secret", - "STORAGE_USERS_MOUNT_ID": "storage-users-id", - "STORAGE_USERS_SERVICE_ACCOUNT_ID": "service-account-id", - "STORAGE_USERS_SERVICE_ACCOUNT_SECRET": "service-account-secret", - "STORAGE_USERS_GATEWAY_GRPC_ADDR": "%s:9142" % OCIS_SERVER_NAME, - "STORAGE_USERS_EVENTS_ENDPOINT": "%s:9233" % OCIS_SERVER_NAME, - "STORAGE_USERS_DATA_GATEWAY_URL": "%s/data" % OCIS_URL, - "OCIS_CACHE_STORE": "nats-js-kv", - "OCIS_CACHE_STORE_NODES": "%s:9233" % OCIS_SERVER_NAME, - "MICRO_REGISTRY_ADDRESS": "%s:9233" % OCIS_SERVER_NAME, - } - storage_users1_environment = { - "STORAGE_USERS_GRPC_ADDR": "storageusers1:9157", - "STORAGE_USERS_HTTP_ADDR": "storageusers1:9158", - "STORAGE_USERS_DEBUG_ADDR": "storageusers1:9159", - "STORAGE_USERS_DATA_SERVER_URL": "http://storageusers1:9158/data", - } - for item in storage_users_environment: - storage_users1_environment[item] = storage_users_environment[item] - - storage_users2_environment = { - "STORAGE_USERS_GRPC_ADDR": "storageusers2:9157", - "STORAGE_USERS_HTTP_ADDR": "storageusers2:9158", - "STORAGE_USERS_DEBUG_ADDR": "storageusers2:9159", - "STORAGE_USERS_DATA_SERVER_URL": "http://storageusers2:9158/data", - } - for item in storage_users_environment: - storage_users2_environment[item] = storage_users_environment[item] - - storage_users_services = startOcisService("storage-users", "storageusers1", storage_users1_environment, [stepVolumeOcisStorage]) + \ - startOcisService("storage-users", "storageusers2", storage_users2_environment, [stepVolumeOcisStorage]) + \ - ocisHealthCheck("storage-users", ["storageusers1:9159", "storageusers2:9159"]) - - for _, suite in config["e2eMultiService"].items(): - if "skip" in suite and suite["skip"]: - continue - - params = {} - for item in defaults: - params[item] = suite[item] if item in suite else defaults[item] - - e2e_args = "" - if params["suites"]: - e2e_args = "--suites %s" % ",".join(params["suites"]) - - # suites to skip - if params["xsuites"]: - e2e_args += " --xsuites %s" % ",".join(params["xsuites"]) - - steps = \ - skipIfUnchanged(ctx, "e2e-tests") + \ - restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin/ocis") + \ - restoreWebCache() + \ - restoreWebPnpmCache() + \ - waitForServices("tika", ["tika:9998"]) + \ - ocisServer(extra_server_environment = extra_server_environment, tika_enabled = params["tikaNeeded"], debug = False) + \ - storage_users_services + \ - [{ - "name": "e2e-tests", - "image": OC_CI_NODEJS % DEFAULT_NODEJS_VERSION, - "environment": { - "BASE_URL_OCIS": OCIS_DOMAIN, - "HEADLESS": "true", - "RETRY": "1", - "SKIP_A11Y_TESTS": "true", - }, - "commands": [ - "cd %s/tests/e2e" % dirs["web"], - "bash run-e2e.sh %s" % e2e_args, - ], - }] + \ - uploadTracingResult(ctx) + \ - logTracingResults() - - pipelines.append({ - "kind": "pipeline", - "type": "docker", - "name": "e2e-tests-multi-service", - "steps": steps, - "depends_on": getPipelineNames(buildOcisBinaryForTesting(ctx) + buildWebCache(ctx)), - "trigger": e2e_trigger, - "volumes": [ - { - "name": "storage", - "temp": {}, - }, - pipelineVolumeGo, - ], - "services": tikaService(), - }) - return pipelines - -def uploadTracingResult(ctx): - return [{ - "name": "upload-tracing-result", - "image": PLUGINS_S3, - "pull": "if-not-exists", - "settings": { - "bucket": S3_PUBLIC_CACHE_BUCKET, - "endpoint": S3_CACHE_SERVER, - "path_style": True, - "source": "webTestRunner/reports/e2e/playwright/tracing/**/*", - "strip_prefix": "webTestRunner/reports/e2e/playwright/tracing", - "target": "/${DRONE_REPO}/${DRONE_BUILD_NUMBER}/tracing", - }, - "environment": { - "AWS_ACCESS_KEY_ID": { - "from_secret": "cache_public_s3_access_key", - }, - "AWS_SECRET_ACCESS_KEY": { - "from_secret": "cache_public_s3_secret_key", - }, - }, - "when": { - "status": [ - "failure", - ], - "event": [ - "pull_request", - "cron", - ], - }, - }] - -def logTracingResults(): - return [{ - "name": "log-tracing-result", - "image": OC_UBUNTU, - "commands": [ - "cd %s/reports/e2e/playwright/tracing/" % dirs["web"], - 'echo "To see the trace, please open the following link in the console"', - 'for f in *.zip; do echo "npx playwright show-trace https://cache.owncloud.com/public/${DRONE_REPO}/${DRONE_BUILD_NUMBER}/tracing/$f \n"; done', - ], - "when": { - "status": [ - "failure", - ], - "event": [ - "pull_request", - "cron", - ], - }, - }] - -def dockerReleases(ctx): - pipelines = [] - docker_repos = [] - build_type = "daily" - - # dockerhub repo - # - "owncloud/ocis-rolling" - repo = ctx.repo.slug + "-rolling" - docker_repos.append(repo) - - # production release repo - if ctx.build.event == "tag": - tag = ctx.build.ref.replace("refs/tags/v", "").lower() - for prod_tag in PRODUCTION_RELEASE_TAGS: - if tag.startswith(prod_tag): - docker_repos.append(ctx.repo.slug) - break - - for repo in docker_repos: - repo_pipelines = [] - if ctx.build.event == "tag": - build_type = "rolling" if "rolling" in repo else "production" - - for arch in config["dockerReleases"]["architectures"]: - repo_pipelines.append(dockerRelease(ctx, arch, repo, build_type)) - - manifest = releaseDockerManifest(ctx, repo, build_type) - manifest["depends_on"] = getPipelineNames(repo_pipelines) - repo_pipelines.append(manifest) - - readme = releaseDockerReadme(ctx, repo, build_type) - readme["depends_on"] = getPipelineNames(repo_pipelines) - repo_pipelines.append(readme) - - pipelines.extend(repo_pipelines) - - return pipelines - -def dockerRelease(ctx, arch, repo, build_type): - build_args = [ - "REVISION=%s" % (ctx.build.commit), - "VERSION=%s" % (ctx.build.ref.replace("refs/tags/", "") if ctx.build.event == "tag" else "master"), - ] - depends_on = getPipelineNames(testOcisAndUploadResults(ctx) + testPipelines(ctx)) - - if ctx.build.event == "tag": - depends_on = [] - - return { - "kind": "pipeline", - "type": "docker", - "name": "docker-%s-%s" % (arch, build_type), - "platform": { - "os": "linux", - "arch": arch, - }, - "steps": skipIfUnchanged(ctx, "build-docker") + - makeNodeGenerate("") + - makeGoGenerate("") + [ - { - "name": "build", - "image": OC_CI_GOLANG, - "environment": DRONE_HTTP_PROXY_ENV, - "commands": [ - "make -C ocis release-linux-docker-%s ENABLE_VIPS=true" % (arch), - ], - }, - { - "name": "dryrun", - "image": PLUGINS_DOCKER, - "settings": { - "dry_run": True, - "context": "ocis", - "tags": "linux-%s" % (arch), - "dockerfile": "ocis/docker/Dockerfile.linux.%s" % (arch), - "repo": repo, - "build_args": build_args, - }, - "when": { - "ref": { - "include": [ - "refs/pull/**", - ], - }, - }, - }, - { - "name": "docker", - "image": PLUGINS_DOCKER, - "settings": { - "username": { - "from_secret": "docker_username", - }, - "password": { - "from_secret": "docker_password", - }, - "auto_tag": True, - "context": "ocis", - "auto_tag_suffix": "linux-%s" % (arch), - "dockerfile": "ocis/docker/Dockerfile.linux.%s" % (arch), - "repo": repo, - "build_args": build_args, - }, - "when": { - "ref": { - "exclude": [ - "refs/pull/**", - ], - }, - }, - }, - ], - "depends_on": depends_on, - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/tags/v*", - "refs/pull/**", - ], - }, - "volumes": [pipelineVolumeGo], - } - -def binaryReleases(ctx): - pipelines = [] - targets = [] - build_type = "daily" - - # uploads binary to https://download.owncloud.com/ocis/ocis/daily/ - target = "/ocis/%s/daily" % (ctx.repo.name.replace("ocis-", "")) - depends_on = getPipelineNames(testOcisAndUploadResults(ctx) + testPipelines(ctx)) - - if ctx.build.event == "tag": - depends_on = [] - - buildref = ctx.build.ref.replace("refs/tags/v", "").lower() - target_path = "/ocis/%s" % ctx.repo.name.replace("ocis-", "") - - if buildref.find("-") != -1: # "x.x.x-alpha", "x.x.x-beta", "x.x.x-rc" - folder = "testing" - target = "%s/%s/%s" % (target_path, folder, buildref) - targets.append(target) - build_type = "testing" - else: - # uploads binary to eg. https://download.owncloud.com/ocis/ocis/rolling/1.0.0/ - folder = "rolling" - target = "%s/%s/%s" % (target_path, folder, buildref) - targets.append(target) - - for prod_tag in PRODUCTION_RELEASE_TAGS: - if buildref.startswith(prod_tag): - # uploads binary to eg. https://download.owncloud.com/ocis/ocis/stable/2.0.0/ - folder = "stable" - target = "%s/%s/%s" % (target_path, folder, buildref) - targets.append(target) - break - - else: - targets.append(target) - - for target in targets: - if "rolling" in target: - build_type = "rolling" - elif "stable" in target: - build_type = "production" - elif "testing" in target: - build_type = "testing" - - for os in config["binaryReleases"]["os"]: - pipelines.append(binaryRelease(ctx, os, build_type, target, depends_on)) - - return pipelines - -def binaryRelease(ctx, arch, build_type, target, depends_on = []): - settings = { - "endpoint": { - "from_secret": "upload_s3_endpoint", - }, - "access_key": { - "from_secret": "upload_s3_access_key", - }, - "secret_key": { - "from_secret": "upload_s3_secret_key", - }, - "bucket": { - "from_secret": "upload_s3_bucket", - }, - "path_style": True, - "strip_prefix": "ocis/dist/release/", - "source": "ocis/dist/release/*", - "target": target, - } - - # [OCISDEV-266] Avoid cross-pipeline races on GitHub Release assets by: - # - Uploading only OS-scoped files from each pipeline - # - Copying and uploading the shared EULA only from the linux pipeline - artifacts = [] - if arch == "linux": - artifacts = [ - "ocis/dist/release/*-linux-*", - "ocis/dist/release/End-User-License-Agreement-for-ownCloud-Infinite-Scale.pdf", - ] - elif arch == "darwin": - artifacts = [ - "ocis/dist/release/*-darwin-*", - ] - - finish_commands = [ - "make -C ocis release-finish", - ] - if arch == "linux": - finish_commands.append("cp assets/End-User-License-Agreement-for-ownCloud-Infinite-Scale.pdf ocis/dist/release/") - - return { - "kind": "pipeline", - "type": "docker", - "name": "binaries-%s-%s" % (arch, build_type), - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": skipIfUnchanged(ctx, "build-binary") + - makeNodeGenerate("") + - makeGoGenerate("") + [ - { - "name": "build", - "image": OC_CI_GOLANG, - "environment": DRONE_HTTP_PROXY_ENV, - "commands": [ - "make -C ocis release-%s" % (arch), - ], - }, - { - "name": "finish", - "image": OC_CI_GOLANG, - "environment": DRONE_HTTP_PROXY_ENV, - "commands": finish_commands, - "when": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/tags/v*", - ], - }, - }, - { - "name": "upload", - "image": PLUGINS_S3, - "settings": settings, - "when": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/tags/v*", - ], - }, - }, - { - "name": "changelog", - "image": OC_CI_GOLANG, - "environment": DRONE_HTTP_PROXY_ENV, - "commands": [ - "make changelog CHANGELOG_VERSION=%s" % ctx.build.ref.replace("refs/tags/v", ""), - ], - "when": { - "ref": [ - "refs/tags/v*", - ], - }, - }, - { - "name": "release", - "image": PLUGINS_GITHUB_RELEASE, - "settings": { - "api_key": { - "from_secret": "github_token", - }, - "files": artifacts, - "title": ctx.build.ref.replace("refs/tags/v", ""), - "note": "ocis/dist/CHANGELOG.md", - "overwrite": True, - "prerelease": len(ctx.build.ref.split("-")) > 1, - }, - "when": { - "ref": [ - "refs/tags/v*", - ], - }, - }, - ], - "depends_on": depends_on, - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/tags/v*", - "refs/pull/**", - ], - }, - "volumes": [pipelineVolumeGo], - } - -def licenseCheck(ctx): - # uploads third-party-licenses to https://download.owncloud.com/ocis/ocis/daily/ - target = "/ocis/%s/daily" % (ctx.repo.name.replace("ocis-", "")) - if ctx.build.event == "tag": - # uploads third-party-licenses to eg. https://download.owncloud.com/ocis/ocis/1.0.0-beta9/ - folder = "stable" - buildref = ctx.build.ref.replace("refs/tags/v", "") - buildref = buildref.lower() - if buildref.find("-") != -1: # "x.x.x-alpha", "x.x.x-beta", "x.x.x-rc" - folder = "testing" - target = "/ocis/%s/%s/%s" % (ctx.repo.name.replace("ocis-", ""), folder, buildref) - - settings = { - "endpoint": { - "from_secret": "upload_s3_endpoint", - }, - "access_key": { - "from_secret": "upload_s3_access_key", - }, - "secret_key": { - "from_secret": "upload_s3_secret_key", - }, - "bucket": { - "from_secret": "upload_s3_bucket", - }, - "path_style": True, - "source": "third-party-licenses.tar.gz", - "target": target, - } - - return [{ - "kind": "pipeline", - "type": "docker", - "name": "check-licenses", - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": [ - { - "name": "node-check-licenses", - "image": OC_CI_NODEJS % DEFAULT_NODEJS_VERSION, - "commands": [ - "make ci-node-check-licenses", - ], - }, - { - "name": "node-save-licenses", - "image": OC_CI_NODEJS % DEFAULT_NODEJS_VERSION, - "commands": [ - "make ci-node-save-licenses", - ], - }, - { - "name": "go-check-licenses", - "image": OC_CI_GOLANG, - "environment": DRONE_HTTP_PROXY_ENV, - "commands": [ - "make ci-go-check-licenses", - ], - "volumes": [stepVolumeGo], - }, - { - "name": "go-save-licenses", - "image": OC_CI_GOLANG, - "environment": DRONE_HTTP_PROXY_ENV, - "commands": [ - "make ci-go-save-licenses", - ], - "volumes": [stepVolumeGo], - }, - { - "name": "tarball", - "image": OC_CI_ALPINE, - "commands": [ - "cd third-party-licenses && tar -czf ../third-party-licenses.tar.gz *", - ], - }, - { - "name": "upload", - "image": PLUGINS_S3, - "settings": settings, - "when": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/tags/v*", - ], - }, - }, - { - "name": "changelog", - "image": OC_CI_GOLANG, - "environment": DRONE_HTTP_PROXY_ENV, - "commands": [ - "make changelog CHANGELOG_VERSION=%s" % ctx.build.ref.replace("refs/tags/v", "").split("-")[0], - ], - "when": { - "ref": [ - "refs/tags/v*", - ], - }, - }, - { - "name": "release", - "image": PLUGINS_GITHUB_RELEASE, - "settings": { - "api_key": { - "from_secret": "github_token", - }, - "files": [ - "third-party-licenses.tar.gz", - ], - "title": ctx.build.ref.replace("refs/tags/v", ""), - "note": "ocis/dist/CHANGELOG.md", - "overwrite": True, - "prerelease": len(ctx.build.ref.split("-")) > 1, - }, - "when": { - "ref": [ - "refs/tags/v*", - ], - }, - }, - ], - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/tags/v*", - "refs/pull/**", - ], - }, - "volumes": [pipelineVolumeGo], - }] - -def releaseDockerManifest(ctx, repo, build_type): - spec = "manifest.tmpl" - spec_latest = "manifest-latest.tmpl" - if "rolling" not in repo: - spec = "manifest.production.tmpl" - spec_latest = "manifest.production-latest.tmpl" - - steps = [ - { - "name": "execute", - "image": PLUGINS_MANIFEST, - "settings": { - "username": { - "from_secret": "docker_username", - }, - "password": { - "from_secret": "docker_password", - }, - "spec": "ocis/docker/%s" % spec, - "auto_tag": True if ctx.build.event == "tag" else False, - "ignore_missing": True, - }, - }, - ] - if len(ctx.build.ref.split("-")) == 1: - steps.append( - { - "name": "execute-latest", - "image": PLUGINS_MANIFEST, - "settings": { - "username": { - "from_secret": "docker_username", - }, - "password": { - "from_secret": "docker_password", - }, - "spec": "ocis/docker/%s" % spec_latest, - "auto_tag": True, - "ignore_missing": True, - }, - "when": { - "ref": [ - "refs/tags/v*", - ], - }, - }, - ) - - return { - "kind": "pipeline", - "type": "docker", - "name": "manifest-%s" % build_type, - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": steps, - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/tags/v*", - ], - }, - } - -def changelog(): - return [{ - "kind": "pipeline", - "type": "docker", - "name": "changelog", - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": [ - { - "name": "generate", - "image": OC_CI_GOLANG, - "environment": DRONE_HTTP_PROXY_ENV, - "commands": [ - "make -C ocis changelog", - ], - }, - { - "name": "diff", - "image": OC_CI_ALPINE, - "commands": [ - "git diff", - ], - }, - { - "name": "output", - "image": OC_CI_ALPINE, - "commands": [ - "cat CHANGELOG.md", - ], - }, - { - "name": "publish", - "image": PLUGINS_GIT_ACTION, - "settings": { - "actions": [ - "commit", - "push", - ], - "message": "Automated changelog update [skip ci]", - "branch": "master", - "author_email": "devops@owncloud.com", - "author_name": "ownClouders", - "netrc_machine": "github.com", - "netrc_username": { - "from_secret": "github_username", - }, - "netrc_password": { - "from_secret": "github_token", - }, - }, - "when": { - "ref": { - "exclude": [ - "refs/pull/**", - ], - }, - }, - }, - ], - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - "event": { - "exclude": [ - "cron", - ], - }, - }, - }] - -def releaseDockerReadme(ctx, repo, build_type): - return { - "kind": "pipeline", - "type": "docker", - "name": "readme-%s" % build_type, - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": [ - { - "name": "execute", - "image": CHKO_DOCKER_PUSHRM, - "environment": { - "DOCKER_USER": { - "from_secret": "docker_username", - }, - "DOCKER_PASS": { - "from_secret": "docker_password", - }, - "PUSHRM_TARGET": repo, - "PUSHRM_SHORT": "Docker images for %s" % (ctx.repo.name), - "PUSHRM_FILE": "README.md", - }, - }, - ], - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/tags/v*", - ], - }, - } - -def documentation(): - return [{ - "kind": "pipeline", - "type": "docker", - "name": "documentation", - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": [ - { - "name": "docs-generate", - "image": OC_CI_GOLANG, - # "pull": "always", - "environment": DRONE_HTTP_PROXY_ENV, - "commands": ["make docs-generate"], - }, - { - "name": "docs-copy", - "image": OC_CI_GOLANG, - "environment": DRONE_HTTP_PROXY_ENV, - "commands": ["make docs-copy"], - }, - { - "name": "docs-hugo-drone-prep", - "image": OC_CI_GOLANG, - "environment": DRONE_HTTP_PROXY_ENV, - "commands": ["make docs-hugo-drone-prep"], - }, - { - "name": "docs-build", - "image": OC_CI_HUGO_STATIC_IMAGE, - "environment": DRONE_HTTP_PROXY_ENV, - "commands": [ - "cd hugo", - "hugo", - ], - }, - { - "name": "publish", - "image": PLUGINS_GH_PAGES, - "settings": { - "username": { - "from_secret": "github_username", - }, - "password": { - "from_secret": "github_token", - }, - "pages_directory": "docs/hugo/content/", - "copy_contents": "true", - "target_branch": "docs", - "delete": "true", - }, - "when": { - "ref": { - "exclude": [ - "refs/pull/**", - ], - }, - }, - }, - { - "name": "list and remove temporary files", - "image": OC_CI_ALPINE, - "commands": [ - "tree docs/hugo/public", - "rm -rf docs/hugo", - "rm -rf hugo", - ], - }, - ], - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - }, - }] - -def makeNodeGenerate(module): - if module == "": - make = "make" - else: - make = "make -C %s" % (module) - return [ - { - "name": "generate nodejs", - "image": OC_CI_NODEJS % DEFAULT_NODEJS_VERSION, - "environment": { - "CHROMEDRIVER_SKIP_DOWNLOAD": "true", # install fails on arm and chromedriver is a test only dependency - }, - "commands": [ - "pnpm config set store-dir ./.pnpm-store", - "retry -t 3 '%s ci-node-generate'" % (make), - ], - "volumes": [stepVolumeGo], - }, - ] - -def makeGoGenerate(module): - if module == "": - make = "make" - else: - make = "make -C %s" % (module) - return [ - { - "name": "generate go", - "image": OC_CI_GOLANG, - "commands": [ - "retry -t 3 '%s ci-go-generate'" % (make), - ], - "environment": DRONE_HTTP_PROXY_ENV, - "volumes": [stepVolumeGo], - }, - ] - -def ocisServer(storage = "ocis", volumes = [], depends_on = [], deploy_type = "", extra_server_environment = {}, with_wrapper = False, tika_enabled = False, debug = True, external_idp = False): - user = "0:0" - container_name = OCIS_SERVER_NAME - environment = { - "OCIS_URL": OCIS_URL, - "OCIS_CONFIG_DIR": "/root/.ocis/config", # needed for checking config later - "STORAGE_USERS_DRIVER": "%s" % (storage), - "PROXY_ENABLE_BASIC_AUTH": True, - "WEB_UI_CONFIG_FILE": "%s/%s" % (dirs["base"], dirs["ocisConfig"]), - "OCIS_LOG_LEVEL": "error", - "IDM_CREATE_DEMO_USERS": True, # needed for litmus and cs3api-validator tests - "IDM_ADMIN_PASSWORD": "admin", # override the random admin password from `ocis init` - "FRONTEND_SEARCH_MIN_LENGTH": "2", - "OCIS_ASYNC_UPLOADS": True, - "OCIS_EVENTS_ENABLE_TLS": False, - "NATS_NATS_HOST": "0.0.0.0", - "NATS_NATS_PORT": 9233, - "OCIS_JWT_SECRET": "some-ocis-jwt-secret", - "EVENTHISTORY_STORE": "memory", - "OCIS_TRANSLATION_PATH": "%s/tests/config/translations" % dirs["base"], - # debug addresses required for running services health tests - "ACTIVITYLOG_DEBUG_ADDR": "0.0.0.0:9197", - "APP_PROVIDER_DEBUG_ADDR": "0.0.0.0:9165", - "APP_REGISTRY_DEBUG_ADDR": "0.0.0.0:9243", - "AUTH_BASIC_DEBUG_ADDR": "0.0.0.0:9147", - "AUTH_MACHINE_DEBUG_ADDR": "0.0.0.0:9167", - "AUTH_SERVICE_DEBUG_ADDR": "0.0.0.0:9198", - "CLIENTLOG_DEBUG_ADDR": "0.0.0.0:9260", - "EVENTHISTORY_DEBUG_ADDR": "0.0.0.0:9270", - "FRONTEND_DEBUG_ADDR": "0.0.0.0:9141", - "GATEWAY_DEBUG_ADDR": "0.0.0.0:9143", - "GRAPH_DEBUG_ADDR": "0.0.0.0:9124", - "GROUPS_DEBUG_ADDR": "0.0.0.0:9161", - "IDM_DEBUG_ADDR": "0.0.0.0:9239", - "IDP_DEBUG_ADDR": "0.0.0.0:9134", - "INVITATIONS_DEBUG_ADDR": "0.0.0.0:9269", - "NATS_DEBUG_ADDR": "0.0.0.0:9234", - "OCDAV_DEBUG_ADDR": "0.0.0.0:9163", - "OCM_DEBUG_ADDR": "0.0.0.0:9281", - "OCS_DEBUG_ADDR": "0.0.0.0:9114", - "POSTPROCESSING_DEBUG_ADDR": "0.0.0.0:9255", - "PROXY_DEBUG_ADDR": "0.0.0.0:9205", - "SEARCH_DEBUG_ADDR": "0.0.0.0:9224", - "SETTINGS_DEBUG_ADDR": "0.0.0.0:9194", - "SHARING_DEBUG_ADDR": "0.0.0.0:9151", - "SSE_DEBUG_ADDR": "0.0.0.0:9139", - "STORAGE_PUBLICLINK_DEBUG_ADDR": "0.0.0.0:9179", - "STORAGE_SHARES_DEBUG_ADDR": "0.0.0.0:9156", - "STORAGE_SYSTEM_DEBUG_ADDR": "0.0.0.0:9217", - "STORAGE_USERS_DEBUG_ADDR": "0.0.0.0:9159", - "THUMBNAILS_DEBUG_ADDR": "0.0.0.0:9189", - "USERLOG_DEBUG_ADDR": "0.0.0.0:9214", - "USERS_DEBUG_ADDR": "0.0.0.0:9145", - "WEB_DEBUG_ADDR": "0.0.0.0:9104", - "WEBDAV_DEBUG_ADDR": "0.0.0.0:9119", - "WEBFINGER_DEBUG_ADDR": "0.0.0.0:9279", - "GOCOVERDIR": "reports", - } - - if deploy_type == "": - # fonts map for txt thumbnails (including unicode support) - environment["THUMBNAILS_TXT_FONTMAP_FILE"] = "%s/tests/config/drone/fontsMap.json" % (dirs["base"]) - - if deploy_type == "cs3api_validator": - environment["GATEWAY_GRPC_ADDR"] = "0.0.0.0:9142" # make gateway available to cs3api-validator - environment["OCIS_SHARING_PUBLIC_SHARE_MUST_HAVE_PASSWORD"] = False - - if deploy_type == "wopi_validator": - environment["GATEWAY_GRPC_ADDR"] = "0.0.0.0:9142" # make gateway available to wopi server - environment["APP_PROVIDER_EXTERNAL_ADDR"] = "com.owncloud.api.app-provider" - environment["APP_PROVIDER_DRIVER"] = "wopi" - environment["APP_PROVIDER_WOPI_APP_NAME"] = "FakeOffice" - environment["APP_PROVIDER_WOPI_APP_URL"] = "http://fakeoffice:8080" - environment["APP_PROVIDER_WOPI_INSECURE"] = "true" - environment["APP_PROVIDER_WOPI_WOPI_SERVER_EXTERNAL_URL"] = "http://wopi-fakeoffice:9300" - environment["APP_PROVIDER_WOPI_FOLDER_URL_BASE_URL"] = OCIS_URL - - if deploy_type == "federation": - environment["OCIS_URL"] = OCIS_FED_URL - environment["PROXY_HTTP_ADDR"] = OCIS_FED_DOMAIN - container_name = FED_OCIS_SERVER_NAME - - if tika_enabled: - environment["FRONTEND_FULL_TEXT_SEARCH_ENABLED"] = True - environment["SEARCH_EXTRACTOR_TYPE"] = "tika" - environment["SEARCH_EXTRACTOR_TIKA_TIKA_URL"] = "http://tika:9998" - environment["SEARCH_EXTRACTOR_CS3SOURCE_INSECURE"] = True - - for item in extra_server_environment: - environment[item] = extra_server_environment[item] - - ocis_bin = "ocis/bin/ocis" - if debug: - ocis_bin = "ocis/bin/ocis-debug" - - build_and_run_commands = [ - "%s server" % ocis_bin, - ] - if with_wrapper: - build_and_run_commands = [ - "make -C %s build" % dirs["ocisWrapper"], - "%s/bin/ociswrapper serve --bin %s --url %s --admin-username admin --admin-password admin" % (dirs["ocisWrapper"], ocis_bin, environment["OCIS_URL"]), - ] - - wait_for_ocis = waitForOcis(container_name, environment["OCIS_URL"], depends_on) - if external_idp: - wait_for_ocis = waitForServices("ocis", [OCIS_DOMAIN]) - - commands = [ - "mkdir -p $GOCOVERDIR", - "%s init --insecure true" % ocis_bin, - "cat $OCIS_CONFIG_DIR/ocis.yaml", - "cp tests/config/drone/app-registry.yaml /root/.ocis/config/app-registry.yaml", - ] + (build_and_run_commands) - - return [{ - "name": container_name, - "image": OC_CI_GOLANG, - "detach": True, - "environment": environment, - "user": user, - "commands": commands, - "volumes": volumes, - "depends_on": depends_on, - }] + wait_for_ocis - -def startOcisService(service = None, name = None, environment = {}, volumes = []): - """ - Starts an OCIS service in a detached container. - - Args: - service (str): The name of the service to start. - name (str): The name of the container. - environment (dict): The environment variables to set in the container. - volumes (list): The volumes to mount in the container. - - Returns: - list: A list of pipeline steps to start the service. - """ - - if not service: - return [] - if not name: - name = service - - return [ - { - "name": name, - "image": OC_CI_GOLANG, - "detach": True, - "environment": environment, - "commands": [ - "ocis/bin/ocis-debug %s server" % service, - ], - "volumes": volumes, - }, - ] - -def ocisServerK8s(federation = False, antivirus = False, email = False, tika = False, wopi = False, auth_app = False): - name = OCIS_SERVER_NAME - url = OCIS_URL_K8S - fed_name = FED_OCIS_SERVER_NAME - fed_url = OCIS_FED_URL_K8S - - steps = [] - expose_ext_server_step = [] - external_servers = [] - - environment = { - "ENABLE_ANTIVIRUS": antivirus, - "ENABLE_EMAIL": email, - "ENABLE_TIKA": tika, - "ENABLE_WOPI": wopi, - "ENABLE_OCM": federation, - "ENABLE_AUTH_APP": auth_app, - } - - if antivirus: - external_servers.append(["clamav", 3310]) - if tika: - external_servers.append(["tika", 9998]) - if email: - external_servers.append([EMAIL_SMTP_HOST, EMAIL_SMTP_PORT]) - if wopi: - external_servers += [["collabora", 9980], ["fakeoffice", 8080], ["onlyoffice", 443]] - - if external_servers: - expose_ext_server_step = exposeExternalServersK8s(external_servers) - - steps += prepareChartsK8s(environment) - - steps += waitK3sCluster(name) + \ - (waitK3sCluster(fed_name) if federation else []) + \ - setupConfigMapsK8s(name) + \ - (setupConfigMapsK8s(fed_name) if federation else []) + \ - expose_ext_server_step + \ - deployOcisK8s(name) + \ - (deployOcisK8s(fed_name) if federation else []) + \ - streamOcisLogsK8s(name) + \ - (streamOcisLogsK8s(fed_name) if federation else []) + \ - waitForOcis(name, url) + \ - (waitForOcis(fed_name, fed_url) if federation else []) + \ - ociswrapperK8s(name) - return steps - -def redis(): - return [ - { - "name": "redis", - "image": REDIS, - }, - ] - -def redisForOCStorage(storage = "ocis"): - if storage == "owncloud": - return redis() - else: - return - -def build(): - return [ - { - "name": "build", - "image": OC_CI_GOLANG, - "commands": [ - "retry -t 3 'make -C ocis build ENABLE_VIPS=true'", - ], - "environment": DRONE_HTTP_PROXY_ENV, - "volumes": [stepVolumeGo], - }, - ] - -def buildDebug(): - return [ - { - "name": "build debug binary", - "image": OC_CI_GOLANG, - "commands": [ - "retry -t 3 'make -C ocis build-debug ENABLE_VIPS=true'", - ], - "environment": DRONE_HTTP_PROXY_ENV, - "volumes": [stepVolumeGo], - }, - ] - -def skipIfUnchanged(ctx, type): - if ("full-ci" in ctx.build.title.lower() or ctx.build.event == "tag" or ctx.build.event == "cron"): - return [] - - base = [ - "^.github/.*", - "^.vscode/.*", - "^changelog/.*", - "^docs/.*", - "^deployments/.*", - "CHANGELOG.md", - "CONTRIBUTING.md", - "LICENSE", - "README.md", - ] - unit = [ - ".*_test.go$", - ] - acceptance = [ - "^tests/acceptance/.*", - ] - - skip = [] - if type == "acceptance-tests" or type == "e2e-tests" or type == "lint": - skip = base + unit - elif type == "unit-tests": - skip = base + acceptance - elif type == "build-binary" or type == "build-docker" or type == "litmus": - skip = base + unit + acceptance - elif type == "cache": - skip = base - else: - return [] - - return [{ - "name": "skip-if-unchanged", - "image": OC_CI_DRONE_SKIP_PIPELINE, - "settings": { - "ALLOW_SKIP_CHANGED": skip, - }, - "when": { - "event": [ - "pull_request", - ], - }, - }] - -def example_deploys(ctx): - on_merge_deploy = [ - "ocis_full/master.yml", - "ocis_full/onlyoffice-master.yml", - ] - nightly_deploy = [ - "ocis_ldap/rolling.yml", - "ocis_keycloak/rolling.yml", - "ocis_full/production.yml", - "ocis_full/rolling.yml", - "ocis_full/onlyoffice-rolling.yml", - "ocis_full/s3-rolling.yml", - ] - - # if on master branch: - configs = on_merge_deploy - rebuild = "false" - - if ctx.build.event == "tag": - configs = nightly_deploy - rebuild = "false" - - if ctx.build.event == "cron": - configs = on_merge_deploy + nightly_deploy - rebuild = "true" - - deploys = [] - for config in configs: - deploys.append(deploy(ctx, config, rebuild)) - - return deploys - -def deploy(ctx, config, rebuild): - return { - "kind": "pipeline", - "type": "docker", - "name": "deploy_%s" % (config), - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": [ - { - "name": "clone continuous deployment playbook", - "image": ALPINE_GIT, - "commands": [ - "cd deployments/continuous-deployment-config", - "git clone https://github.com/owncloud-devops/continuous-deployment.git", - ], - }, - { - "name": "deploy", - "image": OC_CI_DRONE_ANSIBLE, - "failure": "ignore", - "environment": { - "CONTINUOUS_DEPLOY_SERVERS_CONFIG": "../%s" % (config), - "REBUILD": "%s" % (rebuild), - "HCLOUD_API_TOKEN": { - "from_secret": "hcloud_api_token", - }, - "CLOUDFLARE_API_TOKEN": { - "from_secret": "cloudflare_api_token", - }, - }, - "settings": { - "playbook": "deployments/continuous-deployment-config/continuous-deployment/playbook-all.yml", - "galaxy": "deployments/continuous-deployment-config/continuous-deployment/requirements.yml", - "requirements": "deployments/continuous-deployment-config/continuous-deployment/py-requirements.txt", - "inventory": "localhost", - "private_key": { - "from_secret": "ssh_private_key", - }, - }, - }, - ], - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/tags/v*", - ], - }, - } - -def checkStarlark(): - return [{ - "kind": "pipeline", - "type": "docker", - "name": "check-starlark", - "steps": [ - { - "name": "format-check-starlark", - "image": OC_CI_BAZEL_BUILDIFIER, - "commands": [ - "buildifier --mode=check .drone.star", - ], - }, - { - "name": "show-diff", - "image": OC_CI_BAZEL_BUILDIFIER, - "commands": [ - "buildifier --mode=fix .drone.star", - "git diff", - ], - "when": { - "status": [ - "failure", - ], - }, - }, - ], - "depends_on": [], - "trigger": { - "ref": [ - "refs/pull/**", - ], - }, - }] - -def genericCache(name, action, mounts, cache_path): - rebuild = "false" - restore = "false" - if action == "rebuild": - rebuild = "true" - action = "rebuild" - else: - restore = "true" - action = "restore" - - step = { - "name": "%s_%s" % (action, name), - "image": PLUGINS_S3_CACHE, - "settings": { - "endpoint": MINIO_MC_ENV["MC_HOST"], - "rebuild": rebuild, - "restore": restore, - "mount": mounts, - "access_key": MINIO_MC_ENV["AWS_ACCESS_KEY_ID"], - "secret_key": MINIO_MC_ENV["AWS_SECRET_ACCESS_KEY"], - "filename": "%s.tar" % (name), - "path": cache_path, - "fallback_path": cache_path, - }, - } - return step - -def uploadAPITestCoverageReport(ctx): - sonar_env = { - "SONAR_TOKEN": { - "from_secret": "sonarcloud_acceptance_tests", - }, - } - - if ctx.build.event == "pull_request": - sonar_env.update({ - "SONAR_PULL_REQUEST_BASE": "%s" % (ctx.build.target), - "SONAR_PULL_REQUEST_BRANCH": "%s" % (ctx.build.source), - "SONAR_PULL_REQUEST_KEY": "%s" % (ctx.build.ref.replace("refs/pull/", "").split("/")[0]), - }) - - return { - "kind": "pipeline", - "type": "docker", - "name": "sonarcloud", - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": [ - { - "name": "sync-from-cache", - "image": MINIO_MC, - "environment": MINIO_MC_ENV, - "commands": [ - "mkdir -p results", - "mc alias set cache $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", - "mc mirror cache/$CACHE_BUCKET/%s/%s/coverage results/" % (ctx.repo.slug, ctx.build.commit + "-${DRONE_BUILD_NUMBER}"), - ], - }, - { - "name": "sonarcloud-properties", - "image": OC_UBUNTU, - "commands": [ - "mv sonar-project.properties sonar-project.properties.skip", - "mv tests/acceptance/sonar-project.properties sonar-project.properties", - ], - }, - { - "name": "sonarcloud", - "image": SONARSOURCE_SONAR_SCANNER_CLI, - "environment": sonar_env, - }, - { - "name": "purge-cache", - "image": MINIO_MC, - "environment": MINIO_MC_ENV, - "commands": [ - "mc alias set cache $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", - "mc rm --recursive --force cache/$CACHE_BUCKET/%s/%s" % (ctx.repo.slug, ctx.build.commit + "-${DRONE_BUILD_NUMBER}"), - ], - }, - ], - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - ], - "status": [ - "success", - ], - }, - } - -def genericCachePurge(flush_path): - return { - "kind": "pipeline", - "type": "docker", - "name": "purge_build_artifact_cache", - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": [ - { - "name": "purge-cache", - "image": PLUGINS_S3_CACHE, - "settings": { - "access_key": MINIO_MC_ENV["AWS_ACCESS_KEY_ID"], - "secret_key": MINIO_MC_ENV["AWS_SECRET_ACCESS_KEY"], - "endpoint": MINIO_MC_ENV["MC_HOST"], - "flush": True, - "flush_age": 1, - "flush_path": flush_path, - }, - }, - ], - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - "status": [ - "success", - "failure", - ], - }, - } - -def genericBuildArtifactCache(ctx, name, action, path): - if action == "rebuild" or action == "restore": - cache_path = "%s/%s/%s" % (S3_CACHE_BUCKET, ctx.repo.slug, ctx.build.commit + "-${DRONE_BUILD_NUMBER}") - name = "%s_build_artifact_cache" % (name) - return genericCache(name, action, [path], cache_path) - - if action == "purge": - flush_path = "%s/%s" % (S3_CACHE_BUCKET, ctx.repo.slug) - return genericCachePurge(flush_path) - return [] - -def restoreBuildArtifactCache(ctx, name, path): - return [genericBuildArtifactCache(ctx, name, "restore", path)] - -def rebuildBuildArtifactCache(ctx, name, path): - return [genericBuildArtifactCache(ctx, name, "rebuild", path)] - -def purgeBuildArtifactCache(ctx): - return genericBuildArtifactCache(ctx, "", "purge", []) - -def pipelineSanityChecks(ctx, pipelines): - """pipelineSanityChecks helps the CI developers to find errors before running it - - These sanity checks are only executed on when converting starlark to yaml. - Error outputs are only visible when the conversion is done with the drone cli. - - Args: - ctx: drone passes a context with information which the pipeline can be adapted to - pipelines: pipelines to be checked, normally you should run this on the return value of main() - - Returns: - none - """ - - # check if name length of pipeline and steps are exceeded. - max_name_length = 50 - for pipeline in pipelines: - pipeline_name = pipeline["name"] - if len(pipeline_name) > max_name_length: - print("Error: pipeline name %s is longer than 50 characters" % (pipeline_name)) - - for step in pipeline["steps"]: - step_name = step["name"] - if len(step_name) > max_name_length: - print("Error: step name %s in pipeline %s is longer than 50 characters" % (step_name, pipeline_name)) - - # check for non existing depends_on - possible_depends = [] - for pipeline in pipelines: - possible_depends.append(pipeline["name"]) - - for pipeline in pipelines: - if "depends_on" in pipeline.keys(): - for depends in pipeline["depends_on"]: - if not depends in possible_depends: - print("Error: depends_on %s for pipeline %s is not defined" % (depends, pipeline["name"])) - - # check for non declared volumes - for pipeline in pipelines: - pipeline_volumes = [] - if "volumes" in pipeline.keys(): - for volume in pipeline["volumes"]: - pipeline_volumes.append(volume["name"]) - - for step in pipeline["steps"]: - if "volumes" in step.keys(): - for volume in step["volumes"]: - if not volume["name"] in pipeline_volumes: - print("Warning: volume %s for step %s is not defined in pipeline %s" % (volume["name"], step["name"], pipeline["name"])) - - # list used docker images - print("") - print("List of used docker images:") - - images = {} - - for pipeline in pipelines: - for step in pipeline["steps"]: - image = step["image"] - if image in images.keys(): - images[image] = images[image] + 1 - else: - images[image] = 1 - - for image in images.keys(): - print(" %sx\t%s" % (images[image], image)) - -def litmus(ctx, storage): - pipelines = [] - - if (config["litmus"] == False): - return pipelines - - environment = { - "LITMUS_PASSWORD": "admin", - "LITMUS_USERNAME": "admin", - "TESTS": "basic copymove props http", - } - - litmusCommand = "/usr/local/bin/litmus-wrapper" - - result = { - "kind": "pipeline", - "type": "docker", - "name": "litmus", - "workspace": { - "base": "/drone", - "path": "src", - }, - "steps": skipIfUnchanged(ctx, "litmus") + - restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin") + - ocisServer(storage) + - setupForLitmus() + - [ - { - "name": "old-endpoint", - "image": OC_LITMUS, - "environment": environment, - "commands": [ - "source .env", - 'export LITMUS_URL="%s/remote.php/webdav"' % OCIS_URL, - litmusCommand, - ], - }, - { - "name": "new-endpoint", - "image": OC_LITMUS, - "environment": environment, - "commands": [ - "source .env", - 'export LITMUS_URL="%s/remote.php/dav/files/admin"' % OCIS_URL, - litmusCommand, - ], - }, - { - "name": "new-shared", - "image": OC_LITMUS, - "environment": environment, - "commands": [ - "source .env", - 'export LITMUS_URL="%s/remote.php/dav/files/admin/Shares/new_folder/"' % OCIS_URL, - litmusCommand, - ], - }, - { - "name": "old-shared", - "image": OC_LITMUS, - "environment": environment, - "commands": [ - "source .env", - 'export LITMUS_URL="%s/remote.php/webdav/Shares/new_folder/"' % OCIS_URL, - litmusCommand, - ], - }, - # { - # "name": "public-share", - # "image": OC_LITMUS, - # "environment": { - # "LITMUS_PASSWORD": "admin", - # "LITMUS_USERNAME": "admin", - # "TESTS": "basic copymove http", - # }, - # "commands": [ - # "source .env", - # "export LITMUS_URL='%s/remote.php/dav/public-files/'$PUBLIC_TOKEN" % OCIS_URL, - # litmusCommand, - # ], - # }, - { - "name": "spaces-endpoint", - "image": OC_LITMUS, - "environment": environment, - "commands": [ - "source .env", - "export LITMUS_URL='%s/remote.php/dav/spaces/'$SPACE_ID" % OCIS_URL, - litmusCommand, - ], - }, - ], - "services": redisForOCStorage(storage), - "depends_on": getPipelineNames(buildOcisBinaryForTesting(ctx)), - "trigger": { - "ref": [ - "refs/heads/master", - "refs/heads/stable-*", - "refs/pull/**", - ], - }, - } - pipelines.append(result) - - return pipelines - -def setupForLitmus(): - return [{ - "name": "setup-for-litmus", - "image": OC_UBUNTU, - "environment": { - "TEST_SERVER_URL": OCIS_URL, - }, - "commands": [ - "bash ./tests/config/drone/setup-for-litmus.sh", - "cat .env", - ], - }] - -def getDroneEnvAndCheckScript(ctx): - ocis_git_base_url = "https://raw.githubusercontent.com/owncloud/ocis" - path_to_drone_env = "%s/%s/.drone.env" % (ocis_git_base_url, ctx.build.commit) - path_to_check_script = "%s/%s/tests/config/drone/check_web_cache.sh" % (ocis_git_base_url, ctx.build.commit) - return { - "name": "get-drone-env-and-check-script", - "image": OC_UBUNTU, - "commands": [ - "curl -s -o .drone.env %s" % path_to_drone_env, - "curl -s -o check_web_cache.sh %s" % path_to_check_script, - ], - } - -def checkForWebCache(name): - return { - "name": "check-for-%s-cache" % name, - "image": MINIO_MC, - "environment": MINIO_MC_ENV, - "commands": [ - "mc alias set s3 $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", - "bash -x check_web_cache.sh web.tar.gz", - ], - } - -def cloneWeb(): - return { - "name": "clone-web", - "image": OC_CI_NODEJS % DEFAULT_NODEJS_VERSION, - "commands": [ - ". ./.drone.env", - "rm -rf %s" % dirs["web"], - "git clone -b $WEB_BRANCH --single-branch --no-tags https://github.com/owncloud/web.git %s" % dirs["web"], - "cd %s && git checkout $WEB_COMMITID" % dirs["web"], - ], - } - -def generateWebPnpmCache(ctx): - return [ - getDroneEnvAndCheckScript(ctx), - checkForWebCache("web-pnpm"), - cloneWeb(), - { - "name": "install-pnpm", - "image": OC_CI_NODEJS % DEFAULT_NODEJS_VERSION, - "commands": [ - "cd %s" % dirs["web"], - 'npm install --silent --global --force "$(jq -r ".packageManager" < package.json)"', - "pnpm config set store-dir ./.pnpm-store", - "retry -t 3 'pnpm install'", - ], - }, - { - "name": "zip-pnpm", - "image": OC_CI_NODEJS % DEFAULT_NODEJS_VERSION, - "commands": [ - # zip the pnpm deps before caching - "if [ ! -d '%s' ]; then mkdir -p %s; fi" % (dirs["zip"], dirs["zip"]), - "cd %s" % dirs["web"], - "tar -czvf %s .pnpm-store" % dirs["webPnpmZip"], - ], - }, - { - "name": "cache-pnpm", - "image": MINIO_MC, - "environment": MINIO_MC_ENV, - "commands": [ - "source ./.drone.env", - # cache using the minio/mc client to the public bucket (long term bucket) - "mc alias set s3 $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", - "mc cp -r -a %s s3/$CACHE_BUCKET/ocis/web-test-runner/$WEB_COMMITID" % dirs["webPnpmZip"], - ], - }, - ] - -def generateWebCache(ctx): - return [ - getDroneEnvAndCheckScript(ctx), - checkForWebCache("web"), - cloneWeb(), - { - "name": "zip-web", - "image": OC_UBUNTU, - "commands": [ - "if [ ! -d '%s' ]; then mkdir -p %s; fi" % (dirs["zip"], dirs["zip"]), - "tar -czvf %s webTestRunner" % dirs["webZip"], - ], - }, - { - "name": "cache-web", - "image": MINIO_MC, - "environment": MINIO_MC_ENV, - "commands": [ - "source ./.drone.env", - # cache using the minio/mc client to the 'owncloud' bucket (long term bucket) - "mc alias set s3 $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", - "mc cp -r -a %s s3/$CACHE_BUCKET/ocis/web-test-runner/$WEB_COMMITID" % dirs["webZip"], - ], - }, - ] - -def restoreWebCache(): - return [{ - "name": "restore-web-cache", - "image": MINIO_MC, - "environment": MINIO_MC_ENV, - "commands": [ - "source ./.drone.env", - "rm -rf %s" % dirs["web"], - "mkdir -p %s" % dirs["web"], - "mc alias set s3 $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", - "mc cp -r -a s3/$CACHE_BUCKET/ocis/web-test-runner/$WEB_COMMITID/web.tar.gz %s" % dirs["zip"], - ], - }, { - "name": "unzip-web-cache", - "image": OC_UBUNTU, - "commands": [ - "tar -xvf %s -C ." % dirs["webZip"], - ], - }] - -def restoreWebPnpmCache(): - return [{ - "name": "restore-web-pnpm-cache", - "image": MINIO_MC, - "environment": MINIO_MC_ENV, - "commands": [ - "source ./.drone.env", - "mc alias set s3 $MC_HOST $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY", - "mc cp -r -a s3/$CACHE_BUCKET/ocis/web-test-runner/$WEB_COMMITID/pnpm-store.tar.gz %s" % dirs["zip"], - ], - }, { - # we need to install again because the node_modules are not cached - "name": "unzip-and-install-pnpm", - "image": OC_CI_NODEJS % DEFAULT_NODEJS_VERSION, - "commands": [ - "cd %s" % dirs["web"], - "rm -rf .pnpm-store", - "tar -xvf %s" % dirs["webPnpmZip"], - 'npm install --silent --global --force "$(jq -r ".packageManager" < package.json)"', - "pnpm config set store-dir ./.pnpm-store", - "retry -t 3 'pnpm install'", - ], - }] - -def emailService(): - return [{ - "name": EMAIL_SMTP_HOST, - "image": AXLLENT_MAILPIT, - }] - -def clamavService(): - return [{ - "name": "clamav", - "image": OC_CI_CLAMAVD, - }] - -def fakeOffice(): - return [ - { - "name": "fakeoffice", - "image": OC_CI_ALPINE, - "detach": True, - "environment": {}, - "commands": [ - "sh %s/tests/config/drone/serve-hosting-discovery.sh" % (dirs["base"]), - ], - }, - ] - -def wopiCollaborationService(name, ocis_url = OCIS_URL): - service_name = "wopi-%s" % name - - environment = { - "OCIS_URL": ocis_url, - "MICRO_REGISTRY": "nats-js-kv", - "MICRO_REGISTRY_ADDRESS": "%s:9233" % OCIS_SERVER_NAME, - "COLLABORATION_LOG_LEVEL": "debug", - "COLLABORATION_GRPC_ADDR": "0.0.0.0:9301", - "COLLABORATION_HTTP_ADDR": "0.0.0.0:9300", - "COLLABORATION_DEBUG_ADDR": "0.0.0.0:9304", - "COLLABORATION_APP_PROOF_DISABLE": "true", - "COLLABORATION_APP_INSECURE": "true", - "COLLABORATION_CS3API_DATAGATEWAY_INSECURE": "true", - "OCIS_JWT_SECRET": "some-ocis-jwt-secret", - "COLLABORATION_WOPI_SECRET": "some-wopi-secret", - } - - if name == "collabora": - environment["COLLABORATION_APP_NAME"] = "Collabora" - environment["COLLABORATION_APP_PRODUCT"] = "Collabora" - environment["COLLABORATION_APP_ADDR"] = "https://collabora:9980" - environment["COLLABORATION_APP_ICON"] = "https://collabora:9980/favicon.ico" - elif name == "onlyoffice": - environment["COLLABORATION_APP_NAME"] = "OnlyOffice" - environment["COLLABORATION_APP_PRODUCT"] = "OnlyOffice" - environment["COLLABORATION_APP_ADDR"] = "https://onlyoffice" - environment["COLLABORATION_APP_ICON"] = "https://onlyoffice/web-apps/apps/documenteditor/main/resources/img/favicon.ico" - elif name == "fakeoffice": - environment["COLLABORATION_APP_NAME"] = "FakeOffice" - environment["COLLABORATION_APP_PRODUCT"] = "Microsoft" - environment["COLLABORATION_APP_ADDR"] = "http://fakeoffice:8080" - - environment["COLLABORATION_WOPI_SRC"] = "http://%s:9300" % service_name - - return startOcisService("collaboration", service_name, environment) - -def tikaService(): - return [{ - "name": "tika", - "type": "docker", - "image": APACHE_TIKA, - }] - -def apiTestFailureLog(): - return [{ - "name": "api-test-failure-logs", - "image": OC_CI_PHP % DEFAULT_PHP_VERSION, - "commands": [ - "cat %s/tests/acceptance/logs/failed.log" % dirs["base"], - ], - "when": { - "status": [ - "failure", - ], - }, - }] - -def k6LoadTests(ctx): - ocis_remote_environment = { - "SSH_OCIS_REMOTE": { - "from_secret": "k6_ssh_ocis_remote", - }, - "SSH_OCIS_USERNAME": { - "from_secret": "k6_ssh_ocis_user", - }, - "SSH_OCIS_PASSWORD": { - "from_secret": "k6_ssh_ocis_pass", - }, - "TEST_SERVER_URL": { - "from_secret": "k6_ssh_ocis_server_url", - }, - } - k6_remote_environment = { - "SSH_K6_REMOTE": { - "from_secret": "k6_ssh_k6_remote", - }, - "SSH_K6_USERNAME": { - "from_secret": "k6_ssh_k6_user", - }, - "SSH_K6_PASSWORD": { - "from_secret": "k6_ssh_k6_pass", - }, - } - environment = {} - environment.update(ocis_remote_environment) - environment.update(k6_remote_environment) - - if "skip" in config["k6LoadTests"] and config["k6LoadTests"]["skip"]: - return [] - - ocis_git_base_url = "https://raw.githubusercontent.com/owncloud/ocis" - script_link = "%s/%s/tests/config/drone/run_k6_tests.sh" % (ocis_git_base_url, ctx.build.commit) - - event_array = ["cron"] - trigger_ref = ["refs/heads/master"] - - if "k6-test" in ctx.build.title.lower(): - event_array.append("pull_request") - trigger_ref.append("refs/pull/**") - - return [{ - "kind": "pipeline", - "type": "docker", - "name": "k6-load-test", - "clone": { - "disable": True, - }, - "steps": [ - { - "name": "k6-load-test", - "image": OC_CI_ALPINE, - "environment": environment, - "commands": [ - "curl -s -o run_k6_tests.sh %s" % script_link, - "apk add --no-cache openssh-client sshpass", - "sh %s/run_k6_tests.sh" % (dirs["base"]), - ], - }, - { - "name": "ocis-log", - "image": OC_CI_ALPINE, - "environment": ocis_remote_environment, - "commands": [ - "curl -s -o run_k6_tests.sh %s" % script_link, - "apk add --no-cache openssh-client sshpass", - "sh %s/run_k6_tests.sh --ocis-log" % (dirs["base"]), - ], - "when": { - "status": [ - "success", - "failure", - ], - }, - }, - { - "name": "open-grafana-dashboard", - "image": OC_CI_ALPINE, - "commands": [ - "echo 'Grafana Dashboard: https://grafana.k6.infra.owncloud.works'", - ], - "when": { - "status": [ - "success", - "failure", - ], - }, - }, - ], - "depends_on": [], - "trigger": { - "event": event_array, - "ref": trigger_ref, - }, - }] - -def waitForOcis(name = "ocis", ocis_url = OCIS_URL, depends_on = []): - return [{ - "name": "wait-for-%s" % name, - "image": OC_CI_ALPINE, - "commands": [ - # wait for ocis-server to be ready (5 minutes) - "timeout 300 bash -c 'while [ $(curl -sk -uadmin:admin " + - "%s/graph/v1.0/users/admin " % ocis_url + - "-w %{http_code} -o /dev/null) != 200 ]; do sleep 1; done'", - ], - "depends_on": depends_on, - }] - -def waitForServices(name, services = []): - services = ",".join(services) - return [{ - "name": "wait-for-%s" % name, - "image": OC_CI_WAIT_FOR, - "commands": [ - "wait-for -it %s -t 300" % services, - ], - }] - -def ocisHealthCheck(name, services = []): - commands = [] - timeout = 300 - curl_command = ["timeout %s bash -c 'while [ $(curl -s %s/%s ", "-w %{http_code} -o /dev/null) != 200 ]; do sleep 1; done'"] - for service in services: - commands.append(curl_command[0] % (timeout, service, "healthz") + curl_command[1]) - commands.append(curl_command[0] % (timeout, service, "readyz") + curl_command[1]) - - return [{ - "name": "health-check-%s" % name, - "image": OC_CI_ALPINE, - "commands": commands, - }] - -def collaboraService(): - return [ - { - "name": "collabora", - "type": "docker", - "image": COLLABORA_CODE, - "detach": True, - "environment": { - "DONT_GEN_SSL_CERT": "set", - "extra_params": "--o:ssl.enable=true --o:ssl.termination=true --o:welcome.enable=false --o:net.frame_ancestors=https://%s" % OCIS_SERVER_NAME, - }, - "commands": [ - "coolconfig generate-proof-key", - "bash /start-collabora-online.sh", - ], - }, - ] - -def onlyofficeService(): - return [ - { - "name": "onlyoffice", - "type": "docker", - "image": ONLYOFFICE_DOCUMENT_SERVER, - "detach": True, - "environment": { - "WOPI_ENABLED": "true", - "USE_UNAUTHORIZED_STORAGE": "true", # self signed certificates - }, - "commands": [ - "cp %s/tests/config/drone/only-office.json /etc/onlyoffice/documentserver/local.json" % dirs["base"], - "openssl req -x509 -newkey rsa:4096 -keyout onlyoffice.key -out onlyoffice.crt -sha256 -days 365 -batch -nodes", - "mkdir -p /var/www/onlyoffice/Data/certs", - "cp onlyoffice.key /var/www/onlyoffice/Data/certs/", - "cp onlyoffice.crt /var/www/onlyoffice/Data/certs/", - "chmod 400 /var/www/onlyoffice/Data/certs/onlyoffice.key", - "/app/ds/run-document-server.sh", - ], - }, - ] - -def keycloakService(): - return [{ - "name": "generate-keycloak-certs", - "image": OC_CI_NODEJS % DEFAULT_NODEJS_VERSION, - "commands": [ - "cd %s" % dirs["base"], - "mkdir -p keycloak-certs", - "openssl req -x509 -newkey rsa:2048 -keyout keycloak-certs/keycloakkey.pem -out keycloak-certs/keycloakcrt.pem -nodes -days 365 -subj '/CN=keycloak'", - "chmod -R 777 keycloak-certs", - ], - }] + waitForServices("postgres", ["postgres:5432"]) + \ - [{ - "name": "keycloak", - "image": KEYCLOAK_IMAGE, - "detach": True, - "environment": { - "OCIS_DOMAIN": OCIS_URL, - "KC_HOSTNAME": "keycloak", - "KC_PORT": 8443, - "KC_DB": "postgres", - "KC_DB_URL": "jdbc:postgresql://postgres:5432/keycloak", - "KC_DB_USERNAME": "keycloak", - "KC_DB_PASSWORD": "keycloak", - "KC_FEATURES": "impersonation", - "KC_BOOTSTRAP_ADMIN_USERNAME": "admin", - "KC_BOOTSTRAP_ADMIN_PASSWORD": "admin", - "KC_HTTPS_CERTIFICATE_FILE": "%s/keycloak-certs/keycloakcrt.pem" % dirs["base"], - "KC_HTTPS_CERTIFICATE_KEY_FILE": "%s/keycloak-certs/keycloakkey.pem" % dirs["base"], - }, - "commands": [ - "mkdir -p /opt/keycloak/data/import", - "cp tests/config/drone/ocis-ci-realm.dist.json /opt/keycloak/data/import/oCIS-realm.json", - "/opt/keycloak/bin/kc.sh start-dev --proxy-headers xforwarded --spi-connections-http-client-default-disable-trust-manager=true --import-realm --health-enabled=true", - ], - }] + waitForServices("keycloak", ["keycloak:8443"]) - -def postgresService(): - return [ - { - "name": "postgres", - "image": POSTGRES_ALPINE_IMAGE, - "detach": True, - "environment": { - "POSTGRES_DB": "keycloak", - "POSTGRES_USER": "keycloak", - "POSTGRES_PASSWORD": "keycloak", - }, - }, - ] - -def trivyScan(ctx): - steps = [ - { - "name": "trivy-security-scan", - "image": TRIVY_IMAGE, - "commands": [ - # Trivy filesystem scan: recursively walks /drone/src workspace - # - Scans entire repository including compiled artifacts and dependencies - # - --exit-code 0: never fails the job regardless of findings - # - --no-progress: reduces log noise in CI - "trivy fs --exit-code 0 --severity HIGH,CRITICAL --no-progress /drone/src", - ], - "failure": "ignore", - }, - ] - - return { - "kind": "pipeline", - "type": "docker", - "name": "security-scan-trivy", - "platform": { - "os": "linux", - "arch": "amd64", - }, - "steps": steps, - "trigger": { - "ref": [ - "refs/heads/master", - "refs/tags/**", - "refs/pull/**", - ], - }, - } - -def k3sCluster(name = OCIS_SERVER_NAME, ocm = False): - peer_name = OCIS_SERVER_NAME if name == FED_OCIS_SERVER_NAME else FED_OCIS_SERVER_NAME - commands = [] - log_dir = "%s/logs-%s" % (dirs["base"], name) - - commands.extend([ - "nohup dockerd-entrypoint.sh &", - "until docker ps 2>&1 > /dev/null; do sleep 1s; done", - # create ocis logs dir - "mkdir -p %s && chmod 777 %s" % (log_dir, log_dir), - # create cluster - "k3d cluster create %s --api-port %s:33199 " % (name, name) + - "-p '80:80@loadbalancer' -p '443:443@loadbalancer' -p '9100-9399:30100-30399@loadbalancer' " + - "--k3s-arg '--tls-san=k3d@server:*' --k3s-arg '--disable=metrics-server@server:*' " + - "-v %s:/logs" % log_dir, - # wait for services to be ready - "until kubectl get deployment coredns -n kube-system -o go-template='{{.status.availableReplicas}}' | grep -v -e ''; do sleep 1s; done", - "until kubectl get deployment traefik -n kube-system -o go-template='{{.status.availableReplicas}}' | grep -v -e ''; do sleep 1s; done", - "k3d kubeconfig get %s > kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % (name, name), - "chmod 0600 kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % name, - "printf '@@@@@@@@@@@@@@@@@@@@@@@\\n@@@@ k3d is ready @@@@\\n@@@@@@@@@@@@@@@@@@@@@@@\\n'", - # add dns rewrite rule - "kubectl create configmap coredns-custom -n kube-system " + - "--from-literal='rewritehost.override=rewrite name exact %s host.k3d.internal'" % name, - "kubectl -n kube-system rollout restart deployment coredns", - ]) - - if ocm: - commands.extend([ - # wait for peer - "until getent hosts %s >/dev/null 2>&1; do echo 'Waiting for %s...'; sleep 2; done" % (peer_name, peer_name), - # create namespace - "kubectl create namespace ocis || true", - "bash %s/tests/config/k8s/expose-external-svc.sh -n ocis %s:443" % (dirs["base"], peer_name), - ]) - - commands.extend([ - "printf '@@@@@@@@@@@@@@@@@@@@@@@\\n@@@@ k3d is ready @@@@\\n@@@@@@@@@@@@@@@@@@@@@@@\\n'", - # watch events - "kubectl get events -Aw", - ]) - - return [{ - "name": name, - "image": K3D_IMAGE, - "user": "root", - "privileged": True, - "commands": commands, - }] - -def waitK3sCluster(name = OCIS_SERVER_NAME): - step_name = "wait-cluster-" + name - return [{ - "name": step_name, - "image": K3D_IMAGE, - "user": "root", - "commands": [ - "export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % name, - "timeout 300 bash -c 'until test -f $${KUBECONFIG}; do sleep 1; done'", - "kubectl config view", - "kubectl get pods -A", - ], - }] - -def prepareChartsK8s(environment = []): - commands = [ - # build ocis wrapper - "make -C %s build" % dirs["ocisWrapper"], - # get ocis charts - "[ ! -d %s/ocis-charts ] && " % dirs["base"] + - "git clone --single-branch -b main --depth 1 https://github.com/owncloud/ocis-charts.git", - # prepare charts for the tests - "bash %s/tests/config/k8s/setup.sh %s/ocis-charts" % (dirs["base"], dirs["base"]), - ] - - return [{ - "name": "prepare-ocis-deployment", - "image": OC_CI_GOLANG, - "environment": environment, - "commands": commands, - "volumes": [ - { - "name": "gopath", - "path": "/go", - }, - ], - }] - -def setupConfigMapsK8s(name = OCIS_SERVER_NAME): - step_name = "setup-configmaps-" + name - - commands = [ - "export KUBECONFIG=%s/kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % (dirs["base"], name), - # Create namespace for oCIS deployment - "kubectl create namespace ocis || true", - # Setup Unicode font support for thumbnails - create ConfigMaps - "kubectl create configmap -n ocis ocis-fonts-ttf --from-file=%s/tests/config/drone/NotoSans.ttf" % dirs["base"], - ] - - return [{ - "name": step_name, - "image": K3D_IMAGE, - "user": "root", - "commands": commands, - }] - -def deployOcisK8s(name = OCIS_SERVER_NAME): - step_name = "deploy-" + name - - return [{ - "name": step_name, - "image": OC_CI_GOLANG, - "commands": [ - "export KUBECONFIG=%s/kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % (dirs["base"], name), - "cd %s/ocis-charts" % dirs["base"], - # update external domain - "sed -i 's|externalDomain:.*|externalDomain: %s|' ./charts/ocis/ci/deployment-values.yaml" % name, - # deploy ocis - "make helm-install-atomic", - ], - }] - -def streamOcisLogsK8s(name = OCIS_SERVER_NAME): - return [{ - "name": "%s-logs" % name, - "image": OC_CI_ALPINE, - "detach": True, - "commands": [ - "until test -f logs-%s/ocis.log; do sleep 10s; done" % name, - "tail -f logs-%s/ocis.log" % name, - ], - }] - -def ociswrapperK8s(name = OCIS_SERVER_NAME, ocis_url = OCIS_URL_K8S): - return [{ - "name": "ociswrapper", - "image": K3D_IMAGE, - "detach": True, - "commands": [ - "export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % name, - "until test -f $${KUBECONFIG}; do sleep 1s; done", - "%s/bin/ociswrapper serve --url %s --admin-username admin --admin-password admin --skip-ocis-run" % (dirs["ocisWrapper"], ocis_url), - ], - }, { - "name": "wait-for-wrapper", - "image": OC_CI_ALPINE, - "commands": [ - "timeout 60 bash -c 'while [ $(curl -sk " + - "http://ociswrapper:5200 " + - "-w %{http_code} -o /dev/null) != 404 ]; do sleep 1; done'", - ], - }] - -def exposeNodePortsK8s(services = [], name = OCIS_SERVER_NAME): - commands = [] - for idx, service in enumerate(services): - deploy_name = service[0] - service_port = str(service[1]) - node_port = service_port.replace("9", "30", 1) - - # there can be multiple collaboration services - if service_port == "9300" and "collaboration" in deploy_name: - node_port = "3030%d" % idx - service_name = "%s-%s-np" % (deploy_name, node_port) - commands.append("kubectl -n ocis expose deployment %s --type=NodePort --port=%s --name=%s" % (deploy_name, service_port, service_name)) - commands.append("kubectl -n ocis patch svc %s -p '{\"spec\":{\"ports\":[{\"port\":%s,\"nodePort\":%s}]}}'" % (service_name, service_port, node_port)) - - return [{ - "name": "expose-nodeports", - "image": K3D_IMAGE, - "commands": [ - "export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % name, - "until test -f $${KUBECONFIG}; do sleep 1s; done", - ] + commands, - }] - -def exposeExternalServersK8s(servers = [], name = OCIS_SERVER_NAME): - servers_arg = [] - for server in servers: - servers_arg.append("%s:%s" % (server[0], str(server[1]))) - servers_arg = ",".join(servers_arg) - - return [{ - "name": "expose-external-servers", - "image": K3D_IMAGE, - "commands": [ - "export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % name, - "until test -f $${KUBECONFIG}; do sleep 1s; done", - "bash %s/tests/config/k8s/expose-external-svc.sh -n ocis %s" % (dirs["base"], servers_arg), - ], - }] diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 24953cd5d43..8e34fa4cac0 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,4 +1,3 @@ services/settings/ @lukashirt services/web/ @lukashirt -.drone.star @kobergj @phil-davis @individual-it assets/End-User-License-Agreement-for-ownCloud-Infinite-Scale.pdf @kobergj @hodyroff diff --git a/.github/release_template.md b/.github/release_template.md index 9d4adf7f4dc..211867c0489 100644 --- a/.github/release_template.md +++ b/.github/release_template.md @@ -8,7 +8,6 @@ * [ ] DEV/QA: Check new strings and align with clients * [ ] DEV/DOCS: Create list of pending docs tasks * [ ] DEV: Create branch `release-x.x.x-rc.x` -> CODEFREEZE - * [ ] DEV: specify if it is a production release in [.drone.star](https://github.com/owncloud/ocis/blob/b4cf38fa1ba180c58519026dfe762b7c45695466/.drone.star#L8) (if needed) * [ ] DEV: bump ocis version in necessary files * [ ] DEV: `changelog/CHANGELOG.tmpl` * [ ] DEV: `ocis-pkg/version/version.go` diff --git a/.github/workflows/acceptance-tests.yml b/.github/workflows/acceptance-tests.yml index 66e9e495f06..8922594708a 100644 --- a/.github/workflows/acceptance-tests.yml +++ b/.github/workflows/acceptance-tests.yml @@ -219,7 +219,7 @@ jobs: fail-fast: false matrix: suite: - - cliCommands,apiServiceAvailability # grouped like drone; needs ClamAV + email + - cliCommands,apiServiceAvailability # grouped: both need ClamAV + email services steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 @@ -375,7 +375,7 @@ jobs: uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 with: path: ~/.cache/ms-playwright - key: playwright-chromium-${{ hashFiles('.drone.env') }} + key: playwright-chromium-${{ hashFiles('ci.env') }} # --- Tika (search suite only) --- - name: Start Tika @@ -409,9 +409,10 @@ jobs: - name: Start Keycloak if: matrix.keycloak == true run: | - # Patch realm: replace Drone Docker hostname with localhost IP + # Patch realm: ocis-ci-realm.dist.json uses ocis-server:9200 as hostname. + # GitHub Actions runs on the host network so patch it to 127.0.0.1. sed 's|https://ocis-server:9200|https://127.0.0.1:9200|g' \ - tests/config/drone/ocis-ci-realm.dist.json > /tmp/ocis-realm.json + tests/config/ci/ocis-ci-realm.dist.json > /tmp/ocis-realm.json docker run -d --name keycloak --network host \ -e OCIS_DOMAIN=https://127.0.0.1:9200 \ -e KC_HOSTNAME=localhost \ diff --git a/.github/workflows/weekly_pipeline_report.yml b/.github/workflows/weekly_pipeline_report.yml index 760f9573cfa..2dc7364fee4 100644 --- a/.github/workflows/weekly_pipeline_report.yml +++ b/.github/workflows/weekly_pipeline_report.yml @@ -24,9 +24,8 @@ jobs: working-directory: tools/ci-reporter env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # Review the pipelines in last 14 days before the dorne logs expire run: | - GOWORK=off go run ./cmd/list-failed-commits \ + GOWORK=off go run ./cmd/list-flaky-tests \ --github-token "$GITHUB_TOKEN" \ - --since 14d \ - --max-commits 9999999 + --workflow acceptance-tests.yml \ + --since 4w diff --git a/.gitignore b/.gitignore index 33e55761570..cacae4f6d18 100644 --- a/.gitignore +++ b/.gitignore @@ -45,8 +45,6 @@ vendor-php # QA activity reports tests/qa-activity-report/reports/ -# drone CI is in .drone.star, do not let someone accidentally commit a local .drone.yml -.drone.yml **/l10n/template.pot diff --git a/Makefile b/Makefile index 0da1c120f54..11e8752957a 100644 --- a/Makefile +++ b/Makefile @@ -20,7 +20,6 @@ L10N_MODULES := \ services/userlog \ services/settings -# if you add a module here please also add it to the .drone.star file OCIS_MODULES = \ services/activitylog \ services/antivirus \ @@ -206,7 +205,10 @@ docs-serve: docs-clean: @$(MAKE) --no-print-directory -C docs docs-clean -# imitate a full drone run locally to build docs without pushing to the web. +# docs-local imitates the 3-step docs build pipeline (generate → copy → build) +# locally without pushing. docs-hugo-drone-prep creates the ../hugo symlink required by +# the Hugo Docker image (hugomods/hugo:base-0.129.0). +# imitate a full docs build run locally without pushing to the web. # this can help identify uncaught issues when running `make docs-serve` only. .PHONY: docs-local # run all steps as drone would do it (1, 2, 3) docs-local: @@ -365,9 +367,6 @@ l10n-write: $(MAKE) -C $$extension l10n-write || exit 1; \ done -.PHONY: ci-format -ci-format: $(BUILDIFIER) - $(BUILDIFIER) --mode=fix .drone.star .PHONY: test-php-style test-php-style: vendor-bin/owncloud-codestyle/vendor vendor-bin/php_codesniffer/vendor diff --git a/README.md b/README.md index 15ef8058263..0cbb5e56cbb 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # ownCloud Infinite Scale [![Matrix](https://img.shields.io/matrix/ocis%3Amatrix.org?logo=matrix)](https://app.element.io/#/room/#ocis:matrix.org) -[![Build Status](https://drone.owncloud.com/api/badges/owncloud/ocis/status.svg)](https://drone.owncloud.com/owncloud/ocis) +[![Build Status](https://github.com/owncloud/ocis/actions/workflows/acceptance-tests.yml/badge.svg)](https://github.com/owncloud/ocis/actions/workflows/acceptance-tests.yml) [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=owncloud_ocis&metric=security_rating)](https://sonarcloud.io/dashboard?id=owncloud_ocis) [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=owncloud_ocis&metric=coverage)](https://sonarcloud.io/dashboard?id=owncloud_ocis) [![Acceptance Test Coverage](https://sonarcloud.io/api/project_badges/measure?project=owncloud-1_ocis_acceptance-tests&metric=coverage)](https://sonarcloud.io/summary/new_code?id=owncloud-1_ocis_acceptance-tests) diff --git a/ci.env b/ci.env new file mode 100644 index 00000000000..3c149ea0df4 --- /dev/null +++ b/ci.env @@ -0,0 +1,4 @@ +# Pins the ownCloud Web frontend version used in CI tests. +# Read by: tests/acceptance/run-e2e.py and .github/workflows/acceptance-tests.yml (Playwright cache key). +WEB_COMMITID=6165b4e47a47e3a216107e96f90825190f10632e +WEB_BRANCH=stable-12.3 diff --git a/docs/Makefile b/docs/Makefile index 271cbc8332b..fa4083db411 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -37,7 +37,8 @@ help: .PHONY:list list: help -# for drone only. drone uses an image for hugo that needs the hugo folder in the root +# Creates a symlink ../hugo → hugo/ required by the Hugo Docker image +# (hugomods/hugo:base-0.129.0), which expects the hugo folder at the repo root. # CURDIR will work for make only but not when running manually in the shell .PHONY: docs-hugo-drone-prep docs-hugo-drone-prep: diff --git a/docs/helpers/extended_vars.yaml b/docs/helpers/extended_vars.yaml index ce2dc15d8d2..56c733f874e 100644 --- a/docs/helpers/extended_vars.yaml +++ b/docs/helpers/extended_vars.yaml @@ -40,7 +40,7 @@ variables: description: "" do_ignore: true - rawname: GITHUB_TOKEN - path: tools/ci-reporter/cmd/list-failed-commits/main.go:116 + path: tools/ci-reporter/cmd/list-flaky-tests/main.go:64 foundincode: true name: GITHUB_TOKEN type: "" diff --git a/docs/ocis/build-docs.md b/docs/ocis/build-docs.md index 25e4ae1523f..d703e48f7ed 100644 --- a/docs/ocis/build-docs.md +++ b/docs/ocis/build-docs.md @@ -15,7 +15,7 @@ The documentation: * Is based on the [HUGO](https://gohugo.io/) framework written in Go. The underlaying language is markdown plus the extensions provided by hugo. * The framwork including the theme used is maintained in the following [repo](https://github.com/owncloud/owncloud.github.io). -* The hugo version, currently at `0.129.0` must match the image version defined in the root makefile and the framework repo, defined in `.drone.yml`.\ +* The hugo version, currently at `0.129.0` must match the image version defined in the root makefile and the framework repo.\ {{< hint info >}} * Building the theme is part of the loaded framework while building the documentation is done using a separate container. @@ -24,7 +24,7 @@ The documentation: * The documentation sources are distributed over several repos such as `ocis`, `web` and others. When building, these sources act individually and only those sources are build and pushed to the web that come from the respective repo. The definition what is going where is defined in the [framework repo](https://github.com/owncloud/owncloud.github.io/blob/main/.batchfile). This means, each merge of a docs change in one of the sourcing repos only pushes that change to the site. There is no global build process and inter doc links must be treated therefore very carefully ! -* The documentation setup is, with only a few exceptions, identical for both the `ocis` and the `web` repo. This means, for example, running commands locally are the same, the documentation process section below applies for both; only drone uses some specifics. +* The documentation setup is, with only a few exceptions, identical for both the `ocis` and the `web` repo. This means, for example, running commands locally are the same, the documentation process section below applies for both. * {{< hint info >}} Any files or folders that need to be excluded from the build process must be defined in the referenced framework repository above, in the file `config.yaml`. diff --git a/docs/ocis/development/continuous-integration.md b/docs/ocis/development/continuous-integration.md index b5907d7cdc5..5f05977a597 100644 --- a/docs/ocis/development/continuous-integration.md +++ b/docs/ocis/development/continuous-integration.md @@ -9,48 +9,47 @@ geekdocFilePath: continuous-integration.md {{< toc >}} -oCIS uses [DRONE](https://www.drone.io/) as CI system. You can find the pipeline logs [here](https://drone.owncloud.com/owncloud/ocis) or in your PR. +## Overview + +oCIS uses [GitHub Actions](https://github.com/owncloud/ocis/actions) as its CI system. Pipeline logs are visible directly in pull requests. ## Concepts -The pipeline is defined in [Starlark](https://github.com/bazelbuild/starlark) and transformed to YAML upon pipeline run. This enables us to do a highly dynamic and non repeating pipeline configuration. We enforce Starlark format guidelines with Bazel Buildifier. You can format the .drone.star file by running `make ci-format`. +Pipelines are defined in `.github/workflows/`. The main acceptance test workflow is `.github/workflows/acceptance-tests.yml`. -Upon running the pipeline, your branch gets merged to the master branch. This ensures that we always test your changeset if as it was applied to the master of oCIS. Please note that this does not apply to the pipeline definition (`.drone.star`). +Upon running the pipeline, tests run against the branch as-is. Make sure your branch is rebased onto the latest master before running CI to avoid false failures. ## Things done in CI - static code analysis - linting - running UI tests -- running ownCloud 10 test suite against oCIS +- running API acceptance tests - build and release docker images - build and release binaries - build and release documentation ## Flags in commit message and PR title -You may add flags to your commit message or PR title in order to speed up pipeline runs and take load from the CI runners. +You may add flags to your commit message or PR title to control pipeline runs. - `[CI SKIP]`: no CI is run on the commit or PR - -- `[full-ci]`: deactivates the fail early mechanism and runs all available test (as default only smoke tests are run) +- `[k6-test]`: enabled the run of the k6 with smoke and performance test ### Knowledge base - My pipeline fails because some CI related files or commands are missing. - Please make sure to rebase your branch onto the latest master of oCIS. It could be that the pipeline definition (`.drone.star`) was changed on the master branch. This is the only file, that will not be auto merged to master upon pipeline run. So things could be out of sync. + Make sure your branch is rebased onto the latest master. Workflow files in `.github/workflows/` change over time and a stale branch may reference steps or configs that no longer exist. -- How can I see the YAML drone pipeline definition? +- How can I see what a workflow does? - In order to see the Yaml pipeline definition you can use the drone-cli to convert the Starlark file. + Workflow definitions are plain YAML in `.github/workflows/`. Open the relevant file directly in the repo — no CLI tool needed. The main acceptance test entry point is `.github/workflows/acceptance-tests.yml`. +- How can I re-run a failed job? + + In the GitHub Actions UI, click **Re-run jobs** → **Re-run failed jobs** on the failed workflow run. You can also trigger a full re-run from `gh`: + + ```bash + gh run rerun --failed --repo owncloud/ocis ``` - drone starlark - ``` - - {{< hint info >}} - If you experience a `"build" struct has no .title attribute` you need a newer version of drone-cli. - - You currently need to build it yourself from this [source code](https://github.com/drone/drone-cli). If you are not using master as source, please ensure that this [PR](https://github.com/drone/drone-cli/pull/175) is included. - {{< /hint >}} diff --git a/docs/ocis/development/testing.md b/docs/ocis/development/testing.md index 2e1523bb43a..868fbc55b79 100644 --- a/docs/ocis/development/testing.md +++ b/docs/ocis/development/testing.md @@ -581,11 +581,11 @@ THUMBNAILS_TXT_FONTMAP_FILE="/path/to/fontsMap.json" ocis/bin/ocis server ``` -The sample `fontsMap.json` file is located in `tests/config/drone/fontsMap.json`. +The sample `fontsMap.json` file is located in `tests/config/ci/fontsMap.json`. ```json { - "defaultFont": "/path/to/ocis/tests/config/drone/NotoSans.ttf" + "defaultFont": "/path/to/ocis/tests/config/ci/NotoSans.ttf" } ``` diff --git a/docs/ocis/releasing_guide/releasing_guide.md b/docs/ocis/releasing_guide/releasing_guide.md index 842df817cef..16714d6392f 100644 --- a/docs/ocis/releasing_guide/releasing_guide.md +++ b/docs/ocis/releasing_guide/releasing_guide.md @@ -108,10 +108,7 @@ https://owncloud.dev/ocis/releasing_guide/ * [ ] Create orphan branch: `git checkout --orphan docs-stable-7.2` * [ ] Initial commit: `git commit --allow-empty -m "initial commit"` * [ ] Push it: `git push` - * [ ] Adjust the `.drone.star` file to write to `docs-stable-7.2` - * [ ] Find target_branch value in the docs section and change it to `docs-stable-7.2` - * [ ] Example: https://github.com/owncloud/ocis/blame/56f7645f0b11c9112e15ce46f6effd2fea01d6be/.drone.star#L2249 - * [ ] Add `stable-7.2` to the nightly cron jobs in drone (`Settings` -> `Cron Jobs`) + * [ ] Add `stable-7.2` to the nightly cron jobs in GitHub Actions (`Settings` -> `Schedules`) ``` ### Steps for Patch Releases Only diff --git a/docs/services/general-info/add-translations.md b/docs/services/general-info/add-translations.md index 49c06809b20..802c182079f 100644 --- a/docs/services/general-info/add-translations.md +++ b/docs/services/general-info/add-translations.md @@ -16,12 +16,7 @@ Services can have texts that need to be translated. These translations will be s The process for _synchronisation_ with Transifex is already setup and nothing needs to be done here. For any translation, it is necessary to set it up in the respective service and tell to sync it. **IMPORTANT**\ -Translations are automatically synced on a daily basis in the night. To do so, there is an own repo that covers the process for ALL translations from all configured repos: [translation-sync](https://github.com/owncloud/translation-sync). If there is a manual "emergency" sync necessary, you only need to trigger [drone](https://drone.owncloud.com/owncloud/translation-sync) via cli - -```bash -drone cron exec owncloud/translation-sync nightly -``` -Note that you need to be logged on in drone to execute the command. +Translations are automatically synced on a daily basis in the night. To do so, there is an own repo that covers the process for ALL translations from all configured repos: [translation-sync](https://github.com/owncloud/translation-sync). If there is a manual "emergency" sync necessary, trigger the workflow manually via the [GitHub Actions UI](https://github.com/owncloud/translation-sync/actions) using `workflow_dispatch`. ## Implementing ocis Translations diff --git a/docs/services/general-info/new-service-checklist.md b/docs/services/general-info/new-service-checklist.md index eb72f9ad473..b2657c42a75 100644 --- a/docs/services/general-info/new-service-checklist.md +++ b/docs/services/general-info/new-service-checklist.md @@ -36,7 +36,7 @@ Use this checklist with copy/paste in your PR - right from the beginning. It ren - Add the service config to `ocis-pkg/config/defaultconfig.go` - [ ] If the service is using service accounts, add it to `ocis/pkg/init/init.go` - [ ] Check that the service properly responds to `ocis health` and has `/healthz` and `/readyz` endpoints -- [ ] Add the service to `.drone.star` to enable CI. +- [ ] Add the service suite to the GitHub Actions matrix in `.github/workflows/acceptance-tests.yml` to enable CI. - [ ] Inform doc team in an *early stage* to review the readme AND the environment variables created. - The description must reflect the behaviour AND usually has a positive code quality impact. - [ ] Create proper description strings for envvars - see other services for examples, especially when it comes to multiple values. This must include: diff --git a/docs/services/web/releasing.md b/docs/services/web/releasing.md index ac9be9f12f1..b7e09262aea 100644 --- a/docs/services/web/releasing.md +++ b/docs/services/web/releasing.md @@ -32,6 +32,6 @@ and take note of its release tag name. 2. Change into web package folder via `cd web` 3. Inside `web/`, update the `Makefile` so that the WEB_ASSETS_VERSION variable references the currently released version of https://github.com/owncloud/web 4. Move to the changelog (`cd ../changelog/`) and add a changelog file to the `unreleased/` folder (You can copy an old web release changelog item as a template) -5. Move to the repo root (`cd ..`)and update the WEB_COMMITID in the `/.drone.env` file to the commit id from the released version (unless the existing commit id is already newer) +5. Move to the repo root (`cd ..`) and update the `WEB_COMMITID` in `/ci.env` to the commit id from the released version (unless the existing commit id is already newer) 6. **Optional:** Test the changes locally by running `cd ocis && go run cmd/ocis/main.go server`, visiting [https://localhost:9200](https://localhost:9200) and confirming everything renders correctly 7. Commit your changes, push them and [create a PR](https://github.com/owncloud/ocis/pulls) diff --git a/tests/acceptance/docker/src/acceptance.yml b/tests/acceptance/docker/src/acceptance.yml index 732864fe9d9..47519003c12 100644 --- a/tests/acceptance/docker/src/acceptance.yml +++ b/tests/acceptance/docker/src/acceptance.yml @@ -1,10 +1,10 @@ services: acceptance-tests: image: owncloudci/php:8.2 - working_dir: /drone/src + working_dir: /ocis command: /bin/bash /test/run-tests.sh environment: - OCIS_ROOT: /drone/src + OCIS_ROOT: /ocis TEST_SERVER_URL: https://ocis-server:9200 OCIS_WRAPPER_URL: http://ocis-server:5200 STORAGE_DRIVER: $STORAGE_DRIVER @@ -17,8 +17,8 @@ services: EMAIL_HOST: email EMAIL_PORT: 8025 env_file: - - ../../../../.drone.env + - ../../../../ci.env volumes: - ./run-tests.sh:/test/run-tests.sh - - ../../../../:/drone/src + - ../../../../:/ocis - ../../../../vendor-bin/behat/composer.json:/tmp/vendor-bin/behat/composer.json diff --git a/tests/acceptance/docker/src/ocis-base.yml b/tests/acceptance/docker/src/ocis-base.yml index 990f542024c..628250e9c30 100644 --- a/tests/acceptance/docker/src/ocis-base.yml +++ b/tests/acceptance/docker/src/ocis-base.yml @@ -15,7 +15,7 @@ services: STORAGE_SYSTEM_DRIVER_OCIS_ROOT: /srv/app/tmp/ocis/storage/metadata SHARING_USER_JSON_FILE: /srv/app/tmp/ocis/shares.json PROXY_ENABLE_BASIC_AUTH: "true" - WEB_UI_CONFIG_FILE: /drone/src/tests/config/drone/ocis-config.json + WEB_UI_CONFIG_FILE: /ocis/tests/config/ci/ocis-config.json OCIS_INSECURE: "true" IDM_CREATE_DEMO_USERS: "true" IDM_ADMIN_PASSWORD: "admin" @@ -48,7 +48,7 @@ services: SEARCH_EXTRACTOR_CS3SOURCE_INSECURE: "true" # fonts map for txt thumbnails (including unicode support) - THUMBNAILS_TXT_FONTMAP_FILE: "/drone/src/tests/config/drone/fontsMap.json" + THUMBNAILS_TXT_FONTMAP_FILE: "/ocis/tests/config/ci/fontsMap.json" volumes: - - ../../../config:/drone/src/tests/config + - ../../../config:/ocis/tests/config - ../../../ociswrapper/bin/ociswrapper:/usr/bin/ociswrapper diff --git a/tests/acceptance/docker/src/run-tests.sh b/tests/acceptance/docker/src/run-tests.sh index 5465c9bc81f..4f1ced74170 100644 --- a/tests/acceptance/docker/src/run-tests.sh +++ b/tests/acceptance/docker/src/run-tests.sh @@ -1,8 +1,5 @@ #!/bin/bash -#mkdir -p /drone/src/vendor-bin/behat -#cp /tmp/vendor-bin/behat/composer.json /drone/src/vendor-bin/behat/composer.json - git config --global advice.detachedHead false ## CONFIGURE TEST @@ -12,7 +9,7 @@ if [ "$TEST_SOURCE" = "oc10" ]; then if [ "$STORAGE_DRIVER" = "ocis" ]; then export OCIS_REVA_DATA_ROOT='' export BEHAT_FILTER_TAGS='~@skipOnOcis-OCIS-Storage' - export EXPECTED_FAILURES_FILE='/drone/src/tests/acceptance/expected-failures-API-on-OCIS-storage.md' + export EXPECTED_FAILURES_FILE='/ocis/tests/acceptance/expected-failures-API-on-OCIS-storage.md' elif [ "$STORAGE_DRIVER" = "s3ng" ]; then export BEHAT_FILTER_TAGS='~@skip&&~@skipOnOcis-S3NG-Storage' export OCIS_REVA_DATA_ROOT='' diff --git a/tests/acceptance/features/apiSharingNgDriveLinkShare/createDriveLinkShare.feature b/tests/acceptance/features/apiSharingNgDriveLinkShare/createDriveLinkShare.feature index 75d421e03de..ff9b814c6c4 100644 --- a/tests/acceptance/features/apiSharingNgDriveLinkShare/createDriveLinkShare.feature +++ b/tests/acceptance/features/apiSharingNgDriveLinkShare/createDriveLinkShare.feature @@ -286,7 +286,7 @@ Feature: Link sharing of project spaces @env-config Scenario: try to create a link share of a project-space with a password that is listed in the Banned-Password-List using permissions endpoint Given using spaces DAV path - And the config "SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/drone/banned-password-list.txt" for "sharing" service + And the config "SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/ci/banned-password-list.txt" for "sharing" service And the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API And user "Alice" has created a space "projectSpace" with the default quota using the Graph API When user "Alice" creates the following space link share using permissions endpoint of the Graph API: @@ -315,7 +315,7 @@ Feature: Link sharing of project spaces @env-config Scenario: try to create a link share of a project-space with a password that is listed in the Banned-Password-List using root endpoint Given using spaces DAV path - And the config "SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/drone/banned-password-list.txt" for "sharing" service + And the config "SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/ci/banned-password-list.txt" for "sharing" service And the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API And user "Alice" has created a space "projectSpace" with the default quota using the Graph API When user "Alice" creates the following space link share using root endpoint of the Graph API: diff --git a/tests/acceptance/features/apiSharingNgItemLinkShare/createLinkShareBannedPassword.feature b/tests/acceptance/features/apiSharingNgItemLinkShare/createLinkShareBannedPassword.feature index 247196df600..6103d2e46bc 100644 --- a/tests/acceptance/features/apiSharingNgItemLinkShare/createLinkShareBannedPassword.feature +++ b/tests/acceptance/features/apiSharingNgItemLinkShare/createLinkShareBannedPassword.feature @@ -6,7 +6,7 @@ Feature: Link share with banned password Given these users have been created with default attributes: | username | | Alice | - And the config "SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/drone/banned-password-list.txt" for "sharing" service + And the config "SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/ci/banned-password-list.txt" for "sharing" service Scenario: try to create a folder link share with a password that is listed in the Banned-Password-List diff --git a/tests/acceptance/features/apiSharingNgLinkShareManagement/updateItemLinkShare.feature b/tests/acceptance/features/apiSharingNgLinkShareManagement/updateItemLinkShare.feature index 8e8e5bdbd52..97eb2a757d0 100644 --- a/tests/acceptance/features/apiSharingNgLinkShareManagement/updateItemLinkShare.feature +++ b/tests/acceptance/features/apiSharingNgLinkShareManagement/updateItemLinkShare.feature @@ -237,7 +237,7 @@ Feature: Update a link share for a resource Scenario Outline: update a file's link share with a password that is listed in the Banned-Password-List using permissions endpoint - Given the config "SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/drone/banned-password-list.txt" for "sharing" service + Given the config "SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/ci/banned-password-list.txt" for "sharing" service And user "Alice" has uploaded file with content "other data" to "text.txt" And user "Alice" has created the following resource link share: | resource | text.txt | diff --git a/tests/acceptance/features/coreApiSharePublicLink2/enforcePasswordPublicLink.feature b/tests/acceptance/features/coreApiSharePublicLink2/enforcePasswordPublicLink.feature index b6637cc60de..415ed81b8d3 100644 --- a/tests/acceptance/features/coreApiSharePublicLink2/enforcePasswordPublicLink.feature +++ b/tests/acceptance/features/coreApiSharePublicLink2/enforcePasswordPublicLink.feature @@ -283,8 +283,8 @@ Feature: enforce password on public link Scenario Outline: update a public link with a password that is listed in the Banned-Password-List - Given the config "SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/drone/banned-password-list.txt" for "sharing" service - And the config "FRONTEND_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/drone/banned-password-list.txt" for "frontend" service + Given the config "SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/ci/banned-password-list.txt" for "sharing" service + And the config "FRONTEND_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/ci/banned-password-list.txt" for "frontend" service And using OCS API version "2" And user "Alice" has been created with default attributes And user "Alice" has uploaded file with content "test file" to "/testfile.txt" @@ -307,8 +307,8 @@ Feature: enforce password on public link Scenario Outline: create a public link with a password that is listed in the Banned-Password-List - Given the config "SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/drone/banned-password-list.txt" for "sharing" service - And the config "FRONTEND_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/drone/banned-password-list.txt" for "frontend" service + Given the config "SHARING_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/ci/banned-password-list.txt" for "sharing" service + And the config "FRONTEND_PASSWORD_POLICY_BANNED_PASSWORDS_LIST" has been set to path "config/ci/banned-password-list.txt" for "frontend" service And using OCS API version "2" And user "Alice" has been created with default attributes And user "Alice" has uploaded file with content "test file" to "/testfile.txt" diff --git a/tests/acceptance/run-cs3api.py b/tests/acceptance/run-cs3api.py index 9da46cb0888..0d9de34cb72 100644 --- a/tests/acceptance/run-cs3api.py +++ b/tests/acceptance/run-cs3api.py @@ -2,7 +2,6 @@ """ Run CS3 API validator tests locally and in GitHub Actions CI. -Config sourced from .drone.star cs3ApiTests() — single source of truth. Usage: python3 tests/acceptance/run-cs3api.py """ @@ -15,7 +14,7 @@ import time from pathlib import Path # --------------------------------------------------------------------------- -# Constants (mirroring .drone.star) +# Constants # --------------------------------------------------------------------------- # HTTPS — matching drone: ocis init generates a self-signed cert; proxy uses TLS by default. @@ -54,7 +53,7 @@ def base_server_env(repo_root: Path, ocis_config_dir: str, ocis_public_url: str) "NATS_NATS_PORT": "9233", "OCIS_JWT_SECRET": "some-ocis-jwt-secret", "EVENTHISTORY_STORE": "memory", - "WEB_UI_CONFIG_FILE": str(repo_root / "tests/config/drone/ocis-config.json"), + "WEB_UI_CONFIG_FILE": str(repo_root / "tests/config/ci/ocis-config.json"), # cs3api_validator extras (drone ocisServer deploy_type="cs3api_validator") "GATEWAY_GRPC_ADDR": "0.0.0.0:9142", "OCIS_SHARING_PUBLIC_SHARE_MUST_HAVE_PASSWORD": "false", @@ -102,7 +101,7 @@ def main() -> int: check=True, ) shutil.copy( - repo_root / "tests/config/drone/app-registry.yaml", + repo_root / "tests/config/ci/app-registry.yaml", ocis_config_dir / "app-registry.yaml", ) diff --git a/tests/acceptance/run-e2e.py b/tests/acceptance/run-e2e.py index c8d6995fe72..06d46e271f7 100755 --- a/tests/acceptance/run-e2e.py +++ b/tests/acceptance/run-e2e.py @@ -73,15 +73,15 @@ def main() -> int: # clone + install web only if not already provided (e.g. via artifact) if not web_dir.exists(): - drone_env = {} - drone_env_file = repo_root / ".drone.env" - if drone_env_file.exists(): - for line in drone_env_file.read_text().splitlines(): + ci_env = {} + ci_env_file = repo_root / "ci.env" + if ci_env_file.exists(): + for line in ci_env_file.read_text().splitlines(): if "=" in line and not line.startswith("#"): k, v = line.split("=", 1) - drone_env[k.strip()] = v.strip() - web_branch = drone_env.get("WEB_BRANCH", "master") - web_commitid = drone_env.get("WEB_COMMITID", "") + ci_env[k.strip()] = v.strip() + web_branch = ci_env.get("WEB_BRANCH", "master") + web_commitid = ci_env.get("WEB_COMMITID", "") run(["git", "clone", "-b", web_branch, "--single-branch", "--no-tags", WEB_REPO, str(web_dir)]) if web_commitid: @@ -99,7 +99,7 @@ def main() -> int: # init ocis run([str(ocis_bin), "init", "--insecure", "true"]) shutil.copy( - repo_root / "tests/config/drone/app-registry.yaml", + repo_root / "tests/config/ci/app-registry.yaml", ocis_config_dir / "app-registry.yaml", ) @@ -115,7 +115,7 @@ def main() -> int: # Patch web UI config: replace Drone Docker service name with our URL drone_web_cfg = json.loads( - (repo_root / "tests/config/drone/ocis-config.json").read_text() + (repo_root / "tests/config/ci/ocis-config.json").read_text() ) def _patch_urls(obj, old, new): @@ -151,9 +151,9 @@ def main() -> int: "EVENTHISTORY_STORE": "memory", "OCIS_TRANSLATION_PATH": str(repo_root / "tests/config/translations"), "WEB_UI_CONFIG_FILE": str(gha_web_cfg_path), - "THUMBNAILS_TXT_FONTMAP_FILE": str(repo_root / "tests/config/drone/fontsMap.json"), + "THUMBNAILS_TXT_FONTMAP_FILE": str(repo_root / "tests/config/ci/fontsMap.json"), # extra_server_environment — matches drone e2eTestPipeline() - "OCIS_PASSWORD_POLICY_BANNED_PASSWORDS_LIST": str(repo_root / "tests/config/drone/banned-password-list.txt"), + "OCIS_PASSWORD_POLICY_BANNED_PASSWORDS_LIST": str(repo_root / "tests/config/ci/banned-password-list.txt"), "GRAPH_AVAILABLE_ROLES": "b1e2218d-eef8-4d4c-b82d-0f1a1b48f3b5,a8d5fe5e-96e3-418d-825b-534dbdf22b99,fb6c3e19-e378-47e5-b277-9732f9de6e21,58c63c02-1d89-4572-916a-870abc5a1b7d,2d00ce52-1fc2-4dbc-8b95-a73b73395f5a,1c996275-f1c9-4e71-abdf-a42f6495e960,312c0871-5ef7-4b3a-85b6-0e4074c64049,aa97fe03-7980-45ac-9e50-b325749fd7e6,63e64e19-8d43-42ec-a738-2b6af2610efa", "FRONTEND_CONFIGURABLE_NOTIFICATIONS": "true", # debug addresses @@ -215,7 +215,7 @@ def main() -> int: "OCIS_ADMIN_USER_ID": "", "GRAPH_ASSIGN_DEFAULT_USER_ROLE": "false", "GRAPH_USERNAME_MATCH": "none", - "PROXY_CSP_CONFIG_FILE_LOCATION": str(repo_root / "tests/config/drone/csp.yaml"), + "PROXY_CSP_CONFIG_FILE_LOCATION": str(repo_root / "tests/config/ci/csp.yaml"), "KEYCLOAK_DOMAIN": "localhost:8443", "IDM_CREATE_DEMO_USERS": "false", }) diff --git a/tests/acceptance/run-github.py b/tests/acceptance/run-github.py index d2010ca07db..4e11fd085ee 100755 --- a/tests/acceptance/run-github.py +++ b/tests/acceptance/run-github.py @@ -2,7 +2,6 @@ """ Run ocis acceptance tests locally and in GitHub Actions CI. -Config sourced from .drone.star localApiTests — single source of truth. Usage: BEHAT_SUITES=apiGraph python3 tests/acceptance/run-github.py """ @@ -17,7 +16,7 @@ import shutil from pathlib import Path # --------------------------------------------------------------------------- -# Config sourced from .drone.star + # NOTE: EMAIL_SMTP_HOST is "email" (container name) in drone, "localhost" here # --------------------------------------------------------------------------- @@ -216,8 +215,8 @@ def base_server_env(repo_root: Path, ocis_url: str, ocis_config_dir: str) -> dic "OCIS_JWT_SECRET": "some-ocis-jwt-secret", "EVENTHISTORY_STORE": "memory", "OCIS_TRANSLATION_PATH": str(repo_root / "tests/config/translations"), - "WEB_UI_CONFIG_FILE": str(repo_root / "tests/config/drone/ocis-config.json"), - "THUMBNAILS_TXT_FONTMAP_FILE": str(repo_root / "tests/config/drone/fontsMap.json"), + "WEB_UI_CONFIG_FILE": str(repo_root / "tests/config/ci/ocis-config.json"), + "THUMBNAILS_TXT_FONTMAP_FILE": str(repo_root / "tests/config/ci/fontsMap.json"), # default tika off (overridden by search2 extraServerEnvironment) "SEARCH_EXTRACTOR_TYPE": "basic", "FRONTEND_FULL_TEXT_SEARCH_ENABLED": "false", @@ -417,7 +416,7 @@ def main() -> int: # OCM federation: rewrite providers.json with localhost URLs if cfg["federationServer"]: - providers_src = repo_root / "tests/config/drone/providers.json" + providers_src = repo_root / "tests/config/ci/providers.json" providers = json.loads(providers_src.read_text()) for p in providers: # replace container DNS names with localhost @@ -438,12 +437,12 @@ def main() -> int: # init ocis run([str(ocis_bin), "init", "--insecure", "true"]) shutil.copy( - repo_root / "tests/config/drone/app-registry.yaml", + repo_root / "tests/config/ci/app-registry.yaml", ocis_config_dir / "app-registry.yaml", ) - # generate fontsMap.json with correct font path (drone hardcodes /drone/src/...) - font_path = str(repo_root / "tests/config/drone/NotoSans.ttf") + # generate fontsMap.json with the correct absolute font path for this runner + font_path = str(repo_root / "tests/config/ci/NotoSans.ttf") fontmap_tmp = tempfile.NamedTemporaryFile( mode="w", suffix=".json", prefix="fontsMap-", delete=False) json.dump({"defaultFont": font_path}, fontmap_tmp) @@ -491,7 +490,7 @@ def main() -> int: run([str(ocis_bin), "init", "--insecure", "true", "--config-path", str(fed_config_dir)]) shutil.copy( - repo_root / "tests/config/drone/app-registry.yaml", + repo_root / "tests/config/ci/app-registry.yaml", fed_config_dir / "app-registry.yaml", ) @@ -513,11 +512,11 @@ def main() -> int: # → healthz never binds → 300s timeout. Use Python's built-in HTTP server # instead; it handles concurrent connections without gaps. run(["docker", "run", "-d", "--name", "fakeoffice", "--network", "host", - "-v", f"{repo_root}:/drone/src:ro", + "-v", f"{repo_root}:/ocis:ro", "python:3-alpine", "python3", "-c", "import http.server, pathlib\n" - "body = pathlib.Path('/drone/src/tests/config/drone/hosting-discovery.xml').read_bytes()\n" + "body = pathlib.Path('/ocis/tests/config/ci/hosting-discovery.xml').read_bytes()\n" "class H(http.server.BaseHTTPRequestHandler):\n" " def do_GET(self):\n" " self.send_response(200)\n" @@ -552,7 +551,7 @@ def main() -> int: # Drone avoids this because each service has its own network namespace. subprocess.run(["sudo", "systemctl", "stop", "postgresql"], capture_output=True) - only_office_json = repo_root / "tests/config/drone/only-office.json" + only_office_json = repo_root / "tests/config/ci/only-office.json" run(["docker", "run", "-d", "--name", "onlyoffice", "--network", "host", "-e", "WOPI_ENABLED=true", "-e", "USE_UNAUTHORIZED_STORAGE=true", diff --git a/tests/acceptance/run-litmus.py b/tests/acceptance/run-litmus.py index 631f2e7f94f..7b775cbf3a8 100644 --- a/tests/acceptance/run-litmus.py +++ b/tests/acceptance/run-litmus.py @@ -2,7 +2,6 @@ """ Run litmus WebDAV compliance tests locally and in GitHub Actions CI. -Config sourced from .drone.star litmus() / setupForLitmus() — single source of truth. Usage: python3 tests/acceptance/run-litmus.py """ @@ -17,7 +16,7 @@ import time from pathlib import Path # --------------------------------------------------------------------------- -# Constants (mirroring .drone.star) +# Constants # --------------------------------------------------------------------------- # HTTPS — matching drone: ocis init generates a self-signed cert; proxy uses TLS by default. @@ -57,7 +56,7 @@ def base_server_env(repo_root: Path, ocis_config_dir: str, ocis_public_url: str) "NATS_NATS_PORT": "9233", "OCIS_JWT_SECRET": "some-ocis-jwt-secret", "EVENTHISTORY_STORE": "memory", - "WEB_UI_CONFIG_FILE": str(repo_root / "tests/config/drone/ocis-config.json"), + "WEB_UI_CONFIG_FILE": str(repo_root / "tests/config/ci/ocis-config.json"), } @@ -82,7 +81,7 @@ def ocis_healthy(ocis_url: str) -> bool: def setup_for_litmus(ocis_url: str) -> tuple: """ - Translate tests/config/drone/setup-for-litmus.sh to Python. + Translate tests/config/ci/setup-for-litmus.sh to Python. Returns (space_id, public_token). """ # get personal space ID @@ -189,7 +188,7 @@ def main() -> int: check=True, ) shutil.copy( - repo_root / "tests/config/drone/app-registry.yaml", + repo_root / "tests/config/ci/app-registry.yaml", ocis_config_dir / "app-registry.yaml", ) diff --git a/tests/acceptance/run-wopi.py b/tests/acceptance/run-wopi.py index 93607032bb2..d152e72ae1f 100644 --- a/tests/acceptance/run-wopi.py +++ b/tests/acceptance/run-wopi.py @@ -2,7 +2,6 @@ """ Run WOPI validator tests locally and in GitHub Actions CI. -Config sourced from .drone.star wopiValidatorTests() — single source of truth. Usage: python3 tests/acceptance/run-wopi.py --type builtin python3 tests/acceptance/run-wopi.py --type cs3 """ @@ -21,7 +20,7 @@ import urllib.parse from pathlib import Path # --------------------------------------------------------------------------- -# Constants (mirroring .drone.star) +# Constants # --------------------------------------------------------------------------- # HTTPS — matching drone; host-side curl calls use -k. @@ -119,7 +118,7 @@ def base_server_env(repo_root: Path, ocis_config_dir: str, ocis_public_url: str, "NATS_NATS_PORT": "9233", "OCIS_JWT_SECRET": "some-ocis-jwt-secret", "EVENTHISTORY_STORE": "memory", - "WEB_UI_CONFIG_FILE": str(repo_root / "tests/config/drone/ocis-config.json"), + "WEB_UI_CONFIG_FILE": str(repo_root / "tests/config/ci/ocis-config.json"), # wopi_validator extras (drone ocisServer deploy_type="wopi_validator") "GATEWAY_GRPC_ADDR": "0.0.0.0:9142", "APP_PROVIDER_EXTERNAL_ADDR": "com.owncloud.api.app-provider", @@ -265,16 +264,15 @@ def main() -> int: try: # --- fakeoffice: serves hosting-discovery.xml on :8080 --- - # Mirrors drone fakeOffice() — owncloudci/alpine running serve-hosting-discovery.sh. - # Repo is mounted at /drone/src (the path the script uses). + # Mirrors the old fakeOffice() step — owncloudci/alpine running serve-hosting-discovery.sh. containers.append("wopi-fakeoffice-fake") subprocess.run(["docker", "rm", "-f", "wopi-fakeoffice-fake"], capture_output=True) subprocess.run([ "docker", "run", "-d", "--name", "wopi-fakeoffice-fake", "-p", "8080:8080", - "-v", f"{repo_root}:/drone/src", + "-v", f"{repo_root}:/ocis", FAKEOFFICE_IMAGE, - "sh", "/drone/src/tests/config/drone/serve-hosting-discovery.sh", + "sh", "/ocis/tests/config/ci/serve-hosting-discovery.sh", ], check=True) wait_for(lambda: tcp_reachable(bridge_ip, 8080), 60, "fakeoffice:8080") @@ -291,7 +289,7 @@ def main() -> int: env=server_env, check=True, ) shutil.copy( - repo_root / "tests/config/drone/app-registry.yaml", + repo_root / "tests/config/ci/app-registry.yaml", ocis_config_dir / "app-registry.yaml", ) @@ -324,7 +322,7 @@ def main() -> int: else: # cs3: patch wopiserver.conf (replace container hostname with bridge_ip), # then run cs3org/wopiserver as a Docker container. - conf_text = (repo_root / "tests/config/drone/wopiserver.conf").read_text() + conf_text = (repo_root / "tests/config/ci/wopiserver.conf").read_text() conf_text = conf_text.replace("ocis-server", bridge_ip) conf_tmp = Path("/tmp/wopiserver-patched.conf") conf_tmp.write_text(conf_text) diff --git a/tests/acceptance/run.sh b/tests/acceptance/run.sh index 29de2cc6f1f..17f45a0c769 100755 --- a/tests/acceptance/run.sh +++ b/tests/acceptance/run.sh @@ -677,18 +677,4 @@ then ${RED_COLOR}; printf "%s\n" "${UNEXPECTED_BEHAT_EXIT_STATUSES[@]}" fi -# # sync the file-system so all output will be flushed to storage. -# # In drone we sometimes see that the last lines of output are missing from the -# # drone log. -# sync - -# # If we are running in drone CI, then sleep for a bit to (hopefully) let the -# # drone agent send all the output to the drone server. -# NOTE: Not using this anymore, please enable it if needed -# if [ -n "${CI_REPO}" ] -# then -# echo "sleeping for 30 seconds at end of test run" -# sleep 30 -# fi - exit ${FINAL_EXIT_STATUS} diff --git a/tests/config/drone/NotoSans.ttf b/tests/config/ci/NotoSans.ttf similarity index 100% rename from tests/config/drone/NotoSans.ttf rename to tests/config/ci/NotoSans.ttf diff --git a/tests/config/drone/app-registry.yaml b/tests/config/ci/app-registry.yaml similarity index 100% rename from tests/config/drone/app-registry.yaml rename to tests/config/ci/app-registry.yaml diff --git a/tests/config/drone/banned-password-list.txt b/tests/config/ci/banned-password-list.txt similarity index 100% rename from tests/config/drone/banned-password-list.txt rename to tests/config/ci/banned-password-list.txt diff --git a/tests/config/drone/check_go_bin_cache.sh b/tests/config/ci/check_go_bin_cache.sh similarity index 81% rename from tests/config/drone/check_go_bin_cache.sh rename to tests/config/ci/check_go_bin_cache.sh index dac1e142984..ff5f37a07e1 100644 --- a/tests/config/drone/check_go_bin_cache.sh +++ b/tests/config/ci/check_go_bin_cache.sh @@ -7,7 +7,7 @@ ROOT_PATH="$1" if [ -z "$1" ]; then - ROOT_PATH="/drone/src" + ROOT_PATH="." fi BINGO_DIR="$ROOT_PATH/.bingo" @@ -19,8 +19,6 @@ go_cache=$(mc find s3/$CACHE_BUCKET/ocis/go-bin/$BINGO_HASH/$2 2>&1 | grep 'Obje if [[ -z "$go_cache" ]] then echo "[INFO] Go bin cache with has '$BINGO_HASH' exists." - # https://discourse.drone.io/t/how-to-exit-a-pipeline-early-without-failing/3951 - # exit a Pipeline early without failing exit 78 else # stored hash of a .bingo folder to '.bingo_hash' file diff --git a/tests/config/drone/check_web_cache.sh b/tests/config/ci/check_web_cache.sh similarity index 76% rename from tests/config/drone/check_web_cache.sh rename to tests/config/ci/check_web_cache.sh index 752dac0470b..b9651613dd7 100644 --- a/tests/config/drone/check_web_cache.sh +++ b/tests/config/ci/check_web_cache.sh @@ -1,5 +1,7 @@ #!/bin/bash -source .drone.env +# Checks S3 MinIO cache for web test runner artifacts (acceptance/e2e/web). +# Sources ci.env to get WEB_COMMITID used as the cache key. +source ci.env # if no $1 is supplied end the script # Can be web, acceptance or e2e @@ -13,8 +15,6 @@ web_cache=$(mc find s3/$CACHE_BUCKET/ocis/web-test-runner/$WEB_COMMITID/$1 2>&1 if [[ -z "$web_cache" ]]; then echo "$1 cache with commit id $WEB_COMMITID already available." - # https://discourse.drone.io/t/how-to-exit-a-pipeline-early-without-failing/3951 - # exit a Pipeline early without failing exit 78 else echo "$1 cache with commit id $WEB_COMMITID was not available." diff --git a/tests/config/drone/csp.yaml b/tests/config/ci/csp.yaml similarity index 100% rename from tests/config/drone/csp.yaml rename to tests/config/ci/csp.yaml diff --git a/tests/config/ci/fontsMap.json b/tests/config/ci/fontsMap.json new file mode 100644 index 00000000000..b33a3778ec4 --- /dev/null +++ b/tests/config/ci/fontsMap.json @@ -0,0 +1,3 @@ +{ + "defaultFont": "/ocis/tests/config/ci/NotoSans.ttf" +} diff --git a/tests/config/drone/hosting-discovery.xml b/tests/config/ci/hosting-discovery.xml similarity index 100% rename from tests/config/drone/hosting-discovery.xml rename to tests/config/ci/hosting-discovery.xml diff --git a/tests/config/drone/ocis-ci-realm.dist.json b/tests/config/ci/ocis-ci-realm.dist.json similarity index 100% rename from tests/config/drone/ocis-ci-realm.dist.json rename to tests/config/ci/ocis-ci-realm.dist.json diff --git a/tests/config/drone/ocis-config.json b/tests/config/ci/ocis-config.json similarity index 100% rename from tests/config/drone/ocis-config.json rename to tests/config/ci/ocis-config.json diff --git a/tests/config/drone/only-office.json b/tests/config/ci/only-office.json similarity index 100% rename from tests/config/drone/only-office.json rename to tests/config/ci/only-office.json diff --git a/tests/config/drone/providers.json b/tests/config/ci/providers.json similarity index 100% rename from tests/config/drone/providers.json rename to tests/config/ci/providers.json diff --git a/tests/config/drone/run_k6_tests.sh b/tests/config/ci/run_k6_tests.sh similarity index 100% rename from tests/config/drone/run_k6_tests.sh rename to tests/config/ci/run_k6_tests.sh diff --git a/tests/config/ci/serve-hosting-discovery.sh b/tests/config/ci/serve-hosting-discovery.sh new file mode 100644 index 00000000000..3a1c6fa84ce --- /dev/null +++ b/tests/config/ci/serve-hosting-discovery.sh @@ -0,0 +1,5 @@ +#!/bin/sh + +while true; do + echo -e "HTTP/1.1 200 OK\n\n$(cat /ocis/tests/config/ci/hosting-discovery.xml)" | nc -l -k -p 8080 +done diff --git a/tests/config/drone/setup-for-litmus.sh b/tests/config/ci/setup-for-litmus.sh similarity index 100% rename from tests/config/drone/setup-for-litmus.sh rename to tests/config/ci/setup-for-litmus.sh diff --git a/tests/config/drone/wopiserver.conf b/tests/config/ci/wopiserver.conf similarity index 100% rename from tests/config/drone/wopiserver.conf rename to tests/config/ci/wopiserver.conf diff --git a/tests/config/drone/fontsMap.json b/tests/config/drone/fontsMap.json deleted file mode 100644 index 889781d3396..00000000000 --- a/tests/config/drone/fontsMap.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "defaultFont": "/drone/src/tests/config/drone/NotoSans.ttf" -} diff --git a/tests/config/drone/serve-hosting-discovery.sh b/tests/config/drone/serve-hosting-discovery.sh deleted file mode 100644 index b5975786659..00000000000 --- a/tests/config/drone/serve-hosting-discovery.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh - -while true; do - echo -e "HTTP/1.1 200 OK\n\n$(cat /drone/src/tests/config/drone/hosting-discovery.xml)" | nc -l -k -p 8080 -done diff --git a/tests/config/k8s/Makefile b/tests/config/k8s/Makefile index ba63bc7d4cc..8fb94d10078 100644 --- a/tests/config/k8s/Makefile +++ b/tests/config/k8s/Makefile @@ -25,7 +25,7 @@ prepare-charts: @test -d "$(CHART_REPO)" || git clone --single-branch -b main --depth 1 https://github.com/owncloud/ocis-charts.git $(CHART_REPO) bash setup.sh $(CHART_REPO) kubectl create namespace $(DOMAIN) || true - kubectl create configmap -n $(DOMAIN) ocis-fonts-ttf --from-file=../drone/NotoSans.ttf || true + kubectl create configmap -n $(DOMAIN) ocis-fonts-ttf --from-file=../ci/NotoSans.ttf || true .PHONY: deploy-ocis deploy-ocis: diff --git a/tools/ci-reporter/cmd/list-failed-commits/main.go b/tools/ci-reporter/cmd/list-failed-commits/main.go deleted file mode 100644 index b9acc5ce166..00000000000 --- a/tools/ci-reporter/cmd/list-failed-commits/main.go +++ /dev/null @@ -1,379 +0,0 @@ -// Usage examples: -// go run ./cmd/list-failed-commits --max-commits 20 -// go run ./cmd/list-failed-commits --max-commits 50 --out failed.json -// go run ./cmd/list-failed-commits --github-token $GITHUB_TOKEN --max-commits 100 -// go run ./cmd/list-failed-commits --repo owncloud/ocis --branch master --max-commits 20 -// go run ./cmd/list-failed-commits --since 7d --max-commits 50 -// go run ./cmd/list-failed-commits --since 30d --out failed.json -// go run ./cmd/list-failed-commits --since 2026-01-01 --max-commits 100 -// go run ./cmd/list-failed-commits --since 2026-02-15 --out recent.json - -package main - -import ( - "encoding/json" - "flag" - "fmt" - "io" - "net/http" - "os" - "sort" - "strings" - "time" - - "github.com/owncloud/ocis/v2/tools/ci-reporter/pkg/droneextractor" - "github.com/owncloud/ocis/v2/tools/ci-reporter/pkg/githubextractor" - "github.com/owncloud/ocis/v2/tools/ci-reporter/pkg/util" -) - -const ( - defaultRepo = "owncloud/ocis" - defaultBranch = "master" - requestDelay = 1 * time.Second - defaultLimit = 20 - defaultUnlimited = 999999999 -) - -type RunConfig struct { - Repo string - Branch string - MaxCommits int - SinceRaw string - SinceParsed string - OutFile string - Token string - Command string - FetchFailedPipelineHistory bool -} - -type FailureCount struct { - StageName string `json:"stage_name"` - StepName string `json:"step_name"` - Count int `json:"count"` -} - -type DateRange struct { - StartDate string `json:"start_date"` - EndDate string `json:"end_date"` -} - -type Raport struct { - Args string `json:"args"` - Repo string `json:"repo"` - Branch string `json:"branch"` - DateRange DateRange `json:"date_range"` - TotalCommits int `json:"total_commits"` - FailedCommits int `json:"failed_commits"` - Percentage float64 `json:"percentage"` -} - -type RaportMetadata struct { - Args string - Repo string - Branch string - DateRange DateRange - TotalCommits int -} - -type Report struct { - Raport *Raport `json:"raport"` - Count []FailureCount `json:"count"` - Pipelines []FailedCommit `json:"pipelines"` -} - -type FailedCommit struct { - PR int `json:"pr,omitempty"` - SHA string `json:"sha"` - Date string `json:"date"` - Subject string `json:"subject"` - HTMLURL string `json:"html_url"` - CombinedState string `json:"combined_state"` - FailedContexts []StatusContext `json:"failed_contexts"` - PipelineInfo *droneextractor.PipelineInfo `json:"pipeline_info,omitempty"` - FailedPipelineHistory []droneextractor.PipelineInfoSummary `json:"failed_pipeline_history,omitempty"` - PrPipelineHistory []droneextractor.PipelineInfoSummary `json:"pr_pipeline_history,omitempty"` -} - -type StatusContext struct { - Context string `json:"context"` - State string `json:"state"` - TargetURL string `json:"target_url"` - Description string `json:"description"` -} - -func main() { - repo := flag.String("repo", defaultRepo, "GitHub repository (owner/repo)") - branch := flag.String("branch", defaultBranch, "Branch name") - maxCommits := flag.Int("max-commits", 0, "Maximum commits to check (default: 20 if no --since, unlimited if --since set)") - since := flag.String("since", "", "Date filter: YYYY-MM-DD, RFC3339 timestamp, or 'Nd' for last N days (e.g., '7d', '30d')") - outFile := flag.String("out", "", "Output file path (default: stdout)") - githubToken := flag.String("github-token", "", "GitHub token (optional; falls back to env GITHUB_TOKEN)") - failedPipelineHistory := flag.Bool("failed_pipeline_history", false, "if set, fetch failed_pipeline_history per commit (extra Drone API calls)") - flag.Parse() - - token := strings.TrimSpace(*githubToken) - if token == "" { - token = strings.TrimSpace(os.Getenv("GITHUB_TOKEN")) - } - - if token != "" { - fmt.Fprintf(os.Stderr, "Using GitHub token\n") - } else { - fmt.Fprintf(os.Stderr, "No token provided, unauthenticated, 60 req/hr limit\n") - } - - command := strings.Join(os.Args[1:], " ") - command = util.RedactGitHubToken(command) - - parsedSince, err := util.ParseSinceFlag(*since) - if err != nil { - fmt.Fprintf(os.Stderr, "Error parsing --since flag: %v\n", err) - os.Exit(1) - } - - // Determine final max commits based on git-like UX: - // - No flags: default to 20 - // - --since only: unlimited (all in range) - // - --max-commits only: use explicit value - // - Both: use explicit value (both filters apply) - finalMaxCommits := *maxCommits - if finalMaxCommits == 0 { - if *since != "" { - finalMaxCommits = defaultUnlimited // Unlimited when --since is used - } else { - finalMaxCommits = defaultLimit // Default for no flags - } - } - - config := RunConfig{ - Repo: *repo, - Branch: *branch, - MaxCommits: finalMaxCommits, - SinceRaw: *since, - SinceParsed: parsedSince, - OutFile: *outFile, - Token: token, - Command: command, - FetchFailedPipelineHistory: *failedPipelineHistory, - } - - if err := run(config); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) - } -} - -func run(cfg RunConfig) error { - // Configure Transport to prevent stale connection reuse during long pagination - transport := &http.Transport{ - MaxIdleConns: 10, - IdleConnTimeout: 30 * time.Second, - DisableKeepAlives: false, - MaxIdleConnsPerHost: 2, - } - client := &http.Client{ - Timeout: 60 * time.Second, // Increased for long-running pagination - Transport: transport, - } - githubExtractor := githubextractor.NewExtractor(client, cfg.Token) - droneExtractor := droneextractor.NewExtractor(client) - - // Build scanning message - var scanMsg string - if cfg.SinceRaw != "" { - scanMsg = fmt.Sprintf("Scanning commits since %s from %s/%s", cfg.SinceRaw, cfg.Repo, cfg.Branch) - } else { - scanMsg = fmt.Sprintf("Scanning up to %d commits from %s/%s", cfg.MaxCommits, cfg.Repo, cfg.Branch) - } - fmt.Fprintf(os.Stderr, "%s\n", scanMsg) - commits, err := githubExtractor.GetCommits(cfg.Repo, cfg.Branch, cfg.MaxCommits, cfg.SinceParsed) - if err != nil { - return fmt.Errorf("fetching commits: %w", err) - } - - var failedCommits []FailedCommit - for _, commit := range commits { - status, err := githubExtractor.GetCommitStatus(cfg.Repo, commit.SHA) - if err != nil { - fmt.Fprintf(os.Stderr, "⚠ %s: %v\n", commit.SHA[:7], err) - time.Sleep(requestDelay) - continue - } - - if status.State == "failure" || status.State == "error" { - var failedCtxs []StatusContext - var pipelineInfo *droneextractor.PipelineInfo - - for _, s := range status.Statuses { - if s.State != "success" { - // Skip Drone entries - they'll be in pipeline_info instead - if droneExtractor.IsDroneURL(s.TargetURL) { - info, err := droneExtractor.Extract(s.TargetURL) - if err == nil { - pipelineInfo = info - } - // Don't add to failed_contexts to avoid redundancy - continue - } - failedCtxs = append(failedCtxs, toStatusContext(s)) - } - } - // TODO: Refactor redundant field assignment - prPipelineHistory always assigned, failedPipelineHistory conditional - var failedPipelineHistory []droneextractor.PipelineInfoSummary - var prPipelineHistory []droneextractor.PipelineInfoSummary - var prNumber int - var headRef string - - // Get PR for this commit (master commit -> PR ID -> PR branch) - prs, err := githubExtractor.GetPRsForCommit(cfg.Repo, commit.SHA) - if err == nil && len(prs) > 0 { - prNumber = prs[0].Number - headRef = prs[0].Head.Ref - - // Get failed builds by PR branch (black box: all logic in droneextractor) - failedBuilds, err := droneExtractor.GetFailedBuildsByPRBranch(droneextractor.BaseURL, cfg.Repo, headRef) - if err == nil { - prPipelineHistory = failedBuilds - if cfg.FetchFailedPipelineHistory { - failedPipelineHistory = failedBuilds - } - } - } - - // Initialize empty slice if flag is set but no PR/builds found - if cfg.FetchFailedPipelineHistory && failedPipelineHistory == nil { - failedPipelineHistory = []droneextractor.PipelineInfoSummary{} - } - - subject := util.ExtractSubject(commit.Commit.Message) - failedCommits = append(failedCommits, FailedCommit{ - PR: prNumber, - SHA: commit.SHA, - Date: commit.Commit.Author.Date, - Subject: subject, - HTMLURL: commit.HTMLURL, - CombinedState: status.State, - FailedContexts: failedCtxs, - PipelineInfo: pipelineInfo, - FailedPipelineHistory: failedPipelineHistory, - PrPipelineHistory: prPipelineHistory, - }) - - // Single line output: ✗ sha subject -> PR #num (branch: name) - if prNumber > 0 && headRef != "" { - fmt.Fprintf(os.Stderr, "✗ %s %s -> PR #%d (branch: %s)\n", commit.SHA[:7], subject, prNumber, headRef) - } else { - fmt.Fprintf(os.Stderr, "✗ %s %s\n", commit.SHA[:7], subject) - } - } - - time.Sleep(requestDelay) - } - - fmt.Fprintf(os.Stderr, "\nResult: %d failed / %d total\n", len(failedCommits), len(commits)) - - var minDate, maxDate string - for _, c := range commits { - date := c.Commit.Author.Date - if minDate == "" || date < minDate { - minDate = date - } - if maxDate == "" || date > maxDate { - maxDate = date - } - } - - metadata := RaportMetadata{ - Args: cfg.Command, - Repo: cfg.Repo, - Branch: cfg.Branch, - DateRange: DateRange{StartDate: minDate, EndDate: maxDate}, - TotalCommits: len(commits), - } - - report := generateReport(failedCommits, metadata) - - var w io.Writer = os.Stdout - if cfg.OutFile != "" { - f, err := os.Create(cfg.OutFile) - if err != nil { - return fmt.Errorf("creating output file: %w", err) - } - defer f.Close() - w = f - fmt.Fprintf(os.Stderr, "Writing JSON to %s...\n", cfg.OutFile) - } - - enc := json.NewEncoder(w) - enc.SetIndent("", " ") - if err := enc.Encode(report); err != nil { - return fmt.Errorf("encoding JSON: %w", err) - } - - return nil -} - -func toStatusContext(ctx githubextractor.StatusContext) StatusContext { - return StatusContext{ - Context: ctx.Context, - State: ctx.State, - TargetURL: ctx.TargetURL, - Description: ctx.Description, - } -} - - -func generateReport(failedCommits []FailedCommit, metadata RaportMetadata) *Report { - countMap := make(map[string]int) - - for _, commit := range failedCommits { - if commit.PipelineInfo == nil { - continue - } - for _, stage := range commit.PipelineInfo.PipelineStages { - for _, step := range stage.Steps { - if step.Status == "failure" { - key := stage.StageName + "/" + step.StepName - countMap[key]++ - } - } - } - } - - var counts []FailureCount - for key, count := range countMap { - parts := strings.Split(key, "/") - if len(parts) >= 2 { - counts = append(counts, FailureCount{ - StageName: parts[0], - StepName: strings.Join(parts[1:], "/"), - Count: count, - }) - } - } - - sort.Slice(counts, func(i, j int) bool { - return counts[i].Count > counts[j].Count - }) - - percentage := 0.0 - if metadata.TotalCommits > 0 { - percentage = float64(len(failedCommits)) / float64(metadata.TotalCommits) * 100.0 - } - - raport := &Raport{ - Args: metadata.Args, - Repo: metadata.Repo, - Branch: metadata.Branch, - DateRange: metadata.DateRange, - TotalCommits: metadata.TotalCommits, - FailedCommits: len(failedCommits), - Percentage: percentage, - } - - return &Report{ - Raport: raport, - Count: counts, - Pipelines: failedCommits, - } -} diff --git a/tools/ci-reporter/cmd/list-flaky-tests/main.go b/tools/ci-reporter/cmd/list-flaky-tests/main.go new file mode 100644 index 00000000000..5b57f218eb7 --- /dev/null +++ b/tools/ci-reporter/cmd/list-flaky-tests/main.go @@ -0,0 +1,269 @@ +// Usage examples: +// go run ./cmd/list-flaky-tests --since 14d +// go run ./cmd/list-flaky-tests --since 3m --workflow acceptance-tests.yml +// go run ./cmd/list-flaky-tests --github-token $GITHUB_TOKEN --since 30d +// go run ./cmd/list-flaky-tests --repo owncloud/ocis --since 7d --out report.json + +package main + +import ( + "encoding/json" + "flag" + "fmt" + "io" + "net/http" + "os" + "sort" + "strings" + "time" + + "github.com/owncloud/ocis/v2/tools/ci-reporter/pkg/ghaextractor" + "github.com/owncloud/ocis/v2/tools/ci-reporter/pkg/util" +) + +const ( + defaultRepo = "owncloud/ocis" + defaultWorkflow = "acceptance-tests.yml" +) + +type Summary struct { + Args string `json:"args"` + Repo string `json:"repo"` + Workflow string `json:"workflow"` + DateRange Range `json:"date_range"` + TotalRuns int `json:"total_runs"` + RestartedRuns int `json:"restarted_runs"` + RestartRatePct float64 `json:"restart_rate_pct"` + TotalTimeLostMinutes float64 `json:"total_time_lost_minutes"` +} + +type Range struct { + Start string `json:"start"` + End string `json:"end"` +} + +type FlakyJob struct { + JobName string `json:"job_name"` + FailThenPassCount int `json:"fail_then_pass_count"` + FailureRatePct float64 `json:"failure_rate_pct"` +} + +type Report struct { + Summary Summary `json:"summary"` + FlakyJobs []FlakyJob `json:"flaky_jobs"` +} + +func main() { + repo := flag.String("repo", defaultRepo, "GitHub repository (owner/repo)") + workflow := flag.String("workflow", defaultWorkflow, "Workflow filename (e.g. acceptance-tests.yml)") + since := flag.String("since", "14d", "Date filter: YYYY-MM-DD, RFC3339, or 'Nd'/'Nm' (e.g. '7d', '3m')") + outFile := flag.String("out", "", "Output file path (default: stdout)") + githubToken := flag.String("github-token", "", "GitHub token (falls back to GITHUB_TOKEN env)") + flag.Parse() + + token := strings.TrimSpace(*githubToken) + if token == "" { + token = strings.TrimSpace(os.Getenv("GITHUB_TOKEN")) + } + if token != "" { + fmt.Fprintf(os.Stderr, "Using GitHub token\n") + } else { + fmt.Fprintf(os.Stderr, "No token provided, unauthenticated (60 req/hr limit)\n") + } + + sinceRaw := *since + // Support Nm month notation (not in ParseSinceFlag) + sinceRFC, err := parseSince(sinceRaw) + if err != nil { + fmt.Fprintf(os.Stderr, "Error parsing --since: %v\n", err) + os.Exit(1) + } + + command := strings.Join(os.Args[1:], " ") + command = util.RedactGitHubToken(command) + + transport := &http.Transport{ + MaxIdleConns: 10, + IdleConnTimeout: 30 * time.Second, + MaxIdleConnsPerHost: 2, + } + client := &http.Client{ + Timeout: 60 * time.Second, + Transport: transport, + } + extractor := ghaextractor.NewExtractor(client, token) + + fmt.Fprintf(os.Stderr, "Fetching workflow runs for %s/%s since %s...\n", *repo, *workflow, sinceRaw) + runs, err := extractor.GetWorkflowRuns(*repo, *workflow, sinceRFC) + if err != nil { + fmt.Fprintf(os.Stderr, "Error fetching runs: %v\n", err) + os.Exit(1) + } + fmt.Fprintf(os.Stderr, "Found %d completed runs\n", len(runs)) + + report, err := buildReport(extractor, *repo, *workflow, runs, command) + if err != nil { + fmt.Fprintf(os.Stderr, "Error building report: %v\n", err) + os.Exit(1) + } + + var w io.Writer = os.Stdout + if *outFile != "" { + f, err := os.Create(*outFile) + if err != nil { + fmt.Fprintf(os.Stderr, "Error creating output file: %v\n", err) + os.Exit(1) + } + defer f.Close() + w = f + fmt.Fprintf(os.Stderr, "Writing JSON to %s...\n", *outFile) + } + + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + if err := enc.Encode(report); err != nil { + fmt.Fprintf(os.Stderr, "Error encoding JSON: %v\n", err) + os.Exit(1) + } +} + +func buildReport(extractor *ghaextractor.Extractor, repo, workflow string, runs []ghaextractor.WorkflowRun, command string) (*Report, error) { + // The API returns one record per attempt, so a pipeline retried twice yields 3 records. + // Deduplicate by head_sha, keeping the highest-attempt record for each unique pipeline. + type pipelineRecord struct { + latest ghaextractor.WorkflowRun + maxAttempt int + } + bySHA := make(map[string]*pipelineRecord) + for _, run := range runs { + r := bySHA[run.HeadSHA] + if r == nil { + bySHA[run.HeadSHA] = &pipelineRecord{latest: run, maxAttempt: run.RunAttempt} + } else if run.RunAttempt > r.maxAttempt { + r.latest = run + r.maxAttempt = run.RunAttempt + } + } + + pipelines := make([]pipelineRecord, 0, len(bySHA)) + for _, r := range bySHA { + pipelines = append(pipelines, *r) + } + + var minDate, maxDate string + for _, r := range pipelines { + d := r.latest.CreatedAt + if minDate == "" || d < minDate { + minDate = d + } + if maxDate == "" || d > maxDate { + maxDate = d + } + } + + totalPipelines := len(pipelines) + restartedRuns := 0 + var timeLostMinutes float64 + // job name -> count of pipelines where that job was retried (any re-run, regardless of outcome) + flakyCount := make(map[string]int) + for i, r := range pipelines { + run := r.latest + fmt.Fprintf(os.Stderr, " [%d/%d] pipeline %d (max attempt %d)...\n", i+1, len(pipelines), run.ID, r.maxAttempt) + + wasRestarted := r.maxAttempt > 1 + if !wasRestarted { + continue + } + restartedRuns++ + + // Fetch all jobs across all attempts for this run to find which jobs were re-run + // and measure actual wall-clock time lost on retry attempts. + jobs, err := extractor.GetRunJobs(repo, run.ID) + if err != nil { + fmt.Fprintf(os.Stderr, " ⚠ run %d: %v\n", run.ID, err) + continue + } + + // Track which job names appeared in attempt > 1 (= developer had to wait for them again) + retriedJobNames := make(map[string]bool) + var retryStart, retryEnd time.Time + for _, j := range jobs { + if j.RunAttempt <= 1 || j.Name == "all-acceptance-tests" { + continue + } + retriedJobNames[j.Name] = true + if j.StartedAt != "" && j.CompletedAt != "" { + if s, err := time.Parse(time.RFC3339, j.StartedAt); err == nil { + if retryStart.IsZero() || s.Before(retryStart) { + retryStart = s + } + } + if e, err := time.Parse(time.RFC3339, j.CompletedAt); err == nil { + if e.After(retryEnd) { + retryEnd = e + } + } + } + } + + for name := range retriedJobNames { + flakyCount[name]++ + } + if !retryStart.IsZero() && retryEnd.After(retryStart) { + timeLostMinutes += retryEnd.Sub(retryStart).Minutes() + } + } + + restartRatePct := 0.0 + if totalPipelines > 0 { + restartRatePct = float64(restartedRuns) / float64(totalPipelines) * 100.0 + } + + flakyJobs := make([]FlakyJob, 0, len(flakyCount)) + for name, count := range flakyCount { + ratePct := 0.0 + if totalPipelines > 0 { + ratePct = float64(count) / float64(totalPipelines) * 100.0 + } + flakyJobs = append(flakyJobs, FlakyJob{ + JobName: name, + FailThenPassCount: count, + FailureRatePct: ratePct, + }) + } + sort.Slice(flakyJobs, func(i, j int) bool { + return flakyJobs[i].FailThenPassCount > flakyJobs[j].FailThenPassCount + }) + + return &Report{ + Summary: Summary{ + Args: command, + Repo: repo, + Workflow: workflow, + DateRange: Range{Start: minDate, End: maxDate}, + TotalRuns: totalPipelines, + RestartedRuns: restartedRuns, + RestartRatePct: restartRatePct, + TotalTimeLostMinutes: timeLostMinutes, + }, + FlakyJobs: flakyJobs, + }, nil +} + + +// parseSince extends util.ParseSinceFlag with Nm (months) and Nw (weeks) support. +func parseSince(s string) (string, error) { + if numStr, ok := strings.CutSuffix(s, "m"); ok { + var months int + if _, err := fmt.Sscanf(numStr, "%d", &months); err == nil { + return time.Now().AddDate(0, -months, 0).Format(time.RFC3339), nil + } + } + if numStr, ok := strings.CutSuffix(s, "w"); ok { + var weeks int + if _, err := fmt.Sscanf(numStr, "%d", &weeks); err == nil { + return time.Now().AddDate(0, 0, -weeks*7).Format(time.RFC3339), nil + } + } + return util.ParseSinceFlag(s) +} diff --git a/tools/ci-reporter/go.mod b/tools/ci-reporter/go.mod index be147011136..a07af682c22 100644 --- a/tools/ci-reporter/go.mod +++ b/tools/ci-reporter/go.mod @@ -1,5 +1,3 @@ module github.com/owncloud/ocis/v2/tools/ci-reporter go 1.24.0 - -require golang.org/x/net v0.50.0 // indirect diff --git a/tools/ci-reporter/go.sum b/tools/ci-reporter/go.sum index 13ce0c7b95e..e69de29bb2d 100644 --- a/tools/ci-reporter/go.sum +++ b/tools/ci-reporter/go.sum @@ -1,2 +0,0 @@ -golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60= -golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM= diff --git a/tools/ci-reporter/pkg/droneextractor/extractor.go b/tools/ci-reporter/pkg/droneextractor/extractor.go deleted file mode 100644 index 0e1d12b5bc4..00000000000 --- a/tools/ci-reporter/pkg/droneextractor/extractor.go +++ /dev/null @@ -1,631 +0,0 @@ -package droneextractor - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "regexp" - "sort" - "strings" - - "golang.org/x/net/html" -) - -const ( - // BaseURL is the default Drone instance URL - BaseURL = "https://drone.owncloud.com" -) - -type Extractor struct { - client *http.Client -} - -func NewExtractor(client *http.Client) *Extractor { - return &Extractor{client: client} -} - -// IsDroneURL checks if a URL is a Drone CI URL -func (e *Extractor) IsDroneURL(url string) bool { - return strings.Contains(url, "drone.owncloud.com") -} - -func (e *Extractor) Extract(buildURL string) (*PipelineInfo, error) { - apiURL := e.buildURLToAPIURL(buildURL) - if apiURL == "" { - return nil, fmt.Errorf("invalid build URL: %s", buildURL) - } - - buildData, err := e.fetchDroneAPI(apiURL) - if err != nil { - return nil, fmt.Errorf("fetching Drone API: %w", err) - } - - stages := e.parseStagesFromAPI(buildData, buildURL) - - var durationMinutes float64 - if buildData.Finished > 0 && buildData.Started > 0 { - durationMinutes = float64(buildData.Finished-buildData.Started) / 60.0 - } - - return &PipelineInfo{ - BuildURL: buildURL, - Started: buildData.Started, - Finished: buildData.Finished, - DurationMinutes: durationMinutes, - PipelineStages: stages, - }, nil -} - -func (e *Extractor) buildURLToAPIURL(buildURL string) string { - if !strings.Contains(buildURL, "drone.owncloud.com") { - return "" - } - parts := strings.Split(buildURL, "/") - if len(parts) < 5 { - return "" - } - repo := parts[3] + "/" + parts[4] - buildNum := parts[5] - return fmt.Sprintf("https://drone.owncloud.com/api/repos/%s/builds/%s", repo, buildNum) -} - -func (e *Extractor) fetchDroneAPI(url string) (*droneBuildResponse, error) { - resp, err := e.client.Get(url) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) - return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body)) - } - - var buildData droneBuildResponse - if err := json.NewDecoder(resp.Body).Decode(&buildData); err != nil { - return nil, err - } - - return &buildData, nil -} - -func (e *Extractor) parseStagesFromAPI(buildData *droneBuildResponse, buildURL string) []PipelineStage { - var stages []PipelineStage - - for _, apiStage := range buildData.Stages { - normalizedStatus := e.normalizeStatus(apiStage.Status) - if normalizedStatus == "success" || normalizedStatus == "skipped" { - continue - } - - stage := PipelineStage{ - StageNumber: apiStage.Number, - StageName: apiStage.Name, - Status: normalizedStatus, - Steps: []PipelineStep{}, - } - - for _, apiStep := range apiStage.Steps { - normalizedStepStatus := e.normalizeStatus(apiStep.Status) - if normalizedStepStatus == "skipped" { - continue - } - stepURL := fmt.Sprintf("%s/%d/%d", buildURL, apiStage.Number, apiStep.Number) - step := PipelineStep{ - StepNumber: apiStep.Number, - StepName: apiStep.Name, - Status: normalizedStepStatus, - URL: stepURL, - } - - if normalizedStepStatus == "failure" { - logs, err := e.fetchStepLogs(stepURL, buildURL, apiStage.Number, apiStep.Number) - if err == nil { - lines := strings.Split(logs, "\n") - if len(lines) > 500 && (strings.Contains(logs, "--- Failed scenarios:") || strings.Contains(logs, "Scenario:")) { - logs = e.extractBehatFailures(logs) - } - step.Logs = logs - } - } - - stage.Steps = append(stage.Steps, step) - } - - stages = append(stages, stage) - } - - return stages -} - -func (e *Extractor) normalizeStatus(status string) string { - switch strings.ToLower(status) { - case "success", "passed": - return "success" - case "failure", "failed", "error": - return "failure" - case "running", "pending", "started": - return "running" - case "skipped": - return "skipped" - default: - return status - } -} - -// droneBuildResponse matches the structure returned by Drone API: -// GET /api/repos/{owner}/{repo}/builds/{buildNumber} -// Verified against: https://drone.owncloud.com/api/repos/owncloud/ocis/builds/51629 -type droneBuildResponse struct { - Started int64 `json:"started"` - Finished int64 `json:"finished"` - Stages []droneStage `json:"stages"` -} - -type droneStage struct { - Number int `json:"number"` // Stage number (1, 2, 3, ...) - Name string `json:"name"` // Stage name (e.g., "API-wopi", "coding-standard-php8.4") - Status string `json:"status"` // "success", "failure", "running", etc. - Steps []droneStep `json:"steps"` // Array of steps in this stage -} - -type droneStep struct { - Number int `json:"number"` // Step number within stage - Name string `json:"name"` // Step name (e.g., "clone", "test-acceptance-api") - Status string `json:"status"` // "success", "failure", "skipped", etc. -} - -type droneLogEntry struct { - Pos int `json:"pos"` - Out string `json:"out"` - Time int64 `json:"time"` -} - -type BuildInfo struct { - BuildNumber int `json:"build_number"` - Status string `json:"status"` // "success", "failure", "error" - Started int64 `json:"started"` - Finished int64 `json:"finished"` - CommitSHA string `json:"commit_sha"` -} - -type droneBuildListItem struct { - Number int `json:"number"` - Status string `json:"status"` - Event string `json:"event"` // "pull_request", "push", etc. - Source string `json:"source"` // Source branch for PR builds - Target string `json:"target"` // Target branch for PR builds - After string `json:"after"` // Commit SHA - Started int64 `json:"started"` - Finished int64 `json:"finished"` -} - -func (e *Extractor) fetchStepLogs(stepURL, buildURL string, stageNum, stepNum int) (string, error) { - apiLogsURL := e.buildLogsAPIURL(buildURL, stageNum, stepNum) - if apiLogsURL != "" { - logs, err := e.fetchLogsFromAPI(apiLogsURL) - if err == nil { - return logs, nil - } - if err != nil && !strings.Contains(err.Error(), "401") && !strings.Contains(err.Error(), "403") { - return "", err - } - } - - return e.fetchLogsFromHTML(stepURL) -} - -func (e *Extractor) buildLogsAPIURL(buildURL string, stageNum, stepNum int) string { - if !strings.Contains(buildURL, "drone.owncloud.com") { - return "" - } - parts := strings.Split(buildURL, "/") - if len(parts) < 5 { - return "" - } - repo := parts[3] + "/" + parts[4] - buildNum := parts[5] - return fmt.Sprintf("https://drone.owncloud.com/api/repos/%s/builds/%s/logs/%d/%d", repo, buildNum, stageNum, stepNum) -} - -func (e *Extractor) fetchLogsFromAPI(apiURL string) (string, error) { - resp, err := e.client.Get(apiURL) - if err != nil { - return "", err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("HTTP %d", resp.StatusCode) - } - - var logEntries []droneLogEntry - if err := json.NewDecoder(resp.Body).Decode(&logEntries); err != nil { - return "", err - } - - var logs strings.Builder - for _, entry := range logEntries { - logs.WriteString(entry.Out) - } - - return logs.String(), nil -} - -func (e *Extractor) fetchLogsFromHTML(stepURL string) (string, error) { - resp, err := e.client.Get(stepURL) - if err != nil { - return "", err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("HTTP %d", resp.StatusCode) - } - - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", err - } - - return e.extractLogsFromHTML(string(body)) -} - -func (e *Extractor) extractLogsFromHTML(htmlContent string) (string, error) { - doc, err := html.Parse(strings.NewReader(htmlContent)) - if err != nil { - return "", err - } - - var logs strings.Builder - var extractText func(*html.Node) - extractText = func(n *html.Node) { - if n.Type == html.ElementNode { - if n.Data == "pre" || n.Data == "code" { - text := e.getTextContent(n) - if text != "" { - logs.WriteString(text) - logs.WriteString("\n") - } - } - } - for c := n.FirstChild; c != nil; c = c.NextSibling { - extractText(c) - } - } - - extractText(doc) - return strings.TrimSpace(logs.String()), nil -} - -func (e *Extractor) getTextContent(n *html.Node) string { - var text strings.Builder - var collectText func(*html.Node) - collectText = func(n *html.Node) { - if n.Type == html.TextNode { - text.WriteString(n.Data) - } - for c := n.FirstChild; c != nil; c = c.NextSibling { - collectText(c) - } - } - collectText(n) - return text.String() -} - -func (e *Extractor) extractBehatFailures(logs string) string { - var result strings.Builder - - // ANSI red code pattern - redCodePattern := regexp.MustCompile(`\x1b\[31m|\033\[31m|\[31m`) - ansiStripPattern := regexp.MustCompile(`\x1b\[[0-9;]*m|\033\[[0-9;]*m`) - - // Split by Scenario: or Scenario Outline: (case-insensitive) - // Use regex to find all scenario starts while preserving the marker - scenarioPattern := regexp.MustCompile(`(?i)(Scenario(?:\s+Outline)?:\s*)`) - matches := scenarioPattern.FindAllStringIndex(logs, -1) - - if len(matches) == 0 { - // No scenarios found, try to extract just "--- Failed scenarios:" section - return e.extractFailedScenariosSection(logs, ansiStripPattern) - } - - // Extract each scenario section - for i, match := range matches { - start := match[0] - end := len(logs) - if i+1 < len(matches) { - end = matches[i+1][0] - } - - scenarioSection := logs[start:end] - - // Check if this section contains ANSI red codes - if redCodePattern.MatchString(scenarioSection) { - // Strip ANSI codes and add to result - cleaned := ansiStripPattern.ReplaceAllString(scenarioSection, "") - if result.Len() > 0 { - result.WriteString("\n\n") - } - result.WriteString(cleaned) - } - } - - // Extract "--- Failed scenarios:" section - failedScenariosSection := e.extractFailedScenariosSection(logs, ansiStripPattern) - if failedScenariosSection != "" { - if result.Len() > 0 { - result.WriteString("\n\n") - } - result.WriteString(failedScenariosSection) - } - - extracted := strings.TrimSpace(result.String()) - if extracted == "" { - // If extraction failed, return original logs - return logs - } - - return extracted -} - -func (e *Extractor) extractFailedScenariosSection(logs string, ansiStripPattern *regexp.Regexp) string { - failedScenariosMarker := "--- Failed scenarios:" - if idx := strings.Index(logs, failedScenariosMarker); idx != -1 { - failedScenariosSection := logs[idx:] - cleaned := ansiStripPattern.ReplaceAllString(failedScenariosSection, "") - return cleaned - } - return "" -} - -// GetBuildsByCommitSHA queries Drone API for all builds matching a specific commit SHA -func (e *Extractor) GetBuildsByCommitSHA(baseURL, repo, commitSHA string) ([]BuildInfo, error) { - var allBuilds []BuildInfo - page := 1 - maxPages := 200 // Safety limit (25 items per page = 5000 builds max) - - for page <= maxPages { - url := fmt.Sprintf("%s/api/repos/%s/builds?page=%d", baseURL, repo, page) - resp, err := e.client.Get(url) - if err != nil { - return nil, fmt.Errorf("fetching build list: %w", err) - } - - if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) - resp.Body.Close() - return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body)) - } - - var buildList []droneBuildListItem - if err := json.NewDecoder(resp.Body).Decode(&buildList); err != nil { - resp.Body.Close() - return nil, fmt.Errorf("decoding build list: %w", err) - } - resp.Body.Close() - - // Stop when we get an empty page - if len(buildList) == 0 { - break - } - - // Filter builds by commit SHA - for _, item := range buildList { - if item.After == commitSHA { - allBuilds = append(allBuilds, BuildInfo{ - BuildNumber: item.Number, - Status: item.Status, - Started: item.Started, - Finished: item.Finished, - CommitSHA: item.After, - }) - } - } - - page++ - } - - // Sort by build number (ascending = chronological) - sort.Slice(allBuilds, func(i, j int) bool { - return allBuilds[i].BuildNumber < allBuilds[j].BuildNumber - }) - - return allBuilds, nil -} - -// GetBuildsByPRBranch queries Drone API for all builds matching PR event and source branch -func (e *Extractor) GetBuildsByPRBranch(baseURL, repo, sourceBranch string) ([]BuildInfo, error) { - var allBuilds []BuildInfo - page := 1 - maxPages := 200 // Safety limit (25 items per page = 5000 builds max) - - for page <= maxPages { - url := fmt.Sprintf("%s/api/repos/%s/builds?page=%d", baseURL, repo, page) - resp, err := e.client.Get(url) - if err != nil { - return nil, fmt.Errorf("fetching build list: %w", err) - } - - if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) - resp.Body.Close() - return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body)) - } - - var buildList []droneBuildListItem - if err := json.NewDecoder(resp.Body).Decode(&buildList); err != nil { - resp.Body.Close() - return nil, fmt.Errorf("decoding build list: %w", err) - } - resp.Body.Close() - - // Stop when we get an empty page - if len(buildList) == 0 { - break - } - - // Filter builds by event="pull_request" and source branch - for _, item := range buildList { - if item.Event == "pull_request" && item.Source == sourceBranch { - allBuilds = append(allBuilds, BuildInfo{ - BuildNumber: item.Number, - Status: item.Status, - Started: item.Started, - Finished: item.Finished, - CommitSHA: item.After, - }) - } - } - - page++ - } - - // Sort by build number (ascending = chronological) - sort.Slice(allBuilds, func(i, j int) bool { - return allBuilds[i].BuildNumber < allBuilds[j].BuildNumber - }) - - return allBuilds, nil -} - -// GetBuildsByPushBranch queries Drone API for all builds matching push/cron events to a specific branch (e.g., master). -// This is specifically for merged commits to main branches, not PR builds. -// It includes both "push" events (actual merges) and "cron" events (scheduled/nightly builds). -func (e *Extractor) GetBuildsByPushBranch(baseURL, repo, targetBranch string) ([]BuildInfo, error) { - var allBuilds []BuildInfo - page := 1 - maxPages := 200 // Safety limit (25 items per page = 5000 builds max) - - for page <= maxPages { - url := fmt.Sprintf("%s/api/repos/%s/builds?page=%d", baseURL, repo, page) - resp, err := e.client.Get(url) - if err != nil { - return nil, fmt.Errorf("fetching build list: %w", err) - } - - if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) - resp.Body.Close() - return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body)) - } - - var buildList []droneBuildListItem - if err := json.NewDecoder(resp.Body).Decode(&buildList); err != nil { - resp.Body.Close() - return nil, fmt.Errorf("decoding build list: %w", err) - } - resp.Body.Close() - - // Stop when we get an empty page - if len(buildList) == 0 { - break - } - - // Filter builds by event="push" or event="cron" and target branch - // "push" = actual merges to branch - // "cron" = scheduled/nightly builds running on the branch - for _, item := range buildList { - if (item.Event == "push" || item.Event == "cron") && item.Target == targetBranch { - allBuilds = append(allBuilds, BuildInfo{ - BuildNumber: item.Number, - Status: item.Status, - Started: item.Started, - Finished: item.Finished, - CommitSHA: item.After, - }) - } - } - - page++ - } - - // Sort by build number (ascending = chronological) - sort.Slice(allBuilds, func(i, j int) bool { - return allBuilds[i].BuildNumber < allBuilds[j].BuildNumber - }) - - return allBuilds, nil -} - -// extractBaseURL extracts the base URL (e.g., "https://drone.owncloud.com") from a build URL -func extractBaseURL(buildURL string) string { - if !strings.Contains(buildURL, "://") { - return "" - } - parts := strings.Split(buildURL, "/") - if len(parts) >= 3 { - return parts[0] + "//" + parts[2] - } - return "" -} - -// BuildInfoToPipelineSummary converts a BuildInfo to PipelineInfoSummary -func BuildInfoToPipelineSummary(build BuildInfo, baseURL, repo string) PipelineInfoSummary { - var durationMinutes float64 - if build.Finished > 0 && build.Started > 0 { - durationMinutes = float64(build.Finished-build.Started) / 60.0 - } - - // URL format: https://drone.owncloud.com/owncloud/ocis/{buildNumber} - // repo format: "owncloud/ocis" - buildURL := fmt.Sprintf("%s/%s/%d", baseURL, repo, build.BuildNumber) - - return PipelineInfoSummary{ - BuildURL: buildURL, - Started: build.Started, - Finished: build.Finished, - DurationMinutes: durationMinutes, - Status: build.Status, - } -} - -// BuildInfoToPipelineSummaryWithStages converts a BuildInfo to PipelineInfoSummary with failed stages -// by fetching full pipeline details from the build URL -func (e *Extractor) BuildInfoToPipelineSummaryWithStages(build BuildInfo, baseURL, repo string) PipelineInfoSummary { - summary := BuildInfoToPipelineSummary(build, baseURL, repo) - - // Fetch full pipeline info to extract failed stages - pipelineInfo, err := e.Extract(summary.BuildURL) - if err == nil && pipelineInfo != nil { - var failedStages []FailedStage - for _, stage := range pipelineInfo.PipelineStages { - if stage.Status == "failure" || stage.Status == "error" { - failedStages = append(failedStages, FailedStage{ - StageNumber: stage.StageNumber, - StageName: stage.StageName, - Status: stage.Status, - }) - } - } - summary.FailedStages = failedStages - } - - return summary -} - -// IsFailedBuild checks if a build status indicates failure -func IsFailedBuild(status string) bool { - normalized := strings.ToLower(status) - return normalized == "failure" || normalized == "failed" || normalized == "error" -} - -// GetFailedBuildsByPRBranch returns failed builds for a PR branch with pipeline summaries -func (e *Extractor) GetFailedBuildsByPRBranch(baseURL, repo, sourceBranch string) ([]PipelineInfoSummary, error) { - builds, err := e.GetBuildsByPRBranch(baseURL, repo, sourceBranch) - if err != nil { - return nil, err - } - - var failedSummaries []PipelineInfoSummary - for _, build := range builds { - if IsFailedBuild(build.Status) { - summary := e.BuildInfoToPipelineSummaryWithStages(build, baseURL, repo) - failedSummaries = append(failedSummaries, summary) - // Rate limiting delay for API calls in BuildInfoToPipelineSummaryWithStages - } - } - - return failedSummaries, nil -} diff --git a/tools/ci-reporter/pkg/droneextractor/pr_builds.go b/tools/ci-reporter/pkg/droneextractor/pr_builds.go deleted file mode 100644 index d052cdc9f42..00000000000 --- a/tools/ci-reporter/pkg/droneextractor/pr_builds.go +++ /dev/null @@ -1,78 +0,0 @@ -package droneextractor - -import ( - "fmt" - "io" - "time" - - "github.com/owncloud/ocis/v2/tools/ci-reporter/pkg/githubextractor" -) - -const requestDelay = 1 * time.Second - -// FetchPRBuilds fetches all Drone builds for a PR by querying: -// 1. Builds by PR branch (handles force-pushes) -// 2. Builds by individual commit SHAs (fallback for merged/deleted branches) -// -// Returns a map of commit SHA -> builds -func FetchPRBuilds( - extractor *Extractor, - baseURL string, - repo string, - prBranch string, - commits []githubextractor.PRCommit, - logWriter io.Writer, -) (map[string][]BuildInfo, error) { - buildsByCommit := make(map[string][]BuildInfo) - - // Query builds by PR branch (handles force-pushes) - if logWriter != nil { - fmt.Fprintf(logWriter, "Fetching Drone builds for PR (by event and branch)...\n") - } - prBuilds, err := extractor.GetBuildsByPRBranch(baseURL, repo, prBranch) - if err != nil { - if logWriter != nil { - fmt.Fprintf(logWriter, "⚠ Failed to get builds by branch: %v\n", err) - } - } else { - if logWriter != nil { - fmt.Fprintf(logWriter, "Found %d builds for PR branch %s\n", len(prBuilds), prBranch) - } - // Group builds by commit SHA - for _, build := range prBuilds { - buildsByCommit[build.CommitSHA] = append(buildsByCommit[build.CommitSHA], build) - } - } - - // Also query by current commit SHAs (for completeness) - if logWriter != nil { - fmt.Fprintf(logWriter, "Fetching Drone builds for current commits...\n") - } - for i, commit := range commits { - if _, exists := buildsByCommit[commit.SHA]; exists { - if logWriter != nil { - fmt.Fprintf(logWriter, " [%d/%d] %s: already found via PR query\n", i+1, len(commits), commit.SHA[:7]) - } - continue - } - if logWriter != nil { - fmt.Fprintf(logWriter, " [%d/%d] Fetching builds for %s...\n", i+1, len(commits), commit.SHA[:7]) - } - builds, err := extractor.GetBuildsByCommitSHA(baseURL, repo, commit.SHA) - if err != nil { - if logWriter != nil { - fmt.Fprintf(logWriter, " ⚠ Failed to get builds: %v\n", err) - } - continue - } - if len(builds) > 0 { - buildsByCommit[commit.SHA] = append(buildsByCommit[commit.SHA], builds...) - if logWriter != nil { - fmt.Fprintf(logWriter, " Found %d builds\n", len(builds)) - } - } - time.Sleep(requestDelay) - } - - return buildsByCommit, nil -} diff --git a/tools/ci-reporter/pkg/droneextractor/types.go b/tools/ci-reporter/pkg/droneextractor/types.go deleted file mode 100644 index b1895ea8bb9..00000000000 --- a/tools/ci-reporter/pkg/droneextractor/types.go +++ /dev/null @@ -1,39 +0,0 @@ -package droneextractor - -type PipelineInfo struct { - BuildURL string `json:"build_url"` - Started int64 `json:"started,omitempty"` // Unix timestamp - Finished int64 `json:"finished,omitempty"` // Unix timestamp - DurationMinutes float64 `json:"duration_minutes,omitempty"` // Calculated: (finished - started) / 60 - PipelineStages []PipelineStage `json:"pipeline_stages"` -} - -type PipelineStage struct { - StageNumber int `json:"stage_number"` - StageName string `json:"stage_name,omitempty"` - Status string `json:"status,omitempty"` - Steps []PipelineStep `json:"steps"` -} - -type PipelineStep struct { - StepNumber int `json:"step_number"` - StepName string `json:"step_name"` - Status string `json:"status"` // "success", "failure", "error", "running", etc. - URL string `json:"url,omitempty"` - Logs string `json:"logs,omitempty"` // Console logs content -} - -type PipelineInfoSummary struct { - BuildURL string `json:"build_url"` - Started int64 `json:"started,omitempty"` - Finished int64 `json:"finished,omitempty"` - DurationMinutes float64 `json:"duration_minutes,omitempty"` - Status string `json:"status,omitempty"` // Overall build status - FailedStages []FailedStage `json:"failed_stages,omitempty"` -} - -type FailedStage struct { - StageNumber int `json:"stage_number"` - StageName string `json:"stage_name"` - Status string `json:"status"` -} diff --git a/tools/ci-reporter/pkg/ghaextractor/extractor.go b/tools/ci-reporter/pkg/ghaextractor/extractor.go new file mode 100644 index 00000000000..1ae3ca1b1e2 --- /dev/null +++ b/tools/ci-reporter/pkg/ghaextractor/extractor.go @@ -0,0 +1,147 @@ +package ghaextractor + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "time" +) + +const ( + apiBase = "https://api.github.com" + requestDelay = 1 * time.Second + retryDelay = 2 * time.Second + maxRetries = 3 +) + +type Extractor struct { + client *http.Client + token string +} + +func NewExtractor(client *http.Client, token string) *Extractor { + return &Extractor{client: client, token: token} +} + +type WorkflowRun struct { + ID int64 `json:"id"` + RunAttempt int `json:"run_attempt"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + HTMLURL string `json:"html_url"` + HeadBranch string `json:"head_branch"` + HeadSHA string `json:"head_sha"` + Event string `json:"event"` +} + +type workflowRunsPage struct { + TotalCount int `json:"total_count"` + WorkflowRuns []WorkflowRun `json:"workflow_runs"` +} + +type Job struct { + ID int64 `json:"id"` + RunID int64 `json:"run_id"` + RunAttempt int `json:"run_attempt"` + Name string `json:"name"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + StartedAt string `json:"started_at"` + CompletedAt string `json:"completed_at"` +} + +type jobsPage struct { + TotalCount int `json:"total_count"` + Jobs []Job `json:"jobs"` +} + +// GetWorkflowRuns returns all runs for a workflow file created at or after `since` (RFC3339). +func (e *Extractor) GetWorkflowRuns(repo, workflow, since string) ([]WorkflowRun, error) { + var all []WorkflowRun + page := 1 + for { + url := fmt.Sprintf("%s/repos/%s/actions/workflows/%s/runs?per_page=100&page=%d&status=completed", apiBase, repo, workflow, page) + if since != "" { + url += "&created=>=" + since + } + + var result workflowRunsPage + if err := e.get(url, &result); err != nil { + return nil, err + } + all = append(all, result.WorkflowRuns...) + if len(result.WorkflowRuns) < 100 { + break + } + page++ + } + return all, nil +} + +// GetRunJobs returns all jobs for a given run across all attempts (filter=all). +func (e *Extractor) GetRunJobs(repo string, runID int64) ([]Job, error) { + var all []Job + page := 1 + for { + url := fmt.Sprintf("%s/repos/%s/actions/runs/%d/jobs?filter=all&per_page=100&page=%d", apiBase, repo, runID, page) + + var result jobsPage + if err := e.get(url, &result); err != nil { + return nil, err + } + all = append(all, result.Jobs...) + if len(result.Jobs) < 100 { + break + } + page++ + } + return all, nil +} + +func (e *Extractor) get(url string, result any) error { + resp, err := e.request(url) + if err != nil { + return err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + return fmt.Errorf("API error %d: %s", resp.StatusCode, string(body)) + } + + if err := json.NewDecoder(resp.Body).Decode(result); err != nil { + return err + } + + time.Sleep(requestDelay) + return nil +} + +func (e *Extractor) request(url string) (*http.Response, error) { + var lastErr error + for attempt := 0; attempt < maxRetries; attempt++ { + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/vnd.github.v3+json") + if e.token != "" { + req.Header.Set("Authorization", "Bearer "+e.token) + } + resp, err := e.client.Do(req) + if err != nil { + lastErr = err + if attempt < maxRetries-1 { + time.Sleep(retryDelay) + continue + } + return nil, err + } + return resp, nil + } + return nil, lastErr +} diff --git a/vendor/github.com/RoaringBitmap/roaring/v2/.drone.yml b/vendor/github.com/RoaringBitmap/roaring/v2/.drone.yml new file mode 100644 index 00000000000..7936bfe8dfd --- /dev/null +++ b/vendor/github.com/RoaringBitmap/roaring/v2/.drone.yml @@ -0,0 +1,19 @@ +kind: pipeline +name: default + +workspace: + base: /go + path: src/github.com/RoaringBitmap/roaring + +steps: +- name: test + image: golang + commands: + - go get -t + - go test + - go build -tags appengine + - go test -tags appengine + - GOARCH=386 go build + - GOARCH=386 go test + - GOARCH=arm go build + - GOARCH=arm64 go build