repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/principal.go | app/store/database/principal.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"strings"
"github.com/harness/gitness/app/store"
gitness_store "github.com/harness/gitness/store"
"github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/Masterminds/squirrel"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
var _ store.PrincipalStore = (*PrincipalStore)(nil)
// NewPrincipalStore returns a new PrincipalStore.
func NewPrincipalStore(db *sqlx.DB, uidTransformation store.PrincipalUIDTransformation) *PrincipalStore {
return &PrincipalStore{
db: db,
uidTransformation: uidTransformation,
}
}
// PrincipalStore implements a PrincipalStore backed by a relational database.
type PrincipalStore struct {
db *sqlx.DB
uidTransformation store.PrincipalUIDTransformation
}
// principal is a DB representation of a principal.
// It is required to allow storing transformed UIDs used for uniquness constraints and searching.
type principal struct {
types.Principal
UIDUnique string `db:"principal_uid_unique"`
}
// principalCommonColumns defines the columns that are the same across all principals.
const principalCommonColumns = `
principal_id
,principal_uid
,principal_uid_unique
,principal_email
,principal_display_name
,principal_admin
,principal_blocked
,principal_salt
,principal_created
,principal_updated`
// principalColumns defines the column that are used only in a principal itself
// (for explicit principals the type is implicit, only the generic principal struct stores it explicitly).
const principalColumns = principalCommonColumns + `
,principal_type`
//nolint:goconst
const principalSelectBase = `
SELECT` + principalColumns + `
FROM principals`
// Find finds the principal by id.
func (s *PrincipalStore) Find(ctx context.Context, id int64) (*types.Principal, error) {
const sqlQuery = principalSelectBase + `
WHERE principal_id = $1`
db := dbtx.GetAccessor(ctx, s.db)
dst := new(principal)
if err := db.GetContext(ctx, dst, sqlQuery, id); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Select by id query failed")
}
return s.mapDBPrincipal(dst), nil
}
// FindByUID finds the principal by uid.
func (s *PrincipalStore) FindByUID(ctx context.Context, uid string) (*types.Principal, error) {
const sqlQuery = principalSelectBase + `
WHERE principal_uid_unique = $1`
// map the UID to unique UID before searching!
uidUnique, err := s.uidTransformation(uid)
if err != nil {
// in case we fail to transform, return a not found (as it can't exist in the first place)
log.Ctx(ctx).Debug().Msgf("failed to transform uid '%s': %s", uid, err.Error())
return nil, gitness_store.ErrResourceNotFound
}
db := dbtx.GetAccessor(ctx, s.db)
dst := new(principal)
if err = db.GetContext(ctx, dst, sqlQuery, uidUnique); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Select by uid query failed")
}
return s.mapDBPrincipal(dst), nil
}
// FindManyByUID returns all principals found for the provided UIDs.
// If a UID isn't found, it's not returned in the list.
func (s *PrincipalStore) FindManyByUID(ctx context.Context, uids []string) ([]*types.Principal, error) {
// map the UIDs to unique UIDs before searching!
uniqueUIDs := make([]string, len(uids))
for i := range uids {
var err error
uniqueUIDs[i], err = s.uidTransformation(uids[i])
if err != nil {
// in case we fail to transform, skip the entry (as it can't exist in the first place)
log.Ctx(ctx).Warn().Msgf("failed to transform uid '%s': %s", uids[i], err.Error())
}
}
stmt := database.Builder.
Select(principalColumns).
From("principals").
Where(squirrel.Eq{"principal_uid_unique": uids})
db := dbtx.GetAccessor(ctx, s.db)
sqlQuery, params, err := stmt.ToSql()
if err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "failed to generate find many principal query")
}
dst := []*principal{}
if err := db.SelectContext(ctx, &dst, sqlQuery, params...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "find many by uid for principals query failed")
}
return s.mapDBPrincipals(dst), nil
}
// FindByEmail finds the principal by email.
func (s *PrincipalStore) FindByEmail(ctx context.Context, email string) (*types.Principal, error) {
const sqlQuery = principalSelectBase + `
WHERE LOWER(principal_email) = $1`
db := dbtx.GetAccessor(ctx, s.db)
dst := new(principal)
if err := db.GetContext(ctx, dst, sqlQuery, strings.ToLower(email)); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Select by email query failed")
}
return s.mapDBPrincipal(dst), nil
}
func (s *PrincipalStore) FindManyByEmail(
ctx context.Context,
emails []string,
) ([]*types.Principal, error) {
lowerCaseEmails := make([]string, len(emails))
for i := range emails {
lowerCaseEmails[i] = strings.ToLower(emails[i])
}
stmt := database.Builder.
Select(principalColumns).
From("principals").
Where(squirrel.Eq{"principal_email": lowerCaseEmails})
db := dbtx.GetAccessor(ctx, s.db)
sqlQuery, params, err := stmt.ToSql()
if err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "failed to generate find many principal query")
}
dst := []*principal{}
if err := db.SelectContext(ctx, &dst, sqlQuery, params...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "find many by email for principal query failed")
}
return s.mapDBPrincipals(dst), nil
}
// List lists the principals matching the provided filter.
func (s *PrincipalStore) List(ctx context.Context,
opts *types.PrincipalFilter) ([]*types.Principal, error) {
stmt := database.Builder.
Select(principalColumns).
From("principals")
if len(opts.Types) == 1 {
stmt = stmt.Where("principal_type = ?", opts.Types[0])
} else if len(opts.Types) > 1 {
stmt = stmt.Where(squirrel.Eq{"principal_type": opts.Types})
}
if opts.Query != "" {
// TODO: optimize performance
// https://harness.atlassian.net/browse/CODE-522
stmt = stmt.Where(squirrel.Or{
squirrel.Expr(PartialMatch("principal_uid", opts.Query)),
squirrel.Expr(PartialMatch("principal_email", opts.Query)),
squirrel.Expr(PartialMatch("principal_display_name", opts.Query)),
})
}
stmt = stmt.Limit(database.Limit(opts.Size))
stmt = stmt.Offset(database.Offset(opts.Page, opts.Size))
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, s.db)
dst := []*principal{}
if err := db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Search by display_name and email query failed")
}
return s.mapDBPrincipals(dst), nil
}
func (s *PrincipalStore) mapDBPrincipal(dbPrincipal *principal) *types.Principal {
return &dbPrincipal.Principal
}
func (s *PrincipalStore) mapDBPrincipals(dbPrincipals []*principal) []*types.Principal {
res := make([]*types.Principal, len(dbPrincipals))
for i := range dbPrincipals {
res[i] = s.mapDBPrincipal(dbPrincipals[i])
}
return res
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/setup_test.go | app/store/database/setup_test.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database_test
import (
"context"
"fmt"
"os"
"strconv"
"testing"
"time"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/app/store/cache"
"github.com/harness/gitness/app/store/database"
"github.com/harness/gitness/app/store/database/migrate"
"github.com/harness/gitness/types"
"github.com/jmoiron/sqlx"
"github.com/rs/xid"
)
var userID int64 = 1
func New(dsn string) (*sqlx.DB, error) {
if dsn == ":memory:" {
dsn = fmt.Sprintf("file:%s.db?mode=memory&cache=shared", xid.New().String())
}
db, err := sqlx.Connect("sqlite3", dsn)
if err != nil {
return nil, err
}
if _, err := db.Exec(`PRAGMA foreign_keys = ON;`); err != nil {
return nil, fmt.Errorf("foreign keys pragma: %w", err)
}
return db, nil
}
func setupDB(t *testing.T) (*sqlx.DB, func()) {
t.Helper()
// must use file as db because in memory have only basic features
// file is anyway removed on every test. SQLite is fast
// so it will not affect too much performance.
_ = os.Remove("test.db")
db, err := New("test.db")
if err != nil {
t.Fatalf("Error opening db, err: %v", err)
}
_, _ = db.Exec("PRAGMA busy_timeout = 5000;")
if err = migrate.Migrate(context.Background(), db); err != nil {
t.Fatalf("Error migrating db, err: %v", err)
}
return db, func() {
db.Close()
}
}
func setupStores(t *testing.T, db *sqlx.DB) (
*database.PrincipalStore,
*database.SpaceStore,
store.SpacePathStore,
*database.RepoStore,
) {
t.Helper()
principalStore := database.NewPrincipalStore(db, store.ToLowerPrincipalUIDTransformation)
spacePathTransformation := store.ToLowerSpacePathTransformation
spacePathStore := database.NewSpacePathStore(db, store.ToLowerSpacePathTransformation)
evictor := cache.NewEvictor[*types.SpaceCore]("namespace", "space-topic", nil)
spacePathCache := cache.New(context.Background(), spacePathStore, spacePathTransformation, evictor, time.Minute)
spaceStore := database.NewSpaceStore(db, spacePathCache, spacePathStore)
repoStore := database.NewRepoStore(db, spacePathCache, spacePathStore, spaceStore)
return principalStore, spaceStore, spacePathStore, repoStore
}
func createUser(
ctx context.Context,
t *testing.T,
principalStore *database.PrincipalStore,
) {
t.Helper()
uid := "user_" + strconv.FormatInt(userID, 10)
if err := principalStore.CreateUser(ctx,
&types.User{ID: userID, UID: uid}); err != nil {
t.Fatalf("failed to create user %v", err)
}
}
func createSpace(
ctx context.Context,
t *testing.T,
spaceStore *database.SpaceStore,
spacePathStore store.SpacePathStore,
userID int64,
spaceID int64,
parentID int64,
) {
t.Helper()
identifier := "space_" + strconv.FormatInt(spaceID, 10)
space := types.Space{ID: spaceID, Identifier: identifier, CreatedBy: userID, ParentID: parentID}
if err := spaceStore.Create(ctx, &space); err != nil {
t.Fatalf("failed to create space %v", err)
}
if err := spacePathStore.InsertSegment(ctx, &types.SpacePathSegment{
ID: space.ID, Identifier: identifier, CreatedBy: userID, SpaceID: spaceID, IsPrimary: true,
}); err != nil {
t.Fatalf("failed to insert segment %v", err)
}
}
func createSpaceTree() (map[int64][]int64, int) {
spaceTree := make(map[int64][]int64)
spaceTree[1] = []int64{2, 3}
spaceTree[2] = []int64{4, 5, 6}
spaceTree[3] = []int64{7, 8}
spaceTree[4] = []int64{9, 10}
spaceTree[5] = []int64{11}
return spaceTree, 11
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/pullreq_activity.go | app/store/database/pullreq_activity.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/harness/gitness/app/store"
gitness_store "github.com/harness/gitness/store"
"github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/Masterminds/squirrel"
"github.com/guregu/null"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
var _ store.PullReqActivityStore = (*PullReqActivityStore)(nil)
// NewPullReqActivityStore returns a new PullReqJournalStore.
func NewPullReqActivityStore(
db *sqlx.DB,
pCache store.PrincipalInfoCache,
) *PullReqActivityStore {
return &PullReqActivityStore{
db: db,
pCache: pCache,
}
}
// PullReqActivityStore implements store.PullReqActivityStore backed by a relational database.
type PullReqActivityStore struct {
db *sqlx.DB
pCache store.PrincipalInfoCache
}
// journal is used to fetch pull request data from the database.
// The object should be later re-packed into a different struct to return it as an API response.
type pullReqActivity struct {
ID int64 `db:"pullreq_activity_id"`
Version int64 `db:"pullreq_activity_version"`
CreatedBy int64 `db:"pullreq_activity_created_by"`
Created int64 `db:"pullreq_activity_created"`
Updated int64 `db:"pullreq_activity_updated"`
Edited int64 `db:"pullreq_activity_edited"`
Deleted null.Int `db:"pullreq_activity_deleted"`
ParentID null.Int `db:"pullreq_activity_parent_id"`
RepoID int64 `db:"pullreq_activity_repo_id"`
PullReqID int64 `db:"pullreq_activity_pullreq_id"`
Order int64 `db:"pullreq_activity_order"`
SubOrder int64 `db:"pullreq_activity_sub_order"`
ReplySeq int64 `db:"pullreq_activity_reply_seq"`
Type enum.PullReqActivityType `db:"pullreq_activity_type"`
Kind enum.PullReqActivityKind `db:"pullreq_activity_kind"`
Text string `db:"pullreq_activity_text"`
Payload json.RawMessage `db:"pullreq_activity_payload"`
Metadata json.RawMessage `db:"pullreq_activity_metadata"`
ResolvedBy null.Int `db:"pullreq_activity_resolved_by"`
Resolved null.Int `db:"pullreq_activity_resolved"`
Outdated null.Bool `db:"pullreq_activity_outdated"`
CodeCommentMergeBaseSHA null.String `db:"pullreq_activity_code_comment_merge_base_sha"`
CodeCommentSourceSHA null.String `db:"pullreq_activity_code_comment_source_sha"`
CodeCommentPath null.String `db:"pullreq_activity_code_comment_path"`
CodeCommentLineNew null.Int `db:"pullreq_activity_code_comment_line_new"`
CodeCommentSpanNew null.Int `db:"pullreq_activity_code_comment_span_new"`
CodeCommentLineOld null.Int `db:"pullreq_activity_code_comment_line_old"`
CodeCommentSpanOld null.Int `db:"pullreq_activity_code_comment_span_old"`
}
const (
pullreqActivityColumns = `
pullreq_activity_id
,pullreq_activity_version
,pullreq_activity_created_by
,pullreq_activity_created
,pullreq_activity_updated
,pullreq_activity_edited
,pullreq_activity_deleted
,pullreq_activity_parent_id
,pullreq_activity_repo_id
,pullreq_activity_pullreq_id
,pullreq_activity_order
,pullreq_activity_sub_order
,pullreq_activity_reply_seq
,pullreq_activity_type
,pullreq_activity_kind
,pullreq_activity_text
,pullreq_activity_payload
,pullreq_activity_metadata
,pullreq_activity_resolved_by
,pullreq_activity_resolved
,pullreq_activity_outdated
,pullreq_activity_code_comment_merge_base_sha
,pullreq_activity_code_comment_source_sha
,pullreq_activity_code_comment_path
,pullreq_activity_code_comment_line_new
,pullreq_activity_code_comment_span_new
,pullreq_activity_code_comment_line_old
,pullreq_activity_code_comment_span_old`
pullreqActivitySelectBase = `
SELECT` + pullreqActivityColumns + `
FROM pullreq_activities`
)
// Find finds the pull request activity by id.
func (s *PullReqActivityStore) Find(ctx context.Context, id int64) (*types.PullReqActivity, error) {
const sqlQuery = pullreqActivitySelectBase + `
WHERE pullreq_activity_id = $1`
db := dbtx.GetAccessor(ctx, s.db)
dst := &pullReqActivity{}
if err := db.GetContext(ctx, dst, sqlQuery, id); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to find pull request activity")
}
act, err := s.mapPullReqActivity(ctx, dst)
if err != nil {
return nil, fmt.Errorf("failed to map pull request activity: %w", err)
}
return act, nil
}
// Create creates a new pull request.
func (s *PullReqActivityStore) Create(ctx context.Context, act *types.PullReqActivity) error {
const sqlQuery = `
INSERT INTO pullreq_activities (
pullreq_activity_version
,pullreq_activity_created_by
,pullreq_activity_created
,pullreq_activity_updated
,pullreq_activity_edited
,pullreq_activity_deleted
,pullreq_activity_parent_id
,pullreq_activity_repo_id
,pullreq_activity_pullreq_id
,pullreq_activity_order
,pullreq_activity_sub_order
,pullreq_activity_reply_seq
,pullreq_activity_type
,pullreq_activity_kind
,pullreq_activity_text
,pullreq_activity_payload
,pullreq_activity_metadata
,pullreq_activity_resolved_by
,pullreq_activity_resolved
,pullreq_activity_outdated
,pullreq_activity_code_comment_merge_base_sha
,pullreq_activity_code_comment_source_sha
,pullreq_activity_code_comment_path
,pullreq_activity_code_comment_line_new
,pullreq_activity_code_comment_span_new
,pullreq_activity_code_comment_line_old
,pullreq_activity_code_comment_span_old
) values (
:pullreq_activity_version
,:pullreq_activity_created_by
,:pullreq_activity_created
,:pullreq_activity_updated
,:pullreq_activity_edited
,:pullreq_activity_deleted
,:pullreq_activity_parent_id
,:pullreq_activity_repo_id
,:pullreq_activity_pullreq_id
,:pullreq_activity_order
,:pullreq_activity_sub_order
,:pullreq_activity_reply_seq
,:pullreq_activity_type
,:pullreq_activity_kind
,:pullreq_activity_text
,:pullreq_activity_payload
,:pullreq_activity_metadata
,:pullreq_activity_resolved_by
,:pullreq_activity_resolved
,:pullreq_activity_outdated
,:pullreq_activity_code_comment_merge_base_sha
,:pullreq_activity_code_comment_source_sha
,:pullreq_activity_code_comment_path
,:pullreq_activity_code_comment_line_new
,:pullreq_activity_code_comment_span_new
,:pullreq_activity_code_comment_line_old
,:pullreq_activity_code_comment_span_old
) RETURNING pullreq_activity_id`
db := dbtx.GetAccessor(ctx, s.db)
dbAct, err := mapInternalPullReqActivity(act)
if err != nil {
return fmt.Errorf("failed to map pull request activity: %w", err)
}
query, arg, err := db.BindNamed(sqlQuery, dbAct)
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to bind pull request activity object")
}
if err = db.QueryRowContext(ctx, query, arg...).Scan(&act.ID); err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to insert pull request activity")
}
return nil
}
func (s *PullReqActivityStore) CreateWithPayload(
ctx context.Context,
pr *types.PullReq,
principalID int64,
payload types.PullReqActivityPayload,
metadata *types.PullReqActivityMetadata,
) (*types.PullReqActivity, error) {
now := time.Now().UnixMilli()
act := &types.PullReqActivity{
CreatedBy: principalID,
Created: now,
Updated: now,
Edited: now,
RepoID: pr.TargetRepoID,
PullReqID: pr.ID,
Order: pr.ActivitySeq,
SubOrder: 0,
ReplySeq: 0,
Type: payload.ActivityType(),
Kind: enum.PullReqActivityKindSystem,
Text: "",
Metadata: metadata,
}
_ = act.SetPayload(payload)
err := s.Create(ctx, act)
if err != nil {
err = fmt.Errorf("failed to write pull request system '%s' activity: %w", payload.ActivityType(), err)
return nil, err
}
return act, nil
}
// Update updates the pull request.
func (s *PullReqActivityStore) Update(ctx context.Context, act *types.PullReqActivity) error {
const sqlQuery = `
UPDATE pullreq_activities
SET
pullreq_activity_version = :pullreq_activity_version
,pullreq_activity_updated = :pullreq_activity_updated
,pullreq_activity_edited = :pullreq_activity_edited
,pullreq_activity_deleted = :pullreq_activity_deleted
,pullreq_activity_reply_seq = :pullreq_activity_reply_seq
,pullreq_activity_text = :pullreq_activity_text
,pullreq_activity_payload = :pullreq_activity_payload
,pullreq_activity_metadata = :pullreq_activity_metadata
,pullreq_activity_resolved_by = :pullreq_activity_resolved_by
,pullreq_activity_resolved = :pullreq_activity_resolved
,pullreq_activity_outdated = :pullreq_activity_outdated
,pullreq_activity_code_comment_merge_base_sha = :pullreq_activity_code_comment_merge_base_sha
,pullreq_activity_code_comment_source_sha = :pullreq_activity_code_comment_source_sha
,pullreq_activity_code_comment_path = :pullreq_activity_code_comment_path
,pullreq_activity_code_comment_line_new = :pullreq_activity_code_comment_line_new
,pullreq_activity_code_comment_span_new = :pullreq_activity_code_comment_span_new
,pullreq_activity_code_comment_line_old = :pullreq_activity_code_comment_line_old
,pullreq_activity_code_comment_span_old = :pullreq_activity_code_comment_span_old
WHERE pullreq_activity_id = :pullreq_activity_id AND pullreq_activity_version = :pullreq_activity_version - 1`
db := dbtx.GetAccessor(ctx, s.db)
updatedAt := time.Now()
dbAct, err := mapInternalPullReqActivity(act)
if err != nil {
return fmt.Errorf("failed to map pull request activity: %w", err)
}
dbAct.Version++
dbAct.Updated = updatedAt.UnixMilli()
query, arg, err := db.BindNamed(sqlQuery, dbAct)
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to bind pull request activity object")
}
result, err := db.ExecContext(ctx, query, arg...)
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to update pull request activity")
}
count, err := result.RowsAffected()
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to get number of updated rows")
}
if count == 0 {
return gitness_store.ErrVersionConflict
}
updatedAct, err := s.mapPullReqActivity(ctx, dbAct)
if err != nil {
return fmt.Errorf("failed to map db pull request activity: %w", err)
}
*act = *updatedAct
return nil
}
// UpdateOptLock updates the pull request using the optimistic locking mechanism.
func (s *PullReqActivityStore) UpdateOptLock(ctx context.Context,
act *types.PullReqActivity,
mutateFn func(act *types.PullReqActivity) error,
) (*types.PullReqActivity, error) {
for {
dup := *act
err := mutateFn(&dup)
if err != nil {
return nil, err
}
err = s.Update(ctx, &dup)
if err == nil {
return &dup, nil
}
if !errors.Is(err, gitness_store.ErrVersionConflict) {
return nil, err
}
act, err = s.Find(ctx, act.ID)
if err != nil {
return nil, err
}
}
}
// Count of pull requests for a repo.
func (s *PullReqActivityStore) Count(ctx context.Context,
prID int64,
opts *types.PullReqActivityFilter,
) (int64, error) {
stmt := database.Builder.
Select("count(*)").
From("pullreq_activities").
Where("pullreq_activity_pullreq_id = ?", prID)
if len(opts.Types) == 1 {
stmt = stmt.Where("pullreq_activity_type = ?", opts.Types[0])
} else if len(opts.Types) > 1 {
stmt = stmt.Where(squirrel.Eq{"pullreq_activity_type": opts.Types})
}
if len(opts.Kinds) == 1 {
stmt = stmt.Where("pullreq_activity_kind = ?", opts.Kinds[0])
} else if len(opts.Kinds) > 1 {
stmt = stmt.Where(squirrel.Eq{"pullreq_activity_kind": opts.Kinds})
}
if opts.After != 0 {
stmt = stmt.Where("pullreq_activity_created > ?", opts.After)
}
if opts.Before != 0 {
stmt = stmt.Where("pullreq_activity_created < ?", opts.Before)
}
sql, args, err := stmt.ToSql()
if err != nil {
return 0, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, s.db)
var count int64
err = db.QueryRowContext(ctx, sql, args...).Scan(&count)
if err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "Failed executing count query")
}
return count, nil
}
// List returns a list of pull request activities for a PR.
func (s *PullReqActivityStore) List(ctx context.Context,
prID int64,
filter *types.PullReqActivityFilter,
) ([]*types.PullReqActivity, error) {
stmt := database.Builder.
Select(pullreqActivityColumns).
From("pullreq_activities").
Where("pullreq_activity_pullreq_id = ?", prID)
stmt = applyFilter(filter, stmt)
stmt = stmt.OrderBy("pullreq_activity_order asc", "pullreq_activity_sub_order asc")
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert pull request activity query to sql")
}
dst := make([]*pullReqActivity, 0)
db := dbtx.GetAccessor(ctx, s.db)
if err = db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed executing pull request activity list query")
}
result, err := s.mapSlicePullReqActivity(ctx, dst)
if err != nil {
return nil, err
}
return result, nil
}
// ListAuthorIDs returns a list of pull request activity author ids in a thread for a PR.
func (s *PullReqActivityStore) ListAuthorIDs(ctx context.Context, prID int64, order int64) ([]int64, error) {
stmt := database.Builder.
Select("DISTINCT pullreq_activity_created_by").
From("pullreq_activities").
Where("pullreq_activity_pullreq_id = ?", prID).
Where("pullreq_activity_order = ?", order)
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert pull request activity query to sql")
}
var dst []int64
db := dbtx.GetAccessor(ctx, s.db)
if err = db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed executing pull request activity list query")
}
return dst, nil
}
func (s *PullReqActivityStore) CountUnresolved(ctx context.Context, prID int64) (int, error) {
stmt := database.Builder.
Select("count(*)").
From("pullreq_activities").
Where("pullreq_activity_pullreq_id = ?", prID).
Where("pullreq_activity_sub_order = 0").
Where("pullreq_activity_resolved IS NULL").
Where("pullreq_activity_deleted IS NULL").
Where("pullreq_activity_kind <> ?", enum.PullReqActivityKindSystem)
sql, args, err := stmt.ToSql()
if err != nil {
return 0, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, s.db)
var count int
err = db.QueryRowContext(ctx, sql, args...).Scan(&count)
if err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "Failed executing count unresolved query")
}
return count, nil
}
func mapPullReqActivity(act *pullReqActivity) (*types.PullReqActivity, error) {
metadata := &types.PullReqActivityMetadata{}
err := json.Unmarshal(act.Metadata, &metadata)
if err != nil {
return nil, fmt.Errorf("failed to deserialize metadata: %w", err)
}
m := &types.PullReqActivity{
ID: act.ID,
Version: act.Version,
CreatedBy: act.CreatedBy,
Created: act.Created,
Updated: act.Updated,
Edited: act.Edited,
Deleted: act.Deleted.Ptr(),
ParentID: act.ParentID.Ptr(),
RepoID: act.RepoID,
PullReqID: act.PullReqID,
Order: act.Order,
SubOrder: act.SubOrder,
ReplySeq: act.ReplySeq,
Type: act.Type,
Kind: act.Kind,
Text: act.Text,
PayloadRaw: act.Payload,
Metadata: metadata,
ResolvedBy: act.ResolvedBy.Ptr(),
Resolved: act.Resolved.Ptr(),
Author: types.PrincipalInfo{},
Resolver: nil,
}
if m.Type == enum.PullReqActivityTypeCodeComment && m.Kind == enum.PullReqActivityKindChangeComment {
m.CodeComment = &types.CodeCommentFields{
Outdated: act.Outdated.Bool,
MergeBaseSHA: act.CodeCommentMergeBaseSHA.String,
SourceSHA: act.CodeCommentSourceSHA.String,
Path: act.CodeCommentPath.String,
LineNew: int(act.CodeCommentLineNew.Int64),
SpanNew: int(act.CodeCommentSpanNew.Int64),
LineOld: int(act.CodeCommentLineOld.Int64),
SpanOld: int(act.CodeCommentSpanOld.Int64),
}
}
return m, nil
}
func mapInternalPullReqActivity(act *types.PullReqActivity) (*pullReqActivity, error) {
m := &pullReqActivity{
ID: act.ID,
Version: act.Version,
CreatedBy: act.CreatedBy,
Created: act.Created,
Updated: act.Updated,
Edited: act.Edited,
Deleted: null.IntFromPtr(act.Deleted),
ParentID: null.IntFromPtr(act.ParentID),
RepoID: act.RepoID,
PullReqID: act.PullReqID,
Order: act.Order,
SubOrder: act.SubOrder,
ReplySeq: act.ReplySeq,
Type: act.Type,
Kind: act.Kind,
Text: act.Text,
Payload: act.PayloadRaw,
Metadata: nil,
ResolvedBy: null.IntFromPtr(act.ResolvedBy),
Resolved: null.IntFromPtr(act.Resolved),
}
if act.IsValidCodeComment() {
m.Outdated = null.BoolFrom(act.CodeComment.Outdated)
m.CodeCommentMergeBaseSHA = null.StringFrom(act.CodeComment.MergeBaseSHA)
m.CodeCommentSourceSHA = null.StringFrom(act.CodeComment.SourceSHA)
m.CodeCommentPath = null.StringFrom(act.CodeComment.Path)
m.CodeCommentLineNew = null.IntFrom(int64(act.CodeComment.LineNew))
m.CodeCommentSpanNew = null.IntFrom(int64(act.CodeComment.SpanNew))
m.CodeCommentLineOld = null.IntFrom(int64(act.CodeComment.LineOld))
m.CodeCommentSpanOld = null.IntFrom(int64(act.CodeComment.SpanOld))
}
var err error
m.Metadata, err = json.Marshal(act.Metadata)
if err != nil {
return nil, fmt.Errorf("failed to serialize metadata: %w", err)
}
return m, nil
}
func (s *PullReqActivityStore) mapPullReqActivity(
ctx context.Context,
act *pullReqActivity,
) (*types.PullReqActivity, error) {
m, err := mapPullReqActivity(act)
if err != nil {
return nil, err
}
var author, resolver *types.PrincipalInfo
author, err = s.pCache.Get(ctx, act.CreatedBy)
if err != nil {
log.Ctx(ctx).Err(err).Msg("failed to load PR activity author")
}
if author != nil {
m.Author = *author
}
if act.ResolvedBy.Valid {
resolver, err = s.pCache.Get(ctx, act.ResolvedBy.Int64)
if err != nil {
log.Ctx(ctx).Err(err).Msg("failed to load PR activity resolver")
}
m.Resolver = resolver
}
return m, nil
}
func (s *PullReqActivityStore) mapSlicePullReqActivity(
ctx context.Context,
activities []*pullReqActivity,
) ([]*types.PullReqActivity, error) {
// collect all principal IDs
ids := make([]int64, 0, 2*len(activities))
for _, act := range activities {
ids = append(ids, act.CreatedBy)
if act.ResolvedBy.Valid {
ids = append(ids, act.ResolvedBy.Int64)
}
}
// pull principal infos from cache
infoMap, err := s.pCache.Map(ctx, ids)
if err != nil {
return nil, fmt.Errorf("failed to load PR principal infos: %w", err)
}
// attach the principal infos back to the slice items
m := make([]*types.PullReqActivity, len(activities))
for i, act := range activities {
m[i], err = mapPullReqActivity(act)
if err != nil {
return nil, fmt.Errorf("failed to map pull request activity %d: %w", act.ID, err)
}
if author, ok := infoMap[act.CreatedBy]; ok {
m[i].Author = *author
}
if act.ResolvedBy.Valid {
if merger, ok := infoMap[act.ResolvedBy.Int64]; ok {
m[i].Resolver = merger
}
}
}
return m, nil
}
func applyFilter(
filter *types.PullReqActivityFilter,
stmt squirrel.SelectBuilder,
) squirrel.SelectBuilder {
if len(filter.Types) == 1 {
stmt = stmt.Where("pullreq_activity_type = ?", filter.Types[0])
} else if len(filter.Types) > 1 {
stmt = stmt.Where(squirrel.Eq{"pullreq_activity_type": filter.Types})
}
if len(filter.Kinds) == 1 {
stmt = stmt.Where("pullreq_activity_kind = ?", filter.Kinds[0])
} else if len(filter.Kinds) > 1 {
stmt = stmt.Where(squirrel.Eq{"pullreq_activity_kind": filter.Kinds})
}
if filter.After != 0 {
stmt = stmt.Where("pullreq_activity_created > ?", filter.After)
}
if filter.Before != 0 {
stmt = stmt.Where("pullreq_activity_created < ?", filter.Before)
}
if filter.Limit > 0 {
stmt = stmt.Limit(database.Limit(filter.Limit))
}
return stmt
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/usergroup_reviewers.go | app/store/database/usergroup_reviewers.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/jmoiron/sqlx"
)
var _ store.PullReqReviewerStore = (*PullReqReviewerStore)(nil)
func NewUsergroupReviewerStore(
db *sqlx.DB,
pCache store.PrincipalInfoCache,
userGroupStore store.UserGroupStore,
) *UsergroupReviewerStore {
return &UsergroupReviewerStore{
db: db,
pInfoCache: pCache,
userGroupStore: userGroupStore,
}
}
// UsergroupReviewerStore implements store.UsergroupReviewerStore backed by a relational database.
type UsergroupReviewerStore struct {
db *sqlx.DB
pInfoCache store.PrincipalInfoCache
userGroupStore store.UserGroupStore
}
type usergroupReviewer struct {
PullReqID int64 `db:"usergroup_reviewer_pullreq_id"`
UserGroupID int64 `db:"usergroup_reviewer_usergroup_id"`
CreatedBy int64 `db:"usergroup_reviewer_created_by"`
Created int64 `db:"usergroup_reviewer_created"`
Updated int64 `db:"usergroup_reviewer_updated"`
RepoID int64 `db:"usergroup_reviewer_repo_id"`
}
const (
pullreqUserGroupReviewerColumns = `
usergroup_reviewer_pullreq_id
,usergroup_reviewer_usergroup_id
,usergroup_reviewer_created_by
,usergroup_reviewer_created
,usergroup_reviewer_updated
,usergroup_reviewer_repo_id`
pullreqUserGroupReviewerSelectBase = `
SELECT` + pullreqUserGroupReviewerColumns + `
FROM usergroup_reviewers`
)
// Create creates a new pull request usergroup reviewer.
func (s *UsergroupReviewerStore) Create(ctx context.Context, v *types.UserGroupReviewer) error {
const sqlQuery = `
INSERT INTO usergroup_reviewers (
usergroup_reviewer_pullreq_id,
usergroup_reviewer_usergroup_id,
usergroup_reviewer_created_by,
usergroup_reviewer_created,
usergroup_reviewer_updated,
usergroup_reviewer_repo_id
) VALUES (
:usergroup_reviewer_pullreq_id,
:usergroup_reviewer_usergroup_id,
:usergroup_reviewer_created_by,
:usergroup_reviewer_created,
:usergroup_reviewer_updated,
:usergroup_reviewer_repo_id
)`
db := dbtx.GetAccessor(ctx, s.db)
query, arg, err := db.BindNamed(sqlQuery, mapInternalPullReqUserGroupReviewer(v))
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to bind pull request usergroup reviewer object")
}
if _, err := db.ExecContext(ctx, query, arg...); err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to insert pull request usergroup reviewer")
}
return nil
}
// Delete deletes a pull request usergroup reviewer.
func (s *UsergroupReviewerStore) Delete(ctx context.Context, prID, userGroupReviewerID int64) error {
const sqlQuery = `
DELETE FROM usergroup_reviewers
WHERE usergroup_reviewer_pullreq_id = $1 AND usergroup_reviewer_usergroup_id = $2`
db := dbtx.GetAccessor(ctx, s.db)
if _, err := db.ExecContext(ctx, sqlQuery, prID, userGroupReviewerID); err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to delete pull request usergroup reviewer")
}
return nil
}
// List returns a list of pull request usergroup reviewers.
func (s *UsergroupReviewerStore) List(ctx context.Context, prID int64) ([]*types.UserGroupReviewer, error) {
const sqlQuery = pullreqUserGroupReviewerSelectBase + `
WHERE usergroup_reviewer_pullreq_id = $1`
db := dbtx.GetAccessor(ctx, s.db)
var dst []*usergroupReviewer
if err := db.SelectContext(ctx, &dst, sqlQuery, prID); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to list pull request usergroup reviewers")
}
return s.mapSlicePullReqUserGroupReviewer(dst), nil
}
// Find returns a pull request usergroup reviewer by userGroupReviewerID.
func (s *UsergroupReviewerStore) Find(
ctx context.Context,
prID,
userGroupReviewerID int64,
) (*types.UserGroupReviewer, error) {
const sqlQuery = pullreqUserGroupReviewerSelectBase + `
WHERE usergroup_reviewer_pullreq_id = $1 AND usergroup_reviewer_usergroup_id = $2`
db := dbtx.GetAccessor(ctx, s.db)
dst := &usergroupReviewer{}
if err := db.GetContext(ctx, dst, sqlQuery, prID, userGroupReviewerID); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to find pull request usergroup reviewer")
}
return mapPullReqUserGroupReviewer(dst), nil
}
func mapInternalPullReqUserGroupReviewer(v *types.UserGroupReviewer) *usergroupReviewer {
m := &usergroupReviewer{
PullReqID: v.PullReqID,
UserGroupID: v.UserGroupID,
CreatedBy: v.CreatedBy,
Created: v.Created,
Updated: v.Updated,
RepoID: v.RepoID,
}
return m
}
func mapPullReqUserGroupReviewer(v *usergroupReviewer) *types.UserGroupReviewer {
m := &types.UserGroupReviewer{
PullReqID: v.PullReqID,
UserGroupID: v.UserGroupID,
CreatedBy: v.CreatedBy,
Created: v.Created,
Updated: v.Updated,
RepoID: v.RepoID,
}
return m
}
func (s *UsergroupReviewerStore) mapSlicePullReqUserGroupReviewer(
userGroupReviewers []*usergroupReviewer,
) []*types.UserGroupReviewer {
result := make([]*types.UserGroupReviewer, len(userGroupReviewers))
for i, v := range userGroupReviewers {
result[i] = mapPullReqUserGroupReviewer(v)
}
return result
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/label.go | app/store/database/label.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/store/database"
"github.com/harness/gitness/store/database/dbtx"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/Masterminds/squirrel"
"github.com/guregu/null"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
const (
labelColumns = `
label_space_id
,label_repo_id
,label_scope
,label_key
,label_description
,label_type
,label_color
,label_created
,label_updated
,label_created_by
,label_updated_by`
labelColumnsWithIDAndValueCount = labelColumns + `,label_id ,label_value_count`
//nolint:goconst
labelSelectBase = `SELECT ` + labelColumnsWithIDAndValueCount + ` FROM labels`
)
type label struct {
ID int64 `db:"label_id"`
SpaceID null.Int `db:"label_space_id"`
RepoID null.Int `db:"label_repo_id"`
Scope int64 `db:"label_scope"`
Key string `db:"label_key"`
Description string `db:"label_description"`
Type enum.LabelType `db:"label_type"`
Color enum.LabelColor `db:"label_color"`
ValueCount int64 `db:"label_value_count"`
Created int64 `db:"label_created"`
Updated int64 `db:"label_updated"`
CreatedBy int64 `db:"label_created_by"`
UpdatedBy int64 `db:"label_updated_by"`
}
type labelInfo struct {
LabelID int64 `db:"label_id"`
SpaceID null.Int `db:"label_space_id"`
RepoID null.Int `db:"label_repo_id"`
Scope int64 `db:"label_scope"`
Key string `db:"label_key"`
Type enum.LabelType `db:"label_type"`
LabelColor enum.LabelColor `db:"label_color"`
}
type labelStore struct {
db *sqlx.DB
}
func NewLabelStore(
db *sqlx.DB,
) store.LabelStore {
return &labelStore{
db: db,
}
}
var _ store.LabelStore = (*labelStore)(nil)
func (s *labelStore) Define(ctx context.Context, lbl *types.Label) error {
const sqlQuery = `
INSERT INTO labels (` + labelColumns + `)` + `
values (
:label_space_id
,:label_repo_id
,:label_scope
,:label_key
,:label_description
,:label_type
,:label_color
,:label_created
,:label_updated
,:label_created_by
,:label_updated_by
)
RETURNING label_id`
db := dbtx.GetAccessor(ctx, s.db)
query, args, err := db.BindNamed(sqlQuery, mapInternalLabel(lbl))
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to bind query")
}
if err = db.QueryRowContext(ctx, query, args...).Scan(&lbl.ID); err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to create label")
}
return nil
}
func (s *labelStore) Update(ctx context.Context, lbl *types.Label) error {
const sqlQuery = `
UPDATE labels SET
label_key = :label_key
,label_description = :label_description
,label_type = :label_type
,label_color = :label_color
,label_updated = :label_updated
,label_updated_by = :label_updated_by
WHERE label_id = :label_id`
db := dbtx.GetAccessor(ctx, s.db)
query, args, err := db.BindNamed(sqlQuery, mapInternalLabel(lbl))
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to bind query")
}
if _, err := db.ExecContext(ctx, query, args...); err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to update label")
}
return nil
}
func (s *labelStore) IncrementValueCount(
ctx context.Context,
labelID int64,
increment int,
) (int64, error) {
const sqlQuery = `
UPDATE labels
SET label_value_count = label_value_count + $1
WHERE label_id = $2
RETURNING label_value_count
`
db := dbtx.GetAccessor(ctx, s.db)
var valueCount int64
if err := db.QueryRowContext(ctx, sqlQuery, increment, labelID).Scan(&valueCount); err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "Failed to increment label_value_count")
}
return valueCount, nil
}
func (s *labelStore) Find(
ctx context.Context,
spaceID, repoID *int64,
key string,
) (*types.Label, error) {
const sqlQuery = labelSelectBase + `
WHERE (label_space_id = $1 OR label_repo_id = $2) AND LOWER(label_key) = LOWER($3)`
db := dbtx.GetAccessor(ctx, s.db)
var dst label
if err := db.GetContext(ctx, &dst, sqlQuery, spaceID, repoID, key); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to find label")
}
return mapLabel(&dst), nil
}
func (s *labelStore) FindByID(ctx context.Context, id int64) (*types.Label, error) {
const sqlQuery = labelSelectBase + `
WHERE label_id = $1`
db := dbtx.GetAccessor(ctx, s.db)
var dst label
if err := db.GetContext(ctx, &dst, sqlQuery, id); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to find label")
}
return mapLabel(&dst), nil
}
func (s *labelStore) Delete(ctx context.Context, spaceID, repoID *int64, name string) error {
const sqlQuery = `
DELETE FROM labels
WHERE (label_space_id = $1 OR label_repo_id = $2) AND LOWER(label_key) = LOWER($3)`
db := dbtx.GetAccessor(ctx, s.db)
if _, err := db.ExecContext(ctx, sqlQuery, spaceID, repoID, name); err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to delete label")
}
return nil
}
// List returns a list of pull requests for a repo or space.
func (s *labelStore) List(
ctx context.Context,
spaceID, repoID *int64,
filter *types.LabelFilter,
) ([]*types.Label, error) {
stmt := database.Builder.
Select(labelColumnsWithIDAndValueCount).
From("labels").
OrderBy("label_key")
stmt = stmt.Where("(label_space_id = ? OR label_repo_id = ?)", spaceID, repoID)
stmt = stmt.Limit(database.Limit(filter.Size))
stmt = stmt.Offset(database.Offset(filter.Page, filter.Size))
if filter.Query != "" {
stmt = stmt.Where(
"LOWER(label_key) LIKE '%' || LOWER(?) || '%'", filter.Query)
}
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, s.db)
var dst []*label
if err = db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to list labels")
}
return mapSliceLabel(dst), nil
}
func (s *labelStore) ListInScopes(
ctx context.Context,
repoID int64,
spaceIDs []int64,
filter *types.LabelFilter,
) ([]*types.Label, error) {
stmt := database.Builder.
Select(labelColumnsWithIDAndValueCount).
From("labels")
stmt = stmt.Where(squirrel.Or{
squirrel.Eq{"label_space_id": spaceIDs},
squirrel.Eq{"label_repo_id": repoID},
}).
OrderBy("label_key").
OrderBy("label_scope")
stmt = stmt.Limit(database.Limit(filter.Size))
stmt = stmt.Offset(database.Offset(filter.Page, filter.Size))
if filter.Query != "" {
stmt = stmt.Where(
"LOWER(label_key) LIKE '%' || LOWER(?) || '%'", filter.Query)
}
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, s.db)
var dst []*label
if err = db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to list labels in hierarchy")
}
return mapSliceLabel(dst), nil
}
func (s *labelStore) ListInfosInScopes(
ctx context.Context,
repoID int64,
spaceIDs []int64,
filter *types.AssignableLabelFilter,
) ([]*types.LabelInfo, error) {
stmt := database.Builder.
Select(`
label_id
,label_space_id
,label_repo_id
,label_scope
,label_key
,label_type
,label_color`).
From("labels").
Where(squirrel.Or{
squirrel.Eq{"label_space_id": spaceIDs},
squirrel.Eq{"label_repo_id": repoID},
}).
OrderBy("label_key").
OrderBy("label_scope")
stmt = stmt.Limit(database.Limit(filter.Size))
stmt = stmt.Offset(database.Offset(filter.Page, filter.Size))
if filter.Query != "" {
stmt = stmt.Where(
"LOWER(label_key) LIKE '%' || LOWER(?) || '%'", filter.Query)
}
sql, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, s.db)
var dst []*labelInfo
if err = db.SelectContext(ctx, &dst, sql, args...); err != nil {
return nil, database.ProcessSQLErrorf(ctx, err, "Failed to list labels")
}
return mapLabelInfos(dst), nil
}
func (s *labelStore) CountInSpace(
ctx context.Context,
spaceID int64,
filter *types.LabelFilter,
) (int64, error) {
const sqlQuery = `SELECT COUNT(*) FROM labels WHERE label_space_id = $1`
return s.count(ctx, sqlQuery, spaceID, filter)
}
func (s *labelStore) CountInRepo(
ctx context.Context,
repoID int64,
filter *types.LabelFilter,
) (int64, error) {
const sqlQuery = `SELECT COUNT(*) FROM labels WHERE label_repo_id = $1`
return s.count(ctx, sqlQuery, repoID, filter)
}
func (s labelStore) count(
ctx context.Context,
sqlQuery string,
scopeID int64,
filter *types.LabelFilter,
) (int64, error) {
sqlQuery += `
AND LOWER(label_key) LIKE '%' || LOWER($2) || '%'`
db := dbtx.GetAccessor(ctx, s.db)
var count int64
if err := db.QueryRowContext(ctx, sqlQuery, scopeID, filter.Query).Scan(&count); err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "Failed to count labels")
}
return count, nil
}
func (s *labelStore) CountInScopes(
ctx context.Context,
repoID int64,
spaceIDs []int64,
filter *types.LabelFilter,
) (int64, error) {
stmt := database.Builder.Select("COUNT(*)").
From("labels").
Where(squirrel.Or{
squirrel.Eq{"label_space_id": spaceIDs},
squirrel.Eq{"label_repo_id": repoID},
}).
Where("LOWER(label_key) LIKE '%' || LOWER(?) || '%'", filter.Query)
sql, args, err := stmt.ToSql()
if err != nil {
return 0, errors.Wrap(err, "Failed to convert query to sql")
}
db := dbtx.GetAccessor(ctx, s.db)
var count int64
if err = db.QueryRowContext(ctx, sql, args...).Scan(&count); err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "Failed to count labels in scopes")
}
return count, nil
}
func (s *labelStore) UpdateParentSpace(
ctx context.Context,
srcParentSpaceID int64,
targetParentSpaceID int64,
) (int64, error) {
stmt := database.Builder.Update("labels").
Set("label_space_id", targetParentSpaceID).
Where("label_space_id = ?", srcParentSpaceID)
db := dbtx.GetAccessor(ctx, s.db)
query, args, err := stmt.ToSql()
if err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "failed to bind query")
}
result, err := db.ExecContext(ctx, query, args...)
if err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "failed to update label")
}
count, err := result.RowsAffected()
if err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "failed to get number of updated rows")
}
return count, nil
}
func mapLabel(lbl *label) *types.Label {
return &types.Label{
ID: lbl.ID,
SpaceID: lbl.SpaceID.Ptr(),
RepoID: lbl.RepoID.Ptr(),
Scope: lbl.Scope,
Key: lbl.Key,
Type: lbl.Type,
Description: lbl.Description,
ValueCount: lbl.ValueCount,
Color: lbl.Color,
Created: lbl.Created,
Updated: lbl.Updated,
CreatedBy: lbl.CreatedBy,
UpdatedBy: lbl.UpdatedBy,
}
}
func mapSliceLabel(dbLabels []*label) []*types.Label {
result := make([]*types.Label, len(dbLabels))
for i, lbl := range dbLabels {
result[i] = mapLabel(lbl)
}
return result
}
func mapInternalLabel(lbl *types.Label) *label {
return &label{
ID: lbl.ID,
SpaceID: null.IntFromPtr(lbl.SpaceID),
RepoID: null.IntFromPtr(lbl.RepoID),
Scope: lbl.Scope,
Key: lbl.Key,
Description: lbl.Description,
Type: lbl.Type,
Color: lbl.Color,
Created: lbl.Created,
Updated: lbl.Updated,
CreatedBy: lbl.CreatedBy,
UpdatedBy: lbl.UpdatedBy,
}
}
func mapLabelInfo(internal *labelInfo) *types.LabelInfo {
return &types.LabelInfo{
ID: internal.LabelID,
RepoID: internal.RepoID.Ptr(),
SpaceID: internal.SpaceID.Ptr(),
Scope: internal.Scope,
Key: internal.Key,
Type: internal.Type,
Color: internal.LabelColor,
}
}
func mapLabelInfos(
dbLabels []*labelInfo,
) []*types.LabelInfo {
result := make([]*types.LabelInfo, len(dbLabels))
for i, lbl := range dbLabels {
result[i] = mapLabelInfo(lbl)
}
return result
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/migrate/migrate_0039_alter_table_webhooks_uid.go | app/store/database/migrate/migrate_0039_alter_table_webhooks_uid.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package migrate
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/harness/gitness/store/database"
"github.com/harness/gitness/types/check"
"github.com/guregu/null"
gonanoid "github.com/matoous/go-nanoid"
"github.com/rs/zerolog/log"
)
//nolint:gocognit,stylecheck,revive,staticcheck // have naming match migration version
func migrateAfter_0039_alter_table_webhooks_uid(ctx context.Context, dbtx *sql.Tx) error {
log := log.Ctx(ctx)
log.Info().Msg("backfill webhook_uid column")
// Unfortunately we have to process page by page in memory and can't process as we read:
// - lib/pq doesn't support updating webhook while select statement is ongoing
// https://github.com/lib/pq/issues/635
// - sqlite3 doesn't support DECLARE CURSOR functionality
type webhook struct {
id int64
spaceID null.Int
repoID null.Int
identifier null.String
displayName string
}
const pageSize = 1000
buffer := make([]webhook, pageSize)
page := 0
nextPage := func() (int, error) {
const selectQuery = `
SELECT webhook_id, webhook_display_name, webhook_repo_id, webhook_space_id, webhook_uid
FROM webhooks
ORDER BY webhook_repo_id, webhook_space_id, webhook_id
LIMIT $1
OFFSET $2
`
rows, err := dbtx.QueryContext(ctx, selectQuery, pageSize, page*pageSize)
if rows != nil {
defer func() {
err := rows.Close()
if err != nil {
log.Warn().Err(err).Msg("failed to close result rows")
}
}()
}
if err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "failed batch select query")
}
c := 0
for rows.Next() {
err = rows.Scan(&buffer[c].id, &buffer[c].displayName, &buffer[c].repoID, &buffer[c].spaceID, &buffer[c].identifier)
if err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "failed scanning next row")
}
c++
}
if rows.Err() != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "failed reading all rows")
}
page++
return c, nil
}
// keep track of unique identifiers for a given parent in memory (ASSUMPTION: limited number of webhooks per repo)
parentID := ""
parentChildIdentifiers := map[string]bool{}
for {
n, err := nextPage()
if err != nil {
return fmt.Errorf("failed to read next batch of webhooks: %w", err)
}
if n == 0 {
break
}
for i := range n {
wh := buffer[i]
// concatenate repoID + spaceID to get unique parent id (only used to identify same parents)
newParentID := fmt.Sprintf("%d_%d", wh.repoID.ValueOrZero(), wh.spaceID.ValueOrZero())
if newParentID != parentID {
// new parent? reset child identifiers
parentChildIdentifiers = map[string]bool{}
parentID = newParentID
}
// in case of down migration we already have identifiers for webhooks
if len(wh.identifier.ValueOrZero()) > 0 {
parentChildIdentifiers[strings.ToLower(wh.identifier.String)] = true
log.Info().Msgf(
"skip migration of webhook %d with displayname %q as it has a non-empty identifier %q",
wh.id,
wh.displayName,
wh.identifier.String,
)
continue
}
// try to generate unique id (adds random suffix if deterministic identifier derived from display name isn't unique)
for try := range 5 {
randomize := try > 0
newIdentifier, err := WebhookDisplayNameToIdentifier(wh.displayName, randomize)
if err != nil {
return fmt.Errorf("failed to migrate displayname: %w", err)
}
newIdentifierLower := strings.ToLower(newIdentifier)
if !parentChildIdentifiers[newIdentifierLower] {
parentChildIdentifiers[newIdentifierLower] = true
wh.identifier = null.StringFrom(newIdentifier)
break
}
}
if len(wh.identifier.ValueOrZero()) == 0 {
return fmt.Errorf("failed to find a unique identifier for webhook %d with displayname %q", wh.id, wh.displayName)
}
log.Info().Msgf(
"[%s] migrate webhook %d with displayname %q to identifier %q",
parentID,
wh.id,
wh.displayName,
wh.identifier.String,
)
const updateQuery = `
UPDATE webhooks
SET
webhook_uid = $1
WHERE
webhook_id = $2`
result, err := dbtx.ExecContext(ctx, updateQuery, wh.identifier.String, wh.id)
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "failed to update webhook")
}
count, err := result.RowsAffected()
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "Failed to get number of updated rows")
}
if count == 0 {
return fmt.Errorf("failed to update webhook identifier - no rows were updated")
}
}
}
return nil
}
// WebhookDisplayNameToIdentifier migrates the provided displayname to a webhook identifier.
// If randomize is true, a random suffix is added to randomize the identifier.
//
//nolint:gocognit
func WebhookDisplayNameToIdentifier(displayName string, randomize bool) (string, error) {
const placeholder = '_'
const specialChars = ".-_"
// remove / replace any illegal characters
// Identifier Regex: ^[a-zA-Z0-9-_.]*$
identifier := strings.Map(func(r rune) rune {
switch {
// drop any control characters or empty characters
case r < 32 || r == 127:
return -1
// keep all allowed character
case ('a' <= r && r <= 'z') ||
('A' <= r && r <= 'Z') ||
('0' <= r && r <= '9') ||
strings.ContainsRune(specialChars, r):
return r
// everything else is replaced with the placeholder
default:
return placeholder
}
}, displayName)
// remove any leading/trailing special characters
identifier = strings.Trim(identifier, specialChars)
// ensure string doesn't start with numbers (leading '_' is valid)
if len(identifier) > 0 && identifier[0] >= '0' && identifier[0] <= '9' {
identifier = string(placeholder) + identifier
}
// remove consecutive special characters
identifier = santizeConsecutiveChars(identifier, specialChars)
// ensure length restrictions
if len(identifier) > check.MaxIdentifierLength {
identifier = identifier[0:check.MaxIdentifierLength]
}
// backfill randomized identifier if sanitization ends up with empty identifier
if len(identifier) == 0 {
identifier = "webhook"
randomize = true
}
if randomize {
return randomizeIdentifier(identifier)
}
return identifier, nil
}
func santizeConsecutiveChars(in string, charSet string) string {
if len(in) == 0 {
return ""
}
inSet := func(b byte) bool {
return strings.ContainsRune(charSet, rune(b))
}
out := strings.Builder{}
out.WriteByte(in[0])
for i := 1; i < len(in); i++ {
if inSet(in[i]) && inSet(in[i-1]) {
continue
}
out.WriteByte(in[i])
}
return out.String()
}
func randomizeIdentifier(identifier string) (string, error) {
const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
const length = 4
const maxLength = check.MaxIdentifierLength - length - 1 // max length of identifier to fit random suffix
if len(identifier) > maxLength {
identifier = identifier[0:maxLength]
}
suffix, err := gonanoid.Generate(alphabet, length)
if err != nil {
return "", fmt.Errorf("failed to generate gonanoid: %w", err)
}
return identifier + "_" + suffix, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/migrate/migrate_test.go | app/store/database/migrate/migrate_test.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package migrate
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
var dirs = []string{
"postgres",
"sqlite",
}
// TestMigrationFilesExtension checks if all files in the postgres and sqlite
// migration directories have the .sql extension.
func TestMigrationFilesExtension(t *testing.T) {
for _, dir := range dirs {
files, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("Failed to read directory %s: %v", dir, err)
}
for _, file := range files {
if file.IsDir() {
continue
}
fileName := file.Name()
ext := filepath.Ext(fileName)
assert.Equal(t, ".sql", ext, "File %s in %s directory should have .sql extension", fileName, dir)
}
}
}
// TestMigrationFilesNumbering checks if migration files are numbered correctly
// and each version has only 2 files (up and down).
func TestMigrationFilesNumbering(t *testing.T) {
// Known issues with file numbering or files per version
knownIssues := map[string]map[string]bool{
"postgres": {
"0000": true,
"0001": true,
"0002": true,
"0003": true,
"0004": true,
"0005": true,
"0006": true,
"0007": true,
"0008": true,
"0009": true,
"0010": true,
"0011": true,
"0012": true,
"0021": true,
"0026": true,
"0029": true,
"0033": true,
"0058": true,
"0059": true,
"0106": true,
"0111": true,
"0115": true,
"0122": true,
"0134": true,
"0155": true,
},
"sqlite": {
"0000": true,
"0001": true,
"0002": true,
"0003": true,
"0004": true,
"0005": true,
"0006": true,
"0007": true,
"0008": true,
"0009": true,
"0010": true,
"0011": true,
"0012": true,
"0021": true,
"0029": true,
"0033": true,
"0058": true,
"0059": true,
"0097": true,
"0106": true,
"0111": true,
"0115": true,
"0122": true,
"0134": true,
"0135": true,
"0155": true,
},
}
for _, dir := range dirs {
files, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("Failed to read directory %s: %v", dir, err)
}
// Map to count files per version
versionCount := make(map[string][]string)
allVersions := make(map[int]bool)
// Check if files are numbered correctly
for _, file := range files {
if file.IsDir() {
continue
}
fileName := file.Name()
// Extract version number
versionStr, versionInt, _, err := extractVersion(fileName)
if err != nil {
t.Errorf("File %s in %s directory has invalid version: %v", fileName, dir, err)
continue
}
allVersions[versionInt] = true
if _, ok := knownIssues[dir][versionStr]; ok {
continue
}
versionCount[versionStr] = append(versionCount[versionStr], fileName)
}
// Check if each version has exactly 2 files (up and down)
for version, f := range versionCount {
if len(f) != 2 {
t.Errorf("Version %s in %s directory has %d files, expected 2 files (up and down)", version, dir,
len(f))
continue
}
name1, ext1, err := getFileParts(f[0])
if err != nil {
t.Errorf("File %s in %s directory has invalid name format: %v", f[0], dir, err)
}
name2, ext2, err := getFileParts(f[1])
if err != nil {
t.Errorf("File %s in %s directory has invalid name format: %v", f[0], dir, err)
}
if name1 != name2 {
t.Errorf("Name mismatch for version %s in %s directory: %s != %s", version, dir, files[0], files[1])
}
if !((ext1 == "up.sql" && ext2 == "down.sql") || (ext2 == "up.sql" && ext1 == "down.sql")) { //nolint:staticcheck
t.Errorf("Extension mismatch for version %s in %s directory: %s != %s", version, dir, files[0],
files[1])
}
}
// Check if all versions are in sequence order
maxVersion := -1
for versionInt := range allVersions {
if versionInt > maxVersion {
maxVersion = versionInt
}
}
if len(allVersions)-1 != maxVersion {
t.Errorf("Number of versions mismatch for %s in %s directory: %d != %d", dir, dir, len(allVersions),
maxVersion-1)
}
}
}
// getFileParts extracts the name and extension from a migration filename.
// It handles both formats:
// - {version}_{description}.{up|down}.sql → name="description", ext="up.sql"
// - {version}.{up|down}.sql → name="", ext="up.sql".
func getFileParts(filename string) (name, ext string, err error) {
parts := strings.SplitN(filename, "_", 2)
if len(parts) == 2 {
// Format: {version}_{description}.{up|down}.sql
parts2 := strings.SplitN(parts[1], ".", 2)
if len(parts2) != 2 {
return "", "", fmt.Errorf("invalid versioning %s", filename)
}
return parts2[0], parts2[1], nil
}
// Format: {version}.{up|down}.sql (no description suffix)
dotIndex := strings.Index(filename, ".")
if dotIndex == -1 {
return "", "", fmt.Errorf("invalid filename %s", filename)
}
return "", filename[dotIndex+1:], nil
}
// extractVersion extracts the version string and integer from a migration filename.
// It handles both formats:
// - {version}_{description}.{up|down}.sql (e.g., 0156_add_feature.up.sql)
// - {version}.{up|down}.sql (e.g., 0157.up.sql)
// Returns versionStr, versionInt, hasSuffix (true if file has description suffix), and error.
func extractVersion(fileName string) (versionStr string, versionInt int, hasSuffix bool, err error) {
parts := strings.Split(fileName, "_")
if len(parts) >= 2 {
// Format: {version}_{description}.{up|down}.sql
versionStr = parts[0]
hasSuffix = true
} else {
// Format: {version}.{up|down}.sql
dotIndex := strings.Index(fileName, ".")
if dotIndex == -1 {
return "", 0, false, fmt.Errorf("invalid filename format: %s", fileName)
}
versionStr = fileName[:dotIndex]
hasSuffix = false
}
versionInt, err = strconv.Atoi(versionStr)
if err != nil {
return "", 0, false, fmt.Errorf("invalid version number in %s: %w", fileName, err)
}
return versionStr, versionInt, hasSuffix, nil
}
// TestMigrationFilesNoSuffix checks that new migration files (after a certain version)
// don't have any suffix after the version number. This ensures git can detect conflicts
// when multiple developers try to add the same migration version.
// Example: 0157.up.sql is valid, 0157_add_feature.up.sql is not.
func TestMigrationFilesNoSuffix(t *testing.T) {
// Version threshold - files at or after this version should not have a suffix
// (only {version}.up.sql and {version}.down.sql are allowed)
const versionThreshold = 157
for _, dir := range dirs {
files, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("Failed to read directory %s: %v", dir, err)
}
for _, file := range files {
if file.IsDir() {
continue
}
fileName := file.Name()
// Extract version number using common helper
versionStr, versionInt, hasSuffix, err := extractVersion(fileName)
if err != nil {
continue
}
// Check if this is a new migration file
if versionInt >= versionThreshold {
// Version string should be 4 characters (e.g., "0157" not "157")
if len(versionStr) != 4 {
t.Errorf("Migration file %s in %s directory has version string %q with length %d, expected length 4",
fileName, dir, versionStr, len(versionStr))
}
// File should be named {version}.up.sql or {version}.down.sql
// Not {version}_description.up.sql
if hasSuffix {
expectedUpName := fmt.Sprintf("%04d.up.sql", versionInt)
expectedDownName := fmt.Sprintf("%04d.down.sql", versionInt)
t.Errorf("Migration file %s in %s directory should not have a suffix. "+
"Expected %s or %s to ensure git can detect conflicts when multiple "+
"developers add the same migration version",
fileName, dir, expectedUpName, expectedDownName)
}
}
}
}
}
// TestMigrationFilesExistInBothDatabases checks that the same migration files
// exist in both postgres and sqlite directories, with exceptions for known differences.
func TestMigrationFilesExistInBothDatabases(t *testing.T) {
// Known files that only exist in one database but not the other
knownExceptions := map[string]bool{
// Files only in postgres
"0000_create_extension_btree.up.sql": true,
"0000_create_extension_citext.up.sql": true,
"0000_create_extension_trgm.up.sql": true,
"0026_alter_repo_drop_job_id.up.sql": true, // Different naming in sqlite
"0026_alter_repo_drop_join_id.down.sql": true,
"0097_update_ar_generic_artifact_tables.down.sql": true, // Different naming in sqlite
"0097_update_ar_generic_artifact_tables.up.sql": true, // Different naming in sqlite
// Files only in sqlite
"0097_update_ar_generic_artiface_tables.up.sql": true,
"0026_alter_repo_drop_job_id.down.sql": true, // Different naming in postgres
}
// Read postgres directory
postgresFiles, err := os.ReadDir("postgres")
if err != nil {
t.Fatalf("Failed to read postgres directory: %v", err)
}
// Read sqlite directory
sqliteFiles, err := os.ReadDir("sqlite")
if err != nil {
t.Fatalf("Failed to read sqlite directory: %v", err)
}
// Create maps of file names for easier comparison
postgresFileMap := make(map[string]bool)
sqliteFileMap := make(map[string]bool)
for _, file := range postgresFiles {
if !file.IsDir() {
postgresFileMap[file.Name()] = true
}
}
for _, file := range sqliteFiles {
if !file.IsDir() {
sqliteFileMap[file.Name()] = true
}
}
// Check postgres files exist in sqlite
for fileName := range postgresFileMap {
if _, isException := knownExceptions[fileName]; isException {
continue // Skip known exceptions
}
if !sqliteFileMap[fileName] {
t.Errorf("File %s exists in postgres but not in sqlite", fileName)
}
}
// Check sqlite files exist in postgres
for fileName := range sqliteFileMap {
if _, isException := knownExceptions[fileName]; isException {
continue // Skip known exceptions
}
if !postgresFileMap[fileName] {
t.Errorf("File %s exists in sqlite but not in postgres", fileName)
}
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/migrate/migrate.go | app/store/database/migrate/migrate.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package migrate
import (
"context"
"database/sql"
"embed"
"fmt"
"io/fs"
"github.com/jmoiron/sqlx"
"github.com/maragudk/migrate"
"github.com/rs/zerolog/log"
)
//go:embed postgres/*.sql
var Postgres embed.FS
//go:embed sqlite/*.sql
var sqlite embed.FS
const (
tableName = "migrations"
postgresDriverName = "postgres"
postgresSourceDir = "postgres"
sqliteDriverName = "sqlite3"
sqliteSourceDir = "sqlite"
)
// Migrate performs the database migration.
func Migrate(ctx context.Context, db *sqlx.DB) (err error) {
opts, err := getMigrator(db)
if err != nil {
return fmt.Errorf("failed to get migrator: %w", err)
}
if db.DriverName() == sqliteDriverName {
if _, err := db.ExecContext(ctx, `PRAGMA foreign_keys = OFF;`); err != nil {
return fmt.Errorf("failed to disable foreign keys: %w", err)
}
defer func() {
_, fkOnErr := db.ExecContext(ctx, `PRAGMA foreign_keys = ON;`)
if err == nil && fkOnErr != nil {
err = fmt.Errorf("failed to enable foreign keys: %w", fkOnErr)
}
}()
}
return migrate.New(opts).MigrateUp(ctx)
}
// To performs the database migration to the specific version.
func To(ctx context.Context, db *sqlx.DB, version string) (err error) {
opts, err := getMigrator(db)
if err != nil {
return fmt.Errorf("failed to get migrator: %w", err)
}
if db.DriverName() == sqliteDriverName {
if _, err := db.ExecContext(ctx, `PRAGMA foreign_keys = OFF;`); err != nil {
return fmt.Errorf("failed to disable foreign keys: %w", err)
}
defer func() {
_, fkOnErr := db.ExecContext(ctx, `PRAGMA foreign_keys = ON;`)
if err == nil && fkOnErr != nil {
err = fmt.Errorf("failed to enable foreign keys: %w", fkOnErr)
}
}()
}
return migrate.New(opts).MigrateTo(ctx, version)
}
// Current returns the current version ID (the latest migration applied) of the database.
func Current(ctx context.Context, db *sqlx.DB) (string, error) {
var (
query string
migrationTableCount int
)
switch db.DriverName() {
case sqliteDriverName:
query = `
SELECT count(*)
FROM sqlite_master
WHERE name = ? and type = 'table'`
case postgresDriverName:
query = `
SELECT count(*)
FROM information_schema.tables
WHERE table_name = ? and table_schema = 'public'`
default:
return "", fmt.Errorf("unsupported driver '%s'", db.DriverName())
}
if err := db.QueryRowContext(ctx, query, tableName).Scan(&migrationTableCount); err != nil {
return "", fmt.Errorf("failed to check migration table existence: %w", err)
}
if migrationTableCount == 0 {
return "", nil
}
var version string
query = "select version from " + tableName + " limit 1"
if err := db.QueryRowContext(ctx, query).Scan(&version); err != nil {
return "", fmt.Errorf("failed to read current DB version from migration table: %w", err)
}
return version, nil
}
func getMigrator(db *sqlx.DB) (migrate.Options, error) {
before := func(ctx context.Context, _ *sql.Tx, version string) error {
ctx = log.Ctx(ctx).With().
Str("migrate.version", version).
Str("migrate.phase", "before").
Logger().WithContext(ctx)
log := log.Ctx(ctx)
log.Info().Msg("[START]")
defer log.Info().Msg("[DONE]")
return nil
}
after := func(ctx context.Context, dbtx *sql.Tx, version string) error {
ctx = log.Ctx(ctx).With().
Str("migrate.version", version).
Str("migrate.phase", "after").
Logger().WithContext(ctx)
log := log.Ctx(ctx)
log.Info().Msg("[START]")
defer log.Info().Msg("[DONE]")
switch version {
case "0039_alter_table_webhooks_uid":
return migrateAfter_0039_alter_table_webhooks_uid(ctx, dbtx)
case "0042_alter_table_rules":
return migrateAfter_0042_alter_table_rules(ctx, dbtx)
case "0153_migrate_artifacts":
return MigrateAfter_0153_migrate_artifacts(ctx, dbtx)
case "0155_migrate_rpm_artifacts":
return MigrateAfter_0155_migrate_rpm_artifacts(ctx, dbtx, db.DriverName())
default:
return nil
}
}
opts := migrate.Options{
After: after,
Before: before,
DB: db.DB,
FS: sqlite,
Table: tableName,
}
switch db.DriverName() {
case sqliteDriverName:
folder, _ := fs.Sub(sqlite, sqliteSourceDir)
opts.FS = folder
case postgresDriverName:
folder, _ := fs.Sub(Postgres, postgresSourceDir)
opts.FS = folder
default:
return migrate.Options{}, fmt.Errorf("unsupported driver '%s'", db.DriverName())
}
return opts, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/migrate/migrate_0151_migrate_artifacts.go | app/store/database/migrate/migrate_0151_migrate_artifacts.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package migrate
import (
"context"
"database/sql"
"encoding/hex"
"errors"
"fmt"
databaseg "github.com/harness/gitness/store/database"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
)
//nolint:gocognit,stylecheck,revive,staticcheck // have naming match migration version
func MigrateAfter_0153_migrate_artifacts(ctx context.Context, dbtx *sql.Tx) error {
log := log.Ctx(ctx)
mediaTypeIDs, err := getMediaTypeIDs(ctx, dbtx)
if err != nil {
return fmt.Errorf("failed to get media type IDs: %w", err)
}
if len(mediaTypeIDs) == 0 {
log.Info().Msg("no relevant media types found, nothing to migrate")
return nil
}
log.Info().Msg("starting artifacts migration...")
const batchSize = 1000
offset := 0
totalProcessed := 0
batchCount := 0
for {
batchCount++
log.Info().Int("batch", batchCount).Int("offset", offset).Msg("processing batch")
manifests, err := getManifestsBatch(ctx, dbtx, mediaTypeIDs, batchSize, offset)
if err != nil {
return fmt.Errorf("failed to get manifests batch: %w", err)
}
if len(manifests) == 0 {
break // No more manifests to process
}
// Process the batch
err = processManifestsBatch(ctx, dbtx, manifests)
if err != nil {
return fmt.Errorf("failed to process manifests batch: %w", err)
}
totalProcessed += len(manifests)
offset += batchSize
log.Info().
Int("batch", batchCount).
Int("count", len(manifests)).
Int("total", totalProcessed).
Msg("processed batch")
}
log.Info().Int("total_processed", totalProcessed).Msg("artifacts migration completed")
return nil
}
type manifest struct {
ID int64
ImageName string
RegistryID int64
Digest []byte
CreatedAt int64
UpdatedAt int64
CreatedBy int64
UpdatedBy int64
}
func getMediaTypeIDs(ctx context.Context, dbtx *sql.Tx) ([]int64, error) {
query := `
SELECT mt_id
FROM media_types
WHERE mt_media_type IN (
'application/vnd.docker.distribution.manifest.list.v2+json',
'application/vnd.oci.image.index.v1+json'
)`
rows, err := dbtx.QueryContext(ctx, query)
if err != nil {
return nil, fmt.Errorf("failed to query media types: %w", err)
}
defer rows.Close()
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, fmt.Errorf("failed to scan media type ID: %w", err)
}
ids = append(ids, id)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating media types: %w", err)
}
return ids, nil
}
func getManifestsBatch(
ctx context.Context,
dbtx *sql.Tx,
mediaTypeIDs []int64,
limit, offset int,
) ([]manifest, error) {
if len(mediaTypeIDs) != 2 {
return nil, fmt.Errorf("expected exactly 2 media type IDs, got %d", len(mediaTypeIDs))
}
query := `
SELECT
m.manifest_id,
m.manifest_image_name,
m.manifest_registry_id,
m.manifest_digest,
m.manifest_created_at,
m.manifest_updated_at,
m.manifest_created_by,
m.manifest_updated_by
FROM manifests m
WHERE m.manifest_media_type_id IN ($1, $2)
ORDER BY m.manifest_id
LIMIT $3 OFFSET $4`
args := []any{
mediaTypeIDs[0],
mediaTypeIDs[1],
limit,
offset,
}
rows, err := dbtx.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("failed to query manifests: %w", err)
}
defer rows.Close()
var manifests []manifest
for rows.Next() {
var m manifest
err := rows.Scan(
&m.ID,
&m.ImageName,
&m.RegistryID,
&m.Digest,
&m.CreatedAt,
&m.UpdatedAt,
&m.CreatedBy,
&m.UpdatedBy,
)
if err != nil {
return nil, fmt.Errorf("failed to scan manifest: %w", err)
}
manifests = append(manifests, m)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating manifests: %w", err)
}
return manifests, nil
}
func processManifestsBatch(ctx context.Context, dbtx *sql.Tx, manifests []manifest) error {
db := dbtx
for _, m := range manifests {
var imageID int64
q := databaseg.Builder.Select("image_id").
From("images").
Where("image_name = ? AND image_registry_id = ?", m.ImageName, m.RegistryID)
query, args, err := q.ToSql()
if err != nil {
return fmt.Errorf("failed to build image select query: %w", err)
}
err = db.QueryRowContext(ctx, query, args...).Scan(&imageID)
//nolint: nestif
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
imgUUID := uuid.NewString()
q2 := databaseg.Builder.Insert("images").
SetMap(map[string]interface{}{
"image_name": m.ImageName,
"image_registry_id": m.RegistryID,
"image_type": nil,
"image_labels": nil,
"image_enabled": true,
"image_created_at": m.CreatedAt,
"image_updated_at": m.CreatedAt,
"image_created_by": m.CreatedBy,
"image_updated_by": m.UpdatedBy,
"image_uuid": imgUUID,
}).
Suffix("RETURNING image_id")
query2, args2, err2 := q2.ToSql()
if err2 != nil {
return fmt.Errorf("failed to build image insert query: %w", err)
}
err = db.QueryRowContext(ctx, query2, args2...).Scan(&imageID)
if err != nil {
return fmt.Errorf("failed to insert image: %w", err)
}
} else {
return fmt.Errorf("failed to check for existing image: %w", err)
}
digestHex := hex.EncodeToString(m.Digest)
var artifactID int64
q3 := databaseg.Builder.Select("artifact_id").
From("artifacts").
Where("artifact_image_id = ? AND artifact_version = ?", imageID, digestHex)
query3, args3, err3 := q3.ToSql()
if err3 != nil {
return fmt.Errorf("failed to build artifact select query: %w", err)
}
artUUID := uuid.NewString()
err = db.QueryRowContext(ctx, query3, args3...).Scan(&artifactID)
if errors.Is(err, sql.ErrNoRows) {
q4 := databaseg.Builder.Insert("artifacts").
SetMap(map[string]interface{}{
"artifact_version": digestHex,
"artifact_image_id": imageID,
"artifact_created_at": m.CreatedAt,
"artifact_updated_at": m.CreatedAt,
"artifact_created_by": m.CreatedBy,
"artifact_updated_by": m.UpdatedBy,
"artifact_metadata": nil,
"artifact_uuid": artUUID,
})
query4, args4, err4 := q4.ToSql()
if err4 != nil {
return fmt.Errorf("failed to build artifact insert query: %w", err)
}
_, err = db.ExecContext(ctx, query4, args4...)
if err != nil {
return fmt.Errorf("failed to insert artifact: %w", err)
}
} else if err != nil && !errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("failed to check for existing artifact: %w", err)
}
}
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/migrate/migrate_0039_alter_table_webhooks_uid_test.go | app/store/database/migrate/migrate_0039_alter_table_webhooks_uid_test.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package migrate
import (
"regexp"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestWebhookDisplayNameToIdentifier(t *testing.T) {
var tests = []struct {
displayName string
randomize bool
expectedIdentifier string
expectedRandomized bool
}{
// ensure only allowed characters get through
{"az.A-Z_09", false, "az.A-Z_09", false},
{"a" + string(rune(21)) + "a", false, "aa", false},
{"a a", false, "a_a", false},
// ensure leading/trailing special characters are removed
{".-_a_-.", false, "a", false},
// doesn't start with numbers
{"0", false, "_0", false},
// consecutive special characters are removed
{"a .-__--..a", false, "a_a", false},
// max length requirements
{strings.Repeat("a", 101), false, strings.Repeat("a", 100), false},
{" " + strings.Repeat("a", 100) + " ", false, strings.Repeat("a", 100), false},
// empty identifier after sanitization
{"", false, "webhook", true},
{string(rune(21)), false, "webhook", true},
{" .-_-. ", false, "webhook", true},
// randomized
{"a", true, "a", true},
{strings.Repeat("a", 100), true, strings.Repeat("a", 95), true},
// smoke tests
{"harness (pipeline NR. #1)", false, "harness_pipeline_NR.1", false},
{".harness/pipeline/Build.yaml", true, "harness_pipeline_Build.yaml", true},
{".harness/pipeline/Build.yaml", true, "harness_pipeline_Build.yaml", true},
}
rndSuffixRegex := regexp.MustCompile("^_[a-z0-9]{4}$")
for i, test := range tests {
identifier, err := WebhookDisplayNameToIdentifier(test.displayName, test.randomize)
assert.NoError(t, err, "test case %d - migration ended in error (unexpected)") // no errors expected
if test.expectedRandomized {
assert.True(t, len(identifier) >= 5, "test case %d - identifier length doesn't indicate random suffix", i)
rndSuffix := identifier[len(identifier)-5:]
identifier = identifier[:len(identifier)-5]
matched := rndSuffixRegex.Match([]byte(rndSuffix))
assert.True(t, matched, "test case %d - identifier doesn't contain expected random suffix", i)
}
assert.Equal(t, test.expectedIdentifier, identifier, "test case %d doesn't match the expected identifier'", i)
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/migrate/migrate_0042_alter_table_rules.go | app/store/database/migrate/migrate_0042_alter_table_rules.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package migrate
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"github.com/harness/gitness/app/services/protection"
"github.com/harness/gitness/store/database"
"github.com/rs/zerolog/log"
)
//nolint:gocognit,stylecheck,revive,staticcheck // have naming match migration version
func migrateAfter_0042_alter_table_rules(
ctx context.Context,
dbtx *sql.Tx,
) error {
log := log.Ctx(ctx)
log.Info().Msg("migrate all branch rules from uid to identifier")
// Unfortunately we have to process page by page in memory and can't process as we read:
// - lib/pq doesn't support updating rule while select statement is ongoing
// https://github.com/lib/pq/issues/635
// - sqlite3 doesn't support DECLARE CURSOR functionality
type rule struct {
id int64
uid string
definition string
}
const pageSize = 1000
buffer := make([]rule, pageSize)
page := 0
nextPage := func() (int, error) {
const selectQuery = `
SELECT rule_id, rule_uid, rule_definition
FROM rules
WHERE rule_type = 'branch'
LIMIT $1
OFFSET $2
`
rows, err := dbtx.QueryContext(ctx, selectQuery, pageSize, page*pageSize)
if rows != nil {
defer func() {
err := rows.Close()
if err != nil {
log.Warn().Err(err).Msg("failed to close result rows")
}
}()
}
if err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "failed batch select query")
}
c := 0
for rows.Next() {
err = rows.Scan(&buffer[c].id, &buffer[c].uid, &buffer[c].definition)
if err != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "failed scanning next row")
}
c++
}
if rows.Err() != nil {
return 0, database.ProcessSQLErrorf(ctx, err, "failed reading all rows")
}
page++
return c, nil
}
for {
n, err := nextPage()
if err != nil {
return fmt.Errorf("failed to read next batch of rules: %w", err)
}
if n == 0 {
break
}
for i := range n {
r := buffer[i]
log.Info().Msgf(
"migrate rule %d with identifier %q",
r.id,
r.uid,
)
branchDefinition := protection.Branch{}
// unmarshaling the json will deserialize require_uids into require_uids and require_identifiers.
// NOTE: could be done with existing SanitizeJSON method, but that would require dependencies.
err = json.Unmarshal(json.RawMessage(r.definition), &branchDefinition)
if err != nil {
return fmt.Errorf("failed to unmarshal branch definition: %w", err)
}
updatedDefinitionRaw, err := protection.ToJSON(&branchDefinition)
if err != nil {
return fmt.Errorf("failed to marshal branch definition: %w", err)
}
// skip updating DB in case there's no change (e.g. no required checks are configured or migration re-runs)
updatedDefinitionString := string(updatedDefinitionRaw)
if updatedDefinitionString == r.definition {
log.Info().Msg("skip updating rule as there's no change in definition")
continue
}
const updateQuery = `
UPDATE rules
SET
rule_definition = $1
WHERE
rule_id = $2`
result, err := dbtx.ExecContext(ctx, updateQuery, updatedDefinitionString, r.id)
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "failed to update rule")
}
count, err := result.RowsAffected()
if err != nil {
return database.ProcessSQLErrorf(ctx, err, "failed to get number of updated rows")
}
if count == 0 {
return fmt.Errorf("failed to update branch rule definition - no rows were updated")
}
}
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/migrate/migrate_0155_migrate_rpm_artifacts.go | app/store/database/migrate/migrate_0155_migrate_rpm_artifacts.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package migrate
import (
"bytes"
"context"
"crypto/rand"
"database/sql"
"encoding/base32"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/harness/gitness/job"
rpmmetadata "github.com/harness/gitness/registry/app/metadata/rpm"
"github.com/harness/gitness/store/database"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
)
//nolint:gocognit,stylecheck,revive,staticcheck // have naming match migration version
func MigrateAfter_0155_migrate_rpm_artifacts(
ctx context.Context, dbtx *sql.Tx, driverName string,
) error {
log := log.Ctx(ctx)
log.Info().Msg("starting artifacts migration...")
const batchSize = 1000
offset := 0
totalProcessed := 0
batchCount := 0
for {
batchCount++
log.Info().Int("batch", batchCount).Int("offset", offset).Msg("processing batch")
artifacts, err := getArtifactsBatch(ctx, dbtx, driverName, batchSize, offset)
if err != nil {
return fmt.Errorf("failed to get artifacts batch: %w", err)
}
if len(artifacts) == 0 {
break // No more artifacts to process
}
// Process the batch
err = processArtifactsBatch(ctx, dbtx, artifacts)
if err != nil {
return fmt.Errorf("failed to process artifacts batch: %w", err)
}
totalProcessed += len(artifacts)
offset += batchSize
log.Info().
Int("batch", batchCount).
Int("count", len(artifacts)).
Int("total", totalProcessed).
Msg("processed batch")
}
log.Info().Int("total_processed", totalProcessed).Msg("artifacts migration completed")
return nil
}
func getArtifactsBatch(
ctx context.Context,
dbtx *sql.Tx,
driverName string,
limit, offset int,
) ([]artifact, error) {
var query string
if driverName == "sqliteDriverName" {
query = `SELECT a.artifact_id, i.image_name, a.artifact_version, i.image_registry_id, a.artifact_metadata
FROM artifacts a
JOIN images i ON a.artifact_image_id = i.image_id
WHERE COALESCE(json_extract(artifact_metadata, '$.file_metadata.epoch'), '') NOT IN ('0', ''); `
} else {
query = `SELECT a.artifact_id, i.image_name, a.artifact_version, i.image_registry_id, a.artifact_metadata
FROM artifacts a
JOIN images i ON a.artifact_image_id = i.image_id
WHERE COALESCE(artifact_metadata->'file_metadata'->>'epoch', '') NOT IN ('0', '')
LIMIT $1 OFFSET $2`
}
args := []any{
limit,
offset,
}
rows, err := dbtx.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("failed to query artifacts: %w", err)
}
defer rows.Close()
var artifacts []artifact
for rows.Next() {
var a artifact
err := rows.Scan(
&a.ID,
&a.Name,
&a.Version,
&a.RegistryID,
&a.Metadata,
)
if err != nil {
return nil, fmt.Errorf("failed to scan artifact: %w", err)
}
artifacts = append(artifacts, a)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("error fetching rows: %w", err)
}
return artifacts, nil
}
type artifact struct {
ID int64
Name string
Version string
RegistryID int64
Metadata json.RawMessage
}
type node struct {
ID string
Name string
RegistryID int64
IsFile bool
NodePath string
BlobID *string
ParentNodeID *string
CreatedAt int64
CreatedBy int64
}
func processArtifactsBatch(ctx context.Context, dbtx *sql.Tx, artifacts []artifact) error {
db := dbtx
for _, a := range artifacts {
metadata := rpmmetadata.RpmMetadata{}
err := json.Unmarshal(a.Metadata, &metadata)
if err != nil {
return err
}
// nolint:nestif
if strings.HasPrefix(a.Version, metadata.FileMetadata.Epoch+"-") {
_, version, ok := strings.Cut(a.Version, "-")
if !ok {
return fmt.Errorf(
"failed to cut version: %s", a.Version)
}
filename := fmt.Sprintf("%s-%s.rpm", a.Name, version)
metadata.Files[0].Filename = filename
metadataJSON, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to marshal metadata: %w", err)
}
//-------- update metadata
dbVersion := metadata.FileMetadata.Epoch + ":" + version
updateMetadataQuery := `UPDATE artifacts
SET artifact_metadata = $1, artifact_version = $2
WHERE artifact_id = $3`
_, err = db.ExecContext(ctx, updateMetadataQuery, metadataJSON, dbVersion, a.ID)
if err != nil {
return fmt.Errorf("failed to update artifact metadata: %w", err)
}
//-------- update nodes
lastDotIndex := strings.LastIndex(a.Version, ".")
versionNode := a.Version[:lastDotIndex]
nodesQuery := `SELECT * FROM nodes WHERE node_registry_id = $1 AND node_path LIKE $2`
rows, err := dbtx.QueryContext(ctx, nodesQuery, a.RegistryID, "/"+a.Name+"/"+versionNode+"%")
if err != nil {
return fmt.Errorf("failed to query nodes: %w", err)
}
defer rows.Close()
var nodes []node
for rows.Next() {
var n node
err := rows.Scan(
&n.ID,
&n.Name,
&n.ParentNodeID,
&n.RegistryID,
&n.IsFile,
&n.NodePath,
&n.BlobID,
&n.CreatedAt,
&n.CreatedBy,
)
if err != nil {
return fmt.Errorf("failed to scan artifact: %w", err)
}
nodes = append(nodes, n)
}
if err := rows.Err(); err != nil {
return fmt.Errorf("error fetching rows: %w", err)
}
for _, n := range nodes {
l := strings.LastIndex(version, ".")
newNodeName := version[:l]
if n.Name == versionNode {
updateNodeNameQuery := `UPDATE nodes
SET node_name = $1
WHERE node_id = $2`
_, err = db.ExecContext(ctx, updateNodeNameQuery, newNodeName, n.ID)
if err != nil {
return fmt.Errorf("failed to update node: %w", err)
}
}
newPath := strings.Replace(n.NodePath, "/"+versionNode, "/"+newNodeName, 1)
updateNodeQuery := `UPDATE nodes
SET node_path = $1
WHERE node_id = $2`
_, err = db.ExecContext(ctx, updateNodeQuery, newPath, n.ID)
if err != nil {
return fmt.Errorf("failed to update node: %w", err)
}
if strings.HasSuffix(n.NodePath, ".rpm") {
// -------- insert epoch node
lastSlashIndex := strings.LastIndex(newPath, "/")
p := newPath[:lastSlashIndex]
epochNodePath := p + "/" + metadata.FileMetadata.Epoch
epochNodeID := uuid.NewString()
insertQuery := `INSERT INTO nodes
(node_id, node_name, node_parent_id, node_registry_id, node_is_file, node_path,
node_generic_blob_id, node_created_at, node_created_by)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`
_, err = db.ExecContext(ctx, insertQuery,
epochNodeID,
metadata.FileMetadata.Epoch,
n.ParentNodeID,
n.RegistryID,
false,
epochNodePath,
nil,
n.CreatedAt,
n.CreatedBy,
)
if err != nil {
return fmt.Errorf("failed to insert node: %w", err)
}
// ----------- update file node
newFileNodeName := a.Name + "-" + version + ".rpm"
updateNodeNameQuery := `UPDATE nodes
SET node_name = $1, node_path = $2, node_parent_id = $3
WHERE node_id = $4`
_, err = db.ExecContext(ctx, updateNodeNameQuery, newFileNodeName,
epochNodePath+"/"+newFileNodeName, epochNodeID, n.ID)
if err != nil {
return fmt.Errorf("failed to update node: %w", err)
}
}
}
}
err = scheduleIndexJob(ctx, dbtx, RegistrySyncInput{RegistryIDs: []int64{a.RegistryID}})
if err != nil {
return fmt.Errorf("failed to schedule rpm registry index job: %w", err)
}
}
return nil
}
func scheduleIndexJob(ctx context.Context, dbtx *sql.Tx, input RegistrySyncInput) error {
data, err := json.Marshal(input)
if err != nil {
return fmt.Errorf("failed to marshal repository sync job input json: %w", err)
}
data = bytes.TrimSpace(data)
var idRaw [10]byte
if _, err := rand.Read(idRaw[:]); err != nil {
return fmt.Errorf("could not generate rpm registry index job ID: %w", err)
}
id := base32.StdEncoding.EncodeToString(idRaw[:])
jd := job.Definition{
UID: id,
Type: "rpm_registry_index",
MaxRetries: 5,
Timeout: 45 * time.Minute,
Data: string(data),
}
nowMilli := time.Now().UnixMilli()
job := &job.Job{
UID: jd.UID,
Created: nowMilli,
Updated: nowMilli,
Type: jd.Type,
Priority: job.JobPriorityNormal,
Data: jd.Data,
Result: "",
MaxDurationSeconds: int(jd.Timeout / time.Second),
MaxRetries: jd.MaxRetries,
State: job.JobStateScheduled,
Scheduled: nowMilli,
TotalExecutions: 0,
RunBy: "",
RunDeadline: nowMilli,
RunProgress: job.ProgressMin,
LastExecuted: 0, // never executed
IsRecurring: false,
RecurringCron: "",
ConsecutiveFailures: 0,
LastFailureError: "",
}
const sqlQuery = `INSERT INTO jobs (
job_uid,
job_created,
job_updated,
job_type,
job_priority,
job_data,
job_result,
job_max_duration_seconds,
job_max_retries,
job_state,
job_scheduled,
job_total_executions,
job_run_by,
job_run_deadline,
job_run_progress,
job_last_executed,
job_is_recurring,
job_recurring_cron,
job_consecutive_failures,
job_last_failure_error,
job_group_id
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)`
if _, err := dbtx.ExecContext(ctx, sqlQuery, job.UID,
job.Created,
job.Updated,
job.Type,
job.Priority,
job.Data,
job.Result,
job.MaxDurationSeconds,
job.MaxRetries,
job.State,
job.Scheduled,
job.TotalExecutions,
job.RunBy,
job.RunDeadline,
job.RunProgress,
job.LastExecuted,
job.IsRecurring,
job.RecurringCron,
job.ConsecutiveFailures,
job.LastFailureError,
"",
); err != nil {
return database.ProcessSQLErrorf(ctx, err, "Insert job query failed")
}
return nil
}
type RegistrySyncInput struct {
RegistryIDs []int64 `json:"registry_ids"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/store/database/mutex/mutex.go | app/store/database/mutex/mutex.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package mutex provides a global mutex.
package mutex
import "sync"
var m sync.RWMutex
// RLock locks the global mutex for reads.
func RLock() { m.RLock() }
// RUnlock unlocks the global mutex.
func RUnlock() { m.RUnlock() }
// Lock locks the global mutex for writes.
func Lock() { m.Lock() }
// Unlock unlocks the global mutex.
func Unlock() { m.Unlock() }
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/bootstrap/wire.go | app/bootstrap/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bootstrap
import (
"github.com/harness/gitness/app/api/controller/service"
"github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/types"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(ProvideBootstrap)
func ProvideBootstrap(config *types.Config, userCtrl *user.Controller,
serviceCtrl *service.Controller) Bootstrap {
return System(config, userCtrl, serviceCtrl)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/bootstrap/bootstrap.go | app/bootstrap/bootstrap.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bootstrap
import (
"context"
"errors"
"fmt"
"github.com/harness/gitness/app/api/controller/service"
"github.com/harness/gitness/app/api/controller/user"
"github.com/harness/gitness/app/auth"
"github.com/harness/gitness/store"
"github.com/harness/gitness/types"
"github.com/rs/zerolog/log"
)
// systemServicePrincipal is the principal representing Harness.
// It is used for all operations executed by Harness itself.
var systemServicePrincipal *types.Principal
var ErrAdminEmailRequired = errors.New("config.Principal.Admin.Email is required")
func NewSystemServiceSession() *auth.Session {
return &auth.Session{
Principal: *systemServicePrincipal,
Metadata: &auth.EmptyMetadata{},
}
}
// pipelineServicePrincipal is the principal that is used during
// pipeline executions for calling Harness APIs.
var pipelineServicePrincipal *types.Principal
func NewPipelineServiceSession() *auth.Session {
return &auth.Session{
Principal: *pipelineServicePrincipal,
Metadata: &auth.EmptyMetadata{},
}
}
// gitspaceServicePrincipal is the principal that is used during
// gitspace token injection for calling Harness APIs.
var gitspaceServicePrincipal *types.Principal
func NewGitspaceServiceSession() *auth.Session {
return &auth.Session{
Principal: *gitspaceServicePrincipal,
Metadata: &auth.EmptyMetadata{},
}
}
// Bootstrap is an abstraction of a function that bootstraps a system.
type Bootstrap func(context.Context) error
func System(config *types.Config, userCtrl *user.Controller,
serviceCtrl *service.Controller) func(context.Context) error {
return func(ctx context.Context) error {
if err := SystemService(ctx, config, serviceCtrl); err != nil {
return fmt.Errorf("failed to setup system service: %w", err)
}
if err := PipelineService(ctx, config, serviceCtrl); err != nil {
return fmt.Errorf("failed to setup pipeline service: %w", err)
}
if err := GitspaceService(ctx, config, serviceCtrl); err != nil {
return fmt.Errorf("failed to setup gitspace service: %w", err)
}
if err := AdminUser(ctx, config, userCtrl); err != nil {
return fmt.Errorf("failed to setup admin user: %w", err)
}
return nil
}
}
// AdminUser sets up the admin user based on the config (if provided).
func AdminUser(ctx context.Context, config *types.Config, userCtrl *user.Controller) error {
if config.Principal.Admin.Password == "" {
return nil
}
if config.Principal.Admin.Email == "" {
return fmt.Errorf("failed to set up admin user: %w", ErrAdminEmailRequired)
}
usr, err := userCtrl.FindNoAuth(ctx, config.Principal.Admin.UID)
if errors.Is(err, store.ErrResourceNotFound) {
usr, err = createAdminUser(ctx, config, userCtrl)
}
if err != nil {
return fmt.Errorf("failed to setup admin user: %w", err)
}
if !usr.Admin {
return fmt.Errorf("user with uid '%s' exists but is no admin (ID: %d)", usr.UID, usr.ID)
}
log.Ctx(ctx).Info().Msgf("Completed setup of admin user '%s' (id: %d).", usr.UID, usr.ID)
return nil
}
func createAdminUser(
ctx context.Context,
config *types.Config,
userCtrl *user.Controller,
) (*types.User, error) {
in := &user.CreateInput{
UID: config.Principal.Admin.UID,
DisplayName: config.Principal.Admin.DisplayName,
Email: config.Principal.Admin.Email,
Password: config.Principal.Admin.Password,
}
usr, createErr := userCtrl.CreateNoAuth(ctx, in, true)
if createErr == nil || !errors.Is(createErr, store.ErrDuplicate) {
return usr, createErr
}
// user might've been created by another instance in which case we should find it now.
var findErr error
usr, findErr = userCtrl.FindNoAuth(ctx, config.Principal.Admin.UID)
if findErr != nil {
return nil, fmt.Errorf(
"failed to find user with uid '%s' (%w) after duplicate error: %w",
config.Principal.Admin.UID,
findErr,
createErr,
)
}
return usr, nil
}
// SystemService sets up the Harness service principal that is used for
// resources that are automatically created by the system.
func SystemService(
ctx context.Context,
config *types.Config,
serviceCtrl *service.Controller,
) error {
svc, err := serviceCtrl.FindNoAuth(ctx, config.Principal.System.UID)
if errors.Is(err, store.ErrResourceNotFound) {
svc, err = createServicePrincipal(
ctx,
serviceCtrl,
config.Principal.System.UID,
config.Principal.System.Email,
config.Principal.System.DisplayName,
true,
)
}
if err != nil {
return fmt.Errorf("failed to setup system service: %w", err)
}
if !svc.Admin {
return fmt.Errorf("service with uid '%s' exists but is no admin (ID: %d)", svc.UID, svc.ID)
}
systemServicePrincipal = svc.ToPrincipal()
log.Ctx(ctx).Info().Msgf("Completed setup of system service '%s' (id: %d).", svc.UID, svc.ID)
return nil
}
// PipelineService sets up the pipeline service principal that is used during
// pipeline executions for calling Harness APIs.
func PipelineService(
ctx context.Context,
config *types.Config,
serviceCtrl *service.Controller,
) error {
svc, err := serviceCtrl.FindNoAuth(ctx, config.Principal.Pipeline.UID)
if errors.Is(err, store.ErrResourceNotFound) {
svc, err = createServicePrincipal(
ctx,
serviceCtrl,
config.Principal.Pipeline.UID,
config.Principal.Pipeline.Email,
config.Principal.Pipeline.DisplayName,
false,
)
}
if err != nil {
return fmt.Errorf("failed to setup pipeline service: %w", err)
}
pipelineServicePrincipal = svc.ToPrincipal()
log.Ctx(ctx).Info().Msgf("Completed setup of pipeline service '%s' (id: %d).", svc.UID, svc.ID)
return nil
}
// GitspaceService sets up the gitspace service principal that is used during
// gitspace credential injection for calling Harness APIs.
func GitspaceService(
ctx context.Context,
config *types.Config,
serviceCtrl *service.Controller,
) error {
svc, err := serviceCtrl.FindNoAuth(ctx, config.Principal.Gitspace.UID)
if errors.Is(err, store.ErrResourceNotFound) {
svc, err = createServicePrincipal(
ctx,
serviceCtrl,
config.Principal.Gitspace.UID,
config.Principal.Gitspace.Email,
config.Principal.Gitspace.DisplayName,
false,
)
}
if err != nil {
return fmt.Errorf("failed to setup gitspace service: %w", err)
}
gitspaceServicePrincipal = svc.ToPrincipal()
log.Ctx(ctx).Info().Msgf("Completed setup of gitspace service '%s' (id: %d).", svc.UID, svc.ID)
return nil
}
func createServicePrincipal(
ctx context.Context,
serviceCtrl *service.Controller,
uid string,
email string,
displayName string,
admin bool,
) (*types.Service, error) {
in := &service.CreateInput{
UID: uid,
Email: email,
DisplayName: displayName,
}
svc, createErr := serviceCtrl.CreateNoAuth(ctx, in, admin)
if createErr == nil || !errors.Is(createErr, store.ErrDuplicate) {
return svc, createErr
}
// service might've been created by another instance in which case we should find it now.
var findErr error
svc, findErr = serviceCtrl.FindNoAuth(ctx, uid)
if findErr != nil {
return nil, fmt.Errorf(
"failed to find service with uid '%s' (%w) after duplicate error: %w",
uid,
findErr,
createErr,
)
}
return svc, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/connector/wire.go | app/connector/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package connector
import (
"github.com/harness/gitness/app/connector/scm"
"github.com/harness/gitness/app/store"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideConnectorHandler,
ProvideSCMConnectorHandler,
)
// ProvideConnectorHandler provides a connector handler for handling connector-related ops.
func ProvideConnectorHandler(
secretStore store.SecretStore,
scmService *scm.Service,
) *Service {
return New(secretStore, scmService)
}
// ProvideSCMConnectorHandler provides a SCM connector handler for specifically handling
// SCM connector related ops.
func ProvideSCMConnectorHandler(secretStore store.SecretStore) *scm.Service {
return scm.NewService(secretStore)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/connector/connector.go | app/connector/connector.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package connector
import (
"context"
"time"
"github.com/harness/gitness/app/connector/scm"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/types"
)
var (
testConnectionTimeout = 5 * time.Second
)
type Service struct {
secretStore store.SecretStore
// A separate SCM connector service is helpful here since the go-scm library abstracts out all the specific
// SCM interactions, making the interfacing common for all the SCM connectors.
// There might be connectors (eg docker, gcr, etc) in the future which require separate implementations.
// Nevertheless, there should be an attempt to abstract out common functionality for different connector
// types if possible - otherwise separate implementations can be written here.
scmService *scm.Service
}
func New(secretStore store.SecretStore, scmService *scm.Service) *Service {
return &Service{
secretStore: secretStore,
scmService: scmService,
}
}
func (s *Service) Test(
ctx context.Context,
connector *types.Connector,
) (types.ConnectorTestResponse, error) {
// Set a timeout while testing connection.
ctxWithTimeout, cancel := context.WithDeadline(ctx, time.Now().Add(testConnectionTimeout))
defer cancel()
if connector.Type.IsSCM() {
return s.scmService.Test(ctxWithTimeout, connector)
}
return types.ConnectorTestResponse{}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/connector/scm/scm.go | app/connector/scm/scm.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scm
import (
"context"
"fmt"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type Service struct {
secretStore store.SecretStore
}
func NewService(secretStore store.SecretStore) *Service {
return &Service{
secretStore: secretStore,
}
}
func (s *Service) Test(ctx context.Context, c *types.Connector) (types.ConnectorTestResponse, error) {
if !c.Type.IsSCM() {
return types.ConnectorTestResponse{}, fmt.Errorf("connector type: %s is not an SCM connector", c.Type.String())
}
client, err := getSCMProvider(ctx, c, s.secretStore)
if err != nil {
return types.ConnectorTestResponse{}, err
}
// Check whether a valid user exists - if yes, the connection is successful
_, _, err = client.Users.Find(ctx)
if err != nil {
return types.ConnectorTestResponse{Status: enum.ConnectorStatusFailed, ErrorMsg: err.Error()}, nil //nolint:nilerr
}
return types.ConnectorTestResponse{Status: enum.ConnectorStatusSuccess}, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/connector/scm/provider.go | app/connector/scm/provider.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scm
import (
"context"
"fmt"
"net/http"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/drone/go-scm/scm"
"github.com/drone/go-scm/scm/driver/github"
"github.com/drone/go-scm/scm/transport/oauth2"
)
// getSCMProvider returns an SCM client given a connector.
// The SCM client can be used as a common layer for interfacing with any SCM.
func getSCMProvider(
ctx context.Context,
connector *types.Connector,
secretStore store.SecretStore,
) (*scm.Client, error) {
var client *scm.Client
var err error
var transport http.RoundTripper
switch x := connector.Type; x {
case enum.ConnectorTypeGithub:
if connector.Github == nil {
return nil, fmt.Errorf("github connector is nil")
}
if connector.Github.APIURL == "" {
client = github.NewDefault()
} else {
client, err = github.New(connector.Github.APIURL)
if err != nil {
return nil, err
}
}
if connector.Github.Auth == nil {
return nil, fmt.Errorf("github auth needs to be provided")
}
if connector.Github.Auth.AuthType == enum.ConnectorAuthTypeBearer {
creds := connector.Github.Auth.Bearer
pass, err := resolveSecret(ctx, connector.SpaceID, creds.Token, secretStore)
if err != nil {
return nil, err
}
transport = oauthTransport(pass, oauth2.SchemeBearer)
} else {
return nil, fmt.Errorf("unsupported auth type for github connector: %s", connector.Github.Auth.AuthType)
}
default:
return nil, fmt.Errorf("unsupported scm provider type: %s", x)
}
// override default transport if available
if transport != nil {
client.Client = &http.Client{Transport: transport}
}
return client, nil
}
func oauthTransport(token string, scheme string) http.RoundTripper {
if token == "" {
return nil
}
return &oauth2.Transport{
Base: defaultTransport(),
Scheme: scheme,
Source: oauth2.StaticTokenSource(&scm.Token{Token: token}),
}
}
// defaultTransport provides a default http.Transport.
// This can be extended when needed for things like more advanced TLS config, proxies, etc.
func defaultTransport() http.RoundTripper {
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
}
}
// resolveSecret looks into the secret store to find the value of a secret.
func resolveSecret(
ctx context.Context,
spaceID int64,
ref types.SecretRef,
secretStore store.SecretStore,
) (string, error) {
// the secret should be in the same space as the connector
s, err := secretStore.FindByIdentifier(ctx, spaceID, ref.Identifier)
if err != nil {
return "", fmt.Errorf("could not find secret from store: %w", err)
}
return s.Data, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/cron/wire.go | app/cron/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cron
import "github.com/google/wire"
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(NewNightly)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/cron/nightly_test.go | app/cron/nightly_test.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cron
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/cron/nightly.go | app/cron/nightly.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cron
import (
"context"
"time"
"github.com/rs/zerolog/log"
)
// Nightly is a sub-routine that periodically purges historical data.
type Nightly struct {
// Inject required stores here
}
// NewNightly returns a new Nightly sub-routine.
func NewNightly() *Nightly {
return &Nightly{}
}
// Run runs the purge sub-routine.
func (n *Nightly) Run(ctx context.Context) {
const hoursPerDay = 24
ticker := time.NewTicker(hoursPerDay * time.Hour)
logger := log.Ctx(ctx)
for {
select {
case <-ctx.Done():
return // break
case <-ticker.C:
// TODO replace this with your nightly
// cron tasks.
logger.Trace().Msg("cron job executed")
}
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/url/wire.go | app/url/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package url
import (
"github.com/harness/gitness/types"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(ProvideURLProvider)
func ProvideURLProvider(config *types.Config) (Provider, error) {
return NewProvider(
config.URL.Internal,
config.URL.Container,
config.URL.API,
config.URL.Git,
config.URL.GitSSH,
config.SSH.DefaultUser,
config.SSH.Enable,
config.URL.UI,
config.URL.Registry,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/url/provider.go | app/url/provider.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package url
import (
"context"
"fmt"
"net"
"net/url"
"path"
"strconv"
"strings"
"github.com/harness/gitness/app/paths"
"github.com/rs/zerolog/log"
)
const (
// GITSuffix is the suffix used to terminate repo paths for git apis.
GITSuffix = ".git"
// APIMount is the prefix path for the api endpoints.
APIMount = "api"
// GITMount is the prefix path for the git endpoints.
GITMount = "git"
)
// Provider is an abstraction of a component that provides system related URLs.
// NOTE: Abstract to allow for custom implementation for more complex routing environments.
type Provider interface {
// GetInternalAPIURL returns the internally reachable base url of the server.
// NOTE: url is guaranteed to not have any trailing '/'.
GetInternalAPIURL(ctx context.Context) string
// GenerateContainerGITCloneURL generates a URL that can be used by CI container builds to
// interact with Harness and clone a repo.
GenerateContainerGITCloneURL(ctx context.Context, repoPath string) string
// GenerateGITCloneURL generates the public git clone URL for the provided repo path.
// NOTE: url is guaranteed to not have any trailing '/'.
GenerateGITCloneURL(ctx context.Context, repoPath string) string
// GenerateGITCloneSSHURL generates the public git clone URL for the provided repo path.
// NOTE: url is guaranteed to not have any trailing '/'.
GenerateGITCloneSSHURL(ctx context.Context, repoPath string) string
// GenerateUIRepoURL returns the url for the UI screen of a repository.
GenerateUIRepoURL(ctx context.Context, repoPath string) string
// GenerateUIPRURL returns the url for the UI screen of an existing pr.
GenerateUIPRURL(ctx context.Context, repoPath string, prID int64) string
// GenerateUICompareURL returns the url for the UI screen comparing two references.
GenerateUICompareURL(ctx context.Context, repoPath string, ref1 string, ref2 string) string
// GenerateUIRefURL returns the url for the UI screen for given ref.
GenerateUIRefURL(ctx context.Context, repoPath string, ref string) string
// GetAPIHostname returns the host for the api endpoint.
GetAPIHostname(ctx context.Context) string
// GenerateUIBuildURL returns the endpoint to use for viewing build executions.
GenerateUIBuildURL(ctx context.Context, repoPath, pipelineIdentifier string, seqNumber int64) string
// GetGITHostname returns the host for the git endpoint.
GetGITHostname(ctx context.Context) string
// GetAPIProto returns the proto for the API hostname
GetAPIProto(ctx context.Context) string
RegistryURL(ctx context.Context, params ...string) string
PackageURL(ctx context.Context, regRef string, pkgType string, params ...string) string
GetUIBaseURL(ctx context.Context, params ...string) string
// GenerateUIRegistryURL returns the url for the UI screen of a registry.
GenerateUIRegistryURL(ctx context.Context, parentSpacePath string, registryName string) string
}
// Provider provides the URLs of the Harness system.
type provider struct {
// internalURL stores the URL via which the service is reachable at internally
// (no need for internal services to go via public route).
internalURL *url.URL
// containerURL stores the URL that can be used to communicate with Harness from inside a
// build container.
containerURL *url.URL
// apiURL stores the raw URL the api endpoints are reachable at publicly.
apiURL *url.URL
// gitURL stores the URL the git endpoints are available at.
// NOTE: we store it as url.URL so we can derive clone URLS without errors.
gitURL *url.URL
SSHEnabled bool
SSHDefaultUser string
gitSSHURL *url.URL
// uiURL stores the raw URL to the ui endpoints.
uiURL *url.URL
// registryURL stores the raw URL to the registry endpoints.
registryURL *url.URL
}
func NewProvider(
internalURLRaw,
containerURLRaw string,
apiURLRaw string,
gitURLRaw,
gitSSHURLRaw string,
sshDefaultUser string,
sshEnabled bool,
uiURLRaw string,
registryURLRaw string,
) (Provider, error) {
// remove trailing '/' to make usage easier
internalURLRaw = strings.TrimRight(internalURLRaw, "/")
containerURLRaw = strings.TrimRight(containerURLRaw, "/")
apiURLRaw = strings.TrimRight(apiURLRaw, "/")
gitURLRaw = strings.TrimRight(gitURLRaw, "/")
gitSSHURLRaw = strings.TrimRight(gitSSHURLRaw, "/")
uiURLRaw = strings.TrimRight(uiURLRaw, "/")
registryURLRaw = strings.TrimRight(registryURLRaw, "/")
internalURL, err := url.Parse(internalURLRaw)
if err != nil {
return nil, fmt.Errorf("provided internalURLRaw '%s' is invalid: %w", internalURLRaw, err)
}
containerURL, err := url.Parse(containerURLRaw)
if err != nil {
return nil, fmt.Errorf("provided containerURLRaw '%s' is invalid: %w", containerURLRaw, err)
}
apiURL, err := url.Parse(apiURLRaw)
if err != nil {
return nil, fmt.Errorf("provided apiURLRaw '%s' is invalid: %w", apiURLRaw, err)
}
gitURL, err := url.Parse(gitURLRaw)
if err != nil {
return nil, fmt.Errorf("provided gitURLRaw '%s' is invalid: %w", gitURLRaw, err)
}
gitSSHURL, err := url.Parse(gitSSHURLRaw)
if sshEnabled && err != nil {
return nil, fmt.Errorf("provided gitSSHURLRaw '%s' is invalid: %w", gitSSHURLRaw, err)
}
uiURL, err := url.Parse(uiURLRaw)
if err != nil {
return nil, fmt.Errorf("provided uiURLRaw '%s' is invalid: %w", uiURLRaw, err)
}
registryURL, err := url.Parse(registryURLRaw)
if err != nil {
return nil, fmt.Errorf("provided registryURLRaw '%s' is invalid: %w", registryURLRaw, err)
}
return &provider{
internalURL: internalURL,
containerURL: containerURL,
apiURL: apiURL,
gitURL: gitURL,
gitSSHURL: gitSSHURL,
SSHDefaultUser: sshDefaultUser,
SSHEnabled: sshEnabled,
uiURL: uiURL,
registryURL: registryURL,
}, nil
}
func (p *provider) GetInternalAPIURL(context.Context) string {
return p.internalURL.JoinPath(APIMount).String()
}
func (p *provider) GenerateContainerGITCloneURL(_ context.Context, repoPath string) string {
repoPath = path.Clean(repoPath)
if !strings.HasSuffix(repoPath, GITSuffix) {
repoPath += GITSuffix
}
return p.containerURL.JoinPath(GITMount, repoPath).String()
}
func (p *provider) GenerateGITCloneURL(_ context.Context, repoPath string) string {
repoPath = path.Clean(repoPath)
if !strings.HasSuffix(repoPath, GITSuffix) {
repoPath += GITSuffix
}
return p.gitURL.JoinPath(repoPath).String()
}
func (p *provider) GenerateGITCloneSSHURL(_ context.Context, repoPath string) string {
if !p.SSHEnabled {
return ""
}
return BuildGITCloneSSHURL(p.SSHDefaultUser, p.gitSSHURL, repoPath)
}
func (p *provider) GenerateUIBuildURL(_ context.Context, repoPath, pipelineIdentifier string, seqNumber int64) string {
return p.uiURL.JoinPath(
repoPath, "pipelines",
pipelineIdentifier, "execution", strconv.Itoa(int(seqNumber)),
).String()
}
func (p *provider) GenerateUIRepoURL(_ context.Context, repoPath string) string {
return p.uiURL.JoinPath(repoPath).String()
}
func (p *provider) GenerateUIPRURL(_ context.Context, repoPath string, prID int64) string {
return p.uiURL.JoinPath(repoPath, "pulls", fmt.Sprint(prID)).String()
}
func (p *provider) GenerateUICompareURL(_ context.Context, repoPath string, ref1 string, ref2 string) string {
return p.uiURL.JoinPath(repoPath, "pulls/compare", ref1+"..."+ref2).String()
}
func (p *provider) GenerateUIRefURL(_ context.Context, repoPath string, ref string) string {
return p.uiURL.JoinPath(repoPath, "commit", ref).String()
}
func (p *provider) GetAPIHostname(context.Context) string {
return p.apiURL.Hostname()
}
func (p *provider) GetGITHostname(context.Context) string {
return p.gitURL.Hostname()
}
func (p *provider) GetAPIProto(context.Context) string {
return p.apiURL.Scheme
}
func (p *provider) RegistryURL(_ context.Context, params ...string) string {
u := *p.registryURL
segments := []string{u.Path}
if len(params) > 0 {
if len(params) > 1 && (params[1] == "generic" || params[1] == "maven") {
params[0], params[1] = params[1], params[0]
} else {
params[0] = strings.ToLower(params[0])
}
}
segments = append(segments, params...)
fullPath := path.Join(segments...)
u.Path = fullPath
return strings.TrimRight(u.String(), "/")
}
func (p *provider) PackageURL(_ context.Context, regRef string, pkgType string, params ...string) string {
u, err := url.Parse(p.registryURL.String())
if err != nil {
log.Warn().Msgf("failed to parse registry url: %v", err)
return p.registryURL.String()
}
segments := []string{u.Path}
segments = append(segments, "pkg")
segments = append(segments, regRef)
segments = append(segments, pkgType)
segments = append(segments, params...)
fullPath := path.Join(segments...)
u.Path = fullPath
return strings.TrimRight(u.String(), "/")
}
func (p *provider) GetUIBaseURL(_ context.Context, _ ...string) string {
return p.uiURL.String()
}
func (p *provider) GenerateUIRegistryURL(_ context.Context, parentSpacePath string, registryName string) string {
segments := paths.Segments(parentSpacePath)
if len(segments) < 1 {
return ""
}
space := segments[0]
return p.uiURL.String() + "/spaces/" + space + "/registries/" + registryName
}
func BuildGITCloneSSHURL(user string, sshURL *url.URL, repoPath string) string {
repoPath = path.Clean(repoPath)
if !strings.HasSuffix(repoPath, GITSuffix) {
repoPath += GITSuffix
}
// SSH clone url requires custom format depending on port to satisfy git
combinedPath := strings.Trim(path.Join(sshURL.Path, repoPath), "/")
// handle custom ports differently as otherwise git clone fails
if sshURL.Port() != "" && sshURL.Port() != "0" && sshURL.Port() != "22" {
return fmt.Sprintf(
"ssh://%s@%s/%s",
user, net.JoinHostPort(sshURL.Hostname(), sshURL.Port()), combinedPath,
)
}
return fmt.Sprintf(
"%s@%s:%s",
user, sshURL.Hostname(), combinedPath,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/url/provider_test.go | app/url/provider_test.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package url
import (
"context"
"net/url"
"testing"
)
func TestBuildGITCloneSSHURL(t *testing.T) {
tests := []struct {
name string
user string
sshURL string
repoPath string
want string
}{
{
name: "standard port 22",
user: "git",
sshURL: "ssh://git.example.com:22",
repoPath: "org/repo",
want: "git@git.example.com:org/repo.git",
},
{
name: "default port (empty)",
user: "git",
sshURL: "ssh://git.example.com",
repoPath: "org/repo",
want: "git@git.example.com:org/repo.git",
},
{
name: "custom port",
user: "git",
sshURL: "ssh://git.example.com:2222",
repoPath: "org/repo",
want: "ssh://git@git.example.com:2222/org/repo.git",
},
{
name: "repo path with .git suffix",
user: "git",
sshURL: "ssh://git.example.com",
repoPath: "org/repo.git",
want: "git@git.example.com:org/repo.git",
},
{
name: "repo path with leading slash",
user: "git",
sshURL: "ssh://git.example.com",
repoPath: "/org/repo",
want: "git@git.example.com:org/repo.git",
},
{
name: "repo path with trailing slash",
user: "git",
sshURL: "ssh://git.example.com",
repoPath: "org/repo/",
want: "git@git.example.com:org/repo.git",
},
{
name: "custom port with path in URL",
user: "git",
sshURL: "ssh://git.example.com:2222/base",
repoPath: "org/repo",
want: "ssh://git@git.example.com:2222/base/org/repo.git",
},
{
name: "standard port with path in URL",
user: "git",
sshURL: "ssh://git.example.com:22/base",
repoPath: "org/repo",
want: "git@git.example.com:base/org/repo.git",
},
{
name: "port 0 treated as default",
user: "git",
sshURL: "ssh://git.example.com:0",
repoPath: "org/repo",
want: "git@git.example.com:org/repo.git",
},
{
name: "different username",
user: "admin",
sshURL: "ssh://git.example.com",
repoPath: "org/repo",
want: "admin@git.example.com:org/repo.git",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sshURL, err := url.Parse(tt.sshURL)
if err != nil {
t.Fatalf("failed to parse sshURL: %v", err)
}
got := BuildGITCloneSSHURL(tt.user, sshURL, tt.repoPath)
if got != tt.want {
t.Errorf("BuildGITCloneSSHURL() = %v, want %v", got, tt.want)
}
})
}
}
func TestNewProvider(t *testing.T) {
tests := []struct {
name string
internalURLRaw string
containerURLRaw string
apiURLRaw string
gitURLRaw string
gitSSHURLRaw string
sshDefaultUser string
sshEnabled bool
uiURLRaw string
registryURLRaw string
wantErr bool
}{
{
name: "valid URLs",
internalURLRaw: "http://internal.example.com",
containerURLRaw: "http://container.example.com",
apiURLRaw: "http://api.example.com",
gitURLRaw: "http://git.example.com",
gitSSHURLRaw: "ssh://git.example.com:22",
sshDefaultUser: "git",
sshEnabled: true,
uiURLRaw: "http://ui.example.com",
registryURLRaw: "http://registry.example.com",
wantErr: false,
},
{
name: "URLs with trailing slashes",
internalURLRaw: "http://internal.example.com/",
containerURLRaw: "http://container.example.com/",
apiURLRaw: "http://api.example.com/",
gitURLRaw: "http://git.example.com/",
gitSSHURLRaw: "ssh://git.example.com:22/",
sshDefaultUser: "git",
sshEnabled: true,
uiURLRaw: "http://ui.example.com/",
registryURLRaw: "http://registry.example.com/",
wantErr: false,
},
{
name: "invalid internal URL",
internalURLRaw: "://invalid",
containerURLRaw: "http://container.example.com",
apiURLRaw: "http://api.example.com",
gitURLRaw: "http://git.example.com",
gitSSHURLRaw: "ssh://git.example.com:22",
sshDefaultUser: "git",
sshEnabled: false,
uiURLRaw: "http://ui.example.com",
registryURLRaw: "http://registry.example.com",
wantErr: true,
},
{
name: "invalid container URL",
internalURLRaw: "http://internal.example.com",
containerURLRaw: "://invalid",
apiURLRaw: "http://api.example.com",
gitURLRaw: "http://git.example.com",
gitSSHURLRaw: "ssh://git.example.com:22",
sshDefaultUser: "git",
sshEnabled: false,
uiURLRaw: "http://ui.example.com",
registryURLRaw: "http://registry.example.com",
wantErr: true,
},
{
name: "invalid SSH URL when SSH enabled",
internalURLRaw: "http://internal.example.com",
containerURLRaw: "http://container.example.com",
apiURLRaw: "http://api.example.com",
gitURLRaw: "http://git.example.com",
gitSSHURLRaw: "://invalid",
sshDefaultUser: "git",
sshEnabled: true,
uiURLRaw: "http://ui.example.com",
registryURLRaw: "http://registry.example.com",
wantErr: true,
},
{
name: "invalid SSH URL when SSH disabled (should not error)",
internalURLRaw: "http://internal.example.com",
containerURLRaw: "http://container.example.com",
apiURLRaw: "http://api.example.com",
gitURLRaw: "http://git.example.com",
gitSSHURLRaw: "://invalid",
sshDefaultUser: "git",
sshEnabled: false,
uiURLRaw: "http://ui.example.com",
registryURLRaw: "http://registry.example.com",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := NewProvider(
tt.internalURLRaw,
tt.containerURLRaw,
tt.apiURLRaw,
tt.gitURLRaw,
tt.gitSSHURLRaw,
tt.sshDefaultUser,
tt.sshEnabled,
tt.uiURLRaw,
tt.registryURLRaw,
)
if (err != nil) != tt.wantErr {
t.Errorf("NewProvider() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestProvider_GetInternalAPIURL(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
ctx := context.Background()
got := p.GetInternalAPIURL(ctx)
want := "http://internal.example.com/api"
if got != want {
t.Errorf("GetInternalAPIURL() = %v, want %v", got, want)
}
}
func TestProvider_GenerateContainerGITCloneURL(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
tests := []struct {
name string
repoPath string
want string
}{
{
name: "simple repo path",
repoPath: "org/repo",
want: "http://container.example.com/git/org/repo.git",
},
{
name: "repo path with .git suffix",
repoPath: "org/repo.git",
want: "http://container.example.com/git/org/repo.git",
},
{
name: "repo path with leading slash",
repoPath: "/org/repo",
want: "http://container.example.com/git/org/repo.git",
},
}
ctx := context.Background()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := p.GenerateContainerGITCloneURL(ctx, tt.repoPath)
if got != tt.want {
t.Errorf("GenerateContainerGITCloneURL() = %v, want %v", got, tt.want)
}
})
}
}
func TestProvider_GenerateGITCloneURL(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
tests := []struct {
name string
repoPath string
want string
}{
{
name: "simple repo path",
repoPath: "org/repo",
want: "http://git.example.com/org/repo.git",
},
{
name: "repo path with .git suffix",
repoPath: "org/repo.git",
want: "http://git.example.com/org/repo.git",
},
}
ctx := context.Background()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := p.GenerateGITCloneURL(ctx, tt.repoPath)
if got != tt.want {
t.Errorf("GenerateGITCloneURL() = %v, want %v", got, tt.want)
}
})
}
}
func TestProvider_GenerateGITCloneSSHURL(t *testing.T) {
tests := []struct {
name string
sshEnabled bool
repoPath string
want string
}{
{
name: "SSH enabled",
sshEnabled: true,
repoPath: "org/repo",
want: "git@git.example.com:org/repo.git",
},
{
name: "SSH disabled",
sshEnabled: false,
repoPath: "org/repo",
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
tt.sshEnabled,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
ctx := context.Background()
got := p.GenerateGITCloneSSHURL(ctx, tt.repoPath)
if got != tt.want {
t.Errorf("GenerateGITCloneSSHURL() = %v, want %v", got, tt.want)
}
})
}
}
func TestProvider_GenerateUIRepoURL(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
ctx := context.Background()
got := p.GenerateUIRepoURL(ctx, "org/repo")
want := "http://ui.example.com/org/repo"
if got != want {
t.Errorf("GenerateUIRepoURL() = %v, want %v", got, want)
}
}
func TestProvider_GenerateUIPRURL(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
ctx := context.Background()
got := p.GenerateUIPRURL(ctx, "org/repo", 123)
want := "http://ui.example.com/org/repo/pulls/123"
if got != want {
t.Errorf("GenerateUIPRURL() = %v, want %v", got, want)
}
}
func TestProvider_GenerateUICompareURL(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
ctx := context.Background()
got := p.GenerateUICompareURL(ctx, "org/repo", "main", "develop")
want := "http://ui.example.com/org/repo/pulls/compare/main...develop"
if got != want {
t.Errorf("GenerateUICompareURL() = %v, want %v", got, want)
}
}
func TestProvider_GenerateUIRefURL(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
ctx := context.Background()
got := p.GenerateUIRefURL(ctx, "org/repo", "abc123")
want := "http://ui.example.com/org/repo/commit/abc123"
if got != want {
t.Errorf("GenerateUIRefURL() = %v, want %v", got, want)
}
}
func TestProvider_GetAPIHostname(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com:8080",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
ctx := context.Background()
got := p.GetAPIHostname(ctx)
want := "api.example.com"
if got != want {
t.Errorf("GetAPIHostname() = %v, want %v", got, want)
}
}
func TestProvider_GetGITHostname(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com:9090",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
ctx := context.Background()
got := p.GetGITHostname(ctx)
want := "git.example.com"
if got != want {
t.Errorf("GetGITHostname() = %v, want %v", got, want)
}
}
func TestProvider_GetAPIProto(t *testing.T) {
tests := []struct {
name string
apiURLRaw string
want string
}{
{
name: "http protocol",
apiURLRaw: "http://api.example.com",
want: "http",
},
{
name: "https protocol",
apiURLRaw: "https://api.example.com",
want: "https",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
tt.apiURLRaw,
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
ctx := context.Background()
got := p.GetAPIProto(ctx)
if got != tt.want {
t.Errorf("GetAPIProto() = %v, want %v", got, tt.want)
}
})
}
}
func TestProvider_GetUIBaseURL(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
ctx := context.Background()
got := p.GetUIBaseURL(ctx)
want := "http://ui.example.com"
if got != want {
t.Errorf("GetUIBaseURL() = %v, want %v", got, want)
}
}
func TestProvider_GenerateUIBuildURL(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
ctx := context.Background()
got := p.GenerateUIBuildURL(ctx, "org/repo", "my-pipeline", 42)
want := "http://ui.example.com/org/repo/pipelines/my-pipeline/execution/42"
if got != want {
t.Errorf("GenerateUIBuildURL() = %v, want %v", got, want)
}
}
func TestProvider_RegistryURL(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
tests := []struct {
name string
params []string
want string
}{
{
name: "no params",
params: []string{},
want: "http://registry.example.com",
},
{
name: "single param",
params: []string{"docker"},
want: "http://registry.example.com/docker",
},
{
name: "generic type swaps params",
params: []string{"myregistry", "generic"},
want: "http://registry.example.com/generic/myregistry",
},
{
name: "maven type swaps params",
params: []string{"myregistry", "maven"},
want: "http://registry.example.com/maven/myregistry",
},
{
name: "docker type lowercase",
params: []string{"DOCKER"},
want: "http://registry.example.com/docker",
},
}
ctx := context.Background()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := p.RegistryURL(ctx, tt.params...)
if got != tt.want {
t.Errorf("RegistryURL() = %v, want %v", got, tt.want)
}
})
}
}
func TestProvider_PackageURL(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
tests := []struct {
name string
regRef string
pkgType string
params []string
want string
}{
{
name: "basic package URL",
regRef: "myregistry",
pkgType: "docker",
params: []string{},
want: "http://registry.example.com/pkg/myregistry/docker",
},
{
name: "package URL with params",
regRef: "myregistry",
pkgType: "docker",
params: []string{"myimage", "v1.0.0"},
want: "http://registry.example.com/pkg/myregistry/docker/myimage/v1.0.0",
},
}
ctx := context.Background()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := p.PackageURL(ctx, tt.regRef, tt.pkgType, tt.params...)
if got != tt.want {
t.Errorf("PackageURL() = %v, want %v", got, tt.want)
}
})
}
}
func TestProvider_GenerateUIRegistryURL(t *testing.T) {
p, err := NewProvider(
"http://internal.example.com",
"http://container.example.com",
"http://api.example.com",
"http://git.example.com",
"ssh://git.example.com:22",
"git",
false,
"http://ui.example.com",
"http://registry.example.com",
)
if err != nil {
t.Fatalf("NewProvider() error = %v", err)
}
tests := []struct {
name string
parentSpacePath string
registryName string
want string
}{
{
name: "valid space path",
parentSpacePath: "myspace",
registryName: "myregistry",
want: "http://ui.example.com/spaces/myspace/registries/myregistry",
},
{
name: "nested space path",
parentSpacePath: "myspace/subspace",
registryName: "myregistry",
want: "http://ui.example.com/spaces/myspace/registries/myregistry",
},
}
ctx := context.Background()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := p.GenerateUIRegistryURL(ctx, tt.parentSpacePath, tt.registryName)
if got != tt.want {
t.Errorf("GenerateUIRegistryURL() = %v, want %v", got, tt.want)
}
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/githook/types.go | app/githook/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package githook
import (
"errors"
"github.com/harness/gitness/types"
)
// Payload defines the payload that's send to git via environment variables.
type Payload struct {
BaseURL string
RepoID int64
PrincipalID int64
RequestID string
Disabled bool
Internal bool // Internal calls originate from Harness, and external calls are direct git pushes.
}
func (p Payload) Validate() error {
// skip further validation if githook is disabled
if p.Disabled {
return nil
}
if p.BaseURL == "" {
return errors.New("payload doesn't contain a base url")
}
if p.PrincipalID <= 0 {
return errors.New("payload doesn't contain a principal id")
}
if p.RepoID <= 0 {
return errors.New("payload doesn't contain a repo id")
}
return nil
}
func GetInputBaseFromPayload(p Payload) types.GithookInputBase {
return types.GithookInputBase{
RepoID: p.RepoID,
PrincipalID: p.PrincipalID,
Internal: p.Internal,
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/githook/client_rest.go | app/githook/client_rest.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package githook
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/git/hook"
"github.com/harness/gitness/types"
"github.com/harness/gitness/version"
)
const (
// HTTPRequestPathPreReceive is the subpath under the provided base url the client uses to call pre-receive.
HTTPRequestPathPreReceive = "pre-receive"
// HTTPRequestPathPostReceive is the subpath under the provided base url the client uses to call post-receive.
HTTPRequestPathPostReceive = "post-receive"
// HTTPRequestPathUpdate is the subpath under the provided base url the client uses to call update.
HTTPRequestPathUpdate = "update"
)
// RestClientFactory creates clients that make rest api calls to Harness to execute githooks.
type RestClientFactory struct{}
func (f *RestClientFactory) NewClient(envVars map[string]string) (hook.Client, error) {
payload, err := hook.LoadPayloadFromMap[Payload](envVars)
if err != nil {
return nil, fmt.Errorf("failed to load payload from provided map of environment variables: %w", err)
}
// ensure we return disabled message in case it's explicitly disabled
if payload.Disabled {
return hook.NewNoopClient([]string{"hook disabled"}), nil
}
if err := payload.Validate(); err != nil {
return nil, fmt.Errorf("payload validation failed: %w", err)
}
return NewRestClient(payload), nil
}
// RestClient is the hook.Client used to call the githooks api of Harness api server.
type RestClient struct {
httpClient *http.Client
baseURL string
requestID string
baseInput types.GithookInputBase
}
func NewRestClient(
payload Payload,
) hook.Client {
return &RestClient{
httpClient: http.DefaultClient,
baseURL: strings.TrimRight(payload.BaseURL, "/"),
requestID: payload.RequestID,
baseInput: GetInputBaseFromPayload(payload),
}
}
// PreReceive calls the pre-receive githook api of the Harness api server.
func (c *RestClient) PreReceive(
ctx context.Context,
in hook.PreReceiveInput,
) (hook.Output, error) {
return c.githook(ctx, HTTPRequestPathPreReceive, types.GithookPreReceiveInput{
GithookInputBase: c.baseInput,
PreReceiveInput: in,
})
}
// Update calls the update githook api of the Harness api server.
func (c *RestClient) Update(
ctx context.Context,
in hook.UpdateInput,
) (hook.Output, error) {
return c.githook(ctx, HTTPRequestPathUpdate, types.GithookUpdateInput{
GithookInputBase: c.baseInput,
UpdateInput: in,
})
}
// PostReceive calls the post-receive githook api of the Harness api server.
func (c *RestClient) PostReceive(
ctx context.Context,
in hook.PostReceiveInput,
) (hook.Output, error) {
return c.githook(ctx, HTTPRequestPathPostReceive, types.GithookPostReceiveInput{
GithookInputBase: c.baseInput,
PostReceiveInput: in,
})
}
// githook executes the requested githook type using the provided input.
func (c *RestClient) githook(ctx context.Context, githookType string, payload any) (hook.Output, error) {
uri := c.baseURL + "/" + githookType
bodyBytes, err := json.Marshal(payload)
if err != nil {
return hook.Output{}, fmt.Errorf("failed to serialize input: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, uri, bytes.NewBuffer(bodyBytes))
if err != nil {
return hook.Output{}, fmt.Errorf("failed to create new http request: %w", err)
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add(request.HeaderUserAgent, fmt.Sprintf("Gitness/%s", version.Version))
req.Header.Add(request.HeaderRequestID, c.requestID)
// Execute the request
resp, err := c.httpClient.Do(req)
// ensure the body is closed after we read (independent of status code or error)
if resp != nil && resp.Body != nil {
// Use function to satisfy the linter which complains about unhandled errors otherwise
defer func() { _ = resp.Body.Close() }()
}
if err != nil {
return hook.Output{}, fmt.Errorf("request execution failed: %w", err)
}
return unmarshalResponse[hook.Output](resp)
}
// unmarshalResponse reads the response body and if there are no errors marshall's it into
// the data struct.
func unmarshalResponse[T any](resp *http.Response) (T, error) {
var body T
if resp == nil {
return body, errors.New("http response is empty")
}
if resp.StatusCode == http.StatusNotFound {
return body, hook.ErrNotFound
}
if resp.StatusCode != http.StatusOK {
return body, fmt.Errorf("expected response code 200 but got: %s", resp.Status)
}
// ensure we actually got a body returned.
if resp.Body == nil {
return body, errors.New("http response body is empty")
}
rawBody, err := io.ReadAll(resp.Body)
if err != nil {
return body, fmt.Errorf("error reading response body : %w", err)
}
err = json.Unmarshal(rawBody, &body)
if err != nil {
return body, fmt.Errorf("error deserializing response body: %w", err)
}
return body, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/githook/env.go | app/githook/env.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package githook
import (
"context"
"fmt"
"strings"
"time"
"github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/git/hook"
"github.com/rs/zerolog/log"
)
var (
// ExecutionTimeout is the timeout used for githook CLI runs.
ExecutionTimeout = 3 * time.Minute
)
// GenerateEnvironmentVariables generates the required environment variables for a payload
// constructed from the provided parameters.
// The parameter `internal` should be true if the call is coming from the Harness
// and therefore protection from rules shouldn't be verified.
func GenerateEnvironmentVariables(
ctx context.Context,
apiBaseURL string,
repoID int64,
principalID int64,
disabled bool,
internal bool,
) (map[string]string, error) {
// best effort retrieving of requestID - log in case we can't find it but don't fail operation.
requestID, ok := request.RequestIDFrom(ctx)
if !ok {
log.Ctx(ctx).Warn().Msg("operation doesn't have a requestID in the context - generate githook payload without")
}
// generate githook base url
baseURL := strings.TrimLeft(apiBaseURL, "/") + "/v1/internal/git-hooks"
payload := Payload{
BaseURL: baseURL,
RepoID: repoID,
PrincipalID: principalID,
RequestID: requestID,
Disabled: disabled,
Internal: internal,
}
if err := payload.Validate(); err != nil {
return nil, fmt.Errorf("generated payload is invalid: %w", err)
}
return hook.GenerateEnvironmentVariables(payload)
}
// LoadFromEnvironment returns a new githook.CLICore created by loading the payload from the environment variable.
func LoadFromEnvironment() (*hook.CLICore, error) {
payload, err := hook.LoadPayloadFromEnvironment[Payload]()
if err != nil {
return nil, fmt.Errorf("failed to load payload from environment: %w", err)
}
// ensure we return disabled error in case it's explicitly disabled (will result in no-op)
if payload.Disabled {
return nil, hook.ErrDisabled
}
if err := payload.Validate(); err != nil {
return nil, fmt.Errorf("payload validation failed: %w", err)
}
return hook.NewCLICore(
NewRestClient(payload),
ExecutionTimeout,
), nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/platformconnector/wire.go | app/gitspace/platformconnector/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package platformconnector
import (
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideGitnessPlatformConnector,
)
func ProvideGitnessPlatformConnector() PlatformConnector {
return NewGitnessPlatformConnector()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/platformconnector/gitnessplatformconnector.go | app/gitspace/platformconnector/gitnessplatformconnector.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package platformconnector
import (
"context"
"github.com/harness/gitness/types"
)
var _ PlatformConnector = (*GitnessPlatformConnector)(nil)
type GitnessPlatformConnector struct{}
func NewGitnessPlatformConnector() *GitnessPlatformConnector {
return &GitnessPlatformConnector{}
}
func (g *GitnessPlatformConnector) FetchConnectors(
_ context.Context,
ids []string,
_ string,
) ([]types.PlatformConnector, error) {
result := make([]types.PlatformConnector, len(ids))
for i, id := range ids {
result[i] = types.PlatformConnector{ID: id}
}
return result, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/platformconnector/platformconnector.go | app/gitspace/platformconnector/platformconnector.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package platformconnector
import (
"context"
"github.com/harness/gitness/types"
)
type PlatformConnector interface {
// FetchConnectors fetches connector details from given list of connector IDs
FetchConnectors(
ctx context.Context,
connectorRefs []string,
currentSpacePath string,
) ([]types.PlatformConnector, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/wire.go | app/gitspace/orchestrator/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package orchestrator
import (
events "github.com/harness/gitness/app/events/gitspace"
"github.com/harness/gitness/app/gitspace/infrastructure"
"github.com/harness/gitness/app/gitspace/orchestrator/container"
"github.com/harness/gitness/app/gitspace/orchestrator/ide"
"github.com/harness/gitness/app/gitspace/platformconnector"
"github.com/harness/gitness/app/gitspace/platformsecret"
"github.com/harness/gitness/app/gitspace/scm"
"github.com/harness/gitness/app/gitspace/secret"
"github.com/harness/gitness/app/services/gitspacesettings"
"github.com/harness/gitness/app/services/infraprovider"
"github.com/harness/gitness/app/store"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideOrchestrator,
)
func ProvideOrchestrator(
scm *scm.SCM,
platformConnector platformconnector.PlatformConnector,
platformSecret platformsecret.PlatformSecret,
infraProvisioner infrastructure.InfraProvisioner,
containerOrchestratorFactor container.Factory,
reporter *events.Reporter,
config *Config,
ideFactory ide.Factory,
secretResolverFactory *secret.ResolverFactory,
gitspaceInstanceStore store.GitspaceInstanceStore,
gitspaceConfigStore store.GitspaceConfigStore,
settingsService gitspacesettings.Service,
spaceStore store.SpaceStore,
infraProviderSvc *infraprovider.Service,
) Orchestrator {
return NewOrchestrator(
scm,
platformConnector,
platformSecret,
infraProvisioner,
containerOrchestratorFactor,
reporter,
config,
ideFactory,
secretResolverFactory,
gitspaceInstanceStore,
gitspaceConfigStore,
settingsService,
spaceStore,
infraProviderSvc,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/orchestrator_resume.go | app/gitspace/orchestrator/orchestrator_resume.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package orchestrator
import (
"context"
"fmt"
"strconv"
"time"
"github.com/harness/gitness/app/gitspace/orchestrator/container/response"
"github.com/harness/gitness/app/gitspace/orchestrator/ide"
"github.com/harness/gitness/app/gitspace/orchestrator/utils"
"github.com/harness/gitness/app/gitspace/scm"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/gotidy/ptr"
"github.com/rs/zerolog/log"
)
// ResumeStartGitspace saves the provisioned infra, resolves the code repo details & creates the Gitspace container.
func (o Orchestrator) ResumeStartGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
provisionedInfra types.Infrastructure,
) (types.GitspaceInstance, *types.GitspaceError) {
gitspaceInstance := gitspaceConfig.GitspaceInstance
gitspaceInstance.State = enum.GitspaceInstanceStateStarting
secretValue, err := utils.ResolveSecret(ctx, o.secretResolverFactory, gitspaceConfig)
if err != nil {
return *gitspaceInstance, newGitspaceError(
fmt.Errorf("cannot resolve secret for ID %s: %w", gitspaceConfig.InfraProviderResource.UID, err),
)
}
gitspaceInstance.AccessKey = secretValue
ideSvc, err := o.ideFactory.GetIDE(gitspaceConfig.IDE)
if err != nil {
return *gitspaceInstance, newGitspaceError(err)
}
err = o.infraProvisioner.PostInfraEventComplete(ctx, gitspaceConfig, provisionedInfra, enum.InfraEventProvision)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraProvisioningFailed)
return *gitspaceInstance, newGitspaceError(
fmt.Errorf("cannot provision infrastructure for ID %s: %w", gitspaceConfig.InfraProviderResource.UID, err),
)
}
if provisionedInfra.Status != enum.InfraStatusProvisioned {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraProvisioningFailed)
infraStateErr := fmt.Errorf(
"infra state is %s, should be %s for gitspace instance identifier %s",
provisionedInfra.Status,
enum.InfraStatusProvisioned,
gitspaceConfig.GitspaceInstance.Identifier,
)
return *gitspaceInstance, newGitspaceError(infraStateErr)
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraProvisioningCompleted)
scmResolvedDetails, err := o.scm.GetSCMRepoDetails(ctx, gitspaceConfig)
if err != nil {
return *gitspaceInstance, newGitspaceError(
fmt.Errorf("failed to fetch code repo details for gitspace config ID %d: %w", gitspaceConfig.ID, err),
)
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentConnectStart)
containerOrchestrator, err := o.containerOrchestratorFactory.GetContainerOrchestrator(provisionedInfra.ProviderType)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentConnectFailed)
return *gitspaceInstance, newGitspaceError(
fmt.Errorf("failed to get the container orchestrator for infra provider type %s: %w",
provisionedInfra.ProviderType, err),
)
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentConnectCompleted)
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentGitspaceCreationStart)
// fetch connector information and send details to gitspace agent
gitspaceSpecs := scmResolvedDetails.DevcontainerConfig.Customizations.ExtractGitspaceSpec()
connectorRefs := getConnectorRefs(gitspaceSpecs)
aiAPIKeySecretRef := getAIAuthRefs(gitspaceSpecs)
gitspaceConfigSettings, err := o.settingsService.GetGitspaceConfigSettings(
ctx,
gitspaceConfig.InfraProviderResource.SpaceID,
&types.ApplyAlwaysToSpaceCriteria,
)
if err != nil {
return *gitspaceInstance, newGitspaceError(
fmt.Errorf("failed to fetch gitspace settings for space ID %d: %w",
gitspaceConfig.InfraProviderResource.SpaceID, err),
)
}
applyDefaultImageIfNeeded(scmResolvedDetails, gitspaceConfigSettings, &connectorRefs)
if len(connectorRefs) > 0 {
connectors, err := o.platformConnector.FetchConnectors(ctx, connectorRefs, gitspaceConfig.SpacePath)
if err != nil {
fetchConnectorErr := fmt.Errorf("failed to fetch connectors for gitspace: %v :%w", connectorRefs, err)
return *gitspaceInstance, newGitspaceError(fetchConnectorErr)
}
gitspaceConfig.Connectors = connectors
}
if aiAPIKeySecretRef != "" {
aiAgentAuth, err := o.decryptAIAuth(ctx, gitspaceConfig.SpacePath, aiAPIKeySecretRef)
if err != nil {
return *gitspaceInstance, newGitspaceError(
fmt.Errorf("failed to decrypt AI agent auth: %w", err),
)
}
gitspaceConfig.AIAuth = aiAgentAuth
}
gitspaceConfig.GitspaceUser.Identifier = harnessUser
err = containerOrchestrator.CreateAndStartGitspace(
ctx, gitspaceConfig, provisionedInfra, *scmResolvedDetails, o.config.DefaultBaseImage, ideSvc)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentGitspaceCreationFailed)
return *gitspaceInstance, newGitspaceError(
fmt.Errorf("couldn't call the agent start API: %w", err),
)
}
return *gitspaceConfig.GitspaceInstance, nil
}
func newGitspaceError(err error) *types.GitspaceError {
return &types.GitspaceError{
Error: err,
ErrorMessage: ptr.String(err.Error()),
}
}
func applyDefaultImageIfNeeded(
scmResolvedDetails *scm.ResolvedDetails,
gitspaceConfigSettings *types.GitspaceConfigSettings,
connectorRefs *[]string,
) {
if gitspaceConfigSettings == nil {
return
}
if scmResolvedDetails.DevcontainerConfig.Image != "" {
return
}
defaultImage := gitspaceConfigSettings.Devcontainer.DevcontainerImage
if len(defaultImage.ImageName) > 0 {
scmResolvedDetails.DevcontainerConfig.Image = defaultImage.ImageName
if len(defaultImage.ImageConnectorRef) > 0 {
*connectorRefs = append(*connectorRefs, defaultImage.ImageConnectorRef)
}
}
}
// FinishResumeStartGitspace needs to be called from the API Handler.
func (o Orchestrator) FinishResumeStartGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
provisionedInfra types.Infrastructure,
startResponse *response.StartResponse,
) (types.GitspaceInstance, *types.GitspaceError) {
gitspaceInstance := gitspaceConfig.GitspaceInstance
if startResponse == nil || startResponse.Status == response.FailureStatus {
gitspaceInstance.State = enum.GitspaceInstanceStateError
err := fmt.Errorf("gitspace agent does not specify the error for failure")
if startResponse != nil && startResponse.ErrMessage != "" {
err = fmt.Errorf("%s", startResponse.ErrMessage)
}
return *gitspaceInstance, &types.GitspaceError{
Error: err,
ErrorMessage: ptr.String(err.Error()),
}
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentGitspaceCreationCompleted)
ideSvc, err := o.ideFactory.GetIDE(gitspaceConfig.IDE)
if err != nil {
return *gitspaceInstance, &types.GitspaceError{
Error: err,
ErrorMessage: ptr.String(err.Error()),
}
}
idePort := o.getIDEPort(provisionedInfra, ideSvc, startResponse)
ideHost := o.getHost(provisionedInfra)
devcontainerUserName := o.getUserName(provisionedInfra, startResponse)
ideURLString := ideSvc.GenerateURL(startResponse.AbsoluteRepoPath, ideHost, idePort, devcontainerUserName)
gitspaceInstance.URL = &ideURLString
sshCommand := generateSSHCommand(startResponse.AbsoluteRepoPath, ideHost, idePort, devcontainerUserName)
gitspaceInstance.SSHCommand = &sshCommand
pluginURLStr := ideSvc.GeneratePluginURL(
getProjectName(provisionedInfra.SpacePath),
provisionedInfra.GitspaceInstanceIdentifier,
)
gitspaceInstance.PluginURL = &pluginURLStr
now := time.Now().UnixMilli()
gitspaceInstance.LastUsed = &now
gitspaceInstance.ActiveTimeStarted = &now
gitspaceInstance.LastHeartbeat = &now
gitspaceInstance.State = enum.GitspaceInstanceStateRunning
if gitspaceConfig.IsMarkedForReset || gitspaceConfig.IsMarkedForInfraReset {
gitspaceConfig.IsMarkedForReset = false
gitspaceConfig.IsMarkedForInfraReset = false
err := o.gitspaceConfigStore.Update(ctx, &gitspaceConfig)
if err != nil {
return *gitspaceInstance, &types.GitspaceError{
Error: err,
ErrorMessage: ptr.String(err.Error()),
}
}
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeGitspaceActionStartCompleted)
return *gitspaceInstance, nil
}
// getIDEPort returns the port used to connect to the IDE.
func (o Orchestrator) getIDEPort(
provisionedInfra types.Infrastructure,
ideSvc ide.IDE,
startResponse *response.StartResponse,
) string {
idePort := ideSvc.Port()
if provisionedInfra.GitspacePortMappings[idePort.Port].PublishedPort == 0 {
return startResponse.PublishedPorts[idePort.Port]
}
return strconv.Itoa(provisionedInfra.GitspacePortMappings[idePort.Port].ForwardedPort)
}
func getProjectName(spacePath string) string {
_, projectName, err := paths.DisectLeaf(spacePath)
if err != nil {
return ""
}
return projectName
}
// getHost returns the host used to connect to the IDE.
func (o Orchestrator) getHost(
provisionedInfra types.Infrastructure,
) string {
if provisionedInfra.ProxyGitspaceHost != "" {
return provisionedInfra.ProxyGitspaceHost
}
return provisionedInfra.GitspaceHost
}
func (o Orchestrator) getUserName(
provisionedInfra types.Infrastructure,
startResponse *response.StartResponse,
) string {
if provisionedInfra.RoutingKey != "" {
return provisionedInfra.RoutingKey
}
return startResponse.RemoteUser
}
func generateSSHCommand(absoluteRepoPath, host, port, user string) string {
return fmt.Sprintf(
// -t flag to ssh to absoluteRepoPath directory
"ssh -t -p %s %s@%s 'cd %s; exec $SHELL -l'",
port,
user,
host,
absoluteRepoPath,
)
}
// ResumeStopGitspace saves the deprovisioned infra details.
func (o Orchestrator) ResumeStopGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
stoppedInfra types.Infrastructure,
) (enum.GitspaceInstanceStateType, *types.GitspaceError) {
instanceState := enum.GitspaceInstanceStateError
err := o.infraProvisioner.PostInfraEventComplete(ctx, gitspaceConfig, stoppedInfra, enum.InfraEventStop)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraStopFailed)
infraStopErr := fmt.Errorf("cannot stop provisioned infrastructure with ID %s: %w",
gitspaceConfig.InfraProviderResource.UID, err)
return instanceState, &types.GitspaceError{
Error: infraStopErr,
ErrorMessage: ptr.String(infraStopErr.Error()), // TODO: Fetch explicit error msg
}
}
if stoppedInfra.Status != enum.InfraStatusDestroyed &&
stoppedInfra.Status != enum.InfraStatusStopped {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraStopFailed)
incorrectInfraStateErr := fmt.Errorf(
"infra state is %v, should be %v for gitspace instance identifier %s",
stoppedInfra.Status,
enum.InfraStatusDestroyed,
gitspaceConfig.GitspaceInstance.Identifier)
return instanceState, &types.GitspaceError{
Error: incorrectInfraStateErr,
ErrorMessage: ptr.String(incorrectInfraStateErr.Error()), // TODO: Fetch explicit error msg
}
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraStopCompleted)
instanceState = enum.GitspaceInstanceStateStopped
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeGitspaceActionStopCompleted)
return instanceState, nil
}
// ResumeDeleteGitspace saves the deprovisioned infra details.
func (o Orchestrator) ResumeDeleteGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
deprovisionedInfra types.Infrastructure,
) (enum.GitspaceInstanceStateType, error) {
instanceState := enum.GitspaceInstanceStateError
err := o.infraProvisioner.PostInfraEventComplete(ctx, gitspaceConfig, deprovisionedInfra, enum.InfraEventDeprovision)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraDeprovisioningFailed)
return instanceState, fmt.Errorf(
"cannot deprovision infrastructure with ID %s: %w", gitspaceConfig.InfraProviderResource.UID, err)
}
if deprovisionedInfra.Status != enum.InfraStatusDestroyed {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraDeprovisioningFailed)
return instanceState, fmt.Errorf(
"infra state is %v, should be %v for gitspace instance identifier %s",
deprovisionedInfra.Status,
enum.InfraStatusDestroyed,
gitspaceConfig.GitspaceInstance.Identifier)
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraDeprovisioningCompleted)
instanceState = enum.GitspaceInstanceStateDeleted
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeGitspaceActionResetCompleted)
return instanceState, nil
}
// ResumeCleanupInstanceResources saves the cleaned up infra details.
func (o Orchestrator) ResumeCleanupInstanceResources(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
cleanedUpInfra types.Infrastructure,
) (enum.GitspaceInstanceStateType, error) {
instanceState := enum.GitspaceInstanceStateError
err := o.infraProvisioner.PostInfraEventComplete(ctx, gitspaceConfig, cleanedUpInfra, enum.InfraEventCleanup)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraCleanupFailed)
return instanceState, fmt.Errorf(
"cannot cleanup provisioned infrastructure with ID %s: %w",
gitspaceConfig.InfraProviderResource.UID,
err,
)
}
if cleanedUpInfra.Status != enum.InfraStatusDestroyed && cleanedUpInfra.Status != enum.InfraStatusStopped {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraCleanupFailed)
return instanceState, fmt.Errorf(
"infra state is %v, should be %v for gitspace instance identifier %s",
cleanedUpInfra.Status,
[]enum.InfraStatus{enum.InfraStatusDestroyed, enum.InfraStatusStopped},
gitspaceConfig.GitspaceInstance.Identifier)
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraCleanupCompleted)
instanceState = enum.GitspaceInstanceStateCleaned
return instanceState, nil
}
func (o Orchestrator) decryptAIAuth(
ctx context.Context,
spacePath, authSecretRef string,
) (map[enum.AIAgent]types.AIAgentAuth, error) {
apiKey, err := o.platformSecret.FetchSecret(ctx, authSecretRef, spacePath)
if err != nil {
return nil, err
}
return map[enum.AIAgent]types.AIAgentAuth{
enum.AIAgentClaudeCode: {
AuthType: enum.AnthropicAPIKeyAuth,
APIKey: types.APIKey{
Value: apiKey,
},
},
}, nil
}
func getConnectorRefs(specs *types.GitspaceCustomizationSpecs) []string {
if specs == nil {
return nil
}
log.Debug().Msgf("Customization connectors: %v", specs.Connectors)
var connectorRefs []string
for _, connector := range specs.Connectors {
connectorRefs = append(connectorRefs, connector.ID)
}
return connectorRefs
}
func getAIAuthRefs(specs *types.GitspaceCustomizationSpecs) string {
if specs == nil || specs.AIAgent == nil {
return ""
}
log.Debug().Msgf("Customization AI Auth: %v", specs.AIAgent)
return specs.AIAgent.SecretRef
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/orchestrator_trigger.go | app/gitspace/orchestrator/orchestrator_trigger.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package orchestrator
import (
"context"
"fmt"
"time"
events "github.com/harness/gitness/app/events/gitspace"
"github.com/harness/gitness/app/gitspace/infrastructure"
"github.com/harness/gitness/app/gitspace/orchestrator/container"
"github.com/harness/gitness/app/gitspace/orchestrator/container/response"
"github.com/harness/gitness/app/gitspace/orchestrator/ide"
"github.com/harness/gitness/app/gitspace/platformconnector"
"github.com/harness/gitness/app/gitspace/platformsecret"
"github.com/harness/gitness/app/gitspace/scm"
"github.com/harness/gitness/app/gitspace/secret"
"github.com/harness/gitness/app/services/gitspacesettings"
"github.com/harness/gitness/app/services/infraprovider"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/gotidy/ptr"
"github.com/rs/zerolog/log"
"golang.org/x/exp/slices"
)
const harnessUser = "harness"
type Config struct {
DefaultBaseImage string
}
type Orchestrator struct {
scm *scm.SCM
platformConnector platformconnector.PlatformConnector
platformSecret platformsecret.PlatformSecret
infraProvisioner infrastructure.InfraProvisioner
containerOrchestratorFactory container.Factory
eventReporter *events.Reporter
config *Config
ideFactory ide.Factory
secretResolverFactory *secret.ResolverFactory
gitspaceInstanceStore store.GitspaceInstanceStore
gitspaceConfigStore store.GitspaceConfigStore
settingsService gitspacesettings.Service
spaceStore store.SpaceStore
infraProviderSvc *infraprovider.Service
}
func NewOrchestrator(
scm *scm.SCM,
platformConnector platformconnector.PlatformConnector,
platformSecret platformsecret.PlatformSecret,
infraProvisioner infrastructure.InfraProvisioner,
containerOrchestratorFactory container.Factory,
eventReporter *events.Reporter,
config *Config,
ideFactory ide.Factory,
secretResolverFactory *secret.ResolverFactory,
gitspaceInstanceStore store.GitspaceInstanceStore,
gitspaceConfigStore store.GitspaceConfigStore,
settingsService gitspacesettings.Service,
spaceStore store.SpaceStore,
infraProviderSvc *infraprovider.Service,
) Orchestrator {
return Orchestrator{
scm: scm,
platformConnector: platformConnector,
platformSecret: platformSecret,
infraProvisioner: infraProvisioner,
containerOrchestratorFactory: containerOrchestratorFactory,
eventReporter: eventReporter,
config: config,
ideFactory: ideFactory,
secretResolverFactory: secretResolverFactory,
gitspaceInstanceStore: gitspaceInstanceStore,
gitspaceConfigStore: gitspaceConfigStore,
settingsService: settingsService,
spaceStore: spaceStore,
infraProviderSvc: infraProviderSvc,
}
}
// TriggerStartGitspace fetches the infra resources configured for the gitspace and triggers the infra provisioning.
func (o Orchestrator) TriggerStartGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
) *types.GitspaceError {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeFetchDevcontainerStart)
scmResolvedDetails, err := o.scm.GetSCMRepoDetails(ctx, gitspaceConfig)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeFetchDevcontainerFailed)
return &types.GitspaceError{
Error: fmt.Errorf("failed to fetch code repo details for gitspace config ID %d: %w",
gitspaceConfig.ID, err),
ErrorMessage: ptr.String(err.Error()),
}
}
devcontainerConfig := scmResolvedDetails.DevcontainerConfig
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeFetchDevcontainerCompleted)
gitspaceSpecs := devcontainerConfig.Customizations.ExtractGitspaceSpec()
connectorRefs := getConnectorRefs(gitspaceSpecs)
validateSettingsErr := o.settingsService.ValidateResolvedSCMDetails(ctx, gitspaceConfig, scmResolvedDetails)
if validateSettingsErr != nil {
return validateSettingsErr
}
if len(connectorRefs) > 0 {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeFetchConnectorsDetailsStart)
connectors, err := o.platformConnector.FetchConnectors(
ctx, connectorRefs, gitspaceConfig.SpacePath)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeFetchConnectorsDetailsFailed)
log.Ctx(ctx).Err(err).Msgf("failed to fetch connectors for gitspace: %v",
connectorRefs,
)
return &types.GitspaceError{
Error: fmt.Errorf("failed to fetch connectors for gitspace: %v :%w",
connectorRefs,
err,
),
ErrorMessage: ptr.String(err.Error()),
}
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeFetchConnectorsDetailsCompleted)
gitspaceConfig.Connectors = connectors
}
requiredGitspacePorts, err := o.getPortsRequiredForGitspace(gitspaceConfig, devcontainerConfig)
if err != nil {
err = fmt.Errorf("cannot get the ports required for gitspace during start: %w", err)
return &types.GitspaceError{
Error: err,
ErrorMessage: ptr.String(err.Error()),
}
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraProvisioningStart)
opts := infrastructure.InfraEventOpts{RequiredGitspacePorts: requiredGitspacePorts}
err = o.infraProvisioner.TriggerInfraEventWithOpts(ctx, enum.InfraEventProvision, gitspaceConfig, nil, opts)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraProvisioningFailed)
return &types.GitspaceError{
Error: fmt.Errorf("cannot trigger provision infrastructure for ID %s: %w",
gitspaceConfig.InfraProviderResource.UID, err),
ErrorMessage: ptr.String(err.Error()), // TODO: Fetch explicit error msg from infra provisioner.
}
}
return nil
}
// TriggerStopGitspace stops the Gitspace container and triggers infra deprovisioning to deprovision
// all the infra resources which are not required to restart the Gitspace.
func (o Orchestrator) TriggerStopGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
) *types.GitspaceError {
infra, err := o.getProvisionedInfra(ctx, gitspaceConfig,
[]enum.InfraStatus{enum.InfraStatusProvisioned, enum.InfraStatusStopped})
if err != nil {
infraNotFoundErr := fmt.Errorf("unable to find provisioned infra while triggering stop for gitspace "+
"instance %s: %w", gitspaceConfig.GitspaceInstance.Identifier, err)
return &types.GitspaceError{
Error: infraNotFoundErr,
ErrorMessage: ptr.String(infraNotFoundErr.Error()), // TODO: Fetch explicit error msg
}
}
if gitspaceConfig.GitspaceInstance.State == enum.GitspaceInstanceStateRunning ||
gitspaceConfig.GitspaceInstance.State == enum.GitspaceInstanceStateStopping {
err = o.stopGitspaceContainer(ctx, gitspaceConfig, *infra)
if err != nil {
return &types.GitspaceError{
Error: err,
ErrorMessage: ptr.String(err.Error()), // TODO: Fetch explicit error msg
}
}
}
return nil
}
func (o Orchestrator) stopGitspaceContainer(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
infra types.Infrastructure,
) error {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentConnectStart)
containerOrchestrator, err := o.containerOrchestratorFactory.GetContainerOrchestrator(infra.ProviderType)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentConnectFailed)
return fmt.Errorf("couldn't get the container orchestrator: %w", err)
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentConnectCompleted)
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentGitspaceStopStart)
// NOTE: Currently we use a static identifier as the Gitspace user.
gitspaceConfig.GitspaceUser.Identifier = harnessUser
err = containerOrchestrator.StopGitspace(ctx, gitspaceConfig, infra)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentGitspaceStopFailed)
return fmt.Errorf("error stopping the Gitspace container: %w", err)
}
return nil
}
func (o Orchestrator) FinishStopGitspaceContainer(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
infra types.Infrastructure,
stopResponse *response.StopResponse,
) *types.GitspaceError {
if stopResponse == nil || stopResponse.Status == response.FailureStatus {
err := fmt.Errorf("gitspace agent does not specify the error for failure")
if stopResponse != nil && stopResponse.ErrMessage != "" {
err = fmt.Errorf("%s", stopResponse.ErrMessage)
}
return &types.GitspaceError{
Error: err,
ErrorMessage: ptr.String(err.Error()),
}
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentGitspaceStopCompleted)
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraStopStart)
err := o.infraProvisioner.TriggerInfraEvent(ctx, enum.InfraEventStop, gitspaceConfig, &infra)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraStopFailed)
infraStopErr := fmt.Errorf("cannot trigger stop infrastructure with ID %s: %w",
gitspaceConfig.InfraProviderResource.UID, err)
return &types.GitspaceError{
Error: infraStopErr,
ErrorMessage: ptr.String(infraStopErr.Error()), // TODO: Fetch explicit error msg
}
}
return nil
}
func (o Orchestrator) removeGitspaceContainer(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
infra types.Infrastructure,
canDeleteUserData bool,
) error {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentConnectStart)
containerOrchestrator, err := o.containerOrchestratorFactory.GetContainerOrchestrator(infra.ProviderType)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentConnectFailed)
return fmt.Errorf("couldn't get the container orchestrator: %w", err)
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentConnectCompleted)
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentGitspaceDeletionStart)
// NOTE: Currently we use a static identifier as the Gitspace user.
gitspaceConfig.GitspaceUser.Identifier = harnessUser
err = containerOrchestrator.RemoveGitspace(ctx, gitspaceConfig, infra, canDeleteUserData)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentGitspaceDeletionFailed)
log.Err(err).Msgf("error stopping the Gitspace container")
}
return nil
}
func (o Orchestrator) FinishRemoveGitspaceContainer(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
infra types.Infrastructure,
deleteResponse *response.DeleteResponse,
) *types.GitspaceError {
if deleteResponse == nil || deleteResponse.Status == response.FailureStatus {
err := fmt.Errorf("gitspace agent does not specify the error for failure")
if deleteResponse != nil && deleteResponse.ErrMessage != "" {
err = fmt.Errorf("%s", deleteResponse.ErrMessage)
}
return &types.GitspaceError{
Error: err,
ErrorMessage: ptr.String(err.Error()),
}
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentGitspaceDeletionCompleted)
if deleteResponse.CanDeleteUserData {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraDeprovisioningStart)
} else {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraResetStart)
}
opts := infrastructure.InfraEventOpts{DeleteUserData: deleteResponse.CanDeleteUserData}
err := o.infraProvisioner.TriggerInfraEventWithOpts(ctx, enum.InfraEventDeprovision, gitspaceConfig, &infra, opts)
if err != nil {
if deleteResponse.CanDeleteUserData {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraDeprovisioningFailed)
} else {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraResetFailed)
}
return &types.GitspaceError{
Error: fmt.Errorf(
"cannot trigger deprovision infrastructure with ID %s: %w",
gitspaceConfig.InfraProviderResource.UID,
err,
),
ErrorMessage: ptr.String(err.Error()),
}
}
return nil
}
// TriggerCleanupInstanceResources cleans up all the resources exclusive to gitspace instance.
func (o Orchestrator) TriggerCleanupInstanceResources(ctx context.Context, gitspaceConfig types.GitspaceConfig) error {
infra, err := o.getProvisionedInfra(ctx, gitspaceConfig,
[]enum.InfraStatus{
enum.InfraStatusProvisioned,
enum.InfraStatusStopped,
enum.InfraStatusPending,
enum.InfraStatusUnknown,
enum.InfraStatusDestroyed,
})
if err != nil {
return fmt.Errorf(
"unable to find provisioned infra while triggering cleanup for gitspace instance %s: %w",
gitspaceConfig.GitspaceInstance.Identifier, err)
}
if gitspaceConfig.GitspaceInstance.State != enum.GitSpaceInstanceStateCleaning {
return fmt.Errorf("cannot trigger cleanup, expected state: %s, actual state: %s ",
enum.GitSpaceInstanceStateCleaning,
gitspaceConfig.GitspaceInstance.State,
)
}
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraCleanupStart)
err = o.infraProvisioner.TriggerInfraEvent(ctx, enum.InfraEventCleanup, gitspaceConfig, infra)
if err != nil {
return fmt.Errorf("cannot trigger cleanup infrastructure with ID %s: %w",
gitspaceConfig.InfraProviderResource.UID,
err,
)
}
return nil
}
// TriggerDeleteGitspace removes the Gitspace container and triggers infra deprovisioning to deprovision
// the infra resources.
// canDeleteUserData = false -> trigger deprovision of all resources except storage associated to user data.
// canDeleteUserData = true -> trigger deprovision of all resources.
func (o Orchestrator) TriggerDeleteGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
canDeleteUserData bool,
) *types.GitspaceError {
infra, err := o.getProvisionedInfra(ctx, gitspaceConfig,
[]enum.InfraStatus{
enum.InfraStatusPending,
enum.InfraStatusProvisioned,
enum.InfraStatusStopped,
enum.InfraStatusDestroyed,
enum.InfraStatusError,
enum.InfraStatusUnknown,
})
if err != nil {
err := fmt.Errorf(
"unable to find provisioned infra while triggering delete for gitspace instance %s: %w",
gitspaceConfig.GitspaceInstance.Identifier, err)
return &types.GitspaceError{
Error: err,
ErrorMessage: ptr.String(err.Error()),
}
}
if infra.ProviderType == enum.InfraProviderTypeDocker {
if err = o.removeGitspaceContainer(ctx, gitspaceConfig, *infra, canDeleteUserData); err != nil {
return &types.GitspaceError{
Error: err,
ErrorMessage: ptr.String(err.Error()),
}
}
}
if err := o.triggerDeleteGitspace(ctx, gitspaceConfig, infra, canDeleteUserData); err != nil {
return &types.GitspaceError{
Error: err,
ErrorMessage: ptr.String(err.Error()),
}
}
return nil
}
func (o Orchestrator) triggerDeleteGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
infra *types.Infrastructure,
canDeleteUserData bool,
) error {
opts := infrastructure.InfraEventOpts{DeleteUserData: canDeleteUserData}
err := o.infraProvisioner.TriggerInfraEventWithOpts(
ctx,
enum.InfraEventDeprovision,
gitspaceConfig,
infra,
opts,
)
if err != nil {
if canDeleteUserData {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraDeprovisioningFailed)
} else {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeInfraResetFailed)
}
return fmt.Errorf(
"cannot trigger deprovision infrastructure with gitspace identifier %s: %w",
gitspaceConfig.GitspaceInstance.Identifier,
err,
)
}
return nil
}
func (o Orchestrator) emitGitspaceEvent(
ctx context.Context,
config types.GitspaceConfig,
eventType enum.GitspaceEventType,
) {
o.eventReporter.EmitGitspaceEvent(
ctx,
events.GitspaceEvent,
&events.GitspaceEventPayload{
QueryKey: config.Identifier,
EntityID: config.GitspaceInstance.ID,
EntityType: enum.GitspaceEntityTypeGitspaceInstance,
EventType: eventType,
Timestamp: time.Now().UnixNano(),
})
}
func (o Orchestrator) getPortsRequiredForGitspace(
gitspaceConfig types.GitspaceConfig,
devcontainerConfig types.DevcontainerConfig,
) ([]types.GitspacePort, error) {
// TODO: What if the required ports in the config have deviated from when the last instance was created?
resolvedIDE, err := o.ideFactory.GetIDE(gitspaceConfig.IDE)
if err != nil {
return nil, fmt.Errorf("unable to get IDE service while checking required Gitspace ports: %w", err)
}
idePort := resolvedIDE.Port()
gitspacePorts := []types.GitspacePort{*idePort}
forwardPorts := container.ExtractForwardPorts(devcontainerConfig)
for _, port := range forwardPorts {
gitspacePorts = append(gitspacePorts, types.GitspacePort{
Port: port,
Protocol: enum.CommunicationProtocolHTTP,
})
}
return gitspacePorts, nil
}
// GetGitspaceLogs fetches gitspace's start/stop logs.
func (o Orchestrator) GetGitspaceLogs(ctx context.Context, gitspaceConfig types.GitspaceConfig) (string, error) {
if gitspaceConfig.GitspaceInstance == nil {
return "", fmt.Errorf("gitspace %s is not setup yet, please try later", gitspaceConfig.Identifier)
}
infra, err := o.getProvisionedInfra(ctx, gitspaceConfig, []enum.InfraStatus{enum.InfraStatusProvisioned})
if err != nil {
return "", fmt.Errorf(
"unable to find provisioned infra while fetching logs for gitspace instance %s: %w",
gitspaceConfig.GitspaceInstance.Identifier, err)
}
containerOrchestrator, err := o.containerOrchestratorFactory.GetContainerOrchestrator(infra.ProviderType)
if err != nil {
return "", fmt.Errorf("couldn't get the container orchestrator: %w", err)
}
// NOTE: Currently we use a static identifier as the Gitspace user.
gitspaceConfig.GitspaceUser.Identifier = harnessUser
logs, err := containerOrchestrator.StreamLogs(ctx, gitspaceConfig, *infra)
if err != nil {
return "", fmt.Errorf("error while fetching logs from container orchestrator: %w", err)
}
return logs, nil
}
func (o Orchestrator) getProvisionedInfra(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
expectedStatus []enum.InfraStatus,
) (*types.Infrastructure, error) {
infra, err := o.infraProvisioner.Find(ctx, gitspaceConfig)
if err != nil {
return nil, fmt.Errorf("cannot find the provisioned infra: %w", err)
}
if !slices.Contains(expectedStatus, infra.Status) {
return nil, fmt.Errorf("expected infra state in %v, actual state is: %s", expectedStatus, infra.Status)
}
if infra.Storage == "" {
log.Warn().Msgf("couldn't find the storage for resource ID %s", gitspaceConfig.InfraProviderResource.UID)
}
return infra, nil
}
// TriggerAITask triggers ai task by sending the details to gitspace agent.
func (o Orchestrator) TriggerAITask(
ctx context.Context,
aiTask types.AITask,
gitspaceConfig types.GitspaceConfig,
) error {
infra, err := o.getProvisionedInfra(ctx, gitspaceConfig,
[]enum.InfraStatus{enum.InfraStatusProvisioned})
if err != nil {
return fmt.Errorf("cannot find the provisioned infra: %w", err)
}
containerOrchestrator, err := o.containerOrchestratorFactory.GetContainerOrchestrator(infra.ProviderType)
if err != nil {
o.emitGitspaceEvent(ctx, gitspaceConfig, enum.GitspaceEventTypeAgentConnectFailed)
return fmt.Errorf("couldn't get the container orchestrator: %w", err)
}
return containerOrchestrator.StartAITask(ctx, gitspaceConfig, *infra, aiTask)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/runarg_utils.go | app/gitspace/orchestrator/container/runarg_utils.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package container
import (
"fmt"
"math/big"
"strconv"
"strings"
"time"
"github.com/harness/gitness/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/strslice"
"github.com/docker/go-units"
"github.com/rs/zerolog/log"
)
func getHostResources(runArgsMap map[types.RunArg]*types.RunArgValue) (container.Resources, error) { // nolint: gocognit
var resources = container.Resources{}
blkioWeight, err := getArgValueUint16(runArgsMap, types.RunArgBlkioWeight)
if err != nil {
return resources, err
}
resources.BlkioWeight = blkioWeight
cpuShares, err := getArgValueInt64(runArgsMap, types.RunArgCPUShares)
if err != nil {
return resources, err
}
resources.CPUShares = cpuShares
memory, err := getArgValueMemoryBytes(runArgsMap, types.RunArgMemory)
if err != nil {
return resources, err
}
resources.Memory = memory
cpus, err := getCPUs(runArgsMap, types.RunArgCpus)
if err != nil {
return resources, err
}
resources.NanoCPUs = cpus
resources.CgroupParent = getArgValueString(runArgsMap, types.RunArgCgroupParent)
cpuPeriod, err := getArgValueInt64(runArgsMap, types.RunArgCPUPeriod)
if err != nil {
return resources, err
}
resources.CPUPeriod = cpuPeriod
cpuQuota, err := getArgValueInt64(runArgsMap, types.RunArgCPUQuota)
if err != nil {
return resources, err
}
resources.CPUQuota = cpuQuota
cpuRTPeriod, err := getArgValueInt64(runArgsMap, types.RunArgCPURtPeriod)
if err != nil {
return resources, err
}
resources.CPURealtimePeriod = cpuRTPeriod
cpuRTRuntime, err := getArgValueInt64(runArgsMap, types.RunArgCPURtRuntime)
if err != nil {
return resources, err
}
resources.CPURealtimeRuntime = cpuRTRuntime
resources.CpusetCpus = getArgValueString(runArgsMap, types.RunArgCpusetCpus)
resources.CpusetMems = getArgValueString(runArgsMap, types.RunArgCpusetMems)
cpuCount, err := getArgValueInt64(runArgsMap, types.RunArgCPUCount)
if err != nil {
return resources, err
}
resources.CPUCount = cpuCount
cpuPercent, err := getArgValueInt64(runArgsMap, types.RunArgCPUPercent)
if err != nil {
return resources, err
}
resources.CPUPercent = cpuPercent
kernelMemory, err := getArgValueMemoryBytes(runArgsMap, types.RunArgKernelMemory)
if err != nil {
return resources, err
}
resources.KernelMemory = kernelMemory
memoryReservation, err := getArgValueMemoryBytes(runArgsMap, types.RunArgMemoryReservation)
if err != nil {
return resources, err
}
resources.MemoryReservation = memoryReservation
memorySwappiness, err := getArgValueInt64Ptr(runArgsMap, types.RunArgMemorySwappiness)
if err != nil {
return resources, err
}
resources.MemorySwappiness = memorySwappiness
memorySwap, err := getArgValueMemorySwapBytes(runArgsMap, types.RunArgMemorySwap)
if err != nil {
return resources, err
}
resources.MemorySwap = memorySwap
resources.OomKillDisable = getArgValueBoolPtr(runArgsMap, types.RunArgOomKillDisable)
pidsLimit, err := getArgValueInt64Ptr(runArgsMap, types.RunArgPidsLimit)
if err != nil {
return resources, err
}
resources.PidsLimit = pidsLimit
ioMaxiops, err := getArgValueUint64(runArgsMap, types.RunArgIoMaxiops)
if err != nil {
return resources, err
}
resources.IOMaximumIOps = ioMaxiops
ioMaxbandwidth, err := getArgValueMemoryBytes(runArgsMap, types.RunArgIoMaxbandwidth)
if err != nil {
return resources, err
}
resources.IOMaximumBandwidth = uint64(ioMaxbandwidth) //nolint:gosec
if arg, ok := runArgsMap[types.RunArgUlimit]; ok {
ulimits := []*container.Ulimit{}
for _, v := range arg.Values {
ulimit, err := units.ParseUlimit(v)
if err != nil {
return resources, err
}
ulimits = append(ulimits, ulimit)
}
resources.Ulimits = ulimits
}
return resources, nil
}
func getNetworkMode(runArgsMap map[types.RunArg]*types.RunArgValue) container.NetworkMode {
return container.NetworkMode(getArgValueString(runArgsMap, types.RunArgNetwork))
}
func getCapAdd(runArgsMap map[types.RunArg]*types.RunArgValue) strslice.StrSlice {
return getArgValueStringSlice(runArgsMap, types.RunArgCapAdd)
}
func getCapDrop(runArgsMap map[types.RunArg]*types.RunArgValue) strslice.StrSlice {
return getArgValueStringSlice(runArgsMap, types.RunArgCapDrop)
}
func getSHMSize(runArgsMap map[types.RunArg]*types.RunArgValue) (int64, error) {
return getArgValueMemoryBytes(runArgsMap, types.RunArgShmSize)
}
func getArgValueMemorySwapBytes(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) (int64, error) {
value := getArgValueString(runArgsMap, argName)
if value == "" {
return 0, nil
}
if value == "-1" {
return -1, nil
}
memorySwapBytes, err := units.RAMInBytes(value)
if err != nil {
return 0, err
}
return memorySwapBytes, nil
}
func getSysctls(runArgsMap map[types.RunArg]*types.RunArgValue) map[string]string {
values := getArgValueStringSlice(runArgsMap, types.RunArgSysctl)
var opt = map[string]string{}
for _, value := range values {
parts := strings.SplitN(value, "=", 2)
if len(parts) != 2 {
parts = append(parts, "")
}
opt[parts[0]] = parts[1]
}
return opt
}
func getDNS(runArgsMap map[types.RunArg]*types.RunArgValue) []string {
return getArgValueStringSlice(runArgsMap, types.RunArgDNS)
}
func getDNSOptions(runArgsMap map[types.RunArg]*types.RunArgValue) []string {
return getArgValueStringSlice(runArgsMap, types.RunArgDNSOption)
}
func getDNSSearch(runArgsMap map[types.RunArg]*types.RunArgValue) []string {
return getArgValueStringSlice(runArgsMap, types.RunArgDNSSearch)
}
func getCgroupNSMode(runArgsMap map[types.RunArg]*types.RunArgValue) container.CgroupnsMode {
value := getArgValueString(runArgsMap, types.RunArgCgroupns)
return container.CgroupnsMode(value)
}
func getIPCMode(runArgsMap map[types.RunArg]*types.RunArgValue) container.IpcMode {
return container.IpcMode(getArgValueString(runArgsMap, types.RunArgIpc))
}
func getIsolation(runArgsMap map[types.RunArg]*types.RunArgValue) container.Isolation {
return container.Isolation(getArgValueString(runArgsMap, types.RunArgIsolation))
}
func getRuntime(runArgsMap map[types.RunArg]*types.RunArgValue) string {
return getArgValueString(runArgsMap, types.RunArgRuntime)
}
func getPlatform(runArgsMap map[types.RunArg]*types.RunArgValue) string {
return getArgValueString(runArgsMap, types.RunArgPlatform)
}
func getPIDMode(runArgsMap map[types.RunArg]*types.RunArgValue) container.PidMode {
return container.PidMode(getArgValueString(runArgsMap, types.RunArgPid))
}
func getSecurityOpt(runArgsMap map[types.RunArg]*types.RunArgValue) []string {
return getArgValueStringSlice(runArgsMap, types.RunArgSecurityOpt)
}
func getStorageOpt(runArgsMap map[types.RunArg]*types.RunArgValue) map[string]string {
values := getArgValueStringSlice(runArgsMap, types.RunArgStorageOpt)
var opt = map[string]string{}
for _, value := range values {
parts := strings.SplitN(value, "=", 2)
if len(parts) != 2 {
parts = append(parts, "")
}
opt[parts[0]] = parts[1]
}
return opt
}
func getAutoRemove(runArgsMap map[types.RunArg]*types.RunArgValue) bool {
return getArgValueBool(runArgsMap, types.RunArgRm)
}
func getPrivileged(runArgsMap map[types.RunArg]*types.RunArgValue) *bool {
return getArgValueBoolPtr(runArgsMap, types.RunArgPrivileged)
}
func getInit(runArgsMap map[types.RunArg]*types.RunArgValue) *bool {
return getArgValueBoolPtr(runArgsMap, types.RunArgInit)
}
func getEnv(runArgsMap map[types.RunArg]*types.RunArgValue) []string {
return getArgValueStringSlice(runArgsMap, types.RunArgEnv)
}
func getLinks(runArgsMap map[types.RunArg]*types.RunArgValue) []string {
return getArgValueStringSlice(runArgsMap, types.RunArgLink)
}
func getOomScoreAdj(runArgsMap map[types.RunArg]*types.RunArgValue) (int, error) {
return getArgValueInt(runArgsMap, types.RunArgOomScoreAdj)
}
func getRestartPolicy(runArgsMap map[types.RunArg]*types.RunArgValue) (container.RestartPolicy, error) {
value := getArgValueString(runArgsMap, types.RunArgRestart)
if len(value) == 0 {
return container.RestartPolicy{}, nil
}
parts := strings.SplitN(value, ":", 2)
maxCount := 0
if container.RestartPolicyMode(parts[0]) == container.RestartPolicyOnFailure && len(parts) == 2 {
count, err := strconv.Atoi(parts[1])
if err != nil {
return container.RestartPolicy{}, err
}
maxCount = count
}
return container.RestartPolicy{
Name: container.RestartPolicyMode(parts[0]),
MaximumRetryCount: maxCount,
}, nil
}
func getExtraHosts(runArgsMap map[types.RunArg]*types.RunArgValue) []string {
return getArgValueStringSlice(runArgsMap, types.RunArgAddHost)
}
func getHostname(runArgsMap map[types.RunArg]*types.RunArgValue) string {
return getArgValueString(runArgsMap, types.RunArgHostname)
}
func getDomainname(runArgsMap map[types.RunArg]*types.RunArgValue) string {
return getArgValueString(runArgsMap, types.RunArgDomainname)
}
func getMACAddress(runArgsMap map[types.RunArg]*types.RunArgValue) string {
return getArgValueString(runArgsMap, types.RunArgMacAddress)
}
func getStopSignal(runArgsMap map[types.RunArg]*types.RunArgValue) string {
return getArgValueString(runArgsMap, types.RunArgStopSignal)
}
func getStopTimeout(runArgsMap map[types.RunArg]*types.RunArgValue) (*int, error) {
return getArgValueIntPtr(runArgsMap, types.RunArgStopTimeout)
}
func getImagePullPolicy(runArgsMap map[types.RunArg]*types.RunArgValue) string {
policy := getArgValueString(runArgsMap, types.RunArgPull)
if policy == "" {
policy = "missing"
}
return policy
}
func getUser(runArgsMap map[types.RunArg]*types.RunArgValue) string {
return getArgValueString(runArgsMap, types.RunArgUser)
}
func getEntrypoint(runArgsMap map[types.RunArg]*types.RunArgValue) []string {
return getArgValueStringSlice(runArgsMap, types.RunArgEntrypoint)
}
func getMounts(runArgsMap map[types.RunArg]*types.RunArgValue) ([]*types.Mount, error) {
rawMounts, ok := runArgsMap[types.RunArgMount]
var mounts []*types.Mount
if ok {
parsedMounts, err := types.ParseMountsFromStringSlice(rawMounts.Values)
if err != nil {
return nil, err
}
return parsedMounts, nil
}
return mounts, nil
}
func getHealthCheckConfig(runArgsMap map[types.RunArg]*types.RunArgValue) (*container.HealthConfig, error) {
var healthConfig = &container.HealthConfig{}
retries, err := getArgValueInt(runArgsMap, types.RunArgHealthRetries)
if err != nil {
return healthConfig, err
}
healthConfig.Retries = retries
interval, err := getArgValueDuration(runArgsMap, types.RunArgHealthInterval)
if err != nil {
return healthConfig, err
}
healthConfig.Interval = interval
timeout, err := getArgValueDuration(runArgsMap, types.RunArgHealthTimeout)
if err != nil {
return healthConfig, err
}
healthConfig.Timeout = timeout
startPeriod, err := getArgValueDuration(runArgsMap, types.RunArgHealthStartPeriod)
if err != nil {
return healthConfig, err
}
healthConfig.StartPeriod = startPeriod
startInterval, err := getArgValueDuration(runArgsMap, types.RunArgHealthStartInterval)
if err != nil {
return healthConfig, err
}
healthConfig.StartInterval = startInterval
if _, ok := runArgsMap[types.RunArgNoHealthcheck]; ok {
healthConfig.Test = []string{"NONE"}
} else if arg, healthCmdOK := runArgsMap[types.RunArgHealthCmd]; healthCmdOK {
healthConfig.Test = arg.Values
}
return healthConfig, nil
}
func getLabels(runArgsMap map[types.RunArg]*types.RunArgValue) map[string]string {
labelsMap := make(map[string]string)
arg, ok := runArgsMap[types.RunArgLabel]
if ok {
labels := arg.Values
for _, v := range labels {
parts := strings.SplitN(v, "=", 2)
if len(parts) < 2 {
labelsMap[parts[0]] = ""
} else {
labelsMap[parts[0]] = parts[1]
}
}
}
return labelsMap
}
func getAnnotations(runArgsMap map[types.RunArg]*types.RunArgValue) map[string]string {
arg, ok := runArgsMap[types.RunArgAnnotation]
annotationsMap := make(map[string]string)
if ok {
annotations := arg.Values
for _, v := range annotations {
annotationParts := strings.SplitN(v, "=", 2)
if len(annotationParts) != 2 {
log.Warn().Msgf("invalid annotation: %s", v)
} else {
annotationsMap[annotationParts[0]] = annotationParts[1]
}
}
}
return annotationsMap
}
func getArgValueMemoryBytes(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) (int64, error) {
value := getArgValueString(runArgsMap, argName)
if value == "" {
return 0, nil
}
memoryBytes, err := units.RAMInBytes(value)
if err != nil {
return 0, err
}
return memoryBytes, nil
}
func getArgValueString(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) string {
if arg, ok := runArgsMap[argName]; ok {
return arg.Values[0]
}
return ""
}
func getArgValueStringSlice(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) []string {
if arg, ok := runArgsMap[argName]; ok {
return arg.Values
}
return []string{}
}
func getArgValueInt(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) (int, error) {
value, err := getArgValueIntPtr(runArgsMap, argName)
if err != nil {
return 0, err
}
if value == nil {
return 0, nil
}
return *value, nil
}
func getArgValueIntPtr(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) (*int, error) {
if arg, ok := runArgsMap[argName]; ok {
value, err := strconv.Atoi(arg.Values[0])
if err != nil {
return nil, err
}
return &value, nil
}
return nil, nil // nolint: nilnil
}
func getArgValueUint16(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) (uint16, error) {
if arg, ok := runArgsMap[argName]; ok {
value, err := strconv.ParseUint(arg.Values[0], 10, 16)
if err != nil {
return 0, err
}
return uint16(value), nil
}
return 0, nil
}
func getArgValueUint64(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) (uint64, error) {
if arg, ok := runArgsMap[argName]; ok {
value, err := strconv.ParseUint(arg.Values[0], 10, 64)
if err != nil {
return 0, err
}
return value, nil
}
return 0, nil
}
func getCPUs(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) (int64, error) {
if arg, ok := runArgsMap[argName]; ok {
value := arg.Values[0]
cpu, ok1 := new(big.Rat).SetString(value) // nolint: gosec
if !ok1 {
return 0, fmt.Errorf("failed to parse %v as a rational number", value)
}
nano := cpu.Mul(cpu, big.NewRat(1e9, 1))
if !nano.IsInt() {
return 0, fmt.Errorf("value is too precise")
}
return nano.Num().Int64(), nil
}
return 0, nil
}
func getArgValueInt64(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) (int64, error) {
value, err := getArgValueInt64Ptr(runArgsMap, argName)
if err != nil {
return 0, err
}
if value == nil {
return 0, nil
}
return *value, nil
}
func getArgValueInt64Ptr(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) (*int64, error) {
if arg, ok := runArgsMap[argName]; ok {
value, err := strconv.ParseInt(arg.Values[0], 10, 64)
if err != nil {
return nil, err
}
return &value, nil
}
return nil, nil // nolint: nilnil
}
func getArgValueDuration(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) (time.Duration, error) {
defaultDur := time.Second * 0
if arg, ok := runArgsMap[argName]; ok {
dur, err := time.ParseDuration(arg.Values[0])
if err != nil {
return defaultDur, err
}
return dur, nil
}
return defaultDur, nil
}
func getArgValueBool(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) bool {
value := getArgValueBoolPtr(runArgsMap, argName)
if value == nil {
return false
}
return *value
}
func getArgValueBoolPtr(runArgsMap map[types.RunArg]*types.RunArgValue, argName types.RunArg) *bool {
_, ok := runArgsMap[argName]
if ok {
return &ok
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/wire.go | app/gitspace/orchestrator/container/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package container
import (
events "github.com/harness/gitness/app/events/gitspaceoperations"
"github.com/harness/gitness/app/gitspace/logutil"
"github.com/harness/gitness/app/gitspace/orchestrator/runarg"
"github.com/harness/gitness/infraprovider"
"github.com/google/wire"
)
var WireSet = wire.NewSet(
ProvideEmbeddedDockerOrchestrator,
ProvideContainerOrchestratorFactory,
)
func ProvideEmbeddedDockerOrchestrator(
dockerClientFactory *infraprovider.DockerClientFactory,
statefulLogger *logutil.StatefulLogger,
runArgProvider runarg.Provider,
eventReporter *events.Reporter,
) EmbeddedDockerOrchestrator {
return NewEmbeddedDockerOrchestrator(
dockerClientFactory,
statefulLogger,
runArgProvider,
eventReporter,
)
}
func ProvideContainerOrchestratorFactory(
embeddedDockerOrchestrator EmbeddedDockerOrchestrator,
) Factory {
return NewFactory(embeddedDockerOrchestrator)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/types.go | app/gitspace/orchestrator/container/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package container
type PostAction string
const (
PostCreateAction PostAction = "post-create"
PostStartAction PostAction = "post-start"
)
type State string
const (
ContainerStateRunning = State("running")
ContainerStateRemoved = State("removed")
ContainerStateDead = State("dead")
ContainerStateStopped = State("exited")
ContainerStatePaused = State("paused")
ContainerStateUnknown = State("unknown")
ContainerStateCreated = State("created")
)
type Action string
const (
ContainerActionStop = Action("stop")
ContainerActionStart = Action("start")
ContainerActionRemove = Action("remove")
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/orchestrator_factory.go | app/gitspace/orchestrator/container/orchestrator_factory.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package container
import (
"fmt"
"github.com/harness/gitness/types/enum"
)
type Factory interface {
GetContainerOrchestrator(providerType enum.InfraProviderType) (Orchestrator, error)
}
type factory struct {
containerOrchestrators map[enum.InfraProviderType]Orchestrator
}
func NewFactory(embeddedDockerOrchestrator EmbeddedDockerOrchestrator) Factory {
containerOrchestrators := make(map[enum.InfraProviderType]Orchestrator)
containerOrchestrators[enum.InfraProviderTypeDocker] = &embeddedDockerOrchestrator
return &factory{containerOrchestrators: containerOrchestrators}
}
func (f *factory) GetContainerOrchestrator(infraProviderType enum.InfraProviderType) (Orchestrator, error) {
val, exist := f.containerOrchestrators[infraProviderType]
if !exist {
return nil, fmt.Errorf("unsupported infra provider type: %s", infraProviderType)
}
return val, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/util.go | app/gitspace/orchestrator/container/util.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package container
import (
"context"
"encoding/json"
"fmt"
"io"
"path/filepath"
"sync"
"github.com/harness/gitness/app/gitspace/orchestrator/container/response"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
gitspaceTypes "github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/types"
dockerTypes "github.com/docker/docker/api/types"
"github.com/rs/zerolog/log"
)
const (
linuxHome = "/home"
deprecatedRemoteUser = "harness"
gitspaceRemoteUserLabel = "gitspace.remote.user"
gitspaceLifeCycleHooksLabel = "gitspace.lifecycle.hooks"
)
func GetGitspaceContainerName(config types.GitspaceConfig) string {
return "gitspace-" + config.GitspaceUser.Identifier + "-" + config.Identifier
}
func GetUserHomeDir(userIdentifier string) string {
if userIdentifier == "root" {
return "/root"
}
return filepath.Join(linuxHome, userIdentifier)
}
func GetContainerUser(
runArgsMap map[types.RunArg]*types.RunArgValue,
devcontainerConfig types.DevcontainerConfig,
metadataFromImage map[string]any,
imageUser string,
) string {
if containerUser := getUser(runArgsMap); containerUser != "" {
return containerUser
}
if devcontainerConfig.ContainerUser != "" {
return devcontainerConfig.ContainerUser
}
if containerUser, ok := metadataFromImage["containerUser"].(string); ok {
return containerUser
}
return imageUser
}
func GetRemoteUser(
devcontainerConfig types.DevcontainerConfig,
metadataFromImage map[string]any,
containerUser string,
) string {
if devcontainerConfig.RemoteUser != "" {
return devcontainerConfig.RemoteUser
}
if remoteUser, ok := metadataFromImage["remoteUser"].(string); ok {
return remoteUser
}
return containerUser
}
func ExtractRemoteUserFromLabels(inspectResp dockerTypes.ContainerJSON) string {
remoteUser := deprecatedRemoteUser
if remoteUserValue, ok := inspectResp.Config.Labels[gitspaceRemoteUserLabel]; ok {
remoteUser = remoteUserValue
}
return remoteUser
}
func ExtractLifecycleHooksFromLabels(
inspectResp dockerTypes.ContainerJSON,
) (map[PostAction][]*LifecycleHookStep, error) {
var lifecycleHooks = make(map[PostAction][]*LifecycleHookStep)
if lifecycleHooksStr, ok := inspectResp.Config.Labels[gitspaceLifeCycleHooksLabel]; ok {
err := json.Unmarshal([]byte(lifecycleHooksStr), &lifecycleHooks)
if err != nil {
return nil, err
}
}
return lifecycleHooks, nil
}
// ExecuteLifecycleCommands executes commands in parallel, logs with numbers, and prefixes all logs.
func ExecuteLifecycleCommands(
ctx context.Context,
exec devcontainer.Exec,
codeRepoDir string,
gitspaceLogger gitspaceTypes.GitspaceLogger,
commands []string,
actionType PostAction,
) error {
if len(commands) == 0 {
gitspaceLogger.Info(fmt.Sprintf("No %s commands provided, skipping execution", actionType))
return nil
}
gitspaceLogger.Info(fmt.Sprintf("Executing %s commands: %v", actionType, commands))
// Create a WaitGroup to wait for all goroutines to finish.
var wg sync.WaitGroup
// Iterate over commands and execute them in parallel using goroutines.
for index, command := range commands {
// Increment the WaitGroup counter.
wg.Add(1)
// Execute each command in a new goroutine.
go func(index int, command string) {
// Decrement the WaitGroup counter when the goroutine finishes.
defer wg.Done()
// Number the command in the logs and prefix all logs.
commandNumber := index + 1 // Starting from 1 for numbering
logPrefix := fmt.Sprintf("Command #%d - ", commandNumber)
// Log command execution details.
gitspaceLogger.Info(fmt.Sprintf("%sExecuting %s command: %s", logPrefix, actionType, command))
exec.DefaultWorkingDir = codeRepoDir
err := exec.ExecuteCommandInHomeDirAndLog(ctx, command, false, gitspaceLogger, true)
if err != nil {
// Log the error if there is any issue with executing the command.
_ = logStreamWrapError(gitspaceLogger, fmt.Sprintf("%sError while executing %s command: %s",
logPrefix, actionType, command), err)
return
}
// Log completion of the command execution.
gitspaceLogger.Info(fmt.Sprintf(
"%sCompleted execution %s command: %s", logPrefix, actionType, command))
}(index, command)
}
// Wait for all goroutines to finish.
wg.Wait()
return nil
}
func ProcessStartResponse(
ctx context.Context,
config types.GitspaceConfig,
resp io.ReadCloser,
) (*response.StartResponse, error) {
var err error
defer func() {
err = resp.Close()
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msgf(
"failed to close response after starting gitspace %s", config.Identifier)
}
}()
bodyBytes, _ := io.ReadAll(resp)
responseBody := string(bodyBytes)
log.Debug().Msgf("response from %s %s", config.GitspaceInstance.Identifier, responseBody)
var startResponse response.StartResponse
err = json.Unmarshal(bodyBytes, &startResponse)
if err != nil {
return nil, fmt.Errorf("error unmarshalling start response for gitspace instance %s: %w",
config.GitspaceInstance.Identifier, err)
}
return &startResponse, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/container_orchestrator.go | app/gitspace/orchestrator/container/container_orchestrator.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package container
import (
"context"
"github.com/harness/gitness/app/gitspace/orchestrator/ide"
"github.com/harness/gitness/app/gitspace/scm"
"github.com/harness/gitness/types"
)
type Orchestrator interface {
// CreateAndStartGitspace starts an exited container and starts a new container if the container is removed.
// If the container is newly created, it clones the code, sets up the IDE and executes the postCreateCommand.
// It returns the container ID, name and ports used.
CreateAndStartGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
infra types.Infrastructure,
resolvedDetails scm.ResolvedDetails,
defaultBaseImage string,
ideService ide.IDE,
) error
// RetryCreateAndStartGitspaceIfRequired will handle the delegate task response and retry if status code is > 202
RetryCreateAndStartGitspaceIfRequired(ctx context.Context)
// StopGitspace stops the gitspace container.
StopGitspace(ctx context.Context, config types.GitspaceConfig, infra types.Infrastructure) error
// RemoveGitspace force removes the gitspace container.
RemoveGitspace(
ctx context.Context,
config types.GitspaceConfig,
infra types.Infrastructure,
canDeleteUserData bool,
) error
// Status checks if the infra is reachable and ready to orchestrate containers.
Status(ctx context.Context, infra types.Infrastructure) error
// StreamLogs is used to fetch gitspace's start/stop logs from the container orchestrator.
StreamLogs(ctx context.Context, gitspaceConfig types.GitspaceConfig, infra types.Infrastructure) (string, error)
StartAITask(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
infra types.Infrastructure,
aiTask types.AITask,
) error
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/devcontainer_container_utils.go | app/gitspace/orchestrator/container/devcontainer_container_utils.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package container
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"os/exec"
"path/filepath"
"strconv"
"strings"
"github.com/harness/gitness/app/gitspace/orchestrator/container/response"
"github.com/harness/gitness/app/gitspace/orchestrator/runarg"
"github.com/harness/gitness/app/gitspace/orchestrator/utils"
gitspaceTypes "github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/registry"
"github.com/docker/docker/api/types/strslice"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
"github.com/gotidy/ptr"
"github.com/rs/zerolog/log"
)
const (
catchAllIP = "0.0.0.0"
imagePullRunArgMissing = "missing"
)
var containerStateMapping = map[string]State{
"running": ContainerStateRunning,
"exited": ContainerStateStopped,
"dead": ContainerStateDead,
"created": ContainerStateCreated,
"paused": ContainerStatePaused,
}
// Helper function to log messages and handle error wrapping.
func logStreamWrapError(gitspaceLogger gitspaceTypes.GitspaceLogger, msg string, err error) error {
gitspaceLogger.Error(msg, err)
return fmt.Errorf("%s: %w", msg, err)
}
// Generalized Docker Container Management.
func ManageContainer(
ctx context.Context,
action Action,
containerName string,
dockerClient *client.Client,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
var err error
switch action {
case ContainerActionStop:
err = dockerClient.ContainerStop(ctx, containerName, container.StopOptions{})
if err != nil {
return logStreamWrapError(gitspaceLogger, "Error while stopping container", err)
}
gitspaceLogger.Info("Successfully stopped container")
case ContainerActionStart:
err = dockerClient.ContainerStart(ctx, containerName, container.StartOptions{})
if err != nil {
return logStreamWrapError(gitspaceLogger, "Error while starting container", err)
}
gitspaceLogger.Info("Successfully started container")
case ContainerActionRemove:
err = dockerClient.ContainerRemove(ctx, containerName, container.RemoveOptions{Force: true})
if err != nil {
return logStreamWrapError(gitspaceLogger, "Error while removing container", err)
}
gitspaceLogger.Info("Successfully removed container")
default:
return fmt.Errorf("unknown action: %s", action)
}
return nil
}
func FetchContainerState(
ctx context.Context,
containerName string,
dockerClient *client.Client,
) (State, error) {
args := filters.NewArgs()
args.Add("name", containerName)
containers, err := dockerClient.ContainerList(ctx, container.ListOptions{All: true, Filters: args})
if err != nil {
return "", fmt.Errorf("could not list container %s: %w", containerName, err)
}
if len(containers) == 0 {
return ContainerStateRemoved, nil
}
containerState := ContainerStateUnknown
for _, value := range containers {
name, _ := strings.CutPrefix(value.Names[0], "/")
if name == containerName {
if state, ok := containerStateMapping[value.State]; ok {
containerState = state
}
break
}
}
return containerState, nil
}
// Create a new Docker container.
func CreateContainer(
ctx context.Context,
dockerClient *client.Client,
imageName string,
containerName string,
gitspaceLogger gitspaceTypes.GitspaceLogger,
bindMountSource string,
bindMountTarget string,
mountType mount.Type,
portMappings map[int]*types.PortMapping,
env []string,
runArgsMap map[types.RunArg]*types.RunArgValue,
containerUser string,
remoteUser string,
features []*types.ResolvedFeature,
devcontainerConfig types.DevcontainerConfig,
metadataFromImage map[string]any,
) (map[PostAction][]*LifecycleHookStep, error) {
exposedPorts, portBindings := applyPortMappings(portMappings)
gitspaceLogger.Info(fmt.Sprintf("Creating container %s with image %s", containerName, imageName))
hostConfig, err := prepareHostConfig(bindMountSource, bindMountTarget, mountType, portBindings, runArgsMap,
features, devcontainerConfig, metadataFromImage)
if err != nil {
return nil, err
}
healthCheckConfig, err := getHealthCheckConfig(runArgsMap)
if err != nil {
return nil, err
}
stopTimeout, err := getStopTimeout(runArgsMap)
if err != nil {
return nil, err
}
entrypoint := mergeEntrypoints(features, runArgsMap)
var cmd strslice.StrSlice
if len(entrypoint) == 0 {
entrypoint = []string{"/bin/sh"}
cmd = []string{"-c", "trap 'exit 0' 15; sleep infinity & wait $!"}
}
lifecycleHookSteps := mergeLifeCycleHooks(devcontainerConfig, features)
lifecycleHookStepsStr, err := json.Marshal(lifecycleHookSteps)
if err != nil {
return nil, err
}
labels := getLabels(runArgsMap)
// Setting the following so that it can be read later to form gitspace URL.
labels[gitspaceRemoteUserLabel] = remoteUser
// Setting the following so that it can be read later to run the postStartCommands during restarts.
labels[gitspaceLifeCycleHooksLabel] = string(lifecycleHookStepsStr)
// Create the container
containerConfig := &container.Config{
Hostname: getHostname(runArgsMap),
Domainname: getDomainname(runArgsMap),
Image: imageName,
Env: env,
Entrypoint: entrypoint,
Cmd: cmd,
ExposedPorts: exposedPorts,
Labels: labels,
Healthcheck: healthCheckConfig,
MacAddress: getMACAddress(runArgsMap),
StopSignal: getStopSignal(runArgsMap),
StopTimeout: stopTimeout,
User: containerUser,
}
_, err = dockerClient.ContainerCreate(ctx, containerConfig, hostConfig, nil, nil, containerName)
if err != nil {
return nil, logStreamWrapError(gitspaceLogger, "Error while creating container", err)
}
return lifecycleHookSteps, nil
}
func mergeLifeCycleHooks(
devcontainerConfig types.DevcontainerConfig,
features []*types.ResolvedFeature,
) map[PostAction][]*LifecycleHookStep {
var postCreateHooks []*LifecycleHookStep
var postStartHooks []*LifecycleHookStep
for _, feature := range features {
if len(feature.DownloadedFeature.DevcontainerFeatureConfig.PostCreateCommand.ToCommandArray()) > 0 {
postCreateHooks = append(postCreateHooks, &LifecycleHookStep{
Source: feature.DownloadedFeature.Source,
Command: feature.DownloadedFeature.DevcontainerFeatureConfig.PostCreateCommand,
ActionType: PostCreateAction,
StopOnFailure: true,
})
}
if len(feature.DownloadedFeature.DevcontainerFeatureConfig.PostStartCommand.ToCommandArray()) > 0 {
postStartHooks = append(postStartHooks, &LifecycleHookStep{
Source: feature.DownloadedFeature.Source,
Command: feature.DownloadedFeature.DevcontainerFeatureConfig.PostStartCommand,
ActionType: PostStartAction,
StopOnFailure: true,
})
}
}
if len(devcontainerConfig.PostCreateCommand.ToCommandArray()) > 0 {
postCreateHooks = append(postCreateHooks, &LifecycleHookStep{
Source: "devcontainer.json",
Command: devcontainerConfig.PostCreateCommand,
ActionType: PostCreateAction,
StopOnFailure: false,
})
}
if len(devcontainerConfig.PostStartCommand.ToCommandArray()) > 0 {
postStartHooks = append(postStartHooks, &LifecycleHookStep{
Source: "devcontainer.json",
Command: devcontainerConfig.PostStartCommand,
ActionType: PostStartAction,
StopOnFailure: false,
})
}
return map[PostAction][]*LifecycleHookStep{
PostCreateAction: postCreateHooks,
PostStartAction: postStartHooks,
}
}
func mergeEntrypoints(
features []*types.ResolvedFeature,
runArgsMap map[types.RunArg]*types.RunArgValue,
) strslice.StrSlice {
entrypoints := strslice.StrSlice{}
for _, feature := range features {
entrypoint := feature.DownloadedFeature.DevcontainerFeatureConfig.Entrypoint
if entrypoint != "" {
entrypoints = append(entrypoints, entrypoint)
}
}
entrypoints = append(entrypoints, getEntrypoint(runArgsMap)...)
return entrypoints
}
// Prepare port mappings for container creation.
func applyPortMappings(portMappings map[int]*types.PortMapping) (nat.PortSet, nat.PortMap) {
exposedPorts := nat.PortSet{}
portBindings := nat.PortMap{}
for port, mapping := range portMappings {
natPort := nat.Port(strconv.Itoa(port) + "/tcp")
hostPortBindings := []nat.PortBinding{
{
HostIP: catchAllIP,
HostPort: strconv.Itoa(mapping.PublishedPort),
},
}
exposedPorts[natPort] = struct{}{}
portBindings[natPort] = hostPortBindings
}
return exposedPorts, portBindings
}
// Prepare the host configuration for container creation.
func prepareHostConfig(
bindMountSource string,
bindMountTarget string,
mountType mount.Type,
portBindings nat.PortMap,
runArgsMap map[types.RunArg]*types.RunArgValue,
features []*types.ResolvedFeature,
devcontainerConfig types.DevcontainerConfig,
metadataFromImage map[string]any,
) (*container.HostConfig, error) {
hostResources, err := getHostResources(runArgsMap)
if err != nil {
return nil, err
}
extraHosts := getExtraHosts(runArgsMap)
extraHosts = append(extraHosts, "host.docker.internal:host-gateway")
restartPolicy, err := getRestartPolicy(runArgsMap)
if err != nil {
return nil, err
}
oomScoreAdj, err := getOomScoreAdj(runArgsMap)
if err != nil {
return nil, err
}
shmSize, err := getSHMSize(runArgsMap)
if err != nil {
return nil, err
}
defaultMount := mount.Mount{
Type: mountType,
Source: bindMountSource,
Target: bindMountTarget,
}
mergedMounts, err := mergeMounts(devcontainerConfig, runArgsMap, features, defaultMount, metadataFromImage)
if err != nil {
return nil, fmt.Errorf("failed to merge mounts: %w", err)
}
hostConfig := &container.HostConfig{
PortBindings: portBindings,
Mounts: mergedMounts,
Resources: hostResources,
Annotations: getAnnotations(runArgsMap),
ExtraHosts: extraHosts,
NetworkMode: getNetworkMode(runArgsMap),
RestartPolicy: restartPolicy,
AutoRemove: getAutoRemove(runArgsMap),
CapAdd: mergeCapAdd(devcontainerConfig, runArgsMap, features, metadataFromImage),
CapDrop: getCapDrop(runArgsMap),
CgroupnsMode: getCgroupNSMode(runArgsMap),
DNS: getDNS(runArgsMap),
DNSOptions: getDNSOptions(runArgsMap),
DNSSearch: getDNSSearch(runArgsMap),
IpcMode: getIPCMode(runArgsMap),
Isolation: getIsolation(runArgsMap),
Init: mergeInit(devcontainerConfig, runArgsMap, features, metadataFromImage),
Links: getLinks(runArgsMap),
OomScoreAdj: oomScoreAdj,
PidMode: getPIDMode(runArgsMap),
Privileged: mergePriviledged(devcontainerConfig, runArgsMap, features, metadataFromImage),
Runtime: getRuntime(runArgsMap),
SecurityOpt: mergeSecurityOpts(devcontainerConfig, runArgsMap, features, metadataFromImage),
StorageOpt: getStorageOpt(runArgsMap),
ShmSize: shmSize,
Sysctls: getSysctls(runArgsMap),
}
return hostConfig, nil
}
func mergeMounts(
devcontainerConfig types.DevcontainerConfig,
runArgsMap map[types.RunArg]*types.RunArgValue,
features []*types.ResolvedFeature,
defaultMount mount.Mount,
metadataFromImage map[string]any,
) ([]mount.Mount, error) {
var allMountsRaw []*types.Mount
for _, feature := range features {
if len(feature.DownloadedFeature.DevcontainerFeatureConfig.Mounts) > 0 {
allMountsRaw = append(allMountsRaw, feature.DownloadedFeature.DevcontainerFeatureConfig.Mounts...)
}
}
mountsFromRunArgs, err := getMounts(runArgsMap)
if err != nil {
return nil, err
}
// First check if mounts have been overridden in the runArgs, then check if the devcontainer.json
// provides any security options, if not, only then check the image metadata.
switch {
case len(mountsFromRunArgs) > 0:
allMountsRaw = append(allMountsRaw, mountsFromRunArgs...)
case len(devcontainerConfig.Mounts) > 0:
allMountsRaw = append(allMountsRaw, devcontainerConfig.Mounts...)
default:
if values, ok := metadataFromImage["mounts"].([]any); ok {
parsedMounts, err := types.ParseMountsFromRawSlice(values)
if err != nil {
return nil, err
}
allMountsRaw = append(allMountsRaw, parsedMounts...)
}
}
var allMounts []mount.Mount
for _, rawMount := range allMountsRaw {
if rawMount.Type == "" {
rawMount.Type = string(mount.TypeVolume)
}
parsedMount := mount.Mount{
Type: mount.Type(rawMount.Type),
Source: rawMount.Source,
Target: rawMount.Target,
}
allMounts = append(allMounts, parsedMount)
}
allMounts = append(allMounts, defaultMount)
return allMounts, nil
}
func mergeSecurityOpts(
devcontainerConfig types.DevcontainerConfig,
runArgsMap map[types.RunArg]*types.RunArgValue,
features []*types.ResolvedFeature,
metadataFromImage map[string]any,
) []string {
var allOpts []string
for _, feature := range features {
allOpts = append(allOpts, feature.DownloadedFeature.DevcontainerFeatureConfig.SecurityOpt...)
}
// First check if security options have been overridden in the runArgs, then check if the devcontainer.json
// provides any security options, if not, only then check the image metadata.
securityOptsFromRunArgs := getSecurityOpt(runArgsMap)
switch {
case len(securityOptsFromRunArgs) > 0:
allOpts = append(allOpts, securityOptsFromRunArgs...)
case len(devcontainerConfig.SecurityOpt) > 0:
allOpts = append(allOpts, devcontainerConfig.SecurityOpt...)
default:
if value, ok := metadataFromImage["securityOpt"].([]string); ok {
allOpts = append(allOpts, value...)
}
}
return allOpts
}
func mergeCapAdd(
devcontainerConfig types.DevcontainerConfig,
runArgsMap map[types.RunArg]*types.RunArgValue,
features []*types.ResolvedFeature,
metadataFromImage map[string]any,
) strslice.StrSlice {
allCaps := strslice.StrSlice{}
for _, feature := range features {
allCaps = append(allCaps, feature.DownloadedFeature.DevcontainerFeatureConfig.CapAdd...)
}
// First check if capAdd have been overridden in the runArgs, then check if the devcontainer.json
// provides any capAdd, if not, only then check the image metadata.
capAddFromRunArgs := getCapAdd(runArgsMap)
switch {
case len(capAddFromRunArgs) > 0:
allCaps = append(allCaps, capAddFromRunArgs...)
case len(devcontainerConfig.CapAdd) > 0:
allCaps = append(allCaps, devcontainerConfig.CapAdd...)
default:
if value, ok := metadataFromImage["capAdd"].([]string); ok {
allCaps = append(allCaps, value...)
}
}
return allCaps
}
func mergeInit(
devcontainerConfig types.DevcontainerConfig,
runArgsMap map[types.RunArg]*types.RunArgValue,
features []*types.ResolvedFeature,
metadataFromImage map[string]any,
) *bool {
// First check if init has been overridden in the runArgs, if not, then check in the devcontainer.json
// lastly check in the image metadata.
var initPtr = getInit(runArgsMap)
if initPtr == nil {
if devcontainerConfig.Init != nil {
initPtr = devcontainerConfig.Init
} else {
if value, ok := metadataFromImage["init"].(bool); ok {
initPtr = ptr.Bool(value)
}
}
}
var init = ptr.ToBool(initPtr)
// Merge this valye with the value from the features.
if !init {
for _, feature := range features {
if feature.DownloadedFeature.DevcontainerFeatureConfig.Init {
init = true
break
}
}
}
return ptr.Bool(init)
}
func mergePriviledged(
devcontainerConfig types.DevcontainerConfig,
runArgsMap map[types.RunArg]*types.RunArgValue,
features []*types.ResolvedFeature,
metadataFromImage map[string]any,
) bool {
// First check if privileged has been overridden in the runArgs, if not, then check in the devcontainer.json
// lastly check in the image metadata.
var privilegedPtr = getPrivileged(runArgsMap)
if privilegedPtr == nil {
if devcontainerConfig.Privileged != nil {
privilegedPtr = devcontainerConfig.Privileged
} else {
if value, ok := metadataFromImage["privileged"].(bool); ok {
privilegedPtr = ptr.Bool(value)
}
}
}
var privileged = ptr.ToBool(privilegedPtr)
// Merge this valye with the value from the features.
if !privileged {
for _, feature := range features {
if feature.DownloadedFeature.DevcontainerFeatureConfig.Privileged {
privileged = true
break
}
}
}
return privileged
}
func GetContainerInfo(
ctx context.Context,
containerName string,
dockerClient *client.Client,
portMappings map[int]*types.PortMapping,
) (string, map[int]string, string, error) {
inspectResp, err := dockerClient.ContainerInspect(ctx, containerName)
if err != nil {
return "", nil, "", fmt.Errorf("could not inspect container %s: %w", containerName, err)
}
usedPorts := make(map[int]string)
for portAndProtocol, bindings := range inspectResp.NetworkSettings.Ports {
portRaw := strings.Split(string(portAndProtocol), "/")[0]
port, conversionErr := strconv.Atoi(portRaw)
if conversionErr != nil {
return "", nil, "", fmt.Errorf("could not convert port %s to int: %w", portRaw, conversionErr)
}
if portMappings[port] != nil {
usedPorts[port] = bindings[0].HostPort
}
}
remoteUser := ExtractRemoteUserFromLabels(inspectResp)
return inspectResp.ID, usedPorts, remoteUser, nil
}
func ExtractImageData(
ctx context.Context,
imageName string,
dockerClient *client.Client,
) (*types.ImageData, error) {
imageInspect, _, err := dockerClient.ImageInspectWithRaw(ctx, imageName)
if err != nil {
return nil, fmt.Errorf("error while inspecting image: %w", err)
}
imageUser := imageInspect.Config.User
if imageUser == "" {
imageUser = "root"
}
imageData := types.ImageData{
Arch: imageInspect.Architecture,
OS: imageInspect.Os,
User: imageUser,
}
metadataMap := map[string]any{}
if metadata, ok := imageInspect.Config.Labels["devcontainer.metadata"]; ok {
dst := []map[string]any{}
unmarshalErr := json.Unmarshal([]byte(metadata), &dst)
if unmarshalErr != nil {
return &imageData, fmt.Errorf("error while unmarshalling metadata: %w", err)
}
for _, values := range dst {
maps.Copy(metadataMap, values)
}
}
imageData.Metadata = metadataMap
return &imageData, nil
}
func CopyImage(
ctx context.Context,
imageName string,
dockerClient *client.Client,
runArgsMap map[types.RunArg]*types.RunArgValue,
gitspaceLogger gitspaceTypes.GitspaceLogger,
imageAuthMap map[string]gitspaceTypes.DockerRegistryAuth,
httpProxyURL types.MaskSecret,
httpsProxyURL types.MaskSecret,
) error {
gitspaceLogger.Info("Copying image " + imageName + " to local")
imagePullRunArg := getImagePullPolicy(runArgsMap)
if imagePullRunArg == "never" {
return nil
}
if imagePullRunArg == imagePullRunArgMissing {
imagePresentLocally, err := utils.IsImagePresentLocally(ctx, imageName, dockerClient)
if err != nil {
return err
}
if imagePresentLocally {
return nil
}
}
// Build skopeo command
platform := getPlatform(runArgsMap)
args := []string{"copy", "--debug", "--src-tls-verify=false"}
if platform != "" {
args = append(args, "--override-os", platform)
}
// Add credentials if available
if auth, ok := imageAuthMap[imageName]; ok && auth.Password != nil {
gitspaceLogger.Info("Using credentials for registry: " + auth.RegistryURL)
args = append(args, "--src-creds", auth.Username.Value()+":"+auth.Password.Value())
} else {
gitspaceLogger.Warn("No credentials found for registry. Proceeding without authentication.")
}
// Source and destination
source := "docker://" + imageName
image, tag := getImageAndTag(imageName)
destination := "docker-daemon:" + image + ":" + tag
args = append(args, source, destination)
cmd := exec.CommandContext(ctx, "skopeo", args...)
// Set proxy environment variables if provided
env := cmd.Env
if httpProxyURL.Value() != "" {
env = append(env, "HTTP_PROXY="+httpProxyURL.Value())
log.Info().Msg("HTTP_PROXY set in environment")
}
if httpsProxyURL.Value() != "" {
env = append(env, "HTTPS_PROXY="+httpsProxyURL.Value())
log.Info().Msg("HTTPS_PROXY set in environment")
}
cmd.Env = env
var outBuf, errBuf bytes.Buffer
cmd.Stdout = &outBuf
cmd.Stderr = &errBuf
gitspaceLogger.Info("Executing image copy command: " + cmd.String())
cmdErr := cmd.Run()
response, err := io.ReadAll(&outBuf)
if err != nil {
return logStreamWrapError(gitspaceLogger, "Error while reading image output", err)
}
gitspaceLogger.Info("Image copy output: " + string(response))
errResponse, err := io.ReadAll(&errBuf)
if err != nil {
return logStreamWrapError(gitspaceLogger, "Error while reading image output", err)
}
combinedOutput := string(response) + "\n" + string(errResponse)
gitspaceLogger.Info("Image copy combined output: " + combinedOutput)
if cmdErr != nil {
return logStreamWrapError(gitspaceLogger, "Error while pulling image using skopeo", cmdErr)
}
gitspaceLogger.Info("Image copy completed successfully using skopeo")
return nil
}
func PullImage(
ctx context.Context,
imageName string,
dockerClient *client.Client,
runArgsMap map[types.RunArg]*types.RunArgValue,
gitspaceLogger gitspaceTypes.GitspaceLogger,
imageAuthMap map[string]gitspaceTypes.DockerRegistryAuth,
) error {
imagePullRunArg := getImagePullPolicy(runArgsMap)
gitspaceLogger.Info("Image pull policy is: " + imagePullRunArg)
if imagePullRunArg == "never" {
return nil
}
if imagePullRunArg == imagePullRunArgMissing {
gitspaceLogger.Info("Checking if image " + imageName + " is present locally")
imagePresentLocally, err := utils.IsImagePresentLocally(ctx, imageName, dockerClient)
if err != nil {
gitspaceLogger.Error("Error listing images locally", err)
return err
}
if imagePresentLocally {
gitspaceLogger.Info("Image " + imageName + " is present locally")
return nil
}
gitspaceLogger.Info("Image " + imageName + " is not present locally")
}
gitspaceLogger.Info("Pulling image: " + imageName)
pullOpts, err := buildImagePullOptions(imageName, getPlatform(runArgsMap), imageAuthMap)
if err != nil {
return logStreamWrapError(gitspaceLogger, "Error building image pull options", err)
}
pullResponse, err := dockerClient.ImagePull(ctx, imageName, pullOpts)
defer func() {
if pullResponse == nil {
return
}
closingErr := pullResponse.Close()
if closingErr != nil {
log.Warn().Err(closingErr).Msg("failed to close image pull response")
}
}()
if err != nil {
return logStreamWrapError(gitspaceLogger, "Error while pulling image", err)
}
defer func() {
if pullResponse != nil {
if closingErr := pullResponse.Close(); closingErr != nil {
log.Warn().Err(closingErr).Msg("Failed to close image pull response")
}
}
}()
if err = processImagePullResponse(pullResponse, gitspaceLogger); err != nil {
return err
}
gitspaceLogger.Info("Image pull completed successfully")
return nil
}
func ExtractRunArgsWithLogging(
ctx context.Context,
spaceID int64,
runArgProvider runarg.Provider,
runArgsRaw []string,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) (map[types.RunArg]*types.RunArgValue, error) {
runArgsMap, err := ExtractRunArgs(ctx, spaceID, runArgProvider, runArgsRaw)
if err != nil {
return nil, logStreamWrapError(gitspaceLogger, "Error while extracting runArgs", err)
}
if len(runArgsMap) > 0 {
st := ""
for key, value := range runArgsMap {
st = fmt.Sprintf("%s%s: %s\n", st, key, value)
}
gitspaceLogger.Info(fmt.Sprintf("Using the following runArgs\n%v", st))
} else {
gitspaceLogger.Info("No runArgs found")
}
return runArgsMap, nil
}
// GetContainerResponse retrieves container information and prepares the start response.
func GetContainerResponse(
ctx context.Context,
dockerClient *client.Client,
containerName string,
portMappings map[int]*types.PortMapping,
repoName string,
) (*response.StartResponse, error) {
id, ports, remoteUser, err := GetContainerInfo(ctx, containerName, dockerClient, portMappings)
if err != nil {
return nil, err
}
homeDir := GetUserHomeDir(remoteUser)
codeRepoDir := filepath.Join(homeDir, repoName)
return &response.StartResponse{
Status: response.SuccessStatus,
ContainerID: id,
ContainerName: containerName,
PublishedPorts: ports,
AbsoluteRepoPath: codeRepoDir,
RemoteUser: remoteUser,
}, nil
}
func GetGitspaceInfoFromContainerLabels(
ctx context.Context,
containerName string,
dockerClient *client.Client,
) (string, map[PostAction][]*LifecycleHookStep, error) {
inspectResp, err := dockerClient.ContainerInspect(ctx, containerName)
if err != nil {
return "", nil, fmt.Errorf("could not inspect container %s: %w", containerName, err)
}
remoteUser := ExtractRemoteUserFromLabels(inspectResp)
lifecycleHooks, err := ExtractLifecycleHooksFromLabels(inspectResp)
if err != nil {
return "", nil, fmt.Errorf("could not extract lifecycle hooks: %w", err)
}
return remoteUser, lifecycleHooks, nil
}
// Helper function to encode the AuthConfig into a Base64 string.
func encodeAuthToBase64(authConfig registry.AuthConfig) (string, error) {
authJSON, err := json.Marshal(authConfig)
if err != nil {
return "", fmt.Errorf("encoding auth config: %w", err)
}
return base64.URLEncoding.EncodeToString(authJSON), nil
}
func processImagePullResponse(pullResponse io.ReadCloser, gitspaceLogger gitspaceTypes.GitspaceLogger) error {
// Process JSON stream
decoder := json.NewDecoder(pullResponse)
layerStatus := make(map[string]string) // Track last status of each layer
for {
var pullEvent map[string]any
if err := decoder.Decode(&pullEvent); err != nil {
if errors.Is(err, io.EOF) {
break
}
return logStreamWrapError(gitspaceLogger, "Error while decoding image pull response", err)
}
// Extract relevant fields from the JSON object
layerID, _ := pullEvent["id"].(string) // Layer ID (if available)
status, _ := pullEvent["status"].(string) // Current status
// Update logs only when the status changes
if layerID != "" {
if lastStatus, exists := layerStatus[layerID]; !exists || lastStatus != status {
layerStatus[layerID] = status
gitspaceLogger.Info(fmt.Sprintf("Layer %s: %s", layerID, status))
}
} else if status != "" {
// Log non-layer-specific status
gitspaceLogger.Info(status)
}
}
return nil
}
func buildImagePullOptions(
imageName,
platform string,
imageAuthMap map[string]gitspaceTypes.DockerRegistryAuth,
) (image.PullOptions, error) {
pullOpts := image.PullOptions{Platform: platform}
if imageAuth, ok := imageAuthMap[imageName]; ok {
authConfig := registry.AuthConfig{
Username: imageAuth.Username.Value(),
Password: imageAuth.Password.Value(),
ServerAddress: imageAuth.RegistryURL,
}
auth, err := encodeAuthToBase64(authConfig)
if err != nil {
return image.PullOptions{}, fmt.Errorf("encoding auth for docker registry: %w", err)
}
pullOpts.RegistryAuth = auth
}
return pullOpts, nil
}
// getImageAndTag separates the image name and tag correctly.
func getImageAndTag(image string) (string, string) {
// Split the image on the last slash
lastSlashIndex := strings.LastIndex(image, "/")
var name, tag string
if lastSlashIndex != -1 { //nolint:nestif
// If there's a slash, the portion before the last slash is part of the registry/repository
// and the portion after the last slash will be considered for the tag handling.
// Now check if there is a colon in the string
lastColonIndex := strings.LastIndex(image, ":")
if lastColonIndex != -1 && lastColonIndex > lastSlashIndex {
// There is a tag after the last colon
name = image[:lastColonIndex]
tag = image[lastColonIndex+1:]
} else {
// No colon, treat it as the image and assume "latest" tag
name = image
tag = "latest"
}
} else {
// If no slash is present, split on the last colon for image and tag
lastColonIndex := strings.LastIndex(image, ":")
if lastColonIndex != -1 {
name = image[:lastColonIndex]
tag = image[lastColonIndex+1:]
} else {
name = image
tag = "latest"
}
}
return name, tag
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/devcontainer_config_utils.go | app/gitspace/orchestrator/container/devcontainer_config_utils.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package container
import (
"context"
"fmt"
"path"
"regexp"
"strings"
"github.com/harness/gitness/app/gitspace/orchestrator/ide"
"github.com/harness/gitness/app/gitspace/orchestrator/runarg"
gitspaceTypes "github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
func ExtractRunArgs(
ctx context.Context,
spaceID int64,
runArgProvider runarg.Provider,
runArgsRaw []string,
) (map[types.RunArg]*types.RunArgValue, error) {
supportedRunArgsMap, err := runArgProvider.ProvideSupportedRunArgs(ctx, spaceID)
if err != nil {
return nil, err
}
var runArgsMap = make(map[types.RunArg]*types.RunArgValue)
argLoopCounter := 0
for argLoopCounter < len(runArgsRaw) {
currentArg := runArgsRaw[argLoopCounter]
if currentArg == "" || !isArg(currentArg) {
argLoopCounter++
continue
}
argParts := strings.SplitN(currentArg, "=", 2)
argKey := argParts[0]
currentRunArgDefinition, isSupportedArg := supportedRunArgsMap[types.RunArg(argKey)]
if !isSupportedArg {
argLoopCounter++
continue
}
updatedArgLoopCounter, allowedValues, isAnyValueBlocked := getValues(runArgsRaw, argParts, argLoopCounter,
currentRunArgDefinition)
argLoopCounter = updatedArgLoopCounter
if isAnyValueBlocked && len(allowedValues) == 0 {
continue
}
currentRunArgValue := types.RunArgValue{
Name: currentRunArgDefinition.Name,
Values: allowedValues,
}
existingRunArgValue, isAlreadyPresent := runArgsMap[currentRunArgDefinition.Name]
if isAlreadyPresent && currentRunArgDefinition.AllowMultipleOccurences {
existingRunArgValue.Values = append(existingRunArgValue.Values, currentRunArgValue.Values...)
} else {
runArgsMap[currentRunArgDefinition.Name] = ¤tRunArgValue
}
}
return runArgsMap, nil
}
func getValues(
runArgs []string,
argParts []string,
argLoopCounter int,
currentRunArgDefinition types.RunArgDefinition,
) (int, []string, bool) {
values := make([]string, 0)
if len(argParts) > 1 {
values = append(values, strings.TrimSpace(argParts[1]))
argLoopCounter++
} else {
var valueLoopCounter = argLoopCounter + 1
for valueLoopCounter < len(runArgs) {
currentValue := runArgs[valueLoopCounter]
if isArg(currentValue) {
break
}
values = append(values, strings.TrimSpace(currentValue))
valueLoopCounter++
}
argLoopCounter = valueLoopCounter
}
allowedValues, isAnyValueBlocked := filterAllowedValues(values, currentRunArgDefinition)
return argLoopCounter, allowedValues, isAnyValueBlocked
}
func filterAllowedValues(
values []string,
currentRunArgDefinition types.RunArgDefinition,
) ([]string, bool) {
isAnyValueBlocked := false
allowedValues := make([]string, 0)
for _, v := range values {
switch {
case len(currentRunArgDefinition.AllowedValues) > 0:
for allowedValue := range currentRunArgDefinition.AllowedValues {
matches, err := regexp.MatchString(allowedValue, v)
if err != nil {
log.Warn().Err(err).Msgf("error checking allowed values for RunArg %s value %s",
currentRunArgDefinition.Name, v)
continue
}
if matches {
allowedValues = append(allowedValues, v)
} else {
log.Warn().Msgf("Value %s for runArg %s not allowed", v, currentRunArgDefinition.Name)
isAnyValueBlocked = true
}
}
case len(currentRunArgDefinition.BlockedValues) > 0:
var isValueBlocked = false
for blockedValue := range currentRunArgDefinition.BlockedValues {
matches, err := regexp.MatchString(blockedValue, v)
if err != nil {
log.Warn().Err(err).Msgf("error checking blocked values for RunArg %s value %s",
currentRunArgDefinition.Name, v)
continue
}
if matches {
log.Warn().Msgf("Value %s for runArg %s not allowed", v, currentRunArgDefinition.Name)
isValueBlocked = true
isAnyValueBlocked = true
}
}
if !isValueBlocked {
allowedValues = append(allowedValues, v)
}
default:
allowedValues = append(allowedValues, v)
}
}
return allowedValues, isAnyValueBlocked
}
func isArg(str string) bool {
return strings.HasPrefix(str, "--") || strings.HasPrefix(str, "-")
}
func ExtractEnv(devcontainerConfig types.DevcontainerConfig, runArgsMap map[types.RunArg]*types.RunArgValue) []string {
var env []string
for key, value := range devcontainerConfig.ContainerEnv {
env = append(env, fmt.Sprintf("%s=%s", key, value))
}
envFromRunArgs := getEnv(runArgsMap)
env = append(env, envFromRunArgs...)
return env
}
func ExtractForwardPorts(devcontainerConfig types.DevcontainerConfig) []int {
var ports []int
for _, strPort := range devcontainerConfig.ForwardPorts {
portAsInt, err := strPort.Int64() // Using Atoi to convert string to int
if err != nil {
log.Warn().Msgf("Error converting port string '%s' to int: %v", strPort, err)
continue // Skip the invalid port
}
ports = append(ports, int(portAsInt))
}
return ports
}
func ExtractLifecycleCommands(actionType PostAction, devcontainerConfig types.DevcontainerConfig) []string {
switch actionType {
case PostCreateAction:
return devcontainerConfig.PostCreateCommand.ToCommandArray()
case PostStartAction:
return devcontainerConfig.PostStartCommand.ToCommandArray()
default:
return []string{} // Return empty string if actionType is not recognized
}
}
func AddIDECustomizationsArg(
ideService ide.IDE,
devcontainerConfig types.DevcontainerConfig,
args map[gitspaceTypes.IDEArg]any,
) map[gitspaceTypes.IDEArg]any {
switch ideService.Type() {
case enum.IDETypeVSCodeWeb, enum.IDETypeVSCode, enum.IDETypeWindsurf, enum.IDETypeCursor:
// Cursor and Windsurf is a VSCode-based IDE, so it also uses the same customization
// specs as VSCode and Cursor.
vscodeSpecs := devcontainerConfig.Customizations.ExtractVSCodeSpec()
if vscodeSpecs != nil {
args[gitspaceTypes.VSCodeCustomizationArg] = *vscodeSpecs
}
case enum.IDETypeIntelliJ, enum.IDETypePyCharm, enum.IDETypeGoland, enum.IDETypeWebStorm, enum.IDETypeCLion,
enum.IDETypePHPStorm, enum.IDETypeRubyMine, enum.IDETypeRider:
jetbrainsSpecs := devcontainerConfig.Customizations.ExtractJetBrainsSpecs()
if jetbrainsSpecs != nil {
args[gitspaceTypes.JetBrainsCustomizationArg] = *jetbrainsSpecs
}
default:
log.Warn().Msgf("No customizations available for IDE type: %s", ideService.Type())
}
return args
}
func AddIDEDownloadURLArg(
ideService ide.IDE,
args map[gitspaceTypes.IDEArg]any,
) map[gitspaceTypes.IDEArg]any {
if !enum.IsJetBrainsIDE(ideService.Type()) {
// currently download url is only need for jetbrains IDEs
return args
}
ideType := ideService.Type()
ideDownloadURLTemplate := types.JetBrainsIDEDownloadURLTemplateMap[ideType]
args[gitspaceTypes.IDEDownloadURLArg] = types.IDEDownloadURLs{
Amd64Sha: ideDownloadURLTemplate.Amd64Sha,
Arm64Sha: ideDownloadURLTemplate.Arm64Sha,
Amd64: fmt.Sprintf(ideDownloadURLTemplate.Amd64, ideDownloadURLTemplate.Version),
Arm64: fmt.Sprintf(ideDownloadURLTemplate.Arm64, ideDownloadURLTemplate.Version),
}
return args
}
func AddIDEDirNameArg(
ideService ide.IDE,
args map[gitspaceTypes.IDEArg]any,
) map[gitspaceTypes.IDEArg]any {
if !enum.IsJetBrainsIDE(ideService.Type()) {
// currently dirname is only need for jetbrains IDEs
return args
}
ideType := ideService.Type()
dirname := path.Join(".cache", "JetBrains", "RemoteDev", "dist", ideType.String())
args[gitspaceTypes.IDEDIRNameArg] = dirname
return args
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/embedded_docker_container_orchestrator.go | app/gitspace/orchestrator/container/embedded_docker_container_orchestrator.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package container
import (
"context"
"fmt"
"path/filepath"
"strings"
events "github.com/harness/gitness/app/events/gitspaceoperations"
"github.com/harness/gitness/app/gitspace/logutil"
"github.com/harness/gitness/app/gitspace/orchestrator/container/response"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
"github.com/harness/gitness/app/gitspace/orchestrator/ide"
"github.com/harness/gitness/app/gitspace/orchestrator/runarg"
"github.com/harness/gitness/app/gitspace/orchestrator/utils"
"github.com/harness/gitness/app/gitspace/scm"
gitspaceTypes "github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/infraprovider"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/client"
"github.com/rs/zerolog/log"
)
var _ Orchestrator = (*EmbeddedDockerOrchestrator)(nil)
var loggingDivider = "\n" + strings.Repeat("=", 100) + "\n"
const (
loggingKey = "gitspace.container"
)
type EmbeddedDockerOrchestrator struct {
dockerClientFactory *infraprovider.DockerClientFactory
statefulLogger *logutil.StatefulLogger
runArgProvider runarg.Provider
eventReporter *events.Reporter
}
// Step represents a single setup action.
type step struct {
Name string
Execute func(ctx context.Context, exec *devcontainer.Exec, gitspaceLogger gitspaceTypes.GitspaceLogger) error
StopOnFailure bool // Flag to control whether execution should stop on failure
}
type LifecycleHookStep struct {
Source string `json:"source,omitempty"`
Command types.LifecycleCommand `json:"command,omitzero"`
ActionType PostAction `json:"action_type,omitempty"`
StopOnFailure bool `json:"stop_on_failure,omitempty"`
}
// ExecuteSteps executes all registered steps in sequence, respecting stopOnFailure flag.
func (e *EmbeddedDockerOrchestrator) ExecuteSteps(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger gitspaceTypes.GitspaceLogger,
steps []step,
) error {
for _, step := range steps {
// Execute the step
if err := step.Execute(ctx, exec, gitspaceLogger); err != nil {
// Log the error and decide whether to stop or continue based on stopOnFailure flag
if step.StopOnFailure {
return fmt.Errorf("error executing step %s: %w (stopping due to failure)", step.Name, err)
}
// Log that we continue despite the failure
gitspaceLogger.Info(fmt.Sprintf("Step %s failed:", step.Name))
}
}
return nil
}
func NewEmbeddedDockerOrchestrator(
dockerClientFactory *infraprovider.DockerClientFactory,
statefulLogger *logutil.StatefulLogger,
runArgProvider runarg.Provider,
eventReporter *events.Reporter,
) EmbeddedDockerOrchestrator {
return EmbeddedDockerOrchestrator{
dockerClientFactory: dockerClientFactory,
statefulLogger: statefulLogger,
runArgProvider: runArgProvider,
eventReporter: eventReporter,
}
}
// CreateAndStartGitspace starts an exited container and starts a new container if the container is removed.
// If the container is newly created, it clones the code, sets up the IDE and executes the postCreateCommand.
// It returns the container ID, name and ports used.
// It returns an error if the container is not running, exited or removed.
func (e *EmbeddedDockerOrchestrator) CreateAndStartGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
infra types.Infrastructure,
resolvedRepoDetails scm.ResolvedDetails,
defaultBaseImage string,
ideService ide.IDE,
) error {
containerName := GetGitspaceContainerName(gitspaceConfig)
logger := log.Ctx(ctx).With().Str(loggingKey, containerName).Logger()
// Step 1: Validate access key
accessKey, err := e.getAccessKey(gitspaceConfig)
if err != nil {
return err
}
// Step 2: Get Docker client
dockerClient, err := e.getDockerClient(ctx, infra)
if err != nil {
return err
}
defer e.closeDockerClient(dockerClient)
// todo : update the code when private repository integration is supported in gitness
imagAuthMap := make(map[string]gitspaceTypes.DockerRegistryAuth)
// Step 3: Check the current state of the container
state, err := e.checkContainerState(ctx, dockerClient, containerName)
if err != nil {
return err
}
// Step 4: Handle different container states
switch state {
case ContainerStateRunning:
logger.Debug().Msg("gitspace is already running")
case ContainerStateStopped:
if err = e.startStoppedGitspace(
ctx,
gitspaceConfig,
dockerClient,
resolvedRepoDetails,
accessKey,
ideService,
); err != nil {
return err
}
case ContainerStateRemoved:
if err = e.createAndStartNewGitspace(
ctx,
gitspaceConfig,
dockerClient,
resolvedRepoDetails,
infra,
defaultBaseImage,
ideService,
imagAuthMap); err != nil {
return err
}
case ContainerStatePaused, ContainerStateCreated, ContainerStateUnknown, ContainerStateDead:
// TODO handle the following states
return fmt.Errorf("gitspace %s is in a unhandled state: %s", containerName, state)
default:
return fmt.Errorf("gitspace %s is in a bad state: %s", containerName, state)
}
// Step 5: Retrieve container information and return response
startResponse, err := GetContainerResponse(
ctx,
dockerClient,
containerName,
infra.GitspacePortMappings,
resolvedRepoDetails.RepoName,
)
if err != nil {
return err
}
return e.eventReporter.EmitGitspaceOperationsEvent(
ctx,
events.GitspaceOperationsEvent,
&events.GitspaceOperationsEventPayload{
Type: enum.GitspaceOperationsEventStart,
Infra: infra,
Response: *startResponse,
},
)
}
// startStoppedGitspace starts the Gitspace container if it was stopped.
func (e *EmbeddedDockerOrchestrator) startStoppedGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
dockerClient *client.Client,
resolvedRepoDetails scm.ResolvedDetails,
accessKey string,
ideService ide.IDE,
) error {
logStreamInstance, err := e.statefulLogger.CreateLogStream(ctx, gitspaceConfig.ID)
containerName := GetGitspaceContainerName(gitspaceConfig)
if err != nil {
return fmt.Errorf("error getting log stream for gitspace instance %s: %w",
gitspaceConfig.GitspaceInstance.Identifier, err)
}
defer e.flushLogStream(logStreamInstance, gitspaceConfig.ID)
remoteUser, lifecycleHooks, err := GetGitspaceInfoFromContainerLabels(ctx, containerName, dockerClient)
if err != nil {
return fmt.Errorf("error getting remote user for gitspace instance %s: %w",
gitspaceConfig.GitspaceInstance.Identifier, err)
}
homeDir := GetUserHomeDir(remoteUser)
startErr := ManageContainer(ctx, ContainerActionStart, containerName, dockerClient, logStreamInstance)
if startErr != nil {
return startErr
}
codeRepoDir := filepath.Join(homeDir, resolvedRepoDetails.RepoName)
exec := &devcontainer.Exec{
ContainerName: containerName,
DockerClient: dockerClient,
DefaultWorkingDir: homeDir,
RemoteUser: remoteUser,
AccessKey: accessKey,
AccessType: gitspaceConfig.GitspaceInstance.AccessType,
}
// Set up git credentials if needed
if resolvedRepoDetails.UserPasswordCredentials != nil {
if err = utils.SetupGitCredentials(ctx, exec, resolvedRepoDetails, logStreamInstance); err != nil {
return err
}
}
// Run IDE setup
runIDEArgs := make(map[gitspaceTypes.IDEArg]any)
runIDEArgs[gitspaceTypes.IDERepoNameArg] = resolvedRepoDetails.RepoName
runIDEArgs = AddIDEDirNameArg(ideService, runIDEArgs)
if err = ideService.Run(ctx, exec, runIDEArgs, logStreamInstance); err != nil {
return err
}
if len(lifecycleHooks) > 0 && len(lifecycleHooks[PostStartAction]) > 0 {
for _, lifecycleHook := range lifecycleHooks[PostStartAction] {
startErr = ExecuteLifecycleCommands(ctx, *exec, codeRepoDir, logStreamInstance,
lifecycleHook.Command.ToCommandArray(), PostStartAction)
if startErr != nil {
log.Warn().Msgf("Error in post-start command, continuing : %s", startErr.Error())
}
}
} else {
// Execute post-start command for the containers before this label was introduced
devcontainerConfig := resolvedRepoDetails.DevcontainerConfig
command := ExtractLifecycleCommands(PostStartAction, devcontainerConfig)
startErr = ExecuteLifecycleCommands(ctx, *exec, codeRepoDir, logStreamInstance, command, PostStartAction)
if startErr != nil {
log.Warn().Msgf("Error in post-start command, continuing : %s", startErr.Error())
}
}
return nil
}
// StopGitspace stops a container. If it is removed, it returns an error.
func (e *EmbeddedDockerOrchestrator) StopGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
infra types.Infrastructure,
) error {
containerName := GetGitspaceContainerName(gitspaceConfig)
logger := log.Ctx(ctx).With().Str(loggingKey, containerName).Logger()
// Step 1: Get Docker client
dockerClient, err := e.getDockerClient(ctx, infra)
if err != nil {
return err
}
defer e.closeDockerClient(dockerClient)
// Step 2: Check the current state of the container
state, err := e.checkContainerState(ctx, dockerClient, containerName)
if err != nil {
return err
}
// Step 3: Handle container states
switch state {
case ContainerStateRemoved:
return fmt.Errorf("gitspace %s is removed", containerName)
case ContainerStateStopped:
logger.Debug().Msg("gitspace is already stopped")
return nil
case ContainerStateRunning:
logger.Debug().Msg("stopping gitspace")
if err = e.stopRunningGitspace(ctx, gitspaceConfig, containerName, dockerClient); err != nil {
return err
}
case ContainerStatePaused, ContainerStateCreated, ContainerStateUnknown, ContainerStateDead:
// TODO handle the following states
return fmt.Errorf("gitspace %s is in a unhandled state: %s", containerName, state)
default:
return fmt.Errorf("gitspace %s is in a bad state: %s", containerName, state)
}
stopResponse := &response.StopResponse{
Status: response.SuccessStatus,
}
err = e.eventReporter.EmitGitspaceOperationsEvent(
ctx,
events.GitspaceOperationsEvent,
&events.GitspaceOperationsEventPayload{
Type: enum.GitspaceOperationsEventStop,
Infra: infra,
Response: stopResponse,
},
)
logger.Debug().Msg("stopped gitspace")
return err
}
// stopRunningGitspace handles stopping the container when it is in a running state.
func (e *EmbeddedDockerOrchestrator) stopRunningGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
containerName string,
dockerClient *client.Client,
) error {
// Step 4: Create log stream for stopping the container
logStreamInstance, err := e.statefulLogger.CreateLogStream(ctx, gitspaceConfig.ID)
if err != nil {
return fmt.Errorf("error getting log stream for gitspace ID %d: %w", gitspaceConfig.ID, err)
}
defer e.flushLogStream(logStreamInstance, gitspaceConfig.ID)
// Step 5: Stop the container
return ManageContainer(ctx, ContainerActionStop, containerName, dockerClient, logStreamInstance)
}
// Status is NOOP for EmbeddedDockerOrchestrator as the docker host is verified by the infra provisioner.
func (e *EmbeddedDockerOrchestrator) Status(_ context.Context, _ types.Infrastructure) error {
return nil
}
// StartAITask is NOOP for EmbeddedDockerOrchestrator as this feature is not present in embedded docker.
func (e *EmbeddedDockerOrchestrator) StartAITask(
_ context.Context, _ types.GitspaceConfig, _ types.Infrastructure, _ types.AITask) error {
return nil
}
// RemoveGitspace force removes the container and the operation is idempotent.
// If the container is already removed, it returns.
func (e *EmbeddedDockerOrchestrator) RemoveGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
infra types.Infrastructure,
canDeleteUserData bool,
) error {
containerName := GetGitspaceContainerName(gitspaceConfig)
logger := log.Ctx(ctx).With().Str(loggingKey, containerName).Logger()
// Step 1: Get Docker client
dockerClient, err := e.getDockerClient(ctx, infra)
if err != nil {
return err
}
defer e.closeDockerClient(dockerClient)
// Step 4: Create logger stream for stopping and removing the container
logStreamInstance, err := e.createLogStream(ctx, gitspaceConfig.ID)
if err != nil {
return err
}
defer e.flushLogStream(logStreamInstance, gitspaceConfig.ID)
logger.Debug().Msg("removing gitspace")
if err = ManageContainer(
ctx, ContainerActionRemove, containerName, dockerClient, logStreamInstance); err != nil {
if client.IsErrNotFound(err) {
logger.Debug().Msg("gitspace is already removed")
} else {
return fmt.Errorf("failed to remove gitspace %s: %w", containerName, err)
}
}
err = e.eventReporter.EmitGitspaceOperationsEvent(
ctx,
events.GitspaceOperationsEvent,
&events.GitspaceOperationsEventPayload{
Type: enum.GitspaceOperationsEventDelete,
Infra: infra,
Response: &response.DeleteResponse{
Status: response.SuccessStatus,
CanDeleteUserData: canDeleteUserData,
},
},
)
logger.Debug().Msg("removed gitspace")
return err
}
func (e *EmbeddedDockerOrchestrator) StreamLogs(
_ context.Context,
_ types.GitspaceConfig,
_ types.Infrastructure) (string, error) {
return "", fmt.Errorf("not implemented")
}
// getAccessKey retrieves the access key from the Gitspace config, returns an error if not found.
func (e *EmbeddedDockerOrchestrator) getAccessKey(gitspaceConfig types.GitspaceConfig) (string, error) {
if gitspaceConfig.GitspaceInstance != nil && gitspaceConfig.GitspaceInstance.AccessKey != nil {
return *gitspaceConfig.GitspaceInstance.AccessKey, nil
}
return "", fmt.Errorf("no access key is configured: %s", gitspaceConfig.Identifier)
}
func (e *EmbeddedDockerOrchestrator) runGitspaceSetupSteps(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
dockerClient *client.Client,
ideService ide.IDE,
infrastructure types.Infrastructure,
resolvedRepoDetails scm.ResolvedDetails,
defaultBaseImage string,
gitspaceLogger gitspaceTypes.GitspaceLogger,
imageAuthMap map[string]gitspaceTypes.DockerRegistryAuth,
) error {
containerName := GetGitspaceContainerName(gitspaceConfig)
devcontainerConfig := resolvedRepoDetails.DevcontainerConfig
imageName := getImage(devcontainerConfig, defaultBaseImage)
runArgsMap, err := ExtractRunArgsWithLogging(ctx, gitspaceConfig.SpaceID, e.runArgProvider,
devcontainerConfig.RunArgs, gitspaceLogger)
if err != nil {
return err
}
// Pull the required image
if err = PullImage(ctx, imageName, dockerClient, runArgsMap, gitspaceLogger, imageAuthMap); err != nil {
return err
}
imageData, err := ExtractImageData(ctx, imageName, dockerClient)
if err != nil {
return err
}
portMappings := infrastructure.GitspacePortMappings
forwardPorts := ExtractForwardPorts(devcontainerConfig)
if len(forwardPorts) > 0 {
for _, port := range forwardPorts {
portMappings[port] = &types.PortMapping{
PublishedPort: port,
ForwardedPort: port,
}
}
gitspaceLogger.Info(fmt.Sprintf("Forwarding ports : %v", forwardPorts))
}
storage := infrastructure.Storage
environment := ExtractEnv(devcontainerConfig, runArgsMap)
if len(environment) > 0 {
gitspaceLogger.Info(fmt.Sprintf("Setting Environment : %v", environment))
}
containerUser := GetContainerUser(runArgsMap, devcontainerConfig, imageData.Metadata, imageData.User)
remoteUser := GetRemoteUser(devcontainerConfig, imageData.Metadata, containerUser)
containerUserHomeDir := GetUserHomeDir(containerUser)
remoteUserHomeDir := GetUserHomeDir(remoteUser)
gitspaceLogger.Info(fmt.Sprintf("Container user: %s", containerUser))
gitspaceLogger.Info(fmt.Sprintf("Remote user: %s", remoteUser))
var features []*types.ResolvedFeature
if devcontainerConfig.Features != nil && len(*devcontainerConfig.Features) > 0 {
sortedFeatures, newImageName, err := InstallFeatures(ctx, gitspaceConfig.GitspaceInstance.Identifier,
dockerClient, *devcontainerConfig.Features, devcontainerConfig.OverrideFeatureInstallOrder, imageName,
containerUser, remoteUser, containerUserHomeDir, remoteUserHomeDir, gitspaceLogger)
if err != nil {
return err
}
features = sortedFeatures
imageName = newImageName
} else {
gitspaceLogger.Info("No features found")
}
// Create the container
lifecycleHookSteps, err := CreateContainer(
ctx,
dockerClient,
imageName,
containerName,
gitspaceLogger,
storage,
remoteUserHomeDir,
mount.TypeVolume,
portMappings,
environment,
runArgsMap,
containerUser,
remoteUser,
features,
resolvedRepoDetails.DevcontainerConfig,
imageData.Metadata,
)
if err != nil {
return err
}
// Start the container
if err = ManageContainer(ctx, ContainerActionStart, containerName, dockerClient, gitspaceLogger); err != nil {
return err
}
// Setup and run commands
exec := &devcontainer.Exec{
ContainerName: containerName,
DockerClient: dockerClient,
DefaultWorkingDir: remoteUserHomeDir,
RemoteUser: remoteUser,
AccessKey: *gitspaceConfig.GitspaceInstance.AccessKey,
AccessType: gitspaceConfig.GitspaceInstance.AccessType,
Arch: imageData.Arch,
OS: imageData.OS,
}
if err = e.setupGitspaceAndIDE(
ctx,
exec,
gitspaceLogger,
ideService,
gitspaceConfig,
resolvedRepoDetails,
defaultBaseImage,
environment,
lifecycleHookSteps,
); err != nil {
return logStreamWrapError(gitspaceLogger, "Error while setting up gitspace", err)
}
return nil
}
func InstallFeatures(
ctx context.Context,
gitspaceInstanceIdentifier string,
dockerClient *client.Client,
features types.Features,
overrideFeatureInstallOrder []string,
imageName string,
containerUser string,
remoteUser string,
containerUserHomeDir string,
remoteUserHomeDir string,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) ([]*types.ResolvedFeature, string, error) {
gitspaceLogger.Info("Downloading features...")
downloadedFeatures, err := utils.DownloadFeatures(ctx, gitspaceInstanceIdentifier, features)
if err != nil {
return nil, "", logStreamWrapError(gitspaceLogger, "Error downloading features", err)
}
gitspaceLogger.Info(fmt.Sprintf("Downloaded %d features", len(*downloadedFeatures)))
gitspaceLogger.Info("Resolving features...")
resolvedFeatures, err := utils.ResolveFeatures(features, *downloadedFeatures)
if err != nil {
return nil, "", logStreamWrapError(gitspaceLogger, "Error resolving features", err)
}
gitspaceLogger.Info(fmt.Sprintf("Resolved to %d features", len(resolvedFeatures)))
gitspaceLogger.Info("Determining feature installation order...")
sortedFeatures, err := utils.SortFeatures(resolvedFeatures, overrideFeatureInstallOrder)
if err != nil {
return nil, "", logStreamWrapError(gitspaceLogger, "Error sorting features", err)
}
gitspaceLogger.Info("Feature installation order is:")
for index, feature := range sortedFeatures {
gitspaceLogger.Info(fmt.Sprintf("%d. %s", index, feature.Print()))
}
gitspaceLogger.Info("Installing features...")
newImageName, dockerFileContent, err := utils.BuildWithFeatures(ctx, dockerClient, imageName, sortedFeatures,
gitspaceInstanceIdentifier, containerUser, remoteUser, containerUserHomeDir, remoteUserHomeDir)
gitspaceLogger.Info(fmt.Sprintf("Using dockerfile%s%s%s", loggingDivider, dockerFileContent, loggingDivider))
if err != nil {
return nil, "", logStreamWrapError(gitspaceLogger, "Error building with features", err)
}
gitspaceLogger.Info(fmt.Sprintf("Installed features, built new docker image %s", newImageName))
return sortedFeatures, newImageName, nil
}
// buildSetupSteps constructs the steps to be executed in the setup process.
func (e *EmbeddedDockerOrchestrator) buildSetupSteps(
ideService ide.IDE,
gitspaceConfig types.GitspaceConfig,
resolvedRepoDetails scm.ResolvedDetails,
defaultBaseImage string,
environment []string,
codeRepoDir string,
lifecycleHookSteps map[PostAction][]*LifecycleHookStep,
) []step {
steps := []step{
{
Name: "Validate Supported OS",
Execute: utils.ValidateSupportedOS,
StopOnFailure: true,
},
{
Name: "Manage User",
Execute: utils.ManageUser,
StopOnFailure: true,
},
{
Name: "Set environment",
Execute: func(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
return utils.SetEnv(ctx, exec, gitspaceLogger, environment)
},
StopOnFailure: true,
},
{
Name: "Install Tools",
Execute: func(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
return utils.InstallTools(ctx, exec, gitspaceConfig.IDE, gitspaceLogger)
},
StopOnFailure: true,
},
{
Name: "Install Git",
Execute: utils.InstallGit,
StopOnFailure: true,
},
{
Name: "Setup Git Credentials",
Execute: func(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
if resolvedRepoDetails.ResolvedCredentials.UserPasswordCredentials != nil {
return utils.SetupGitCredentials(ctx, exec, resolvedRepoDetails, gitspaceLogger)
}
return nil
},
StopOnFailure: true,
},
{
Name: "Clone Code",
Execute: func(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
return utils.CloneCode(ctx, exec, resolvedRepoDetails, defaultBaseImage, gitspaceLogger)
},
StopOnFailure: true,
},
{
Name: "Install AI agents",
Execute: func(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
return utils.InstallAIAgents(ctx, exec, gitspaceLogger, gitspaceConfig.AIAgents)
},
StopOnFailure: true,
},
{
Name: "Setup IDE",
Execute: func(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
// Run IDE setup
args := make(map[gitspaceTypes.IDEArg]any)
args = AddIDECustomizationsArg(ideService, resolvedRepoDetails.DevcontainerConfig, args)
args[gitspaceTypes.IDERepoNameArg] = resolvedRepoDetails.RepoName
args = AddIDEDownloadURLArg(ideService, args)
args = AddIDEDirNameArg(ideService, args)
return ideService.Setup(ctx, exec, args, gitspaceLogger)
},
StopOnFailure: true,
},
{
Name: "Run IDE",
Execute: func(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
args := make(map[gitspaceTypes.IDEArg]any)
args[gitspaceTypes.IDERepoNameArg] = resolvedRepoDetails.RepoName
args = AddIDEDirNameArg(ideService, args)
return ideService.Run(ctx, exec, args, gitspaceLogger)
},
StopOnFailure: true,
}}
// Add the postCreateCommand lifecycle hooks to the steps
for _, lifecycleHook := range lifecycleHookSteps[PostCreateAction] {
steps = append(steps, step{
Name: fmt.Sprintf("Execute postCreateCommand from %s", lifecycleHook.Source),
Execute: func(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
return ExecuteLifecycleCommands(ctx, *exec, codeRepoDir, gitspaceLogger,
lifecycleHook.Command.ToCommandArray(), PostCreateAction)
},
StopOnFailure: lifecycleHook.StopOnFailure,
})
}
// Add the postStartCommand lifecycle hooks to the steps
for _, lifecycleHook := range lifecycleHookSteps[PostStartAction] {
steps = append(steps, step{
Name: fmt.Sprintf("Execute postStartCommand from %s", lifecycleHook.Source),
Execute: func(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
return ExecuteLifecycleCommands(ctx, *exec, codeRepoDir, gitspaceLogger,
lifecycleHook.Command.ToCommandArray(), PostStartAction)
},
StopOnFailure: lifecycleHook.StopOnFailure,
})
}
return steps
}
// setupGitspaceAndIDE initializes Gitspace and IdeType by registering and executing the setup steps.
func (e *EmbeddedDockerOrchestrator) setupGitspaceAndIDE(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger gitspaceTypes.GitspaceLogger,
ideService ide.IDE,
gitspaceConfig types.GitspaceConfig,
resolvedRepoDetails scm.ResolvedDetails,
defaultBaseImage string,
environment []string,
lifecycleHookSteps map[PostAction][]*LifecycleHookStep,
) error {
homeDir := GetUserHomeDir(exec.RemoteUser)
codeRepoDir := filepath.Join(homeDir, resolvedRepoDetails.RepoName)
steps := e.buildSetupSteps(
ideService,
gitspaceConfig,
resolvedRepoDetails,
defaultBaseImage,
environment,
codeRepoDir,
lifecycleHookSteps,
)
// Execute the registered steps
if err := e.ExecuteSteps(ctx, exec, gitspaceLogger, steps); err != nil {
return err
}
return nil
}
// getDockerClient creates and returns a new Docker client using the factory.
func (e *EmbeddedDockerOrchestrator) getDockerClient(
ctx context.Context,
infra types.Infrastructure,
) (*client.Client, error) {
dockerClient, err := e.dockerClientFactory.NewDockerClient(ctx, infra)
if err != nil {
return nil, fmt.Errorf("error getting docker client from docker client factory: %w", err)
}
return dockerClient, nil
}
// closeDockerClient safely closes the Docker client.
func (e *EmbeddedDockerOrchestrator) closeDockerClient(dockerClient *client.Client) {
if err := dockerClient.Close(); err != nil {
log.Warn().Err(err).Msg("failed to close docker client")
}
}
// checkContainerState checks the current state of the Docker container.
func (e *EmbeddedDockerOrchestrator) checkContainerState(
ctx context.Context,
dockerClient *client.Client,
containerName string,
) (State, error) {
log.Debug().Msg("checking current state of gitspace")
state, err := FetchContainerState(ctx, containerName, dockerClient)
if err != nil {
return "", err
}
return state, nil
}
// createAndStartNewGitspace creates a new Gitspace if it was removed.
func (e *EmbeddedDockerOrchestrator) createAndStartNewGitspace(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
dockerClient *client.Client,
resolvedRepoDetails scm.ResolvedDetails,
infrastructure types.Infrastructure,
defaultBaseImage string,
ideService ide.IDE,
imageAuthMap map[string]gitspaceTypes.DockerRegistryAuth,
) error {
logStreamInstance, err := e.statefulLogger.CreateLogStream(ctx, gitspaceConfig.ID)
if err != nil {
return fmt.Errorf("error getting log stream for gitspace ID %d: %w", gitspaceConfig.ID, err)
}
defer e.flushLogStream(logStreamInstance, gitspaceConfig.ID)
startErr := e.runGitspaceSetupSteps(
ctx,
gitspaceConfig,
dockerClient,
ideService,
infrastructure,
resolvedRepoDetails,
defaultBaseImage,
logStreamInstance,
imageAuthMap,
)
if startErr != nil {
return fmt.Errorf("failed to start gitspace %s: %w", gitspaceConfig.Identifier, startErr)
}
return nil
}
// createLogStream creates and returns a log stream for the given gitspace ID.
func (e *EmbeddedDockerOrchestrator) createLogStream(
ctx context.Context,
gitspaceID int64,
) (*logutil.LogStreamInstance, error) {
logStreamInstance, err := e.statefulLogger.CreateLogStream(ctx, gitspaceID)
if err != nil {
return nil, fmt.Errorf("error getting log stream for gitspace ID %d: %w", gitspaceID, err)
}
return logStreamInstance, nil
}
func (e *EmbeddedDockerOrchestrator) flushLogStream(logStreamInstance *logutil.LogStreamInstance, gitspaceID int64) {
if err := logStreamInstance.Flush(); err != nil {
log.Warn().Err(err).Msgf("failed to flush log stream for gitspace ID %d", gitspaceID)
}
}
func getImage(devcontainerConfig types.DevcontainerConfig, defaultBaseImage string) string {
imageName := devcontainerConfig.Image
if imageName == "" {
imageName = defaultBaseImage
}
return imageName
}
func (e *EmbeddedDockerOrchestrator) RetryCreateAndStartGitspaceIfRequired(_ context.Context) {
// Nothing to do here as the event will be published from CreateAndStartGitspace itself.
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/response/start.go | app/gitspace/orchestrator/container/response/start.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package response
type StartResponse struct {
ContainerID string `json:"container_id"`
Status Status `json:"status"`
ErrMessage string `json:"err_message"`
ContainerName string `json:"container_name"`
PublishedPorts map[int]string `json:"published_ports"`
AbsoluteRepoPath string `json:"absolute_repo_path"`
RemoteUser string `json:"remote_user"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/response/stop.go | app/gitspace/orchestrator/container/response/stop.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package response
type StopResponse struct {
Status Status `json:"status"`
ErrMessage string `json:"err_message"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/response/status.go | app/gitspace/orchestrator/container/response/status.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package response
type Status string
const (
SuccessStatus Status = "success"
FailureStatus Status = "failure"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/container/response/delete.go | app/gitspace/orchestrator/container/response/delete.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package response
type DeleteResponse struct {
Status Status `json:"status"`
ErrMessage string `json:"err_message"`
CanDeleteUserData bool `json:"can_delete_user_data"`
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/git.go | app/gitspace/orchestrator/utils/git.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"context"
"fmt"
"net/url"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
"github.com/harness/gitness/app/gitspace/scm"
"github.com/harness/gitness/app/gitspace/types"
)
func InstallGit(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger types.GitspaceLogger,
) error {
script, err := GenerateScriptFromTemplate(
templateGitInstallScript, &types.SetupGitInstallPayload{
OSInfoScript: GetOSInfoScript(),
})
if err != nil {
return fmt.Errorf(
"failed to generate scipt to setup git install from template %s: %w", templateGitInstallScript, err)
}
gitspaceLogger.Info("Install git output...")
gitspaceLogger.Info("Setting up git inside container")
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, true, gitspaceLogger, false)
if err != nil {
return fmt.Errorf("failed to setup git: %w", err)
}
gitspaceLogger.Info("Successfully setup git")
return nil
}
func SetupGitCredentials(
ctx context.Context,
exec *devcontainer.Exec,
resolvedRepoDetails scm.ResolvedDetails,
gitspaceLogger types.GitspaceLogger,
) error {
script, err := GenerateScriptFromTemplate(
templateSetupGitCredentials, &types.SetupGitCredentialsPayload{
CloneURLWithCreds: resolvedRepoDetails.CloneURL.Value(),
})
if err != nil {
return fmt.Errorf(
"failed to generate scipt to setup git credentials from template %s: %w", templateSetupGitCredentials, err)
}
gitspaceLogger.Info("Setting up git credentials output...")
gitspaceLogger.Info("Setting up git credentials inside container")
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, false, gitspaceLogger, true)
if err != nil {
return fmt.Errorf("failed to setup git credentials: %w", err)
}
gitspaceLogger.Info("Successfully setup git credentials")
return nil
}
func CloneCode(
ctx context.Context,
exec *devcontainer.Exec,
resolvedRepoDetails scm.ResolvedDetails,
defaultBaseImage string,
gitspaceLogger types.GitspaceLogger,
) error {
cloneURL, err := url.Parse(resolvedRepoDetails.CloneURL.Value())
if err != nil {
return fmt.Errorf(
"failed to parse clone url %s: %w", resolvedRepoDetails.CloneURL, err)
}
cloneURL.User = nil
data := &types.CloneCodePayload{
RepoURL: cloneURL.String(),
Image: defaultBaseImage,
Branch: resolvedRepoDetails.Branch,
RepoName: resolvedRepoDetails.RepoName,
}
if resolvedRepoDetails.ResolvedCredentials.UserPasswordCredentials != nil {
data.Email = resolvedRepoDetails.UserPasswordCredentials.Email
data.Name = resolvedRepoDetails.UserPasswordCredentials.Name.Value()
}
script, err := GenerateScriptFromTemplate(
templateCloneCode, data)
if err != nil {
return fmt.Errorf(
"failed to generate scipt to clone code from template %s: %w", templateCloneCode, err)
}
gitspaceLogger.Info(fmt.Sprintf("Cloning repository: %s inside container...", resolvedRepoDetails.RepoName))
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, false, gitspaceLogger, true)
if err != nil {
return fmt.Errorf("failed to clone code: %w", err)
}
gitspaceLogger.Info(fmt.Sprintf("Successfully cloned repository: %s", resolvedRepoDetails.RepoName))
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/tools.go | app/gitspace/orchestrator/utils/tools.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"context"
"fmt"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
"github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/types/enum"
)
func InstallTools(
ctx context.Context,
exec *devcontainer.Exec,
ideType enum.IDEType,
gitspaceLogger types.GitspaceLogger,
) error {
switch ideType {
case enum.IDETypeVSCodeWeb:
err := InstallToolsForVsCodeWeb(ctx, exec, gitspaceLogger)
if err != nil {
return err
}
return nil
case enum.IDETypeVSCode:
err := InstallToolsForVsCode(ctx, exec, gitspaceLogger)
if err != nil {
return err
}
return nil
case enum.IDETypeCursor:
err := InstallToolsForCursor(ctx, exec, gitspaceLogger)
if err != nil {
return err
}
return nil
case enum.IDETypeWindsurf:
err := InstallToolsForWindsurf(ctx, exec, gitspaceLogger)
if err != nil {
return err
}
return nil
case enum.IDETypeIntelliJ, enum.IDETypePyCharm, enum.IDETypeGoland, enum.IDETypeWebStorm, enum.IDETypeCLion,
enum.IDETypePHPStorm, enum.IDETypeRubyMine, enum.IDETypeRider:
err := InstallToolsForJetBrains(ctx, exec, ideType, gitspaceLogger)
if err != nil {
return err
}
return nil
}
return nil
}
func InstallToolsForVsCodeWeb(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger types.GitspaceLogger,
) error {
script, err := GenerateScriptFromTemplate(
templateVsCodeWebToolsInstallation, &types.InstallToolsPayload{
OSInfoScript: osDetectScript,
})
if err != nil {
return fmt.Errorf(
"failed to generate scipt to install tools for vs code web from template %s: %w",
templateVsCodeWebToolsInstallation, err)
}
gitspaceLogger.Info("Installing tools for vs code web inside container")
gitspaceLogger.Info("Tools installation output...")
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, true, gitspaceLogger, false)
if err != nil {
return fmt.Errorf("failed to install tools for vs code web: %w", err)
}
gitspaceLogger.Info("Successfully installed tools for vs code web")
return nil
}
func InstallToolsForVsCode(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger types.GitspaceLogger,
) error {
script, err := GenerateScriptFromTemplate(
templateVsCodeToolsInstallation, &types.InstallToolsPayload{
OSInfoScript: osDetectScript,
})
if err != nil {
return fmt.Errorf(
"failed to generate scipt to install tools for vs code from template %s: %w",
templateVsCodeToolsInstallation, err)
}
gitspaceLogger.Info("Installing tools for vs code in container")
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, true, gitspaceLogger, false)
if err != nil {
return fmt.Errorf("failed to install tools for vs code: %w", err)
}
gitspaceLogger.Info("Successfully installed tools for vs code")
return nil
}
func InstallToolsForJetBrains(
ctx context.Context,
exec *devcontainer.Exec,
ideType enum.IDEType,
gitspaceLogger types.GitspaceLogger,
) error {
script, err := GenerateScriptFromTemplate(
templateIntellijToolsInstallation, &types.InstallToolsPayload{
OSInfoScript: osDetectScript,
})
if err != nil {
return fmt.Errorf(
"failed to generate scipt to install tools for %s from template %s: %w",
ideType, templateIntellijToolsInstallation, err)
}
gitspaceLogger.Info(fmt.Sprintf("Installing tools for %s in container", ideType))
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, true, gitspaceLogger, false)
if err != nil {
return fmt.Errorf("failed to install tools for %s: %w", ideType, err)
}
gitspaceLogger.Info(fmt.Sprintf("Successfully installed tools for %s in container", ideType))
return nil
}
func InstallToolsForWindsurf(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger types.GitspaceLogger,
) error {
script, err := GenerateScriptFromTemplate(
templateWindsurfToolsInstallation, &types.InstallToolsPayload{
OSInfoScript: osDetectScript,
})
if err != nil {
return fmt.Errorf(
"failed to generate scipt to install tools for windsurf from template %s: %w",
templateWindsurfToolsInstallation, err)
}
gitspaceLogger.Info("Installing tools for windsurf in container")
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, true, gitspaceLogger, false)
if err != nil {
return fmt.Errorf("failed to install tools for windsurf: %w", err)
}
gitspaceLogger.Info("Successfully installed tools for windsurf")
return nil
}
func InstallToolsForCursor(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger types.GitspaceLogger,
) error {
script, err := GenerateScriptFromTemplate(
templateCursorToolsInstallation, &types.InstallToolsPayload{
OSInfoScript: osDetectScript,
})
if err != nil {
return fmt.Errorf(
"failed to generate scipt to install tools for cursor from template %s: %w",
templateCursorToolsInstallation, err)
}
gitspaceLogger.Info("Installing tools for cursor in container")
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, true, gitspaceLogger, false)
if err != nil {
return fmt.Errorf("failed to install tools for cursor: %w", err)
}
gitspaceLogger.Info("Successfully installed tools for cursor")
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/build_with_features.go | app/gitspace/orchestrator/utils/build_with_features.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"archive/tar"
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/harness/gitness/types"
dockerTypes "github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/rs/zerolog/log"
)
// convertOptionsToEnvVariables converts the option keys to standardised env variables using the
// devcontainer specification to ensure uniformity in the naming and casing of the env variables.
// eg: 217yat%_fg -> _YAT_FG
// Reference: https://containers.dev/implementors/features/#option-resolution
func convertOptionsToEnvVariables(str string) string {
// Replace all non-alphanumeric characters (excluding underscores) with '_'
reNonAlnum := regexp.MustCompile(`[^\w_]`)
str = reNonAlnum.ReplaceAllString(str, "_")
// Replace leading digits or underscores with a single '_'
reLeadingDigitsOrUnderscores := regexp.MustCompile(`^[\d_]+`)
str = reLeadingDigitsOrUnderscores.ReplaceAllString(str, "_")
// Convert the string to uppercase
str = strings.ToUpper(str)
return str
}
// BuildWithFeatures builds a docker image using the provided image as the base image.
// It sets some common env variables using the ARG instruction.
// For every feature, it copies the containerEnv variables using the ENV instruction and passes the resolved options
// as env variables in the RUN instruction. It further executes the install script.
func BuildWithFeatures(
ctx context.Context,
dockerClient *client.Client,
imageName string,
features []*types.ResolvedFeature,
gitspaceInstanceIdentifier string,
containerUser string,
remoteUser string,
containerUserHomeDir string,
remoteUserHomeDir string,
) (string, string, error) {
buildContextPath := getGitspaceInstanceDirectory(gitspaceInstanceIdentifier)
defer func() {
err := os.RemoveAll(buildContextPath)
if err != nil {
log.Ctx(ctx).Err(err).Msgf("failed to remove build context directory %s", buildContextPath)
}
}()
dockerFileContent, err := generateDockerFileWithFeatures(imageName, features, buildContextPath, containerUser,
containerUserHomeDir, remoteUser, remoteUserHomeDir)
if err != nil {
return "", "", err
}
buildContext, err := packBuildContextDirectory(buildContextPath)
if err != nil {
return "", dockerFileContent, err
}
newImageName := "gitspace-with-features:" + gitspaceInstanceIdentifier
buildRes, imageBuildErr := dockerClient.ImageBuild(ctx, buildContext, dockerTypes.ImageBuildOptions{
SuppressOutput: false,
Tags: []string{newImageName},
Version: dockerTypes.BuilderBuildKit,
})
defer func() {
if buildRes.Body != nil {
closeErr := buildRes.Body.Close()
if closeErr != nil {
log.Ctx(ctx).Err(closeErr).Msg("failed to close docker image build response body")
}
}
}()
if imageBuildErr != nil {
return "", dockerFileContent, imageBuildErr
}
_, err = io.Copy(io.Discard, buildRes.Body)
if err != nil {
return "", dockerFileContent, err
}
imagePresentLocally, err := IsImagePresentLocally(ctx, newImageName, dockerClient)
if err != nil {
return "", dockerFileContent, err
}
if !imagePresentLocally {
return "", dockerFileContent, fmt.Errorf("error during docker build, image %s not present", newImageName)
}
return newImageName, dockerFileContent, nil
}
func packBuildContextDirectory(path string) (io.Reader, error) {
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
err := filepath.Walk(path, func(file string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := tar.FileInfoHeader(fi, file)
if err != nil {
return err
}
header.Name, err = filepath.Rel(path, file)
if err != nil {
return err
}
if err := tw.WriteHeader(header); err != nil {
return err
}
if fi.Mode().IsRegular() {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(tw, f)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to walk path %q: %w", path, err)
}
if err := tw.Close(); err != nil {
return nil, fmt.Errorf("failed to close tar writer: %w", err)
}
return &buf, nil
}
// generateDockerFileWithFeatures creates and saves a dockerfile inside the build context directory.
func generateDockerFileWithFeatures(
imageName string,
features []*types.ResolvedFeature,
buildContextPath string,
containerUser string,
remoteUser string,
containerUserHomeDir string,
remoteUserHomeDir string,
) (string, error) {
dockerFile := fmt.Sprintf(`FROM %s
ARG %s=%s
ARG %s=%s
ARG %s=%s
ARG %s=%s
COPY ./devcontainer-features %s`,
imageName, convertOptionsToEnvVariables("_CONTAINER_USER"), containerUser,
convertOptionsToEnvVariables("_REMOTE_USER"), remoteUser,
convertOptionsToEnvVariables("_CONTAINER_USER_HOME"), containerUserHomeDir,
convertOptionsToEnvVariables("_REMOTE_USER_HOME"), remoteUserHomeDir,
"/tmp/devcontainer-features")
for _, feature := range features {
if len(feature.DownloadedFeature.DevcontainerFeatureConfig.ContainerEnv) > 0 {
envVariables := ""
for key, value := range feature.DownloadedFeature.DevcontainerFeatureConfig.ContainerEnv {
envVariables += " " + key + "=" + value
}
dockerFile += fmt.Sprintf("\nENV%s", envVariables)
}
finalOptionsMap := make(map[string]string)
for key, value := range feature.ResolvedOptions {
finalOptionsMap[convertOptionsToEnvVariables(key)] = value
}
optionEnvVariables := ""
for key, value := range finalOptionsMap {
optionEnvVariables += " " + key + "=" + value
}
installScriptPath := filepath.Join("/tmp/devcontainer-features",
getFeatureFolderNameWithTag(feature.DownloadedFeature.FeatureFolderName, feature.DownloadedFeature.Tag),
feature.DownloadedFeature.FeatureFolderName, "install.sh")
dockerFile += fmt.Sprintf("\nRUN%s chmod +x %s && %s",
optionEnvVariables, installScriptPath, installScriptPath)
}
log.Debug().Msgf("generated dockerfile for build context %s\n%s", buildContextPath, dockerFile)
file, err := os.OpenFile(filepath.Join(buildContextPath, "Dockerfile"), os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return "", fmt.Errorf("failed to create Dockerfile: %w", err)
}
defer file.Close()
_, err = file.WriteString(dockerFile)
if err != nil {
return "", fmt.Errorf("failed to write content to Dockerfile: %w", err)
}
return dockerFile, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/script_template.go | app/gitspace/orchestrator/utils/script_template.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"bytes"
"embed"
"fmt"
"io/fs"
"path"
"text/template"
)
const (
ScriptTemplatesDir = "script_templates"
)
var (
//go:embed script_templates/*
files embed.FS
scriptTemplates map[string]*template.Template
)
func init() {
err := LoadTemplates()
if err != nil {
panic(fmt.Sprintf("error loading script templates: %v", err))
}
}
func LoadTemplates() error {
scriptTemplates = make(map[string]*template.Template)
tmplFiles, err := fs.ReadDir(files, ScriptTemplatesDir)
if err != nil {
return fmt.Errorf("error reading script templates: %w", err)
}
for _, tmpl := range tmplFiles {
if tmpl.IsDir() {
continue
}
textTemplate, parsingErr := template.ParseFS(files, path.Join(ScriptTemplatesDir, tmpl.Name()))
if parsingErr != nil {
return fmt.Errorf("error parsing template %s: %w", tmpl.Name(), parsingErr)
}
scriptTemplates[tmpl.Name()] = textTemplate
}
return nil
}
func GenerateScriptFromTemplate(name string, data any) (string, error) {
if scriptTemplates[name] == nil {
return "", fmt.Errorf("no script template found for %s", name)
}
tmplOutput := bytes.Buffer{}
err := scriptTemplates[name].Execute(&tmplOutput, data)
if err != nil {
return "", fmt.Errorf("error executing template %s with data %+v: %w", name, data, err)
}
return tmplOutput.String(), nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/image.go | app/gitspace/orchestrator/utils/image.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"context"
"regexp"
"strings"
"github.com/docker/distribution/reference"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/client"
"github.com/rs/zerolog/log"
)
func IsImagePresentLocally(ctx context.Context, imageName string, dockerClient *client.Client) (bool, error) {
filterArgs := filters.NewArgs()
filterArgs.Add("reference", imageName)
images, err := dockerClient.ImageList(ctx, image.ListOptions{Filters: filterArgs})
if err != nil {
return false, err
}
return len(images) > 0, nil
}
// Image Expression Classification types.
const (
ExpressionTypeInvalid = "invalid"
ExpressionTypeRepository = "repository"
ExpressionTypeImageTag = "image (tag)"
ExpressionTypeImageDigest = "image (digest)"
ExpressionTypeWildcardTag = "wildcard image (tag)"
ExpressionTypeWildcardRepo = "wildcard (repo)"
ExpressionTypeWildcardRepoPrefix = "wildcard (repo-prefix)"
ExpressionTypeWildcardTagPrefix = "wildcard image (tag-prefix)"
)
func CheckContainerImageExpression(input string) string {
// Reject wildcard not at the end
if idx := strings.IndexByte(input, '*'); idx != -1 && idx != len(input)-1 {
return ExpressionTypeInvalid
}
switch {
case strings.HasSuffix(input, "/*"):
return classifyWildcardRepo(input)
case strings.HasSuffix(input, ":*"):
return classifyWildcardTag(input)
case strings.HasSuffix(input, "*"):
if strings.Contains(input, ":") {
return classifyWildcardTagPrefix(input)
}
return classifyWildcardRepoPrefix(input)
default:
return classifyStandardImage(input)
}
}
func classifyWildcardRepo(input string) string {
base := strings.TrimSuffix(input, "/*")
if _, err := reference.ParseAnyReference(base); err == nil {
return ExpressionTypeWildcardRepo
}
return ExpressionTypeInvalid
}
func classifyWildcardTag(input string) string {
base := strings.TrimSuffix(input, ":*")
if _, err := reference.ParseAnyReference(base); err == nil {
return ExpressionTypeWildcardTag
}
return ExpressionTypeInvalid
}
func classifyWildcardTagPrefix(input string) string {
colonIndex := strings.LastIndex(input, ":")
if colonIndex == -1 {
return ExpressionTypeInvalid
}
repo := input[:colonIndex]
tag := input[colonIndex+1:]
if !strings.HasSuffix(tag, "*") {
return ExpressionTypeInvalid
}
tagPrefix := strings.TrimSuffix(tag, "*")
if !isValidTag(tagPrefix) {
log.Warn().Str("tag", tagPrefix).Msg("Invalid tag prefix")
return ExpressionTypeInvalid
}
if _, err := reference.ParseAnyReference(repo); err == nil {
return ExpressionTypeWildcardTagPrefix
}
log.Error().Msgf("invalid repository in tag prefix: %s", repo)
return ExpressionTypeInvalid
}
func classifyWildcardRepoPrefix(input string) string {
base := strings.TrimSuffix(input, "*")
if _, err := reference.ParseAnyReference(base); err == nil {
return ExpressionTypeWildcardRepoPrefix
}
return ExpressionTypeInvalid
}
func classifyStandardImage(input string) string {
ref, err := reference.ParseAnyReference(input)
if err != nil {
return ExpressionTypeInvalid
}
switch ref.(type) {
case reference.Canonical:
return ExpressionTypeImageDigest
case reference.Tagged:
return ExpressionTypeImageTag
case reference.Named:
return ExpressionTypeRepository
default:
return ExpressionTypeInvalid
}
}
var tagRegexp = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$`)
func isValidTag(tag string) bool {
return tagRegexp.MatchString(tag)
}
func MatchesContainerImageExpression(expr, image string) bool {
switch CheckContainerImageExpression(expr) {
case ExpressionTypeImageDigest, ExpressionTypeImageTag:
return expr == image
case ExpressionTypeRepository:
return getRepo(image) == expr
case ExpressionTypeWildcardRepo:
return strings.HasPrefix(getRepo(image), strings.TrimSuffix(expr, "/*")+"/")
case ExpressionTypeWildcardTag:
repoExpr := strings.TrimSuffix(expr, ":*")
repo, tag := splitImage(image)
return repo == repoExpr && tag != ""
case ExpressionTypeWildcardRepoPrefix:
return strings.HasPrefix(getRepo(image), strings.TrimSuffix(expr, "*"))
case ExpressionTypeWildcardTagPrefix:
colon := strings.LastIndex(expr, ":")
if colon == -1 {
return false
}
repoExpr := expr[:colon]
tagPrefix := strings.TrimSuffix(expr[colon+1:], "*")
repo, tag := splitImage(image)
return repo == repoExpr && strings.HasPrefix(tag, tagPrefix)
default:
return false
}
}
func getRepo(image string) string {
if i := strings.IndexAny(image, "@:"); i != -1 {
return image[:i]
}
return image
}
func splitImage(image string) (repo, tag string) {
if i := strings.LastIndex(image, ":"); i != -1 && !strings.Contains(image[i:], "/") {
return image[:i], image[i+1:]
}
return image, ""
}
func IsValidContainerImage(image string) bool {
_, err := reference.ParseAnyReference(image)
return err == nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/image_test.go | app/gitspace/orchestrator/utils/image_test.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"testing"
)
func TestCheckContainerImageExpression(t *testing.T) {
tests := []struct {
input string
expected string
}{
// Valid expressions
{"nginx", ExpressionTypeRepository},
{"nginx:latest", ExpressionTypeImageTag},
{"nginx@sha256:01eb582bca526c37aad8dbc5c9ba69899ecf2540f561694979d153bcbbf146fe",
ExpressionTypeImageDigest},
{"repo/*", ExpressionTypeWildcardRepo},
{"repo/image:*", ExpressionTypeWildcardTag},
{"repo/image:dev*", ExpressionTypeWildcardTagPrefix},
{"repo/image*", ExpressionTypeWildcardRepoPrefix},
// Invalid expressions
{"nginx:*:latest", ExpressionTypeInvalid},
{"nginx:*latest", ExpressionTypeInvalid},
{"nginx:lat*est", ExpressionTypeInvalid},
{"*nginx:latest", ExpressionTypeInvalid},
{"invalid@@@", ExpressionTypeInvalid},
{"repo/image:!invalid", ExpressionTypeInvalid},
{"repo/image:prefix*", ExpressionTypeWildcardTagPrefix},
{"mcr.microsoft.com/devcontainers/", ExpressionTypeInvalid},
}
for _, test := range tests {
t.Run(test.input, func(t *testing.T) {
actual := CheckContainerImageExpression(test.input)
if actual != test.expected {
t.Errorf("CheckContainerImageExpression(%q) = %q, want %q", test.input, actual, test.expected)
}
})
}
}
func TestMatchesContainerImageExpression(t *testing.T) {
tests := []struct {
expr string
image string
expected bool
}{
// Exact image tag
{"nginx:latest", "nginx:latest", true},
{"nginx:1.19", "nginx:latest", false},
// Image digest
{"nginx@sha256:01eb582bca526c37aad8dbc5c9ba69899ecf2540f561694979d153bcbbf146fe",
"nginx@sha256:01eb582bca526c37aad8dbc5c9ba69899ecf2540f561694979d153bcbbf146fe", true},
{"nginx@sha256:abc123", "nginx@sha256:def456", false},
// Repository match
{"nginx", "nginx:latest", true},
{"nginx", "nginx@sha256:abc123", true},
{"nginx", "nginx", true},
// Wildcard repo
{"repo/*", "repo/app:tag", true},
{"repo/*", "repo/sub/app:tag", true},
{"repo/*", "other/image:tag", false},
// Wildcard tag
{"repo/image:*", "repo/image:latest", true},
{"repo/image:*", "repo/image:v1.0", true},
{"repo/image:*", "repo/image", false},
{"repo/image:*", "repo/image@sha256:abc", false},
// Wildcard tag prefix
{"repo/image:dev*", "repo/image:dev123", true},
{"repo/image:dev*", "repo/image:dev", true},
{"repo/image:dev*", "repo/image:prod", false},
{"repo/image:dev*", "other/image:dev123", false},
// Wildcard repo prefix
{"repo/image*", "repo/image:tag", true},
{"repo/image*", "repo/image-extra:tag", true},
{"repo/image*", "repo/image/child:tag", true},
{"repo/image*", "other/image:tag", false},
// Invalid expression
{"nginx:*latest", "nginx:latest", false},
{"mcr.microsoft.com/devcontainers/", "mcr.microsoft.com/devcontainers/python:latest", false},
// Valid wildcard repo correction
{"mcr.microsoft.com/devcontainers/*",
"mcr.microsoft.com/devcontainers/python:latest", true},
{"mcr.microsoft.com/devcontainers/",
"mcr.microsoft.com/devcontainers/python:latest", false},
{"mcr.microsoft.com/devcontainers/python",
"mcr.microsoft.com/devcontainers/python:latest", true},
{"mcr.microsoft.com/devcontainers/python/",
"mcr.microsoft.com/devcontainers/python:latest", false},
{"mcr.microsoft.com/devcontainers/python/*",
"mcr.microsoft.com/devcontainers/python:latest", false},
{"mcr.microsoft.com/devcontainers/python/*",
"mcr.microsoft.com/devcontainers/python/image:latest", true},
{"mcr.microsoft.com/devcontainers/python:*",
"mcr.microsoft.com/devcontainers/python:latest", true},
}
for _, test := range tests {
name := test.expr + " matches " + test.image
t.Run(name, func(t *testing.T) {
actual := MatchesContainerImageExpression(test.expr, test.image)
if actual != test.expected {
t.Errorf("MatchesContainerImageExpression(%q, %q) = %v, want %v", test.expr, test.image, actual, test.expected)
}
})
}
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/secret.go | app/gitspace/orchestrator/utils/secret.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"context"
"fmt"
"github.com/harness/gitness/app/gitspace/secret"
"github.com/harness/gitness/app/gitspace/secret/enum"
"github.com/harness/gitness/app/paths"
"github.com/harness/gitness/types"
gitnessenum "github.com/harness/gitness/types/enum"
)
func ResolveSecret(ctx context.Context, secretResolverFactory *secret.ResolverFactory, config types.GitspaceConfig) (
*string,
error,
) {
rootSpaceID, _, err := paths.DisectRoot(config.SpacePath)
if err != nil {
return nil, fmt.Errorf("unable to find root space id from space path: %s", config.SpacePath)
}
secretType := GetSecretType(config.GitspaceInstance.AccessType)
secretResolver, err := secretResolverFactory.GetSecretResolver(secretType)
if err != nil {
return nil, fmt.Errorf("could not find secret resolver for type: %s", config.GitspaceInstance.AccessType)
}
resolvedSecret, err := secretResolver.Resolve(ctx, secret.ResolutionContext{
UserIdentifier: config.GitspaceUser.Identifier,
GitspaceIdentifier: config.Identifier,
SecretRef: *config.GitspaceInstance.AccessKeyRef,
SpaceIdentifier: rootSpaceID,
})
if err != nil {
return nil, fmt.Errorf(
"could not resolve secret type: %s, ref: %s : %w",
config.GitspaceInstance.AccessType,
*config.GitspaceInstance.AccessKeyRef,
err,
)
}
return &resolvedSecret.SecretValue, nil
}
func GetSecretType(accessType gitnessenum.GitspaceAccessType) enum.SecretType {
secretType := enum.PasswordSecretType
switch accessType {
case gitnessenum.GitspaceAccessTypeUserCredentials:
secretType = enum.PasswordSecretType
case gitnessenum.GitspaceAccessTypeJWTToken:
secretType = enum.JWTSecretType
case gitnessenum.GitspaceAccessTypeSSHKey:
secretType = enum.SSHSecretType
}
return secretType
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/environment.go | app/gitspace/orchestrator/utils/environment.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"context"
"fmt"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
"github.com/harness/gitness/app/gitspace/types"
_ "embed"
)
const (
templateSupportedOSDistribution = "supported_os_distribution.sh"
templateVsCodeWebToolsInstallation = "install_tools_vs_code_web.sh"
templateVsCodeToolsInstallation = "install_tools_vs_code.sh"
templateIntellijToolsInstallation = "install_tools_intellij.sh"
templateWindsurfToolsInstallation = "install_tools_windsurf.sh"
templateCursorToolsInstallation = "install_tools_cursor.sh"
templateSetEnv = "set_env.sh"
templateGitInstallScript = "install_git.sh"
templateSetupGitCredentials = "setup_git_credentials.sh" // nolint:gosec
templateCloneCode = "clone_code.sh"
templateManagerUser = "manage_user.sh"
)
//go:embed script/os_info.sh
var osDetectScript string
func GetOSInfoScript() (script string) {
return osDetectScript
}
func ValidateSupportedOS(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger types.GitspaceLogger,
) error {
// TODO: Currently not supporting arch, freebsd and alpine.
// For alpine wee need to install multiple things from
// https://github.com/microsoft/vscode/wiki/How-to-Contribute#prerequisites
script, err := GenerateScriptFromTemplate(
templateSupportedOSDistribution, &types.SupportedOSDistributionPayload{
OSInfoScript: osDetectScript,
})
if err != nil {
return fmt.Errorf("failed to generate scipt to validate supported os distribution from template %s: %w",
templateSupportedOSDistribution, err)
}
gitspaceLogger.Info("Validate supported OSes...")
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, true, gitspaceLogger, false)
if err != nil {
return fmt.Errorf("error while detecting os distribution: %w", err)
}
return nil
}
func SetEnv(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger types.GitspaceLogger,
environment []string,
) error {
if len(environment) > 0 {
script, err := GenerateScriptFromTemplate(
templateSetEnv, &types.SetEnvPayload{
EnvVariables: environment,
})
if err != nil {
return fmt.Errorf("failed to generate scipt to set env from template %s: %w",
templateSetEnv, err)
}
gitspaceLogger.Info("Setting env...")
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, true, gitspaceLogger, true)
if err != nil {
return fmt.Errorf("error while setting env vars: %w", err)
}
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/ai_agent.go | app/gitspace/orchestrator/utils/ai_agent.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"context"
"fmt"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
"github.com/harness/gitness/app/gitspace/types"
gitnessTypes "github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
const (
templateClaudeCodeInstallScript = "install_claude_code.sh"
templateClaudeCodeConfigureScript = "configure_claude_code.sh"
)
type (
installAgentFun func(context.Context, *devcontainer.Exec, types.GitspaceLogger) error
configureAgentFun func(
ctx context.Context,
exec *devcontainer.Exec,
aiAgentAuth map[enum.AIAgent]gitnessTypes.AIAgentAuth,
gitspaceLogger types.GitspaceLogger) error
)
var installationMap = map[enum.AIAgent]installAgentFun{
enum.AIAgentClaudeCode: installClaudeCode,
}
var configurationMap = map[enum.AIAgent]configureAgentFun{
enum.AIAgentClaudeCode: configureClaudeCode,
}
func InstallAIAgents(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger types.GitspaceLogger,
aiAgents []enum.AIAgent,
) error {
gitspaceLogger.Info(fmt.Sprintf("Installing ai agents: %v...", aiAgents))
for _, aiAgent := range aiAgents {
installFun, ok := installationMap[aiAgent]
if !ok {
return fmt.Errorf("installation not available for %s", aiAgent)
}
if err := installFun(ctx, exec, gitspaceLogger); err != nil {
return err
}
}
gitspaceLogger.Info("Successfully installed ai agents")
return nil
}
func ConfigureAIAgent(ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger types.GitspaceLogger,
aiAgents []enum.AIAgent,
aiAgentAuth map[enum.AIAgent]gitnessTypes.AIAgentAuth,
) error {
gitspaceLogger.Info(fmt.Sprintf("configuring ai agents: %v...", aiAgents))
for _, aiAgent := range aiAgents {
configureFun, ok := configurationMap[aiAgent]
if !ok {
gitspaceLogger.Info(fmt.Sprintf("configuration not available for %s", aiAgent))
continue
}
if err := configureFun(ctx, exec, aiAgentAuth, gitspaceLogger); err != nil {
return err
}
}
gitspaceLogger.Info("Successfully configured ai agents")
return nil
}
func installClaudeCode(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger types.GitspaceLogger,
) error {
script, err := GenerateScriptFromTemplate(
templateClaudeCodeInstallScript, &types.SetupClaudeCodePayload{
OSInfoScript: GetOSInfoScript(),
})
if err != nil {
return fmt.Errorf(
"failed to generate script to install claude code from template %s: %w",
templateClaudeCodeInstallScript, err)
}
gitspaceLogger.Info("Installing claude code output...")
gitspaceLogger.Info("Installing claude code inside container")
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, true, gitspaceLogger, true)
if err != nil {
return fmt.Errorf("failed to install claude code : %w", err)
}
gitspaceLogger.Info("Successfully Installed claude code")
return nil
}
func configureClaudeCode(
ctx context.Context,
exec *devcontainer.Exec,
aiAgentAuth map[enum.AIAgent]gitnessTypes.AIAgentAuth,
gitspaceLogger types.GitspaceLogger,
) error {
claudeAuth, ok := aiAgentAuth[enum.AIAgentClaudeCode]
if !ok {
gitspaceLogger.Info("auth is not available for claude code")
return fmt.Errorf("auth not available for %s", enum.AIAgentClaudeCode)
}
if claudeAuth.AuthType != enum.AnthropicAPIKeyAuth || claudeAuth.APIKey.Value == nil {
gitspaceLogger.Info(fmt.Sprintf("%s is not available for claude code", claudeAuth.AuthType))
return fmt.Errorf("auth type not available for %s", enum.AIAgentClaudeCode)
}
script, err := GenerateScriptFromTemplate(
templateClaudeCodeConfigureScript, &types.ConfigureClaudeCodePayload{
AnthropicAPIKey: claudeAuth.APIKey.Value.Value(),
})
if err != nil {
return fmt.Errorf(
"failed to generate script to configure claude code from template %s: %w",
templateClaudeCodeInstallScript, err)
}
gitspaceLogger.Info("configuring claude code output...")
gitspaceLogger.Info("claude code is setup using anthropic api key")
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, false, gitspaceLogger, true)
if err != nil {
return fmt.Errorf("failed to configure claude code : %w", err)
}
gitspaceLogger.Info("Successfully configured claude code")
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/download_features.go | app/gitspace/orchestrator/utils/download_features.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"archive/tar"
"context"
"encoding/json"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/tidwall/jsonc"
"oras.land/oras-go/v2"
"oras.land/oras-go/v2/content/file"
"oras.land/oras-go/v2/registry/remote"
)
type featureSource struct {
sourceURL string
sourceType enum.FeatureSourceType
}
// DownloadFeatures downloads the user specified features and all the features on which the user defined features
// depend. It does it by checking the dependencies of a downloaded feature from the devcontainer-feature.json
// and adding that feature to the download queue, if it is not already marked for download.
func DownloadFeatures(
ctx context.Context,
gitspaceInstanceIdentifier string,
features types.Features,
) (*map[string]*types.DownloadedFeature, error) {
downloadedFeatures := sync.Map{}
featuresToBeDownloaded := sync.Map{}
downloadQueue := make(chan featureSource, 100)
errorCh := make(chan error, 100)
// startCh and endCh are used to check if all the goroutines spawned to download features have completed or not.
// Whenever a new goroutine is spawned, it increments the counter listening to the startCh.
// Upon completion, it increments the counter listening to the endCh.
// When the start count == end count and end count is > 0, it means all the goroutines have completed execution.
startCh := make(chan int, 100)
endCh := make(chan int, 100)
for key, value := range features {
featuresToBeDownloaded.Store(key, value)
downloadQueue <- featureSource{sourceURL: key, sourceType: value.SourceType}
}
// NOTE: The following logic might see performance issues with spikes in memory and CPU usage.
// If there are such issues, we can introduce throttling on the basis of memory, CPU, etc.
go func(ctx context.Context) {
for source := range downloadQueue {
select {
case <-ctx.Done():
return
default:
startCh <- 1
go func(source featureSource) {
defer func(endCh chan int) { endCh <- 1 }(endCh)
err := downloadFeature(ctx, gitspaceInstanceIdentifier, &source, &featuresToBeDownloaded,
downloadQueue, &downloadedFeatures)
errorCh <- err
}(source)
}
}
}(ctx)
var totalStart int
var totalEnd int
var downloadError error
waitLoop:
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case start := <-startCh:
totalStart += start
case end := <-endCh:
totalEnd += end
case err := <-errorCh:
if err == nil {
continue
}
if downloadError != nil {
downloadError = fmt.Errorf("error downloading features: %w\n%w", err, downloadError)
} else {
downloadError = fmt.Errorf("error downloading features: %w", err)
}
default:
if totalEnd > 0 && totalStart == totalEnd {
break waitLoop
} else {
time.Sleep(time.Millisecond * 10)
}
}
}
close(startCh)
close(endCh)
close(downloadQueue)
close(errorCh)
if downloadError != nil {
return nil, downloadError
}
var finalMap = make(map[string]*types.DownloadedFeature)
var saveToMapFunc = func(key, value any) bool {
finalMap[key.(string)] = value.(*types.DownloadedFeature) // nolint:errcheck
return true
}
downloadedFeatures.Range(saveToMapFunc)
return &finalMap, nil
}
// downloadFeature downloads a single feature. Depending on the source type, it either downloads it from an OCI
// repo or an HTTP(S) URL. It then fetches its devcontainer-feature.json and also checks which dependencies need
// to be downloaded for this feature.
func downloadFeature(
ctx context.Context,
gitspaceInstanceIdentifier string,
source *featureSource,
featuresToBeDownloaded *sync.Map,
downloadQueue chan featureSource,
downloadedFeatures *sync.Map,
) error {
var tarballName string
var featureFolderName string
var featureTag string
var sourceWithoutTag string
var canonicalName string
var downloadDirectory string
switch source.sourceType {
case enum.FeatureSourceTypeOCI:
sourceWithoutTag = strings.SplitN(source.sourceURL, ":", 2)[0]
partialFeatureNameWithTag := filepath.Base(source.sourceURL)
parts := strings.SplitN(partialFeatureNameWithTag, ":", 2)
tarballName = fmt.Sprintf("devcontainer-feature-%s.tgz", parts[0])
featureFolderName = strings.TrimSuffix(tarballName, ".tgz")
featureTag = parts[1]
downloadDirectory = getFeatureDownloadDirectory(gitspaceInstanceIdentifier, featureFolderName, featureTag)
contentDigest, err := downloadTarballFromOCIRepo(ctx, source.sourceURL, downloadDirectory)
if err != nil {
return fmt.Errorf("error downloading oci artifact for feature %s: %w", source.sourceURL, err)
}
canonicalName = contentDigest
case enum.FeatureSourceTypeTarball:
sourceWithoutTag = source.sourceURL
canonicalName = source.sourceURL
featureTag = types.FeatureDefaultTag // using static tag for comparison
tarballURL, err := url.Parse(source.sourceURL)
if err != nil {
return fmt.Errorf("error parsing feature URL for feature %s: %w", source.sourceURL, err)
}
tarballName = filepath.Base(tarballURL.Path)
featureFolderName = strings.TrimSuffix(tarballName, ".tgz")
downloadDirectory = getFeatureDownloadDirectory(gitspaceInstanceIdentifier, featureFolderName, featureTag)
err = downloadTarball(source.sourceURL, downloadDirectory, filepath.Join(downloadDirectory, tarballName))
if err != nil {
return fmt.Errorf("error downloading tarball for feature %s: %w", source.sourceURL, err)
}
default:
return fmt.Errorf("unsupported feature type: %s", source.sourceType)
}
devcontainerFeature, err := getDevcontainerFeatureConfig(downloadDirectory, featureFolderName, tarballName, source)
if err != nil {
return err
}
downloadedFeature := types.DownloadedFeature{
FeatureFolderName: featureFolderName,
Source: source.sourceURL,
SourceWithoutTag: sourceWithoutTag,
Tag: featureTag,
CanonicalName: canonicalName,
DevcontainerFeatureConfig: devcontainerFeature,
}
downloadedFeatures.Store(source.sourceURL, &downloadedFeature)
// Check all the dependencies which are required for this feature. If any, check if they are already marked
// for downloaded. If not, push to the download queue.
if downloadedFeature.DevcontainerFeatureConfig.DependsOn != nil &&
len(*downloadedFeature.DevcontainerFeatureConfig.DependsOn) > 0 {
for key, value := range *downloadedFeature.DevcontainerFeatureConfig.DependsOn {
_, present := featuresToBeDownloaded.LoadOrStore(key, value)
if !present {
downloadQueue <- featureSource{sourceURL: key, sourceType: value.SourceType}
}
}
}
return nil
}
// getDevcontainerFeatureConfig returns the devcontainer-feature.json by unpacking the downloaded tarball,
// unmarshalling the file contents to types.DevcontainerFeatureConfig. It removes any comments before unmarshalling.
func getDevcontainerFeatureConfig(
downloadDirectory string,
featureName string,
tarballName string,
source *featureSource,
) (*types.DevcontainerFeatureConfig, error) {
dst := filepath.Join(downloadDirectory, featureName)
err := unpackTarball(filepath.Join(downloadDirectory, tarballName), dst)
if err != nil {
return nil, fmt.Errorf("error unpacking tarball for feature %s: %w", source.sourceURL, err)
}
// Delete the tarball to avoid unnecessary packaging and copying during docker build.
err = os.Remove(filepath.Join(downloadDirectory, tarballName))
if err != nil {
return nil, fmt.Errorf("error deleting tarball for feature %s: %w", source.sourceURL, err)
}
devcontainerFeatureRaw, err := os.ReadFile(filepath.Join(dst, "devcontainer-feature.json"))
if err != nil {
return nil, fmt.Errorf("error reading devcontainer-feature.json file for feature %s: %w",
source.sourceURL, err)
}
var devcontainerFeature types.DevcontainerFeatureConfig
err = json.Unmarshal(jsonc.ToJSON(devcontainerFeatureRaw), &devcontainerFeature)
if err != nil {
return nil, fmt.Errorf("error parsing devcontainer-feature.json for feature %s: %w",
source.sourceURL, err)
}
return &devcontainerFeature, nil
}
func getGitspaceInstanceDirectory(gitspaceInstanceIdentifier string) string {
return filepath.Join("/tmp", gitspaceInstanceIdentifier)
}
func getFeaturesDownloadDirectory(gitspaceInstanceIdentifier string) string {
return filepath.Join(getGitspaceInstanceDirectory(gitspaceInstanceIdentifier), "devcontainer-features")
}
func getFeatureDownloadDirectory(gitspaceInstanceIdentifier, featureFolderName, featureTag string) string {
return filepath.Join(getFeaturesDownloadDirectory(gitspaceInstanceIdentifier),
getFeatureFolderNameWithTag(featureFolderName, featureTag))
}
func getFeatureFolderNameWithTag(featureFolderName string, featureTag string) string {
return featureFolderName + "-" + featureTag
}
func downloadTarballFromOCIRepo(ctx context.Context, ociRepo string, filePath string) (string, error) {
parts := strings.SplitN(ociRepo, ":", 2)
if len(parts) != 2 {
return "", fmt.Errorf("invalid oci repo: %s", ociRepo)
}
fs, err := file.New(filePath)
if err != nil {
return "", err
}
defer fs.Close()
repo, err := remote.NewRepository(parts[0])
if err != nil {
return "", err
}
tag := parts[1]
md, err := oras.Copy(ctx, repo, tag, fs, tag, oras.DefaultCopyOptions)
if err != nil {
return "", err
}
return md.Digest.String(), nil
}
func downloadTarball(url, dirPath, fileName string) error {
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
err := os.MkdirAll(dirPath, fs.ModePerm)
if err != nil {
return err
}
}
out, err := os.Create(fileName)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
defer out.Close()
resp, err := http.Get(url) // nolint:gosec,noctx
if err != nil {
return fmt.Errorf("failed to download tarball: %w", err)
}
defer resp.Body.Close()
// Check the HTTP response status
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download tarball: HTTP status %d", resp.StatusCode)
}
// Copy the response body to the file
_, err = io.Copy(out, resp.Body)
if err != nil {
return fmt.Errorf("failed to save tarball: %w", err)
}
return nil
}
// unpackTarball extracts a .tgz file to a specified output directory.
func unpackTarball(tarball, outputDir string) error {
// Open the tarball file
file, err := os.Open(tarball)
if err != nil {
return fmt.Errorf("failed to open tarball: %w", err)
}
defer file.Close()
// Create a tar reader
tarReader := tar.NewReader(file)
// Iterate through the files in the tar archive
for {
header, err := tarReader.Next()
if err == io.EOF {
break // End of tar archive
}
if err != nil {
return fmt.Errorf("failed to read tar header: %w", err)
}
// Determine the file's full path
targetPath := filepath.Join(outputDir, header.Name) // nolint:gosec
switch header.Typeflag {
case tar.TypeDir:
// Create the directory if it doesn't exist
//nolint:gosec
if err := os.MkdirAll(targetPath, os.FileMode(header.Mode)); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
case tar.TypeReg:
// Extract the file
if err := extractFile(tarReader, targetPath, header.Mode); err != nil {
return err
}
default:
return fmt.Errorf("skipping unsupported type: %c in %s", header.Typeflag, header.Name)
}
}
return nil
}
// extractFile writes the content of a file from the tar archive.
func extractFile(tarReader *tar.Reader, targetPath string, mode int64) error {
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
return fmt.Errorf("failed to create parent directories: %w", err)
}
outFile, err := os.Create(targetPath)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
defer outFile.Close()
if _, err := io.Copy(outFile, tarReader); err != nil {
return fmt.Errorf("failed to copy file content: %w", err)
}
//nolint:gosec
if err := os.Chmod(targetPath, os.FileMode(mode)); err != nil {
return fmt.Errorf("failed to set file permissions: %w", err)
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/resolve_features.go | app/gitspace/orchestrator/utils/resolve_features.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/harness/gitness/types"
)
// ResolveFeatures resolves all the downloaded features ie starting from the user-specified features, it checks
// which features need to be installed with which options. A feature in considered uniquely installable if its
// id or source and the options overrides are unique.
// Reference: https://containers.dev/implementors/features/#definition-feature-equality
func ResolveFeatures(
userDefinedFeatures types.Features,
downloadedFeatures map[string]*types.DownloadedFeature,
) (map[string]*types.ResolvedFeature, error) {
featuresToBeResolved := make([]types.FeatureValue, 0)
for _, featureValue := range userDefinedFeatures {
featuresToBeResolved = append(featuresToBeResolved, *featureValue)
}
resolvedFeatures := make(map[string]*types.ResolvedFeature)
for i := 0; i < len(featuresToBeResolved); i++ {
currentFeature := featuresToBeResolved[i]
digest, err := calculateDigest(currentFeature.Source, currentFeature.Options)
if err != nil {
return nil, fmt.Errorf("error calculating digest for %s: %w", currentFeature.Source, err)
}
if _, alreadyResolved := resolvedFeatures[digest]; alreadyResolved {
continue
}
downloadedFeature := downloadedFeatures[currentFeature.Source]
resolvedOptions, err := getResolvedOptions(downloadedFeature, currentFeature)
if err != nil {
return nil, err
}
resolvedFeature := types.ResolvedFeature{
Digest: digest,
ResolvedOptions: resolvedOptions,
OverriddenOptions: currentFeature.Options, // used to calculate digest and sort features
DownloadedFeature: downloadedFeature,
}
resolvedFeatures[digest] = &resolvedFeature
if resolvedFeature.DownloadedFeature.DevcontainerFeatureConfig.DependsOn != nil &&
len(*resolvedFeature.DownloadedFeature.DevcontainerFeatureConfig.DependsOn) > 0 {
for _, featureValue := range *resolvedFeature.DownloadedFeature.DevcontainerFeatureConfig.DependsOn {
featuresToBeResolved = append(featuresToBeResolved, *featureValue)
}
}
}
return resolvedFeatures, nil
}
func getResolvedOptions(
downloadedFeature *types.DownloadedFeature,
currentFeature types.FeatureValue,
) (map[string]string, error) {
resolvedOptions := make(map[string]string)
if downloadedFeature.DevcontainerFeatureConfig.Options != nil {
for optionKey, optionDefinition := range *downloadedFeature.DevcontainerFeatureConfig.Options {
var optionValue = optionDefinition.Default
if userProvidedOptionValue, ok := currentFeature.Options[optionKey]; ok {
optionValue = userProvidedOptionValue
}
stringValue, err := optionDefinition.ValidateValue(optionValue, optionKey, currentFeature.Source)
if err != nil {
return nil, err
}
resolvedOptions[optionKey] = stringValue
}
}
return resolvedOptions, nil
}
// calculateDigest calculates a deterministic hash for a feature using its source and options overrides.
func calculateDigest(source string, optionsOverrides map[string]any) (string, error) {
data := map[string]any{
"options": optionsOverrides,
"source": source,
}
jsonBytes, err := json.Marshal(data)
if err != nil {
return "", fmt.Errorf("failed to serialize data: %w", err)
}
hash := sha256.Sum256(jsonBytes)
return hex.EncodeToString(hash[:]), nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/user.go | app/gitspace/orchestrator/utils/user.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"context"
"fmt"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
"github.com/harness/gitness/app/gitspace/types"
)
func ManageUser(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger types.GitspaceLogger,
) error {
script, err := GenerateScriptFromTemplate(
templateManagerUser, &types.SetupUserPayload{
Username: exec.RemoteUser,
AccessKey: exec.AccessKey,
AccessType: exec.AccessType,
HomeDir: exec.DefaultWorkingDir,
})
if err != nil {
return fmt.Errorf(
"failed to generate scipt to manager user from template %s: %w", templateManagerUser, err)
}
gitspaceLogger.Info("Configuring user directory and credentials inside container")
err = exec.ExecuteCommandInHomeDirAndLog(ctx, script, true, gitspaceLogger, true)
if err != nil {
return fmt.Errorf("failed to setup user: %w", err)
}
gitspaceLogger.Info("Successfully configured the user directory and credentials.")
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/utils/sort_features.go | app/gitspace/orchestrator/utils/sort_features.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"fmt"
"slices"
"github.com/harness/gitness/types"
)
type node struct {
Digest string
Dependencies map[string]bool
Priority int
Feature *types.ResolvedFeature
}
type featureWithPriority struct {
Priority int
Feature *types.ResolvedFeature
}
// SortFeatures sorts the features topologically, using round priorities and feature installation order override
// if provided by the user. It also keeps track of hard dependencies and soft dependencies.
// Reference: https://containers.dev/implementors/features/#dependency-installation-order-algorithm.
func SortFeatures(
featuresToBeInstalled map[string]*types.ResolvedFeature,
overrideFeatureInstallOrder []string,
) ([]*types.ResolvedFeature, error) {
sourcesWithoutTagsMappedToDigests := getSourcesWithoutTagsMappedToDigests(featuresToBeInstalled)
adjacencyList, err := buildAdjacencyList(featuresToBeInstalled, sourcesWithoutTagsMappedToDigests,
overrideFeatureInstallOrder)
if err != nil {
return nil, err
}
sortedFeatures, err := applyTopologicalSorting(adjacencyList)
if err != nil {
return nil, err
}
return sortedFeatures, nil
}
// getSourcesWithoutTagsMappedToDigests is used to map feature source (without tags) to their digests.
// Multiple features in the install set can have the same source but different options. All these features
// will be mapped to the same source and must be installed before any dependent features.
func getSourcesWithoutTagsMappedToDigests(featuresToBeInstalled map[string]*types.ResolvedFeature) map[string][]string {
sourcesWithoutTagsMappedToDigests := map[string][]string{}
for _, featureToBeInstalled := range featuresToBeInstalled {
sourceWithoutTag := featureToBeInstalled.DownloadedFeature.SourceWithoutTag
if _, initialized := sourcesWithoutTagsMappedToDigests[sourceWithoutTag]; !initialized {
sourcesWithoutTagsMappedToDigests[sourceWithoutTag] = []string{}
}
sourcesWithoutTagsMappedToDigests[sourceWithoutTag] =
append(sourcesWithoutTagsMappedToDigests[sourceWithoutTag], featureToBeInstalled.Digest)
}
return sourcesWithoutTagsMappedToDigests
}
func buildAdjacencyList(
featuresToBeInstalled map[string]*types.ResolvedFeature,
sourcesWithoutTagsMappedToDigests map[string][]string,
overrideFeatureInstallOrder []string,
) ([]*node, error) {
counter := 0
adjacencyList := make([]*node, 0)
for _, featureToBeInstalled := range featuresToBeInstalled {
dependencies := map[string]bool{}
err := populateHardDependencies(featureToBeInstalled, dependencies)
if err != nil {
return nil, err
}
populateSoftDependencies(sourcesWithoutTagsMappedToDigests, featureToBeInstalled, dependencies)
// While the default priority is 0, it can be varied by the user through the overrideFeatureInstallOrder
// in the devcontainer.json.
// Reference: https://containers.dev/implementors/features/#overrideFeatureInstallOrder.
priority := 0
index := slices.Index(overrideFeatureInstallOrder, featureToBeInstalled.DownloadedFeature.SourceWithoutTag)
if index > -1 {
priority = len(overrideFeatureInstallOrder) - index
counter++
}
graphNode := node{
Digest: featureToBeInstalled.Digest,
Dependencies: dependencies,
Priority: priority,
Feature: featureToBeInstalled,
}
adjacencyList = append(adjacencyList, &graphNode)
}
// If any feature mentioned by the user in the overrideFeatureInstallOrder is not present in the install set,
// fail the flow.
difference := len(overrideFeatureInstallOrder) - counter
if difference > 0 {
return nil, fmt.Errorf("overrideFeatureInstallOrder contains %d extra features", difference)
}
return adjacencyList, nil
}
// populateSoftDependencies populates the digests of all the features whose source name is present in the installAfter
// property for the current feature ie which must be installed before the current feature can be installed.
// Any feature mentioned in the installAfter but not part of the install set is ignored.
func populateSoftDependencies(
sourcesWithoutTagsMappedToDigests map[string][]string,
featureToBeInstalled *types.ResolvedFeature,
dependencies map[string]bool,
) {
softDependencies := featureToBeInstalled.DownloadedFeature.DevcontainerFeatureConfig.InstallsAfter
if len(softDependencies) > 0 {
for _, softDependency := range softDependencies {
if digests, ok := sourcesWithoutTagsMappedToDigests[softDependency]; ok {
for _, digest := range digests {
if _, alreadyAdded := dependencies[digest]; !alreadyAdded {
dependencies[digest] = true
}
}
}
}
}
}
// populateHardDependencies populates the digests of all the features which must be installed before the current
// feature can be installed.
func populateHardDependencies(featureToBeInstalled *types.ResolvedFeature, dependencies map[string]bool) error {
hardDependencies := featureToBeInstalled.DownloadedFeature.DevcontainerFeatureConfig.DependsOn
if hardDependencies != nil && len(*hardDependencies) > 0 {
for _, hardDependency := range *hardDependencies {
digest, err := calculateDigest(hardDependency.Source, hardDependency.Options)
if err != nil {
return fmt.Errorf("error calculating digest for %s: %w", hardDependency.Source, err)
}
dependencies[digest] = true
}
}
return nil
}
func applyTopologicalSorting(
adjacencyList []*node,
) ([]*types.ResolvedFeature, error) {
sortedFeatures := make([]*types.ResolvedFeature, 0)
for len(sortedFeatures) < len(adjacencyList) {
maxPriority, eligibleFeatures := getFeaturesEligibleInThisRound(adjacencyList)
if len(eligibleFeatures) == 0 {
return nil, fmt.Errorf("features can not be sorted")
}
selectedFeatures := []*types.ResolvedFeature{}
// only select those features which have the max priority, rest will be picked up in the next iteration.
for _, eligibleFeature := range eligibleFeatures {
if eligibleFeature.Priority == maxPriority {
selectedFeatures = append(selectedFeatures, eligibleFeature.Feature)
}
}
slices.SortStableFunc(selectedFeatures, types.CompareResolvedFeature)
for _, selectedFeature := range selectedFeatures {
sortedFeatures = append(sortedFeatures, selectedFeature)
for _, vertex := range adjacencyList {
delete(vertex.Dependencies, selectedFeature.Digest)
}
}
}
return sortedFeatures, nil
}
func getFeaturesEligibleInThisRound(adjacencyList []*node) (int, []featureWithPriority) {
maxPriorityInRound := 0
eligibleFeatures := []featureWithPriority{}
for _, vertex := range adjacencyList {
if len(vertex.Dependencies) == 0 {
eligibleFeatures = append(eligibleFeatures, featureWithPriority{
Priority: vertex.Priority,
Feature: vertex.Feature,
})
if maxPriorityInRound < vertex.Priority {
maxPriorityInRound = vertex.Priority
}
}
}
return maxPriorityInRound, eligibleFeatures
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/runarg/wire.go | app/gitspace/orchestrator/runarg/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package runarg
import (
"github.com/google/wire"
)
var WireSet = wire.NewSet(
ProvideStaticProvider,
ProvideResolver,
)
func ProvideStaticProvider(resolver *Resolver) (Provider, error) {
return NewStaticProvider(resolver)
}
func ProvideResolver() (*Resolver, error) {
return NewResolver()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/runarg/static_provider.go | app/gitspace/orchestrator/runarg/static_provider.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package runarg
import (
"context"
"github.com/harness/gitness/types"
)
var _ Provider = (*StaticProvider)(nil)
type StaticProvider struct {
supportedRunArgsMap map[types.RunArg]types.RunArgDefinition
}
func NewStaticProvider(resolver *Resolver) (Provider, error) {
return &StaticProvider{supportedRunArgsMap: resolver.ResolveSupportedRunArgs()}, nil
}
// ProvideSupportedRunArgs provides a static map of supported run args.
func (s *StaticProvider) ProvideSupportedRunArgs(
_ context.Context,
_ int64,
) (map[types.RunArg]types.RunArgDefinition, error) {
return s.supportedRunArgsMap, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/runarg/resolver.go | app/gitspace/orchestrator/runarg/resolver.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package runarg
import (
"fmt"
"github.com/harness/gitness/types"
"gopkg.in/yaml.v3"
_ "embed"
)
//go:embed runArgs.yaml
var supportedRunArgsRaw []byte
type Resolver struct {
supportedRunArgsMap map[types.RunArg]types.RunArgDefinition
}
func NewResolver() (*Resolver, error) {
allRunArgs := make([]types.RunArgDefinition, 0)
err := yaml.Unmarshal(supportedRunArgsRaw, &allRunArgs)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal runArgs.yaml: %w", err)
}
argsMap := make(map[types.RunArg]types.RunArgDefinition)
for _, arg := range allRunArgs {
if arg.Supported {
argsMap[arg.Name] = arg
if arg.ShortHand != "" {
argsMap[arg.ShortHand] = arg
}
}
}
return &Resolver{supportedRunArgsMap: argsMap}, nil
}
func (r *Resolver) ResolveSupportedRunArgs() map[types.RunArg]types.RunArgDefinition {
return r.supportedRunArgsMap
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/runarg/provider.go | app/gitspace/orchestrator/runarg/provider.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package runarg
import (
"context"
"github.com/harness/gitness/types"
)
type Provider interface {
// ProvideSupportedRunArgs returns a map of the run arg definitions for all the supported arg applicable for the
// given gitspace spaceID.
ProvideSupportedRunArgs(ctx context.Context, spaceID int64) (map[types.RunArg]types.RunArgDefinition, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/devcontainer/exec.go | app/gitspace/orchestrator/devcontainer/exec.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package devcontainer
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"strconv"
"strings"
"sync"
"github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/types/enum"
dockerTypes "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"github.com/rs/zerolog/log"
)
const RootUser = "root"
const ErrMsgTCP = "unable to upgrade to tcp, received 200"
const LoggerErrorPrefix = "ERR>> "
const ChannelExitStatus = "DEVCONTAINER_EXIT_STATUS"
type Exec struct {
ContainerName string
DockerClient *client.Client
DefaultWorkingDir string
RemoteUser string
AccessKey string
AccessType enum.GitspaceAccessType
Arch string
OS string
}
type execResult struct {
ExecID string
StdOut io.Reader
StdErr io.Reader
}
func (e *Exec) ExecuteCommand(
ctx context.Context,
command string,
root bool,
workingDir string,
) (string, error) {
containerExecCreate, err := e.createExecution(ctx, command, root, workingDir, false)
if err != nil {
return "", fmt.Errorf("failed to create exec instance: %w", err)
}
resp, err := e.DockerClient.ContainerExecAttach(
ctx, containerExecCreate.ID, container.ExecStartOptions{Detach: false})
if err != nil {
return "", fmt.Errorf("failed to attach to exec session: %w", err)
}
defer resp.Close()
// Prepare buffers for stdout and stderr
var stdoutBuf, stderrBuf bytes.Buffer
// Use stdcopy to demultiplex output
_, err = stdcopy.StdCopy(&stdoutBuf, &stderrBuf, resp.Reader)
if err != nil {
return "", fmt.Errorf("error during stdcopy: %w", err)
}
inspect, err := e.DockerClient.ContainerExecInspect(ctx, containerExecCreate.ID)
if err != nil {
return "", fmt.Errorf("failed to inspect exec session: %w", err)
}
// Handle non-zero exit codes
if inspect.ExitCode != 0 {
return fmt.Sprintf(
"STDOUT:\n%s\nSTDERR:\n%s", stdoutBuf.String(), stderrBuf.String(),
), fmt.Errorf("command exited with non-zero status: %d", inspect.ExitCode)
}
return stdoutBuf.String(), nil
}
func (e *Exec) ExecuteCommandInHomeDirAndLog(
ctx context.Context,
script string,
root bool,
gitspaceLogger types.GitspaceLogger,
verbose bool,
) error {
// Buffer upto a thousand messages
outputCh := make(chan []byte, 1000)
err := e.executeCmdInHomeDirectoryAsyncStream(ctx, script, root, false, outputCh)
if err != nil {
return err
}
// Use select to wait for the output and exit status
for {
select {
case output := <-outputCh:
done, chErr := handleOutputChannel(output, verbose, gitspaceLogger)
if done {
return chErr
}
case <-ctx.Done():
// Handle context cancellation or timeout
return ctx.Err()
}
}
}
func (e *Exec) createExecution(
ctx context.Context,
command string,
root bool,
workingDir string,
detach bool,
) (*dockerTypes.IDResponse, error) {
user := e.RemoteUser
if root {
user = RootUser
}
cmd := []string{"/bin/sh", "-c", command}
execConfig := container.ExecOptions{
User: user,
AttachStdout: !detach,
AttachStderr: !detach,
Cmd: cmd,
Detach: detach,
WorkingDir: workingDir,
}
// Create exec instance for the container
log.Debug().Msgf("Creating execution for container %s", e.ContainerName)
containerExecCreate, err := e.DockerClient.ContainerExecCreate(ctx, e.ContainerName, execConfig)
if err != nil {
return nil, fmt.Errorf("failed to create docker exec for container %s: %w", e.ContainerName, err)
}
return &containerExecCreate, nil
}
func (e *Exec) executeCmdAsyncStream(
ctx context.Context,
command string,
root bool,
detach bool,
workingDir string,
outputCh chan []byte, // channel to stream output as []byte
) error {
containerExecCreate, err := e.createExecution(ctx, command, root, workingDir, detach)
if err != nil {
return err
}
// Attach and inspect exec session to get the output
inspectExec, err := e.attachAndInspectExec(ctx, containerExecCreate.ID, detach)
if err != nil && !strings.Contains(err.Error(), ErrMsgTCP) {
return fmt.Errorf("failed to start docker exec for container %s: %w", e.ContainerName, err)
}
// If in detach mode, exit early as the command will run in the background
if detach {
close(outputCh)
return nil
}
e.streamResponse(inspectExec, outputCh) // nolint:contextcheck
return nil
}
func (e *Exec) executeCmdInHomeDirectoryAsyncStream(
ctx context.Context,
command string,
root bool,
detach bool,
outputCh chan []byte, // channel to stream output as []byte
) error {
return e.executeCmdAsyncStream(ctx, command, root, detach, e.DefaultWorkingDir, outputCh)
}
func (e *Exec) attachAndInspectExec(ctx context.Context, id string, detach bool) (*execResult, error) {
resp, attachErr := e.DockerClient.ContainerExecAttach(ctx, id, container.ExecStartOptions{Detach: detach})
if attachErr != nil {
return nil, fmt.Errorf("failed to attach to exec session: %w", attachErr)
}
// If in detach mode, we just need to close the connection, not process output
if detach {
resp.Close()
return nil, nil //nolint:nilnil
}
// Create pipes for stdout and stderr
stdoutPipe, stdoutWriter := io.Pipe()
stderrPipe, stderrWriter := io.Pipe()
go e.copyOutput(resp, stdoutWriter, stderrWriter)
// Return the output streams and the response
return &execResult{
ExecID: id,
StdOut: stdoutPipe, // Pipe for stdout
StdErr: stderrPipe, // Pipe for stderr
}, nil
}
func (e *Exec) streamResponse(resp *execResult, outputCh chan []byte) {
// Stream the output asynchronously if not in detach mode
go func() {
defer close(outputCh)
if resp != nil {
var wg sync.WaitGroup
// Handle stdout as a streaming reader
if resp.StdOut != nil {
wg.Add(1)
go e.streamStdOut(resp.StdOut, outputCh, &wg)
}
// Handle stderr as a streaming reader
if resp.StdErr != nil {
wg.Add(1)
go e.streamStdErr(resp.StdErr, outputCh, &wg)
}
// Wait for all readers to finish before closing the channel
wg.Wait()
// Now that streaming is finished, inspect the exit status
log.Debug().Msgf("Inspecting container for status: %s", resp.ExecID)
inspect, err := e.DockerClient.ContainerExecInspect(context.Background(), resp.ExecID)
if err != nil {
log.Error().Err(err).Msgf("Failed to inspect exec session: %s", err.Error())
return
}
// Send the exit status as a final message
exitStatusMsg := fmt.Sprintf(ChannelExitStatus+"%d", inspect.ExitCode)
outputCh <- []byte(exitStatusMsg)
}
}()
}
func (e *Exec) copyOutput(response dockerTypes.HijackedResponse, stdoutWriter, stderrWriter io.WriteCloser) {
defer func() {
if err := stdoutWriter.Close(); err != nil {
log.Error().Err(err).Msg("Error closing stdoutWriter")
}
if err := stderrWriter.Close(); err != nil {
log.Error().Err(err).Msg("Error closing stderrWriter")
}
response.Close()
}()
_, err := stdcopy.StdCopy(stdoutWriter, stderrWriter, response.Reader)
if err != nil {
log.Error().Err(err).Msg("Error in stdcopy.StdCopy " + err.Error())
}
}
// streamStdOut reads from the stdout pipe and sends each line to the output channel.
func (e *Exec) streamStdOut(stdout io.Reader, outputCh chan []byte, wg *sync.WaitGroup) {
defer wg.Done()
stdoutReader := bufio.NewScanner(stdout)
for stdoutReader.Scan() {
select {
case <-context.Background().Done():
log.Info().Msg("Context canceled, stopping stdout streaming")
return
default:
outputCh <- stdoutReader.Bytes()
}
}
if err := stdoutReader.Err(); err != nil {
log.Error().Err(err).Msg("Error reading stdout " + err.Error())
}
}
// streamStdErr reads from the stderr pipe and sends each line to the output channel.
func (e *Exec) streamStdErr(stderr io.Reader, outputCh chan []byte, wg *sync.WaitGroup) {
defer wg.Done()
stderrReader := bufio.NewScanner(stderr)
for stderrReader.Scan() {
select {
case <-context.Background().Done():
log.Info().Msg("Context canceled, stopping stderr streaming")
return
default:
outputCh <- []byte(LoggerErrorPrefix + stderrReader.Text())
}
}
if err := stderrReader.Err(); err != nil {
log.Error().Err(err).Msg("Error reading stderr " + err.Error())
}
}
func handleOutputChannel(output []byte, verbose bool, gitspaceLogger types.GitspaceLogger) (bool, error) {
// Handle the exit status first
if after, ok := strings.CutPrefix(string(output), ChannelExitStatus); ok {
// Extract the exit code from the message
exitCodeStr := after
exitCode, err := strconv.Atoi(exitCodeStr)
if err != nil {
return true, fmt.Errorf("invalid exit status format: %w", err)
}
if exitCode != 0 {
gitspaceLogger.Info("Process Exited with status " + exitCodeStr)
return true, fmt.Errorf("command exited with non-zero status: %d", exitCode)
}
// If exit status is zero, just continue processing
return true, nil
}
// Handle regular command output
msg := string(output)
if len(output) > 0 {
// Log output if verbose or if it's an error
if verbose || strings.HasPrefix(msg, LoggerErrorPrefix) {
gitspaceLogger.Info(msg)
}
}
return false, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/ide/wire.go | app/gitspace/orchestrator/ide/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ide
import (
"github.com/harness/gitness/types/enum"
"github.com/google/wire"
)
var WireSet = wire.NewSet(
ProvideVSCodeWebService,
ProvideVSCodeService,
ProvideCursorService,
ProvideWindsurfService,
ProvideJetBrainsIDEsService,
ProvideIDEFactory,
)
func ProvideVSCodeWebService(config *VSCodeWebConfig) *VSCodeWeb {
return NewVsCodeWebService(config, "http")
}
func ProvideVSCodeService(config *VSCodeConfig) *VSCode {
return NewVsCodeService(config)
}
func ProvideCursorService(config *CursorConfig) *Cursor {
return NewCursorService(config)
}
func ProvideWindsurfService(config *WindsurfConfig) *Windsurf {
return NewWindsurfService(config)
}
func ProvideJetBrainsIDEsService(config *JetBrainsIDEConfig) map[enum.IDEType]*JetBrainsIDE {
return map[enum.IDEType]*JetBrainsIDE{
enum.IDETypeIntelliJ: NewJetBrainsIDEService(config, enum.IDETypeIntelliJ),
enum.IDETypePyCharm: NewJetBrainsIDEService(config, enum.IDETypePyCharm),
enum.IDETypeGoland: NewJetBrainsIDEService(config, enum.IDETypeGoland),
enum.IDETypeWebStorm: NewJetBrainsIDEService(config, enum.IDETypeWebStorm),
enum.IDETypeCLion: NewJetBrainsIDEService(config, enum.IDETypeCLion),
enum.IDETypePHPStorm: NewJetBrainsIDEService(config, enum.IDETypePHPStorm),
enum.IDETypeRubyMine: NewJetBrainsIDEService(config, enum.IDETypeRubyMine),
enum.IDETypeRider: NewJetBrainsIDEService(config, enum.IDETypeRider),
}
}
func ProvideIDEFactory(
vscode *VSCode,
vscodeWeb *VSCodeWeb,
jetBrainsIDEsMap map[enum.IDEType]*JetBrainsIDE,
cursor *Cursor,
windsurf *Windsurf,
) Factory {
return NewFactory(vscode, vscodeWeb, jetBrainsIDEsMap, cursor, windsurf)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/ide/ide.go | app/gitspace/orchestrator/ide/ide.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ide
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
"github.com/harness/gitness/app/gitspace/orchestrator/utils"
gitspaceTypes "github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
const (
templateSetupSSHServer string = "setup_ssh_server.sh"
templateRunSSHServer string = "run_ssh_server.sh"
)
type IDE interface {
// Setup is responsible for doing all the operations for setting up the IDE in the container e.g. installation,
// copying settings and configurations.
Setup(
ctx context.Context,
exec *devcontainer.Exec,
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error
// Run runs the IDE and supporting services.
Run(
ctx context.Context,
exec *devcontainer.Exec,
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error
// Port provides the port which will be used by this IDE.
Port() *types.GitspacePort
// Type provides the IDE type to which the service belongs.
Type() enum.IDEType
// GenerateURL returns the url to redirect user to ide from gitspace
GenerateURL(absoluteRepoPath, host, port, user string) string
// GenerateURL returns the url to redirect user to ide from gitspace
GeneratePluginURL(projectName, gitspaceInstaceUID string) string
}
func getHomePath(absoluteRepoPath string) string {
pathList := strings.Split(absoluteRepoPath, "/")
return strings.Join(pathList[:len(pathList)-1], "/")
}
// setupSSHServer is responsible for setting up the SSH server inside the container.
// This is a common operation done by most of the IDEs that require SSH to connect.
func setupSSHServer(
ctx context.Context,
exec *devcontainer.Exec,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
osInfoScript := utils.GetOSInfoScript()
payload := gitspaceTypes.SetupSSHServerPayload{
Username: exec.RemoteUser,
AccessType: exec.AccessType,
OSInfoScript: osInfoScript,
}
sshServerScript, err := utils.GenerateScriptFromTemplate(
templateSetupSSHServer, &payload)
if err != nil {
return fmt.Errorf(
"failed to generate scipt to setup ssh server from template %s: %w", templateSetupSSHServer, err)
}
err = exec.ExecuteCommandInHomeDirAndLog(ctx, sshServerScript, true, gitspaceLogger, false)
if err != nil {
return fmt.Errorf("failed to setup SSH serverr: %w", err)
}
return nil
}
// runSSHServer runs the SSH server inside the container.
// This is a common operation done by most of the IDEs that require ssh connection.
func runSSHServer(
ctx context.Context,
exec *devcontainer.Exec,
port int,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
payload := gitspaceTypes.RunSSHServerPayload{
Port: strconv.Itoa(port),
}
runSSHScript, err := utils.GenerateScriptFromTemplate(
templateRunSSHServer, &payload)
if err != nil {
return fmt.Errorf(
"failed to generate scipt to run ssh server from template %s: %w", templateRunSSHServer, err)
}
err = exec.ExecuteCommandInHomeDirAndLog(ctx, runSSHScript, true, gitspaceLogger, true)
if err != nil {
return fmt.Errorf("failed to run SSH server: %w", err)
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/ide/vscode.go | app/gitspace/orchestrator/ide/vscode.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ide
import (
"context"
"encoding/json"
"fmt"
"net/url"
"path/filepath"
"strings"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
"github.com/harness/gitness/app/gitspace/orchestrator/utils"
gitspaceTypes "github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
var _ IDE = (*VSCode)(nil)
const (
templateSetupVSCodeExtensions string = "setup_vscode_extensions.sh"
vSCodeURLScheme string = "vscode-remote"
)
type VSCodeConfig struct {
Port int
PluginName string
}
type VSCode struct {
config *VSCodeConfig
}
func NewVsCodeService(config *VSCodeConfig) *VSCode {
return &VSCode{config: config}
}
// Setup installs the SSH server inside the container.
func (v *VSCode) Setup(
ctx context.Context,
exec *devcontainer.Exec,
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
gitspaceLogger.Info("Installing ssh-server inside container...")
err := setupSSHServer(ctx, exec, gitspaceLogger)
if err != nil {
return fmt.Errorf("failed to setup %s IDE: %w", enum.IDETypeVSCode, err)
}
gitspaceLogger.Info("Successfully installed ssh-server")
gitspaceLogger.Info("Installing vs-code extensions inside container...")
err = v.setupVSCodeExtensions(ctx, exec, args, gitspaceLogger)
if err != nil {
return fmt.Errorf("failed to setup vs code extensions: %w", err)
}
gitspaceLogger.Info("Successfully installed vs-code extensions")
gitspaceLogger.Info(fmt.Sprintf("Successfully set up %s IDE inside container", enum.IDETypeVSCode))
return nil
}
func (v *VSCode) setupVSCodeExtensions(
ctx context.Context,
exec *devcontainer.Exec,
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
payload := gitspaceTypes.SetupVSCodeExtensionsPayload{
Username: exec.RemoteUser,
}
if err := v.updateVSCodeSetupPayload(args, gitspaceLogger, &payload); err != nil {
return err
}
vscodeExtensionsScript, err := utils.GenerateScriptFromTemplate(
templateSetupVSCodeExtensions, &payload)
if err != nil {
return fmt.Errorf(
"failed to generate scipt to setup vscode extensions from template %s: %w",
templateSetupVSCodeExtensions,
err,
)
}
err = exec.ExecuteCommandInHomeDirAndLog(ctx, vscodeExtensionsScript,
true, gitspaceLogger, false)
if err != nil {
return fmt.Errorf("failed to setup vs-code extensions: %w", err)
}
return nil
}
// Run runs the SSH server inside the container.
func (v *VSCode) Run(
ctx context.Context,
exec *devcontainer.Exec,
_ map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
gitspaceLogger.Info("Running ssh-server...")
err := runSSHServer(ctx, exec, v.config.Port, gitspaceLogger)
if err != nil {
return fmt.Errorf("failed to run %s IDE: %w", enum.IDETypeVSCode, err)
}
gitspaceLogger.Info("Successfully run ssh-server")
return nil
}
// Port returns the port on which the ssh-server is listening.
func (v *VSCode) Port() *types.GitspacePort {
return &types.GitspacePort{
Port: v.config.Port,
Protocol: enum.CommunicationProtocolSSH,
}
}
func (v *VSCode) Type() enum.IDEType {
return enum.IDETypeVSCode
}
func (v *VSCode) updateVSCodeSetupPayload(
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
payload *gitspaceTypes.SetupVSCodeExtensionsPayload,
) error {
if args == nil {
return nil
}
// Handle VSCode Customization
if err := v.handleVSCodeCustomization(args, gitspaceLogger, payload); err != nil {
return err
}
// Handle Repository Name
repoName, exists := args[gitspaceTypes.IDERepoNameArg]
if !exists {
return nil // No repo name found, nothing to do
}
repoNameStr, ok := repoName.(string)
if !ok {
return fmt.Errorf("repo name is not of type string")
}
payload.RepoName = repoNameStr
return nil
}
func (v *VSCode) handleVSCodeCustomization(
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
payload *gitspaceTypes.SetupVSCodeExtensionsPayload,
) error {
customization, exists := args[gitspaceTypes.VSCodeCustomizationArg]
if !exists {
return nil // No customization found, nothing to do
}
// Perform type assertion to ensure it's the correct type
vsCodeCustomizationSpecs, ok := customization.(types.VSCodeCustomizationSpecs)
if !ok {
return fmt.Errorf("customization is not of type VSCodeCustomizationSpecs")
}
// Log customization details
gitspaceLogger.Info(fmt.Sprintf(
"VSCode Customizations : Extensions %v", vsCodeCustomizationSpecs.Extensions))
// Marshal extensions and set payload
jsonData, err := json.Marshal(vsCodeCustomizationSpecs.Extensions)
if err != nil {
log.Warn().Msg("Error marshalling JSON for VSCode extensions")
return err
}
payload.Extensions = string(jsonData)
return nil
}
// GenerateURL returns the url to redirect user to ide(here to vscode application).
func (v *VSCode) GenerateURL(absoluteRepoPath, host, port, user string) string {
relativeRepoPath := strings.TrimPrefix(absoluteRepoPath, "/")
ideURL := url.URL{
Scheme: vSCodeURLScheme,
Host: "", // Empty since we include the host and port in the path
Path: fmt.Sprintf(
"ssh-remote+%s@%s:%s",
user,
host,
filepath.Join(port, relativeRepoPath),
),
}
return ideURL.String()
}
func (v *VSCode) GeneratePluginURL(projectName, gitspaceInstanceUID string) string {
deepLinkURL := url.URL{
Scheme: "vscode",
Host: "",
Path: fmt.Sprintf("%s/%s/%s", v.config.PluginName, projectName, gitspaceInstanceUID),
}
return deepLinkURL.String()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/ide/factory.go | app/gitspace/orchestrator/ide/factory.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ide
import (
"fmt"
"github.com/harness/gitness/types/enum"
)
type Factory struct {
ides map[enum.IDEType]IDE
}
func NewFactory(
vscode *VSCode,
vscodeWeb *VSCodeWeb,
jetBrainsIDEsMap map[enum.IDEType]*JetBrainsIDE,
cursor *Cursor,
windsurf *Windsurf,
) Factory {
ides := make(map[enum.IDEType]IDE)
ides[enum.IDETypeVSCode] = vscode
ides[enum.IDETypeVSCodeWeb] = vscodeWeb
ides[enum.IDETypeCursor] = cursor
ides[enum.IDETypeWindsurf] = windsurf
ides[enum.IDETypeIntelliJ] = jetBrainsIDEsMap[enum.IDETypeIntelliJ]
ides[enum.IDETypePyCharm] = jetBrainsIDEsMap[enum.IDETypePyCharm]
ides[enum.IDETypeGoland] = jetBrainsIDEsMap[enum.IDETypeGoland]
ides[enum.IDETypeWebStorm] = jetBrainsIDEsMap[enum.IDETypeWebStorm]
ides[enum.IDETypeCLion] = jetBrainsIDEsMap[enum.IDETypeCLion]
ides[enum.IDETypePHPStorm] = jetBrainsIDEsMap[enum.IDETypePHPStorm]
ides[enum.IDETypeRubyMine] = jetBrainsIDEsMap[enum.IDETypeRubyMine]
ides[enum.IDETypeRider] = jetBrainsIDEsMap[enum.IDETypeRider]
return Factory{ides: ides}
}
func NewFactoryWithIDEs(ides map[enum.IDEType]IDE) Factory {
return Factory{ides: ides}
}
func (f *Factory) GetIDE(ideType enum.IDEType) (IDE, error) {
val, exist := f.ides[ideType]
if !exist {
return nil, fmt.Errorf("unsupported IDE type: %s", ideType)
}
return val, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/ide/windsurf.go | app/gitspace/orchestrator/ide/windsurf.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ide
import (
"context"
"fmt"
"net/url"
"path/filepath"
"strings"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
gitspaceTypes "github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
const windSurfURLScheme string = "windsurf"
var _ IDE = (*Windsurf)(nil)
// WindsurfConfig defines Windsurf IDE specific configuration.
type WindsurfConfig struct {
Port int
}
// Windsurf implements the IDE interface for Windsurf IDE (VSCode-based).
type Windsurf struct {
config *WindsurfConfig
}
// NewWindsurfService creates a new Windsurf IDE service.
func NewWindsurfService(config *WindsurfConfig) *Windsurf {
return &Windsurf{config: config}
}
// Setup installs the SSH server inside the container.
func (w *Windsurf) Setup(
ctx context.Context,
exec *devcontainer.Exec,
_ map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
gitspaceLogger.Info("Installing ssh-server inside container...")
err := setupSSHServer(ctx, exec, gitspaceLogger)
if err != nil {
return fmt.Errorf("failed to setup %s IDE: %w", enum.IDETypeWindsurf, err)
}
gitspaceLogger.Info("Successfully installed ssh-server")
gitspaceLogger.Info(fmt.Sprintf("Successfully set up %s IDE inside container", enum.IDETypeWindsurf))
return nil
}
// Run starts the SSH server inside the container.
func (w *Windsurf) Run(
ctx context.Context,
exec *devcontainer.Exec,
_ map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
gitspaceLogger.Info("Starting ssh-server...")
err := runSSHServer(ctx, exec, w.config.Port, gitspaceLogger)
if err != nil {
return fmt.Errorf("failed to run %s IDE: %w", enum.IDETypeWindsurf, err)
}
gitspaceLogger.Info("Successfully run ssh-server")
return nil
}
// Port returns the port on which the ssh-server is listening.
func (w *Windsurf) Port() *types.GitspacePort {
return &types.GitspacePort{
Port: w.config.Port,
Protocol: enum.CommunicationProtocolSSH,
}
}
// Type returns the IDE type this service represents.
func (w *Windsurf) Type() enum.IDEType {
return enum.IDETypeWindsurf
}
// GenerateURL returns a ssh command needed to ssh details need to be pasted in windsurf to connect via remote ssh
// plugin.
func (w *Windsurf) GenerateURL(absoluteRepoPath, host, port, user string) string { //nolint:revive // match interface
relativeRepoPath := strings.TrimPrefix(absoluteRepoPath, "/")
ideURL := url.URL{
Scheme: windSurfURLScheme,
Host: "", // Empty since we include the host and port in the path
Path: fmt.Sprintf(
"vscode-remote:/ssh-remote+%s@%s:%s",
user,
host,
filepath.Join(port, relativeRepoPath),
),
}
return ideURL.String()
}
func (w *Windsurf) GeneratePluginURL(_, _ string) string {
return ""
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/ide/cursor.go | app/gitspace/orchestrator/ide/cursor.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ide
import (
"context"
"fmt"
"net/url"
"path/filepath"
"strings"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
gitspaceTypes "github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
const cursorURLScheme string = "cursor"
var _ IDE = (*Cursor)(nil)
// CursorConfig defines Cursor IDE specific configuration.
type CursorConfig struct {
Port int
}
// Cursor implements the IDE interface for Cursor IDE (VSCode-based).
type Cursor struct {
config *CursorConfig
}
// NewCursorService creates a new Cursor IDE service.
func NewCursorService(config *CursorConfig) *Cursor {
return &Cursor{config: config}
}
// Setup installs the SSH server inside the container.
func (c *Cursor) Setup(
ctx context.Context,
exec *devcontainer.Exec,
_ map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
gitspaceLogger.Info("Installing ssh-server inside container...")
err := setupSSHServer(ctx, exec, gitspaceLogger)
if err != nil {
return fmt.Errorf("failed to setup %s IDE: %w", enum.IDETypeCursor, err)
}
gitspaceLogger.Info("Successfully installed ssh-server")
gitspaceLogger.Info(fmt.Sprintf("Successfully set up %s IDE inside container", enum.IDETypeCursor))
return nil
}
// Run starts the SSH server inside the container.
func (c *Cursor) Run(
ctx context.Context,
exec *devcontainer.Exec,
_ map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
gitspaceLogger.Info("Starting ssh-server...")
err := runSSHServer(ctx, exec, c.config.Port, gitspaceLogger)
if err != nil {
return fmt.Errorf("failed to run %s IDE: %w", enum.IDETypeCursor, err)
}
gitspaceLogger.Info("Successfully run ssh-server")
return nil
}
// Port returns the port on which the ssh-server is listening.
func (c *Cursor) Port() *types.GitspacePort {
return &types.GitspacePort{
Port: c.config.Port,
Protocol: enum.CommunicationProtocolSSH,
}
}
// Type returns the IDE type this service represents.
func (c *Cursor) Type() enum.IDEType {
return enum.IDETypeCursor
}
// GenerateURL returns SSH config snippet that user need to add to ssh config to connect with cursor.
func (c *Cursor) GenerateURL(absoluteRepoPath, host, port, user string) string { //nolint:revive // match interface
relativeRepoPath := strings.TrimPrefix(absoluteRepoPath, "/")
ideURL := url.URL{
Scheme: cursorURLScheme,
Host: "", // Empty since we include the host and port in the path
Path: fmt.Sprintf(
"vscode-remote:/ssh-remote+%s@%s:%s",
user,
host,
filepath.Join(port, relativeRepoPath),
),
}
return ideURL.String()
}
func (c *Cursor) GeneratePluginURL(_, _ string) string {
return ""
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/ide/jetbrains.go | app/gitspace/orchestrator/ide/jetbrains.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ide
import (
"context"
"fmt"
"net/url"
"path"
"strings"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
"github.com/harness/gitness/app/gitspace/orchestrator/utils"
gitspaceTypes "github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
var _ IDE = (*JetBrainsIDE)(nil)
const (
templateSetupJetBrainsIDE string = "setup_jetbrains_ide.sh"
templateSetupJetBrainsIDEPlugins string = "setup_jetbrains_plugins.sh"
templateRunRemoteJetBrainsIDE string = "run_jetbrains_ide.sh"
intellijURLScheme string = "jetbrains-gateway"
)
type JetBrainsIDEConfig struct {
IntelliJPort int
GolandPort int
PyCharmPort int
WebStormPort int
CLionPort int
PHPStormPort int
RubyMinePort int
RiderPort int
}
type JetBrainsIDE struct {
ideType enum.IDEType
config JetBrainsIDEConfig
}
func NewJetBrainsIDEService(config *JetBrainsIDEConfig, ideType enum.IDEType) *JetBrainsIDE {
return &JetBrainsIDE{
ideType: ideType,
config: *config,
}
}
func (jb *JetBrainsIDE) port() int {
switch jb.ideType {
case enum.IDETypeIntelliJ:
return jb.config.IntelliJPort
case enum.IDETypeGoland:
return jb.config.GolandPort
case enum.IDETypePyCharm:
return jb.config.PyCharmPort
case enum.IDETypeWebStorm:
return jb.config.WebStormPort
case enum.IDETypeCLion:
return jb.config.CLionPort
case enum.IDETypePHPStorm:
return jb.config.PHPStormPort
case enum.IDETypeRubyMine:
return jb.config.RubyMinePort
case enum.IDETypeRider:
return jb.config.RiderPort
case enum.IDETypeVSCode, enum.IDETypeCursor, enum.IDETypeWindsurf:
return 0
case enum.IDETypeVSCodeWeb:
// IDETypeVSCodeWeb is not JetBrainsIDE
return 0
default:
return 0
}
}
// Setup installs the SSH server inside the container.
func (jb *JetBrainsIDE) Setup(
ctx context.Context,
exec *devcontainer.Exec,
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
gitspaceLogger.Info("Installing ssh-server inside container...")
err := setupSSHServer(ctx, exec, gitspaceLogger)
if err != nil {
return fmt.Errorf("failed to setup %s IDE: %w", jb.ideType, err)
}
gitspaceLogger.Info("Successfully installed ssh-server")
gitspaceLogger.Info(fmt.Sprintf("Installing %s IDE inside container...", jb.ideType))
gitspaceLogger.Info("IDE setup output...")
err = jb.setupJetbrainsIDE(ctx, exec, args, gitspaceLogger)
if err != nil {
return fmt.Errorf("failed to setup %s IDE: %w", jb.ideType, err)
}
gitspaceLogger.Info(fmt.Sprintf("Successfully installed %s IDE binary", jb.ideType))
gitspaceLogger.Info("Installing JetBrains plugins inside container...")
err = jb.setupJetbrainsPlugins(ctx, exec, args, gitspaceLogger)
if err != nil {
return fmt.Errorf("failed to setup %s IDE: %w", jb.ideType, err)
}
gitspaceLogger.Info(fmt.Sprintf("Successfully installed JetBrains plugins for %s IDE", jb.ideType))
gitspaceLogger.Info(fmt.Sprintf("Successfully set up %s IDE inside container", jb.ideType))
return nil
}
func (jb *JetBrainsIDE) setupJetbrainsIDE(
ctx context.Context,
exec *devcontainer.Exec,
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
payload := gitspaceTypes.SetupJetBrainsIDEPayload{
Username: exec.RemoteUser,
}
// get Download URL
downloadURL, err := getIDEDownloadURL(args)
if err != nil {
return err
}
payload.IdeDownloadURLArm64 = downloadURL.Arm64
payload.IdeDownloadURLAmd64 = downloadURL.Amd64
// get DIR name
dirName, err := getIDEDirName(args)
if err != nil {
return err
}
payload.IdeDirName = dirName
intellijIDEScript, err := utils.GenerateScriptFromTemplate(
templateSetupJetBrainsIDE, &payload)
if err != nil {
return fmt.Errorf(
"failed to generate script to setup JetBrains idea from template %s: %w",
templateSetupJetBrainsIDE,
err,
)
}
err = exec.ExecuteCommandInHomeDirAndLog(ctx, intellijIDEScript,
false, gitspaceLogger, true)
if err != nil {
return fmt.Errorf("failed to setup JetBrains IdeType: %w", err)
}
return nil
}
func (jb *JetBrainsIDE) setupJetbrainsPlugins(
ctx context.Context,
exec *devcontainer.Exec,
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
payload := gitspaceTypes.SetupJetBrainsPluginPayload{
Username: exec.RemoteUser,
}
// get DIR name
dirName, err := getIDEDirName(args)
if err != nil {
return err
}
payload.IdeDirName = dirName
// get jetbrains plugins
customization, exists := args[gitspaceTypes.JetBrainsCustomizationArg]
if !exists {
return nil
}
jetBrainsCustomization, ok := customization.(types.JetBrainsCustomizationSpecs)
if !ok {
return fmt.Errorf("customization is not of type JetBrainsCustomizationSpecs")
}
payload.IdePluginsName = strings.Join(jetBrainsCustomization.Plugins, " ")
gitspaceLogger.Info(fmt.Sprintf(
"JetBrains Customizations : Plugins %v", jetBrainsCustomization.Plugins))
intellijIDEScript, err := utils.GenerateScriptFromTemplate(
templateSetupJetBrainsIDEPlugins, &payload)
if err != nil {
return fmt.Errorf(
"failed to generate script to setup Jetbrains plugins from template %s: %w",
templateSetupJetBrainsIDEPlugins,
err,
)
}
err = exec.ExecuteCommandInHomeDirAndLog(ctx, intellijIDEScript,
false, gitspaceLogger, true)
if err != nil {
return fmt.Errorf("failed to setup Jetbrains plugins: %w", err)
}
return nil
}
// Run runs the SSH server inside the container.
func (jb *JetBrainsIDE) Run(
ctx context.Context,
exec *devcontainer.Exec,
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
gitspaceLogger.Info("Running ssh-server...")
err := runSSHServer(ctx, exec, jb.port(), gitspaceLogger)
if err != nil {
return fmt.Errorf("failed to run %s IDE: %w", jb.ideType, err)
}
gitspaceLogger.Info("Successfully run ssh-server")
gitspaceLogger.Info(fmt.Sprintf("Running remote %s IDE backend...", jb.ideType))
err = jb.runRemoteIDE(ctx, exec, args, gitspaceLogger)
if err != nil {
return err
}
gitspaceLogger.Info(fmt.Sprintf("Successfully run %s IDE backend", jb.ideType))
return nil
}
func (jb *JetBrainsIDE) runRemoteIDE(
ctx context.Context,
exec *devcontainer.Exec,
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
payload := gitspaceTypes.RunIntellijIDEPayload{
Username: exec.RemoteUser,
}
// get Repository Name
repoName, err := getRepoName(args)
if err != nil {
return err
}
payload.RepoName = repoName
// get DIR name
dirName, err := getIDEDirName(args)
if err != nil {
return err
}
payload.IdeDirName = dirName
runSSHScript, err := utils.GenerateScriptFromTemplate(
templateRunRemoteJetBrainsIDE, &payload)
if err != nil {
return fmt.Errorf(
"failed to generate scipt to run intelliJ IdeType from template %s: %w", templateRunSSHServer, err)
}
err = exec.ExecuteCommandInHomeDirAndLog(ctx, runSSHScript, false, gitspaceLogger, true)
if err != nil {
return fmt.Errorf("failed to run intelliJ IdeType: %w", err)
}
return nil
}
// Port returns the port on which the ssh-server is listening.
func (jb *JetBrainsIDE) Port() *types.GitspacePort {
return &types.GitspacePort{
Port: jb.port(),
Protocol: enum.CommunicationProtocolSSH,
}
}
func (jb *JetBrainsIDE) Type() enum.IDEType {
return jb.ideType
}
// GenerateURL returns the url to redirect user to ide(here to jetbrains gateway application).
func (jb *JetBrainsIDE) GenerateURL(absoluteRepoPath, host, port, user string) string {
homePath := getHomePath(absoluteRepoPath)
idePath := path.Join(homePath, ".cache", "JetBrains", "RemoteDev", "dist", jb.ideType.String())
ideURL := url.URL{
Scheme: intellijURLScheme,
Host: "", // Empty since we include the host and port in the path
Path: "connect",
Fragment: fmt.Sprintf("idePath=%s&projectPath=%s&host=%s&port=%s&user=%s&type=%s&deploy=%s",
idePath,
absoluteRepoPath,
host,
port,
user,
"ssh",
"false",
),
}
return ideURL.String()
}
func (jb *JetBrainsIDE) GeneratePluginURL(_, _ string) string {
return ""
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/ide/vscodeweb.go | app/gitspace/orchestrator/ide/vscodeweb.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ide
import (
"archive/tar"
"bytes"
"context"
"embed"
"fmt"
"io"
"net/url"
"path/filepath"
"strconv"
"strings"
"github.com/harness/gitness/app/gitspace/orchestrator/devcontainer"
"github.com/harness/gitness/app/gitspace/orchestrator/utils"
gitspaceTypes "github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/docker/docker/api/types/container"
)
var _ IDE = (*VSCodeWeb)(nil)
//go:embed script/find_vscode_web_path.sh
var findPathScript string
//go:embed media/vscodeweb/*
var mediaFiles embed.FS
const templateRunVSCodeWeb = "run_vscode_web.sh"
const templateSetupVSCodeWeb = "install_vscode_web.sh"
const startMarker = "START_MARKER"
const endMarker = "END_MARKER"
type VSCodeWebConfig struct {
Port int
}
type VSCodeWeb struct {
urlScheme string
config *VSCodeWebConfig
}
func NewVsCodeWebService(config *VSCodeWebConfig, urlScheme string) *VSCodeWeb {
return &VSCodeWeb{
urlScheme: urlScheme,
config: config,
}
}
// Setup runs the installScript which downloads the required version of the code-server binary.
func (v *VSCodeWeb) Setup(
ctx context.Context,
exec *devcontainer.Exec,
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
gitspaceLogger.Info("Installing VSCode Web inside container...")
payload := &gitspaceTypes.SetupVSCodeWebPayload{}
if args != nil {
if err := updateSetupPayloadFromArgs(args, payload, gitspaceLogger); err != nil {
return err
}
}
setupScript, err := utils.GenerateScriptFromTemplate(templateSetupVSCodeWeb, payload)
if err != nil {
return fmt.Errorf(
"failed to generate script to setup VSCode Web from template %s: %w",
templateSetupVSCodeWeb,
err,
)
}
err = exec.ExecuteCommandInHomeDirAndLog(ctx, setupScript, false, gitspaceLogger, false)
if err != nil {
return fmt.Errorf("failed to install VSCode Web: %w", err)
}
if err = v.updateMediaContent(ctx, exec); err != nil {
return err
}
gitspaceLogger.Info(fmt.Sprintf("Successfully installed %s IDE inside container", enum.IDETypeVSCodeWeb))
return nil
}
func (v *VSCodeWeb) updateMediaContent(ctx context.Context, exec *devcontainer.Exec) error {
findOutput, err := exec.ExecuteCommand(ctx, findPathScript, true, exec.DefaultWorkingDir)
if err != nil {
return fmt.Errorf("failed to find VSCode Web install path: %w", err)
}
path := findOutput
startIndex := strings.Index(path, startMarker)
endIndex := strings.Index(path, endMarker)
if startIndex == -1 || endIndex == -1 || startIndex >= endIndex {
return fmt.Errorf("could not find media folder path from find output: %s", path)
}
mediaFolderPath := path[startIndex+len(startMarker) : endIndex]
if len(mediaFolderPath) == 0 {
return fmt.Errorf("media folder path should not be empty, VSCode web is not installed")
}
err = v.copyMediaToContainer(ctx, exec, mediaFolderPath)
if err != nil {
return fmt.Errorf("failed to copy media folder to container at path %s: %w", mediaFolderPath, err)
}
return nil
}
// Run runs the code-server binary.
func (v *VSCodeWeb) Run(
ctx context.Context,
exec *devcontainer.Exec,
args map[gitspaceTypes.IDEArg]any,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
payload := gitspaceTypes.RunVSCodeWebPayload{
Port: strconv.Itoa(v.config.Port),
}
if args != nil {
if proxyURI, exists := args[gitspaceTypes.VSCodeProxyURIArg]; exists {
// Perform a type assertion to ensure proxyURI is a string
proxyURIStr, ok := proxyURI.(string)
if !ok {
return fmt.Errorf("%s is not a string", gitspaceTypes.VSCodeProxyURIArg)
}
payload.ProxyURI = proxyURIStr
}
}
runScript, err := utils.GenerateScriptFromTemplate(templateRunVSCodeWeb, payload)
if err != nil {
return fmt.Errorf(
"failed to generate script to run VSCode Web from template %s: %w",
templateRunVSCodeWeb,
err,
)
}
gitspaceLogger.Info("Starting IDE ...")
// Execute the script in the home directory
err = exec.ExecuteCommandInHomeDirAndLog(ctx, runScript, false, gitspaceLogger, true)
if err != nil {
return fmt.Errorf("failed to run VSCode Web: %w", err)
}
return nil
}
func updateSetupPayloadFromArgs(
args map[gitspaceTypes.IDEArg]any,
payload *gitspaceTypes.SetupVSCodeWebPayload,
gitspaceLogger gitspaceTypes.GitspaceLogger,
) error {
if customization, exists := args[gitspaceTypes.VSCodeCustomizationArg]; exists {
// Perform a type assertion to ensure customization is a VSCodeCustomizationSpecs
vsCodeCustomizationSpecs, ok := customization.(types.VSCodeCustomizationSpecs)
if !ok {
return fmt.Errorf("customization is not of type VSCodeCustomizationSpecs")
}
payload.Extensions = vsCodeCustomizationSpecs.Extensions
gitspaceLogger.Info(fmt.Sprintf(
"VSCode Customizations: Extensions %v", vsCodeCustomizationSpecs.Extensions))
}
return nil
}
// PortAndProtocol returns the port on which the code-server is listening.
func (v *VSCodeWeb) Port() *types.GitspacePort {
return &types.GitspacePort{
Port: v.config.Port,
Protocol: enum.CommunicationProtocolHTTP,
}
}
func (v *VSCodeWeb) Type() enum.IDEType {
return enum.IDETypeVSCodeWeb
}
func (v *VSCodeWeb) copyMediaToContainer(
ctx context.Context,
exec *devcontainer.Exec,
path string,
) error {
// Create a buffer to hold the tar data
var tarBuffer bytes.Buffer
tarWriter := tar.NewWriter(&tarBuffer)
// Walk through the embedded files and add them to the tar archive
err := embedToTar(tarWriter, "media/vscodeweb", "")
if err != nil {
return fmt.Errorf("error creating tar archive: %w", err)
}
// Close the tar writer
closeErr := tarWriter.Close()
if closeErr != nil {
return fmt.Errorf("error closing tar writer: %w", closeErr)
}
// Copy the tar archive to the container
err = exec.DockerClient.CopyToContainer(
ctx,
exec.ContainerName,
path,
&tarBuffer,
container.CopyToContainerOptions{},
)
if err != nil {
return fmt.Errorf("error copying files to container: %w", err)
}
return nil
}
func embedToTar(tarWriter *tar.Writer, baseDir, prefix string) error {
entries, err := mediaFiles.ReadDir(baseDir)
if err != nil {
return fmt.Errorf("error reading media files from base dir %s: %w", baseDir, err)
}
for _, entry := range entries {
fullPath := filepath.Join(baseDir, entry.Name())
info, err2 := entry.Info()
if err2 != nil {
return fmt.Errorf("error getting file info for %s: %w", fullPath, err2)
}
// Remove the baseDir from the header name to ensure the files are copied directly into the destination
headerName := filepath.Join(prefix, entry.Name())
header, err2 := tar.FileInfoHeader(info, "")
if err2 != nil {
return fmt.Errorf("error getting file info header for %s: %w", fullPath, err2)
}
header.Name = strings.TrimPrefix(headerName, "/")
if err2 = tarWriter.WriteHeader(header); err2 != nil {
return fmt.Errorf("error writing file header %+v: %w", header, err2)
}
if !entry.IsDir() {
file, err3 := mediaFiles.Open(fullPath)
if err3 != nil {
return fmt.Errorf("error opening file %s: %w", fullPath, err3)
}
defer file.Close()
_, err3 = io.Copy(tarWriter, file)
if err3 != nil {
return fmt.Errorf("error copying file %s: %w", fullPath, err3)
}
} else {
if err3 := embedToTar(tarWriter, fullPath, headerName); err3 != nil {
return fmt.Errorf("error embeding file %s: %w", fullPath, err3)
}
}
}
return nil
}
// GenerateURL returns the url to redirect user to ide(here to another ta).
func (v *VSCodeWeb) GenerateURL(absoluteRepoPath, host, port, _ string) string {
relativeRepoPath := strings.TrimPrefix(absoluteRepoPath, "/")
ideURL := url.URL{
Scheme: v.urlScheme,
Host: host + ":" + port,
RawQuery: filepath.Join("folder=", relativeRepoPath),
}
return ideURL.String()
}
func (v *VSCodeWeb) GeneratePluginURL(_, _ string) string {
return ""
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/orchestrator/ide/common.go | app/gitspace/orchestrator/ide/common.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ide
import (
"fmt"
gitspaceTypes "github.com/harness/gitness/app/gitspace/types"
"github.com/harness/gitness/types"
)
func getIDEDownloadURL(
args map[gitspaceTypes.IDEArg]any,
) (types.IDEDownloadURLs, error) {
downloadURL, exists := args[gitspaceTypes.IDEDownloadURLArg]
if !exists {
return types.IDEDownloadURLs{}, fmt.Errorf("ide download url not found")
}
downloadURLs, ok := downloadURL.(types.IDEDownloadURLs)
if !ok {
return types.IDEDownloadURLs{}, fmt.Errorf("ide download url is not of type JetBrainsSpecs")
}
return downloadURLs, nil
}
func getIDEDirName(args map[gitspaceTypes.IDEArg]any) (string, error) {
dirName, exists := args[gitspaceTypes.IDEDIRNameArg]
if !exists {
return "", fmt.Errorf("ide dirname not found")
}
dirNameStr, ok := dirName.(string)
if !ok {
return "", fmt.Errorf("ide dirname is not of type string")
}
return dirNameStr, nil
}
func getRepoName(
args map[gitspaceTypes.IDEArg]any,
) (string, error) {
repoName, exists := args[gitspaceTypes.IDERepoNameArg]
if !exists {
return "", nil // No repo name found, nothing to do
}
repoNameStr, ok := repoName.(string)
if !ok {
return "", fmt.Errorf("repo name is not of type string")
}
return repoNameStr, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/secret/wire.go | app/gitspace/secret/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package secret
import "github.com/google/wire"
var WireSet = wire.NewSet(
ProvidePasswordResolver,
ProvideResolverFactory,
)
func ProvidePasswordResolver() *PasswordResolver {
return NewPasswordResolver()
}
func ProvideResolverFactory(passwordResolver *PasswordResolver) *ResolverFactory {
return NewFactoryWithProviders(passwordResolver)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/secret/resolver.go | app/gitspace/secret/resolver.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package secret
import (
"context"
"github.com/harness/gitness/app/gitspace/secret/enum"
)
type ResolvedSecret struct {
SecretValue string
}
type ResolutionContext struct {
SecretRef string
SpaceIdentifier string
UserIdentifier string
GitspaceIdentifier string
}
type Resolver interface {
Resolve(ctx context.Context, resolutionContext ResolutionContext) (ResolvedSecret, error)
Type() enum.SecretType
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/secret/password_resolver.go | app/gitspace/secret/password_resolver.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package secret
import (
"context"
"github.com/harness/gitness/app/gitspace/secret/enum"
)
type PasswordResolver struct {
}
const defaultPassword = "Harness@123"
func NewPasswordResolver() *PasswordResolver {
return &PasswordResolver{}
}
// Resolve implements Resolver.
func (p *PasswordResolver) Resolve(_ context.Context, _ ResolutionContext) (ResolvedSecret, error) {
return ResolvedSecret{
SecretValue: defaultPassword,
}, nil
}
func (p *PasswordResolver) Type() enum.SecretType {
return enum.PasswordSecretType
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/secret/resolver_factory.go | app/gitspace/secret/resolver_factory.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package secret
import (
"fmt"
"github.com/harness/gitness/app/gitspace/secret/enum"
)
type ResolverFactory struct {
resolvers map[enum.SecretType]Resolver
}
func NewFactoryWithProviders(resolvers ...Resolver) *ResolverFactory {
resolversMap := make(map[enum.SecretType]Resolver)
for _, r := range resolvers {
resolversMap[r.Type()] = r
}
return &ResolverFactory{resolvers: resolversMap}
}
func (f *ResolverFactory) GetSecretResolver(secretType enum.SecretType) (Resolver, error) {
val := f.resolvers[secretType]
if val == nil {
return nil, fmt.Errorf("unknown secret type: %s", secretType)
}
return val, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/secret/enum/types.go | app/gitspace/secret/enum/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package enum
type SecretType string
const (
SSHSecretType SecretType = "ssh_key"
PasswordSecretType SecretType = "password"
JWTSecretType SecretType = "jwt"
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/infrastructure/wire.go | app/gitspace/infrastructure/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package infrastructure
import (
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/infraprovider"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideInfraProvisionerService,
)
func ProvideInfraProvisionerService(
infraProviderConfig store.InfraProviderConfigStore,
infraProviderResource store.InfraProviderResourceStore,
providerFactory infraprovider.Factory,
infraProviderTemplateStore store.InfraProviderTemplateStore,
infraProvisionedStore store.InfraProvisionedStore,
config *Config,
) InfraProvisioner {
return NewInfraProvisionerService(
infraProviderConfig,
infraProviderResource,
providerFactory,
infraProviderTemplateStore,
infraProvisionedStore,
config,
)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/infrastructure/infra_post_exec.go | app/gitspace/infrastructure/infra_post_exec.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package infrastructure
import (
"context"
"encoding/json"
"fmt"
"math"
"strconv"
"time"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// PostInfraEventComplete performs action taken on completion of the submitted infra task which can be
// success or failure. It stores the infrastructure details in the db depending on the provisioning type.
func (i InfraProvisioner) PostInfraEventComplete(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
infra types.Infrastructure,
eventType enum.InfraEvent,
) error {
infraProvider, err := i.providerFactory.GetInfraProvider(infra.ProviderType)
if err != nil {
return fmt.Errorf("unable to get infra provider of type %v: %w", infra.ProviderType, err)
}
if infraProvider.ProvisioningType() != enum.InfraProvisioningTypeNew {
return nil
}
switch eventType {
case enum.InfraEventProvision,
enum.InfraEventDeprovision,
enum.InfraEventStop,
enum.InfraEventCleanup:
return i.UpdateInfraProvisioned(ctx, gitspaceConfig.GitspaceInstance.ID, infra)
default:
return fmt.Errorf("unsupported event type: %s", eventType)
}
}
func (i InfraProvisioner) UpdateInfraProvisioned(
ctx context.Context,
gitspaceInstanceID int64,
infrastructure types.Infrastructure,
) error {
infraProvisionedLatest, err := i.infraProvisionedStore.FindLatestByGitspaceInstanceID(ctx, gitspaceInstanceID)
if err != nil {
return fmt.Errorf(
"could not find latest infra provisioned entity for instance %d: %w", gitspaceInstanceID, err)
}
responseMetadata, err := json.Marshal(infrastructure)
if err != nil {
return fmt.Errorf("unable to marshal infra object %+v: %w", responseMetadata, err)
}
responseMetaDataJSON := string(responseMetadata)
infraProvisionedLatest.InfraStatus = infrastructure.Status
infraProvisionedLatest.ServerHostIP = infrastructure.AgentHost
infraProvisionedLatest.ServerHostPort = strconv.Itoa(infrastructure.AgentPort)
proxyHost := infrastructure.AgentHost
if infrastructure.ProxyAgentHost != "" {
proxyHost = infrastructure.ProxyAgentHost
}
infraProvisionedLatest.ProxyHost = proxyHost
proxyPort := infrastructure.AgentPort
if infrastructure.ProxyAgentPort != 0 {
proxyPort = infrastructure.ProxyAgentPort
}
if proxyPort > math.MaxInt32 || proxyPort < math.MinInt32 {
return fmt.Errorf("proxyPort value %d exceeds int32 range", proxyPort)
}
infraProvisionedLatest.ProxyPort = int32(proxyPort)
infraProvisionedLatest.ResponseMetadata = &responseMetaDataJSON
infraProvisionedLatest.Updated = time.Now().UnixMilli()
infraProvisionedLatest.GatewayHost = infrastructure.GatewayHost
err = i.infraProvisionedStore.Update(ctx, infraProvisionedLatest)
if err != nil {
return fmt.Errorf("unable to update infraProvisioned %d: %w", infraProvisionedLatest.ID, err)
}
return nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/infrastructure/find.go | app/gitspace/infrastructure/find.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package infrastructure
import (
"context"
"encoding/json"
"fmt"
"github.com/harness/gitness/infraprovider"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
)
// Find finds the provisioned infra resources for the gitspace instance.
func (i InfraProvisioner) Find(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
) (*types.Infrastructure, error) {
infraProviderResource := gitspaceConfig.InfraProviderResource
infraProviderEntity, err := i.getConfigFromResource(ctx, infraProviderResource)
if err != nil {
return nil, err
}
infraProvider, err := i.providerFactory.GetInfraProvider(infraProviderEntity.Type)
if err != nil {
return nil, fmt.Errorf("unable to get infra provider of type %v: %w", infraProviderEntity.Type, err)
}
var infra *types.Infrastructure
//nolint:nestif
if infraProvider.ProvisioningType() == enum.InfraProvisioningTypeNew {
inputParams, _, err := i.paramsForProvisioningTypeNew(ctx, gitspaceConfig)
if err != nil {
return nil, err
}
infra, err = i.GetInfraFromStoredInfo(ctx, gitspaceConfig)
if err != nil {
return nil, fmt.Errorf("failed to find infrastructure from stored info: %w", err)
}
status, err := infraProvider.FindInfraStatus(
ctx,
gitspaceConfig.Identifier,
gitspaceConfig.GitspaceInstance.Identifier,
inputParams,
)
if err != nil {
return nil, fmt.Errorf("failed to find infra status: %w", err)
}
if status != nil {
infra.Status = *status
}
} else {
inputParams, _, err := i.paramsForProvisioningTypeExisting(ctx, infraProviderResource, infraProvider)
if err != nil {
return nil, err
}
infra, err = infraProvider.Find(
ctx,
gitspaceConfig.SpaceID,
gitspaceConfig.SpacePath,
gitspaceConfig.Identifier,
inputParams,
)
if err != nil {
return nil, fmt.Errorf("failed to find infrastructure from provider: %w", err)
}
}
gitspaceScheme, err := getGitspaceScheme(gitspaceConfig.IDE, infraProviderResource.Metadata["gitspace_scheme"])
if err != nil {
return nil, fmt.Errorf("failed to get gitspace_scheme: %w", err)
}
infra.GitspaceScheme = gitspaceScheme
return infra, nil
}
func (i InfraProvisioner) paramsForProvisioningTypeNew(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
) ([]types.InfraProviderParameter, map[string]any, error) {
infraProvisionedLatest, err := i.infraProvisionedStore.FindLatestByGitspaceInstanceID(ctx,
gitspaceConfig.GitspaceInstance.ID)
if err != nil {
return nil, nil, fmt.Errorf(
"could not find latest infra provisioned entity for instance %d: %w",
gitspaceConfig.GitspaceInstance.ID, err)
}
if infraProvisionedLatest.InputParams == "" {
return []types.InfraProviderParameter{}, nil, err
}
allParams, err := deserializeInfraProviderParams(infraProvisionedLatest.InputParams)
if err != nil {
return nil, nil, err
}
infraProviderConfig, err := i.infraProviderConfigStore.Find(ctx,
gitspaceConfig.InfraProviderResource.InfraProviderConfigID, true)
if err != nil {
return nil, nil, err
}
return allParams, infraProviderConfig.Metadata, nil
}
func deserializeInfraProviderParams(in string) ([]types.InfraProviderParameter, error) {
var parameters []types.InfraProviderParameter
err := json.Unmarshal([]byte(in), ¶meters)
if err != nil {
return nil, fmt.Errorf("unable to unmarshal infra provider params %+v: %w", in, err)
}
return parameters, nil
}
func (i InfraProvisioner) paramsForProvisioningTypeExisting(
ctx context.Context,
infraProviderResource types.InfraProviderResource,
infraProvider infraprovider.InfraProvider,
) ([]types.InfraProviderParameter, map[string]any, error) {
allParams, configMetadata, err := i.getAllParamsFromDB(ctx, infraProviderResource, infraProvider)
if err != nil {
return nil, nil, fmt.Errorf("could not get all params from DB while finding: %w", err)
}
return allParams, configMetadata, nil
}
func getGitspaceScheme(ideType enum.IDEType, gitspaceSchemeFromMetadata string) (string, error) {
switch ideType {
case enum.IDETypeVSCodeWeb:
return gitspaceSchemeFromMetadata, nil
case enum.IDETypeVSCode, enum.IDETypeWindsurf, enum.IDETypeCursor:
return "ssh", nil
case enum.IDETypeIntelliJ, enum.IDETypePyCharm, enum.IDETypeGoland, enum.IDETypeWebStorm, enum.IDETypeCLion,
enum.IDETypePHPStorm, enum.IDETypeRubyMine, enum.IDETypeRider:
return "ssh", nil
default:
return "", fmt.Errorf("unknown ideType %s", ideType)
}
}
func (i InfraProvisioner) GetInfraFromStoredInfo(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
) (*types.Infrastructure, error) {
infraProvisioned, err := i.infraProvisionedStore.FindLatestByGitspaceInstanceID(
ctx,
gitspaceConfig.GitspaceInstance.ID,
)
if err != nil {
return nil, fmt.Errorf("failed to find infraProvisioned: %w", err)
}
var infra types.Infrastructure
err = json.Unmarshal([]byte(*infraProvisioned.ResponseMetadata), &infra)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal response metadata: %w", err)
}
return &infra, nil
}
func (i InfraProvisioner) GetStoppedInfraFromStoredInfo(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
) (types.Infrastructure, error) {
var infra types.Infrastructure
var infraProvisioned *types.InfraProvisioned
var err error
if gitspaceConfig.IsMarkedForInfraReset {
infraProvisioned, err = i.infraProvisionedStore.FindStoppedInfraForGitspaceConfigIdentifierByState(
ctx,
gitspaceConfig.Identifier,
enum.GitspaceInstanceStatePendingCleanup,
)
if err != nil {
log.Warn().Err(err).Msgf("failed to find infraProvisioned with state pending cleanup: %v", err)
}
}
if infraProvisioned == nil {
infraProvisioned, err = i.infraProvisionedStore.FindStoppedInfraForGitspaceConfigIdentifierByState(
ctx,
gitspaceConfig.Identifier,
enum.GitspaceInstanceStateStarting,
)
if err != nil {
return infra, fmt.Errorf("failed to find infraProvisioned with state starting: %w", err)
}
}
err = json.Unmarshal([]byte(*infraProvisioned.ResponseMetadata), &infra)
if err != nil {
// empty infra is returned to avoid nil pointer dereference
return infra, fmt.Errorf("failed to unmarshal response metadata: %w", err)
}
return infra, nil
}
// Methods to find infra provider resources.
func (i InfraProvisioner) getConfigFromResource(
ctx context.Context,
infraProviderResource types.InfraProviderResource,
) (*types.InfraProviderConfig, error) {
config, err := i.infraProviderConfigStore.Find(ctx, infraProviderResource.InfraProviderConfigID, true)
if err != nil {
return nil, fmt.Errorf(
"unable to get infra provider details for ID %d: %w",
infraProviderResource.InfraProviderConfigID, err)
}
return config, nil
}
func (i InfraProvisioner) getAllParamsFromDB(
ctx context.Context,
infraProviderResource types.InfraProviderResource,
infraProvider infraprovider.InfraProvider,
) ([]types.InfraProviderParameter, map[string]any, error) {
var allParams []types.InfraProviderParameter
templateParams, err := i.getTemplateParams(ctx, infraProvider, infraProviderResource)
if err != nil {
return nil, nil, err
}
allParams = append(allParams, templateParams...)
params := i.paramsFromResource(infraProviderResource, infraProvider)
allParams = append(allParams, params...)
configMetadata, err := i.configMetadata(ctx, infraProviderResource)
if err != nil {
return nil, nil, err
}
return allParams, configMetadata, nil
}
func (i InfraProvisioner) getTemplateParams(
ctx context.Context,
infraProvider infraprovider.InfraProvider,
infraProviderResource types.InfraProviderResource,
) ([]types.InfraProviderParameter, error) {
var params []types.InfraProviderParameter
templateParams := infraProvider.TemplateParams()
for _, param := range templateParams {
key := param.Name
if infraProviderResource.Metadata[key] != "" {
templateIdentifier := infraProviderResource.Metadata[key]
template, err := i.infraProviderTemplateStore.FindByIdentifier(
ctx, infraProviderResource.SpaceID, templateIdentifier)
if err != nil {
return nil, fmt.Errorf("unable to get template params for ID %s: %w",
infraProviderResource.Metadata[key], err)
}
params = append(params, types.InfraProviderParameter{
Name: key,
Value: template.Data,
})
}
}
return params, nil
}
func (i InfraProvisioner) paramsFromResource(
infraProviderResource types.InfraProviderResource,
infraProvider infraprovider.InfraProvider,
) []types.InfraProviderParameter {
// NOTE: templateParamsMap is required to filter out template params since their values have already been fetched
// and we dont need the template identifiers, which are the values for template params in the resource Metadata.
templateParamsMap := make(map[string]bool)
for _, templateParam := range infraProvider.TemplateParams() {
templateParamsMap[templateParam.Name] = true
}
params := make([]types.InfraProviderParameter, 0, len(infraProviderResource.Metadata))
for key, value := range infraProviderResource.Metadata {
if key == "" || value == "" || templateParamsMap[key] {
continue
}
params = append(params, types.InfraProviderParameter{
Name: key,
Value: value,
})
}
return params
}
func (i InfraProvisioner) configMetadata(
ctx context.Context,
infraProviderResource types.InfraProviderResource,
) (map[string]any, error) {
infraProviderConfig, err := i.infraProviderConfigStore.Find(ctx, infraProviderResource.InfraProviderConfigID, true)
if err != nil {
return nil, err
}
return infraProviderConfig.Metadata, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/infrastructure/trigger_infra_event.go | app/gitspace/infrastructure/trigger_infra_event.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package infrastructure
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/infraprovider"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
)
type Config struct {
AgentPort int
UseSSHPiper bool
}
type InfraEventOpts struct {
RequiredGitspacePorts []types.GitspacePort
DeleteUserData bool
}
type InfraProvisioner struct {
infraProviderConfigStore store.InfraProviderConfigStore
infraProviderResourceStore store.InfraProviderResourceStore
providerFactory infraprovider.Factory
infraProviderTemplateStore store.InfraProviderTemplateStore
infraProvisionedStore store.InfraProvisionedStore
config *Config
}
func NewInfraProvisionerService(
infraProviderConfigStore store.InfraProviderConfigStore,
infraProviderResourceStore store.InfraProviderResourceStore,
providerFactory infraprovider.Factory,
infraProviderTemplateStore store.InfraProviderTemplateStore,
infraProvisionedStore store.InfraProvisionedStore,
config *Config,
) InfraProvisioner {
return InfraProvisioner{
infraProviderConfigStore: infraProviderConfigStore,
infraProviderResourceStore: infraProviderResourceStore,
providerFactory: providerFactory,
infraProviderTemplateStore: infraProviderTemplateStore,
infraProvisionedStore: infraProvisionedStore,
config: config,
}
}
// TriggerInfraEvent an interaction with the infrastructure, and once completed emits event in an asynchronous manner.
func (i InfraProvisioner) TriggerInfraEvent(
ctx context.Context,
eventType enum.InfraEvent,
gitspaceConfig types.GitspaceConfig,
infra *types.Infrastructure,
) error {
opts := InfraEventOpts{DeleteUserData: false}
return i.TriggerInfraEventWithOpts(ctx, eventType, gitspaceConfig, infra, opts)
}
// TriggerInfraEventWithOpts triggers the provisionining of infra resources using the
// infraProviderResource with different infra providers.
// Stop event deprovisions those resources which can be stopped without losing the Gitspace data.
// CleanupInstance event cleans up resources exclusive for a gitspace instance
// Deprovision triggers deprovisioning of resources created for a Gitspace.
// canDeleteUserData = true -> deprovision of all resources
// canDeleteUserData = false -> deprovision of all resources except storage associated to user data.
func (i InfraProvisioner) TriggerInfraEventWithOpts(
ctx context.Context,
eventType enum.InfraEvent,
gitspaceConfig types.GitspaceConfig,
infra *types.Infrastructure,
opts InfraEventOpts,
) error {
logger := log.Logger.With().Logger()
infraProviderEntity, err := i.getConfigFromResource(ctx, gitspaceConfig.InfraProviderResource)
if err != nil {
return err
}
infraProvider, err := i.providerFactory.GetInfraProvider(infraProviderEntity.Type)
if err != nil {
return fmt.Errorf("unable to get infra provider of type %v: %w", infraProviderEntity.Type, err)
}
allParams, configMetadata, err := i.getAllParamsFromDB(ctx, gitspaceConfig.InfraProviderResource, infraProvider)
if err != nil {
return fmt.Errorf("could not get all params from DB while provisioning: %w", err)
}
switch eventType {
case enum.InfraEventProvision:
// We usually suspend/hibernate infra so during subsequent provision we can reuse it.
// provision resume suspended infra(VM) if it was created before else create new infra during provision.
var stoppedInfra types.Infrastructure
stoppedInfra, err = i.GetStoppedInfraFromStoredInfo(ctx, gitspaceConfig)
if err != nil {
logger.Info().
Str("error", err.Error()).
Msgf(
"could not find stopped infra provisioned entity for instance %s",
gitspaceConfig.Identifier,
)
}
if infraProvider.ProvisioningType() == enum.InfraProvisioningTypeNew {
return i.provisionNewInfrastructure(
ctx,
infraProvider,
infraProviderEntity.Type,
gitspaceConfig,
opts.RequiredGitspacePorts,
stoppedInfra,
configMetadata,
allParams,
)
}
return i.provisionExistingInfrastructure(
ctx,
infraProvider,
gitspaceConfig,
opts.RequiredGitspacePorts,
stoppedInfra,
)
case enum.InfraEventDeprovision:
if infraProvider.ProvisioningType() == enum.InfraProvisioningTypeNew {
return i.deprovisionNewInfrastructure(
ctx,
infraProvider,
gitspaceConfig,
*infra,
opts.DeleteUserData,
configMetadata,
allParams,
)
}
return infraProvider.Deprovision(ctx, *infra, gitspaceConfig, opts.DeleteUserData, configMetadata, allParams)
case enum.InfraEventCleanup:
return infraProvider.CleanupInstanceResources(ctx, *infra)
case enum.InfraEventStop:
return infraProvider.Stop(ctx, *infra, gitspaceConfig, configMetadata)
default:
return fmt.Errorf("unsupported event type: %s", eventType)
}
}
func (i InfraProvisioner) provisionNewInfrastructure(
ctx context.Context,
infraProvider infraprovider.InfraProvider,
infraProviderType enum.InfraProviderType,
gitspaceConfig types.GitspaceConfig,
requiredGitspacePorts []types.GitspacePort,
stoppedInfra types.Infrastructure,
configMetadata map[string]any,
allParams []types.InfraProviderParameter,
) error {
// Logic for new provisioning...
infraProvisionedLatest, _ := i.infraProvisionedStore.FindLatestByGitspaceInstanceID(
ctx, gitspaceConfig.GitspaceInstance.ID)
if infraProvisionedLatest != nil &&
infraProvisionedLatest.InfraStatus == enum.InfraStatusPending &&
time.Since(time.UnixMilli(infraProvisionedLatest.Updated)).Milliseconds() < (10*60*1000) {
return fmt.Errorf("there is already infra provisioning in pending state %d", infraProvisionedLatest.ID)
} else if infraProvisionedLatest != nil {
infraProvisionedLatest.InfraStatus = enum.InfraStatusUnknown
err := i.infraProvisionedStore.Update(ctx, infraProvisionedLatest)
if err != nil {
return fmt.Errorf("could not update Infra Provisioned entity: %w", err)
}
}
infraProviderResource := gitspaceConfig.InfraProviderResource
err := infraProvider.ValidateParams(allParams)
if err != nil {
return fmt.Errorf("invalid provisioning params %v: %w", infraProviderResource.Metadata, err)
}
now := time.Now()
paramsBytes, err := serializeInfraProviderParams(allParams)
if err != nil {
return err
}
infrastructure := types.Infrastructure{
Identifier: gitspaceConfig.GitspaceInstance.Identifier,
SpaceID: gitspaceConfig.SpaceID,
SpacePath: gitspaceConfig.SpacePath,
GitspaceConfigIdentifier: gitspaceConfig.Identifier,
GitspaceInstanceIdentifier: gitspaceConfig.GitspaceInstance.Identifier,
ProviderType: infraProviderType,
InputParameters: allParams,
ConfigMetadata: configMetadata,
InstanceInfo: stoppedInfra.InstanceInfo,
Status: enum.InfraStatusPending,
}
if i.useRoutingKey(infraProviderType, gitspaceConfig.GitspaceInstance.AccessType) {
infrastructure.RoutingKey = i.getRoutingKey(gitspaceConfig.SpacePath, gitspaceConfig.Identifier)
}
responseMetadata, err := json.Marshal(infrastructure)
if err != nil {
return fmt.Errorf("unable to marshal infra object %+v: %w", responseMetadata, err)
}
responseMetaDataJSON := string(responseMetadata)
infraProvisioned := &types.InfraProvisioned{
GitspaceInstanceID: gitspaceConfig.GitspaceInstance.ID,
InfraProviderType: infraProviderType,
InfraProviderResourceID: infraProviderResource.ID,
Created: now.UnixMilli(),
Updated: now.UnixMilli(),
InputParams: paramsBytes,
InfraStatus: enum.InfraStatusPending,
SpaceID: gitspaceConfig.SpaceID,
ResponseMetadata: &responseMetaDataJSON,
}
err = i.infraProvisionedStore.Create(ctx, infraProvisioned)
if err != nil {
return fmt.Errorf("unable to create infraProvisioned entry for %d", gitspaceConfig.GitspaceInstance.ID)
}
agentPort := i.config.AgentPort
err = infraProvider.Provision(
ctx,
gitspaceConfig,
agentPort,
requiredGitspacePorts,
allParams,
configMetadata,
infrastructure,
)
if err != nil {
infraProvisioned.InfraStatus = enum.InfraStatusUnknown
infraProvisioned.Updated = time.Now().UnixMilli()
updateErr := i.infraProvisionedStore.Update(ctx, infraProvisioned)
if updateErr != nil {
log.Err(updateErr).Msgf("unable to update infraProvisioned Entry for %d", infraProvisioned.ID)
}
return fmt.Errorf(
"unable to trigger provision infrastructure for gitspaceConfigIdentifier %v: %w",
gitspaceConfig.Identifier,
err,
)
}
return nil
}
func (i InfraProvisioner) provisionExistingInfrastructure(
ctx context.Context,
infraProvider infraprovider.InfraProvider,
gitspaceConfig types.GitspaceConfig,
requiredGitspacePorts []types.GitspacePort,
stoppedInfra types.Infrastructure,
) error {
allParams, configMetadata, err := i.getAllParamsFromDB(ctx, gitspaceConfig.InfraProviderResource, infraProvider)
if err != nil {
return fmt.Errorf("could not get all params from DB while provisioning: %w", err)
}
err = infraProvider.ValidateParams(allParams)
if err != nil {
return fmt.Errorf("invalid provisioning params %v: %w", gitspaceConfig.InfraProviderResource.Metadata, err)
}
err = infraProvider.Provision(
ctx,
gitspaceConfig,
0, // NOTE: Agent port is not required for provisioning type Existing.
requiredGitspacePorts,
allParams,
configMetadata,
stoppedInfra,
)
if err != nil {
return fmt.Errorf(
"unable to trigger provision infrastructure for gitspaceConfigIdentifier %v: %w",
gitspaceConfig.Identifier,
err,
)
}
return nil
}
func (i InfraProvisioner) deprovisionNewInfrastructure(
ctx context.Context,
infraProvider infraprovider.InfraProvider,
gitspaceConfig types.GitspaceConfig,
infra types.Infrastructure,
canDeleteUserData bool,
configMetadata map[string]any,
params []types.InfraProviderParameter,
) error {
infraProvisionedLatest, err := i.infraProvisionedStore.FindLatestByGitspaceInstanceID(
ctx, gitspaceConfig.GitspaceInstance.ID)
if err != nil {
return fmt.Errorf(
"could not find latest infra provisioned entity for instance %d: %w",
gitspaceConfig.GitspaceInstance.ID, err)
}
if infraProvisionedLatest.InfraStatus == enum.InfraStatusDestroyed {
log.Debug().Msgf(
"infra already deprovisioned for gitspace instance %d", gitspaceConfig.GitspaceInstance.ID)
}
err = infraProvider.Deprovision(ctx, infra, gitspaceConfig, canDeleteUserData, configMetadata, params)
if err != nil {
return fmt.Errorf("unable to trigger deprovision infra %s: %w", infra.Identifier, err)
}
return err
}
func serializeInfraProviderParams(in []types.InfraProviderParameter) (string, error) {
output, err := json.Marshal(in)
if err != nil {
return "", fmt.Errorf("unable to marshal infra provider params: %w", err)
}
return string(output), nil
}
func (i InfraProvisioner) useRoutingKey(
infraProviderType enum.InfraProviderType,
accessType enum.GitspaceAccessType,
) bool {
return i.config.UseSSHPiper && infraProviderType == enum.InfraProviderTypeHybridVMAWS &&
accessType == enum.GitspaceAccessTypeSSHKey
}
func (i InfraProvisioner) getRoutingKey(spacePath string, gitspaceConfigIdentifier string) string {
return uuid.NewSHA1(uuid.NameSpaceURL,
fmt.Appendf(nil, "%s%s", spacePath, gitspaceConfigIdentifier)).String()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/types/zerolog_adapter.go | app/gitspace/types/zerolog_adapter.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"github.com/rs/zerolog"
)
// NewZerologAdapter creates a new adapter from a zerolog.Logger.
func NewZerologAdapter(logger *zerolog.Logger) *ZerologAdapter {
return &ZerologAdapter{logger: logger}
}
// Implement the Logger interface for ZerologAdapter.
func (z *ZerologAdapter) Info(msg string) {
z.logger.Info().Msg("INFO: " + msg)
}
func (z *ZerologAdapter) Debug(msg string) {
z.logger.Debug().Msg("DEBUG: " + msg)
}
func (z *ZerologAdapter) Warn(msg string) {
z.logger.Warn().Msg("WARN: " + msg)
}
func (z *ZerologAdapter) Error(msg string, err error) {
z.logger.Err(err).Msg("ERROR: " + msg)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/types/types.go | app/gitspace/types/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"github.com/harness/gitness/types"
"github.com/rs/zerolog"
)
type IDEArg string
const (
VSCodeCustomizationArg IDEArg = "VSCODE_CUSTOMIZATION"
JetBrainsCustomizationArg IDEArg = "JETBRAINS_CUSTOMIZATION"
VSCodeProxyURIArg IDEArg = "VSCODE_PROXY_URI"
IDERepoNameArg IDEArg = "IDE_REPO_NAME"
IDEDownloadURLArg IDEArg = "IDE_DOWNLOAD_URL"
IDEDIRNameArg IDEArg = "IDE_DIR_NAME"
)
type GitspaceLogger interface {
Info(msg string)
Debug(msg string)
Warn(msg string)
Error(msg string, err error)
}
type ZerologAdapter struct {
logger *zerolog.Logger
}
type DockerRegistryAuth struct {
// only host name is required
// eg: docker.io instead of https://docker.io
RegistryURL string
Username *types.MaskSecret
Password *types.MaskSecret
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/types/script_template_payload.go | app/gitspace/types/script_template_payload.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import "github.com/harness/gitness/types/enum"
type CloneCodePayload struct {
RepoURL string
Image string
Branch string
RepoName string
Name string
Email string
}
type SetupGitInstallPayload struct {
OSInfoScript string
}
type SetupGitCredentialsPayload struct {
CloneURLWithCreds string
}
type RunVSCodeWebPayload struct {
Port string
Arguments string
ProxyURI string
}
type SetupVSCodeWebPayload struct {
Extensions []string
}
type SetupUserPayload struct {
Username string
AccessKey string
AccessType enum.GitspaceAccessType
HomeDir string
}
type SetupSSHServerPayload struct {
Username string
AccessType enum.GitspaceAccessType
OSInfoScript string
}
type SetupVSCodeExtensionsPayload struct {
Username string
Extensions string
RepoName string
}
type RunSSHServerPayload struct {
Port string
}
type InstallToolsPayload struct {
OSInfoScript string
}
type SupportedOSDistributionPayload struct {
OSInfoScript string
}
type SetEnvPayload struct {
EnvVariables []string
}
type SetupJetBrainsIDEPayload struct {
Username string
IdeDownloadURLArm64 string
IdeDownloadURLAmd64 string
IdeDirName string
}
type SetupJetBrainsPluginPayload struct {
Username string
IdeDirName string
// IdePluginsName contains like of plugins each separated with space.
IdePluginsName string
}
type RunIntellijIDEPayload struct {
Username string
RepoName string
IdeDownloadURL string
IdeDirName string
}
type SetupClaudeCodePayload struct {
OSInfoScript string
}
type ConfigureClaudeCodePayload struct {
AnthropicAPIKey string
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/scm/public_scm.go | app/gitspace/scm/public_scm.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scm
import (
"bytes"
"context"
"fmt"
"io"
"net/url"
"os"
"path"
"strings"
"github.com/harness/gitness/git/command"
"github.com/harness/gitness/types"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
)
var _ ListingProvider = (*GenericSCM)(nil)
var _ AuthAndFileContentProvider = (*GenericSCM)(nil)
type GenericSCM struct {
}
func NewGenericSCM() *GenericSCM {
return &GenericSCM{}
}
func (s *GenericSCM) ListBranches(
_ context.Context,
_ *BranchFilter,
_ *ResolvedCredentials,
) ([]Branch, error) {
return []Branch{}, nil
}
func (s *GenericSCM) ListRepositories(
_ context.Context,
_ *RepositoryFilter,
_ *ResolvedCredentials,
) ([]Repository, error) {
return []Repository{}, nil
}
func (s *GenericSCM) GetFileContent(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
filePath string,
_ *ResolvedCredentials,
) ([]byte, error) {
gitWorkingDirectory := "/tmp/git/"
cloneDir := gitWorkingDirectory + uuid.New().String()
err := os.MkdirAll(cloneDir, os.ModePerm)
if err != nil {
return nil, fmt.Errorf("error creating directory %s: %w", cloneDir, err)
}
defer func() {
err = os.RemoveAll(cloneDir)
if err != nil {
log.Ctx(ctx).Warn().Err(err).Msg("Unable to remove working directory")
}
}()
log.Info().Msg("Cloning the repository...")
cmd := command.New("clone",
command.WithFlag("--branch", gitspaceConfig.CodeRepo.Branch),
command.WithFlag("--no-checkout"),
command.WithFlag("--depth", "1"),
command.WithArg(gitspaceConfig.CodeRepo.URL),
command.WithArg(cloneDir),
)
if err := cmd.Run(ctx, command.WithDir(cloneDir)); err != nil {
return nil, fmt.Errorf("failed to clone repository %s: %w", gitspaceConfig.CodeRepo.URL, err)
}
var lsTreeOutput bytes.Buffer
lsTreeCmd := command.New("ls-tree",
command.WithArg("HEAD"),
command.WithArg(filePath),
)
if err := lsTreeCmd.Run(ctx, command.WithDir(cloneDir), command.WithStdout(&lsTreeOutput)); err != nil {
return nil, fmt.Errorf("failed to list files in repository %s: %w", cloneDir, err)
}
if lsTreeOutput.Len() == 0 {
log.Info().Msg("File not found, returning empty devcontainerConfig")
return nil, nil
}
fields := strings.Fields(lsTreeOutput.String())
blobSHA := fields[2]
var catFileOutput bytes.Buffer
catFileCmd := command.New("cat-file", command.WithFlag("-p"), command.WithArg(blobSHA))
err = catFileCmd.Run(
ctx,
command.WithDir(cloneDir),
command.WithStderr(io.Discard),
command.WithStdout(&catFileOutput),
)
if err != nil {
return nil, fmt.Errorf("failed to read devcontainer file from path %s: %w", filePath, err)
}
return catFileOutput.Bytes(), nil
}
func (s *GenericSCM) ResolveCredentials(
_ context.Context,
gitspaceConfig types.GitspaceConfig,
) (*ResolvedCredentials, error) {
var resolvedCredentials = &ResolvedCredentials{
Branch: gitspaceConfig.Branch,
CloneURL: types.NewMaskSecret(gitspaceConfig.CodeRepo.URL),
}
repoURL, err := url.Parse(gitspaceConfig.CodeRepo.URL)
if err != nil {
return nil, fmt.Errorf("failed to parse repository URL %s: %w", gitspaceConfig.CodeRepo.URL, err)
}
repoName := strings.TrimSuffix(path.Base(repoURL.Path), ".git")
resolvedCredentials.RepoName = repoName
return resolvedCredentials, err
}
func (s *GenericSCM) GetBranchURL(_ string, repoURL string, _ string) (string, error) {
return repoURL, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/scm/wire.go | app/gitspace/scm/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scm
import (
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/git"
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideGitnessSCM, ProvideGenericSCM, ProvideFactory, ProvideSCM,
)
func ProvideGitnessSCM(
repoStore store.RepoStore,
repoFinder refcache.RepoFinder,
rpcClient git.Interface,
tokenStore store.TokenStore,
principalStore store.PrincipalStore,
urlProvider urlprovider.Provider,
) *GitnessSCM {
return NewGitnessSCM(repoStore, repoFinder, rpcClient, tokenStore, principalStore, urlProvider)
}
func ProvideGenericSCM() *GenericSCM {
return NewGenericSCM()
}
func ProvideFactory(gitness *GitnessSCM, genericSCM *GenericSCM) Factory {
return NewFactory(gitness, genericSCM)
}
func ProvideSCM(factory Factory) *SCM {
return NewSCM(factory)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/scm/types.go | app/gitspace/scm/types.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scm
import (
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
type CodeRepositoryRequest struct {
URL string
RepoType enum.GitspaceCodeRepoType
UserIdentifier string
UserID int64
SpacePath string
}
type CodeRepositoryResponse struct {
URL string `json:"url"`
Branch string `json:"branch,omitempty"`
CodeRepoIsPrivate bool `json:"is_private"`
}
// CredentialType represents the type of credential.
type CredentialType string
const (
CredentialTypeUserPassword CredentialType = "user_password"
CredentialTypeOAuthTokenRef CredentialType = "oauth_token_ref" // #nosec G101
)
type (
ResolvedDetails struct {
ResolvedCredentials
DevcontainerConfig types.DevcontainerConfig
}
// UserPasswordCredentials contains login and initialization information used
// by an automated login process.
UserPasswordCredentials struct {
Email string
Name types.MaskSecret
Password types.MaskSecret
}
OAuth2TokenRefCredentials struct {
UserPasswordCredentials
RefreshTokenRef string
AccessTokenRef string
}
ResolvedCredentials struct {
Branch string
// CloneURL contains credentials for private repositories in url prefix
CloneURL types.MaskSecret
UserPasswordCredentials *UserPasswordCredentials
OAuth2TokenRefCredentials *OAuth2TokenRefCredentials
RepoName string
CredentialType CredentialType
}
RepositoryFilter struct {
SpaceID int64 `json:"space_id"`
Page int `json:"page"`
Size int `json:"size"`
Query string `json:"query"`
User string `json:"user"`
}
BranchFilter struct {
SpaceID int64 `json:"space_id"`
Repository string `json:"repo"`
Query string `json:"query"`
Page int32 `json:"page"`
Size int32 `json:"size"`
RepoURL string `json:"repo_url"`
}
Repository struct {
Name string `json:"name"`
DefaultBranch string `json:"default_branch"`
// git urls
GitURL string `json:"git_url"`
GitSSHURL string `json:"git_ssh_url,omitempty"`
}
Branch struct {
Name string `json:"name"`
SHA string `json:"sha"`
}
)
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/scm/scm_auth_file_provider.go | app/gitspace/scm/scm_auth_file_provider.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scm
import (
"context"
"github.com/harness/gitness/types"
)
type AuthAndFileContentProvider interface {
GetFileContent(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
filePath string,
credentials *ResolvedCredentials,
) ([]byte, error)
ResolveCredentials(ctx context.Context, gitspaceConfig types.GitspaceConfig) (*ResolvedCredentials, error)
GetBranchURL(spacePath string, repoURL string, branch string) (string, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/scm/scm.go | app/gitspace/scm/scm.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scm
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"regexp"
"strings"
"github.com/harness/gitness/git/command"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
"github.com/rs/zerolog/log"
"github.com/tidwall/jsonc"
)
var (
ErrNoDefaultBranch = errors.New("no default branch")
)
const devcontainerDefaultPath = ".devcontainer/devcontainer.json"
type SCM struct {
scmProviderFactory Factory
}
func NewSCM(factory Factory) *SCM {
return &SCM{scmProviderFactory: factory}
}
// CheckValidCodeRepo checks if the current URL is a valid and accessible code repo,
// input can be connector info, user token etc.
func (s *SCM) CheckValidCodeRepo(
ctx context.Context,
codeRepositoryRequest CodeRepositoryRequest,
) (*CodeRepositoryResponse, error) {
codeRepositoryResponse := &CodeRepositoryResponse{
URL: codeRepositoryRequest.URL,
CodeRepoIsPrivate: true,
}
branch, err := s.detectBranch(ctx, codeRepositoryRequest.URL)
if err == nil {
codeRepositoryResponse.Branch = branch
codeRepositoryResponse.CodeRepoIsPrivate = false
return codeRepositoryResponse, nil
}
authAndFileContentProvider, err := s.getSCMAuthAndFileProvider(codeRepositoryRequest.RepoType)
if err != nil {
return nil, fmt.Errorf("failed to resolve SCM provider: %w", err)
}
resolvedCreds, err := s.resolveRepoCredentials(ctx, authAndFileContentProvider, codeRepositoryRequest)
if err != nil {
return nil, fmt.Errorf("failed to resolve repo credentials and URL: %w", err)
}
if branch, err = s.detectBranch(ctx, resolvedCreds.CloneURL.Value()); err == nil {
codeRepositoryResponse.Branch = branch
}
return codeRepositoryResponse, nil
}
// GetSCMRepoDetails fetches repository name, credentials & devcontainer config file from the given repo and branch.
func (s *SCM) GetSCMRepoDetails(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
) (*ResolvedDetails, error) {
scmAuthAndFileContentProvider, err := s.getSCMAuthAndFileProvider(gitspaceConfig.CodeRepo.Type)
if err != nil {
return nil, fmt.Errorf("failed to resolve SCM Auth and File COntent provider: %w", err)
}
resolvedCredentials, err := scmAuthAndFileContentProvider.ResolveCredentials(ctx, gitspaceConfig)
if err != nil {
return nil, fmt.Errorf("failed to resolve repo credentials and url: %w", err)
}
scmAuthAndFileProvider, err := s.getSCMAuthAndFileProvider(gitspaceConfig.CodeRepo.Type)
if err != nil {
return nil, fmt.Errorf("failed to resolve SCM Auth and File content provider: %w", err)
}
devcontainerConfig, err := s.getDevcontainerConfig(ctx, scmAuthAndFileProvider, gitspaceConfig, resolvedCredentials)
if err != nil {
return nil, fmt.Errorf("failed to read or parse devcontainer config: %w", err)
}
var resolvedDetails = &ResolvedDetails{
ResolvedCredentials: *resolvedCredentials,
DevcontainerConfig: devcontainerConfig,
}
return resolvedDetails, nil
}
func detectDefaultGitBranch(ctx context.Context, gitRepoDir string) (string, error) {
cmd := command.New("ls-remote",
command.WithFlag("--symref"),
command.WithFlag("-q"),
command.WithArg(gitRepoDir),
command.WithArg("HEAD"),
)
output := &bytes.Buffer{}
if err := cmd.Run(ctx, command.WithStdout(output)); err != nil {
return "", fmt.Errorf("failed to ls remote repo: %w", err)
}
var lsRemoteHeadRegexp = regexp.MustCompile(`ref: refs/heads/([^\s]+)\s+HEAD`)
match := lsRemoteHeadRegexp.FindStringSubmatch(strings.TrimSpace(output.String()))
if match == nil {
return "", ErrNoDefaultBranch
}
return match[1], nil
}
func (s *SCM) GetBranchURL(
spacePath string,
repoType enum.GitspaceCodeRepoType,
repoURL string,
branch string,
) (string, error) {
scmProvider, err := s.getSCMAuthAndFileProvider(repoType)
if err != nil {
return "", fmt.Errorf("failed to resolve scm provider while generating branch url: %w", err)
}
return scmProvider.GetBranchURL(spacePath, repoURL, branch)
}
// detectBranch tries to detect the default Git branch for a given URL.
func (s *SCM) detectBranch(ctx context.Context, repoURL string) (string, error) {
defaultBranch, err := detectDefaultGitBranch(ctx, repoURL)
if err != nil {
return "", err
}
if defaultBranch == "" {
return "main", nil
}
return defaultBranch, nil
}
func (s *SCM) getSCMAuthAndFileProvider(repoType enum.GitspaceCodeRepoType) (AuthAndFileContentProvider, error) {
if repoType == "" {
repoType = enum.CodeRepoTypeUnknown
}
return s.scmProviderFactory.GetSCMAuthAndFileProvider(repoType)
}
func (s *SCM) resolveRepoCredentials(
ctx context.Context,
authAndFileContentProvider AuthAndFileContentProvider,
codeRepositoryRequest CodeRepositoryRequest,
) (*ResolvedCredentials, error) {
codeRepo := types.CodeRepo{URL: codeRepositoryRequest.URL}
gitspaceUser := types.GitspaceUser{Identifier: codeRepositoryRequest.UserIdentifier}
gitspaceConfig := types.GitspaceConfig{
CodeRepo: codeRepo,
SpacePath: codeRepositoryRequest.SpacePath,
GitspaceUser: gitspaceUser,
}
return authAndFileContentProvider.ResolveCredentials(ctx, gitspaceConfig)
}
func (s *SCM) getDevcontainerConfig(
ctx context.Context,
scmAuthAndFileContentProvider AuthAndFileContentProvider,
gitspaceConfig types.GitspaceConfig,
resolvedCredentials *ResolvedCredentials,
) (types.DevcontainerConfig, error) {
config := types.DevcontainerConfig{}
filePath := devcontainerDefaultPath
catFileOutputBytes, err := scmAuthAndFileContentProvider.GetFileContent(
ctx, gitspaceConfig, filePath, resolvedCredentials)
if err != nil {
return config, fmt.Errorf("failed to read devcontainer file: %w", err)
}
if len(catFileOutputBytes) == 0 {
return config, nil // Return an empty config if the file is empty
}
if err = json.Unmarshal(jsonc.ToJSON(catFileOutputBytes), &config); err != nil {
return config, fmt.Errorf("failed to parse devcontainer JSON: %w", err)
}
return config, nil
}
func BuildAuthenticatedCloneURL(repoURL *url.URL, accessToken string, codeRepoType enum.GitspaceCodeRepoType) *url.URL {
switch codeRepoType {
case enum.CodeRepoTypeGithubEnterprise, enum.CodeRepoTypeGithub:
repoURL.User = url.UserPassword(accessToken, "x-oauth-basic")
case enum.CodeRepoTypeGitlab, enum.CodeRepoTypeGitlabOnPrem:
repoURL.User = url.UserPassword("oauth2", accessToken)
case enum.CodeRepoTypeBitbucket, enum.CodeRepoTypeBitbucketServer:
repoURL.User = url.UserPassword("x-token-auth", accessToken)
case enum.CodeRepoTypeGitness:
repoURL.User = url.UserPassword("harness", accessToken)
case enum.CodeRepoTypeHarnessCode:
repoURL.User = url.UserPassword("Basic", accessToken)
case enum.CodeRepoTypeUnknown:
log.Warn().Msgf("unknown repo type, cannot set credentials")
default:
log.Warn().Msgf("Unsupported repo type: %s", codeRepoType)
}
return repoURL
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/scm/scm_listing_provider.go | app/gitspace/scm/scm_listing_provider.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scm
import (
"context"
)
type ListingProvider interface {
ListRepositories(
ctx context.Context,
filter *RepositoryFilter,
credentials *ResolvedCredentials,
) ([]Repository, error)
ListBranches(
ctx context.Context,
filter *BranchFilter,
credentials *ResolvedCredentials,
) ([]Branch, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/scm/scm_factory.go | app/gitspace/scm/scm_factory.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scm
import (
"fmt"
"github.com/harness/gitness/types/enum"
)
type Factory struct {
listingProviders map[enum.GitspaceCodeRepoType]ListingProvider
authAndFileProviders map[enum.GitspaceCodeRepoType]AuthAndFileContentProvider
}
func NewFactoryWithProviders(
providers map[enum.GitspaceCodeRepoType]ListingProvider,
authProviders map[enum.GitspaceCodeRepoType]AuthAndFileContentProvider) Factory {
return Factory{listingProviders: providers,
authAndFileProviders: authProviders}
}
func NewFactory(gitnessProvider *GitnessSCM, genericSCM *GenericSCM) Factory {
listingProviders := make(map[enum.GitspaceCodeRepoType]ListingProvider)
listingProviders[enum.CodeRepoTypeGitness] = gitnessProvider
listingProviders[enum.CodeRepoTypeUnknown] = genericSCM
authAndFileContentProviders := make(map[enum.GitspaceCodeRepoType]AuthAndFileContentProvider)
authAndFileContentProviders[enum.CodeRepoTypeGitness] = gitnessProvider
authAndFileContentProviders[enum.CodeRepoTypeUnknown] = genericSCM
return Factory{
listingProviders: listingProviders,
authAndFileProviders: authAndFileContentProviders,
}
}
func (f *Factory) GetSCMProvider(providerType enum.GitspaceCodeRepoType) (ListingProvider, error) {
val := f.listingProviders[providerType]
if val == nil {
return nil, fmt.Errorf("unknown scm provider type: %s", providerType)
}
return val, nil
}
func (f *Factory) GetSCMAuthAndFileProvider(providerType enum.GitspaceCodeRepoType) (
AuthAndFileContentProvider, error) {
val := f.authAndFileProviders[providerType]
if val == nil {
return nil, fmt.Errorf("unknown scm provider type: %s", providerType)
}
return val, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/scm/gitness_scm.go | app/gitspace/scm/gitness_scm.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scm
import (
"context"
"fmt"
"io"
"net/url"
"path"
"strings"
"time"
"github.com/harness/gitness/app/api/usererror"
"github.com/harness/gitness/app/bootstrap"
"github.com/harness/gitness/app/jwt"
"github.com/harness/gitness/app/services/refcache"
"github.com/harness/gitness/app/store"
"github.com/harness/gitness/app/token"
urlprovider "github.com/harness/gitness/app/url"
"github.com/harness/gitness/git"
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
var _ ListingProvider = (*GitnessSCM)(nil)
var _ AuthAndFileContentProvider = (*GitnessSCM)(nil)
var gitspaceJWTLifetime = 720 * 24 * time.Hour
const defaultGitspacePATIdentifier = "Gitspace_Default"
type GitnessSCM struct {
git git.Interface
repoStore store.RepoStore
repoFinder refcache.RepoFinder
tokenStore store.TokenStore
principalStore store.PrincipalStore
urlProvider urlprovider.Provider
}
// ListBranches implements ListingProvider.
func (s *GitnessSCM) ListBranches(
ctx context.Context,
filter *BranchFilter,
_ *ResolvedCredentials,
) ([]Branch, error) {
repo, err := s.repoFinder.FindByRef(ctx, filter.Repository)
if err != nil {
return nil, fmt.Errorf("failed to find repo: %w", err)
}
rpcOut, err := s.git.ListBranches(ctx, &git.ListBranchesParams{
ReadParams: git.CreateReadParams(repo),
IncludeCommit: false,
Query: filter.Query,
Sort: git.BranchSortOptionDate,
Order: git.SortOrderDesc,
Page: filter.Page,
PageSize: filter.Size,
})
if err != nil {
return nil, err
}
branches := make([]Branch, len(rpcOut.Branches))
for i := range rpcOut.Branches {
branches[i] = mapBranch(rpcOut.Branches[i])
}
return branches, nil
}
func mapBranch(b git.Branch) Branch {
return Branch{
Name: b.Name,
SHA: b.SHA.String(),
}
}
// ListRepositories implements ListingProvider.
func (s *GitnessSCM) ListRepositories(
ctx context.Context,
filter *RepositoryFilter,
_ *ResolvedCredentials,
) ([]Repository, error) {
repos, err := s.repoStore.List(ctx, filter.SpaceID, &types.RepoFilter{
Page: filter.Page,
Size: filter.Size,
Query: filter.Query,
Sort: enum.RepoAttrUpdated,
Order: enum.OrderDesc,
})
if err != nil {
return nil, fmt.Errorf("failed to list child repos: %w", err)
}
var reposOut []Repository
for _, repo := range repos {
// backfill URLs
repo.GitURL = s.urlProvider.GenerateGITCloneURL(ctx, repo.Path)
repo.GitSSHURL = s.urlProvider.GenerateGITCloneSSHURL(ctx, repo.Path)
repoOut, err := mapRepository(repo)
if err != nil {
return nil, fmt.Errorf("failed to get repo %q output: %w", repo.Path, err)
}
reposOut = append(reposOut, repoOut)
}
return reposOut, nil
}
func mapRepository(repo *types.Repository) (Repository, error) {
if repo == nil {
return Repository{}, fmt.Errorf("repository is null")
}
return Repository{
Name: repo.Identifier,
DefaultBranch: repo.DefaultBranch,
GitURL: repo.GitURL,
GitSSHURL: repo.GitSSHURL,
}, nil
}
func NewGitnessSCM(
repoStore store.RepoStore,
repoFinder refcache.RepoFinder,
git git.Interface,
tokenStore store.TokenStore,
principalStore store.PrincipalStore,
urlProvider urlprovider.Provider,
) *GitnessSCM {
return &GitnessSCM{
repoStore: repoStore,
repoFinder: repoFinder,
git: git,
tokenStore: tokenStore,
principalStore: principalStore,
urlProvider: urlProvider,
}
}
func (s *GitnessSCM) ResolveCredentials(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
) (*ResolvedCredentials, error) {
repoURL, err := url.Parse(gitspaceConfig.CodeRepo.URL)
if err != nil {
return nil, fmt.Errorf("failed to parse repository URL %s: %w", gitspaceConfig.CodeRepo.URL, err)
}
repoName := strings.TrimSuffix(path.Base(repoURL.Path), ".git")
repo, err := s.repoFinder.FindByRef(ctx, *gitspaceConfig.CodeRepo.Ref)
if err != nil {
return nil, fmt.Errorf("failed to find repository: %w", err)
}
cloneURL, err := url.Parse(repo.Path)
if err != nil {
return nil, fmt.Errorf("failed to parse clone url '%s': %w", cloneURL, err)
}
// Backfill clone URL
gitURL := s.urlProvider.GenerateContainerGITCloneURL(ctx, repo.Path)
resolvedCredentails := &ResolvedCredentials{Branch: gitspaceConfig.CodeRepo.Branch}
resolvedCredentails.RepoName = repoName
gitspacePrincipal := bootstrap.NewGitspaceServiceSession().Principal
user, err := findUserFromUID(ctx, s.principalStore, gitspaceConfig.GitspaceUser.Identifier)
if err != nil {
return nil, err
}
var jwtToken string
existingToken, _ := s.tokenStore.FindByIdentifier(ctx, user.ID, defaultGitspacePATIdentifier)
if existingToken != nil {
// create jwt token.
jwtToken, err = jwt.GenerateForToken(existingToken, user.ToPrincipal().Salt)
if err != nil {
return nil, fmt.Errorf("failed to create JWT token: %w", err)
}
} else {
_, jwtToken, err = token.CreatePAT(
ctx,
s.tokenStore,
&gitspacePrincipal,
user,
defaultGitspacePATIdentifier,
&gitspaceJWTLifetime)
}
if err != nil {
return nil, fmt.Errorf("failed to create JWT: %w", err)
}
modifiedURL, err := url.Parse(gitURL)
if err != nil {
return nil, fmt.Errorf("error while parsing the clone url: %s", gitURL)
}
resolvedCredentails.CloneURL = types.NewMaskSecret(
BuildAuthenticatedCloneURL(modifiedURL, jwtToken, enum.CodeRepoTypeGitness).String())
credentials := &UserPasswordCredentials{
Email: user.Email,
Name: types.NewMaskSecret(user.DisplayName),
Password: types.NewMaskSecret(jwtToken),
}
resolvedCredentails.UserPasswordCredentials = credentials
return resolvedCredentails, nil
}
func (s *GitnessSCM) GetFileContent(
ctx context.Context,
gitspaceConfig types.GitspaceConfig,
filePath string,
_ *ResolvedCredentials,
) ([]byte, error) {
repo, err := s.repoFinder.FindByRef(ctx, *gitspaceConfig.CodeRepo.Ref)
if err != nil {
return nil, fmt.Errorf("failed to find repository: %w", err)
}
// create read params once
readParams := git.CreateReadParams(repo)
treeNodeOutput, err := s.git.GetTreeNode(ctx, &git.GetTreeNodeParams{
ReadParams: readParams,
GitREF: gitspaceConfig.CodeRepo.Branch,
Path: filePath,
IncludeLatestCommit: false,
})
if err != nil {
return make([]byte, 0), nil //nolint:nilerr
}
// viewing Raw content is only supported for blob content
if treeNodeOutput.Node.Type != git.TreeNodeTypeBlob {
return nil, usererror.BadRequestf(
"Object in '%s' at '/%s' is of type '%s'. Only objects of type %s support raw viewing.",
gitspaceConfig.CodeRepo.Branch, filePath, treeNodeOutput.Node.Type, git.TreeNodeTypeBlob)
}
blobReader, err := s.git.GetBlob(ctx, &git.GetBlobParams{
ReadParams: readParams,
SHA: treeNodeOutput.Node.SHA,
SizeLimit: 0, // no size limit, we stream whatever data there is
})
if err != nil {
return nil, fmt.Errorf("failed to read blob: %w", err)
}
catFileOutput, err := io.ReadAll(blobReader.Content)
if err != nil {
return nil, fmt.Errorf("failed to read blob content: %w", err)
}
return catFileOutput, nil
}
func findUserFromUID(
ctx context.Context,
principalStore store.PrincipalStore, userUID string,
) (*types.User, error) {
return principalStore.FindUserByUID(ctx, userUID)
}
func (s *GitnessSCM) GetBranchURL(_ string, repoURL string, branch string) (string, error) {
return fmt.Sprintf("%s/files/%s", strings.TrimSuffix(repoURL, ".git"), branch), nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/platformsecret/gitnessplatformsecret.go | app/gitspace/platformsecret/gitnessplatformsecret.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package platformsecret
import (
"context"
"github.com/harness/gitness/types"
)
var _ PlatformSecret = (*GitnessPlatformSecret)(nil)
type GitnessPlatformSecret struct{}
func NewGitnessPlatformSecret() *GitnessPlatformSecret {
return &GitnessPlatformSecret{}
}
func (g *GitnessPlatformSecret) FetchSecret(
_ context.Context,
secret string,
_ string,
) (*types.MaskSecret, error) {
maskedVal := types.NewMaskSecret(secret)
return &maskedVal, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/platformsecret/wire.go | app/gitspace/platformsecret/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package platformsecret
import (
"github.com/google/wire"
)
// WireSet provides a wire set for this package.
var WireSet = wire.NewSet(
ProvideGitnessPlatformSecret,
)
func ProvideGitnessPlatformSecret() PlatformSecret {
return NewGitnessPlatformSecret()
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/platformsecret/platformsecret.go | app/gitspace/platformsecret/platformsecret.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package platformsecret
import (
"context"
"github.com/harness/gitness/types"
)
type PlatformSecret interface {
// FetchSecret fetch secret val
FetchSecret(
ctx context.Context,
secretRef string,
currentSpacePath string,
) (*types.MaskSecret, error)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/logutil/wire.go | app/gitspace/logutil/wire.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package logutil
import (
"github.com/harness/gitness/livelog"
"github.com/google/wire"
)
var WireSet = wire.NewSet(
ProvideStatefulLogger,
)
func ProvideStatefulLogger(logz livelog.LogStream) *StatefulLogger {
return NewStatefulLogger(logz)
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/logutil/stateful_logger.go | app/gitspace/logutil/stateful_logger.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package logutil
import (
"context"
"fmt"
"time"
"github.com/harness/gitness/livelog"
)
const offset int64 = 1000000000
// StatefulLogger is a wrapper on livelog.Logstream. It is used to create stateful instances of LogStreamInstance.
type StatefulLogger struct {
logz livelog.LogStream
}
// LogStreamInstance is a stateful instance of the livelog.LogStream. It keeps track of the position & log key (id).
type LogStreamInstance struct {
ctx context.Context
id int64
offsetID int64
position int
scanner *scanner
logz livelog.LogStream
}
func NewStatefulLogger(logz livelog.LogStream) *StatefulLogger {
return &StatefulLogger{
logz: logz,
}
}
// GetLogStream returns an instance of LogStreamInstance tied to the given id.
func (s *StatefulLogger) CreateLogStream(ctx context.Context, id int64) (*LogStreamInstance, error) {
// TODO: As livelog.LogStreamInstance uses only a single id as key, conflicts are likely if pipelines and gitspaces
// are used in the same instance of Harness. We need to update the underlying implementation to use another unique
// key. To avoid that, we offset the ID by offset (1000000000).
offsetID := offset + id
// Create new logstream
err := s.logz.Create(ctx, offsetID)
if err != nil {
return nil, fmt.Errorf("error creating log stream for ID %d: %w", id, err)
}
newStream := &LogStreamInstance{
id: id,
offsetID: offsetID,
ctx: ctx,
scanner: newScanner(),
logz: s.logz,
}
return newStream, nil
}
// TailLogStream tails the underlying livelog.LogStream stream and returns the data and error channels.
func (s *StatefulLogger) TailLogStream(
ctx context.Context,
id int64,
) (<-chan *livelog.Line, <-chan error) {
offsetID := offset + id
return s.logz.Tail(ctx, offsetID)
}
// Write writes the msg into the underlying log stream.
func (l *LogStreamInstance) Write(msg string) error {
lines, err := l.scanner.scan(msg)
if err != nil {
return fmt.Errorf("error parsing log lines %s: %w", msg, err)
}
now := time.Now().UnixMilli()
for _, line := range lines {
err = l.logz.Write(
l.ctx,
l.offsetID,
&livelog.Line{
Number: l.position,
Message: line,
Timestamp: now,
})
if err != nil {
return fmt.Errorf("could not write log %s for ID %d at pos %d: %w", line, l.id, l.position, err)
}
l.position++
}
return nil
}
// Flush deletes the underlying stream.
func (l *LogStreamInstance) Flush() error {
err := l.logz.Delete(l.ctx, l.offsetID)
if err != nil {
return fmt.Errorf("failed to delete old log stream for ID %d: %w", l.id, err)
}
return nil
}
func (l *LogStreamInstance) Info(msg string) {
l.Write("INFO: " + msg) //nolint:errcheck
}
func (l *LogStreamInstance) Debug(msg string) {
l.Write("DEBUG: " + msg) //nolint:errcheck
}
func (l *LogStreamInstance) Warn(msg string) {
l.Write("WARN: " + msg) //nolint:errcheck
}
func (l *LogStreamInstance) Error(msg string, err error) {
l.Write("ERROR: " + msg + ": " + err.Error()) //nolint:errcheck
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
harness/harness | https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/gitspace/logutil/scanner.go | app/gitspace/logutil/scanner.go | // Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package logutil
import (
"bufio"
"fmt"
"strings"
)
type scanner struct {
reader *strings.Reader
}
func newScanner() *scanner {
reader := strings.NewReader("")
return &scanner{
reader: reader,
}
}
func (r *scanner) scan(input string) ([]string, error) {
r.reader.Reset(input)
scanner := bufio.NewScanner(r.reader)
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading string %s: %w", input, err)
}
return lines, nil
}
| go | Apache-2.0 | a087eef054a8fc8317f4fda02d3c7ee599b71fec | 2026-01-07T08:36:08.091982Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.