Skip to content

feat: Add "coder projects create" command #246

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

Merged
merged 21 commits into from
Feb 12, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Basic creation flow works!
  • Loading branch information
kylecarbs committed Feb 10, 2022
commit 79a56b6d293033d66488e1187c77aded894e5abb
72 changes: 47 additions & 25 deletions cli/projectcreate.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ import (

"github.com/briandowns/spinner"
"github.com/fatih/color"
"github.com/google/uuid"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"golang.org/x/xerrors"

"github.com/coder/coder/coderd"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/database"
"github.com/coder/coder/provisionerd"
)

func projectCreate() *cobra.Command {
Expand Down Expand Up @@ -49,8 +51,8 @@ func projectCreate() *cobra.Command {
Default: filepath.Base(directory),
Label: "What's your project's name?",
Validate: func(s string) error {
_, err = client.Project(cmd.Context(), organization.Name, s)
if err == nil {
project, _ := client.Project(cmd.Context(), organization.Name, s)
if project.ID.String() != uuid.Nil.String() {
return xerrors.New("A project already exists with that name!")
}
return nil
Expand All @@ -63,6 +65,7 @@ func projectCreate() *cobra.Command {
spin := spinner.New(spinner.CharSets[0], 25*time.Millisecond)
spin.Suffix = " Uploading current directory..."
spin.Start()

defer spin.Stop()

bytes, err := tarDirectory(directory)
Expand All @@ -79,14 +82,6 @@ func projectCreate() *cobra.Command {
StorageMethod: database.ProvisionerStorageMethodFile,
StorageSource: resp.Hash,
Provisioner: database.ProvisionerTypeTerraform,
// SkipResources on first import to detect variables defined by the project.
SkipResources: true,
// ParameterValues: []coderd.CreateParameterValueRequest{{
// Name: "aws_access_key",
// SourceValue: "tomato",
// SourceScheme: database.ParameterSourceSchemeData,
// DestinationScheme: database.ParameterDestinationSchemeProvisionerVariable,
// }},
})
if err != nil {
return err
Expand All @@ -102,33 +97,60 @@ func projectCreate() *cobra.Command {
if !ok {
break
}
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s %s\n", color.HiGreenString("[parse]"), log.Output)
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s %s\n", color.HiGreenString("[tf]"), log.Output)
}

_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Parsed project source... displaying parameters:")

schemas, err := client.ProvisionerJobParameterSchemas(cmd.Context(), organization.Name, job.ID)
job, err = client.ProvisionerJob(cmd.Context(), organization.Name, job.ID)
if err != nil {
return err
}

values, err := client.ProvisionerJobParameterValues(cmd.Context(), organization.Name, job.ID)
if provisionerd.IsMissingParameterError(job.Error) {
fmt.Printf("Missing something!\n")
return nil
}

resources, err := client.ProvisionerJobResources(cmd.Context(), organization.Name, job.ID)
if err != nil {
return err
}
valueBySchemaID := map[string]coderd.ComputedParameterValue{}
for _, value := range values {
valueBySchemaID[value.SchemaID.String()] = value
}

for _, schema := range schemas {
if value, ok := valueBySchemaID[schema.ID.String()]; ok {
fmt.Printf("Value for: %s %s\n", value.Name, value.SourceValue)
continue
}
fmt.Printf("No value for: %s\n", schema.Name)
fmt.Printf("Resources: %+v\n", resources)

project, err := client.CreateProject(cmd.Context(), organization.Name, coderd.CreateProjectRequest{
Name: name,
VersionImportJobID: job.ID,
})
if err != nil {
return err
}

fmt.Printf("Project: %+v\n", project)

// _, _ = fmt.Fprintf(cmd.OutOrStdout(), "Parsed project source... displaying parameters:")

// schemas, err := client.ProvisionerJobParameterSchemas(cmd.Context(), organization.Name, job.ID)
// if err != nil {
// return err
// }

// values, err := client.ProvisionerJobParameterValues(cmd.Context(), organization.Name, job.ID)
// if err != nil {
// return err
// }
// valueBySchemaID := map[string]coderd.ComputedParameterValue{}
// for _, value := range values {
// valueBySchemaID[value.SchemaID.String()] = value
// }

// for _, schema := range schemas {
// if value, ok := valueBySchemaID[schema.ID.String()]; ok {
// fmt.Printf("Value for: %s %s\n", value.Name, value.SourceValue)
// continue
// }
// fmt.Printf("No value for: %s\n", schema.Name)
// }

// schemas, err := client.ProvisionerJobParameterSchemas(cmd.Context(), organization.Name, job.ID)
// if err != nil {
// return err
Expand Down
10 changes: 10 additions & 0 deletions cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,16 @@ func runPrompt(cmd *cobra.Command, prompt *promptui.Prompt) (string, error) {
Invalid: invalid,
Valid: valid,
}
oldValidate := prompt.Validate
if oldValidate != nil {
// Override the validate function to pass our default!
prompt.Validate = func(s string) error {
if s == "" {
s = defaultValue
}
return oldValidate(s)
}
}
value, err := prompt.Run()
if value == "" && !prompt.IsConfirm {
value = defaultValue
Expand Down
1 change: 1 addition & 0 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ func New(options *Options) http.Handler {
r.Get("/", api.provisionerJobByOrganization)
r.Get("/schemas", api.provisionerJobParameterSchemasByID)
r.Get("/computed", api.provisionerJobComputedParametersByID)
r.Get("/resources", api.provisionerJobResourcesByID)
r.Get("/logs", api.provisionerJobLogsByID)
})
})
Expand Down
24 changes: 24 additions & 0 deletions coderd/provisionerdaemons.go
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,30 @@ func (server *provisionerdServer) CompleteJob(ctx context.Context, completed *pr

switch jobType := completed.Type.(type) {
case *proto.CompletedJob_ProjectImport_:
for transition, resources := range map[database.WorkspaceTransition][]*sdkproto.Resource{
database.WorkspaceTransitionStart: jobType.ProjectImport.StartResources,
database.WorkspaceTransitionStop: jobType.ProjectImport.StopResources,
} {
for _, resource := range resources {
server.Logger.Info(ctx, "inserting project import job resource",
slog.F("job_id", job.ID.String()),
slog.F("resource_name", resource.Name),
slog.F("resource_type", resource.Type),
slog.F("transition", transition))
_, err = server.Database.InsertProjectImportJobResource(ctx, database.InsertProjectImportJobResourceParams{
ID: uuid.New(),
CreatedAt: database.Now(),
JobID: jobID,
Transition: transition,
Type: resource.Type,
Name: resource.Name,
})
if err != nil {
return nil, xerrors.Errorf("insert resource: %w", err)
}
}
}

err = server.Database.UpdateProvisionerJobWithCompleteByID(ctx, database.UpdateProvisionerJobWithCompleteByIDParams{
ID: jobID,
UpdatedAt: database.Now(),
Expand Down
33 changes: 29 additions & 4 deletions coderd/provisionerjobs.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import (
"github.com/coder/coder/httpmw"
)

type ProjectImportJobResource database.ProjectImportJobResource

type ProvisionerJobStatus string

// Completed returns whether the job is still processing.
Expand Down Expand Up @@ -125,9 +127,9 @@ func (api *api) postProvisionerImportJobByOrganization(rw http.ResponseWriter, r
// Return parsed parameter schemas for a job.
func (api *api) provisionerJobParameterSchemasByID(rw http.ResponseWriter, r *http.Request) {
job := httpmw.ProvisionerJobParam(r)
if convertProvisionerJob(job).Status != ProvisionerJobStatusSucceeded {
if !convertProvisionerJob(job).Status.Completed() {
httpapi.Write(rw, http.StatusPreconditionFailed, httpapi.Response{
Message: fmt.Sprintf("Job is in state %q! Must be %q.", convertProvisionerJob(job).Status, ProvisionerJobStatusSucceeded),
Message: "Job hasn't completed!",
})
return
}
Expand All @@ -150,9 +152,9 @@ func (api *api) provisionerJobParameterSchemasByID(rw http.ResponseWriter, r *ht
func (api *api) provisionerJobComputedParametersByID(rw http.ResponseWriter, r *http.Request) {
apiKey := httpmw.APIKey(r)
job := httpmw.ProvisionerJobParam(r)
if convertProvisionerJob(job).Status != ProvisionerJobStatusSucceeded {
if !convertProvisionerJob(job).Status.Completed() {
httpapi.Write(rw, http.StatusPreconditionFailed, httpapi.Response{
Message: fmt.Sprintf("Job is in state %q! Must be %q.", convertProvisionerJob(job).Status, ProvisionerJobStatusSucceeded),
Message: "Job hasn't completed!",
})
return
}
Expand All @@ -163,6 +165,29 @@ func (api *api) provisionerJobComputedParametersByID(rw http.ResponseWriter, r *
})
}

func (api *api) provisionerJobResourcesByID(rw http.ResponseWriter, r *http.Request) {
job := httpmw.ProvisionerJobParam(r)
if !convertProvisionerJob(job).Status.Completed() {
httpapi.Write(rw, http.StatusPreconditionFailed, httpapi.Response{
Message: "Job hasn't completed!",
})
return
}
resources, err := api.Database.GetProjectImportJobResourcesByJobID(r.Context(), job.ID)
if errors.Is(err, sql.ErrNoRows) {
err = nil
}
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Message: fmt.Sprintf("get project import job resources: %s", err),
})
return
}

render.Status(r, http.StatusOK)
render.JSON(rw, r, resources)
}

func convertProvisionerJob(provisionerJob database.ProvisionerJob) ProvisionerJob {
job := ProvisionerJob{
ID: provisionerJob.ID,
Expand Down
37 changes: 37 additions & 0 deletions coderd/provisionerjobs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

"github.com/coder/coder/coderd"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/coderd/parameter"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/database"
"github.com/coder/coder/provisioner/echo"
Expand Down Expand Up @@ -170,3 +171,39 @@ func TestProvisionerJobParametersByID(t *testing.T) {
require.Equal(t, params[0].SourceValue, "")
})
}

func TestProvisionerJobResourcesByID(t *testing.T) {
t.Parallel()
t.Run("Something", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t)
user := coderdtest.CreateInitialUser(t, client)
_ = coderdtest.NewProvisionerDaemon(t, client)
job := coderdtest.CreateProjectImportProvisionerJob(t, client, user.Organization, &echo.Responses{
Parse: []*proto.Parse_Response{{
Type: &proto.Parse_Response_Complete{
Complete: &proto.Parse_Complete{
ParameterSchemas: []*proto.ParameterSchema{{
Name: parameter.CoderWorkspaceTransition,
}},
},
},
}},
Provision: []*proto.Provision_Response{{
Type: &proto.Provision_Response_Complete{
Complete: &proto.Provision_Complete{
Resources: []*proto.Resource{{
Name: "hello",
Type: "ec2_instance",
}},
},
},
}},
})
coderdtest.AwaitProvisionerJob(t, client, user.Organization, job.ID)
resources, err := client.ProvisionerJobResources(context.Background(), user.Organization, job.ID)
require.NoError(t, err)
// One for start, and one for stop!
require.Len(t, resources, 2)
})
}
13 changes: 13 additions & 0 deletions codersdk/provisioners.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,16 @@ func (c *Client) ProvisionerJobParameterValues(ctx context.Context, organization
var params []coderd.ComputedParameterValue
return params, json.NewDecoder(res.Body).Decode(&params)
}

func (c *Client) ProvisionerJobResources(ctx context.Context, organization string, job uuid.UUID) ([]coderd.ProjectImportJobResource, error) {
res, err := c.request(ctx, http.MethodGet, fmt.Sprintf("/api/v2/provisioners/jobs/%s/%s/resources", organization, job), nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, readBodyAsError(res)
}
var resources []coderd.ProjectImportJobResource
return resources, json.NewDecoder(res.Body).Decode(&resources)
}
17 changes: 17 additions & 0 deletions database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,23 @@ func (q *fakeQuerier) GetProjectByOrganizationAndName(_ context.Context, arg dat
return database.Project{}, sql.ErrNoRows
}

func (q *fakeQuerier) GetProjectImportJobResourcesByJobID(ctx context.Context, jobID uuid.UUID) ([]database.ProjectImportJobResource, error) {
q.mutex.Lock()
defer q.mutex.Unlock()

resources := make([]database.ProjectImportJobResource, 0)
for _, resource := range q.projectImportJobResource {
if resource.JobID.String() != jobID.String() {
continue
}
resources = append(resources, resource)
}
if len(resources) == 0 {
return nil, sql.ErrNoRows
}
return resources, nil
}

func (q *fakeQuerier) GetProjectVersionsByProjectID(_ context.Context, projectID uuid.UUID) ([]database.ProjectVersion, error) {
q.mutex.Lock()
defer q.mutex.Unlock()
Expand Down
1 change: 1 addition & 0 deletions database/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions database/query.sql
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,14 @@ FROM
WHERE
job_id = $1;

-- name: GetProjectImportJobResourcesByJobID :many
SELECT
*
FROM
project_import_job_resource
WHERE
job_id = $1;

-- name: GetProjectVersionsByProjectID :many
SELECT
*
Expand Down
Loading