Skip to content

Commit ba870d2

Browse files
authored
Merge pull request #1644 from diggerhq/feat/dgctl-artefacts-support
feat/dgctl artefacts support
2 parents a76bfc3 + 355739e commit ba870d2

File tree

19 files changed

+572
-68
lines changed

19 files changed

+572
-68
lines changed

backend/middleware/basic.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ func HttpBasicApiAuth() gin.HandlerFunc {
5959
} else {
6060
setDefaultOrganisationId(c)
6161
c.Set(ACCESS_LEVEL_KEY, jobToken.Type)
62+
c.Set(JOB_TOKEN_KEY, jobToken.Value)
6263
}
6364
} else if token == os.Getenv("BEARER_AUTH_TOKEN") {
6465
setDefaultOrganisationId(c)

backend/middleware/jwt.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,3 +309,4 @@ func CORSMiddleware() gin.HandlerFunc {
309309

310310
const ORGANISATION_ID_KEY = "organisation_ID"
311311
const ACCESS_LEVEL_KEY = "access_level"
312+
const JOB_TOKEN_KEY = "job_token"

backend/migrations/20240729155442.sql

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
-- Create "job_artefacts" table
2+
CREATE TABLE "public"."job_artefacts" (
3+
"id" bigserial NOT NULL,
4+
"created_at" timestamptz NULL,
5+
"updated_at" timestamptz NULL,
6+
"deleted_at" timestamptz NULL,
7+
"job_token_id" bigint NULL,
8+
"contents" bytea NULL,
9+
PRIMARY KEY ("id"),
10+
CONSTRAINT "fk_job_artefacts_job_token" FOREIGN KEY ("job_token_id") REFERENCES "public"."job_tokens" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION
11+
);
12+
-- Create index "idx_job_artefacts_deleted_at" to table: "job_artefacts"
13+
CREATE INDEX "idx_job_artefacts_deleted_at" ON "public"."job_artefacts" ("deleted_at");

backend/migrations/20240729155926.sql

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
-- Modify "job_artefacts" table
2+
ALTER TABLE "public"."job_artefacts" ADD COLUMN "size" bigint NULL, ADD COLUMN "content_type" text NULL;

backend/migrations/20240729160028.sql

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
-- Modify "job_artefacts" table
2+
ALTER TABLE "public"."job_artefacts" ADD COLUMN "filename" text NULL;

backend/migrations/atlas.sum

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
h1:r0O5Hy6gJdMDgkCW9ocd4ytiCyPghNcXKTAT3tuppZ8=
1+
h1:A7OaxVcBVM26DpHZ8tH+NLsfDZxrkpsFUxFJbK3Am68=
22
20231227132525.sql h1:43xn7XC0GoJsCnXIMczGXWis9d504FAWi4F1gViTIcw=
33
20240115170600.sql h1:IW8fF/8vc40+eWqP/xDK+R4K9jHJ9QBSGO6rN9LtfSA=
44
20240116123649.sql h1:R1JlUIgxxF6Cyob9HdtMqiKmx/BfnsctTl5rvOqssQw=
@@ -27,3 +27,6 @@ h1:r0O5Hy6gJdMDgkCW9ocd4ytiCyPghNcXKTAT3tuppZ8=
2727
20240704192835.sql h1:F84HKuE3qX8hYqDCU2K9NDG4WQaSfmnk2P4OCje54qg=
2828
20240705144450.sql h1:AAB4GbML2Jea1MSv/+E0DLMMCI9GLqwptpvBScvU19s=
2929
20240709165155.sql h1:HWDuhwXD+esr9uaKHsqwltPfUEq5uLdcEzpnZ1biKgU=
30+
20240729155442.sql h1:s7PCALP3SgPz5y9Ya7HkDzYjeN86Q5NniW2YIkOMBrQ=
31+
20240729155926.sql h1:8vsDrpy/R1UDI+meIp6KoDfhS60t+ngu8aPB+uonFZ4=
32+
20240729160028.sql h1:snkkxhA2aEQhqBmIhN8l+nPlBhrPOZiPP+dnyhobwD8=

backend/models/artefact.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package models
2+
3+
import (
4+
"gorm.io/gorm"
5+
)
6+
7+
type JobArtefact struct {
8+
gorm.Model
9+
JobTokenID uint
10+
JobToken JobToken
11+
Filename string
12+
Contents []byte `gorm:"type:bytea"`
13+
Size int64
14+
ContentType string
15+
}

backend/models/storage.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,6 +1126,25 @@ func (db *Database) GetJobToken(tenantId any) (*JobToken, error) {
11261126
return token, nil
11271127
}
11281128

1129+
func (db *Database) DeleteJobTokenArtefacts(jobTokenId uint) error {
1130+
artefact := JobArtefact{}
1131+
result := db.GormDB.Where("job_token_id = ?", jobTokenId).Delete(&artefact)
1132+
if result.Error != nil {
1133+
return result.Error
1134+
}
1135+
log.Printf("DeleteJobTokenArtefacts %v has been deleted successfully\n", jobTokenId)
1136+
return nil
1137+
1138+
}
1139+
1140+
func (db *Database) GetJobArtefact(jobTokenId uint) (*JobArtefact, error) {
1141+
var artefact JobArtefact
1142+
if err := DB.GormDB.Where("job_token_id = ?", jobTokenId).First(&artefact).Error; err != nil {
1143+
return nil, err
1144+
}
1145+
return &artefact, nil
1146+
}
1147+
11291148
func (db *Database) CreateGithubAppInstallation(installationId int64, githubAppId int64, login string, accountId int, repoFullName string) (*GithubAppInstallation, error) {
11301149
installation := &GithubAppInstallation{
11311150
GithubInstallationId: installationId,

cli/pkg/spec/spec.go

Lines changed: 51 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import (
44
"fmt"
55
"github.com/diggerhq/digger/cli/pkg/digger"
66
"github.com/diggerhq/digger/cli/pkg/usage"
7+
"github.com/diggerhq/digger/cli/pkg/utils"
8+
"github.com/diggerhq/digger/libs/backendapi"
79
"github.com/diggerhq/digger/libs/ci"
810
"github.com/diggerhq/digger/libs/comment_utils/reporting"
911
comment_summary "github.com/diggerhq/digger/libs/comment_utils/summary"
@@ -14,6 +16,7 @@ import (
1416
"github.com/samber/lo"
1517
"log"
1618
"os"
19+
"os/exec"
1720
"time"
1821
)
1922

@@ -169,6 +172,45 @@ func RunSpecManualCommand(
169172
usage.ReportErrorAndExit(spec.VCS.Actor, fmt.Sprintf("could not get backend api: %v", err), 1)
170173
}
171174

175+
// download zip artefact, git init and prepare for job execution
176+
tempDir, err := os.MkdirTemp("", "downloaded-zip-")
177+
if err != nil {
178+
log.Printf("failed to create temp dir: %v", err)
179+
os.Exit(1)
180+
}
181+
182+
// downloading artefact zip , extracting, git init and then chdir to that directory for job execution
183+
absoluteFileName, err := backendApi.DownloadJobArtefact(tempDir)
184+
if err != nil {
185+
usage.ReportErrorAndExit(spec.VCS.Actor, fmt.Sprintf("could not download job artefact: %v", err), 1)
186+
}
187+
zipPath := *absoluteFileName
188+
err = utils.ExtractZip(zipPath, tempDir)
189+
if err != nil {
190+
log.Printf("ExtractZip err: %v", err)
191+
usage.ReportErrorAndExit(spec.VCS.Actor, fmt.Sprintf("artefact zip extraction err: %v", err), 1)
192+
193+
}
194+
195+
// remove the zipPath
196+
err = os.Remove(zipPath)
197+
if err != nil {
198+
log.Printf("os.Remove err: %v", err)
199+
usage.ReportErrorAndExit(spec.VCS.Actor, fmt.Sprintf("zip path removal err: %v", err), 1)
200+
}
201+
202+
// Navigating to our diractory
203+
err = os.Chdir(tempDir)
204+
if err != nil {
205+
log.Printf("Chdir err: %v", err)
206+
usage.ReportErrorAndExit(spec.VCS.Actor, fmt.Sprintf("Chdir err: %v", err), 1)
207+
}
208+
209+
cmd := exec.Command("git", "init")
210+
cmd.Stdout = os.Stdout
211+
cmd.Stderr = os.Stderr
212+
cmd.Run()
213+
172214
policyChecker, err := policyProvider.GetPolicyProvider(spec.Policy, spec.Backend.BackendHostname, spec.Backend.BackendOrganisationName, spec.Backend.BackendJobToken)
173215
if err != nil {
174216
usage.ReportErrorAndExit(spec.VCS.Actor, fmt.Sprintf("could not get policy provider: %v", err), 1)
@@ -182,11 +224,13 @@ func RunSpecManualCommand(
182224

183225
jobs := []scheduler.Job{job}
184226

185-
fullRepoName := fmt.Sprintf("%v-%v", spec.VCS.RepoOwner, spec.VCS.RepoName)
186-
_, err = backendApi.ReportProjectJobStatus(fullRepoName, spec.Job.ProjectName, spec.JobId, "started", time.Now(), nil, "", "")
187-
if err != nil {
188-
usage.ReportErrorAndExit(spec.VCS.Actor, fmt.Sprintf("Failed to report jobSpec status to backend. Exiting. %v", err), 4)
189-
}
227+
//fullRepoName := fmt.Sprintf("%v-%v", spec.VCS.RepoOwner, spec.VCS.RepoName)
228+
//_, err = backendApi.ReportProjectJobStatus(fullRepoName, spec.Job.ProjectName, spec.JobId, "started", time.Now(), nil, "", "")
229+
//if err != nil {
230+
// usage.ReportErrorAndExit(spec.VCS.Actor, fmt.Sprintf("Failed to report jobSpec status to backend. Exiting. %v", err), 4)
231+
//}
232+
233+
noopBackendApi := backendapi.NoopApi{}
190234

191235
commentId := spec.CommentId
192236
if err != nil {
@@ -199,9 +243,9 @@ func RunSpecManualCommand(
199243
}
200244

201245
commentUpdater := comment_summary.NoopCommentUpdater{}
202-
// TODO: do not require conversion to gh service
246+
// do not change these placeholders as they are parsed by dgctl to stream logs
203247
log.Printf("<========= DIGGER RUNNING IN MANUAL MODE =========>")
204-
allAppliesSuccess, _, err := digger.RunJobs(jobs, prService, orgService, lock, reporter, planStorage, policyChecker, commentUpdater, backendApi, spec.JobId, false, false, commentId, currentDir)
248+
allAppliesSuccess, _, err := digger.RunJobs(jobs, prService, orgService, lock, reporter, planStorage, policyChecker, commentUpdater, noopBackendApi, spec.JobId, false, false, commentId, currentDir)
205249
log.Printf("<========= DIGGER COMPLETED =========>")
206250
if err != nil || allAppliesSuccess == false {
207251
usage.ReportErrorAndExit(spec.VCS.RepoOwner, "Terraform execution failed", 1)

cli/pkg/utils/io.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package utils
2+
3+
import (
4+
"archive/zip"
5+
"fmt"
6+
"io"
7+
"os"
8+
"path/filepath"
9+
)
10+
11+
func ExtractZip(zipFilePath string, outDir string) error {
12+
13+
// Open the zip file
14+
zipReader, err := zip.OpenReader(zipFilePath)
15+
if err != nil {
16+
return fmt.Errorf("failed to open zip: %w", err)
17+
}
18+
defer zipReader.Close()
19+
20+
for _, file := range zipReader.File {
21+
path := filepath.Join(outDir, file.Name)
22+
23+
if file.FileInfo().IsDir() {
24+
os.MkdirAll(path, os.ModePerm)
25+
continue
26+
}
27+
28+
if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
29+
return fmt.Errorf("failed to create directory: %w", err)
30+
}
31+
32+
dstFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
33+
if err != nil {
34+
return fmt.Errorf("failed to create file: %w", err)
35+
}
36+
37+
srcFile, err := file.Open()
38+
if err != nil {
39+
dstFile.Close()
40+
return fmt.Errorf("failed to open zip file: %w", err)
41+
}
42+
43+
_, err = io.Copy(dstFile, srcFile)
44+
srcFile.Close()
45+
dstFile.Close()
46+
47+
if err != nil {
48+
return fmt.Errorf("failed to extract file: %w", err)
49+
}
50+
}
51+
return nil
52+
}

0 commit comments

Comments
 (0)