hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 2, "code_window": [ "func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller {\n", "\treturn &Controller{\n", "\t\tprincipalStore: principalStore,\n", "\t\tconfig: config,\n", "\t}\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tIsUserRegistrationAllowed: func(ctx context.Context) (bool, error) {\n", "\t\t\tusrCount, err := principalStore.CountUsers(ctx)\n", "\t\t\tif err != nil {\n", "\t\t\t\treturn false, err\n", "\t\t\t}\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 22 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package router import ( "fmt" "net/http" "github.com/harness/gitness/githook" "github.com/harness/gitness/internal/api/controller/check" controllergithook "github.com/harness/gitness/internal/api/controller/githook" "github.com/harness/gitness/internal/api/controller/principal" "github.com/harness/gitness/internal/api/controller/pullreq" "github.com/harness/gitness/internal/api/controller/repo" "github.com/harness/gitness/internal/api/controller/serviceaccount" "github.com/harness/gitness/internal/api/controller/space" "github.com/harness/gitness/internal/api/controller/system" "github.com/harness/gitness/internal/api/controller/user" "github.com/harness/gitness/internal/api/controller/webhook" "github.com/harness/gitness/internal/api/handler/account" handlercheck "github.com/harness/gitness/internal/api/handler/check" handlergithook "github.com/harness/gitness/internal/api/handler/githook" handlerprincipal "github.com/harness/gitness/internal/api/handler/principal" handlerpullreq "github.com/harness/gitness/internal/api/handler/pullreq" handlerrepo "github.com/harness/gitness/internal/api/handler/repo" "github.com/harness/gitness/internal/api/handler/resource" handlerserviceaccount "github.com/harness/gitness/internal/api/handler/serviceaccount" handlerspace "github.com/harness/gitness/internal/api/handler/space" handlersystem "github.com/harness/gitness/internal/api/handler/system" handleruser "github.com/harness/gitness/internal/api/handler/user" "github.com/harness/gitness/internal/api/handler/users" handlerwebhook "github.com/harness/gitness/internal/api/handler/webhook" middlewareauthn "github.com/harness/gitness/internal/api/middleware/authn" "github.com/harness/gitness/internal/api/middleware/encode" "github.com/harness/gitness/internal/api/middleware/logging" middlewareprincipal "github.com/harness/gitness/internal/api/middleware/principal" "github.com/harness/gitness/internal/api/request" "github.com/harness/gitness/internal/auth/authn" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/go-chi/cors" "github.com/rs/zerolog/hlog" ) // APIHandler is an abstraction of a http handler that handles API calls. type APIHandler interface { http.Handler } var ( // terminatedPathPrefixesAPI is the list of prefixes that will require resolving terminated paths. terminatedPathPrefixesAPI = []string{"/v1/spaces/", "/v1/repos/"} ) // NewAPIHandler returns a new APIHandler. func NewAPIHandler( config *types.Config, authenticator authn.Authenticator, repoCtrl *repo.Controller, spaceCtrl *space.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, githookCtrl *controllergithook.Controller, saCtrl *serviceaccount.Controller, userCtrl *user.Controller, principalCtrl principal.Controller, checkCtrl *check.Controller, sysCtrl *system.Controller, ) APIHandler { // Use go-chi router for inner routing. r := chi.NewRouter() // Apply common api middleware. r.Use(middleware.NoCache) r.Use(middleware.Recoverer) // configure logging middleware. r.Use(hlog.URLHandler("http.url")) r.Use(hlog.MethodHandler("http.method")) r.Use(logging.HLogRequestIDHandler()) r.Use(logging.HLogAccessLogHandler()) // configure cors middleware r.Use(corsHandler(config)) // for now always attempt auth - enforced per operation. r.Use(middlewareauthn.Attempt(authenticator, authn.SourceRouterAPI)) r.Route("/v1", func(r chi.Router) { setupRoutesV1(r, repoCtrl, spaceCtrl, pullreqCtrl, webhookCtrl, githookCtrl, saCtrl, userCtrl, principalCtrl, checkCtrl, sysCtrl) }) // wrap router in terminatedPath encoder. return encode.TerminatedPathBefore(terminatedPathPrefixesAPI, r) } func corsHandler(config *types.Config) func(http.Handler) http.Handler { return cors.New( cors.Options{ AllowedOrigins: config.Cors.AllowedOrigins, AllowedMethods: config.Cors.AllowedMethods, AllowedHeaders: config.Cors.AllowedHeaders, ExposedHeaders: config.Cors.ExposedHeaders, AllowCredentials: config.Cors.AllowCredentials, MaxAge: config.Cors.MaxAge, }, ).Handler } func setupRoutesV1(r chi.Router, repoCtrl *repo.Controller, spaceCtrl *space.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, githookCtrl *controllergithook.Controller, saCtrl *serviceaccount.Controller, userCtrl *user.Controller, principalCtrl principal.Controller, checkCtrl *check.Controller, sysCtrl *system.Controller, ) { setupSpaces(r, spaceCtrl, repoCtrl) setupRepos(r, repoCtrl, pullreqCtrl, webhookCtrl, checkCtrl) setupUser(r, userCtrl) setupServiceAccounts(r, saCtrl) setupPrincipals(r, principalCtrl) setupInternal(r, githookCtrl) setupAdmin(r, userCtrl) setupAccount(r, userCtrl) setupSystem(r, sysCtrl) setupResources(r) } func setupSpaces(r chi.Router, spaceCtrl *space.Controller, repoCtrl *repo.Controller) { r.Route("/spaces", func(r chi.Router) { // Create takes path and parentId via body, not uri r.Post("/", handlerspace.HandleCreate(spaceCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamSpaceRef), func(r chi.Router) { // space operations r.Get("/", handlerspace.HandleFind(spaceCtrl)) r.Patch("/", handlerspace.HandleUpdate(spaceCtrl)) r.Delete("/", handlerspace.HandleDelete(spaceCtrl, repoCtrl)) r.Post("/move", handlerspace.HandleMove(spaceCtrl)) r.Get("/spaces", handlerspace.HandleListSpaces(spaceCtrl)) r.Get("/repos", handlerspace.HandleListRepos(spaceCtrl)) r.Get("/service-accounts", handlerspace.HandleListServiceAccounts(spaceCtrl)) // Child collections r.Route("/paths", func(r chi.Router) { r.Get("/", handlerspace.HandleListPaths(spaceCtrl)) r.Post("/", handlerspace.HandleCreatePath(spaceCtrl)) // per path operations r.Route(fmt.Sprintf("/{%s}", request.PathParamPathID), func(r chi.Router) { r.Delete("/", handlerspace.HandleDeletePath(spaceCtrl)) }) }) }) }) } func setupRepos(r chi.Router, repoCtrl *repo.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, checkCtrl *check.Controller, ) { r.Route("/repos", func(r chi.Router) { // Create takes path and parentId via body, not uri r.Post("/", handlerrepo.HandleCreate(repoCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamRepoRef), func(r chi.Router) { // repo level operations r.Get("/", handlerrepo.HandleFind(repoCtrl)) r.Patch("/", handlerrepo.HandleUpdate(repoCtrl)) r.Delete("/", handlerrepo.HandleDelete(repoCtrl)) r.Post("/move", handlerrepo.HandleMove(repoCtrl)) r.Get("/service-accounts", handlerrepo.HandleListServiceAccounts(repoCtrl)) // content operations // NOTE: this allows /content and /content/ to both be valid (without any other tricks.) // We don't expect there to be any other operations in that route (as that could overlap with file names) r.Route("/content", func(r chi.Router) { r.Get("/*", handlerrepo.HandleGetContent(repoCtrl)) }) r.Route("/blame", func(r chi.Router) { r.Get("/*", handlerrepo.HandleBlame(repoCtrl)) }) r.Route("/raw", func(r chi.Router) { r.Get("/*", handlerrepo.HandleRaw(repoCtrl)) }) // commit operations r.Route("/commits", func(r chi.Router) { r.Get("/", handlerrepo.HandleListCommits(repoCtrl)) r.Post("/calculate-divergence", handlerrepo.HandleCalculateCommitDivergence(repoCtrl)) r.Post("/", handlerrepo.HandleCommitFiles(repoCtrl)) // per commit operations r.Route(fmt.Sprintf("/{%s}", request.PathParamCommitSHA), func(r chi.Router) { r.Get("/", handlerrepo.HandleGetCommit(repoCtrl)) }) }) // branch operations r.Route("/branches", func(r chi.Router) { r.Get("/", handlerrepo.HandleListBranches(repoCtrl)) r.Post("/", handlerrepo.HandleCreateBranch(repoCtrl)) // per branch operations (can't be grouped in single route) r.Get("/*", handlerrepo.HandleGetBranch(repoCtrl)) r.Delete("/*", handlerrepo.HandleDeleteBranch(repoCtrl)) }) // tags operations r.Route("/tags", func(r chi.Router) { r.Get("/", handlerrepo.HandleListCommitTags(repoCtrl)) r.Post("/", handlerrepo.HandleCreateCommitTag(repoCtrl)) r.Delete("/*", handlerrepo.HandleDeleteCommitTag(repoCtrl)) }) // repo path operations r.Route("/paths", func(r chi.Router) { r.Get("/", handlerrepo.HandleListPaths(repoCtrl)) r.Post("/", handlerrepo.HandleCreatePath(repoCtrl)) // per path operations r.Route(fmt.Sprintf("/{%s}", request.PathParamPathID), func(r chi.Router) { r.Delete("/", handlerrepo.HandleDeletePath(repoCtrl)) }) }) // diffs r.Route("/compare", func(r chi.Router) { r.Get("/*", handlerrepo.HandleRawDiff(repoCtrl)) }) r.Route("/merge-check", func(r chi.Router) { r.Post("/*", handlerrepo.HandleMergeCheck(repoCtrl)) }) r.Route("/diff-stats", func(r chi.Router) { r.Get("/*", handlerrepo.HandleDiffStats(repoCtrl)) }) SetupPullReq(r, pullreqCtrl) SetupWebhook(r, webhookCtrl) SetupChecks(r, checkCtrl) }) }) } func setupInternal(r chi.Router, githookCtrl *controllergithook.Controller) { r.Route("/internal", func(r chi.Router) { SetupGitHooks(r, githookCtrl) }) } func SetupGitHooks(r chi.Router, githookCtrl *controllergithook.Controller) { r.Route("/git-hooks", func(r chi.Router) { r.Post("/"+githook.HTTPRequestPathPreReceive, handlergithook.HandlePreReceive(githookCtrl)) r.Post("/"+githook.HTTPRequestPathUpdate, handlergithook.HandleUpdate(githookCtrl)) r.Post("/"+githook.HTTPRequestPathPostReceive, handlergithook.HandlePostReceive(githookCtrl)) }) } func SetupPullReq(r chi.Router, pullreqCtrl *pullreq.Controller) { r.Route("/pullreq", func(r chi.Router) { r.Post("/", handlerpullreq.HandleCreate(pullreqCtrl)) r.Get("/", handlerpullreq.HandleList(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamPullReqNumber), func(r chi.Router) { r.Get("/", handlerpullreq.HandleFind(pullreqCtrl)) r.Patch("/", handlerpullreq.HandleUpdate(pullreqCtrl)) r.Post("/state", handlerpullreq.HandleState(pullreqCtrl)) r.Get("/activities", handlerpullreq.HandleListActivities(pullreqCtrl)) r.Route("/comments", func(r chi.Router) { r.Post("/", handlerpullreq.HandleCommentCreate(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamPullReqCommentID), func(r chi.Router) { r.Patch("/", handlerpullreq.HandleCommentUpdate(pullreqCtrl)) r.Delete("/", handlerpullreq.HandleCommentDelete(pullreqCtrl)) r.Put("/status", handlerpullreq.HandleCommentStatus(pullreqCtrl)) }) }) r.Route("/reviewers", func(r chi.Router) { r.Get("/", handlerpullreq.HandleReviewerList(pullreqCtrl)) r.Put("/", handlerpullreq.HandleReviewerAdd(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamReviewerID), func(r chi.Router) { r.Delete("/", handlerpullreq.HandleReviewerDelete(pullreqCtrl)) }) }) r.Route("/reviews", func(r chi.Router) { r.Post("/", handlerpullreq.HandleReviewSubmit(pullreqCtrl)) }) r.Post("/merge", handlerpullreq.HandleMerge(pullreqCtrl)) r.Get("/diff", handlerpullreq.HandleRawDiff(pullreqCtrl)) r.Get("/commits", handlerpullreq.HandleCommits(pullreqCtrl)) r.Get("/metadata", handlerpullreq.HandleMetadata(pullreqCtrl)) }) }) } func SetupWebhook(r chi.Router, webhookCtrl *webhook.Controller) { r.Route("/webhooks", func(r chi.Router) { r.Post("/", handlerwebhook.HandleCreate(webhookCtrl)) r.Get("/", handlerwebhook.HandleList(webhookCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamWebhookID), func(r chi.Router) { r.Get("/", handlerwebhook.HandleFind(webhookCtrl)) r.Patch("/", handlerwebhook.HandleUpdate(webhookCtrl)) r.Delete("/", handlerwebhook.HandleDelete(webhookCtrl)) r.Route("/executions", func(r chi.Router) { r.Get("/", handlerwebhook.HandleListExecutions(webhookCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamWebhookExecutionID), func(r chi.Router) { r.Get("/", handlerwebhook.HandleFindExecution(webhookCtrl)) r.Post("/retrigger", handlerwebhook.HandleRetriggerExecution(webhookCtrl)) }) }) }) }) } func SetupChecks(r chi.Router, checkCtrl *check.Controller) { r.Route("/checks", func(r chi.Router) { r.Route(fmt.Sprintf("/commits/{%s}", request.PathParamCommitSHA), func(r chi.Router) { r.Put("/", handlercheck.HandleCheckReport(checkCtrl)) r.Get("/", handlercheck.HandleCheckList(checkCtrl)) }) }) } func setupUser(r chi.Router, userCtrl *user.Controller) { r.Route("/user", func(r chi.Router) { // enforce principal authenticated and it's a user r.Use(middlewareprincipal.RestrictTo(enum.PrincipalTypeUser)) r.Get("/", handleruser.HandleFind(userCtrl)) r.Patch("/", handleruser.HandleUpdate(userCtrl)) // PAT r.Route("/tokens", func(r chi.Router) { r.Get("/", handleruser.HandleListTokens(userCtrl, enum.TokenTypePAT)) r.Post("/", handleruser.HandleCreateAccessToken(userCtrl)) // per token operations r.Route(fmt.Sprintf("/{%s}", request.PathParamTokenUID), func(r chi.Router) { r.Delete("/", handleruser.HandleDeleteToken(userCtrl, enum.TokenTypePAT)) }) }) // SESSION TOKENS r.Route("/sessions", func(r chi.Router) { r.Get("/", handleruser.HandleListTokens(userCtrl, enum.TokenTypeSession)) // per token operations r.Route(fmt.Sprintf("/{%s}", request.PathParamTokenUID), func(r chi.Router) { r.Delete("/", handleruser.HandleDeleteToken(userCtrl, enum.TokenTypeSession)) }) }) }) } func setupServiceAccounts(r chi.Router, saCtrl *serviceaccount.Controller) { r.Route("/service-accounts", func(r chi.Router) { // create takes parent information via body r.Post("/", handlerserviceaccount.HandleCreate(saCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamServiceAccountUID), func(r chi.Router) { r.Get("/", handlerserviceaccount.HandleFind(saCtrl)) r.Delete("/", handlerserviceaccount.HandleDelete(saCtrl)) // SAT r.Route("/tokens", func(r chi.Router) { r.Get("/", handlerserviceaccount.HandleListTokens(saCtrl)) r.Post("/", handlerserviceaccount.HandleCreateToken(saCtrl)) // per token operations r.Route(fmt.Sprintf("/{%s}", request.PathParamTokenUID), func(r chi.Router) { r.Delete("/", handlerserviceaccount.HandleDeleteToken(saCtrl)) }) }) }) }) } func setupSystem(r chi.Router, sysCtrl *system.Controller) { r.Route("/system", func(r chi.Router) { r.Get("/health", handlersystem.HandleHealth) r.Get("/version", handlersystem.HandleVersion) r.Get("/config", handlersystem.HandleListConfig(sysCtrl)) }) } func setupResources(r chi.Router) { r.Route("/resources", func(r chi.Router) { r.Get("/gitignore", resource.HandleGitIgnore()) r.Get("/license", resource.HandleLicence()) }) } func setupPrincipals(r chi.Router, principalCtrl principal.Controller) { r.Route("/principals", func(r chi.Router) { r.Get("/", handlerprincipal.HandleList(principalCtrl)) }) } func setupAdmin(r chi.Router, userCtrl *user.Controller) { r.Route("/admin", func(r chi.Router) { r.Use(middlewareprincipal.RestrictToAdmin()) r.Route("/users", func(r chi.Router) { r.Get("/", users.HandleList(userCtrl)) r.Post("/", users.HandleCreate(userCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamUserUID), func(r chi.Router) { r.Get("/", users.HandleFind(userCtrl)) r.Patch("/", users.HandleUpdate(userCtrl)) r.Delete("/", users.HandleDelete(userCtrl)) r.Patch("/admin", handleruser.HandleUpdateAdmin(userCtrl)) }) }) }) } func setupAccount(r chi.Router, userCtrl *user.Controller) { r.Post("/login", account.HandleLogin(userCtrl)) r.Post("/register", account.HandleRegister(userCtrl)) r.Post("/logout", account.HandleLogout(userCtrl)) }
internal/router/api.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.10979121923446655, 0.003494459670037031, 0.00016406683425884694, 0.00017553524230606854, 0.016300508752465248 ]
{ "id": 2, "code_window": [ "func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller {\n", "\treturn &Controller{\n", "\t\tprincipalStore: principalStore,\n", "\t\tconfig: config,\n", "\t}\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tIsUserRegistrationAllowed: func(ctx context.Context) (bool, error) {\n", "\t\t\tusrCount, err := principalStore.CountUsers(ctx)\n", "\t\t\tif err != nil {\n", "\t\t\t\treturn false, err\n", "\t\t\t}\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 22 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package user import ( "context" "errors" "github.com/harness/gitness/internal/api/usererror" "github.com/harness/gitness/internal/auth" "github.com/harness/gitness/types/enum" ) // Logout searches for the user's token present in the request and proceeds to delete it, // returns nil if successful. func (c *Controller) Logout(ctx context.Context, session *auth.Session) error { var ( tokenID int64 tokenType enum.TokenType ) if session == nil { return usererror.BadRequest("no authenticated user") } switch t := session.Metadata.(type) { case *auth.TokenMetadata: tokenID = t.TokenID tokenType = t.TokenType default: return errors.New("session metadata is of unknown type") } if tokenType != enum.TokenTypeSession { return usererror.BadRequestf("unsupported logout token type %v", tokenType) } return c.tokenStore.Delete(ctx, tokenID) }
internal/api/controller/user/logout.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.045601919293403625, 0.009261088445782661, 0.00017212866805493832, 0.00017750852566678077, 0.018170416355133057 ]
{ "id": 2, "code_window": [ "func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller {\n", "\treturn &Controller{\n", "\t\tprincipalStore: principalStore,\n", "\t\tconfig: config,\n", "\t}\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tIsUserRegistrationAllowed: func(ctx context.Context) (bool, error) {\n", "\t\t\tusrCount, err := principalStore.CountUsers(ctx)\n", "\t\t\tif err != nil {\n", "\t\t\t\treturn false, err\n", "\t\t\t}\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 22 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package hash import ( "context" "io" "testing" "time" "github.com/stretchr/testify/require" ) var ( byte1 = []byte{1} byte2 = []byte{2} ) func TestSourceFromChannel_blockingChannel(t *testing.T) { nextChan := make(chan SourceNext) ctx, cncl := context.WithTimeout(context.Background(), 1*time.Second) defer cncl() source := SourceFromChannel(ctx, nextChan) go func() { defer close(nextChan) select { case nextChan <- SourceNext{Data: byte1}: case <-ctx.Done(): require.Fail(t, "writing data to source chan timed out") } }() next, err := source.Next() require.NoError(t, err, "no error expected on first call to next") require.Equal(t, byte1, next) _, err = source.Next() require.ErrorIs(t, err, io.EOF, "EOF expected after first element was read") } func TestSourceFromChannel_contextCanceled(t *testing.T) { nextChan := make(chan SourceNext) ctx, cncl := context.WithTimeout(context.Background(), 1*time.Second) cncl() source := SourceFromChannel(ctx, nextChan) _, err := source.Next() require.ErrorIs(t, err, context.Canceled, "Canceled error expected") } func TestSourceFromChannel_sourceChannelDrainedOnClosing(t *testing.T) { nextChan := make(chan SourceNext, 1) ctx, cncl := context.WithTimeout(context.Background(), 1*time.Second) defer cncl() source := SourceFromChannel(ctx, nextChan) nextChan <- SourceNext{Data: byte1} close(nextChan) next, err := source.Next() require.NoError(t, err, "no error expected on first call to next") require.Equal(t, byte1, next) _, err = source.Next() require.ErrorIs(t, err, io.EOF, "EOF expected after first element was read") } func TestSourceFromChannel_errorReturnedOnError(t *testing.T) { nextChan := make(chan SourceNext, 1) ctx, cncl := context.WithTimeout(context.Background(), 1*time.Second) defer cncl() source := SourceFromChannel(ctx, nextChan) nextChan <- SourceNext{ Data: byte1, Err: io.ErrClosedPipe, } next, err := source.Next() require.ErrorIs(t, err, io.ErrClosedPipe, "ErrClosedPipe expected") require.Equal(t, byte1, next) } func TestSourceFromChannel_fullChannel(t *testing.T) { nextChan := make(chan SourceNext, 1) ctx, cncl := context.WithTimeout(context.Background(), 1*time.Second) defer cncl() source := SourceFromChannel(ctx, nextChan) nextChan <- SourceNext{Data: byte1} go func() { defer close(nextChan) select { case nextChan <- SourceNext{Data: byte2}: case <-ctx.Done(): require.Fail(t, "writing data to source chan timed out") } }() next, err := source.Next() require.NoError(t, err, "no error expected on first call to next") require.Equal(t, byte1, next) next, err = source.Next() require.NoError(t, err, "no error expected on second call to next") require.Equal(t, byte2, next) _, err = source.Next() require.ErrorIs(t, err, io.EOF, "EOF expected after two elements were read") }
gitrpc/hash/source_test.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00018042701412923634, 0.0001741278829285875, 0.00017100822879001498, 0.0001735663099680096, 0.000002472783307894133 ]
{ "id": 2, "code_window": [ "func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller {\n", "\treturn &Controller{\n", "\t\tprincipalStore: principalStore,\n", "\t\tconfig: config,\n", "\t}\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tIsUserRegistrationAllowed: func(ctx context.Context) (bool, error) {\n", "\t\t\tusrCount, err := principalStore.CountUsers(ctx)\n", "\t\t\tif err != nil {\n", "\t\t\t\treturn false, err\n", "\t\t\t}\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 22 }
allowpaths: ['*'] operationIdOverrides: {}
web/src/services/code/overrides.yaml
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00016586646961513907, 0.00016586646961513907, 0.00016586646961513907, 0.00016586646961513907, 0 ]
{ "id": 3, "code_window": [ "\n", "func IsUserRegistrationAllowed(ctx context.Context, principalStore store.PrincipalStore,\n", "\tconfig *types.Config) (bool, error) {\n", "\tusrCount, err := principalStore.CountUsers(ctx)\n", "\tif err != nil {\n", "\t\treturn false, err\n", "\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\treturn usrCount == 0 || config.AllowSignUp, nil\n", "\t\t},\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 25 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package system import ( "context" "github.com/harness/gitness/internal/store" "github.com/harness/gitness/types" ) type Controller struct { principalStore store.PrincipalStore config *types.Config } func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller { return &Controller{ principalStore: principalStore, config: config, } } func IsUserRegistrationAllowed(ctx context.Context, principalStore store.PrincipalStore, config *types.Config) (bool, error) { usrCount, err := principalStore.CountUsers(ctx) if err != nil { return false, err } return usrCount == 0 || config.AllowSignUp, nil }
internal/api/controller/system/controller.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.9988934397697449, 0.49969178438186646, 0.0001748234935803339, 0.49984943866729736, 0.4986926019191742 ]
{ "id": 3, "code_window": [ "\n", "func IsUserRegistrationAllowed(ctx context.Context, principalStore store.PrincipalStore,\n", "\tconfig *types.Config) (bool, error) {\n", "\tusrCount, err := principalStore.CountUsers(ctx)\n", "\tif err != nil {\n", "\t\treturn false, err\n", "\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\treturn usrCount == 0 || config.AllowSignUp, nil\n", "\t\t},\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 25 }
import React from 'react' import { useGet } from 'restful-react' import type { TypesCommit } from 'services/code' import type { GitInfoProps } from 'utils/GitUtils' import { voidFn, LIST_FETCHING_LIMIT } from 'utils/Utils' import { usePageIndex } from 'hooks/usePageIndex' import { useStrings } from 'framework/strings' import { ResourceListingPagination } from 'components/ResourceListingPagination/ResourceListingPagination' import { CommitsView } from 'components/CommitsView/CommitsView' import { PullRequestTabContentWrapper } from '../PullRequestTabContentWrapper' interface CommitProps extends Pick<GitInfoProps, 'repoMetadata' | 'pullRequestMetadata'> { prHasChanged: boolean handleRefresh: () => void } export const PullRequestCommits: React.FC<CommitProps> = ({ repoMetadata, pullRequestMetadata, prHasChanged, handleRefresh }) => { const limit = LIST_FETCHING_LIMIT const [page, setPage] = usePageIndex() const { getString } = useStrings() const { data: commits, error, loading, refetch, response } = useGet<TypesCommit[]>({ path: `/api/v1/repos/${repoMetadata?.path}/+/pullreq/${pullRequestMetadata.number}/commits`, queryParams: { limit, page, git_ref: pullRequestMetadata.source_branch, after: pullRequestMetadata.target_branch }, lazy: !repoMetadata }) return ( <PullRequestTabContentWrapper loading={loading} error={error} onRetry={voidFn(refetch)}> <CommitsView commits={commits} repoMetadata={repoMetadata} emptyTitle={getString('noCommits')} emptyMessage={getString('noCommitsPR')} prHasChanged={prHasChanged} handleRefresh={voidFn(handleRefresh)} /> <ResourceListingPagination response={response} page={page} setPage={setPage} /> </PullRequestTabContentWrapper> ) }
web/src/pages/PullRequest/PullRequestCommits/PullRequestCommits.tsx
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0001765606866683811, 0.00017240858869627118, 0.00016916570893954486, 0.0001726563205011189, 0.0000024476782982674194 ]
{ "id": 3, "code_window": [ "\n", "func IsUserRegistrationAllowed(ctx context.Context, principalStore store.PrincipalStore,\n", "\tconfig *types.Config) (bool, error) {\n", "\tusrCount, err := principalStore.CountUsers(ctx)\n", "\tif err != nil {\n", "\t\treturn false, err\n", "\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\treturn usrCount == 0 || config.AllowSignUp, nil\n", "\t\t},\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 25 }
*.class # Package Files # *.jar *.war # gwt caches and compiled units # war/gwt_bree/ gwt-unitCache/ # boilerplate generated classes # .apt_generated/ # more caches and things from deploy # war/WEB-INF/deploy/ war/WEB-INF/classes/ #compilation logs .gwt/ #gwt junit compilation files www-test/ #old GWT (1.5) created this dir .gwt-tmp/
resources/gitignore/GWT.gitignore
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00016940671775955707, 0.00016764858446549624, 0.00016614045307505876, 0.00016739859711378813, 0.0000013451129916575155 ]
{ "id": 3, "code_window": [ "\n", "func IsUserRegistrationAllowed(ctx context.Context, principalStore store.PrincipalStore,\n", "\tconfig *types.Config) (bool, error) {\n", "\tusrCount, err := principalStore.CountUsers(ctx)\n", "\tif err != nil {\n", "\t\treturn false, err\n", "\t}\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\treturn usrCount == 0 || config.AllowSignUp, nil\n", "\t\t},\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 25 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package repo import ( "context" "io" "strings" "github.com/harness/gitness/gitrpc" apiauth "github.com/harness/gitness/internal/api/auth" "github.com/harness/gitness/internal/api/usererror" "github.com/harness/gitness/internal/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) func (c *Controller) RawDiff( ctx context.Context, session *auth.Session, repoRef string, path string, w io.Writer, ) error { repo, err := c.repoStore.FindByRef(ctx, repoRef) if err != nil { return err } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, enum.PermissionRepoView, false); err != nil { return err } info, err := parseDiffPath(path) if err != nil { return err } return c.gitRPCClient.RawDiff(ctx, &gitrpc.DiffParams{ ReadParams: CreateRPCReadParams(repo), BaseRef: info.BaseRef, HeadRef: info.HeadRef, MergeBase: info.MergeBase, }, w) } type CompareInfo struct { BaseRef string HeadRef string MergeBase bool } func parseDiffPath(path string) (CompareInfo, error) { infos := strings.SplitN(path, "...", 2) if len(infos) != 2 { infos = strings.SplitN(path, "..", 2) } if len(infos) != 2 { return CompareInfo{}, usererror.BadRequestf("invalid format \"%s\"", path) } return CompareInfo{ BaseRef: infos[0], HeadRef: infos[1], MergeBase: strings.Contains(path, "..."), }, nil } func (c *Controller) DiffStats( ctx context.Context, session *auth.Session, repoRef string, path string, ) (types.DiffStats, error) { repo, err := c.repoStore.FindByRef(ctx, repoRef) if err != nil { return types.DiffStats{}, err } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, enum.PermissionRepoView, false); err != nil { return types.DiffStats{}, err } info, err := parseDiffPath(path) if err != nil { return types.DiffStats{}, err } output, err := c.gitRPCClient.DiffStats(ctx, &gitrpc.DiffParams{ ReadParams: gitrpc.CreateRPCReadParams(repo), BaseRef: info.BaseRef, HeadRef: info.HeadRef, }) if err != nil { return types.DiffStats{}, err } return types.DiffStats{ Commits: output.Commits, FilesChanged: output.FilesChanged, }, nil }
internal/api/controller/repo/diff.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0008042411063797772, 0.0002599992440082133, 0.00016649696044623852, 0.00017541075067128986, 0.0001810093381209299 ]
{ "id": 4, "code_window": [ "\t}\n", "\n", "\treturn usrCount == 0 || config.AllowSignUp, nil\n", "}" ], "labels": [ "keep", "replace", "replace", "keep" ], "after_edit": [], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 31 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package user import ( "context" "fmt" "github.com/harness/gitness/internal/api/controller/system" "github.com/harness/gitness/internal/api/usererror" "github.com/harness/gitness/internal/token" "github.com/harness/gitness/types" ) // Register creates a new user and returns a new session token on success. // This differs from the Create method as it doesn't require auth, but has limited // functionalities (unable to create admin user for example). func (c *Controller) Register(ctx context.Context, in *CreateInput) (*types.TokenResponse, error) { signUpAllowed, err := system.IsUserRegistrationAllowed(ctx, c.principalStore, c.config) if err != nil { return nil, err } if !signUpAllowed { return nil, usererror.ErrForbidden } user, err := c.CreateNoAuth(ctx, &CreateInput{ UID: in.UID, Email: in.Email, DisplayName: in.DisplayName, Password: in.Password, }, false) if err != nil { return nil, fmt.Errorf("failed to create user: %w", err) } // TODO: how should we name session tokens? token, jwtToken, err := token.CreateUserSession(ctx, c.tokenStore, user, "register") if err != nil { return nil, fmt.Errorf("failed to create token after successful user creation: %w", err) } return &types.TokenResponse{Token: *token, AccessToken: jwtToken}, nil }
internal/api/controller/user/register.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0044996654614806175, 0.001036602072417736, 0.00016631226753816009, 0.00016919475456234068, 0.0017315380973741412 ]
{ "id": 4, "code_window": [ "\t}\n", "\n", "\treturn usrCount == 0 || config.AllowSignUp, nil\n", "}" ], "labels": [ "keep", "replace", "replace", "keep" ], "after_edit": [], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 31 }
// This import is required in order for ModuleFederationPlugin // to work properly. import('./bootstrap')
web/src/index.tsx
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0001729402138153091, 0.0001729402138153091, 0.0001729402138153091, 0.0001729402138153091, 0 ]
{ "id": 4, "code_window": [ "\t}\n", "\n", "\treturn usrCount == 0 || config.AllowSignUp, nil\n", "}" ], "labels": [ "keep", "replace", "replace", "keep" ], "after_edit": [], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 31 }
ALTER TABLE pullreq_activities ADD COLUMN pullreq_activity_outdated BOOLEAN; ALTER TABLE pullreq_activities ADD COLUMN pullreq_activity_code_comment_merge_base_sha TEXT; ALTER TABLE pullreq_activities ADD COLUMN pullreq_activity_code_comment_source_sha TEXT; ALTER TABLE pullreq_activities ADD COLUMN pullreq_activity_code_comment_path TEXT; ALTER TABLE pullreq_activities ADD COLUMN pullreq_activity_code_comment_line_new INTEGER; ALTER TABLE pullreq_activities ADD COLUMN pullreq_activity_code_comment_span_new INTEGER; ALTER TABLE pullreq_activities ADD COLUMN pullreq_activity_code_comment_line_old INTEGER; ALTER TABLE pullreq_activities ADD COLUMN pullreq_activity_code_comment_span_old INTEGER;
internal/store/database/migrate/sqlite/0014_alter_pullreq_activity_code_comments.up.sql
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.000256716477451846, 0.000256716477451846, 0.000256716477451846, 0.000256716477451846, 0 ]
{ "id": 4, "code_window": [ "\t}\n", "\n", "\treturn usrCount == 0 || config.AllowSignUp, nil\n", "}" ], "labels": [ "keep", "replace", "replace", "keep" ], "after_edit": [], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 31 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package repo import ( "encoding/json" "net/http" "github.com/harness/gitness/internal/api/controller/repo" "github.com/harness/gitness/internal/api/render" "github.com/harness/gitness/internal/api/request" ) // HandleCreate returns a http.HandlerFunc that creates a new repository. func HandleCreate(repoCtrl *repo.Controller) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() session, _ := request.AuthSessionFrom(ctx) in := new(repo.CreateInput) err := json.NewDecoder(r.Body).Decode(in) if err != nil { render.BadRequestf(w, "Invalid Request Body: %s.", err) return } repo, err := repoCtrl.Create(ctx, session, in) if err != nil { render.TranslatedUserError(w, err) return } render.JSON(w, http.StatusCreated, repo) } }
internal/api/handler/repo/create.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00018003485456574708, 0.00017350699636153877, 0.00017024211410898715, 0.00017187550838571042, 0.000003987510353908874 ]
{ "id": 5, "code_window": [ ")\n", "\n", "// RegisterCheck checks the DB and env config flag to return boolean\n", "// which represents if a user sign-up is allowed or not.\n", "func (c *Controller) RegisterCheck(ctx context.Context) (bool, error) {\n", "\tcheck, err := IsUserRegistrationAllowed(ctx, c.principalStore, c.config)\n", "\tif err != nil {\n", "\t\treturn false, err\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tcheck, err := c.IsUserRegistrationAllowed(ctx)\n" ], "file_path": "internal/api/controller/system/register_check.go", "type": "replace", "edit_start_line_idx": 13 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package router import ( "fmt" "net/http" "github.com/harness/gitness/githook" "github.com/harness/gitness/internal/api/controller/check" controllergithook "github.com/harness/gitness/internal/api/controller/githook" "github.com/harness/gitness/internal/api/controller/principal" "github.com/harness/gitness/internal/api/controller/pullreq" "github.com/harness/gitness/internal/api/controller/repo" "github.com/harness/gitness/internal/api/controller/serviceaccount" "github.com/harness/gitness/internal/api/controller/space" "github.com/harness/gitness/internal/api/controller/system" "github.com/harness/gitness/internal/api/controller/user" "github.com/harness/gitness/internal/api/controller/webhook" "github.com/harness/gitness/internal/api/handler/account" handlercheck "github.com/harness/gitness/internal/api/handler/check" handlergithook "github.com/harness/gitness/internal/api/handler/githook" handlerprincipal "github.com/harness/gitness/internal/api/handler/principal" handlerpullreq "github.com/harness/gitness/internal/api/handler/pullreq" handlerrepo "github.com/harness/gitness/internal/api/handler/repo" "github.com/harness/gitness/internal/api/handler/resource" handlerserviceaccount "github.com/harness/gitness/internal/api/handler/serviceaccount" handlerspace "github.com/harness/gitness/internal/api/handler/space" handlersystem "github.com/harness/gitness/internal/api/handler/system" handleruser "github.com/harness/gitness/internal/api/handler/user" "github.com/harness/gitness/internal/api/handler/users" handlerwebhook "github.com/harness/gitness/internal/api/handler/webhook" middlewareauthn "github.com/harness/gitness/internal/api/middleware/authn" "github.com/harness/gitness/internal/api/middleware/encode" "github.com/harness/gitness/internal/api/middleware/logging" middlewareprincipal "github.com/harness/gitness/internal/api/middleware/principal" "github.com/harness/gitness/internal/api/request" "github.com/harness/gitness/internal/auth/authn" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/go-chi/cors" "github.com/rs/zerolog/hlog" ) // APIHandler is an abstraction of a http handler that handles API calls. type APIHandler interface { http.Handler } var ( // terminatedPathPrefixesAPI is the list of prefixes that will require resolving terminated paths. terminatedPathPrefixesAPI = []string{"/v1/spaces/", "/v1/repos/"} ) // NewAPIHandler returns a new APIHandler. func NewAPIHandler( config *types.Config, authenticator authn.Authenticator, repoCtrl *repo.Controller, spaceCtrl *space.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, githookCtrl *controllergithook.Controller, saCtrl *serviceaccount.Controller, userCtrl *user.Controller, principalCtrl principal.Controller, checkCtrl *check.Controller, sysCtrl *system.Controller, ) APIHandler { // Use go-chi router for inner routing. r := chi.NewRouter() // Apply common api middleware. r.Use(middleware.NoCache) r.Use(middleware.Recoverer) // configure logging middleware. r.Use(hlog.URLHandler("http.url")) r.Use(hlog.MethodHandler("http.method")) r.Use(logging.HLogRequestIDHandler()) r.Use(logging.HLogAccessLogHandler()) // configure cors middleware r.Use(corsHandler(config)) // for now always attempt auth - enforced per operation. r.Use(middlewareauthn.Attempt(authenticator, authn.SourceRouterAPI)) r.Route("/v1", func(r chi.Router) { setupRoutesV1(r, repoCtrl, spaceCtrl, pullreqCtrl, webhookCtrl, githookCtrl, saCtrl, userCtrl, principalCtrl, checkCtrl, sysCtrl) }) // wrap router in terminatedPath encoder. return encode.TerminatedPathBefore(terminatedPathPrefixesAPI, r) } func corsHandler(config *types.Config) func(http.Handler) http.Handler { return cors.New( cors.Options{ AllowedOrigins: config.Cors.AllowedOrigins, AllowedMethods: config.Cors.AllowedMethods, AllowedHeaders: config.Cors.AllowedHeaders, ExposedHeaders: config.Cors.ExposedHeaders, AllowCredentials: config.Cors.AllowCredentials, MaxAge: config.Cors.MaxAge, }, ).Handler } func setupRoutesV1(r chi.Router, repoCtrl *repo.Controller, spaceCtrl *space.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, githookCtrl *controllergithook.Controller, saCtrl *serviceaccount.Controller, userCtrl *user.Controller, principalCtrl principal.Controller, checkCtrl *check.Controller, sysCtrl *system.Controller, ) { setupSpaces(r, spaceCtrl, repoCtrl) setupRepos(r, repoCtrl, pullreqCtrl, webhookCtrl, checkCtrl) setupUser(r, userCtrl) setupServiceAccounts(r, saCtrl) setupPrincipals(r, principalCtrl) setupInternal(r, githookCtrl) setupAdmin(r, userCtrl) setupAccount(r, userCtrl) setupSystem(r, sysCtrl) setupResources(r) } func setupSpaces(r chi.Router, spaceCtrl *space.Controller, repoCtrl *repo.Controller) { r.Route("/spaces", func(r chi.Router) { // Create takes path and parentId via body, not uri r.Post("/", handlerspace.HandleCreate(spaceCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamSpaceRef), func(r chi.Router) { // space operations r.Get("/", handlerspace.HandleFind(spaceCtrl)) r.Patch("/", handlerspace.HandleUpdate(spaceCtrl)) r.Delete("/", handlerspace.HandleDelete(spaceCtrl, repoCtrl)) r.Post("/move", handlerspace.HandleMove(spaceCtrl)) r.Get("/spaces", handlerspace.HandleListSpaces(spaceCtrl)) r.Get("/repos", handlerspace.HandleListRepos(spaceCtrl)) r.Get("/service-accounts", handlerspace.HandleListServiceAccounts(spaceCtrl)) // Child collections r.Route("/paths", func(r chi.Router) { r.Get("/", handlerspace.HandleListPaths(spaceCtrl)) r.Post("/", handlerspace.HandleCreatePath(spaceCtrl)) // per path operations r.Route(fmt.Sprintf("/{%s}", request.PathParamPathID), func(r chi.Router) { r.Delete("/", handlerspace.HandleDeletePath(spaceCtrl)) }) }) }) }) } func setupRepos(r chi.Router, repoCtrl *repo.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, checkCtrl *check.Controller, ) { r.Route("/repos", func(r chi.Router) { // Create takes path and parentId via body, not uri r.Post("/", handlerrepo.HandleCreate(repoCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamRepoRef), func(r chi.Router) { // repo level operations r.Get("/", handlerrepo.HandleFind(repoCtrl)) r.Patch("/", handlerrepo.HandleUpdate(repoCtrl)) r.Delete("/", handlerrepo.HandleDelete(repoCtrl)) r.Post("/move", handlerrepo.HandleMove(repoCtrl)) r.Get("/service-accounts", handlerrepo.HandleListServiceAccounts(repoCtrl)) // content operations // NOTE: this allows /content and /content/ to both be valid (without any other tricks.) // We don't expect there to be any other operations in that route (as that could overlap with file names) r.Route("/content", func(r chi.Router) { r.Get("/*", handlerrepo.HandleGetContent(repoCtrl)) }) r.Route("/blame", func(r chi.Router) { r.Get("/*", handlerrepo.HandleBlame(repoCtrl)) }) r.Route("/raw", func(r chi.Router) { r.Get("/*", handlerrepo.HandleRaw(repoCtrl)) }) // commit operations r.Route("/commits", func(r chi.Router) { r.Get("/", handlerrepo.HandleListCommits(repoCtrl)) r.Post("/calculate-divergence", handlerrepo.HandleCalculateCommitDivergence(repoCtrl)) r.Post("/", handlerrepo.HandleCommitFiles(repoCtrl)) // per commit operations r.Route(fmt.Sprintf("/{%s}", request.PathParamCommitSHA), func(r chi.Router) { r.Get("/", handlerrepo.HandleGetCommit(repoCtrl)) }) }) // branch operations r.Route("/branches", func(r chi.Router) { r.Get("/", handlerrepo.HandleListBranches(repoCtrl)) r.Post("/", handlerrepo.HandleCreateBranch(repoCtrl)) // per branch operations (can't be grouped in single route) r.Get("/*", handlerrepo.HandleGetBranch(repoCtrl)) r.Delete("/*", handlerrepo.HandleDeleteBranch(repoCtrl)) }) // tags operations r.Route("/tags", func(r chi.Router) { r.Get("/", handlerrepo.HandleListCommitTags(repoCtrl)) r.Post("/", handlerrepo.HandleCreateCommitTag(repoCtrl)) r.Delete("/*", handlerrepo.HandleDeleteCommitTag(repoCtrl)) }) // repo path operations r.Route("/paths", func(r chi.Router) { r.Get("/", handlerrepo.HandleListPaths(repoCtrl)) r.Post("/", handlerrepo.HandleCreatePath(repoCtrl)) // per path operations r.Route(fmt.Sprintf("/{%s}", request.PathParamPathID), func(r chi.Router) { r.Delete("/", handlerrepo.HandleDeletePath(repoCtrl)) }) }) // diffs r.Route("/compare", func(r chi.Router) { r.Get("/*", handlerrepo.HandleRawDiff(repoCtrl)) }) r.Route("/merge-check", func(r chi.Router) { r.Post("/*", handlerrepo.HandleMergeCheck(repoCtrl)) }) r.Route("/diff-stats", func(r chi.Router) { r.Get("/*", handlerrepo.HandleDiffStats(repoCtrl)) }) SetupPullReq(r, pullreqCtrl) SetupWebhook(r, webhookCtrl) SetupChecks(r, checkCtrl) }) }) } func setupInternal(r chi.Router, githookCtrl *controllergithook.Controller) { r.Route("/internal", func(r chi.Router) { SetupGitHooks(r, githookCtrl) }) } func SetupGitHooks(r chi.Router, githookCtrl *controllergithook.Controller) { r.Route("/git-hooks", func(r chi.Router) { r.Post("/"+githook.HTTPRequestPathPreReceive, handlergithook.HandlePreReceive(githookCtrl)) r.Post("/"+githook.HTTPRequestPathUpdate, handlergithook.HandleUpdate(githookCtrl)) r.Post("/"+githook.HTTPRequestPathPostReceive, handlergithook.HandlePostReceive(githookCtrl)) }) } func SetupPullReq(r chi.Router, pullreqCtrl *pullreq.Controller) { r.Route("/pullreq", func(r chi.Router) { r.Post("/", handlerpullreq.HandleCreate(pullreqCtrl)) r.Get("/", handlerpullreq.HandleList(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamPullReqNumber), func(r chi.Router) { r.Get("/", handlerpullreq.HandleFind(pullreqCtrl)) r.Patch("/", handlerpullreq.HandleUpdate(pullreqCtrl)) r.Post("/state", handlerpullreq.HandleState(pullreqCtrl)) r.Get("/activities", handlerpullreq.HandleListActivities(pullreqCtrl)) r.Route("/comments", func(r chi.Router) { r.Post("/", handlerpullreq.HandleCommentCreate(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamPullReqCommentID), func(r chi.Router) { r.Patch("/", handlerpullreq.HandleCommentUpdate(pullreqCtrl)) r.Delete("/", handlerpullreq.HandleCommentDelete(pullreqCtrl)) r.Put("/status", handlerpullreq.HandleCommentStatus(pullreqCtrl)) }) }) r.Route("/reviewers", func(r chi.Router) { r.Get("/", handlerpullreq.HandleReviewerList(pullreqCtrl)) r.Put("/", handlerpullreq.HandleReviewerAdd(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamReviewerID), func(r chi.Router) { r.Delete("/", handlerpullreq.HandleReviewerDelete(pullreqCtrl)) }) }) r.Route("/reviews", func(r chi.Router) { r.Post("/", handlerpullreq.HandleReviewSubmit(pullreqCtrl)) }) r.Post("/merge", handlerpullreq.HandleMerge(pullreqCtrl)) r.Get("/diff", handlerpullreq.HandleRawDiff(pullreqCtrl)) r.Get("/commits", handlerpullreq.HandleCommits(pullreqCtrl)) r.Get("/metadata", handlerpullreq.HandleMetadata(pullreqCtrl)) }) }) } func SetupWebhook(r chi.Router, webhookCtrl *webhook.Controller) { r.Route("/webhooks", func(r chi.Router) { r.Post("/", handlerwebhook.HandleCreate(webhookCtrl)) r.Get("/", handlerwebhook.HandleList(webhookCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamWebhookID), func(r chi.Router) { r.Get("/", handlerwebhook.HandleFind(webhookCtrl)) r.Patch("/", handlerwebhook.HandleUpdate(webhookCtrl)) r.Delete("/", handlerwebhook.HandleDelete(webhookCtrl)) r.Route("/executions", func(r chi.Router) { r.Get("/", handlerwebhook.HandleListExecutions(webhookCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamWebhookExecutionID), func(r chi.Router) { r.Get("/", handlerwebhook.HandleFindExecution(webhookCtrl)) r.Post("/retrigger", handlerwebhook.HandleRetriggerExecution(webhookCtrl)) }) }) }) }) } func SetupChecks(r chi.Router, checkCtrl *check.Controller) { r.Route("/checks", func(r chi.Router) { r.Route(fmt.Sprintf("/commits/{%s}", request.PathParamCommitSHA), func(r chi.Router) { r.Put("/", handlercheck.HandleCheckReport(checkCtrl)) r.Get("/", handlercheck.HandleCheckList(checkCtrl)) }) }) } func setupUser(r chi.Router, userCtrl *user.Controller) { r.Route("/user", func(r chi.Router) { // enforce principal authenticated and it's a user r.Use(middlewareprincipal.RestrictTo(enum.PrincipalTypeUser)) r.Get("/", handleruser.HandleFind(userCtrl)) r.Patch("/", handleruser.HandleUpdate(userCtrl)) // PAT r.Route("/tokens", func(r chi.Router) { r.Get("/", handleruser.HandleListTokens(userCtrl, enum.TokenTypePAT)) r.Post("/", handleruser.HandleCreateAccessToken(userCtrl)) // per token operations r.Route(fmt.Sprintf("/{%s}", request.PathParamTokenUID), func(r chi.Router) { r.Delete("/", handleruser.HandleDeleteToken(userCtrl, enum.TokenTypePAT)) }) }) // SESSION TOKENS r.Route("/sessions", func(r chi.Router) { r.Get("/", handleruser.HandleListTokens(userCtrl, enum.TokenTypeSession)) // per token operations r.Route(fmt.Sprintf("/{%s}", request.PathParamTokenUID), func(r chi.Router) { r.Delete("/", handleruser.HandleDeleteToken(userCtrl, enum.TokenTypeSession)) }) }) }) } func setupServiceAccounts(r chi.Router, saCtrl *serviceaccount.Controller) { r.Route("/service-accounts", func(r chi.Router) { // create takes parent information via body r.Post("/", handlerserviceaccount.HandleCreate(saCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamServiceAccountUID), func(r chi.Router) { r.Get("/", handlerserviceaccount.HandleFind(saCtrl)) r.Delete("/", handlerserviceaccount.HandleDelete(saCtrl)) // SAT r.Route("/tokens", func(r chi.Router) { r.Get("/", handlerserviceaccount.HandleListTokens(saCtrl)) r.Post("/", handlerserviceaccount.HandleCreateToken(saCtrl)) // per token operations r.Route(fmt.Sprintf("/{%s}", request.PathParamTokenUID), func(r chi.Router) { r.Delete("/", handlerserviceaccount.HandleDeleteToken(saCtrl)) }) }) }) }) } func setupSystem(r chi.Router, sysCtrl *system.Controller) { r.Route("/system", func(r chi.Router) { r.Get("/health", handlersystem.HandleHealth) r.Get("/version", handlersystem.HandleVersion) r.Get("/config", handlersystem.HandleListConfig(sysCtrl)) }) } func setupResources(r chi.Router) { r.Route("/resources", func(r chi.Router) { r.Get("/gitignore", resource.HandleGitIgnore()) r.Get("/license", resource.HandleLicence()) }) } func setupPrincipals(r chi.Router, principalCtrl principal.Controller) { r.Route("/principals", func(r chi.Router) { r.Get("/", handlerprincipal.HandleList(principalCtrl)) }) } func setupAdmin(r chi.Router, userCtrl *user.Controller) { r.Route("/admin", func(r chi.Router) { r.Use(middlewareprincipal.RestrictToAdmin()) r.Route("/users", func(r chi.Router) { r.Get("/", users.HandleList(userCtrl)) r.Post("/", users.HandleCreate(userCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamUserUID), func(r chi.Router) { r.Get("/", users.HandleFind(userCtrl)) r.Patch("/", users.HandleUpdate(userCtrl)) r.Delete("/", users.HandleDelete(userCtrl)) r.Patch("/admin", handleruser.HandleUpdateAdmin(userCtrl)) }) }) }) } func setupAccount(r chi.Router, userCtrl *user.Controller) { r.Post("/login", account.HandleLogin(userCtrl)) r.Post("/register", account.HandleRegister(userCtrl)) r.Post("/logout", account.HandleLogout(userCtrl)) }
internal/router/api.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0015444094315171242, 0.0002911872579716146, 0.00016515408060513437, 0.00017089313769247383, 0.00030036020325496793 ]
{ "id": 5, "code_window": [ ")\n", "\n", "// RegisterCheck checks the DB and env config flag to return boolean\n", "// which represents if a user sign-up is allowed or not.\n", "func (c *Controller) RegisterCheck(ctx context.Context) (bool, error) {\n", "\tcheck, err := IsUserRegistrationAllowed(ctx, c.principalStore, c.config)\n", "\tif err != nil {\n", "\t\treturn false, err\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tcheck, err := c.IsUserRegistrationAllowed(ctx)\n" ], "file_path": "internal/api/controller/system/register_check.go", "type": "replace", "edit_start_line_idx": 13 }
import React, { useCallback, useMemo } from 'react' import cx from 'classnames' import { Button, ButtonSize, Container, Layout, Pagination } from '@harness/uicore' import { useStrings } from 'framework/strings' import { useUpdateQueryParams } from 'hooks/useUpdateQueryParams' import css from './ResourceListingPagination.module.scss' interface ResourceListingPaginationProps { response: Response | null page: number setPage: React.Dispatch<React.SetStateAction<number>> scrollTop?: boolean } // There are two type of pagination results returned from Code API. // One returns information that works with UICore Pagination component in which we know total pages, total items, etc... The other // has only information to render Prev, Next. // // This component consolidates both cases to remove same pagination logic in pages and components. export const ResourceListingPagination: React.FC<ResourceListingPaginationProps> = ({ response, page, setPage, scrollTop = true }) => { const { updateQueryParams } = useUpdateQueryParams() const { X_NEXT_PAGE, X_PREV_PAGE, totalItems, totalPages, pageSize } = useParsePaginationInfo(response) const _setPage = useCallback( (_page: number) => { if (scrollTop) { setTimeout(() => { window.scrollTo({ top: 0, left: 0, behavior: 'smooth' }) }, 0) } setPage(_page) updateQueryParams({ page: _page.toString() }) }, [setPage, scrollTop, response] // eslint-disable-line react-hooks/exhaustive-deps ) return totalItems ? ( page === 1 && totalItems < pageSize ? null : ( <Container margin={{ left: 'medium', right: 'medium' }}> <Pagination className={css.pagination} hidePageNumbers gotoPage={index => _setPage(index + 1)} itemCount={totalItems} pageCount={totalPages} pageIndex={page - 1} pageSize={pageSize} /> </Container> ) ) : page === 1 && !X_PREV_PAGE && !X_NEXT_PAGE ? null : ( <PrevNextPagination onPrev={ !!X_PREV_PAGE && (() => { _setPage(page - 1) }) } onNext={ !!X_NEXT_PAGE && (() => { _setPage(page + 1) }) } /> ) } function useParsePaginationInfo(response: Nullable<Response>) { const totalItems = useMemo(() => parseInt(response?.headers?.get('x-total') || '0'), [response]) const totalPages = useMemo(() => parseInt(response?.headers?.get('x-total-pages') || '0'), [response]) const pageSize = useMemo(() => parseInt(response?.headers?.get('x-per-page') || '0'), [response]) const X_NEXT_PAGE = useMemo(() => parseInt(response?.headers?.get('x-next-page') || '0'), [response]) const X_PREV_PAGE = useMemo(() => parseInt(response?.headers?.get('x-prev-page') || '0'), [response]) return { totalItems, totalPages, pageSize, X_NEXT_PAGE, X_PREV_PAGE } } interface PrevNextPaginationProps { onPrev?: false | (() => void) onNext?: false | (() => void) skipLayout?: boolean } function PrevNextPagination({ onPrev, onNext, skipLayout }: PrevNextPaginationProps) { const { getString } = useStrings() return ( <Container className={skipLayout ? undefined : css.main}> <Layout.Horizontal> <Button text={getString('prev')} icon="arrow-left" size={ButtonSize.SMALL} className={cx(css.roundedButton, css.buttonLeft)} iconProps={{ size: 12 }} onClick={onPrev ? onPrev : undefined} disabled={!onPrev} /> <Button text={getString('next')} rightIcon="arrow-right" size={ButtonSize.SMALL} className={cx(css.roundedButton, css.buttonRight)} iconProps={{ size: 12 }} onClick={onNext ? onNext : undefined} disabled={!onNext} /> </Layout.Horizontal> </Container> ) }
web/src/components/ResourceListingPagination/ResourceListingPagination.tsx
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00017567453323863447, 0.00017144487355835736, 0.00016788132779765874, 0.00017131929052993655, 0.000002376045586061082 ]
{ "id": 5, "code_window": [ ")\n", "\n", "// RegisterCheck checks the DB and env config flag to return boolean\n", "// which represents if a user sign-up is allowed or not.\n", "func (c *Controller) RegisterCheck(ctx context.Context) (bool, error) {\n", "\tcheck, err := IsUserRegistrationAllowed(ctx, c.principalStore, c.config)\n", "\tif err != nil {\n", "\t\treturn false, err\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tcheck, err := c.IsUserRegistrationAllowed(ctx)\n" ], "file_path": "internal/api/controller/system/register_check.go", "type": "replace", "edit_start_line_idx": 13 }
/* eslint-disable */ // this is an auto-generated file declare const styles: { readonly pagination: string readonly main: string readonly roundedButton: string readonly selected: string readonly buttonLeft: string readonly buttonRight: string } export default styles
web/src/components/ResourceListingPagination/ResourceListingPagination.module.scss.d.ts
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0001729139912640676, 0.0001726349873933941, 0.0001723559689708054, 0.0001726349873933941, 2.7901114663109183e-7 ]
{ "id": 5, "code_window": [ ")\n", "\n", "// RegisterCheck checks the DB and env config flag to return boolean\n", "// which represents if a user sign-up is allowed or not.\n", "func (c *Controller) RegisterCheck(ctx context.Context) (bool, error) {\n", "\tcheck, err := IsUserRegistrationAllowed(ctx, c.principalStore, c.config)\n", "\tif err != nil {\n", "\t\treturn false, err\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tcheck, err := c.IsUserRegistrationAllowed(ctx)\n" ], "file_path": "internal/api/controller/system/register_check.go", "type": "replace", "edit_start_line_idx": 13 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package gitrpc type Repository interface { GetGitUID() string } // CreateRPCReadParams creates base read parameters for gitrpc read operations. // IMPORTANT: repo is assumed to be not nil! func CreateRPCReadParams(repo Repository) ReadParams { return ReadParams{ RepoUID: repo.GetGitUID(), } }
gitrpc/params.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00018128148803953081, 0.0001784899941412732, 0.0001756985002430156, 0.0001784899941412732, 0.000002791493898257613 ]
{ "id": 6, "code_window": [ "\n", "// Register creates a new user and returns a new session token on success.\n", "// This differs from the Create method as it doesn't require auth, but has limited\n", "// functionalities (unable to create admin user for example).\n", "func (c *Controller) Register(ctx context.Context,\n", "\tin *CreateInput) (*types.TokenResponse, error) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "func (c *Controller) Register(ctx context.Context, sysCtrl *system.Controller,\n" ], "file_path": "internal/api/controller/user/register.go", "type": "replace", "edit_start_line_idx": 19 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package user import ( "context" "fmt" "github.com/harness/gitness/internal/api/controller/system" "github.com/harness/gitness/internal/api/usererror" "github.com/harness/gitness/internal/token" "github.com/harness/gitness/types" ) // Register creates a new user and returns a new session token on success. // This differs from the Create method as it doesn't require auth, but has limited // functionalities (unable to create admin user for example). func (c *Controller) Register(ctx context.Context, in *CreateInput) (*types.TokenResponse, error) { signUpAllowed, err := system.IsUserRegistrationAllowed(ctx, c.principalStore, c.config) if err != nil { return nil, err } if !signUpAllowed { return nil, usererror.ErrForbidden } user, err := c.CreateNoAuth(ctx, &CreateInput{ UID: in.UID, Email: in.Email, DisplayName: in.DisplayName, Password: in.Password, }, false) if err != nil { return nil, fmt.Errorf("failed to create user: %w", err) } // TODO: how should we name session tokens? token, jwtToken, err := token.CreateUserSession(ctx, c.tokenStore, user, "register") if err != nil { return nil, fmt.Errorf("failed to create token after successful user creation: %w", err) } return &types.TokenResponse{Token: *token, AccessToken: jwtToken}, nil }
internal/api/controller/user/register.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.9916704893112183, 0.40894460678100586, 0.00017512612976133823, 0.4623793363571167, 0.36868810653686523 ]
{ "id": 6, "code_window": [ "\n", "// Register creates a new user and returns a new session token on success.\n", "// This differs from the Create method as it doesn't require auth, but has limited\n", "// functionalities (unable to create admin user for example).\n", "func (c *Controller) Register(ctx context.Context,\n", "\tin *CreateInput) (*types.TokenResponse, error) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "func (c *Controller) Register(ctx context.Context, sysCtrl *system.Controller,\n" ], "file_path": "internal/api/controller/user/register.go", "type": "replace", "edit_start_line_idx": 19 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package repo import ( "encoding/json" "net/http" "github.com/harness/gitness/internal/api/controller/repo" "github.com/harness/gitness/internal/api/render" "github.com/harness/gitness/internal/api/request" ) /* * Updates an existing repository. */ func HandleUpdate(repoCtrl *repo.Controller) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() session, _ := request.AuthSessionFrom(ctx) repoRef, err := request.GetRepoRefFromPath(r) if err != nil { render.TranslatedUserError(w, err) return } in := new(repo.UpdateInput) err = json.NewDecoder(r.Body).Decode(in) if err != nil { render.BadRequestf(w, "Invalid request body: %s.", err) return } repo, err := repoCtrl.Update(ctx, session, repoRef, in) if err != nil { render.TranslatedUserError(w, err) return } render.JSON(w, http.StatusOK, repo) } }
internal/api/handler/repo/update.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0016342946328222752, 0.00046917685540392995, 0.0001700955763226375, 0.0001783583575161174, 0.0005825982079841197 ]
{ "id": 6, "code_window": [ "\n", "// Register creates a new user and returns a new session token on success.\n", "// This differs from the Create method as it doesn't require auth, but has limited\n", "// functionalities (unable to create admin user for example).\n", "func (c *Controller) Register(ctx context.Context,\n", "\tin *CreateInput) (*types.TokenResponse, error) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "func (c *Controller) Register(ctx context.Context, sysCtrl *system.Controller,\n" ], "file_path": "internal/api/controller/user/register.go", "type": "replace", "edit_start_line_idx": 19 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. // Package types defines common data structures. package types import "github.com/harness/gitness/types/enum" type ( // ServiceAccount is a principal representing a service account. ServiceAccount struct { // Fields from Principal (without admin, as it's never an admin) ID int64 `db:"principal_id" json:"-"` UID string `db:"principal_uid" json:"uid"` Email string `db:"principal_email" json:"email"` DisplayName string `db:"principal_display_name" json:"display_name"` Admin bool `db:"principal_admin" json:"admin"` Blocked bool `db:"principal_blocked" json:"blocked"` Salt string `db:"principal_salt" json:"-"` Created int64 `db:"principal_created" json:"created"` Updated int64 `db:"principal_updated" json:"updated"` // ServiceAccount specific fields ParentType enum.ParentResourceType `db:"principal_sa_parent_type" json:"parent_type"` ParentID int64 `db:"principal_sa_parent_id" json:"parent_id"` } // ServiceAccountInput store details used to // create or update a service account. ServiceAccountInput struct { DisplayName *string `json:"display_name"` ParentType *enum.ParentResourceType `json:"parent_type"` ParentID *int64 `json:"parent_id"` } ) func (s *ServiceAccount) ToPrincipal() *Principal { return &Principal{ ID: s.ID, UID: s.UID, Email: s.Email, Type: enum.PrincipalTypeServiceAccount, DisplayName: s.DisplayName, Admin: s.Admin, Blocked: s.Blocked, Salt: s.Salt, Created: s.Created, Updated: s.Updated, } } func (s *ServiceAccount) ToPrincipalInfo() *PrincipalInfo { return s.ToPrincipal().ToPrincipalInfo() }
types/service_account.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00023268748191185296, 0.0001815131981857121, 0.00016427737136837095, 0.0001719386491458863, 0.000023247586796060205 ]
{ "id": 6, "code_window": [ "\n", "// Register creates a new user and returns a new session token on success.\n", "// This differs from the Create method as it doesn't require auth, but has limited\n", "// functionalities (unable to create admin user for example).\n", "func (c *Controller) Register(ctx context.Context,\n", "\tin *CreateInput) (*types.TokenResponse, error) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "func (c *Controller) Register(ctx context.Context, sysCtrl *system.Controller,\n" ], "file_path": "internal/api/controller/user/register.go", "type": "replace", "edit_start_line_idx": 19 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package events import ( "context" "github.com/harness/gitness/stream" ) // StreamProducer is an abstraction of a producer from the streams package. type StreamProducer interface { Send(ctx context.Context, streamID string, payload map[string]interface{}) (string, error) } // StreamConsumer is an abstraction of a consumer from the streams package. type StreamConsumer interface { Register(streamID string, handler stream.HandlerFunc, opts ...stream.HandlerOption) error Configure(opts ...stream.ConsumerOption) Start(ctx context.Context) error Errors() <-chan error Infos() <-chan string } // StreamConsumerFactoryFunc is an abstraction of a factory method for stream consumers. type StreamConsumerFactoryFunc func(groupName string, consumerName string) (StreamConsumer, error)
events/stream.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.9941794872283936, 0.33159586787223816, 0.0001772053074091673, 0.00043094780994579196, 0.46851736307144165 ]
{ "id": 7, "code_window": [ "\tin *CreateInput) (*types.TokenResponse, error) {\n", "\tsignUpAllowed, err := system.IsUserRegistrationAllowed(ctx, c.principalStore, c.config)\n", "\tif err != nil {\n", "\t\treturn nil, err\n", "\t}\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tsignUpAllowed, err := sysCtrl.IsUserRegistrationAllowed(ctx)\n" ], "file_path": "internal/api/controller/user/register.go", "type": "replace", "edit_start_line_idx": 21 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package user import ( "context" "fmt" "github.com/harness/gitness/internal/api/controller/system" "github.com/harness/gitness/internal/api/usererror" "github.com/harness/gitness/internal/token" "github.com/harness/gitness/types" ) // Register creates a new user and returns a new session token on success. // This differs from the Create method as it doesn't require auth, but has limited // functionalities (unable to create admin user for example). func (c *Controller) Register(ctx context.Context, in *CreateInput) (*types.TokenResponse, error) { signUpAllowed, err := system.IsUserRegistrationAllowed(ctx, c.principalStore, c.config) if err != nil { return nil, err } if !signUpAllowed { return nil, usererror.ErrForbidden } user, err := c.CreateNoAuth(ctx, &CreateInput{ UID: in.UID, Email: in.Email, DisplayName: in.DisplayName, Password: in.Password, }, false) if err != nil { return nil, fmt.Errorf("failed to create user: %w", err) } // TODO: how should we name session tokens? token, jwtToken, err := token.CreateUserSession(ctx, c.tokenStore, user, "register") if err != nil { return nil, fmt.Errorf("failed to create token after successful user creation: %w", err) } return &types.TokenResponse{Token: *token, AccessToken: jwtToken}, nil }
internal/api/controller/user/register.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.9982306361198425, 0.20001666247844696, 0.00017861975356936455, 0.00039982402813620865, 0.39910703897476196 ]
{ "id": 7, "code_window": [ "\tin *CreateInput) (*types.TokenResponse, error) {\n", "\tsignUpAllowed, err := system.IsUserRegistrationAllowed(ctx, c.principalStore, c.config)\n", "\tif err != nil {\n", "\t\treturn nil, err\n", "\t}\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tsignUpAllowed, err := sysCtrl.IsUserRegistrationAllowed(ctx)\n" ], "file_path": "internal/api/controller/user/register.go", "type": "replace", "edit_start_line_idx": 21 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package check import ( "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvidePrincipalUIDCheck, ProvidePathUIDCheck, ) func ProvidePathUIDCheck() PathUID { return PathUIDDefault } func ProvidePrincipalUIDCheck() PrincipalUID { return PrincipalUIDDefault }
types/check/wire.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0007845404325053096, 0.00037679789238609374, 0.00016634906933177263, 0.000179504175321199, 0.00028836753335781395 ]
{ "id": 7, "code_window": [ "\tin *CreateInput) (*types.TokenResponse, error) {\n", "\tsignUpAllowed, err := system.IsUserRegistrationAllowed(ctx, c.principalStore, c.config)\n", "\tif err != nil {\n", "\t\treturn nil, err\n", "\t}\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tsignUpAllowed, err := sysCtrl.IsUserRegistrationAllowed(ctx)\n" ], "file_path": "internal/api/controller/user/register.go", "type": "replace", "edit_start_line_idx": 21 }
.mainCtn { height: var(--page-min-height, 100%); background-color: var(--primary-bg) !important; .adminBadge { padding: var(--spacing-xsmall) 6px; border-radius: 4px; border: 1px solid var(--grey-200); background: var(--grey-50); } }
web/src/pages/UsersListing/UsersListing.module.scss
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00017830412252806127, 0.00017703490448184311, 0.00017576568643562496, 0.00017703490448184311, 0.0000012692180462181568 ]
{ "id": 7, "code_window": [ "\tin *CreateInput) (*types.TokenResponse, error) {\n", "\tsignUpAllowed, err := system.IsUserRegistrationAllowed(ctx, c.principalStore, c.config)\n", "\tif err != nil {\n", "\t\treturn nil, err\n", "\t}\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tsignUpAllowed, err := sysCtrl.IsUserRegistrationAllowed(ctx)\n" ], "file_path": "internal/api/controller/user/register.go", "type": "replace", "edit_start_line_idx": 21 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package webhook import ( "github.com/harness/gitness/internal/auth/authz" "github.com/harness/gitness/internal/services/webhook" "github.com/harness/gitness/internal/store" "github.com/google/wire" "github.com/jmoiron/sqlx" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideController, ) func ProvideController(config webhook.Config, db *sqlx.DB, authorizer authz.Authorizer, webhookStore store.WebhookStore, webhookExecutionStore store.WebhookExecutionStore, repoStore store.RepoStore, webhookService *webhook.Service) *Controller { return NewController(config.AllowLoopback, config.AllowPrivateNetwork, db, authorizer, webhookStore, webhookExecutionStore, repoStore, webhookService) }
internal/api/controller/webhook/wire.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00017775548622012138, 0.00017330533592030406, 0.0001682279398664832, 0.0001739325962262228, 0.000003914811259164708 ]
{ "id": 8, "code_window": [ "import (\n", "\t\"encoding/json\"\n", "\t\"net/http\"\n", "\n", "\t\"github.com/harness/gitness/internal/api/controller/user\"\n", "\t\"github.com/harness/gitness/internal/api/render\"\n", ")\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\"github.com/harness/gitness/internal/api/controller/system\"\n" ], "file_path": "internal/api/handler/account/register.go", "type": "add", "edit_start_line_idx": 10 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package router import ( "fmt" "net/http" "github.com/harness/gitness/githook" "github.com/harness/gitness/internal/api/controller/check" controllergithook "github.com/harness/gitness/internal/api/controller/githook" "github.com/harness/gitness/internal/api/controller/principal" "github.com/harness/gitness/internal/api/controller/pullreq" "github.com/harness/gitness/internal/api/controller/repo" "github.com/harness/gitness/internal/api/controller/serviceaccount" "github.com/harness/gitness/internal/api/controller/space" "github.com/harness/gitness/internal/api/controller/system" "github.com/harness/gitness/internal/api/controller/user" "github.com/harness/gitness/internal/api/controller/webhook" "github.com/harness/gitness/internal/api/handler/account" handlercheck "github.com/harness/gitness/internal/api/handler/check" handlergithook "github.com/harness/gitness/internal/api/handler/githook" handlerprincipal "github.com/harness/gitness/internal/api/handler/principal" handlerpullreq "github.com/harness/gitness/internal/api/handler/pullreq" handlerrepo "github.com/harness/gitness/internal/api/handler/repo" "github.com/harness/gitness/internal/api/handler/resource" handlerserviceaccount "github.com/harness/gitness/internal/api/handler/serviceaccount" handlerspace "github.com/harness/gitness/internal/api/handler/space" handlersystem "github.com/harness/gitness/internal/api/handler/system" handleruser "github.com/harness/gitness/internal/api/handler/user" "github.com/harness/gitness/internal/api/handler/users" handlerwebhook "github.com/harness/gitness/internal/api/handler/webhook" middlewareauthn "github.com/harness/gitness/internal/api/middleware/authn" "github.com/harness/gitness/internal/api/middleware/encode" "github.com/harness/gitness/internal/api/middleware/logging" middlewareprincipal "github.com/harness/gitness/internal/api/middleware/principal" "github.com/harness/gitness/internal/api/request" "github.com/harness/gitness/internal/auth/authn" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/go-chi/cors" "github.com/rs/zerolog/hlog" ) // APIHandler is an abstraction of a http handler that handles API calls. type APIHandler interface { http.Handler } var ( // terminatedPathPrefixesAPI is the list of prefixes that will require resolving terminated paths. terminatedPathPrefixesAPI = []string{"/v1/spaces/", "/v1/repos/"} ) // NewAPIHandler returns a new APIHandler. func NewAPIHandler( config *types.Config, authenticator authn.Authenticator, repoCtrl *repo.Controller, spaceCtrl *space.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, githookCtrl *controllergithook.Controller, saCtrl *serviceaccount.Controller, userCtrl *user.Controller, principalCtrl principal.Controller, checkCtrl *check.Controller, sysCtrl *system.Controller, ) APIHandler { // Use go-chi router for inner routing. r := chi.NewRouter() // Apply common api middleware. r.Use(middleware.NoCache) r.Use(middleware.Recoverer) // configure logging middleware. r.Use(hlog.URLHandler("http.url")) r.Use(hlog.MethodHandler("http.method")) r.Use(logging.HLogRequestIDHandler()) r.Use(logging.HLogAccessLogHandler()) // configure cors middleware r.Use(corsHandler(config)) // for now always attempt auth - enforced per operation. r.Use(middlewareauthn.Attempt(authenticator, authn.SourceRouterAPI)) r.Route("/v1", func(r chi.Router) { setupRoutesV1(r, repoCtrl, spaceCtrl, pullreqCtrl, webhookCtrl, githookCtrl, saCtrl, userCtrl, principalCtrl, checkCtrl, sysCtrl) }) // wrap router in terminatedPath encoder. return encode.TerminatedPathBefore(terminatedPathPrefixesAPI, r) } func corsHandler(config *types.Config) func(http.Handler) http.Handler { return cors.New( cors.Options{ AllowedOrigins: config.Cors.AllowedOrigins, AllowedMethods: config.Cors.AllowedMethods, AllowedHeaders: config.Cors.AllowedHeaders, ExposedHeaders: config.Cors.ExposedHeaders, AllowCredentials: config.Cors.AllowCredentials, MaxAge: config.Cors.MaxAge, }, ).Handler } func setupRoutesV1(r chi.Router, repoCtrl *repo.Controller, spaceCtrl *space.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, githookCtrl *controllergithook.Controller, saCtrl *serviceaccount.Controller, userCtrl *user.Controller, principalCtrl principal.Controller, checkCtrl *check.Controller, sysCtrl *system.Controller, ) { setupSpaces(r, spaceCtrl, repoCtrl) setupRepos(r, repoCtrl, pullreqCtrl, webhookCtrl, checkCtrl) setupUser(r, userCtrl) setupServiceAccounts(r, saCtrl) setupPrincipals(r, principalCtrl) setupInternal(r, githookCtrl) setupAdmin(r, userCtrl) setupAccount(r, userCtrl) setupSystem(r, sysCtrl) setupResources(r) } func setupSpaces(r chi.Router, spaceCtrl *space.Controller, repoCtrl *repo.Controller) { r.Route("/spaces", func(r chi.Router) { // Create takes path and parentId via body, not uri r.Post("/", handlerspace.HandleCreate(spaceCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamSpaceRef), func(r chi.Router) { // space operations r.Get("/", handlerspace.HandleFind(spaceCtrl)) r.Patch("/", handlerspace.HandleUpdate(spaceCtrl)) r.Delete("/", handlerspace.HandleDelete(spaceCtrl, repoCtrl)) r.Post("/move", handlerspace.HandleMove(spaceCtrl)) r.Get("/spaces", handlerspace.HandleListSpaces(spaceCtrl)) r.Get("/repos", handlerspace.HandleListRepos(spaceCtrl)) r.Get("/service-accounts", handlerspace.HandleListServiceAccounts(spaceCtrl)) // Child collections r.Route("/paths", func(r chi.Router) { r.Get("/", handlerspace.HandleListPaths(spaceCtrl)) r.Post("/", handlerspace.HandleCreatePath(spaceCtrl)) // per path operations r.Route(fmt.Sprintf("/{%s}", request.PathParamPathID), func(r chi.Router) { r.Delete("/", handlerspace.HandleDeletePath(spaceCtrl)) }) }) }) }) } func setupRepos(r chi.Router, repoCtrl *repo.Controller, pullreqCtrl *pullreq.Controller, webhookCtrl *webhook.Controller, checkCtrl *check.Controller, ) { r.Route("/repos", func(r chi.Router) { // Create takes path and parentId via body, not uri r.Post("/", handlerrepo.HandleCreate(repoCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamRepoRef), func(r chi.Router) { // repo level operations r.Get("/", handlerrepo.HandleFind(repoCtrl)) r.Patch("/", handlerrepo.HandleUpdate(repoCtrl)) r.Delete("/", handlerrepo.HandleDelete(repoCtrl)) r.Post("/move", handlerrepo.HandleMove(repoCtrl)) r.Get("/service-accounts", handlerrepo.HandleListServiceAccounts(repoCtrl)) // content operations // NOTE: this allows /content and /content/ to both be valid (without any other tricks.) // We don't expect there to be any other operations in that route (as that could overlap with file names) r.Route("/content", func(r chi.Router) { r.Get("/*", handlerrepo.HandleGetContent(repoCtrl)) }) r.Route("/blame", func(r chi.Router) { r.Get("/*", handlerrepo.HandleBlame(repoCtrl)) }) r.Route("/raw", func(r chi.Router) { r.Get("/*", handlerrepo.HandleRaw(repoCtrl)) }) // commit operations r.Route("/commits", func(r chi.Router) { r.Get("/", handlerrepo.HandleListCommits(repoCtrl)) r.Post("/calculate-divergence", handlerrepo.HandleCalculateCommitDivergence(repoCtrl)) r.Post("/", handlerrepo.HandleCommitFiles(repoCtrl)) // per commit operations r.Route(fmt.Sprintf("/{%s}", request.PathParamCommitSHA), func(r chi.Router) { r.Get("/", handlerrepo.HandleGetCommit(repoCtrl)) }) }) // branch operations r.Route("/branches", func(r chi.Router) { r.Get("/", handlerrepo.HandleListBranches(repoCtrl)) r.Post("/", handlerrepo.HandleCreateBranch(repoCtrl)) // per branch operations (can't be grouped in single route) r.Get("/*", handlerrepo.HandleGetBranch(repoCtrl)) r.Delete("/*", handlerrepo.HandleDeleteBranch(repoCtrl)) }) // tags operations r.Route("/tags", func(r chi.Router) { r.Get("/", handlerrepo.HandleListCommitTags(repoCtrl)) r.Post("/", handlerrepo.HandleCreateCommitTag(repoCtrl)) r.Delete("/*", handlerrepo.HandleDeleteCommitTag(repoCtrl)) }) // repo path operations r.Route("/paths", func(r chi.Router) { r.Get("/", handlerrepo.HandleListPaths(repoCtrl)) r.Post("/", handlerrepo.HandleCreatePath(repoCtrl)) // per path operations r.Route(fmt.Sprintf("/{%s}", request.PathParamPathID), func(r chi.Router) { r.Delete("/", handlerrepo.HandleDeletePath(repoCtrl)) }) }) // diffs r.Route("/compare", func(r chi.Router) { r.Get("/*", handlerrepo.HandleRawDiff(repoCtrl)) }) r.Route("/merge-check", func(r chi.Router) { r.Post("/*", handlerrepo.HandleMergeCheck(repoCtrl)) }) r.Route("/diff-stats", func(r chi.Router) { r.Get("/*", handlerrepo.HandleDiffStats(repoCtrl)) }) SetupPullReq(r, pullreqCtrl) SetupWebhook(r, webhookCtrl) SetupChecks(r, checkCtrl) }) }) } func setupInternal(r chi.Router, githookCtrl *controllergithook.Controller) { r.Route("/internal", func(r chi.Router) { SetupGitHooks(r, githookCtrl) }) } func SetupGitHooks(r chi.Router, githookCtrl *controllergithook.Controller) { r.Route("/git-hooks", func(r chi.Router) { r.Post("/"+githook.HTTPRequestPathPreReceive, handlergithook.HandlePreReceive(githookCtrl)) r.Post("/"+githook.HTTPRequestPathUpdate, handlergithook.HandleUpdate(githookCtrl)) r.Post("/"+githook.HTTPRequestPathPostReceive, handlergithook.HandlePostReceive(githookCtrl)) }) } func SetupPullReq(r chi.Router, pullreqCtrl *pullreq.Controller) { r.Route("/pullreq", func(r chi.Router) { r.Post("/", handlerpullreq.HandleCreate(pullreqCtrl)) r.Get("/", handlerpullreq.HandleList(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamPullReqNumber), func(r chi.Router) { r.Get("/", handlerpullreq.HandleFind(pullreqCtrl)) r.Patch("/", handlerpullreq.HandleUpdate(pullreqCtrl)) r.Post("/state", handlerpullreq.HandleState(pullreqCtrl)) r.Get("/activities", handlerpullreq.HandleListActivities(pullreqCtrl)) r.Route("/comments", func(r chi.Router) { r.Post("/", handlerpullreq.HandleCommentCreate(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamPullReqCommentID), func(r chi.Router) { r.Patch("/", handlerpullreq.HandleCommentUpdate(pullreqCtrl)) r.Delete("/", handlerpullreq.HandleCommentDelete(pullreqCtrl)) r.Put("/status", handlerpullreq.HandleCommentStatus(pullreqCtrl)) }) }) r.Route("/reviewers", func(r chi.Router) { r.Get("/", handlerpullreq.HandleReviewerList(pullreqCtrl)) r.Put("/", handlerpullreq.HandleReviewerAdd(pullreqCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamReviewerID), func(r chi.Router) { r.Delete("/", handlerpullreq.HandleReviewerDelete(pullreqCtrl)) }) }) r.Route("/reviews", func(r chi.Router) { r.Post("/", handlerpullreq.HandleReviewSubmit(pullreqCtrl)) }) r.Post("/merge", handlerpullreq.HandleMerge(pullreqCtrl)) r.Get("/diff", handlerpullreq.HandleRawDiff(pullreqCtrl)) r.Get("/commits", handlerpullreq.HandleCommits(pullreqCtrl)) r.Get("/metadata", handlerpullreq.HandleMetadata(pullreqCtrl)) }) }) } func SetupWebhook(r chi.Router, webhookCtrl *webhook.Controller) { r.Route("/webhooks", func(r chi.Router) { r.Post("/", handlerwebhook.HandleCreate(webhookCtrl)) r.Get("/", handlerwebhook.HandleList(webhookCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamWebhookID), func(r chi.Router) { r.Get("/", handlerwebhook.HandleFind(webhookCtrl)) r.Patch("/", handlerwebhook.HandleUpdate(webhookCtrl)) r.Delete("/", handlerwebhook.HandleDelete(webhookCtrl)) r.Route("/executions", func(r chi.Router) { r.Get("/", handlerwebhook.HandleListExecutions(webhookCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamWebhookExecutionID), func(r chi.Router) { r.Get("/", handlerwebhook.HandleFindExecution(webhookCtrl)) r.Post("/retrigger", handlerwebhook.HandleRetriggerExecution(webhookCtrl)) }) }) }) }) } func SetupChecks(r chi.Router, checkCtrl *check.Controller) { r.Route("/checks", func(r chi.Router) { r.Route(fmt.Sprintf("/commits/{%s}", request.PathParamCommitSHA), func(r chi.Router) { r.Put("/", handlercheck.HandleCheckReport(checkCtrl)) r.Get("/", handlercheck.HandleCheckList(checkCtrl)) }) }) } func setupUser(r chi.Router, userCtrl *user.Controller) { r.Route("/user", func(r chi.Router) { // enforce principal authenticated and it's a user r.Use(middlewareprincipal.RestrictTo(enum.PrincipalTypeUser)) r.Get("/", handleruser.HandleFind(userCtrl)) r.Patch("/", handleruser.HandleUpdate(userCtrl)) // PAT r.Route("/tokens", func(r chi.Router) { r.Get("/", handleruser.HandleListTokens(userCtrl, enum.TokenTypePAT)) r.Post("/", handleruser.HandleCreateAccessToken(userCtrl)) // per token operations r.Route(fmt.Sprintf("/{%s}", request.PathParamTokenUID), func(r chi.Router) { r.Delete("/", handleruser.HandleDeleteToken(userCtrl, enum.TokenTypePAT)) }) }) // SESSION TOKENS r.Route("/sessions", func(r chi.Router) { r.Get("/", handleruser.HandleListTokens(userCtrl, enum.TokenTypeSession)) // per token operations r.Route(fmt.Sprintf("/{%s}", request.PathParamTokenUID), func(r chi.Router) { r.Delete("/", handleruser.HandleDeleteToken(userCtrl, enum.TokenTypeSession)) }) }) }) } func setupServiceAccounts(r chi.Router, saCtrl *serviceaccount.Controller) { r.Route("/service-accounts", func(r chi.Router) { // create takes parent information via body r.Post("/", handlerserviceaccount.HandleCreate(saCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamServiceAccountUID), func(r chi.Router) { r.Get("/", handlerserviceaccount.HandleFind(saCtrl)) r.Delete("/", handlerserviceaccount.HandleDelete(saCtrl)) // SAT r.Route("/tokens", func(r chi.Router) { r.Get("/", handlerserviceaccount.HandleListTokens(saCtrl)) r.Post("/", handlerserviceaccount.HandleCreateToken(saCtrl)) // per token operations r.Route(fmt.Sprintf("/{%s}", request.PathParamTokenUID), func(r chi.Router) { r.Delete("/", handlerserviceaccount.HandleDeleteToken(saCtrl)) }) }) }) }) } func setupSystem(r chi.Router, sysCtrl *system.Controller) { r.Route("/system", func(r chi.Router) { r.Get("/health", handlersystem.HandleHealth) r.Get("/version", handlersystem.HandleVersion) r.Get("/config", handlersystem.HandleListConfig(sysCtrl)) }) } func setupResources(r chi.Router) { r.Route("/resources", func(r chi.Router) { r.Get("/gitignore", resource.HandleGitIgnore()) r.Get("/license", resource.HandleLicence()) }) } func setupPrincipals(r chi.Router, principalCtrl principal.Controller) { r.Route("/principals", func(r chi.Router) { r.Get("/", handlerprincipal.HandleList(principalCtrl)) }) } func setupAdmin(r chi.Router, userCtrl *user.Controller) { r.Route("/admin", func(r chi.Router) { r.Use(middlewareprincipal.RestrictToAdmin()) r.Route("/users", func(r chi.Router) { r.Get("/", users.HandleList(userCtrl)) r.Post("/", users.HandleCreate(userCtrl)) r.Route(fmt.Sprintf("/{%s}", request.PathParamUserUID), func(r chi.Router) { r.Get("/", users.HandleFind(userCtrl)) r.Patch("/", users.HandleUpdate(userCtrl)) r.Delete("/", users.HandleDelete(userCtrl)) r.Patch("/admin", handleruser.HandleUpdateAdmin(userCtrl)) }) }) }) } func setupAccount(r chi.Router, userCtrl *user.Controller) { r.Post("/login", account.HandleLogin(userCtrl)) r.Post("/register", account.HandleRegister(userCtrl)) r.Post("/logout", account.HandleLogout(userCtrl)) }
internal/router/api.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.004100764635950327, 0.0003390689962543547, 0.00016421833424828947, 0.0001720136497169733, 0.0006163254729472101 ]
{ "id": 8, "code_window": [ "import (\n", "\t\"encoding/json\"\n", "\t\"net/http\"\n", "\n", "\t\"github.com/harness/gitness/internal/api/controller/user\"\n", "\t\"github.com/harness/gitness/internal/api/render\"\n", ")\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\"github.com/harness/gitness/internal/api/controller/system\"\n" ], "file_path": "internal/api/handler/account/register.go", "type": "add", "edit_start_line_idx": 10 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package client import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "net/http/httputil" "net/url" "github.com/harness/gitness/internal/api/controller/user" "github.com/harness/gitness/types" "github.com/harness/gitness/version" "github.com/rs/zerolog/log" ) // ensure HTTPClient implements Client interface. var _ Client = (*HTTPClient)(nil) // HTTPClient provides an HTTP client for interacting // with the remote API. type HTTPClient struct { client *http.Client base string token string debug bool } // New returns a client at the specified url. func New(uri string) *HTTPClient { return NewToken(uri, "") } // NewToken returns a client at the specified url that // authenticates all outbound requests with the given token. func NewToken(uri, token string) *HTTPClient { return &HTTPClient{http.DefaultClient, uri, token, false} } // SetClient sets the default http client. This can be // used in conjunction with golang.org/x/oauth2 to // authenticate requests to the server. func (c *HTTPClient) SetClient(client *http.Client) { c.client = client } // SetDebug sets the debug flag. When the debug flag is // true, the http.Resposne body to stdout which can be // helpful when debugging. func (c *HTTPClient) SetDebug(debug bool) { c.debug = debug } // Login authenticates the user and returns a JWT token. func (c *HTTPClient) Login(ctx context.Context, username, password string) (*types.TokenResponse, error) { form := &url.Values{} form.Add("username", username) form.Add("password", password) out := new(types.TokenResponse) uri := fmt.Sprintf("%s/api/v1/login", c.base) err := c.post(ctx, uri, true, form, out) return out, err } // Register registers a new user and returns a JWT token. func (c *HTTPClient) Register(ctx context.Context, username, displayName, email, password string) (*types.TokenResponse, error) { form := &url.Values{} form.Add("username", username) form.Add("displayname", displayName) form.Add("email", email) form.Add("password", password) out := new(types.TokenResponse) uri := fmt.Sprintf("%s/api/v1/register", c.base) err := c.post(ctx, uri, true, form, out) return out, err } // // User Endpoints // // Self returns the currently authenticated user. func (c *HTTPClient) Self(ctx context.Context) (*types.User, error) { out := new(types.User) uri := fmt.Sprintf("%s/api/v1/user", c.base) err := c.get(ctx, uri, out) return out, err } // UserCreatePAT creates a new PAT for the user. func (c *HTTPClient) UserCreatePAT(ctx context.Context, in user.CreateTokenInput) (*types.TokenResponse, error) { out := new(types.TokenResponse) uri := fmt.Sprintf("%s/api/v1/user/tokens", c.base) err := c.post(ctx, uri, false, in, out) return out, err } // User returns a user by ID or email. func (c *HTTPClient) User(ctx context.Context, key string) (*types.User, error) { out := new(types.User) uri := fmt.Sprintf("%s/api/v1/users/%s", c.base, key) err := c.get(ctx, uri, out) return out, err } // UserList returns a list of all registered users. func (c *HTTPClient) UserList(ctx context.Context, params types.UserFilter) ([]types.User, error) { out := []types.User{} uri := fmt.Sprintf("%s/api/v1/users?page=%d&limit=%d", c.base, params.Page, params.Size) err := c.get(ctx, uri, &out) return out, err } // UserCreate creates a new user account. func (c *HTTPClient) UserCreate(ctx context.Context, user *types.User) (*types.User, error) { out := new(types.User) uri := fmt.Sprintf("%s/api/v1/users", c.base) err := c.post(ctx, uri, false, user, out) return out, err } // UserUpdate updates a user account by ID or email. func (c *HTTPClient) UserUpdate(ctx context.Context, key string, user *types.UserInput) (*types.User, error) { out := new(types.User) uri := fmt.Sprintf("%s/api/v1/users/%s", c.base, key) err := c.patch(ctx, uri, user, out) return out, err } // UserDelete deletes a user account by ID or email. func (c *HTTPClient) UserDelete(ctx context.Context, key string) error { uri := fmt.Sprintf("%s/api/v1/users/%s", c.base, key) err := c.delete(ctx, uri) return err } // // http request helper functions // // helper function for making an http GET request. func (c *HTTPClient) get(ctx context.Context, rawurl string, out interface{}) error { return c.do(ctx, rawurl, "GET", false, nil, out) } // helper function for making an http POST request. func (c *HTTPClient) post(ctx context.Context, rawurl string, noToken bool, in, out interface{}) error { return c.do(ctx, rawurl, "POST", noToken, in, out) } // helper function for making an http PATCH request. func (c *HTTPClient) patch(ctx context.Context, rawurl string, in, out interface{}) error { return c.do(ctx, rawurl, "PATCH", false, in, out) } // helper function for making an http DELETE request. func (c *HTTPClient) delete(ctx context.Context, rawurl string) error { return c.do(ctx, rawurl, "DELETE", false, nil, nil) } // helper function to make an http request. func (c *HTTPClient) do(ctx context.Context, rawurl, method string, noToken bool, in, out interface{}) error { // executes the http request and returns the body as // and io.ReadCloser body, err := c.stream(ctx, rawurl, method, noToken, in, out) if body != nil { defer func(body io.ReadCloser) { _ = body.Close() }(body) } if err != nil { return err } // if a json response is expected, parse and return // the json response. if out != nil { return json.NewDecoder(body).Decode(out) } return nil } // helper function to stream a http request. func (c *HTTPClient) stream(ctx context.Context, rawurl, method string, noToken bool, in, _ interface{}) (io.ReadCloser, error) { uri, err := url.Parse(rawurl) if err != nil { return nil, err } // if we are posting or putting data, we need to // write it to the body of the request. var buf io.ReadWriter if in != nil { buf = &bytes.Buffer{} // if posting form data, encode the form values. if form, ok := in.(*url.Values); ok { if _, err = io.WriteString(buf, form.Encode()); err != nil { log.Err(err).Msg("in stream method") } } else if err = json.NewEncoder(buf).Encode(in); err != nil { return nil, err } } // creates a new http request. req, err := http.NewRequestWithContext(ctx, method, uri.String(), buf) if err != nil { return nil, err } if in != nil { req.Header.Set("Content-Type", "application/json") } if !noToken && c.token != "" { req.Header.Set("Authorization", "Bearer "+c.token) } if _, ok := in.(*url.Values); ok { req.Header.Set("Content-Type", "application/x-www-form-urlencoded") } // include the client version information in the // http accept header for debugging purposes. req.Header.Set("Accept", "application/json;version="+version.Version.String()) // send the http request. resp, err := c.client.Do(req) if err != nil { return nil, err } if c.debug { dump, _ := httputil.DumpResponse(resp, true) log.Debug().Msgf("method %s, url %s", method, rawurl) log.Debug().Msg(string(dump)) } if resp.StatusCode >= http.StatusMultipleChoices { defer func(Body io.ReadCloser) { _ = Body.Close() }(resp.Body) err = &remoteError{} if decodeErr := json.NewDecoder(resp.Body).Decode(err); decodeErr != nil { return nil, decodeErr } return nil, err } return resp.Body, nil }
client/client.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.03731555491685867, 0.0016014198772609234, 0.000164046956342645, 0.00016762458835728467, 0.007142849266529083 ]
{ "id": 8, "code_window": [ "import (\n", "\t\"encoding/json\"\n", "\t\"net/http\"\n", "\n", "\t\"github.com/harness/gitness/internal/api/controller/user\"\n", "\t\"github.com/harness/gitness/internal/api/render\"\n", ")\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\"github.com/harness/gitness/internal/api/controller/system\"\n" ], "file_path": "internal/api/handler/account/register.go", "type": "add", "edit_start_line_idx": 10 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package repo import ( "context" "fmt" "strings" "time" apiauth "github.com/harness/gitness/internal/api/auth" "github.com/harness/gitness/internal/api/usererror" "github.com/harness/gitness/internal/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/harness/gitness/types/enum" ) // CreatePathInput used for path creation apis. type CreatePathInput struct { Path string `json:"path"` } // CreatePath creates a new path for a repo. func (c *Controller) CreatePath(ctx context.Context, session *auth.Session, repoRef string, in *CreatePathInput) (*types.Path, error) { repo, err := c.repoStore.FindByRef(ctx, repoRef) if err != nil { return nil, err } if err = apiauth.CheckRepo(ctx, c.authorizer, session, repo, enum.PermissionRepoEdit, false); err != nil { return nil, err } if err = c.sanitizeCreatePathInput(in, repo.Path); err != nil { return nil, fmt.Errorf("failed to sanitize input: %w", err) } now := time.Now().UnixMilli() path := &types.Path{ Version: 0, Value: in.Path, IsPrimary: false, TargetType: enum.PathTargetTypeRepo, TargetID: repo.ID, CreatedBy: session.Principal.ID, Created: now, Updated: now, } // TODO: ensure principal is authorized to create a path pointing to in.Path err = c.pathStore.Create(ctx, path) if err != nil { return nil, err } return path, nil } func (c *Controller) sanitizeCreatePathInput(in *CreatePathInput, oldPath string) error { in.Path = strings.Trim(in.Path, "/") if err := check.Path(in.Path, false, c.uidCheck); err != nil { return err } rootSeparatorIdx := strings.Index(in.Path, types.PathSeparator) if rootSeparatorIdx < 0 { return usererror.BadRequest("Top level paths are not allowed for repositories.") } // add '/' at the end of the root uid to avoid false negatives (e.g. abc/repo-> abcdef/repo) newPathRoot := in.Path[:rootSeparatorIdx] + types.PathSeparator if !strings.HasPrefix(oldPath, newPathRoot) { return usererror.BadRequest("Path has to stay within the same top level space.") } return nil }
internal/api/controller/repo/create_path.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0010135348420590162, 0.00029444816755130887, 0.00016952208534348756, 0.00017454501357860863, 0.0002601658634375781 ]
{ "id": 8, "code_window": [ "import (\n", "\t\"encoding/json\"\n", "\t\"net/http\"\n", "\n", "\t\"github.com/harness/gitness/internal/api/controller/user\"\n", "\t\"github.com/harness/gitness/internal/api/render\"\n", ")\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\"github.com/harness/gitness/internal/api/controller/system\"\n" ], "file_path": "internal/api/handler/account/register.go", "type": "add", "edit_start_line_idx": 10 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package pullreq import ( "strconv" "github.com/harness/gitness/lock" ) func (c *Controller) newMutexForPR(repoUID string, pr int64, options ...lock.Option) (lock.Mutex, error) { key := repoUID + "/pulls" if pr != 0 { key += "/" + strconv.FormatInt(pr, 10) } return c.mtxManager.NewMutex(key, append(options, lock.WithNamespace("repo"))...) }
internal/api/controller/pullreq/locks.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0002000716485781595, 0.00018783607811201364, 0.00017560050764586776, 0.00018783607811201364, 0.000012235570466145873 ]
{ "id": 9, "code_window": [ ")\n", "\n", "// HandleRegister returns an http.HandlerFunc that processes an http.Request\n", "// to register the named user account with the system.\n", "func HandleRegister(userCtrl *user.Controller) http.HandlerFunc {\n", "\treturn func(w http.ResponseWriter, r *http.Request) {\n", "\t\tctx := r.Context()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "func HandleRegister(userCtrl *user.Controller, sysCtrl *system.Controller) http.HandlerFunc {\n" ], "file_path": "internal/api/handler/account/register.go", "type": "replace", "edit_start_line_idx": 16 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package system import ( "context" "github.com/harness/gitness/internal/store" "github.com/harness/gitness/types" ) type Controller struct { principalStore store.PrincipalStore config *types.Config } func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller { return &Controller{ principalStore: principalStore, config: config, } } func IsUserRegistrationAllowed(ctx context.Context, principalStore store.PrincipalStore, config *types.Config) (bool, error) { usrCount, err := principalStore.CountUsers(ctx) if err != nil { return false, err } return usrCount == 0 || config.AllowSignUp, nil }
internal/api/controller/system/controller.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00219017849303782, 0.0007199353422038257, 0.0001656491367612034, 0.0002619569131638855, 0.0008518637041561306 ]
{ "id": 9, "code_window": [ ")\n", "\n", "// HandleRegister returns an http.HandlerFunc that processes an http.Request\n", "// to register the named user account with the system.\n", "func HandleRegister(userCtrl *user.Controller) http.HandlerFunc {\n", "\treturn func(w http.ResponseWriter, r *http.Request) {\n", "\t\tctx := r.Context()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "func HandleRegister(userCtrl *user.Controller, sysCtrl *system.Controller) http.HandlerFunc {\n" ], "file_path": "internal/api/handler/account/register.go", "type": "replace", "edit_start_line_idx": 16 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. // Package version provides the version number. package version import ( "strconv" "github.com/coreos/go-semver/semver" ) var ( // GitRepository is the git repository that was compiled. GitRepository string // GitCommit is the git commit that was compiled. GitCommit string ) var ( // major is for an API incompatible changes. major string // minor is for functionality in a backwards-compatible manner. minor string // patch is for backwards-compatible bug fixes. patch string // pre indicates prerelease. pre = "" // dev indicates development branch. Releases will be empty string. dev string // Version is the specification version that the package types support. Version = semver.Version{ Major: parseVersionNumber(major), Minor: parseVersionNumber(minor), Patch: parseVersionNumber(patch), PreRelease: semver.PreRelease(pre), Metadata: dev, } ) func parseVersionNumber(versionNum string) int64 { if versionNum == "" { return 0 } i, err := strconv.ParseInt(versionNum, 10, 64) if err != nil { panic(err) } return i }
version/version.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0001789610687410459, 0.00017553182260598987, 0.0001726522168610245, 0.00017541844863444567, 0.000002225558546342654 ]
{ "id": 9, "code_window": [ ")\n", "\n", "// HandleRegister returns an http.HandlerFunc that processes an http.Request\n", "// to register the named user account with the system.\n", "func HandleRegister(userCtrl *user.Controller) http.HandlerFunc {\n", "\treturn func(w http.ResponseWriter, r *http.Request) {\n", "\t\tctx := r.Context()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "func HandleRegister(userCtrl *user.Controller, sysCtrl *system.Controller) http.HandlerFunc {\n" ], "file_path": "internal/api/handler/account/register.go", "type": "replace", "edit_start_line_idx": 16 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package account import ( "encoding/json" "net/http" "github.com/harness/gitness/internal/api/controller/user" "github.com/harness/gitness/internal/api/render" "github.com/harness/gitness/internal/api/request" ) // HandleLogin returns an http.HandlerFunc that authenticates // the user and returns an authentication token on success. func HandleLogin(userCtrl *user.Controller) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() session, _ := request.AuthSessionFrom(ctx) in := new(user.LoginInput) err := json.NewDecoder(r.Body).Decode(in) if err != nil { render.BadRequestf(w, "Invalid request body: %s.", err) return } tokenResponse, err := userCtrl.Login(ctx, session, in) if err != nil { render.TranslatedUserError(w, err) return } render.JSON(w, http.StatusOK, tokenResponse) } }
internal/api/handler/account/login.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.9896155595779419, 0.2892308235168457, 0.00016822504403535277, 0.08356976509094238, 0.41006067395210266 ]
{ "id": 9, "code_window": [ ")\n", "\n", "// HandleRegister returns an http.HandlerFunc that processes an http.Request\n", "// to register the named user account with the system.\n", "func HandleRegister(userCtrl *user.Controller) http.HandlerFunc {\n", "\treturn func(w http.ResponseWriter, r *http.Request) {\n", "\t\tctx := r.Context()\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "func HandleRegister(userCtrl *user.Controller, sysCtrl *system.Controller) http.HandlerFunc {\n" ], "file_path": "internal/api/handler/account/register.go", "type": "replace", "edit_start_line_idx": 16 }
import React from 'react' import { Text, StringSubstitute, IconName } from '@harness/uicore' import cx from 'classnames' import { CodeIcon } from 'utils/GitUtils' import { useStrings } from 'framework/strings' import css from './ExecutionStatusLabel.module.scss' export type EnumPullReqExecutionState = 'success' | 'failed' | 'unknown' export const ExecutionStatusLabel: React.FC<{ data: { state?: EnumPullReqExecutionState } iconSize?: number iconOnly?: boolean }> = ({ data, iconSize = 20, iconOnly = false }) => { const { getString } = useStrings() const maps = { unknown: { icon: CodeIcon.PullRequest, css: css.open }, success: { icon: 'execution-success', css: css.success }, failed: { icon: 'danger-icon', css: css.failure } } const map = maps[data.state || 'unknown'] return ( <Text tag="span" className={cx(css.executionStatus, map.css, { [css.iconOnly]: iconOnly })} icon={map.icon as IconName} iconProps={{ size: iconOnly ? iconSize : 14 }}> {!iconOnly && <StringSubstitute str={getString('pr.executionState')} vars={{ state: data.state }} />} </Text> ) }
web/src/components/ExecutionStatusLabel/ExecutionStatusLabel.tsx
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00017893427866511047, 0.0001748664362821728, 0.0001722654269542545, 0.00017451787425670773, 0.000002208023033745121 ]
{ "id": 10, "code_window": [ "\t\tif err != nil {\n", "\t\t\trender.BadRequestf(w, \"Invalid request body: %s.\", err)\n", "\t\t\treturn\n", "\t\t}\n", "\n", "\t\ttokenResponse, err := userCtrl.Register(ctx, in)\n", "\t\tif err != nil {\n", "\t\t\trender.TranslatedUserError(w, err)\n", "\t\t\treturn\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\ttokenResponse, err := userCtrl.Register(ctx, sysCtrl, in)\n" ], "file_path": "internal/api/handler/account/register.go", "type": "replace", "edit_start_line_idx": 27 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package system import ( "context" "github.com/harness/gitness/internal/store" "github.com/harness/gitness/types" ) type Controller struct { principalStore store.PrincipalStore config *types.Config } func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller { return &Controller{ principalStore: principalStore, config: config, } } func IsUserRegistrationAllowed(ctx context.Context, principalStore store.PrincipalStore, config *types.Config) (bool, error) { usrCount, err := principalStore.CountUsers(ctx) if err != nil { return false, err } return usrCount == 0 || config.AllowSignUp, nil }
internal/api/controller/system/controller.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0002146231709048152, 0.00018470364739187062, 0.00017139232659246773, 0.00017639953875914216, 0.000017557422324898653 ]
{ "id": 10, "code_window": [ "\t\tif err != nil {\n", "\t\t\trender.BadRequestf(w, \"Invalid request body: %s.\", err)\n", "\t\t\treturn\n", "\t\t}\n", "\n", "\t\ttokenResponse, err := userCtrl.Register(ctx, in)\n", "\t\tif err != nil {\n", "\t\t\trender.TranslatedUserError(w, err)\n", "\t\t\treturn\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\ttokenResponse, err := userCtrl.Register(ctx, sysCtrl, in)\n" ], "file_path": "internal/api/handler/account/register.go", "type": "replace", "edit_start_line_idx": 27 }
// Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: // - protoc-gen-go-grpc v1.2.0 // - protoc v3.21.11 // source: http.proto package rpc import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.32.0 or later. const _ = grpc.SupportPackageIsVersion7 // SmartHTTPServiceClient is the client API for SmartHTTPService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type SmartHTTPServiceClient interface { // The response body for GET /info/refs?service=git-upload-pack // Will be invoked when the user executes a `git fetch`, meaning the server // will upload the packs to that user. The user doesn't upload new objects. InfoRefs(ctx context.Context, in *InfoRefsRequest, opts ...grpc.CallOption) (SmartHTTPService_InfoRefsClient, error) // ServicePack is just upload-pack or receive-pack ServicePack(ctx context.Context, opts ...grpc.CallOption) (SmartHTTPService_ServicePackClient, error) } type smartHTTPServiceClient struct { cc grpc.ClientConnInterface } func NewSmartHTTPServiceClient(cc grpc.ClientConnInterface) SmartHTTPServiceClient { return &smartHTTPServiceClient{cc} } func (c *smartHTTPServiceClient) InfoRefs(ctx context.Context, in *InfoRefsRequest, opts ...grpc.CallOption) (SmartHTTPService_InfoRefsClient, error) { stream, err := c.cc.NewStream(ctx, &SmartHTTPService_ServiceDesc.Streams[0], "/rpc.SmartHTTPService/InfoRefs", opts...) if err != nil { return nil, err } x := &smartHTTPServiceInfoRefsClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } type SmartHTTPService_InfoRefsClient interface { Recv() (*InfoRefsResponse, error) grpc.ClientStream } type smartHTTPServiceInfoRefsClient struct { grpc.ClientStream } func (x *smartHTTPServiceInfoRefsClient) Recv() (*InfoRefsResponse, error) { m := new(InfoRefsResponse) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *smartHTTPServiceClient) ServicePack(ctx context.Context, opts ...grpc.CallOption) (SmartHTTPService_ServicePackClient, error) { stream, err := c.cc.NewStream(ctx, &SmartHTTPService_ServiceDesc.Streams[1], "/rpc.SmartHTTPService/ServicePack", opts...) if err != nil { return nil, err } x := &smartHTTPServiceServicePackClient{stream} return x, nil } type SmartHTTPService_ServicePackClient interface { Send(*ServicePackRequest) error Recv() (*ServicePackResponse, error) grpc.ClientStream } type smartHTTPServiceServicePackClient struct { grpc.ClientStream } func (x *smartHTTPServiceServicePackClient) Send(m *ServicePackRequest) error { return x.ClientStream.SendMsg(m) } func (x *smartHTTPServiceServicePackClient) Recv() (*ServicePackResponse, error) { m := new(ServicePackResponse) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // SmartHTTPServiceServer is the server API for SmartHTTPService service. // All implementations must embed UnimplementedSmartHTTPServiceServer // for forward compatibility type SmartHTTPServiceServer interface { // The response body for GET /info/refs?service=git-upload-pack // Will be invoked when the user executes a `git fetch`, meaning the server // will upload the packs to that user. The user doesn't upload new objects. InfoRefs(*InfoRefsRequest, SmartHTTPService_InfoRefsServer) error // ServicePack is just upload-pack or receive-pack ServicePack(SmartHTTPService_ServicePackServer) error mustEmbedUnimplementedSmartHTTPServiceServer() } // UnimplementedSmartHTTPServiceServer must be embedded to have forward compatible implementations. type UnimplementedSmartHTTPServiceServer struct { } func (UnimplementedSmartHTTPServiceServer) InfoRefs(*InfoRefsRequest, SmartHTTPService_InfoRefsServer) error { return status.Errorf(codes.Unimplemented, "method InfoRefs not implemented") } func (UnimplementedSmartHTTPServiceServer) ServicePack(SmartHTTPService_ServicePackServer) error { return status.Errorf(codes.Unimplemented, "method ServicePack not implemented") } func (UnimplementedSmartHTTPServiceServer) mustEmbedUnimplementedSmartHTTPServiceServer() {} // UnsafeSmartHTTPServiceServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to SmartHTTPServiceServer will // result in compilation errors. type UnsafeSmartHTTPServiceServer interface { mustEmbedUnimplementedSmartHTTPServiceServer() } func RegisterSmartHTTPServiceServer(s grpc.ServiceRegistrar, srv SmartHTTPServiceServer) { s.RegisterService(&SmartHTTPService_ServiceDesc, srv) } func _SmartHTTPService_InfoRefs_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(InfoRefsRequest) if err := stream.RecvMsg(m); err != nil { return err } return srv.(SmartHTTPServiceServer).InfoRefs(m, &smartHTTPServiceInfoRefsServer{stream}) } type SmartHTTPService_InfoRefsServer interface { Send(*InfoRefsResponse) error grpc.ServerStream } type smartHTTPServiceInfoRefsServer struct { grpc.ServerStream } func (x *smartHTTPServiceInfoRefsServer) Send(m *InfoRefsResponse) error { return x.ServerStream.SendMsg(m) } func _SmartHTTPService_ServicePack_Handler(srv interface{}, stream grpc.ServerStream) error { return srv.(SmartHTTPServiceServer).ServicePack(&smartHTTPServiceServicePackServer{stream}) } type SmartHTTPService_ServicePackServer interface { Send(*ServicePackResponse) error Recv() (*ServicePackRequest, error) grpc.ServerStream } type smartHTTPServiceServicePackServer struct { grpc.ServerStream } func (x *smartHTTPServiceServicePackServer) Send(m *ServicePackResponse) error { return x.ServerStream.SendMsg(m) } func (x *smartHTTPServiceServicePackServer) Recv() (*ServicePackRequest, error) { m := new(ServicePackRequest) if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // SmartHTTPService_ServiceDesc is the grpc.ServiceDesc for SmartHTTPService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var SmartHTTPService_ServiceDesc = grpc.ServiceDesc{ ServiceName: "rpc.SmartHTTPService", HandlerType: (*SmartHTTPServiceServer)(nil), Methods: []grpc.MethodDesc{}, Streams: []grpc.StreamDesc{ { StreamName: "InfoRefs", Handler: _SmartHTTPService_InfoRefs_Handler, ServerStreams: true, }, { StreamName: "ServicePack", Handler: _SmartHTTPService_ServicePack_Handler, ServerStreams: true, ClientStreams: true, }, }, Metadata: "http.proto", }
gitrpc/rpc/http_grpc.pb.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0044305711053311825, 0.0005596625269390643, 0.00016481599595863372, 0.00017745843797456473, 0.0009113047854043543 ]
{ "id": 10, "code_window": [ "\t\tif err != nil {\n", "\t\t\trender.BadRequestf(w, \"Invalid request body: %s.\", err)\n", "\t\t\treturn\n", "\t\t}\n", "\n", "\t\ttokenResponse, err := userCtrl.Register(ctx, in)\n", "\t\tif err != nil {\n", "\t\t\trender.TranslatedUserError(w, err)\n", "\t\t\treturn\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\ttokenResponse, err := userCtrl.Register(ctx, sysCtrl, in)\n" ], "file_path": "internal/api/handler/account/register.go", "type": "replace", "edit_start_line_idx": 27 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package user import ( "context" "encoding/json" "os" "text/template" "time" "github.com/harness/gitness/cli/provide" "github.com/drone/funcmap" "gopkg.in/alecthomas/kingpin.v2" ) const userTmpl = ` uid: {{ .UID }} name: {{ .DisplayName }} email: {{ .Email }} admin: {{ .Admin }} ` type command struct { tmpl string json bool } func (c *command) run(*kingpin.ParseContext) error { ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() user, err := provide.Client().Self(ctx) if err != nil { return err } if c.json { enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") return enc.Encode(user) } tmpl, err := template.New("_").Funcs(funcmap.Funcs).Parse(c.tmpl) if err != nil { return err } return tmpl.Execute(os.Stdout, user) } // Register the command. func registerSelf(app *kingpin.CmdClause) { c := &command{} cmd := app.Command("self", "display authenticated user"). Action(c.run) cmd.Flag("json", "json encode the output"). BoolVar(&c.json) cmd.Flag("format", "format the output using a Go template"). Default(userTmpl). Hidden(). StringVar(&c.tmpl) }
cli/operations/user/self.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0001790549431461841, 0.00016945631068665534, 0.0001583676494192332, 0.0001699376734904945, 0.000006275962732615881 ]
{ "id": 10, "code_window": [ "\t\tif err != nil {\n", "\t\t\trender.BadRequestf(w, \"Invalid request body: %s.\", err)\n", "\t\t\treturn\n", "\t\t}\n", "\n", "\t\ttokenResponse, err := userCtrl.Register(ctx, in)\n", "\t\tif err != nil {\n", "\t\t\trender.TranslatedUserError(w, err)\n", "\t\t\treturn\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\ttokenResponse, err := userCtrl.Register(ctx, sysCtrl, in)\n" ], "file_path": "internal/api/handler/account/register.go", "type": "replace", "edit_start_line_idx": 27 }
CREATE TABLE spaces ( space_id SERIAL PRIMARY KEY ,space_version INTEGER NOT NULL DEFAULT 0 ,space_parent_id INTEGER DEFAULT NULL ,space_uid TEXT NOT NULL ,space_description TEXT ,space_is_public BOOLEAN NOT NULL ,space_created_by INTEGER NOT NULL ,space_created BIGINT NOT NULL ,space_updated BIGINT NOT NULL ,CONSTRAINT fk_space_parent_id FOREIGN KEY (space_parent_id) REFERENCES spaces (space_id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE CASCADE );
internal/store/database/migrate/postgres/0001_create_table_b_spaces.up.sql
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00016420206520706415, 0.00016200714162550867, 0.0001598122325958684, 0.00016200714162550867, 0.0000021949163055978715 ]
{ "id": 11, "code_window": [ "\tsetupServiceAccounts(r, saCtrl)\n", "\tsetupPrincipals(r, principalCtrl)\n", "\tsetupInternal(r, githookCtrl)\n", "\tsetupAdmin(r, userCtrl)\n", "\tsetupAccount(r, userCtrl)\n", "\tsetupSystem(r, sysCtrl)\n", "\tsetupResources(r)\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tsetupAccount(r, userCtrl, sysCtrl)\n" ], "file_path": "internal/router/api.go", "type": "replace", "edit_start_line_idx": 134 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package user import ( "context" "fmt" "github.com/harness/gitness/internal/api/controller/system" "github.com/harness/gitness/internal/api/usererror" "github.com/harness/gitness/internal/token" "github.com/harness/gitness/types" ) // Register creates a new user and returns a new session token on success. // This differs from the Create method as it doesn't require auth, but has limited // functionalities (unable to create admin user for example). func (c *Controller) Register(ctx context.Context, in *CreateInput) (*types.TokenResponse, error) { signUpAllowed, err := system.IsUserRegistrationAllowed(ctx, c.principalStore, c.config) if err != nil { return nil, err } if !signUpAllowed { return nil, usererror.ErrForbidden } user, err := c.CreateNoAuth(ctx, &CreateInput{ UID: in.UID, Email: in.Email, DisplayName: in.DisplayName, Password: in.Password, }, false) if err != nil { return nil, fmt.Errorf("failed to create user: %w", err) } // TODO: how should we name session tokens? token, jwtToken, err := token.CreateUserSession(ctx, c.tokenStore, user, "register") if err != nil { return nil, fmt.Errorf("failed to create token after successful user creation: %w", err) } return &types.TokenResponse{Token: *token, AccessToken: jwtToken}, nil }
internal/api/controller/user/register.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0002620341256260872, 0.00019248855824116617, 0.00016864438657648861, 0.0001763537438819185, 0.00003494675183901563 ]
{ "id": 11, "code_window": [ "\tsetupServiceAccounts(r, saCtrl)\n", "\tsetupPrincipals(r, principalCtrl)\n", "\tsetupInternal(r, githookCtrl)\n", "\tsetupAdmin(r, userCtrl)\n", "\tsetupAccount(r, userCtrl)\n", "\tsetupSystem(r, sysCtrl)\n", "\tsetupResources(r)\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tsetupAccount(r, userCtrl, sysCtrl)\n" ], "file_path": "internal/router/api.go", "type": "replace", "edit_start_line_idx": 134 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package space import ( "context" "fmt" "math" "github.com/harness/gitness/internal/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) // deleteRepositoriesNoAuth does not check PermissionRepoView, and PermissionRepoDelete permissions. // Call this through Delete(Space) api to make sure the caller has DeleteSpace permission. func (c *Controller) deleteRepositoriesNoAuth(ctx context.Context, session *auth.Session, spaceID int64) error { filter := &types.RepoFilter{ Page: 1, Size: int(math.MaxInt), Query: "", Order: enum.OrderAsc, Sort: enum.RepoAttrNone, } repos, _, err := c.ListRepositoriesNoAuth(ctx, spaceID, filter) if err != nil { return fmt.Errorf("failed to list space repositories: %w", err) } for _, repo := range repos { err = c.repoCtrl.DeleteNoAuth(ctx, session, repo) if err != nil { return fmt.Errorf("failed to delete repository %d: %w", repo.ID, err) } } return nil }
internal/api/controller/space/delete_repositories.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.0001794158888515085, 0.00017583734006620944, 0.00017279302119277418, 0.00017557022511027753, 0.0000024401915652561 ]
{ "id": 11, "code_window": [ "\tsetupServiceAccounts(r, saCtrl)\n", "\tsetupPrincipals(r, principalCtrl)\n", "\tsetupInternal(r, githookCtrl)\n", "\tsetupAdmin(r, userCtrl)\n", "\tsetupAccount(r, userCtrl)\n", "\tsetupSystem(r, sysCtrl)\n", "\tsetupResources(r)\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tsetupAccount(r, userCtrl, sysCtrl)\n" ], "file_path": "internal/router/api.go", "type": "replace", "edit_start_line_idx": 134 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package space import ( "net/http" "github.com/harness/gitness/internal/api/controller/space" "github.com/harness/gitness/internal/api/render" "github.com/harness/gitness/internal/api/request" "github.com/harness/gitness/types/enum" ) // HandleListRepos writes json-encoded list of repos in the request body. func HandleListRepos(spaceCtrl *space.Controller) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() session, _ := request.AuthSessionFrom(ctx) spaceRef, err := request.GetSpaceRefFromPath(r) if err != nil { render.TranslatedUserError(w, err) return } filter := request.ParseRepoFilter(r) if filter.Order == enum.OrderDefault { filter.Order = enum.OrderAsc } repos, totalCount, err := spaceCtrl.ListRepositories(ctx, session, spaceRef, filter) if err != nil { render.TranslatedUserError(w, err) return } render.Pagination(r, w, filter.Page, filter.Size, int(totalCount)) render.JSON(w, http.StatusOK, repos) } }
internal/api/handler/space/list_repos.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00018021777214016765, 0.0001760062004905194, 0.00017230848607141525, 0.00017616634431760758, 0.000002956293428724166 ]
{ "id": 11, "code_window": [ "\tsetupServiceAccounts(r, saCtrl)\n", "\tsetupPrincipals(r, principalCtrl)\n", "\tsetupInternal(r, githookCtrl)\n", "\tsetupAdmin(r, userCtrl)\n", "\tsetupAccount(r, userCtrl)\n", "\tsetupSystem(r, sysCtrl)\n", "\tsetupResources(r)\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tsetupAccount(r, userCtrl, sysCtrl)\n" ], "file_path": "internal/router/api.go", "type": "replace", "edit_start_line_idx": 134 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package events import ( "bytes" "context" "encoding/gob" "fmt" "time" ) // GenericReporter represents an event reporter that supports sending typesafe messages // for an arbitrary set of custom events within an event category using the ReporterSendEvent method. // NOTE: Optimally this should be an interface with SendEvent[T] method, but that's not possible in go. type GenericReporter struct { producer StreamProducer category string } // ReportEvent reports an event using the provided GenericReporter. // Returns the reported event's ID in case of success. // NOTE: This call is blocking until the event was send (not until it was processed). // //nolint:revive // emphasize that this is meant to be an operation on *GenericReporter func ReporterSendEvent[T interface{}](reporter *GenericReporter, ctx context.Context, eventType EventType, payload T) (string, error) { streamID := getStreamID(reporter.category, eventType) event := Event[T]{ ID: "", // will be set by GenericReader Timestamp: time.Now(), Payload: payload, } buff := &bytes.Buffer{} encoder := gob.NewEncoder(buff) if err := encoder.Encode(&event); err != nil { return "", fmt.Errorf("failed to encode payload: %w", err) } streamPayload := map[string]interface{}{ streamPayloadKey: buff.Bytes(), } // We are using the message ID as event ID. return reporter.producer.Send(ctx, streamID, streamPayload) }
events/reporter.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00018014390661846846, 0.0001743292814353481, 0.00016667168529238552, 0.0001748802897054702, 0.000004791337232745718 ]
{ "id": 12, "code_window": [ "\t\t\t})\n", "\t\t})\n", "\t})\n", "}\n", "\n", "func setupAccount(r chi.Router, userCtrl *user.Controller) {\n", "\tr.Post(\"/login\", account.HandleLogin(userCtrl))\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "func setupAccount(r chi.Router, userCtrl *user.Controller, sysCtrl *system.Controller) {\n" ], "file_path": "internal/router/api.go", "type": "replace", "edit_start_line_idx": 435 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package account import ( "encoding/json" "net/http" "github.com/harness/gitness/internal/api/controller/user" "github.com/harness/gitness/internal/api/render" ) // HandleRegister returns an http.HandlerFunc that processes an http.Request // to register the named user account with the system. func HandleRegister(userCtrl *user.Controller) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() in := new(user.CreateInput) err := json.NewDecoder(r.Body).Decode(in) if err != nil { render.BadRequestf(w, "Invalid request body: %s.", err) return } tokenResponse, err := userCtrl.Register(ctx, in) if err != nil { render.TranslatedUserError(w, err) return } render.JSON(w, http.StatusOK, tokenResponse) } }
internal/api/handler/account/register.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.023076022043824196, 0.008751560933887959, 0.0001718736457405612, 0.005879174917936325, 0.009492077864706516 ]
{ "id": 12, "code_window": [ "\t\t\t})\n", "\t\t})\n", "\t})\n", "}\n", "\n", "func setupAccount(r chi.Router, userCtrl *user.Controller) {\n", "\tr.Post(\"/login\", account.HandleLogin(userCtrl))\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "func setupAccount(r chi.Router, userCtrl *user.Controller, sysCtrl *system.Controller) {\n" ], "file_path": "internal/router/api.go", "type": "replace", "edit_start_line_idx": 435 }
const generateStringTypes = require('../strings/generateTypes.cjs') class GenerateStringTypesPlugin { apply(compiler) { compiler.hooks.emit.tapAsync('GenerateStringTypesPlugin', (compilation, callback) => { try { generateStringTypes().then( () => callback(), e => callback(e) ) } catch (e) { callback(e) } }) } } module.exports.GenerateStringTypesPlugin = GenerateStringTypesPlugin
web/scripts/webpack/GenerateStringTypesPlugin.js
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00017233443213626742, 0.00017204825417138636, 0.00017176206165459007, 0.00017204825417138636, 2.861852408386767e-7 ]
{ "id": 12, "code_window": [ "\t\t\t})\n", "\t\t})\n", "\t})\n", "}\n", "\n", "func setupAccount(r chi.Router, userCtrl *user.Controller) {\n", "\tr.Post(\"/login\", account.HandleLogin(userCtrl))\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "func setupAccount(r chi.Router, userCtrl *user.Controller, sysCtrl *system.Controller) {\n" ], "file_path": "internal/router/api.go", "type": "replace", "edit_start_line_idx": 435 }
/* eslint-disable */ // this is an auto-generated file declare const styles: { readonly main: string } export default styles
web/src/components/NavigationCheck/NavigationCheck.module.scss.d.ts
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00017380081408191472, 0.00017380081408191472, 0.00017380081408191472, 0.00017380081408191472, 0 ]
{ "id": 12, "code_window": [ "\t\t\t})\n", "\t\t})\n", "\t})\n", "}\n", "\n", "func setupAccount(r chi.Router, userCtrl *user.Controller) {\n", "\tr.Post(\"/login\", account.HandleLogin(userCtrl))\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "func setupAccount(r chi.Router, userCtrl *user.Controller, sysCtrl *system.Controller) {\n" ], "file_path": "internal/router/api.go", "type": "replace", "edit_start_line_idx": 435 }
/.htaccess /administrator/cache/* /administrator/components/com_actionlogs/* /administrator/components/com_admin/* /administrator/components/com_ajax/* /administrator/components/com_associations/* /administrator/components/com_banners/* /administrator/components/com_cache/* /administrator/components/com_categories/* /administrator/components/com_checkin/* /administrator/components/com_config/* /administrator/components/com_contact/* /administrator/components/com_content/* /administrator/components/com_contenthistory/* /administrator/components/com_cpanel/* /administrator/components/com_fields/* /administrator/components/com_finder/* /administrator/components/com_installer/* /administrator/components/com_joomlaupdate/* /administrator/components/com_languages/* /administrator/components/com_login/* /administrator/components/com_media/* /administrator/components/com_menus/* /administrator/components/com_messages/* /administrator/components/com_modules/* /administrator/components/com_newsfeeds/* /administrator/components/com_plugins/* /administrator/components/com_postinstall/* /administrator/components/com_privacy/* /administrator/components/com_redirect/* /administrator/components/com_search/* /administrator/components/com_tags/* /administrator/components/com_templates/* /administrator/components/com_users/* /administrator/help/* /administrator/includes/* /administrator/index.php /administrator/language/en-GB/en-GB.com_actionlogs.ini /administrator/language/en-GB/en-GB.com_actionlogs.sys.ini /administrator/language/en-GB/en-GB.com_admin.ini /administrator/language/en-GB/en-GB.com_admin.sys.ini /administrator/language/en-GB/en-GB.com_ajax.ini /administrator/language/en-GB/en-GB.com_ajax.sys.ini /administrator/language/en-GB/en-GB.com_associations.ini /administrator/language/en-GB/en-GB.com_associations.sys.ini /administrator/language/en-GB/en-GB.com_banners.ini /administrator/language/en-GB/en-GB.com_banners.sys.ini /administrator/language/en-GB/en-GB.com_cache.ini /administrator/language/en-GB/en-GB.com_cache.sys.ini /administrator/language/en-GB/en-GB.com_categories.ini /administrator/language/en-GB/en-GB.com_categories.sys.ini /administrator/language/en-GB/en-GB.com_checkin.ini /administrator/language/en-GB/en-GB.com_checkin.sys.ini /administrator/language/en-GB/en-GB.com_config.ini /administrator/language/en-GB/en-GB.com_config.sys.ini /administrator/language/en-GB/en-GB.com_contact.ini /administrator/language/en-GB/en-GB.com_contact.sys.ini /administrator/language/en-GB/en-GB.com_content.ini /administrator/language/en-GB/en-GB.com_content.sys.ini /administrator/language/en-GB/en-GB.com_contenthistory.ini /administrator/language/en-GB/en-GB.com_contenthistory.sys.ini /administrator/language/en-GB/en-GB.com_cpanel.ini /administrator/language/en-GB/en-GB.com_cpanel.sys.ini /administrator/language/en-GB/en-GB.com_fields.ini /administrator/language/en-GB/en-GB.com_fields.sys.ini /administrator/language/en-GB/en-GB.com_finder.ini /administrator/language/en-GB/en-GB.com_finder.sys.ini /administrator/language/en-GB/en-GB.com_installer.ini /administrator/language/en-GB/en-GB.com_installer.sys.ini /administrator/language/en-GB/en-GB.com_joomlaupdate.ini /administrator/language/en-GB/en-GB.com_joomlaupdate.sys.ini /administrator/language/en-GB/en-GB.com_languages.ini /administrator/language/en-GB/en-GB.com_languages.sys.ini /administrator/language/en-GB/en-GB.com_login.ini /administrator/language/en-GB/en-GB.com_login.sys.ini /administrator/language/en-GB/en-GB.com_mailto.sys.ini /administrator/language/en-GB/en-GB.com_media.ini /administrator/language/en-GB/en-GB.com_media.sys.ini /administrator/language/en-GB/en-GB.com_menus.ini /administrator/language/en-GB/en-GB.com_menus.sys.ini /administrator/language/en-GB/en-GB.com_messages.ini /administrator/language/en-GB/en-GB.com_messages.sys.ini /administrator/language/en-GB/en-GB.com_modules.ini /administrator/language/en-GB/en-GB.com_modules.sys.ini /administrator/language/en-GB/en-GB.com_newsfeeds.ini /administrator/language/en-GB/en-GB.com_newsfeeds.sys.ini /administrator/language/en-GB/en-GB.com_plugins.ini /administrator/language/en-GB/en-GB.com_plugins.sys.ini /administrator/language/en-GB/en-GB.com_postinstall.ini /administrator/language/en-GB/en-GB.com_postinstall.sys.ini /administrator/language/en-GB/en-GB.com_privacy.ini /administrator/language/en-GB/en-GB.com_privacy.sys.ini /administrator/language/en-GB/en-GB.com_redirect.ini /administrator/language/en-GB/en-GB.com_redirect.sys.ini /administrator/language/en-GB/en-GB.com_search.ini /administrator/language/en-GB/en-GB.com_search.sys.ini /administrator/language/en-GB/en-GB.com_tags.ini /administrator/language/en-GB/en-GB.com_tags.sys.ini /administrator/language/en-GB/en-GB.com_templates.ini /administrator/language/en-GB/en-GB.com_templates.sys.ini /administrator/language/en-GB/en-GB.com_users.ini /administrator/language/en-GB/en-GB.com_users.sys.ini /administrator/language/en-GB/en-GB.com_weblinks.ini /administrator/language/en-GB/en-GB.com_weblinks.sys.ini /administrator/language/en-GB/en-GB.com_wrapper.ini /administrator/language/en-GB/en-GB.com_wrapper.sys.ini /administrator/language/en-GB/en-GB.ini /administrator/language/en-GB/en-GB.lib_joomla.ini /administrator/language/en-GB/en-GB.localise.php /administrator/language/en-GB/en-GB.mod_custom.ini /administrator/language/en-GB/en-GB.mod_custom.sys.ini /administrator/language/en-GB/en-GB.mod_feed.ini /administrator/language/en-GB/en-GB.mod_feed.sys.ini /administrator/language/en-GB/en-GB.mod_latest.ini /administrator/language/en-GB/en-GB.mod_latest.sys.ini /administrator/language/en-GB/en-GB.mod_latestactions.ini /administrator/language/en-GB/en-GB.mod_latestactions.sys.ini /administrator/language/en-GB/en-GB.mod_logged.ini /administrator/language/en-GB/en-GB.mod_logged.sys.ini /administrator/language/en-GB/en-GB.mod_login.ini /administrator/language/en-GB/en-GB.mod_login.sys.ini /administrator/language/en-GB/en-GB.mod_menu.ini /administrator/language/en-GB/en-GB.mod_menu.sys.ini /administrator/language/en-GB/en-GB.mod_multilangstatus.ini /administrator/language/en-GB/en-GB.mod_multilangstatus.sys.ini /administrator/language/en-GB/en-GB.mod_online.ini /administrator/language/en-GB/en-GB.mod_online.sys.ini /administrator/language/en-GB/en-GB.mod_popular.ini /administrator/language/en-GB/en-GB.mod_popular.sys.ini /administrator/language/en-GB/en-GB.mod_privacy_dashboard.ini /administrator/language/en-GB/en-GB.mod_privacy_dashboard.sys.ini /administrator/language/en-GB/en-GB.mod_quickicon.ini /administrator/language/en-GB/en-GB.mod_quickicon.sys.ini /administrator/language/en-GB/en-GB.mod_sampledata.ini /administrator/language/en-GB/en-GB.mod_sampledata.sys.ini /administrator/language/en-GB/en-GB.mod_stats_admin.ini /administrator/language/en-GB/en-GB.mod_stats_admin.sys.ini /administrator/language/en-GB/en-GB.mod_status.ini /administrator/language/en-GB/en-GB.mod_status.sys.ini /administrator/language/en-GB/en-GB.mod_submenu.ini /administrator/language/en-GB/en-GB.mod_submenu.sys.ini /administrator/language/en-GB/en-GB.mod_title.ini /administrator/language/en-GB/en-GB.mod_title.sys.ini /administrator/language/en-GB/en-GB.mod_toolbar.ini /administrator/language/en-GB/en-GB.mod_toolbar.sys.ini /administrator/language/en-GB/en-GB.mod_unread.ini /administrator/language/en-GB/en-GB.mod_unread.sys.ini /administrator/language/en-GB/en-GB.mod_version.ini /administrator/language/en-GB/en-GB.mod_version.sys.ini /administrator/language/en-GB/en-GB.plg_actionlog_joomla.ini /administrator/language/en-GB/en-GB.plg_actionlog_joomla.sys.ini /administrator/language/en-GB/en-GB.plg_authentication_cookie.ini /administrator/language/en-GB/en-GB.plg_authentication_cookie.sys.ini /administrator/language/en-GB/en-GB.plg_authentication_example.ini /administrator/language/en-GB/en-GB.plg_authentication_example.sys.ini /administrator/language/en-GB/en-GB.plg_authentication_gmail.ini /administrator/language/en-GB/en-GB.plg_authentication_gmail.sys.ini /administrator/language/en-GB/en-GB.plg_authentication_joomla.ini /administrator/language/en-GB/en-GB.plg_authentication_joomla.sys.ini /administrator/language/en-GB/en-GB.plg_authentication_ldap.ini /administrator/language/en-GB/en-GB.plg_authentication_ldap.sys.ini /administrator/language/en-GB/en-GB.plg_captcha_recaptcha.ini /administrator/language/en-GB/en-GB.plg_captcha_recaptcha.sys.ini /administrator/language/en-GB/en-GB.plg_captcha_recaptcha_invisible.ini /administrator/language/en-GB/en-GB.plg_captcha_recaptcha_invisible.sys.ini /administrator/language/en-GB/en-GB.plg_content_confirmconsent.ini /administrator/language/en-GB/en-GB.plg_content_confirmconsent.sys.ini /administrator/language/en-GB/en-GB.plg_content_contact.ini /administrator/language/en-GB/en-GB.plg_content_contact.sys.ini /administrator/language/en-GB/en-GB.plg_content_emailcloak.ini /administrator/language/en-GB/en-GB.plg_content_emailcloak.sys.ini /administrator/language/en-GB/en-GB.plg_content_fields.ini /administrator/language/en-GB/en-GB.plg_content_fields.sys.ini /administrator/language/en-GB/en-GB.plg_content_finder.ini /administrator/language/en-GB/en-GB.plg_content_finder.sys.ini /administrator/language/en-GB/en-GB.plg_content_geshi.ini /administrator/language/en-GB/en-GB.plg_content_geshi.sys.ini /administrator/language/en-GB/en-GB.plg_content_joomla.ini /administrator/language/en-GB/en-GB.plg_content_joomla.sys.ini /administrator/language/en-GB/en-GB.plg_content_loadmodule.ini /administrator/language/en-GB/en-GB.plg_content_loadmodule.sys.ini /administrator/language/en-GB/en-GB.plg_content_pagebreak.ini /administrator/language/en-GB/en-GB.plg_content_pagebreak.sys.ini /administrator/language/en-GB/en-GB.plg_content_pagenavigation.ini /administrator/language/en-GB/en-GB.plg_content_pagenavigation.sys.ini /administrator/language/en-GB/en-GB.plg_content_vote.ini /administrator/language/en-GB/en-GB.plg_content_vote.sys.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_article.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_article.sys.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_contact.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_contact.sys.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_fields.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_fields.sys.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_image.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_image.sys.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_menu.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_menu.sys.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_module.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_module.sys.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_pagebreak.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_pagebreak.sys.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_readmore.ini /administrator/language/en-GB/en-GB.plg_editors-xtd_readmore.sys.ini /administrator/language/en-GB/en-GB.plg_editors_codemirror.ini /administrator/language/en-GB/en-GB.plg_editors_codemirror.sys.ini /administrator/language/en-GB/en-GB.plg_editors_none.ini /administrator/language/en-GB/en-GB.plg_editors_none.sys.ini /administrator/language/en-GB/en-GB.plg_editors_tinymce.ini /administrator/language/en-GB/en-GB.plg_editors_tinymce.sys.ini /administrator/language/en-GB/en-GB.plg_extension_joomla.ini /administrator/language/en-GB/en-GB.plg_extension_joomla.sys.ini /administrator/language/en-GB/en-GB.plg_fields_calendar.ini /administrator/language/en-GB/en-GB.plg_fields_calendar.sys.ini /administrator/language/en-GB/en-GB.plg_fields_checkboxes.ini /administrator/language/en-GB/en-GB.plg_fields_checkboxes.sys.ini /administrator/language/en-GB/en-GB.plg_fields_color.ini /administrator/language/en-GB/en-GB.plg_fields_color.sys.ini /administrator/language/en-GB/en-GB.plg_fields_editor.ini /administrator/language/en-GB/en-GB.plg_fields_editor.sys.ini /administrator/language/en-GB/en-GB.plg_fields_image.ini /administrator/language/en-GB/en-GB.plg_fields_image.sys.ini /administrator/language/en-GB/en-GB.plg_fields_imagelist.ini /administrator/language/en-GB/en-GB.plg_fields_imagelist.sys.ini /administrator/language/en-GB/en-GB.plg_fields_integer.ini /administrator/language/en-GB/en-GB.plg_fields_integer.sys.ini /administrator/language/en-GB/en-GB.plg_fields_list.ini /administrator/language/en-GB/en-GB.plg_fields_list.sys.ini /administrator/language/en-GB/en-GB.plg_fields_media.ini /administrator/language/en-GB/en-GB.plg_fields_media.sys.ini /administrator/language/en-GB/en-GB.plg_fields_radio.ini /administrator/language/en-GB/en-GB.plg_fields_radio.sys.ini /administrator/language/en-GB/en-GB.plg_fields_repeatable.ini /administrator/language/en-GB/en-GB.plg_fields_repeatable.sys.ini /administrator/language/en-GB/en-GB.plg_fields_sql.ini /administrator/language/en-GB/en-GB.plg_fields_sql.sys.ini /administrator/language/en-GB/en-GB.plg_fields_text.ini /administrator/language/en-GB/en-GB.plg_fields_text.sys.ini /administrator/language/en-GB/en-GB.plg_fields_textarea.ini /administrator/language/en-GB/en-GB.plg_fields_textarea.sys.ini /administrator/language/en-GB/en-GB.plg_fields_url.ini /administrator/language/en-GB/en-GB.plg_fields_url.sys.ini /administrator/language/en-GB/en-GB.plg_fields_user.ini /administrator/language/en-GB/en-GB.plg_fields_user.sys.ini /administrator/language/en-GB/en-GB.plg_fields_usergrouplist.ini /administrator/language/en-GB/en-GB.plg_fields_usergrouplist.sys.ini /administrator/language/en-GB/en-GB.plg_finder_categories.ini /administrator/language/en-GB/en-GB.plg_finder_categories.sys.ini /administrator/language/en-GB/en-GB.plg_finder_contacts.ini /administrator/language/en-GB/en-GB.plg_finder_contacts.sys.ini /administrator/language/en-GB/en-GB.plg_finder_content.ini /administrator/language/en-GB/en-GB.plg_finder_content.sys.ini /administrator/language/en-GB/en-GB.plg_finder_newsfeeds.ini /administrator/language/en-GB/en-GB.plg_finder_newsfeeds.sys.ini /administrator/language/en-GB/en-GB.plg_finder_tags.ini /administrator/language/en-GB/en-GB.plg_finder_tags.sys.ini /administrator/language/en-GB/en-GB.plg_finder_weblinks.ini /administrator/language/en-GB/en-GB.plg_finder_weblinks.sys.ini /administrator/language/en-GB/en-GB.plg_installer_folderinstaller.ini /administrator/language/en-GB/en-GB.plg_installer_folderinstaller.sys.ini /administrator/language/en-GB/en-GB.plg_installer_packageinstaller.ini /administrator/language/en-GB/en-GB.plg_installer_packageinstaller.sys.ini /administrator/language/en-GB/en-GB.plg_installer_urlinstaller.ini /administrator/language/en-GB/en-GB.plg_installer_urlinstaller.sys.ini /administrator/language/en-GB/en-GB.plg_installer_webinstaller.ini /administrator/language/en-GB/en-GB.plg_installer_webinstaller.sys.ini /administrator/language/en-GB/en-GB.plg_privacy_actionlogs.ini /administrator/language/en-GB/en-GB.plg_privacy_actionlogs.sys.ini /administrator/language/en-GB/en-GB.plg_privacy_consents.ini /administrator/language/en-GB/en-GB.plg_privacy_consents.sys.ini /administrator/language/en-GB/en-GB.plg_privacy_contact.ini /administrator/language/en-GB/en-GB.plg_privacy_contact.sys.ini /administrator/language/en-GB/en-GB.plg_privacy_content.ini /administrator/language/en-GB/en-GB.plg_privacy_content.sys.ini /administrator/language/en-GB/en-GB.plg_privacy_message.ini /administrator/language/en-GB/en-GB.plg_privacy_message.sys.ini /administrator/language/en-GB/en-GB.plg_privacy_user.ini /administrator/language/en-GB/en-GB.plg_privacy_user.sys.ini /administrator/language/en-GB/en-GB.plg_quickicon_extensionupdate.ini /administrator/language/en-GB/en-GB.plg_quickicon_extensionupdate.sys.ini /administrator/language/en-GB/en-GB.plg_quickicon_joomlaupdate.ini /administrator/language/en-GB/en-GB.plg_quickicon_joomlaupdate.sys.ini /administrator/language/en-GB/en-GB.plg_quickicon_phpversioncheck.ini /administrator/language/en-GB/en-GB.plg_quickicon_phpversioncheck.sys.ini /administrator/language/en-GB/en-GB.plg_quickicon_privacycheck.ini /administrator/language/en-GB/en-GB.plg_quickicon_privacycheck.sys.ini /administrator/language/en-GB/en-GB.plg_sampledata_blog.ini /administrator/language/en-GB/en-GB.plg_sampledata_blog.sys.ini /administrator/language/en-GB/en-GB.plg_search_categories.ini /administrator/language/en-GB/en-GB.plg_search_categories.sys.ini /administrator/language/en-GB/en-GB.plg_search_contacts.ini /administrator/language/en-GB/en-GB.plg_search_contacts.sys.ini /administrator/language/en-GB/en-GB.plg_search_content.ini /administrator/language/en-GB/en-GB.plg_search_content.sys.ini /administrator/language/en-GB/en-GB.plg_search_newsfeeds.ini /administrator/language/en-GB/en-GB.plg_search_newsfeeds.sys.ini /administrator/language/en-GB/en-GB.plg_search_tags.ini /administrator/language/en-GB/en-GB.plg_search_tags.sys.ini /administrator/language/en-GB/en-GB.plg_search_weblinks.ini /administrator/language/en-GB/en-GB.plg_search_weblinks.sys.ini /administrator/language/en-GB/en-GB.plg_system_actionlogs.ini /administrator/language/en-GB/en-GB.plg_system_actionlogs.sys.ini /administrator/language/en-GB/en-GB.plg_system_cache.ini /administrator/language/en-GB/en-GB.plg_system_cache.sys.ini /administrator/language/en-GB/en-GB.plg_system_debug.ini /administrator/language/en-GB/en-GB.plg_system_debug.sys.ini /administrator/language/en-GB/en-GB.plg_system_fields.ini /administrator/language/en-GB/en-GB.plg_system_fields.sys.ini /administrator/language/en-GB/en-GB.plg_system_highlight.ini /administrator/language/en-GB/en-GB.plg_system_highlight.sys.ini /administrator/language/en-GB/en-GB.plg_system_languagecode.ini /administrator/language/en-GB/en-GB.plg_system_languagecode.sys.ini /administrator/language/en-GB/en-GB.plg_system_languagefilter.ini /administrator/language/en-GB/en-GB.plg_system_languagefilter.sys.ini /administrator/language/en-GB/en-GB.plg_system_log.ini /administrator/language/en-GB/en-GB.plg_system_log.sys.ini /administrator/language/en-GB/en-GB.plg_system_logout.ini /administrator/language/en-GB/en-GB.plg_system_logout.sys.ini /administrator/language/en-GB/en-GB.plg_system_logrotation.ini /administrator/language/en-GB/en-GB.plg_system_logrotation.sys.ini /administrator/language/en-GB/en-GB.plg_system_p3p.ini /administrator/language/en-GB/en-GB.plg_system_p3p.sys.ini /administrator/language/en-GB/en-GB.plg_system_privacyconsent.ini /administrator/language/en-GB/en-GB.plg_system_privacyconsent.sys.ini /administrator/language/en-GB/en-GB.plg_system_redirect.ini /administrator/language/en-GB/en-GB.plg_system_redirect.sys.ini /administrator/language/en-GB/en-GB.plg_system_remember.ini /administrator/language/en-GB/en-GB.plg_system_remember.sys.ini /administrator/language/en-GB/en-GB.plg_system_sef.ini /administrator/language/en-GB/en-GB.plg_system_sef.sys.ini /administrator/language/en-GB/en-GB.plg_system_sessiongc.ini /administrator/language/en-GB/en-GB.plg_system_sessiongc.sys.ini /administrator/language/en-GB/en-GB.plg_system_stats.ini /administrator/language/en-GB/en-GB.plg_system_stats.sys.ini /administrator/language/en-GB/en-GB.plg_system_updatenotification.ini /administrator/language/en-GB/en-GB.plg_system_updatenotification.sys.ini /administrator/language/en-GB/en-GB.plg_twofactorauth_totp.ini /administrator/language/en-GB/en-GB.plg_twofactorauth_totp.sys.ini /administrator/language/en-GB/en-GB.plg_twofactorauth_yubikey.ini /administrator/language/en-GB/en-GB.plg_twofactorauth_yubikey.sys.ini /administrator/language/en-GB/en-GB.plg_user_contactcreator.ini /administrator/language/en-GB/en-GB.plg_user_contactcreator.sys.ini /administrator/language/en-GB/en-GB.plg_user_joomla.ini /administrator/language/en-GB/en-GB.plg_user_joomla.sys.ini /administrator/language/en-GB/en-GB.plg_user_profile.ini /administrator/language/en-GB/en-GB.plg_user_profile.sys.ini /administrator/language/en-GB/en-GB.plg_user_terms.ini /administrator/language/en-GB/en-GB.plg_user_terms.sys.ini /administrator/language/en-GB/en-GB.tpl_hathor.ini /administrator/language/en-GB/en-GB.tpl_hathor.sys.ini /administrator/language/en-GB/en-GB.tpl_isis.ini /administrator/language/en-GB/en-GB.tpl_isis.sys.ini /administrator/language/en-GB/en-GB.xml /administrator/language/en-GB/install.xml /administrator/language/overrides/* /administrator/language/index.html /administrator/logs/* /administrator/manifests/files/joomla.xml /administrator/manifests/libraries/fof.xml /administrator/manifests/libraries/idna_convert.xml /administrator/manifests/libraries/joomla.xml /administrator/manifests/libraries/phpass.xml /administrator/manifests/libraries/phputf8.xml /administrator/manifests/packages/pkg_en-GB.xml /administrator/manifests/packages/index.html /administrator/modules/mod_custom/* /administrator/modules/mod_feed/* /administrator/modules/mod_latest/* /administrator/modules/mod_latestactions/* /administrator/modules/mod_logged/* /administrator/modules/mod_login/* /administrator/modules/mod_menu/* /administrator/modules/mod_multilangstatus/* /administrator/modules/mod_online/* /administrator/modules/mod_popular/* /administrator/modules/mod_privacy_dashboard/* /administrator/modules/mod_quickicon/* /administrator/modules/mod_sampledata/* /administrator/modules/mod_stats_admin/* /administrator/modules/mod_status/* /administrator/modules/mod_submenu/* /administrator/modules/mod_title/* /administrator/modules/mod_toolbar/* /administrator/modules/mod_unread/* /administrator/modules/mod_version/* /administrator/templates/hathor/* /administrator/templates/isis/* /administrator/templates/system/* /bin/* /cache/* /cli/* /components/com_ajax/* /components/com_banners/* /components/com_config/* /components/com_contact/* /components/com_content/* /components/com_contenthistory/* /components/com_fields/* /components/com_finder/* /components/com_mailto/* /components/com_media/* /components/com_menus/* /components/com_modules/* /components/com_newsfeeds/* /components/com_privacy/* /components/com_search/* /components/com_tags/* /components/com_users/* /components/com_wrapper/* /components/index.html /images/banners/* /images/headers/* /images/sampledata/* /images/index.html /images/joomla* /images/powered_by.png /includes/* /installation/* /language/en-GB/en-GB.com_ajax.ini /language/en-GB/en-GB.com_config.ini /language/en-GB/en-GB.com_contact.ini /language/en-GB/en-GB.com_content.ini /language/en-GB/en-GB.com_finder.ini /language/en-GB/en-GB.com_mailto.ini /language/en-GB/en-GB.com_media.ini /language/en-GB/en-GB.com_messages.ini /language/en-GB/en-GB.com_newsfeeds.ini /language/en-GB/en-GB.com_privacy.ini /language/en-GB/en-GB.com_search.ini /language/en-GB/en-GB.com_tags.ini /language/en-GB/en-GB.com_users.ini /language/en-GB/en-GB.com_weblinks.ini /language/en-GB/en-GB.com_wrapper.ini /language/en-GB/en-GB.files_joomla.sys.ini /language/en-GB/en-GB.finder_cli.ini /language/en-GB/en-GB.ini /language/en-GB/en-GB.lib_fof.ini /language/en-GB/en-GB.lib_fof.sys.ini /language/en-GB/en-GB.lib_idna_convert.sys.ini /language/en-GB/en-GB.lib_joomla.ini /language/en-GB/en-GB.lib_joomla.sys.ini /language/en-GB/en-GB.lib_phpass.sys.ini /language/en-GB/en-GB.lib_phpmailer.sys.ini /language/en-GB/en-GB.lib_phputf8.sys.ini /language/en-GB/en-GB.lib_simplepie.sys.ini /language/en-GB/en-GB.localise.php /language/en-GB/en-GB.mod_articles_archive.ini /language/en-GB/en-GB.mod_articles_archive.sys.ini /language/en-GB/en-GB.mod_articles_categories.ini /language/en-GB/en-GB.mod_articles_categories.sys.ini /language/en-GB/en-GB.mod_articles_category.ini /language/en-GB/en-GB.mod_articles_category.sys.ini /language/en-GB/en-GB.mod_articles_latest.ini /language/en-GB/en-GB.mod_articles_latest.sys.ini /language/en-GB/en-GB.mod_articles_news.ini /language/en-GB/en-GB.mod_articles_news.sys.ini /language/en-GB/en-GB.mod_articles_popular.ini /language/en-GB/en-GB.mod_articles_popular.sys.ini /language/en-GB/en-GB.mod_banners.ini /language/en-GB/en-GB.mod_banners.sys.ini /language/en-GB/en-GB.mod_breadcrumbs.ini /language/en-GB/en-GB.mod_breadcrumbs.sys.ini /language/en-GB/en-GB.mod_custom.ini /language/en-GB/en-GB.mod_custom.sys.ini /language/en-GB/en-GB.mod_feed.ini /language/en-GB/en-GB.mod_feed.sys.ini /language/en-GB/en-GB.mod_finder.ini /language/en-GB/en-GB.mod_finder.sys.ini /language/en-GB/en-GB.mod_footer.ini /language/en-GB/en-GB.mod_footer.sys.ini /language/en-GB/en-GB.mod_languages.ini /language/en-GB/en-GB.mod_languages.sys.ini /language/en-GB/en-GB.mod_login.ini /language/en-GB/en-GB.mod_login.sys.ini /language/en-GB/en-GB.mod_menu.ini /language/en-GB/en-GB.mod_menu.sys.ini /language/en-GB/en-GB.mod_random_image.ini /language/en-GB/en-GB.mod_random_image.sys.ini /language/en-GB/en-GB.mod_related_items.ini /language/en-GB/en-GB.mod_related_items.sys.ini /language/en-GB/en-GB.mod_search.ini /language/en-GB/en-GB.mod_search.sys.ini /language/en-GB/en-GB.mod_stats.ini /language/en-GB/en-GB.mod_stats.sys.ini /language/en-GB/en-GB.mod_syndicate.ini /language/en-GB/en-GB.mod_syndicate.sys.ini /language/en-GB/en-GB.mod_tags_popular.ini /language/en-GB/en-GB.mod_tags_popular.sys.ini /language/en-GB/en-GB.mod_tags_similar.ini /language/en-GB/en-GB.mod_tags_similar.sys.ini /language/en-GB/en-GB.mod_users_latest.ini /language/en-GB/en-GB.mod_users_latest.sys.ini /language/en-GB/en-GB.mod_weblinks.ini /language/en-GB/en-GB.mod_weblinks.sys.ini /language/en-GB/en-GB.mod_whosonline.ini /language/en-GB/en-GB.mod_whosonline.sys.ini /language/en-GB/en-GB.mod_wrapper.ini /language/en-GB/en-GB.mod_wrapper.sys.ini /language/en-GB/en-GB.tpl_atomic.ini /language/en-GB/en-GB.tpl_atomic.sys.ini /language/en-GB/en-GB.tpl_beez3.ini /language/en-GB/en-GB.tpl_beez3.sys.ini /language/en-GB/en-GB.tpl_beez5.ini /language/en-GB/en-GB.tpl_beez5.sys.ini /language/en-GB/en-GB.tpl_beez_20.ini /language/en-GB/en-GB.tpl_beez_20.sys.ini /language/en-GB/en-GB.tpl_protostar.ini /language/en-GB/en-GB.tpl_protostar.sys.ini /language/en-GB/en-GB.xml /language/en-GB/install.xml /language/overrides/* /language/index.html /layouts/joomla/* /layouts/libraries/* /layouts/plugins/* /layouts/index.html /libraries/cms/* /libraries/fof/* /libraries/idna_convert/* /libraries/joomla/* /libraries/legacy/* /libraries/php-encryption/* /libraries/phpass/* /libraries/phpmailer/* /libraries/phputf8/* /libraries/simplepie/* /libraries/src/* /libraries/vendor/* /libraries/classmap.php /libraries/cms.php /libraries/import.legacy.php /libraries/import.php /libraries/index.html /libraries/loader.php /media/cms/* /media/com_associations/* /media/com_contact/* /media/com_content/* /media/com_contenthistory/* /media/com_fields/* /media/com_finder/* /media/com_joomlaupdate/* /media/com_menus/* /media/com_modules/* /media/com_wrapper/* /media/contacts/* /media/editors/* /media/jui/* /media/mailto/* /media/media/* /media/mod_languages/* /media/mod_sampledata/* /media/overrider/* /media/plg_captcha_recaptcha/* /media/plg_captcha_recaptcha_invisible/* /media/plg_quickicon_extensionupdate/* /media/plg_quickicon_joomlaupdate/* /media/plg_quickicon_privacycheck/* /media/plg_system_highlight/* /media/plg_system_stats/* /media/plg_twofactorauth_totp/* /media/system/* /media/index.html /modules/mod_articles_archive/* /modules/mod_articles_categories/* /modules/mod_articles_category/* /modules/mod_articles_latest/* /modules/mod_articles_news/* /modules/mod_articles_popular/* /modules/mod_banners/* /modules/mod_breadcrumbs/* /modules/mod_custom/* /modules/mod_feed/* /modules/mod_finder/* /modules/mod_footer/* /modules/mod_languages/* /modules/mod_login/* /modules/mod_menu/* /modules/mod_random_image/* /modules/mod_related_items/* /modules/mod_search/* /modules/mod_stats/* /modules/mod_syndicate/* /modules/mod_tags_popular/* /modules/mod_tags_similar/* /modules/mod_users_latest/* /modules/mod_whosonline/* /modules/mod_wrapper/* /modules/index.html /plugins/actionlog/joomla/* /plugins/authentication/cookie/* /plugins/authentication/example/* /plugins/authentication/gmail/* /plugins/authentication/joomla/* /plugins/authentication/ldap/* /plugins/captcha/recaptcha/* /plugins/captcha/recaptcha_invisible/* /plugins/content/confirmconsent/* /plugins/content/contact/* /plugins/content/emailcloak/* /plugins/content/example/* /plugins/content/fields/* /plugins/content/finder/* /plugins/content/geshi/* /plugins/content/joomla/* /plugins/content/loadmodule/* /plugins/content/pagebreak/* /plugins/content/pagenavigation/* /plugins/content/vote/* /plugins/editors/codemirror/* /plugins/editors/none/* /plugins/editors/tinymce/* /plugins/editors-xtd/article/* /plugins/editors-xtd/contact/* /plugins/editors-xtd/fields/* /plugins/editors-xtd/image/* /plugins/editors-xtd/menu/* /plugins/editors-xtd/module/* /plugins/editors-xtd/pagebreak/* /plugins/editors-xtd/readmore/* /plugins/extension/example/* /plugins/extension/joomla/* /plugins/fields/calendar/* /plugins/fields/checkboxes/* /plugins/fields/color/* /plugins/fields/editor/* /plugins/fields/imagelist/* /plugins/fields/integer/* /plugins/fields/list/* /plugins/fields/media/* /plugins/fields/radio/* /plugins/fields/repeatable/* /plugins/fields/sql/* /plugins/fields/text/* /plugins/fields/textarea/* /plugins/fields/url/* /plugins/fields/user/* /plugins/fields/usergrouplist/* /plugins/finder/categories/* /plugins/finder/contacts/* /plugins/finder/content/* /plugins/finder/newsfeeds/* /plugins/finder/tags/* /plugins/installer/folderinstaller/* /plugins/installer/packageinstaller/* /plugins/installer/urlinstaller/* /plugins/privacy/actionlogs/* /plugins/privacy/consents/* /plugins/privacy/contact/* /plugins/privacy/content/* /plugins/privacy/message/* /plugins/privacy/user/* /plugins/quickicon/extensionupdate/* /plugins/quickicon/joomlaupdate/* /plugins/quickicon/phpversioncheck/* /plugins/quickicon/privacycheck/* /plugins/quickicon/index.html /plugins/sampledata/blog/* /plugins/search/categories/* /plugins/search/contacts/* /plugins/search/content/* /plugins/search/newsfeeds/* /plugins/search/tags/* /plugins/search/weblinks/* /plugins/search/index.html /plugins/system/actionlogs/* /plugins/system/cache/* /plugins/system/debug/* /plugins/system/fields/* /plugins/system/highlight/* /plugins/system/languagecode/* /plugins/system/languagefilter/* /plugins/system/log/* /plugins/system/logout/* /plugins/system/logrotation/* /plugins/system/p3p/* /plugins/system/privacyconsent/* /plugins/system/redirect/* /plugins/system/remember/* /plugins/system/sef/* /plugins/system/sessiongc/* /plugins/system/stats/* /plugins/system/updatenotification/* /plugins/system/index.html /plugins/twofactorauth/totp/* /plugins/twofactorauth/yubikey/* /plugins/user/contactcreator/* /plugins/user/example/* /plugins/user/joomla/* /plugins/user/profile/* /plugins/user/terms/* /plugins/user/index.html /plugins/index.html /templates/beez3/* /templates/protostar/* /templates/system/* /templates/index.html /tmp/* /configuration.php /htaccess.txt /index.php /joomla.xml /LICENSE.txt /README.txt /robots.txt.dist /web.config.txt
resources/gitignore/Joomla.gitignore
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00017476783250458539, 0.00016808546206448227, 0.0001634823129279539, 0.00016787364438641816, 0.000003045184257643996 ]
{ "id": 13, "code_window": [ "\tr.Post(\"/login\", account.HandleLogin(userCtrl))\n", "\tr.Post(\"/register\", account.HandleRegister(userCtrl))\n", "\tr.Post(\"/logout\", account.HandleLogout(userCtrl))\n", "}" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\tr.Post(\"/register\", account.HandleRegister(userCtrl, sysCtrl))\n" ], "file_path": "internal/router/api.go", "type": "replace", "edit_start_line_idx": 437 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package system import ( "context" "github.com/harness/gitness/internal/store" "github.com/harness/gitness/types" ) type Controller struct { principalStore store.PrincipalStore config *types.Config } func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller { return &Controller{ principalStore: principalStore, config: config, } } func IsUserRegistrationAllowed(ctx context.Context, principalStore store.PrincipalStore, config *types.Config) (bool, error) { usrCount, err := principalStore.CountUsers(ctx) if err != nil { return false, err } return usrCount == 0 || config.AllowSignUp, nil }
internal/api/controller/system/controller.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00018203684885520488, 0.00017612078227102757, 0.00017068404122255743, 0.0001758811267791316, 0.000004997563792130677 ]
{ "id": 13, "code_window": [ "\tr.Post(\"/login\", account.HandleLogin(userCtrl))\n", "\tr.Post(\"/register\", account.HandleRegister(userCtrl))\n", "\tr.Post(\"/logout\", account.HandleLogout(userCtrl))\n", "}" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\tr.Post(\"/register\", account.HandleRegister(userCtrl, sysCtrl))\n" ], "file_path": "internal/router/api.go", "type": "replace", "edit_start_line_idx": 437 }
import PrOpen from 'images/pull-request-open.svg' import PrMerged from 'images/pull-request-merged.svg' import PrClosed from 'images/pull-request-closed.svg' import PrRejected from 'images/pull-request-rejected.svg' import PrDraft from 'images/pull-request-draft.svg' import EmptyState from 'images/empty-state.svg' import error404 from 'images/404-error.svg' import PrUnchecked from 'images/pull-request-unchecked.svg' import DarkBackground from 'images/dark-background.png' import Signup from 'images/signup.png' import Subtract from 'images/Subtract.png' export const Images = { PrOpen, PrMerged, PrClosed, PrRejected, PrDraft, error404, EmptyState, PrUnchecked, DarkBackground, Signup, Subtract }
web/src/images/index.ts
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00017556888633407652, 0.00017208245117217302, 0.0001666340249357745, 0.00017404441314283758, 0.000003902558091795072 ]
{ "id": 13, "code_window": [ "\tr.Post(\"/login\", account.HandleLogin(userCtrl))\n", "\tr.Post(\"/register\", account.HandleRegister(userCtrl))\n", "\tr.Post(\"/logout\", account.HandleLogout(userCtrl))\n", "}" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\tr.Post(\"/register\", account.HandleRegister(userCtrl, sysCtrl))\n" ], "file_path": "internal/router/api.go", "type": "replace", "edit_start_line_idx": 437 }
import React, { useEffect, useMemo, useRef } from 'react' import { Container } from '@harness/uicore' import { LanguageDescription } from '@codemirror/language' import { indentWithTab } from '@codemirror/commands' import cx from 'classnames' import type { ViewUpdate } from '@codemirror/view' import type { Text } from '@codemirror/state' import { languages } from '@codemirror/language-data' import { markdown } from '@codemirror/lang-markdown' import { EditorView, keymap, placeholder as placeholderExtension } from '@codemirror/view' import { Compartment, EditorState, Extension } from '@codemirror/state' import { color } from '@uiw/codemirror-extensions-color' import { hyperLink } from '@uiw/codemirror-extensions-hyper-link' import { githubLight as theme } from '@uiw/codemirror-themes-all' import css from './Editor.module.scss' export interface EditorProps { content: string filename?: string forMarkdown?: boolean placeholder?: string readonly?: boolean autoFocus?: boolean className?: string extensions?: Extension maxHeight?: string | number viewRef?: React.MutableRefObject<EditorView | undefined> setDirty?: React.Dispatch<React.SetStateAction<boolean>> onChange?: (doc: Text, viewUpdate: ViewUpdate, isDirty: boolean) => void onViewUpdate?: (viewUpdate: ViewUpdate) => void } export const Editor = React.memo(function CodeMirrorReactEditor({ content, filename, forMarkdown, placeholder, readonly = false, autoFocus, className, extensions = new Compartment().of([]), maxHeight, viewRef, setDirty, onChange, onViewUpdate }: EditorProps) { const view = useRef<EditorView>() const ref = useRef<HTMLDivElement>() const languageConfig = useMemo(() => new Compartment(), []) const markdownLanguageSupport = useMemo(() => markdown({ codeLanguages: languages }), []) const style = useMemo(() => { if (maxHeight) { return { '--editor-max-height': Number.isInteger(maxHeight) ? `${maxHeight}px` : maxHeight } as React.CSSProperties } }, [maxHeight]) const onChangeRef = useRef<EditorProps['onChange']>(onChange) useEffect(() => { onChangeRef.current = onChange }, [onChange]) useEffect(() => { const editorView = new EditorView({ doc: content, extensions: [ extensions, color, hyperLink, theme, EditorView.lineWrapping, ...(placeholder ? [placeholderExtension(placeholder)] : []), keymap.of([indentWithTab]), ...(readonly ? [EditorState.readOnly.of(true), EditorView.editable.of(false)] : []), EditorView.updateListener.of(viewUpdate => { const isDirty = !cleanDoc.eq(viewUpdate.state.doc) setDirty?.(isDirty) onViewUpdate?.(viewUpdate) if (viewUpdate.docChanged) { onChangeRef.current?.(viewUpdate.state.doc, viewUpdate, isDirty) } }), /** languageConfig is a compartment that defaults to an empty array (no language support) at first, when a language is detected, languageConfig is used to reconfigure dynamically. @see https://codemirror.net/examples/config/ */ languageConfig.of([]) ], parent: ref.current }) view.current = editorView if (viewRef) { viewRef.current = editorView } const cleanDoc = editorView.state.doc if (autoFocus) { editorView.focus() } return () => { editorView.destroy() } }, []) // eslint-disable-line react-hooks/exhaustive-deps // Dynamically load language support based on filename. Note that // we need to configure languageSupport for Markdown separately to // enable syntax highlighting for all code blocks (multi-lang). useEffect(() => { if (forMarkdown) { view.current?.dispatch({ effects: languageConfig.reconfigure(markdownLanguageSupport) }) } else if (filename) { LanguageDescription.matchFilename(languages, filename) ?.load() .then(languageSupport => { view.current?.dispatch({ effects: languageConfig.reconfigure( languageSupport.language.name === 'markdown' ? markdownLanguageSupport : languageSupport ) }) }) } }, [filename, forMarkdown, view, languageConfig, markdownLanguageSupport]) return <Container ref={ref} className={cx(css.editor, className)} style={style} /> })
web/src/components/Editor/Editor.tsx
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00017991216736845672, 0.000174529806827195, 0.0001700128777883947, 0.00017441822274122387, 0.000002591164957266301 ]
{ "id": 13, "code_window": [ "\tr.Post(\"/login\", account.HandleLogin(userCtrl))\n", "\tr.Post(\"/register\", account.HandleRegister(userCtrl))\n", "\tr.Post(\"/logout\", account.HandleLogout(userCtrl))\n", "}" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\tr.Post(\"/register\", account.HandleRegister(userCtrl, sysCtrl))\n" ], "file_path": "internal/router/api.go", "type": "replace", "edit_start_line_idx": 437 }
/* eslint-disable */ // this is an auto-generated file declare const styles: { readonly main: string readonly withBorder: string readonly standalone: string readonly layout: string readonly text: string } export default styles
web/src/components/LoadingSpinner/LoadingSpinner.module.scss.d.ts
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00017991216736845672, 0.00017483059491496533, 0.00016974902246147394, 0.00017483059491496533, 0.00000508157245349139 ]
{ "id": 0, "code_window": [ "\n", "// MaxUnavailable returns the maximum unavailable pods a rolling deployment can take.\n", "func MaxUnavailable(deployment extensions.Deployment) int32 {\n", "\tif !IsRollingUpdate(&deployment) || *(deployment.Spec.Replicas) == 0 {\n", "\t\treturn int32(0)\n", "\t}\n", "\t// Error caught by validation\n", "\t_, maxUnavailable, _ := ResolveFenceposts(deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, *(deployment.Spec.Replicas))\n", "\treturn maxUnavailable\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tif !IsRollingUpdate(&deployment) {\n" ], "file_path": "pkg/controller/deployment/util/deployment_util.go", "type": "replace", "edit_start_line_idx": 412 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.9987285733222961, 0.22264932096004486, 0.00016709609190002084, 0.000938807672355324, 0.41005009412765503 ]
{ "id": 0, "code_window": [ "\n", "// MaxUnavailable returns the maximum unavailable pods a rolling deployment can take.\n", "func MaxUnavailable(deployment extensions.Deployment) int32 {\n", "\tif !IsRollingUpdate(&deployment) || *(deployment.Spec.Replicas) == 0 {\n", "\t\treturn int32(0)\n", "\t}\n", "\t// Error caught by validation\n", "\t_, maxUnavailable, _ := ResolveFenceposts(deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, *(deployment.Spec.Replicas))\n", "\treturn maxUnavailable\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tif !IsRollingUpdate(&deployment) {\n" ], "file_path": "pkg/controller/deployment/util/deployment_util.go", "type": "replace", "edit_start_line_idx": 412 }
/* Copyright 2014 The Kubernetes Authors. 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 serviceaccount import ( apiserverserviceaccount "k8s.io/apiserver/pkg/authentication/serviceaccount" "k8s.io/apiserver/pkg/authentication/user" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/v1" ) // UserInfo returns a user.Info interface for the given namespace, service account name and UID func UserInfo(namespace, name, uid string) user.Info { return &user.DefaultInfo{ Name: apiserverserviceaccount.MakeUsername(namespace, name), UID: uid, Groups: apiserverserviceaccount.MakeGroupNames(namespace, name), } } // IsServiceAccountToken returns true if the secret is a valid api token for the service account func IsServiceAccountToken(secret *v1.Secret, sa *v1.ServiceAccount) bool { if secret.Type != v1.SecretTypeServiceAccountToken { return false } name := secret.Annotations[v1.ServiceAccountNameKey] uid := secret.Annotations[v1.ServiceAccountUIDKey] if name != sa.Name { // Name must match return false } if len(uid) > 0 && uid != string(sa.UID) { // If UID is specified, it must match return false } return true } // TODO: remove the duplicate code // InternalIsServiceAccountToken returns true if the secret is a valid api token for the service account func InternalIsServiceAccountToken(secret *api.Secret, sa *api.ServiceAccount) bool { if secret.Type != api.SecretTypeServiceAccountToken { return false } name := secret.Annotations[api.ServiceAccountNameKey] uid := secret.Annotations[api.ServiceAccountUIDKey] if name != sa.Name { // Name must match return false } if len(uid) > 0 && uid != string(sa.UID) { // If UID is specified, it must match return false } return true }
pkg/serviceaccount/util.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00019922282081097364, 0.00017591429059393704, 0.00016611781029496342, 0.00017325347289443016, 0.000009806582056626212 ]
{ "id": 0, "code_window": [ "\n", "// MaxUnavailable returns the maximum unavailable pods a rolling deployment can take.\n", "func MaxUnavailable(deployment extensions.Deployment) int32 {\n", "\tif !IsRollingUpdate(&deployment) || *(deployment.Spec.Replicas) == 0 {\n", "\t\treturn int32(0)\n", "\t}\n", "\t// Error caught by validation\n", "\t_, maxUnavailable, _ := ResolveFenceposts(deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, *(deployment.Spec.Replicas))\n", "\treturn maxUnavailable\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tif !IsRollingUpdate(&deployment) {\n" ], "file_path": "pkg/controller/deployment/util/deployment_util.go", "type": "replace", "edit_start_line_idx": 412 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "bytes" "fmt" "os" "os/signal" "syscall" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/watch" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/apps" "k8s.io/kubernetes/pkg/apis/extensions" externalextensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" printersinternal "k8s.io/kubernetes/pkg/printers/internalversion" sliceutil "k8s.io/kubernetes/pkg/util/slice" ) // Rollbacker provides an interface for resources that can be rolled back. type Rollbacker interface { Rollback(obj runtime.Object, updatedAnnotations map[string]string, toRevision int64, dryRun bool) (string, error) } func RollbackerFor(kind schema.GroupKind, c clientset.Interface) (Rollbacker, error) { switch kind { case extensions.Kind("Deployment"), apps.Kind("Deployment"): return &DeploymentRollbacker{c}, nil } return nil, fmt.Errorf("no rollbacker has been implemented for %q", kind) } type DeploymentRollbacker struct { c clientset.Interface } func (r *DeploymentRollbacker) Rollback(obj runtime.Object, updatedAnnotations map[string]string, toRevision int64, dryRun bool) (string, error) { d, ok := obj.(*extensions.Deployment) if !ok { return "", fmt.Errorf("passed object is not a Deployment: %#v", obj) } if dryRun { return simpleDryRun(d, r.c, toRevision) } if d.Spec.Paused { return "", fmt.Errorf("you cannot rollback a paused deployment; resume it first with 'kubectl rollout resume deployment/%s' and try again", d.Name) } deploymentRollback := &extensions.DeploymentRollback{ Name: d.Name, UpdatedAnnotations: updatedAnnotations, RollbackTo: extensions.RollbackConfig{ Revision: toRevision, }, } result := "" // Get current events events, err := r.c.Core().Events(d.Namespace).List(metav1.ListOptions{}) if err != nil { return result, err } // Do the rollback if err := r.c.Extensions().Deployments(d.Namespace).Rollback(deploymentRollback); err != nil { return result, err } // Watch for the changes of events watch, err := r.c.Core().Events(d.Namespace).Watch(metav1.ListOptions{Watch: true, ResourceVersion: events.ResourceVersion}) if err != nil { return result, err } result = watchRollbackEvent(watch) return result, err } // watchRollbackEvent watches for rollback events and returns rollback result func watchRollbackEvent(w watch.Interface) string { signals := make(chan os.Signal, 1) signal.Notify(signals, os.Interrupt, os.Kill, syscall.SIGTERM) for { select { case event, ok := <-w.ResultChan(): if !ok { return "" } obj, ok := event.Object.(*api.Event) if !ok { w.Stop() return "" } isRollback, result := isRollbackEvent(obj) if isRollback { w.Stop() return result } case <-signals: w.Stop() } } } // isRollbackEvent checks if the input event is about rollback, and returns true and // related result string back if it is. func isRollbackEvent(e *api.Event) (bool, string) { rollbackEventReasons := []string{deploymentutil.RollbackRevisionNotFound, deploymentutil.RollbackTemplateUnchanged, deploymentutil.RollbackDone} for _, reason := range rollbackEventReasons { if e.Reason == reason { if reason == deploymentutil.RollbackDone { return true, "rolled back" } return true, fmt.Sprintf("skipped rollback (%s: %s)", e.Reason, e.Message) } } return false, "" } func simpleDryRun(deployment *extensions.Deployment, c clientset.Interface, toRevision int64) (string, error) { externalDeployment := &externalextensions.Deployment{} if err := api.Scheme.Convert(deployment, externalDeployment, nil); err != nil { return "", fmt.Errorf("failed to convert deployment, %v", err) } versionedClient := versionedClientsetForDeployment(c) _, allOldRSs, newRS, err := deploymentutil.GetAllReplicaSets(externalDeployment, versionedClient) if err != nil { return "", fmt.Errorf("failed to retrieve replica sets from deployment %s: %v", deployment.Name, err) } allRSs := allOldRSs if newRS != nil { allRSs = append(allRSs, newRS) } revisionToSpec := make(map[int64]*v1.PodTemplateSpec) for _, rs := range allRSs { v, err := deploymentutil.Revision(rs) if err != nil { continue } revisionToSpec[v] = &rs.Spec.Template } if len(revisionToSpec) < 2 { return "", fmt.Errorf("no rollout history found for deployment %q", deployment.Name) } if toRevision > 0 { template, ok := revisionToSpec[toRevision] if !ok { return "", fmt.Errorf("unable to find specified revision") } buf := bytes.NewBuffer([]byte{}) internalTemplate := &api.PodTemplateSpec{} if err := v1.Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(template, internalTemplate, nil); err != nil { return "", fmt.Errorf("failed to convert podtemplate, %v", err) } w := printersinternal.NewPrefixWriter(buf) printersinternal.DescribePodTemplate(internalTemplate, w) return buf.String(), nil } // Sort the revisionToSpec map by revision revisions := make([]int64, 0, len(revisionToSpec)) for r := range revisionToSpec { revisions = append(revisions, r) } sliceutil.SortInts64(revisions) template, _ := revisionToSpec[revisions[len(revisions)-2]] buf := bytes.NewBuffer([]byte{}) buf.WriteString("\n") internalTemplate := &api.PodTemplateSpec{} if err := v1.Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(template, internalTemplate, nil); err != nil { return "", fmt.Errorf("failed to convert podtemplate, %v", err) } w := printersinternal.NewPrefixWriter(buf) printersinternal.DescribePodTemplate(internalTemplate, w) return buf.String(), nil }
pkg/kubectl/rollback.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.2916630208492279, 0.020020712167024612, 0.0001671842037467286, 0.0003942938055843115, 0.06409919261932373 ]
{ "id": 0, "code_window": [ "\n", "// MaxUnavailable returns the maximum unavailable pods a rolling deployment can take.\n", "func MaxUnavailable(deployment extensions.Deployment) int32 {\n", "\tif !IsRollingUpdate(&deployment) || *(deployment.Spec.Replicas) == 0 {\n", "\t\treturn int32(0)\n", "\t}\n", "\t// Error caught by validation\n", "\t_, maxUnavailable, _ := ResolveFenceposts(deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, *(deployment.Spec.Replicas))\n", "\treturn maxUnavailable\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tif !IsRollingUpdate(&deployment) {\n" ], "file_path": "pkg/controller/deployment/util/deployment_util.go", "type": "replace", "edit_start_line_idx": 412 }
The MIT License (MIT) Copyright (c) 2016 Yasuhiro Matsumoto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/LICENSE
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0001881675561890006, 0.00018006771279033273, 0.00017400278011336923, 0.00017803280206862837, 0.000005959075224382104 ]
{ "id": 1, "code_window": [ "\t_, maxUnavailable, _ := ResolveFenceposts(deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, *(deployment.Spec.Replicas))\n", "\treturn maxUnavailable\n", "}\n", "\n", "// MaxUnavailableInternal returns the maximum unavailable pods a rolling deployment can take.\n", "// TODO: remove the duplicate\n", "func MaxUnavailableInternal(deployment internalextensions.Deployment) int32 {\n", "\tif !(deployment.Spec.Strategy.Type == internalextensions.RollingUpdateDeploymentStrategyType) || deployment.Spec.Replicas == 0 {\n", "\t\treturn int32(0)\n", "\t}\n", "\t// Error caught by validation\n", "\t_, maxUnavailable, _ := ResolveFenceposts(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, &deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, deployment.Spec.Replicas)\n", "\treturn maxUnavailable\n", "}\n", "\n", "// MinAvailable returns the minimum available pods of a given deployment\n", "func MinAvailable(deployment *extensions.Deployment) int32 {\n", "\tif !IsRollingUpdate(deployment) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/controller/deployment/util/deployment_util.go", "type": "replace", "edit_start_line_idx": 420 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.11441151052713394, 0.006042172200977802, 0.00016401021275669336, 0.00023923754633869976, 0.021287813782691956 ]
{ "id": 1, "code_window": [ "\t_, maxUnavailable, _ := ResolveFenceposts(deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, *(deployment.Spec.Replicas))\n", "\treturn maxUnavailable\n", "}\n", "\n", "// MaxUnavailableInternal returns the maximum unavailable pods a rolling deployment can take.\n", "// TODO: remove the duplicate\n", "func MaxUnavailableInternal(deployment internalextensions.Deployment) int32 {\n", "\tif !(deployment.Spec.Strategy.Type == internalextensions.RollingUpdateDeploymentStrategyType) || deployment.Spec.Replicas == 0 {\n", "\t\treturn int32(0)\n", "\t}\n", "\t// Error caught by validation\n", "\t_, maxUnavailable, _ := ResolveFenceposts(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, &deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, deployment.Spec.Replicas)\n", "\treturn maxUnavailable\n", "}\n", "\n", "// MinAvailable returns the minimum available pods of a given deployment\n", "func MinAvailable(deployment *extensions.Deployment) int32 {\n", "\tif !IsRollingUpdate(deployment) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/controller/deployment/util/deployment_util.go", "type": "replace", "edit_start_line_idx": 420 }
/* Copyright 2016 The Kubernetes Authors. 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 imagepolicy contains an admission controller that configures a webhook to which policy // decisions are delegated. package imagepolicy import ( "encoding/json" "errors" "fmt" "io" "strings" "time" "github.com/golang/glog" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime/schema" kubeschema "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/util/cache" "k8s.io/apiserver/pkg/util/webhook" "k8s.io/client-go/rest" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/imagepolicy/v1alpha1" kubeapiserveradmission "k8s.io/kubernetes/pkg/kubeapiserver/admission" // install the clientgo image policy API for use with api registry _ "k8s.io/kubernetes/pkg/apis/imagepolicy/install" ) var ( groupVersions = []schema.GroupVersion{v1alpha1.SchemeGroupVersion} ) func init() { kubeapiserveradmission.Plugins.Register("ImagePolicyWebhook", func(config io.Reader) (admission.Interface, error) { newImagePolicyWebhook, err := NewImagePolicyWebhook(config) if err != nil { return nil, err } return newImagePolicyWebhook, nil }) } // imagePolicyWebhook is an implementation of admission.Interface. type imagePolicyWebhook struct { *admission.Handler webhook *webhook.GenericWebhook responseCache *cache.LRUExpireCache allowTTL time.Duration denyTTL time.Duration retryBackoff time.Duration defaultAllow bool } func (a *imagePolicyWebhook) statusTTL(status v1alpha1.ImageReviewStatus) time.Duration { if status.Allowed { return a.allowTTL } return a.denyTTL } // Filter out annotations that don't match *.image-policy.k8s.io/* func (a *imagePolicyWebhook) filterAnnotations(allAnnotations map[string]string) map[string]string { annotations := make(map[string]string) for k, v := range allAnnotations { if strings.Contains(k, ".image-policy.k8s.io/") { annotations[k] = v } } return annotations } // Function to call on webhook failure; behavior determined by defaultAllow flag func (a *imagePolicyWebhook) webhookError(attributes admission.Attributes, err error) error { if err != nil { glog.V(2).Infof("error contacting webhook backend: %s", err) if a.defaultAllow { glog.V(2).Infof("resource allowed in spite of webhook backend failure") return nil } glog.V(2).Infof("resource not allowed due to webhook backend failure ") return admission.NewForbidden(attributes, err) } return nil } func (a *imagePolicyWebhook) Admit(attributes admission.Attributes) (err error) { // Ignore all calls to subresources or resources other than pods. allowedResources := map[kubeschema.GroupResource]bool{ api.Resource("pods"): true, } if len(attributes.GetSubresource()) != 0 || !allowedResources[attributes.GetResource().GroupResource()] { return nil } pod, ok := attributes.GetObject().(*api.Pod) if !ok { return apierrors.NewBadRequest("Resource was marked with kind Pod but was unable to be converted") } // Build list of ImageReviewContainerSpec var imageReviewContainerSpecs []v1alpha1.ImageReviewContainerSpec containers := make([]api.Container, 0, len(pod.Spec.Containers)+len(pod.Spec.InitContainers)) containers = append(containers, pod.Spec.Containers...) containers = append(containers, pod.Spec.InitContainers...) for _, c := range containers { imageReviewContainerSpecs = append(imageReviewContainerSpecs, v1alpha1.ImageReviewContainerSpec{ Image: c.Image, }) } imageReview := v1alpha1.ImageReview{ Spec: v1alpha1.ImageReviewSpec{ Containers: imageReviewContainerSpecs, Annotations: a.filterAnnotations(pod.Annotations), Namespace: attributes.GetNamespace(), }, } if err := a.admitPod(attributes, &imageReview); err != nil { return admission.NewForbidden(attributes, err) } return nil } func (a *imagePolicyWebhook) admitPod(attributes admission.Attributes, review *v1alpha1.ImageReview) error { cacheKey, err := json.Marshal(review.Spec) if err != nil { return err } if entry, ok := a.responseCache.Get(string(cacheKey)); ok { review.Status = entry.(v1alpha1.ImageReviewStatus) } else { result := a.webhook.WithExponentialBackoff(func() rest.Result { return a.webhook.RestClient.Post().Body(review).Do() }) if err := result.Error(); err != nil { return a.webhookError(attributes, err) } var statusCode int if result.StatusCode(&statusCode); statusCode < 200 || statusCode >= 300 { return a.webhookError(attributes, fmt.Errorf("Error contacting webhook: %d", statusCode)) } if err := result.Into(review); err != nil { return a.webhookError(attributes, err) } a.responseCache.Add(string(cacheKey), review.Status, a.statusTTL(review.Status)) } if !review.Status.Allowed { if len(review.Status.Reason) > 0 { return fmt.Errorf("image policy webook backend denied one or more images: %s", review.Status.Reason) } return errors.New("one or more images rejected by webhook backend") } return nil } // NewImagePolicyWebhook a new imagePolicyWebhook from the provided config file. // The config file is specified by --admission-controller-config-file and has the // following format for a webhook: // // { // "imagePolicy": { // "kubeConfigFile": "path/to/kubeconfig/for/backend", // "allowTTL": 30, # time in s to cache approval // "denyTTL": 30, # time in s to cache denial // "retryBackoff": 500, # time in ms to wait between retries // "defaultAllow": true # determines behavior if the webhook backend fails // } // } // // The config file may be json or yaml. // // The kubeconfig property refers to another file in the kubeconfig format which // specifies how to connect to the webhook backend. // // The kubeconfig's cluster field is used to refer to the remote service, user refers to the returned authorizer. // // # clusters refers to the remote service. // clusters: // - name: name-of-remote-imagepolicy-service // cluster: // certificate-authority: /path/to/ca.pem # CA for verifying the remote service. // server: https://images.example.com/policy # URL of remote service to query. Must use 'https'. // // # users refers to the API server's webhook configuration. // users: // - name: name-of-api-server // user: // client-certificate: /path/to/cert.pem # cert for the webhook plugin to use // client-key: /path/to/key.pem # key matching the cert // // For additional HTTP configuration, refer to the kubeconfig documentation // http://kubernetes.io/v1.1/docs/user-guide/kubeconfig-file.html. func NewImagePolicyWebhook(configFile io.Reader) (admission.Interface, error) { // TODO: move this to a versioned configuration file format var config AdmissionConfig d := yaml.NewYAMLOrJSONDecoder(configFile, 4096) err := d.Decode(&config) if err != nil { return nil, err } whConfig := config.ImagePolicyWebhook if err := normalizeWebhookConfig(&whConfig); err != nil { return nil, err } gw, err := webhook.NewGenericWebhook(api.Registry, api.Codecs, whConfig.KubeConfigFile, groupVersions, whConfig.RetryBackoff) if err != nil { return nil, err } return &imagePolicyWebhook{ Handler: admission.NewHandler(admission.Create, admission.Update), webhook: gw, responseCache: cache.NewLRUExpireCache(1024), allowTTL: whConfig.AllowTTL, denyTTL: whConfig.DenyTTL, defaultAllow: whConfig.DefaultAllow, }, nil }
plugin/pkg/admission/imagepolicy/admission.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0011614436516538262, 0.00022030744003131986, 0.00016344443429261446, 0.0001672329963184893, 0.00019708345644176006 ]
{ "id": 1, "code_window": [ "\t_, maxUnavailable, _ := ResolveFenceposts(deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, *(deployment.Spec.Replicas))\n", "\treturn maxUnavailable\n", "}\n", "\n", "// MaxUnavailableInternal returns the maximum unavailable pods a rolling deployment can take.\n", "// TODO: remove the duplicate\n", "func MaxUnavailableInternal(deployment internalextensions.Deployment) int32 {\n", "\tif !(deployment.Spec.Strategy.Type == internalextensions.RollingUpdateDeploymentStrategyType) || deployment.Spec.Replicas == 0 {\n", "\t\treturn int32(0)\n", "\t}\n", "\t// Error caught by validation\n", "\t_, maxUnavailable, _ := ResolveFenceposts(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, &deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, deployment.Spec.Replicas)\n", "\treturn maxUnavailable\n", "}\n", "\n", "// MinAvailable returns the minimum available pods of a given deployment\n", "func MinAvailable(deployment *extensions.Deployment) int32 {\n", "\tif !IsRollingUpdate(deployment) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/controller/deployment/util/deployment_util.go", "type": "replace", "edit_start_line_idx": 420 }
package(default_visibility = ["//visibility:public"]) licenses(["notice"]) load( "@io_bazel_rules_go//go:def.bzl", "go_library", ) go_library( name = "go_default_library", srcs = ["assertion.go"], tags = ["automanaged"], deps = ["//vendor/github.com/onsi/gomega/types:go_default_library"], ) filegroup( name = "package-srcs", srcs = glob(["**"]), tags = ["automanaged"], visibility = ["//visibility:private"], ) filegroup( name = "all-srcs", srcs = [":package-srcs"], tags = ["automanaged"], )
vendor/github.com/onsi/gomega/internal/assertion/BUILD
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0001679312699707225, 0.00016618722293060273, 0.00016447236703243107, 0.00016615803178865463, 0.000001412242113474349 ]
{ "id": 1, "code_window": [ "\t_, maxUnavailable, _ := ResolveFenceposts(deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, *(deployment.Spec.Replicas))\n", "\treturn maxUnavailable\n", "}\n", "\n", "// MaxUnavailableInternal returns the maximum unavailable pods a rolling deployment can take.\n", "// TODO: remove the duplicate\n", "func MaxUnavailableInternal(deployment internalextensions.Deployment) int32 {\n", "\tif !(deployment.Spec.Strategy.Type == internalextensions.RollingUpdateDeploymentStrategyType) || deployment.Spec.Replicas == 0 {\n", "\t\treturn int32(0)\n", "\t}\n", "\t// Error caught by validation\n", "\t_, maxUnavailable, _ := ResolveFenceposts(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, &deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, deployment.Spec.Replicas)\n", "\treturn maxUnavailable\n", "}\n", "\n", "// MinAvailable returns the minimum available pods of a given deployment\n", "func MinAvailable(deployment *extensions.Deployment) int32 {\n", "\tif !IsRollingUpdate(deployment) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/controller/deployment/util/deployment_util.go", "type": "replace", "edit_start_line_idx": 420 }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package unix func itoa(val int) string { // do it here rather than with fmt to avoid dependency if val < 0 { return "-" + uitoa(uint(-val)) } return uitoa(uint(val)) } func uitoa(val uint) string { var buf [32]byte // big enough for int64 i := len(buf) - 1 for val >= 10 { buf[i] = byte(val%10 + '0') i-- val /= 10 } buf[i] = byte(val + '0') return string(buf[i:]) }
vendor/golang.org/x/sys/unix/str.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00019376756972633302, 0.00017612677766010165, 0.0001662707218201831, 0.0001683420268818736, 0.000012502556273830123 ]
{ "id": 2, "code_window": [ "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d out of %d new replicas have been updated...\\n\", deployment.Status.UpdatedReplicas, deployment.Spec.Replicas), false, nil\n", "\t\t}\n", "\t\tif deployment.Status.Replicas > deployment.Status.UpdatedReplicas {\n", "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d old replicas are pending termination...\\n\", deployment.Status.Replicas-deployment.Status.UpdatedReplicas), false, nil\n", "\t\t}\n", "\t\tminRequired := deployment.Spec.Replicas - util.MaxUnavailableInternal(*deployment)\n", "\t\tif deployment.Status.AvailableReplicas < minRequired {\n", "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d of %d updated replicas are available (minimum required: %d)...\\n\", deployment.Status.AvailableReplicas, deployment.Status.UpdatedReplicas, minRequired), false, nil\n", "\t\t}\n", "\t\treturn fmt.Sprintf(\"deployment %q successfully rolled out\\n\", name), true, nil\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tif deployment.Status.AvailableReplicas < deployment.Status.UpdatedReplicas {\n", "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d of %d updated replicas are available...\\n\", deployment.Status.AvailableReplicas, deployment.Status.UpdatedReplicas), false, nil\n" ], "file_path": "pkg/kubectl/rollout_status.go", "type": "replace", "edit_start_line_idx": 80 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0028353931847959757, 0.000315033714286983, 0.000162201322382316, 0.00017006606503855437, 0.0004796290013473481 ]
{ "id": 2, "code_window": [ "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d out of %d new replicas have been updated...\\n\", deployment.Status.UpdatedReplicas, deployment.Spec.Replicas), false, nil\n", "\t\t}\n", "\t\tif deployment.Status.Replicas > deployment.Status.UpdatedReplicas {\n", "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d old replicas are pending termination...\\n\", deployment.Status.Replicas-deployment.Status.UpdatedReplicas), false, nil\n", "\t\t}\n", "\t\tminRequired := deployment.Spec.Replicas - util.MaxUnavailableInternal(*deployment)\n", "\t\tif deployment.Status.AvailableReplicas < minRequired {\n", "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d of %d updated replicas are available (minimum required: %d)...\\n\", deployment.Status.AvailableReplicas, deployment.Status.UpdatedReplicas, minRequired), false, nil\n", "\t\t}\n", "\t\treturn fmt.Sprintf(\"deployment %q successfully rolled out\\n\", name), true, nil\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tif deployment.Status.AvailableReplicas < deployment.Status.UpdatedReplicas {\n", "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d of %d updated replicas are available...\\n\", deployment.Status.AvailableReplicas, deployment.Status.UpdatedReplicas), false, nil\n" ], "file_path": "pkg/kubectl/rollout_status.go", "type": "replace", "edit_start_line_idx": 80 }
package(default_visibility = ["//visibility:public"]) licenses(["notice"]) load( "@io_bazel_rules_go//go:def.bzl", "go_library", "go_test", ) go_library( name = "go_default_library", srcs = ["controller.go"], tags = ["automanaged"], deps = [ "//federation/apis/federation/v1beta1:go_default_library", "//federation/client/clientset_generated/federation_clientset:go_default_library", "//federation/pkg/federatedtypes:go_default_library", "//federation/pkg/federation-controller/util:go_default_library", "//federation/pkg/federation-controller/util/deletionhelper:go_default_library", "//federation/pkg/federation-controller/util/eventsink:go_default_library", "//pkg/api:go_default_library", "//pkg/client/clientset_generated/clientset:go_default_library", "//pkg/controller:go_default_library", "//vendor/github.com/golang/glog:go_default_library", "//vendor/k8s.io/apimachinery/pkg/api/errors:go_default_library", "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", "//vendor/k8s.io/apimachinery/pkg/types:go_default_library", "//vendor/k8s.io/apimachinery/pkg/watch:go_default_library", "//vendor/k8s.io/client-go/pkg/api/v1:go_default_library", "//vendor/k8s.io/client-go/rest:go_default_library", "//vendor/k8s.io/client-go/tools/cache:go_default_library", "//vendor/k8s.io/client-go/tools/record:go_default_library", "//vendor/k8s.io/client-go/util/flowcontrol:go_default_library", ], ) filegroup( name = "package-srcs", srcs = glob(["**"]), tags = ["automanaged"], visibility = ["//visibility:private"], ) filegroup( name = "all-srcs", srcs = [":package-srcs"], tags = ["automanaged"], ) go_test( name = "go_default_test", srcs = ["secret_controller_test.go"], library = ":go_default_library", tags = ["automanaged"], deps = [ "//federation/apis/federation/v1beta1:go_default_library", "//federation/client/clientset_generated/federation_clientset/fake:go_default_library", "//federation/pkg/federatedtypes:go_default_library", "//federation/pkg/federation-controller/util:go_default_library", "//federation/pkg/federation-controller/util/deletionhelper:go_default_library", "//federation/pkg/federation-controller/util/test:go_default_library", "//pkg/api/v1:go_default_library", "//pkg/client/clientset_generated/clientset:go_default_library", "//pkg/client/clientset_generated/clientset/fake:go_default_library", "//vendor/github.com/golang/glog:go_default_library", "//vendor/github.com/stretchr/testify/assert:go_default_library", "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", "//vendor/k8s.io/apimachinery/pkg/types:go_default_library", "//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library", ], )
federation/pkg/federation-controller/sync/BUILD
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017380826466251165, 0.00017104441940318793, 0.00016655919898767024, 0.00017156641115434468, 0.0000022261167487158673 ]
{ "id": 2, "code_window": [ "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d out of %d new replicas have been updated...\\n\", deployment.Status.UpdatedReplicas, deployment.Spec.Replicas), false, nil\n", "\t\t}\n", "\t\tif deployment.Status.Replicas > deployment.Status.UpdatedReplicas {\n", "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d old replicas are pending termination...\\n\", deployment.Status.Replicas-deployment.Status.UpdatedReplicas), false, nil\n", "\t\t}\n", "\t\tminRequired := deployment.Spec.Replicas - util.MaxUnavailableInternal(*deployment)\n", "\t\tif deployment.Status.AvailableReplicas < minRequired {\n", "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d of %d updated replicas are available (minimum required: %d)...\\n\", deployment.Status.AvailableReplicas, deployment.Status.UpdatedReplicas, minRequired), false, nil\n", "\t\t}\n", "\t\treturn fmt.Sprintf(\"deployment %q successfully rolled out\\n\", name), true, nil\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tif deployment.Status.AvailableReplicas < deployment.Status.UpdatedReplicas {\n", "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d of %d updated replicas are available...\\n\", deployment.Status.AvailableReplicas, deployment.Status.UpdatedReplicas), false, nil\n" ], "file_path": "pkg/kubectl/rollout_status.go", "type": "replace", "edit_start_line_idx": 80 }
# Copyright 2013 The Go Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. CLEANFILES+=maketables maketables: maketables.go go build $^ tables: maketables ./maketables > tables.go gofmt -w -s tables.go # Build (but do not run) maketables during testing, # just to make sure it still compiles. testshort: maketables
vendor/golang.org/x/text/language/Makefile
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017464904522057623, 0.00017302337801083922, 0.00017139772535301745, 0.00017302337801083922, 0.0000016256599337793887 ]
{ "id": 2, "code_window": [ "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d out of %d new replicas have been updated...\\n\", deployment.Status.UpdatedReplicas, deployment.Spec.Replicas), false, nil\n", "\t\t}\n", "\t\tif deployment.Status.Replicas > deployment.Status.UpdatedReplicas {\n", "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d old replicas are pending termination...\\n\", deployment.Status.Replicas-deployment.Status.UpdatedReplicas), false, nil\n", "\t\t}\n", "\t\tminRequired := deployment.Spec.Replicas - util.MaxUnavailableInternal(*deployment)\n", "\t\tif deployment.Status.AvailableReplicas < minRequired {\n", "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d of %d updated replicas are available (minimum required: %d)...\\n\", deployment.Status.AvailableReplicas, deployment.Status.UpdatedReplicas, minRequired), false, nil\n", "\t\t}\n", "\t\treturn fmt.Sprintf(\"deployment %q successfully rolled out\\n\", name), true, nil\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tif deployment.Status.AvailableReplicas < deployment.Status.UpdatedReplicas {\n", "\t\t\treturn fmt.Sprintf(\"Waiting for rollout to finish: %d of %d updated replicas are available...\\n\", deployment.Status.AvailableReplicas, deployment.Status.UpdatedReplicas), false, nil\n" ], "file_path": "pkg/kubectl/rollout_status.go", "type": "replace", "edit_start_line_idx": 80 }
language: go go: - 1.5.4 - 1.6.3 - 1.7 go_import_path: google.golang.org/grpc before_install: - if [[ $TRAVIS_GO_VERSION != 1.5* ]]; then go get github.com/golang/lint/golint; fi - go get -u golang.org/x/tools/cmd/goimports github.com/axw/gocov/gocov github.com/mattn/goveralls golang.org/x/tools/cmd/cover script: - '! gofmt -s -d -l . 2>&1 | read' - '! goimports -l . | read' - 'if [[ $TRAVIS_GO_VERSION != 1.5* ]]; then ! golint ./... | grep -vE "(_string|\.pb)\.go:"; fi' - '! go tool vet -all . 2>&1 | grep -vE "constant [0-9]+ not a string in call to Errorf" | grep -vF .pb.go:' # https://github.com/golang/protobuf/issues/214 - make test testrace
vendor/google.golang.org/grpc/.travis.yml
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017560587730258703, 0.00017270594253204763, 0.00016980600776150823, 0.00017270594253204763, 0.000002899934770539403 ]
{ "id": 3, "code_window": [ "\t\"testing\"\n", "\n", "\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n", "\tintstrutil \"k8s.io/apimachinery/pkg/util/intstr\"\n", "\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n", "\t\"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake\"\n", ")\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 22 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.2713809311389923, 0.00896336231380701, 0.00016512574802618474, 0.0001735113764880225, 0.0479109026491642 ]
{ "id": 3, "code_window": [ "\t\"testing\"\n", "\n", "\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n", "\tintstrutil \"k8s.io/apimachinery/pkg/util/intstr\"\n", "\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n", "\t\"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake\"\n", ")\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 22 }
package pflag import "strconv" // -- uint64 Value type uint64Value uint64 func newUint64Value(val uint64, p *uint64) *uint64Value { *p = val return (*uint64Value)(p) } func (i *uint64Value) Set(s string) error { v, err := strconv.ParseUint(s, 0, 64) *i = uint64Value(v) return err } func (i *uint64Value) Type() string { return "uint64" } func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) } func uint64Conv(sval string) (interface{}, error) { v, err := strconv.ParseUint(sval, 0, 64) if err != nil { return 0, err } return uint64(v), nil } // GetUint64 return the uint64 value of a flag with the given name func (f *FlagSet) GetUint64(name string) (uint64, error) { val, err := f.getFlagType(name, "uint64", uint64Conv) if err != nil { return 0, err } return val.(uint64), nil } // Uint64Var defines a uint64 flag with specified name, default value, and usage string. // The argument p points to a uint64 variable in which to store the value of the flag. func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) { f.VarP(newUint64Value(value, p), name, "", usage) } // Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { f.VarP(newUint64Value(value, p), name, shorthand, usage) } // Uint64Var defines a uint64 flag with specified name, default value, and usage string. // The argument p points to a uint64 variable in which to store the value of the flag. func Uint64Var(p *uint64, name string, value uint64, usage string) { CommandLine.VarP(newUint64Value(value, p), name, "", usage) } // Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage) } // Uint64 defines a uint64 flag with specified name, default value, and usage string. // The return value is the address of a uint64 variable that stores the value of the flag. func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 { p := new(uint64) f.Uint64VarP(p, name, "", value, usage) return p } // Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 { p := new(uint64) f.Uint64VarP(p, name, shorthand, value, usage) return p } // Uint64 defines a uint64 flag with specified name, default value, and usage string. // The return value is the address of a uint64 variable that stores the value of the flag. func Uint64(name string, value uint64, usage string) *uint64 { return CommandLine.Uint64P(name, "", value, usage) } // Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. func Uint64P(name, shorthand string, value uint64, usage string) *uint64 { return CommandLine.Uint64P(name, shorthand, value, usage) }
vendor/github.com/spf13/pflag/uint64.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0041886926628649235, 0.0007223426946438849, 0.00016489994595758617, 0.0001938954519573599, 0.0012402806896716356 ]
{ "id": 3, "code_window": [ "\t\"testing\"\n", "\n", "\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n", "\tintstrutil \"k8s.io/apimachinery/pkg/util/intstr\"\n", "\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n", "\t\"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake\"\n", ")\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 22 }
/* Copyright 2016 The Kubernetes Authors. 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 retry import ( "fmt" "testing" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/wait" ) func TestRetryOnConflict(t *testing.T) { opts := wait.Backoff{Factor: 1.0, Steps: 3} conflictErr := errors.NewConflict(schema.GroupResource{Resource: "test"}, "other", nil) // never returns err := RetryOnConflict(opts, func() error { return conflictErr }) if err != conflictErr { t.Errorf("unexpected error: %v", err) } // returns immediately i := 0 err = RetryOnConflict(opts, func() error { i++ return nil }) if err != nil || i != 1 { t.Errorf("unexpected error: %v", err) } // returns immediately on error testErr := fmt.Errorf("some other error") err = RetryOnConflict(opts, func() error { return testErr }) if err != testErr { t.Errorf("unexpected error: %v", err) } // keeps retrying i = 0 err = RetryOnConflict(opts, func() error { if i < 2 { i++ return errors.NewConflict(schema.GroupResource{Resource: "test"}, "other", nil) } return nil }) if err != nil || i != 2 { t.Errorf("unexpected error: %v", err) } }
pkg/client/retry/util_test.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.004404434934258461, 0.0007024186197668314, 0.00016779618454165757, 0.00017517845844849944, 0.0013992342865094543 ]
{ "id": 3, "code_window": [ "\t\"testing\"\n", "\n", "\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n", "\tintstrutil \"k8s.io/apimachinery/pkg/util/intstr\"\n", "\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n", "\t\"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake\"\n", ")\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 22 }
package gophercloud import ( "errors" "net/url" "path/filepath" "strings" "time" ) // WaitFor polls a predicate function, once per second, up to a timeout limit. // It usually does this to wait for a resource to transition to a certain state. // Resource packages will wrap this in a more convenient function that's // specific to a certain resource, but it can also be useful on its own. func WaitFor(timeout int, predicate func() (bool, error)) error { start := time.Now().Second() for { // Force a 1s sleep time.Sleep(1 * time.Second) // If a timeout is set, and that's been exceeded, shut it down if timeout >= 0 && time.Now().Second()-start >= timeout { return errors.New("A timeout occurred") } // Execute the function satisfied, err := predicate() if err != nil { return err } if satisfied { return nil } } } // NormalizeURL is an internal function to be used by provider clients. // // It ensures that each endpoint URL has a closing `/`, as expected by // ServiceClient's methods. func NormalizeURL(url string) string { if !strings.HasSuffix(url, "/") { return url + "/" } return url } // NormalizePathURL is used to convert rawPath to a fqdn, using basePath as // a reference in the filesystem, if necessary. basePath is assumed to contain // either '.' when first used, or the file:// type fqdn of the parent resource. // e.g. myFavScript.yaml => file://opt/lib/myFavScript.yaml func NormalizePathURL(basePath, rawPath string) (string, error) { u, err := url.Parse(rawPath) if err != nil { return "", err } // if a scheme is defined, it must be a fqdn already if u.Scheme != "" { return u.String(), nil } // if basePath is a url, then child resources are assumed to be relative to it bu, err := url.Parse(basePath) if err != nil { return "", err } var basePathSys, absPathSys string if bu.Scheme != "" { basePathSys = filepath.FromSlash(bu.Path) absPathSys = filepath.Join(basePathSys, rawPath) bu.Path = filepath.ToSlash(absPathSys) return bu.String(), nil } absPathSys = filepath.Join(basePath, rawPath) u.Path = filepath.ToSlash(absPathSys) if err != nil { return "", err } u.Scheme = "file" return u.String(), nil }
vendor/github.com/rackspace/gophercloud/util.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00029753008857369423, 0.00019018485909327865, 0.00016440573381260037, 0.00017476300126872957, 0.00004085849650437012 ]
{ "id": 4, "code_window": [ "\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n", "\t\"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake\"\n", ")\n", "\n", "func intOrStringP(i int) *intstrutil.IntOrString {\n", "\tintstr := intstrutil.FromInt(i)\n", "\treturn &intstr\n", "}\n", "\n", "func TestDeploymentStatusViewerStatus(t *testing.T) {\n", "\ttests := []struct {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 27 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.999037504196167, 0.3295153081417084, 0.00016523267549928278, 0.0001761737366905436, 0.46073105931282043 ]
{ "id": 4, "code_window": [ "\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n", "\t\"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake\"\n", ")\n", "\n", "func intOrStringP(i int) *intstrutil.IntOrString {\n", "\tintstr := intstrutil.FromInt(i)\n", "\treturn &intstr\n", "}\n", "\n", "func TestDeploymentStatusViewerStatus(t *testing.T) {\n", "\ttests := []struct {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 27 }
/* Copyright 2017 The Kubernetes Authors. 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. */ // This file was automatically generated by informer-gen package autoscaling import ( v1 "k8s.io/client-go/informers/autoscaling/v1" v2alpha1 "k8s.io/client-go/informers/autoscaling/v2alpha1" internalinterfaces "k8s.io/client-go/informers/internalinterfaces" ) // Interface provides access to each of this group's versions. type Interface interface { // V1 provides access to shared informers for resources in V1. V1() v1.Interface // V2alpha1 provides access to shared informers for resources in V2alpha1. V2alpha1() v2alpha1.Interface } type group struct { internalinterfaces.SharedInformerFactory } // New returns a new Interface. func New(f internalinterfaces.SharedInformerFactory) Interface { return &group{f} } // V1 returns a new v1.Interface. func (g *group) V1() v1.Interface { return v1.New(g.SharedInformerFactory) } // V2alpha1 returns a new v2alpha1.Interface. func (g *group) V2alpha1() v2alpha1.Interface { return v2alpha1.New(g.SharedInformerFactory) }
staging/src/k8s.io/client-go/informers/autoscaling/interface.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0003433204547036439, 0.0002014329074881971, 0.00016651632904540747, 0.0001750566007103771, 0.00006361304986057803 ]
{ "id": 4, "code_window": [ "\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n", "\t\"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake\"\n", ")\n", "\n", "func intOrStringP(i int) *intstrutil.IntOrString {\n", "\tintstr := intstrutil.FromInt(i)\n", "\treturn &intstr\n", "}\n", "\n", "func TestDeploymentStatusViewerStatus(t *testing.T) {\n", "\ttests := []struct {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 27 }
package autorest import ( "bytes" "encoding/json" "encoding/xml" "fmt" "io" "net/url" "reflect" "sort" "strings" ) // EncodedAs is a series of constants specifying various data encodings type EncodedAs string const ( // EncodedAsJSON states that data is encoded as JSON EncodedAsJSON EncodedAs = "JSON" // EncodedAsXML states that data is encoded as Xml EncodedAsXML EncodedAs = "XML" ) // Decoder defines the decoding method json.Decoder and xml.Decoder share type Decoder interface { Decode(v interface{}) error } // NewDecoder creates a new decoder appropriate to the passed encoding. // encodedAs specifies the type of encoding and r supplies the io.Reader containing the // encoded data. func NewDecoder(encodedAs EncodedAs, r io.Reader) Decoder { if encodedAs == EncodedAsJSON { return json.NewDecoder(r) } else if encodedAs == EncodedAsXML { return xml.NewDecoder(r) } return nil } // CopyAndDecode decodes the data from the passed io.Reader while making a copy. Having a copy // is especially useful if there is a chance the data will fail to decode. // encodedAs specifies the expected encoding, r provides the io.Reader to the data, and v // is the decoding destination. func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffer, error) { b := bytes.Buffer{} return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v) } // TeeReadCloser returns a ReadCloser that writes to w what it reads from rc. // It utilizes io.TeeReader to copy the data read and has the same behavior when reading. // Further, when it is closed, it ensures that rc is closed as well. func TeeReadCloser(rc io.ReadCloser, w io.Writer) io.ReadCloser { return &teeReadCloser{rc, io.TeeReader(rc, w)} } type teeReadCloser struct { rc io.ReadCloser r io.Reader } func (t *teeReadCloser) Read(p []byte) (int, error) { return t.r.Read(p) } func (t *teeReadCloser) Close() error { return t.rc.Close() } func containsInt(ints []int, n int) bool { for _, i := range ints { if i == n { return true } } return false } func escapeValueStrings(m map[string]string) map[string]string { for key, value := range m { m[key] = url.QueryEscape(value) } return m } func ensureValueStrings(mapOfInterface map[string]interface{}) map[string]string { mapOfStrings := make(map[string]string) for key, value := range mapOfInterface { mapOfStrings[key] = ensureValueString(value) } return mapOfStrings } func ensureValueString(value interface{}) string { if value == nil { return "" } switch v := value.(type) { case string: return v case []byte: return string(v) default: return fmt.Sprintf("%v", v) } } // MapToValues method converts map[string]interface{} to url.Values. func MapToValues(m map[string]interface{}) url.Values { v := url.Values{} for key, value := range m { x := reflect.ValueOf(value) if x.Kind() == reflect.Array || x.Kind() == reflect.Slice { for i := 0; i < x.Len(); i++ { v.Add(key, ensureValueString(x.Index(i))) } } else { v.Add(key, ensureValueString(value)) } } return v } // String method converts interface v to string. If interface is a list, it // joins list elements using separator. func String(v interface{}, sep ...string) string { if len(sep) > 0 { return ensureValueString(strings.Join(v.([]string), sep[0])) } return ensureValueString(v) } // Encode method encodes url path and query parameters. func Encode(location string, v interface{}, sep ...string) string { s := String(v, sep...) switch strings.ToLower(location) { case "path": return pathEscape(s) case "query": return queryEscape(s) default: return s } } func pathEscape(s string) string { return strings.Replace(url.QueryEscape(s), "+", "%20", -1) } func queryEscape(s string) string { return url.QueryEscape(s) } // This method is same as Encode() method of "net/url" go package, // except it does not encode the query parameters because they // already come encoded. It formats values map in query format (bar=foo&a=b). func createQuery(v url.Values) string { var buf bytes.Buffer keys := make([]string, 0, len(v)) for k := range v { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { vs := v[k] prefix := url.QueryEscape(k) + "=" for _, v := range vs { if buf.Len() > 0 { buf.WriteByte('&') } buf.WriteString(prefix) buf.WriteString(v) } } return buf.String() }
vendor/github.com/Azure/go-autorest/autorest/utility.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0018184841610491276, 0.00028720416594296694, 0.00016261928249150515, 0.00016926435637287796, 0.0003789804468397051 ]
{ "id": 4, "code_window": [ "\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n", "\t\"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake\"\n", ")\n", "\n", "func intOrStringP(i int) *intstrutil.IntOrString {\n", "\tintstr := intstrutil.FromInt(i)\n", "\treturn &intstr\n", "}\n", "\n", "func TestDeploymentStatusViewerStatus(t *testing.T) {\n", "\ttests := []struct {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 27 }
/* Copyright 2017 The Kubernetes Authors. 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 v1beta1 type DaemonSetExpansion interface{} type IngressExpansion interface{} type ReplicaSetExpansion interface{}
federation/client/clientset_generated/federation_clientset/typed/extensions/v1beta1/generated_expansion.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0001777434372343123, 0.0001737002021400258, 0.00016601913375779986, 0.00017733799177221954, 0.000005433846581581747 ]
{ "id": 5, "code_window": [ "func TestDeploymentStatusViewerStatus(t *testing.T) {\n", "\ttests := []struct {\n", "\t\tgeneration int64\n", "\t\tspecReplicas int32\n", "\t\tmaxUnavailable *intstrutil.IntOrString\n", "\t\tstatus extensions.DeploymentStatus\n", "\t\tmsg string\n", "\t\tdone bool\n", "\t}{\n", "\t\t{\n", "\t\t\tgeneration: 0,\n", "\t\t\tspecReplicas: 1,\n", "\t\t\tstatus: extensions.DeploymentStatus{\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tgeneration int64\n", "\t\tspecReplicas int32\n", "\t\tstatus extensions.DeploymentStatus\n", "\t\tmsg string\n", "\t\tdone bool\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 34 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.9980044960975647, 0.07349064946174622, 0.00016378829604946077, 0.00048296112800017, 0.2446385622024536 ]
{ "id": 5, "code_window": [ "func TestDeploymentStatusViewerStatus(t *testing.T) {\n", "\ttests := []struct {\n", "\t\tgeneration int64\n", "\t\tspecReplicas int32\n", "\t\tmaxUnavailable *intstrutil.IntOrString\n", "\t\tstatus extensions.DeploymentStatus\n", "\t\tmsg string\n", "\t\tdone bool\n", "\t}{\n", "\t\t{\n", "\t\t\tgeneration: 0,\n", "\t\t\tspecReplicas: 1,\n", "\t\t\tstatus: extensions.DeploymentStatus{\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tgeneration int64\n", "\t\tspecReplicas int32\n", "\t\tstatus extensions.DeploymentStatus\n", "\t\tmsg string\n", "\t\tdone bool\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 34 }
package(default_visibility = ["//visibility:public"]) licenses(["notice"]) load( "@io_bazel_rules_go//go:def.bzl", "go_library", ) go_library( name = "go_default_library", srcs = [ "api.go", "service.go", "waiters.go", ], tags = ["automanaged"], deps = [ "//vendor/github.com/aws/aws-sdk-go/aws:go_default_library", "//vendor/github.com/aws/aws-sdk-go/aws/awsutil:go_default_library", "//vendor/github.com/aws/aws-sdk-go/aws/client:go_default_library", "//vendor/github.com/aws/aws-sdk-go/aws/client/metadata:go_default_library", "//vendor/github.com/aws/aws-sdk-go/aws/request:go_default_library", "//vendor/github.com/aws/aws-sdk-go/aws/signer/v4:go_default_library", "//vendor/github.com/aws/aws-sdk-go/private/protocol/query:go_default_library", "//vendor/github.com/aws/aws-sdk-go/private/waiter:go_default_library", ], ) filegroup( name = "package-srcs", srcs = glob(["**"]), tags = ["automanaged"], visibility = ["//visibility:private"], ) filegroup( name = "all-srcs", srcs = [":package-srcs"], tags = ["automanaged"], )
vendor/github.com/aws/aws-sdk-go/service/elb/BUILD
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017406034749001265, 0.00017214423860423267, 0.0001672765356488526, 0.0001729532377794385, 0.000002470799472575891 ]
{ "id": 5, "code_window": [ "func TestDeploymentStatusViewerStatus(t *testing.T) {\n", "\ttests := []struct {\n", "\t\tgeneration int64\n", "\t\tspecReplicas int32\n", "\t\tmaxUnavailable *intstrutil.IntOrString\n", "\t\tstatus extensions.DeploymentStatus\n", "\t\tmsg string\n", "\t\tdone bool\n", "\t}{\n", "\t\t{\n", "\t\t\tgeneration: 0,\n", "\t\t\tspecReplicas: 1,\n", "\t\t\tstatus: extensions.DeploymentStatus{\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tgeneration int64\n", "\t\tspecReplicas int32\n", "\t\tstatus extensions.DeploymentStatus\n", "\t\tmsg string\n", "\t\tdone bool\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 34 }
# -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" # Require a recent version of vagrant otherwise some have reported errors setting host names on boxes Vagrant.require_version ">= 1.7.4" if ARGV.first == "up" && ENV['USING_KUBE_SCRIPTS'] != 'true' raise Vagrant::Errors::VagrantError.new, <<END Calling 'vagrant up' directly is not supported. Instead, please run the following: export KUBERNETES_PROVIDER=vagrant export VAGRANT_DEFAULT_PROVIDER=providername ./cluster/kube-up.sh END end # The number of nodes to provision $num_node = (ENV['NUM_NODES'] || 1).to_i # ip configuration $master_ip = ENV['MASTER_IP'] $node_ip_base = ENV['NODE_IP_BASE'] || "" $node_ips = $num_node.times.collect { |n| $node_ip_base + "#{n+3}" } # Determine the OS platform to use $kube_os = ENV['KUBERNETES_OS'] || "fedora" # Determine whether vagrant should use nfs to sync folders $use_nfs = ENV['KUBERNETES_VAGRANT_USE_NFS'] == 'true' # Determine whether vagrant should use rsync to sync folders $use_rsync = ENV['KUBERNETES_VAGRANT_USE_RSYNC'] == 'true' # To override the vagrant provider, use (e.g.): # KUBERNETES_PROVIDER=vagrant VAGRANT_DEFAULT_PROVIDER=... .../cluster/kube-up.sh # To override the box, use (e.g.): # KUBERNETES_PROVIDER=vagrant KUBERNETES_BOX_NAME=... .../cluster/kube-up.sh # You can specify a box version: # KUBERNETES_PROVIDER=vagrant KUBERNETES_BOX_NAME=... KUBERNETES_BOX_VERSION=... .../cluster/kube-up.sh # You can specify a box location: # KUBERNETES_PROVIDER=vagrant KUBERNETES_BOX_NAME=... KUBERNETES_BOX_URL=... .../cluster/kube-up.sh # KUBERNETES_BOX_URL and KUBERNETES_BOX_VERSION will be ignored unless # KUBERNETES_BOX_NAME is set # Default OS platform to provider/box information $kube_provider_boxes = { :parallels => { 'fedora' => { # :box_url and :box_version are optional (and mutually exclusive); # if :box_url is omitted the box will be retrieved by :box_name (and # :box_version if provided) from # http://atlas.hashicorp.com/boxes/search (formerly # http://vagrantcloud.com/); this allows you override :box_name with # your own value so long as you provide :box_url; for example, the # "official" name of this box is "rickard-von-essen/ # opscode_fedora-20", but by providing the URL and our own name, we # make it appear as yet another provider under the "kube-fedora22" # box :box_name => 'kube-fedora23', :box_url => 'https://opscode-vm-bento.s3.amazonaws.com/vagrant/parallels/opscode_fedora-23_chef-provisionerless.box' } }, :virtualbox => { 'fedora' => { :box_name => 'kube-fedora23', :box_url => 'https://opscode-vm-bento.s3.amazonaws.com/vagrant/virtualbox/opscode_fedora-23_chef-provisionerless.box' } }, :libvirt => { 'fedora' => { :box_name => 'kube-fedora23', :box_url => 'https://dl.fedoraproject.org/pub/fedora/linux/releases/23/Cloud/x86_64/Images/Fedora-Cloud-Base-Vagrant-23-20151030.x86_64.vagrant-libvirt.box' } }, :vmware_desktop => { 'fedora' => { :box_name => 'kube-fedora23', :box_url => 'https://opscode-vm-bento.s3.amazonaws.com/vagrant/vmware/opscode_fedora-23_chef-provisionerless.box' } }, :vsphere => { 'fedora' => { :box_name => 'vsphere-dummy', :box_url => 'https://github.com/deromka/vagrant-vsphere/blob/master/vsphere-dummy.box?raw=true' } } } # Give access to all physical cpu cores # Previously cargo-culted from here: # http://www.stefanwrobel.com/how-to-make-vagrant-performance-not-suck # Rewritten to actually determine the number of hardware cores instead of assuming # that the host has hyperthreading enabled. host = RbConfig::CONFIG['host_os'] if host =~ /darwin/ $vm_cpus = `sysctl -n hw.physicalcpu`.to_i elsif host =~ /linux/ #This should work on most processors, however it will fail on ones without the core id field. #So far i have only seen this on a raspberry pi. which you probably don't want to run vagrant on anyhow... #But just in case we'll default to the result of nproc if we get 0 just to be safe. $vm_cpus = `cat /proc/cpuinfo | grep 'core id' | sort -u | wc -l`.to_i if $vm_cpus < 1 $vm_cpus = `nproc`.to_i end else # sorry Windows folks, I can't help you $vm_cpus = 2 end # Give VM 1024MB of RAM by default # In Fedora VM, tmpfs device is mapped to /tmp. tmpfs is given 50% of RAM allocation. # When doing Salt provisioning, we copy approximately 200MB of content in /tmp before anything else happens. # This causes problems if anything else was in /tmp or the other directories that are bound to tmpfs device (i.e /run, etc.) $vm_master_mem = (ENV['KUBERNETES_MASTER_MEMORY'] || ENV['KUBERNETES_MEMORY'] || 1280).to_i $vm_node_mem = (ENV['KUBERNETES_NODE_MEMORY'] || ENV['KUBERNETES_MEMORY'] || 2048).to_i Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| if Vagrant.has_plugin?("vagrant-proxyconf") $http_proxy = ENV['KUBERNETES_HTTP_PROXY'] || "" $https_proxy = ENV['KUBERNETES_HTTPS_PROXY'] || "" $no_proxy = ENV['KUBERNETES_NO_PROXY'] || "127.0.0.1" config.proxy.http = $http_proxy config.proxy.https = $https_proxy config.proxy.no_proxy = $no_proxy end # this corrects a bug in 1.8.5 where an invalid SSH key is inserted. if Vagrant::VERSION == "1.8.5" config.ssh.insert_key = false end def setvmboxandurl(config, provider) if ENV['KUBERNETES_BOX_NAME'] then config.vm.box = ENV['KUBERNETES_BOX_NAME'] if ENV['KUBERNETES_BOX_URL'] then config.vm.box_url = ENV['KUBERNETES_BOX_URL'] end if ENV['KUBERNETES_BOX_VERSION'] then config.vm.box_version = ENV['KUBERNETES_BOX_VERSION'] end else config.vm.box = $kube_provider_boxes[provider][$kube_os][:box_name] if $kube_provider_boxes[provider][$kube_os][:box_url] then config.vm.box_url = $kube_provider_boxes[provider][$kube_os][:box_url] end if $kube_provider_boxes[provider][$kube_os][:box_version] then config.vm.box_version = $kube_provider_boxes[provider][$kube_os][:box_version] end end end def customize_vm(config, vm_mem) if $use_nfs then config.vm.synced_folder ".", "/vagrant", nfs: true elsif $use_rsync then opts = {} if ENV['KUBERNETES_VAGRANT_RSYNC_ARGS'] then opts[:rsync__args] = ENV['KUBERNETES_VAGRANT_RSYNC_ARGS'].split(" ") end if ENV['KUBERNETES_VAGRANT_RSYNC_EXCLUDE'] then opts[:rsync__exclude] = ENV['KUBERNETES_VAGRANT_RSYNC_EXCLUDE'].split(" ") end config.vm.synced_folder ".", "/vagrant", opts end # Try VMWare Fusion first (see # https://docs.vagrantup.com/v2/providers/basic_usage.html) config.vm.provider :vmware_fusion do |v, override| setvmboxandurl(override, :vmware_desktop) v.vmx['memsize'] = vm_mem v.vmx['numvcpus'] = $vm_cpus end # configure libvirt provider config.vm.provider :libvirt do |v, override| setvmboxandurl(override, :libvirt) v.memory = vm_mem v.cpus = $vm_cpus v.nested = true v.volume_cache = 'none' end # Then try VMWare Workstation config.vm.provider :vmware_workstation do |v, override| setvmboxandurl(override, :vmware_desktop) v.vmx['memsize'] = vm_mem v.vmx['numvcpus'] = $vm_cpus end # Then try Parallels config.vm.provider :parallels do |v, override| setvmboxandurl(override, :parallels) v.memory = vm_mem # v.customize ['set', :id, '--memsize', vm_mem] v.cpus = $vm_cpus # v.customize ['set', :id, '--cpus', $vm_cpus] # Don't attempt to update the Parallels tools on the image (this can # be done manually if necessary) v.update_guest_tools = false # v.customize ['set', :id, '--tools-autoupdate', 'off'] # Set up Parallels folder sharing to behave like VirtualBox (i.e., # mount the current directory as /vagrant and that's it) v.customize ['set', :id, '--shf-guest', 'off'] v.customize ['set', :id, '--shf-guest-automount', 'off'] v.customize ['set', :id, '--shf-host', 'on'] # Synchronize VM clocks to host clock (Avoid certificate invalid issue) v.customize ['set', :id, '--time-sync', 'on'] # Remove all auto-mounted "shared folders"; the result seems to # persist between runs (i.e., vagrant halt && vagrant up) override.vm.provision :shell, :inline => (%q{ set -ex if [ -d /media/psf ]; then for i in /media/psf/*; do if [ -d "${i}" ]; then umount "${i}" || true rmdir -v "${i}" fi done rmdir -v /media/psf fi exit }).strip end # Then try vsphere config.vm.provider :vsphere do |vsphere, override| setvmboxandurl(override, :vsphere) #config.vm.hostname = ENV['MASTER_NAME'] config.ssh.username = ENV['MASTER_USER'] config.ssh.password = ENV['MASTER_PASSWD'] config.ssh.pty = true config.ssh.insert_key = true #config.ssh.private_key_path = '~/.ssh/id_rsa_vsphere' # Don't attempt to update the tools on the image (this can # be done manually if necessary) # vsphere.update_guest_tools = false # v.customize ['set', :id, '--tools-autoupdate', 'off'] # The vSphere host we're going to connect to vsphere.host = ENV['VAGRANT_VSPHERE_URL'] # The ESX host for the new VM vsphere.compute_resource_name = ENV['VAGRANT_VSPHERE_RESOURCE_POOL'] # The resource pool for the new VM #vsphere.resource_pool_name = 'Comp' # path to folder where new VM should be created, if not specified template's parent folder will be used vsphere.vm_base_path = ENV['VAGRANT_VSPHERE_BASE_PATH'] # The template we're going to clone vsphere.template_name = ENV['VAGRANT_VSPHERE_TEMPLATE_NAME'] # The name of the new machine #vsphere.name = ENV['MASTER_NAME'] # vSphere login vsphere.user = ENV['VAGRANT_VSPHERE_USERNAME'] # vSphere password vsphere.password = ENV['VAGRANT_VSPHERE_PASSWORD'] # cpu count vsphere.cpu_count = $vm_cpus # memory in MB vsphere.memory_mb = vm_mem # If you don't have SSL configured correctly, set this to 'true' vsphere.insecure = ENV['VAGRANT_VSPHERE_INSECURE'] end # Don't attempt to update Virtualbox Guest Additions (requires gcc) if Vagrant.has_plugin?("vagrant-vbguest") then config.vbguest.auto_update = false end # Finally, fall back to VirtualBox config.vm.provider :virtualbox do |v, override| setvmboxandurl(override, :virtualbox) v.memory = vm_mem # v.customize ["modifyvm", :id, "--memory", vm_mem] v.cpus = $vm_cpus # v.customize ["modifyvm", :id, "--cpus", $vm_cpus] # Use faster paravirtualized networking v.customize ["modifyvm", :id, "--nictype1", "virtio"] v.customize ["modifyvm", :id, "--nictype2", "virtio"] end end # Kubernetes master config.vm.define "master" do |c| customize_vm c, $vm_master_mem if ENV['KUBE_TEMP'] then script = "#{ENV['KUBE_TEMP']}/master-start.sh" c.vm.provision "shell", run: "always", path: script end c.vm.network "private_network", ip: "#{$master_ip}" end # Kubernetes node $num_node.times do |n| node_vm_name = "node-#{n+1}" config.vm.define node_vm_name do |node| customize_vm node, $vm_node_mem node_ip = $node_ips[n] if ENV['KUBE_TEMP'] then script = "#{ENV['KUBE_TEMP']}/node-start-#{n}.sh" node.vm.provision "shell", run: "always", path: script end node.vm.network "private_network", ip: "#{node_ip}" end end end
Vagrantfile
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0001818094460759312, 0.00017150321218650788, 0.00016314921958837658, 0.0001717245759209618, 0.000003662283234007191 ]
{ "id": 5, "code_window": [ "func TestDeploymentStatusViewerStatus(t *testing.T) {\n", "\ttests := []struct {\n", "\t\tgeneration int64\n", "\t\tspecReplicas int32\n", "\t\tmaxUnavailable *intstrutil.IntOrString\n", "\t\tstatus extensions.DeploymentStatus\n", "\t\tmsg string\n", "\t\tdone bool\n", "\t}{\n", "\t\t{\n", "\t\t\tgeneration: 0,\n", "\t\t\tspecReplicas: 1,\n", "\t\t\tstatus: extensions.DeploymentStatus{\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tgeneration int64\n", "\t\tspecReplicas int32\n", "\t\tstatus extensions.DeploymentStatus\n", "\t\tmsg string\n", "\t\tdone bool\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 34 }
/* Copyright (c) 2015 VMware, Inc. All Rights Reserved. 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 object import ( "context" "github.com/vmware/govmomi/vim25" "github.com/vmware/govmomi/vim25/methods" "github.com/vmware/govmomi/vim25/types" ) type OvfManager struct { Common } func NewOvfManager(c *vim25.Client) *OvfManager { o := OvfManager{ Common: NewCommon(c, *c.ServiceContent.OvfManager), } return &o } // CreateDescriptor wraps methods.CreateDescriptor func (o OvfManager) CreateDescriptor(ctx context.Context, obj Reference, cdp types.OvfCreateDescriptorParams) (*types.OvfCreateDescriptorResult, error) { req := types.CreateDescriptor{ This: o.Reference(), Obj: obj.Reference(), Cdp: cdp, } res, err := methods.CreateDescriptor(ctx, o.c, &req) if err != nil { return nil, err } return &res.Returnval, nil } // CreateImportSpec wraps methods.CreateImportSpec func (o OvfManager) CreateImportSpec(ctx context.Context, ovfDescriptor string, resourcePool Reference, datastore Reference, cisp types.OvfCreateImportSpecParams) (*types.OvfCreateImportSpecResult, error) { req := types.CreateImportSpec{ This: o.Reference(), OvfDescriptor: ovfDescriptor, ResourcePool: resourcePool.Reference(), Datastore: datastore.Reference(), Cisp: cisp, } res, err := methods.CreateImportSpec(ctx, o.c, &req) if err != nil { return nil, err } return &res.Returnval, nil } // ParseDescriptor wraps methods.ParseDescriptor func (o OvfManager) ParseDescriptor(ctx context.Context, ovfDescriptor string, pdp types.OvfParseDescriptorParams) (*types.OvfParseDescriptorResult, error) { req := types.ParseDescriptor{ This: o.Reference(), OvfDescriptor: ovfDescriptor, Pdp: pdp, } res, err := methods.ParseDescriptor(ctx, o.c, &req) if err != nil { return nil, err } return &res.Returnval, nil } // ValidateHost wraps methods.ValidateHost func (o OvfManager) ValidateHost(ctx context.Context, ovfDescriptor string, host Reference, vhp types.OvfValidateHostParams) (*types.OvfValidateHostResult, error) { req := types.ValidateHost{ This: o.Reference(), OvfDescriptor: ovfDescriptor, Host: host.Reference(), Vhp: vhp, } res, err := methods.ValidateHost(ctx, o.c, &req) if err != nil { return nil, err } return &res.Returnval, nil }
vendor/github.com/vmware/govmomi/object/ovf_manager.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017715326976031065, 0.00017252932593692094, 0.00016762524319346994, 0.00017209092038683593, 0.0000032216075851465575 ]
{ "id": 6, "code_window": [ "\t\t\tdone: false,\n", "\t\t},\n", "\t\t{\n", "\t\t\tgeneration: 1,\n", "\t\t\tspecReplicas: 2,\n", "\t\t\tmaxUnavailable: intOrStringP(0),\n", "\t\t\tstatus: extensions.DeploymentStatus{\n", "\t\t\t\tObservedGeneration: 1,\n", "\t\t\t\tReplicas: 2,\n", "\t\t\t\tUpdatedReplicas: 2,\n", "\t\t\t\tAvailableReplicas: 1,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tgeneration: 1,\n", "\t\t\tspecReplicas: 2,\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 70 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.11707483977079391, 0.005038021132349968, 0.00016366744239348918, 0.00027229267288930714, 0.020615627989172935 ]
{ "id": 6, "code_window": [ "\t\t\tdone: false,\n", "\t\t},\n", "\t\t{\n", "\t\t\tgeneration: 1,\n", "\t\t\tspecReplicas: 2,\n", "\t\t\tmaxUnavailable: intOrStringP(0),\n", "\t\t\tstatus: extensions.DeploymentStatus{\n", "\t\t\t\tObservedGeneration: 1,\n", "\t\t\t\tReplicas: 2,\n", "\t\t\t\tUpdatedReplicas: 2,\n", "\t\t\t\tAvailableReplicas: 1,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tgeneration: 1,\n", "\t\t\tspecReplicas: 2,\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 70 }
/* Copyright 2017 The Kubernetes Authors. 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. */ // This file was automatically generated by informer-gen package v1alpha1 import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" cache "k8s.io/client-go/tools/cache" rbac_v1alpha1 "k8s.io/kubernetes/pkg/apis/rbac/v1alpha1" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/clientset" internalinterfaces "k8s.io/kubernetes/pkg/client/informers/informers_generated/externalversions/internalinterfaces" v1alpha1 "k8s.io/kubernetes/pkg/client/listers/rbac/v1alpha1" time "time" ) // ClusterRoleInformer provides access to a shared informer and lister for // ClusterRoles. type ClusterRoleInformer interface { Informer() cache.SharedIndexInformer Lister() v1alpha1.ClusterRoleLister } type clusterRoleInformer struct { factory internalinterfaces.SharedInformerFactory } func newClusterRoleInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { sharedIndexInformer := cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return client.RbacV1alpha1().ClusterRoles().List(options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return client.RbacV1alpha1().ClusterRoles().Watch(options) }, }, &rbac_v1alpha1.ClusterRole{}, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, ) return sharedIndexInformer } func (f *clusterRoleInformer) Informer() cache.SharedIndexInformer { return f.factory.InformerFor(&rbac_v1alpha1.ClusterRole{}, newClusterRoleInformer) } func (f *clusterRoleInformer) Lister() v1alpha1.ClusterRoleLister { return v1alpha1.NewClusterRoleLister(f.Informer().GetIndexer()) }
pkg/client/informers/informers_generated/externalversions/rbac/v1alpha1/clusterrole.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00018766942957881838, 0.00017239709268324077, 0.00016399675223510712, 0.00016978770145215094, 0.000007468625881301705 ]
{ "id": 6, "code_window": [ "\t\t\tdone: false,\n", "\t\t},\n", "\t\t{\n", "\t\t\tgeneration: 1,\n", "\t\t\tspecReplicas: 2,\n", "\t\t\tmaxUnavailable: intOrStringP(0),\n", "\t\t\tstatus: extensions.DeploymentStatus{\n", "\t\t\t\tObservedGeneration: 1,\n", "\t\t\t\tReplicas: 2,\n", "\t\t\t\tUpdatedReplicas: 2,\n", "\t\t\t\tAvailableReplicas: 1,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tgeneration: 1,\n", "\t\t\tspecReplicas: 2,\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 70 }
This file has moved to [https://github.com/kubernetes/community/blob/master/contributors/design-proposals/kubectl-login.md](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/kubectl-login.md)
docs/proposals/kubectl-login.md
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017185694014187902, 0.00017185694014187902, 0.00017185694014187902, 0.00017185694014187902, 0 ]
{ "id": 6, "code_window": [ "\t\t\tdone: false,\n", "\t\t},\n", "\t\t{\n", "\t\t\tgeneration: 1,\n", "\t\t\tspecReplicas: 2,\n", "\t\t\tmaxUnavailable: intOrStringP(0),\n", "\t\t\tstatus: extensions.DeploymentStatus{\n", "\t\t\t\tObservedGeneration: 1,\n", "\t\t\t\tReplicas: 2,\n", "\t\t\t\tUpdatedReplicas: 2,\n", "\t\t\t\tAvailableReplicas: 1,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tgeneration: 1,\n", "\t\t\tspecReplicas: 2,\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 70 }
reviewers: - justinsb - freehan - david-mcmahon
pkg/api/service/OWNERS
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017171933723147959, 0.00017171933723147959, 0.00017171933723147959, 0.00017171933723147959, 0 ]
{ "id": 7, "code_window": [ "\t\t\t\tAvailableReplicas: 1,\n", "\t\t\t\tUnavailableReplicas: 1,\n", "\t\t\t},\n", "\n", "\t\t\tmsg: \"Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\\n\",\n", "\t\t\tdone: false,\n", "\t\t},\n", "\t\t{\n", "\t\t\tgeneration: 1,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tmsg: \"Waiting for rollout to finish: 1 of 2 updated replicas are available...\\n\",\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 81 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.40700942277908325, 0.01725403033196926, 0.0001644842850510031, 0.00021906908659730107, 0.0730416402220726 ]
{ "id": 7, "code_window": [ "\t\t\t\tAvailableReplicas: 1,\n", "\t\t\t\tUnavailableReplicas: 1,\n", "\t\t\t},\n", "\n", "\t\t\tmsg: \"Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\\n\",\n", "\t\t\tdone: false,\n", "\t\t},\n", "\t\t{\n", "\t\t\tgeneration: 1,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tmsg: \"Waiting for rollout to finish: 1 of 2 updated replicas are available...\\n\",\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 81 }
/* Copyright 2017 The Kubernetes Authors. 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. */ // This file was autogenerated by go-to-protobuf. Do not edit it manually! syntax = 'proto2'; package k8s.io.kubernetes.pkg.apis.authorization.v1beta1; import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; import "k8s.io/apimachinery/pkg/runtime/generated.proto"; import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; import "k8s.io/apimachinery/pkg/util/intstr/generated.proto"; import "k8s.io/apiserver/pkg/apis/example/v1/generated.proto"; import "k8s.io/kubernetes/pkg/api/v1/generated.proto"; // Package-wide variables from generator "generated". option go_package = "v1beta1"; // ExtraValue masks the value so protobuf can generate // +protobuf.nullable=true // +protobuf.options.(gogoproto.goproto_stringer)=false message ExtraValue { // items, if empty, will result in an empty slice repeated string items = 1; } // LocalSubjectAccessReview checks whether or not a user or group can perform an action in a given namespace. // Having a namespace scoped resource makes it much easier to grant namespace scoped policy that includes permissions // checking. message LocalSubjectAccessReview { // +optional optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec holds information about the request being evaluated. spec.namespace must be equal to the namespace // you made the request against. If empty, it is defaulted. optional SubjectAccessReviewSpec spec = 2; // Status is filled in by the server and indicates whether the request is allowed or not // +optional optional SubjectAccessReviewStatus status = 3; } // NonResourceAttributes includes the authorization attributes available for non-resource requests to the Authorizer interface message NonResourceAttributes { // Path is the URL path of the request // +optional optional string path = 1; // Verb is the standard HTTP verb // +optional optional string verb = 2; } // ResourceAttributes includes the authorization attributes available for resource requests to the Authorizer interface message ResourceAttributes { // Namespace is the namespace of the action being requested. Currently, there is no distinction between no namespace and all namespaces // "" (empty) is defaulted for LocalSubjectAccessReviews // "" (empty) is empty for cluster-scoped resources // "" (empty) means "all" for namespace scoped resources from a SubjectAccessReview or SelfSubjectAccessReview // +optional optional string namespace = 1; // Verb is a kubernetes resource API verb, like: get, list, watch, create, update, delete, proxy. "*" means all. // +optional optional string verb = 2; // Group is the API Group of the Resource. "*" means all. // +optional optional string group = 3; // Version is the API Version of the Resource. "*" means all. // +optional optional string version = 4; // Resource is one of the existing resource types. "*" means all. // +optional optional string resource = 5; // Subresource is one of the existing resource types. "" means none. // +optional optional string subresource = 6; // Name is the name of the resource being requested for a "get" or deleted for a "delete". "" (empty) means all. // +optional optional string name = 7; } // SelfSubjectAccessReview checks whether or the current user can perform an action. Not filling in a // spec.namespace means "in all namespaces". Self is a special case, because users should always be able // to check whether they can perform an action message SelfSubjectAccessReview { // +optional optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec holds information about the request being evaluated. user and groups must be empty optional SelfSubjectAccessReviewSpec spec = 2; // Status is filled in by the server and indicates whether the request is allowed or not // +optional optional SubjectAccessReviewStatus status = 3; } // SelfSubjectAccessReviewSpec is a description of the access request. Exactly one of ResourceAuthorizationAttributes // and NonResourceAuthorizationAttributes must be set message SelfSubjectAccessReviewSpec { // ResourceAuthorizationAttributes describes information for a resource access request // +optional optional ResourceAttributes resourceAttributes = 1; // NonResourceAttributes describes information for a non-resource access request // +optional optional NonResourceAttributes nonResourceAttributes = 2; } // SubjectAccessReview checks whether or not a user or group can perform an action. message SubjectAccessReview { // +optional optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec holds information about the request being evaluated optional SubjectAccessReviewSpec spec = 2; // Status is filled in by the server and indicates whether the request is allowed or not // +optional optional SubjectAccessReviewStatus status = 3; } // SubjectAccessReviewSpec is a description of the access request. Exactly one of ResourceAuthorizationAttributes // and NonResourceAuthorizationAttributes must be set message SubjectAccessReviewSpec { // ResourceAuthorizationAttributes describes information for a resource access request // +optional optional ResourceAttributes resourceAttributes = 1; // NonResourceAttributes describes information for a non-resource access request // +optional optional NonResourceAttributes nonResourceAttributes = 2; // User is the user you're testing for. // If you specify "User" but not "Group", then is it interpreted as "What if User were not a member of any groups // +optional optional string verb = 3; // Groups is the groups you're testing for. // +optional repeated string group = 4; // Extra corresponds to the user.Info.GetExtra() method from the authenticator. Since that is input to the authorizer // it needs a reflection here. // +optional map<string, ExtraValue> extra = 5; } // SubjectAccessReviewStatus message SubjectAccessReviewStatus { // Allowed is required. True if the action would be allowed, false otherwise. optional bool allowed = 1; // Reason is optional. It indicates why a request was allowed or denied. // +optional optional string reason = 2; // EvaluationError is an indication that some error occurred during the authorization check. // It is entirely possible to get an error and be able to continue determine authorization status in spite of it. // For instance, RBAC can be missing a role, but enough roles are still present and bound to reason about the request. // +optional optional string evaluationError = 3; }
staging/src/k8s.io/client-go/pkg/apis/authorization/v1beta1/generated.proto
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0002677790471352637, 0.00017939551617018878, 0.00016256254457402974, 0.0001688910706434399, 0.000028483313144533895 ]
{ "id": 7, "code_window": [ "\t\t\t\tAvailableReplicas: 1,\n", "\t\t\t\tUnavailableReplicas: 1,\n", "\t\t\t},\n", "\n", "\t\t\tmsg: \"Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\\n\",\n", "\t\t\tdone: false,\n", "\t\t},\n", "\t\t{\n", "\t\t\tgeneration: 1,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tmsg: \"Waiting for rollout to finish: 1 of 2 updated replicas are available...\\n\",\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 81 }
## Java EE Application using WildFly and MySQL The following document describes the deployment of a Java EE application using [WildFly](http://wildfly.org) application server and MySQL database server on Kubernetes. The sample application source code is at: https://github.com/javaee-samples/javaee7-simple-sample. ### Prerequisites https://github.com/kubernetes/kubernetes/blob/master/docs/user-guide/prereqs.md ### Start MySQL Pod In Kubernetes a [_Pod_](../../docs/user-guide/pods.md) is the smallest deployable unit that can be created, scheduled, and managed. It's a collocated group of containers that share an IP and storage volume. Here is the config for MySQL pod: [mysql-pod.yaml](mysql-pod.yaml) <!-- BEGIN MUNGE: mysql-pod.yaml --> <!-- END MUNGE: EXAMPLE --> Create the MySQL pod: ```sh kubectl create -f examples/javaee/mysql-pod.yaml ``` Check status of the pod: ```sh kubectl get -w po NAME READY STATUS RESTARTS AGE mysql-pod 0/1 Pending 0 4s NAME READY STATUS RESTARTS AGE mysql-pod 0/1 Running 0 44s mysql-pod 1/1 Running 0 44s ``` Wait for the status to `1/1` and `Running`. ### Start MySQL Service We are creating a [_Service_](../../docs/user-guide/services.md) to expose the TCP port of the MySQL server. A Service distributes traffic across a set of Pods. The order of Service and the targeted Pods does not matter. However Service needs to be started before any other Pods consuming the Service are started. In this application, we will use a Kubernetes Service to provide a discoverable endpoints for the MySQL endpoint in the cluster. MySQL service target pods with the labels `name: mysql-pod` and `context: docker-k8s-lab`. Here is definition of the MySQL service: [mysql-service.yaml](mysql-service.yaml) <!-- BEGIN MUNGE: mysql-service.yaml --> <!-- END MUNGE: EXAMPLE --> Create this service: ```sh kubectl create -f examples/javaee/mysql-service.yaml ``` Get status of the service: ```sh kubectl get -w svc NAME LABELS SELECTOR IP(S) PORT(S) kubernetes component=apiserver,provider=kubernetes <none> 10.247.0.1 443/TCP mysql-service context=docker-k8s-lab,name=mysql-pod context=docker-k8s-lab,name=mysql-pod 10.247.63.43 3306/TCP ``` If multiple services are running, then it can be narrowed by specifying labels: ```sh kubectl get -w po -l context=docker-k8s-lab,name=mysql-pod NAME READY STATUS RESTARTS AGE mysql-pod 1/1 Running 0 4m ``` This is also the selector label used by service to target pods. When a Service is run on a node, the kubelet adds a set of environment variables for each active Service. It supports both Docker links compatible variables and simpler `{SVCNAME}_SERVICE_HOST` and `{SVCNAME}_SERVICE_PORT` variables, where the Service name is upper-cased and dashes are converted to underscores. Our service name is ``mysql-service'' and so ``MYSQL_SERVICE_SERVICE_HOST'' and ``MYSQL_SERVICE_SERVICE_PORT'' variables are available to other pods. This host and port variables are then used to create the JDBC resource in WildFly. ### Start WildFly Replication Controller WildFly is a lightweight Java EE 7 compliant application server. It is wrapped in a Replication Controller and used as the Java EE runtime. In Kubernetes a [_Replication Controller_](../../docs/user-guide/replication-controller.md) is responsible for replicating sets of identical pods. Like a _Service_ it has a selector query which identifies the members of it's set. Unlike a service it also has a desired number of replicas, and it will create or delete pods to ensure that the number of pods matches up with it's desired state. Here is definition of the MySQL service: [wildfly-rc.yaml](wildfly-rc.yaml). <!-- BEGIN MUNGE: wildfly-rc.yaml --> <!-- END MUNGE: EXAMPLE --> Create this controller: ```sh kubectl create -f examples/javaee/wildfly-rc.yaml ``` Check status of the pod inside replication controller: ```sh kubectl get po NAME READY STATUS RESTARTS AGE mysql-pod 1/1 Running 0 1h wildfly-rc-w2kk5 1/1 Running 0 6m ``` ### Access the application Get IP address of the pod: ```sh kubectl get -o template po wildfly-rc-w2kk5 --template={{.status.podIP}} 10.246.1.23 ``` Log in to node and access the application: ```sh vagrant ssh node-1 Last login: Thu Jul 16 00:24:36 2015 from 10.0.2.2 [vagrant@kubernetes-node-1 ~]$ curl http://10.246.1.23:8080/employees/resources/employees/ <?xml version="1.0" encoding="UTF-8" standalone="yes"?><collection><employee><id>1</id><name>Penny</name></employee><employee><id>2</id><name>Sheldon</name></employee><employee><id>3</id><name>Amy</name></employee><employee><id>4</id><name>Leonard</name></employee><employee><id>5</id><name>Bernadette</name></employee><employee><id>6</id><name>Raj</name></employee><employee><id>7</id><name>Howard</name></employee><employee><id>8</id><name>Priya</name></employee></collection> ``` ### Delete resources All resources created in this application can be deleted: ```sh kubectl delete -f examples/javaee/mysql-pod.yaml kubectl delete -f examples/javaee/mysql-service.yaml kubectl delete -f examples/javaee/wildfly-rc.yaml ``` <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/examples/javaee/README.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
examples/javaee/README.md
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0001734620745992288, 0.00016667430463712662, 0.00015918684948701411, 0.00016674186917953193, 0.000003827133696177043 ]
{ "id": 7, "code_window": [ "\t\t\t\tAvailableReplicas: 1,\n", "\t\t\t\tUnavailableReplicas: 1,\n", "\t\t\t},\n", "\n", "\t\t\tmsg: \"Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\\n\",\n", "\t\t\tdone: false,\n", "\t\t},\n", "\t\t{\n", "\t\t\tgeneration: 1,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tmsg: \"Waiting for rollout to finish: 1 of 2 updated replicas are available...\\n\",\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 81 }
package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "bytes" "errors" "fmt" "net/http" "os" "runtime" "strings" "sync" "github.com/emicklei/go-restful/log" ) // Container holds a collection of WebServices and a http.ServeMux to dispatch http requests. // The requests are further dispatched to routes of WebServices using a RouteSelector type Container struct { webServicesLock sync.RWMutex webServices []*WebService ServeMux *http.ServeMux isRegisteredOnRoot bool containerFilters []FilterFunction doNotRecover bool // default is true recoverHandleFunc RecoverHandleFunction serviceErrorHandleFunc ServiceErrorHandleFunction router RouteSelector // default is a CurlyRouter (RouterJSR311 is a slower alternative) contentEncodingEnabled bool // default is false } // NewContainer creates a new Container using a new ServeMux and default router (RouterJSR311) func NewContainer() *Container { return &Container{ webServices: []*WebService{}, ServeMux: http.NewServeMux(), isRegisteredOnRoot: false, containerFilters: []FilterFunction{}, doNotRecover: true, recoverHandleFunc: logStackOnRecover, serviceErrorHandleFunc: writeServiceError, router: CurlyRouter{}, contentEncodingEnabled: false} } // RecoverHandleFunction declares functions that can be used to handle a panic situation. // The first argument is what recover() returns. The second must be used to communicate an error response. type RecoverHandleFunction func(interface{}, http.ResponseWriter) // RecoverHandler changes the default function (logStackOnRecover) to be called // when a panic is detected. DoNotRecover must be have its default value (=false). func (c *Container) RecoverHandler(handler RecoverHandleFunction) { c.recoverHandleFunc = handler } // ServiceErrorHandleFunction declares functions that can be used to handle a service error situation. // The first argument is the service error, the second is the request that resulted in the error and // the third must be used to communicate an error response. type ServiceErrorHandleFunction func(ServiceError, *Request, *Response) // ServiceErrorHandler changes the default function (writeServiceError) to be called // when a ServiceError is detected. func (c *Container) ServiceErrorHandler(handler ServiceErrorHandleFunction) { c.serviceErrorHandleFunc = handler } // DoNotRecover controls whether panics will be caught to return HTTP 500. // If set to true, Route functions are responsible for handling any error situation. // Default value is true. func (c *Container) DoNotRecover(doNot bool) { c.doNotRecover = doNot } // Router changes the default Router (currently RouterJSR311) func (c *Container) Router(aRouter RouteSelector) { c.router = aRouter } // EnableContentEncoding (default=false) allows for GZIP or DEFLATE encoding of responses. func (c *Container) EnableContentEncoding(enabled bool) { c.contentEncodingEnabled = enabled } // Add a WebService to the Container. It will detect duplicate root paths and exit in that case. func (c *Container) Add(service *WebService) *Container { c.webServicesLock.Lock() defer c.webServicesLock.Unlock() // if rootPath was not set then lazy initialize it if len(service.rootPath) == 0 { service.Path("/") } // cannot have duplicate root paths for _, each := range c.webServices { if each.RootPath() == service.RootPath() { log.Printf("[restful] WebService with duplicate root path detected:['%v']", each) os.Exit(1) } } // If not registered on root then add specific mapping if !c.isRegisteredOnRoot { c.isRegisteredOnRoot = c.addHandler(service, c.ServeMux) } c.webServices = append(c.webServices, service) return c } // addHandler may set a new HandleFunc for the serveMux // this function must run inside the critical region protected by the webServicesLock. // returns true if the function was registered on root ("/") func (c *Container) addHandler(service *WebService, serveMux *http.ServeMux) bool { pattern := fixedPrefixPath(service.RootPath()) // check if root path registration is needed if "/" == pattern || "" == pattern { serveMux.HandleFunc("/", c.dispatch) return true } // detect if registration already exists alreadyMapped := false for _, each := range c.webServices { if each.RootPath() == service.RootPath() { alreadyMapped = true break } } if !alreadyMapped { serveMux.HandleFunc(pattern, c.dispatch) if !strings.HasSuffix(pattern, "/") { serveMux.HandleFunc(pattern+"/", c.dispatch) } } return false } func (c *Container) Remove(ws *WebService) error { if c.ServeMux == http.DefaultServeMux { errMsg := fmt.Sprintf("[restful] cannot remove a WebService from a Container using the DefaultServeMux: ['%v']", ws) log.Printf(errMsg) return errors.New(errMsg) } c.webServicesLock.Lock() defer c.webServicesLock.Unlock() // build a new ServeMux and re-register all WebServices newServeMux := http.NewServeMux() newServices := []*WebService{} newIsRegisteredOnRoot := false for _, each := range c.webServices { if each.rootPath != ws.rootPath { // If not registered on root then add specific mapping if !newIsRegisteredOnRoot { newIsRegisteredOnRoot = c.addHandler(each, newServeMux) } newServices = append(newServices, each) } } c.webServices, c.ServeMux, c.isRegisteredOnRoot = newServices, newServeMux, newIsRegisteredOnRoot return nil } // logStackOnRecover is the default RecoverHandleFunction and is called // when DoNotRecover is false and the recoverHandleFunc is not set for the container. // Default implementation logs the stacktrace and writes the stacktrace on the response. // This may be a security issue as it exposes sourcecode information. func logStackOnRecover(panicReason interface{}, httpWriter http.ResponseWriter) { var buffer bytes.Buffer buffer.WriteString(fmt.Sprintf("[restful] recover from panic situation: - %v\r\n", panicReason)) for i := 2; ; i += 1 { _, file, line, ok := runtime.Caller(i) if !ok { break } buffer.WriteString(fmt.Sprintf(" %s:%d\r\n", file, line)) } log.Print(buffer.String()) httpWriter.WriteHeader(http.StatusInternalServerError) httpWriter.Write(buffer.Bytes()) } // writeServiceError is the default ServiceErrorHandleFunction and is called // when a ServiceError is returned during route selection. Default implementation // calls resp.WriteErrorString(err.Code, err.Message) func writeServiceError(err ServiceError, req *Request, resp *Response) { resp.WriteErrorString(err.Code, err.Message) } // Dispatch the incoming Http Request to a matching WebService. func (c *Container) dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request) { writer := httpWriter // CompressingResponseWriter should be closed after all operations are done defer func() { if compressWriter, ok := writer.(*CompressingResponseWriter); ok { compressWriter.Close() } }() // Instal panic recovery unless told otherwise if !c.doNotRecover { // catch all for 500 response defer func() { if r := recover(); r != nil { c.recoverHandleFunc(r, writer) return } }() } // Install closing the request body (if any) defer func() { if nil != httpRequest.Body { httpRequest.Body.Close() } }() // Detect if compression is needed // assume without compression, test for override if c.contentEncodingEnabled { doCompress, encoding := wantsCompressedResponse(httpRequest) if doCompress { var err error writer, err = NewCompressingResponseWriter(httpWriter, encoding) if err != nil { log.Print("[restful] unable to install compressor: ", err) httpWriter.WriteHeader(http.StatusInternalServerError) return } } } // Find best match Route ; err is non nil if no match was found var webService *WebService var route *Route var err error func() { c.webServicesLock.RLock() defer c.webServicesLock.RUnlock() webService, route, err = c.router.SelectRoute( c.webServices, httpRequest) }() if err != nil { // a non-200 response has already been written // run container filters anyway ; they should not touch the response... chain := FilterChain{Filters: c.containerFilters, Target: func(req *Request, resp *Response) { switch err.(type) { case ServiceError: ser := err.(ServiceError) c.serviceErrorHandleFunc(ser, req, resp) } // TODO }} chain.ProcessFilter(NewRequest(httpRequest), NewResponse(writer)) return } wrappedRequest, wrappedResponse := route.wrapRequestResponse(writer, httpRequest) // pass through filters (if any) if len(c.containerFilters)+len(webService.filters)+len(route.Filters) > 0 { // compose filter chain allFilters := []FilterFunction{} allFilters = append(allFilters, c.containerFilters...) allFilters = append(allFilters, webService.filters...) allFilters = append(allFilters, route.Filters...) chain := FilterChain{Filters: allFilters, Target: func(req *Request, resp *Response) { // handle request by route after passing all filters route.Function(wrappedRequest, wrappedResponse) }} chain.ProcessFilter(wrappedRequest, wrappedResponse) } else { // no filters, handle request by route route.Function(wrappedRequest, wrappedResponse) } } // fixedPrefixPath returns the fixed part of the partspec ; it may include template vars {} func fixedPrefixPath(pathspec string) string { varBegin := strings.Index(pathspec, "{") if -1 == varBegin { return pathspec } return pathspec[:varBegin] } // ServeHTTP implements net/http.Handler therefore a Container can be a Handler in a http.Server func (c *Container) ServeHTTP(httpwriter http.ResponseWriter, httpRequest *http.Request) { c.ServeMux.ServeHTTP(httpwriter, httpRequest) } // Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics. func (c *Container) Handle(pattern string, handler http.Handler) { c.ServeMux.Handle(pattern, handler) } // HandleWithFilter registers the handler for the given pattern. // Container's filter chain is applied for handler. // If a handler already exists for pattern, HandleWithFilter panics. func (c *Container) HandleWithFilter(pattern string, handler http.Handler) { f := func(httpResponse http.ResponseWriter, httpRequest *http.Request) { if len(c.containerFilters) == 0 { handler.ServeHTTP(httpResponse, httpRequest) return } chain := FilterChain{Filters: c.containerFilters, Target: func(req *Request, resp *Response) { handler.ServeHTTP(httpResponse, httpRequest) }} chain.ProcessFilter(NewRequest(httpRequest), NewResponse(httpResponse)) } c.Handle(pattern, http.HandlerFunc(f)) } // Filter appends a container FilterFunction. These are called before dispatching // a http.Request to a WebService from the container func (c *Container) Filter(filter FilterFunction) { c.containerFilters = append(c.containerFilters, filter) } // RegisteredWebServices returns the collections of added WebServices func (c *Container) RegisteredWebServices() []*WebService { c.webServicesLock.RLock() defer c.webServicesLock.RUnlock() result := make([]*WebService, len(c.webServices)) for ix := range c.webServices { result[ix] = c.webServices[ix] } return result } // computeAllowedMethods returns a list of HTTP methods that are valid for a Request func (c *Container) computeAllowedMethods(req *Request) []string { // Go through all RegisteredWebServices() and all its Routes to collect the options methods := []string{} requestPath := req.Request.URL.Path for _, ws := range c.RegisteredWebServices() { matches := ws.pathExpr.Matcher.FindStringSubmatch(requestPath) if matches != nil { finalMatch := matches[len(matches)-1] for _, rt := range ws.Routes() { matches := rt.pathExpr.Matcher.FindStringSubmatch(finalMatch) if matches != nil { lastMatch := matches[len(matches)-1] if lastMatch == "" || lastMatch == "/" { // do not include if value is neither empty nor ‘/’. methods = append(methods, rt.Method) } } } } } // methods = append(methods, "OPTIONS") not sure about this return methods } // newBasicRequestResponse creates a pair of Request,Response from its http versions. // It is basic because no parameter or (produces) content-type information is given. func newBasicRequestResponse(httpWriter http.ResponseWriter, httpRequest *http.Request) (*Request, *Response) { resp := NewResponse(httpWriter) resp.requestAccept = httpRequest.Header.Get(HEADER_Accept) return NewRequest(httpRequest), resp }
vendor/github.com/emicklei/go-restful/container.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0007859010365791619, 0.00019852422701660544, 0.0001640721457079053, 0.0001722219167277217, 0.00010654501966200769 ]
{ "id": 8, "code_window": [ "\n", "\t\t\tmsg: \"Waiting for deployment spec update to be observed...\\n\",\n", "\t\t\tdone: false,\n", "\t\t},\n", "\t\t{\n", "\t\t\tgeneration: 1,\n", "\t\t\tspecReplicas: 2,\n", "\t\t\tmaxUnavailable: intOrStringP(1),\n", "\t\t\tstatus: extensions.DeploymentStatus{\n", "\t\t\t\tObservedGeneration: 1,\n", "\t\t\t\tReplicas: 2,\n", "\t\t\t\tUpdatedReplicas: 2,\n", "\t\t\t\tAvailableReplicas: 1,\n", "\t\t\t\tUnavailableReplicas: 0,\n", "\t\t\t},\n", "\n", "\t\t\tmsg: \"deployment \\\"foo\\\" successfully rolled out\\n\",\n", "\t\t\tdone: true,\n", "\t\t},\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 112 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.842667818069458, 0.030400250107049942, 0.00016227169544436038, 0.00037908865488134325, 0.14881515502929688 ]
{ "id": 8, "code_window": [ "\n", "\t\t\tmsg: \"Waiting for deployment spec update to be observed...\\n\",\n", "\t\t\tdone: false,\n", "\t\t},\n", "\t\t{\n", "\t\t\tgeneration: 1,\n", "\t\t\tspecReplicas: 2,\n", "\t\t\tmaxUnavailable: intOrStringP(1),\n", "\t\t\tstatus: extensions.DeploymentStatus{\n", "\t\t\t\tObservedGeneration: 1,\n", "\t\t\t\tReplicas: 2,\n", "\t\t\t\tUpdatedReplicas: 2,\n", "\t\t\t\tAvailableReplicas: 1,\n", "\t\t\t\tUnavailableReplicas: 0,\n", "\t\t\t},\n", "\n", "\t\t\tmsg: \"deployment \\\"foo\\\" successfully rolled out\\n\",\n", "\t\t\tdone: true,\n", "\t\t},\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 112 }
The MIT License (MIT) Copyright (c) 2015 Microsoft Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
vendor/github.com/Azure/go-ansiterm/LICENSE
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017916270007845014, 0.00017310114344581962, 0.00016753528325352818, 0.00017260546155739576, 0.000004759795501740882 ]
{ "id": 8, "code_window": [ "\n", "\t\t\tmsg: \"Waiting for deployment spec update to be observed...\\n\",\n", "\t\t\tdone: false,\n", "\t\t},\n", "\t\t{\n", "\t\t\tgeneration: 1,\n", "\t\t\tspecReplicas: 2,\n", "\t\t\tmaxUnavailable: intOrStringP(1),\n", "\t\t\tstatus: extensions.DeploymentStatus{\n", "\t\t\t\tObservedGeneration: 1,\n", "\t\t\t\tReplicas: 2,\n", "\t\t\t\tUpdatedReplicas: 2,\n", "\t\t\t\tAvailableReplicas: 1,\n", "\t\t\t\tUnavailableReplicas: 0,\n", "\t\t\t},\n", "\n", "\t\t\tmsg: \"deployment \\\"foo\\\" successfully rolled out\\n\",\n", "\t\t\tdone: true,\n", "\t\t},\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 112 }
apiVersion: v1 items: - apiVersion: v1 kind: Service metadata: labels: app: svc1 name: svc1 spec: ports: - name: "81" port: 81 protocol: TCP targetPort: 81 selector: app: svc1 sessionAffinity: None type: ClusterIP - apiVersion: v1 kind: Service metadata: labels: app: svc2 name: svc2 namespace: edit-test spec: ports: - name: "80" port: 80 protocol: TCP targetPort: 80 selector: app: svc2 sessionAffinity: None type: ClusterIP kind: List metadata: {} resourceVersion: "" selfLink: ""
pkg/kubectl/cmd/testdata/edit/testcase-create-list/svc.yaml
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017471534374635667, 0.0001728829665808007, 0.0001721178414300084, 0.00017234931874554604, 0.000001062190676748287 ]
{ "id": 8, "code_window": [ "\n", "\t\t\tmsg: \"Waiting for deployment spec update to be observed...\\n\",\n", "\t\t\tdone: false,\n", "\t\t},\n", "\t\t{\n", "\t\t\tgeneration: 1,\n", "\t\t\tspecReplicas: 2,\n", "\t\t\tmaxUnavailable: intOrStringP(1),\n", "\t\t\tstatus: extensions.DeploymentStatus{\n", "\t\t\t\tObservedGeneration: 1,\n", "\t\t\t\tReplicas: 2,\n", "\t\t\t\tUpdatedReplicas: 2,\n", "\t\t\t\tAvailableReplicas: 1,\n", "\t\t\t\tUnavailableReplicas: 0,\n", "\t\t\t},\n", "\n", "\t\t\tmsg: \"deployment \\\"foo\\\" successfully rolled out\\n\",\n", "\t\t\tdone: true,\n", "\t\t},\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 112 }
// +build !windows package system import ( "os" "path/filepath" ) // MkdirAll creates a directory named path along with any necessary parents, // with permission specified by attribute perm for all dir created. func MkdirAll(path string, perm os.FileMode) error { return os.MkdirAll(path, perm) } // IsAbs is a platform-specific wrapper for filepath.IsAbs. func IsAbs(path string) bool { return filepath.IsAbs(path) }
vendor/github.com/docker/docker/pkg/system/filesys.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00016350818623322994, 0.0001626076700631529, 0.00016170715389307588, 0.0001626076700631529, 9.005161700770259e-7 ]
{ "id": 9, "code_window": [ "\t}\n", "\n", "\tfor i := range tests {\n", "\t\ttest := tests[i]\n", "\t\tt.Logf(\"testing scenario %d\", i)\n", "\t\td := &extensions.Deployment{\n", "\t\t\tObjectMeta: metav1.ObjectMeta{\n", "\t\t\t\tNamespace: \"bar\",\n", "\t\t\t\tName: \"foo\",\n", "\t\t\t\tUID: \"8764ae47-9092-11e4-8393-42010af018ff\",\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tfor _, test := range tests {\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 129 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.998085618019104, 0.1944446861743927, 0.0001647173339733854, 0.0001780986785888672, 0.37185919284820557 ]
{ "id": 9, "code_window": [ "\t}\n", "\n", "\tfor i := range tests {\n", "\t\ttest := tests[i]\n", "\t\tt.Logf(\"testing scenario %d\", i)\n", "\t\td := &extensions.Deployment{\n", "\t\t\tObjectMeta: metav1.ObjectMeta{\n", "\t\t\t\tNamespace: \"bar\",\n", "\t\t\t\tName: \"foo\",\n", "\t\t\t\tUID: \"8764ae47-9092-11e4-8393-42010af018ff\",\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tfor _, test := range tests {\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 129 }
// Copyright 2014 Google Inc. All Rights Reserved. // // 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 raw import ( "flag" "fmt" "github.com/google/cadvisor/container" "github.com/google/cadvisor/container/common" "github.com/google/cadvisor/container/libcontainer" "github.com/google/cadvisor/fs" info "github.com/google/cadvisor/info/v1" watch "github.com/google/cadvisor/manager/watcher" "github.com/golang/glog" ) var dockerOnly = flag.Bool("docker_only", false, "Only report docker containers in addition to root stats") type rawFactory struct { // Factory for machine information. machineInfoFactory info.MachineInfoFactory // Information about the cgroup subsystems. cgroupSubsystems *libcontainer.CgroupSubsystems // Information about mounted filesystems. fsInfo fs.FsInfo // Watcher for inotify events. watcher *common.InotifyWatcher // List of metrics to be ignored. ignoreMetrics map[container.MetricKind]struct{} } func (self *rawFactory) String() string { return "raw" } func (self *rawFactory) NewContainerHandler(name string, inHostNamespace bool) (container.ContainerHandler, error) { rootFs := "/" if !inHostNamespace { rootFs = "/rootfs" } return newRawContainerHandler(name, self.cgroupSubsystems, self.machineInfoFactory, self.fsInfo, self.watcher, rootFs, self.ignoreMetrics) } // The raw factory can handle any container. If --docker_only is set to false, non-docker containers are ignored. func (self *rawFactory) CanHandleAndAccept(name string) (bool, bool, error) { accept := name == "/" || !*dockerOnly return true, accept, nil } func (self *rawFactory) DebugInfo() map[string][]string { return common.DebugInfo(self.watcher.GetWatches()) } func Register(machineInfoFactory info.MachineInfoFactory, fsInfo fs.FsInfo, ignoreMetrics map[container.MetricKind]struct{}) error { cgroupSubsystems, err := libcontainer.GetCgroupSubsystems() if err != nil { return fmt.Errorf("failed to get cgroup subsystems: %v", err) } if len(cgroupSubsystems.Mounts) == 0 { return fmt.Errorf("failed to find supported cgroup mounts for the raw factory") } watcher, err := common.NewInotifyWatcher() if err != nil { return err } glog.Infof("Registering Raw factory") factory := &rawFactory{ machineInfoFactory: machineInfoFactory, fsInfo: fsInfo, cgroupSubsystems: &cgroupSubsystems, watcher: watcher, ignoreMetrics: ignoreMetrics, } container.RegisterContainerHandlerFactory(factory, []watch.ContainerWatchSource{watch.Raw}) return nil }
vendor/github.com/google/cadvisor/container/raw/factory.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0001777641155058518, 0.00017242744797840714, 0.00016448175301775336, 0.00017308531096205115, 0.000004247119250067044 ]
{ "id": 9, "code_window": [ "\t}\n", "\n", "\tfor i := range tests {\n", "\t\ttest := tests[i]\n", "\t\tt.Logf(\"testing scenario %d\", i)\n", "\t\td := &extensions.Deployment{\n", "\t\t\tObjectMeta: metav1.ObjectMeta{\n", "\t\t\t\tNamespace: \"bar\",\n", "\t\t\t\tName: \"foo\",\n", "\t\t\t\tUID: \"8764ae47-9092-11e4-8393-42010af018ff\",\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tfor _, test := range tests {\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 129 }
/* Copyright 2017 The Kubernetes Authors. 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 token import ( "strconv" "testing" "time" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" kubeconfigutil "k8s.io/kubernetes/cmd/kubeadm/app/util/kubeconfig" ) func TestRunForEndpointsAndReturnFirst(t *testing.T) { tests := []struct { endpoints []string expectedEndpoint string }{ { endpoints: []string{"1", "2", "3"}, expectedEndpoint: "1", }, { endpoints: []string{"6", "5"}, expectedEndpoint: "5", }, { endpoints: []string{"10", "4"}, expectedEndpoint: "4", }, } for _, rt := range tests { returnKubeConfig := runForEndpointsAndReturnFirst(rt.endpoints, func(endpoint string) (*clientcmdapi.Config, error) { timeout, _ := strconv.Atoi(endpoint) time.Sleep(time.Second * time.Duration(timeout)) return kubeconfigutil.CreateBasic(endpoint, "foo", "foo", []byte{}), nil }) endpoint := returnKubeConfig.Clusters[returnKubeConfig.Contexts[returnKubeConfig.CurrentContext].Cluster].Server if endpoint != rt.expectedEndpoint { t.Errorf( "failed TestRunForEndpointsAndReturnFirst:\n\texpected: %s\n\t actual: %s", endpoint, rt.expectedEndpoint, ) } } }
cmd/kubeadm/app/discovery/token/token_test.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.013938254676759243, 0.0023279848974198103, 0.0001718901767162606, 0.0001782979816198349, 0.004761213902384043 ]
{ "id": 9, "code_window": [ "\t}\n", "\n", "\tfor i := range tests {\n", "\t\ttest := tests[i]\n", "\t\tt.Logf(\"testing scenario %d\", i)\n", "\t\td := &extensions.Deployment{\n", "\t\t\tObjectMeta: metav1.ObjectMeta{\n", "\t\t\t\tNamespace: \"bar\",\n", "\t\t\t\tName: \"foo\",\n", "\t\t\t\tUID: \"8764ae47-9092-11e4-8393-42010af018ff\",\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tfor _, test := range tests {\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 129 }
{ "plugin": "filelog", "pluginConfig": { "timestamp": "dummy", "message": "dummy", "timestampFormat": "dummy" }, "logPath": "/dev/null", "lookback": "10m", "bufferSize": 10, "source": "kernel-monitor", "conditions": [], "rules": [] }
test/kubemark/resources/kernel-monitor.json
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.000177097535924986, 0.00017494198982603848, 0.00017278642917517573, 0.00017494198982603848, 0.000002155553374905139 ]
{ "id": 10, "code_window": [ "\t\t\t\tGeneration: test.generation,\n", "\t\t\t},\n", "\t\t\tSpec: extensions.DeploymentSpec{\n", "\t\t\t\tStrategy: extensions.DeploymentStrategy{\n", "\t\t\t\t\tType: extensions.RollingUpdateDeploymentStrategyType,\n", "\t\t\t\t\tRollingUpdate: &extensions.RollingUpdateDeployment{\n", "\t\t\t\t\t\tMaxSurge: *intOrStringP(1),\n", "\t\t\t\t\t},\n", "\t\t\t\t},\n", "\t\t\t\tReplicas: test.specReplicas,\n", "\t\t\t},\n", "\t\t\tStatus: test.status,\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 140 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.05649162083864212, 0.0024279740173369646, 0.00016406243958044797, 0.00020671692618634552, 0.009914012625813484 ]
{ "id": 10, "code_window": [ "\t\t\t\tGeneration: test.generation,\n", "\t\t\t},\n", "\t\t\tSpec: extensions.DeploymentSpec{\n", "\t\t\t\tStrategy: extensions.DeploymentStrategy{\n", "\t\t\t\t\tType: extensions.RollingUpdateDeploymentStrategyType,\n", "\t\t\t\t\tRollingUpdate: &extensions.RollingUpdateDeployment{\n", "\t\t\t\t\t\tMaxSurge: *intOrStringP(1),\n", "\t\t\t\t\t},\n", "\t\t\t\t},\n", "\t\t\t\tReplicas: test.specReplicas,\n", "\t\t\t},\n", "\t\t\tStatus: test.status,\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 140 }
/* Copyright 2016 The Kubernetes Authors. 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 azure import ( "encoding/json" "io" "io/ioutil" "net/http" "sync" "k8s.io/kubernetes/pkg/cloudprovider" ) const instanceInfoURL = "http://169.254.169.254/metadata/v1/InstanceInfo" var faultMutex = &sync.Mutex{} var faultDomain *string type instanceInfo struct { ID string `json:"ID"` UpdateDomain string `json:"UD"` FaultDomain string `json:"FD"` } // GetZone returns the Zone containing the current failure zone and locality region that the program is running in func (az *Cloud) GetZone() (cloudprovider.Zone, error) { faultMutex.Lock() if faultDomain == nil { var err error faultDomain, err = fetchFaultDomain() if err != nil { return cloudprovider.Zone{}, err } } zone := cloudprovider.Zone{ FailureDomain: *faultDomain, Region: az.Location, } faultMutex.Unlock() return zone, nil } func fetchFaultDomain() (*string, error) { resp, err := http.Get(instanceInfoURL) if err != nil { return nil, err } defer resp.Body.Close() return readFaultDomain(resp.Body) } func readFaultDomain(reader io.Reader) (*string, error) { var instanceInfo instanceInfo body, err := ioutil.ReadAll(reader) if err != nil { return nil, err } err = json.Unmarshal(body, &instanceInfo) if err != nil { return nil, err } return &instanceInfo.FaultDomain, nil }
pkg/cloudprovider/providers/azure/azure_zones.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0001787466899259016, 0.00017310553812421858, 0.0001704646274447441, 0.0001718213752610609, 0.00000318137767862936 ]
{ "id": 10, "code_window": [ "\t\t\t\tGeneration: test.generation,\n", "\t\t\t},\n", "\t\t\tSpec: extensions.DeploymentSpec{\n", "\t\t\t\tStrategy: extensions.DeploymentStrategy{\n", "\t\t\t\t\tType: extensions.RollingUpdateDeploymentStrategyType,\n", "\t\t\t\t\tRollingUpdate: &extensions.RollingUpdateDeployment{\n", "\t\t\t\t\t\tMaxSurge: *intOrStringP(1),\n", "\t\t\t\t\t},\n", "\t\t\t\t},\n", "\t\t\t\tReplicas: test.specReplicas,\n", "\t\t\t},\n", "\t\t\tStatus: test.status,\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 140 }
/* Copyright 2017 The Kubernetes Authors. 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. */ // This package is generated by client-gen with custom arguments. // Package fake has the automatically generated clients. package fake
staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/fake/doc.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017859251238405704, 0.00017640892474446446, 0.00017321102495770901, 0.0001774232368916273, 0.0000023110926576919155 ]
{ "id": 10, "code_window": [ "\t\t\t\tGeneration: test.generation,\n", "\t\t\t},\n", "\t\t\tSpec: extensions.DeploymentSpec{\n", "\t\t\t\tStrategy: extensions.DeploymentStrategy{\n", "\t\t\t\t\tType: extensions.RollingUpdateDeploymentStrategyType,\n", "\t\t\t\t\tRollingUpdate: &extensions.RollingUpdateDeployment{\n", "\t\t\t\t\t\tMaxSurge: *intOrStringP(1),\n", "\t\t\t\t\t},\n", "\t\t\t\t},\n", "\t\t\t\tReplicas: test.specReplicas,\n", "\t\t\t},\n", "\t\t\tStatus: test.status,\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 140 }
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.2 package language import "sort" var sortStable = sort.Stable
vendor/golang.org/x/text/language/go1_2.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017796661995816976, 0.00017433208995498717, 0.00017069754539988935, 0.00017433208995498717, 0.000003634537279140204 ]
{ "id": 11, "code_window": [ "\t\t\t\tReplicas: test.specReplicas,\n", "\t\t\t},\n", "\t\t\tStatus: test.status,\n", "\t\t}\n", "\t\tif test.maxUnavailable != nil {\n", "\t\t\td.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable\n", "\t\t}\n", "\t\tclient := fake.NewSimpleClientset(d).Extensions()\n", "\t\tdsv := &DeploymentStatusViewer{c: client}\n", "\t\tmsg, done, err := dsv.Status(\"bar\", \"foo\", 0)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 150 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.9980151653289795, 0.1394057422876358, 0.00016369897639378905, 0.0001950371079146862, 0.33342453837394714 ]
{ "id": 11, "code_window": [ "\t\t\t\tReplicas: test.specReplicas,\n", "\t\t\t},\n", "\t\t\tStatus: test.status,\n", "\t\t}\n", "\t\tif test.maxUnavailable != nil {\n", "\t\t\td.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable\n", "\t\t}\n", "\t\tclient := fake.NewSimpleClientset(d).Extensions()\n", "\t\tdsv := &DeploymentStatusViewer{c: client}\n", "\t\tmsg, done, err := dsv.Status(\"bar\", \"foo\", 0)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 150 }
/* Copyright 2016 The Kubernetes Authors. 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 cm import ( "fmt" "io/ioutil" "os" "path" "strings" "github.com/golang/glog" "k8s.io/apimachinery/pkg/types" utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/qos" ) const ( podCgroupNamePrefix = "pod" ) // podContainerManagerImpl implements podContainerManager interface. // It is the general implementation which allows pod level container // management if qos Cgroup is enabled. type podContainerManagerImpl struct { // qosContainersInfo hold absolute paths of the top level qos containers qosContainersInfo QOSContainersInfo // Stores the mounted cgroup subsystems subsystems *CgroupSubsystems // cgroupManager is the cgroup Manager Object responsible for managing all // pod cgroups. cgroupManager CgroupManager } // Make sure that podContainerManagerImpl implements the PodContainerManager interface var _ PodContainerManager = &podContainerManagerImpl{} // applyLimits sets pod cgroup resource limits // It also updates the resource limits on top level qos containers. func (m *podContainerManagerImpl) applyLimits(pod *v1.Pod) error { // This function will house the logic for setting the resource parameters // on the pod container config and updating top level qos container configs return nil } // Exists checks if the pod's cgroup already exists func (m *podContainerManagerImpl) Exists(pod *v1.Pod) bool { podContainerName, _ := m.GetPodContainerName(pod) return m.cgroupManager.Exists(podContainerName) } // EnsureExists takes a pod as argument and makes sure that // pod cgroup exists if qos cgroup hierarchy flag is enabled. // If the pod level container doesen't already exist it is created. func (m *podContainerManagerImpl) EnsureExists(pod *v1.Pod) error { podContainerName, _ := m.GetPodContainerName(pod) // check if container already exist alreadyExists := m.Exists(pod) if !alreadyExists { // Create the pod container containerConfig := &CgroupConfig{ Name: podContainerName, ResourceParameters: ResourceConfigForPod(pod), } if err := m.cgroupManager.Create(containerConfig); err != nil { return fmt.Errorf("failed to create container for %v : %v", podContainerName, err) } } // Apply appropriate resource limits on the pod container // Top level qos containers limits are not updated // until we figure how to maintain the desired state in the kubelet. // Because maintaining the desired state is difficult without checkpointing. if err := m.applyLimits(pod); err != nil { return fmt.Errorf("failed to apply resource limits on container for %v : %v", podContainerName, err) } return nil } // GetPodContainerName returns the CgroupName identifer, and its literal cgroupfs form on the host. func (m *podContainerManagerImpl) GetPodContainerName(pod *v1.Pod) (CgroupName, string) { podQOS := qos.GetPodQOS(pod) // Get the parent QOS container name var parentContainer string switch podQOS { case v1.PodQOSGuaranteed: parentContainer = m.qosContainersInfo.Guaranteed case v1.PodQOSBurstable: parentContainer = m.qosContainersInfo.Burstable case v1.PodQOSBestEffort: parentContainer = m.qosContainersInfo.BestEffort } podContainer := podCgroupNamePrefix + string(pod.UID) // Get the absolute path of the cgroup cgroupName := (CgroupName)(path.Join(parentContainer, podContainer)) // Get the literal cgroupfs name cgroupfsName := m.cgroupManager.Name(cgroupName) return cgroupName, cgroupfsName } // Scan through the whole cgroup directory and kill all processes either // attached to the pod cgroup or to a container cgroup under the pod cgroup func (m *podContainerManagerImpl) tryKillingCgroupProcesses(podCgroup CgroupName) error { pidsToKill := m.cgroupManager.Pids(podCgroup) // No pids charged to the terminated pod cgroup return if len(pidsToKill) == 0 { return nil } var errlist []error // os.Kill often errors out, // We try killing all the pids multiple times for i := 0; i < 5; i++ { if i != 0 { glog.V(3).Infof("Attempt %v failed to kill all unwanted process. Retyring", i) } errlist = []error{} for _, pid := range pidsToKill { p, err := os.FindProcess(pid) if err != nil { // Process not running anymore, do nothing continue } glog.V(3).Infof("Attempt to kill process with pid: %v", pid) if err := p.Kill(); err != nil { glog.V(3).Infof("failed to kill process with pid: %v", pid) errlist = append(errlist, err) } } if len(errlist) == 0 { glog.V(3).Infof("successfully killed all unwanted processes.") return nil } } return utilerrors.NewAggregate(errlist) } // Destroy destroys the pod container cgroup paths func (m *podContainerManagerImpl) Destroy(podCgroup CgroupName) error { // Try killing all the processes attached to the pod cgroup if err := m.tryKillingCgroupProcesses(podCgroup); err != nil { glog.V(3).Infof("failed to kill all the processes attached to the %v cgroups", podCgroup) return fmt.Errorf("failed to kill all the processes attached to the %v cgroups : %v", podCgroup, err) } // Now its safe to remove the pod's cgroup containerConfig := &CgroupConfig{ Name: podCgroup, ResourceParameters: &ResourceConfig{}, } if err := m.cgroupManager.Destroy(containerConfig); err != nil { return fmt.Errorf("failed to delete cgroup paths for %v : %v", podCgroup, err) } return nil } // ReduceCPULimits reduces the CPU CFS values to the minimum amount of shares. func (m *podContainerManagerImpl) ReduceCPULimits(podCgroup CgroupName) error { return m.cgroupManager.ReduceCPULimits(podCgroup) } // GetAllPodsFromCgroups scans through all the subsytems of pod cgroups // Get list of pods whose cgroup still exist on the cgroup mounts func (m *podContainerManagerImpl) GetAllPodsFromCgroups() (map[types.UID]CgroupName, error) { // Map for storing all the found pods on the disk foundPods := make(map[types.UID]CgroupName) qosContainersList := [3]string{m.qosContainersInfo.BestEffort, m.qosContainersInfo.Burstable, m.qosContainersInfo.Guaranteed} // Scan through all the subsystem mounts // and through each QoS cgroup directory for each subsystem mount // If a pod cgroup exists in even a single subsystem mount // we will attempt to delete it for _, val := range m.subsystems.MountPoints { for _, qosContainerName := range qosContainersList { // get the subsystems QoS cgroup absolute name qcConversion := m.cgroupManager.Name(CgroupName(qosContainerName)) qc := path.Join(val, qcConversion) dirInfo, err := ioutil.ReadDir(qc) if err != nil { if os.IsNotExist(err) { continue } return nil, fmt.Errorf("failed to read the cgroup directory %v : %v", qc, err) } for i := range dirInfo { // its not a directory, so continue on... if !dirInfo[i].IsDir() { continue } // convert the concrete cgroupfs name back to an internal identifier // this is needed to handle path conversion for systemd environments. // we pass the fully qualified path so decoding can work as expected // since systemd encodes the path in each segment. cgroupfsPath := path.Join(qcConversion, dirInfo[i].Name()) internalPath := m.cgroupManager.CgroupName(cgroupfsPath) // we only care about base segment of the converted path since that // is what we are reading currently to know if it is a pod or not. basePath := path.Base(string(internalPath)) if !strings.Contains(basePath, podCgroupNamePrefix) { continue } // we then split the name on the pod prefix to determine the uid parts := strings.Split(basePath, podCgroupNamePrefix) // the uid is missing, so we log the unexpected cgroup not of form pod<uid> if len(parts) != 2 { glog.Errorf("pod cgroup manager ignoring unexpected cgroup %v because it is not a pod", cgroupfsPath) continue } podUID := parts[1] foundPods[types.UID(podUID)] = internalPath } } } return foundPods, nil } // podContainerManagerNoop implements podContainerManager interface. // It is a no-op implementation and basically does nothing // podContainerManagerNoop is used in case the QoS cgroup Hierarchy is not // enabled, so Exists() returns true always as the cgroupRoot // is expected to always exist. type podContainerManagerNoop struct { cgroupRoot CgroupName } // Make sure that podContainerManagerStub implements the PodContainerManager interface var _ PodContainerManager = &podContainerManagerNoop{} func (m *podContainerManagerNoop) Exists(_ *v1.Pod) bool { return true } func (m *podContainerManagerNoop) EnsureExists(_ *v1.Pod) error { return nil } func (m *podContainerManagerNoop) GetPodContainerName(_ *v1.Pod) (CgroupName, string) { return m.cgroupRoot, string(m.cgroupRoot) } func (m *podContainerManagerNoop) GetPodContainerNameForDriver(_ *v1.Pod) string { return "" } // Destroy destroys the pod container cgroup paths func (m *podContainerManagerNoop) Destroy(_ CgroupName) error { return nil } func (m *podContainerManagerNoop) ReduceCPULimits(_ CgroupName) error { return nil } func (m *podContainerManagerNoop) GetAllPodsFromCgroups() (map[types.UID]CgroupName, error) { return nil, nil }
pkg/kubelet/cm/pod_container_manager_linux.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017907987057697028, 0.0001712130178930238, 0.0001618034002603963, 0.00017187712364830077, 0.00000448608852821053 ]
{ "id": 11, "code_window": [ "\t\t\t\tReplicas: test.specReplicas,\n", "\t\t\t},\n", "\t\t\tStatus: test.status,\n", "\t\t}\n", "\t\tif test.maxUnavailable != nil {\n", "\t\t\td.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable\n", "\t\t}\n", "\t\tclient := fake.NewSimpleClientset(d).Extensions()\n", "\t\tdsv := &DeploymentStatusViewer{c: client}\n", "\t\tmsg, done, err := dsv.Status(\"bar\", \"foo\", 0)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 150 }
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "errors" "fmt" "io" ) // clientAuthenticate authenticates with the remote server. See RFC 4252. func (c *connection) clientAuthenticate(config *ClientConfig) error { // initiate user auth session if err := c.transport.writePacket(Marshal(&serviceRequestMsg{serviceUserAuth})); err != nil { return err } packet, err := c.transport.readPacket() if err != nil { return err } var serviceAccept serviceAcceptMsg if err := Unmarshal(packet, &serviceAccept); err != nil { return err } // during the authentication phase the client first attempts the "none" method // then any untried methods suggested by the server. tried := make(map[string]bool) var lastMethods []string for auth := AuthMethod(new(noneAuth)); auth != nil; { ok, methods, err := auth.auth(c.transport.getSessionID(), config.User, c.transport, config.Rand) if err != nil { return err } if ok { // success return nil } tried[auth.method()] = true if methods == nil { methods = lastMethods } lastMethods = methods auth = nil findNext: for _, a := range config.Auth { candidateMethod := a.method() if tried[candidateMethod] { continue } for _, meth := range methods { if meth == candidateMethod { auth = a break findNext } } } } return fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", keys(tried)) } func keys(m map[string]bool) []string { s := make([]string, 0, len(m)) for key := range m { s = append(s, key) } return s } // An AuthMethod represents an instance of an RFC 4252 authentication method. type AuthMethod interface { // auth authenticates user over transport t. // Returns true if authentication is successful. // If authentication is not successful, a []string of alternative // method names is returned. If the slice is nil, it will be ignored // and the previous set of possible methods will be reused. auth(session []byte, user string, p packetConn, rand io.Reader) (bool, []string, error) // method returns the RFC 4252 method name. method() string } // "none" authentication, RFC 4252 section 5.2. type noneAuth int func (n *noneAuth) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { if err := c.writePacket(Marshal(&userAuthRequestMsg{ User: user, Service: serviceSSH, Method: "none", })); err != nil { return false, nil, err } return handleAuthResponse(c) } func (n *noneAuth) method() string { return "none" } // passwordCallback is an AuthMethod that fetches the password through // a function call, e.g. by prompting the user. type passwordCallback func() (password string, err error) func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { type passwordAuthMsg struct { User string `sshtype:"50"` Service string Method string Reply bool Password string } pw, err := cb() // REVIEW NOTE: is there a need to support skipping a password attempt? // The program may only find out that the user doesn't have a password // when prompting. if err != nil { return false, nil, err } if err := c.writePacket(Marshal(&passwordAuthMsg{ User: user, Service: serviceSSH, Method: cb.method(), Reply: false, Password: pw, })); err != nil { return false, nil, err } return handleAuthResponse(c) } func (cb passwordCallback) method() string { return "password" } // Password returns an AuthMethod using the given password. func Password(secret string) AuthMethod { return passwordCallback(func() (string, error) { return secret, nil }) } // PasswordCallback returns an AuthMethod that uses a callback for // fetching a password. func PasswordCallback(prompt func() (secret string, err error)) AuthMethod { return passwordCallback(prompt) } type publickeyAuthMsg struct { User string `sshtype:"50"` Service string Method string // HasSig indicates to the receiver packet that the auth request is signed and // should be used for authentication of the request. HasSig bool Algoname string PubKey []byte // Sig is tagged with "rest" so Marshal will exclude it during // validateKey Sig []byte `ssh:"rest"` } // publicKeyCallback is an AuthMethod that uses a set of key // pairs for authentication. type publicKeyCallback func() ([]Signer, error) func (cb publicKeyCallback) method() string { return "publickey" } func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { // Authentication is performed in two stages. The first stage sends an // enquiry to test if each key is acceptable to the remote. The second // stage attempts to authenticate with the valid keys obtained in the // first stage. signers, err := cb() if err != nil { return false, nil, err } var validKeys []Signer for _, signer := range signers { if ok, err := validateKey(signer.PublicKey(), user, c); ok { validKeys = append(validKeys, signer) } else { if err != nil { return false, nil, err } } } // methods that may continue if this auth is not successful. var methods []string for _, signer := range validKeys { pub := signer.PublicKey() pubKey := pub.Marshal() sign, err := signer.Sign(rand, buildDataSignedForAuth(session, userAuthRequestMsg{ User: user, Service: serviceSSH, Method: cb.method(), }, []byte(pub.Type()), pubKey)) if err != nil { return false, nil, err } // manually wrap the serialized signature in a string s := Marshal(sign) sig := make([]byte, stringLength(len(s))) marshalString(sig, s) msg := publickeyAuthMsg{ User: user, Service: serviceSSH, Method: cb.method(), HasSig: true, Algoname: pub.Type(), PubKey: pubKey, Sig: sig, } p := Marshal(&msg) if err := c.writePacket(p); err != nil { return false, nil, err } var success bool success, methods, err = handleAuthResponse(c) if err != nil { return false, nil, err } if success { return success, methods, err } } return false, methods, nil } // validateKey validates the key provided is acceptable to the server. func validateKey(key PublicKey, user string, c packetConn) (bool, error) { pubKey := key.Marshal() msg := publickeyAuthMsg{ User: user, Service: serviceSSH, Method: "publickey", HasSig: false, Algoname: key.Type(), PubKey: pubKey, } if err := c.writePacket(Marshal(&msg)); err != nil { return false, err } return confirmKeyAck(key, c) } func confirmKeyAck(key PublicKey, c packetConn) (bool, error) { pubKey := key.Marshal() algoname := key.Type() for { packet, err := c.readPacket() if err != nil { return false, err } switch packet[0] { case msgUserAuthBanner: // TODO(gpaul): add callback to present the banner to the user case msgUserAuthPubKeyOk: var msg userAuthPubKeyOkMsg if err := Unmarshal(packet, &msg); err != nil { return false, err } if msg.Algo != algoname || !bytes.Equal(msg.PubKey, pubKey) { return false, nil } return true, nil case msgUserAuthFailure: return false, nil default: return false, unexpectedMessageError(msgUserAuthSuccess, packet[0]) } } } // PublicKeys returns an AuthMethod that uses the given key // pairs. func PublicKeys(signers ...Signer) AuthMethod { return publicKeyCallback(func() ([]Signer, error) { return signers, nil }) } // PublicKeysCallback returns an AuthMethod that runs the given // function to obtain a list of key pairs. func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod { return publicKeyCallback(getSigners) } // handleAuthResponse returns whether the preceding authentication request succeeded // along with a list of remaining authentication methods to try next and // an error if an unexpected response was received. func handleAuthResponse(c packetConn) (bool, []string, error) { for { packet, err := c.readPacket() if err != nil { return false, nil, err } switch packet[0] { case msgUserAuthBanner: // TODO: add callback to present the banner to the user case msgUserAuthFailure: var msg userAuthFailureMsg if err := Unmarshal(packet, &msg); err != nil { return false, nil, err } return false, msg.Methods, nil case msgUserAuthSuccess: return true, nil, nil default: return false, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0]) } } } // KeyboardInteractiveChallenge should print questions, optionally // disabling echoing (e.g. for passwords), and return all the answers. // Challenge may be called multiple times in a single session. After // successful authentication, the server may send a challenge with no // questions, for which the user and instruction messages should be // printed. RFC 4256 section 3.3 details how the UI should behave for // both CLI and GUI environments. type KeyboardInteractiveChallenge func(user, instruction string, questions []string, echos []bool) (answers []string, err error) // KeyboardInteractive returns a AuthMethod using a prompt/response // sequence controlled by the server. func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod { return challenge } func (cb KeyboardInteractiveChallenge) method() string { return "keyboard-interactive" } func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { type initiateMsg struct { User string `sshtype:"50"` Service string Method string Language string Submethods string } if err := c.writePacket(Marshal(&initiateMsg{ User: user, Service: serviceSSH, Method: "keyboard-interactive", })); err != nil { return false, nil, err } for { packet, err := c.readPacket() if err != nil { return false, nil, err } // like handleAuthResponse, but with less options. switch packet[0] { case msgUserAuthBanner: // TODO: Print banners during userauth. continue case msgUserAuthInfoRequest: // OK case msgUserAuthFailure: var msg userAuthFailureMsg if err := Unmarshal(packet, &msg); err != nil { return false, nil, err } return false, msg.Methods, nil case msgUserAuthSuccess: return true, nil, nil default: return false, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0]) } var msg userAuthInfoRequestMsg if err := Unmarshal(packet, &msg); err != nil { return false, nil, err } // Manually unpack the prompt/echo pairs. rest := msg.Prompts var prompts []string var echos []bool for i := 0; i < int(msg.NumPrompts); i++ { prompt, r, ok := parseString(rest) if !ok || len(r) == 0 { return false, nil, errors.New("ssh: prompt format error") } prompts = append(prompts, string(prompt)) echos = append(echos, r[0] != 0) rest = r[1:] } if len(rest) != 0 { return false, nil, errors.New("ssh: extra data following keyboard-interactive pairs") } answers, err := cb(msg.User, msg.Instruction, prompts, echos) if err != nil { return false, nil, err } if len(answers) != len(prompts) { return false, nil, errors.New("ssh: not enough answers from keyboard-interactive callback") } responseLength := 1 + 4 for _, a := range answers { responseLength += stringLength(len(a)) } serialized := make([]byte, responseLength) p := serialized p[0] = msgUserAuthInfoResponse p = p[1:] p = marshalUint32(p, uint32(len(answers))) for _, a := range answers { p = marshalString(p, []byte(a)) } if err := c.writePacket(serialized); err != nil { return false, nil, err } } } type retryableAuthMethod struct { authMethod AuthMethod maxTries int } func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader) (ok bool, methods []string, err error) { for i := 0; r.maxTries <= 0 || i < r.maxTries; i++ { ok, methods, err = r.authMethod.auth(session, user, c, rand) if ok || err != nil { // either success or error terminate return ok, methods, err } } return ok, methods, err } func (r *retryableAuthMethod) method() string { return r.authMethod.method() } // RetryableAuthMethod is a decorator for other auth methods enabling them to // be retried up to maxTries before considering that AuthMethod itself failed. // If maxTries is <= 0, will retry indefinitely // // This is useful for interactive clients using challenge/response type // authentication (e.g. Keyboard-Interactive, Password, etc) where the user // could mistype their response resulting in the server issuing a // SSH_MSG_USERAUTH_FAILURE (rfc4252 #8 [password] and rfc4256 #3.4 // [keyboard-interactive]); Without this decorator, the non-retryable // AuthMethod would be removed from future consideration, and never tried again // (and so the user would never be able to retry their entry). func RetryableAuthMethod(auth AuthMethod, maxTries int) AuthMethod { return &retryableAuthMethod{authMethod: auth, maxTries: maxTries} }
vendor/golang.org/x/crypto/ssh/client_auth.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0003403269511181861, 0.0001725887559587136, 0.00016040564514696598, 0.00016902570496313274, 0.000024786131689324975 ]
{ "id": 11, "code_window": [ "\t\t\t\tReplicas: test.specReplicas,\n", "\t\t\t},\n", "\t\t\tStatus: test.status,\n", "\t\t}\n", "\t\tif test.maxUnavailable != nil {\n", "\t\t\td.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable\n", "\t\t}\n", "\t\tclient := fake.NewSimpleClientset(d).Extensions()\n", "\t\tdsv := &DeploymentStatusViewer{c: client}\n", "\t\tmsg, done, err := dsv.Status(\"bar\", \"foo\", 0)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 150 }
This file is autogenerated, but we've stopped checking such files into the repository to reduce the need for rebases. Please run hack/generate-docs.sh to populate this file.
docs/yaml/kubectl/kubectl_drain.yaml
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017620011931285262, 0.00017620011931285262, 0.00017620011931285262, 0.00017620011931285262, 0 ]
{ "id": 12, "code_window": [ "\t\tclient := fake.NewSimpleClientset(d).Extensions()\n", "\t\tdsv := &DeploymentStatusViewer{c: client}\n", "\t\tmsg, done, err := dsv.Status(\"bar\", \"foo\", 0)\n", "\t\tif err != nil {\n", "\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n", "\t\t}\n", "\t\tif done != test.done || msg != test.msg {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\tt.Fatalf(\"DeploymentStatusViewer.Status(): %v\", err)\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 157 }
/* Copyright 2016 The Kubernetes Authors. 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 kubectl import ( "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" intstrutil "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" ) func intOrStringP(i int) *intstrutil.IntOrString { intstr := intstrutil.FromInt(i) return &intstr } func TestDeploymentStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 specReplicas int32 maxUnavailable *intstrutil.IntOrString status extensions.DeploymentStatus msg string done bool }{ { generation: 0, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 1, UpdatedReplicas: 0, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new replicas have been updated...\n", done: false, }, { generation: 1, specReplicas: 1, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 1, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for rollout to finish: 1 old replicas are pending termination...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(0), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated replicas are available (minimum required: 2)...\n", done: false, }, { generation: 1, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, { generation: 2, specReplicas: 2, status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 2, UnavailableReplicas: 0, }, msg: "Waiting for deployment spec update to be observed...\n", done: false, }, { generation: 1, specReplicas: 2, maxUnavailable: intOrStringP(1), status: extensions.DeploymentStatus{ ObservedGeneration: 1, Replicas: 2, UpdatedReplicas: 2, AvailableReplicas: 1, UnavailableReplicas: 0, }, msg: "deployment \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ Type: extensions.RollingUpdateDeploymentStrategyType, RollingUpdate: &extensions.RollingUpdateDeployment{ MaxSurge: *intOrStringP(1), }, }, Replicas: test.specReplicas, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.Strategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DeploymentStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("deployment with generation %d, %d replicas specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, test.specReplicas, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatus(t *testing.T) { tests := []struct { generation int64 maxUnavailable *intstrutil.IntOrString status extensions.DaemonSetStatus msg string done bool }{ { generation: 0, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 0, DesiredNumberScheduled: 1, NumberAvailable: 0, }, msg: "Waiting for rollout to finish: 0 out of 1 new pods have been updated...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(0), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "Waiting for rollout to finish: 1 of 2 updated pods are available (minimum required: 2)...\n", done: false, }, { generation: 1, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, { generation: 2, status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 2, }, msg: "Waiting for daemon set spec update to be observed...\n", done: false, }, { generation: 1, maxUnavailable: intOrStringP(1), status: extensions.DaemonSetStatus{ ObservedGeneration: 1, UpdatedNumberScheduled: 2, DesiredNumberScheduled: 2, NumberAvailable: 1, }, msg: "daemon set \"foo\" successfully rolled out\n", done: true, }, } for i := range tests { test := tests[i] t.Logf("testing scenario %d", i) d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", Generation: test.generation, }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.RollingUpdateDaemonSetStrategyType, RollingUpdate: &extensions.RollingUpdateDaemonSet{}, }, }, Status: test.status, } if test.maxUnavailable != nil { d.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = *test.maxUnavailable } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) if err != nil { t.Fatalf("unexpected error: %v", err) } if done != test.done || msg != test.msg { t.Errorf("daemon set with generation %d, %d pods specified, and status:\n%+v\nreturned:\n%q, %t\nwant:\n%q, %t", test.generation, d.Status.DesiredNumberScheduled, test.status, msg, done, test.msg, test.done, ) } } } func TestDaemonSetStatusViewerStatusWithWrongUpdateStrategyType(t *testing.T) { d := &extensions.DaemonSet{ ObjectMeta: metav1.ObjectMeta{ Namespace: "bar", Name: "foo", UID: "8764ae47-9092-11e4-8393-42010af018ff", }, Spec: extensions.DaemonSetSpec{ UpdateStrategy: extensions.DaemonSetUpdateStrategy{ Type: extensions.OnDeleteDaemonSetStrategyType, }, }, } client := fake.NewSimpleClientset(d).Extensions() dsv := &DaemonSetStatusViewer{c: client} msg, done, err := dsv.Status("bar", "foo", 0) errMsg := "Status is available only for RollingUpdate strategy type" if err == nil || err.Error() != errMsg { t.Errorf("Status for daemon sets with UpdateStrategy type different than RollingUpdate should return error. Instead got: msg: %s\ndone: %t\n err: %v", msg, done, err) } }
pkg/kubectl/rollout_status_test.go
1
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.9990425705909729, 0.14244282245635986, 0.00016364699695259333, 0.0007231629570014775, 0.3326268196105957 ]
{ "id": 12, "code_window": [ "\t\tclient := fake.NewSimpleClientset(d).Extensions()\n", "\t\tdsv := &DeploymentStatusViewer{c: client}\n", "\t\tmsg, done, err := dsv.Status(\"bar\", \"foo\", 0)\n", "\t\tif err != nil {\n", "\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n", "\t\t}\n", "\t\tif done != test.done || msg != test.msg {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\tt.Fatalf(\"DeploymentStatusViewer.Status(): %v\", err)\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 157 }
/* Copyright 2015 The Kubernetes Authors. 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 conversion import ( "k8s.io/apimachinery/third_party/forked/golang/reflect" ) // The code for this type must be located in third_party, since it forks from // go std lib. But for convenience, we expose the type here, too. type Equalities struct { reflect.Equalities } // For convenience, panics on errors func EqualitiesOrDie(funcs ...interface{}) Equalities { e := Equalities{reflect.Equalities{}} if err := e.AddFuncs(funcs...); err != nil { panic(err) } return e }
staging/src/k8s.io/apimachinery/pkg/conversion/deep_equal.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0001791418471839279, 0.00017317227320745587, 0.00016814230184536427, 0.00017270247917622328, 0.000004732100478577195 ]
{ "id": 12, "code_window": [ "\t\tclient := fake.NewSimpleClientset(d).Extensions()\n", "\t\tdsv := &DeploymentStatusViewer{c: client}\n", "\t\tmsg, done, err := dsv.Status(\"bar\", \"foo\", 0)\n", "\t\tif err != nil {\n", "\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n", "\t\t}\n", "\t\tif done != test.done || msg != test.msg {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\tt.Fatalf(\"DeploymentStatusViewer.Status(): %v\", err)\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 157 }
/* Copyright 2017 The Kubernetes Authors. 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 fake import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" v1beta1 "k8s.io/kubernetes/pkg/apis/rbac/v1beta1" ) // FakeRoles implements RoleInterface type FakeRoles struct { Fake *FakeRbacV1beta1 ns string } var rolesResource = schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "roles"} func (c *FakeRoles) Create(role *v1beta1.Role) (result *v1beta1.Role, err error) { obj, err := c.Fake. Invokes(testing.NewCreateAction(rolesResource, c.ns, role), &v1beta1.Role{}) if obj == nil { return nil, err } return obj.(*v1beta1.Role), err } func (c *FakeRoles) Update(role *v1beta1.Role) (result *v1beta1.Role, err error) { obj, err := c.Fake. Invokes(testing.NewUpdateAction(rolesResource, c.ns, role), &v1beta1.Role{}) if obj == nil { return nil, err } return obj.(*v1beta1.Role), err } func (c *FakeRoles) Delete(name string, options *v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewDeleteAction(rolesResource, c.ns, name), &v1beta1.Role{}) return err } func (c *FakeRoles) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { action := testing.NewDeleteCollectionAction(rolesResource, c.ns, listOptions) _, err := c.Fake.Invokes(action, &v1beta1.RoleList{}) return err } func (c *FakeRoles) Get(name string, options v1.GetOptions) (result *v1beta1.Role, err error) { obj, err := c.Fake. Invokes(testing.NewGetAction(rolesResource, c.ns, name), &v1beta1.Role{}) if obj == nil { return nil, err } return obj.(*v1beta1.Role), err } func (c *FakeRoles) List(opts v1.ListOptions) (result *v1beta1.RoleList, err error) { obj, err := c.Fake. Invokes(testing.NewListAction(rolesResource, c.ns, opts), &v1beta1.RoleList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &v1beta1.RoleList{} for _, item := range obj.(*v1beta1.RoleList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } // Watch returns a watch.Interface that watches the requested roles. func (c *FakeRoles) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewWatchAction(rolesResource, c.ns, opts)) } // Patch applies the patch and returns the patched role. func (c *FakeRoles) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.Role, err error) { obj, err := c.Fake. Invokes(testing.NewPatchSubresourceAction(rolesResource, c.ns, name, data, subresources...), &v1beta1.Role{}) if obj == nil { return nil, err } return obj.(*v1beta1.Role), err }
pkg/client/clientset_generated/clientset/typed/rbac/v1beta1/fake/fake_role.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.00017918508092407137, 0.00016751674411352724, 0.000163470467668958, 0.0001655433006817475, 0.000004631466254068073 ]
{ "id": 12, "code_window": [ "\t\tclient := fake.NewSimpleClientset(d).Extensions()\n", "\t\tdsv := &DeploymentStatusViewer{c: client}\n", "\t\tmsg, done, err := dsv.Status(\"bar\", \"foo\", 0)\n", "\t\tif err != nil {\n", "\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n", "\t\t}\n", "\t\tif done != test.done || msg != test.msg {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\tt.Fatalf(\"DeploymentStatusViewer.Status(): %v\", err)\n" ], "file_path": "pkg/kubectl/rollout_status_test.go", "type": "replace", "edit_start_line_idx": 157 }
package jlexer import "fmt" // LexerError implements the error interface and represents all possible errors that can be // generated during parsing the JSON data. type LexerError struct { Reason string Offset int Data string } func (l *LexerError) Error() string { return fmt.Sprintf("parse error: %s near offset %d of '%s'", l.Reason, l.Offset, l.Data) }
vendor/github.com/mailru/easyjson/jlexer/error.go
0
https://github.com/kubernetes/kubernetes/commit/1923cc60c95943543f036a1c9633f3c4219c917f
[ 0.0002936081727966666, 0.00025274697691202164, 0.0002118857519235462, 0.00025274697691202164, 0.000040861210436560214 ]