Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

atc: behaviour: add ArchivePipeline endpoint #5346

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions atc/api/accessor/accessor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,11 @@ var _ = Describe("Accessor", func() {
Entry("pipeline-operator :: "+atc.PausePipeline, atc.PausePipeline, accessor.OperatorRole, true),
Entry("viewer :: "+atc.PausePipeline, atc.PausePipeline, accessor.ViewerRole, false),

Entry("owner :: "+atc.ArchivePipeline, atc.ArchivePipeline, accessor.OwnerRole, true),
Entry("member :: "+atc.ArchivePipeline, atc.ArchivePipeline, accessor.MemberRole, false),
Entry("pipeline-operator :: "+atc.ArchivePipeline, atc.ArchivePipeline, accessor.OperatorRole, false),
Entry("viewer :: "+atc.ArchivePipeline, atc.ArchivePipeline, accessor.ViewerRole, false),

Entry("owner :: "+atc.UnpausePipeline, atc.UnpausePipeline, accessor.OwnerRole, true),
Entry("member :: "+atc.UnpausePipeline, atc.UnpausePipeline, accessor.MemberRole, true),
Entry("pipeline-operator :: "+atc.UnpausePipeline, atc.UnpausePipeline, accessor.OperatorRole, true),
Expand Down
1 change: 1 addition & 0 deletions atc/api/accessor/role_action_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ var requiredRoles = map[string]string{
atc.DeletePipeline: MemberRole,
atc.OrderPipelines: MemberRole,
atc.PausePipeline: OperatorRole,
atc.ArchivePipeline: OwnerRole,
atc.UnpausePipeline: OperatorRole,
atc.ExposePipeline: MemberRole,
atc.HidePipeline: MemberRole,
Expand Down
2 changes: 2 additions & 0 deletions atc/api/api_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,8 @@ var _ = BeforeEach(func() {
time.Second,
dbWall,
fakeClock,

true, /* enableArchivePipeline */
)

Expect(err).NotTo(HaveOccurred())
Expand Down
5 changes: 4 additions & 1 deletion atc/api/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ func NewHandler(
interceptUpdateInterval time.Duration,
dbWall db.Wall,
clock clock.Clock,

enableArchivePipeline bool,
) (http.Handler, error) {

absCLIDownloadsDir, err := filepath.Abs(cliDownloadsDir)
Expand All @@ -91,7 +93,7 @@ func NewHandler(
resourceServer := resourceserver.NewServer(logger, secretManager, varSourcePool, dbCheckFactory, dbResourceFactory, dbResourceConfigFactory)

versionServer := versionserver.NewServer(logger, externalURL)
pipelineServer := pipelineserver.NewServer(logger, dbTeamFactory, dbPipelineFactory, externalURL)
pipelineServer := pipelineserver.NewServer(logger, dbTeamFactory, dbPipelineFactory, externalURL, enableArchivePipeline)
configServer := configserver.NewServer(logger, dbTeamFactory, secretManager)
ccServer := ccserver.NewServer(logger, dbTeamFactory, externalURL)
workerServer := workerserver.NewServer(logger, dbTeamFactory, dbWorkerFactory)
Expand Down Expand Up @@ -148,6 +150,7 @@ func NewHandler(
atc.DeletePipeline: pipelineHandlerFactory.HandlerFor(pipelineServer.DeletePipeline),
atc.OrderPipelines: http.HandlerFunc(pipelineServer.OrderPipelines),
atc.PausePipeline: pipelineHandlerFactory.HandlerFor(pipelineServer.PausePipeline),
atc.ArchivePipeline: pipelineHandlerFactory.HandlerFor(pipelineServer.ArchivePipeline),
atc.UnpausePipeline: pipelineHandlerFactory.HandlerFor(pipelineServer.UnpausePipeline),
atc.ExposePipeline: pipelineHandlerFactory.HandlerFor(pipelineServer.ExposePipeline),
atc.HidePipeline: pipelineHandlerFactory.HandlerFor(pipelineServer.HidePipeline),
Expand Down
49 changes: 48 additions & 1 deletion atc/api/pipelines_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ var _ = Describe("Pipelines API", func() {
privatePipeline.IDReturns(3)
privatePipeline.PausedReturns(false)
privatePipeline.PublicReturns(false)
privatePipeline.ArchivedReturns(true)
privatePipeline.TeamNameReturns("main")
privatePipeline.NameReturns("private-pipeline")
privatePipeline.GroupsReturns(atc.GroupConfigs{
Expand Down Expand Up @@ -280,7 +281,7 @@ var _ = Describe("Pipelines API", func() {
"name": "private-pipeline",
"paused": false,
"public": false,
"archived": false,
"archived": true,
"team_name": "main",
"last_updated": 1,
"groups": [
Expand Down Expand Up @@ -948,6 +949,52 @@ var _ = Describe("Pipelines API", func() {
})
})

Describe("PUT /api/v1/teams/:team_name/pipelines/:pipeline_name/archive", func() {
var response *http.Response

BeforeEach(func() {
fakeaccess.IsAuthenticatedReturns(true)
fakeaccess.IsAuthorizedReturns(true)
dbTeamFactory.FindTeamReturns(fakeTeam, true, nil)
fakeTeam.PipelineReturns(dbPipeline, true, nil)
})

JustBeforeEach(func() {
request, _ := http.NewRequest("PUT", server.URL+"/api/v1/teams/a-team/pipelines/a-pipeline/archive", nil)
var err error
response, err = client.Do(request)
Expect(err).NotTo(HaveOccurred())
})

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the same suite there are quite a bit of tests that also validate what happens when an unauthorized users tries to reach the corresponding endpoint

 ~/workspace/concourse/atc/api $ ag "401" ./pipelines_test.go
415:                    It("returns 401", func() {
509:                            It("returns 401", func() {
589:                                    It("returns 401", func() {
867:                    It("returns 401 Unauthorized", func() {
946:                    It("returns 401", func() {
1066:                   It("returns 401 Unauthorized", func() {
1146:                   It("returns 401 Unauthorized", func() {
1224:                   It("returns 401 Unauthorized", func() {
1335:                   It("returns 401 Unauthorized", func() {
1538:                   It("returns 401 Unauthorized", func() {
1616:                   It("returns 401 Unauthorized", func() {
1644:                           It("returns 401", func() {
1830:                   It("returns 401", func() {

e.g.

Context("when not authenticated", func() {
BeforeEach(func() {
fakeaccess.IsAuthenticatedReturns(false)
})
It("returns 401", func() {
Expect(response.StatusCode).To(Equal(http.StatusUnauthorized))
})
})

wdyt of adding tests for this one too? it seems to me that the big purpose of this more "end-to-end" approach of testing at the api level would be to catch these things 🤔 please correct me if i'm wrong! 😁

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm, we tried to drive out this feature by pretty rigorously practicing TDD. While pairing with @aoldershaw and @YoussB on different occasions, I recall weighing the decision to add these kinds of tests, and they felt redundant since we were already adding the table test entries for accessor itself. Indeed I think if we followed the boilerplate of the other tests, the newly-added tests would never actually go red. However, leaving them out is really only safe if we trust the other components we are integrating with and we have a solid contract with them. For example, I think there is a component with a name like 'api auth wrappa' that is conceptually 'responsible' for the behaviours you are describing, but we don't have a unit test anywhere saying "this code delegates to the api auth wrappa", and maybe we should? After all, if we ended up switching away from using the api auth wrappa, there would be nothing ensuring this "sensible default" behaviour.

It("returns 200", func() {
Expect(response.StatusCode).To(Equal(http.StatusOK))
})

It("archives the pipeline", func() {
Expect(dbPipeline.ArchiveCallCount()).To(Equal(1), "Archive() called the wrong number of times")
})

Context("when archiving the pipeline fails due to the DB", func() {
BeforeEach(func() {
dbPipeline.ArchiveReturns(errors.New("pq: a db error"))
})

It("gives a server error", func() {
Expect(response.StatusCode).To(Equal(http.StatusInternalServerError))
})
})

Context("when not authenticated", func() {
BeforeEach(func() {
fakeaccess.IsAuthenticatedReturns(false)
})

It("returns 401", func() {
Expect(response.StatusCode).To(Equal(http.StatusUnauthorized))
})
})
})

Describe("PUT /api/v1/teams/:team_name/pipelines/:pipeline_name/unpause", func() {
var response *http.Response

Expand Down
22 changes: 22 additions & 0 deletions atc/api/pipelineserver/archive.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package pipelineserver

import (
"net/http"

"github.com/concourse/concourse/atc/db"
)

func (s *Server) ArchivePipeline(pipelineDB db.Pipeline) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !s.enableArchivePipeline {
http.Error(w, "endpoint is not enabled", http.StatusForbidden)
return
}
s.logger.Debug("archive-pipeline")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh was this intentionally left here? if one wants to get a sense of "this endpoint was hit", one could leverage the audit logs

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given that I find myself reading other people's logs (more on that below), I feel motivated to make the system more verbose by default, just in case. This line is actually enforced by a unit test, because I don't want to rely on other people to turn on auditing if they're then going to be needing my advice on the state of their cluster.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, I do get the feeling :/

I don't want to rely on other people to turn on auditing if they're then going to be needing my advice on the state of their cluster.

although this does rely on the fact that they turned debug on, right? (which, sure, can be turned on at runtime, which is quite useful, but is also super expensive to have it on AFAIR).

if the same was true for audit (assuming the pain-point is quickly turning the system into a more verbose mode), would you think this log message in this particular endpoint would not be needed anymore?

err := pipelineDB.Archive()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
s.logger.Error("archive-pipeline", err)
}
})
}
91 changes: 91 additions & 0 deletions atc/api/pipelineserver/archive_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package pipelineserver_test

import (
"errors"
"io/ioutil"
"net/http"
"net/http/httptest"

"github.com/concourse/concourse/atc/api/pipelineserver"
"github.com/concourse/concourse/atc/api/pipelineserver/pipelineserverfakes"
"github.com/concourse/concourse/atc/db/dbfakes"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)

//go:generate counterfeiter code.cloudfoundry.org/lager.Logger
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this caught my attention, it's something we seem to only be doing here

$  ~/workspace/concourse/atc $ ag -Q "lager.Logger" | grep counter
api/pipelineserver/archive_test.go:16://go:generate counterfeiter code.cloudfoundry.org/lager.Logger

do you think this is something we should adopt more? I'm curious about the rationale to testing the log statements here, and would challenge is a bit: if we were adding a someMetric.Add(1) (i.e., if we were incrementing a counter for something we want to measure), and even more, we had a trace that we wanted to capture, should we test those three things? log, metric, and trace?

(please don't take the above as criticism 😅 curious to know more about it)

thanks!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've spent a lot of time inspecting logs from Concourse with no access to the cluster. Based on this, I'm shocked by how often I really wish Concourse was logging something and I find that it's not. In general I haven't yet felt like it's necessary to unit-test every log message, but there are times and places where logging feels like a really desirable feature with real business value and I want a test to verify that it will definitely be happening - in such cases I'd be pretty upset if the log stopped happening haha.


var _ = Describe("Archive Handler", func() {
var (
fakeLogger *pipelineserverfakes.FakeLogger
server *pipelineserver.Server
dbPipeline *dbfakes.FakePipeline
handler http.Handler
recorder *httptest.ResponseRecorder
request *http.Request
)

BeforeEach(func() {
fakeLogger = new(pipelineserverfakes.FakeLogger)
server = pipelineserver.NewServer(
fakeLogger,
new(dbfakes.FakeTeamFactory),
new(dbfakes.FakePipelineFactory),
"",
true, /* enableArchivePipeline */
)
dbPipeline = new(dbfakes.FakePipeline)
handler = server.ArchivePipeline(dbPipeline)
recorder = httptest.NewRecorder()
request = httptest.NewRequest("PUT", "http://example.com", nil)
})

It("logs database errors", func() {
expectedError := errors.New("db error")
dbPipeline.ArchiveReturns(expectedError)

handler.ServeHTTP(recorder, request)

Expect(fakeLogger.ErrorCallCount()).To(Equal(1))
action, actualError, _ := fakeLogger.ErrorArgsForCall(0)
Expect(action).To(Equal("archive-pipeline"), "wrong action name")
Expect(actualError).To(Equal(expectedError))
})

It("write a debug log on every request", func() {
handler.ServeHTTP(recorder, request)

Expect(fakeLogger.DebugCallCount()).To(Equal(1))
action, _ := fakeLogger.DebugArgsForCall(0)
Expect(action).To(Equal("archive-pipeline"), "wrong action name")
})

It("logs no errors if everything works", func() {
dbPipeline.ArchiveReturns(nil)

handler.ServeHTTP(recorder, request)

Expect(fakeLogger.ErrorCallCount()).To(Equal(0))
})

Context("when the endpoint is not enabled", func() {
BeforeEach(func() {
server = pipelineserver.NewServer(
fakeLogger,
new(dbfakes.FakeTeamFactory),
new(dbfakes.FakePipelineFactory),
"",
false, /* enableArchivePipeline */
)
handler = server.ArchivePipeline(dbPipeline)
})

It("responds with status Forbidden", func() {
handler.ServeHTTP(recorder, request)

Expect(recorder.Code).To(Equal(http.StatusForbidden))
body, _ := ioutil.ReadAll(recorder.Body)
Expect(body).To(Equal([]byte("endpoint is not enabled\n")))
})
})
})